From de7404b256c1a72bf01a70c3702627d972e90d7f Mon Sep 17 00:00:00 2001 From: Houcine EL ADDALI Date: Sat, 27 Jan 2024 14:12:39 +0100 Subject: [PATCH] feat: array indexing parser --- internal/parser/data/test_data.go | 2 +- internal/parser/parser.go | 13 ++++++------- internal/parser/parser_test.go | 4 ++-- 3 files changed, 9 insertions(+), 10 deletions(-) diff --git a/internal/parser/data/test_data.go b/internal/parser/data/test_data.go index 9741847..a1ad450 100644 --- a/internal/parser/data/test_data.go +++ b/internal/parser/data/test_data.go @@ -120,5 +120,5 @@ var ( } Arrays = "[1,12 - 8 ,7]" - ArrayIndex = "nums[7-4];" + ArrayIndex = "nums[7-4]" ) diff --git a/internal/parser/parser.go b/internal/parser/parser.go index 8731c6d..9fcf506 100644 --- a/internal/parser/parser.go +++ b/internal/parser/parser.go @@ -88,7 +88,7 @@ func InitParser(l *lexer.Lexer) *Parser { token.DECREMENT, token.INCREMENT, }, p.parsePostFixExpression) - p.addInfixFn(token.RB, p.parseIndexExp) + p.addInfixFn(token.LB, p.parseIndexExp) return p } @@ -484,9 +484,9 @@ func (p *Parser) parseAssignmentExpr(left *ast.Identifier) ast.Expression { func (p *Parser) parseArrayLit() ast.Expression { exp := &ast.ArrayLiteral{ - Token: p.currToken, + Token: p.currToken, } - fmt.Println("------- parse array --------> ", p.currToken) + exp.Values = p.parseExpressionList(token.CreateToken(token.RB, "]")) return exp @@ -497,20 +497,19 @@ func (p *Parser) parseExpressionList(t token.Token) []ast.Expression { if p.peekTokenEquals(t.Type) { p.Next() - return res // an empty array + return res // an empty array } p.Next() res = append(res, p.parseExpression(LOWEST)) - fmt.Println("-------List exp--------> ", p.currToken) + for p.peekTokenEquals(token.COMMA) { p.Next() p.Next() - fmt.Println("-------List exp--------> ", p.currToken) + res = append(res, p.parseExpression(LOWEST)) } - fmt.Println("---------------> ", p.currToken) if !p.expectedNextToken(t) { return nil } diff --git a/internal/parser/parser_test.go b/internal/parser/parser_test.go index 98ce6cf..b5a861c 100644 --- a/internal/parser/parser_test.go +++ b/internal/parser/parser_test.go @@ -416,7 +416,7 @@ func TestParseArraysLit(t *testing.T) { } -/*func TestArrayIndexExp(t *testing.T) { +func TestArrayIndexExp(t *testing.T) { input := data.ArrayIndex pr, parser := getProg(input) @@ -441,7 +441,7 @@ func TestParseArraysLit(t *testing.T) { if !testInfixExpression(t, arrIdx.Index, 7, 4, "-") { return } -}*/ +} // Tests helper functions func checkIsProgramStmLengthValid(program *ast.Program, t *testing.T, length int) {