vm, chunk: add binary operators

This commit is contained in:
Luna 2019-06-01 15:40:18 -03:00
parent 2822676707
commit 3377d1675c
3 changed files with 54 additions and 6 deletions

View file

@ -5,10 +5,14 @@ const Allocator = std.mem.Allocator;
// hack. ugly hack. zig has compiler crash.
const AllOpcodes = struct {
pub Constant: u8 = 0,
pub ConstantLong: u8 = 1,
pub Return: u8 = 2,
pub Negate: u8 = 3,
pub Return: u8 = 0,
pub Constant: u8 = 1,
pub ConstantLong: u8 = 2,
pub Add: u8 = 3,
pub Subtract: u8 = 4,
pub Multiply: u8 = 5,
pub Divide: u8 = 6,
pub Negate: u8 = 7,
};
pub const OpCode = AllOpcodes{};
@ -151,6 +155,14 @@ pub const Chunk = struct {
);
} else if (instruction == OpCode.Negate) {
return try simpleInstruction(stdout, "OP_NEGATE", index);
} else if (instruction == OpCode.Add) {
return try simpleInstruction(stdout, "OP_ADD", index);
} else if (instruction == OpCode.Subtract) {
return try simpleInstruction(stdout, "OP_SUBTRACT", index);
} else if (instruction == OpCode.Multiply) {
return try simpleInstruction(stdout, "OP_MULTIPLY", index);
} else if (instruction == OpCode.Divide) {
return try simpleInstruction(stdout, "OP_DIVIDE", index);
} else {
try stdout.print("Unknown opcode: {}\n", instruction);
return index + 1;

View file

@ -116,8 +116,11 @@ pub fn main() !void {
//var opcode_byte: u8 = @enumToInt(chunk.OpCode.Return);
//try chk.write(chunk.OpCode.Return);
var constant = try chk.writeConstant(1.2, 123);
try chk.write(chunk.OpCode.Negate, 123);
try chk.writeConstant(1.2, 123);
try chk.writeConstant(3.4, 123);
try chk.write(chunk.OpCode.Add, 123);
try chk.writeConstant(5.6, 123);
try chk.write(chunk.OpCode.Divide, 123);
try chk.write(chunk.OpCode.Return, 123);
var vmach = vm.VM.init(stdout, &chk, true);

View file

@ -81,6 +81,35 @@ pub const VM = struct {
try self.stdout.print("\n");
}
/// gets a f64 out of a value on the top of the stack.
fn popNum(self: *VM) f64 {
return self.pop();
}
fn doAdd(self: *VM) void {
var b = self.popNum();
var a = self.popNum();
self.push(a + b);
}
fn doSub(self: *VM) void {
var b = self.popNum();
var a = self.popNum();
self.push(a * b);
}
fn doMul(self: *VM) void {
var b = self.popNum();
var a = self.popNum();
self.push(a * b);
}
fn doDiv(self: *VM) void {
var b = self.popNum();
var a = self.popNum();
self.push(a / b);
}
fn run(self: *VM) !InterpretResult {
while (true) {
if (self.debug_flag) {
@ -108,6 +137,10 @@ pub const VM = struct {
return InterpretResult.Ok;
},
chunk.OpCode.Add => self.doAdd(),
chunk.OpCode.Subtract => self.doSub(),
chunk.OpCode.Multiply => self.doMul(),
chunk.OpCode.Divide => self.doDiv(),
chunk.OpCode.Negate => self.push(-self.pop()),
else => blk: {
std.debug.warn("Unknown instruction: {x}\n", instruction);