Class: Dentaku::AST::Case

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

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Node

arity, peek, precedence, #type

Constructor Details

#initialize(*nodes) ⇒ Case

Returns a new instance of Case.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/dentaku/ast/case.rb', line 19

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

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

  @conditions = nodes

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

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

Class Method Details

.max_param_countObject



15
16
17
# File 'lib/dentaku/ast/case.rb', line 15

def self.max_param_count
  Float::INFINITY
end

.min_param_countObject



11
12
13
# File 'lib/dentaku/ast/case.rb', line 11

def self.min_param_count
  2
end

Instance Method Details

#dependencies(context = {}) ⇒ Object



53
54
55
56
57
58
# File 'lib/dentaku/ast/case.rb', line 53

def dependencies(context = {})
  # TODO: should short-circuit
  switch_dependencies(context) +
  condition_dependencies(context) +
  else_dependencies(context)
end

#value(context = {}) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/dentaku/ast/case.rb', line 38

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 ArgumentError.for(:invalid_value), "No block matched the switch value '#{switch_value}'"
  end
end