vm: add greater and less

This commit is contained in:
Luna 2019-06-02 00:23:50 -03:00
parent 15c58a2216
commit 71dba5c77d
3 changed files with 21 additions and 1 deletions

View file

@ -183,6 +183,12 @@ pub const Chunk = struct {
return try simpleInstruction(stdout, "OP_FALSE", index);
} else if (instruction == OpCode.Not) {
return try simpleInstruction(stdout, "OP_NOT", index);
} else if (instruction == OpCode.Equal) {
return try simpleInstruction(stdout, "OP_EQUAL", index);
} else if (instruction == OpCode.Greater) {
return try simpleInstruction(stdout, "OP_GREATER", index);
} else if (instruction == OpCode.Less) {
return try simpleInstruction(stdout, "OP_LESS", index);
} else {
try stdout.print("Unknown opcode: {}\n", instruction);
return index + 1;

View file

@ -221,7 +221,6 @@ pub const Compiler = struct {
/// Emits bytecode for a number being loaded into the code.
fn number(self: *Compiler) !void {
std.debug.warn("parsing number: '{}'\n", self.parser.previous.lexeme);
var value: f64 = try std.fmt.parseFloat(
f64,
self.parser.previous.lexeme,

View file

@ -143,6 +143,18 @@ pub const VM = struct {
try self.push(values.NumberVal(a / b));
}
fn doGreater(self: *VM) !void {
var b = try self.popNum();
var a = try self.popNum();
try self.push(values.BoolVal(a > b));
}
fn doLess(self: *VM) !void {
var b = try self.popNum();
var a = try self.popNum();
try self.push(values.BoolVal(a < b));
}
fn runtimeError(self: *VM, comptime fmt: []const u8, args: ...) void {
std.debug.warn(fmt, args);
std.debug.warn("\n[line {}] in script\n", self.chk.lines[self.ip]);
@ -186,6 +198,9 @@ pub const VM = struct {
try self.push(values.BoolVal(valuesEqual(a, b)));
},
chunk.OpCode.Greater => try self.doGreater(),
chunk.OpCode.Less => try self.doLess(),
chunk.OpCode.Add => try self.doAdd(),
chunk.OpCode.Subtract => try self.doSub(),
chunk.OpCode.Multiply => try self.doMul(),