From 596cfe8b9d7319085465bbd134247e2967652f6f Mon Sep 17 00:00:00 2001 From: Baitinq Date: Wed, 22 Jan 2025 00:30:28 +0100 Subject: Feature: Add support for negation --- src/evaluator.zig | 5 ++++- src/parser.zig | 9 +++++---- 2 files changed, 9 insertions(+), 5 deletions(-) (limited to 'src') 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(), } }); } -- cgit 1.4.1