rubyx/lib/sol/method_expression.rb

75 lines
2.2 KiB
Ruby
Raw Permalink Normal View History

module Sol
class MethodExpression < Expression
attr_reader :name, :args , :body
2017-04-01 15:27:32 +02:00
def initialize( name , args , body )
@name , @args , @body = name , args , body
raise "no bod" unless @body
raise "Not Sol #{@body}" unless @body.is_a?(Statement)
end
# create the parfait SolMethod to hold the code for this method
#
# Must pass in the actual Parfait class (default nil is just to conform to api)
def to_parfait( clazz = nil )
raise "No class given to method #{name}" unless clazz
if( method = clazz.get_instance_method(name))
#FIXME , should check arg_type, and if the same, clear method and ok
raise "Redefining #{clazz.name}.#{name} not supported #{method}"
end
sol_m = clazz.create_instance_method_for(name , make_arg_type , make_frame , body )
sol_m.create_callable_method_for(clazz.instance_type)
sol_m
end
# Creates the SlotMachine::MethodCompiler that will do the next step
def to_slot(clazz)
raise( "no class in #{self}") unless clazz
method = clazz.get_instance_method(@name)
raise( "no method in #{@name} in #{clazz.name}") unless method
compiler = method.compiler_for(clazz.instance_type)
compiler
2017-04-01 15:27:32 +02:00
end
def each(&block)
block.call(self)
@body.each(&block)
2017-04-08 11:10:42 +02:00
end
2018-06-28 19:15:24 +02:00
def has_yield?
each{|statement| return true if statement.is_a?(YieldStatement)}
return false
end
2017-04-08 16:22:53 +02:00
2018-06-27 16:09:50 +02:00
def make_arg_type( )
2017-04-08 16:22:53 +02:00
type_hash = {}
2017-04-09 09:14:28 +02:00
@args.each {|arg| type_hash[arg] = :Object }
type_hash[:implicit_block] = :Block if has_yield?
Parfait::Type.for_hash( type_hash )
2017-04-08 16:22:53 +02:00
end
2018-07-03 21:18:19 +02:00
def to_s(depth = 0)
arg_str = @args.collect{|a| a.to_s}.join(', ')
at_depth(depth , "def #{name}(#{arg_str})\n#{@body.to_s(1)}\nend")
2018-07-03 21:18:19 +02:00
end
2018-06-28 19:15:24 +02:00
private
2018-03-14 15:54:47 +01:00
def make_frame
nodes = []
@body.each { |node| nodes << node }
nodes.dup.each do |node|
next unless node.is_a?(LambdaExpression)
node.each {|block_scope| nodes.delete(block_scope)}
end
2017-04-08 16:22:53 +02:00
type_hash = {}
nodes.each do |node|
next unless node.is_a?(LocalVariable) or node.is_a?(LocalAssignment)
type_hash[node.name] = :Object
end
Parfait::Type.for_hash( type_hash )
2017-04-08 16:22:53 +02:00
end
2017-04-01 15:27:32 +02:00
end
end