summary refs log tree commit diff
diff options
context:
space:
mode:
authorBaitinq <manuelpalenzuelamerino@gmail.com>2025-01-21 00:10:04 +0100
committerBaitinq <manuelpalenzuelamerino@gmail.com>2025-01-21 00:10:04 +0100
commit0ae6498192f838d091ef61c8e8518ec938cefd19 (patch)
tree246a49681855671b9f57f85712e22fb0ad298d25
parentExample: Add example for while loop (diff)
downloadinterpreter-0ae6498192f838d091ef61c8e8518ec938cefd19.tar.gz
interpreter-0ae6498192f838d091ef61c8e8518ec938cefd19.tar.bz2
interpreter-0ae6498192f838d091ef61c8e8518ec938cefd19.zip
Parser: Make additive expression left associative
-rw-r--r--examples/7.src2
-rw-r--r--grammar.ebnf2
-rw-r--r--src/parser.zig18
3 files changed, 13 insertions, 9 deletions
diff --git a/examples/7.src b/examples/7.src
index 3bb1b91..8e3ad60 100644
--- a/examples/7.src
+++ b/examples/7.src
@@ -1,7 +1,7 @@
 let main = () => {
 	let i = 4;
 	
-	if i + 1 == 5 - (1 + 1) {
+	if i + 1 == 5 - 1 + 1 {
 		print(i);
 		return i;
 	};
diff --git a/grammar.ebnf b/grammar.ebnf
index bde99cb..b770797 100644
--- a/grammar.ebnf
+++ b/grammar.ebnf
@@ -16,7 +16,7 @@ Expression   ::= EqualityExpression | AdditiveExpression | FunctionDefinition |
 
 EqualityExpression ::= AdditiveExpression "==" AdditiveExpression
 
-AdditiveExpression ::= PrimaryExpression (("+" | "-") AdditiveExpression)?
+AdditiveExpression ::= PrimaryExpression (("+" | "-") PrimaryExpression)*
 
 PrimaryExpression ::= NUMBER | BOOLEAN | IDENTIFIER | FunctionCallStatement
 
diff --git a/src/parser.zig b/src/parser.zig
index 76f2127..eead436 100644
--- a/src/parser.zig
+++ b/src/parser.zig
@@ -251,17 +251,21 @@ pub const Parser = struct {
         } });
     }
 
-    // AdditiveExpression ::= PrimaryExpression (("+" | "-") AdditiveExpression)?
+    // AdditiveExpression ::= PrimaryExpression (("+" | "-") PrimaryExpression)*
     fn parse_additive_expression(self: *Parser) ParserError!*Node {
         errdefer if (!self.try_context) std.debug.print("Error parsing additive expression\n", .{});
 
-        const lhs = try self.parse_primary_expression();
+        var lhs = try self.parse_primary_expression();
 
-        const plus = self.accept_token(tokenizer.TokenType.PLUS);
-        const minus = self.accept_token(tokenizer.TokenType.MINUS);
-        if (plus != null or minus != null) {
-            const rhs = try self.parse_additive_expression();
-            return self.create_node(.{ .ADDITIVE_EXPRESSION = .{
+        while (true) {
+            const plus = self.accept_token(tokenizer.TokenType.PLUS);
+            const minus = self.accept_token(tokenizer.TokenType.MINUS);
+
+            if (plus == null and minus == null) break;
+
+            const rhs = try self.parse_primary_expression();
+
+            lhs = try self.create_node(.{ .ADDITIVE_EXPRESSION = .{
                 .addition = plus != null,
                 .lhs = lhs,
                 .rhs = rhs,