You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
92 lines
1.9 KiB
Go
92 lines
1.9 KiB
Go
package parser
|
|
|
|
import (
|
|
"golox/ast"
|
|
"golox/token"
|
|
"testing"
|
|
)
|
|
|
|
type mockErrorLogger struct{}
|
|
|
|
func (el *mockErrorLogger) Error(line int, message string) {
|
|
}
|
|
|
|
func (el *mockErrorLogger) ErrorAtToken(t token.Token, message string) {
|
|
}
|
|
|
|
func newMockErrorLogger() *mockErrorLogger {
|
|
return &mockErrorLogger{}
|
|
}
|
|
|
|
func TestParser(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
tokens []token.Token
|
|
expected string
|
|
}{
|
|
{
|
|
name: "Simple expression",
|
|
tokens: []token.Token{
|
|
{Type: token.NUMBER, Literal: 1},
|
|
{Type: token.PLUS, Lexeme: "+"},
|
|
{Type: token.NUMBER, Literal: 2},
|
|
{Type: token.EOF},
|
|
},
|
|
expected: "(+ 1 2)",
|
|
},
|
|
{
|
|
name: "Unary expression",
|
|
tokens: []token.Token{
|
|
{Type: token.MINUS, Lexeme: "-"},
|
|
{Type: token.NUMBER, Literal: 123},
|
|
{Type: token.EOF},
|
|
},
|
|
expected: "(- 123)",
|
|
},
|
|
{
|
|
name: "Grouping expression",
|
|
tokens: []token.Token{
|
|
{Type: token.LEFT_PAREN, Lexeme: "("},
|
|
{Type: token.NUMBER, Literal: 1},
|
|
{Type: token.PLUS, Lexeme: "+"},
|
|
{Type: token.NUMBER, Literal: 2},
|
|
{Type: token.RIGHT_PAREN, Lexeme: ")"},
|
|
{Type: token.EOF},
|
|
},
|
|
expected: "(group (+ 1 2))",
|
|
},
|
|
{
|
|
name: "Comparison expression",
|
|
tokens: []token.Token{
|
|
{Type: token.NUMBER, Literal: 1},
|
|
{Type: token.GREATER, Lexeme: ">"},
|
|
{Type: token.NUMBER, Literal: 2},
|
|
{Type: token.EOF},
|
|
},
|
|
expected: "(> 1 2)",
|
|
},
|
|
{
|
|
name: "Equality expression",
|
|
tokens: []token.Token{
|
|
{Type: token.NUMBER, Literal: 1},
|
|
{Type: token.EQUAL_EQUAL, Lexeme: "=="},
|
|
{Type: token.NUMBER, Literal: 2},
|
|
{Type: token.EOF},
|
|
},
|
|
expected: "(== 1 2)",
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
parser := New(tt.tokens, newMockErrorLogger())
|
|
expr := parser.Parse()
|
|
ap := ast.NewPrinter()
|
|
s := ap.Print(expr)
|
|
if s != tt.expected {
|
|
t.Errorf("expected %v, got %v", tt.expected, s)
|
|
}
|
|
})
|
|
}
|
|
}
|