rubyx/lib/ast/function_expression.rb

54 lines
1.5 KiB
Ruby
Raw Normal View History

2014-05-05 09:02:02 +02:00
module Ast
class FunctionExpression < Expression
attr_reader :name, :params, :block
def initialize name, params, block
@name, @params, @block = name.to_sym, params, block
2014-05-05 09:02:02 +02:00
end
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
def compile context , into
raise "function does not compile into anything #{self}" if into
args = []
locals = {}
params.each_with_index do |param , index|
arg = param.name
arg_value = Vm::Integer.new(index)
locals[arg] = arg_value
args << arg_value
end
function = Vm::Function.new(name , args )
context.program.add_function function
parent_locals = context.locals
parent_function = context.function
context.locals = locals
context.function = function
into = function.entry
2014-05-10 09:58:25 +02:00
block.each do |b|
compiled = b.compile(context , into)
2014-05-10 09:58:25 +02:00
if compiled.is_a? Vm::Block
into = compiled
2014-05-10 09:58:25 +02:00
he.breaks.loose
else
function.body.add_code compiled
end
puts compiled.inspect
end
context.locals = parent_locals
context.function = parent_function
2014-05-10 09:58:25 +02:00
function
end
2014-05-05 09:02:02 +02:00
end
end