Class: RuboCop::Cop::Style::InverseMethods
| 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:
self,
::RuboCop::Cop::RangeHelp,
::RuboCop::Cop::Base,
::RuboCop::Cop::AutocorrectLogic,
::RuboCop::Cop::IgnoredNode,
::RuboCop::Util,
RuboCop::AST::Sexp
|
|
| Inherits: |
RuboCop::Cop::Base
|
| Defined in: | lib/rubocop/cop/style/inverse_methods.rb |
Overview
Checks for usages of not (not or !) called on a method
when an inverse of that method can be used instead.
Methods that can be inverted by a not (not or !) should be defined
in InverseMethods.
Methods that are inverted by inverting the return
of the block that is passed to the method should be defined in
InverseBlocks.
Constant Summary
-
CAMEL_CASE =
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 52/[A-Z]+[a-z]+/.freeze
-
CLASS_COMPARISON_METHODS =
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 48%i[<= >= < >].freeze
-
EQUALITY_METHODS =
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 50%i[== != =~ !~ <= >= < >].freeze
-
MSG =
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 47'Use `%<inverse>s` instead of inverting `%<method>s`.' -
NEGATED_EQUALITY_METHODS =
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 51%i[!= !~].freeze
-
RESTRICT_ON_SEND =
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 54[:!].freeze
-
SAFE_NAVIGATION_INCOMPATIBLE_METHODS =
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 49(CLASS_COMPARISON_METHODS + %i[any? none?]).freeze
::RuboCop::Cop::Base - Inherited
DEPARTMENT_SEVERITIES, EMPTY_OFFENSES, RESTRICT_ON_SEND
::RuboCop::Cop::RangeHelp - 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
::RuboCop::Cop::Base - Inherited
| #active_support_extensions_enabled?, #always_autocorrect?, #config, #config_to_allow_offenses, #config_to_allow_offenses=, #contextual_autocorrect?, #disabled_autocorrect?, | |
| #preview? | Whether the user opted in to unstable behavior, with |
| #processed_source, #project_index, #string_literals_frozen_by_default?, #target_satisfies_all_gem_version_requirements? | |
::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 |
| #contextual_autocorrect_held_back? | When LSP is enabled or the |
Instance Method Summary
- #class_hierarchy_value_method?(node)
- #inverse_block?(node)
- #inverse_candidate?(node)
- #on_block(node) (also: #on_numblock, #on_itblock)
-
#on_csend(node)
Alias for #on_send.
-
#on_itblock(node)
Alias for #on_block.
-
#on_numblock(node)
Alias for #on_block.
- #on_send(node) (also: #on_csend)
- #binary_operator?(node) ⇒ Boolean private
- #camel_case_constant?(node) ⇒ Boolean private
- #class_hierarchy_operand?(node) ⇒ Boolean private
- #correct_inverse_block(corrector, node) private
- #correct_inverse_method(corrector, node) private
- #correct_inverse_selector(block, corrector) private
- #dot_range(loc) private
- #end_parentheses(node, method_call) private
- #inverse_blocks private
- #inverse_methods private
- #keep_parentheses?(node, method_call) ⇒ Boolean private
- #message(method, inverse) private
- #negated?(node) ⇒ Boolean private
- #not_to_receiver(node, method_call) private
-
#possible_class_hierarchy_check?(lhs, rhs, method) ⇒ Boolean
private
When comparing classes,
!(Integer < Numeric)is not the same asInteger > Numeric, since the comparison isnilfor unrelated classes. - #remove_end_parenthesis(corrector, node, method, method_call) private
- #remove_negation(corrector, node, method, method_call) private
- #safe_navigation_incompatible?(node) ⇒ Boolean private
::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_for_statement_removal | Returns the range to remove a statement: its whole lines, including a trailing comment and the final newline, when no other code shares them, and otherwise the range itself with the spaces after it. |
| #range_with_comments, #range_with_comments_and_lines, #range_with_surrounding_comma, #range_with_surrounding_space, #source_range | |
::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: |
| #file_independent_relevance | Whether |
| #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 The source is parsed the way the file under investigation was. |
| #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 |
| #use_corrector | |
::RuboCop::Cop::AutocorrectLogic - Included
::RuboCop::Cop::IgnoredNode - Included
Constructor Details
This class inherits a constructor from RuboCop::Cop::Base
Class Method Details
.autocorrect_incompatible_with
[ GitHub ]# File 'lib/rubocop/cop/style/inverse_methods.rb', line 56
def self.autocorrect_incompatible_with [Style::Not, Style::SymbolProc] end
Instance Method Details
#binary_operator?(node) ⇒ Boolean (private)
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 147
def binary_operator?(node) node.operator_method? && !node.loc.dot && !node.method?(:[]) && !node.method?(:[]=) end
#camel_case_constant?(node) ⇒ Boolean (private)
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 215
def camel_case_constant?(node) node.const_type? && CAMEL_CASE.match?(node.source) end
#class_hierarchy_operand?(node) ⇒ Boolean (private)
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 211
def class_hierarchy_operand?(node) camel_case_constant?(node) || class_hierarchy_value_method?(node) end
#class_hierarchy_value_method?(node)
[ GitHub ]# File 'lib/rubocop/cop/style/inverse_methods.rb', line 79
def_node_matcher :class_hierarchy_value_method?, <<~PATTERN (call _ {:class :superclass :singleton_class}) PATTERN
#correct_inverse_block(corrector, node) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/inverse_methods.rb', line 151
def correct_inverse_block(corrector, node) method_call, method, block = inverse_block?(node) corrector.replace(method_call.loc.selector, inverse_blocks[method].to_s) correct_inverse_selector(block, corrector) end
#correct_inverse_method(corrector, node) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/inverse_methods.rb', line 120
def correct_inverse_method(corrector, node) method_call, _lhs, method, _rhs = inverse_candidate?(node) return unless method_call && method remove_negation(corrector, node, method, method_call) corrector.replace(method_call.loc.selector, inverse_methods[method].to_s) end
#correct_inverse_selector(block, corrector) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/inverse_methods.rb', line 158
def correct_inverse_selector(block, corrector) selector_loc = block.loc.selector selector = selector_loc.source if NEGATED_EQUALITY_METHODS.include?(selector.to_sym) selector[0] = '=' corrector.replace(selector_loc, selector) else if block.loc.dot range = dot_range(block.loc) corrector.remove(range) end corrector.remove(selector_loc) end end
#dot_range(loc) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/inverse_methods.rb', line 219
def dot_range(loc) range_between(loc.dot.begin_pos, loc.expression.end_pos) end
#end_parentheses(node, method_call) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/inverse_methods.rb', line 192
def end_parentheses(node, method_call) method_call.source_range.end.join(node.source_range.end) end
#inverse_block?(node)
[ GitHub ]# File 'lib/rubocop/cop/style/inverse_methods.rb', line 70
def_node_matcher :inverse_block?, <<~PATTERN (any_block $(call (...) $_) ... { $(call ... :!) $(send (...) {:!= :!~} ...) (begin ... $(call ... :!)) (begin ... $(send (...) {:!= :!~} ...)) }) PATTERN
#inverse_blocks (private)
[ GitHub ]# File 'lib/rubocop/cop/style/inverse_methods.rb', line 180
def inverse_blocks @inverse_blocks ||= cop_config['InverseBlocks'].merge(cop_config['InverseBlocks'].invert) end
#inverse_candidate?(node)
[ GitHub ]# File 'lib/rubocop/cop/style/inverse_methods.rb', line 61
def_node_matcher :inverse_candidate?, <<~PATTERN { (send $(call $(...) $_ $...) :!) (send (any_block $(call $(...) $_) $...) :!) (send (begin $(call $(...) $_ $...)) :!) } PATTERN
#inverse_methods (private)
[ GitHub ]# File 'lib/rubocop/cop/style/inverse_methods.rb', line 175
def inverse_methods @inverse_methods ||= cop_config['InverseMethods'] .merge(cop_config['InverseMethods'].invert) end
#keep_parentheses?(node, method_call) ⇒ Boolean (private)
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 139
def keep_parentheses?(node, method_call) return false unless node.receiver.begin_type? || node.parenthesized? return false unless method_call.operator_method? return false unless (parent = node.parent)&.call_type? binary_operator?(parent) || parent.receiver.equal?(node) end
#message(method, inverse) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/inverse_methods.rb', line 229
def (method, inverse) format(MSG, method: method, inverse: inverse) end
#negated?(node) ⇒ Boolean (private)
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 184
def negated?(node) node.parent.respond_to?(:method?) && node.parent.method?(:!) end
#not_to_receiver(node, method_call) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/inverse_methods.rb', line 188
def not_to_receiver(node, method_call) node.loc.selector.begin.join(method_call.source_range.begin) end
#on_block(node) Also known as: #on_numblock, #on_itblock
[ GitHub ]# File 'lib/rubocop/cop/style/inverse_methods.rb', line 99
def on_block(node) inverse_block?(node) do |_method_call, method, block| return unless inverse_blocks.key?(method) return if negated?(node) && negated?(node.parent) return if node.each_node(:next).any? # Inverse method offenses inside of the block of an inverse method # offense, such as `y.reject { |key, _value| !(key =~ /c\d/) }`, # can cause autocorrection to apply improper corrections. ignore_node(block) add_offense(node, message: (method, inverse_blocks[method])) do |corrector| correct_inverse_block(corrector, node) end end end
#on_csend(node)
Alias for #on_send.
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 97
alias on_csend on_send
#on_itblock(node)
Alias for #on_block.
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 116
alias on_itblock on_block
#on_numblock(node)
Alias for #on_block.
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 115
alias on_numblock on_block
#on_send(node) Also known as: #on_csend
[ GitHub ]# File 'lib/rubocop/cop/style/inverse_methods.rb', line 83
def on_send(node) return unless node.unary_operation? inverse_candidate?(node) do |method_call, lhs, method, rhs| return unless inverse_methods.key?(method) return if negated?(node) || (method_call) return if part_of_ignored_node?(node) return if possible_class_hierarchy_check?(lhs, rhs, method) add_offense(node, message: (method, inverse_methods[method])) do |corrector| correct_inverse_method(corrector, node) end end end
#possible_class_hierarchy_check?(lhs, rhs, method) ⇒ Boolean (private)
When comparing classes, !(Integer < Numeric) is not the same as
Integer > Numeric, since the comparison is nil for unrelated classes.
The same goes for an operand like foo.class or foo.superclass.
# File 'lib/rubocop/cop/style/inverse_methods.rb', line 205
def possible_class_hierarchy_check?(lhs, rhs, method) CLASS_COMPARISON_METHODS.include?(method) && (class_hierarchy_operand?(lhs) || (rhs.size == 1 && class_hierarchy_operand?(rhs.first))) end
#remove_end_parenthesis(corrector, node, method, method_call) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/inverse_methods.rb', line 223
def remove_end_parenthesis(corrector, node, method, method_call) return unless EQUALITY_METHODS.include?(method) || method_call.parent.begin_type? corrector.remove(end_parentheses(node, method_call)) end
#remove_negation(corrector, node, method, method_call) (private)
[ GitHub ]# File 'lib/rubocop/cop/style/inverse_methods.rb', line 128
def remove_negation(corrector, node, method, method_call) if !keep_parentheses?(node, method_call) corrector.remove(not_to_receiver(node, method_call)) remove_end_parenthesis(corrector, node, method, method_call) elsif node.parenthesized? corrector.remove(node.loc.selector) else corrector.remove(node.loc.selector.join(node.receiver.source_range.begin)) end end