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()
This commit is contained in:
Luna 2019-06-03 00:02:07 -03:00
parent 005981fbbd
commit 3936b4a426
2 changed files with 16 additions and 9 deletions

View File

@ -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: {

View File

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