@ -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)
def visit_if(stmt)
if truthy?(evaluate(stmt.cond))
evaluate(stmt.then)
@ -13,7 +13,7 @@ module Lox
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
def test_function
assert_interpreted <<~EXPECTED.chomp, <<~SRC
Hi, Dear Reader!
EXPECTED
fun sayHi(first, last) {
print "Hi, " + first + " " + last + "!";
}
sayHi("Dear", "Reader");
private
def assert_interpreted(expected, src)