summary refs log tree commit diff
diff options
context:
space:
mode:
authorBaitinq <manuelpalenzuelamerino@gmail.com>2025-01-07 19:49:15 +0100
committerBaitinq <manuelpalenzuelamerino@gmail.com>2025-01-07 19:49:15 +0100
commit8ae30dba883c1c8caea6d1528f3cb4e92c92caf7 (patch)
tree4540069f1857cfb11fa396b40d08d7e80fa116f7
parentParser: Memory improvements (diff)
downloadinterpreter-8ae30dba883c1c8caea6d1528f3cb4e92c92caf7.tar.gz
interpreter-8ae30dba883c1c8caea6d1528f3cb4e92c92caf7.tar.bz2
interpreter-8ae30dba883c1c8caea6d1528f3cb4e92c92caf7.zip
Parser: Fix mem leaks
-rw-r--r--src/parser.zig20
1 files changed, 16 insertions, 4 deletions
diff --git a/src/parser.zig b/src/parser.zig
index 00921e8..8499732 100644
--- a/src/parser.zig
+++ b/src/parser.zig
@@ -52,10 +52,21 @@ pub const Parser = struct {
 
     pub fn deinit(self: *Parser, ast: *Node) void {
         std.debug.assert(ast.* == .PROGRAM);
-        std.debug.print("STATEMENTS FREE: {any}\n", .{ast.PROGRAM.statements.len});
         for (ast.PROGRAM.statements) |statement| {
-            self.allocator.destroy(statement); //TODO: We're missing frees of children. we also dont want to double free!
+            switch (statement.*) {
+                .VARIABLE_STATEMENT => unreachable,
+                .PRINT_STATEMENT => |x| {
+                    self.allocator.destroy(x.expression);
+                },
+                .NUMBER => unreachable,
+                .IDENTIFIER => unreachable,
+                else => unreachable,
+            }
+            self.allocator.destroy(statement);
         }
+        self.allocator.free(ast.PROGRAM.statements);
+        self.allocator.destroy(ast);
+        self.allocator.destroy(self);
     }
 
     pub fn parse(self: *Parser) !*Node {
@@ -64,8 +75,9 @@ pub const Parser = struct {
 
     fn parse_program(self: *Parser) !*Node {
         var nodes = std.ArrayList(*Node).init(self.allocator);
+        defer nodes.deinit();
         while (self.offset < self.tokens.len) {
-            try nodes.append(@constCast(try self.parse_statement())); //TODO: This is not good, should we be allocating mem for every node?
+            try nodes.append(@constCast(try self.parse_statement()));
         }
 
         const node = try self.allocator.create(Node);
@@ -128,7 +140,7 @@ pub const Parser = struct {
         const node = try self.allocator.create(Node);
         node.* = .{
             .PRINT_STATEMENT = .{
-                .expression = @constCast(expression), //TODO: Warning ptr
+                .expression = @constCast(expression),
             },
         };
         return node;