Class: RuboCop::Cop::Lint::Void
| 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/lint/void.rb |
Overview
Checks for operators, variables, literals, lambda, proc and nonmutating methods used in void context.
each blocks are allowed to prevent false positives.
For example, the expression inside the each block below.
It’s not void, especially when the receiver is an Enumerator:
enumerator = [1, 2, 3].filter
enumerator.each { |item| item >= 2 } #=> [2, 3]
|
Note
|
The last expression in an assignment method definition such as def foo=(arg)
is not flagged. Ruby discards it (the method returns its argument), but the method can
still be called directly and its return value relied upon, so flagging it would be a
false positive for this lint.
|
|
Note
|
A constant used in a void context is flagged but not autocorrected, since referencing a constant can trigger autoloading side effects (e.g. forcing a file to load before a monkey-patch), so removing it may change behavior. |
Constant Summary
-
BINARY_OPERATORS =
# File 'lib/rubocop/cop/lint/void.rb', line 75%i[* / % + - == === != < > <= >= <=>].freeze
-
CONST_MSG =
# File 'lib/rubocop/cop/lint/void.rb', line 69'Constant `%<var>s` used in void context.' -
EXPRESSION_MSG =
# File 'lib/rubocop/cop/lint/void.rb', line 72'`%<expression>s` used in void context.' -
LIT_MSG =
# File 'lib/rubocop/cop/lint/void.rb', line 70'Literal `%<lit>s` used in void context.' -
METHODS_REPLACEABLE_BY_EACH =
# File 'lib/rubocop/cop/lint/void.rb', line 86%i[collect map].freeze
-
NONMUTATING_METHODS =
# File 'lib/rubocop/cop/lint/void.rb', line 88(NONMUTATING_METHODS_WITH_BANG_VERSION + METHODS_REPLACEABLE_BY_EACH).freeze
-
NONMUTATING_METHODS_WITH_BANG_VERSION =
# File 'lib/rubocop/cop/lint/void.rb', line 79%i[capitalize chomp chop compact delete_prefix delete_suffix downcase encode flatten gsub lstrip merge next reject reverse rotate rstrip scrub select shuffle slice sort sort_by squeeze strip sub succ swapcase tr tr_s transform_values unicode_normalize uniq upcase].freeze
-
NONMUTATING_MSG =
# File 'lib/rubocop/cop/lint/void.rb', line 73'Method `#%<method>s` used in void context. Did you mean `#%<suggest>s`?' -
NON_VALUE_ARGUMENT_TYPES =
# File 'lib/rubocop/cop/lint/void.rb', line 78%i[splat block_pass forwarded_args forwarded_restarg].freeze
-
OPERATORS =
# File 'lib/rubocop/cop/lint/void.rb', line 77(BINARY_OPERATORS + UNARY_OPERATORS).freeze
-
OP_MSG =
# File 'lib/rubocop/cop/lint/void.rb', line 67'Operator `%<op>s` used in void context.' -
SELF_MSG =
# File 'lib/rubocop/cop/lint/void.rb', line 71'`self` used in void context.' -
UNARY_OPERATORS =
# File 'lib/rubocop/cop/lint/void.rb', line 76%i[+@ -@ ~ !].freeze
-
VAR_MSG =
# File 'lib/rubocop/cop/lint/void.rb', line 68'Variable `%<var>s` used in void context.'
::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
- #on_begin(node) (also: #on_kwbegin)
- #on_block(node) (also: #on_numblock, #on_itblock)
- #on_ensure(node)
-
#on_itblock(node)
Alias for #on_block.
-
#on_kwbegin(node)
Alias for #on_begin.
-
#on_numblock(node)
Alias for #on_block.
- #all_keys_entirely_literal?(node) ⇒ Boolean private
- #all_values_entirely_literal?(node) ⇒ Boolean private
- #autocorrect_nonmutating_send(corrector, node, suggestion) private
- #autocorrect_void_expression(corrector, node) private
- #autocorrect_void_op(corrector, node) private
- #check_begin(node) private
- #check_case_expression(case_node) private
- #check_case_match_expression(case_node) private
- #check_ensure(node) private
- #check_expression(expr) private
- #check_if_expression(if_node) private
- #check_literal(node) private
- #check_nonmutating(node) private
- #check_self(node) private
- #check_var(node) private
- #check_void_expression(node) private
- #check_void_expression_nodes(expr) private
-
#check_void_op(node, &block)
private
rubocop:disable-next Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity.
- #entirely_literal?(node) ⇒ Boolean private
- #in_void_context?(node) ⇒ Boolean private
- #operation?(node) ⇒ Boolean private
- #setter_method?(node) ⇒ Boolean private
- #trailing_comma?(node) ⇒ Boolean private
- #void_expression_range(node) 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_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: |
| #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 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
Instance Method Details
#all_keys_entirely_literal?(node) ⇒ Boolean (private)
# File 'lib/rubocop/cop/lint/void.rb', line 317
def all_keys_entirely_literal?(node) node.each_key.all? { |key| entirely_literal?(key) } end
#all_values_entirely_literal?(node) ⇒ Boolean (private)
# File 'lib/rubocop/cop/lint/void.rb', line 321
def all_values_entirely_literal?(node) node.each_value.all? { |value| entirely_literal?(value) } end
#autocorrect_nonmutating_send(corrector, node, suggestion) (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/void.rb', line 298
def autocorrect_nonmutating_send(corrector, node, suggestion) send_node = node.call_type? ? node : node.send_node corrector.replace(send_node.loc.selector, suggestion) end
#autocorrect_void_expression(corrector, node) (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/void.rb', line 280
def autocorrect_void_expression(corrector, node) # Referencing a constant can trigger autoloading side effects (e.g. forcing a file # to load before a monkey-patch), so removing it may change behavior. Flag but don't # autocorrect, leaving it to the user. return if node.const_type? && !node.special_keyword? return if node.parent.type?(:if, :case, :when, :case_match, :in_pattern) return if (def_node = node.each_ancestor(:any_def).first) && def_node.assignment_method? range = range_with_surrounding_space(range: void_expression_range(node), side: :left) corrector.remove(range) end
#autocorrect_void_op(corrector, node) (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/void.rb', line 267
def autocorrect_void_op(corrector, node) if node.arguments.empty? corrector.replace(node, node.receiver.source) else corrector.remove(node.loc.dot) if node.loc.dot corrector.replace( range_with_surrounding_space(range: node.loc.selector, side: :both, newlines: false), "\n" ) end end
#check_begin(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/void.rb', line 113
def check_begin(node) expressions = *node inside_each_block = node.each_ancestor(:any_block).first&.method?(:each) expressions.pop if !in_void_context?(node) || inside_each_block || setter_method?(node) expressions.each do |expr| check_void_op(expr) { inside_each_block } check_expression(expr) end end
#check_case_expression(case_node) (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/void.rb', line 145
def check_case_expression(case_node) case_node.each_when { |when_node| check_expression(when_node.body) if when_node.body } check_expression(case_node.else_branch) if case_node.else_branch end
#check_case_match_expression(case_node) (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/void.rb', line 150
def check_case_match_expression(case_node) case_node.each_in_pattern do |in_pattern_node| check_expression(in_pattern_node.body) if in_pattern_node.body end check_expression(case_node.else_branch) if case_node.else_branch end
#check_ensure(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/void.rb', line 248
def check_ensure(node) return unless (body = node.branch) # NOTE: the `begin` node case is already handled via `on_begin` return if body.begin_type? check_expression(body) end
#check_expression(expr) (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/void.rb', line 123
def check_expression(expr) return check_if_expression(expr) if expr.if_type? return check_case_expression(expr) if expr.case_type? return check_case_match_expression(expr) if expr.case_match_type? check_void_expression_nodes(expr) end
#check_if_expression(if_node) (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/void.rb', line 141
def check_if_expression(if_node) check_void_expression_nodes(if_node.body) if if_node.body end
#check_literal(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/void.rb', line 202
def check_literal(node) if !entirely_literal?(node) || node.xstr_type? || node.range_type? || node.nil_type? return end add_offense(node, message: format(LIT_MSG, lit: node.source)) do |corrector| next if node.each_descendant(:begin).any? autocorrect_void_expression(corrector, node) end end
#check_nonmutating(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/void.rb', line 230
def check_nonmutating(node) return unless node.type?(:call, :any_block) method_name = node.method_name return unless NONMUTATING_METHODS.include?(method_name) suggestion = if METHODS_REPLACEABLE_BY_EACH.include?(method_name) 'each' else "#{method_name}!" end add_offense(node, message: format(NONMUTATING_MSG, method: method_name, suggest: suggestion)) do |corrector| autocorrect_nonmutating_send(corrector, node, suggestion) end end
#check_self(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/void.rb', line 214
def check_self(node) return unless node.self_type? add_offense(node, message: SELF_MSG) do |corrector| autocorrect_void_expression(corrector, node) end end
#check_var(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/void.rb', line 184
def check_var(node) return unless node.variable? || node.const_type? if node.const_type? template = node.special_keyword? ? VAR_MSG : CONST_MSG offense_range = node = format(template, var: node.source) else offense_range = node.loc.name = format(VAR_MSG, var: node.loc.name.source) end add_offense(offense_range, message: ) do |corrector| autocorrect_void_expression(corrector, node) end end
#check_void_expression(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/void.rb', line 222
def check_void_expression(node) return unless node.defined_type? || node.lambda_or_proc? add_offense(node, message: format(EXPRESSION_MSG, expression: node.source)) do |corrector| autocorrect_void_expression(corrector, node) end end
#check_void_expression_nodes(expr) (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/void.rb', line 131
def check_void_expression_nodes(expr) check_literal(expr) check_var(expr) check_self(expr) check_void_expression(expr) return unless cop_config['CheckForMethodsWithNoSideEffects'] check_nonmutating(expr) end
#check_void_op(node, &block) (private)
rubocop:disable-next Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
# File 'lib/rubocop/cop/lint/void.rb', line 158
def check_void_op(node, &block) node = node.children.first while node&.begin_type? return unless node&.call_type? && OPERATORS.include?(node.method_name) return unless operation?(node) return if block && yield(node) add_offense(node.loc.selector, message: format(OP_MSG, op: node.method_name)) do |corrector| autocorrect_void_op(corrector, node) end end
#entirely_literal?(node) ⇒ Boolean (private)
# File 'lib/rubocop/cop/lint/void.rb', line 304
def entirely_literal?(node) case node.type when :array all_values_entirely_literal?(node) when :hash all_keys_entirely_literal?(node) && all_values_entirely_literal?(node) when :send, :csend node.method?(:freeze) && node.receiver && entirely_literal?(node.receiver) else node.literal? end end
#in_void_context?(node) ⇒ Boolean (private)
# File 'lib/rubocop/cop/lint/void.rb', line 256
def in_void_context?(node) parent = node.parent return false unless parent && parent.children.last == node parent.respond_to?(:void_context?) && parent.void_context? end
#on_begin(node) Also known as: #on_kwbegin
[ GitHub ]# File 'lib/rubocop/cop/lint/void.rb', line 102
def on_begin(node) check_begin(node) end
#on_block(node) Also known as: #on_numblock, #on_itblock
[ GitHub ]# File 'lib/rubocop/cop/lint/void.rb', line 91
def on_block(node) return unless node.body && !node.body.begin_type? return unless in_void_context?(node.body) return if node.method?(:each) check_void_op(node.body) check_expression(node.body) end
#on_ensure(node)
[ GitHub ]# File 'lib/rubocop/cop/lint/void.rb', line 107
def on_ensure(node) check_ensure(node) end
#on_itblock(node)
Alias for #on_block.
# File 'lib/rubocop/cop/lint/void.rb', line 100
alias on_itblock on_block
#on_kwbegin(node)
Alias for #on_begin.
# File 'lib/rubocop/cop/lint/void.rb', line 105
alias on_kwbegin on_begin
#on_numblock(node)
Alias for #on_block.
# File 'lib/rubocop/cop/lint/void.rb', line 99
alias on_numblock on_block
#operation?(node) ⇒ Boolean (private)
# File 'lib/rubocop/cop/lint/void.rb', line 171
def operation?(node) return UNARY_OPERATORS.include?(node.method_name) || !node.loc.dot if node.arguments.none? return false if !node.arguments.one? || trailing_comma?(node) argument = node.first_argument argument.hash_type? ? argument.braces? : !argument.type?(*NON_VALUE_ARGUMENT_TYPES) end
#setter_method?(node) ⇒ Boolean (private)
# File 'lib/rubocop/cop/lint/void.rb', line 263
def setter_method?(node) node.parent&.any_def_type? && node.parent.assignment_method? end
#trailing_comma?(node) ⇒ Boolean (private)
# File 'lib/rubocop/cop/lint/void.rb', line 180
def trailing_comma?(node) node.last_argument.source_range.end.join(node.source_range.end).source.include?(',') end
#void_expression_range(node) (private)
[ GitHub ]# File 'lib/rubocop/cop/lint/void.rb', line 292
def void_expression_range(node) return node.source_range unless node.respond_to?(:heredoc?) && node.heredoc? node.source_range.join(node.loc.heredoc_end) end