rubyx/lib/virtual/compiler/if_expression.rb

43 lines
1.6 KiB
Ruby
Raw Normal View History

module Virtual
module Compiler
# if - attr_reader :cond, :if_true, :if_false
2015-05-06 14:14:47 +02:00
def self.compile_if expression , method
# to execute the logic as the if states it, the blocks are the other way around
# so we can the jump over the else if true ,and the else joins unconditionally after the true_block
merge_block = method.new_block "if_merge" # last one, created first
true_block = method.new_block "if_true" # second, linked in after current, before merge
false_block = method.new_block "if_false" # directly next in order, ie if we don't jump we land here
2015-05-06 14:14:47 +02:00
is = Compiler.compile(expression.cond, method )
# TODO should/will use different branches for different conditions.
# just a scetch : cond_val = cond_val.is_true?(method) unless cond_val.is_a? BranchCondition
method.add_code IsTrueBranch.new( true_block )
# compile the true block (as we think of it first, even it is second in sequential order)
method.current true_block
2014-07-16 12:20:47 +02:00
last = is
2015-05-06 14:14:47 +02:00
expression.if_true.each do |part|
last = Compiler.compile(part,method )
2014-07-16 12:20:47 +02:00
raise part.inspect if last.nil?
end
# compile the false block
method.current false_block
2015-05-06 14:14:47 +02:00
expression.if_false.each do |part|
#puts "compiling in if false #{part}"
2015-05-06 14:14:47 +02:00
last = Compiler.compile(part,method )
raise part.inspect if last.nil?
end
method.add_code UnconditionalBranch.new( merge_block )
2015-05-15 20:11:44 +02:00
#puts "compiled if: end"
method.current merge_block
#TODO should return the union of the true and false types
2014-07-16 12:20:47 +02:00
last
end
end
end