Class: Dentaku::AST::Case

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Node

arity, #name, precedence, resolve_class, #type

Constructor Details

#initialize(*nodes) ⇒ Case

Returns a new instance of Case.



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

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

Instance Attribute Details

#conditionsObject (readonly)

Returns the value of attribute conditions.



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

def conditions
  @conditions
end

#elseObject (readonly)

Returns the value of attribute else.



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

def else
  @else
end

#switchObject (readonly)

Returns the value of attribute switch.



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

def switch
  @switch
end

Class Method Details

.max_param_countObject



17
18
19
# File 'lib/dentaku/ast/case.rb', line 17

def self.max_param_count
  Float::INFINITY
end

.min_param_countObject



13
14
15
# File 'lib/dentaku/ast/case.rb', line 13

def self.min_param_count
  2
end

Instance Method Details

#accept(visitor) ⇒ Object



62
63
64
# File 'lib/dentaku/ast/case.rb', line 62

def accept(visitor)
  visitor.visit_case(self)
end

#dependencies(context = {}) ⇒ Object



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

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

#value(context = {}) ⇒ Object



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

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