add object list cleaning on VM.deinit

This commit is contained in:
Luna 2019-06-02 15:39:04 -03:00
parent cf53b6fc86
commit 3f2a8f3801
2 changed files with 31 additions and 0 deletions

View file

@ -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();
}

View file

@ -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);