From 3936b4a4263995b2cc30624cd1c44c98217b0274 Mon Sep 17 00:00:00 2001 From: Luna Date: Mon, 3 Jun 2019 00:02:07 -0300 Subject: [PATCH] main: keep a long-running vm instance for REPL enables us to declare variables and keep them going for as long as the REPL goes. - vm: remove source arg from init(), move to interpret() --- src/main.zig | 17 ++++++++++++++--- src/vm.zig | 8 ++------ 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/src/main.zig b/src/main.zig index 8451723..a38e2a3 100644 --- a/src/main.zig +++ b/src/main.zig @@ -16,9 +16,17 @@ fn run(allocator: *Allocator, data: []u8) !void { var stdout_file = try std.io.getStdOut(); const stdout = &stdout_file.outStream().stream; - var vmach = try vm.VM.init(allocator, stdout, data, true); + var vmach = try vm.VM.init(allocator, stdout, true); defer vmach.deinit(); - try vmach.interpret(); + try vmach.interpret(data); +} + +fn runWithVM(vmach: *vm.VM, data: []u8) !void { + var stdout_file = try std.io.getStdOut(); + const stdout = &stdout_file.outStream().stream; + + defer vmach.deinit(); + try vmach.interpret(data); } pub fn doError(line: usize, message: []const u8) !void { @@ -55,6 +63,9 @@ fn runPrompt(allocator: *Allocator) !void { var stdout_file = try std.io.getStdOut(); const stdout = &stdout_file.outStream().stream; + var vmach = try vm.VM.init(allocator, stdout, true); + defer vmach.deinit(); + while (true) { try stdout.print(">"); var buffer = try std.Buffer.init(allocator, ""[0..]); @@ -65,7 +76,7 @@ fn runPrompt(allocator: *Allocator) !void { return err; }; - run(allocator, line) catch |err| { + runWithVM(&vmach, line) catch |err| { switch (err) { InterpretResult.Ok => {}, InterpretResult.CompileError, InterpretResult.RuntimeError => blk: { diff --git a/src/vm.zig b/src/vm.zig index 646dfbe..24a72f8 100644 --- a/src/vm.zig +++ b/src/vm.zig @@ -40,7 +40,6 @@ pub const ValueMap = std.AutoHashMap([]const u8, values.Value); pub const VM = struct { chk: *Chunk = undefined, - src: []const u8, ip: usize = 0, stack: []Value, @@ -60,12 +59,9 @@ pub const VM = struct { pub fn init( allocator: *std.mem.Allocator, stdout: StdOut, - source: []const u8, debug_flag: bool, ) !VM { var self = VM{ - .src = source, - .stack = try allocator.alloc(Value, 256), .stdout = stdout, .debug_flag = debug_flag, @@ -352,7 +348,7 @@ pub const VM = struct { } } - pub fn interpret(self: *VM) !void { + pub fn interpret(self: *VM, src: []const u8) !void { //self.ip = 0; //self.debug("VM start\n"); //var res = try self.run(); @@ -364,7 +360,7 @@ pub const VM = struct { self.allocator, &chk, self.stdout, - self.src, + src, self.debug_flag, self, );