Class: Preval::Visitors::Arithmetic

Inherits:
Preval::Visitor show all
Defined in:
lib/preval/visitors/arithmetic.rb

Constant Summary collapse

OPERATORS =
%i[+ - * / % **].freeze

Instance Method Summary collapse

Methods inherited from Preval::Visitor

enable!

Instance Method Details

#on_binary(node) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/preval/visitors/arithmetic.rb', line 22

def on_binary(node)
  left, operation, right = node.body

  if left.is?(:@int) && OPERATORS.include?(operation) && right.is?(:@int)
    value = left.to_int.public_send(operation, right.to_int).to_s
    node.update(:@int, value)
  elsif %i[+ -].include?(operation)
    if right.int?(0)
      node.replace(left)
    elsif left.int?(0)
      node.replace(right)
    end
  elsif %i[* /].include?(operation)
    if right.int?(1)
      node.replace(left)
    elsif left.int?(1)
      node.replace(right)
    end
  elsif operation == :**
    if left.is?(:@int) && right.int?(0)
      node.update(:@int, left.to_int < 0 ? -1 : 1)
    elsif right.int?(1)
      node.replace(left)
    elsif left.int?(1)
      node.replace(left)
    end
  end
end