From 887cb1adea74bafa0188b1fbc4bab75dfa498da1 Mon Sep 17 00:00:00 2001 From: Luna Date: Sun, 2 Jun 2019 23:43:12 -0300 Subject: [PATCH] add emitting of GetGlobal/GetGlobalLong --- src/chunk.zig | 2 ++ src/compiler.zig | 36 +++++++++++++++++++++++++++++++----- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/src/chunk.zig b/src/chunk.zig index 76d4bb9..1c0f58e 100644 --- a/src/chunk.zig +++ b/src/chunk.zig @@ -31,6 +31,8 @@ const AllOpcodes = struct { pub DefineGlobal: u8 = 17, pub DefineGlobalLong: u8 = 18, + pub GetGlobal: u8 = 19, + pub GetGlobalLong: u8 = 20, }; pub const OpCode = AllOpcodes{}; diff --git a/src/compiler.zig b/src/compiler.zig index 1b44624..3a8df90 100644 --- a/src/compiler.zig +++ b/src/compiler.zig @@ -89,7 +89,7 @@ var rules = []ParseRule{ ParseRule{ .infix = Compiler.binary, .precedence = .Comparison }, ParseRule{ .infix = Compiler.binary, .precedence = .Comparison }, - ParseRule{}, + ParseRule{ .prefix = Compiler.variable }, ParseRule{ .prefix = Compiler.string }, ParseRule{ .prefix = Compiler.number }, ParseRule{ .precedence = .And }, @@ -252,6 +252,19 @@ pub const Compiler = struct { ))); } + fn namedVariable(self: *Compiler, tok: *Token) !void { + var idx = try self.identifierConstant(tok); + try self.emitConstWithIndex( + chunks.OpCode.GetGlobal, + chunks.OpCode.GetGlobalLong, + idx, + ); + } + + fn variable(self: *Compiler) !void { + try self.namedVariable(self.parser.previous); + } + /// Emits bytecode for a given unary. fn unary(self: *Compiler) !void { var ttype = self.parser.previous.ttype; @@ -368,11 +381,16 @@ pub const Compiler = struct { return try self.identifierConstant(&self.parser.previous); } - fn defineVariable(self: *Compiler, global: chunks.ConstantIndex) !void { - switch (global) { - .Small => |val| try self.emitBytes(chunks.OpCode.DefineGlobal, val), + fn emitConstWithIndex( + self: *Compiler, + op_short: u8, + op_long: u8, + idx: chunks.ConstantIndex, + ) !void { + switch (idx) { + .Small => |val| try self.emitBytes(op_short, val), .Long => |val| blk: { - try self.emitByte(chunks.OpCode.DefineGlobalLong); + try self.emitByte(op_long); try self.emitByte(val[0]); try self.emitByte(val[1]); try self.emitByte(val[2]); @@ -381,6 +399,14 @@ pub const Compiler = struct { } } + fn defineVariable(self: *Compiler, global: chunks.ConstantIndex) !void { + try self.emitConstWithIndex( + chunks.OpCode.DefineGlobal, + chunks.OpCode.DefineGlobalLong, + global, + ); + } + fn varDecl(self: *Compiler) !void { var global = try self.parseVariable("Expect variable name.");