diff options
author | Baitinq <manuelpalenzuelamerino@gmail.com> | 2025-01-21 00:32:14 +0100 |
---|---|---|
committer | Baitinq <manuelpalenzuelamerino@gmail.com> | 2025-01-21 00:32:14 +0100 |
commit | 967dc36c30abbab9e2983568feab9bb514ab58df (patch) | |
tree | dd038d87758bfe17edba4c1ba5457b1ebbde9184 /src/parser.zig | |
parent | Parser: Add support for parenthesis grouping (diff) | |
download | interpreter-967dc36c30abbab9e2983568feab9bb514ab58df.tar.gz interpreter-967dc36c30abbab9e2983568feab9bb514ab58df.tar.bz2 interpreter-967dc36c30abbab9e2983568feab9bb514ab58df.zip |
Feature: Add support for NOT unary expression
Diffstat (limited to 'src/parser.zig')
-rw-r--r-- | src/parser.zig | 27 |
1 files changed, 24 insertions, 3 deletions
diff --git a/src/parser.zig b/src/parser.zig index ce5522d..f574161 100644 --- a/src/parser.zig +++ b/src/parser.zig @@ -15,6 +15,7 @@ const NodeType = enum { EXPRESSION, EQUALITY_EXPRESSION, ADDITIVE_EXPRESSION, + UNARY_EXPRESSION, PRIMARY_EXPRESSION, FUNCTION_DEFINITION, RETURN_STATEMENT, @@ -58,6 +59,10 @@ pub const Node = union(NodeType) { lhs: *Node, rhs: *Node, }, + UNARY_EXPRESSION: struct { + negation: bool, + expression: *Node, + }, PRIMARY_EXPRESSION: union(enum) { NUMBER: struct { value: i64, @@ -244,11 +249,11 @@ pub const Parser = struct { } }); } - // AdditiveExpression ::= PrimaryExpression (("+" | "-") PrimaryExpression)* + // AdditiveExpression ::= UnaryExpression (("+" | "-") UnaryExpression)* fn parse_additive_expression(self: *Parser) ParserError!*Node { errdefer if (!self.try_context) std.debug.print("Error parsing additive expression\n", .{}); - var lhs = try self.parse_primary_expression(); + var lhs = try self.parse_unary_expression(); while (true) { const plus = self.accept_token(tokenizer.TokenType.PLUS); @@ -256,7 +261,7 @@ pub const Parser = struct { if (plus == null and minus == null) break; - const rhs = try self.parse_primary_expression(); + const rhs = try self.parse_unary_expression(); lhs = try self.create_node(.{ .ADDITIVE_EXPRESSION = .{ .addition = plus != null, @@ -268,6 +273,22 @@ pub const Parser = struct { return lhs; } + // UnaryExpression ::= "!" UnaryExpression | PrimaryExpression + fn parse_unary_expression(self: *Parser) ParserError!*Node { + errdefer if (!self.try_context) std.debug.print("Error parsing unary expression\n", .{}); + + const negation = self.accept_token(tokenizer.TokenType.NOT) != null; + + if (!negation) { + return try self.parse_primary_expression(); + } + + return self.create_node(.{ .UNARY_EXPRESSION = .{ + .negation = negation, + .expression = try self.parse_unary_expression(), + } }); + } + // PrimaryExpression ::= NUMBER | BOOLEAN | IDENTIFIER | FunctionCallStatement | LPAREN Expression RPAREN fn parse_primary_expression(self: *Parser) ParserError!*Node { errdefer if (!self.try_context) std.debug.print("Error parsing primary expression\n", .{}); |