Class: Opal::Rewriters::Base

Inherits:
Parser::AST::Processor
  • Object
show all
Defined in:
opal/lib/opal/rewriters/base.rb

Defined Under Namespace

Classes: DummyLocation

Constant Summary

DUMMY_LOCATION =
DummyLocation.new

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#current_nodeObject

Store the current node for reporting.



98
99
100
# File 'opal/lib/opal/rewriters/base.rb', line 98

def current_node
  @current_node
end

Class Method Details

.s(type, *children) ⇒ Object



47
48
49
# File 'opal/lib/opal/rewriters/base.rb', line 47

def self.s(type, *children)
  ::Opal::AST::Node.new(type, children, location: DUMMY_LOCATION)
end

Instance Method Details

#append_to_body(body, node) ⇒ Object

Appends given +node+ to +body+ node.

Supports +body+ to be one of:

  1. nil - empty body
  2. s(:begin) / s(:kwbegin) - multiline body
  3. s(:anything_else) - singleline body

Returns a new body with +node+ injected as a last statement.



87
88
89
90
91
92
93
94
95
# File 'opal/lib/opal/rewriters/base.rb', line 87

def append_to_body(body, node)
  if body.nil?
    node
  elsif [:begin, :kwbegin].include?(body.type)
    body.updated(nil, [*body, node])
  else
    s(:begin, body, node)
  end
end

#prepend_to_body(body, node) ⇒ Object

Prepends given +node+ to +body+ node.

Supports +body+ to be one of:

  1. nil - empty body
  2. s(:begin) / s(:kwbegin) - multiline body
  3. s(:anything_else) - singleline body

Returns a new body with +node+ injected as a first statement.



68
69
70
71
72
73
74
75
76
# File 'opal/lib/opal/rewriters/base.rb', line 68

def prepend_to_body(body, node)
  if body.nil?
    node
  elsif [:begin, :kwbegin].include?(body.type)
    body.updated(nil, [node, *body])
  else
    s(:begin, node, body)
  end
end

#process(node) ⇒ Object

Intercept the main call and assign current node.



101
102
103
104
105
106
# File 'opal/lib/opal/rewriters/base.rb', line 101

def process(node)
  self.current_node = node
  super
ensure
  self.current_node = nil
end

#s(type, *children) ⇒ Object



42
43
44
45
# File 'opal/lib/opal/rewriters/base.rb', line 42

def s(type, *children)
  loc = current_node ? current_node.loc : DUMMY_LOCATION
  ::Opal::AST::Node.new(type, children, location: loc)
end