diff options
| author | Baitinq <[email protected]> | 2025-01-22 00:30:28 +0100 |
|---|---|---|
| committer | Baitinq <[email protected]> | 2025-01-22 00:30:59 +0100 |
| commit | 774498ff4db405eadd8ce295eb699586ed217f6d (patch) | |
| tree | 106c0926321316cac67d57ea94df8444fd0b3f8f /src | |
| parent | Feature: Add support for division and multiplication (diff) | |
| download | interpreter-774498ff4db405eadd8ce295eb699586ed217f6d.tar.gz interpreter-774498ff4db405eadd8ce295eb699586ed217f6d.tar.bz2 interpreter-774498ff4db405eadd8ce295eb699586ed217f6d.zip | |
Feature: Add support for negation
Diffstat (limited to 'src')
| -rw-r--r-- | src/evaluator.zig | 5 | ||||
| -rw-r--r-- | src/parser.zig | 9 |
2 files changed, 9 insertions, 5 deletions
diff --git a/src/evaluator.zig b/src/evaluator.zig index 9f8b61f..798d66c 100644 --- a/src/evaluator.zig +++ b/src/evaluator.zig @@ -174,6 +174,10 @@ pub const Evaluator = struct { }, .UNARY_EXPRESSION => |x| { const val = try self.get_expression_value(x.expression) orelse return EvaluatorError.EvaluationError; + if (!x.negation) { + std.debug.assert(val.* == .NUMBER); + return try self.create_variable(.{ .NUMBER = -val.NUMBER }); + } std.debug.assert(val.* == .BOOLEAN); return try self.create_variable(.{ .BOOLEAN = !val.BOOLEAN }); }, @@ -268,7 +272,6 @@ const Environment = struct { .allocator = allocator, }; - //TODO: Add more scopes when evaluating functions // Create global scope try self.create_scope(); diff --git a/src/parser.zig b/src/parser.zig index 966cad3..b407c42 100644 --- a/src/parser.zig +++ b/src/parser.zig @@ -322,18 +322,19 @@ pub const Parser = struct { return lhs; } - // UnaryExpression ::= "!" UnaryExpression | PrimaryExpression + // 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.BANG) != null; + const not = self.accept_token(tokenizer.TokenType.BANG) != null; + const minus = self.accept_token(tokenizer.TokenType.MINUS) != null; - if (!negation) { + if (!not and !minus) { return try self.parse_primary_expression(); } return self.create_node(.{ .UNARY_EXPRESSION = .{ - .negation = negation, + .negation = not, .expression = try self.parse_unary_expression(), } }); } |