rubyx/lib/vm/method_compiler/if_statement.rb

42 lines
1.3 KiB
Ruby
Raw Normal View History

2017-01-14 18:28:44 +01:00
module Vm
2016-12-09 12:38:07 +01:00
module IfStatement
# an if evaluates the condition and jumps to the true block if true
# so the else block is automatically after that.
# But then the else needs to jump over the true block unconditionally.
2016-12-09 12:38:07 +01:00
def on_IfStatement( statement )
# branch_type , condition , if_true , if_false = *statement
2016-12-09 13:29:06 +01:00
true_block = compile_if_condition( statement )
merge = compile_if_false( statement )
2016-12-09 12:38:07 +01:00
add_code true_block
2016-12-09 13:29:06 +01:00
compile_if_true(statement)
2016-12-09 12:38:07 +01:00
add_code merge
nil # statements don't return anything
end
private
2016-12-09 13:29:06 +01:00
def compile_if_condition( statement )
reset_regs
process(statement.condition)
branch_class = Object.const_get "Register::Is#{statement.branch_type.capitalize}"
true_block = Register.label(statement, "if_true")
add_code branch_class.new( statement.condition , true_block )
2016-12-09 12:38:07 +01:00
return true_block
end
2016-12-09 13:29:06 +01:00
def compile_if_true( statement )
2016-12-09 12:38:07 +01:00
reset_regs
process(statement.if_true)
end
2016-12-09 13:29:06 +01:00
def compile_if_false( statement )
reset_regs
process(statement.if_false) if statement.if_false.statements
merge = Register.label(statement , "if_merge")
add_code Register::Branch.new(statement.if_false, merge )
2016-12-09 12:38:07 +01:00
merge
end
end
end