diff options
Diffstat (limited to 'parser')
| -rw-r--r-- | parser/parser.go | 36 | ||||
| -rw-r--r-- | parser/parser_test.go | 25 |
2 files changed, 60 insertions, 1 deletions
diff --git a/parser/parser.go b/parser/parser.go index 6ca88b3..a4472b2 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -72,6 +72,7 @@ func New(l *lexer.Lexer) *Parser { p.registerPrefix(tokens.FUNCTION, p.parseFunctionLiteral) p.registerPrefix(tokens.LPAREN, p.parseGroupedExpression) p.registerPrefix(tokens.STRING, p.parseStringLiteral) + p.registerPrefix(tokens.LBRACKET, p.parseArrayLiteral) // Initialize the infix parse functions. p.infixParseFns = make(map[tokens.TokenType]infixParseFn) @@ -407,7 +408,7 @@ func (p *Parser) parseGroupedExpression() ast.Expression { // parseCallExpression parses a call expression. func (p *Parser) parseCallExpression(function ast.Expression) ast.Expression { exp := &ast.CallExpression{Token: p.curToken, Function: function} - exp.Arguments = p.parseCallArguments() + exp.Arguments = p.parseExpressionList(tokens.RPAREN) return exp } @@ -444,6 +445,39 @@ func (p *Parser) parseStringLiteral() ast.Expression { } } +func (p *Parser) parseArrayLiteral() ast.Expression { + array := &ast.ArrayLiteral{Token: p.curToken} + + array.Elements = p.parseExpressionList(tokens.RBRACKET) + + return array +} + +func (p *Parser) parseExpressionList(end tokens.TokenType) []ast.Expression { + list := []ast.Expression{} + + if p.peekTokenIs(end) { + p.nextToken() + return list + } + + p.nextToken() + + list = append(list, p.parseExpression(LOWEST)) + + for p.peekTokenIs(tokens.COMMA) { + p.nextToken() + p.nextToken() + list = append(list, p.parseExpression(LOWEST)) + } + + if !p.expectPeek(end) { + return nil + } + + return list +} + // curTokenIs returns true if the current token is of the given type. func (p *Parser) curTokenIs(t tokens.TokenType) bool { return p.curToken.Type == t diff --git a/parser/parser_test.go b/parser/parser_test.go index 3a574a7..f1b8b8c 100644 --- a/parser/parser_test.go +++ b/parser/parser_test.go @@ -791,3 +791,28 @@ func TestStringLiteralExpression(t *testing.T) { t.Errorf("literal.Value not %q. got=%q", "hello world", literal.Value) } } + +func TestParsingArrayLiterals(t *testing.T) { + input := "[1, 2 * 2, 3 + 3]" + + var l *lexer.Lexer = lexer.New(input) + var p *Parser = New(l) + + var program *ast.Program = p.ParseProgram() + checkParserErrors(t, p) + + stmt, ok := program.Statements[0].(*ast.ExpressionStatement) + array, ok := stmt.Expression.(*ast.ArrayLiteral) + + if !ok { + t.Fatalf("exp is not ast.ArrayLiteral. got=%T", stmt.Expression) + } + + if len(array.Elements) != 3 { + t.Fatalf("len(array.Elements) not 3. got=%d", len(array.Elements)) + } + + testIntegerLiteral(t, array.Elements[0], 1) + testInfixExpression(t, array.Elements[1], 2, "*", 2) + testInfixExpression(t, array.Elements[2], 3, "+", 3) +} |
