Class: SyntaxTree::YARV::OptCaseDispatch

Inherits:
Object
  • Object
show all
Defined in:
lib/syntax_tree/yarv/instructions.rb

Overview

### Summary

opt_case_dispatch is a branch instruction that moves the control flow for case statements that have clauses where they can all be used as hash keys for an internal hash.

It has two arguments: the case_dispatch_hash and an else_label. It pops one value off the stack: a hash key. opt_case_dispatch looks up the key in the case_dispatch_hash and jumps to the corresponding label if there is one. If there is no value in the case_dispatch_hash, opt_case_dispatch jumps to the else_label index.

### Usage

~~~ruby case 1 when 1

puts "foo"

else

puts "bar"

end ~~~

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(case_dispatch_hash, else_label) ⇒ OptCaseDispatch



2789
2790
2791
2792
# File 'lib/syntax_tree/yarv/instructions.rb', line 2789

def initialize(case_dispatch_hash, else_label)
  @case_dispatch_hash = case_dispatch_hash
  @else_label = else_label
end

Instance Attribute Details

#case_dispatch_hashObject (readonly)

Returns the value of attribute case_dispatch_hash.



2787
2788
2789
# File 'lib/syntax_tree/yarv/instructions.rb', line 2787

def case_dispatch_hash
  @case_dispatch_hash
end

#else_labelObject (readonly)

Returns the value of attribute else_label.



2787
2788
2789
# File 'lib/syntax_tree/yarv/instructions.rb', line 2787

def else_label
  @else_label
end

Instance Method Details

#call(vm) ⇒ Object



2825
2826
2827
# File 'lib/syntax_tree/yarv/instructions.rb', line 2825

def call(vm)
  vm.jump(case_dispatch_hash.fetch(vm.pop, else_label))
end

#canonicalObject



2821
2822
2823
# File 'lib/syntax_tree/yarv/instructions.rb', line 2821

def canonical
  self
end

#disasm(fmt) ⇒ Object



2794
2795
2796
2797
2798
2799
# File 'lib/syntax_tree/yarv/instructions.rb', line 2794

def disasm(fmt)
  fmt.instruction(
    "opt_case_dispatch",
    ["<cdhash>", fmt.label(else_label)]
  )
end

#lengthObject



2809
2810
2811
# File 'lib/syntax_tree/yarv/instructions.rb', line 2809

def length
  3
end

#popsObject



2813
2814
2815
# File 'lib/syntax_tree/yarv/instructions.rb', line 2813

def pops
  1
end

#pushesObject



2817
2818
2819
# File 'lib/syntax_tree/yarv/instructions.rb', line 2817

def pushes
  0
end

#to_a(_iseq) ⇒ Object



2801
2802
2803
2804
2805
2806
2807
# File 'lib/syntax_tree/yarv/instructions.rb', line 2801

def to_a(_iseq)
  [
    :opt_case_dispatch,
    case_dispatch_hash.flat_map { |key, value| [key, value.name] },
    else_label.name
  ]
end