123456789_123456789_123456789_123456789_123456789_

Module: RuboCop::Ext::RegexpNode

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Instance Chain:
self, RuboCop::Ext::RegexpNode.self
Defined in: lib/rubocop/ext/regexp_node.rb

Overview

Extensions to AST::RegexpNode for our cached parsed regexp info

Constant Summary

Instance Attribute Summary

Instance Method Summary

Instance Attribute Details

#parsed_treeRegexp::Expression::Root? (readonly)

Note: we extend Regexp nodes to provide loc and expression see ext/regexp_parser.

[ GitHub ]

  
# File 'lib/rubocop/ext/regexp_node.rb', line 16

attr_reader :parsed_tree

Instance Method Details

#assign_properties

[ GitHub ]

  
# File 'lib/rubocop/ext/regexp_node.rb', line 18

def assign_properties(*)
  super

  str = with_interpolations_blanked
  @parsed_tree = begin
    Regexp::Parser.parse(str, options: options)
  rescue StandardError
    nil
  end
  origin = loc.begin.end
  @parsed_tree&.each_expression(true) { |e| e.origin = origin }
end

#each_capture(named: ANY)

[ GitHub ]

  
# File 'lib/rubocop/ext/regexp_node.rb', line 31

def each_capture(named: ANY)
  return enum_for(__method__, named: named) unless block_given?

  parsed_tree&.traverse do |event, exp, _index|
    yield(exp) if named_capturing?(exp, event, named)
  end

  self
end

#named_capturing?(exp, event, named) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/ext/regexp_node.rb', line 43

def named_capturing?(exp, event, named)
  event == :enter &&
    named == exp.respond_to?(:name) &&
    !exp.text.start_with?('(?<=') &&
    exp.respond_to?(:capturing?) &&
    exp.capturing?
end

#with_interpolations_blanked (private)

[ GitHub ]

  
# File 'lib/rubocop/ext/regexp_node.rb', line 51

def with_interpolations_blanked
  # Ignore the trailing regopt node
  children[0...-1].map do |child|
    source = child.source

    # We don't want to consider the contents of interpolations as part of the pattern source,
    # but need to preserve their width, to allow offsets to correctly line up with the
    # original source: spaces have no effect, and preserve width.
    if child.begin_type?
      ' ' * source.length
    else
      source
    end
  end.join
end