aboutsummaryrefslogtreecommitdiff
path: root/parser/parser_test.go
diff options
context:
space:
mode:
Diffstat (limited to 'parser/parser_test.go')
-rw-r--r--parser/parser_test.go74
1 files changed, 74 insertions, 0 deletions
diff --git a/parser/parser_test.go b/parser/parser_test.go
index f26fa1e..415b8cb 100644
--- a/parser/parser_test.go
+++ b/parser/parser_test.go
@@ -652,3 +652,77 @@ func TestIfElseExpression(t *testing.T) {
return
}
}
+
+func TestFunctionLiteralParsing(t *testing.T) {
+ input := "fn(x, y) { x + y; }"
+
+ var l *lexer.Lexer = lexer.New(input)
+ var p *Parser = New(l)
+ var program *ast.Program = p.ParseProgram()
+ checkParserErrors(t, p)
+
+ if len(program.Statements) != 1 {
+ t.Fatalf("program.Statements does not contain %d statements. got=%d", 1, len(program.Statements))
+ }
+
+ stmt, ok := program.Statements[0].(*ast.ExpressionStatement)
+
+ if !ok {
+ t.Fatalf("program.Statements[0] is not ast.ExpressionStatement. got=%T", program.Statements[0])
+ }
+
+ function, ok := stmt.Expression.(*ast.FunctionLiteral)
+
+ if !ok {
+ t.Fatalf("stmt.Expression is not ast.FunctionLiteral. got=%T", stmt.Expression)
+ }
+
+ if len(function.Parameters) != 2 {
+ t.Fatalf("function literal parameters wrong. want 2, got=%d\n", len(function.Parameters))
+ }
+
+ testLiteralExpression(t, function.Parameters[0], "x")
+ testLiteralExpression(t, function.Parameters[1], "y")
+
+ if len(function.Body.Statements) != 1 {
+ t.Fatalf("function.Body.Statements has not 1 statements. got=%d", len(function.Body.Statements))
+ }
+
+ bodyStmt, ok := function.Body.Statements[0].(*ast.ExpressionStatement)
+
+ if !ok {
+ t.Fatalf("function body stmt is not ast.ExpressionStatement. got=%T", function.Body.Statements[0])
+ }
+
+ testInfixExpression(t, bodyStmt.Expression, "x", "+", "y")
+}
+
+func TestFunctionParameterParsing(t *testing.T) {
+ var tests = []struct {
+ input string
+ expectedParams []string
+ }{
+ {input: "fn() {};", expectedParams: []string{}},
+ {input: "fn(x) {};", expectedParams: []string{"x"}},
+ {input: "fn(x, y, z) {};", expectedParams: []string{"x", "y", "z"}},
+ }
+
+ for _, tt := range tests {
+ var l *lexer.Lexer = lexer.New(tt.input)
+ var p *Parser = New(l)
+
+ var program *ast.Program = p.ParseProgram()
+ checkParserErrors(t, p)
+
+ stmt := program.Statements[0].(*ast.ExpressionStatement)
+ function := stmt.Expression.(*ast.FunctionLiteral)
+
+ if len(function.Parameters) != len(tt.expectedParams) {
+ t.Errorf("length parameters wrong. want %d, got=%d\n", len(tt.expectedParams), len(function.Parameters))
+ }
+
+ for i, ident := range tt.expectedParams {
+ testLiteralExpression(t, function.Parameters[i], ident)
+ }
+ }
+}