Class: RuboCop::Cop::Style::ConditionalAssignment
| 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/conditional_assignment.rb |
Overview
Checks for if and case statements where each branch is used for
both the assignment and comparison of the same variable
when using the return of the condition can be used instead.
Constant Summary
-
ASSIGNMENT_TYPES =
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 212VARIABLE_ASSIGNMENT_TYPES + %i[and_asgn or_asgn op_asgn masgn].freeze
-
ASSIGN_TO_CONDITION_MSG =
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 210'Assign variables inside of conditionals.' -
ENABLED =
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 213'Enabled' -
MSG =
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 209'Use the return of the conditional for variable assignment and comparison.' -
SINGLE_LINE_CONDITIONS_ONLY =
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 214'SingleLineConditionsOnly' -
VARIABLE_ASSIGNMENT_TYPES =
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 211%i[casgn cvasgn gvasgn ivasgn lvasgn].freeze
::RuboCop::Cop::Base - Inherited
EMPTY_OFFENSES, RESTRICT_ON_SEND
ConditionalAssignmentHelper - Included
ALIGN_WITH, END_ALIGNMENT, EQUAL, KEYWORD
::RuboCop::Cop::ConfigurableEnforcedStyle - Included
::RuboCop::Cop::ReparsedEquivalence - Included
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 |
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
- #include_ternary? ⇒ Boolean readonly private
- #single_line_conditions_only? ⇒ Boolean readonly private
::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 |
Instance Method Summary
-
#assignment_type?(node)
The shovel operator
<<does not have its own type. - #on_case(node)
- #on_case_match(node)
- #on_if(node)
- #on_send(node)
- #allowed_single_line?(branches) ⇒ Boolean private
- #allowed_statements?(branches) ⇒ Boolean private
- #allowed_ternary?(assignment) ⇒ Boolean private
-
#apply_reparse_correction(corrector, node)
private
ReparsedEquivalence#correction_parses? contract: apply the exact correction this cop would perform.
- #assignment_node(node) private
- #assignment_types_match?(*nodes) ⇒ Boolean private
- #autocorrect(corrector, node) private
- #candidate_condition?(node) private
- #candidate_node?(node) ⇒ Boolean private
- #check_assignment_to_condition(node) private
- #check_node(node, branches) private
-
#correction_exceeds_line_limit?(node, branches) ⇒ Boolean
private
If
Layout/LineLengthis enabled, we do not want to introduce an offense by autocorrecting this cop. - #lhs_all_match?(branches) ⇒ Boolean private
- #longest_line(node, assignment) private
- #longest_line_exceeds_line_limit?(node, assignment) ⇒ Boolean private
- #move_assignment_inside_condition(corrector, node) private
- #move_assignment_outside_condition(corrector, node) private
-
#safe_to_correct?(node) ⇒ Boolean
private
The correction rewrites the conditional structurally, so full AST equivalence cannot be asserted, but the result must at least reparse to valid Ruby.
- #ternary_condition?(node) ⇒ Boolean private
::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 |
| #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 |
| #preprocess_reparsed_source | Hook: rewrite both sides before parsing. |
| #reparse_scope | The innermost scope that both contains |
| #scope_groups, #verification_too_large?, | |
| #verified_by_reparse | Returns the items whose corrections are verified. |
::RuboCop::Cop::ConfigurableEnforcedStyle - Included
ConditionalAssignmentHelper - Included
| #end_with_eq?, | |
| #expand_elses |
|
| #expand_when_branches |
|
| #indent, #lhs, #tail, #assignment_rhs_exist?, #expand_elsif, #lhs_for_casgn, #lhs_for_send | |
::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 |
| #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, #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?, #range_for_original, #range_from_node_or_range, | |
| #reset_investigation | Actually private methods. |
| #suppression_reason | The |
| #use_corrector | |
::RuboCop::Cop::AutocorrectLogic - Included
::RuboCop::Cop::IgnoredNode - Included
Constructor Details
This class inherits a constructor from RuboCop::Cop::Base
Instance Attribute Details
#include_ternary? ⇒ Boolean (readonly, private)
[ GitHub ]
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 443
def include_ternary? cop_config['IncludeTernaryExpressions'] end
#single_line_conditions_only? ⇒ Boolean (readonly, private)
[ GitHub ]
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 439
def single_line_conditions_only? cop_config[SINGLE_LINE_CONDITIONS_ONLY] end
Instance Method Details
#allowed_single_line?(branches) ⇒ Boolean (private)
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 310
def allowed_single_line?(branches) single_line_conditions_only? && branches.compact.any?(&:begin_type?) end
#allowed_statements?(branches) ⇒ Boolean (private)
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 404
def allowed_statements?(branches) return false unless branches.all? statements = branches.filter_map { |branch| tail(branch) } lhs_all_match?(statements) && statements.none?(&:masgn_type?) && assignment_types_match?(*statements) end
#allowed_ternary?(assignment) ⇒ Boolean (private)
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 306
def allowed_ternary?(assignment) assignment.if_type? && assignment.ternary? && !include_ternary? end
#apply_reparse_correction(corrector, node) (private)
ReparsedEquivalence#correction_parses? contract: apply the exact correction this cop would perform.
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 400
def apply_reparse_correction(corrector, node) autocorrect(corrector, node) end
#assignment_node(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 314
def assignment_node(node) assignment = node.send_type? ? node.last_argument : node.expression return unless assignment # ignore pseudo-assignments without rhs in for nodes return if node.parent&.for_type? if assignment.begin_type? && assignment.children.one? assignment = assignment.children.first end assignment end
#assignment_type?(node)
The shovel operator << does not have its own type. It is a send
type.
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 219
def_node_matcher :assignment_type?, <<~PATTERN { #{ASSIGNMENT_TYPES.join(' ')} (send _recv {:[]= :<< :=~ :!~ :<=> #end_with_eq? :< :>} ...) } PATTERN
#assignment_types_match?(*nodes) ⇒ Boolean (private)
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 361
def assignment_types_match?(*nodes) return false unless assignment_type?(nodes.first) nodes.map(&:type).uniq.one? end
#autocorrect(corrector, node) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 377
def autocorrect(corrector, node) if assignment_type?(node) move_assignment_inside_condition(corrector, node) else move_assignment_outside_condition(corrector, node) end end
#candidate_condition?(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 304
def_node_matcher :candidate_condition?, '[{if case case_match} !#allowed_ternary?]'
#candidate_node?(node) ⇒ Boolean (private)
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 299
def candidate_node?(node) style == :assign_inside_condition && assignment_rhs_exist?(node) end
#check_assignment_to_condition(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 277
def check_assignment_to_condition(node) return unless candidate_node?(node) ignore_node(node) assignment = assignment_node(node) return unless candidate_condition?(assignment) _condition, *branches, else_branch = *assignment # Use the node accessor rather than the raw destructured branch: for # `x = unless cond; body; end` (no `else`) the parser puts `body` in the # else slot, but `else_branch` correctly reports there is no `else` clause. return unless assignment.else_branch return if allowed_single_line?([*branches, else_branch]) return unless safe_to_correct?(node) add_offense(node, message: ASSIGN_TO_CONDITION_MSG) do |corrector| autocorrect(corrector, node) end end
#check_node(node, branches) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 367
def check_node(node, branches) return if allowed_ternary?(node) return unless allowed_statements?(branches) return if allowed_single_line?(branches) return if correction_exceeds_line_limit?(node, branches) return unless safe_to_correct?(node) add_offense(node) { |corrector| autocorrect(corrector, node) } end
#correction_exceeds_line_limit?(node, branches) ⇒ Boolean (private)
If Layout/LineLength is enabled, we do not want to introduce an
offense by autocorrecting this cop. Find the max configured line
length. Find the longest line of condition. Remove the assignment
from lines that contain the offending assignment because after
correcting, this will not be on the line anymore. Check if the length
of the longest line + the length of the corrected assignment is
greater than the max configured line length
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 420
def correction_exceeds_line_limit?(node, branches) return false unless config.cop_enabled?('Layout/LineLength') assignment = lhs(tail(branches[0])) longest_line_exceeds_line_limit?(node, assignment) end
#lhs_all_match?(branches) ⇒ Boolean (private)
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 354
def lhs_all_match?(branches) return true if branches.empty? first_lhs = lhs(branches.first) branches.all? { |branch| lhs(branch) == first_lhs } end
#longest_line(node, assignment) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 432
def longest_line(node, assignment) assignment_regex = /\s*#{Regexp.escape(assignment).gsub('\ ', '\s*')}/ lines = node.source.lines.map { |line| line.chomp.sub(assignment_regex, '') } longest_line = lines.max_by(&:length) assignment + longest_line end
#longest_line_exceeds_line_limit?(node, assignment) ⇒ Boolean (private)
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 428
def longest_line_exceeds_line_limit?(node, assignment) longest_line(node, assignment).length > max_line_length end
#move_assignment_inside_condition(corrector, node) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 338
def move_assignment_inside_condition(corrector, node) condition = node.send_type? ? node.last_argument : node.expression if ternary_condition?(condition) TernaryCorrector.move_assignment_inside_condition(corrector, node) elsif condition.type?(:case, :case_match) CaseCorrector.move_assignment_inside_condition(corrector, node) elsif condition.if_type? IfCorrector.move_assignment_inside_condition(corrector, node) end end
#move_assignment_outside_condition(corrector, node) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 328
def move_assignment_outside_condition(corrector, node) if node.type?(:case, :case_match) CaseCorrector.correct(corrector, self, node) elsif node.ternary? TernaryCorrector.correct(corrector, node) elsif node.if? || node.unless? IfCorrector.correct(corrector, self, node) end end
#on_case(node)
[ GitHub ]# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 255
def on_case(node) return unless style == :assign_to_condition return unless node.else_branch when_branches = (node.when_branches) branches = [*when_branches, node.else_branch] check_node(node, branches) end
#on_case_match(node)
[ GitHub ]# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 265
def on_case_match(node) return unless style == :assign_to_condition return unless node.else_branch in_pattern_branches = (node.in_pattern_branches) branches = [*in_pattern_branches, node.else_branch] check_node(node, branches) end
#on_if(node)
[ GitHub ]# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 241
def on_if(node) return unless style == :assign_to_condition return if node.elsif? else_branch = node.else_branch elsif_branches, else_branch = (else_branch) return unless else_branch branches = [node.if_branch, *elsif_branches, else_branch] check_node(node, branches) end
#on_send(node)
[ GitHub ]# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 235
def on_send(node) return unless assignment_type?(node) check_assignment_to_condition(node) end
#safe_to_correct?(node) ⇒ Boolean (private)
The correction rewrites the conditional structurally, so full AST equivalence cannot be asserted, but the result must at least reparse to valid Ruby. Applying the correction to a throwaway buffer here also exercises the branch-shape handling before an offense is even reported, so unusual branches that the corrector cannot handle are left alone instead of crashing or emitting invalid code - the bug class behind most of this cop’s history.
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 392
def safe_to_correct?(node) correction_parses?(node) rescue StandardError false end
#ternary_condition?(node) ⇒ Boolean (private)
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 350
def ternary_condition?(node) [node, node.children.first].compact.any? { |n| n.if_type? && n.ternary? } end