Alpha Chen 2 years ago
parent f83031935f
commit 766f281a5e

@ -0,0 +1,11 @@
module Lox
class Instance
def initialize(klass)
@klass = klass
end
def to_s = "#{@klass.name} instance"
end
end

@ -1,5 +1,6 @@
require_relative "environment"
require_relative "function"
require_relative "lox_class"
module Lox
class Interpreter
@ -43,6 +44,13 @@ module Lox
nil
end
def visit_class(stmt)
@env.define(stmt.name.lexeme, nil)
klass = LoxClass.new(stmt.name.lexeme)
@env.assign(stmt.name, klass)
nil
end
def execute_block(stmts, env)
prev_env = @env
@env = env

@ -24,6 +24,12 @@ module Lox
nil
end
def visit_class(stmt)
declare(stmt.name)
define(stmt.name)
nil
end
def visit_expr(stmt) = resolve(stmt.expr)
def visit_function(stmt)

@ -306,6 +306,36 @@ class TestInterpreter < Lox::Test
SRC
end
def test_class
assert_interpreted "", <<~SRC
class Breakfast {
cook() {
print "Eggs a-fryin'!";
}
serve(who) {
print "Enjoy your breakfast, " + who + ".";
}
}
SRC
assert_interpreted "DevonshireCream", <<~SRC
class DevonshireCream {
serveOn() {
return "Scones";
}
}
print DevonshireCream; // Prints "DevonshireCream".
SRC
assert_interpreted "Bagel instance", <<~SRC
class Bagel {}
var bagel = Bagel();
print bagel; // Prints "Bagel instance".
SRC
end
private
def assert_interpreted(expected, src)

Loading…
Cancel
Save