add test for uninitialized vars

FossilOrigin-Name: 9b734dc92b4bca6a25fde30f556565d5a48a64f9a9531c89f2927f6674e82a70
private
alpha 2 years ago
parent e21f070968
commit 42dd033fb4

@ -40,9 +40,7 @@ module Lox
def run(src) def run(src)
super super
rescue Lox::ParseError => e rescue Lox::ParseError, Lox::RuntimeError => e
STDERR.puts e.message
rescue Lox::RuntimeError => e
STDERR.puts e.message STDERR.puts e.message
end end

@ -14,11 +14,13 @@ module Lox
def get(token) def get(token)
name = token.lexeme name = token.lexeme
@values.fetch(name) { if @values.has_key?(name)
raise RuntimeError.new(token, "Undefined variable '#{name}'.") if @enclosing.nil? @values[name]
elsif @enclosing
@enclosing.get(token) @enclosing.get(token)
} else
raise RuntimeError.new(token, "Undefined variable '#{name}'.")
end
end end
def assign(name, value) def assign(name, value)
@ -26,15 +28,11 @@ module Lox
if @values.has_key?(lexeme) if @values.has_key?(lexeme)
@values[lexeme] = value @values[lexeme] = value
return elsif @enclosing
end
unless @enclosing.nil?
@enclosing.assign(name, value) @enclosing.assign(name, value)
return else
end
raise RuntimeError.new(name, "Undefined variable '#{lexeme}'.") raise RuntimeError.new(name, "Undefined variable '#{lexeme}'.")
end end
end end
end
end end

@ -150,13 +150,19 @@ class TestInterpreter < Lox::Test
SRC SRC
end end
def test_uninitialized_vars_are_nil
assert_interpreted <<~EXPECTED.chomp, <<~SRC
nil
EXPECTED
var a;
print a;
SRC
end
private private
def assert_interpreted(expected, src) def assert_interpreted(expected, src)
output = with_stdout { output = interpret(src)
stmts = Lox::Parser.new(@scanner.scan(src)).parse!
@interpreter.interpret(stmts)
}
assert_equal expected, output assert_equal expected, output
end end
@ -175,4 +181,11 @@ class TestInterpreter < Lox::Test
output output
end end
def interpret(src)
with_stdout {
stmts = Lox::Parser.new(@scanner.scan(src)).parse!
@interpreter.interpret(stmts)
}
end
end end

Loading…
Cancel
Save