add expression statements

This commit is contained in:
Luna 2019-06-02 18:04:36 -03:00
parent bea6e34365
commit 06df2d37ee
3 changed files with 13 additions and 0 deletions

View file

@ -27,6 +27,7 @@ const AllOpcodes = struct {
pub Less: u8 = 14,
pub Print: u8 = 15,
pub Pop: u8 = 16,
};
pub const OpCode = AllOpcodes{};
@ -193,6 +194,8 @@ pub const Chunk = struct {
return try simpleInstruction(stdout, "OP_LESS", index);
} else if (instruction == OpCode.Print) {
return try simpleInstruction(stdout, "OP_PRINT", index);
} else if (instruction == OpCode.Pop) {
return try simpleInstruction(stdout, "OP_POP", index);
} else {
try stdout.print("Unknown opcode: {}\n", instruction);
return index + 1;

View file

@ -331,6 +331,12 @@ pub const Compiler = struct {
try self.emitByte(OpCode.Print);
}
fn exprStmt(self: *Compiler) !void {
try self.expression();
try self.consume(.SEMICOLON, "Expect ';' after expression.");
try self.emitByte(OpCode.Pop);
}
fn declaration(self: *Compiler) !void {
try self.statement();
}
@ -338,6 +344,8 @@ pub const Compiler = struct {
fn statement(self: *Compiler) !void {
if (try self.match(.PRINT)) {
try self.printStmt();
} else {
try self.exprStmt();
}
}

View file

@ -255,6 +255,8 @@ pub const VM = struct {
chunk.OpCode.True => try self.push(values.BoolVal(true)),
chunk.OpCode.False => try self.push(values.BoolVal(false)),
chunk.OpCode.Pop => self.pop(),
chunk.OpCode.Equal => blk: {
var a = self.pop();
var b = self.pop();