2014-05-05 09:02:02 +02:00
|
|
|
module Ast
|
|
|
|
class FunctionExpression < Expression
|
2014-05-14 10:33:23 +02:00
|
|
|
attr_reader :name, :params, :body
|
|
|
|
def initialize name, params, body
|
|
|
|
@name, @params, @body = name.to_sym, params, body
|
2014-05-05 09:02:02 +02:00
|
|
|
end
|
2014-05-10 11:54:10 +02:00
|
|
|
def attributes
|
2014-05-14 10:33:23 +02:00
|
|
|
[:name, :params, :body]
|
2014-05-10 11:54:10 +02:00
|
|
|
end
|
|
|
|
def inspect
|
|
|
|
self.class.name + ".new(" + name.inspect + ", ["+
|
|
|
|
params.collect{|m| m.inspect }.join( ",") +"] , [" +
|
2014-05-14 10:33:23 +02:00
|
|
|
body.collect{|m| m.inspect }.join( ",") +"] )"
|
2014-05-05 09:02:02 +02:00
|
|
|
end
|
2014-05-10 09:58:25 +02:00
|
|
|
|
2014-05-13 09:49:26 +02:00
|
|
|
def to_s
|
2014-05-14 10:33:23 +02:00
|
|
|
"def #{name}( " + params.join(",") + ") \n" + body.join("\n") + "end\n"
|
2014-05-13 09:49:26 +02:00
|
|
|
end
|
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
|
|
|
|
arg_value = Vm::Integer.new(index)
|
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-05-13 15:24:19 +02:00
|
|
|
function = Vm::Function.new(name , args )
|
2014-05-13 20:06:12 +02:00
|
|
|
context.program.add_function function
|
|
|
|
|
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-14 10:33:23 +02:00
|
|
|
body.each do |b|
|
2014-05-13 15:24:19 +02:00
|
|
|
compiled = b.compile(context , into)
|
2014-05-14 09:47:30 +02:00
|
|
|
function.return_type = compiled
|
2014-05-14 10:33:23 +02:00
|
|
|
puts "compiled in function #{compiled.inspect}"
|
|
|
|
raise "alarm #{compiled} \n #{b}" unless compiled.is_a? Vm::Word
|
2014-05-10 09:58:25 +02:00
|
|
|
end
|
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
|