main
Alpha Chen 2 years ago
parent c697f9480b
commit 7c4aaa5e3c

@ -33,7 +33,8 @@ module Lox
@scopes.last["this"] = true @scopes.last["this"] = true
stmt.methods.each do |method| stmt.methods.each do |method|
resolve_function(method, :METHOD) decl = method.name.lexeme == "init" ? :INIT : :METHOD
resolve_function(method, decl)
end end
define(stmt.name) define(stmt.name)
@ -59,9 +60,15 @@ module Lox
end end
def visit_print(stmt) = resolve(stmt.expr) def visit_print(stmt) = resolve(stmt.expr)
def visit_return(stmt) def visit_return(stmt)
raise ResolverError.new(stmt.keyword, "Can't return from top-level code.") if @current_func == :NONE raise ResolverError.new(stmt.keyword, "Can't return from top-level code.") if @current_func == :NONE
resolve(stmt.value) if stmt.value
return unless stmt.value
raise ResolverError.new(stmt.keyword, "Can't return a value from an initializer.") if @current_func == :INIT
resolve(stmt.value)
end end
def visit_var(stmt) def visit_var(stmt)

@ -431,6 +431,24 @@ class TestInterpreter < Lox::Test
var foo = Foo(); var foo = Foo();
print foo.init(); print foo.init();
SRC SRC
assert_raises Lox::ResolverError do
interpret(<<~SRC)
class Foo {
init() {
return "something else";
}
}
SRC
end
assert_interpreted "", <<~SRC
class Foo {
init() {
return;
}
}
SRC
end end
private private

Loading…
Cancel
Save