From c6c9ab9bf9681e179703d4635cb3b6983370a0da Mon Sep 17 00:00:00 2001 From: Kamil Turek Date: Sat, 15 Jun 2024 10:37:23 +0200 Subject: [PATCH 1/2] Parse grouped expressions --- parser/parser.go | 13 +++++++++++++ parser/parser_test.go | 20 ++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/parser/parser.go b/parser/parser.go index 19d7ecc..db910fe 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -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) @@ -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} } diff --git a/parser/parser_test.go b/parser/parser_test.go index d66849e..4310c14 100644 --- a/parser/parser_test.go +++ b/parser/parser_test.go @@ -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 { From 3f7fd290d8aabe24241a167493645814145aaa97 Mon Sep 17 00:00:00 2001 From: Kamil Turek Date: Sat, 15 Jun 2024 10:44:42 +0200 Subject: [PATCH 2/2] Update README.md --- README.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/README.md b/README.md index d7068dd..e808b52 100644 --- a/README.md +++ b/README.md @@ -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)); +```