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.



111
112
113
# File 'opal/lib/opal/rewriters/base.rb', line 111

def current_node
  @current_node
end

Class Method Details

.s(type, *children) ⇒ Object



49
50
51
# File 'opal/lib/opal/rewriters/base.rb', line 49

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.



84
85
86
87
# File 'opal/lib/opal/rewriters/base.rb', line 84

def append_to_body(body, node)
  stmts = stmts_of(body) + stmts_of(node)
  begin_with_stmts(stmts)
end

#begin_with_stmts(stmts) ⇒ Object



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

def begin_with_stmts(stmts)
  case stmts.length
  when 0
    nil
  when 1
    stmts[0]
  else
    s(:begin, *stmts)
  end
end

#error(msg) ⇒ Object

This is called when a rewriting error occurs.



122
123
124
125
126
# File 'opal/lib/opal/rewriters/base.rb', line 122

def error(msg)
  error = ::Opal::RewritingError.new(msg)
  error.location = current_node.loc if current_node
  raise error
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.



70
71
72
73
# File 'opal/lib/opal/rewriters/base.rb', line 70

def prepend_to_body(body, node)
  stmts = stmts_of(node) + stmts_of(body)
  begin_with_stmts(stmts)
end

#process(node) ⇒ Object

Intercept the main call and assign current node.



114
115
116
117
118
119
# File 'opal/lib/opal/rewriters/base.rb', line 114

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

#s(type, *children) ⇒ Object



44
45
46
47
# File 'opal/lib/opal/rewriters/base.rb', line 44

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

#stmts_of(node) ⇒ Object



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

def stmts_of(node)
  if node.nil?
    []
  elsif %i[begin kwbegin].include?(node.type)
    node.children
  else
    [node]
  end
end