123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Style::TernaryParentheses

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

Overview

Checks for the presence of parentheses around ternary conditions. It is configurable to enforce inclusion or omission of parentheses using EnforcedStyle. Omission is only enforced when removing the parentheses won’t cause a different behavior.

AllowSafeAssignment option for safe assignment. By safe assignment we mean putting parentheses around an assignment to indicate "I know I’m using an assignment as a condition. It’s not a mistake."

Examples:

EnforcedStyle: require_no_parentheses (default)

# bad
foo = (bar?) ? a : b
foo = (bar.baz?) ? a : b
foo = (bar && baz) ? a : b

# good
foo = bar? ? a : b
foo = bar.baz? ? a : b
foo = bar && baz ? a : b

EnforcedStyle: require_parentheses

# bad
foo = bar? ? a : b
foo = bar.baz? ? a : b
foo = bar && baz ? a : b

# good
foo = (bar?) ? a : b
foo = (bar.baz?) ? a : b
foo = (bar && baz) ? a : b

EnforcedStyle: require_parentheses_when_complex

# bad
foo = (bar?) ? a : b
foo = (bar.baz?) ? a : b
foo = bar && baz ? a : b

# good
foo = bar? ? a : b
foo = bar.baz? ? a : b
foo = (bar && baz) ? a : b

AllowSafeAssignment: true (default)

# good
foo = (bar = baz) ? a : b

AllowSafeAssignment: false

# bad
foo = (bar = baz) ? a : b

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

::RuboCop::Cop::SurroundingSpace - Included

NO_SPACE_COMMAND, SINGLE_SPACE_REGEXP, SPACE_COMMAND

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

#verified_subset

Verifies a group with a single reparse and bisects it when that fails, so a few significant items among many cost a logarithmic number of reparses rather than one each.

::RuboCop::Cop::SurroundingSpace - Included

::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::SafeAssignment - 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

#require_parentheses? ⇒ Boolean (readonly, private)

[ GitHub ]

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

def require_parentheses?
  style == :require_parentheses
end

#require_parentheses_when_complex? ⇒ Boolean (readonly, private)

[ GitHub ]

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

def require_parentheses_when_complex?
  style == :require_parentheses_when_complex
end

Instance Method Details

#apply_reparse_correction(corrector, condition) (private)

Whatever binds looser than the ternary operator (n += 1, a rescue b, a nested ternary, yield a, several statements, …​) changes meaning without the parentheses, so their removal is verified by reparsing.

[ GitHub ]

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

def apply_reparse_correction(corrector, condition)
  correct_parenthesized(corrector, condition)
end

#autocorrect(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 101

def autocorrect(corrector, node)
  condition = node.condition

  return nil if parenthesized?(condition) &&
                (safe_assignment?(condition) || unsafe_autocorrect?(condition) ||
                 verified_by_reparse([condition]).empty?)

  if parenthesized?(condition)
    correct_parenthesized(corrector, condition)
  else
    correct_unparenthesized(corrector, condition)
  end
end

#below_ternary_precedence?(child) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 194

def below_ternary_precedence?(child)
  # Handle English "or", e.g. 'foo or bar ? a : b'
  (child.or_type? && child.semantic_operator?) ||
    # Handle English "and", e.g. 'foo and bar ? a : b'
    (child.and_type? && child.semantic_operator?) ||
    # Handle English "not", e.g. 'not foo ? a : b'
    (child.send_type? && child.prefix_not?)
end

#complex_condition?(condition) ⇒ Boolean (private)

If the condition is parenthesized we recurse and check for any complex expressions within it.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 137

def complex_condition?(condition)
  if condition.begin_type?
    condition.to_a.any? { |x| complex_condition?(x) }
  else
    !non_complex_expression?(condition)
  end
end

#condition_as_parenthesized_one_line_pattern_matching?(condition) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 90

def condition_as_parenthesized_one_line_pattern_matching?(condition)
  return false unless condition.parenthesized_call?
  return false unless (first_child = condition.children.first)

  if target_ruby_version >= 3.0
    first_child.match_pattern_p_type?
  else
    first_child.match_pattern_type? # For Ruby 2.7's one line pattern matching AST.
  end
end

#correct_parenthesized(corrector, condition) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 209

def correct_parenthesized(corrector, condition)
  corrector.remove(condition.loc.begin)
  corrector.remove(condition.loc.end)

  # Ruby allows no space between the question mark and parentheses.
  # If we remove the parentheses, we need to add a space or we'll
  # generate invalid code.
  corrector.insert_after(condition.loc.end, ' ') unless whitespace_after?(condition)

  if (send_node = condition.child_nodes.last) && node_args_need_parens?(send_node)
    parenthesize_condition_arguments(corrector, send_node)
  end
end

#correct_unparenthesized(corrector, condition) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 243

def correct_unparenthesized(corrector, condition)
  corrector.wrap(condition, '(', ')')
end

#message(node) (private)

[ GitHub ]

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

def message(node)
  if require_parentheses_when_complex?
    command = parenthesized?(node.condition) ? 'Only use' : 'Use'
    format(MSG_COMPLEX, command: command)
  else
    command = require_parentheses? ? 'Use' : 'Omit'
    format(MSG, command: command)
  end
end

#method_name(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 204

def_node_matcher :method_name, <<~PATTERN
  {($:defined? _ ...)
   (call {_ nil?} $_ _ ...)}
PATTERN

#node_args_need_parens?(send_node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 260

def node_args_need_parens?(send_node)
  return false unless node_with_args?(send_node)
  return false if send_node.arguments.none? || send_node.parenthesized?

  send_node.dot? || send_node.safe_navigation? || unparenthesized_method_call?(send_node)
end

#node_with_args?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 267

def node_with_args?(node)
  node.type?(:call, :defined?)
end

#non_complex_expression?(condition) ⇒ Boolean (private)

Anything that is not a variable, constant, or method/.method call will be counted as a complex expression.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 147

def non_complex_expression?(condition)
  NON_COMPLEX_TYPES.include?(condition.type) || non_complex_send?(condition)
end

#non_complex_send?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 151

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

  !node.operator_method? || node.method?(:[])
end

#normalize_reparsed_ast(node) (private)

The removed parentheses are the only expected difference.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 232

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

  children = node.children.map { |child| normalize_reparsed_ast(child) }
  if node.begin_type? && children.one? && children.first.is_a?(::Parser::AST::Node)
    children.first
  else
    node.updated(nil, children)
  end
end

#offense?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 115

def offense?(node)
  condition = node.condition

  # A modifier `if`/`unless` requires the parentheses, e.g. `(a if b) ? x : y`,
  # so removing them would change the meaning. Don't flag it.
  return false if parenthesized_modifier_condition?(condition)

  if safe_assignment?(condition)
    !safe_assignment_allowed?
  else
    parens = parenthesized?(condition)
    case style
    when :require_parentheses_when_complex
      complex_condition?(condition) ? !parens : parens
    else
      require_parentheses? ? !parens : parens
    end
  end
end

#on_if(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 70

def on_if(node)
  condition = node.condition

  return if only_closing_parenthesis_is_last_line?(condition)
  return if condition_as_parenthesized_one_line_pattern_matching?(condition)
  return unless node.ternary? && offense?(node)

  message = message(node)

  add_offense(node, message: message) do |corrector|
    autocorrect(corrector, node)
  end
end

#only_closing_parenthesis_is_last_line?(condition) ⇒ Boolean (private)

[ GitHub ]

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

def only_closing_parenthesis_is_last_line?(condition)
  condition.source.split("\n").last == ')'
end

#parenthesize_condition_arguments(corrector, send_node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 247

def parenthesize_condition_arguments(corrector, send_node)
  range_start = send_node.defined_type? ? send_node.loc.keyword : send_node.loc.selector
  opening_range = range_start.end.join(send_node.first_argument.source_range.begin)

  corrector.replace(opening_range, '(')
  corrector.insert_after(send_node.last_argument, ')')
end

#parenthesized?(node) ⇒ Boolean (private)

[ GitHub ]

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

def parenthesized?(node)
  node.begin_type?
end

#parenthesized_modifier_condition?(condition) ⇒ Boolean (private)

[ GitHub ]

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

def parenthesized_modifier_condition?(condition)
  return false unless condition.begin_type?

  inner = condition.children.first
  inner&.if_type? && inner.modifier_form?
end

#unparenthesized_method_call?(child) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 190

def unparenthesized_method_call?(child)
  /^[a-z]/i.match?(method_name(child)) && !child.parenthesized?
end

#unsafe_autocorrect?(condition) ⇒ Boolean (private)

[ GitHub ]

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

def unsafe_autocorrect?(condition)
  condition.children.any? { |child| below_ternary_precedence?(child) }
end

#whitespace_after?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/ternary_parentheses.rb', line 255

def whitespace_after?(node)
  last_token = processed_source.last_token_of(node)
  last_token.space_after?
end