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
2.0 KiB
Go

package parser
import (
"golox/ast"
"golox/errors"
"golox/token"
"testing"
)
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)",
},
{
name: "Parsing error - missing right parenthesis",
tokens: []token.Token{
{Type: token.LEFT_PAREN, Lexeme: "("},
{Type: token.NUMBER, Literal: 1},
{Type: token.PLUS, Lexeme: "+"},
{Type: token.NUMBER, Literal: 2},
{Type: token.EOF},
},
expected: "Expect ')' after expression.",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
parser := New(tt.tokens, errors.NewMockErrorLogger())
expr := parser.Parse()
ap := ast.NewPrinter()
s := ap.Print(expr)
if s != tt.expected {
t.Errorf("expected %v, got %v", tt.expected, s)
}
})
}
}