add other bytecode emitters

This commit is contained in:
Luna 2019-06-01 20:48:26 -03:00
parent 2736bee8d8
commit 230fef20b5

View file

@ -3,12 +3,15 @@ const scanner = @import("new_scanner.zig");
const vm = @import("vm.zig");
const chunks = @import("chunk.zig");
const tokens = @import("token.zig");
const values = @import("value.zig");
const Allocator = std.mem.Allocator;
const Scanner = scanner.Scanner;
const Chunk = chunks.Chunk;
const Token = tokens.Token;
const TokenType = tokens.TokenType;
const Value = values.Value;
const OpCode = chunks.OpCode;
pub const Parser = struct {
previous: Token = undefined,
@ -101,14 +104,44 @@ pub const Compiler = struct {
try self.emitByte(byte2);
}
fn writeReturn(self: *Compiler) !void {
try self.emitByte(chunks.OpCode.Return);
fn emitReturn(self: *Compiler) !void {
try self.emitByte(OpCode.Return);
}
fn emitConstant(self: *Compiler, value: Value) !void {
try self.currentChunk().writeConstant(
value,
self.parser.previous.line,
);
}
fn end(self: *Compiler) !void {
try self.writeReturn();
try self.emitReturn();
}
fn grouping(self: *Compiler) !void {
try self.expression();
try self.consume(.RIGHT_PAREN, "Expect ')' after expression.");
}
/// Emits bytecode for a number being loaded into the code.
fn number(self: *Compiler) !void {
var value: f64 = try std.fmt.parseFloat(f64, parser.previous.lexeme);
try self.emitConstant(value);
}
/// Emits bytecode for a given unary.
fn unary(self: *Compiler) !void {
var ttype = self.parser.previous.ttype;
try self.expression();
switch (ttype) {
.MINUS => try self.emitByte(OpCode.Negate),
else => unreachable,
}
}
fn expression(self: *Compiler) !void {}
/// Compile the source given when initializing the compiler
/// into the given chunk.
pub fn compile(self: *Compiler, chunk: *Chunk) !bool {