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-05-13 15:24:19 +02:00
|
|
|
def compile context , into
|
|
|
|
raise "function does not compile into anything #{self}" if into
|
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-05-25 09:57:56 +02:00
|
|
|
arg_value = Vm::Integer.new(index+1)
|
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-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
|
|
|
|
|
|
|
|
function = Vm::Function.new(name , args )
|
|
|
|
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-14 09:47:30 +02:00
|
|
|
into = function.body
|
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-05-25 07:43:07 +02:00
|
|
|
last_compiled = b.compile(context , into)
|
|
|
|
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-05-25 09:57:56 +02:00
|
|
|
return_reg = Vm::Integer.new(7)
|
2014-05-25 07:43:07 +02:00
|
|
|
if last_compiled.is_a?(Vm::IntegerConstant) or last_compiled.is_a?(Vm::StringConstant)
|
|
|
|
return_reg.load into , last_compiled if last_compiled.register != return_reg.register
|
|
|
|
else
|
|
|
|
return_reg.move( into, last_compiled ) if last_compiled.register != return_reg.register
|
|
|
|
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
|