Skip to content

Commit

Permalink
Merge pull request #2 from kamilturek/grouped-expressions
Browse files Browse the repository at this point in the history
Grouped Expressions
  • Loading branch information
kamilturek authored Jun 15, 2024
2 parents 8d84ad0 + 3f7fd29 commit b4daf99
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,24 @@ let y = 5 < 5;
let z = 5 == 5;
let v = 5 != 5;
```

### Operator Precedence

The following table shows the operator precedence in Monkey, from lowest to highest:

| Precedence Level | Operators | Description |
|------------------|-----------------|----------------------------|
| 6 (Highest) | Function calls | Function calls |
| 5 | Prefix `-`, `!` | Unary operations |
| 4 | `*`, `/` | Multiplication and Division|
| 3 | `+`, `-` | Addition and Subtraction |
| 2 | `<`, `>` | Comparison |
| 1 (Lowest) | `==`, `!=` | Equality |

### Grouped Expressions

You can use parentheses to influence the order of executing arithmetic operations.

```
let x = (2 / (5 + 5));
```
13 changes: 13 additions & 0 deletions parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ func NewParser(l *lexer.Lexer) *Parser {
p.registerPrefix(token.FALSE, p.parseBooleanLiteral)
p.registerPrefix(token.BANG, p.parsePrefixExpression)
p.registerPrefix(token.MINUS, p.parsePrefixExpression)
p.registerPrefix(token.LPAREN, p.parseGroupedExpression)

p.registerInfix(token.PLUS, p.parseInfixExpression)
p.registerInfix(token.MINUS, p.parseInfixExpression)
Expand Down Expand Up @@ -259,6 +260,18 @@ func (p *Parser) parseInfixExpression(left ast.Expression) ast.Expression {
return expression
}

func (p *Parser) parseGroupedExpression() ast.Expression {
p.nextToken()

exp := p.parseExpression(LOWEST)

if !p.exceptPeek(token.RPAREN) {
return nil
}

return exp
}

func (p *Parser) parseIdentifier() ast.Expression {
return &ast.Identifier{Token: p.curToken, Value: p.curToken.Literal}
}
Expand Down
20 changes: 20 additions & 0 deletions parser/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,26 @@ func TestOperatorPrecedenceParsing(t *testing.T) {
"3 < 5 == true",
"((3 < 5) == true)",
},
{
"1 + (2 + 3) + 4",
"((1 + (2 + 3)) + 4)",
},
{
"(5 + 5) * 2",
"((5 + 5) * 2)",
},
{
"2 / (5 + 5)",
"(2 / (5 + 5))",
},
{
"-(5 + 5)",
"(-(5 + 5))",
},
{
"!(true == true)",
"(!(true == true))",
},
}

for _, tt := range tests {
Expand Down

0 comments on commit b4daf99

Please sign in to comment.