Class: Dentaku::AST::Case

Inherits:
Node
  • Object
show all
Defined in:
lib/dentaku/ast/case.rb

Instance Method Summary collapse

Methods inherited from Node

arity, precedence

Constructor Details

#initialize(*nodes) ⇒ Case

Returns a new instance of Case.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/dentaku/ast/case.rb', line 10

def initialize(*nodes)
  @switch = nodes.shift

  unless @switch.is_a?(AST::CaseSwitchVariable)
    raise 'Case missing switch variable'
  end

  @conditions = nodes

  @else = @conditions.pop if @conditions.last.is_a?(AST::CaseElse)

  @conditions.each do |condition|
    unless condition.is_a?(AST::CaseConditional)
      raise "#{condition} is not a CaseConditional"
    end
  end
end

Instance Method Details

#dependencies(context = {}) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/dentaku/ast/case.rb', line 43

def dependencies(context={})
  # TODO: should short-circuit
  @switch.dependencies(context) +
    @conditions.flat_map do |condition|
      condition.dependencies(context)
    end
end

#value(context = {}) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/dentaku/ast/case.rb', line 28

def value(context={})
  switch_value = @switch.value(context)
  @conditions.each do |condition|
    if condition.when.value(context) == switch_value
      return condition.then.value(context)
    end
  end

  if @else
    return @else.value(context)
  else
    raise "No block matched the switch value '#{switch_value}'"
  end
end