repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/safe_navigation_consistency.rb
lib/rubocop/cop/lint/safe_navigation_consistency.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Check to make sure that if safe navigation is used in an `&&` or `||` condition, # consistent and appropriate safe navigation, without excess or deficiency, # is used for all method calls on the same object. # # @example # # bad # foo&.bar && foo&.baz # # # good # foo&.bar && foo.baz # # # bad # foo.bar && foo&.baz # # # good # foo.bar && foo.baz # # # bad # foo&.bar || foo.baz # # # good # foo&.bar || foo&.baz # # # bad # foo.bar || foo&.baz # # # good # foo.bar || foo.baz # # # bad # foo&.bar && (foobar.baz || foo&.baz) # # # good # foo&.bar && (foobar.baz || foo.baz) # class SafeNavigationConsistency < Base include NilMethods extend AutoCorrector USE_DOT_MSG = 'Use `.` instead of unnecessary `&.`.' USE_SAFE_NAVIGATION_MSG = 'Use `&.` for consistency with safe navigation.' def on_and(node) all_operands = collect_operands(node, []) operand_groups = all_operands.group_by { |operand| receiver_name_as_key(operand, +'') } operand_groups.each_value do |grouped_operands| next unless (dot_op, begin_of_rest_operands = find_consistent_parts(grouped_operands)) rest_operands = grouped_operands[begin_of_rest_operands..] rest_operands.each do |operand| next if already_appropriate_call?(operand, dot_op) register_offense(operand, dot_op) end end end alias on_or on_and private def collect_operands(node, operand_nodes) operand_nodes(node.lhs, operand_nodes) operand_nodes(node.rhs, operand_nodes) operand_nodes end def receiver_name_as_key(method, fully_receivers) if method.parent.call_type? receiver(method.parent, fully_receivers) else fully_receivers << method.receiver&.source.to_s end end # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity def find_consistent_parts(grouped_operands) csend_in_and, csend_in_or, send_in_and, send_in_or = most_left_indices(grouped_operands) return if csend_in_and && csend_in_or && csend_in_and < csend_in_or if csend_in_and ['.', (send_in_and ? [send_in_and, csend_in_and].min : csend_in_and) + 1] elsif send_in_or && csend_in_or send_in_or < csend_in_or ? ['.', send_in_or + 1] : ['&.', csend_in_or + 1] elsif send_in_and && csend_in_or && send_in_and < csend_in_or ['.', csend_in_or] end end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity def already_appropriate_call?(operand, dot_op) return true if operand.safe_navigation? && dot_op == '&.' (operand.dot? || operand.operator_method?) && dot_op == '.' end def register_offense(operand, dot_operator) offense_range = operand.operator_method? ? operand : operand.loc.dot message = dot_operator == '.' ? USE_DOT_MSG : USE_SAFE_NAVIGATION_MSG add_offense(offense_range, message: message) do |corrector| next if operand.operator_method? corrector.replace(operand.loc.dot, dot_operator) end end def operand_nodes(operand, operand_nodes) if operand.operator_keyword? collect_operands(operand, operand_nodes) elsif operand.call_type? operand_nodes << operand end end # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity def most_left_indices(grouped_operands) indices = { csend_in_and: nil, csend_in_or: nil, send_in_and: nil, send_in_or: nil } grouped_operands.each_with_index do |operand, index| indices[:csend_in_and] ||= index if operand_in_and?(operand) && operand.csend_type? indices[:csend_in_or] ||= index if operand_in_or?(operand) && operand.csend_type? indices[:send_in_and] ||= index if operand_in_and?(operand) && !nilable?(operand) indices[:send_in_or] ||= index if operand_in_or?(operand) && !nilable?(operand) end indices.values end # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity def operand_in_and?(node) return true if node.parent.and_type? parent = node.parent.parent while node.parent.begin_type? parent&.and_type? end def operand_in_or?(node) return true if node.parent.or_type? parent = node.parent.parent while node.parent.begin_type? parent&.or_type? end def nilable?(node) node.csend_type? || nil_methods.include?(node.method_name) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/non_deterministic_require_order.rb
lib/rubocop/cop/lint/non_deterministic_require_order.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # `Dir[...]` and `Dir.glob(...)` do not make any guarantees about # the order in which files are returned. The final order is # determined by the operating system and file system. # This means that using them in cases where the order matters, # such as requiring files, can lead to intermittent failures # that are hard to debug. To ensure this doesn't happen, # always sort the list. # # `Dir.glob` and `Dir[]` sort globbed results by default in Ruby 3.0. # So all bad cases are acceptable when Ruby 3.0 or higher are used. # # NOTE: This cop will be deprecated and removed when supporting only Ruby 3.0 and higher. # # @safety # This cop is unsafe in the case where sorting files changes existing # expected behavior. # # @example # # # bad # Dir["./lib/**/*.rb"].each do |file| # require file # end # # # good # Dir["./lib/**/*.rb"].sort.each do |file| # require file # end # # # bad # Dir.glob(Rails.root.join(__dir__, 'test', '*.rb')) do |file| # require file # end # # # good # Dir.glob(Rails.root.join(__dir__, 'test', '*.rb')).sort.each do |file| # require file # end # # # bad # Dir['./lib/**/*.rb'].each(&method(:require)) # # # good # Dir['./lib/**/*.rb'].sort.each(&method(:require)) # # # bad # Dir.glob(Rails.root.join('test', '*.rb'), &method(:require)) # # # good # Dir.glob(Rails.root.join('test', '*.rb')).sort.each(&method(:require)) # # # good - Respect intent if `sort` keyword option is specified in Ruby 3.0 or higher. # Dir.glob(Rails.root.join(__dir__, 'test', '*.rb'), sort: false).each(&method(:require)) # class NonDeterministicRequireOrder < Base extend AutoCorrector extend TargetRubyVersion MSG = 'Sort files before requiring them.' maximum_target_ruby_version 2.7 def on_block(node) return unless node.body return unless unsorted_dir_loop?(node.send_node) loop_variable(node.arguments) do |var_name| return unless var_is_required?(node.body, var_name) add_offense(node.send_node) { |corrector| correct_block(corrector, node.send_node) } end end def on_numblock(node) return unless node.body return unless unsorted_dir_loop?(node.send_node) node.argument_list .filter { |argument| var_is_required?(node.body, argument.name) } .each do add_offense(node.send_node) { |corrector| correct_block(corrector, node.send_node) } end end def on_block_pass(node) return unless method_require?(node) return unless unsorted_dir_pass?(node.parent) parent_node = node.parent add_offense(parent_node) do |corrector| if parent_node.last_argument&.block_pass_type? correct_block_pass(corrector, parent_node) else correct_block(corrector, parent_node) end end end private def correct_block(corrector, node) if unsorted_dir_block?(node) corrector.replace(node, "#{node.source}.sort.each") else source = node.receiver.source corrector.replace(node, "#{source}.sort.each") end end def correct_block_pass(corrector, node) if unsorted_dir_glob_pass?(node) block_arg = node.last_argument corrector.remove(last_arg_range(node)) corrector.insert_after(node, ".sort.each(#{block_arg.source})") else corrector.replace(node.loc.selector, 'sort.each') end end # Returns range of last argument including comma and whitespace. # # @return [Parser::Source::Range] # def last_arg_range(node) node.last_argument.source_range.join(node.arguments[-2].source_range.end) end def unsorted_dir_loop?(node) unsorted_dir_block?(node) || unsorted_dir_each?(node) end def unsorted_dir_pass?(node) unsorted_dir_glob_pass?(node) || unsorted_dir_each_pass?(node) end # @!method unsorted_dir_block?(node) def_node_matcher :unsorted_dir_block?, <<~PATTERN (send (const {nil? cbase} :Dir) :glob ...) PATTERN # @!method unsorted_dir_each?(node) def_node_matcher :unsorted_dir_each?, <<~PATTERN (send (send (const {nil? cbase} :Dir) {:[] :glob} ...) :each) PATTERN # @!method method_require?(node) def_node_matcher :method_require?, <<~PATTERN (block-pass (send nil? :method (sym {:require :require_relative}))) PATTERN # @!method unsorted_dir_glob_pass?(node) def_node_matcher :unsorted_dir_glob_pass?, <<~PATTERN (send (const {nil? cbase} :Dir) :glob ... (block-pass (send nil? :method (sym {:require :require_relative})))) PATTERN # @!method unsorted_dir_each_pass?(node) def_node_matcher :unsorted_dir_each_pass?, <<~PATTERN (send (send (const {nil? cbase} :Dir) {:[] :glob} ...) :each (block-pass (send nil? :method (sym {:require :require_relative})))) PATTERN # @!method loop_variable(node) def_node_matcher :loop_variable, <<~PATTERN (args (arg $_)) PATTERN # @!method var_is_required?(node, name) def_node_search :var_is_required?, <<~PATTERN (send nil? {:require :require_relative} (lvar %1)) PATTERN end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/symbol_conversion.rb
lib/rubocop/cop/lint/symbol_conversion.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for uses of literal strings converted to # a symbol where a literal symbol could be used instead. # # There are two possible styles for this cop. # `strict` (default) will register an offense for any incorrect usage. # `consistent` additionally requires hashes to use the same style for # every symbol key (ie. if any symbol key needs to be quoted it requires # all keys to be quoted). # # @example # # bad # 'string'.to_sym # :symbol.to_sym # 'underscored_string'.to_sym # :'underscored_symbol' # 'hyphenated-string'.to_sym # "string_#{interpolation}".to_sym # # # good # :string # :symbol # :underscored_string # :underscored_symbol # :'hyphenated-string' # :"string_#{interpolation}" # # @example EnforcedStyle: strict (default) # # # bad # { # 'a': 1, # "b": 2, # 'c-d': 3 # } # # # good (don't quote keys that don't require quoting) # { # a: 1, # b: 2, # 'c-d': 3 # } # # @example EnforcedStyle: consistent # # # bad # { # a: 1, # 'b-c': 2 # } # # # good (quote all keys if any need quoting) # { # 'a': 1, # 'b-c': 2 # } # # # good (no quoting required) # { # a: 1, # b: 2 # } # class SymbolConversion < Base extend AutoCorrector include ConfigurableEnforcedStyle include SymbolHelp MSG = 'Unnecessary symbol conversion; use `%<correction>s` instead.' MSG_CONSISTENCY = 'Symbol hash key should be quoted for consistency; ' \ 'use `%<correction>s` instead.' RESTRICT_ON_SEND = %i[to_sym intern].freeze def on_send(node) return unless node.receiver if node.receiver.type?(:str, :sym) register_offense(node, correction: node.receiver.value.to_sym.inspect) elsif node.receiver.dstr_type? register_offense(node, correction: ":\"#{node.receiver.value.to_sym}\"") end end def on_sym(node) return if ignored_node?(node) || properly_quoted?(node.source, node.value.inspect) # `alias` arguments are symbols but since a symbol that requires # being quoted is not a valid method identifier, it can be ignored return if in_alias?(node) # The `%I[]` and `%i[]` macros are parsed as normal arrays of symbols # so they need to be ignored. return if in_percent_literal_array?(node) # Symbol hash keys have a different format and need to be handled separately return correct_hash_key(node) if hash_key?(node) register_offense(node, correction: node.value.inspect) end def on_hash(node) # For `EnforcedStyle: strict`, hash keys are evaluated in `on_sym` return unless style == :consistent keys = node.keys.select(&:sym_type?) if keys.any? { |key| requires_quotes?(key) } correct_inconsistent_hash_keys(keys) else # If there are no symbol keys requiring quoting, # treat the hash like `EnforcedStyle: strict`. keys.each { |key| correct_hash_key(key) } end end private def register_offense(node, correction:, message: format(MSG, correction: correction)) add_offense(node, message: message) { |corrector| corrector.replace(node, correction) } end def properly_quoted?(source, value) return true if style == :strict && (!source.match?(/['"]/) || value.end_with?('=')) source == value || # `Symbol#inspect` uses double quotes, but allow single-quoted # symbols to work as well. source.gsub('"', '\"').tr("'", '"') == value end def requires_quotes?(sym_node) sym_node.value.inspect.match?(/^:".*?"|=$/) end def in_alias?(node) node.parent&.alias_type? end def in_percent_literal_array?(node) node.parent&.array_type? && node.parent.percent_literal? end def correct_hash_key(node) # Although some operators can be converted to symbols normally # (ie. `:==`), these are not accepted as hash keys and will # raise a syntax error (eg. `{ ==: ... }`). Therefore, if the # symbol does not start with an alphanumeric or underscore, it # will be ignored. return unless node.value.to_s.match?(/\A[a-z0-9_]/i) correction = node.value.inspect correction = correction.delete_prefix(':') if node.parent.colon? return if properly_quoted?(node.source, correction) register_offense( node, correction: correction, message: format(MSG, correction: node.parent.colon? ? "#{correction}:" : correction) ) end def correct_inconsistent_hash_keys(keys) keys.each do |key| ignore_node(key) next if requires_quotes?(key) next if properly_quoted?(key.source, %("#{key.value}")) correction = %("#{key.value}") register_offense( key, correction: correction, message: format(MSG_CONSISTENCY, correction: "#{correction}:") ) end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/ambiguous_range.rb
lib/rubocop/cop/lint/ambiguous_range.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for ambiguous ranges. # # Ranges have quite low precedence, which leads to unexpected behavior when # using a range with other operators. This cop avoids that by making ranges # explicit by requiring parenthesis around complex range boundaries (anything # that is not a literal: numerics, strings, symbols, etc.). # # This cop can be configured with `RequireParenthesesForMethodChains` in order to # specify whether method chains (including `self.foo`) should be wrapped in parens # by this cop. # # NOTE: Regardless of this configuration, if a method receiver is a basic literal # value, it will be wrapped in order to prevent the ambiguity of `1..2.to_a`. # # @safety # The cop autocorrects by wrapping the entire boundary in parentheses, which # makes the outcome more explicit but is possible to not be the intention of the # programmer. For this reason, this cop's autocorrect is unsafe (it will not # change the behavior of the code, but will not necessarily match the # intent of the program). # # @example # # bad # x || 1..2 # x - 1..2 # (x || 1..2) # x || 1..y || 2 # 1..2.to_a # # # good, unambiguous # 1..2 # 'a'..'z' # :bar..:baz # MyClass::MIN..MyClass::MAX # @min..@max # a..b # -a..b # # # good, ambiguity removed # x || (1..2) # (x - 1)..2 # (x || 1)..2 # (x || 1)..(y || 2) # (1..2).to_a # # @example RequireParenthesesForMethodChains: false (default) # # good # a.foo..b.bar # (a.foo)..(b.bar) # # @example RequireParenthesesForMethodChains: true # # bad # a.foo..b.bar # # # good # (a.foo)..(b.bar) class AmbiguousRange < Base include RationalLiteral extend AutoCorrector MSG = 'Wrap complex range boundaries with parentheses to avoid ambiguity.' def on_irange(node) each_boundary(node) do |boundary| next if acceptable?(boundary) add_offense(boundary) do |corrector| corrector.wrap(boundary, '(', ')') end end end alias on_erange on_irange private def each_boundary(range) yield range.begin if range.begin yield range.end if range.end end # rubocop:disable Metrics/CyclomaticComplexity def acceptable?(node) node.begin_type? || node.literal? || rational_literal?(node) || node.variable? || node.const_type? || node.self_type? || (node.call_type? && acceptable_call?(node)) end # rubocop:enable Metrics/CyclomaticComplexity def acceptable_call?(node) return true if node.unary_operation? # Require parentheses when making a method call on a literal # to avoid the ambiguity of `1..2.to_a`. return false if node.receiver&.basic_literal? return false if node.operator_method? && !node.method?(:[]) require_parentheses_for_method_chain? || node.receiver.nil? end def require_parentheses_for_method_chain? !cop_config['RequireParenthesesForMethodChains'] end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/void.rb
lib/rubocop/cop/lint/void.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # 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`: # # [source,ruby] # ---- # enumerator = [1, 2, 3].filter # enumerator.each { |item| item >= 2 } #=> [2, 3] # ---- # # NOTE: Return values in assignment method definitions such as `def foo=(arg)` are # detected because they are in a void context. However, autocorrection does not remove # the return value, as that would change behavior. In such cases, whether to remove # the return value or rename the method to something more appropriate should be left to # the user. # # @example CheckForMethodsWithNoSideEffects: false (default) # # bad # def some_method # some_num * 10 # do_something # end # # def some_method(some_var) # some_var # do_something # end # # @example CheckForMethodsWithNoSideEffects: true # # bad # def some_method(some_array) # some_array.sort # do_something(some_array) # end # # # good # def some_method # do_something # some_num * 10 # end # # def some_method(some_var) # do_something # some_var # end # # def some_method(some_array) # some_array.sort! # do_something(some_array) # end class Void < Base extend AutoCorrector include RangeHelp OP_MSG = 'Operator `%<op>s` used in void context.' VAR_MSG = 'Variable `%<var>s` used in void context.' CONST_MSG = 'Constant `%<var>s` used in void context.' LIT_MSG = 'Literal `%<lit>s` used in void context.' SELF_MSG = '`self` used in void context.' EXPRESSION_MSG = '`%<expression>s` used in void context.' NONMUTATING_MSG = 'Method `#%<method>s` used in void context. Did you mean `#%<suggest>s`?' BINARY_OPERATORS = %i[* / % + - == === != < > <= >= <=>].freeze UNARY_OPERATORS = %i[+@ -@ ~ !].freeze OPERATORS = (BINARY_OPERATORS + UNARY_OPERATORS).freeze NONMUTATING_METHODS_WITH_BANG_VERSION = %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 METHODS_REPLACEABLE_BY_EACH = %i[collect map].freeze NONMUTATING_METHODS = (NONMUTATING_METHODS_WITH_BANG_VERSION + METHODS_REPLACEABLE_BY_EACH).freeze def on_block(node) return unless node.body && !node.body.begin_type? return unless in_void_context?(node.body) check_void_op(node.body) { node.method?(:each) } check_expression(node.body) end alias on_numblock on_block alias on_itblock on_block def on_begin(node) check_begin(node) end alias on_kwbegin on_begin def on_ensure(node) check_ensure(node) end private def check_begin(node) expressions = *node expressions.pop unless in_void_context?(node) expressions.each do |expr| check_void_op(expr) do block_node = node.each_ancestor(:any_block).first block_node&.method?(:each) end check_expression(expr) end end def check_expression(expr) expr = expr.body if expr.if_type? return unless expr check_literal(expr) check_var(expr) check_self(expr) check_void_expression(expr) return unless cop_config['CheckForMethodsWithNoSideEffects'] check_nonmutating(expr) end # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity def check_void_op(node, &block) node = node.children.first while node&.begin_type? return unless node&.call_type? && OPERATORS.include?(node.method_name) if !UNARY_OPERATORS.include?(node.method_name) && node.loc.dot && node.arguments.none? return end 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 # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity 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 message = format(template, var: node.source) else offense_range = node.loc.name message = format(VAR_MSG, var: node.loc.name.source) end add_offense(offense_range, message: message) do |corrector| autocorrect_void_expression(corrector, node) end end def check_literal(node) return if !entirely_literal?(node) || node.xstr_type? || node.range_type? add_offense(node, message: format(LIT_MSG, lit: node.source)) do |corrector| autocorrect_void_expression(corrector, node) end end def check_self(node) return unless node.self_type? add_offense(node, message: SELF_MSG) do |corrector| autocorrect_void_expression(corrector, node) end end 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 def check_nonmutating(node) return unless node.type?(:send, :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 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 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 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 def autocorrect_void_expression(corrector, node) return if node.parent.if_type? return if (def_node = node.each_ancestor(:any_def).first) && def_node.assignment_method? corrector.remove(range_with_surrounding_space(range: node.source_range, side: :left)) end def autocorrect_nonmutating_send(corrector, node, suggestion) send_node = if node.send_type? node else node.send_node end corrector.replace(send_node.loc.selector, suggestion) end 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 def all_keys_entirely_literal?(node) node.each_key.all? { |key| entirely_literal?(key) } end def all_values_entirely_literal?(node) node.each_value.all? { |value| entirely_literal?(value) } end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/empty_file.rb
lib/rubocop/cop/lint/empty_file.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Enforces that Ruby source files are not empty. # # @example # # bad # # Empty file # # # good # # File containing non commented source lines # # @example AllowComments: true (default) # # good # # File consisting only of comments # # @example AllowComments: false # # bad # # File consisting only of comments # class EmptyFile < Base MSG = 'Empty file detected.' def on_new_investigation add_global_offense(MSG) if offending? end private def offending? empty_file? || (!cop_config['AllowComments'] && contains_only_comments?) end def empty_file? processed_source.buffer.source.empty? end def contains_only_comments? processed_source.lines.all? { |line| line.blank? || comment_line?(line) } end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/useless_access_modifier.rb
lib/rubocop/cop/lint/useless_access_modifier.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for redundant access modifiers, including those with no # code, those which are repeated, those which are on top-level, and # leading `public` modifiers in a class or module body. # Conditionally-defined methods are considered as always being defined, # and thus access modifiers guarding such methods are not redundant. # # This cop has `ContextCreatingMethods` option. The default setting value # is an empty array that means no method is specified. # This setting is an array of methods which, when called, are known to # create its own context in the module's current access context. # # It also has `MethodCreatingMethods` option. The default setting value # is an empty array that means no method is specified. # This setting is an array of methods which, when called, are known to # create other methods in the module's current access context. # # @example # # bad # class Foo # public # this is redundant (default access is public) # # def method # end # end # # # bad # class Foo # # The following is redundant (methods defined on the class' # # singleton class are not affected by the private modifier) # private # # def self.method3 # end # end # # # bad # class Foo # protected # # define_method(:method2) do # end # # protected # this is redundant (repeated from previous modifier) # # [1,2,3].each do |i| # define_method("foo#{i}") do # end # end # end # # # bad # class Foo # private # this is redundant (no following methods are defined) # end # # # bad # private # this is useless (access modifiers have no effect on top-level) # # def method # end # # # good # class Foo # private # this is not redundant (a method is defined) # # def method2 # end # end # # # good # class Foo # # The following is not redundant (conditionally defined methods are # # considered as always defining a method) # private # # if condition? # def method # end # end # end # # # good # class Foo # protected # this is not redundant (a method is defined) # # define_method(:method2) do # end # end # # @example ContextCreatingMethods: concerning # # Lint/UselessAccessModifier: # # ContextCreatingMethods: # # - concerning # # # good # require 'active_support/concern' # class Foo # concerning :Bar do # def some_public_method # end # # private # # def some_private_method # end # end # # # this is not redundant because `concerning` created its own context # private # # def some_other_private_method # end # end # # @example MethodCreatingMethods: delegate # # Lint/UselessAccessModifier: # # MethodCreatingMethods: # # - delegate # # # good # require 'active_support/core_ext/module/delegation' # class Foo # # this is not redundant because `delegate` creates methods # private # # delegate :method_a, to: :method_b # end class UselessAccessModifier < Base include RangeHelp extend AutoCorrector MSG = 'Useless `%<current>s` access modifier.' def on_class(node) check_node(node.body) end alias on_module on_class alias on_sclass on_class def on_block(node) return unless eval_call?(node) || included_block?(node) check_node(node.body) end alias on_numblock on_block alias on_itblock on_block def on_begin(node) return if node.parent node.child_nodes.each do |child| next unless child.send_type? && access_modifier?(child) # This call always registers an offense for access modifier `child.method_name` check_send_node(child, child.method_name, true) end end private def autocorrect(corrector, node) range = range_by_whole_lines(node.source_range, include_final_newline: true) corrector.remove(range) end # @!method static_method_definition?(node) def_node_matcher :static_method_definition?, <<~PATTERN {def (send nil? {:attr :attr_reader :attr_writer :attr_accessor} ...)} PATTERN # @!method dynamic_method_definition?(node) def_node_matcher :dynamic_method_definition?, <<~PATTERN {(send nil? :define_method ...) (any_block (send nil? :define_method ...) ...)} PATTERN # @!method class_or_instance_eval?(node) def_node_matcher :class_or_instance_eval?, <<~PATTERN (any_block (send _ {:class_eval :instance_eval}) ...) PATTERN def check_node(node) return if node.nil? if node.begin_type? check_scope(node) elsif node.send_type? && node.bare_access_modifier? add_offense(node, message: format(MSG, current: node.method_name)) do |corrector| autocorrect(corrector, node) end end end def access_modifier?(node) node.bare_access_modifier? || node.method?(:private_class_method) end def check_scope(node) cur_vis, unused = check_child_nodes(node, nil, :public) return unless unused add_offense(unused, message: format(MSG, current: cur_vis)) do |corrector| autocorrect(corrector, unused) end end # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity def check_child_nodes(node, unused, cur_vis) node.child_nodes.each do |child| if child.send_type? && access_modifier?(child) cur_vis, unused = check_send_node(child, cur_vis, unused) elsif child.block_type? && included_block?(child) next elsif method_definition?(child) unused = nil elsif start_of_new_scope?(child) check_scope(child) elsif !child.defs_type? cur_vis, unused = check_child_nodes(child, unused, cur_vis) end end [cur_vis, unused] end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity def check_send_node(node, cur_vis, unused) if node.bare_access_modifier? check_new_visibility(node, unused, node.method_name, cur_vis) elsif node.method?(:private_class_method) && !node.arguments? add_offense(node, message: format(MSG, current: node.method_name)) do |corrector| autocorrect(corrector, node) end [cur_vis, unused] end end def check_new_visibility(node, unused, new_vis, cur_vis) # does this modifier just repeat the existing visibility? if new_vis == cur_vis add_offense(node, message: format(MSG, current: cur_vis)) do |corrector| autocorrect(corrector, node) end else # was the previous modifier never applied to any defs? if unused add_offense(unused, message: format(MSG, current: cur_vis)) do |corrector| autocorrect(corrector, unused) end end # once we have already warned about a certain modifier, don't # warn again even if it is never applied to any method defs unused = node end [new_vis, unused] end def included_block?(block_node) active_support_extensions_enabled? && block_node.method?(:included) end def method_definition?(child) static_method_definition?(child) || dynamic_method_definition?(child) || any_method_definition?(child) end def any_method_definition?(child) cop_config.fetch('MethodCreatingMethods', []).any? do |m| # Some users still have `"included"` in their `MethodCreatingMethods` configurations, # so to prevent Ruby method redefinition warnings let's just skip this value. next if m == 'included' matcher_name = :"#{m}_method?" unless respond_to?(matcher_name) self.class.def_node_matcher matcher_name, <<~PATTERN {def (send nil? :#{m} ...)} PATTERN end public_send(matcher_name, child) end end def start_of_new_scope?(child) child.type?(:module, :class, :sclass) || eval_call?(child) end def eval_call?(child) class_or_instance_eval?(child) || child.class_constructor? || any_context_creating_methods?(child) end def any_context_creating_methods?(child) # Some users still have `"included"` in their `ContextCreatingMethods` configurations, # so to prevent Ruby method redefinition warnings let's just skip this value. cop_config.fetch('ContextCreatingMethods', []).any? do |m| next if m == 'included' matcher_name = :"#{m}_block?" unless respond_to?(matcher_name) self.class.def_node_matcher matcher_name, <<~PATTERN (any_block (send {nil? const} {:#{m}} ...) ...) PATTERN end public_send(matcher_name, child) end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/ambiguous_regexp_literal.rb
lib/rubocop/cop/lint/ambiguous_regexp_literal.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for ambiguous regexp literals in the first argument of # a method invocation without parentheses. # # @example # # # bad # # # This is interpreted as a method invocation with a regexp literal, # # but it could possibly be `/` method invocations. # # (i.e. `do_something./(pattern)./(i)`) # do_something /pattern/i # # # good # # # With parentheses, there's no ambiguity. # do_something(/pattern/i) class AmbiguousRegexpLiteral < Base extend AutoCorrector MSG = 'Ambiguous regexp literal. Parenthesize the method arguments ' \ "if it's surely a regexp literal, or add a whitespace to the " \ 'right of the `/` if it should be a division.' def on_new_investigation processed_source.diagnostics.each do |diagnostic| if target_ruby_version >= 3.0 next unless diagnostic.reason == :ambiguous_regexp else next unless diagnostic.reason == :ambiguous_literal end offense_node = find_offense_node_by(diagnostic) add_offense(diagnostic.location, severity: diagnostic.level) do |corrector| add_parentheses(offense_node, corrector) end end end private def find_offense_node_by(diagnostic) node = processed_source.ast.each_node(:regexp).find do |regexp_node| regexp_node.source_range.begin_pos == diagnostic.location.begin_pos end find_offense_node(node.parent, node) end def find_offense_node(node, regexp_receiver) return node if first_argument_is_regexp?(node) || !node.parent if (node.parent.send_type? && node.receiver) || method_chain_to_regexp_receiver?(node, regexp_receiver) node = find_offense_node(node.parent, regexp_receiver) end node end def first_argument_is_regexp?(node) node.send_type? && node.first_argument&.regexp_type? end def method_chain_to_regexp_receiver?(node, regexp_receiver) return false unless (parent = node.parent) return false unless (parent_receiver = parent.receiver) parent.parent && parent_receiver.receiver == regexp_receiver end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/next_without_accumulator.rb
lib/rubocop/cop/lint/next_without_accumulator.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Don't omit the accumulator when calling `next` in a `reduce` block. # # @example # # # bad # result = (1..4).reduce(0) do |acc, i| # next if i.odd? # acc + i # end # # # good # result = (1..4).reduce(0) do |acc, i| # next acc if i.odd? # acc + i # end class NextWithoutAccumulator < Base MSG = 'Use `next` with an accumulator argument in a `reduce`.' def on_block(node) on_block_body_of_reduce(node) do |body| void_next = body.each_node(:next).find do |n| n.children.empty? && parent_block_node(n) == node end add_offense(void_next) if void_next end end alias on_numblock on_block private # @!method on_block_body_of_reduce(node) def_node_matcher :on_block_body_of_reduce, <<~PATTERN { (block (call _recv {:reduce :inject} !sym) _blockargs $(begin ...)) (numblock (call _recv {:reduce :inject} !sym) _argscount $(begin ...)) } PATTERN def parent_block_node(node) node.each_ancestor(:any_block).first end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/implicit_string_concatenation.rb
lib/rubocop/cop/lint/implicit_string_concatenation.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for implicit string concatenation of string literals # which are on the same line. # # @example # # # bad # array = ['Item 1' 'Item 2'] # # # good # array = ['Item 1Item 2'] # array = ['Item 1' + 'Item 2'] # array = [ # 'Item 1' \ # 'Item 2' # ] class ImplicitStringConcatenation < Base extend AutoCorrector MSG = 'Combine %<lhs>s and %<rhs>s into a single string ' \ 'literal, rather than using implicit string concatenation.' FOR_ARRAY = ' Or, if they were intended to be separate array ' \ 'elements, separate them with a comma.' FOR_METHOD = ' Or, if they were intended to be separate method ' \ 'arguments, separate them with a comma.' # rubocop:disable Metrics/AbcSize, Metrics/MethodLength, Metrics/PerceivedComplexity def on_dstr(node) each_bad_cons(node) do |lhs_node, rhs_node| range = lhs_node.source_range.join(rhs_node.source_range) message = format(MSG, lhs: display_str(lhs_node), rhs: display_str(rhs_node)) if node.parent&.array_type? message << FOR_ARRAY elsif node.parent&.send_type? message << FOR_METHOD end add_offense(range, message: message) do |corrector| if lhs_node.value == '' corrector.remove(lhs_node) elsif rhs_node.value == '' corrector.remove(rhs_node) else range = lhs_node.source_range.end.join(rhs_node.source_range.begin) corrector.replace(range, ' + ') end end end end # rubocop:enable Metrics/AbcSize, Metrics/MethodLength, Metrics/PerceivedComplexity private def each_bad_cons(node) node.children.each_cons(2) do |child_node1, child_node2| # `'abc' 'def'` -> (dstr (str "abc") (str "def")) next unless string_literals?(child_node1, child_node2) next unless child_node1.last_line == child_node2.first_line # Make sure we don't flag a string literal which simply has # embedded newlines # `"abc\ndef"` also -> (dstr (str "abc") (str "def")) next unless child_node1.source[-1] == ending_delimiter(child_node1) yield child_node1, child_node2 end end def ending_delimiter(str) # implicit string concatenation does not work with %{}, etc. case str.source[0] when "'" "'" when '"' '"' end end def string_literal?(node) node.type?(:str, :dstr) end def string_literals?(node1, node2) string_literal?(node1) && string_literal?(node2) end def display_str(node) if node.source.include?("\n") str_content(node).inspect else node.source end end def str_content(node) return unless node.respond_to?(:str_type?) if node.str_type? node.children[0] else node.children.map { |c| str_content(c) }.join end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/regexp_as_condition.rb
lib/rubocop/cop/lint/regexp_as_condition.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for regexp literals used as `match-current-line`. # If a regexp literal is in condition, the regexp matches `$_` implicitly. # # @example # # bad # if /foo/ # do_something # end # # # good # if /foo/ =~ $_ # do_something # end class RegexpAsCondition < Base extend AutoCorrector MSG = 'Do not use regexp literal as a condition. ' \ 'The regexp literal matches `$_` implicitly.' def on_match_current_line(node) return if node.ancestors.none?(&:conditional?) return if part_of_ignored_node?(node) add_offense(node) { |corrector| corrector.replace(node, "#{node.source} =~ $_") } ignore_node(node) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/else_layout.rb
lib/rubocop/cop/lint/else_layout.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for odd `else` block layout - like # having an expression on the same line as the `else` keyword, # which is usually a mistake. # # Its autocorrection tweaks layout to keep the syntax. So, this autocorrection # is compatible correction for bad case syntax, but if your code makes a mistake # with `elsif` and `else`, you will have to correct it manually. # # @example # # # bad # # if something # # ... # else do_this # do_that # end # # # good # # # This code is compatible with the bad case. It will be autocorrected like this. # if something # # ... # else # do_this # do_that # end # # # This code is incompatible with the bad case. # # If `do_this` is a condition, `elsif` should be used instead of `else`. # if something # # ... # elsif do_this # do_that # end # # # bad # # # For single-line conditionals using `then` the layout is disallowed # # when the `else` body is multiline because it is treated as a lint offense. # if something then on_the_same_line_as_then # else first_line # second_line # end # # # good # # # For single-line conditional using `then` the layout is allowed # # when `else` body is a single-line because it is treated as intentional. # # if something then on_the_same_line_as_then # else single_line # end class ElseLayout < Base include Alignment include RangeHelp extend AutoCorrector MSG = 'Odd `else` layout detected. Did you mean to use `elsif`?' def on_if(node) return if node.ternary? return if node.then? && !node.else_branch&.begin_type? # If the if is on a single line, it'll be handled by `Style/OneLineConditional` return if node.single_line? check(node) end private def check(node) return unless node.else_branch if node.else? && node.loc.else.is?('else') check_else(node) elsif node.if? check(node.else_branch) end end def check_else(node) else_branch = node.else_branch first_else = else_branch.begin_type? ? else_branch.children.first : else_branch return unless first_else return unless same_line?(first_else, node.loc.else) add_offense(first_else) { |corrector| autocorrect(corrector, node, first_else) } end def autocorrect(corrector, node, first_else) corrector.insert_after(node.loc.else, "\n") blank_range = range_between(node.loc.else.end_pos, first_else.source_range.begin_pos) corrector.replace(blank_range, indentation(node)) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/disjunctive_assignment_in_constructor.rb
lib/rubocop/cop/lint/disjunctive_assignment_in_constructor.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks constructors for disjunctive assignments (`||=`) that should # be plain assignments. # # So far, this cop is only concerned with disjunctive assignment of # instance variables. # # In ruby, an instance variable is nil until a value is assigned, so the # disjunction is unnecessary. A plain assignment has the same effect. # # @safety # This cop is unsafe because it can register a false positive when a # method is redefined in a subclass that calls super. For example: # # [source,ruby] # ---- # class Base # def initialize # @config ||= 'base' # end # end # # class Derived < Base # def initialize # @config = 'derived' # super # end # end # ---- # # Without the disjunctive assignment, `Derived` will be unable to override # the value for `@config`. # # @example # # bad # def initialize # @x ||= 1 # end # # # good # def initialize # @x = 1 # end class DisjunctiveAssignmentInConstructor < Base extend AutoCorrector MSG = 'Unnecessary disjunctive assignment. Use plain assignment.' def on_def(node) check(node) end private # @param [DefNode] node a constructor definition def check(node) return unless node.method?(:initialize) check_body(node.body) end def check_body(body) return if body.nil? case body.type when :begin check_body_lines(body.child_nodes) else check_body_lines([body]) end end # @param [Array] lines the logical lines of the constructor def check_body_lines(lines) lines.each do |line| case line.type when :or_asgn check_disjunctive_assignment(line) else # Once we encounter something other than a disjunctive # assignment, we cease our investigation, because we can't be # certain that any future disjunctive assignments are offensive. # You're off the case, detective! break end end end # Add an offense if the LHS of the given disjunctive assignment is # an instance variable. # # For now, we only care about assignments to instance variables. # # @param [Node] node a disjunctive assignment def check_disjunctive_assignment(node) lhs = node.child_nodes.first return unless lhs.ivasgn_type? add_offense(node.loc.operator) do |corrector| corrector.replace(node.loc.operator, '=') end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/redundant_string_coercion.rb
lib/rubocop/cop/lint/redundant_string_coercion.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for string conversion in string interpolation, `print`, `puts`, and `warn` arguments, # which is redundant. # # @example # # # bad # "result is #{something.to_s}" # print something.to_s # puts something.to_s # warn something.to_s # # # good # "result is #{something}" # print something # puts something # warn something # class RedundantStringCoercion < Base include Interpolation extend AutoCorrector MSG_DEFAULT = 'Redundant use of `Object#to_s` in %<context>s.' MSG_SELF = 'Use `self` instead of `Object#to_s` in %<context>s.' RESTRICT_ON_SEND = %i[print puts warn].freeze # @!method to_s_without_args?(node) def_node_matcher :to_s_without_args?, '(call _ :to_s)' def on_interpolation(begin_node) final_node = begin_node.children.last return unless to_s_without_args?(final_node) register_offense(final_node, 'interpolation') end def on_send(node) return if node.receiver node.each_child_node(:call) do |child| next if !child.method?(:to_s) || child.arguments.any? register_offense(child, "`#{node.method_name}`") end end private def register_offense(node, context) receiver = node.receiver template = receiver ? MSG_DEFAULT : MSG_SELF message = format(template, context: context) add_offense(node.loc.selector, message: message) do |corrector| replacement = receiver ? receiver.source : 'self' corrector.replace(node, replacement) end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/trailing_comma_in_attribute_declaration.rb
lib/rubocop/cop/lint/trailing_comma_in_attribute_declaration.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for trailing commas in attribute declarations, such as # `#attr_reader`. Leaving a trailing comma will nullify the next method # definition by overriding it with a getter method. # # @example # # # bad # class Foo # attr_reader :foo, # # def bar # puts "Unreachable." # end # end # # # good # class Foo # attr_reader :foo # # def bar # puts "No problem!" # end # end # class TrailingCommaInAttributeDeclaration < Base extend AutoCorrector include RangeHelp MSG = 'Avoid leaving a trailing comma in attribute declarations.' def on_send(node) return unless node.attribute_accessor? && node.last_argument.def_type? trailing_comma = trailing_comma_range(node) add_offense(trailing_comma) { |corrector| corrector.remove(trailing_comma) } end private def trailing_comma_range(node) range_with_surrounding_space( node.arguments[-2].source_range, side: :right ).end.resize(1) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/unreachable_loop.rb
lib/rubocop/cop/lint/unreachable_loop.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for loops that will have at most one iteration. # # A loop that can never reach the second iteration is a possible error in the code. # In rare cases where only one iteration (or at most one iteration) is intended behavior, # the code should be refactored to use `if` conditionals. # # NOTE: Block methods that are used with ``Enumerable``s are considered to be loops. # # `AllowedPatterns` can be used to match against the block receiver in order to allow # code that would otherwise be registered as an offense (eg. `times` used not in an # `Enumerable` context). # # @example # # bad # while node # do_something(node) # node = node.parent # break # end # # # good # while node # do_something(node) # node = node.parent # end # # # bad # def verify_list(head) # item = head # begin # if verify(item) # return true # else # return false # end # end while(item) # end # # # good # def verify_list(head) # item = head # begin # if verify(item) # item = item.next # else # return false # end # end while(item) # # true # end # # # bad # def find_something(items) # items.each do |item| # if something?(item) # return item # else # raise NotFoundError # end # end # end # # # good # def find_something(items) # items.each do |item| # if something?(item) # return item # end # end # raise NotFoundError # end # # # bad # 2.times { raise ArgumentError } # # @example AllowedPatterns: ['(exactly|at_least|at_most)\(\d+\)\.times'] (default) # # # good # exactly(2).times { raise StandardError } class UnreachableLoop < Base include AllowedPattern MSG = 'This loop will have at most one iteration.' CONTINUE_KEYWORDS = %i[next redo].freeze def on_while(node) check(node) end alias on_until on_while alias on_while_post on_while alias on_until_post on_while alias on_for on_while def on_block(node) check(node) if loop_method?(node) end alias on_numblock on_block alias on_itblock on_block private def loop_method?(node) return false unless node.any_block_type? send_node = node.send_node loopable = send_node.enumerable_method? || send_node.enumerator_method? || send_node.method?(:loop) loopable && !matches_allowed_pattern?(send_node.source) end def check(node) statements = statements(node) break_statement = statements.find { |statement| break_statement?(statement) } return unless break_statement unless preceded_by_continue_statement?(break_statement) || conditional_continue_keyword?(break_statement) add_offense(node) end end def statements(node) body = node.body if body.nil? [] elsif body.begin_type? body.children else [body] end end # @!method break_command?(node) def_node_matcher :break_command?, <<~PATTERN { return break (send {nil? (const {nil? cbase} :Kernel)} {:raise :fail :throw :exit :exit! :abort} ...) } PATTERN def break_statement?(node) return true if break_command?(node) case node.type when :begin, :kwbegin statements = *node break_statement = statements.find { |statement| break_statement?(statement) } break_statement && !preceded_by_continue_statement?(break_statement) when :if check_if(node) when :case, :case_match check_case(node) else false end end def check_if(node) if_branch = node.if_branch else_branch = node.else_branch if_branch && else_branch && break_statement?(if_branch) && break_statement?(else_branch) end def check_case(node) else_branch = node.else_branch return false unless else_branch return false unless break_statement?(else_branch) branches = if node.case_type? node.when_branches else node.in_pattern_branches end branches.all? { |branch| branch.body && break_statement?(branch.body) } end def preceded_by_continue_statement?(break_statement) break_statement.left_siblings.any? do |sibling| # Numblocks have the arguments count as a number or, # itblocks have `:it` symbol in the AST. next if sibling.is_a?(Integer) || sibling.is_a?(Symbol) next if sibling.loop_keyword? || loop_method?(sibling) sibling.each_descendant(*CONTINUE_KEYWORDS).any? end end def conditional_continue_keyword?(break_statement) or_node = break_statement.each_descendant(:or).to_a.last or_node && CONTINUE_KEYWORDS.include?(or_node.rhs.type) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/inherit_exception.rb
lib/rubocop/cop/lint/inherit_exception.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Looks for error classes inheriting from `Exception`. # It is configurable to suggest using either `StandardError` (default) or # `RuntimeError` instead. # # @safety # This cop's autocorrection is unsafe because `rescue` that omit # exception class handle `StandardError` and its subclasses, # but not `Exception` and its subclasses. # # @example EnforcedStyle: standard_error (default) # # bad # # class C < Exception; end # # C = Class.new(Exception) # # # good # # class C < StandardError; end # # C = Class.new(StandardError) # # @example EnforcedStyle: runtime_error # # bad # # class C < Exception; end # # C = Class.new(Exception) # # # good # # class C < RuntimeError; end # # C = Class.new(RuntimeError) class InheritException < Base include ConfigurableEnforcedStyle extend AutoCorrector MSG = 'Inherit from `%<prefer>s` instead of `Exception`.' PREFERRED_BASE_CLASS = { runtime_error: 'RuntimeError', standard_error: 'StandardError' }.freeze RESTRICT_ON_SEND = %i[new].freeze # @!method class_new_call?(node) def_node_matcher :class_new_call?, <<~PATTERN (send (const {cbase nil?} :Class) :new $(const {cbase nil?} _)) PATTERN def on_class(node) return unless node.parent_class && exception_class?(node.parent_class) return if inherit_exception_class_with_omitted_namespace?(node) message = message(node.parent_class) add_offense(node.parent_class, message: message) do |corrector| corrector.replace(node.parent_class, preferred_base_class) end end def on_send(node) constant = class_new_call?(node) return unless constant && exception_class?(constant) message = message(constant) add_offense(constant, message: message) do |corrector| corrector.replace(constant, preferred_base_class) end end private def message(node) format(MSG, prefer: preferred_base_class, current: node.const_name) end def exception_class?(class_node) class_node.const_name == 'Exception' end def inherit_exception_class_with_omitted_namespace?(class_node) return false if class_node.parent_class.namespace&.cbase_type? class_node.left_siblings.any? do |sibling| sibling.respond_to?(:identifier) && exception_class?(sibling.identifier) end end def preferred_base_class PREFERRED_BASE_CLASS[style] end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/non_local_exit_from_iterator.rb
lib/rubocop/cop/lint/non_local_exit_from_iterator.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for non-local exits from iterators without a return # value. It registers an offense under these conditions: # # * No value is returned, # * the block is preceded by a method chain, # * the block has arguments, # * the method which receives the block is not `define_method` # or `define_singleton_method`, # * the return is not contained in an inner scope, e.g. a lambda or a # method definition. # # @example # # class ItemApi # rescue_from ValidationError do |e| # non-iteration block with arg # return { message: 'validation error' } unless e.errors # allowed # error_array = e.errors.map do |error| # block with method chain # return if error.suppress? # warned # return "#{error.param}: invalid" unless error.message # allowed # "#{error.param}: #{error.message}" # end # { message: 'validation error', errors: error_array } # end # # def update_items # transaction do # block without arguments # return unless update_necessary? # allowed # find_each do |item| # block without method chain # return if item.stock == 0 # false-negative... # item.update!(foobar: true) # end # end # end # end # class NonLocalExitFromIterator < Base MSG = 'Non-local exit from iterator, without return value. ' \ '`next`, `break`, `Array#find`, `Array#any?`, etc. ' \ 'is preferred.' def on_return(return_node) return if return_value?(return_node) return_node.each_ancestor(:any_block, :any_def) do |node| break if scoped_node?(node) # if a proc is passed to `Module#define_method` or # `Object#define_singleton_method`, `return` will not cause a # non-local exit error break if define_method?(node.send_node) next if node.argument_list.empty? if chained_send?(node.send_node) add_offense(return_node.loc.keyword) break end end end private def scoped_node?(node) node.any_def_type? || node.lambda? end def return_value?(return_node) !return_node.children.empty? end # @!method chained_send?(node) def_node_matcher :chained_send?, '(send !nil? ...)' # @!method define_method?(node) def_node_matcher :define_method?, <<~PATTERN (send _ {:define_method :define_singleton_method} _) PATTERN end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/uri_escape_unescape.rb
lib/rubocop/cop/lint/uri_escape_unescape.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Identifies places where `URI.escape` can be replaced by # `CGI.escape`, `URI.encode_www_form`, or `URI.encode_www_form_component` # depending on your specific use case. # Also this cop identifies places where `URI.unescape` can be replaced by # `CGI.unescape`, `URI.decode_www_form`, # or `URI.decode_www_form_component` depending on your specific use case. # # @example # # bad # URI.escape('http://example.com') # URI.encode('http://example.com') # # # good # CGI.escape('http://example.com') # URI.encode_uri_component(uri) # Since Ruby 3.1 # URI.encode_www_form([['example', 'param'], ['lang', 'en']]) # URI.encode_www_form(page: 10, locale: 'en') # URI.encode_www_form_component('http://example.com') # # # bad # URI.unescape(enc_uri) # URI.decode(enc_uri) # # # good # CGI.unescape(enc_uri) # URI.decode_uri_component(uri) # Since Ruby 3.1 # URI.decode_www_form(enc_uri) # URI.decode_www_form_component(enc_uri) class UriEscapeUnescape < Base ALTERNATE_METHODS_OF_URI_ESCAPE = %w[ CGI.escape URI.encode_www_form URI.encode_www_form_component ].freeze ALTERNATE_METHODS_OF_URI_UNESCAPE = %w[ CGI.unescape URI.decode_www_form URI.decode_www_form_component ].freeze MSG = '`%<uri_method>s` method is obsolete and should not be used. ' \ 'Instead, use %<replacements>s depending on your specific use ' \ 'case.' METHOD_NAMES = %i[escape encode unescape decode].freeze RESTRICT_ON_SEND = METHOD_NAMES # @!method uri_escape_unescape?(node) def_node_matcher :uri_escape_unescape?, <<~PATTERN (send (const ${nil? cbase} :URI) ${:#{METHOD_NAMES.join(' :')}} ...) PATTERN def on_send(node) uri_escape_unescape?(node) do |top_level, obsolete_method| replacements = if %i[escape encode].include?(obsolete_method) ALTERNATE_METHODS_OF_URI_ESCAPE else ALTERNATE_METHODS_OF_URI_UNESCAPE end double_colon = top_level ? '::' : '' message = format( MSG, uri_method: "#{double_colon}URI.#{obsolete_method}", replacements: "`#{replacements[0]}`, `#{replacements[1]}` " \ "or `#{replacements[2]}`" ) add_offense(node, message: message) end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/duplicate_case_condition.rb
lib/rubocop/cop/lint/duplicate_case_condition.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks that there are no repeated conditions # used in case 'when' expressions. # # @example # # # bad # case x # when 'first' # do_something # when 'first' # do_something_else # end # # # good # case x # when 'first' # do_something # when 'second' # do_something_else # end class DuplicateCaseCondition < Base MSG = 'Duplicate `when` condition detected.' def on_case(case_node) case_node.when_branches.each_with_object(Set.new) do |when_node, previous| when_node.conditions.each do |condition| add_offense(condition) unless previous.add?(condition) end end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/unified_integer.rb
lib/rubocop/cop/lint/unified_integer.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for using Fixnum or Bignum constant. # # @example # # # bad # 1.is_a?(Fixnum) # 1.is_a?(Bignum) # # # good # 1.is_a?(Integer) class UnifiedInteger < Base extend AutoCorrector MSG = 'Use `Integer` instead of `%<klass>s`.' # @!method fixnum_or_bignum_const(node) def_node_matcher :fixnum_or_bignum_const, <<~PATTERN (:const {nil? (:cbase)} ${:Fixnum :Bignum}) PATTERN def on_const(node) klass = fixnum_or_bignum_const(node) return unless klass add_offense(node, message: format(MSG, klass: klass)) do |corrector| next if target_ruby_version <= 2.3 corrector.replace(node.loc.name, 'Integer') end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/duplicate_hash_key.rb
lib/rubocop/cop/lint/duplicate_hash_key.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for duplicated keys in hash literals. # This cop considers both primitive types and constants for the hash keys. # # This cop mirrors a warning in Ruby 2.2. # # @example # # # bad # hash = { food: 'apple', food: 'orange' } # # # good # hash = { food: 'apple', other_food: 'orange' } class DuplicateHashKey < Base include Duplication MSG = 'Duplicated key in hash literal.' def on_hash(node) keys = node.keys.select { |key| key.recursive_basic_literal? || key.const_type? } return unless duplicates?(keys) consecutive_duplicates(keys).each { |key| add_offense(key) } end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/deprecated_open_ssl_constant.rb
lib/rubocop/cop/lint/deprecated_open_ssl_constant.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Algorithmic constants for `OpenSSL::Cipher` and `OpenSSL::Digest` # deprecated since OpenSSL version 2.2.0. Prefer passing a string # instead. # # @example # # # bad # OpenSSL::Cipher::AES.new(128, :GCM) # # # good # OpenSSL::Cipher.new('aes-128-gcm') # # # bad # OpenSSL::Digest::SHA256.new # # # good # OpenSSL::Digest.new('SHA256') # # # bad # OpenSSL::Digest::SHA256.digest('foo') # # # good # OpenSSL::Digest.digest('SHA256', 'foo') # class DeprecatedOpenSSLConstant < Base include RangeHelp extend AutoCorrector MSG = 'Use `%<constant>s.%<method>s(%<replacement_args>s)` instead of `%<original>s`.' RESTRICT_ON_SEND = %i[new digest].freeze NO_ARG_ALGORITHM = %w[BF DES IDEA RC4].freeze # @!method algorithm_const(node) def_node_matcher :algorithm_const, <<~PATTERN (send $(const (const (const {nil? cbase} :OpenSSL) {:Cipher :Digest}) _) ...) PATTERN # @!method digest_const?(node) def_node_matcher :digest_const?, <<~PATTERN (const _ :Digest) PATTERN def on_send(node) return if node.arguments.any? { |arg| arg.variable? || arg.call_type? || arg.const_type? } return if digest_const?(node.receiver) return unless algorithm_const(node) message = message(node) add_offense(node, message: message) { |corrector| autocorrect(corrector, node) } end private def autocorrect(corrector, node) algorithm_constant, = algorithm_const(node) corrector.remove(algorithm_constant.loc.double_colon) corrector.remove(algorithm_constant.loc.name) corrector.replace( correction_range(node), "#{node.loc.selector.source}(#{replacement_args(node)})" ) end def message(node) algorithm_constant, = algorithm_const(node) parent_constant = openssl_class(algorithm_constant) replacement_args = replacement_args(node) method = node.loc.selector.source format( MSG, constant: parent_constant, method: method, replacement_args: replacement_args, original: node.source ) end def correction_range(node) range_between(node.loc.dot.end_pos, node.source_range.end_pos) end def openssl_class(node) node.children.first.source end def algorithm_name(node) name = node.loc.name.source if openssl_class(node) == 'OpenSSL::Cipher' && !NO_ARG_ALGORITHM.include?(name) name.scan(/.{3}/).join('-') else name end end def sanitize_arguments(arguments) arguments.flat_map do |arg| argument = arg.str_type? ? arg.value : arg.source argument.tr(":'", '').split('-') end end def replacement_args(node) algorithm_constant, = algorithm_const(node) if algorithm_constant.source == 'OpenSSL::Cipher::Cipher' return node.first_argument.source end algorithm_name = algorithm_name(algorithm_constant) if openssl_class(algorithm_constant) == 'OpenSSL::Cipher' build_cipher_arguments(node, algorithm_name, node.arguments.empty?) else (["'#{algorithm_name}'"] + node.arguments.map(&:source)).join(', ') end end def build_cipher_arguments(node, algorithm_name, no_arguments) algorithm_parts = algorithm_name.downcase.split('-') size_and_mode = sanitize_arguments(node.arguments).map(&:downcase) if NO_ARG_ALGORITHM.include?(algorithm_parts.first.upcase) && no_arguments "'#{algorithm_parts.first}'" else mode = 'cbc' if size_and_mode.empty? "'#{(algorithm_parts + size_and_mode + [mode]).compact.take(3).join('-')}'" end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/shadowed_exception.rb
lib/rubocop/cop/lint/shadowed_exception.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for a rescued exception that get shadowed by a # less specific exception being rescued before a more specific # exception is rescued. # # An exception is considered shadowed if it is rescued after its # ancestor is, or if it and its ancestor are both rescued in the # same `rescue` statement. In both cases, the more specific rescue is # unnecessary because it is covered by rescuing the less specific # exception. (ie. `rescue Exception, StandardError` has the same behavior # whether `StandardError` is included or not, because all ``StandardError``s # are rescued by `rescue Exception`). # # @example # # # bad # # begin # something # rescue Exception # handle_exception # rescue StandardError # handle_standard_error # end # # # bad # begin # something # rescue Exception, StandardError # handle_error # end # # # good # # begin # something # rescue StandardError # handle_standard_error # rescue Exception # handle_exception # end # # # good, however depending on runtime environment. # # # # This is a special case for system call errors. # # System dependent error code depends on runtime environment. # # For example, whether `Errno::EAGAIN` and `Errno::EWOULDBLOCK` are # # the same error code or different error code depends on environment. # # This good case is for `Errno::EAGAIN` and `Errno::EWOULDBLOCK` with # # the same error code. # begin # something # rescue Errno::EAGAIN, Errno::EWOULDBLOCK # handle_standard_error # end # class ShadowedException < Base include RescueNode include RangeHelp MSG = 'Do not shadow rescued Exceptions.' def on_rescue(node) return if rescue_modifier?(node) rescues = node.resbody_branches rescued_groups = rescued_groups_for(rescues) rescue_group_rescues_multiple_levels = rescued_groups.any? do |group| contains_multiple_levels_of_exceptions?(group) end return if !rescue_group_rescues_multiple_levels && sorted?(rescued_groups) add_offense(offense_range(rescues)) end private def offense_range(rescues) shadowing_rescue = find_shadowing_rescue(rescues) expression = shadowing_rescue.source_range range_between(expression.begin_pos, expression.end_pos) end def rescued_groups_for(rescues) rescues.map { |group| evaluate_exceptions(group) } end def contains_multiple_levels_of_exceptions?(group) # Always treat `Exception` as the highest level exception. return true if group.size > 1 && group.include?(Exception) group.combination(2).any? { |a, b| compare_exceptions(a, b) } end def compare_exceptions(exception, other_exception) if system_call_err?(exception) && system_call_err?(other_exception) # This condition logic is for special case. # System dependent error code depends on runtime environment. # For example, whether `Errno::EAGAIN` and `Errno::EWOULDBLOCK` are # the same error code or different error code depends on runtime # environment. This checks the error code for that. exception.const_get(:Errno) != other_exception.const_get(:Errno) && exception <=> other_exception else exception && other_exception && exception <=> other_exception end end def system_call_err?(error) error && error.ancestors[1] == SystemCallError end def evaluate_exceptions(group) rescued_exceptions = group.exceptions if rescued_exceptions.any? rescued_exceptions.each_with_object([]) do |exception, converted| RuboCop::Util.silence_warnings do # Avoid printing deprecation warnings about constants converted << Kernel.const_get(exception.source) end rescue NameError converted << nil end else # treat an empty `rescue` as `rescue StandardError` [StandardError] end end def sorted?(rescued_groups) rescued_groups.each_cons(2).all? do |x, y| if x.include?(Exception) false elsif y.include?(Exception) || # consider sorted if a group is empty or only contains # `nil`s x.none? || y.none? true else (x <=> y || 0) <= 0 end end end def find_shadowing_rescue(rescues) rescued_groups = rescued_groups_for(rescues) rescued_groups.zip(rescues).each do |group, res| return res if contains_multiple_levels_of_exceptions?(group) end rescued_groups.each_cons(2).with_index do |group_pair, i| return rescues[i] unless sorted?(group_pair) end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/percent_symbol_array.rb
lib/rubocop/cop/lint/percent_symbol_array.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for colons and commas in %i, e.g. `%i(:foo, :bar)` # # It is more likely that the additional characters are unintended (for # example, mistranslating an array of literals to percent string notation) # rather than meant to be part of the resulting symbols. # # @example # # # bad # %i(:foo, :bar) # # # good # %i(foo bar) class PercentSymbolArray < Base include PercentLiteral extend AutoCorrector MSG = "Within `%i`/`%I`, ':' and ',' are unnecessary and may be " \ 'unwanted in the resulting symbols.' def on_array(node) process(node, '%i', '%I') end def on_percent_literal(node) return unless contains_colons_or_commas?(node) add_offense(node) { |corrector| autocorrect(corrector, node) } end private def autocorrect(corrector, node) node.children.each do |child| range = child.source_range corrector.remove_trailing(range, 1) if range.source.end_with?(',') corrector.remove_leading(range, 1) if range.source.start_with?(':') end end def contains_colons_or_commas?(node) node.children.any? do |child| literal = child.children.first.to_s next if non_alphanumeric_literal?(literal) literal.start_with?(':') || literal.end_with?(',') end end def non_alphanumeric_literal?(literal) !/[[:alnum:]]/.match?(literal) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/each_with_object_argument.rb
lib/rubocop/cop/lint/each_with_object_argument.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks if each_with_object is called with an immutable # argument. Since the argument is the object that the given block shall # make calls on to build something based on the enumerable that # each_with_object iterates over, an immutable argument makes no sense. # It's definitely a bug. # # @example # # # bad # sum = numbers.each_with_object(0) { |e, a| a += e } # # # good # num = 0 # sum = numbers.each_with_object(num) { |e, a| a += e } class EachWithObjectArgument < Base MSG = 'The argument to each_with_object cannot be immutable.' RESTRICT_ON_SEND = %i[each_with_object].freeze # @!method each_with_object?(node) def_node_matcher :each_with_object?, <<~PATTERN (call _ :each_with_object $_) PATTERN def on_send(node) each_with_object?(node) do |arg| return unless arg.immutable_literal? add_offense(node) end end alias on_csend on_send end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/redundant_cop_disable_directive.rb
lib/rubocop/cop/lint/redundant_cop_disable_directive.rb
# frozen_string_literal: true # The Lint/RedundantCopDisableDirective cop needs to be disabled so as # to be able to provide a (bad) example of a redundant disable. # rubocop:disable Lint/RedundantCopDisableDirective module RuboCop module Cop module Lint # Detects instances of rubocop:disable comments that can be # removed without causing any offenses to be reported. It's implemented # as a cop in that it inherits from the Cop base class and calls # add_offense. The unusual part of its implementation is that it doesn't # have any on_* methods or an investigate method. This means that it # doesn't take part in the investigation phase when the other cops do # their work. Instead, it waits until it's called in a later stage of the # execution. The reason it can't be implemented as a normal cop is that # it depends on the results of all other cops to do its work. # # # @example # # bad # # rubocop:disable Layout/LineLength # x += 1 # # rubocop:enable Layout/LineLength # # # good # x += 1 class RedundantCopDisableDirective < Base # rubocop:todo Metrics/ClassLength include RangeHelp extend AutoCorrector COP_NAME = 'Lint/RedundantCopDisableDirective' DEPARTMENT_MARKER = 'DEPARTMENT' attr_accessor :offenses_to_check def initialize(config = nil, options = nil, offenses = nil) @offenses_to_check = offenses super(config, options) end def on_new_investigation return unless offenses_to_check redundant_cops = Hash.new { |h, k| h[k] = Set.new } each_redundant_disable do |comment, redundant_cop| redundant_cops[comment].add(redundant_cop) end add_offenses(redundant_cops) super end private def cop_disabled_line_ranges processed_source.disabled_line_ranges end def disabled_ranges cop_disabled_line_ranges[COP_NAME] || [0..0] end def previous_line_blank?(range) processed_source.buffer.source_line(range.line - 1).blank? end def comment_range_with_surrounding_space(directive_comment_range, line_comment_range) if previous_line_blank?(directive_comment_range) && processed_source.comment_config.comment_only_line?(directive_comment_range.line) && directive_comment_range.begin_pos == line_comment_range.begin_pos # When the previous line is blank, it should be retained range_with_surrounding_space(directive_comment_range, side: :right) else # Eat the entire comment, the preceding space, and the preceding # newline if there is one. original_begin = directive_comment_range.begin_pos range = range_with_surrounding_space( directive_comment_range, side: :left, newlines: true ) range_with_surrounding_space(range, side: :right, # Special for a comment that # begins the file: remove # the newline at the end. newlines: original_begin.zero?) end end def directive_range_in_list(range, ranges) # Is there any cop between this one and the end of the line, which # is NOT being removed? if ends_its_line?(ranges.last) && trailing_range?(ranges, range) # Eat the comma on the left. range = range_with_surrounding_space(range, side: :left) range = range_with_surrounding_comma(range, :left) end range = range_with_surrounding_comma(range, :right) # Eat following spaces up to EOL, but not the newline itself. range_with_surrounding_space(range, side: :right, newlines: false) end def each_redundant_disable(&block) cop_disabled_line_ranges.each do |cop, line_ranges| each_already_disabled(cop, line_ranges, &block) each_line_range(cop, line_ranges, &block) end end def each_line_range(cop, line_ranges) line_ranges.each_with_index do |line_range, line_range_index| next if should_skip_line_range?(cop, line_range) comment = processed_source.comment_at_line(line_range.begin) next if skip_directive?(comment) next_range = line_ranges[line_range_index + 1] redundant = find_redundant_directive(cop, comment, line_range, next_range) yield comment, redundant if redundant end end def should_skip_line_range?(cop, line_range) ignore_offense?(line_range) || expected_final_disable?(cop, line_range) end def skip_directive?(comment) directive = DirectiveComment.new(comment) directive.push? || directive.pop? end def find_redundant_directive(cop, comment, line_range, next_range) if all_disabled?(comment) find_redundant_all(line_range, next_range) elsif department_disabled?(cop, comment) find_redundant_department(cop, line_range) else find_redundant_cop(cop, line_range) end end # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity def each_already_disabled(cop, line_ranges) line_ranges.each_cons(2) do |previous_range, range| next if ignore_offense?(range) # If a cop is disabled in a range that begins on the same line as # the end of the previous range, it means that the cop was # already disabled by an earlier comment. So it's redundant # whether there are offenses or not. next unless followed_ranges?(previous_range, range) comment = processed_source.comment_at_line(range.begin) next unless comment # Comments disabling all cops don't count since it's reasonable # to disable a few select cops first and then all cops further # down in the code. next if all_disabled?(comment) redundant = if department_disabled?(cop, comment) find_redundant_department(cop, range) else cop end yield comment, redundant if redundant end end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity def find_redundant_cop(cop, range) cop_offenses = offenses_to_check.select { |offense| offense.cop_name == cop } cop if range_with_offense?(range, cop_offenses) end def find_redundant_all(range, next_range) # If there's a disable all comment followed by a comment # specifically disabling `cop`, we don't report the `all` # comment. If the disable all comment is truly redundant, we will # detect that when examining the comments of another cop, and we # get the full line range for the disable all. has_no_next_range = next_range.nil? || !followed_ranges?(range, next_range) 'all' if has_no_next_range && range_with_offense?(range) end def find_redundant_department(cop, range) department = cop.split('/').first offenses = offenses_to_check.select { |offense| offense.cop_name.start_with?(department) } add_department_marker(department) if range_with_offense?(range, offenses) end def followed_ranges?(range, next_range) range.end == next_range.begin end def range_with_offense?(range, offenses = offenses_to_check) offenses.none? { |offense| range.cover?(offense.line) } end def all_disabled?(comment) DirectiveComment.new(comment).disabled_all? end def ignore_offense?(line_range) return true if line_range.min == CommentConfig::CONFIG_DISABLED_LINE_RANGE_MIN disabled_ranges.any? do |range| range.cover?(line_range.min) && range.cover?(line_range.max) end end def expected_final_disable?(cop, line_range) # A cop which is disabled in the config is being re-disabled until end of file cop_class = RuboCop::Cop::Registry.global.find_by_cop_name cop cop_class && !processed_source.registry.enabled?(cop_class, config) && line_range.max == Float::INFINITY end def department_disabled?(cop, comment) directive = DirectiveComment.new(comment) directive.in_directive_department?(cop) && !directive.overridden_by_department?(cop) end def directive_count(comment) DirectiveComment.new(comment).directive_count end def add_offenses(redundant_cops) redundant_cops.each do |comment, cops| if all_disabled?(comment) || directive_count(comment) == cops.size add_offense_for_entire_comment(comment, cops) else add_offense_for_some_cops(comment, cops) end end end def add_offense_for_entire_comment(comment, cops) location = DirectiveComment.new(comment).range cop_names = cops.sort.map { |c| describe(c) }.join(', ') add_offense(location, message: message(cop_names)) do |corrector| range = comment_range_with_surrounding_space(location, comment.source_range) if leave_free_comment?(comment, range) corrector.replace(range, ' # ') else corrector.remove(range) end end end def add_offense_for_some_cops(comment, cops) cop_ranges = cops.map { |c| [c, cop_range(comment, c)] } cop_ranges.sort_by! { |_, r| r.begin_pos } ranges = cop_ranges.map { |_, r| r } cop_ranges.each do |cop, range| cop_name = describe(cop) add_offense(range, message: message(cop_name)) do |corrector| range = directive_range_in_list(range, ranges) corrector.remove(range) end end end def leave_free_comment?(comment, range) free_comment = comment.text.gsub(range.source.strip, '') !free_comment.empty? && !free_comment.start_with?('#') end def cop_range(comment, cop) cop = remove_department_marker(cop) matching_range(comment.source_range, cop) || matching_range(comment.source_range, Badge.parse(cop).cop_name) || raise("Couldn't find #{cop} in comment: #{comment.text}") end def matching_range(haystack, needle) offset = haystack.source.index(needle) return unless offset offset += haystack.begin_pos Parser::Source::Range.new(haystack.source_buffer, offset, offset + needle.size) end def trailing_range?(ranges, range) ranges .drop_while { |r| !r.equal?(range) } .each_cons(2) .map { |range1, range2| range1.end.join(range2.begin).source } .all?(/\A\s*,\s*\z/) end SIMILAR_COP_NAMES_CACHE = Hash.new do |hash, cop_name| hash[:all_cop_names] = Registry.global.names unless hash.key?(:all_cop_names) hash[cop_name] = NameSimilarity.find_similar_name(cop_name, hash[:all_cop_names]) end private_constant :SIMILAR_COP_NAMES_CACHE def describe(cop) return 'all cops' if cop == 'all' return "`#{remove_department_marker(cop)}` department" if department_marker?(cop) return "`#{cop}`" if all_cop_names.include?(cop) similar = SIMILAR_COP_NAMES_CACHE[cop] similar ? "`#{cop}` (did you mean `#{similar}`?)" : "`#{cop}` (unknown cop)" end def message(cop_names) "Unnecessary disabling of #{cop_names}." end def all_cop_names @all_cop_names ||= Registry.global.names end def ends_its_line?(range) line = range.source_buffer.source_line(range.last_line) (line =~ /\s*\z/) == range.last_column end def department_marker?(department) department.start_with?(DEPARTMENT_MARKER) end def remove_department_marker(department) department.gsub(DEPARTMENT_MARKER, '') end def add_department_marker(department) DEPARTMENT_MARKER + department end end end end end # rubocop:enable Lint/RedundantCopDisableDirective
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/unused_block_argument.rb
lib/rubocop/cop/lint/unused_block_argument.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for unused block arguments. # # @example # # bad # do_something do |used, unused| # puts used # end # # do_something do |bar| # puts :foo # end # # define_method(:foo) do |bar| # puts :baz # end # # # good # do_something do |used, _unused| # puts used # end # # do_something do # puts :foo # end # # define_method(:foo) do |_bar| # puts :baz # end # # @example IgnoreEmptyBlocks: true (default) # # good # do_something { |unused| } # # @example IgnoreEmptyBlocks: false # # bad # do_something { |unused| } # # @example AllowUnusedKeywordArguments: false (default) # # bad # do_something do |unused: 42| # foo # end # # @example AllowUnusedKeywordArguments: true # # good # do_something do |unused: 42| # foo # end # class UnusedBlockArgument < Base include UnusedArgument extend AutoCorrector def self.joining_forces VariableForce end private def autocorrect(corrector, node) UnusedArgCorrector.correct(corrector, processed_source, node) end def check_argument(variable) return if allowed_block?(variable) || allowed_keyword_argument?(variable) || used_block_local?(variable) super end def used_block_local?(variable) variable.explicit_block_local_variable? && !variable.assignments.empty? end def allowed_block?(variable) !variable.block_argument? || (ignore_empty_blocks? && empty_block?(variable)) end def allowed_keyword_argument?(variable) variable.keyword_argument? && allow_unused_keyword_arguments? end def message(variable) message = "Unused #{variable_type(variable)} - `#{variable.name}`." if variable.explicit_block_local_variable? message else augment_message(message, variable) end end def augment_message(message, variable) scope = variable.scope all_arguments = scope.variables.each_value.select(&:block_argument?) augmentation = if scope.node.lambda? message_for_lambda(variable, all_arguments) else message_for_normal_block(variable, all_arguments) end [message, augmentation].join(' ') end def variable_type(variable) if variable.explicit_block_local_variable? 'block local variable' else 'block argument' end end def message_for_normal_block(variable, all_arguments) if all_arguments.none?(&:referenced?) && !define_method_call?(variable) if all_arguments.count > 1 "You can omit all the arguments if you don't care about them." else "You can omit the argument if you don't care about it." end else message_for_underscore_prefix(variable) end end def message_for_lambda(variable, all_arguments) message = message_for_underscore_prefix(variable) if all_arguments.none?(&:referenced?) proc_message = 'Also consider using a proc without arguments ' \ 'instead of a lambda if you want it ' \ "to accept any arguments but don't care about them." end [message, proc_message].compact.join(' ') end def message_for_underscore_prefix(variable) "If it's necessary, use `_` or `_#{variable.name}` " \ "as an argument name to indicate that it won't be used." end def define_method_call?(variable) call, = *variable.scope.node _, method, = *call method == :define_method end def empty_block?(variable) _send, _args, body = *variable.scope.node body.nil? end def allow_unused_keyword_arguments? cop_config['AllowUnusedKeywordArguments'] end def ignore_empty_blocks? cop_config['IgnoreEmptyBlocks'] end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/duplicate_branch.rb
lib/rubocop/cop/lint/duplicate_branch.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks that there are no repeated bodies # within `if/unless`, `case-when`, `case-in` and `rescue` constructs. # # With `IgnoreLiteralBranches: true`, branches are not registered # as offenses if they return a basic literal value (string, symbol, # integer, float, rational, complex, `true`, `false`, or `nil`), or # return an array, hash, regexp or range that only contains one of # the above basic literal values. # # With `IgnoreConstantBranches: true`, branches are not registered # as offenses if they return a constant value. # # With `IgnoreDuplicateElseBranch: true`, in conditionals with multiple branches, # duplicate 'else' branches are not registered as offenses. # # @example # # bad # if foo # do_foo # do_something_else # elsif bar # do_foo # do_something_else # end # # # good # if foo || bar # do_foo # do_something_else # end # # # bad # case x # when foo # do_foo # when bar # do_foo # else # do_something_else # end # # # good # case x # when foo, bar # do_foo # else # do_something_else # end # # # bad # begin # do_something # rescue FooError # handle_error # rescue BarError # handle_error # end # # # good # begin # do_something # rescue FooError, BarError # handle_error # end # # @example IgnoreLiteralBranches: true # # good # case size # when "small" then 100 # when "medium" then 250 # when "large" then 1000 # else 250 # end # # @example IgnoreConstantBranches: true # # good # case size # when "small" then SMALL_SIZE # when "medium" then MEDIUM_SIZE # when "large" then LARGE_SIZE # else MEDIUM_SIZE # end # # @example IgnoreDuplicateElseBranch: true # # good # if foo # do_foo # elsif bar # do_bar # else # do_foo # end # class DuplicateBranch < Base MSG = 'Duplicate branch body detected.' def on_branching_statement(node) branches = branches(node) branches.each_with_object(Set.new) do |branch, previous| next unless consider_branch?(branches, branch) add_offense(offense_range(branch)) unless previous.add?(branch) end end alias on_case on_branching_statement alias on_case_match on_branching_statement alias on_rescue on_branching_statement def on_if(node) # Ignore 'elsif' nodes, because we don't want to check them separately whether # the 'else' branch is duplicated. We want to check only on the outermost conditional. on_branching_statement(node) unless node.elsif? end private def offense_range(duplicate_branch) parent = duplicate_branch.parent if parent.respond_to?(:else_branch) && parent.else_branch.equal?(duplicate_branch) if parent.if_type? && parent.ternary? duplicate_branch.source_range else parent.loc.else end else parent.source_range end end def branches(node) node.branches.compact end def consider_branch?(branches, branch) return false if ignore_literal_branches? && literal_branch?(branch) return false if ignore_constant_branches? && const_branch?(branch) if ignore_duplicate_else_branches? && duplicate_else_branch?(branches, branch) return false end true end def ignore_literal_branches? cop_config.fetch('IgnoreLiteralBranches', false) end def ignore_constant_branches? cop_config.fetch('IgnoreConstantBranches', false) end def ignore_duplicate_else_branches? cop_config.fetch('IgnoreDuplicateElseBranch', false) end def literal_branch?(branch) # rubocop:disable Metrics/CyclomaticComplexity return false if !branch.literal? || branch.xstr_type? return true if branch.basic_literal? branch.each_descendant.all? do |node| node.basic_literal? || node.pair_type? || # hash keys and values are contained within a `pair` node (node.const_type? && ignore_constant_branches?) end end def const_branch?(branch) branch.const_type? end def duplicate_else_branch?(branches, branch) return false unless (parent = branch.parent) branches.size > 2 && branch.equal?(branches.last) && parent.respond_to?(:else?) && parent.else? end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/empty_ensure.rb
lib/rubocop/cop/lint/empty_ensure.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for empty `ensure` blocks. # # @example # # # bad # def some_method # do_something # ensure # end # # # bad # begin # do_something # ensure # end # # # good # def some_method # do_something # ensure # do_something_else # end # # # good # begin # do_something # ensure # do_something_else # end class EmptyEnsure < Base extend AutoCorrector MSG = 'Empty `ensure` block detected.' def on_ensure(node) return if node.branch add_offense(node.loc.keyword) { |corrector| corrector.remove(node.loc.keyword) } end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/identity_comparison.rb
lib/rubocop/cop/lint/identity_comparison.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Prefer `equal?` over `==` when comparing `object_id`. # # `Object#equal?` is provided to compare objects for identity, and in contrast # `Object#==` is provided for the purpose of doing value comparison. # # @example # # bad # foo.object_id == bar.object_id # foo.object_id != baz.object_id # # # good # foo.equal?(bar) # !foo.equal?(baz) # class IdentityComparison < Base extend AutoCorrector MSG = 'Use `%<bang>sequal?` instead of `%<comparison_method>s` when comparing `object_id`.' RESTRICT_ON_SEND = %i[== !=].freeze # @!method object_id_comparison(node) def_node_matcher :object_id_comparison, <<~PATTERN (send (send _lhs_receiver :object_id) ${:== :!=} (send _rhs_receiver :object_id)) PATTERN def on_send(node) return unless (comparison_method = object_id_comparison(node)) bang = comparison_method == :== ? '' : '!' add_offense(node, message: format(MSG, comparison_method: comparison_method, bang: bang)) do |corrector| receiver = node.receiver.receiver argument = node.first_argument.receiver return unless receiver && argument replacement = "#{bang}#{receiver.source}.equal?(#{argument.source})" corrector.replace(node, replacement) end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/heredoc_method_call_position.rb
lib/rubocop/cop/lint/heredoc_method_call_position.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for the ordering of a method call where # the receiver of the call is a HEREDOC. # # @example # # bad # <<-SQL # bar # SQL # .strip_indent # # <<-SQL # bar # SQL # .strip_indent # .trim # # # good # <<~SQL # bar # SQL # # <<~SQL.trim # bar # SQL # class HeredocMethodCallPosition < Base include RangeHelp extend AutoCorrector MSG = 'Put a method call with a HEREDOC receiver on the same line as the HEREDOC opening.' def on_send(node) heredoc = heredoc_node_descendent_receiver(node) return unless heredoc return if correctly_positioned?(node, heredoc) add_offense(call_after_heredoc_range(heredoc)) do |corrector| autocorrect(corrector, node, heredoc) end end alias on_csend on_send private def autocorrect(corrector, node, heredoc) call_range = call_range_to_safely_reposition(node, heredoc) return if call_range.nil? call_source = call_range.source.strip corrector.remove(call_range) corrector.insert_after(heredoc_begin_line_range(node), call_source) end def heredoc_node_descendent_receiver(node) while send_node?(node) return node.receiver if heredoc_node?(node.receiver) node = node.receiver end end def send_node?(node) return false unless node node.call_type? end def heredoc_node?(node) node.respond_to?(:heredoc?) && node.heredoc? end def call_after_heredoc_range(heredoc) pos = heredoc_end_pos(heredoc) range_between(pos + 1, pos + 2) end def correctly_positioned?(node, heredoc) heredoc_end_pos(heredoc) > call_end_pos(node) end def calls_on_multiple_lines?(node, _heredoc) last_line = node.last_line while send_node?(node) return true unless last_line == node.last_line return true unless all_on_same_line?(node.arguments) node = node.receiver end false end def all_on_same_line?(nodes) return true if nodes.empty? nodes.first.first_line == nodes.last.last_line end def heredoc_end_pos(heredoc) heredoc.location.heredoc_end.end_pos end def call_end_pos(node) node.source_range.end_pos end def heredoc_begin_line_range(heredoc) pos = heredoc.source_range.begin_pos range_by_whole_lines(range_between(pos, pos)) end def call_line_range(node) pos = node.source_range.end_pos range_by_whole_lines(range_between(pos, pos)) end # Returns nil if no range can be safely repositioned. def call_range_to_safely_reposition(node, heredoc) return nil if calls_on_multiple_lines?(node, heredoc) heredoc_end_pos = heredoc_end_pos(heredoc) call_end_pos = call_end_pos(node) call_range = range_between(heredoc_end_pos, call_end_pos) call_line_range = call_line_range(node) call_source = call_range.source.strip call_line_source = call_line_range.source.strip return call_range if call_source == call_line_source if trailing_comma?(call_source, call_line_source) # If there's some on the last line other than the call, e.g. # a trailing comma, then we leave the "\n" following the # heredoc_end in place. return range_between(heredoc_end_pos, call_end_pos + 1) end nil end def trailing_comma?(call_source, call_line_source) "#{call_source}," == call_line_source end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/nested_method_definition.rb
lib/rubocop/cop/lint/nested_method_definition.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for nested method definitions. # # @example # # # bad # # # `bar` definition actually produces methods in the same scope # # as the outer `foo` method. Furthermore, the `bar` method # # will be redefined every time `foo` is invoked. # def foo # def bar # end # end # # # good # # def foo # bar = -> { puts 'hello' } # bar.call # end # # # good # # # `class_eval`, `instance_eval`, `module_eval`, `class_exec`, `instance_exec`, and # # `module_exec` blocks are allowed by default. # # def foo # self.class.class_eval do # def bar # end # end # end # # def foo # self.class.module_exec do # def bar # end # end # end # # # good # # def foo # class << self # def bar # end # end # end # # @example AllowedMethods: [] (default) # # bad # def do_something # has_many :articles do # def find_or_create_by_name(name) # end # end # end # # @example AllowedMethods: ['has_many'] # # bad # def do_something # has_many :articles do # def find_or_create_by_name(name) # end # end # end # # @example AllowedPatterns: [] (default) # # bad # def foo(obj) # obj.do_baz do # def bar # end # end # end # # @example AllowedPatterns: ['baz'] # # good # def foo(obj) # obj.do_baz do # def bar # end # end # end # class NestedMethodDefinition < Base include AllowedMethods include AllowedPattern MSG = 'Method definitions must not be nested. Use `lambda` instead.' def on_def(node) subject, = *node # rubocop:disable InternalAffairs/NodeDestructuring return if node.defs_type? && allowed_subject_type?(subject) def_ancestor = node.each_ancestor(:any_def).first return unless def_ancestor within_scoping_def = node.each_ancestor(:any_block, :sclass).any? do |ancestor| scoping_method_call?(ancestor) end add_offense(node) if def_ancestor && !within_scoping_def end alias on_defs on_def private def scoping_method_call?(child) child.sclass_type? || eval_call?(child) || exec_call?(child) || child.class_constructor? || allowed_method_name?(child) end def allowed_subject_type?(subject) subject.variable? || subject.const_type? || subject.call_type? end def allowed_method_name?(node) name = node.method_name allowed_method?(name) || matches_allowed_pattern?(name) end # @!method eval_call?(node) def_node_matcher :eval_call?, <<~PATTERN (any_block (send _ {:instance_eval :class_eval :module_eval} ...) ...) PATTERN # @!method exec_call?(node) def_node_matcher :exec_call?, <<~PATTERN (any_block (send _ {:instance_exec :class_exec :module_exec} ...) ...) PATTERN end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/require_range_parentheses.rb
lib/rubocop/cop/lint/require_range_parentheses.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks that a range literal is enclosed in parentheses when the end of the range is # at a line break. # # NOTE: The following is maybe intended for `(42..)`. But, compatible is `42..do_something`. # So, this cop does not provide autocorrection because it is left to user. # # [source,ruby] # ---- # case condition # when 42.. # do_something # end # ---- # # @example # # # bad - Represents `(1..42)`, not endless range. # 1.. # 42 # # # good - It's incompatible, but your intentions when using endless range may be: # (1..) # 42 # # # good # 1..42 # # # good # (1..42) # # # good # (1.. # 42) # class RequireRangeParentheses < Base MSG = 'Wrap the endless range literal `%<range>s` to avoid precedence ambiguity.' def on_irange(node) return if node.parent&.begin_type? return unless node.begin && node.end return if same_line?(node.loc.operator, node.end) message = format(MSG, range: "#{node.begin.source}#{node.loc.operator.source}") add_offense(node, message: message) end alias on_erange on_irange end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/triple_quotes.rb
lib/rubocop/cop/lint/triple_quotes.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for "triple quotes" (strings delimited by any odd number # of quotes greater than 1). # # Ruby allows multiple strings to be implicitly concatenated by just # being adjacent in a statement (ie. `"foo""bar" == "foobar"`). This sometimes # gives the impression that there is something special about triple quotes, but # in fact it is just extra unnecessary quotes and produces the same string. Each # pair of quotes produces an additional concatenated empty string, so the result # is still only the "actual" string within the delimiters. # # NOTE: Although this cop is called triple quotes, the same behavior is present # for strings delimited by 5, 7, etc. quotation marks. # # @example # # bad # """ # A string # """ # # # bad # ''' # A string # ''' # # # good # " # A string # " # # # good # <<STRING # A string # STRING # # # good (but not the same spacing as the bad case) # 'A string' class TripleQuotes < Base extend AutoCorrector MSG = 'Delimiting a string with multiple quotes has no effect, use a single quote instead.' def on_dstr(node) return if (empty_str_nodes = empty_str_nodes(node)).none? opening_quotes = node.source.scan(/(?<=\A)['"]*/)[0] return if opening_quotes.size < 3 # If the node is composed of only empty `str` nodes, keep one empty_str_nodes.shift if empty_str_nodes.size == node.child_nodes.size add_offense(node) do |corrector| empty_str_nodes.each do |str| corrector.remove(str) end end end private def empty_str_nodes(node) node.each_child_node(:str).select { |str| str.value == '' } end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/require_parentheses.rb
lib/rubocop/cop/lint/require_parentheses.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for expressions where there is a call to a predicate # method with at least one argument, where no parentheses are used around # the parameter list, and a boolean operator, && or ||, is used in the # last argument. # # The idea behind warning for these constructs is that the user might # be under the impression that the return value from the method call is # an operand of &&/||. # # @example # # # bad # if day.is? :tuesday && month == :jan # # ... # end # # # good # if day.is?(:tuesday) && month == :jan # # ... # end class RequireParentheses < Base include RangeHelp MSG = 'Use parentheses in the method call to avoid confusion about precedence.' def on_send(node) return if !node.arguments? || node.parenthesized? if node.first_argument.if_type? && node.first_argument.ternary? check_ternary(node.first_argument, node) elsif node.predicate_method? check_predicate(node.last_argument, node) end end alias on_csend on_send private def check_ternary(ternary, node) if node.method?(:[]) || node.assignment_method? || !ternary.condition.operator_keyword? return end range = range_between(node.source_range.begin_pos, ternary.condition.source_range.end_pos) add_offense(range) end def check_predicate(predicate, node) return unless predicate.operator_keyword? add_offense(node) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/parentheses_as_grouped_expression.rb
lib/rubocop/cop/lint/parentheses_as_grouped_expression.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for space between the name of a called method and a left # parenthesis. # # @example # # # bad # do_something (foo) # # # good # do_something(foo) # do_something (2 + 3) * 4 # do_something (foo * bar).baz class ParenthesesAsGroupedExpression < Base include RangeHelp extend AutoCorrector MSG = '`%<argument>s` interpreted as grouped expression.' def on_send(node) return if valid_context?(node) space_length = spaces_before_left_parenthesis(node) return unless space_length.positive? range = space_range(node.first_argument.source_range, space_length) message = format(MSG, argument: node.first_argument.source) add_offense(range, message: message) { |corrector| corrector.remove(range) } end alias on_csend on_send private def valid_context?(node) return true unless node.arguments.one? && node.first_argument.parenthesized_call? return true if node.first_argument.any_block_type? node.operator_method? || node.setter_method? || chained_calls?(node) || valid_first_argument?(node.first_argument) end def valid_first_argument?(first_arg) first_arg.operator_keyword? || first_arg.hash_type? || ternary_expression?(first_arg) || compound_range?(first_arg) end def compound_range?(first_arg) first_arg.range_type? && first_arg.parenthesized_call? end def chained_calls?(node) first_argument = node.first_argument first_argument.call_type? && (node.children.last&.children&.count || 0) > 1 end def ternary_expression?(node) node.if_type? && node.ternary? end def spaces_before_left_parenthesis(node) receiver = node.receiver receiver_length = if receiver receiver.source.length else 0 end without_receiver = node.source[receiver_length..] # Escape question mark if any. method_regexp = Regexp.escape(node.method_name) match = without_receiver.match(/^\s*&?\.?\s*#{method_regexp}(\s+)\(/) match ? match.captures[0].length : 0 end def space_range(expr, space_length) range_between(expr.begin_pos - space_length, expr.begin_pos) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/numeric_operation_with_constant_result.rb
lib/rubocop/cop/lint/numeric_operation_with_constant_result.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Certain numeric operations have a constant result, usually 0 or 1. # Multiplying a number by 0 will always return 0. # Dividing a number by itself or raising it to the power of 0 will always return 1. # As such, they can be replaced with that result. # These are probably leftover from debugging, or are mistakes. # Other numeric operations that are similarly leftover from debugging or mistakes # are handled by `Lint/UselessNumericOperation`. # # NOTE: This cop doesn't detect offenses for the `-` and `%` operator because it # can't determine the type of `x`. If `x` is an `Array` or `String`, it doesn't perform # a numeric operation. # # @example # # # bad # x * 0 # # # good # 0 # # # bad # x *= 0 # # # good # x = 0 # # # bad # x / x # x ** 0 # # # good # 1 # # # bad # x /= x # x **= 0 # # # good # x = 1 # class NumericOperationWithConstantResult < Base extend AutoCorrector MSG = 'Numeric operation with a constant result detected.' RESTRICT_ON_SEND = %i[* / **].freeze # @!method operation_with_constant_result?(node) def_node_matcher :operation_with_constant_result?, '(call (call nil? $_lhs) $_operation ({int | call nil?} $_rhs))' # @!method abbreviated_assignment_with_constant_result?(node) def_node_matcher :abbreviated_assignment_with_constant_result?, '(op-asgn (lvasgn $_lhs) $_operation ({int lvar} $_rhs))' def on_send(node) return unless (lhs, operation, rhs = operation_with_constant_result?(node)) return unless (result = constant_result?(lhs, operation, rhs)) add_offense(node) do |corrector| corrector.replace(node, result.to_s) end end alias on_csend on_send def on_op_asgn(node) return unless (lhs, operation, rhs = abbreviated_assignment_with_constant_result?(node)) return unless (result = constant_result?(lhs, operation, rhs)) add_offense(node) do |corrector| corrector.replace(node, "#{lhs} = #{result}") end end private def constant_result?(lhs, operation, rhs) if rhs.to_s == '0' return 0 if operation == :* return 1 if operation == :** elsif rhs == lhs return 1 if operation == :/ end # If we weren't able to find any matches, return false so we can bail out. false end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/redundant_splat_expansion.rb
lib/rubocop/cop/lint/redundant_splat_expansion.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for unneeded usages of splat expansion. # # @example # # # bad # a = *[1, 2, 3] # a = *'a' # a = *1 # ['a', 'b', *%w(c d e), 'f', 'g'] # # # good # c = [1, 2, 3] # a = *c # a, b = *c # a, *b = *c # a = *1..10 # a = ['a'] # ['a', 'b', 'c', 'd', 'e', 'f', 'g'] # # # bad # do_something(*['foo', 'bar', 'baz']) # # # good # do_something('foo', 'bar', 'baz') # # # bad # begin # foo # rescue *[StandardError, ApplicationError] # bar # end # # # good # begin # foo # rescue StandardError, ApplicationError # bar # end # # # bad # case foo # when *[1, 2, 3] # bar # else # baz # end # # # good # case foo # when 1, 2, 3 # bar # else # baz # end # # @example AllowPercentLiteralArrayArgument: true (default) # # # good # do_something(*%w[foo bar baz]) # # @example AllowPercentLiteralArrayArgument: false # # # bad # do_something(*%w[foo bar baz]) # class RedundantSplatExpansion < Base extend AutoCorrector MSG = 'Replace splat expansion with comma separated values.' ARRAY_PARAM_MSG = 'Pass array contents as separate arguments.' PERCENT_W = '%w' PERCENT_CAPITAL_W = '%W' PERCENT_I = '%i' PERCENT_CAPITAL_I = '%I' ASSIGNMENT_TYPES = %i[lvasgn ivasgn cvasgn gvasgn].freeze # @!method array_new?(node) def_node_matcher :array_new?, <<~PATTERN { $(send (const {nil? cbase} :Array) :new ...) $(block (send (const {nil? cbase} :Array) :new ...) ...) } PATTERN # @!method literal_expansion(node) def_node_matcher :literal_expansion, <<~PATTERN (splat {$({str dstr int float array} ...) (block $#array_new? ...) $#array_new?} ...) PATTERN def on_splat(node) redundant_splat_expansion(node) do if array_splat?(node) && (method_argument?(node) || part_of_an_array?(node)) return if allow_percent_literal_array_argument? && use_percent_literal_array_argument?(node) add_offense(node, message: ARRAY_PARAM_MSG) do |corrector| autocorrect(corrector, node) end else add_offense(node) { |corrector| autocorrect(corrector, node) } end end end private def autocorrect(corrector, node) range, content = replacement_range_and_content(node) corrector.replace(range, content) end def redundant_splat_expansion(node) literal_expansion(node) do |expanded_item| if expanded_item.send_type? return if array_new_inside_array_literal?(expanded_item) grandparent = node.parent.parent return if grandparent && !ASSIGNMENT_TYPES.include?(grandparent.type) end yield end end def array_new_inside_array_literal?(array_new_node) return false unless array_new?(array_new_node) grandparent = array_new_node.parent.parent grandparent.array_type? && grandparent.children.size > 1 end # rubocop:disable Metrics/AbcSize def replacement_range_and_content(node) variable = node.children.first expression = node.source_range if array_new?(variable) expression = node.parent.source_range if node.parent.array_type? [expression, variable.source] elsif !variable.array_type? replacement = variable.source replacement = "[#{replacement}]" if wrap_in_brackets?(node) [expression, replacement] elsif redundant_brackets?(node) [expression, remove_brackets(variable)] else [node.loc.operator, ''] end end # rubocop:enable Metrics/AbcSize def array_splat?(node) node.children.first.array_type? end def method_argument?(node) node.parent.call_type? end def part_of_an_array?(node) # The parent of a splat expansion is an array that does not have # `begin` or `end` parent = node.parent parent.array_type? && parent.loc.begin && parent.loc.end end def redundant_brackets?(node) parent = node.parent grandparent = node.parent.parent parent.when_type? || method_argument?(node) || part_of_an_array?(node) || grandparent&.resbody_type? end def wrap_in_brackets?(node) node.parent.array_type? && !node.parent.bracketed? end def remove_brackets(array) array_start = array.loc.begin.source elements = *array elements = elements.map(&:source) if array_start.start_with?(PERCENT_W) "'#{elements.join("', '")}'" elsif array_start.start_with?(PERCENT_CAPITAL_W) %("#{elements.join('", "')}") elsif array_start.start_with?(PERCENT_I) ":#{elements.join(', :')}" elsif array_start.start_with?(PERCENT_CAPITAL_I) %(:"#{elements.join('", :"')}") else elements.join(', ') end end def use_percent_literal_array_argument?(node) argument = node.children.first method_argument?(node) && (argument.percent_literal?(:string) || argument.percent_literal?(:symbol)) end def allow_percent_literal_array_argument? cop_config.fetch('AllowPercentLiteralArrayArgument', true) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/mixed_regexp_capture_types.rb
lib/rubocop/cop/lint/mixed_regexp_capture_types.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Do not mix named captures and numbered captures in a `Regexp` literal # because numbered capture is ignored if they're mixed. # Replace numbered captures with non-capturing groupings or # named captures. # # @example # # bad # /(?<foo>FOO)(BAR)/ # # # good # /(?<foo>FOO)(?<bar>BAR)/ # # # good # /(?<foo>FOO)(?:BAR)/ # # # good # /(FOO)(BAR)/ # class MixedRegexpCaptureTypes < Base MSG = 'Do not mix named captures and numbered captures in a Regexp literal.' def on_regexp(node) return if node.interpolation? return if node.each_capture(named: false).none? return if node.each_capture(named: true).none? add_offense(node) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/shadowing_outer_local_variable.rb
lib/rubocop/cop/lint/shadowing_outer_local_variable.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for the use of local variable names from an outer scope # in block arguments or block-local variables. This mirrors the warning # given by `ruby -cw` prior to Ruby 2.6: # "shadowing outer local variable - foo". # # The cop is now disabled by default to match the upstream Ruby behavior. # It's useful, however, if you'd like to avoid shadowing variables from outer # scopes, which some people consider an anti-pattern that makes it harder # to keep track of what's going on in a program. # # NOTE: Shadowing of variables in block passed to `Ractor.new` is allowed # because `Ractor` should not access outer variables. # eg. following style is encouraged: # # [source,ruby] # ---- # worker_id, pipe = env # Ractor.new(worker_id, pipe) do |worker_id, pipe| # end # ---- # # @example # # # bad # def some_method # foo = 1 # # 2.times do |foo| # shadowing outer `foo` # do_something(foo) # end # end # # # good # def some_method # foo = 1 # # 2.times do |bar| # do_something(bar) # end # end class ShadowingOuterLocalVariable < Base MSG = 'Shadowing outer local variable - `%<variable>s`.' # @!method ractor_block?(node) def_node_matcher :ractor_block?, <<~PATTERN (block (send (const nil? :Ractor) :new ...) ...) PATTERN def self.joining_forces VariableForce end def before_declaring_variable(variable, variable_table) return if variable.should_be_unused? return if ractor_block?(variable.scope.node) outer_local_variable = variable_table.find_variable(variable.name) return unless outer_local_variable return if variable_used_in_declaration_of_outer?(variable, outer_local_variable) return if same_conditions_node_different_branch?(variable, outer_local_variable) message = format(MSG, variable: variable.name) add_offense(variable.declaration_node, message: message) end private def variable_used_in_declaration_of_outer?(variable, outer_local_variable) variable.scope.node.each_ancestor.any?(outer_local_variable.declaration_node) end def same_conditions_node_different_branch?(variable, outer_local_variable) variable_node = variable_node(variable) return false unless node_or_its_ascendant_conditional?(variable_node) outer_local_variable_node = find_conditional_node_from_ascendant(outer_local_variable.declaration_node) return false unless outer_local_variable_node return false unless outer_local_variable_node.conditional? return true if variable_node == outer_local_variable_node outer_local_variable_node.if_type? && variable_node == outer_local_variable_node.else_branch end def variable_node(variable) parent_node = variable.scope.node.parent if parent_node.when_type? parent_node.parent else parent_node end end def find_conditional_node_from_ascendant(node) return unless (parent = node.parent) return parent if parent.conditional? find_conditional_node_from_ascendant(parent) end def node_or_its_ascendant_conditional?(node) return true if node.conditional? !!find_conditional_node_from_ascendant(node) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/useless_setter_call.rb
lib/rubocop/cop/lint/useless_setter_call.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for setter call to local variable as the final # expression of a function definition. # # @safety # There are edge cases in which the local variable references a # value that is also accessible outside the local scope. This is not # detected by the cop, and it can yield a false positive. # # As well, autocorrection is unsafe because the method's # return value will be changed. # # @example # # # bad # def something # x = Something.new # x.attr = 5 # end # # # good # def something # x = Something.new # x.attr = 5 # x # end class UselessSetterCall < Base extend AutoCorrector MSG = 'Useless setter call to local variable `%<variable>s`.' ASSIGNMENT_TYPES = %i[lvasgn ivasgn cvasgn gvasgn].freeze def on_def(node) return unless node.body last_expr = last_expression(node.body) return unless setter_call_to_local_variable?(last_expr) tracker = MethodVariableTracker.new(node.body) receiver, = *last_expr variable_name, = *receiver return unless tracker.contain_local_object?(variable_name) loc_name = receiver.loc.name add_offense(loc_name, message: format(MSG, variable: loc_name.source)) do |corrector| corrector.insert_after(last_expr, "\n#{indent(last_expr)}#{loc_name.source}") end end alias on_defs on_def private # @!method setter_call_to_local_variable?(node) def_node_matcher :setter_call_to_local_variable?, <<~PATTERN [(send (lvar _) ...) setter_method?] PATTERN def last_expression(body) expression = body.begin_type? ? body.children : body expression.is_a?(Array) ? expression.last : expression end # This class tracks variable assignments in a method body # and if a variable contains object passed as argument at the end of # the method. class MethodVariableTracker def initialize(body_node) @body_node = body_node @local = nil end def contain_local_object?(variable_name) return @local[variable_name] if @local @local = {} scan(@body_node) { |node| process_assignment_node(node) } @local[variable_name] end def scan(node, &block) catch(:skip_children) do yield node node.each_child_node { |child_node| scan(child_node, &block) } end end def process_assignment_node(node) case node.type when :masgn process_multiple_assignment(node) when :or_asgn, :and_asgn process_logical_operator_assignment(node) when :op_asgn process_binary_operator_assignment(node) when *ASSIGNMENT_TYPES process_assignment(node, node.rhs) if node.rhs end end def process_multiple_assignment(masgn_node) masgn_node.assignments.each_with_index do |lhs_node, index| next unless ASSIGNMENT_TYPES.include?(lhs_node.type) if masgn_node.rhs.array_type? && (rhs_node = masgn_node.rhs.children[index]) process_assignment(lhs_node, rhs_node) else @local[lhs_node.name] = true end end throw :skip_children end def process_logical_operator_assignment(asgn_node) return unless ASSIGNMENT_TYPES.include?(asgn_node.lhs.type) process_assignment(asgn_node.lhs, asgn_node.rhs) throw :skip_children end def process_binary_operator_assignment(op_asgn_node) lhs_node = op_asgn_node.lhs return unless ASSIGNMENT_TYPES.include?(lhs_node.type) @local[lhs_node.name] = true throw :skip_children end def process_assignment(asgn_node, rhs_node) @local[asgn_node.name] = if rhs_node.variable? @local[rhs_node.name] else constructor?(rhs_node) end end def constructor?(node) return true if node.literal? return false unless node.send_type? node.method?(:new) end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/redundant_type_conversion.rb
lib/rubocop/cop/lint/redundant_type_conversion.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for redundant uses of `to_s`, `to_sym`, `to_i`, `to_f`, `to_d`, `to_r`, `to_c`, # `to_a`, `to_h`, and `to_set`. # # When one of these methods is called on an object of the same type, that object # is returned, making the call unnecessary. The cop detects conversion methods called # on object literals, class constructors, class `[]` methods, and the `Kernel` methods # `String()`, `Integer()`, `Float()`, BigDecimal(), `Rational()`, `Complex()`, and `Array()`. # # Specifically, these cases are detected for each conversion method: # # * `to_s` when called on a string literal, interpolated string, heredoc, # or with `String.new` or `String()`. # * `to_sym` when called on a symbol literal or interpolated symbol. # * `to_i` when called on an integer literal or with `Integer()`. # * `to_f` when called on a float literal of with `Float()`. # * `to_r` when called on a rational literal or with `Rational()`. # * `to_c` when called on a complex literal of with `Complex()`. # * `to_a` when called on an array literal, or with `Array.new`, `Array()` or `Array[]`. # * `to_h` when called on a hash literal, or with `Hash.new`, `Hash()` or `Hash[]`. # * `to_set` when called on `Set.new` or `Set[]`. # # In all cases, chaining one same `to_*` conversion methods listed above is redundant. # # The cop can also register an offense for chaining conversion methods on methods that are # expected to return a specific type regardless of receiver (eg. `foo.inspect.to_s` and # `foo.to_json.to_s`). # # @example # # bad # "text".to_s # :sym.to_sym # 42.to_i # 8.5.to_f # 12r.to_r # 1i.to_c # [].to_a # {}.to_h # Set.new.to_set # # # good # "text" # :sym # 42 # 8.5 # 12r # 1i # [] # {} # Set.new # # # bad # Integer(var).to_i # # # good # Integer(var) # # # good - chaining to a type constructor with exceptions suppressed # # in this case, `Integer()` could return `nil` # Integer(var, exception: false).to_i # # # bad - chaining the same conversion # foo.to_s.to_s # # # good # foo.to_s # # # bad - chaining a conversion to a method that is expected to return the same type # foo.inspect.to_s # foo.to_json.to_s # # # good # foo.inspect # foo.to_json # class RedundantTypeConversion < Base extend AutoCorrector MSG = 'Redundant `%<method>s` detected.' # Maps conversion methods to the node types for the literals of that type LITERAL_NODE_TYPES = { to_s: %i[str dstr], to_sym: %i[sym dsym], to_i: %i[int], to_f: %i[float], to_r: %i[rational], to_c: %i[complex], to_a: %i[array], to_h: %i[hash], to_set: [] # sets don't have a literal or node type }.freeze # Maps each conversion method to the pattern matcher for that type's constructors # Not every type has a constructor, for instance Symbol. CONSTRUCTOR_MAPPING = { to_s: 'string_constructor?', to_i: 'integer_constructor?', to_f: 'float_constructor?', to_d: 'bigdecimal_constructor?', to_r: 'rational_constructor?', to_c: 'complex_constructor?', to_a: 'array_constructor?', to_h: 'hash_constructor?', to_set: 'set_constructor?' }.freeze # Methods that already are expected to return a given type, which makes a further # conversion redundant. TYPED_METHODS = { to_s: %i[inspect to_json] }.freeze CONVERSION_METHODS = Set[*LITERAL_NODE_TYPES.keys].freeze RESTRICT_ON_SEND = CONVERSION_METHODS + [:to_d] private_constant :LITERAL_NODE_TYPES, :CONSTRUCTOR_MAPPING # @!method type_constructor?(node, type_symbol) def_node_matcher :type_constructor?, <<~PATTERN (send {nil? (const {cbase nil?} :Kernel)} %1 ...) PATTERN # @!method string_constructor?(node) def_node_matcher :string_constructor?, <<~PATTERN { (send (const {cbase nil?} :String) :new ...) #type_constructor?(:String) } PATTERN # @!method integer_constructor?(node) def_node_matcher :integer_constructor?, <<~PATTERN #type_constructor?(:Integer) PATTERN # @!method float_constructor?(node) def_node_matcher :float_constructor?, <<~PATTERN #type_constructor?(:Float) PATTERN # @!method bigdecimal_constructor?(node) def_node_matcher :bigdecimal_constructor?, <<~PATTERN #type_constructor?(:BigDecimal) PATTERN # @!method rational_constructor?(node) def_node_matcher :rational_constructor?, <<~PATTERN #type_constructor?(:Rational) PATTERN # @!method complex_constructor?(node) def_node_matcher :complex_constructor?, <<~PATTERN #type_constructor?(:Complex) PATTERN # @!method array_constructor?(node) def_node_matcher :array_constructor?, <<~PATTERN { (send (const {cbase nil?} :Array) {:new :[]} ...) #type_constructor?(:Array) } PATTERN # @!method hash_constructor?(node) def_node_matcher :hash_constructor?, <<~PATTERN { (block (send (const {cbase nil?} :Hash) :new) ...) (send (const {cbase nil?} :Hash) {:new :[]} ...) (send {nil? (const {cbase nil?} :Kernel)} :Hash ...) } PATTERN # @!method set_constructor?(node) def_node_matcher :set_constructor?, <<~PATTERN { (send (const {cbase nil?} :Set) {:new :[]} ...) } PATTERN # @!method exception_false_keyword_argument?(node) def_node_matcher :exception_false_keyword_argument?, <<~PATTERN (hash (pair (sym :exception) false)) PATTERN # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity def on_send(node) return if node.arguments.any? || hash_or_set_with_block?(node) receiver = find_receiver(node) return unless literal_receiver?(node, receiver) || constructor?(node, receiver) || chained_conversion?(node, receiver) || chained_to_typed_method?(node, receiver) message = format(MSG, method: node.method_name) add_offense(node.loc.selector, message: message) do |corrector| corrector.remove(node.loc.dot.join(node.loc.end || node.loc.selector)) end end # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity alias on_csend on_send private def hash_or_set_with_block?(node) return false if !node.method?(:to_h) && !node.method?(:to_set) node.parent&.any_block_type? || node.last_argument&.block_pass_type? end def find_receiver(node) receiver = node.receiver return unless receiver while receiver.begin_type? break unless receiver.children.one? receiver = receiver.children.first end receiver end def literal_receiver?(node, receiver) return false unless receiver receiver.type?(*LITERAL_NODE_TYPES[node.method_name]) end def constructor?(node, receiver) matcher = CONSTRUCTOR_MAPPING[node.method_name] return false unless matcher public_send(matcher, receiver) && !constructor_suppresses_exceptions?(receiver) end def constructor_suppresses_exceptions?(receiver) # If the constructor suppresses exceptions with `exception: false`, it is possible # it could return `nil`, and therefore a chained conversion is not redundant. receiver.arguments.any? { |arg| exception_false_keyword_argument?(arg) } end def chained_conversion?(node, receiver) return false unless receiver&.call_type? receiver.method?(node.method_name) end def chained_to_typed_method?(node, receiver) return false unless receiver&.call_type? TYPED_METHODS.fetch(node.method_name, []).include?(receiver.method_name) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/ordered_magic_comments.rb
lib/rubocop/cop/lint/ordered_magic_comments.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks the proper ordering of magic comments and whether # a magic comment is not placed before a shebang. # # @safety # This cop's autocorrection is unsafe because file encoding may change. # # @example # # bad # # # frozen_string_literal: true # # encoding: ascii # p [''.frozen?, ''.encoding] #=> [true, #<Encoding:UTF-8>] # # # good # # # encoding: ascii # # frozen_string_literal: true # p [''.frozen?, ''.encoding] #=> [true, #<Encoding:US-ASCII>] # # # good # # #!/usr/bin/env ruby # # encoding: ascii # # frozen_string_literal: true # p [''.frozen?, ''.encoding] #=> [true, #<Encoding:US-ASCII>] # class OrderedMagicComments < Base include FrozenStringLiteral extend AutoCorrector MSG = 'The encoding magic comment should precede all other magic comments.' def on_new_investigation return if processed_source.buffer.source.empty? encoding_line, frozen_string_literal_line = magic_comment_lines return unless encoding_line && frozen_string_literal_line return if encoding_line < frozen_string_literal_line range = processed_source.buffer.line_range(encoding_line + 1) add_offense(range) do |corrector| autocorrect(corrector, encoding_line, frozen_string_literal_line) end end private def autocorrect(corrector, encoding_line, frozen_string_literal_line) range1 = processed_source.buffer.line_range(encoding_line + 1) range2 = processed_source.buffer.line_range(frozen_string_literal_line + 1) corrector.replace(range1, range2.source) corrector.replace(range2, range1.source) end def magic_comment_lines lines = [nil, nil] leading_magic_comments.each.with_index do |comment, index| if comment.encoding_specified? lines[0] = index elsif comment.frozen_string_literal_specified? lines[1] = index end return lines if lines[0] && lines[1] end lines end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/or_assignment_to_constant.rb
lib/rubocop/cop/lint/or_assignment_to_constant.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for unintended or-assignment to a constant. # # Constants should always be assigned in the same location. And its value # should always be the same. If constants are assigned in multiple # locations, the result may vary depending on the order of `require`. # # @safety # This cop is unsafe because code that is already conditionally # assigning a constant may have its behavior changed by autocorrection. # # @example # # # bad # CONST ||= 1 # # # good # CONST = 1 # class OrAssignmentToConstant < Base extend AutoCorrector MSG = 'Avoid using or-assignment with constants.' def on_or_asgn(node) return unless node.lhs&.casgn_type? add_offense(node.loc.operator) do |corrector| next if node.each_ancestor(:any_def).any? corrector.replace(node.loc.operator, '=') end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/literal_assignment_in_condition.rb
lib/rubocop/cop/lint/literal_assignment_in_condition.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for literal assignments in the conditions of `if`, `while`, and `until`. # It emulates the following Ruby warning: # # [source,console] # ---- # $ ruby -we 'if x = true; end' # -e:1: warning: found `= literal' in conditional, should be == # ---- # # As a lint cop, it cannot be determined if `==` is appropriate as intended, # therefore this cop does not provide autocorrection. # # @example # # # bad # if x = 42 # do_something # end # # # good # if x == 42 # do_something # end # # # good # if x = y # do_something # end # class LiteralAssignmentInCondition < Base MSG = "Don't use literal assignment `= %<literal>s` in conditional, " \ 'should be `==` or non-literal operand.' def on_if(node) traverse_node(node.condition) do |asgn_node| next unless asgn_node.loc.operator rhs = asgn_node.rhs next if !all_literals?(rhs) || parallel_assignment_with_splat_operator?(rhs) range = offense_range(asgn_node, rhs) add_offense(range, message: format(MSG, literal: rhs.source)) end end alias on_while on_if alias on_until on_if private def traverse_node(node, &block) yield node if node.equals_asgn? node.each_child_node { |child| traverse_node(child, &block) } end def all_literals?(node) case node.type when :dstr, :xstr false when :array node.values.all? { |value| all_literals?(value) } when :hash (node.values + node.keys).all? { |item| all_literals?(item) } else node.respond_to?(:literal?) && node.literal? end end def parallel_assignment_with_splat_operator?(node) node.array_type? && node.values.first&.splat_type? end def offense_range(asgn_node, rhs) asgn_node.loc.operator.join(rhs.source_range.end) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/refinement_import_methods.rb
lib/rubocop/cop/lint/refinement_import_methods.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks if `include` or `prepend` is called in `refine` block. # These methods are deprecated and should be replaced with `Refinement#import_methods`. # # It emulates deprecation warnings in Ruby 3.1. Functionality has been removed in Ruby 3.2. # # @safety # This cop's autocorrection is unsafe because `include M` will affect the included class # if any changes are made to module `M`. # On the other hand, `import_methods M` uses a snapshot of method definitions, # thus it will not be affected if module `M` changes. # # @example # # # bad # refine Foo do # include Bar # end # # # bad # refine Foo do # prepend Bar # end # # # good # refine Foo do # import_methods Bar # end # class RefinementImportMethods < Base extend TargetRubyVersion MSG = 'Use `import_methods` instead of `%<current>s` because it is deprecated in Ruby 3.1.' RESTRICT_ON_SEND = %i[include prepend].freeze minimum_target_ruby_version 3.1 def on_send(node) return if node.receiver return unless (parent = node.parent) return unless parent.block_type? && parent.method?(:refine) add_offense(node.loc.selector, message: format(MSG, current: node.method_name)) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/constant_definition_in_block.rb
lib/rubocop/cop/lint/constant_definition_in_block.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Do not define constants within a block, since the block's scope does not # isolate or namespace the constant in any way. # # If you are trying to define that constant once, define it outside of # the block instead, or use a variable or method if defining the constant # in the outer scope would be problematic. # # For meta-programming, use `const_set`. # # @example # # bad # task :lint do # FILES_TO_LINT = Dir['lib/*.rb'] # end # # # bad # describe 'making a request' do # class TestRequest; end # end # # # bad # module M # extend ActiveSupport::Concern # included do # LIST = [] # end # end # # # good # task :lint do # files_to_lint = Dir['lib/*.rb'] # end # # # good # describe 'making a request' do # let(:test_request) { Class.new } # # see also `stub_const` for RSpec # end # # # good # module M # extend ActiveSupport::Concern # included do # const_set(:LIST, []) # end # end # # @example AllowedMethods: ['enums'] (default) # # good # # # `enums` for Typed Enums via `T::Enum` in Sorbet. # # https://sorbet.org/docs/tenum # class TestEnum < T::Enum # enums do # Foo = new("foo") # end # end # class ConstantDefinitionInBlock < Base include AllowedMethods MSG = 'Do not define constants this way within a block.' # @!method constant_assigned_in_block?(node) def_node_matcher :constant_assigned_in_block?, <<~PATTERN ({^any_block [^begin ^^any_block]} nil? ...) PATTERN # @!method module_defined_in_block?(node) def_node_matcher :module_defined_in_block?, <<~PATTERN ({^any_block [^begin ^^any_block]} ...) PATTERN def on_casgn(node) return if !constant_assigned_in_block?(node) || allowed_method?(method_name(node)) add_offense(node) end def on_class(node) return if !module_defined_in_block?(node) || allowed_method?(method_name(node)) add_offense(node) end alias on_module on_class private def method_name(node) node.ancestors.find(&:any_block_type?).method_name end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/suppressed_exception_in_number_conversion.rb
lib/rubocop/cop/lint/suppressed_exception_in_number_conversion.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for cases where exceptions unrelated to the numeric constructors `Integer()`, # `Float()`, `BigDecimal()`, `Complex()`, and `Rational()` may be unintentionally swallowed. # # @safety # The cop is unsafe for autocorrection because unexpected errors occurring in the argument # passed to numeric constructor (e.g., `Integer()`) can lead to incompatible behavior. # For example, changing it to `Integer(potential_exception_method_call, exception: false)` # ensures that exceptions raised by `potential_exception_method_call` are not ignored. # # [source,ruby] # ---- # Integer(potential_exception_method_call) rescue nil # ---- # # @example # # # bad # Integer(arg) rescue nil # # # bad # begin # Integer(arg) # rescue # nil # end # # # bad # begin # Integer(arg) # rescue # end # # # good # Integer(arg, exception: false) # class SuppressedExceptionInNumberConversion < Base extend AutoCorrector extend TargetRubyVersion MSG = 'Use `%<prefer>s` instead.' EXPECTED_EXCEPTION_CLASSES = %w[ArgumentError TypeError ::ArgumentError ::TypeError].freeze # @!method numeric_constructor_rescue_nil(node) def_node_matcher :numeric_constructor_rescue_nil, <<~PATTERN (rescue $#numeric_method? (resbody nil? nil? (nil)) nil?) PATTERN # @!method begin_numeric_constructor_rescue_nil(node) def_node_matcher :begin_numeric_constructor_rescue_nil, <<~PATTERN (kwbegin (rescue $#numeric_method? (resbody $_? nil? {(nil) nil?}) nil?)) PATTERN # @!method numeric_method?(node) def_node_matcher :numeric_method?, <<~PATTERN { (call #constructor_receiver? {:Integer :BigDecimal :Complex :Rational} _ _?) (call #constructor_receiver? :Float _) } PATTERN # @!method constructor_receiver?(node) def_node_matcher :constructor_receiver?, <<~PATTERN {nil? (const {nil? cbase} :Kernel)} PATTERN minimum_target_ruby_version 2.6 # rubocop:disable Metrics/AbcSize def on_rescue(node) if (method, exception_classes = begin_numeric_constructor_rescue_nil(node.parent)) return unless expected_exception_classes_only?(exception_classes) node = node.parent else return unless (method = numeric_constructor_rescue_nil(node)) end arguments = method.arguments.map(&:source) << 'exception: false' prefer = "#{method.method_name}(#{arguments.join(', ')})" prefer = "#{method.receiver.source}#{method.loc.dot.source}#{prefer}" if method.receiver add_offense(node, message: format(MSG, prefer: prefer)) do |corrector| corrector.replace(node, prefer) end end # rubocop:enable Metrics/AbcSize private def expected_exception_classes_only?(exception_classes) return true unless (arguments = exception_classes.first) (arguments.values.map(&:source) - EXPECTED_EXCEPTION_CLASSES).none? end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/assignment_in_condition.rb
lib/rubocop/cop/lint/assignment_in_condition.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for assignments in the conditions of # if/while/until. # # `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." # # @safety # This cop's autocorrection is unsafe because it assumes that # the author meant to use an assignment result as a condition. # # @example # # bad # if some_var = value # do_something # end # # # good # if some_var == value # do_something # end # # @example AllowSafeAssignment: true (default) # # good # if (some_var = value) # do_something # end # # @example AllowSafeAssignment: false # # bad # if (some_var = value) # do_something # end # class AssignmentInCondition < Base extend AutoCorrector include SafeAssignment MSG_WITH_SAFE_ASSIGNMENT_ALLOWED = 'Use `==` if you meant to do a comparison or wrap the expression ' \ 'in parentheses to indicate you meant to assign in a ' \ 'condition.' MSG_WITHOUT_SAFE_ASSIGNMENT_ALLOWED = 'Use `==` if you meant to do a comparison or move the assignment ' \ 'up out of the condition.' ASGN_TYPES = [:begin, *AST::Node::EQUALS_ASSIGNMENTS, :send, :csend].freeze def on_if(node) traverse_node(node.condition) do |asgn_node| next :skip_children if skip_children?(asgn_node) next if allowed_construct?(asgn_node) add_offense(asgn_node.loc.operator) do |corrector| next unless safe_assignment_allowed? corrector.wrap(asgn_node, '(', ')') end end end alias on_while on_if alias on_until on_if private def message(_node) if safe_assignment_allowed? MSG_WITH_SAFE_ASSIGNMENT_ALLOWED else MSG_WITHOUT_SAFE_ASSIGNMENT_ALLOWED end end def allowed_construct?(asgn_node) asgn_node.begin_type? || conditional_assignment?(asgn_node) end def conditional_assignment?(asgn_node) !asgn_node.loc.operator end def skip_children?(asgn_node) (asgn_node.call_type? && !asgn_node.assignment_method?) || empty_condition?(asgn_node) || (safe_assignment_allowed? && safe_assignment?(asgn_node)) end def traverse_node(node, &block) # if the node is a block, any assignments are irrelevant return if node.any_block_type? result = yield node if ASGN_TYPES.include?(node.type) return if result == :skip_children node.each_child_node { |child| traverse_node(child, &block) } end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/it_without_arguments_in_block.rb
lib/rubocop/cop/lint/it_without_arguments_in_block.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Emulates the following Ruby warning in Ruby 3.3. # # [source,ruby] # ---- # $ ruby -e '0.times { it }' # -e:1: warning: `it` calls without arguments will refer to the first block param in Ruby 3.4; # use it() or self.it # ---- # # `it` calls without arguments will refer to the first block param in Ruby 3.4. # So use `it()` or `self.it` to ensure compatibility. # # @example # # # bad # do_something { it } # # # good # do_something { it() } # do_something { self.it } # class ItWithoutArgumentsInBlock < Base include NodePattern::Macros extend TargetRubyVersion maximum_target_ruby_version 3.3 MSG = '`it` calls without arguments will refer to the first block param in Ruby 3.4; ' \ 'use `it()` or `self.it`.' RESTRICT_ON_SEND = %i[it].freeze def on_send(node) return unless (block_node = node.each_ancestor(:block).first) return unless block_node.arguments.empty_and_without_delimiters? add_offense(node) if deprecated_it_method?(node) end def deprecated_it_method?(node) !node.receiver && node.arguments.empty? && !node.parenthesized? && !node.block_literal? end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/utils/nil_receiver_checker.rb
lib/rubocop/cop/lint/utils/nil_receiver_checker.rb
# frozen_string_literal: true module RuboCop module Cop module Lint module Utils # Utility class that checks if the receiver can't be nil. class NilReceiverChecker NIL_METHODS = (nil.methods + %i[!]).to_set.freeze def initialize(receiver, additional_nil_methods) @receiver = receiver @additional_nil_methods = additional_nil_methods @checked_nodes = {}.compare_by_identity end def cant_be_nil? sole_condition_of_parent_if?(@receiver) || _cant_be_nil?(@receiver.parent, @receiver) end private # rubocop:disable Metrics def _cant_be_nil?(node, receiver) return false unless node # For some nodes, we check their parent and then some children for these parents. # This is added to avoid infinite loops. return false if @checked_nodes.key?(node) @checked_nodes[node] = true case node.type when :def, :defs, :class, :module, :sclass return false when :send return non_nil_method?(node.method_name) if node.receiver == receiver node.arguments.each do |argument| return true if _cant_be_nil?(argument, receiver) end return true if _cant_be_nil?(node.receiver, receiver) when :begin return true if _cant_be_nil?(node.children.first, receiver) when :if, :case return true if _cant_be_nil?(node.condition, receiver) when :and, :or return true if _cant_be_nil?(node.lhs, receiver) when :pair if _cant_be_nil?(node.key, receiver) || _cant_be_nil?(node.value, receiver) return true end when :when node.each_condition do |condition| return true if _cant_be_nil?(condition, receiver) end when :lvasgn, :ivasgn, :cvasgn, :gvasgn, :casgn return true if _cant_be_nil?(node.expression, receiver) end # Due to how `if/else` are implemented (`elsif` is a child of `if` or another `elsif`), # using left_siblings will not work correctly for them. if !else_branch?(node) || (node.if_type? && !node.elsif?) node.left_siblings.reverse_each do |sibling| next unless sibling.is_a?(AST::Node) return true if _cant_be_nil?(sibling, receiver) end end if node.parent _cant_be_nil?(node.parent, receiver) else false end end # rubocop:enable Metrics def non_nil_method?(method_name) !NIL_METHODS.include?(method_name) && !@additional_nil_methods.include?(method_name) end # rubocop:disable Metrics/PerceivedComplexity def sole_condition_of_parent_if?(node) parent = node.parent while parent if parent.if_type? if parent.condition == node return true elsif parent.elsif? parent = find_top_if(parent) end elsif else_branch?(parent) # Find the top `if` for `else`. parent = parent.parent end parent = parent&.parent end false end # rubocop:enable Metrics/PerceivedComplexity def else_branch?(node) node.parent&.if_type? && node.parent.else_branch == node end def find_top_if(node) node = node.parent while node.elsif? node end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/generator/configuration_injector.rb
lib/rubocop/cop/generator/configuration_injector.rb
# frozen_string_literal: true module RuboCop module Cop class Generator # A class that injects a require directive into the root RuboCop file. # It looks for other directives that require files in the same (cop) # namespace and injects the provided one in alpha class ConfigurationInjector TEMPLATE = <<~YAML %<badge>s: Description: 'TODO: Write a description of the cop.' Enabled: pending VersionAdded: '%<version_added>s' YAML def initialize(configuration_file_path:, badge:, version_added: '<<next>>') @configuration_file_path = configuration_file_path @badge = badge @version_added = version_added @output = output end def inject target_line = find_target_line if target_line configuration_entries.insert(target_line, "#{new_configuration_entry}\n") else configuration_entries.push("\n#{new_configuration_entry}") end File.write(configuration_file_path, configuration_entries.join) yield if block_given? end private attr_reader :configuration_file_path, :badge, :version_added, :output def configuration_entries @configuration_entries ||= File.readlines(configuration_file_path) end def new_configuration_entry format(TEMPLATE, badge: badge, version_added: version_added) end def find_target_line configuration_entries.find.with_index do |line, index| next unless cop_name_line?(line) return index if badge.to_s < line end nil end def cop_name_line?(yaml) !/^[\s#]/.match?(yaml) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/generator/require_file_injector.rb
lib/rubocop/cop/generator/require_file_injector.rb
# frozen_string_literal: true module RuboCop module Cop class Generator # A class that injects a require directive into the root RuboCop file. # It looks for other directives that require files in the same (cop) # namespace and injects the provided one in alpha class RequireFileInjector REQUIRE_PATH = /require_relative ['"](.+)['"]/.freeze def initialize(source_path:, root_file_path:, output: $stdout) @source_path = Pathname(source_path) @root_file_path = Pathname(root_file_path) @require_entries = File.readlines(root_file_path) @output = output end def inject return if require_exists? || !target_line File.write(root_file_path, updated_directives) require = injectable_require_directive.chomp output.puts "[modify] #{root_file_path} - `#{require}` was injected." end private attr_reader :require_entries, :root_file_path, :source_path, :output def require_exists? require_entries.any?(injectable_require_directive) end def updated_directives require_entries.insert(target_line, injectable_require_directive).join end def target_line @target_line ||= begin in_the_same_department = false inject_parts = require_path_fragments(injectable_require_directive) require_entries.find.with_index do |entry, index| current_entry_parts = require_path_fragments(entry) if inject_parts[0..-2] == current_entry_parts[0..-2] in_the_same_department = true break index if inject_parts.last < current_entry_parts.last elsif in_the_same_department break index end end || require_entries.size end end def require_path_fragments(require_directive) path = require_directive.match(REQUIRE_PATH) path ? path.captures.first.split('/') : [] end def injectable_require_directive "require_relative '#{require_path}'\n" end def require_path path = source_path.relative_path_from(root_file_path.dirname) path.to_s.delete_suffix('.rb') end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/method_called_on_do_end_block.rb
lib/rubocop/cop/style/method_called_on_do_end_block.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for methods called on a do...end block. The point of # this check is that it's easy to miss the call tacked on to the block # when reading code. # # @example # # bad # a do # b # end.c # # # good # a { b }.c # # # good # foo = a do # b # end # foo.c class MethodCalledOnDoEndBlock < Base include RangeHelp MSG = 'Avoid chaining a method call on a do...end block.' def on_block(node) # If the method that is chained on the do...end block is itself a # method with a block, we allow it. It's pretty safe to assume that # these calls are not missed by anyone reading code. We also want to # avoid double reporting of offenses checked by the # MultilineBlockChain cop. ignore_node(node.send_node) end alias on_numblock on_block alias on_itblock on_block def on_send(node) return if ignored_node?(node) return unless (receiver = node.receiver) return unless receiver.any_block_type? && receiver.keywords? range = range_between(receiver.loc.end.begin_pos, node.source_range.end_pos) add_offense(range) end alias on_csend on_send end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/min_max_comparison.rb
lib/rubocop/cop/style/min_max_comparison.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Enforces the use of `max` or `min` instead of comparison for greater or less. # # NOTE: It can be used if you want to present limit or threshold in Ruby 2.7+. # That it is slow though. So autocorrection will apply generic `max` or `min`: # # [source,ruby] # ---- # a.clamp(b..) # Same as `[a, b].max` # a.clamp(..b) # Same as `[a, b].min` # ---- # # @safety # This cop is unsafe because even if a value has `<` or `>` method, # it is not necessarily `Comparable`. # # @example # # # bad # a > b ? a : b # a >= b ? a : b # # # good # [a, b].max # # # bad # a < b ? a : b # a <= b ? a : b # # # good # [a, b].min # class MinMaxComparison < Base extend AutoCorrector include RangeHelp MSG = 'Use `%<prefer>s` instead.' GREATER_OPERATORS = %i[> >=].freeze LESS_OPERATORS = %i[< <=].freeze COMPARISON_OPERATORS = (GREATER_OPERATORS + LESS_OPERATORS).to_set.freeze # @!method comparison_condition(node, name) def_node_matcher :comparison_condition, <<~PATTERN { (send $_lhs $COMPARISON_OPERATORS $_rhs) (begin (send $_lhs $COMPARISON_OPERATORS $_rhs)) } PATTERN def on_if(node) lhs, operator, rhs = comparison_condition(node.condition) return unless operator if_branch = node.if_branch else_branch = node.else_branch preferred_method = preferred_method(operator, lhs, rhs, if_branch, else_branch) return unless preferred_method replacement = "[#{lhs.source}, #{rhs.source}].#{preferred_method}" add_offense(node, message: format(MSG, prefer: replacement)) do |corrector| autocorrect(corrector, node, replacement) end end private def preferred_method(operator, lhs, rhs, if_branch, else_branch) if lhs == if_branch && rhs == else_branch GREATER_OPERATORS.include?(operator) ? 'max' : 'min' elsif lhs == else_branch && rhs == if_branch LESS_OPERATORS.include?(operator) ? 'max' : 'min' end end def autocorrect(corrector, node, replacement) if node.elsif? corrector.remove(range_between(node.parent.loc.else.begin_pos, node.loc.else.begin_pos)) corrector.replace(node.else_branch, replacement) else corrector.replace(node, replacement) end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/proc.rb
lib/rubocop/cop/style/proc.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for uses of Proc.new where Kernel#proc # would be more appropriate. # # @example # # bad # p = Proc.new { |n| puts n } # # # good # p = proc { |n| puts n } # class Proc < Base extend AutoCorrector MSG = 'Use `proc` instead of `Proc.new`.' # @!method proc_new?(node) def_node_matcher :proc_new?, '(any_block $(send (const {nil? cbase} :Proc) :new) ...)' def on_block(node) proc_new?(node) do |block_method| add_offense(block_method) do |corrector| corrector.replace(block_method, 'proc') end end end alias on_numblock on_block alias on_itblock on_block end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/even_odd.rb
lib/rubocop/cop/style/even_odd.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for places where `Integer#even?` or `Integer#odd?` # can be used. # # @example # # # bad # if x % 2 == 0 # end # # # good # if x.even? # end class EvenOdd < Base extend AutoCorrector MSG = 'Replace with `Integer#%<method>s?`.' RESTRICT_ON_SEND = %i[== !=].freeze # @!method even_odd_candidate?(node) def_node_matcher :even_odd_candidate?, <<~PATTERN (send {(send $_ :% (int 2)) (begin (send $_ :% (int 2)))} ${:== :!=} (int ${0 1})) PATTERN def on_send(node) even_odd_candidate?(node) do |base_number, method, arg| replacement_method = replacement_method(arg, method) add_offense(node, message: format(MSG, method: replacement_method)) do |corrector| correction = "#{base_number.source}.#{replacement_method}?" corrector.replace(node, correction) end end end private def replacement_method(arg, method) case arg when 0 method == :== ? :even : :odd when 1 method == :== ? :odd : :even end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/inverse_methods.rb
lib/rubocop/cop/style/inverse_methods.rb
# frozen_string_literal: true module RuboCop module Cop module Style # 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`. # # @safety # This cop is unsafe because it cannot be guaranteed that the method # and its inverse method are both defined on receiver, and also are # actually inverse of each other. # # @example # # bad # !foo.none? # !foo.any? { |f| f.even? } # !foo.blank? # !(foo == bar) # foo.select { |f| !f.even? } # foo.reject { |f| f != 7 } # # # good # foo.none? # foo.blank? # foo.any? { |f| f.even? } # foo != bar # foo == bar # !!('foo' =~ /^\w+$/) # !(foo.class < Numeric) # Checking class hierarchy is allowed # # Blocks with guard clauses are ignored: # foo.select do |f| # next if f.zero? # f != 1 # end class InverseMethods < Base include RangeHelp extend AutoCorrector MSG = 'Use `%<inverse>s` instead of inverting `%<method>s`.' CLASS_COMPARISON_METHODS = %i[<= >= < >].freeze SAFE_NAVIGATION_INCOMPATIBLE_METHODS = (CLASS_COMPARISON_METHODS + %i[any? none?]).freeze EQUALITY_METHODS = %i[== != =~ !~ <= >= < >].freeze NEGATED_EQUALITY_METHODS = %i[!= !~].freeze CAMEL_CASE = /[A-Z]+[a-z]+/.freeze RESTRICT_ON_SEND = [:!].freeze def self.autocorrect_incompatible_with [Style::Not, Style::SymbolProc] end # @!method inverse_candidate?(node) def_node_matcher :inverse_candidate?, <<~PATTERN { (send $(call $(...) $_ $...) :!) (send (any_block $(call $(...) $_) $...) :!) (send (begin $(call $(...) $_ $...)) :!) } PATTERN # @!method inverse_block?(node) def_node_matcher :inverse_block?, <<~PATTERN (any_block $(call (...) $_) ... { $(call ... :!) $(send (...) {:!= :!~} ...) (begin ... $(call ... :!)) (begin ... $(send (...) {:!= :!~} ...)) }) PATTERN def on_send(node) inverse_candidate?(node) do |method_call, lhs, method, rhs| return unless inverse_methods.key?(method) return if negated?(node) || safe_navigation_incompatible?(method_call) return if part_of_ignored_node?(node) return if possible_class_hierarchy_check?(lhs, rhs, method) add_offense(node, message: message(method, inverse_methods[method])) do |corrector| correct_inverse_method(corrector, node) end end end alias on_csend on_send 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: message(method, inverse_blocks[method])) do |corrector| correct_inverse_block(corrector, node) end end end alias on_numblock on_block alias on_itblock on_block private def correct_inverse_method(corrector, node) method_call, _lhs, method, _rhs = inverse_candidate?(node) return unless method_call && method corrector.remove(not_to_receiver(node, method_call)) corrector.replace(method_call.loc.selector, inverse_methods[method].to_s) remove_end_parenthesis(corrector, node, method, method_call) end 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 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 def inverse_methods @inverse_methods ||= cop_config['InverseMethods'] .merge(cop_config['InverseMethods'].invert) end def inverse_blocks @inverse_blocks ||= cop_config['InverseBlocks'].merge(cop_config['InverseBlocks'].invert) end def negated?(node) node.parent.respond_to?(:method?) && node.parent.method?(:!) end def not_to_receiver(node, method_call) node.loc.selector.begin.join(method_call.source_range.begin) end def end_parentheses(node, method_call) method_call.source_range.end.join(node.source_range.end) end def safe_navigation_incompatible?(node) return false unless node.csend_type? SAFE_NAVIGATION_INCOMPATIBLE_METHODS.include?(node.method_name) end # When comparing classes, `!(Integer < Numeric)` is not the same as # `Integer > Numeric`. def possible_class_hierarchy_check?(lhs, rhs, method) CLASS_COMPARISON_METHODS.include?(method) && (camel_case_constant?(lhs) || (rhs.size == 1 && camel_case_constant?(rhs.first))) end def camel_case_constant?(node) node.const_type? && CAMEL_CASE.match?(node.source) end def dot_range(loc) range_between(loc.dot.begin_pos, loc.expression.end_pos) end 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 def message(method, inverse) format(MSG, method: method, inverse: inverse) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/comment_annotation.rb
lib/rubocop/cop/style/comment_annotation.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks that comment annotation keywords are written according # to guidelines. # # Annotation keywords can be specified by overriding the cop's `Keywords` # configuration. Keywords are allowed to be single words or phrases. # # NOTE: With a multiline comment block (where each line is only a # comment), only the first line will be able to register an offense, even # if an annotation keyword starts another line. This is done to prevent # incorrect registering of keywords (eg. `review`) inside a paragraph as an # annotation. # # @example RequireColon: true (default) # # bad # # TODO make better # # # good # # TODO: make better # # # bad # # TODO:make better # # # good # # TODO: make better # # # bad # # fixme: does not work # # # good # # FIXME: does not work # # # bad # # Optimize does not work # # # good # # OPTIMIZE: does not work # # @example RequireColon: false # # bad # # TODO: make better # # # good # # TODO make better # # # bad # # fixme does not work # # # good # # FIXME does not work # # # bad # # Optimize does not work # # # good # # OPTIMIZE does not work class CommentAnnotation < Base include RangeHelp extend AutoCorrector MSG_COLON_STYLE = 'Annotation keywords like `%<keyword>s` should be all ' \ 'upper case, followed by a colon, and a space, ' \ 'then a note describing the problem.' MSG_SPACE_STYLE = 'Annotation keywords like `%<keyword>s` should be all ' \ 'upper case, followed by a space, ' \ 'then a note describing the problem.' MISSING_NOTE = 'Annotation comment, with keyword `%<keyword>s`, is missing a note.' def on_new_investigation processed_source.comments.each_with_index do |comment, index| next unless first_comment_line?(processed_source.comments, index) || inline_comment?(comment) annotation = AnnotationComment.new(comment, keywords) next unless annotation.annotation? && !annotation.correct?(colon: requires_colon?) register_offense(annotation) end end private def register_offense(annotation) range = annotation_range(annotation) message = if annotation.note requires_colon? ? MSG_COLON_STYLE : MSG_SPACE_STYLE else MISSING_NOTE end add_offense(range, message: format(message, keyword: annotation.keyword)) do |corrector| next if annotation.note.nil? correct_offense(corrector, range, annotation.keyword) end end def first_comment_line?(comments, index) index.zero? || comments[index - 1].loc.line < comments[index].loc.line - 1 end def inline_comment?(comment) !comment_line?(comment.source_range.source_line) end def annotation_range(annotation) range_between(*annotation.bounds) end def correct_offense(corrector, range, keyword) return corrector.replace(range, "#{keyword.upcase}: ") if requires_colon? corrector.replace(range, "#{keyword.upcase} ") end def requires_colon? cop_config['RequireColon'] end def keywords cop_config['Keywords'] end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/class_equality_comparison.rb
lib/rubocop/cop/style/class_equality_comparison.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Enforces the use of `Object#instance_of?` instead of class comparison # for equality. # `==`, `equal?`, and `eql?` custom method definitions are allowed by default. # These are customizable with `AllowedMethods` option. # # @safety # This cop's autocorrection is unsafe because there is no guarantee that # the constant `Foo` exists when autocorrecting `var.class.name == 'Foo'` to # `var.instance_of?(Foo)`. # # @example # # bad # var.class == Date # var.class.equal?(Date) # var.class.eql?(Date) # var.class.name == 'Date' # # # good # var.instance_of?(Date) # # @example AllowedMethods: ['==', 'equal?', 'eql?'] (default) # # good # def ==(other) # self.class == other.class && name == other.name # end # # def equal?(other) # self.class.equal?(other.class) && name.equal?(other.name) # end # # def eql?(other) # self.class.eql?(other.class) && name.eql?(other.name) # end # # @example AllowedPatterns: [] (default) # # bad # def eq(other) # self.class.eq(other.class) && name.eq(other.name) # end # # @example AllowedPatterns: ['eq'] # # good # def eq(other) # self.class.eq(other.class) && name.eq(other.name) # end # class ClassEqualityComparison < Base include RangeHelp include AllowedMethods include AllowedPattern extend AutoCorrector MSG = 'Use `instance_of?%<class_argument>s` instead of comparing classes.' RESTRICT_ON_SEND = %i[== equal? eql?].freeze CLASS_NAME_METHODS = %i[name to_s inspect].freeze # @!method class_comparison_candidate?(node) def_node_matcher :class_comparison_candidate?, <<~PATTERN (send {$(send _ :class) (send $(send _ :class) #class_name_method?)} {:== :equal? :eql?} $_) PATTERN def on_send(node) def_node = node.each_ancestor(:any_def).first return if def_node && (allowed_method?(def_node.method_name) || matches_allowed_pattern?(def_node.method_name)) class_comparison_candidate?(node) do |receiver_node, class_node| return if class_node.dstr_type? range = offense_range(receiver_node, node) class_argument = (class_name = class_name(class_node, node)) ? "(#{class_name})" : '' add_offense(range, message: format(MSG, class_argument: class_argument)) do |corrector| next unless class_name corrector.replace(range, "instance_of?#{class_argument}") end end end private def class_name(class_node, node) if class_name_method?(node.children.first.method_name) if (receiver = class_node.receiver) && class_name_method?(class_node.method_name) return receiver.source end if class_node.str_type? value = trim_string_quotes(class_node) value.prepend('::') if require_cbase?(class_node) return value elsif unable_to_determine_type?(class_node) # When a variable or return value of a method is used, it returns nil # because the type is not known and cannot be suggested. return end end class_node.source end def class_name_method?(method_name) CLASS_NAME_METHODS.include?(method_name) end def require_cbase?(class_node) class_node.each_ancestor(:class, :module).any? end def unable_to_determine_type?(class_node) class_node.variable? || class_node.call_type? end def trim_string_quotes(class_node) class_node.source.delete('"').delete("'") end def offense_range(receiver_node, node) range_between(receiver_node.loc.selector.begin_pos, node.source_range.end_pos) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_fetch_block.rb
lib/rubocop/cop/style/redundant_fetch_block.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Identifies places where `fetch(key) { value }` can be replaced by `fetch(key, value)`. # # In such cases `fetch(key, value)` method is faster than `fetch(key) { value }`. # # NOTE: The block string `'value'` in `hash.fetch(:key) { 'value' }` is detected # when frozen string literal magic comment is enabled (i.e. `# frozen_string_literal: true`), # but not when disabled. # # @safety # This cop is unsafe because it cannot be guaranteed that the receiver # does not have a different implementation of `fetch`. # # @example SafeForConstants: false (default) # # bad # hash.fetch(:key) { 5 } # hash.fetch(:key) { true } # hash.fetch(:key) { nil } # array.fetch(5) { :value } # ENV.fetch(:key) { 'value' } # # # good # hash.fetch(:key, 5) # hash.fetch(:key, true) # hash.fetch(:key, nil) # array.fetch(5, :value) # ENV.fetch(:key, 'value') # # @example SafeForConstants: true # # bad # ENV.fetch(:key) { VALUE } # # # good # ENV.fetch(:key, VALUE) # class RedundantFetchBlock < Base include FrozenStringLiteral include RangeHelp extend AutoCorrector MSG = 'Use `%<good>s` instead of `%<bad>s`.' # @!method redundant_fetch_block_candidate?(node) def_node_matcher :redundant_fetch_block_candidate?, <<~PATTERN (block $(call _ :fetch _) (args) ${nil? basic_literal? const_type?}) PATTERN def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler redundant_fetch_block_candidate?(node) do |send, body| return if should_not_check?(send, body) range = fetch_range(send, node) good = build_good_method(send, body) bad = build_bad_method(send, body) add_offense(range, message: format(MSG, good: good, bad: bad)) do |corrector| _, _, key = send.children default_value = body ? body.source : 'nil' corrector.replace(range, "fetch(#{key.source}, #{default_value})") end end end private def should_not_check?(send, body) (body&.const_type? && !check_for_constant?) || (body&.str_type? && !check_for_string?) || rails_cache?(send.receiver) end # @!method rails_cache?(node) def_node_matcher :rails_cache?, <<~PATTERN (send (const _ :Rails) :cache) PATTERN def fetch_range(send, node) range_between(send.loc.selector.begin_pos, node.loc.end.end_pos) end def build_good_method(send, body) key = send.children[2].source default_value = body ? body.source : 'nil' "fetch(#{key}, #{default_value})" end def build_bad_method(send, body) key = send.children[2].source block = body ? "{ #{body.source} }" : '{}' "fetch(#{key}) #{block}" end def check_for_constant? cop_config['SafeForConstants'] end def check_for_string? frozen_string_literals_enabled? end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/multiline_in_pattern_then.rb
lib/rubocop/cop/style/multiline_in_pattern_then.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks uses of the `then` keyword in multi-line `in` statement. # # @example # # bad # case expression # in pattern then # end # # # good # case expression # in pattern # end # # # good # case expression # in pattern then do_something # end # # # good # case expression # in pattern then do_something(arg1, # arg2) # end # class MultilineInPatternThen < Base include RangeHelp extend AutoCorrector extend TargetRubyVersion minimum_target_ruby_version 2.7 MSG = 'Do not use `then` for multiline `in` statement.' def on_in_pattern(node) return if !node.then? || require_then?(node) range = node.loc.begin add_offense(range) do |corrector| corrector.remove(range_with_surrounding_space(range, side: :left, newlines: false)) end end private # Requires `then` for write `in` and its body on the same line. def require_then?(in_pattern_node) return true unless in_pattern_node.pattern.single_line? return false unless in_pattern_node.body same_line?(in_pattern_node, in_pattern_node.body) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/exact_regexp_match.rb
lib/rubocop/cop/style/exact_regexp_match.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for exact regexp match inside `Regexp` literals. # # @example # # # bad # string =~ /\Astring\z/ # string === /\Astring\z/ # string.match(/\Astring\z/) # string.match?(/\Astring\z/) # # # good # string == 'string' # # # bad # string !~ /\Astring\z/ # # # good # string != 'string' # class ExactRegexpMatch < Base extend AutoCorrector MSG = 'Use `%<prefer>s`.' RESTRICT_ON_SEND = %i[=~ === !~ match match?].freeze # @!method exact_regexp_match(node) def_node_matcher :exact_regexp_match, <<~PATTERN (call _ {:=~ :=== :!~ :match :match?} (regexp (str $_) (regopt))) PATTERN def on_send(node) return unless (receiver = node.receiver) return unless (regexp = exact_regexp_match(node)) return unless (parsed_regexp = parse_regexp(regexp)) return unless exact_match_pattern?(parsed_regexp) prefer = "#{receiver.source} #{new_method(node)} '#{parsed_regexp[1].text}'" add_offense(node, message: format(MSG, prefer: prefer)) do |corrector| corrector.replace(node, prefer) end end alias on_csend on_send private def exact_match_pattern?(parsed_regexp) tokens = parsed_regexp.map(&:token) return false unless tokens[0] == :bos && tokens[1] == :literal && tokens[2] == :eos !parsed_regexp[1].quantifier end def new_method(node) node.method?(:!~) ? '!=' : '==' end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/numeric_literals.rb
lib/rubocop/cop/style/numeric_literals.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for big numeric literals without `_` between groups # of digits in them. # # Additional allowed patterns can be added by adding regexps to # the `AllowedPatterns` configuration. All regexps are treated # as anchored even if the patterns do not contain anchors (so # `\d{4}_\d{4}` will allow `1234_5678` but not `1234_5678_9012`). # # NOTE: Even if `AllowedPatterns` are given, autocorrection will # only correct to the standard pattern of an `_` every 3 digits. # # @example # # # bad # 1000000 # 1_00_000 # 1_0000 # # # good # 1_000_000 # 1000 # # @example Strict: false (default) # # # good # 10_000_00 # typical representation of $10,000 in cents # # @example Strict: true # # # bad # 10_000_00 # typical representation of $10,000 in cents # # @example AllowedNumbers: [3000] # # # good # 3000 # You can specify allowed numbers. (e.g. port number) # class NumericLiterals < Base include IntegerNode include AllowedPattern extend AutoCorrector MSG = 'Use underscores(_) as thousands separator and separate every 3 digits with them.' DELIMITER_REGEXP = /[eE.]/.freeze # The parameter is called MinDigits (meaning the minimum number of # digits for which an offense can be registered), but essentially it's # a Max parameter (the maximum number of something that's allowed). exclude_limit 'MinDigits' def on_int(node) check(node) end def on_float(node) check(node) end private def check(node) int = integer_part(node) # TODO: handle non-decimal literals as well return if int.start_with?('0') return if allowed_numbers.include?(int) return if matches_allowed_pattern?(int) return unless int.size >= min_digits case int when /^\d+$/ register_offense(node) { self.min_digits = int.size + 1 } when /\d{4}/, short_group_regex register_offense(node) { self.config_to_allow_offenses = { 'Enabled' => false } } end end def register_offense(node, &_block) add_offense(node) do |corrector| yield corrector.replace(node, format_number(node)) end end def short_group_regex cop_config['Strict'] ? /_\d{1,2}(_|$)/ : /_\d{1,2}_/ end def format_number(node) source = node.source.gsub(/\s+/, '') int_part, additional_part = source.split(DELIMITER_REGEXP, 2) formatted_int = format_int_part(int_part) delimiter = source[DELIMITER_REGEXP] if additional_part formatted_int + delimiter + additional_part else formatted_int end end # @param int_part [String] def format_int_part(int_part) int_part = Integer(int_part) formatted_int = int_part.abs.to_s.reverse.gsub(/...(?=.)/, '\&_').reverse formatted_int.insert(0, '-') if int_part.negative? formatted_int end def min_digits cop_config['MinDigits'] end def allowed_numbers cop_config.fetch('AllowedNumbers', []).map(&:to_s) end def allowed_patterns # Convert the patterns to be anchored super.map { |regexp| /\A#{regexp}\z/ } end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/data_inheritance.rb
lib/rubocop/cop/style/data_inheritance.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for inheritance from `Data.define` to avoid creating the anonymous parent class. # Inheriting from `Data.define` adds a superfluous level in inheritance tree. # # @safety # Autocorrection is unsafe because it will change the inheritance # tree (e.g. return value of `Module#ancestors`) of the constant. # # @example # # bad # class Person < Data.define(:first_name, :last_name) # def age # 42 # end # end # # Person.ancestors # # => [Person, #<Class:0x000000010b4e14a0>, Data, (...)] # # # good # Person = Data.define(:first_name, :last_name) do # def age # 42 # end # end # # Person.ancestors # # => [Person, Data, (...)] class DataInheritance < Base include RangeHelp extend AutoCorrector extend TargetRubyVersion MSG = "Don't extend an instance initialized by `Data.define`. " \ 'Use a block to customize the class.' minimum_target_ruby_version 3.2 def on_class(node) return unless data_define?(node.parent_class) add_offense(node.parent_class) do |corrector| corrector.remove(range_with_surrounding_space(node.loc.keyword, newlines: false)) corrector.replace(node.loc.operator, '=') correct_parent(node.parent_class, corrector) end end # @!method data_define?(node) def_node_matcher :data_define?, <<~PATTERN {(send (const {nil? cbase} :Data) :define ...) (block (send (const {nil? cbase} :Data) :define ...) ...)} PATTERN private def correct_parent(parent, corrector) if parent.block_type? corrector.remove(range_with_surrounding_space(parent.loc.end, newlines: false)) elsif (class_node = parent.parent).body.nil? corrector.remove(range_for_empty_class_body(class_node, parent)) else corrector.insert_after(parent, ' do') end end def range_for_empty_class_body(class_node, data_define) if class_node.single_line? range_between(data_define.source_range.end_pos, class_node.source_range.end_pos) else range_by_whole_lines(class_node.loc.end, include_final_newline: true) end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/mixin_usage.rb
lib/rubocop/cop/style/mixin_usage.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks that `include`, `extend` and `prepend` statements appear # inside classes and modules, not at the top level, so as to not affect # the behavior of `Object`. # # @example # # bad # include M # # class C # end # # # bad # extend M # # class C # end # # # bad # prepend M # # class C # end # # # good # class C # include M # end # # # good # class C # extend M # end # # # good # class C # prepend M # end class MixinUsage < Base MSG = '`%<statement>s` is used at the top level. Use inside `class` or `module`.' RESTRICT_ON_SEND = %i[include extend prepend].freeze # @!method include_statement(node) def_node_matcher :include_statement, <<~PATTERN (send nil? ${:include :extend :prepend} const) PATTERN # @!method in_top_level_scope?(node) def_node_matcher :in_top_level_scope?, <<~PATTERN { root? # either at the top level ^[ {kwbegin begin if def} # or wrapped within one of these #in_top_level_scope? ] # that is in top level scope } PATTERN def on_send(node) include_statement(node) do |statement| return unless in_top_level_scope?(node) add_offense(node, message: format(MSG, statement: statement)) end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/for.rb
lib/rubocop/cop/style/for.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Looks for uses of the `for` keyword or `each` method. The # preferred alternative is set in the EnforcedStyle configuration # parameter. An `each` call with a block on a single line is always # allowed. # # @example EnforcedStyle: each (default) # # bad # def foo # for n in [1, 2, 3] do # puts n # end # end # # # good # def foo # [1, 2, 3].each do |n| # puts n # end # end # # @example EnforcedStyle: for # # bad # def foo # [1, 2, 3].each do |n| # puts n # end # end # # # good # def foo # for n in [1, 2, 3] do # puts n # end # end # # @safety # This cop's autocorrection is unsafe because the scope of # variables is different between `each` and `for`. # class For < Base include ConfigurableEnforcedStyle extend AutoCorrector EACH_LENGTH = 'each'.length PREFER_EACH = 'Prefer `each` over `for`.' PREFER_FOR = 'Prefer `for` over `each`.' def on_for(node) if style == :each add_offense(node, message: PREFER_EACH) do |corrector| ForToEachCorrector.new(node).call(corrector) opposite_style_detected end else correct_style_detected end end def on_block(node) return unless suspect_enumerable?(node) if style == :for return unless node.receiver add_offense(node, message: PREFER_FOR) do |corrector| EachToForCorrector.new(node).call(corrector) opposite_style_detected end else correct_style_detected end end alias on_numblock on_block alias on_itblock on_block private def suspect_enumerable?(node) node.multiline? && node.method?(:each) && !node.send_node.arguments? end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/struct_inheritance.rb
lib/rubocop/cop/style/struct_inheritance.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for inheritance from `Struct.new`. Inheriting from `Struct.new` # adds a superfluous level in inheritance tree. # # @safety # Autocorrection is unsafe because it will change the inheritance # tree (e.g. return value of `Module#ancestors`) of the constant. # # @example # # bad # class Person < Struct.new(:first_name, :last_name) # def age # 42 # end # end # # Person.ancestors # # => [Person, #<Class:0x000000010b4e14a0>, Struct, (...)] # # # good # Person = Struct.new(:first_name, :last_name) do # def age # 42 # end # end # # Person.ancestors # # => [Person, Struct, (...)] class StructInheritance < Base include RangeHelp extend AutoCorrector MSG = "Don't extend an instance initialized by `Struct.new`. " \ 'Use a block to customize the struct.' def on_class(node) return unless struct_constructor?(node.parent_class) add_offense(node.parent_class) do |corrector| corrector.remove(range_with_surrounding_space(node.loc.keyword, newlines: false)) corrector.replace(node.loc.operator, '=') correct_parent(node.parent_class, corrector) end end # @!method struct_constructor?(node) def_node_matcher :struct_constructor?, <<~PATTERN {(send (const {nil? cbase} :Struct) :new ...) (block (send (const {nil? cbase} :Struct) :new ...) ...)} PATTERN private def correct_parent(parent, corrector) if parent.block_type? corrector.remove(range_with_surrounding_space(parent.loc.end, newlines: false)) elsif (class_node = parent.parent).body.nil? corrector.remove(range_for_empty_class_body(class_node, parent)) else corrector.insert_after(parent, ' do') end end def range_for_empty_class_body(class_node, struct_new) if class_node.single_line? range_between(struct_new.source_range.end_pos, class_node.source_range.end_pos) else range_by_whole_lines(class_node.loc.end, include_final_newline: true) end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/case_like_if.rb
lib/rubocop/cop/style/case_like_if.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Identifies places where `if-elsif` constructions # can be replaced with `case-when`. # # @safety # This cop is unsafe. `case` statements use `===` for equality, # so if the original conditional used a different equality operator, the # behavior may be different. # # @example MinBranchesCount: 3 (default) # # bad # if status == :active # perform_action # elsif status == :inactive || status == :hibernating # check_timeout # elsif status == :invalid # report_invalid # else # final_action # end # # # good # case status # when :active # perform_action # when :inactive, :hibernating # check_timeout # when :invalid # report_invalid # else # final_action # end # # @example MinBranchesCount: 4 # # good # if status == :active # perform_action # elsif status == :inactive || status == :hibernating # check_timeout # elsif status == :invalid # report_invalid # else # final_action # end # class CaseLikeIf < Base include RangeHelp include MinBranchesCount extend AutoCorrector MSG = 'Convert `if-elsif` to `case-when`.' def on_if(node) return unless should_check?(node) target = find_target(node.condition) return unless target conditions = [] convertible = true branch_conditions(node).each do |branch_condition| return false if regexp_with_working_captures?(branch_condition) conditions << [] convertible = collect_conditions(branch_condition, target, conditions.last) break unless convertible end return unless convertible add_offense(node) { |corrector| autocorrect(corrector, node) } end private def autocorrect(corrector, node) target = find_target(node.condition) corrector.insert_before(node, "case #{target.source}\n#{indent(node)}") branch_conditions(node).each do |branch_condition| conditions = [] collect_conditions(branch_condition, target, conditions) range = correction_range(branch_condition) branch_replacement = "when #{conditions.map(&:source).join(', ')}" corrector.replace(range, branch_replacement) end end def should_check?(node) !node.unless? && !node.elsif? && !node.modifier_form? && !node.ternary? && node.elsif_conditional? && min_branches_count?(node) end # rubocop:disable Metrics/MethodLength def find_target(node) case node.type when :begin find_target(node.children.first) when :or find_target(node.lhs) when :match_with_lvasgn lhs, rhs = *node # rubocop:disable InternalAffairs/NodeDestructuring if lhs.regexp_type? rhs elsif rhs.regexp_type? lhs end when :send find_target_in_send_node(node) end end # rubocop:enable Metrics/MethodLength def find_target_in_send_node(node) case node.method_name when :is_a? node.receiver when :==, :eql?, :equal? find_target_in_equality_node(node) when :=== node.first_argument when :include?, :cover? find_target_in_include_or_cover_node(node) when :match, :match?, :=~ find_target_in_match_node(node) end end def find_target_in_equality_node(node) argument = node.first_argument receiver = node.receiver return unless argument && receiver if argument.literal? || const_reference?(argument) receiver elsif receiver.literal? || const_reference?(receiver) argument end end def find_target_in_include_or_cover_node(node) return unless (receiver = node.receiver) node.first_argument if deparenthesize(receiver).range_type? end def find_target_in_match_node(node) argument = node.first_argument receiver = node.receiver return unless receiver if receiver.regexp_type? argument elsif argument.regexp_type? receiver end end def collect_conditions(node, target, conditions) condition = case node.type when :begin return collect_conditions(node.children.first, target, conditions) when :or return collect_conditions(node.lhs, target, conditions) && collect_conditions(node.rhs, target, conditions) when :match_with_lvasgn lhs, rhs = *node # rubocop:disable InternalAffairs/NodeDestructuring condition_from_binary_op(lhs, rhs, target) when :send condition_from_send_node(node, target) end conditions << condition if condition end # rubocop:disable Metrics/CyclomaticComplexity def condition_from_send_node(node, target) case node.method_name when :is_a? node.first_argument if node.receiver == target when :==, :eql?, :equal? condition_from_equality_node(node, target) when :=~, :match, :match? condition_from_match_node(node, target) when :=== node.receiver if node.first_argument == target when :include?, :cover? condition_from_include_or_cover_node(node, target) end end # rubocop:enable Metrics/CyclomaticComplexity def condition_from_equality_node(node, target) condition = condition_from_binary_op(node.receiver, node.first_argument, target) condition if condition && !class_reference?(condition) end def condition_from_match_node(node, target) condition_from_binary_op(node.receiver, node.first_argument, target) end def condition_from_include_or_cover_node(node, target) return unless (receiver = node.receiver) receiver = deparenthesize(receiver) receiver if receiver.range_type? && node.first_argument == target end def condition_from_binary_op(lhs, rhs, target) lhs = deparenthesize(lhs) rhs = deparenthesize(rhs) if lhs == target rhs elsif rhs == target lhs end end def branch_conditions(node) conditions = [] while node&.if_type? && !node.ternary? conditions << node.condition node = node.else_branch end conditions end def const_reference?(node) return false unless node.const_type? name = node.children[1].to_s # We can no be sure if, e.g. `C`, represents a constant or a class reference name.length > 1 && name == name.upcase end def class_reference?(node) node.const_type? && node.children[1].match?(/[[:lower:]]/) end def deparenthesize(node) node = node.children.last while node.begin_type? node end def correction_range(node) range_between(node.parent.loc.keyword.begin_pos, node.source_range.end_pos) end # Named captures work with `=~` (if regexp is on lhs) and with `match` (both sides) def regexp_with_working_captures?(node) case node.type when :match_with_lvasgn lhs, _rhs = *node # rubocop:disable InternalAffairs/NodeDestructuring node.loc.selector.source == '=~' && regexp_with_named_captures?(lhs) when :send node.method?(:match) && [node.receiver, node.first_argument].any? { |n| regexp_with_named_captures?(n) } end end def regexp_with_named_captures?(node) node.regexp_type? && node.each_capture(named: true).any? end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/map_to_set.rb
lib/rubocop/cop/style/map_to_set.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Looks for uses of `map.to_set` or `collect.to_set` that could be # written with just `to_set`. # # @safety # This cop is unsafe, as it can produce false positives if the receiver # is not an `Enumerable`. # # @example # # bad # something.map { |i| i * 2 }.to_set # # # good # something.to_set { |i| i * 2 } # # # bad # [1, 2, 3].collect { |i| i.to_s }.to_set # # # good # [1, 2, 3].to_set { |i| i.to_s } # class MapToSet < Base extend AutoCorrector include RangeHelp MSG = 'Pass a block to `to_set` instead of calling `%<method>s.to_set`.' RESTRICT_ON_SEND = %i[to_set].freeze # @!method map_to_set?(node) def_node_matcher :map_to_set?, <<~PATTERN { $(call (any_block $(call _ {:map :collect}) ...) :to_set) $(call $(call _ {:map :collect} (block_pass sym)) :to_set) } PATTERN def on_send(node) return unless (to_set_node, map_node = map_to_set?(node)) return if to_set_node.block_literal? message = format(MSG, method: map_node.loc.selector.source) add_offense(map_node.loc.selector, message: message) do |corrector| autocorrect(corrector, to_set_node, map_node) end end alias on_csend on_send private def autocorrect(corrector, to_set, map) removal_range = range_between(to_set.loc.dot.begin_pos, to_set.loc.selector.end_pos) corrector.remove(range_with_surrounding_space(removal_range, side: :left)) corrector.replace(map.loc.selector, 'to_set') end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/numeric_predicate.rb
lib/rubocop/cop/style/numeric_predicate.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for usage of comparison operators (`==`, # `>`, `<`) to test numbers as zero, positive, or negative. # These can be replaced by their respective predicate methods. # This cop can also be configured to do the reverse. # # This cop's allowed methods can be customized with `AllowedMethods`. # By default, there are no allowed methods. # # This cop disregards `#nonzero?` as its value is truthy or falsey, # but not `true` and `false`, and thus not always interchangeable with # `!= 0`. # # This cop allows comparisons to global variables, since they are often # populated with objects which can be compared with integers, but are # not themselves `Integer` polymorphic. # # @safety # This cop is unsafe because it cannot be guaranteed that the receiver # defines the predicates or can be compared to a number, which may lead # to a false positive for non-standard classes. # # @example EnforcedStyle: predicate (default) # # bad # foo == 0 # 0 > foo # bar.baz > 0 # # # good # foo.zero? # foo.negative? # bar.baz.positive? # # @example EnforcedStyle: comparison # # bad # foo.zero? # foo.negative? # bar.baz.positive? # # # good # foo == 0 # 0 > foo # bar.baz > 0 # # @example AllowedMethods: [] (default) with EnforcedStyle: predicate # # bad # foo == 0 # 0 > foo # bar.baz > 0 # # @example AllowedMethods: [==] with EnforcedStyle: predicate # # good # foo == 0 # # # bad # 0 > foo # bar.baz > 0 # # @example AllowedPatterns: [] (default) with EnforcedStyle: comparison # # bad # foo.zero? # foo.negative? # bar.baz.positive? # # @example AllowedPatterns: ['zero'] with EnforcedStyle: predicate # # good # # bad # foo.zero? # # # bad # foo.negative? # bar.baz.positive? # class NumericPredicate < Base include ConfigurableEnforcedStyle include AllowedMethods include AllowedPattern extend AutoCorrector MSG = 'Use `%<prefer>s` instead of `%<current>s`.' REPLACEMENTS = { 'zero?' => '==', 'positive?' => '>', 'negative?' => '<' }.freeze RESTRICT_ON_SEND = %i[== > < positive? negative? zero?].freeze def on_send(node) numeric, replacement = check(node) return unless numeric return if allowed_method_name?(node.method_name) || node.each_ancestor(:send, :block).any? do |ancestor| allowed_method_name?(ancestor.method_name) end message = format(MSG, prefer: replacement, current: node.source) add_offense(node, message: message) do |corrector| corrector.replace(node, replacement) end end private def allowed_method_name?(name) allowed_method?(name) || matches_allowed_pattern?(name) end def check(node) numeric, operator = if style == :predicate comparison(node) || inverted_comparison(node, &invert) else predicate(node) end return unless numeric && operator && replacement_supported?(operator) [numeric, replacement(node, numeric, operator)] end def replacement(node, numeric, operation) if style == :predicate [parenthesized_source(numeric), REPLACEMENTS.invert[operation.to_s]].join('.') elsif negated?(node) "(#{numeric.source} #{REPLACEMENTS[operation.to_s]} 0)" else [numeric.source, REPLACEMENTS[operation.to_s], 0].join(' ') end end def parenthesized_source(node) if require_parentheses?(node) "(#{node.source})" else node.source end end def require_parentheses?(node) node.send_type? && node.binary_operation? && !node.parenthesized? end def replacement_supported?(operator) if %i[> <].include?(operator) target_ruby_version >= 2.3 else true end end def invert lambda do |comparison, numeric| comparison = { :> => :<, :< => :> }[comparison] || comparison [numeric, comparison] end end def negated?(node) return false unless (parent = node.parent) parent.send_type? && parent.method?(:!) end # @!method predicate(node) def_node_matcher :predicate, <<~PATTERN (send $(...) ${:zero? :positive? :negative?}) PATTERN # @!method comparison(node) def_node_matcher :comparison, <<~PATTERN (send [$(...) !gvar_type?] ${:== :> :<} (int 0)) PATTERN # @!method inverted_comparison(node) def_node_matcher :inverted_comparison, <<~PATTERN (send (int 0) ${:== :> :<} [$(...) !gvar_type?]) PATTERN end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/expand_path_arguments.rb
lib/rubocop/cop/style/expand_path_arguments.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for use of the `File.expand_path` arguments. # Likewise, it also checks for the `Pathname.new` argument. # # Contrastive bad case and good case are alternately shown in # the following examples. # # @example # # bad # File.expand_path('..', __FILE__) # # # good # File.expand_path(__dir__) # # # bad # File.expand_path('../..', __FILE__) # # # good # File.expand_path('..', __dir__) # # # bad # File.expand_path('.', __FILE__) # # # good # File.expand_path(__FILE__) # # # bad # Pathname(__FILE__).parent.expand_path # # # good # Pathname(__dir__).expand_path # # # bad # Pathname.new(__FILE__).parent.expand_path # # # good # Pathname.new(__dir__).expand_path # class ExpandPathArguments < Base include RangeHelp extend AutoCorrector MSG = 'Use `expand_path(%<new_path>s%<new_default_dir>s)` instead of ' \ '`expand_path(%<current_path>s, __FILE__)`.' PATHNAME_MSG = 'Use `Pathname(__dir__).expand_path` instead of ' \ '`Pathname(__FILE__).parent.expand_path`.' PATHNAME_NEW_MSG = 'Use `Pathname.new(__dir__).expand_path` ' \ 'instead of ' \ '`Pathname.new(__FILE__).parent.expand_path`.' RESTRICT_ON_SEND = %i[expand_path].freeze # @!method file_expand_path(node) def_node_matcher :file_expand_path, <<~PATTERN (send (const {nil? cbase} :File) :expand_path $_ $_) PATTERN # @!method pathname_parent_expand_path(node) def_node_matcher :pathname_parent_expand_path, <<~PATTERN (send (send (send nil? :Pathname $_) :parent) :expand_path) PATTERN # @!method pathname_new_parent_expand_path(node) def_node_matcher :pathname_new_parent_expand_path, <<~PATTERN (send (send (send (const {nil? cbase} :Pathname) :new $_) :parent) :expand_path) PATTERN def on_send(node) if (current_path, default_dir = file_expand_path(node)) inspect_offense_for_expand_path(node, current_path, default_dir) elsif (default_dir = pathname_parent_expand_path(node)) return unless unrecommended_argument?(default_dir) add_offense(node, message: PATHNAME_MSG) { |corrector| autocorrect(corrector, node) } elsif (default_dir = pathname_new_parent_expand_path(node)) return unless unrecommended_argument?(default_dir) add_offense(node, message: PATHNAME_NEW_MSG) do |corrector| autocorrect(corrector, node) end end end private def autocorrect(corrector, node) if (current_path, default_dir = file_expand_path(node)) autocorrect_expand_path(corrector, current_path, default_dir) elsif (dir = pathname_parent_expand_path(node) || pathname_new_parent_expand_path(node)) corrector.replace(dir, '__dir__') remove_parent_method(corrector, dir) end end def unrecommended_argument?(default_dir) default_dir.source == '__FILE__' end def inspect_offense_for_expand_path(node, current_path, default_dir) return unless unrecommended_argument?(default_dir) && current_path.str_type? current_path = strip_surrounded_quotes!(current_path.source) parent_path = parent_path(current_path) new_path = parent_path == '' ? '' : "'#{parent_path}', " new_default_dir = depth(current_path).zero? ? '__FILE__' : '__dir__' message = format( MSG, new_path: new_path, new_default_dir: new_default_dir, current_path: "'#{current_path}'" ) add_offense(node.loc.selector, message: message) do |corrector| autocorrect(corrector, node) end end def autocorrect_expand_path(corrector, current_path, default_dir) stripped_current_path = strip_surrounded_quotes!(current_path.source) case depth(stripped_current_path) when 0 range = arguments_range(current_path.parent) corrector.replace(range, '__FILE__') when 1 range = arguments_range(current_path.parent) corrector.replace(range, '__dir__') else new_path = "'#{parent_path(stripped_current_path)}'" corrector.replace(current_path, new_path) corrector.replace(default_dir, '__dir__') end end def strip_surrounded_quotes!(path_string) path_string.slice!(path_string.length - 1) path_string.slice!(0) path_string end def depth(current_path) paths = current_path.split(File::SEPARATOR) paths.count { |path| path != '.' } end def parent_path(current_path) paths = current_path.split(File::SEPARATOR) paths.delete('.') paths.each_with_index do |path, index| if path == '..' paths.delete_at(index) break end end paths.join(File::SEPARATOR) end def remove_parent_method(corrector, default_dir) node = default_dir.parent.parent.parent.children.first corrector.remove(node.loc.dot) corrector.remove(node.loc.selector) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/hash_each_methods.rb
lib/rubocop/cop/style/hash_each_methods.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for uses of `each_key` and `each_value` `Hash` methods. # # NOTE: If you have an array of two-element arrays, you can put # parentheses around the block arguments to indicate that you're not # working with a hash, and suppress RuboCop offenses. # # @safety # This cop is unsafe because it cannot be guaranteed that the receiver # is a `Hash`. The `AllowedReceivers` configuration can mitigate, # but not fully resolve, this safety issue. # # @example # # bad # hash.keys.each { |k| p k } # hash.each { |k, unused_value| p k } # # # good # hash.each_key { |k| p k } # # # bad # hash.values.each { |v| p v } # hash.each { |unused_key, v| p v } # # # good # hash.each_value { |v| p v } # # @example AllowedReceivers: ['execute'] # # good # execute(sql).keys.each { |v| p v } # execute(sql).values.each { |v| p v } class HashEachMethods < Base include AllowedReceivers include Lint::UnusedArgument extend AutoCorrector MSG = 'Use `%<prefer>s` instead of `%<current>s`.' UNUSED_BLOCK_ARG_MSG = "#{MSG.chop} and remove the unused `%<unused_code>s` block argument." ARRAY_CONVERTER_METHODS = %i[assoc chunk flatten rassoc sort sort_by to_a].freeze # @!method kv_each(node) def_node_matcher :kv_each, <<~PATTERN (any_block $(call (call _ ${:keys :values}) :each) ...) PATTERN # @!method each_arguments(node) def_node_matcher :each_arguments, <<~PATTERN (block (call _ :each)(args $_key $_value) ...) PATTERN # @!method kv_each_with_block_pass(node) def_node_matcher :kv_each_with_block_pass, <<~PATTERN (call $(call _ ${:keys :values}) :each (block_pass (sym _))) PATTERN # @!method hash_mutated?(node, receiver) def_node_matcher :hash_mutated?, <<~PATTERN `(send %1 :[]= ...) PATTERN def on_block(node) return unless handleable?(node) kv_each(node) do |target, method| register_kv_offense(target, method) and return end return unless (key, value = each_arguments(node)) check_unused_block_args(node, key, value) end alias on_numblock on_block alias on_itblock on_block # rubocop:disable Metrics/AbcSize def check_unused_block_args(node, key, value) return if node.body.nil? value_unused = unused_block_arg_exist?(node, value) key_unused = unused_block_arg_exist?(node, key) return if value_unused && key_unused if value_unused message = message('each_key', node.method_name, value.source) unused_range = key.source_range.end.join(value.source_range.end) register_each_args_offense(node, message, 'each_key', unused_range) elsif key_unused message = message('each_value', node.method_name, key.source) unused_range = key.source_range.begin.join(value.source_range.begin) register_each_args_offense(node, message, 'each_value', unused_range) end end # rubocop:enable Metrics/AbcSize def on_block_pass(node) kv_each_with_block_pass(node.parent) do |target, method| register_kv_with_block_pass_offense(node, target, method) end end private def handleable?(node) return false if use_array_converter_method_as_preceding?(node) return false unless (root_receiver = root_receiver(node)) return false if hash_mutated?(node, root_receiver) !root_receiver.literal? || root_receiver.hash_type? end def register_kv_offense(target, method) return unless (parent_receiver = target.receiver.receiver) return if allowed_receiver?(parent_receiver) current = target.receiver.loc.selector.join(target.source_range.end).source add_offense(kv_range(target), message: format_message(method, current)) do |corrector| correct_key_value_each(target, corrector) end end def unused_block_arg_exist?(node, block_arg) lvar_sources = node.body.each_descendant(:lvar).map(&:source) if block_arg.mlhs_type? block_arg.each_descendant(:arg, :restarg).all? do |descendant| lvar_sources.none?(descendant.source.delete_prefix('*')) end else lvar_sources.none?(block_arg.source.delete_prefix('*')) end end def message(prefer, method_name, unused_code) format( UNUSED_BLOCK_ARG_MSG, prefer: prefer, current: method_name, unused_code: unused_code ) end def register_each_args_offense(node, message, prefer, unused_range) add_offense(node, message: message) do |corrector| corrector.replace(node.send_node.loc.selector, prefer) corrector.remove(unused_range) end end def register_kv_with_block_pass_offense(node, target, method) return unless (parent_receiver = node.parent.receiver.receiver) return if allowed_receiver?(parent_receiver) range = target.loc.selector.join(node.parent.loc.selector.end) add_offense(range, message: format_message(method, range.source)) do |corrector| corrector.replace(range, "each_#{method[0..-2]}") end end def use_array_converter_method_as_preceding?(node) return false unless (preceding_method = node.children.first.children.first) return false unless preceding_method.type?(:call, :any_block) ARRAY_CONVERTER_METHODS.include?(preceding_method.method_name) end def root_receiver(node) receiver = node.receiver if receiver&.receiver root_receiver(receiver) else receiver end end def format_message(method_name, current) format(MSG, prefer: "each_#{method_name[0..-2]}", current: current) end def check_argument(variable) return unless variable.block_argument? (@block_args ||= []).push(variable) end def used?(arg) @block_args.find { |var| var.declaration_node.loc == arg.loc }.used? end def correct_implicit(node, corrector, method_name) corrector.replace(node, method_name) correct_args(node, corrector) end def correct_key_value_each(node, corrector) receiver = node.receiver.receiver name = "each_#{node.receiver.method_name.to_s.chop}" return correct_implicit(node, corrector, name) unless receiver new_source = receiver.source + "#{node.loc.dot.source}#{name}" corrector.replace(node, new_source) end def correct_args(node, corrector) args = node.parent.arguments name, = *args.children.find { |arg| used?(arg) } corrector.replace(args, "|#{name}|") end def kv_range(outer_node) outer_node.receiver.loc.selector.join(outer_node.loc.selector) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/trailing_underscore_variable.rb
lib/rubocop/cop/style/trailing_underscore_variable.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for extra underscores in variable assignment. # # @example # # bad # a, b, _ = foo # a, b, _, = foo # a, _, _ = foo # a, _, _, = foo # # # good # a, b, = foo # a, = foo # *a, b, _ = foo # # => We need to know to not include 2 variables in a # a, *b, _ = foo # # => The correction `a, *b, = foo` is a syntax error # # @example AllowNamedUnderscoreVariables: true (default) # # good # a, b, _something = foo # # @example AllowNamedUnderscoreVariables: false # # bad # a, b, _something = foo # class TrailingUnderscoreVariable < Base include SurroundingSpace include RangeHelp extend AutoCorrector MSG = 'Do not use trailing `_`s in parallel assignment. Prefer `%<code>s`.' UNDERSCORE = '_' DISALLOW = %i[lvasgn splat].freeze private_constant :DISALLOW def on_masgn(node) ranges = unneeded_ranges(node) ranges.each do |range| good_code = node.source offset = range.begin_pos - node.source_range.begin_pos good_code[offset, range.size] = '' add_offense(range, message: format(MSG, code: good_code)) do |corrector| corrector.remove(range) end end end private def find_first_offense(variables) first_offense = find_first_possible_offense(variables.reverse) return unless first_offense return if splat_variable_before?(first_offense, variables) first_offense end def find_first_possible_offense(variables) variables.reduce(nil) do |offense, variable| break offense unless DISALLOW.include?(variable.type) var, = *variable var, = *var break offense if (allow_named_underscore_variables && var != :_) || !var.to_s.start_with?(UNDERSCORE) variable end end def splat_variable_before?(first_offense, variables) # Account for cases like `_, *rest, _`, where we would otherwise get # the index of the first underscore. first_offense_index = reverse_index(variables, first_offense) variables[0...first_offense_index].any?(&:splat_type?) end def reverse_index(collection, item) collection.size - 1 - collection.reverse.index(item) end def allow_named_underscore_variables @allow_named_underscore_variables ||= cop_config['AllowNamedUnderscoreVariables'] end def unneeded_ranges(node) mlhs_node = node.masgn_type? ? node.lhs : node variables = *mlhs_node main_offense = main_node_offense(node) if main_offense.nil? children_offenses(variables) else children_offenses(variables) << main_offense end end def main_node_offense(node) mlhs_node = node.masgn_type? ? node.lhs : node variables = *mlhs_node first_offense = find_first_offense(variables) return unless first_offense if unused_variables_only?(first_offense, variables) return unused_range(node.type, mlhs_node, node.rhs) end return range_for_parentheses(first_offense, mlhs_node) if Util.parentheses?(mlhs_node) range_between(first_offense.source_range.begin_pos, node.loc.operator.begin_pos) end def children_offenses(variables) variables.select(&:mlhs_type?).flat_map { |v| unneeded_ranges(v) } end def unused_variables_only?(offense, variables) offense.source_range == variables.first.source_range end def unused_range(node_type, mlhs_node, right) start_range = mlhs_node.source_range.begin_pos end_range = case node_type when :masgn right.source_range.begin_pos when :mlhs mlhs_node.source_range.end_pos end range_between(start_range, end_range) end def range_for_parentheses(offense, left) range_between(offense.source_range.begin_pos - 1, left.source_range.end_pos - 1) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/select_by_regexp.rb
lib/rubocop/cop/style/select_by_regexp.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Looks for places where a subset of an Enumerable (array, # range, set, etc.; see note below) is calculated based on a `Regexp` # match, and suggests `grep` or `grep_v` instead. # # NOTE: Hashes do not behave as you may expect with `grep`, which # means that `hash.grep` is not equivalent to `hash.select`. Although # RuboCop is limited by static analysis, this cop attempts to avoid # registering an offense when the receiver is a hash (hash literal, # `Hash.new`, `Hash#[]`, or `to_h`/`to_hash`). # # NOTE: `grep` and `grep_v` were optimized when used without a block # in Ruby 3.0, but may be slower in previous versions. # See https://bugs.ruby-lang.org/issues/17030 # # @safety # Autocorrection is marked as unsafe because `MatchData` will # not be created by `grep`, but may have previously been relied # upon after the `match?` or `=~` call. # # Additionally, the cop cannot guarantee that the receiver of # `select` or `reject` is actually an array by static analysis, # so the correction may not be actually equivalent. # # @example # # bad (select, filter, or find_all) # array.select { |x| x.match? /regexp/ } # array.select { |x| /regexp/.match?(x) } # array.select { |x| x =~ /regexp/ } # array.select { |x| /regexp/ =~ x } # # # bad (reject) # array.reject { |x| x.match? /regexp/ } # array.reject { |x| /regexp/.match?(x) } # array.reject { |x| x =~ /regexp/ } # array.reject { |x| /regexp/ =~ x } # # # good # array.grep(regexp) # array.grep_v(regexp) class SelectByRegexp < Base extend AutoCorrector include RangeHelp MSG = 'Prefer `%<replacement>s` to `%<original_method>s` with a regexp match.' RESTRICT_ON_SEND = %i[select filter find_all reject].freeze REPLACEMENTS = { select: 'grep', filter: 'grep', find_all: 'grep', reject: 'grep_v' }.freeze OPPOSITE_REPLACEMENTS = { select: 'grep_v', filter: 'grep_v', find_all: 'grep_v', reject: 'grep' }.freeze REGEXP_METHODS = %i[match? =~ !~].to_set.freeze # @!method regexp_match?(node) def_node_matcher :regexp_match?, <<~PATTERN { (block call (args (arg $_)) ${(send _ %REGEXP_METHODS _) match-with-lvasgn}) (numblock call $1 ${(send _ %REGEXP_METHODS _) match-with-lvasgn}) (itblock call $_ ${(send _ %REGEXP_METHODS _) match-with-lvasgn}) } PATTERN # Returns true if a node appears to return a hash # @!method creates_hash?(node) def_node_matcher :creates_hash?, <<~PATTERN { (call (const _ :Hash) {:new :[]} ...) (block (call (const _ :Hash) :new ...) ...) (call _ { :to_h :to_hash } ...) } PATTERN # @!method env_const?(node) def_node_matcher :env_const?, <<~PATTERN (const {nil? cbase} :ENV) PATTERN # @!method calls_lvar?(node, name) def_node_matcher :calls_lvar?, <<~PATTERN { (send (lvar %1) ...) (send ... (lvar %1)) (match-with-lvasgn regexp (lvar %1)) } PATTERN # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity def on_send(node) return if target_ruby_version < 2.6 && node.method?(:filter) return unless (block_node = node.block_node) return if block_node.body&.begin_type? return if receiver_allowed?(block_node.receiver) return unless (regexp_method_send_node = extract_send_node(block_node)) return if match_predicate_without_receiver?(regexp_method_send_node) replacement = replacement(regexp_method_send_node, node) return if target_ruby_version <= 2.2 && replacement == 'grep_v' regexp = find_regexp(regexp_method_send_node, block_node) register_offense(node, block_node, regexp, replacement) end # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity alias on_csend on_send private def receiver_allowed?(node) return false unless node node.hash_type? || creates_hash?(node) || env_const?(node) end def replacement(regexp_method_send_node, node) opposite = opposite?(regexp_method_send_node) method_name = node.method_name opposite ? OPPOSITE_REPLACEMENTS[method_name] : REPLACEMENTS[method_name] end def register_offense(node, block_node, regexp, replacement) message = format(MSG, replacement: replacement, original_method: node.method_name) add_offense(block_node, message: message) do |corrector| # Only correct if it can be determined what the regexp is if regexp range = range_between(node.loc.selector.begin_pos, block_node.loc.end.end_pos) corrector.replace(range, "#{replacement}(#{regexp.source})") end end end def extract_send_node(block_node) return unless (block_arg_name, regexp_method_send_node = regexp_match?(block_node)) block_arg_name = :"_#{block_arg_name}" if block_node.numblock_type? return unless calls_lvar?(regexp_method_send_node, block_arg_name) regexp_method_send_node end def opposite?(regexp_method_send_node) regexp_method_send_node.send_type? && regexp_method_send_node.method?(:!~) end def find_regexp(node, block) return node.child_nodes.first if node.match_with_lvasgn_type? if node.receiver.lvar_type? && (block.type?(:numblock, :itblock) || node.receiver.source == block.first_argument.source) node.first_argument elsif node.first_argument.lvar_type? node.receiver end end def match_predicate_without_receiver?(node) node.send_type? && node.method?(:match?) && node.receiver.nil? end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/ip_addresses.rb
lib/rubocop/cop/style/ip_addresses.rb
# frozen_string_literal: true require 'resolv' module RuboCop module Cop module Style # Checks for hardcoded IP addresses, which can make code # brittle. IP addresses are likely to need to be changed when code # is deployed to a different server or environment, which may break # a deployment if forgotten. Prefer setting IP addresses in ENV or # other configuration. # # @example # # # bad # ip_address = '127.59.241.29' # # # good # ip_address = ENV['DEPLOYMENT_IP_ADDRESS'] class IpAddresses < Base include StringHelp IPV6_MAX_SIZE = 45 # IPv4-mapped IPv6 is the longest MSG = 'Do not hardcode IP addresses.' def offense?(node) contents = node.source[1...-1] return false if contents.empty? return false if allowed_addresses.include?(contents.downcase) # To try to avoid doing two regex checks on every string, # shortcut out if the string does not look like an IP address return false unless potential_ip?(contents) ::Resolv::IPv4::Regex.match?(contents) || ::Resolv::IPv6::Regex.match?(contents) end # Dummy implementation of method in ConfigurableEnforcedStyle that is # called from StringHelp. def opposite_style_detected; end # Dummy implementation of method in ConfigurableEnforcedStyle that is # called from StringHelp. def correct_style_detected; end private def allowed_addresses allowed_addresses = cop_config['AllowedAddresses'] Array(allowed_addresses).map(&:downcase) end def potential_ip?(str) # If the string is too long, it can't be an IP return false if too_long?(str) # If the string doesn't start with a colon or hexadecimal char, # we know it's not an IP address starts_with_hex_or_colon?(str) end def too_long?(str) str.size > IPV6_MAX_SIZE end def starts_with_hex_or_colon?(str) first_char = str[0].ord (48..58).cover?(first_char) || (65..70).cover?(first_char) || (97..102).cover?(first_char) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/end_block.rb
lib/rubocop/cop/style/end_block.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for END blocks. # # @example # # bad # END { puts 'Goodbye!' } # # # good # at_exit { puts 'Goodbye!' } # class EndBlock < Base extend AutoCorrector MSG = 'Avoid the use of `END` blocks. Use `Kernel#at_exit` instead.' def on_postexe(node) add_offense(node.loc.keyword) do |corrector| corrector.replace(node.loc.keyword, 'at_exit') end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/file_read.rb
lib/rubocop/cop/style/file_read.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Favor `File.(bin)read` convenience methods. # # @example # # bad - text mode # File.open(filename).read # File.open(filename, &:read) # File.open(filename) { |f| f.read } # File.open(filename) do |f| # f.read # end # File.open(filename, 'r').read # File.open(filename, 'r', &:read) # File.open(filename, 'r') do |f| # f.read # end # # # good # File.read(filename) # # # bad - binary mode # File.open(filename, 'rb').read # File.open(filename, 'rb', &:read) # File.open(filename, 'rb') do |f| # f.read # end # # # good # File.binread(filename) # class FileRead < Base extend AutoCorrector include RangeHelp MSG = 'Use `File.%<read_method>s`.' RESTRICT_ON_SEND = %i[open].freeze READ_FILE_START_TO_FINISH_MODES = %w[r rt rb r+ r+t r+b].to_set.freeze # @!method file_open?(node) def_node_matcher :file_open?, <<~PATTERN (send (const {nil? cbase} :File) :open $_ (str $%READ_FILE_START_TO_FINISH_MODES)? $(block-pass (sym :read))? ) PATTERN # @!method send_read?(node) def_node_matcher :send_read?, <<~PATTERN (send _ :read) PATTERN # @!method block_read?(node) def_node_matcher :block_read?, <<~PATTERN (block _ (args (arg _name)) (send (lvar _name) :read)) PATTERN def on_send(node) evidence(node) do |filename, mode, read_node| message = format(MSG, read_method: read_method(mode)) add_offense(read_node, message: message) do |corrector| range = range_between(node.loc.selector.begin_pos, read_node.source_range.end_pos) replacement = "#{read_method(mode)}(#{filename.source})" corrector.replace(range, replacement) end end end private def evidence(node) file_open?(node) do |filename, mode_array, block_pass| read_node?(node, block_pass) do |read_node| yield(filename, mode_array.first || 'r', read_node) end end end def read_node?(node, block_pass) if block_pass.any? yield(node) elsif file_open_read?(node.parent) yield(node.parent) end end def file_open_read?(node) return true if send_read?(node) block_read?(node) end def read_method(mode) mode.end_with?('b') ? :binread : :read end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/unless_else.rb
lib/rubocop/cop/style/unless_else.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Looks for `unless` expressions with `else` clauses. # # @example # # bad # unless foo_bar.nil? # # do something... # else # # do a different thing... # end # # # good # if foo_bar.present? # # do something... # else # # do a different thing... # end class UnlessElse < Base extend AutoCorrector MSG = 'Do not use `unless` with `else`. Rewrite these with the positive case first.' def on_if(node) return unless node.unless? && node.else? add_offense(node) do |corrector| next if part_of_ignored_node?(node) corrector.replace(node.loc.keyword, 'if') body_range = range_between_condition_and_else(node) else_range = range_between_else_and_end(node) corrector.swap(body_range, else_range) end ignore_node(node) end def range_between_condition_and_else(node) range = node.loc.begin ? node.loc.begin.end : node.condition.source_range range.end.join(node.loc.else.begin) end def range_between_else_and_end(node) node.loc.else.end.join(node.loc.end.begin) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/require_order.rb
lib/rubocop/cop/style/require_order.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Sort `require` and `require_relative` in alphabetical order. # # @safety # This cop's autocorrection is unsafe because it will obviously change the execution order. # # @example # # bad # require 'b' # require 'a' # # # good # require 'a' # require 'b' # # # bad # require_relative 'b' # require_relative 'a' # # # good # require_relative 'a' # require_relative 'b' # # # good (sorted within each section separated by a blank line) # require 'a' # require 'd' # # require 'b' # require 'c' # # # good # require 'b' # require_relative 'c' # require 'a' # # # bad # require 'a' # require 'c' if foo # require 'b' # # # good # require 'a' # require 'b' # require 'c' if foo # # # bad # require 'c' # if foo # require 'd' # require 'b' # end # require 'a' # # # good # require 'c' # if foo # require 'b' # require 'd' # end # require 'a' # class RequireOrder < Base extend AutoCorrector include RangeHelp RESTRICT_ON_SEND = %i[require require_relative].freeze MSG = 'Sort `%<name>s` in alphabetical order.' # @!method if_inside_only_require(node) def_node_matcher :if_inside_only_require, <<~PATTERN { (if _ _ $(send nil? {:require :require_relative} _)) (if _ $(send nil? {:require :require_relative} _) _) } PATTERN def on_send(node) return unless node.parent && node.arguments? return if not_modifier_form?(node.parent) previous_older_sibling = find_previous_older_sibling(node) return unless previous_older_sibling add_offense(node, message: format(MSG, name: node.method_name)) do |corrector| autocorrect(corrector, node, previous_older_sibling) end end private def not_modifier_form?(node) node.if_type? && !node.modifier_form? end def find_previous_older_sibling(node) # rubocop:disable Metrics search_node(node).left_siblings.reverse.find do |sibling| next unless sibling.is_a?(AST::Node) sibling = sibling_node(sibling) break unless sibling&.send_type? && sibling.method?(node.method_name) break unless sibling.arguments? && !sibling.receiver break unless in_same_section?(sibling, node) break unless node.first_argument.str_type? && sibling.first_argument.str_type? node.first_argument.value < sibling.first_argument.value end end def autocorrect(corrector, node, previous_older_sibling) range1 = range_with_comments_and_lines(previous_older_sibling) range2 = range_with_comments_and_lines(node.parent.if_type? ? node.parent : node) corrector.remove(range2) corrector.insert_before(range1, range2.source) end def search_node(node) node.parent.if_type? ? node.parent : node end def sibling_node(node) return if not_modifier_form?(node) node.if_type? ? if_inside_only_require(node) : node end def in_same_section?(node1, node2) !node1.source_range.join(node2.source_range.end).source.include?("\n\n") end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/self_assignment.rb
lib/rubocop/cop/style/self_assignment.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Enforces the use the shorthand for self-assignment. # # @example # # # bad # x = x + 1 # # # good # x += 1 class SelfAssignment < Base extend AutoCorrector MSG = 'Use self-assignment shorthand `%<method>s=`.' OPS = %i[+ - * ** / % ^ << >> | &].freeze def self.autocorrect_incompatible_with [Layout::SpaceAroundOperators] end def on_lvasgn(node) check(node, :lvar) end def on_ivasgn(node) check(node, :ivar) end def on_cvasgn(node) check(node, :cvar) end private def check(node, var_type) return unless (rhs = node.expression) if rhs.send_type? && rhs.arguments.one? check_send_node(node, rhs, node.name, var_type) elsif rhs.operator_keyword? check_boolean_node(node, rhs, node.name, var_type) end end def check_send_node(node, rhs, var_name, var_type) return unless OPS.include?(rhs.method_name) target_node = s(var_type, var_name) return unless rhs.receiver == target_node add_offense(node, message: format(MSG, method: rhs.method_name)) do |corrector| autocorrect(corrector, node) end end def check_boolean_node(node, rhs, var_name, var_type) target_node = s(var_type, var_name) return unless rhs.lhs == target_node operator = rhs.loc.operator.source add_offense(node, message: format(MSG, method: operator)) do |corrector| autocorrect(corrector, node) end end def autocorrect(corrector, node) rhs = node.expression if rhs.send_type? autocorrect_send_node(corrector, node, rhs) elsif rhs.operator_keyword? autocorrect_boolean_node(corrector, node, rhs) end end def autocorrect_send_node(corrector, node, rhs) apply_autocorrect(corrector, node, rhs, rhs.method_name, rhs.first_argument) end def autocorrect_boolean_node(corrector, node, rhs) apply_autocorrect(corrector, node, rhs, rhs.loc.operator.source, rhs.rhs) end def apply_autocorrect(corrector, node, rhs, operator, new_rhs) corrector.insert_before(node.loc.operator, operator) corrector.replace(rhs, new_rhs.source) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/bitwise_predicate.rb
lib/rubocop/cop/style/bitwise_predicate.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Prefer bitwise predicate methods over direct comparison operations. # # @safety # This cop is unsafe, as it can produce false positives if the receiver # is not an `Integer` object. # # @example # # # bad - checks any set bits # (variable & flags).positive? # # # good # variable.anybits?(flags) # # # bad - checks all set bits # (variable & flags) == flags # # # good # variable.allbits?(flags) # # # bad - checks no set bits # (variable & flags).zero? # # # good # variable.nobits?(flags) # class BitwisePredicate < Base extend AutoCorrector extend TargetRubyVersion MSG = 'Replace with `%<preferred>s` for comparison with bit flags.' RESTRICT_ON_SEND = %i[!= == > >= positive? zero?].freeze minimum_target_ruby_version 2.5 # @!method anybits?(node) def_node_matcher :anybits?, <<~PATTERN { (send #bit_operation? :positive?) (send #bit_operation? :> (int 0)) (send #bit_operation? :>= (int 1)) (send #bit_operation? :!= (int 0)) } PATTERN # @!method allbits?(node) def_node_matcher :allbits?, <<~PATTERN { (send (begin (send _ :& _flags)) :== _flags) (send (begin (send _flags :& _)) :== _flags) } PATTERN # @!method nobits?(node) def_node_matcher :nobits?, <<~PATTERN { (send #bit_operation? :zero?) (send #bit_operation? :== (int 0)) } PATTERN # @!method bit_operation?(node) def_node_matcher :bit_operation?, <<~PATTERN (begin (send _ :& _)) PATTERN # rubocop:disable Metrics/AbcSize def on_send(node) return unless node.receiver&.begin_type? return unless (preferred_method = preferred_method(node)) bit_operation = node.receiver.children.first lhs, _operator, rhs = *bit_operation preferred = if preferred_method == 'allbits?' && lhs.source == node.first_argument.source "#{rhs.source}.allbits?(#{lhs.source})" else "#{lhs.source}.#{preferred_method}(#{rhs.source})" end add_offense(node, message: format(MSG, preferred: preferred)) do |corrector| corrector.replace(node, preferred) end end # rubocop:enable Metrics/AbcSize private def preferred_method(node) if anybits?(node) 'anybits?' elsif allbits?(node) 'allbits?' elsif nobits?(node) 'nobits?' end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/and_or.rb
lib/rubocop/cop/style/and_or.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for uses of `and` and `or`, and suggests using `&&` and # `||` instead. It can be configured to check only in conditions or in # all contexts. # # @safety # Autocorrection is unsafe because there is a different operator precedence # between logical operators (`&&` and `||`) and semantic operators (`and` and `or`), # and that might change the behavior. # # @example EnforcedStyle: conditionals (default) # # bad # if foo and bar # end # # # good # foo.save && return # # # good # foo.save and return # # # good # if foo && bar # end # # @example EnforcedStyle: always # # bad # foo.save and return # # # bad # if foo and bar # end # # # good # foo.save && return # # # good # if foo && bar # end class AndOr < Base include ConfigurableEnforcedStyle include RangeHelp extend AutoCorrector MSG = 'Use `%<prefer>s` instead of `%<current>s`.' def on_and(node) process_logical_operator(node) if style == :always end alias on_or on_and def on_if(node) on_conditionals(node) if style == :conditionals end alias on_while on_if alias on_while_post on_if alias on_until on_if alias on_until_post on_if private def process_logical_operator(node) return if node.logical_operator? message = message(node) add_offense(node.loc.operator, message: message) do |corrector| node.each_child_node do |expr| if expr.send_type? correct_send(expr, corrector) elsif expr.return_type? || expr.assignment? correct_other(expr, corrector) end end corrector.replace(node.loc.operator, node.alternate_operator) keep_operator_precedence(corrector, node) end end def on_conditionals(node) node.condition.each_node(*AST::Node::OPERATOR_KEYWORDS) do |operator| process_logical_operator(operator) end end def message(node) format(MSG, prefer: node.alternate_operator, current: node.operator) end def correct_send(node, corrector) return correct_not(node, node.receiver, corrector) if node.method?(:!) return correct_setter(node, corrector) if node.setter_method? return correct_other(node, corrector) if node.comparison_method? return unless correctable_send?(node) whitespace_before_arg_range = whitespace_before_arg(node) corrector.remove(whitespace_before_arg_range) corrector.insert_before(whitespace_before_arg_range, '(') corrector.insert_after(node.last_argument, ')') end def correct_setter(node, corrector) corrector.insert_before(node.receiver, '(') corrector.insert_after(node.last_argument, ')') end # ! is a special case: # 'x and !obj.method arg' can be autocorrected if we # recurse down a level and add parens to 'obj.method arg' # however, 'not x' also parses as (send x :!) def correct_not(node, receiver, corrector) if node.prefix_bang? return unless receiver.send_type? correct_send(receiver, corrector) elsif node.prefix_not? correct_other(node, corrector) else raise 'unrecognized unary negation operator' end end def correct_other(node, corrector) return if node.parenthesized_call? corrector.wrap(node, '(', ')') end def keep_operator_precedence(corrector, node) if node.or_type? && node.parent&.and_type? corrector.wrap(node, '(', ')') elsif node.and_type? && node.rhs.or_type? corrector.wrap(node.rhs, '(', ')') end end def correctable_send?(node) !node.parenthesized? && node.arguments? && !node.method?(:[]) end def whitespace_before_arg(node) begin_paren = node.loc.selector.end_pos end_paren = begin_paren # Increment position of parenthesis, unless message is a predicate # method followed by a non-whitespace char (e.g. is_a?String). end_paren += 1 unless /\?\S/.match?(node.source) range_between(begin_paren, end_paren) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/dir_empty.rb
lib/rubocop/cop/style/dir_empty.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Prefer to use `Dir.empty?('path/to/dir')` when checking if a directory is empty. # # @example # # bad # Dir.entries('path/to/dir').size == 2 # Dir.children('path/to/dir').empty? # Dir.children('path/to/dir').size == 0 # Dir.each_child('path/to/dir').none? # # # good # Dir.empty?('path/to/dir') # class DirEmpty < Base extend AutoCorrector extend TargetRubyVersion MSG = 'Use `%<replacement>s` instead.' RESTRICT_ON_SEND = %i[== != > empty? none?].freeze minimum_target_ruby_version 2.4 # @!method offensive?(node) def_node_matcher :offensive?, <<~PATTERN { (send (send (send $(const {nil? cbase} :Dir) :entries $_) :size) {:== :!= :>} (int 2)) (send (send (send $(const {nil? cbase} :Dir) :children $_) :size) {:== :!= :>} (int 0)) (send (send $(const {nil? cbase} :Dir) :children $_) :empty?) (send (send $(const {nil? cbase} :Dir) :each_child $_) :none?) } PATTERN def on_send(node) offensive?(node) do |const_node, arg_node| replacement = "#{bang(node)}#{const_node.source}.empty?(#{arg_node.source})" add_offense(node, message: format(MSG, replacement: replacement)) do |corrector| corrector.replace(node, replacement) end end end private def bang(node) '!' if %i[!= >].include? node.method_name end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/symbol_array.rb
lib/rubocop/cop/style/symbol_array.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for array literals made up of symbols that are not # using the %i() syntax. # # Alternatively, it checks for symbol arrays using the %i() syntax on # projects which do not want to use that syntax, perhaps because they # support a version of Ruby lower than 2.0. # # Configuration option: MinSize # If set, arrays with fewer elements than this value will not trigger the # cop. For example, a `MinSize` of `3` will not enforce a style on an # array of 2 or fewer elements. # # @example EnforcedStyle: percent (default) # # good # %i[foo bar baz] # # # bad # [:foo, :bar, :baz] # # # bad (contains spaces) # %i[foo\ bar baz\ quux] # # # bad (contains [] with spaces) # %i[foo \[ \]] # # # bad (contains () with spaces) # %i(foo \( \)) # # @example EnforcedStyle: brackets # # good # [:foo, :bar, :baz] # # # bad # %i[foo bar baz] class SymbolArray < Base include ArrayMinSize include ArraySyntax include ConfigurableEnforcedStyle include PercentArray extend AutoCorrector extend TargetRubyVersion minimum_target_ruby_version 2.0 PERCENT_MSG = 'Use `%i` or `%I` for an array of symbols.' ARRAY_MSG = 'Use %<prefer>s for an array of symbols.' DELIMITERS = ['[', ']', '(', ')'].freeze SPECIAL_GVARS = %w[ $! $" $$ $& $' $* $+ $, $/ $; $: $. $< $= $> $? $@ $\\ $_ $` $~ $0 $-0 $-F $-I $-K $-W $-a $-d $-i $-l $-p $-v $-w ].freeze REDEFINABLE_OPERATORS = %w( | ^ & <=> == === =~ > >= < <= << >> + - * / % ** ~ +@ -@ [] []= ` ! != !~ ).freeze class << self attr_accessor :largest_brackets end def on_array(node) if bracketed_array_of?(:sym, node) return if complex_content?(node) check_bracketed_array(node, 'i') elsif node.percent_literal?(:symbol) check_percent_array(node) end end private def complex_content?(node) node.children.any? do |sym| return false if DELIMITERS.include?(sym.source) content = *sym content = content.map { |c| c.is_a?(AST::Node) ? c.source : c }.join content_without_delimiter_pairs = content.gsub(/(\[[^\s\[\]]*\])|(\([^\s()]*\))/, '') content.include?(' ') || DELIMITERS.any? do |delimiter| content_without_delimiter_pairs.include?(delimiter) end end end def invalid_percent_array_contents?(node) complex_content?(node) end def build_bracketed_array(node) return '[]' if node.children.empty? syms = node.children.map do |c| if c.dsym_type? string_literal = to_string_literal(c.source) ":#{trim_string_interpolation_escape_character(string_literal)}" else to_symbol_literal(c.value.to_s) end end build_bracketed_array_with_appropriate_whitespace(elements: syms, node: node) end def to_symbol_literal(string) if symbol_without_quote?(string) ":#{string}" else ":#{to_string_literal(string)}" end end def symbol_without_quote?(string) # method name /\A[a-zA-Z_]\w*[!?]?\z/.match?(string) || # instance / class variable /\A@@?[a-zA-Z_]\w*\z/.match?(string) || # global variable /\A\$[1-9]\d*\z/.match?(string) || /\A\$[a-zA-Z_]\w*\z/.match?(string) || SPECIAL_GVARS.include?(string) || REDEFINABLE_OPERATORS.include?(string) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/multiline_if_then.rb
lib/rubocop/cop/style/multiline_if_then.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for uses of the `then` keyword in multi-line if statements. # # @example # # bad # # This is considered bad practice. # if cond then # end # # # good # # If statements can contain `then` on the same line. # if cond then a # elsif cond then b # end class MultilineIfThen < Base include OnNormalIfUnless include RangeHelp extend AutoCorrector NON_MODIFIER_THEN = /then\s*(#.*)?$/.freeze MSG = 'Do not use `then` for multi-line `%<keyword>s`.' def on_normal_if_unless(node) return unless non_modifier_then?(node) add_offense(node.loc.begin, message: format(MSG, keyword: node.keyword)) do |corrector| corrector.remove(range_with_surrounding_space(node.loc.begin, side: :left)) end end private def non_modifier_then?(node) NON_MODIFIER_THEN.match?(node.loc.begin&.source_line) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/random_with_offset.rb
lib/rubocop/cop/style/random_with_offset.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for the use of randomly generated numbers, # added/subtracted with integer literals, as well as those with # Integer#succ and Integer#pred methods. Prefer using ranges instead, # as it clearly states the intentions. # # @example # # bad # rand(6) + 1 # 1 + rand(6) # rand(6) - 1 # 1 - rand(6) # rand(6).succ # rand(6).pred # Random.rand(6) + 1 # Kernel.rand(6) + 1 # rand(0..5) + 1 # # # good # rand(1..6) # rand(1...7) class RandomWithOffset < Base extend AutoCorrector MSG = 'Prefer ranges when generating random numbers instead of integers with offsets.' RESTRICT_ON_SEND = %i[+ - succ pred next].freeze # @!method integer_op_rand?(node) def_node_matcher :integer_op_rand?, <<~PATTERN (send int {:+ :-} (send {nil? (const {nil? cbase} :Random) (const {nil? cbase} :Kernel)} :rand {int (range int int)})) PATTERN # @!method rand_op_integer?(node) def_node_matcher :rand_op_integer?, <<~PATTERN (send (send {nil? (const {nil? cbase} :Random) (const {nil? cbase} :Kernel)} :rand {int (range int int)}) {:+ :-} int) PATTERN # @!method rand_modified?(node) def_node_matcher :rand_modified?, <<~PATTERN (send (send {nil? (const {nil? cbase} :Random) (const {nil? cbase} :Kernel)} :rand {int (range int int)}) {:succ :pred :next}) PATTERN def on_send(node) return unless node.receiver return unless integer_op_rand?(node) || rand_op_integer?(node) || rand_modified?(node) add_offense(node) { |corrector| autocorrect(corrector, node) } end private # @!method random_call(node) def_node_matcher :random_call, <<~PATTERN {(send (send $_ _ $_) ...) (send _ _ (send $_ _ $_))} PATTERN def autocorrect(corrector, node) if integer_op_rand?(node) corrector.replace(node, corrected_integer_op_rand(node)) elsif rand_op_integer?(node) corrector.replace(node, corrected_rand_op_integer(node)) elsif rand_modified?(node) corrector.replace(node, corrected_rand_modified(node)) end end def corrected_integer_op_rand(node) random_call(node) do |prefix_node, random_node| prefix = prefix_from_prefix_node(prefix_node) left_int, right_int = boundaries_from_random_node(random_node) offset = to_int(node.receiver) if node.method?(:+) "#{prefix}(#{offset + left_int}..#{offset + right_int})" else "#{prefix}(#{offset - right_int}..#{offset - left_int})" end end end def corrected_rand_op_integer(node) random_call(node) do |prefix_node, random_node| prefix = prefix_from_prefix_node(prefix_node) left_int, right_int = boundaries_from_random_node(random_node) offset = to_int(node.first_argument) if node.method?(:+) "#{prefix}(#{left_int + offset}..#{right_int + offset})" else "#{prefix}(#{left_int - offset}..#{right_int - offset})" end end end def corrected_rand_modified(node) random_call(node) do |prefix_node, random_node| prefix = prefix_from_prefix_node(prefix_node) left_int, right_int = boundaries_from_random_node(random_node) if %i[succ next].include?(node.method_name) "#{prefix}(#{left_int + 1}..#{right_int + 1})" elsif node.method?(:pred) "#{prefix}(#{left_int - 1}..#{right_int - 1})" end end end def prefix_from_prefix_node(node) [node&.source, 'rand'].compact.join('.') end def boundaries_from_random_node(random_node) case random_node.type when :int [0, to_int(random_node) - 1] when :irange [to_int(random_node.begin), to_int(random_node.end)] when :erange [to_int(random_node.begin), to_int(random_node.end) - 1] end end # @!method to_int(node) def_node_matcher :to_int, <<~PATTERN (int $_) PATTERN end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/hash_except.rb
lib/rubocop/cop/style/hash_except.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for usages of `Hash#reject`, `Hash#select`, and `Hash#filter` methods # that can be replaced with `Hash#except` method. # # This cop should only be enabled on Ruby version 3.0 or higher. # (`Hash#except` was added in Ruby 3.0.) # # For safe detection, it is limited to commonly used string and symbol comparisons # when using `==` or `!=`. # # This cop doesn't check for `Hash#delete_if` and `Hash#keep_if` because they # modify the receiver. # # @safety # This cop is unsafe because it cannot be guaranteed that the receiver # is a `Hash` or responds to the replacement method. # # @example # # # bad # {foo: 1, bar: 2, baz: 3}.reject {|k, v| k == :bar } # {foo: 1, bar: 2, baz: 3}.select {|k, v| k != :bar } # {foo: 1, bar: 2, baz: 3}.filter {|k, v| k != :bar } # {foo: 1, bar: 2, baz: 3}.reject {|k, v| k.eql?(:bar) } # # # bad # {foo: 1, bar: 2, baz: 3}.reject {|k, v| %i[bar].include?(k) } # {foo: 1, bar: 2, baz: 3}.select {|k, v| !%i[bar].include?(k) } # {foo: 1, bar: 2, baz: 3}.filter {|k, v| !%i[bar].include?(k) } # # # good # {foo: 1, bar: 2, baz: 3}.except(:bar) # # @example AllCops:ActiveSupportExtensionsEnabled: false (default) # # # good # {foo: 1, bar: 2, baz: 3}.reject {|k, v| !%i[bar].exclude?(k) } # {foo: 1, bar: 2, baz: 3}.select {|k, v| %i[bar].exclude?(k) } # # # good # {foo: 1, bar: 2, baz: 3}.reject {|k, v| k.in?(%i[bar]) } # {foo: 1, bar: 2, baz: 3}.select {|k, v| !k.in?(%i[bar]) } # # @example AllCops:ActiveSupportExtensionsEnabled: true # # # bad # {foo: 1, bar: 2, baz: 3}.reject {|k, v| !%i[bar].exclude?(k) } # {foo: 1, bar: 2, baz: 3}.select {|k, v| %i[bar].exclude?(k) } # # # bad # {foo: 1, bar: 2, baz: 3}.reject {|k, v| k.in?(%i[bar]) } # {foo: 1, bar: 2, baz: 3}.select {|k, v| !k.in?(%i[bar]) } # # # good # {foo: 1, bar: 2, baz: 3}.except(:bar) # class HashExcept < Base include HashSubset extend TargetRubyVersion extend AutoCorrector minimum_target_ruby_version 3.0 private def semantically_subset_method?(node) semantically_except_method?(node) end def preferred_method_name 'except' end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/conditional_assignment.rb
lib/rubocop/cop/style/conditional_assignment.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Helper module to provide common methods to classes needed for the # ConditionalAssignment Cop. module ConditionalAssignmentHelper extend NodePattern::Macros EQUAL = '=' END_ALIGNMENT = 'Layout/EndAlignment' ALIGN_WITH = 'EnforcedStyleAlignWith' KEYWORD = 'keyword' # `elsif` branches show up in the `node` as an `else`. We need # to recursively iterate over all `else` branches and consider all # but the last `node` an `elsif` branch and consider the last `node` # the actual `else` branch. def expand_elses(branch) elsif_branches = expand_elsif(branch) else_branch = elsif_branches.any? ? elsif_branches.pop : branch [elsif_branches, else_branch] end # `when` nodes contain the entire branch including the condition. # We only need the contents of the branch, not the condition. def expand_when_branches(when_branches) when_branches.map(&:body) end def tail(branch) branch.begin_type? ? Array(branch).last : branch end def lhs(node) case node.type when :send lhs_for_send(node) when :op_asgn, :and_asgn, :or_asgn "#{node.assignment_node.source} #{node.operator}= " when :casgn lhs_for_casgn(node) when *ConditionalAssignment::VARIABLE_ASSIGNMENT_TYPES "#{node.name} = " else node.source end end def indent(cop, source) conf = cop.config.for_cop(END_ALIGNMENT) if conf[ALIGN_WITH] == KEYWORD ' ' * source.length else '' end end def end_with_eq?(sym) sym.to_s.end_with?(EQUAL) end private def expand_elsif(node, elsif_branches = []) return [] if node.nil? || !node.if_type? || !node.elsif? elsif_branches << node.if_branch else_branch = node.else_branch if else_branch&.if_type? && else_branch.elsif? expand_elsif(else_branch, elsif_branches) else elsif_branches << else_branch end end def lhs_for_send(node) receiver = node.receiver ? node.receiver.source : '' if node.method?(:[]=) indices = node.arguments[0...-1].map(&:source).join(', ') "#{receiver}[#{indices}] = " elsif node.setter_method? "#{receiver}.#{node.method_name[0...-1]} = " else "#{receiver} #{node.method_name} " end end def lhs_for_casgn(node) if node.namespace.nil? "#{node.name} = " elsif node.namespace.cbase_type? "::#{node.name} = " else "#{node.namespace.const_name}::#{node.name} = " end end def setter_method?(method_name) method_name.to_s.end_with?(EQUAL) && !%i[!= == === >= <=].include?(method_name) end def assignment_rhs_exist?(node) parent = node.parent return true unless parent !parent.type?(:mlhs, :resbody) end end # 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. # # @example EnforcedStyle: assign_to_condition (default) # # bad # if foo # bar = 1 # else # bar = 2 # end # # case foo # when 'a' # bar += 1 # else # bar += 2 # end # # if foo # some_method # bar = 1 # else # some_other_method # bar = 2 # end # # # good # bar = if foo # 1 # else # 2 # end # # bar += case foo # when 'a' # 1 # else # 2 # end # # bar << if foo # some_method # 1 # else # some_other_method # 2 # end # # @example EnforcedStyle: assign_inside_condition # # bad # bar = if foo # 1 # else # 2 # end # # bar += case foo # when 'a' # 1 # else # 2 # end # # bar << if foo # some_method # 1 # else # some_other_method # 2 # end # # # good # if foo # bar = 1 # else # bar = 2 # end # # case foo # when 'a' # bar += 1 # else # bar += 2 # end # # if foo # some_method # bar = 1 # else # some_other_method # bar = 2 # end class ConditionalAssignment < Base include ConditionalAssignmentHelper include ConfigurableEnforcedStyle extend AutoCorrector MSG = 'Use the return of the conditional for variable assignment and comparison.' ASSIGN_TO_CONDITION_MSG = 'Assign variables inside of conditionals.' VARIABLE_ASSIGNMENT_TYPES = %i[casgn cvasgn gvasgn ivasgn lvasgn].freeze ASSIGNMENT_TYPES = VARIABLE_ASSIGNMENT_TYPES + %i[and_asgn or_asgn op_asgn masgn].freeze ENABLED = 'Enabled' SINGLE_LINE_CONDITIONS_ONLY = 'SingleLineConditionsOnly' # The shovel operator `<<` does not have its own type. It is a `send` # type. # @!method assignment_type?(node) def_node_matcher :assignment_type?, <<~PATTERN { #{ASSIGNMENT_TYPES.join(' ')} (send _recv {:[]= :<< :=~ :!~ :<=> #end_with_eq? :< :>} ...) } PATTERN ASSIGNMENT_TYPES.each do |type| define_method :"on_#{type}" do |node| return if part_of_ignored_node?(node) return if node.parent&.shorthand_asgn? check_assignment_to_condition(node) end end def on_send(node) return unless assignment_type?(node) check_assignment_to_condition(node) end def on_if(node) return unless style == :assign_to_condition return if node.elsif? else_branch = node.else_branch elsif_branches, else_branch = expand_elses(else_branch) return unless else_branch branches = [node.if_branch, *elsif_branches, else_branch] check_node(node, branches) end def on_case(node) return unless style == :assign_to_condition return unless node.else_branch when_branches = expand_when_branches(node.when_branches) branches = [*when_branches, node.else_branch] check_node(node, branches) end def on_case_match(node) return unless style == :assign_to_condition return unless node.else_branch in_pattern_branches = expand_when_branches(node.in_pattern_branches) branches = [*in_pattern_branches, node.else_branch] check_node(node, branches) end private 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 return unless else_branch return if allowed_single_line?([*branches, else_branch]) add_offense(node, message: ASSIGN_TO_CONDITION_MSG) do |corrector| autocorrect(corrector, node) end end def candidate_node?(node) style == :assign_inside_condition && assignment_rhs_exist?(node) end # @!method candidate_condition?(node) def_node_matcher :candidate_condition?, '[{if case case_match} !#allowed_ternary?]' def allowed_ternary?(assignment) assignment.if_type? && assignment.ternary? && !include_ternary? end def allowed_single_line?(branches) single_line_conditions_only? && branches.compact.any?(&:begin_type?) end 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 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 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 def ternary_condition?(node) [node, node.children.first].compact.any? { |n| n.if_type? && n.ternary? } end def lhs_all_match?(branches) return true if branches.empty? first_lhs = lhs(branches.first) branches.all? { |branch| lhs(branch) == first_lhs } end def assignment_types_match?(*nodes) return false unless assignment_type?(nodes.first) nodes.map(&:type).uniq.one? end 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) add_offense(node) { |corrector| autocorrect(corrector, node) } end def autocorrect(corrector, node) if assignment_type?(node) move_assignment_inside_condition(corrector, node) else move_assignment_outside_condition(corrector, node) end end 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 # 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 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 def longest_line_exceeds_line_limit?(node, assignment) longest_line(node, assignment).length > max_line_length end 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 def single_line_conditions_only? cop_config[SINGLE_LINE_CONDITIONS_ONLY] end def include_ternary? cop_config['IncludeTernaryExpressions'] end end # Helper module to provide common methods to ConditionalAssignment # correctors module ConditionalCorrectorHelper # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity def remove_whitespace_in_branches(corrector, branch, condition, column) branch.each_node do |child| next if child.source_range.nil? next if child.parent.dstr_type? white_space = white_space_range(child, column) corrector.remove(white_space) if white_space end if condition.loc.else && !same_line?(condition.else_branch, condition) corrector.remove_preceding(condition.loc.else, condition.loc.else.column - column) end return unless condition.loc.end && !same_line?( condition.branches.last.parent.else_branch, condition.loc.end ) corrector.remove_preceding(condition.loc.end, condition.loc.end.column - column) end # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity def same_line?(node1, node2) RuboCop::Cop::Util.same_line?(node1, node2) end def white_space_range(node, column) expression = node.source_range end_pos = expression.begin_pos begin_pos = end_pos - (expression.column - column - 2) return nil if begin_pos > end_pos white_space = Parser::Source::Range.new(expression.source_buffer, begin_pos, end_pos) white_space if white_space.source.strip.empty? end def assignment(node) condition = node.send_type? ? node.last_argument : node.expression node.source_range.begin.join(condition.source_range.begin) end def correct_if_branches(corrector, cop, node) if_branch, elsif_branches, else_branch = extract_tail_branches(node) corrector.insert_before(node, lhs(if_branch)) replace_branch_assignment(corrector, if_branch) correct_branches(corrector, elsif_branches) replace_branch_assignment(corrector, else_branch) corrector.insert_before(node.loc.end, indent(cop, lhs(if_branch))) end def replace_branch_assignment(corrector, branch) _variable, *_operator, assignment = *branch source = assignment.source replacement = if assignment.array_type? && !assignment.bracketed? "[#{source}]" else source end corrector.replace(branch, replacement) end def correct_branches(corrector, branches) branches.each do |branch| *_, assignment = *branch corrector.replace(branch, assignment.source) end end end # Corrector to correct conditional assignment in ternary conditions. class TernaryCorrector class << self include ConditionalAssignmentHelper include ConditionalCorrectorHelper def correct(corrector, node) corrector.replace(node, correction(node)) end def move_assignment_inside_condition(corrector, node) rhs = node.send_type? ? node.last_argument : node.expression if_branch, else_branch = extract_branches(node) assignment = assignment(node) remove_parentheses(corrector, rhs) if Util.parentheses?(rhs) corrector.remove(assignment) move_branch_inside_condition(corrector, if_branch, assignment) move_branch_inside_condition(corrector, else_branch, assignment) end private def correction(node) "#{lhs(node.if_branch)}#{ternary(node)}" end def ternary(node) _variable, *_operator, if_rhs = *node.if_branch _else_variable, *_operator, else_rhs = *node.else_branch expr = "#{node.condition.source} ? #{if_rhs.source} : #{else_rhs.source}" element_assignment?(node.if_branch) ? "(#{expr})" : expr end def element_assignment?(node) node.send_type? && !node.method?(:[]=) end def extract_branches(node) rhs = node.send_type? ? node.last_argument : node.expression condition = rhs.children.first if rhs.begin_type? && rhs.children.one? _condition, if_branch, else_branch = *(condition || rhs) [if_branch, else_branch] end def remove_parentheses(corrector, node) corrector.remove(node.loc.begin) corrector.remove(node.loc.end) end def move_branch_inside_condition(corrector, branch, assignment) corrector.insert_before(branch, assignment.source) end end end # Corrector to correct conditional assignment in `if` statements. class IfCorrector class << self include ConditionalAssignmentHelper include ConditionalCorrectorHelper def correct(corrector, cop, node) correct_if_branches(corrector, cop, node) end def move_assignment_inside_condition(corrector, node) column = node.source_range.column condition = node.send_type? ? node.last_argument : node.expression assignment = assignment(node) corrector.remove(assignment) condition.branches.flatten.each do |branch| move_branch_inside_condition(corrector, branch, condition, assignment, column) end end private def extract_tail_branches(node) if_branch, *elsif_branches, else_branch = *node.branches elsif_branches.map! { |branch| tail(branch) } [tail(if_branch), elsif_branches, tail(else_branch)] end def move_branch_inside_condition(corrector, branch, condition, assignment, column) branch_assignment = tail(branch) corrector.insert_before(branch_assignment, assignment.source) remove_whitespace_in_branches(corrector, branch, condition, column) return unless (branch_else = branch.parent.loc.else) return if same_line?(branch_else, condition) corrector.remove_preceding(branch_else, branch_else.column - column) end end end # Corrector to correct conditional assignment in `case` statements. class CaseCorrector class << self include ConditionalAssignmentHelper include ConditionalCorrectorHelper def correct(corrector, cop, node) when_branches, else_branch = extract_tail_branches(node) corrector.insert_before(node, lhs(else_branch)) correct_branches(corrector, when_branches) replace_branch_assignment(corrector, else_branch) corrector.insert_before(node.loc.end, indent(cop, lhs(else_branch))) end def move_assignment_inside_condition(corrector, node) column = node.source_range.column condition = node.send_type? ? node.last_argument : node.expression assignment = assignment(node) corrector.remove(assignment) extract_branches(condition).flatten.each do |branch| move_branch_inside_condition(corrector, branch, condition, assignment, column) end end private def extract_tail_branches(node) when_branches, else_branch = extract_branches(node) when_branches.map! { |branch| tail(branch) } [when_branches, tail(else_branch)] end def extract_branches(case_node) when_branches = if case_node.case_type? expand_when_branches(case_node.when_branches) else expand_when_branches(case_node.in_pattern_branches) end [when_branches, case_node.else_branch] end def move_branch_inside_condition(corrector, branch, condition, assignment, column) branch_assignment = tail(branch) corrector.insert_before(branch_assignment, assignment.source) remove_whitespace_in_branches(corrector, branch, condition, column) parent_keyword = branch.parent.loc.keyword corrector.remove_preceding(parent_keyword, parent_keyword.column - column) end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_filter_chain.rb
lib/rubocop/cop/style/redundant_filter_chain.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Identifies usages of `any?`, `empty?` or `none?` predicate methods # chained to `select`/`filter`/`find_all` and change them to use predicate method instead. # # @safety # This cop's autocorrection is unsafe because `array.select.any?` evaluates all elements # through the `select` method, while `array.any?` uses short-circuit evaluation. # In other words, `array.select.any?` guarantees the evaluation of every element, # but `array.any?` does not necessarily evaluate all of them. # # @example # # bad # arr.select { |x| x > 1 }.any? # # # good # arr.any? { |x| x > 1 } # # # bad # arr.select { |x| x > 1 }.empty? # arr.select { |x| x > 1 }.none? # # # good # arr.none? { |x| x > 1 } # # # good # relation.select(:name).any? # arr.select { |x| x > 1 }.any?(&:odd?) # # @example AllCops:ActiveSupportExtensionsEnabled: false (default) # # good # arr.select { |x| x > 1 }.many? # # # good # arr.select { |x| x > 1 }.present? # # @example AllCops:ActiveSupportExtensionsEnabled: true # # bad # arr.select { |x| x > 1 }.many? # # # good # arr.many? { |x| x > 1 } # # # bad # arr.select { |x| x > 1 }.present? # # # good # arr.any? { |x| x > 1 } # class RedundantFilterChain < Base extend AutoCorrector MSG = 'Use `%<prefer>s` instead of `%<first_method>s.%<second_method>s`.' RAILS_METHODS = %i[many? present?].freeze RESTRICT_ON_SEND = (%i[any? empty? none? one?] + RAILS_METHODS).freeze # @!method select_predicate?(node) def_node_matcher :select_predicate?, <<~PATTERN (call { (block $(call _ {:select :filter :find_all}) ...) $(call _ {:select :filter :find_all} block_pass_type?) } ${:#{RESTRICT_ON_SEND.join(' :')}}) PATTERN REPLACEMENT_METHODS = { any?: :any?, empty?: :none?, none?: :none?, one?: :one?, many?: :many?, present?: :any? }.freeze private_constant :REPLACEMENT_METHODS def on_send(node) return if node.arguments? || node.block_literal? select_predicate?(node) do |select_node, filter_method| return if RAILS_METHODS.include?(filter_method) && !active_support_extensions_enabled? register_offense(select_node, node) end end alias on_csend on_send private def register_offense(select_node, predicate_node) replacement = REPLACEMENT_METHODS[predicate_node.method_name] message = format(MSG, prefer: replacement, first_method: select_node.method_name, second_method: predicate_node.method_name) offense_range = offense_range(select_node, predicate_node) add_offense(offense_range, message: message) do |corrector| corrector.remove(predicate_range(predicate_node)) corrector.replace(select_node.loc.selector, replacement) end end def offense_range(select_node, predicate_node) select_node.loc.selector.join(predicate_node.loc.selector) end def predicate_range(predicate_node) predicate_node.receiver.source_range.end.join(predicate_node.loc.selector) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/map_into_array.rb
lib/rubocop/cop/style/map_into_array.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for usages of `each` with `<<`, `push`, or `append` which # can be replaced by `map`. # # If `PreferredMethods` is configured for `map` in `Style/CollectionMethods`, # this cop uses the specified method for replacement. # # NOTE: The return value of `Enumerable#each` is `self`, whereas the # return value of `Enumerable#map` is an `Array`. They are not autocorrected # when a return value could be used because these types differ. # # NOTE: It only detects when the mapping destination is either: # * a local variable initialized as an empty array and referred to only by the # pushing operation; # * or, if it is the single block argument to a `[].tap` block. # This is because, if not, it's challenging to statically guarantee that the # mapping destination variable remains an empty array: # # [source,ruby] # ---- # ret = [] # src.each { |e| ret << e * 2 } # `<<` method may mutate `ret` # # dest = [] # src.each { |e| dest << transform(e, dest) } # `transform` method may mutate `dest` # ---- # # @safety # This cop is unsafe because not all objects that have an `each` # method also have a `map` method (e.g. `ENV`). Additionally, for calls # with a block, not all objects that have a `map` method return an array # (e.g. `Enumerator::Lazy`). # # @example # # bad # dest = [] # src.each { |e| dest << e * 2 } # dest # # # good # dest = src.map { |e| e * 2 } # # # bad # [].tap do |dest| # src.each { |e| dest << e * 2 } # end # # # good # dest = src.map { |e| e * 2 } # # # good - contains another operation # dest = [] # src.each { |e| dest << e * 2; puts e } # dest # class MapIntoArray < Base include RangeHelp extend AutoCorrector MSG = 'Use `%<new_method_name>s` instead of `each` to map elements into an array.' # @!method suitable_argument_node?(node) def_node_matcher :suitable_argument_node?, <<-PATTERN !{splat forwarded-restarg forwarded-args (hash (forwarded-kwrestarg)) (block-pass nil?)} PATTERN # @!method each_block_with_push?(node) def_node_matcher :each_block_with_push?, <<-PATTERN [ ^({begin kwbegin block} ...) (any_block (send !{nil? self} :each) _ (send (lvar _) {:<< :push :append} #suitable_argument_node?)) ] PATTERN # @!method empty_array_asgn?(node) def_node_matcher :empty_array_asgn?, <<~PATTERN ( lvasgn _ { (array) (send (const {nil? cbase} :Array) :[]) (send (const {nil? cbase} :Array) :new (array)?) (send nil? :Array (array)) } ) PATTERN # @!method empty_array_tap(node) def_node_matcher :empty_array_tap, <<~PATTERN ^^$( block (send (array) :tap) (args (arg _)) ... ) PATTERN # @!method lvar_ref?(node, name) def_node_matcher :lvar_ref?, '(lvar %1)' def self.joining_forces VariableForce end def after_leaving_scope(scope, _variable_table) (@scopes ||= []) << scope end def on_block(node) return unless each_block_with_push?(node) dest_var = find_dest_var(node) if offending_empty_array_tap?(node, dest_var) asgn = dest_var.declaration_node else return unless (asgn = find_closest_assignment(node, dest_var)) return unless empty_array_asgn?(asgn) return unless dest_used_only_for_mapping?(node, dest_var, asgn) end register_offense(node, dest_var, asgn) end alias on_numblock on_block alias on_itblock on_block private def find_dest_var(block) node = block.body.receiver name = node.children.first candidates = @scopes.lazy.filter_map { |s| s.variables[name] } candidates.find { |v| v.references.any? { |n| n.node.equal?(node) } } end def offending_empty_array_tap?(node, dest_var) return false unless (tap_block_node = empty_array_tap(dest_var.declaration_node)) # A `tap` block only offends if the array push is the only thing in it; # otherwise we cannot guarantee that the block variable is still an empty # array when pushed to. tap_block_node.body == node end def find_closest_assignment(block, dest_var) dest_var.assignments.reverse_each.lazy.map(&:node).find do |node| node.source_range.end_pos < block.source_range.begin_pos end end def dest_used_only_for_mapping?(block, dest_var, asgn) range = asgn.source_range.join(block.source_range) asgn.parent.equal?(block.parent) && dest_var.references.one? { |r| range.contains?(r.node.source_range) } && dest_var.assignments.one? { |a| range.contains?(a.node.source_range) } end def register_offense(block, dest_var, asgn) add_offense(block, message: format(MSG, new_method_name: new_method_name)) do |corrector| next if return_value_used?(block) corrector.replace(block.send_node.selector, new_method_name) if (tap_block_node = empty_array_tap(dest_var.declaration_node)) remove_tap(corrector, block, tap_block_node) else remove_assignment(corrector, asgn) end correct_push_node(corrector, block.body) correct_return_value_handling(corrector, block, dest_var) end end def new_method_name default = 'map' alternative = config.for_cop('Style/CollectionMethods').dig('PreferredMethods', default) alternative || default end def return_value_used?(node) parent = node.parent case parent&.type when nil false when :begin, :kwbegin !node.right_sibling && return_value_used?(parent) else !parent.respond_to?(:void_context?) || !parent.void_context? end end def remove_assignment(corrector, asgn) range = range_with_surrounding_space(asgn.source_range, side: :right) range = range_with_surrounding_space(range, side: :right, newlines: false) corrector.remove(range) end def remove_tap(corrector, node, block_node) range = range_between(block_node.source_range.begin_pos, node.source_range.begin_pos) corrector.remove(range) corrector.remove(range_with_surrounding_space(block_node.loc.end, side: :left)) end def correct_push_node(corrector, push_node) arg_node = push_node.first_argument range = push_node.source_range arg_range = arg_node.source_range corrector.wrap(arg_node, '{ ', ' }') if arg_node.hash_type? && !arg_node.braces? corrector.remove(range_between(range.begin_pos, arg_range.begin_pos)) corrector.remove(range_between(arg_range.end_pos, range.end_pos)) end def correct_return_value_handling(corrector, block, dest_var) next_node = block.right_sibling if lvar_ref?(next_node, dest_var.name) corrector.remove(range_with_surrounding_space(next_node.source_range, side: :left)) end corrector.insert_before(block, "#{dest_var.name} = ") end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/return_nil_in_predicate_method_definition.rb
lib/rubocop/cop/style/return_nil_in_predicate_method_definition.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for predicate method definitions that return `nil`. # A predicate method should only return a boolean value. # # @safety # Autocorrection is marked as unsafe because the change of the return value # from `nil` to `false` could potentially lead to incompatibility issues. # # @example # # bad # def foo? # return if condition # # do_something? # end # # # bad # def foo? # return nil if condition # # do_something? # end # # # good # def foo? # return false if condition # # do_something? # end # # # bad # def foo? # if condition # nil # else # true # end # end # # # good # def foo? # if condition # false # else # true # end # end # # @example AllowedMethods: ['foo?'] # # good # def foo? # return if condition # # do_something? # end # # @example AllowedPatterns: [/foo/] # # good # def foo? # return if condition # # do_something? # end # class ReturnNilInPredicateMethodDefinition < Base extend AutoCorrector include AllowedMethods include AllowedPattern MSG = 'Return `false` instead of `nil` in predicate methods.' # @!method return_nil?(node) def_node_matcher :return_nil?, <<~PATTERN {(return) (return (nil))} PATTERN def on_def(node) return unless node.predicate_method? return if allowed_method?(node.method_name) || matches_allowed_pattern?(node.method_name) return unless (body = node.body) body.each_descendant(:return) { |return_node| handle_return(return_node) } handle_implicit_return_values(body) end alias on_defs on_def private def last_node_of_type(node, type) return unless node return node if node_type?(node, type) return unless node.begin_type? return unless (last_child = node.children.last) last_child if last_child.is_a?(AST::Node) && node_type?(last_child, type) end def node_type?(node, type) node.type == type.to_sym end def register_offense(offense_node, replacement) add_offense(offense_node) do |corrector| corrector.replace(offense_node, replacement) end end def handle_implicit_return_values(node) handle_if(last_node_of_type(node, :if)) handle_nil(last_node_of_type(node, :nil)) end def handle_return(return_node) register_offense(return_node, 'return false') if return_nil?(return_node) end def handle_nil(nil_node) return unless nil_node register_offense(nil_node, 'false') end def handle_if(if_node) return unless if_node handle_implicit_return_values(if_node.if_branch) handle_implicit_return_values(if_node.else_branch) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/array_intersect_with_single_element.rb
lib/rubocop/cop/style/array_intersect_with_single_element.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Use `include?(element)` instead of `intersect?([element])`. # # @safety # The receiver might not be an array. # # @example # # bad # array.intersect?([element]) # # # good # array.include?(element) class ArrayIntersectWithSingleElement < Base extend AutoCorrector MSG = 'Use `include?(element)` instead of `intersect?([element])`.' RESTRICT_ON_SEND = %i[intersect?].freeze # @!method single_element(node) def_node_matcher :single_element, <<~PATTERN (send _ _ $(array $_)) PATTERN def on_send(node) array, element = single_element(node) return unless array add_offense( node.source_range.with(begin_pos: node.loc.selector.begin_pos) ) do |corrector| corrector.replace(node.loc.selector, 'include?') corrector.replace( array, array.percent_literal? ? element.value.inspect : element.source ) end end alias on_csend on_send end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/env_home.rb
lib/rubocop/cop/style/env_home.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for consistent usage of `ENV['HOME']`. If `nil` is used as # the second argument of `ENV.fetch`, it is treated as a bad case like `ENV[]`. # # @safety # The cop is unsafe because the result when `nil` is assigned to `ENV['HOME']` changes: # # [source,ruby] # ---- # ENV['HOME'] = nil # ENV['HOME'] # => nil # Dir.home # => '/home/foo' # ---- # # @example # # # bad # ENV['HOME'] # ENV.fetch('HOME', nil) # # # good # Dir.home # # # good # ENV.fetch('HOME', default) # class EnvHome < Base extend AutoCorrector MSG = 'Use `Dir.home` instead.' RESTRICT_ON_SEND = %i[[] fetch].freeze # @!method env_home?(node) def_node_matcher :env_home?, <<~PATTERN (send (const {cbase nil?} :ENV) {:[] :fetch} (str "HOME") ...) PATTERN def on_send(node) return unless env_home?(node) return if node.arguments.count == 2 && !node.arguments[1].nil_type? add_offense(node) do |corrector| corrector.replace(node, 'Dir.home') end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/comparable_clamp.rb
lib/rubocop/cop/style/comparable_clamp.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Enforces the use of `Comparable#clamp` instead of comparison by minimum and maximum. # # This cop supports autocorrection for `if/elsif/else` bad style only. # Because `ArgumentError` occurs if the minimum and maximum of `clamp` arguments are reversed. # When these are variables, it is not possible to determine which is the minimum and maximum: # # [source,ruby] # ---- # [1, [2, 3].max].min # => 1 # 1.clamp(3, 1) # => min argument must be smaller than max argument (ArgumentError) # ---- # # @example # # # bad # [[x, low].max, high].min # # # bad # if x < low # low # elsif high < x # high # else # x # end # # # good # x.clamp(low, high) # class ComparableClamp < Base include Alignment extend AutoCorrector extend TargetRubyVersion minimum_target_ruby_version 2.4 MSG = 'Use `%<prefer>s` instead of `if/elsif/else`.' MSG_MIN_MAX = 'Use `Comparable#clamp` instead.' RESTRICT_ON_SEND = %i[min max].freeze # @!method if_elsif_else_condition?(node) def_node_matcher :if_elsif_else_condition?, <<~PATTERN { (if (send _x :< _min) _min (if (send _max :< _x) _max _x)) (if (send _min :> _x) _min (if (send _max :< _x) _max _x)) (if (send _x :< _min) _min (if (send _x :> _max) _max _x)) (if (send _min :> _x) _min (if (send _x :> _max) _max _x)) (if (send _max :< _x) _max (if (send _x :< _min) _min _x)) (if (send _x :> _max) _max (if (send _x :< _min) _min _x)) (if (send _max :< _x) _max (if (send _min :> _x) _min _x)) (if (send _x :> _max) _max (if (send _min :> _x) _min _x)) } PATTERN # @!method array_min_max?(node) def_node_matcher :array_min_max?, <<~PATTERN { (send (array (send (array _ _) :max) _) :min) (send (array _ (send (array _ _) :max)) :min) (send (array (send (array _ _) :min) _) :max) (send (array _ (send (array _ _) :min)) :max) } PATTERN def on_if(node) return unless if_elsif_else_condition?(node) if_body, elsif_body, else_body = *node.branches else_body_source = else_body.source if min_condition?(node.condition, else_body_source) min = if_body.source max = elsif_body.source else min = elsif_body.source max = if_body.source end prefer = "#{else_body_source}.clamp(#{min}, #{max})" add_offense(node, message: format(MSG, prefer: prefer)) do |corrector| autocorrect(corrector, node, prefer) end end def on_send(node) return unless array_min_max?(node) add_offense(node, message: MSG_MIN_MAX) end private def autocorrect(corrector, node, prefer) if node.elsif? corrector.insert_before(node, "else\n") corrector.replace(node, "#{indentation(node)}#{prefer}") else corrector.replace(node, prefer) end end def min_condition?(if_condition, else_body) lhs, op, rhs = *if_condition (lhs.source == else_body && op == :<) || (rhs.source == else_body && op == :>) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/copyright.rb
lib/rubocop/cop/style/copyright.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Check that a copyright notice was given in each source file. # # The default regexp for an acceptable copyright notice can be found in # config/default.yml. The default can be changed as follows: # # [source,yaml] # ---- # Style/Copyright: # Notice: '^Copyright (\(c\) )?2\d{3} Acme Inc' # ---- # # This regex string is treated as an unanchored regex. For each file # that RuboCop scans, a comment that matches this regex must be found or # an offense is reported. # class Copyright < Base include RangeHelp extend AutoCorrector MSG = 'Include a copyright notice matching /%<notice>s/ before any code.' AUTOCORRECT_EMPTY_WARNING = 'An AutocorrectNotice must be defined in your RuboCop config' def on_new_investigation return if notice.empty? || notice_found?(processed_source) verify_autocorrect_notice! message = format(MSG, notice: notice) if processed_source.blank? add_global_offense(message) else offense_range = source_range(processed_source.buffer, 1, 0) add_offense(offense_range, message: message) do |corrector| autocorrect(corrector) end end end private def autocorrect(corrector) token = insert_notice_before(processed_source) range = token.nil? ? range_between(0, 0) : token.pos corrector.insert_before(range, "#{autocorrect_notice}\n") end def notice cop_config['Notice'] end def autocorrect_notice cop_config['AutocorrectNotice'] end def verify_autocorrect_notice! if autocorrect_notice.nil? || autocorrect_notice.empty? raise Warning, "#{cop_name}: #{AUTOCORRECT_EMPTY_WARNING}" end regex = Regexp.new(notice) return if autocorrect_notice.gsub(/^# */, '').match?(regex) message = "AutocorrectNotice '#{autocorrect_notice}' must match Notice /#{notice}/" raise Warning, "#{cop_name}: #{message}" end def insert_notice_before(processed_source) token_index = 0 token_index += 1 if shebang_token?(processed_source, token_index) token_index += 1 if encoding_token?(processed_source, token_index) processed_source.tokens[token_index] end def shebang_token?(processed_source, token_index) return false if token_index >= processed_source.tokens.size token = processed_source.tokens[token_index] token.comment? && /\A#!.*\z/.match?(token.text) end def encoding_token?(processed_source, token_index) return false if token_index >= processed_source.tokens.size token = processed_source.tokens[token_index] token.comment? && /\A#.*coding\s?[:=]\s?(?:UTF|utf)-8/.match?(token.text) end def notice_found?(processed_source) notice_regexp = Regexp.new(notice.lines.map(&:strip).join) multiline_notice = +'' processed_source.tokens.each do |token| break unless token.comment? multiline_notice << token.text.sub(/\A# */, '') break if notice_regexp.match?(token.text) end multiline_notice.match?(notice_regexp) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/non_nil_check.rb
lib/rubocop/cop/style/non_nil_check.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for non-nil checks, which are usually redundant. # # With `IncludeSemanticChanges` set to `false` by default, this cop # does not report offenses for `!x.nil?` and does no changes that might # change behavior. # Also `IncludeSemanticChanges` set to `false` with `EnforcedStyle: comparison` of # `Style/NilComparison` cop, this cop does not report offenses for `x != nil` and # does no changes to `!x.nil?` style. # # With `IncludeSemanticChanges` set to `true`, this cop reports offenses # for `!x.nil?` and autocorrects that and `x != nil` to solely `x`, which # is *usually* OK, but might change behavior. # # @example # # bad # if x != nil # end # # # good # if x # end # # # Non-nil checks are allowed if they are the final nodes of predicate. # # good # def signed_in? # !current_user.nil? # end # # @example IncludeSemanticChanges: false (default) # # good # if !x.nil? # end # # @example IncludeSemanticChanges: true # # bad # if !x.nil? # end # class NonNilCheck < Base extend AutoCorrector MSG_FOR_REPLACEMENT = 'Prefer `%<prefer>s` over `%<current>s`.' MSG_FOR_REDUNDANCY = 'Explicit non-nil checks are usually redundant.' RESTRICT_ON_SEND = %i[!= nil? !].freeze # @!method not_equal_to_nil?(node) def_node_matcher :not_equal_to_nil?, '(send _ :!= nil)' # @!method unless_check?(node) def_node_matcher :unless_check?, '(if (send _ :nil?) ...)' # @!method nil_check?(node) def_node_matcher :nil_check?, '(send _ :nil?)' # @!method not_and_nil_check?(node) def_node_matcher :not_and_nil_check?, '(send (send _ :nil?) :!)' def on_send(node) return if ignored_node?(node) || (!include_semantic_changes? && nil_comparison_style == 'comparison') return unless register_offense?(node) message = message(node) add_offense(node, message: message) { |corrector| autocorrect(corrector, node) } end def on_def(node) body = node.body return unless node.predicate_method? && body if body.begin_type? ignore_node(body.children.last) else ignore_node(body) end end alias on_defs on_def private def register_offense?(node) not_equal_to_nil?(node) || (include_semantic_changes? && (not_and_nil_check?(node) || unless_and_nil_check?(node))) end def autocorrect(corrector, node) case node.method_name when :!= autocorrect_comparison(corrector, node) when :! autocorrect_non_nil(corrector, node, node.receiver) when :nil? autocorrect_unless_nil(corrector, node, node.receiver) end end def unless_and_nil_check?(send_node) parent = send_node.parent nil_check?(send_node) && unless_check?(parent) && !parent.ternary? && parent.unless? end def message(node) if node.method?(:!=) && !include_semantic_changes? prefer = "!#{node.receiver.source}.nil?" format(MSG_FOR_REPLACEMENT, prefer: prefer, current: node.source) else MSG_FOR_REDUNDANCY end end def include_semantic_changes? cop_config['IncludeSemanticChanges'] end def autocorrect_comparison(corrector, node) expr = node.source new_code = if include_semantic_changes? expr.sub(/\s*!=\s*nil/, '') else expr.sub(/^(\S*)\s*!=\s*nil/, '!\1.nil?') end return if expr == new_code corrector.replace(node, new_code) end def autocorrect_non_nil(corrector, node, inner_node) if inner_node.receiver corrector.replace(node, inner_node.receiver.source) else corrector.replace(node, 'self') end end def autocorrect_unless_nil(corrector, node, receiver) corrector.replace(node.parent.loc.keyword, 'if') corrector.replace(node, receiver.source) end def nil_comparison_style nil_comparison_conf = config.for_cop('Style/NilComparison') nil_comparison_conf['Enabled'] && nil_comparison_conf['EnforcedStyle'] end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_condition.rb
lib/rubocop/cop/style/redundant_condition.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for unnecessary conditional expressions. # # NOTE: Since the intention of the comment cannot be automatically determined, # autocorrection is not applied when a comment is used, as shown below: # # [source,ruby] # ----- # if b # # Important note. # b # else # c # end # ----- # # @example # # bad # a = b ? b : c # # # good # a = b || c # # # bad # if b # b # else # c # end # # # good # b || c # # # good # if b # b # elsif cond # c # end # # # bad # a.nil? ? true : a # # # good # a.nil? || a # # # bad # if a.nil? # true # else # a # end # # # good # a.nil? || a # # @example AllowedMethods: ['nonzero?'] (default) # # good # num.nonzero? ? true : false # class RedundantCondition < Base include AllowedMethods include CommentsHelp include RangeHelp extend AutoCorrector MSG = 'Use double pipes `||` instead.' REDUNDANT_CONDITION = 'This condition is not needed.' ARGUMENT_WITH_OPERATOR_TYPES = %i[ splat block_pass forwarded_restarg forwarded_kwrestarg forwarded_args ].freeze def on_if(node) return if node.modifier_form? || node.elsif_conditional? || !offense?(node) message = message(node) add_offense(range_of_offense(node), message: message) do |corrector| autocorrect(corrector, node) end end private def message(node) if redundant_condition?(node) REDUNDANT_CONDITION else MSG end end def autocorrect(corrector, node) return if node.each_descendant.any? { |descendant| contains_comments?(descendant) } if node.ternary? && !branches_have_method?(node) correct_ternary(corrector, node) elsif redundant_condition?(node) corrector.replace(node, node.if_branch.source) else corrected = make_ternary_form(node) corrector.replace(node, corrected) end end def range_of_offense(node) return node.source_range unless node.ternary? return node.source_range if node.ternary? && branches_have_method?(node) range_between(node.loc.question.begin_pos, node.loc.colon.end_pos) end def offense?(node) _condition, _if_branch, else_branch = *node # rubocop:disable InternalAffairs/NodeDestructuring return false if use_if_branch?(else_branch) || use_hash_key_assignment?(else_branch) synonymous_condition_and_branch?(node) && !node.elsif? && (node.ternary? || !else_branch.instance_of?(AST::Node) || else_branch.single_line?) end def redundant_condition?(node) node.modifier_form? || !node.else_branch end def use_if_branch?(else_branch) else_branch&.if_type? end def use_hash_key_assignment?(else_branch) else_branch&.send_type? && else_branch.method?(:[]=) end def use_hash_key_access?(node) node.send_type? && node.method?(:[]) end def synonymous_condition_and_branch?(node) condition, if_branch, _else_branch = *node # rubocop:disable InternalAffairs/NodeDestructuring # e.g. # if var # var # else # 'foo' # end return true if condition == if_branch # e.g. # a.nil? ? true : a # or # if a.nil? # true # else # a # end return true if if_branch_is_true_type_and_else_is_not?(node) # e.g. # if foo # @value = foo # else # @value = another_value? # end return true if branches_have_assignment?(node) && condition == if_branch.expression # e.g. # if foo # test.value = foo # else # test.value = another_value? # end branches_have_method?(node) && condition == if_branch.first_argument && !use_hash_key_access?(if_branch) end # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity def if_branch_is_true_type_and_else_is_not?(node) return false unless node.ternary? || node.if? cond = node.condition return false unless cond.call_type? return false if !cond.predicate_method? || allowed_method?(cond.method_name) node.if_branch&.true_type? && node.else_branch && !node.else_branch.true_type? end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity def branches_have_assignment?(node) _condition, if_branch, else_branch = *node # rubocop:disable InternalAffairs/NodeDestructuring return false unless if_branch && else_branch asgn_type?(if_branch) && (if_branch_variable_name = if_branch.name) && asgn_type?(else_branch) && (else_branch_variable_name = else_branch.name) && if_branch_variable_name == else_branch_variable_name end def asgn_type?(node) node.type?(:lvasgn, :ivasgn, :cvasgn, :gvasgn, :casgn) end def branches_have_method?(node) return false unless node.if_branch && node.else_branch single_argument_method?(node.if_branch) && single_argument_method?(node.else_branch) && same_method?(node.if_branch, node.else_branch) end def single_argument_method?(node) return false if !node.send_type? || node.method?(:[]) || !node.arguments.one? !argument_with_operator?(node.first_argument) end def same_method?(if_branch, else_branch) if_branch.method?(else_branch.method_name) && if_branch.receiver == else_branch.receiver end # If the argument is using an operator, it is an invalid syntax. # e.g. `foo || *bar`, `foo || **bar`, and `foo || &bar`. def argument_with_operator?(argument) return true if ARGUMENT_WITH_OPERATOR_TYPES.include?(argument.type) return false unless argument.hash_type? return false unless (node = argument.children.first) node.type?(:kwsplat, :forwarded_kwrestarg) end def wrap_arguments_with_parens(condition) method = condition.source_range.begin.join(condition.loc.selector.end) arguments = condition.first_argument.source_range.begin.join(condition.source_range.end) "#{method.source}(#{arguments.source})" end # rubocop:disable Metrics/AbcSize def if_source(if_branch, arithmetic_operation) if branches_have_method?(if_branch.parent) && if_branch.parenthesized? if_branch.source.delete_suffix(')') elsif arithmetic_operation argument_source = if_branch.first_argument.source "#{if_branch.receiver.source} #{if_branch.method_name} (#{argument_source}" elsif if_branch.true_type? condition = if_branch.parent.condition return condition.source if condition.arguments.empty? || condition.parenthesized? wrap_arguments_with_parens(condition) else if_branch.source end end # rubocop:enable Metrics/AbcSize def else_source(else_branch, arithmetic_operation) # rubocop:disable Metrics/AbcSize if arithmetic_operation "#{else_branch.first_argument.source})" elsif branches_have_method?(else_branch.parent) else_source_if_has_method(else_branch) elsif require_parentheses?(else_branch) "(#{else_branch.source})" elsif without_argument_parentheses_method?(else_branch) "#{else_branch.method_name}(#{else_branch.arguments.map(&:source).join(', ')})" elsif branches_have_assignment?(else_branch.parent) else_source_if_has_assignment(else_branch) else else_branch.source end end def else_source_if_has_method(else_branch) if require_parentheses?(else_branch.first_argument) "(#{else_branch.first_argument.source})" elsif require_braces?(else_branch.first_argument) "{ #{else_branch.first_argument.source} }" else else_branch.first_argument.source end end def else_source_if_has_assignment(else_branch) if require_parentheses?(else_branch.expression) "(#{else_branch.expression.source})" elsif require_braces?(else_branch.expression) "{ #{else_branch.expression.source} }" else else_branch.expression.source end end def make_ternary_form(node) _condition, if_branch, else_branch = *node # rubocop:disable InternalAffairs/NodeDestructuring arithmetic_operation = use_arithmetic_operation?(if_branch) ternary_form = [ if_source(if_branch, arithmetic_operation), else_source(else_branch, arithmetic_operation) ].join(' || ') ternary_form += ')' if branches_have_method?(node) && if_branch.parenthesized? if node.parent&.send_type? "(#{ternary_form})" else ternary_form end end def correct_ternary(corrector, node) corrector.replace(range_of_offense(node), '||') return unless node.else_branch.range_type? corrector.wrap(node.else_branch, '(', ')') end def require_parentheses?(node) (node.basic_conditional? && node.modifier_form?) || node.range_type? || node.rescue_type? || (node.respond_to?(:semantic_operator?) && node.semantic_operator?) end def require_braces?(node) node.hash_type? && !node.braces? end def use_arithmetic_operation?(node) node.respond_to?(:arithmetic_operation?) && node.arithmetic_operation? end def without_argument_parentheses_method?(node) node.send_type? && !node.arguments.empty? && !node.parenthesized? && !node.operator_method? && !node.assignment_method? end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/symbol_proc.rb
lib/rubocop/cop/style/symbol_proc.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Use symbols as procs when possible. # # If you prefer a style that allows block for method with arguments, # please set `true` to `AllowMethodsWithArguments`. # `define_method?` methods are allowed by default. # These are customizable with `AllowedMethods` option. # # @safety # This cop is unsafe because there is a difference that a `Proc` # generated from `Symbol#to_proc` behaves as a lambda, while # a `Proc` generated from a block does not. # For example, a lambda will raise an `ArgumentError` if the # number of arguments is wrong, but a non-lambda `Proc` will not. # # For example: # # [source,ruby] # ---- # class Foo # def bar # :bar # end # end # # def call(options = {}, &block) # block.call(Foo.new, options) # end # # call { |x| x.bar } # #=> :bar # call(&:bar) # # ArgumentError: wrong number of arguments (given 1, expected 0) # ---- # # It is also unsafe because `Symbol#to_proc` does not work with # `protected` methods which would otherwise be accessible. # # For example: # # [source,ruby] # ---- # class Box # def initialize # @secret = rand # end # # def normal_matches?(*others) # others.map { |other| other.secret }.any?(secret) # end # # def symbol_to_proc_matches?(*others) # others.map(&:secret).any?(secret) # end # # protected # # attr_reader :secret # end # # boxes = [Box.new, Box.new] # Box.new.normal_matches?(*boxes) # # => false # boxes.first.normal_matches?(*boxes) # # => true # Box.new.symbol_to_proc_matches?(*boxes) # # => NoMethodError: protected method `secret' called for #<Box...> # boxes.first.symbol_to_proc_matches?(*boxes) # # => NoMethodError: protected method `secret' called for #<Box...> # ---- # # @example # # bad # something.map { |s| s.upcase } # something.map { _1.upcase } # # # good # something.map(&:upcase) # # @example AllowMethodsWithArguments: false (default) # # bad # something.do_something(foo) { |o| o.bar } # # # good # something.do_something(foo, &:bar) # # @example AllowMethodsWithArguments: true # # good # something.do_something(foo) { |o| o.bar } # # @example AllowComments: false (default) # # bad # something.do_something do |s| # some comment # # some comment # s.upcase # some comment # # some comment # end # # @example AllowComments: true # # good - if there are comment in either position # something.do_something do |s| # some comment # # some comment # s.upcase # some comment # # some comment # end # # @example AllowedMethods: [define_method] (default) # # good # define_method(:foo) { |foo| foo.bar } # # @example AllowedPatterns: [] (default) # # bad # something.map { |s| s.upcase } # # @example AllowedPatterns: ['map'] (default) # # good # something.map { |s| s.upcase } # # @example AllCops:ActiveSupportExtensionsEnabled: false (default) # # bad # ->(x) { x.foo } # proc { |x| x.foo } # Proc.new { |x| x.foo } # # # good # lambda(&:foo) # proc(&:foo) # Proc.new(&:foo) # # @example AllCops:ActiveSupportExtensionsEnabled: true # # good # ->(x) { x.foo } # proc { |x| x.foo } # Proc.new { |x| x.foo } # class SymbolProc < Base include CommentsHelp include RangeHelp include AllowedMethods include AllowedPattern extend AutoCorrector MSG = 'Pass `&:%<method>s` as an argument to `%<block_method>s` instead of a block.' SUPER_TYPES = %i[super zsuper].freeze LAMBDA_OR_PROC = %i[lambda proc].freeze # @!method proc_node?(node) def_node_matcher :proc_node?, '(send (const {nil? cbase} :Proc) :new)' # @!method symbol_proc_receiver?(node) def_node_matcher :symbol_proc_receiver?, '{(call ...) (super ...) zsuper}' # @!method symbol_proc?(node) def_node_matcher :symbol_proc?, <<~PATTERN { (block $#symbol_proc_receiver? $(args (arg _var)) (send (lvar _var) $_)) (numblock $#symbol_proc_receiver? $1 (send (lvar :_1) $_)) (itblock $#symbol_proc_receiver? $_ (send (lvar :it) $_)) } PATTERN def self.autocorrect_incompatible_with [Layout::SpaceBeforeBlockBraces] end # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity def on_block(node) symbol_proc?(node) do |dispatch_node, arguments_node, method_name| if active_support_extensions_enabled? return if proc_node?(dispatch_node) return if LAMBDA_OR_PROC.include?(dispatch_node.method_name) end return if unsafe_hash_usage?(dispatch_node) return if unsafe_array_usage?(dispatch_node) return if allowed_method_name?(dispatch_node.method_name) return if allow_if_method_has_argument?(node.send_node) return if node.block_type? && destructuring_block_argument?(arguments_node) return if allow_comments? && contains_comments?(node) register_offense(node, method_name, dispatch_node.method_name) end end # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity alias on_numblock on_block alias on_itblock on_block def destructuring_block_argument?(argument_node) argument_node.one? && argument_node.source.include?(',') end private # See: https://github.com/rubocop/rubocop/issues/10864 def unsafe_hash_usage?(node) node.receiver&.hash_type? && %i[reject select].include?(node.method_name) end def unsafe_array_usage?(node) node.receiver&.array_type? && %i[min max].include?(node.method_name) end def allowed_method_name?(name) allowed_method?(name) || matches_allowed_pattern?(name) end def register_offense(node, method_name, block_method_name) block_start = node.loc.begin.begin_pos block_end = node.loc.end.end_pos range = range_between(block_start, block_end) message = format(MSG, method: method_name, block_method: block_method_name) add_offense(range, message: message) { |corrector| autocorrect(corrector, node) } end def autocorrect(corrector, node) if node.send_node.arguments? autocorrect_with_args(corrector, node, node.send_node.arguments, node.body.method_name) else autocorrect_without_args(corrector, node) end end def autocorrect_without_args(corrector, node) if node.send_node.lambda_literal? if node.send_node.loc.selector.source == '->' corrector.replace(node, "lambda(&:#{node.body.method_name})") return else autocorrect_lambda_block(corrector, node) end end corrector.replace(block_range_with_space(node), "(&:#{node.body.method_name})") end def autocorrect_with_args(corrector, node, args, method_name) arg_range = args.last.source_range arg_range = range_with_surrounding_comma(arg_range, :right) replacement = " &:#{method_name}" replacement = ",#{replacement}" unless arg_range.source.end_with?(',') corrector.insert_after(arg_range, replacement) corrector.remove(block_range_with_space(node)) end def autocorrect_lambda_block(corrector, node) send_node_loc = node.send_node.loc corrector.replace(send_node_loc.selector, 'lambda') range = range_between(send_node_loc.selector.end_pos, node.loc.begin.end_pos - 2) corrector.remove(range) end def block_range_with_space(node) block_range = range_between(begin_pos_for_replacement(node), node.loc.end.end_pos) range_with_surrounding_space(block_range, side: :left) end def begin_pos_for_replacement(node) expr = node.send_node.source_range if (paren_pos = (expr.source =~ /\(\s*\)$/)) expr.begin_pos + paren_pos else node.loc.begin.begin_pos end end def allow_if_method_has_argument?(send_node) !!cop_config.fetch('AllowMethodsWithArguments', false) && send_node.arguments.any? end def allow_comments? cop_config.fetch('AllowComments', false) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false