2014-05-05 09:02:02 +02:00
|
|
|
module Ast
|
|
|
|
class FunctionExpression < Expression
|
|
|
|
attr_reader :name, :params, :block
|
|
|
|
def initialize name, params, block
|
2014-05-10 14:24:56 +02:00
|
|
|
@name, @params, @block = name.to_sym, params, block
|
2014-05-05 09:02:02 +02:00
|
|
|
end
|
2014-05-10 11:54:10 +02:00
|
|
|
def attributes
|
|
|
|
[:name, :params, :block]
|
|
|
|
end
|
|
|
|
def inspect
|
|
|
|
self.class.name + ".new(" + name.inspect + ", ["+
|
|
|
|
params.collect{|m| m.inspect }.join( ",") +"] , [" +
|
|
|
|
block.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
|
|
|
|
"def #{name}( " + params.join(",") + ") \n" + block.join("\n") + "end\n"
|
|
|
|
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-13 15:24:19 +02:00
|
|
|
into = function.entry
|
2014-05-10 09:58:25 +02:00
|
|
|
block.each do |b|
|
2014-05-13 15:24:19 +02:00
|
|
|
compiled = b.compile(context , into)
|
2014-05-10 09:58:25 +02:00
|
|
|
if compiled.is_a? Vm::Block
|
2014-05-13 15:24:19 +02:00
|
|
|
into = compiled
|
2014-05-10 09:58:25 +02:00
|
|
|
he.breaks.loose
|
|
|
|
else
|
|
|
|
function.body.add_code compiled
|
|
|
|
end
|
|
|
|
puts compiled.inspect
|
|
|
|
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
|