Class: RuboCop::AST::Node

Inherits:
Parser::AST::Node
  • Object
show all
Extended by:
RuboCop::AST::NodePattern::Macros
Includes:
Descendence, 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 =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

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

%i[== === != <= >= > <].to_set.freeze
TRUTHY_LITERALS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

%i[str dstr xstr int float sym dsym array
hash regexp true irange erange complex
rational regopt].to_set.freeze
FALSEY_LITERALS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

%i[false nil].to_set.freeze
LITERALS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

(TRUTHY_LITERALS + FALSEY_LITERALS).freeze
COMPOSITE_LITERALS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

%i[dstr xstr dsym array hash irange
erange regexp].to_set.freeze
BASIC_LITERALS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

(LITERALS - COMPOSITE_LITERALS).freeze
MUTABLE_LITERALS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

%i[str dstr xstr array hash
regexp irange erange].to_set.freeze
IMMUTABLE_LITERALS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

(LITERALS - MUTABLE_LITERALS).freeze
EQUALS_ASSIGNMENTS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

%i[lvasgn ivasgn cvasgn gvasgn
casgn masgn].to_set.freeze
SHORTHAND_ASSIGNMENTS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

%i[op_asgn or_asgn and_asgn].to_set.freeze
ASSIGNMENTS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

(EQUALS_ASSIGNMENTS + SHORTHAND_ASSIGNMENTS).freeze
BASIC_CONDITIONALS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

%i[if while until].to_set.freeze
CONDITIONALS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

(BASIC_CONDITIONALS + [:case]).freeze
POST_CONDITION_LOOP_TYPES =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

%i[while_post until_post].to_set.freeze
LOOP_TYPES =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

(POST_CONDITION_LOOP_TYPES + %i[while until for]).freeze
VARIABLES =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

%i[ivar gvar cvar lvar].to_set.freeze
REFERENCES =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

%i[nth_ref back_ref].to_set.freeze
KEYWORDS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

%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].to_set.freeze
OPERATOR_KEYWORDS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

%i[and or].to_set.freeze
SPECIAL_KEYWORDS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

%w[__FILE__ __LINE__ __ENCODING__].to_set.freeze
ARGUMENT_TYPES =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

%i[arg optarg restarg kwarg kwoptarg kwrestarg
blockarg forward_arg shadowarg].to_set.freeze

Instance Method Summary collapse

Methods included from RuboCop::AST::NodePattern::Macros

def_node_matcher, def_node_search

Methods included from Descendence

#child_nodes, #descendants, #each_child_node, #each_descendant, #each_node

Methods included from Sexp

#s

Constructor Details

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

Returns a new instance of Node.


88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/rubocop/ast/node.rb', line 88

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

Returns:

  • (Array<Node>)

    an array of ancestor nodes


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

def ancestors
  each_ancestor.to_a
end

#argument?Boolean

Returns:

  • (Boolean)

446
447
448
# File 'lib/rubocop/ast/node.rb', line 446

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

#argument_type?Boolean

Returns:

  • (Boolean)

450
451
452
# File 'lib/rubocop/ast/node.rb', line 450

def argument_type?
  ARGUMENT_TYPES.include?(type)
end

#assignment?Boolean

Returns:

  • (Boolean)

398
399
400
# File 'lib/rubocop/ast/node.rb', line 398

def assignment?
  ASSIGNMENTS.include?(type)
end

#basic_conditional?Boolean

Returns:

  • (Boolean)

402
403
404
# File 'lib/rubocop/ast/node.rb', line 402

def basic_conditional?
  BASIC_CONDITIONALS.include?(type)
end

#basic_literal?Boolean

Returns:

  • (Boolean)

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

def basic_literal?
  BASIC_LITERALS.include?(type)
end

#boolean_type?Boolean

Returns:

  • (Boolean)

454
455
456
# File 'lib/rubocop/ast/node.rb', line 454

def boolean_type?
  true_type? || false_type?
end

#call_type?Boolean

Returns:

  • (Boolean)

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

def call_type?
  send_type? || csend_type?
end

#chained?Boolean

Returns:

  • (Boolean)

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

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

#complete!Object


132
133
134
135
# File 'lib/rubocop/ast/node.rb', line 132

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

#complete?Boolean

Returns:

  • (Boolean)

137
138
139
# File 'lib/rubocop/ast/node.rb', line 137

def complete?
  @mutable_attributes.frozen?
end

#conditional?Boolean

Returns:

  • (Boolean)

406
407
408
# File 'lib/rubocop/ast/node.rb', line 406

def conditional?
  CONDITIONALS.include?(type)
end

#const_nameObject


281
282
283
284
285
286
287
288
289
290
# File 'lib/rubocop/ast/node.rb', line 281

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


301
302
303
304
# File 'lib/rubocop/ast/node.rb', line 301

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

#defined_module_nameObject


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

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

#each_ancestorself, Enumerator #each_ancestor(type) ⇒ self, Enumerator #each_ancestor(type_a, type_b, ...) ⇒ 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

Yield Parameters:

  • node (Node)

    each ancestor node

Returns:

  • (self)

    if a block is given

  • (Enumerator)

    if no block is given


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

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

  visit_ancestors(types, &block)

  self
end

#empty_source?Boolean

Returns:

  • (Boolean)

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

def empty_source?
  source_length.zero?
end

#equals_asgn?Boolean

Returns:

  • (Boolean)

390
391
392
# File 'lib/rubocop/ast/node.rb', line 390

def equals_asgn?
  EQUALS_ASSIGNMENTS.include?(type)
end

#falsey_literal?Boolean

Returns:

  • (Boolean)

353
354
355
# File 'lib/rubocop/ast/node.rb', line 353

def falsey_literal?
  FALSEY_LITERALS.include?(type)
end

#first_lineObject


251
252
253
# File 'lib/rubocop/ast/node.rb', line 251

def first_line
  loc.line
end

#guard_clause?Boolean

Returns:

  • (Boolean)

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

def guard_clause?
  node = and_type? || or_type? ? rhs : self

  node.match_guard_clause?
end

#immutable_literal?Boolean

Returns:

  • (Boolean)

361
362
363
# File 'lib/rubocop/ast/node.rb', line 361

def immutable_literal?
  IMMUTABLE_LITERALS.include?(type)
end

#keyword?Boolean

Returns:

  • (Boolean)

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

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


255
256
257
# File 'lib/rubocop/ast/node.rb', line 255

def last_line
  loc.last_line
end

#left_siblingNode?

Use is discouraged, this is a potentially slow method and can lead to even slower algorithms

Returns:

  • (Node, nil)

    the left (aka previous) sibling


175
176
177
178
179
180
# File 'lib/rubocop/ast/node.rb', line 175

def left_sibling
  i = sibling_index
  return if i.nil? || i.zero?

  parent.children[i - 1].freeze
end

#left_siblingsArray<Node>

Use is discouraged, this is a potentially slow method and can lead to even slower algorithms

Returns:

  • (Array<Node>)

    the left (aka previous) siblings


185
186
187
188
189
# File 'lib/rubocop/ast/node.rb', line 185

def left_siblings
  return [].freeze unless parent

  parent.children[0...sibling_index].freeze
end

#line_countObject


259
260
261
262
263
# File 'lib/rubocop/ast/node.rb', line 259

def line_count
  return 0 unless source_range

  source_range.last_line - source_range.first_line + 1
end

#literal?Boolean

Returns:

  • (Boolean)

341
342
343
# File 'lib/rubocop/ast/node.rb', line 341

def literal?
  LITERALS.include?(type)
end

#loop_keyword?Boolean

NOTE: `loop { }` is a normal method call and thus not a loop keyword.

Returns:

  • (Boolean)

415
416
417
# File 'lib/rubocop/ast/node.rb', line 415

def loop_keyword?
  LOOP_TYPES.include?(type)
end

#multiline?Boolean

Predicates

Returns:

  • (Boolean)

324
325
326
# File 'lib/rubocop/ast/node.rb', line 324

def multiline?
  line_count > 1
end

#mutable_literal?Boolean

Returns:

  • (Boolean)

357
358
359
# File 'lib/rubocop/ast/node.rb', line 357

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.

Returns:

  • (Array<Node>)

    the different parts of the ndde


206
207
208
# File 'lib/rubocop/ast/node.rb', line 206

def node_parts
  to_a
end

#nonempty_line_countObject


265
266
267
# File 'lib/rubocop/ast/node.rb', line 265

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

#numeric_type?Boolean

Returns:

  • (Boolean)

458
459
460
# File 'lib/rubocop/ast/node.rb', line 458

def numeric_type?
  int_type? || float_type?
end

#operator_keyword?Boolean

Returns:

  • (Boolean)

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

def operator_keyword?
  OPERATOR_KEYWORDS.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`


114
115
116
# File 'lib/rubocop/ast/node.rb', line 114

def parent
  @mutable_attributes[:parent]
end

#parent?Boolean

Returns:

  • (Boolean)

123
124
125
# File 'lib/rubocop/ast/node.rb', line 123

def parent?
  !!parent
end

#parent_module_nameObject

Searching the AST


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

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

Returns:

  • (Boolean)

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

def parenthesized_call?
  loc.respond_to?(:begin) && loc.begin && loc.begin.is?('(')
end

#post_condition_loop?Boolean

Returns:

  • (Boolean)

410
411
412
# File 'lib/rubocop/ast/node.rb', line 410

def post_condition_loop?
  POST_CONDITION_LOOP_TYPES.include?(type)
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)

548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
# File 'lib/rubocop/ast/node.rb', line 548

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

Returns:

  • (Boolean)

462
463
464
# File 'lib/rubocop/ast/node.rb', line 462

def range_type?
  irange_type? || erange_type?
end

#receiverObject

Destructuring


275
276
277
# File 'lib/rubocop/ast/node.rb', line 275

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

#reference?Boolean

Returns:

  • (Boolean)

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

def reference?
  REFERENCES.include?(type)
end

#right_siblingNode?

Use is discouraged, this is a potentially slow method and can lead to even slower algorithms

Returns:

  • (Node, nil)

    the right (aka next) sibling


166
167
168
169
170
# File 'lib/rubocop/ast/node.rb', line 166

def right_sibling
  return unless parent

  parent.children[sibling_index + 1].freeze
end

#right_siblingsArray<Node>

Use is discouraged, this is a potentially slow method and can lead to even slower algorithms

Returns:

  • (Array<Node>)

    the right (aka next) siblings


194
195
196
197
198
# File 'lib/rubocop/ast/node.rb', line 194

def right_siblings
  return [].freeze unless parent

  parent.children[sibling_index + 1..-1].freeze
end

#root?Boolean

Returns:

  • (Boolean)

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

def root?
  !parent
end

#shorthand_asgn?Boolean

Returns:

  • (Boolean)

394
395
396
# File 'lib/rubocop/ast/node.rb', line 394

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.) Use is discouraged, this is a potentially slow method.

Returns:

  • (Integer, nil)

    the index of the receiver node in its siblings


159
160
161
# File 'lib/rubocop/ast/node.rb', line 159

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

#single_line?Boolean

Returns:

  • (Boolean)

328
329
330
# File 'lib/rubocop/ast/node.rb', line 328

def single_line?
  line_count == 1
end

#sourceString?

NOTE: Some rare nodes may have no source, like `s(:args)` in `foo {}`

Returns:

  • (String, nil)

243
244
245
# File 'lib/rubocop/ast/node.rb', line 243

def source
  loc.expression&.source
end

#source_lengthObject


269
270
271
# File 'lib/rubocop/ast/node.rb', line 269

def source_length
  source_range ? source_range.size : 0
end

#source_rangeObject


247
248
249
# File 'lib/rubocop/ast/node.rb', line 247

def source_range
  loc.expression
end

#special_keyword?Boolean

Returns:

  • (Boolean)

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

def special_keyword?
  SPECIAL_KEYWORDS.include?(source)
end

#truthy_literal?Boolean

Returns:

  • (Boolean)

349
350
351
# File 'lib/rubocop/ast/node.rb', line 349

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.


148
149
150
151
152
# File 'lib/rubocop/ast/node.rb', line 148

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

Returns:

  • (Boolean)

517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
# File 'lib/rubocop/ast/node.rb', line 517

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

Returns:

  • (Boolean)

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

def variable?
  VARIABLES.include?(type)
end