From 230fef20b55e503499281ebcbb6717c0ae8547d0 Mon Sep 17 00:00:00 2001 From: Luna Date: Sat, 1 Jun 2019 20:48:26 -0300 Subject: [PATCH] add other bytecode emitters --- src/compiler.zig | 39 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/src/compiler.zig b/src/compiler.zig index a04fd1f..3fea307 100644 --- a/src/compiler.zig +++ b/src/compiler.zig @@ -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 {