Class: Semdiff::ConstantsCompiler

Inherits:
Prism::MutationCompiler
  • Object
show all
Includes:
Prism::DSL, CompilerUtils
Defined in:
lib/semdiff/constants_compiler.rb

Overview

ConstantsCompiler is a compiler that folds constant literal expressions into single constants.

Examples:

```ruby
# Expression        Canonical Form
(2 + 3)             5
(4 * 2 - 1)         7
(8 / 4) + 3         5
(1 + 2**3)          9
```

Constant Summary collapse

SUPPORTED_OPS =
%i[+ - * / % ** & | ^ << >>].freeze

Instance Method Summary collapse

Methods included from CompilerUtils

inherit_newline

Instance Method Details

#visit_call_node(node) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/semdiff/constants_compiler.rb', line 21

def visit_call_node(node)
  receiver  = visit(node.receiver)
  arguments = visit(node.arguments)
  result    = nil

  result = fold_constants(node, receiver, arguments) if constant_foldable?(node, receiver, arguments)

  if result
    CompilerUtils.inherit_newline(node, result)
  else
    # finalized transformations
    node.copy(receiver: receiver, arguments: arguments, block: visit(node.block))
  end
end

#visit_parentheses_node(node) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/semdiff/constants_compiler.rb', line 36

def visit_parentheses_node(node)
  if node.multiple_statements?
    statements = visit_all(node.body.body)
    body = node.body.copy(body: statements)
    return node.copy(body: body)
  end

  single_child = node.body.body.first
  visited = visit(single_child)

  return visited if visited.is_a?(Prism::IntegerNode)

  new_body = node.body.copy(body: [visited])
  node.copy(body: new_body)
end