Compare commits
10 Commits
c8cd24afbf
...
trunk
Author | SHA1 | Date | |
---|---|---|---|
7e216dd382 | |||
031ca59a07 | |||
3ecbe5ca9d | |||
980312bd62 | |||
1300c42a09 | |||
22ed27a931 | |||
0bc5f495b9 | |||
b839d67cea | |||
b522f05c8c | |||
3c1c37799c |
@ -18,9 +18,9 @@ While reading [Crafting Interpreters](https://craftinginterpreters.com/), after
|
|||||||
- [x] 25 - Closures
|
- [x] 25 - Closures
|
||||||
- [x] 26 - Garbage Collection
|
- [x] 26 - Garbage Collection
|
||||||
- [x] 27 - Classes and Instances
|
- [x] 27 - Classes and Instances
|
||||||
- [ ] 28 - Method and Initializers
|
- [x] 28 - Method and Initializers
|
||||||
- [ ] 29 - Superclasses
|
- [x] 29 - Superclasses
|
||||||
- [ ] 30 - Optimization
|
- [x] 30 - Optimization (without NaN boxing/NaN tagging)
|
||||||
|
|
||||||
## Build & run
|
## Build & run
|
||||||
|
|
||||||
|
9
samples/ch28_calling_methods.lox
Normal file
9
samples/ch28_calling_methods.lox
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
class Scone {
|
||||||
|
topping(first, second) {
|
||||||
|
return "scone with " + first + " and " + second;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var scone = Scone();
|
||||||
|
var result = scone.topping("berries", "cream");
|
||||||
|
print result;
|
14
samples/ch28_initializers.lox
Normal file
14
samples/ch28_initializers.lox
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
class CoffeeMaker {
|
||||||
|
init(coffee) {
|
||||||
|
this.coffee = coffee;
|
||||||
|
}
|
||||||
|
brew() {
|
||||||
|
print "Enjoy your cup of " + this.coffee;
|
||||||
|
// No reusing the grounds!
|
||||||
|
this.coffee = nil;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var maker = CoffeeMaker("coffee and chicory");
|
||||||
|
print maker;
|
||||||
|
maker.brew();
|
12
samples/ch28_methods_again.lox
Normal file
12
samples/ch28_methods_again.lox
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
class Brunch {
|
||||||
|
bacon() {
|
||||||
|
print "calling bacon()";
|
||||||
|
}
|
||||||
|
eggs() {
|
||||||
|
print "calling eggs()";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var brunch = Brunch();
|
||||||
|
print brunch;
|
||||||
|
brunch.bacon();
|
4
samples/ch28_methods_initializers.lox
Normal file
4
samples/ch28_methods_initializers.lox
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
class Brunch {
|
||||||
|
init(food, drink) {}
|
||||||
|
}
|
||||||
|
Brunch("eggs", "coffee");
|
17
samples/ch28_optimized_invocation.lox
Normal file
17
samples/ch28_optimized_invocation.lox
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
class Oops {
|
||||||
|
init() {
|
||||||
|
fun f() {
|
||||||
|
print "not a method";
|
||||||
|
return "returned value from f";
|
||||||
|
}
|
||||||
|
this.field = f;
|
||||||
|
}
|
||||||
|
|
||||||
|
blah() {
|
||||||
|
return "returned value from blah";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var oops = Oops();
|
||||||
|
print oops.field();
|
||||||
|
print oops.blah();
|
11
samples/ch28_say_name.lox
Normal file
11
samples/ch28_say_name.lox
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
class Person {
|
||||||
|
sayName() {
|
||||||
|
print this.name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var jane = Person();
|
||||||
|
jane.name = "Jane";
|
||||||
|
|
||||||
|
var method = jane.sayName;
|
||||||
|
method();
|
5
samples/ch28_this_outside.lox
Normal file
5
samples/ch28_this_outside.lox
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
print this;
|
||||||
|
|
||||||
|
fun invalid() {
|
||||||
|
print this;
|
||||||
|
}
|
21
samples/ch29_superclass.lox
Normal file
21
samples/ch29_superclass.lox
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
class Doughnut {
|
||||||
|
cook() {
|
||||||
|
print "Dunk in the fryer.";
|
||||||
|
}
|
||||||
|
|
||||||
|
zzz() {
|
||||||
|
print "Bla";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Cruller < Doughnut {
|
||||||
|
finish() {
|
||||||
|
print "Glaze with icing.";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var o2 = Cruller();
|
||||||
|
o2.cook();
|
||||||
|
o2.finish();
|
||||||
|
|
||||||
|
|
19
samples/ch29_superclass2.lox
Normal file
19
samples/ch29_superclass2.lox
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
class A {
|
||||||
|
method() {
|
||||||
|
print "A method";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class B < A {
|
||||||
|
method() {
|
||||||
|
print "B method";
|
||||||
|
}
|
||||||
|
|
||||||
|
test() {
|
||||||
|
this.method();
|
||||||
|
super.method();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class C < B {}
|
||||||
|
C().test();
|
2
samples/ch29_superclass_error.lox
Normal file
2
samples/ch29_superclass_error.lox
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
class Cake < Cake {
|
||||||
|
}
|
2
samples/ch29_superclass_error2.lox
Normal file
2
samples/ch29_superclass_error2.lox
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
var NotClass = "So not a class";
|
||||||
|
class OhNo < NotClass {}
|
17
samples/ch8_initalizers.lox
Normal file
17
samples/ch8_initalizers.lox
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
class Brunch {
|
||||||
|
var food;
|
||||||
|
var drink;
|
||||||
|
|
||||||
|
init(food, drink) {
|
||||||
|
this.food = food;
|
||||||
|
this.drink = drink;
|
||||||
|
}
|
||||||
|
|
||||||
|
fun get_recipe() {
|
||||||
|
return this.food + " " + this.drink;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var instance = Brunch("eggs", "coffee");
|
||||||
|
print instance;
|
||||||
|
print instance.get_recipe();
|
3
samples/indices.lox
Normal file
3
samples/indices.lox
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
var alphabet = "abcdefghijklmnopqrstuvwxyz"; var X = alphabet; print "hello " + X[3] + X[0] + X[10];
|
||||||
|
|
||||||
|
var s = " "; s[0] = "d"; s[1] = "a"; s[2] = "k"; var hey = "hello " + s + "!"; print hey;
|
@ -73,18 +73,18 @@ pub const Chunk = struct {
|
|||||||
debug.print("== end of chunk dump \n\n", .{});
|
debug.print("== end of chunk dump \n\n", .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn dissassemble(self: Chunk, name: []const u8) void {
|
pub fn disassemble(self: Chunk, name: []const u8) void {
|
||||||
debug.print("== {s} ==\n", .{name});
|
debug.print("== {s} ==\n", .{name});
|
||||||
|
|
||||||
var offset: usize = 0;
|
var offset: usize = 0;
|
||||||
|
|
||||||
while (offset < self.count) {
|
while (offset < self.count) {
|
||||||
offset = self.dissassemble_instruction(offset);
|
offset = self.disassemble_instruction(offset);
|
||||||
}
|
}
|
||||||
debug.print("== end of {s} ==\n\n", .{name});
|
debug.print("== end of {s} ==\n\n", .{name});
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn dissassemble_instruction(self: Chunk, offset: usize) usize {
|
pub fn disassemble_instruction(self: Chunk, offset: usize) usize {
|
||||||
var current_offset = offset;
|
var current_offset = offset;
|
||||||
debug.print("{d:0>4} ", .{offset});
|
debug.print("{d:0>4} ", .{offset});
|
||||||
|
|
||||||
@ -151,6 +151,13 @@ pub const Chunk = struct {
|
|||||||
@intFromEnum(OpCode.OP_CLASS) => return utils.constant_instruction("OP_CLASS", self, offset),
|
@intFromEnum(OpCode.OP_CLASS) => return utils.constant_instruction("OP_CLASS", self, offset),
|
||||||
@intFromEnum(OpCode.OP_GET_PROPERTY) => return utils.constant_instruction("OP_GET_PROPERTY", self, offset),
|
@intFromEnum(OpCode.OP_GET_PROPERTY) => return utils.constant_instruction("OP_GET_PROPERTY", self, offset),
|
||||||
@intFromEnum(OpCode.OP_SET_PROPERTY) => return utils.constant_instruction("OP_SET_PROPERTY", self, offset),
|
@intFromEnum(OpCode.OP_SET_PROPERTY) => return utils.constant_instruction("OP_SET_PROPERTY", self, offset),
|
||||||
|
@intFromEnum(OpCode.OP_METHOD) => return utils.constant_instruction("OP_METHOD", self, offset),
|
||||||
|
@intFromEnum(OpCode.OP_INDEX_GET) => return utils.simple_instruction("OP_INDEX_GET", offset),
|
||||||
|
@intFromEnum(OpCode.OP_INDEX_SET) => return utils.simple_instruction("OP_INDEX_SET", offset),
|
||||||
|
@intFromEnum(OpCode.OP_INVOKE) => return utils.invoke_instruction("OP_INVOKE", self, offset),
|
||||||
|
@intFromEnum(OpCode.OP_INHERIT) => return utils.simple_instruction("OP_INHERIT", offset),
|
||||||
|
@intFromEnum(OpCode.OP_GET_SUPER) => return utils.constant_instruction("OP_GET_SUPER", self, offset),
|
||||||
|
@intFromEnum(OpCode.OP_SUPER_INVOKE) => return utils.invoke_instruction("OP_SUPER_INVOKE", self, offset),
|
||||||
else => {
|
else => {
|
||||||
debug.print("unknown opcode {d}\n", .{instruction});
|
debug.print("unknown opcode {d}\n", .{instruction});
|
||||||
return offset + 1;
|
return offset + 1;
|
||||||
|
169
src/compile.zig
169
src/compile.zig
@ -29,12 +29,18 @@ const Precedence = enum {
|
|||||||
Term,
|
Term,
|
||||||
Factor,
|
Factor,
|
||||||
Unary,
|
Unary,
|
||||||
|
Index,
|
||||||
Call,
|
Call,
|
||||||
Primary,
|
Primary,
|
||||||
};
|
};
|
||||||
|
|
||||||
const ParserFn = *const fn (*Parser, bool) ParsingError!void;
|
const ParserFn = *const fn (*Parser, bool) ParsingError!void;
|
||||||
|
|
||||||
|
const ClassCompiler = struct {
|
||||||
|
enclosing: ?*ClassCompiler,
|
||||||
|
has_super_class: bool,
|
||||||
|
};
|
||||||
|
|
||||||
const ParserRule = struct {
|
const ParserRule = struct {
|
||||||
prefix: ?ParserFn,
|
prefix: ?ParserFn,
|
||||||
infix: ?ParserFn,
|
infix: ?ParserFn,
|
||||||
@ -49,6 +55,7 @@ pub const Parser = struct {
|
|||||||
had_error: bool,
|
had_error: bool,
|
||||||
panic_mode: bool,
|
panic_mode: bool,
|
||||||
vm: *VM,
|
vm: *VM,
|
||||||
|
class_compiler: ?*ClassCompiler,
|
||||||
|
|
||||||
fn new(vm: *VM, compiler: *Compiler, scanner: *Scanner) Parser {
|
fn new(vm: *VM, compiler: *Compiler, scanner: *Scanner) Parser {
|
||||||
return Parser{
|
return Parser{
|
||||||
@ -59,6 +66,7 @@ pub const Parser = struct {
|
|||||||
.had_error = false,
|
.had_error = false,
|
||||||
.panic_mode = false,
|
.panic_mode = false,
|
||||||
.vm = vm,
|
.vm = vm,
|
||||||
|
.class_compiler = null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -66,6 +74,10 @@ pub const Parser = struct {
|
|||||||
return self.compiler.function.chunk;
|
return self.compiler.function.chunk;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
inline fn current_class_compiler(self: *Parser) ?*ClassCompiler {
|
||||||
|
return self.class_compiler;
|
||||||
|
}
|
||||||
|
|
||||||
fn advance(self: *Parser) void {
|
fn advance(self: *Parser) void {
|
||||||
self.previous = self.current;
|
self.previous = self.current;
|
||||||
|
|
||||||
@ -134,15 +146,26 @@ pub const Parser = struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn emit_return(self: *Parser) ParsingError!void {
|
fn emit_return(self: *Parser) ParsingError!void {
|
||||||
try self.emit_byte(@intFromEnum(OpCode.OP_NIL));
|
if (self.compiler.function_type == FunctionType.Initializer) {
|
||||||
|
try self.emit_bytes(@intFromEnum(OpCode.OP_GET_LOCAL), 0);
|
||||||
|
} else {
|
||||||
|
try self.emit_byte(@intFromEnum(OpCode.OP_NIL));
|
||||||
|
}
|
||||||
|
|
||||||
try self.emit_byte(@intFromEnum(OpCode.OP_RETURN));
|
try self.emit_byte(@intFromEnum(OpCode.OP_RETURN));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn end_parser(self: *Parser) !*Obj.Function {
|
fn end_parser(self: *Parser) !*Obj.Function {
|
||||||
try self.emit_return();
|
try self.emit_return();
|
||||||
|
|
||||||
|
const compiler_function = self.compiler.function;
|
||||||
|
|
||||||
if (!self.had_error and constants.DEBUG_PRINT_CODE) {
|
if (!self.had_error and constants.DEBUG_PRINT_CODE) {
|
||||||
self.current_chunk().dissassemble("code");
|
var label: []const u8 = "<script>";
|
||||||
|
if (compiler_function.name != null) {
|
||||||
|
label = compiler_function.name.?.chars;
|
||||||
|
}
|
||||||
|
self.current_chunk().disassemble(label);
|
||||||
}
|
}
|
||||||
|
|
||||||
const function_obj = self.compiler.function;
|
const function_obj = self.compiler.function;
|
||||||
@ -191,6 +214,18 @@ pub const Parser = struct {
|
|||||||
self.consume(TokenType.RIGHT_PAREN, "Expect ')' after expression.");
|
self.consume(TokenType.RIGHT_PAREN, "Expect ')' after expression.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn index_(self: *Parser, can_assign: bool) ParsingError!void {
|
||||||
|
try self.expression();
|
||||||
|
self.consume(TokenType.RIGHT_BRACKET, "Expecting ']");
|
||||||
|
|
||||||
|
if (can_assign and self.match(TokenType.EQUAL)) {
|
||||||
|
try self.expression();
|
||||||
|
try self.emit_byte(@intFromEnum(OpCode.OP_INDEX_SET));
|
||||||
|
} else {
|
||||||
|
try self.emit_byte(@intFromEnum(OpCode.OP_INDEX_GET));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn unary(self: *Parser, can_assign: bool) ParsingError!void {
|
fn unary(self: *Parser, can_assign: bool) ParsingError!void {
|
||||||
_ = can_assign;
|
_ = can_assign;
|
||||||
|
|
||||||
@ -252,6 +287,8 @@ pub const Parser = struct {
|
|||||||
TokenType.DOT => ParserRule{ .prefix = null, .infix = dot, .precedence = Precedence.Call },
|
TokenType.DOT => ParserRule{ .prefix = null, .infix = dot, .precedence = Precedence.Call },
|
||||||
TokenType.MINUS => ParserRule{ .prefix = unary, .infix = binary, .precedence = Precedence.Term },
|
TokenType.MINUS => ParserRule{ .prefix = unary, .infix = binary, .precedence = Precedence.Term },
|
||||||
TokenType.PLUS => ParserRule{ .prefix = null, .infix = binary, .precedence = Precedence.Term },
|
TokenType.PLUS => ParserRule{ .prefix = null, .infix = binary, .precedence = Precedence.Term },
|
||||||
|
TokenType.LEFT_BRACKET => ParserRule{ .prefix = null, .infix = index_, .precedence = Precedence.Unary },
|
||||||
|
TokenType.RIGHT_BRACKET => ParserRule{ .prefix = null, .infix = null, .precedence = Precedence.None },
|
||||||
TokenType.SEMICOLON => ParserRule{ .prefix = null, .infix = null, .precedence = Precedence.None },
|
TokenType.SEMICOLON => ParserRule{ .prefix = null, .infix = null, .precedence = Precedence.None },
|
||||||
TokenType.SLASH => ParserRule{ .prefix = null, .infix = binary, .precedence = Precedence.Factor },
|
TokenType.SLASH => ParserRule{ .prefix = null, .infix = binary, .precedence = Precedence.Factor },
|
||||||
TokenType.STAR => ParserRule{ .prefix = null, .infix = binary, .precedence = Precedence.Factor },
|
TokenType.STAR => ParserRule{ .prefix = null, .infix = binary, .precedence = Precedence.Factor },
|
||||||
@ -277,8 +314,8 @@ pub const Parser = struct {
|
|||||||
TokenType.OR => ParserRule{ .prefix = null, .infix = or_, .precedence = Precedence.Or },
|
TokenType.OR => ParserRule{ .prefix = null, .infix = or_, .precedence = Precedence.Or },
|
||||||
TokenType.PRINT => ParserRule{ .prefix = null, .infix = null, .precedence = Precedence.None },
|
TokenType.PRINT => ParserRule{ .prefix = null, .infix = null, .precedence = Precedence.None },
|
||||||
TokenType.RETURN => ParserRule{ .prefix = null, .infix = null, .precedence = Precedence.None },
|
TokenType.RETURN => ParserRule{ .prefix = null, .infix = null, .precedence = Precedence.None },
|
||||||
TokenType.SUPER => ParserRule{ .prefix = null, .infix = null, .precedence = Precedence.None },
|
TokenType.SUPER => ParserRule{ .prefix = super_, .infix = null, .precedence = Precedence.None },
|
||||||
TokenType.THIS => ParserRule{ .prefix = null, .infix = null, .precedence = Precedence.None },
|
TokenType.THIS => ParserRule{ .prefix = this_, .infix = null, .precedence = Precedence.None },
|
||||||
TokenType.TRUE => ParserRule{ .prefix = literal, .infix = null, .precedence = Precedence.None },
|
TokenType.TRUE => ParserRule{ .prefix = literal, .infix = null, .precedence = Precedence.None },
|
||||||
TokenType.VAR => ParserRule{ .prefix = null, .infix = null, .precedence = Precedence.None },
|
TokenType.VAR => ParserRule{ .prefix = null, .infix = null, .precedence = Precedence.None },
|
||||||
TokenType.WHILE => ParserRule{ .prefix = null, .infix = null, .precedence = Precedence.None },
|
TokenType.WHILE => ParserRule{ .prefix = null, .infix = null, .precedence = Precedence.None },
|
||||||
@ -354,6 +391,17 @@ pub const Parser = struct {
|
|||||||
set_op = OpCode.OP_SET_GLOBAL;
|
set_op = OpCode.OP_SET_GLOBAL;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// handle assignments by index:
|
||||||
|
// - push value to the stack
|
||||||
|
// - modify it (through a OP_INDEX_SET)
|
||||||
|
// - update the variable
|
||||||
|
if (can_assign and self.match(TokenType.LEFT_BRACKET)) {
|
||||||
|
try self.emit_bytes(@intFromEnum(get_op), @intCast(arg));
|
||||||
|
try self.index_(can_assign);
|
||||||
|
try self.emit_bytes(@intFromEnum(set_op), @intCast(arg));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (can_assign and self.match(TokenType.EQUAL)) {
|
if (can_assign and self.match(TokenType.EQUAL)) {
|
||||||
try self.expression();
|
try self.expression();
|
||||||
try self.emit_bytes(@intFromEnum(set_op), @intCast(arg));
|
try self.emit_bytes(@intFromEnum(set_op), @intCast(arg));
|
||||||
@ -855,6 +903,9 @@ pub const Parser = struct {
|
|||||||
if (self.match(TokenType.SEMICOLON)) {
|
if (self.match(TokenType.SEMICOLON)) {
|
||||||
try self.emit_return();
|
try self.emit_return();
|
||||||
} else {
|
} else {
|
||||||
|
if (self.compiler.function_type == FunctionType.Initializer) {
|
||||||
|
self.error_msg("Can't return a value from an initialiaer");
|
||||||
|
}
|
||||||
try self.expression();
|
try self.expression();
|
||||||
self.consume(TokenType.SEMICOLON, "Expect ';' after return value.");
|
self.consume(TokenType.SEMICOLON, "Expect ';' after return value.");
|
||||||
try self.emit_byte(@intFromEnum(OpCode.OP_RETURN));
|
try self.emit_byte(@intFromEnum(OpCode.OP_RETURN));
|
||||||
@ -863,14 +914,62 @@ pub const Parser = struct {
|
|||||||
|
|
||||||
fn class_declaration(self: *Parser) ParsingError!void {
|
fn class_declaration(self: *Parser) ParsingError!void {
|
||||||
self.consume(TokenType.IDENTIFIER, "Expect class name.");
|
self.consume(TokenType.IDENTIFIER, "Expect class name.");
|
||||||
|
const class_name = self.previous.?;
|
||||||
|
|
||||||
const name_constant = try self.identifier_constant(self.previous.?);
|
const name_constant = try self.identifier_constant(self.previous.?);
|
||||||
self.declare_variable();
|
self.declare_variable();
|
||||||
|
|
||||||
try self.emit_bytes(@intFromEnum(OpCode.OP_CLASS), name_constant);
|
try self.emit_bytes(@intFromEnum(OpCode.OP_CLASS), name_constant);
|
||||||
try self.define_variable(name_constant);
|
try self.define_variable(name_constant);
|
||||||
|
|
||||||
|
var class_compiler = ClassCompiler{
|
||||||
|
.enclosing = self.current_class_compiler(),
|
||||||
|
.has_super_class = false,
|
||||||
|
};
|
||||||
|
self.class_compiler = &class_compiler;
|
||||||
|
|
||||||
|
if (self.match(TokenType.LESS)) {
|
||||||
|
self.consume(TokenType.IDENTIFIER, "Expect superclass name.");
|
||||||
|
try self.variable(false);
|
||||||
|
|
||||||
|
if (identifiers_equals(class_name, self.previous.?)) {
|
||||||
|
self.error_msg("A class can't inherit from itself.");
|
||||||
|
}
|
||||||
|
|
||||||
|
self.begin_scope();
|
||||||
|
self.add_local(self.synthetic_token("super"));
|
||||||
|
try self.define_variable(0);
|
||||||
|
|
||||||
|
try self.named_variable(class_name, false);
|
||||||
|
try self.emit_byte(@intFromEnum(OpCode.OP_INHERIT));
|
||||||
|
|
||||||
|
self.current_class_compiler().?.has_super_class = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
try self.named_variable(class_name, false);
|
||||||
|
|
||||||
self.consume(TokenType.LEFT_BRACE, "Expect '{' before class body.");
|
self.consume(TokenType.LEFT_BRACE, "Expect '{' before class body.");
|
||||||
|
while (!self.check(TokenType.RIGHT_BRACE) and !self.check(TokenType.EOF)) {
|
||||||
|
try self.method();
|
||||||
|
}
|
||||||
self.consume(TokenType.RIGHT_BRACE, "Expect '}' after class body.");
|
self.consume(TokenType.RIGHT_BRACE, "Expect '}' after class body.");
|
||||||
|
try self.emit_byte(@intFromEnum(OpCode.OP_POP));
|
||||||
|
|
||||||
|
if (self.current_class_compiler().?.has_super_class) {
|
||||||
|
try self.end_scope();
|
||||||
|
}
|
||||||
|
|
||||||
|
self.class_compiler = self.current_class_compiler().?.enclosing;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn synthetic_token(self: *Parser, text: []const u8) Token {
|
||||||
|
_ = self;
|
||||||
|
return Token{
|
||||||
|
.token_type = TokenType.EOF,
|
||||||
|
.start = text,
|
||||||
|
.length = text.len,
|
||||||
|
.line = 0,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
fn dot(self: *Parser, can_assign: bool) ParsingError!void {
|
fn dot(self: *Parser, can_assign: bool) ParsingError!void {
|
||||||
@ -880,15 +979,70 @@ pub const Parser = struct {
|
|||||||
if (can_assign and self.match(TokenType.EQUAL)) {
|
if (can_assign and self.match(TokenType.EQUAL)) {
|
||||||
try self.expression();
|
try self.expression();
|
||||||
try self.emit_bytes(@intFromEnum(OpCode.OP_SET_PROPERTY), name);
|
try self.emit_bytes(@intFromEnum(OpCode.OP_SET_PROPERTY), name);
|
||||||
|
} else if (self.match(TokenType.LEFT_PAREN)) {
|
||||||
|
const arg_count = try self.argument_list();
|
||||||
|
try self.emit_bytes(@intFromEnum(OpCode.OP_INVOKE), name);
|
||||||
|
try self.emit_byte(@intCast(arg_count));
|
||||||
} else {
|
} else {
|
||||||
try self.emit_bytes(@intFromEnum(OpCode.OP_GET_PROPERTY), name);
|
try self.emit_bytes(@intFromEnum(OpCode.OP_GET_PROPERTY), name);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn method(self: *Parser) ParsingError!void {
|
||||||
|
self.consume(TokenType.IDENTIFIER, "Expect method name.");
|
||||||
|
const constant = try self.identifier_constant(self.previous.?);
|
||||||
|
|
||||||
|
var function_type: FunctionType = FunctionType.Method;
|
||||||
|
// std.debug.print("len: {d} {s}\n", .{self.previous.?.length, });
|
||||||
|
if (self.previous.?.length == 4 and std.mem.eql(u8, self.previous.?.start[0..4], "init")) {
|
||||||
|
function_type = FunctionType.Initializer;
|
||||||
|
}
|
||||||
|
try self.function(function_type);
|
||||||
|
try self.emit_bytes(@intFromEnum(OpCode.OP_METHOD), constant);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn this_(self: *Parser, can_assign: bool) ParsingError!void {
|
||||||
|
if (self.current_class_compiler() == null) {
|
||||||
|
self.error_msg("Can't use 'this' outside of a class.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = can_assign;
|
||||||
|
try self.variable(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn super_(self: *Parser, can_assign: bool) ParsingError!void {
|
||||||
|
_ = can_assign;
|
||||||
|
|
||||||
|
if (self.current_class_compiler() == null) {
|
||||||
|
self.error_msg("Can't use 'super' outside of a class.");
|
||||||
|
} else if (!self.current_class_compiler().?.has_super_class) {
|
||||||
|
self.error_msg("Can't use 'super' in a class with no superclass.");
|
||||||
|
}
|
||||||
|
|
||||||
|
self.consume(TokenType.DOT, "Expect '.' after 'super'.");
|
||||||
|
self.consume(TokenType.IDENTIFIER, "Expect superclass method name.");
|
||||||
|
const name = try self.identifier_constant(self.previous.?);
|
||||||
|
|
||||||
|
try self.named_variable(self.synthetic_token("this"), false);
|
||||||
|
|
||||||
|
if (self.match(TokenType.LEFT_PAREN)) {
|
||||||
|
const arg_count = try self.argument_list();
|
||||||
|
try self.named_variable(self.synthetic_token("super"), false);
|
||||||
|
try self.emit_bytes(@intFromEnum(OpCode.OP_SUPER_INVOKE), name);
|
||||||
|
try self.emit_byte(@intCast(arg_count));
|
||||||
|
} else {
|
||||||
|
try self.named_variable(self.synthetic_token("super"), false);
|
||||||
|
try self.emit_bytes(@intFromEnum(OpCode.OP_GET_SUPER), name);
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const FunctionType = enum {
|
const FunctionType = enum {
|
||||||
Function,
|
Function,
|
||||||
Script,
|
Script,
|
||||||
|
Method,
|
||||||
|
Initializer,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const Compiler = struct {
|
pub const Compiler = struct {
|
||||||
@ -915,6 +1069,8 @@ pub const Compiler = struct {
|
|||||||
.enclosing = enclosing,
|
.enclosing = enclosing,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
compiler.local_count += 1;
|
||||||
|
|
||||||
compiler.locals[0].depth = 0;
|
compiler.locals[0].depth = 0;
|
||||||
compiler.locals[0].name = Token{
|
compiler.locals[0].name = Token{
|
||||||
.token_type = TokenType.EOF,
|
.token_type = TokenType.EOF,
|
||||||
@ -924,7 +1080,10 @@ pub const Compiler = struct {
|
|||||||
};
|
};
|
||||||
compiler.locals[0].is_captured = false;
|
compiler.locals[0].is_captured = false;
|
||||||
|
|
||||||
compiler.local_count += 1;
|
if (function_type != FunctionType.Function) {
|
||||||
|
compiler.locals[0].name.start = "this";
|
||||||
|
compiler.locals[0].name.length = 4;
|
||||||
|
}
|
||||||
|
|
||||||
return compiler;
|
return compiler;
|
||||||
}
|
}
|
||||||
|
@ -72,7 +72,6 @@ pub fn main() !void {
|
|||||||
} else {
|
} else {
|
||||||
vm.init_vm(allocator);
|
vm.init_vm(allocator);
|
||||||
}
|
}
|
||||||
|
|
||||||
defer vm.destroy();
|
defer vm.destroy();
|
||||||
|
|
||||||
if (args.len == 1) {
|
if (args.len == 1) {
|
||||||
|
@ -25,7 +25,7 @@ pub const ZloxAllocator = struct {
|
|||||||
.parent_allocator = parent_allocator,
|
.parent_allocator = parent_allocator,
|
||||||
.vm = vm,
|
.vm = vm,
|
||||||
.bytes_allocated = 0,
|
.bytes_allocated = 0,
|
||||||
.next_gc = 1024,
|
.next_gc = 4096,
|
||||||
.current_gc = false,
|
.current_gc = false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@ -145,6 +145,8 @@ pub const ZloxAllocator = struct {
|
|||||||
self.mark_table(&self.vm.globals);
|
self.mark_table(&self.vm.globals);
|
||||||
|
|
||||||
self.mark_compiler_roots();
|
self.mark_compiler_roots();
|
||||||
|
|
||||||
|
self.mark_object(&self.vm.init_string.?.obj);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn mark_value(self: *Self, value: *Value) void {
|
pub fn mark_value(self: *Self, value: *Value) void {
|
||||||
@ -237,12 +239,18 @@ pub const ZloxAllocator = struct {
|
|||||||
ObjType.Class => {
|
ObjType.Class => {
|
||||||
const class: *Obj.Class = obj.as_class();
|
const class: *Obj.Class = obj.as_class();
|
||||||
self.mark_object(&class.name.obj);
|
self.mark_object(&class.name.obj);
|
||||||
|
self.mark_table(&class.methods);
|
||||||
},
|
},
|
||||||
ObjType.Instance => {
|
ObjType.Instance => {
|
||||||
const instance: *Obj.Instance = obj.as_instance();
|
const instance: *Obj.Instance = obj.as_instance();
|
||||||
self.mark_object(&instance.class.obj);
|
self.mark_object(&instance.class.obj);
|
||||||
self.mark_table(&instance.fields);
|
self.mark_table(&instance.fields);
|
||||||
},
|
},
|
||||||
|
ObjType.BoundMethod => {
|
||||||
|
const bound_method: *Obj.BoundMethod = obj.as_bound_method();
|
||||||
|
self.mark_value(&bound_method.receiver);
|
||||||
|
self.mark_object(&bound_method.method.obj);
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -258,6 +266,9 @@ pub const ZloxAllocator = struct {
|
|||||||
for (0..table.capacity) |idx| {
|
for (0..table.capacity) |idx| {
|
||||||
const entry: *Entry = &table.entries[idx];
|
const entry: *Entry = &table.entries[idx];
|
||||||
if (entry.key != null and !entry.key.?.obj.is_marked) {
|
if (entry.key != null and !entry.key.?.obj.is_marked) {
|
||||||
|
if (comptime constants.DEBUG_LOG_GC) {
|
||||||
|
std.debug.print("GC: table_remove_white: deleting {s}\n", .{entry.key.?.chars});
|
||||||
|
}
|
||||||
_ = table.del(entry.key.?);
|
_ = table.del(entry.key.?);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -282,7 +293,7 @@ pub const ZloxAllocator = struct {
|
|||||||
self.vm.objects = object;
|
self.vm.objects = object;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (comptime constants.DEBUG_LOG_GC == true) {
|
if (comptime constants.DEBUG_LOG_GC) {
|
||||||
std.debug.print("GC: sweeping {*}: ", .{unreached});
|
std.debug.print("GC: sweeping {*}: ", .{unreached});
|
||||||
unreached.print();
|
unreached.print();
|
||||||
std.debug.print("\n", .{});
|
std.debug.print("\n", .{});
|
||||||
|
@ -17,6 +17,7 @@ pub const ObjType = enum {
|
|||||||
Upvalue,
|
Upvalue,
|
||||||
Class,
|
Class,
|
||||||
Instance,
|
Instance,
|
||||||
|
BoundMethod,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const NativeFn = *const fn (vm: *VM, arg_count: usize, args: []Value) Value;
|
pub const NativeFn = *const fn (vm: *VM, arg_count: usize, args: []Value) Value;
|
||||||
@ -51,6 +52,7 @@ pub const Obj = struct {
|
|||||||
ObjType.Upvalue => self.as_upvalue().destroy(),
|
ObjType.Upvalue => self.as_upvalue().destroy(),
|
||||||
ObjType.Class => self.as_class().destroy(),
|
ObjType.Class => self.as_class().destroy(),
|
||||||
ObjType.Instance => self.as_instance().destroy(),
|
ObjType.Instance => self.as_instance().destroy(),
|
||||||
|
ObjType.BoundMethod => self.as_bound_method().destroy(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -166,16 +168,19 @@ pub const Obj = struct {
|
|||||||
pub const Class = struct {
|
pub const Class = struct {
|
||||||
obj: Obj,
|
obj: Obj,
|
||||||
name: *Obj.String,
|
name: *Obj.String,
|
||||||
|
methods: Table,
|
||||||
|
|
||||||
pub fn new(vm: *VM, name: *Obj.String) *Class {
|
pub fn new(vm: *VM, name: *Obj.String) *Class {
|
||||||
const class_obj = Obj.new(Class, vm, ObjType.Class);
|
const class_obj = Obj.new(Class, vm, ObjType.Class);
|
||||||
|
|
||||||
class_obj.name = name;
|
class_obj.name = name;
|
||||||
|
class_obj.methods = Table.new(vm.allocator);
|
||||||
|
|
||||||
return class_obj;
|
return class_obj;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn destroy(self: *Class) void {
|
pub fn destroy(self: *Class) void {
|
||||||
|
self.methods.destroy();
|
||||||
self.obj.allocator.destroy(self);
|
self.obj.allocator.destroy(self);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -200,6 +205,25 @@ pub const Obj = struct {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
pub const BoundMethod = struct {
|
||||||
|
obj: Obj,
|
||||||
|
receiver: Value,
|
||||||
|
method: *Obj.Closure,
|
||||||
|
|
||||||
|
pub fn new(vm: *VM, receiver: Value, method: *Obj.Closure) *BoundMethod {
|
||||||
|
const bound_method = Obj.new(BoundMethod, vm, ObjType.BoundMethod);
|
||||||
|
|
||||||
|
bound_method.receiver = receiver;
|
||||||
|
bound_method.method = method;
|
||||||
|
|
||||||
|
return bound_method;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn destroy(self: *BoundMethod) void {
|
||||||
|
self.obj.allocator.destroy(self);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
pub fn is_type(self: *Obj, kind: ObjType) bool {
|
pub fn is_type(self: *Obj, kind: ObjType) bool {
|
||||||
return self.kind == kind;
|
return self.kind == kind;
|
||||||
}
|
}
|
||||||
@ -232,6 +256,10 @@ pub const Obj = struct {
|
|||||||
return self.is_type(ObjType.Instance);
|
return self.is_type(ObjType.Instance);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn is_bound_method(self: *Obj) bool {
|
||||||
|
return self.is_type(ObjType.BoundMethod);
|
||||||
|
}
|
||||||
|
|
||||||
pub fn print(self: *Obj) void {
|
pub fn print(self: *Obj) void {
|
||||||
switch (self.kind) {
|
switch (self.kind) {
|
||||||
ObjType.String => {
|
ObjType.String => {
|
||||||
@ -264,6 +292,10 @@ pub const Obj = struct {
|
|||||||
const obj = self.as_instance();
|
const obj = self.as_instance();
|
||||||
debug.print("{s} instance", .{obj.class.name.chars});
|
debug.print("{s} instance", .{obj.class.name.chars});
|
||||||
},
|
},
|
||||||
|
ObjType.BoundMethod => {
|
||||||
|
const obj = self.as_bound_method();
|
||||||
|
obj.method.function.obj.print();
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -301,4 +333,9 @@ pub const Obj = struct {
|
|||||||
std.debug.assert(self.kind == ObjType.Instance);
|
std.debug.assert(self.kind == ObjType.Instance);
|
||||||
return @fieldParentPtr("obj", self);
|
return @fieldParentPtr("obj", self);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn as_bound_method(self: *Obj) *BoundMethod {
|
||||||
|
std.debug.assert(self.kind == ObjType.BoundMethod);
|
||||||
|
return @fieldParentPtr("obj", self);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
@ -31,4 +31,11 @@ pub const OpCode = enum(u8) {
|
|||||||
OP_CLOSE_UPVALUE,
|
OP_CLOSE_UPVALUE,
|
||||||
OP_RETURN,
|
OP_RETURN,
|
||||||
OP_CLASS,
|
OP_CLASS,
|
||||||
|
OP_METHOD,
|
||||||
|
OP_INDEX_SET,
|
||||||
|
OP_INDEX_GET,
|
||||||
|
OP_INVOKE,
|
||||||
|
OP_INHERIT,
|
||||||
|
OP_GET_SUPER,
|
||||||
|
OP_SUPER_INVOKE,
|
||||||
};
|
};
|
||||||
|
@ -6,6 +6,8 @@ pub const TokenType = enum {
|
|||||||
RIGHT_PAREN,
|
RIGHT_PAREN,
|
||||||
LEFT_BRACE,
|
LEFT_BRACE,
|
||||||
RIGHT_BRACE,
|
RIGHT_BRACE,
|
||||||
|
LEFT_BRACKET,
|
||||||
|
RIGHT_BRACKET,
|
||||||
COMMA,
|
COMMA,
|
||||||
DOT,
|
DOT,
|
||||||
MINUS,
|
MINUS,
|
||||||
@ -55,6 +57,8 @@ pub const TokenType = enum {
|
|||||||
TokenType.RIGHT_PAREN => "RIGHT_PAREN",
|
TokenType.RIGHT_PAREN => "RIGHT_PAREN",
|
||||||
TokenType.LEFT_BRACE => "LEFT_BRACE",
|
TokenType.LEFT_BRACE => "LEFT_BRACE",
|
||||||
TokenType.RIGHT_BRACE => "RIGHT_BRACE",
|
TokenType.RIGHT_BRACE => "RIGHT_BRACE",
|
||||||
|
TokenType.LEFT_BRACKET => "LEFT_BRACKET",
|
||||||
|
TokenType.RIGHT_BRACKET => "RIGHT_BRACKET",
|
||||||
TokenType.COMMA => "COMMA",
|
TokenType.COMMA => "COMMA",
|
||||||
TokenType.DOT => "DOT",
|
TokenType.DOT => "DOT",
|
||||||
TokenType.MINUS => "MINUS",
|
TokenType.MINUS => "MINUS",
|
||||||
@ -140,6 +144,8 @@ pub const Scanner = struct {
|
|||||||
')' => self.make_token(TokenType.RIGHT_PAREN),
|
')' => self.make_token(TokenType.RIGHT_PAREN),
|
||||||
'{' => self.make_token(TokenType.LEFT_BRACE),
|
'{' => self.make_token(TokenType.LEFT_BRACE),
|
||||||
'}' => self.make_token(TokenType.RIGHT_BRACE),
|
'}' => self.make_token(TokenType.RIGHT_BRACE),
|
||||||
|
'[' => self.make_token(TokenType.LEFT_BRACKET),
|
||||||
|
']' => self.make_token(TokenType.RIGHT_BRACKET),
|
||||||
';' => self.make_token(TokenType.SEMICOLON),
|
';' => self.make_token(TokenType.SEMICOLON),
|
||||||
',' => self.make_token(TokenType.COMMA),
|
',' => self.make_token(TokenType.COMMA),
|
||||||
'.' => self.make_token(TokenType.DOT),
|
'.' => self.make_token(TokenType.DOT),
|
||||||
|
@ -61,11 +61,11 @@ pub const Table = struct {
|
|||||||
|
|
||||||
pub fn find_entry(entries: []Entry, key: *Obj.String) ?*Entry {
|
pub fn find_entry(entries: []Entry, key: *Obj.String) ?*Entry {
|
||||||
var tombstone: ?*Entry = null;
|
var tombstone: ?*Entry = null;
|
||||||
var index = key.hash % entries.len;
|
// var index = key.hash % entries.len;
|
||||||
|
var index = key.hash & (entries.len - 1);
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
const entry = &entries[index];
|
const entry = &entries[index];
|
||||||
|
|
||||||
if (entry.key == null) {
|
if (entry.key == null) {
|
||||||
if (entry.value.is_nil()) {
|
if (entry.value.is_nil()) {
|
||||||
// Empty entry.
|
// Empty entry.
|
||||||
@ -85,7 +85,8 @@ pub const Table = struct {
|
|||||||
return entry;
|
return entry;
|
||||||
}
|
}
|
||||||
|
|
||||||
index = (index + 1) % entries.len;
|
// index = (index + 1) % entries.len;
|
||||||
|
index = (index + 1) & (entries.len - 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -121,7 +122,7 @@ pub const Table = struct {
|
|||||||
std.debug.print("== Hash table count:{} capacity:{} ==\n", .{ self.count, self.capacity });
|
std.debug.print("== Hash table count:{} capacity:{} ==\n", .{ self.count, self.capacity });
|
||||||
for (self.entries, 0..) |entry, idx| {
|
for (self.entries, 0..) |entry, idx| {
|
||||||
if (entry.key != null) {
|
if (entry.key != null) {
|
||||||
std.debug.print("{d} ({d}) - {s}: ", .{ idx, entry.key.?.hash, entry.key.?.chars });
|
std.debug.print("{d} {*} (size: {d} hash:{d}) - {s}: ", .{ idx, entry.key, entry.key.?.chars.len, entry.key.?.hash, entry.key.?.chars });
|
||||||
entry.value.type_print();
|
entry.value.type_print();
|
||||||
std.debug.print("\n", .{});
|
std.debug.print("\n", .{});
|
||||||
}
|
}
|
||||||
@ -133,12 +134,12 @@ pub const Table = struct {
|
|||||||
std.debug.print("== End of hash table ==\n\n", .{});
|
std.debug.print("== End of hash table ==\n\n", .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn add_all(self: *Table, from: Table) void {
|
pub fn add_all(self: *Table, to: *Table) void {
|
||||||
for (from.entries) |entry| {
|
for (self.entries) |entry| {
|
||||||
if (entry.key == null) {
|
if (entry.key == null) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
_ = self.set(entry.key.?, entry.value);
|
_ = to.set(entry.key.?, entry.value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -180,7 +181,8 @@ pub const Table = struct {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
var index = hash % self.capacity;
|
// var index = hash % self.capacity;
|
||||||
|
var index = hash & (self.capacity - 1);
|
||||||
while (true) {
|
while (true) {
|
||||||
const entry = &self.entries[index];
|
const entry = &self.entries[index];
|
||||||
if (entry.key == null) {
|
if (entry.key == null) {
|
||||||
@ -192,7 +194,8 @@ pub const Table = struct {
|
|||||||
return entry.key;
|
return entry.key;
|
||||||
}
|
}
|
||||||
|
|
||||||
index = (index + 1) % self.capacity;
|
// index = (index + 1) % self.capacity;
|
||||||
|
index = (index + 1) & (self.capacity - 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
@ -55,3 +55,14 @@ pub fn identifiers_equals(a: Token, b: Token) bool {
|
|||||||
|
|
||||||
return std.mem.eql(u8, a.start[0..a.length], b.start[0..b.length]);
|
return std.mem.eql(u8, a.start[0..a.length], b.start[0..b.length]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn invoke_instruction(opcode_name: []const u8, chunk: Chunk, offset: usize) usize {
|
||||||
|
const constant = chunk.code[offset + 1];
|
||||||
|
const arg_count = chunk.code[offset + 2];
|
||||||
|
|
||||||
|
std.debug.print("{s:<16} ({d} args) {d:4} '", .{ opcode_name, arg_count, constant });
|
||||||
|
chunk.constants.values[constant].print();
|
||||||
|
std.debug.print("'\n", .{});
|
||||||
|
|
||||||
|
return offset + 3;
|
||||||
|
}
|
||||||
|
160
src/vm.zig
160
src/vm.zig
@ -49,6 +49,7 @@ pub const VM = struct {
|
|||||||
gray_count: usize,
|
gray_count: usize,
|
||||||
gray_capacity: usize,
|
gray_capacity: usize,
|
||||||
gray_stack: ?[]*Obj,
|
gray_stack: ?[]*Obj,
|
||||||
|
init_string: ?*Obj.String,
|
||||||
|
|
||||||
pub fn new() VM {
|
pub fn new() VM {
|
||||||
const vm = VM{
|
const vm = VM{
|
||||||
@ -65,6 +66,7 @@ pub const VM = struct {
|
|||||||
.gray_capacity = 0,
|
.gray_capacity = 0,
|
||||||
.gray_count = 0,
|
.gray_count = 0,
|
||||||
.gray_stack = &.{},
|
.gray_stack = &.{},
|
||||||
|
.init_string = null,
|
||||||
};
|
};
|
||||||
|
|
||||||
return vm;
|
return vm;
|
||||||
@ -75,6 +77,9 @@ pub const VM = struct {
|
|||||||
self.globals = Table.new(self.allocator);
|
self.globals = Table.new(self.allocator);
|
||||||
self.strings = Table.new(self.allocator);
|
self.strings = Table.new(self.allocator);
|
||||||
|
|
||||||
|
_ = try self.push(Value.obj_val(&self.copy_string("init").obj));
|
||||||
|
self.init_string = self.pop().as_string();
|
||||||
|
|
||||||
self.define_native("clock", natives.clock);
|
self.define_native("clock", natives.clock);
|
||||||
self.define_native("power", natives.power);
|
self.define_native("power", natives.power);
|
||||||
self.define_native("str2num", natives.str2num);
|
self.define_native("str2num", natives.str2num);
|
||||||
@ -88,6 +93,7 @@ pub const VM = struct {
|
|||||||
|
|
||||||
self.strings.destroy();
|
self.strings.destroy();
|
||||||
self.globals.destroy();
|
self.globals.destroy();
|
||||||
|
self.init_string = null;
|
||||||
self.destroy_objects();
|
self.destroy_objects();
|
||||||
|
|
||||||
if (self.gray_stack != null) {
|
if (self.gray_stack != null) {
|
||||||
@ -108,7 +114,9 @@ pub const VM = struct {
|
|||||||
var obj = self.objects;
|
var obj = self.objects;
|
||||||
while (obj != null) {
|
while (obj != null) {
|
||||||
const obj_next = obj.?.next;
|
const obj_next = obj.?.next;
|
||||||
std.debug.print("OBJ: {*}\n", .{obj.?});
|
std.debug.print("OBJ: {*} {any}", .{ obj.?, obj.?.kind });
|
||||||
|
// obj.?.print();
|
||||||
|
std.debug.print("\n", .{});
|
||||||
obj = obj_next;
|
obj = obj_next;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -148,7 +156,7 @@ pub const VM = struct {
|
|||||||
}
|
}
|
||||||
debug.print("\n", .{});
|
debug.print("\n", .{});
|
||||||
}
|
}
|
||||||
_ = self.current_chunk().dissassemble_instruction(self.current_frame().ip);
|
_ = self.current_chunk().disassemble_instruction(self.current_frame().ip);
|
||||||
}
|
}
|
||||||
|
|
||||||
const instruction = self.read_byte();
|
const instruction = self.read_byte();
|
||||||
@ -311,8 +319,9 @@ pub const VM = struct {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.runtime_error("Undefined property"); // XXX to complete with name.chars
|
if (!self.bind_method(instance.class, name)) {
|
||||||
return InterpretResult.RUNTIME_ERROR;
|
return InterpretResult.RUNTIME_ERROR;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
@intFromEnum(OpCode.OP_SET_PROPERTY) => {
|
@intFromEnum(OpCode.OP_SET_PROPERTY) => {
|
||||||
if (!self.peek(1).is_obj() or !self.peek(1).as_obj().is_instance()) {
|
if (!self.peek(1).is_obj() or !self.peek(1).as_obj().is_instance()) {
|
||||||
@ -326,6 +335,79 @@ pub const VM = struct {
|
|||||||
_ = self.pop();
|
_ = self.pop();
|
||||||
_ = try self.push(value);
|
_ = try self.push(value);
|
||||||
},
|
},
|
||||||
|
@intFromEnum(OpCode.OP_METHOD) => {
|
||||||
|
self.define_method(self.read_constant().as_string());
|
||||||
|
},
|
||||||
|
@intFromEnum(OpCode.OP_INDEX_GET) => {
|
||||||
|
if (!self.peek(0).is_number() or !self.peek(1).is_string()) {
|
||||||
|
self.runtime_error("A number and a string are required for indexes.");
|
||||||
|
return InterpretResult.RUNTIME_ERROR;
|
||||||
|
}
|
||||||
|
const index_val = self.pop();
|
||||||
|
const value = self.pop();
|
||||||
|
|
||||||
|
const index: usize = @as(usize, @intFromFloat(index_val.as_number()));
|
||||||
|
if (index >= value.as_cstring().len) {
|
||||||
|
self.runtime_error("The index must be set between 0 and string len.");
|
||||||
|
return InterpretResult.RUNTIME_ERROR;
|
||||||
|
}
|
||||||
|
const c = value.as_cstring()[index .. index + 1];
|
||||||
|
|
||||||
|
_ = try self.push(Value.obj_val(&self.copy_string(c).obj));
|
||||||
|
},
|
||||||
|
@intFromEnum(OpCode.OP_INDEX_SET) => {
|
||||||
|
const value = self.pop();
|
||||||
|
const index_val = self.pop();
|
||||||
|
const origin = self.pop();
|
||||||
|
|
||||||
|
if (!value.is_string() or value.as_cstring().len != 1) {
|
||||||
|
self.runtime_error("Value to assign must be one byte.");
|
||||||
|
return InterpretResult.RUNTIME_ERROR;
|
||||||
|
}
|
||||||
|
|
||||||
|
const index: usize = @as(usize, @intFromFloat(index_val.as_number()));
|
||||||
|
|
||||||
|
var str = self.allocator.dupe(u8, origin.as_cstring()) catch unreachable;
|
||||||
|
str[index] = value.as_cstring()[0];
|
||||||
|
|
||||||
|
_ = try self.push(Value.obj_val(&self.take_string(str).obj));
|
||||||
|
},
|
||||||
|
@intFromEnum(OpCode.OP_INVOKE) => {
|
||||||
|
const method = self.read_constant().as_string();
|
||||||
|
const arg_count = self.read_byte();
|
||||||
|
if (!self.invoke(method, arg_count)) {
|
||||||
|
return InterpretResult.RUNTIME_ERROR;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
@intFromEnum(OpCode.OP_INHERIT) => {
|
||||||
|
const superclass = self.peek(1);
|
||||||
|
const subclass = self.peek(0).as_obj().as_class();
|
||||||
|
|
||||||
|
if (!superclass.is_obj() or !superclass.as_obj().is_class()) {
|
||||||
|
self.runtime_error("Superclass must be a class.");
|
||||||
|
return InterpretResult.RUNTIME_ERROR;
|
||||||
|
}
|
||||||
|
|
||||||
|
superclass.as_obj().as_class().methods.add_all(&subclass.methods);
|
||||||
|
_ = self.pop(); // subclass
|
||||||
|
},
|
||||||
|
@intFromEnum(OpCode.OP_GET_SUPER) => {
|
||||||
|
const name: *Obj.String = self.read_constant().as_string();
|
||||||
|
const superclass = self.pop().as_obj().as_class();
|
||||||
|
|
||||||
|
if (!self.bind_method(superclass, name)) {
|
||||||
|
return InterpretResult.RUNTIME_ERROR;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
@intFromEnum(OpCode.OP_SUPER_INVOKE) => {
|
||||||
|
const method = self.read_constant().as_string();
|
||||||
|
const arg_count = self.read_byte();
|
||||||
|
const superclass = self.pop().as_obj().as_class();
|
||||||
|
|
||||||
|
if (!self.invoke_from_class(superclass, method, arg_count)) {
|
||||||
|
return InterpretResult.RUNTIME_ERROR;
|
||||||
|
}
|
||||||
|
},
|
||||||
else => {
|
else => {
|
||||||
debug.print("Invalid instruction: {d}\n", .{instruction});
|
debug.print("Invalid instruction: {d}\n", .{instruction});
|
||||||
return InterpretResult.RUNTIME_ERROR;
|
return InterpretResult.RUNTIME_ERROR;
|
||||||
@ -496,8 +578,21 @@ pub const VM = struct {
|
|||||||
const class = callee.as_obj().as_class();
|
const class = callee.as_obj().as_class();
|
||||||
self.stack[self.stack_top - arg_count - 1] = Value.obj_val(&Obj.Instance.new(self, class).obj);
|
self.stack[self.stack_top - arg_count - 1] = Value.obj_val(&Obj.Instance.new(self, class).obj);
|
||||||
|
|
||||||
|
var initializer = Value.nil_val();
|
||||||
|
|
||||||
|
if (class.methods.get(self.init_string.?, &initializer) == true) {
|
||||||
|
return self.call(initializer.as_obj().as_closure(), arg_count);
|
||||||
|
} else if (arg_count != 0) {
|
||||||
|
self.runtime_error("Expected 0 arguments."); // XXX show number of arguments.
|
||||||
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
|
ObjType.BoundMethod => {
|
||||||
|
const bound_method = callee.as_obj().as_bound_method();
|
||||||
|
self.stack[self.stack_top - arg_count - 1] = bound_method.receiver;
|
||||||
|
return self.call(bound_method.method, arg_count);
|
||||||
|
},
|
||||||
else => {},
|
else => {},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -505,10 +600,29 @@ pub const VM = struct {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn bind_method(self: *VM, class: *Obj.Class, name: *Obj.String) bool {
|
||||||
|
var method: Value = Value.nil_val();
|
||||||
|
|
||||||
|
if (!class.methods.get(name, &method)) {
|
||||||
|
const err_msg = std.fmt.allocPrint(self.allocator, "Undefined property '{s}'.", .{name.chars}) catch unreachable;
|
||||||
|
defer self.allocator.free(err_msg);
|
||||||
|
self.runtime_error(err_msg);
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bound: *Obj.BoundMethod = Obj.BoundMethod.new(self, self.peek(0), method.as_obj().as_closure());
|
||||||
|
_ = self.pop();
|
||||||
|
try self.push(Value.obj_val(&bound.obj));
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
pub fn call(self: *VM, closure: *Obj.Closure, arg_count: usize) bool {
|
pub fn call(self: *VM, closure: *Obj.Closure, arg_count: usize) bool {
|
||||||
if (arg_count != closure.function.arity) {
|
if (arg_count != closure.function.arity) {
|
||||||
self.runtime_error("Invalid argument count.");
|
const err_msg = std.fmt.allocPrint(self.allocator, "Expected {d} arguments but got {d}.", .{ closure.function.arity, arg_count }) catch unreachable;
|
||||||
// runtimeError("Expected %d arguments but got %d.", function->arity, argCount);
|
defer self.allocator.free(err_msg);
|
||||||
|
self.runtime_error(err_msg);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -571,4 +685,38 @@ pub const VM = struct {
|
|||||||
self.open_upvalues = upvalue.next;
|
self.open_upvalues = upvalue.next;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn define_method(self: *VM, name: *Obj.String) void {
|
||||||
|
const method = self.peek(0);
|
||||||
|
const class = self.peek(1).as_obj().as_class();
|
||||||
|
|
||||||
|
_ = class.methods.set(name, method);
|
||||||
|
_ = self.pop();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn invoke(self: *VM, name: *Obj.String, arg_count: usize) bool {
|
||||||
|
const receiver = self.peek(arg_count);
|
||||||
|
const instance = receiver.as_obj().as_instance();
|
||||||
|
|
||||||
|
var value = Value.nil_val();
|
||||||
|
if (instance.fields.get(name, &value)) {
|
||||||
|
self.stack[self.stack_top - arg_count - 1] = value;
|
||||||
|
|
||||||
|
return self.call_value(value, arg_count);
|
||||||
|
}
|
||||||
|
|
||||||
|
return self.invoke_from_class(instance.class, name, arg_count);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn invoke_from_class(self: *VM, class: *Obj.Class, name: *Obj.String, arg_count: usize) bool {
|
||||||
|
var method = Value.nil_val();
|
||||||
|
if (!class.methods.get(name, &method)) {
|
||||||
|
const err_msg = std.fmt.allocPrint(self.allocator, "Undefined property '{s}'.", .{name.chars}) catch unreachable;
|
||||||
|
defer self.allocator.free(err_msg);
|
||||||
|
self.runtime_error(err_msg);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return self.call(method.as_obj().as_closure(), arg_count);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
Reference in New Issue
Block a user