Skip to content

Commit

Permalink
✨ Parse grouped expressions
Browse files Browse the repository at this point in the history
  • Loading branch information
ChmielewskiKamil committed Aug 28, 2024
1 parent 8f7ae71 commit 6877512
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
18 changes: 18 additions & 0 deletions parser/exprparsing.go
Original file line number Diff line number Diff line change
Expand Up @@ -256,3 +256,21 @@ func (p *Parser) parseInfixExpression(left ast.Expression) ast.Expression {

return exp
}

func (p *Parser) parseGroupedExpression() ast.Expression {
if p.trace {
defer un(trace("parseGroupedExpression"))
}

p.nextToken()

// Parse the thing inside parentheses.
exp := p.parseExpression(LOWEST)

// There should be a closing parenthesis.
if !p.expectPeek(token.RPAREN) {
return nil
}

return exp
}
8 changes: 6 additions & 2 deletions parser/exprparsing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -224,14 +224,16 @@ func Test_ParseOperatorPrecedence(t *testing.T) {
1 + 2;
3 > 8 == false;
3 < 8 == true;
3 * (8 + 2) * 2;
10 / (1 + 1);
}`

file := test_helper_parseSource(t, src, false)

fnBody := test_helper_parseFnBody(t, file)

if len(fnBody.Statements) != 18 {
t.Fatalf("Expected 18 statements, got %d", len(fnBody.Statements))
if len(fnBody.Statements) != 20 {
t.Fatalf("Expected 20 statements, got %d", len(fnBody.Statements))
}

tests := []struct {
Expand All @@ -255,6 +257,8 @@ func Test_ParseOperatorPrecedence(t *testing.T) {
{"(1 + 2)"},
{"((3 > 8) == false)"},
{"((3 < 8) == true)"},
{"((3 * (8 + 2)) * 2)"},
{"(10 / (1 + 1))"},
}

for i, tt := range tests {
Expand Down
1 change: 1 addition & 0 deletions parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ func (p *Parser) Init(file *token.File) {
p.registerPrefix(token.HEX_NUMBER, p.parseNumberLiteral)
p.registerPrefix(token.TRUE_LITERAL, p.parseBooleanLiteral)
p.registerPrefix(token.FALSE_LITERAL, p.parseBooleanLiteral)
p.registerPrefix(token.LPAREN, p.parseGroupedExpression)

// Prefix Expressions
p.registerPrefix(token.NOT, p.parsePrefixExpression)
Expand Down

0 comments on commit 6877512

Please sign in to comment.