class RuboCop::AST::Node
‘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:
@example
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?)
Constants
- ARGUMENT_TYPES
@api private
- ASSIGNMENTS
@api private
- BASIC_CONDITIONALS
@api private
- BASIC_LITERALS
@api private
- COMPARISON_OPERATORS
@api private <=> isn’t included here, because it doesn’t return a boolean.
- COMPOSITE_LITERALS
@api private
- CONDITIONALS
@api private
- EMPTY_CHILDREN
- EMPTY_PROPERTIES
- EQUALS_ASSIGNMENTS
@api private
- FALSEY_LITERALS
@api private
- IMMUTABLE_LITERALS
@api private
- KEYWORDS
@api private
- LITERALS
@api private
- LITERAL_RECURSIVE_METHODS
- LITERAL_RECURSIVE_TYPES
- LOOP_TYPES
@api private
- MUTABLE_LITERALS
@api private
- OPERATOR_KEYWORDS
@api private
- POST_CONDITION_LOOP_TYPES
@api private
- REFERENCES
@api private
- SHORTHAND_ASSIGNMENTS
@api private
- SPECIAL_KEYWORDS
@api private
- TRUTHY_LITERALS
@api private
- VARIABLES
@api private
Public Class Methods
@see www.rubydoc.info/gems/ast/AST/Node:initialize
# File lib/rubocop/ast/node.rb, line 92 def initialize(type, children = EMPTY_CHILDREN, properties = EMPTY_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
Public Instance Methods
Returns an array of ancestor nodes. This is a shorthand for ‘node.each_ancestor.to_a`.
@return [Array<Node>] an array of ancestor nodes
# File lib/rubocop/ast/node.rb, line 247 def ancestors each_ancestor.to_a end
# File lib/rubocop/ast/node.rb, line 464 def argument? parent&.send_type? && parent.arguments.include?(self) end
# File lib/rubocop/ast/node.rb, line 468 def argument_type? ARGUMENT_TYPES.include?(type) end
# File lib/rubocop/ast/node.rb, line 416 def assignment? ASSIGNMENTS.include?(type) end
# File lib/rubocop/ast/node.rb, line 420 def basic_conditional? BASIC_CONDITIONALS.include?(type) end
# File lib/rubocop/ast/node.rb, line 363 def basic_literal? BASIC_LITERALS.include?(type) end
# File lib/rubocop/ast/node.rb, line 472 def boolean_type? true_type? || false_type? end
# File lib/rubocop/ast/node.rb, line 456 def call_type? send_type? || csend_type? end
# File lib/rubocop/ast/node.rb, line 460 def chained? parent&.call_type? && eql?(parent.receiver) end
# File lib/rubocop/ast/node.rb, line 144 def complete! @mutable_attributes.freeze each_child_node(&:complete!) end
# File lib/rubocop/ast/node.rb, line 149 def complete? @mutable_attributes.frozen? end
# File lib/rubocop/ast/node.rb, line 424 def conditional? CONDITIONALS.include?(type) end
# File lib/rubocop/ast/node.rb, line 293 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
# File lib/rubocop/ast/node.rb, line 314 def defined_module namespace, name = *defined_module0 s(:const, namespace, name) if name end
# File lib/rubocop/ast/node.rb, line 319 def defined_module_name (const = defined_module) && const.const_name end
Calls the given block for each ancestor node from parent to root. If no block is given, an ‘Enumerator` is returned.
@overload each_ancestor
Yield all nodes.
@overload each_ancestor(type)
Yield only nodes matching the type. @param [Symbol] type a node type
@overload each_ancestor(type_a, type_b, …)
Yield only nodes matching any of the types. @param [Symbol] type_a a node type @param [Symbol] type_b a node type
@yieldparam [Node] node each ancestor node @return [self] if a block is given @return [Enumerator] if no block is given
# File lib/rubocop/ast/node.rb, line 235 def each_ancestor(*types, &block) return to_enum(__method__, *types) unless block visit_ancestors(types, &block) self end
# File lib/rubocop/ast/node.rb, line 349 def empty_source? source_length.zero? end
# File lib/rubocop/ast/node.rb, line 408 def equals_asgn? EQUALS_ASSIGNMENTS.include?(type) end
# File lib/rubocop/ast/node.rb, line 371 def falsey_literal? FALSEY_LITERALS.include?(type) end
# File lib/rubocop/ast/node.rb, line 261 def first_line loc.line end
# File lib/rubocop/ast/node.rb, line 484 def guard_clause? node = and_type? || or_type? ? rhs : self node.match_guard_clause? end
# File lib/rubocop/ast/node.rb, line 379 def immutable_literal? IMMUTABLE_LITERALS.include?(type) end
# File lib/rubocop/ast/node.rb, line 437 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
# File lib/rubocop/ast/node.rb, line 265 def last_line loc.last_line end
Use is discouraged, this is a potentially slow method and can lead to even slower algorithms @return [Node, nil] the left (aka previous) sibling
# File lib/rubocop/ast/node.rb, line 187 def left_sibling i = sibling_index return if i.nil? || i.zero? parent.children[i - 1].freeze end
Use is discouraged, this is a potentially slow method and can lead to even slower algorithms @return [Array<Node>] the left (aka previous) siblings
# File lib/rubocop/ast/node.rb, line 197 def left_siblings return [].freeze unless parent parent.children[0...sibling_index].freeze end
# File lib/rubocop/ast/node.rb, line 269 def line_count return 0 unless source_range source_range.last_line - source_range.first_line + 1 end
# File lib/rubocop/ast/node.rb, line 359 def literal? LITERALS.include?(type) end
NOTE: ‘loop { }` is a normal method call and thus not a loop keyword.
# File lib/rubocop/ast/node.rb, line 433 def loop_keyword? LOOP_TYPES.include?(type) end
Predicates
# File lib/rubocop/ast/node.rb, line 341 def multiline? line_count > 1 end
# File lib/rubocop/ast/node.rb, line 375 def mutable_literal? MUTABLE_LITERALS.include?(type) end
# File lib/rubocop/ast/node.rb, line 275 def nonempty_line_count source.lines.grep(/\S/).size end
# File lib/rubocop/ast/node.rb, line 476 def numeric_type? int_type? || float_type? || rational_type? || complex_type? end
# File lib/rubocop/ast/node.rb, line 448 def operator_keyword? OPERATOR_KEYWORDS.include?(type) end
Returns the parent node, or ‘nil` if the receiver is a root node.
@return [Node, nil] the parent node or ‘nil`
# File lib/rubocop/ast/node.rb, line 126 def parent @mutable_attributes[:parent] end
@return [Boolean]
# File lib/rubocop/ast/node.rb, line 135 def parent? !!parent end
Searching the AST
# File lib/rubocop/ast/node.rb, line 325 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) do |full_name| return nil unless full_name full_name end end.compact.reverse.join('::') result.empty? ? 'Object' : result end
# File lib/rubocop/ast/node.rb, line 452 def parenthesized_call? loc.respond_to?(:begin) && loc.begin && loc.begin.is?('(') end
# File lib/rubocop/ast/node.rb, line 428 def post_condition_loop? POST_CONDITION_LOOP_TYPES.include?(type) end
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?
# File lib/rubocop/ast/node.rb, line 582 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
# File lib/rubocop/ast/node.rb, line 480 def range_type? irange_type? || erange_type? end
# File lib/rubocop/ast/node.rb, line 404 def reference? REFERENCES.include?(type) end
Use is discouraged, this is a potentially slow method and can lead to even slower algorithms @return [Node, nil] the right (aka next) sibling
# File lib/rubocop/ast/node.rb, line 178 def right_sibling return unless parent parent.children[sibling_index + 1].freeze end
Use is discouraged, this is a potentially slow method and can lead to even slower algorithms @return [Array<Node>] the right (aka next) siblings
# File lib/rubocop/ast/node.rb, line 206 def right_siblings return [].freeze unless parent parent.children[sibling_index + 1..].freeze end
@return [Boolean]
# File lib/rubocop/ast/node.rb, line 140 def root? !parent end
Most nodes are of ‘send’ type, so this method is defined separately to make this check as fast as possible.
# File lib/rubocop/ast/node.rb, line 119 def send_type? false end
# File lib/rubocop/ast/node.rb, line 412 def shorthand_asgn? SHORTHAND_ASSIGNMENTS.include?(type) end
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.
@return [Integer, nil] the index of the receiver node in its siblings
# File lib/rubocop/ast/node.rb, line 171 def sibling_index parent&.children&.index { |sibling| sibling.equal?(self) } end
# File lib/rubocop/ast/node.rb, line 345 def single_line? line_count == 1 end
NOTE: Some rare nodes may have no source, like ‘s(:args)` in `foo {}` @return [String, nil]
# File lib/rubocop/ast/node.rb, line 253 def source loc.expression&.source end
# File lib/rubocop/ast/node.rb, line 279 def source_length source_range ? source_range.size : 0 end
# File lib/rubocop/ast/node.rb, line 257 def source_range loc.expression end
# File lib/rubocop/ast/node.rb, line 444 def special_keyword? SPECIAL_KEYWORDS.include?(source) end
# File lib/rubocop/ast/node.rb, line 367 def truthy_literal? TRUTHY_LITERALS.include?(type) end
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.
# File lib/rubocop/ast/node.rb, line 160 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
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
# File lib/rubocop/ast/node.rb, line 551 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
# File lib/rubocop/ast/node.rb, line 400 def variable? VARIABLES.include?(type) end
Protected Instance Methods
# File lib/rubocop/ast/node.rb, line 130 def parent=(node) @mutable_attributes[:parent] = node end
Private Instance Methods
# File lib/rubocop/ast/node.rb, line 610 def begin_value_used? # the last child node determines the value of the parent sibling_index == parent.children.size - 1 ? parent.value_used? : false end
# File lib/rubocop/ast/node.rb, line 621 def case_if_value_used? # (case <condition> <when...>) # (if <condition> <truebranch> <falsebranch>) sibling_index.zero? ? true : parent.value_used? end
# File lib/rubocop/ast/node.rb, line 615 def for_value_used? # `for var in enum; body; end` # (for <var> <enum> <body>) sibling_index == 2 ? parent.value_used? : true end
# File lib/rubocop/ast/node.rb, line 657 def parent_module_name_for_block(ancestor) if ancestor.method?(:class_eval) # `class_eval` with no receiver applies to whatever module or class # we are currently in return unless (receiver = ancestor.receiver) yield unless receiver.const_type? receiver.const_name elsif !new_class_or_module_block?(ancestor) yield end end
# File lib/rubocop/ast/node.rb, line 645 def parent_module_name_for_sclass(sclass_node) # TODO: look for constant definition and see if it is nested # inside a class or module subject = sclass_node.children[0] if subject.const_type? "#<Class:#{subject.const_name}>" elsif subject.self_type? "#<Class:#{sclass_node.parent_module_name}>" end end
# File lib/rubocop/ast/node.rb, line 632 def parent_module_name_part(node) case node.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 node.defined_module_name when :sclass yield parent_module_name_for_sclass(node) else # block parent_module_name_for_block(node) { yield nil } end end
# File lib/rubocop/ast/node.rb, line 600 def visit_ancestors(types) last_node = self while (current_node = last_node.parent) yield current_node if types.empty? || types.include?(current_node.type) last_node = current_node end end
# File lib/rubocop/ast/node.rb, line 627 def while_until_value_used? # (while <condition> <body>) -> always evaluates to `nil` sibling_index.zero? end