main
Alpha Chen 2 years ago
parent a944813d0d
commit 91dc2b2c66

@ -1,8 +1,11 @@
require_relative "environment"
require_relative "function"
module Lox
class Interpreter
attr_reader :globals
def initialize(env=Environment.new)
@globals = env
@env = @globals
@ -46,6 +49,12 @@ module Lox
nil
end
def visit_function(stmt)
function = Function.new(stmt)
@env.define(stmt.name.lexeme, function)
nil
end
def visit_if(stmt)
if truthy?(evaluate(stmt.cond))
evaluate(stmt.then)

@ -13,7 +13,7 @@ module Lox
end
stmt :Block, :stmts
stmt :Fun, :name, :params, :body
stmt :Function, :name, :params, :body
stmt :Expr, :expr
stmt :If, :cond, :then, :else
stmt :Print, :expr

@ -224,6 +224,17 @@ class TestInterpreter < Lox::Test
SRC
end
def test_function
assert_interpreted <<~EXPECTED.chomp, <<~SRC
Hi, Dear Reader!
EXPECTED
fun sayHi(first, last) {
print "Hi, " + first + " " + last + "!";
}
sayHi("Dear", "Reader");
SRC
end
private
def assert_interpreted(expected, src)

Loading…
Cancel
Save