From 5d4b9d4834a08cfb8a5b93f1bf5f54be6960ba51 Mon Sep 17 00:00:00 2001 From: Torsten Ruger Date: Sun, 8 Apr 2018 00:50:51 +0300 Subject: [PATCH] add branches to builder --- lib/risc/builder.rb | 10 ++++++++++ lib/risc/builtin/word.rb | 6 +++--- test/risc/test_builder.rb | 16 ++++++++++++++++ 3 files changed, 29 insertions(+), 3 deletions(-) diff --git a/lib/risc/builder.rb b/lib/risc/builder.rb index 4d3c69c3..d7bb3947 100644 --- a/lib/risc/builder.rb +++ b/lib/risc/builder.rb @@ -32,6 +32,16 @@ module Risc reg end + def if_zero( label ) + add Risc::IsZero.new("jump if zero" , label) + end + def if_not_zero( label ) + add Risc::IsNotZero.new("jump if not zero" , label) + end + def branch( label ) + add Risc::Branch.new("jump to" , label) + end + # build code using dsl (see __init__ or MessageSetup for examples) # names (that ruby would resolve to a variable/method) are converted # to registers. << means assignment and [] is supported both on diff --git a/lib/risc/builtin/word.rb b/lib/risc/builtin/word.rb index 263c43d2..066af51a 100644 --- a/lib/risc/builtin/word.rb +++ b/lib/risc/builtin/word.rb @@ -70,11 +70,11 @@ module Risc space << space[:nil_object] add Risc.op(source + "if method is nil", :- , space , typed_method ) - add Risc::IsZero.new(source + "jump if nil" , exit_label) + if_zero exit_label name << typed_method[:name] add Risc.op(source + " compare name with me", :- , name , word ) - add Risc::IsNotZero.new(source + "jump if not same" , false_label) + if_not_zero false_label typed_method << typed_method[:binary] message[:return_value] << typed_method @@ -83,7 +83,7 @@ module Risc add false_label typed_method << typed_method[:next_method] - add Risc::Branch.new(source + "back to while", while_start_label) + branch while_start_label add exit_label end diff --git a/test/risc/test_builder.rb b/test/risc/test_builder.rb index a9881460..990a9dc0 100644 --- a/test/risc/test_builder.rb +++ b/test/risc/test_builder.rb @@ -6,6 +6,7 @@ module Risc def setup Risc.machine.boot init = Parfait.object_space.get_init + @label = Risc::Label.new("source","name") @builder = Risc::MethodCompiler.new( init ).builder end def test_has_build @@ -74,5 +75,20 @@ module Risc label2 = @builder.exit_label assert_equal label1 , label2 end + def test_if_zero + ret = @builder.if_zero @label + assert_equal IsZero , ret.class + assert_equal @label , ret.label + end + def test_if_not_zero + ret = @builder.if_not_zero @label + assert_equal IsNotZero , ret.class + assert_equal @label , ret.label + end + def test_branch + ret = @builder.branch @label + assert_equal Branch , ret.class + assert_equal @label , ret.label + end end end