From 3f2a8f3801e5dfc0688768360cb5c808c51274e0 Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 2 Jun 2019 15:39:04 -0300 Subject: [PATCH] add object list cleaning on VM.deinit --- src/main.zig | 1 + src/vm.zig | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/src/main.zig b/src/main.zig index 660a9e7..8451723 100644 --- a/src/main.zig +++ b/src/main.zig @@ -17,6 +17,7 @@ fn run(allocator: *Allocator, data: []u8) !void { const stdout = &stdout_file.outStream().stream; var vmach = try vm.VM.init(allocator, stdout, data, true); + defer vmach.deinit(); try vmach.interpret(); } diff --git a/src/vm.zig b/src/vm.zig index 674f7f7..197ba46 100644 --- a/src/vm.zig +++ b/src/vm.zig @@ -74,6 +74,36 @@ pub const VM = struct { return self; } + fn deinitObject(self: *VM, obj: *objects.Object) void { + switch (obj.otype) { + .String => blk: { + self.allocator.free(obj.value.String); + self.allocator.destroy(obj); + break :blk; + }, + else => unreachable, + } + } + + fn deinitObjects(self: *VM) void { + var obj_opt: ?*objects.Object = self.objs; + + // doing a while(obj != null) but with optionals + while (true) { + if (obj_opt) |obj| { + var next = obj.next; + self.deinitObject(obj); + obj_opt = next; + } else { + break; + } + } + } + + pub fn deinit(self: *VM) void { + self.deinitObjects(); + } + pub fn debug(self: *VM, comptime fmt: []const u8, args: ...) void { if (self.debug_flag) { std.debug.warn(fmt, args);