main
Alpha Chen 2 years ago
parent ec7a788377
commit ac36917f76

@ -8,6 +8,7 @@ module Lox
@scopes = [] @scopes = []
@current_func = :NONE @current_func = :NONE
@current_class = :NONE
end end
def resolve(*resolvees) def resolve(*resolvees)
@ -25,6 +26,7 @@ module Lox
end end
def visit_class(stmt) def visit_class(stmt)
with_current_class(:CLASS) do
declare(stmt.name) declare(stmt.name)
with_scope do with_scope do
@ -36,6 +38,7 @@ module Lox
define(stmt.name) define(stmt.name)
end end
end
nil nil
end end
@ -104,6 +107,8 @@ module Lox
end end
def visit_this(expr) def visit_this(expr)
raise ResolverError.new(expr.keyword, "Can't use 'this' outside of a class.") if @current_class == :NONE
resolve_local(expr, expr.keyword) resolve_local(expr, expr.keyword)
nil nil
end end
@ -163,5 +168,14 @@ module Lox
@current_func = enclosing_func @current_func = enclosing_func
end end
def with_current_class(type)
enclosing_class = @current_class
@current_class = type
yield
@current_class = enclosing_class
end
end end
end end

@ -402,6 +402,20 @@ class TestInterpreter < Lox::Test
SRC SRC
end end
def test_invalid_this
assert_raises Lox::ResolverError, "Can't use 'this' outside of a class." do
interpret("print this;")
end
assert_raises Lox::ResolverError, "Can't use 'this' outside of a class." do
interpret(<<~SRC)
fun notAMethod() {
print this;
}
SRC
end
end
private private
def assert_interpreted(expected, src) def assert_interpreted(expected, src)

Loading…
Cancel
Save