Class: RuboCop::Node

Inherits:
Parser::AST::Node
  • Object
show all
Includes:
Sexp
Defined in:
lib/rubocop/ast_node.rb,
lib/rubocop/ast_node/builder.rb

Overview

RuboCop::Node is a subclass of Parser::AST::Node. It provides access to parent nodes and an object-oriented way to traverse an AST with the power of Enumerable.

It has predicate methods for every node type, like this:

Examples:

node.send_type?    # Equivalent to: `node.type == :send`
node.op_asgn_type? # Equivalent to: `node.type == :op_asgn`

# Non-word characters (other than a-zA-Z0-9_) in type names are omitted.
node.defined_type? # Equivalent to: `node.type == :defined?`

# Find the first lvar node under the receiver node.
lvar_node = node.each_descendant.find(&:lvar_type?)

Defined Under Namespace

Classes: Builder

Constant Summary collapse

COMPARISON_OPERATORS =
[:==, :===, :!=, :<=, :>=, :>, :<, :<=>].freeze
TRUTHY_LITERALS =
[:str, :dstr, :xstr, :int, :float, :sym, :dsym, :array,
:hash, :regexp, :true, :irange, :erange, :complex,
:rational].freeze
FALSEY_LITERALS =
[:false, :nil].freeze
LITERALS =
(TRUTHY_LITERALS + FALSEY_LITERALS).freeze
BASIC_LITERALS =
LITERALS - [:dstr, :xstr, :dsym, :array, :hash, :irange,
:erange].freeze
MUTABLE_LITERALS =
[:str, :dstr, :xstr, :array, :hash].freeze
IMMUTABLE_LITERALS =
(LITERALS - MUTABLE_LITERALS).freeze
VARIABLES =
[:ivar, :gvar, :cvar, :lvar].freeze
REFERENCES =
[:nth_ref, :back_ref].freeze
KEYWORDS =
[:alias, :and, :break, :case, :class, :def, :defs, :defined?,
:kwbegin, :do, :else, :ensure, :for, :if, :module, :next, :not,
:or, :postexe, :redo, :rescue, :retry, :return, :self, :super,
:zsuper, :then, :undef, :until, :when, :while, :yield].freeze
OPERATOR_KEYWORDS =
[:and, :or].freeze
SPECIAL_KEYWORDS =
%w(__FILE__ __LINE__ __ENCODING__).freeze

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Sexp

#s

Constructor Details

#initialize(type, children = [], properties = {}) ⇒ Node

Returns a new instance of Node.



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/rubocop/ast_node.rb', line 59

def initialize(type, children = [], properties = {})
  @mutable_attributes = {}

  # ::AST::Node#initialize freezes itself.
  super

  # #parent= may be invoked multiple times for a node because there are
  # pending nodes while constructing AST and they are replaced later.
  # For example, `lvar` and `send` type nodes are initially created as an
  # `ident` type node and fixed to the appropriate type later.
  # So, the #parent attribute needs to be mutable.
  each_child_node do |child_node|
    child_node.parent = self
  end
end

Class Method Details

.def_matcher(method_name, pattern_str) ⇒ Object



47
48
49
50
51
52
53
54
55
# File 'lib/rubocop/ast_node.rb', line 47

def def_matcher(method_name, pattern_str)
  compiler = RuboCop::NodePattern::Compiler.new(pattern_str, 'self')
  src = "def #{method_name}(" \
        "#{compiler.emit_param_list});" \
        "#{compiler.emit_method_code};end"

  file, lineno = *caller.first.split(':')
  class_eval(src, file, lineno.to_i)
end

Instance Method Details

#ancestorsArray<Node>

Returns an array of ancestor nodes. This is a shorthand for node.each_ancestor.to_a.

Returns:

  • (Array<Node>)

    an array of ancestor nodes



138
139
140
# File 'lib/rubocop/ast_node.rb', line 138

def ancestors
  each_ancestor.to_a
end

#asgn_method_call?Boolean

Returns:

  • (Boolean)


349
350
351
352
# File 'lib/rubocop/ast_node.rb', line 349

def asgn_method_call?
  !COMPARISON_OPERATORS.include?(method_name) &&
    method_name.to_s.end_with?('=')
end

#basic_literal?Boolean

Returns:

  • (Boolean)


362
363
364
# File 'lib/rubocop/ast_node.rb', line 362

def basic_literal?
  BASIC_LITERALS.include?(type)
end

#child_nodesArray<Node>

Returns an array of child nodes. This is a shorthand for node.each_child_node.to_a.

Returns:

  • (Array<Node>)

    an array of child nodes



180
181
182
# File 'lib/rubocop/ast_node.rb', line 180

def child_nodes
  each_child_node.to_a
end

#const_nameObject



279
280
281
282
283
284
285
286
287
# File 'lib/rubocop/ast_node.rb', line 279

def const_name
  return unless const_type?
  namespace, name = *self
  if namespace && !namespace.cbase_type?
    "#{namespace.const_name}::#{name}"
  else
    name.to_s
  end
end

#defined_moduleObject



297
298
299
300
# File 'lib/rubocop/ast_node.rb', line 297

def defined_module
  namespace, name = *defined_module0
  s(:const, namespace, name) if name
end

#defined_module_nameObject



302
303
304
# File 'lib/rubocop/ast_node.rb', line 302

def defined_module_name
  (const = defined_module) && const.const_name
end

#descendantsArray<Node>

Returns an array of descendant nodes. This is a shorthand for node.each_descendant.to_a.

Returns:

  • (Array<Node>)

    an array of descendant nodes



220
221
222
# File 'lib/rubocop/ast_node.rb', line 220

def descendants
  each_descendant.to_a
end

#each_ancestorself, Enumerator #each_ancestor(type) ⇒ self, Enumerator #each_ancestor(type_a, type_b, ...) ⇒ self, Enumerator #each_ancestor(types) ⇒ self, Enumerator

Calls the given block for each ancestor node from parent to root. If no block is given, an Enumerator is returned.

Overloads:

  • #each_ancestorself, Enumerator

    Yield all nodes.

  • #each_ancestor(type) ⇒ self, Enumerator

    Yield only nodes matching the type.

    Parameters:

    • type (Symbol)

      a node type

  • #each_ancestor(type_a, type_b, ...) ⇒ self, Enumerator

    Yield only nodes matching any of the types.

    Parameters:

    • type_a (Symbol)

      a node type

    • type_b (Symbol)

      a node type

  • #each_ancestor(types) ⇒ self, Enumerator

    Yield only nodes matching any of types in the array.

    Parameters:

    • types (Array<Symbol>)

      an array containing node types

Yield Parameters:

  • node (Node)

    each ancestor node

Returns:

  • (self)

    if a block is given

  • (Enumerator)

    if no block is given



120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/rubocop/ast_node.rb', line 120

def each_ancestor(*types, &block)
  return to_enum(__method__, *types) unless block_given?

  types.flatten!

  if types.empty?
    visit_ancestors(&block)
  else
    visit_ancestors_with_types(types, &block)
  end

  self
end

#each_child_nodeself, Enumerator #each_child_node(type) ⇒ self, Enumerator #each_child_node(type_a, type_b, ...) ⇒ self, Enumerator #each_child_node(types) ⇒ self, Enumerator

Calls the given block for each child node. If no block is given, an Enumerator is returned.

Note that this is different from node.children.each { |child| ... } which yields all children including non-node elements.

Overloads:

  • #each_child_nodeself, Enumerator

    Yield all nodes.

  • #each_child_node(type) ⇒ self, Enumerator

    Yield only nodes matching the type.

    Parameters:

    • type (Symbol)

      a node type

  • #each_child_node(type_a, type_b, ...) ⇒ self, Enumerator

    Yield only nodes matching any of the types.

    Parameters:

    • type_a (Symbol)

      a node type

    • type_b (Symbol)

      a node type

  • #each_child_node(types) ⇒ self, Enumerator

    Yield only nodes matching any of types in the array.

    Parameters:

    • types (Array<Symbol>)

      an array containing node types

Yield Parameters:

  • node (Node)

    each child node

Returns:

  • (self)

    if a block is given

  • (Enumerator)

    if no block is given



163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/rubocop/ast_node.rb', line 163

def each_child_node(*types)
  return to_enum(__method__, *types) unless block_given?

  types.flatten!

  children.each do |child|
    next unless child.is_a?(Node)
    yield child if types.empty? || types.include?(child.type)
  end

  self
end

#each_descendantself, Enumerator #each_descendant(type) ⇒ self, Enumerator #each_descendant(type_a, type_b, ...) ⇒ self, Enumerator #each_descendant(types) ⇒ self, Enumerator

Calls the given block for each descendant node with depth first order. If no block is given, an Enumerator is returned.

Overloads:

  • #each_descendantself, Enumerator

    Yield all nodes.

  • #each_descendant(type) ⇒ self, Enumerator

    Yield only nodes matching the type.

    Parameters:

    • type (Symbol)

      a node type

  • #each_descendant(type_a, type_b, ...) ⇒ self, Enumerator

    Yield only nodes matching any of the types.

    Parameters:

    • type_a (Symbol)

      a node type

    • type_b (Symbol)

      a node type

  • #each_descendant(types) ⇒ self, Enumerator

    Yield only nodes matching any of types in the array.

    Parameters:

    • types (Array<Symbol>)

      an array containing node types

Yield Parameters:

  • node (Node)

    each descendant node

Returns:

  • (self)

    if a block is given

  • (Enumerator)

    if no block is given



202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/rubocop/ast_node.rb', line 202

def each_descendant(*types, &block)
  return to_enum(__method__, *types) unless block_given?

  types.flatten!

  if types.empty?
    visit_descendants(&block)
  else
    visit_descendants_with_types(types, &block)
  end

  self
end

#each_nodeself, Enumerator #each_node(type) ⇒ self, Enumerator #each_node(type_a, type_b, ...) ⇒ self, Enumerator #each_node(types) ⇒ self, Enumerator

Calls the given block for the receiver and each descendant node in depth-first order. If no block is given, an Enumerator is returned.

This method would be useful when you treat the receiver node as the root of a tree and want to iterate over all nodes in the tree.

Overloads:

  • #each_nodeself, Enumerator

    Yield all nodes.

  • #each_node(type) ⇒ self, Enumerator

    Yield only nodes matching the type.

    Parameters:

    • type (Symbol)

      a node type

  • #each_node(type_a, type_b, ...) ⇒ self, Enumerator

    Yield only nodes matching any of the types.

    Parameters:

    • type_a (Symbol)

      a node type

    • type_b (Symbol)

      a node type

  • #each_node(types) ⇒ self, Enumerator

    Yield only nodes matching any of types in the array.

    Parameters:

    • types (Array<Symbol>)

      an array containing node types

Yield Parameters:

  • node (Node)

    each node

Returns:

  • (self)

    if a block is given

  • (Enumerator)

    if no block is given



246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/rubocop/ast_node.rb', line 246

def each_node(*types, &block)
  return to_enum(__method__, *types) unless block_given?

  types.flatten!

  yield self if types.empty? || types.include?(type)

  if types.empty?
    visit_descendants(&block)
  else
    visit_descendants_with_types(types, &block)
  end

  self
end

#falsey_literal?Boolean

Returns:

  • (Boolean)


370
371
372
# File 'lib/rubocop/ast_node.rb', line 370

def falsey_literal?
  FALSEY_LITERALS.include?(type)
end

#immutable_literal?Boolean

Returns:

  • (Boolean)


378
379
380
# File 'lib/rubocop/ast_node.rb', line 378

def immutable_literal?
  IMMUTABLE_LITERALS.include?(type)
end

#keyword?Boolean

Returns:

  • (Boolean)


390
391
392
393
394
395
# File 'lib/rubocop/ast_node.rb', line 390

def keyword?
  return true if special_keyword? || keyword_not?
  return false unless KEYWORDS.include?(type)

  !OPERATOR_KEYWORDS.include?(type) || loc.operator.is?(type.to_s)
end

#keyword_not?Boolean

Returns:

  • (Boolean)


401
402
403
404
# File 'lib/rubocop/ast_node.rb', line 401

def keyword_not?
  _receiver, method_name, *args = *self
  args.empty? && method_name == :! && loc.selector.is?('not'.freeze)
end

#literal?Boolean

Returns:

  • (Boolean)


358
359
360
# File 'lib/rubocop/ast_node.rb', line 358

def literal?
  LITERALS.include?(type)
end

#multiline?Boolean

Predicates

Returns:

  • (Boolean)


340
341
342
343
# File 'lib/rubocop/ast_node.rb', line 340

def multiline?
  expr = loc.expression
  expr && (expr.first_line != expr.last_line)
end

#mutable_literal?Boolean

Returns:

  • (Boolean)


374
375
376
# File 'lib/rubocop/ast_node.rb', line 374

def mutable_literal?
  MUTABLE_LITERALS.include?(type)
end

#parentNode?

Returns the parent node, or nil if the receiver is a root node.

Returns:

  • (Node, nil)

    the parent node or nil



85
86
87
# File 'lib/rubocop/ast_node.rb', line 85

def parent
  @mutable_attributes[:parent]
end

#parent_module_nameObject

Searching the AST



308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/rubocop/ast_node.rb', line 308

def parent_module_name
  # what class or module is this method/constant/etc definition in?
  # returns nil if answer cannot be determined
  ancestors = each_ancestor(:class, :module, :sclass, :casgn, :block)
  result    = ancestors.map do |ancestor|
    case ancestor.type
    when :class, :module, :casgn
      # TODO: if constant name has cbase (leading ::), then we don't need
      # to keep traversing up through nested classes/modules
      ancestor.defined_module_name
    when :sclass
      obj = ancestor.children[0]
      # TODO: look for constant definition and see if it is nested
      # inside a class or module
      return "#<Class:#{obj.const_name}>" if obj.const_type?
      return "#<Class:#{ancestor.parent_module_name}>" if obj.self_type?
      return nil
    else # block
      # Known DSL methods which eval body inside an anonymous class/module
      return nil if [:describe, :it].include?(ancestor.method_name) &&
                    ancestor.receiver.nil?
      if ancestor.method_name == :class_eval
        return nil unless ancestor.receiver.const_type?
        ancestor.receiver.const_name
      end
    end
  end.compact.reverse.join('::')
  result.empty? ? 'Object' : result
end

#pure?Boolean

Some expressions are evaluated for their value, some for their side effects, and some for both If we know that expressions are useful only for their return values, and have no side effects, that means we can reorder them, change the number of times they are evaluated, or replace them with other expressions which are equivalent in value So, is evaluation of this node free of side effects?

Returns:

  • (Boolean)


469
470
471
472
473
474
475
476
477
478
479
480
481
482
# File 'lib/rubocop/ast_node.rb', line 469

def pure?
  # Be conservative and return false if we're not sure
  case type
  when :__FILE__, :__LINE__, :const, :cvar, :defined?, :false, :float,
       :gvar, :int, :ivar, :lvar, :nil, :str, :sym, :true
    true
  when :and, :array, :begin, :case, :dstr, :dsym, :eflipflop, :ensure,
       :erange, :for, :hash, :if, :iflipflop, :irange, :kwbegin, :not, :or,
       :pair, :regexp, :until, :until_post, :when, :while, :while_post
    child_nodes.all?(&:pure?)
  else
    false
  end
end

#receiverObject

Destructuring



272
# File 'lib/rubocop/ast_node.rb', line 272

def_matcher :receiver,    '{(send $_ ...) (block (send $_ ...) ...)}'

#reference?Boolean

Returns:

  • (Boolean)


386
387
388
# File 'lib/rubocop/ast_node.rb', line 386

def reference?
  REFERENCES.include?(type)
end

#sibling_indexInteger

Returns the index of the receiver node in its siblings.

Returns:

  • (Integer)

    the index of the receiver node in its siblings



98
99
100
# File 'lib/rubocop/ast_node.rb', line 98

def sibling_index
  parent.children.index { |sibling| sibling.equal?(self) }
end

#single_line?Boolean

Returns:

  • (Boolean)


345
346
347
# File 'lib/rubocop/ast_node.rb', line 345

def single_line?
  !multiline?
end

#sourceObject



262
263
264
# File 'lib/rubocop/ast_node.rb', line 262

def source
  loc.expression.source
end

#source_rangeObject



266
267
268
# File 'lib/rubocop/ast_node.rb', line 266

def source_range
  loc.expression
end

#special_keyword?Boolean

Returns:

  • (Boolean)


397
398
399
# File 'lib/rubocop/ast_node.rb', line 397

def special_keyword?
  SPECIAL_KEYWORDS.include?(source)
end

#truthy_literal?Boolean

Returns:

  • (Boolean)


366
367
368
# File 'lib/rubocop/ast_node.rb', line 366

def truthy_literal?
  TRUTHY_LITERALS.include?(type)
end

#value_used?Boolean

Some expressions are evaluated for their value, some for their side effects, and some for both If we know that an expression is useful only for its side effects, that means we can transform it in ways which preserve the side effects, but change the return value So, does the return value of this node matter? If we changed it to (...; nil), might that affect anything?

Returns:

  • (Boolean)


432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
# File 'lib/rubocop/ast_node.rb', line 432

def value_used?
  # Be conservative and return true if we're not sure
  return false if parent.nil?
  index = parent.children.index { |child| child.equal?(self) }

  case parent.type
  when :array, :block, :defined?, :dstr, :dsym, :eflipflop, :erange, :float,
       :hash, :iflipflop, :irange, :not, :pair, :regexp, :str, :sym, :when,
       :xstr
    parent.value_used?
  when :begin, :kwbegin
    # the last child node determines the value of the parent
    index == parent.children.size - 1 ? parent.value_used? : false
  when :for
    # `for var in enum; body; end`
    # (for <var> <enum> <body>)
    index == 2 ? parent.value_used? : true
  when :case, :if
    # (case <condition> <when...>)
    # (if <condition> <truebranch> <falsebranch>)
    index == 0 ? true : parent.value_used?
  when :while, :until, :while_post, :until_post
    # (while <condition> <body>) -> always evaluates to `nil`
    index == 0
  else
    true
  end
end

#variable?Boolean

Returns:

  • (Boolean)


382
383
384
# File 'lib/rubocop/ast_node.rb', line 382

def variable?
  VARIABLES.include?(type)
end