123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Style::RedundantParentheses

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/redundant_parentheses.rb

Overview

Checks for redundant parentheses.

Examples:

# bad
(x) if ((y.z).nil?)

# good
x if y.z.nil?

Constant Summary

::RuboCop::Cop::Base - Inherited

EMPTY_OFFENSES, RESTRICT_ON_SEND

::RuboCop::Cop::ReparsedEquivalence - Included

MAX_VERIFICATION_FRAGMENT_SIZE

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

Instance Method Summary

::RuboCop::Cop::ReparsedEquivalence - Included

#corrected_scope_fragment

The corrections' edits are all contained within the scope, so the corrected fragment can be cut out of the corrected source by adjusting for the edits' length delta.

#correction_parses?

Whether the exact correction for item produces source that still parses, without requiring an equivalent AST.

#corrections_verify?, #item_range,
#normalize_reparsed_ast

Hook: loosen strict tree equality for corrections that are equivalence-preserving beyond parse identity.

#normalized_original,
#parses_equivalently?

Both sides are parsed with the original path so that FILE resolves identically.

#preprocess_reparsed_source

Hook: rewrite both sides before parsing.

#reparse_scope

The innermost scope that both contains range and parses standalone.

#scope_groups, #verification_too_large?,
#verified_by_reparse

Returns the items whose corrections are verified.

::RuboCop::Cop::Parentheses - 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,
#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 a gems locked versions (i.e.

#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, #current_corrector,
#current_offense_locations

Reserved for Commissioner:

#current_offenses, #currently_disabled_lines, #custom_severity, #default_severity, #disable_uncorrectable, #enabled_line?, #file_name_matches_any?, #find_message, #find_severity, #matches_absolute_include_pattern?, #range_for_original, #range_from_node_or_range,
#reset_investigation

Actually private methods.

#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_in_multiline_conditions?Boolean (readonly, private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 221

def allow_in_multiline_conditions?
  !!config.for_enabled_cop('Style/ParenthesesAroundCondition')['AllowInMultilineConditions']
end

#ternary_parentheses_required?Boolean (readonly, private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 106

def ternary_parentheses_required?
  config = @config.for_cop('Style/TernaryParentheses')
  allowed_styles = %w[require_parentheses require_parentheses_when_complex]

  config.fetch('Enabled') && allowed_styles.include?(config['EnforcedStyle'])
end

Instance Method Details

#allowed_ancestor?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 86

def allowed_ancestor?(node)
  # Don't flag `break(1)`, etc
  keyword_ancestor?(node) && parens_required?(node)
end

#allowed_expression?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 79

def allowed_expression?(node)
  allowed_ancestor?(node) ||
    allowed_multiple_expression?(node) ||
    allowed_ternary?(node) ||
    node.parent&.range_type?
end

#allowed_multiple_expression?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 91

def allowed_multiple_expression?(node)
  return false if node.children.one?

  ancestor = node.ancestors.first
  return false unless ancestor

  !ancestor.type?(:begin, :any_def, :any_block)
end

#allowed_pin_operator?(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 32

def_node_matcher :allowed_pin_operator?, '^(pin (begin !{lvar ivar cvar gvar}))'

#allowed_ternary?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 100

def allowed_ternary?(node)
  return false unless node&.parent&.if_type?

  node.parent.ternary? && ternary_parentheses_required?
end

#apply_reparse_correction(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 252

def apply_reparse_correction(corrector, node)
  ParenthesesCorrector.correct(corrector, node)
end

#argument_of_parenthesized_method_call?(begin_node, node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 197

def argument_of_parenthesized_method_call?(begin_node, node)
  if node.basic_conditional? || node.rescue_type? || method_call_parentheses_required?(node)
    return false
  end
  return false unless (parent = begin_node.parent)

  parent.call_type? && parent.parenthesized? && parent.receiver != begin_node
end

#body_range?(begin_node, node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 309

def body_range?(begin_node, node)
  return false if begin_node.chained?
  return false unless node.range_type?
  return false unless (parent = begin_node.parent)
  return false unless parent.begin_type?

  (node.begin.nil? && begin_node == parent.children.first) ||
    (node.end.nil? && begin_node == parent.children.last)
end

#call_node?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 225

def call_node?(node)
  node.call_type? || (node.any_block_type? && node.braces? && !node.lambda_or_proc?)
end

#check(begin_node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 139

def check(begin_node)
  node = begin_node.children.first

  if (message = find_offense_message(begin_node, node))
    return offense(begin_node, message) if message == 'block body'

    if node.range_type? && !argument_of_parenthesized_method_call?(begin_node, node)
      begin_node = begin_node.parent
    end

    return offense(begin_node, message)
  end

  check_send(begin_node, node) if call_node?(node)
end

#check_send(begin_node, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 229

def check_send(begin_node, node)
  node = node.send_node if node.any_block_type?

  return check_unary(begin_node, node) if node.unary_operation?

  return unless method_call_with_redundant_parentheses?(begin_node, node)

  offense(begin_node, 'a method call')
end

#check_unary(begin_node, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 239

def check_unary(begin_node, node)
  return if begin_node.chained?

  node = node.children.first while suspect_unary?(node)
  return unless method_call_with_redundant_parentheses?(begin_node, node)

  offense(begin_node, 'a unary operation')
end

#disallowed_literal?(begin_node, node) ⇒ Boolean (private)

[ GitHub ]

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

def disallowed_literal?(begin_node, node)
  return true unless node.range_type?
  return false unless (parent = begin_node.parent)

  parent.begin_type? && parent.children.one?
end

#disallowed_one_line_pattern_matching?(begin_node, node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 320

def disallowed_one_line_pattern_matching?(begin_node, node)
  if (parent = begin_node.parent)
    return false if parent.any_def_type? && parent.endless?
    return false if parent.assignment?
  end

  node.any_match_pattern_type? && node.each_ancestor.none?(&:operator_keyword?)
end

#empty_parentheses?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 127

def empty_parentheses?(node)
  # Don't flag `()`
  node.children.empty?
end

#find_offense_message(begin_node, node) (private)

Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 156

def find_offense_message(begin_node, node)
  return 'a keyword' if keyword_with_redundant_parentheses?(node)
  return 'a literal' if node.literal? && disallowed_literal?(begin_node, node)
  return 'a variable' if node.variable?
  return 'a constant' if node.const_type?
  return 'block body' if begin_node.parent&.any_block_type? || body_range?(begin_node, node)

  if node.assignment? && (begin_node.parent.nil? || begin_node.parent.begin_type?)
    return 'an assignment'
  end
  if node.lambda_or_proc? && (node.braces? || node.send_node.lambda_literal?)
    return 'an expression'
  end
  if disallowed_one_line_pattern_matching?(begin_node, node)
    return 'a one-line pattern matching'
  end
  return 'an interpolated expression' if interpolation?(begin_node)
  return 'a method argument' if argument_of_parenthesized_method_call?(begin_node, node)
  return 'a one-line rescue' if oneline_rescue_parentheses_required?(begin_node, node)

  return if begin_node.chained?

  if node.operator_keyword?
    return if node.semantic_operator? && begin_node.parent
    return if node.multiline? && allow_in_multiline_conditions?
    return if ALLOWED_NODE_TYPES.include?(begin_node.parent&.type)
    return if !node.and_type? && begin_node.parent&.and_type?
    return if begin_node.parent&.if_type? && begin_node.parent.ternary?

    'a logical expression'
  elsif node.respond_to?(:comparison_method?) && node.comparison_method?
    return unless begin_node.parent.nil?

    'a comparison expression'
  end
end

#ignore_syntax?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 72

def ignore_syntax?(node)
  return false unless (parent = node.parent)

  parent.type?(:while_post, :until_post, :match_with_lvasgn) ||
    like_method_argument_parentheses?(parent) || multiline_control_flow_statements?(node)
end

#in_pattern_matching_in_method_argument?(begin_node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 132

def in_pattern_matching_in_method_argument?(begin_node)
  return false unless begin_node.parent&.call_type?
  return false unless (node = begin_node.children.first)

  target_ruby_version <= 2.7 ? node.match_pattern_type? : node.match_pattern_p_type?
end

#interpolation?(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 195

def_node_matcher :interpolation?, '[^begin ^^dstr]'

#keyword_ancestor?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 297

def keyword_ancestor?(node)
  node.parent&.keyword?
end

#keyword_with_redundant_parentheses?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 329

def keyword_with_redundant_parentheses?(node)
  return false unless node.keyword?
  return true if node.special_keyword?

  args = *node

  if only_begin_arg?(args)
    parentheses?(args.first)
  else
    args.empty? || parentheses?(node)
  end
end

#like_method_argument_parentheses?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 113

def like_method_argument_parentheses?(node)
  return false unless node.type?(:send, :super, :yield)

  node.arguments.one? && !node.parenthesized? &&
    !node.operator_method? && node.first_argument.begin_type?
end

#method_call_parentheses_required?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 215

def method_call_parentheses_required?(node)
  return false unless node.call_type?

  (node.receiver.nil? || node.loc.dot) && node.arguments.any?
end

#method_call_with_redundant_parentheses?(begin_node, node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 342

def method_call_with_redundant_parentheses?(begin_node, node)
  return false unless node.type?(:call, :super, :yield, :defined?)
  return false if node.prefix_not?
  return true if singular_parenthesized_parent?(begin_node)

  node.arguments.empty? || parentheses?(node) || square_brackets?(node)
end

#multiline_control_flow_statements?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 120

def multiline_control_flow_statements?(node)
  return false unless (parent = node.parent)
  return false if parent.single_line?

  parent.type?(:return, :next, :break)
end

#normalize_reparsed_ast(node) (private)

Grouping parentheses are transparent to the comparison: single-child begin nodes are collapsed, a parenthesized statement sequence inside another sequence is spliced in place, and chains of the same &&/|| operator are normalized to left association (x && (y && z) and x && y && z differ as trees but && and {||} cannot be redefined, so same-operator regrouping is semantically transparent).

[ GitHub ]

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

def normalize_reparsed_ast(node)
  return node unless node.is_a?(::Parser::AST::Node)

  children = node.children.map { |child| normalize_reparsed_ast(child) }
  children = splice_nested_sequences(children) if %i[begin kwbegin].include?(node.type)

  node = node.updated(nil, children)
  if node.begin_type? && children.one? && children.first.is_a?(::Parser::AST::Node)
    children.first
  else
    rotate_same_operator(node)
  end
end

#offense(node, msg) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 248

def offense(node, msg)
  @pending_offenses[node] = "Don't use parentheses around #{msg}."
end

#on_begin(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 39

def on_begin(node)
  return if !parentheses?(node) || parens_allowed?(node) || ignore_syntax?(node)

  check(node)
end

#on_investigation_end

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 45

def on_investigation_end
  # Each candidate's exact correction is verified by reparsing before
  # the offense is registered, so redundancy never depends on
  # hand-maintained knowledge of Ruby's grammar.
  verified_by_reparse(@pending_offenses.keys).each do |node|
    add_offense(node, message: @pending_offenses[node]) do |corrector|
      ParenthesesCorrector.correct(corrector, node)
    end
  end

  super
end

#on_new_investigation

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 34

def on_new_investigation
  @pending_offenses = {}.compare_by_identity
  super
end

#oneline_rescue_parentheses_required?(begin_node, node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 206

def oneline_rescue_parentheses_required?(begin_node, node)
  return false unless node.rescue_type?
  return false unless (parent = begin_node.parent)
  return false if parent.if_type? && parent.ternary?
  return false if parent.conditional? && parent.condition == begin_node

  !parent.type?(:call, :array, :pair)
end

#only_begin_arg?(args) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 357

def only_begin_arg?(args)
  args.one? && args.first&.begin_type?
end

#parens_allowed?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 64

def parens_allowed?(node)
  empty_parentheses?(node) ||
    rescue?(node) ||
    in_pattern_matching_in_method_argument?(node) ||
    allowed_pin_operator?(node) ||
    allowed_expression?(node)
end

#rescue?(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 29

def_node_matcher :rescue?, '{^resbody ^^resbody}'

#rotate_same_operator(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 282

def rotate_same_operator(node)
  return node unless node.type?(:and, :or)

  right = node.rhs
  return node unless right.is_a?(::Parser::AST::Node) && right.type == node.type

  rotated_left = rotate_same_operator(node.updated(nil, [node.lhs, right.lhs]))

  rotate_same_operator(node.updated(nil, [rotated_left, right.rhs]))
end

#singular_parenthesized_parent?(begin_node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 350

def singular_parenthesized_parent?(begin_node)
  return true unless (parent = begin_node.parent)
  return false if parent.type?(:splat, :kwsplat)

  parent.children.one?
end

#splice_nested_sequences(children) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 276

def splice_nested_sequences(children)
  children.flat_map do |child|
    child.is_a?(::Parser::AST::Node) && child.begin_type? ? child.children : [child]
  end
end

#square_brackets?(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 24

def_node_matcher :square_brackets?, <<~PATTERN
  (send `{(send _recv _msg) str array hash const #variable?} :[] ...)
PATTERN

#suspect_unary?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 293

def suspect_unary?(node)
  node.send_type? && node.unary_operation? && !node.prefix_not?
end

#variable?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/redundant_parentheses.rb', line 60

def variable?(node)
  node.respond_to?(:variable?) && node.variable?
end