2014-05-05 09:02:02 +02:00
|
|
|
module Ast
|
|
|
|
class FunctionExpression < Expression
|
2014-06-04 21:03:45 +02:00
|
|
|
# attr_reader :name, :params, :body , :receiver
|
2014-06-10 22:57:56 +02:00
|
|
|
def compile context
|
2014-05-10 16:55:02 +02:00
|
|
|
args = []
|
2014-05-13 17:21:24 +02:00
|
|
|
locals = {}
|
2014-05-13 15:24:19 +02:00
|
|
|
params.each_with_index do |param , index|
|
|
|
|
arg = param.name
|
2014-06-10 12:29:01 +02:00
|
|
|
register = Vm::RegisterUse.new(Vm::RegisterMachine.instance.receiver_register).next_reg_use(index + 1)
|
|
|
|
arg_value = Vm::Integer.new(register)
|
2014-05-13 17:21:24 +02:00
|
|
|
locals[arg] = arg_value
|
2014-05-13 15:24:19 +02:00
|
|
|
args << arg_value
|
2014-05-10 16:55:02 +02:00
|
|
|
end
|
2014-06-02 14:11:48 +02:00
|
|
|
# class depends on receiver
|
2014-06-10 12:29:01 +02:00
|
|
|
me = Vm::Integer.new( Vm::RegisterMachine.instance.receiver_register )
|
2014-06-03 13:49:02 +02:00
|
|
|
if receiver.nil?
|
|
|
|
clazz = context.current_class
|
|
|
|
else
|
|
|
|
c = context.object_space.get_or_create_class receiver.name.to_sym
|
|
|
|
clazz = c.meta_class
|
|
|
|
end
|
|
|
|
|
2014-06-06 20:49:03 +02:00
|
|
|
function = Vm::Function.new(name , me , args )
|
2014-06-03 13:49:02 +02:00
|
|
|
clazz.add_function function
|
2014-05-13 20:06:12 +02:00
|
|
|
|
2014-05-13 17:21:24 +02:00
|
|
|
parent_locals = context.locals
|
|
|
|
parent_function = context.function
|
|
|
|
context.locals = locals
|
|
|
|
context.function = function
|
|
|
|
|
2014-05-25 07:43:07 +02:00
|
|
|
last_compiled = nil
|
2014-05-14 10:33:23 +02:00
|
|
|
body.each do |b|
|
2014-06-02 14:11:48 +02:00
|
|
|
puts "compiling in function #{b}"
|
2014-06-10 22:57:56 +02:00
|
|
|
last_compiled = b.compile(context)
|
2014-05-25 07:43:07 +02:00
|
|
|
raise "alarm #{last_compiled} \n #{b}" unless last_compiled.is_a? Vm::Word
|
2014-05-10 09:58:25 +02:00
|
|
|
end
|
2014-05-25 07:43:07 +02:00
|
|
|
|
2014-06-10 12:29:01 +02:00
|
|
|
return_reg = Vm::Integer.new(Vm::RegisterMachine.instance.return_register)
|
2014-06-07 16:59:44 +02:00
|
|
|
if last_compiled.is_a?(Vm::IntegerConstant) or last_compiled.is_a?(Vm::ObjectConstant)
|
2014-06-10 23:38:46 +02:00
|
|
|
return_reg.load function , last_compiled if last_compiled.register_symbol != return_reg.register_symbol
|
2014-05-25 07:43:07 +02:00
|
|
|
else
|
2014-06-10 23:38:46 +02:00
|
|
|
return_reg.move( function, last_compiled ) if last_compiled.register_symbol != return_reg.register_symbol
|
2014-05-25 07:43:07 +02:00
|
|
|
end
|
|
|
|
function.set_return return_reg
|
|
|
|
|
2014-05-13 15:24:19 +02:00
|
|
|
context.locals = parent_locals
|
2014-05-13 17:21:24 +02:00
|
|
|
context.function = parent_function
|
2014-05-10 09:58:25 +02:00
|
|
|
function
|
|
|
|
end
|
2014-05-05 09:02:02 +02:00
|
|
|
end
|
|
|
|
end
|