| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
package parser |
| 16 |
|
| 17 |
import ( |
| 18 |
"fmt" |
| 19 |
"testing" |
| 20 |
|
| 21 |
antlr "github.com/antlr4-go/antlr/v4" |
| 22 |
) |
| 23 |
|
| 24 |
type errListener struct { |
| 25 |
antlr.DefaultErrorListener |
| 26 |
|
| 27 |
errs []error |
| 28 |
} |
| 29 |
|
| 30 |
func (l *errListener) SyntaxError(recognizer antlr.Recognizer, offendingSymbol any, line, column int, msg string, e antlr.RecognitionException) { |
| 31 |
l.errs = append(l.errs, fmt.Errorf("(%d:%d) %s", line, column, msg)) |
| 32 |
} |
| 33 |
|
| 34 |
func tryParse(t testing.TB, s string) error { |
| 35 |
t.Helper() |
| 36 |
|
| 37 |
l := &errListener{} |
| 38 |
is := antlr.NewInputStream(s) |
| 39 |
lexer := NewCommandsLexer(is) |
| 40 |
lexer.RemoveErrorListeners() |
| 41 |
lexer.AddErrorListener(l) |
| 42 |
p := NewCommandsParser(antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)) |
| 43 |
p.RemoveErrorListeners() |
| 44 |
p.AddErrorListener(l) |
| 45 |
p.StartCommand() |
| 46 |
|
| 47 |
if len(l.errs) == 0 { |
| 48 |
return nil |
| 49 |
} |
| 50 |
|
| 51 |
err := l.errs[0].Error() |
| 52 |
for _, el := range l.errs[1:] { |
| 53 |
err = err + "\n" + el.Error() |
| 54 |
} |
| 55 |
return fmt.Errorf("parse errors: %s", err) |
| 56 |
} |
| 57 |
|
| 58 |
func TestAccept(t *testing.T) { |
| 59 |
var testCases = []string{ |
| 60 |
"%exit", |
| 61 |
"%let id = 2", |
| 62 |
"%arbitrary", |
| 63 |
"%arbitrary --flag --another-flag 'string arg'", |
| 64 |
" ", |
| 65 |
"%let y : int = [1, 2, 3]", |
| 66 |
"%let fn (y : int) : int -> y + 10", |
| 67 |
"%let fn () : int -> 10", |
| 68 |
"%let fn (x:int, y : int) : int -> x + y", |
| 69 |
"%let fn (x:int, y : int) : int -> x + y", |
| 70 |
"%let x : Abstract() = MakeAbstract()", |
| 71 |
"%let com.google.fn (x:int, y : int) : int -> x + y", |
| 72 |
"%let int.plus (x: int) : int -> this + x", |
| 73 |
"%delete id", |
| 74 |
"%delete com.google.id", |
| 75 |
"%delete int.fn(x:int): int", |
| 76 |
"%declare x : int", |
| 77 |
"%declare fn (x : int) : int", |
| 78 |
"%declare x", |
| 79 |
"x + 2", |
| 80 |
} |
| 81 |
for _, tc := range testCases { |
| 82 |
err := tryParse(t, tc) |
| 83 |
if err != nil { |
| 84 |
t.Errorf("parse %s:\ngot %v\nexpected nil", tc, err) |
| 85 |
} |
| 86 |
|
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
func TestReject(t *testing.T) { |
| 91 |
var testCases = []string{ |
| 92 |
"%declare 1", |
| 93 |
"%let 1 = 2", |
| 94 |
"%1badid", |
| 95 |
"%let fn x : int : int -> x + 2", |
| 96 |
"%let fn (x : int) -> x + 2", |
| 97 |
"x{{", |
| 98 |
"%declare fn (x: int)", |
| 99 |
"%declare fn (x) : int", |
| 100 |
} |
| 101 |
for _, tc := range testCases { |
| 102 |
err := tryParse(t, tc) |
| 103 |
if err == nil { |
| 104 |
t.Errorf("parse %s got nil, expected error", tc) |
| 105 |
} |
| 106 |
|
| 107 |
} |
| 108 |
} |