123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Style::RegexpLiteral

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, ::RuboCop::Cop::AutoCorrector, ::RuboCop::Cop::Base, ::RuboCop::ExcludeLimit, NodePattern::Macros, RuboCop::AST::Sexp
Instance Chain:
Inherits: RuboCop::Cop::Base
Defined in: lib/rubocop/cop/style/regexp_literal.rb

Overview

Enforces using // or %r around regular expressions.

Note
The following %r cases using a regexp that starts with a blank or = as a method argument are allowed to prevent syntax errors.
do_something %r{ regexp} # `do_something / regexp/` is an invalid syntax.
do_something %r{=regexp} # `do_something /=regexp/` is an invalid syntax.

Examples:

EnforcedStyle: slashes (default)

# bad
snake_case = %r{^[\dA-Z_]+$}

# bad
regex = %r{
  foo
  (bar)
  (baz)
}x

# good
snake_case = /^[\dA-Z_]+$/

# good
regex = /
  foo
  (bar)
  (baz)
/x

EnforcedStyle: percent_r

# bad
snake_case = /^[\dA-Z_]+$/

# bad
regex = /
  foo
  (bar)
  (baz)
/x

# good
snake_case = %r{^[\dA-Z_]+$}

# good
regex = %r{
  foo
  (bar)
  (baz)
}x

EnforcedStyle: mixed

# bad
snake_case = %r{^[\dA-Z_]+$}

# bad
regex = /
  foo
  (bar)
  (baz)
/x

# good
snake_case = /^[\dA-Z_]+$/

# good
regex = %r{
  foo
  (bar)
  (baz)
}x

AllowInnerSlashes: false (default)

# If {false}, the cop will always recommend using {%r} if one or more
# slashes are found in the regexp string.

# bad
x =~ /home\//

# good
x =~ %r{home/}

AllowInnerSlashes: true

# good
x =~ /home\//

Constant Summary

::RuboCop::Cop::Base - Inherited

DEPARTMENT_SEVERITIES, EMPTY_OFFENSES, RESTRICT_ON_SEND

::RuboCop::Cop::ConfigurableEnforcedStyle - Included

SYMBOL_TO_STRING_CACHE

::RuboCop::Cop::RangeHelp - Included

BYTE_ORDER_MARK, NOT_GIVEN

Class Attribute Summary

::RuboCop::Cop::AutoCorrector - Extended

::RuboCop::Cop::Base - Inherited

.gem_requirements, .lint?,
.support_autocorrect?

Returns if class supports autocorrect.

.support_multiple_source?

Override if your cop should be called repeatedly for multiple investigations Between calls to on_new_investigation and on_investigation_end, the result of processed_source will remain constant.

Class Method Summary

::RuboCop::Cop::Base - Inherited

.autocorrect_incompatible_with

List of cops that should not try to autocorrect at the same time as this cop.

.badge

Naming.

.callbacks_needed, .cop_name, .department,
.documentation_url

Returns a url to view this cops documentation online.

.exclude_from_registry

Call for abstract Cop classes.

.inherited,
.joining_forces

Override and return the Force class(es) you need to join.

.match?

Returns true if the cop name or the cop namespace matches any of the given names.

.new,
.requires_gem

Register a version requirement for the given gem name.

.restrict_on_send

Reserved for Commissioner.

::RuboCop::ExcludeLimit - Extended

exclude_limit

Sets up a configuration option to have an exclude limit tracked.

transform

Instance Attribute Summary

::RuboCop::Cop::ConfigurableEnforcedStyle - Included

::RuboCop::Cop::Base - Inherited

::RuboCop::Cop::AutocorrectLogic - Included

#autocorrect?, #autocorrect_enabled?, #autocorrect_requested?, #autocorrect_with_disable_uncorrectable?, #correctable?, #disable_uncorrectable?, #safe_autocorrect?,
#skipped_unsafe_correction_with_disable_uncorrectable?

Whether a correction exists but is skipped because it is unsafe in a safe autocorrect run, while --disable-uncorrectable asks for a todo comment on everything this run cannot correct.

#contextual_autocorrect_held_back?

When LSP is enabled or the --editor-mode option is on, it is considered as editing source code, and autocorrection with AutoCorrect: contextual will not be performed.

Instance Method Summary

::RuboCop::Cop::RangeHelp - Included

#add_range,
#arguments_range

A range containing the first to the last argument of a method call or method definition.

#column_offset_between,
#contents_range

A range containing only the contents of a literal with delimiters (e.g.

#directions,
#effective_column

Returns the column attribute of the range, except if the range is on the first line and there’s a byte order mark at the beginning of that line, in which case 1 is subtracted from the column value.

#final_pos

rubocop:disable-next Metrics/ParameterLists.

#move_pos, #move_pos_str, #range_between, #range_by_whole_lines, #range_with_comments, #range_with_comments_and_lines, #range_with_surrounding_comma, #range_with_surrounding_space, #source_range

::RuboCop::Cop::ConfigurableEnforcedStyle - Included

::RuboCop::Cop::Base - Inherited

#add_global_offense

Adds an offense that has no particular location.

#add_offense

Adds an offense on the specified range (or node with an expression) Unless that offense is disabled for this range, a corrector will be yielded to provide the cop the opportunity to autocorrect the offense.

#begin_investigation

Called before any investigation.

#callbacks_needed

 — grouped under the Commissioner heading above.

#cop_config

Configuration Helpers.

#cop_name, #excluded_file?,
#external_dependency_checksum

This method should be overridden when a cop’s behavior depends on state that lives outside of these locations:

#inspect,
#message

Gets called if no message is specified when calling add_offense or add_global_offense Cops are discouraged to override this; instead pass your message directly.

#name

Alias for Base#cop_name.

#offenses,
#on_investigation_end

Called after all on_…​

#on_new_investigation

Called before all on_…​

#on_other_file

Called instead of all on_…​

#parse

There should be very limited reasons for a Cop to do it’s own parsing.

#parser_engine,
#ready

Called between investigations.

#relevant_file?,
#target_gem_version

Returns the version of a gem in the target, by default its locked version (i.e. from Gemfile.lock or gems.locked).

#target_rails_version, #target_ruby_version, #annotate, #apply_correction, #attempt_correction,
#callback_argument

Reserved for Cop::Cop.

#complete_investigation

Called to complete an investigation.

#correct, #covering_disabled_range, #current_corrector,
#current_offense_locations

Reserved for Commissioner:

#current_offenses, #currently_disabled_lines, #custom_severity, #default_severity, #disable_uncorrectable, #enabled_line?,
#enabled_lines?

A multi-line offense is suppressed by a directive on any line of its range, not only its first line, matching the intuition that the directive is attached to the offending code.

#file_name_matches_any?, #find_message, #find_severity, #matches_absolute_include_pattern?, #new_offense, #range_for_original, #range_from_node_or_range,
#reset_investigation

Actually private methods.

#suppression_reason

The -- reason on the directive that suppresses offenses on this range, or nil when the directive carries none.

#use_corrector

::RuboCop::Cop::AutocorrectLogic - Included

::RuboCop::Cop::IgnoredNode - Included

Constructor Details

This class inherits a constructor from RuboCop::Cop::Base

Instance Attribute Details

#allow_inner_slashes? ⇒ Boolean (readonly, private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 175

def allow_inner_slashes?
  cop_config['AllowInnerSlashes']
end

Instance Method Details

#allowed_mixed_percent_r?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 163

def allowed_mixed_percent_r?(node)
  (style == :mixed && node.multiline?) || contains_disallowed_slash?(node)
end

#allowed_mixed_slash?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 153

def allowed_mixed_slash?(node)
  style == :mixed && node.single_line? && !contains_disallowed_slash?(node)
end

#allowed_omit_parentheses_with_percent_r_literal?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 191

def allowed_omit_parentheses_with_percent_r_literal?(node)
  return false unless node.parent&.call_type?
  return true if node.content.start_with?(' ', '=')
  return true if first_argument_of_command?(node) && node.content.match?(/\A\s/)

  enforced_style = config.for_cop('Style/MethodCallWithArgsParentheses')['EnforcedStyle']

  enforced_style == 'omit_parentheses'
end

#allowed_percent_r_literal?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 157

def allowed_percent_r_literal?(node)
  (style == :slashes && contains_disallowed_slash?(node)) ||
    style == :percent_r ||
    allowed_mixed_percent_r?(node) || allowed_omit_parentheses_with_percent_r_literal?(node)
end

#allowed_slash_literal?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 149

def allowed_slash_literal?(node)
  (style == :slashes && !contains_disallowed_slash?(node)) || allowed_mixed_slash?(node)
end

#balanced_delimiters?(text, opening, closing, pattern) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 136

def balanced_delimiters?(text, opening, closing, pattern)
  depth = 0
  text.scan(pattern) do |match|
    if match == opening
      depth += 1
    elsif match == closing
      depth -= 1
      return false if depth.negative?
    end
  end
  depth.zero?
end

#calculate_replacement(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 254

def calculate_replacement(node)
  if slash_literal?(node)
    ['%r', ''].zip(preferred_delimiters).map(&:join)
  else
    %w[/ /]
  end
end

#contains_disallowed_slash?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 167

def contains_disallowed_slash?(node)
  !allow_inner_slashes? && contains_slash?(node)
end

#contains_slash?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 171

def contains_slash?(node)
  node_body(node).include?('/')
end

#correct_delimiters(node, corrector) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 208

def correct_delimiters(node, corrector)
  replacement = calculate_replacement(node)
  corrector.replace(node.loc.begin, replacement.first)
  corrector.replace(node.loc.end, replacement.last)
end

#correct_escaped_delimiters(node, corrector) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 262

def correct_escaped_delimiters(node, corrector)
  return unless (delimiter = delimiter_to_unescape(node))

  node.each_child_node(:str) do |str_node|
    text = str_node.source

    escaped_delimiter_indices(text, delimiter).each do |index|
      start = str_node.source_range.begin_pos + index
      replacement = escaped_delimiter_replacement(node, delimiter, text[index + 2])

      corrector.replace(range_between(start, start + 2), replacement)
    end
  end
end

#correct_inner_slashes(node, corrector) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 214

def correct_inner_slashes(node, corrector)
  pattern = inner_slash_before_correction(node)
  replacement = inner_slash_after_correction(node)

  node.each_child_node(:str) do |str_node|
    inner_slash_indices(str_node.source, pattern).each do |index|
      start = str_node.source_range.begin_pos + index

      corrector.replace(range_between(start, start + pattern.length), replacement)
    end
  end
end

#delimiter_to_unescape(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 277

def delimiter_to_unescape(node)
  return if slash_literal?(node)

  delimiter = node.delimiters.first

  delimiter unless delimiter == '/' || DELIMITERS_KEEPING_ESCAPE.include?(delimiter)
end

#escaped_delimiter_indices(text, delimiter) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 285

def escaped_delimiter_indices(text, delimiter)
  indices = []
  index = 0

  while (index = text.index('\\', index))
    indices << index if text[index + 1] == delimiter
    index += 2
  end

  indices
end

#escaped_delimiter_replacement(node, delimiter, next_char) (private)

A bare before {, {@} or {$} would start an interpolation between slashes. {\} still reads as a literal {} there, except in extended mode, where %r#a\{b}#x reads {b} as a comment; \{ keeps both that comment and a {#} inside a character class.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 301

def escaped_delimiter_replacement(node, delimiter, next_char)
  return delimiter unless delimiter == '#' && next_char&.match?(/[{@$]/)

  node.extended? ? '#\\' : '\\#'
end

#first_argument_of_command?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 201

def first_argument_of_command?(node)
  call = node.parent
  return false unless call.first_argument.equal?(node)

  !call.parenthesized? && !call.operator_method? && !call.setter_method?
end

#inner_slash_after_correction(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 231

def inner_slash_after_correction(node)
  inner_slash_for(calculate_replacement(node).first)
end

#inner_slash_before_correction(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 227

def inner_slash_before_correction(node)
  inner_slash_for(node.loc.begin.source)
end

#inner_slash_for(opening_delimiter) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 246

def inner_slash_for(opening_delimiter)
  if ['/', '%r/'].include?(opening_delimiter)
    '\/'
  else
    '/'
  end
end

#inner_slash_indices(text, pattern) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 235

def inner_slash_indices(text, pattern)
  index = -1
  indices = []

  while (index = text.index(pattern, index + 1))
    indices << index
  end

  indices
end

#node_body(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 179

def node_body(node)
  node.each_child_node(:str).map(&:source).join
end

#on_regexp(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 109

def on_regexp(node)
  return if slash_literal?(node) && percent_r_delimiters_conflict?(node)

  message = if slash_literal?(node)
              MSG_USE_PERCENT_R unless allowed_slash_literal?(node)
            else
              MSG_USE_SLASHES unless allowed_percent_r_literal?(node)
            end

  return unless message

  add_offense(node, message: message) do |corrector|
    correct_delimiters(node, corrector)
    correct_inner_slashes(node, corrector)
    correct_escaped_delimiters(node, corrector)
  end
end

#percent_r_delimiters_conflict?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 129

def percent_r_delimiters_conflict?(node)
  opening, closing = preferred_delimiters
  return false unless (pattern = PAIR_DELIMITER_PATTERNS[[opening, closing]])

  !balanced_delimiters?(node_body(node), opening, closing, pattern)
end

#preferred_delimiters (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 187

def preferred_delimiters
  config.for_cop('Style/PercentLiteralDelimiters')['PreferredDelimiters']['%r'].chars
end

#slash_literal?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/regexp_literal.rb', line 183

def slash_literal?(node)
  node.loc.begin.source == '/'
end