Skip to content

Commit

Permalink
feat: adds support for builtin array access by index
Browse files Browse the repository at this point in the history
Signed-off-by: maxwellgithinji <[email protected]>
  • Loading branch information
maxwellgithinji committed Feb 4, 2024
1 parent 9e0aae6 commit 1a44600
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions pkg/parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ func New(l *lexer.Lexer) *Parser {
p.registerInfix(token.SLASH, p.parseInfixExpression)
p.registerInfix(token.ASTERISK, p.parseInfixExpression)
p.registerInfix(token.LPAREN, p.parseCallExpression)
p.registerInfix(token.LBRACKET, p.parseIndexExpression)

p.nextToken()
p.nextToken()
Expand Down Expand Up @@ -217,6 +218,9 @@ const (

// CALL has the value 7. add(x, y)
CALL

// INDEX has the value 8. array[index]
INDEX
)

// precedences is a hashmap containing infix operator tokens mapped to respective precedence values
Expand All @@ -230,6 +234,7 @@ var precedences = map[token.TokenType]int{
token.SLASH: PRODUCT,
token.ASTERISK: PRODUCT,
token.LPAREN: CALL,
token.LBRACKET: INDEX,
}

// registerPrefix records a prefix token
Expand Down Expand Up @@ -563,3 +568,18 @@ func (p *Parser) parseExpressionList(delimiter token.TokenType) []ast.Expression

return list
}

// parseIndexExpression is an infix expression where [ is the infix operator
func (p *Parser) parseIndexExpression(left ast.Expression) ast.Expression {
expression := &ast.IndexExpression{Token: p.currentToken, Left: left}

p.nextToken()

expression.Index = p.parseExpression(LOWEST)

if !p.expectPeek(token.RBRACKET) {
return nil
}

return expression
}

0 comments on commit 1a44600

Please sign in to comment.