Class: RuboCop::AST::Node

Inherits:
Parser::AST::Node
  • Object
show all
Extended by:
NodePattern::Macros
Includes:
Sexp
Defined in:
lib/rubocop/ast/node.rb

Overview

`RuboCop::AST::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?)

Constant Summary collapse

COMPARISON_OPERATORS =

<=> isn't included here, because it doesn't return a boolean.

i[== === != <= >= > <].freeze
TRUTHY_LITERALS =
i[str dstr xstr int float sym dsym array
hash regexp true irange erange complex
rational regopt].freeze
FALSEY_LITERALS =
i[false nil].freeze
LITERALS =
(TRUTHY_LITERALS + FALSEY_LITERALS).freeze
COMPOSITE_LITERALS =
i[dstr xstr dsym array hash irange
erange regexp].freeze
BASIC_LITERALS =
(LITERALS - COMPOSITE_LITERALS).freeze
MUTABLE_LITERALS =
i[str dstr xstr array hash
regexp irange erange].freeze
IMMUTABLE_LITERALS =
(LITERALS - MUTABLE_LITERALS).freeze
EQUALS_ASSIGNMENTS =
i[lvasgn ivasgn cvasgn gvasgn
casgn masgn].freeze
SHORTHAND_ASSIGNMENTS =
i[op_asgn or_asgn and_asgn].freeze
ASSIGNMENTS =
(EQUALS_ASSIGNMENTS + SHORTHAND_ASSIGNMENTS).freeze
BASIC_CONDITIONALS =
i[if while until].freeze
CONDITIONALS =
[*BASIC_CONDITIONALS, :case].freeze
VARIABLES =
i[ivar gvar cvar lvar].freeze
REFERENCES =
i[nth_ref back_ref].freeze
KEYWORDS =
i[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 =
i[and or].freeze
SPECIAL_KEYWORDS =
%w[__FILE__ __LINE__ __ENCODING__].freeze

Instance Method Summary collapse

Methods included from NodePattern::Macros

def_node_matcher, def_node_search, node_search, node_search_all, node_search_body, node_search_first

Methods included from Sexp

#s

Constructor Details

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

Returns a new instance of Node


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

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 unless child_node.complete?
  end
end

Instance Method Details

#ancestorsArray<Node>

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


162
163
164
# File 'lib/rubocop/ast/node.rb', line 162

def ancestors
  each_ancestor.to_a
end

#argument?Boolean


468
469
470
# File 'lib/rubocop/ast/node.rb', line 468

def argument?
  parent&.send_type? && parent.arguments.include?(self)
end

#assignment?Boolean


429
430
431
# File 'lib/rubocop/ast/node.rb', line 429

def assignment?
  ASSIGNMENTS.include?(type)
end

#basic_conditional?Boolean


433
434
435
# File 'lib/rubocop/ast/node.rb', line 433

def basic_conditional?
  BASIC_CONDITIONALS.include?(type)
end

#basic_literal?Boolean


376
377
378
# File 'lib/rubocop/ast/node.rb', line 376

def basic_literal?
  BASIC_LITERALS.include?(type)
end

#boolean_type?Boolean


472
473
474
# File 'lib/rubocop/ast/node.rb', line 472

def boolean_type?
  true_type? || false_type?
end

#call_type?Boolean


460
461
462
# File 'lib/rubocop/ast/node.rb', line 460

def call_type?
  send_type? || csend_type?
end

#chained?Boolean


464
465
466
# File 'lib/rubocop/ast/node.rb', line 464

def chained?
  parent&.call_type? && eql?(parent.receiver)
end

#child_nodesArray<Node>

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


203
204
205
# File 'lib/rubocop/ast/node.rb', line 203

def child_nodes
  each_child_node.to_a
end

#complete!Object


92
93
94
95
# File 'lib/rubocop/ast/node.rb', line 92

def complete!
  @mutable_attributes.freeze
  each_child_node(&:complete!)
end

#complete?Boolean


97
98
99
# File 'lib/rubocop/ast/node.rb', line 97

def complete?
  @mutable_attributes.frozen?
end

#conditional?Boolean


437
438
439
# File 'lib/rubocop/ast/node.rb', line 437

def conditional?
  CONDITIONALS.include?(type)
end

#const_nameObject


311
312
313
314
315
316
317
318
319
320
# File 'lib/rubocop/ast/node.rb', line 311

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

rubocop:enable Style/AccessModifierDeclarations


332
333
334
335
# File 'lib/rubocop/ast/node.rb', line 332

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

#defined_module_nameObject


337
338
339
# File 'lib/rubocop/ast/node.rb', line 337

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`.


237
238
239
# File 'lib/rubocop/ast/node.rb', line 237

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.

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

    Yield only nodes matching any of the types.

  • #each_ancestor(types) ⇒ self, Enumerator

    Yield only nodes matching any of types in the array.

Yield Parameters:

  • node (Node)

    each ancestor node


150
151
152
153
154
155
156
# File 'lib/rubocop/ast/node.rb', line 150

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

  visit_ancestors(types, &block)

  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.

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

    Yield only nodes matching any of the types.

  • #each_child_node(types) ⇒ self, Enumerator

    Yield only nodes matching any of types in the array.

Yield Parameters:

  • node (Node)

    each child node


187
188
189
190
191
192
193
194
195
196
197
# File 'lib/rubocop/ast/node.rb', line 187

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

  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.

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

    Yield only nodes matching any of the types.

  • #each_descendant(types) ⇒ self, Enumerator

    Yield only nodes matching any of types in the array.

Yield Parameters:

  • node (Node)

    each descendant node


225
226
227
228
229
230
231
# File 'lib/rubocop/ast/node.rb', line 225

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

  visit_descendants(types, &block)

  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.

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

    Yield only nodes matching any of the types.

  • #each_node(types) ⇒ self, Enumerator

    Yield only nodes matching any of types in the array.

Yield Parameters:

  • node (Node)

    each node


263
264
265
266
267
268
269
270
271
# File 'lib/rubocop/ast/node.rb', line 263

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

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

  visit_descendants(types, &block)

  self
end

#empty_source?Boolean


363
364
365
# File 'lib/rubocop/ast/node.rb', line 363

def empty_source?
  source_length.zero?
end

#equals_asgn?Boolean


421
422
423
# File 'lib/rubocop/ast/node.rb', line 421

def equals_asgn?
  EQUALS_ASSIGNMENTS.include?(type)
end

#falsey_literal?Boolean


384
385
386
# File 'lib/rubocop/ast/node.rb', line 384

def falsey_literal?
  FALSEY_LITERALS.include?(type)
end

#first_lineObject


281
282
283
# File 'lib/rubocop/ast/node.rb', line 281

def first_line
  loc.line
end

#immutable_literal?Boolean


392
393
394
# File 'lib/rubocop/ast/node.rb', line 392

def immutable_literal?
  IMMUTABLE_LITERALS.include?(type)
end

#keyword?Boolean


441
442
443
444
445
446
# File 'lib/rubocop/ast/node.rb', line 441

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

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

#last_lineObject


285
286
287
# File 'lib/rubocop/ast/node.rb', line 285

def last_line
  loc.last_line
end

#line_countObject


289
290
291
292
293
# File 'lib/rubocop/ast/node.rb', line 289

def line_count
  return 0 unless source_range

  source_range.last_line - source_range.first_line + 1
end

#literal?Boolean


372
373
374
# File 'lib/rubocop/ast/node.rb', line 372

def literal?
  LITERALS.include?(type)
end

#multiline?Boolean

Predicates


355
356
357
# File 'lib/rubocop/ast/node.rb', line 355

def multiline?
  line_count > 1
end

#mutable_literal?Boolean


388
389
390
# File 'lib/rubocop/ast/node.rb', line 388

def mutable_literal?
  MUTABLE_LITERALS.include?(type)
end

#node_partsArray<Node>

Common destructuring method. This can be used to normalize destructuring for different variations of the node. Some node types override this with their own custom destructuring method.


128
129
130
# File 'lib/rubocop/ast/node.rb', line 128

def node_parts
  to_a
end

#nonempty_line_countObject


295
296
297
# File 'lib/rubocop/ast/node.rb', line 295

def nonempty_line_count
  source.lines.grep(/\S/).size
end

#numeric_type?Boolean


476
477
478
# File 'lib/rubocop/ast/node.rb', line 476

def numeric_type?
  int_type? || float_type?
end

#operator_keyword?Boolean


452
453
454
# File 'lib/rubocop/ast/node.rb', line 452

def operator_keyword?
  OPERATOR_KEYWORDS.include?(type)
end

#parentNode?

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


84
85
86
# File 'lib/rubocop/ast/node.rb', line 84

def parent
  @mutable_attributes[:parent]
end

#parent_module_nameObject

Searching the AST


343
344
345
346
347
348
349
350
351
# File 'lib/rubocop/ast/node.rb', line 343

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|
    parent_module_name_part(ancestor) { |full_name| return full_name }
  end.compact.reverse.join('::')
  result.empty? ? 'Object' : result
end

#parenthesized_call?Boolean


456
457
458
# File 'lib/rubocop/ast/node.rb', line 456

def parenthesized_call?
  loc.respond_to?(:begin) && loc.begin && loc.begin.is?('(')
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?


542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
# File 'lib/rubocop/ast/node.rb', line 542

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, :regopt
    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

#range_type?Boolean


480
481
482
# File 'lib/rubocop/ast/node.rb', line 480

def range_type?
  irange_type? || erange_type?
end

#receiverObject

Destructuring


305
306
307
# File 'lib/rubocop/ast/node.rb', line 305

def_node_matcher :receiver, <<~PATTERN
  {(send $_ ...) (block (send $_ ...) ...)}
PATTERN

#reference?Boolean


417
418
419
# File 'lib/rubocop/ast/node.rb', line 417

def reference?
  REFERENCES.include?(type)
end

#shorthand_asgn?Boolean


425
426
427
# File 'lib/rubocop/ast/node.rb', line 425

def shorthand_asgn?
  SHORTHAND_ASSIGNMENTS.include?(type)
end

#sibling_indexInteger

Returns the index of the receiver node in its siblings. (Sibling index uses zero based numbering.)


118
119
120
# File 'lib/rubocop/ast/node.rb', line 118

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

#single_line?Boolean


359
360
361
# File 'lib/rubocop/ast/node.rb', line 359

def single_line?
  line_count == 1
end

#sourceObject


273
274
275
# File 'lib/rubocop/ast/node.rb', line 273

def source
  loc.expression.source
end

#source_lengthObject


299
300
301
# File 'lib/rubocop/ast/node.rb', line 299

def source_length
  source_range ? source_range.size : 0
end

#source_rangeObject


277
278
279
# File 'lib/rubocop/ast/node.rb', line 277

def source_range
  loc.expression
end

#special_keyword?Boolean


448
449
450
# File 'lib/rubocop/ast/node.rb', line 448

def special_keyword?
  SPECIAL_KEYWORDS.include?(source)
end

#truthy_literal?Boolean


380
381
382
# File 'lib/rubocop/ast/node.rb', line 380

def truthy_literal?
  TRUTHY_LITERALS.include?(type)
end

#updated(type = nil, children = nil, properties = {}) ⇒ Object

Override `AST::Node#updated` so that `AST::Processor` does not try to mutate our ASTs. Since we keep references from children to parents and not just the other way around, we cannot update an AST and share identical subtrees. Rather, the entire AST must be copied any time any part of it is changed.


108
109
110
111
112
# File 'lib/rubocop/ast/node.rb', line 108

def updated(type = nil, children = nil, properties = {})
  properties[:location] ||= @location
  klass = RuboCop::AST::Builder::NODE_MAP[type || @type] || Node
  klass.new(type || @type, children || @children, properties)
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?

rubocop:disable Metrics/MethodLength, Metrics/CyclomaticComplexity


511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
# File 'lib/rubocop/ast/node.rb', line 511

def value_used?
  # Be conservative and return true if we're not sure.
  return false if parent.nil?

  case parent.type
  when :array, :defined?, :dstr, :dsym, :eflipflop, :erange, :float,
       :hash, :iflipflop, :irange, :not, :pair, :regexp, :str, :sym,
       :when, :xstr
    parent.value_used?
  when :begin, :kwbegin
    begin_value_used?
  when :for
    for_value_used?
  when :case, :if
    case_if_value_used?
  when :while, :until, :while_post, :until_post
    while_until_value_used?
  else
    true
  end
end

#variable?Boolean


413
414
415
# File 'lib/rubocop/ast/node.rb', line 413

def variable?
  VARIABLES.include?(type)
end