Class: SimpleLogic::InfixOperation

Inherits:
Treetop::Runtime::SyntaxNode
  • Object
show all
Defined in:
lib/simple_logic/syntax_nodes.rb

Instance Method Summary collapse

Instance Method Details

#eval(context) ⇒ Object



6
7
8
# File 'lib/simple_logic/syntax_nodes.rb', line 6

def eval(context)
  rpn(shunting_yard(values_and_operators(context)))
end

#listObject



10
11
12
# File 'lib/simple_logic/syntax_nodes.rb', line 10

def list
  lhs.list + [rhs]
end

#rpn(input) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/simple_logic/syntax_nodes.rb', line 40

def rpn(input)
  results = []
  input.each do |object|
    if object.instance_of?(PrecedenceTable::Operator)
      r, l = results.pop, results.pop
      results << object.apply(l, r)
    else
      results << object
    end
  end
  results.first
end

#shunting_yard(input) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/simple_logic/syntax_nodes.rb', line 24

def shunting_yard(input)
  [].tap do |rpn|
    operator_stack = []
    input.each do |object|
      if object.instance_of?(PrecedenceTable::Operator)
        op1 = object
        rpn << operator_stack.pop while (op2 = operator_stack.last) && (op1.left_associative? ? op1.precedence <= op2.precedence : op1.precedence < op2.precedence)
        operator_stack << op1
      else
        rpn << object
      end
    end
    rpn << operator_stack.pop until operator_stack.empty?
  end
end

#values_and_operators(context) ⇒ Object



14
15
16
17
18
19
20
21
22
# File 'lib/simple_logic/syntax_nodes.rb', line 14

def values_and_operators(context)
  list.map do |node|
    if node.instance_of?(Treetop::Runtime::SyntaxNode)
      PrecedenceTable.lookup(node.text_value)
    else
      node.eval(context)
    end
  end
end