finish impl for ConstantLong

This commit is contained in:
Luna 2019-06-01 14:18:44 -03:00
parent 2d33e03efb
commit 14fa63e1f6
2 changed files with 27 additions and 24 deletions

View file

@ -15,26 +15,26 @@ pub const OpCode = AllOpcodes{};
fn simpleInstruction(
stdout: var,
comptime name: []const u8,
offset: usize,
index: usize,
) !usize {
try stdout.print("{}\n", name);
return offset + 1;
return index + 1;
}
fn constantInstruction(
stdout: var,
comptime name: []const u8,
chunk: *Chunk,
offset: usize,
index: usize,
) !usize {
// get the constant's index in constants slice
var idx = chunk.code[offset + 1];
var idx = chunk.code[index + 1];
try stdout.print("\t{}\t{} '", name, idx);
try value.printValue(stdout, chunk.constants.values[idx]);
try stdout.print("'\n");
return offset + 2;
return index + 2;
}
fn constantLongInstruction(
@ -43,24 +43,19 @@ fn constantLongInstruction(
chunk: *Chunk,
offset: usize,
) !usize {
// get the constant's index in constants slice
var v0: u8 = chunk.code[offset + 3];
var v1: u8 = chunk.code[offset + 2];
var v2: u8 = chunk.code[offset + 1];
// constantLong uses three u8's that encode a u24 as the
// contants' index.
var v3: u8 = chunk.code[offset + 1];
var v2: u8 = chunk.code[offset + 2];
var v1: u8 = chunk.code[offset + 3];
// TODO: this does not work. just decreased first term
// to fix a compile error.
// we should also move the actual printing into its own
// function too since constantInstruction and
// constantLongInstruction share code.
var idx: u24 = (v2 << 4) | (v1 << 7) | v0;
var idx: u24 = (@intCast(u24, v3) << 16) | (@intCast(u24, v2) << 8) | v1;
try stdout.print("\t{}\t{} '", name, idx);
try value.printValue(stdout, chunk.constants.values[idx]);
try stdout.print("'\n");
return offset + 2;
return offset + 4;
}
pub const Chunk = struct {
@ -112,13 +107,18 @@ pub const Chunk = struct {
try self.write(OpCode.Constant, line);
try self.write(@intCast(u8, constant_idx), line);
} else {
// TODO: convert the usize to u24, and from
// u24, split it into three u8's.
var idx_u24: u24 = @intCast(u24, constant_idx);
// also convert from u8 back to u24.
// i know that we can do from two u8's to go to a u16
// with (v1 << 7) | v0.
try self.write(0, line);
const mask = @intCast(u24, 0xff);
const v1: u8 = @intCast(u8, idx_u24 & mask);
const v2: u8 = @intCast(u8, (idx_u24 >> 8) & mask);
const v3: u8 = @intCast(u8, (idx_u24 >> 16) & mask);
try self.write(OpCode.ConstantLong, line);
try self.write(v3, line);
try self.write(v2, line);
try self.write(v1, line);
}
}

View file

@ -115,7 +115,10 @@ pub fn main() !void {
//var opcode_byte: u8 = @enumToInt(chunk.OpCode.Return);
//try chk.write(chunk.OpCode.Return);
var i: usize = 0;
while (i < 260) : (i += 1) {
var constant = try chk.writeConstant(1.2, 123);
}
try chk.write(chunk.OpCode.Return, 123);
try chk.disassemble(stdout, "test chunk");