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/to_json.rb
lib/rubocop/cop/lint/to_json.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks to make sure `#to_json` includes an optional argument. # When overriding `#to_json`, callers may invoke JSON # generation via `JSON.generate(your_obj)`. Since `JSON#generate` allows # for an optional argument, your method should too. # # @example # class Point # attr_reader :x, :y # # # bad, incorrect arity # def to_json # JSON.generate([x, y]) # end # # # good, preserving args # def to_json(*args) # JSON.generate([x, y], *args) # end # # # good, discarding args # def to_json(*_args) # JSON.generate([x, y]) # end # end # class ToJSON < Base extend AutoCorrector MSG = '`#to_json` requires an optional argument to be parsable via JSON.generate(obj).' def on_def(node) return unless node.method?(:to_json) && node.arguments.empty? add_offense(node) do |corrector| # The following used `*_args` because `to_json(*args)` has # an offense of `Lint/UnusedMethodArgument` cop if `*args` # is not used. corrector.insert_after(node.loc.name, '(*_args)') 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/hash_compare_by_identity.rb
lib/rubocop/cop/lint/hash_compare_by_identity.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Prefer using `Hash#compare_by_identity` rather than using `object_id` # for hash keys. # # This cop looks for hashes being keyed by objects' `object_id`, using # one of these methods: `key?`, `has_key?`, `fetch`, `[]` and `[]=`. # # @safety # This cop is unsafe. Although unlikely, the hash could store both object # ids and other values that need be compared by value, and thus # could be a false positive. # # Furthermore, this cop cannot guarantee that the receiver of one of the # methods (`key?`, etc.) is actually a hash. # # @example # # bad # hash = {} # hash[foo.object_id] = :bar # hash.key?(baz.object_id) # # # good # hash = {}.compare_by_identity # hash[foo] = :bar # hash.key?(baz) # class HashCompareByIdentity < Base RESTRICT_ON_SEND = %i[key? has_key? fetch [] []=].freeze MSG = 'Use `Hash#compare_by_identity` instead of using `object_id` for keys.' # @!method id_as_hash_key?(node) def_node_matcher :id_as_hash_key?, <<~PATTERN (call _ {:key? :has_key? :fetch :[] :[]=} (send _ :object_id) ...) PATTERN def on_send(node) add_offense(node) if id_as_hash_key?(node) 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/missing_cop_enable_directive.rb
lib/rubocop/cop/lint/missing_cop_enable_directive.rb
# frozen_string_literal: true # rubocop:disable Lint/RedundantCopDisableDirective module RuboCop module Cop module Lint # Checks that there is an `# rubocop:enable ...` statement # after a `# rubocop:disable ...` statement. This will prevent leaving # cop disables on wide ranges of code, that latter contributors to # a file wouldn't be aware of. # # You can set `MaximumRangeSize` to define the maximum number of # consecutive lines a cop can be disabled for. # # - `.inf` any size (default) # - `0` allows only single-line disables # - `1` means the maximum allowed is as follows: # # [source,ruby] # ---- # # rubocop:disable SomeCop # a = 1 # # rubocop:enable SomeCop # ---- # # @example MaximumRangeSize: .inf (default) # # # good # # rubocop:disable Layout/SpaceAroundOperators # x= 0 # # rubocop:enable Layout/SpaceAroundOperators # # y = 1 # # EOF # # # bad # # rubocop:disable Layout/SpaceAroundOperators # x= 0 # # EOF # # @example MaximumRangeSize: 2 # # # good # # rubocop:disable Layout/SpaceAroundOperators # x= 0 # # With the previous, there are 2 lines on which cop is disabled. # # rubocop:enable Layout/SpaceAroundOperators # # # bad # # rubocop:disable Layout/SpaceAroundOperators # x= 0 # x += 1 # # Including this, that's 3 lines on which the cop is disabled. # # rubocop:enable Layout/SpaceAroundOperators # class MissingCopEnableDirective < Base include RangeHelp MSG = 'Re-enable %<cop>s %<type>s with `# rubocop:enable` after disabling it.' MSG_BOUND = 'Re-enable %<cop>s %<type>s within %<max_range>s lines after disabling it.' def on_new_investigation each_missing_enable do |cop, line_range| next if acceptable_range?(cop, line_range) comment = processed_source.comment_at_line(line_range.begin) add_offense(comment, message: message(cop, comment)) end end private def each_missing_enable processed_source.disabled_line_ranges.each do |cop, line_ranges| line_ranges.each { |line_range| yield cop, line_range } end end def acceptable_range?(cop, line_range) # This has to remain a strict inequality to handle # the case when max_range is Float::INFINITY return true if line_range.max - line_range.min < max_range + 2 # This cop is disabled in the config, it is not expected to be re-enabled return true if line_range.min == CommentConfig::CONFIG_DISABLED_LINE_RANGE_MIN cop_class = RuboCop::Cop::Registry.global.find_by_cop_name cop if cop_class && !processed_source.registry.enabled?(cop_class, config) && line_range.max == Float::INFINITY return true end false end def max_range @max_range ||= cop_config['MaximumRangeSize'] end def message(cop, comment, type = 'cop') if department_enabled?(cop, comment) type = 'department' cop = cop.split('/').first end if max_range == Float::INFINITY format(MSG, cop: cop, type: type) else format(MSG_BOUND, cop: cop, type: type, max_range: max_range) end end def department_enabled?(cop, comment) DirectiveComment.new(comment).in_directive_department?(cop) 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/send_with_mixin_argument.rb
lib/rubocop/cop/lint/send_with_mixin_argument.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for `send`, `public_send`, and `__send__` methods # when using mix-in. # # `include` and `prepend` methods were private methods until Ruby 2.0, # they were mixed-in via `send` method. This cop uses Ruby 2.1 or # higher style that can be called by public methods. # And `extend` method that was originally a public method is also targeted # for style unification. # # @example # # bad # Foo.send(:include, Bar) # Foo.send(:prepend, Bar) # Foo.send(:extend, Bar) # # # bad # Foo.public_send(:include, Bar) # Foo.public_send(:prepend, Bar) # Foo.public_send(:extend, Bar) # # # bad # Foo.__send__(:include, Bar) # Foo.__send__(:prepend, Bar) # Foo.__send__(:extend, Bar) # # # good # Foo.include Bar # Foo.prepend Bar # Foo.extend Bar # class SendWithMixinArgument < Base include RangeHelp extend AutoCorrector MSG = 'Use `%<method>s %<module_name>s` instead of `%<bad_method>s`.' MIXIN_METHODS = %i[include prepend extend].freeze SEND_METHODS = %i[send public_send __send__].freeze RESTRICT_ON_SEND = SEND_METHODS # @!method send_with_mixin_argument?(node) def_node_matcher :send_with_mixin_argument?, <<~PATTERN (send (const _ _) {:#{SEND_METHODS.join(' :')}} ({sym str} $#mixin_method?) $(const _ _)+) PATTERN def on_send(node) send_with_mixin_argument?(node) do |method, module_names| module_names_source = module_names.map(&:source).join(', ') message = message(method, module_names_source, bad_location(node).source) bad_location = bad_location(node) add_offense(bad_location, message: message) do |corrector| corrector.replace(bad_location, "#{method} #{module_names_source}") end end end private def bad_location(node) loc = node.loc range_between(loc.selector.begin_pos, loc.expression.end_pos) end def message(method, module_name, bad_method) format(MSG, method: method, module_name: module_name, bad_method: bad_method) end def mixin_method?(node) MIXIN_METHODS.include?(node.to_sym) 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/syntax.rb
lib/rubocop/cop/lint/syntax.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Repacks Parser's diagnostics/errors # into RuboCop's offenses. class Syntax < Base LEVELS = %i[error fatal].freeze def on_other_file add_offense_from_error(processed_source.parser_error) if processed_source.parser_error syntax_errors = processed_source.diagnostics.select { |d| LEVELS.include?(d.level) } syntax_errors.each do |diagnostic| add_offense_from_diagnostic(diagnostic, processed_source.ruby_version) end super end private def add_offense_from_diagnostic(diagnostic, ruby_version) message = if LSP.enabled? diagnostic.message else "#{diagnostic.message}\n(Using Ruby #{ruby_version} parser; " \ 'configure using `TargetRubyVersion` parameter, under `AllCops`)' end add_offense(diagnostic.location, message: message, severity: diagnostic.level) end def add_offense_from_error(error) message = beautify_message(error.message) add_global_offense(message, severity: :fatal) end def beautify_message(message) message = message.capitalize message << '.' unless message.end_with?('.') message end def find_severity(_range, _severity) :fatal 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/big_decimal_new.rb
lib/rubocop/cop/lint/big_decimal_new.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # `BigDecimal.new()` is deprecated since BigDecimal 1.3.3. # This cop identifies places where `BigDecimal.new()` # can be replaced by `BigDecimal()`. # # @example # # bad # BigDecimal.new(123.456, 3) # # # good # BigDecimal(123.456, 3) # class BigDecimalNew < Base extend AutoCorrector MSG = '`BigDecimal.new()` is deprecated. Use `BigDecimal()` instead.' RESTRICT_ON_SEND = %i[new].freeze # @!method big_decimal_new(node) def_node_matcher :big_decimal_new, <<~PATTERN (send (const ${nil? cbase} :BigDecimal) :new ...) PATTERN def on_send(node) big_decimal_new(node) do |cbase| add_offense(node.loc.selector) do |corrector| corrector.remove(node.loc.selector) corrector.remove(node.loc.dot) corrector.remove(cbase) if cbase 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/useless_numeric_operation.rb
lib/rubocop/cop/lint/useless_numeric_operation.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Certain numeric operations have no impact, being: # Adding or subtracting 0, multiplying or dividing by 1 or raising to the power of 1. # These are probably leftover from debugging, or are mistakes. # # @example # # # bad # x + 0 # x - 0 # x * 1 # x / 1 # x ** 1 # # # good # x # # # bad # x += 0 # x -= 0 # x *= 1 # x /= 1 # x **= 1 # # # good # x = x # class UselessNumericOperation < Base extend AutoCorrector MSG = 'Do not apply inconsequential numeric operations to variables.' RESTRICT_ON_SEND = %i[+ - * / **].freeze # @!method useless_operation?(node) def_node_matcher :useless_operation?, '(call (call nil? $_) $_ (int $_))' # @!method useless_abbreviated_assignment?(node) def_node_matcher :useless_abbreviated_assignment?, '(op-asgn (lvasgn $_) $_ (int $_))' def on_send(node) return unless useless_operation?(node) variable, operation, number = useless_operation?(node) return unless useless?(operation, number) add_offense(node) do |corrector| corrector.replace(node, variable) end end alias on_csend on_send def on_op_asgn(node) return unless useless_abbreviated_assignment?(node) variable, operation, number = useless_abbreviated_assignment?(node) return unless useless?(operation, number) add_offense(node) do |corrector| corrector.replace(node, "#{variable} = #{variable}") end end private def useless?(operation, number) if number.zero? true if %i[+ -].include?(operation) elsif number == 1 true if %i[* / **].include?(operation) 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/circular_argument_reference.rb
lib/rubocop/cop/lint/circular_argument_reference.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for circular argument references in optional keyword # arguments and optional ordinal arguments. # # NOTE: This syntax was made invalid on Ruby 2.7 - Ruby 3.3 but is allowed # again since Ruby 3.4. # # @example # # # bad # def bake(pie: pie) # pie.heat_up # end # # # good # def bake(pie:) # pie.refrigerate # end # # # good # def bake(pie: self.pie) # pie.feed_to(user) # end # # # bad # def cook(dry_ingredients = dry_ingredients) # dry_ingredients.reduce(&:+) # end # # # good # def cook(dry_ingredients = self.dry_ingredients) # dry_ingredients.combine # end # # # bad # def foo(pie = pie = pie) # pie.heat_up # end # # # good # def foo(pie) # pie.heat_up # end # # # bad # def foo(pie = cake = pie) # [pie, cake].each(&:heat_up) # end # # # good # def foo(cake = pie) # [pie, cake].each(&:heat_up) # end class CircularArgumentReference < Base extend TargetRubyVersion MSG = 'Circular argument reference - `%<arg_name>s`.' def on_kwoptarg(node) check_for_circular_argument_references(*node) end def on_optarg(node) check_for_circular_argument_references(*node) end private def check_for_circular_argument_references(arg_name, arg_value) if arg_value.lvar_type? && arg_value.to_a == [arg_name] add_offense(arg_value, message: format(MSG, arg_name: arg_name)) return end check_assignment_chain(arg_name, arg_value) end # rubocop:disable Metrics/AbcSize def check_assignment_chain(arg_name, node) return unless node.lvasgn_type? seen_variables = Set[] current_node = node while current_node.lvasgn_type? seen_variables << current_node.children.first if current_node.lvasgn_type? current_node = current_node.children.last end return unless current_node.lvar_type? variable_node = current_node.children.first return unless seen_variables.include?(variable_node) || variable_node == arg_name add_offense(current_node, message: format(MSG, arg_name: arg_name)) end # rubocop:enable Metrics/AbcSize 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/numbered_parameter_assignment.rb
lib/rubocop/cop/lint/numbered_parameter_assignment.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for uses of numbered parameter assignment. # It emulates the following warning in Ruby 2.7: # # $ ruby -ve '_1 = :value' # ruby 2.7.2p137 (2020-10-01 revision 5445e04352) [x86_64-darwin19] # -e:1: warning: `_1' is reserved for numbered parameter; consider another name # # Assigning to a numbered parameter (from `_1` to `_9`) causes an error in Ruby 3.0. # # $ ruby -ve '_1 = :value' # ruby 3.0.0p0 (2020-12-25 revision 95aff21468) [x86_64-darwin19] # -e:1: _1 is reserved for numbered parameter # # NOTE: The parametered parameters are from `_1` to `_9`. This cop checks `_0`, and over `_10` # as well to prevent confusion. # # @example # # # bad # _1 = :value # # # good # non_numbered_parameter_name = :value # class NumberedParameterAssignment < Base NUM_PARAM_MSG = '`_%<number>s` is reserved for numbered parameter; consider another name.' LVAR_MSG = '`_%<number>s` is similar to numbered parameter; consider another name.' NUMBERED_PARAMETER_RANGE = (1..9).freeze def on_lvasgn(node) return unless /\A_(\d+)\z/ =~ node.name number = Regexp.last_match(1).to_i template = NUMBERED_PARAMETER_RANGE.include?(number) ? NUM_PARAM_MSG : LVAR_MSG add_offense(node, message: format(template, number: number)) 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_as_condition.rb
lib/rubocop/cop/lint/literal_as_condition.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for literals used as the conditions or as # operands in and/or expressions serving as the conditions of # if/while/until/case-when/case-in. # # NOTE: Literals in `case-in` condition where the match variable is used in # `in` are accepted as a pattern matching. # # @example # # # bad # if 20 # do_something # end # # # bad # # We're only interested in the left hand side being a truthy literal, # # because it affects the evaluation of the &&, whereas the right hand # # side will be conditionally executed/called and can be a literal. # if true && some_var # do_something # end # # # good # if some_var # do_something # end # # # good # # When using a boolean value for an infinite loop. # while true # break if condition # end class LiteralAsCondition < Base include RangeHelp extend AutoCorrector MSG = 'Literal `%<literal>s` appeared as a condition.' RESTRICT_ON_SEND = [:!].freeze def on_and(node) return unless node.lhs.truthy_literal? add_offense(node.lhs) do |corrector| # Don't autocorrect `'foo' && return` because having `return` as # the leftmost node can lead to a void value expression syntax error. next if node.rhs.type?(:return, :break, :next) corrector.replace(node, node.rhs.source) end end def on_or(node) return unless node.lhs.falsey_literal? add_offense(node.lhs) do |corrector| # Don't autocorrect `'foo' && return` because having `return` as # the leftmost node can lead to a void value expression syntax error. next if node.rhs.type?(:return, :break, :next) corrector.replace(node, node.rhs.source) end end def on_if(node) cond = condition(node) return unless cond.falsey_literal? || cond.truthy_literal? correct_if_node(node, cond) end def on_while(node) return if node.condition.source == 'true' if node.condition.truthy_literal? add_offense(node.condition) do |corrector| corrector.replace(node.condition, 'true') end elsif node.condition.falsey_literal? add_offense(node.condition) do |corrector| corrector.remove(node) end end end # rubocop:disable Metrics/AbcSize def on_while_post(node) return if node.condition.source == 'true' if node.condition.truthy_literal? add_offense(node.condition) do |corrector| corrector.replace(node, node.source.sub(node.condition.source, 'true')) end elsif node.condition.falsey_literal? add_offense(node.condition) do |corrector| corrector.replace(node, node.body.child_nodes.map(&:source).join("\n")) end end end # rubocop:enable Metrics/AbcSize def on_until(node) return if node.condition.source == 'false' if node.condition.falsey_literal? add_offense(node.condition) do |corrector| corrector.replace(node.condition, 'false') end elsif node.condition.truthy_literal? add_offense(node.condition) do |corrector| corrector.remove(node) end end end # rubocop:disable Metrics/AbcSize def on_until_post(node) return if node.condition.source == 'false' if node.condition.falsey_literal? add_offense(node.condition) do |corrector| corrector.replace(node, node.source.sub(node.condition.source, 'false')) end elsif node.condition.truthy_literal? add_offense(node.condition) do |corrector| corrector.replace(node, node.body.child_nodes.map(&:source).join("\n")) end end end # rubocop:enable Metrics/AbcSize def on_case(case_node) if (cond = case_node.condition) return if !cond.falsey_literal? && !cond.truthy_literal? check_case(case_node) else case_node.when_branches.each do |when_node| next unless when_node.conditions.all?(&:literal?) range = when_conditions_range(when_node) message = message(range) add_offense(range, message: message) end end end def on_case_match(case_match_node) if case_match_node.condition return if case_match_node.descendants.any?(&:match_var_type?) check_case(case_match_node) else case_match_node.each_in_pattern do |in_pattern_node| next unless in_pattern_node.condition.literal? add_offense(in_pattern_node) end end end def on_send(node) return unless node.negation_method? check_for_literal(node) end def message(node) format(MSG, literal: node.source) end private def check_for_literal(node) cond = condition(node) if cond.literal? add_offense(cond) else check_node(cond) end end def basic_literal?(node) if node.array_type? primitive_array?(node) else node.basic_literal? end end def primitive_array?(node) node.children.all? { |n| basic_literal?(n) } end def check_node(node) if node.send_type? && node.prefix_bang? handle_node(node.receiver) elsif node.operator_keyword? node.each_child_node { |op| handle_node(op) } elsif node.begin_type? && node.children.one? handle_node(node.children.first) end end def handle_node(node) if node.literal? return if node.parent.and_type? add_offense(node) elsif %i[send and or begin].include?(node.type) check_node(node) end end def check_case(case_node) condition = case_node.condition return if condition.array_type? && !primitive_array?(condition) return if condition.dstr_type? handle_node(condition) end def condition(node) if node.send_type? node.receiver else node.condition end end def when_conditions_range(when_node) range_between( when_node.conditions.first.source_range.begin_pos, when_node.conditions.last.source_range.end_pos ) end def condition_evaluation?(node, cond) if node.unless? cond.falsey_literal? else cond.truthy_literal? end end # rubocop:disable Metrics/AbcSize, Metrics/MethodLength, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity def correct_if_node(node, cond) result = condition_evaluation?(node, cond) new_node = if node.elsif? && result "else\n #{range_with_comments(node.if_branch).source}" elsif node.elsif? && !result "else\n #{node.else_branch.source}" elsif node.if_branch && result node.if_branch.source elsif node.elsif_conditional? "#{node.else_branch.source.sub('elsif', 'if')}\nend" elsif node.else? || node.ternary? node.else_branch.source else '' # Equivalent to removing the node end add_offense(cond) do |corrector| next if part_of_ignored_node?(node) corrector.replace(node, new_node) ignore_node(node) end end # rubocop:enable Metrics/AbcSize, Metrics/MethodLength, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity 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_times.rb
lib/rubocop/cop/lint/useless_times.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for uses of `Integer#times` that will never yield # (when the integer ``<= 0``) or that will only ever yield once # (`1.times`). # # @safety # This cop is unsafe as `times` returns its receiver, which is # *usually* OK, but might change behavior. # # @example # # bad # -5.times { do_something } # 0.times { do_something } # 1.times { do_something } # 1.times { |i| do_something(i) } # # # good # do_something # do_something(1) class UselessTimes < Base include RangeHelp extend AutoCorrector MSG = 'Useless call to `%<count>i.times` detected.' RESTRICT_ON_SEND = %i[times].freeze # @!method times_call?(node) def_node_matcher :times_call?, <<~PATTERN (send (int $_) :times (block-pass (sym $_))?) PATTERN # @!method block_arg(node) def_node_matcher :block_arg, <<~PATTERN (block _ (args (arg $_)) ...) PATTERN # @!method block_reassigns_arg?(node) def_node_search :block_reassigns_arg?, <<~PATTERN (lvasgn %) PATTERN def on_send(node) return unless (count, proc_name = times_call?(node)) return if count > 1 # Get the block node if applicable node = node.block_node if node.block_literal? add_offense(node, message: format(MSG, count: count)) do |corrector| next if !own_line?(node) || node.parent&.send_type? autocorrect(corrector, count, node, proc_name) end end private def autocorrect(corrector, count, node, proc_name) if never_process?(count, node) remove_node(corrector, node) elsif !proc_name.empty? autocorrect_block_pass(corrector, node, proc_name) elsif node.block_type? autocorrect_block(corrector, node) end end def never_process?(count, node) count < 1 || (node.block_type? && node.body.nil?) end def remove_node(corrector, node) corrector.remove(range_by_whole_lines(node.source_range, include_final_newline: true)) end def autocorrect_block_pass(corrector, node, proc_name) corrector.replace(node, proc_name) end def autocorrect_block(corrector, node) block_arg = block_arg(node) return if block_reassigns_arg?(node, block_arg) source = node.body.source source.gsub!(/\b#{block_arg}\b/, '0') if block_arg corrector.replace(node, fix_indentation(source, node.loc.column...node.body.loc.column)) end def fix_indentation(source, range) # Cleanup indentation in a multiline block source_lines = source.split("\n") source_lines[1..].each do |line| next if line.empty? line[range] = '' end source_lines.join("\n") end def own_line?(node) # If there is anything else on the line other than whitespace, # don't try to autocorrect processed_source.buffer.source_line(node.loc.line)[0...node.loc.column] !~ /\S/ 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/float_out_of_range.rb
lib/rubocop/cop/lint/float_out_of_range.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Identifies `Float` literals which are, like, really really really # really really really really really big. Too big. No-one needs Floats # that big. If you need a float that big, something is wrong with you. # # @example # # # bad # float = 3.0e400 # # # good # float = 42.9 class FloatOutOfRange < Base MSG = 'Float out of range.' def on_float(node) return unless node.value.infinite? || (node.value.zero? && /[1-9]/.match?(node.source)) 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/to_enum_arguments.rb
lib/rubocop/cop/lint/to_enum_arguments.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Ensures that `to_enum`/`enum_for`, called for the current method, # has correct arguments. # # @example # # bad # def foo(x, y = 1) # return to_enum(__callee__, x) # `y` is missing # end # # # good # def foo(x, y = 1) # # Alternatives to `__callee__` are `__method__` and `:foo`. # return to_enum(__callee__, x, y) # end # # # good # def foo(x, y = 1) # # It is also allowed if it is wrapped in some method like Sorbet. # return to_enum(T.must(__callee__), x, y) # end # class ToEnumArguments < Base MSG = 'Ensure you correctly provided all the arguments.' RESTRICT_ON_SEND = %i[to_enum enum_for].freeze # @!method enum_conversion_call?(node) def_node_matcher :enum_conversion_call?, <<~PATTERN (send {nil? self} {:to_enum :enum_for} $_ $...) PATTERN # @!method method_name?(node, name) def_node_matcher :method_name?, <<~PATTERN {(send nil? {:__method__ :__callee__}) (sym %1)} PATTERN # @!method passing_keyword_arg?(node, name) def_node_matcher :passing_keyword_arg?, <<~PATTERN (pair (sym %1) (lvar %1)) PATTERN def on_send(node) def_node = node.each_ancestor(:any_def).first return unless def_node enum_conversion_call?(node) do |method_node, arguments| next if !method_name?(method_node, def_node.method_name) || arguments_match?(arguments, def_node) add_offense(node) end end private def arguments_match?(arguments, def_node) index = 0 def_node.arguments.reject(&:blockarg_type?).all? do |def_arg| send_arg = arguments[index] case def_arg.type when :arg, :restarg, :optarg index += 1 end send_arg && argument_match?(send_arg, def_arg) end end # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength def argument_match?(send_arg, def_arg) def_arg_name = def_arg.children[0] case def_arg.type when :arg, :restarg send_arg.source == def_arg.source when :optarg send_arg.source == def_arg_name.to_s when :kwoptarg, :kwarg send_arg.hash_type? && send_arg.pairs.any? { |pair| passing_keyword_arg?(pair, def_arg_name) } when :kwrestarg send_arg.each_child_node(:kwsplat, :forwarded_kwrestarg).any? do |child| child.source == def_arg.source end when :forward_arg send_arg.forwarded_args_type? end end # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength 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/self_assignment.rb
lib/rubocop/cop/lint/self_assignment.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for self-assignments. # # @example # # bad # foo = foo # foo, bar = foo, bar # Foo = Foo # hash['foo'] = hash['foo'] # obj.attr = obj.attr # # # good # foo = bar # foo, bar = bar, foo # Foo = Bar # hash['foo'] = hash['bar'] # obj.attr = obj.attr2 # # # good (method calls possibly can return different results) # hash[foo] = hash[foo] # # @example AllowRBSInlineAnnotation: false (default) # # bad # foo = foo #: Integer # foo, bar = foo, bar #: Integer # Foo = Foo #: Integer # hash['foo'] = hash['foo'] #: Integer # obj.attr = obj.attr #: Integer # # @example AllowRBSInlineAnnotation: true # # good # foo = foo #: Integer # foo, bar = foo, bar #: Integer # Foo = Foo #: Integer # hash['foo'] = hash['foo'] #: Integer # obj.attr = obj.attr #: Integer # class SelfAssignment < Base MSG = 'Self-assignment detected.' ASSIGNMENT_TYPE_TO_RHS_TYPE = { lvasgn: :lvar, ivasgn: :ivar, cvasgn: :cvar, gvasgn: :gvar }.freeze def on_send(node) return if allow_rbs_inline_annotation? && rbs_inline_annotation?(node.receiver) if node.method?(:[]=) handle_key_assignment(node) elsif node.assignment_method? handle_attribute_assignment(node) if node.arguments.size == 1 end end alias on_csend on_send def on_lvasgn(node) return unless node.rhs return if allow_rbs_inline_annotation? && rbs_inline_annotation?(node.rhs) rhs_type = ASSIGNMENT_TYPE_TO_RHS_TYPE[node.type] add_offense(node) if node.rhs.type == rhs_type && node.rhs.source == node.lhs.to_s end alias on_ivasgn on_lvasgn alias on_cvasgn on_lvasgn alias on_gvasgn on_lvasgn def on_casgn(node) return unless node.rhs&.const_type? return if allow_rbs_inline_annotation? && rbs_inline_annotation?(node.rhs) add_offense(node) if node.namespace == node.rhs.namespace && node.short_name == node.rhs.short_name end def on_masgn(node) first_lhs = node.lhs.assignments.first return if allow_rbs_inline_annotation? && rbs_inline_annotation?(first_lhs) add_offense(node) if multiple_self_assignment?(node) end def on_or_asgn(node) return if allow_rbs_inline_annotation? && rbs_inline_annotation?(node.lhs) add_offense(node) if rhs_matches_lhs?(node.rhs, node.lhs) end alias on_and_asgn on_or_asgn private def multiple_self_assignment?(node) lhs = node.lhs rhs = node.rhs return false unless rhs.array_type? return false unless lhs.children.size == rhs.children.size lhs.children.zip(rhs.children).all? do |lhs_item, rhs_item| rhs_matches_lhs?(rhs_item, lhs_item) end end def rhs_matches_lhs?(rhs, lhs) rhs.type == ASSIGNMENT_TYPE_TO_RHS_TYPE[lhs.type] && rhs.children.first == lhs.children.first end def handle_key_assignment(node) value_node = node.last_argument node_arguments = node.arguments[0...-1] if value_node.respond_to?(:method?) && value_node.method?(:[]) && node.receiver == value_node.receiver && node_arguments.none?(&:call_type?) && node_arguments == value_node.arguments add_offense(node) end end def handle_attribute_assignment(node) first_argument = node.first_argument return unless first_argument.respond_to?(:arguments) && first_argument.arguments.empty? if first_argument.call_type? && node.receiver == first_argument.receiver && first_argument.method_name.to_s == node.method_name.to_s.delete_suffix('=') add_offense(node) end end def rbs_inline_annotation?(node) processed_source.ast_with_comments[node].any? { |comment| comment.text.start_with?('#:') } end def allow_rbs_inline_annotation? cop_config['AllowRBSInlineAnnotation'] 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_class_methods.rb
lib/rubocop/cop/lint/deprecated_class_methods.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for uses of the deprecated class method usages. # # @example # # # bad # File.exists?(some_path) # Dir.exists?(some_path) # iterator? # attr :name, true # attr :name, false # ENV.freeze # Calling `Env.freeze` raises `TypeError` since Ruby 2.7. # ENV.clone # ENV.dup # Calling `Env.dup` raises `TypeError` since Ruby 3.1. # Socket.gethostbyname(host) # Socket.gethostbyaddr(host) # # # good # File.exist?(some_path) # Dir.exist?(some_path) # block_given? # attr_accessor :name # attr_reader :name # ENV # `ENV.freeze` cannot prohibit changes to environment variables. # ENV.to_h # ENV.to_h # `ENV.dup` cannot dup `ENV`, use `ENV.to_h` to get a copy of `ENV` as a hash. # Addrinfo.getaddrinfo(nodename, service) # Addrinfo.tcp(host, port).getnameinfo class DeprecatedClassMethods < Base extend AutoCorrector MSG = '`%<current>s` is deprecated in favor of `%<prefer>s`.' RESTRICT_ON_SEND = %i[ attr clone dup exists? freeze gethostbyaddr gethostbyname iterator? ].freeze PREFERRED_METHODS = { clone: 'to_h', dup: 'to_h', exists?: 'exist?', gethostbyaddr: 'Addrinfo#getnameinfo', gethostbyname: 'Addrinfo.getaddrinfo', iterator?: 'block_given?' }.freeze DIR_ENV_FILE_CONSTANTS = %i[Dir ENV File].freeze # @!method deprecated_class_method?(node) def_node_matcher :deprecated_class_method?, <<~PATTERN { (send (const {cbase nil?} :ENV) {:clone :dup :freeze}) (send (const {cbase nil?} {:File :Dir}) :exists? _) (send (const {cbase nil?} :Socket) {:gethostbyaddr :gethostbyname} ...) (send nil? :attr _ boolean) (send nil? :iterator?) } PATTERN def on_send(node) return unless deprecated_class_method?(node) offense_range = offense_range(node) prefer = preferred_method(node) message = format(MSG, current: offense_range.source, prefer: prefer) add_offense(offense_range, message: message) do |corrector| next if socket_const?(node.receiver) if node.method?(:freeze) corrector.replace(node, 'ENV') else corrector.replace(offense_range, prefer) end end end private def offense_range(node) if socket_const?(node.receiver) || dir_env_file_const?(node.receiver) node.source_range.begin.join(node.loc.selector.end) elsif node.method?(:attr) node else node.loc.selector end end def preferred_method(node) if node.method?(:attr) boolean_argument = node.arguments[1].source preferred_attr_method = boolean_argument == 'true' ? 'attr_accessor' : 'attr_reader' "#{preferred_attr_method} #{node.first_argument.source}" elsif dir_env_file_const?(node.receiver) prefer = PREFERRED_METHODS[node.method_name] prefer ? "#{node.receiver.source}.#{prefer}" : 'ENV' else PREFERRED_METHODS[node.method_name] end end def socket_const?(node) node&.short_name == :Socket end def dir_env_file_const?(node) DIR_ENV_FILE_CONSTANTS.include?(node&.short_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/duplicate_elsif_condition.rb
lib/rubocop/cop/lint/duplicate_elsif_condition.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks that there are no repeated conditions used in if 'elsif'. # # @example # # bad # if x == 1 # do_something # elsif x == 1 # do_something_else # end # # # good # if x == 1 # do_something # elsif x == 2 # do_something_else # end # class DuplicateElsifCondition < Base MSG = 'Duplicate `elsif` condition detected.' def on_if(node) previous = [] while node.if? || node.elsif? condition = node.condition add_offense(condition) if previous.include?(condition) previous << condition node = node.else_branch break unless node&.if_type? 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/missing_super.rb
lib/rubocop/cop/lint/missing_super.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for the presence of constructors and lifecycle callbacks # without calls to `super`. # # This cop does not consider `method_missing` (and `respond_to_missing?`) # because in some cases it makes sense to overtake what is considered a # missing method. In other cases, the theoretical ideal handling could be # challenging or verbose for no actual gain. # # Autocorrection is not supported because the position of `super` cannot be # determined automatically. # # `Object` and `BasicObject` are allowed by this cop because of their # stateless nature. However, sometimes you might want to allow other parent # classes from this cop, for example in the case of an abstract class that is # not meant to be called with `super`. In those cases, you can use the # `AllowedParentClasses` option to specify which classes should be allowed # *in addition to* `Object` and `BasicObject`. # # @example # # bad # class Employee < Person # def initialize(name, salary) # @salary = salary # end # end # # # good # class Employee < Person # def initialize(name, salary) # super(name) # @salary = salary # end # end # # # bad # Employee = Class.new(Person) do # def initialize(name, salary) # @salary = salary # end # end # # # good # Employee = Class.new(Person) do # def initialize(name, salary) # super(name) # @salary = salary # end # end # # # bad # class Parent # def self.inherited(base) # do_something # end # end # # # good # class Parent # def self.inherited(base) # super # do_something # end # end # # # good # class ClassWithNoParent # def initialize # do_something # end # end # # @example AllowedParentClasses: [MyAbstractClass] # # good # class MyConcreteClass < MyAbstractClass # def initialize # do_something # end # end # class MissingSuper < Base CONSTRUCTOR_MSG = 'Call `super` to initialize state of the parent class.' CALLBACK_MSG = 'Call `super` to invoke callback defined in the parent class.' STATELESS_CLASSES = %w[BasicObject Object].freeze CLASS_LIFECYCLE_CALLBACKS = %i[inherited].freeze METHOD_LIFECYCLE_CALLBACKS = %i[method_added method_removed method_undefined singleton_method_added singleton_method_removed singleton_method_undefined].freeze CALLBACKS = (CLASS_LIFECYCLE_CALLBACKS + METHOD_LIFECYCLE_CALLBACKS).to_set.freeze # @!method class_new_block(node) def_node_matcher :class_new_block, <<~RUBY (any_block (send (const {nil? cbase} :Class) :new $_) ...) RUBY def on_def(node) return unless offender?(node) if node.method?(:initialize) && inside_class_with_stateful_parent?(node) add_offense(node, message: CONSTRUCTOR_MSG) elsif callback_method_def?(node) add_offense(node, message: CALLBACK_MSG) end end def on_defs(node) return if !callback_method_def?(node) || contains_super?(node) add_offense(node, message: CALLBACK_MSG) end private def offender?(node) (node.method?(:initialize) || callback_method_def?(node)) && !contains_super?(node) end def callback_method_def?(node) return false unless CALLBACKS.include?(node.method_name) node.each_ancestor(:class, :sclass, :module).first end def contains_super?(node) node.each_descendant(:super, :zsuper).any? end def inside_class_with_stateful_parent?(node) if (block_node = node.each_ancestor(:any_block).first) return false unless (super_class = class_new_block(block_node)) !allowed_class?(super_class) elsif (class_node = node.each_ancestor(:class).first) class_node.parent_class && !allowed_class?(class_node.parent_class) else false end end def allowed_class?(node) allowed_classes.include?(node.const_name) end def allowed_classes @allowed_classes ||= STATELESS_CLASSES + cop_config.fetch('AllowedParentClasses', []) 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/number_conversion.rb
lib/rubocop/cop/lint/number_conversion.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Warns the usage of unsafe number conversions. Unsafe # number conversion can cause unexpected error if auto type conversion # fails. Cop prefer parsing with number class instead. # # Conversion with `Integer`, `Float`, etc. will raise an `ArgumentError` # if given input that is not numeric (eg. an empty string), whereas # `to_i`, etc. will try to convert regardless of input (``''.to_i => 0``). # As such, this cop is disabled by default because it's not necessarily # always correct to raise if a value is not numeric. # # NOTE: Some values cannot be converted properly using one of the `Kernel` # method (for instance, `Time` and `DateTime` values are allowed by this # cop by default). Similarly, Rails' duration methods do not work well # with `Integer()` and can be allowed with `AllowedMethods`. By default, # there are no methods to allowed. # # @safety # Autocorrection is unsafe because it is not guaranteed that the # replacement `Kernel` methods are able to properly handle the # input if it is not a standard class. # # @example # # # bad # # '10'.to_i # '10.2'.to_f # '10'.to_c # '1/3'.to_r # ['1', '2', '3'].map(&:to_i) # foo.try(:to_f) # bar.send(:to_c) # # # good # # Integer('10', 10) # Float('10.2') # Complex('10') # Rational('1/3') # ['1', '2', '3'].map { |i| Integer(i, 10) } # foo.try { |i| Float(i) } # bar.send { |i| Complex(i) } # # @example AllowedMethods: [] (default) # # # bad # 10.minutes.to_i # # @example AllowedMethods: [minutes] # # # good # 10.minutes.to_i # # @example AllowedPatterns: [] (default) # # # bad # 10.minutes.to_i # # @example AllowedPatterns: ['min*'] # # # good # 10.minutes.to_i # # @example IgnoredClasses: [Time, DateTime] (default) # # # good # Time.now.to_datetime.to_i class NumberConversion < Base extend AutoCorrector include AllowedMethods include AllowedPattern CONVERSION_METHOD_CLASS_MAPPING = { to_i: "#{Integer.name}(%<number_object>s, 10)", to_f: "#{Float.name}(%<number_object>s)", to_c: "#{Complex.name}(%<number_object>s)", to_r: "#{Rational.name}(%<number_object>s)" }.freeze MSG = 'Replace unsafe number conversion with number ' \ 'class parsing, instead of using ' \ '`%<current>s`, use stricter ' \ '`%<corrected_method>s`.' CONVERSION_METHODS = %i[Integer Float Complex Rational to_i to_f to_c to_r].freeze METHODS = CONVERSION_METHOD_CLASS_MAPPING.keys.map(&:inspect).join(' ') # @!method to_method(node) def_node_matcher :to_method, <<~PATTERN (call $_ ${#{METHODS}}) PATTERN # @!method to_method_symbol(node) def_node_matcher :to_method_symbol, <<~PATTERN (call _ $_ ${ { (sym ${#{METHODS}}) (block_pass (sym ${#{METHODS}})) } } ...) PATTERN def on_send(node) handle_conversion_method(node) handle_as_symbol(node) end alias on_csend on_send private def handle_conversion_method(node) to_method(node) do |receiver, to_method| next if receiver.nil? || allow_receiver?(receiver) message = format( MSG, current: "#{receiver.source}.#{to_method}", corrected_method: correct_method(node, receiver) ) add_offense(node, message: message) do |corrector| next if part_of_ignored_node?(node) corrector.replace(node, correct_method(node, node.receiver)) ignore_node(node) end end end def handle_as_symbol(node) to_method_symbol(node) do |receiver, sym_node, to_method| next if receiver.nil? || !node.arguments.one? message = format( MSG, current: sym_node.source, corrected_method: correct_sym_method(to_method) ) add_offense(node, message: message) do |corrector| remove_parentheses(corrector, node) if node.parenthesized? corrector.replace(sym_node, correct_sym_method(to_method)) end end end def correct_method(node, receiver) format(CONVERSION_METHOD_CLASS_MAPPING[node.method_name], number_object: receiver.source) end def correct_sym_method(to_method) body = format(CONVERSION_METHOD_CLASS_MAPPING[to_method], number_object: 'i') "{ |i| #{body} }" end def remove_parentheses(corrector, node) corrector.replace(node.loc.begin, ' ') corrector.remove(node.loc.end) end def allow_receiver?(receiver) if receiver.numeric_type? || (receiver.send_type? && (conversion_method?(receiver.method_name) || allowed_method_name?(receiver.method_name))) true elsif (receiver = top_receiver(receiver)) receiver.const_type? && ignored_class?(receiver.const_name) else false end end def allowed_method_name?(name) allowed_method?(name) || matches_allowed_pattern?(name) end def top_receiver(node) receiver = node receiver = receiver.receiver until receiver.receiver.nil? receiver end def conversion_method?(method_name) CONVERSION_METHODS.include?(method_name) end def ignored_classes cop_config.fetch('IgnoredClasses', []) end def ignored_class?(name) ignored_classes.include?(name.to_s) 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_regexp_character_class_element.rb
lib/rubocop/cop/lint/duplicate_regexp_character_class_element.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for duplicate elements in `Regexp` character classes. # # @example # # # bad # r = /[xyx]/ # # # bad # r = /[0-9x0-9]/ # # # good # r = /[xy]/ # # # good # r = /[0-9x]/ class DuplicateRegexpCharacterClassElement < Base include RangeHelp extend AutoCorrector MSG_REPEATED_ELEMENT = 'Duplicate element inside regexp character class' def on_regexp(node) each_repeated_character_class_element_loc(node) do |loc| add_offense(loc, message: MSG_REPEATED_ELEMENT) do |corrector| corrector.remove(loc) end end end def each_repeated_character_class_element_loc(node) node.parsed_tree&.each_expression do |expr| next if skip_expression?(expr) seen = Set.new group_expressions(node, expr.expressions) do |group| group_source = group.to_s yield group.expression if seen.include?(group_source) seen << group_source end end end private def group_expressions(node, expressions) expressions.each do |expression| next if within_interpolation?(node, expression) yield(expression) end end def skip_expression?(expr) expr.type != :set || expr.token == :intersection end # Since we blank interpolations with a space for every char of the interpolation, we would # mark every space (except the first) as duplicate if we do not skip regexp_parser nodes # that are within an interpolation. def within_interpolation?(node, child) parse_tree_child_loc = child.expression interpolation_locs(node).any? { |il| il.overlaps?(parse_tree_child_loc) } end def interpolation_locs(node) @interpolation_locs ||= {} # Cache by loc, not by regexp content, as content can be repeated in multiple patterns key = node.loc @interpolation_locs[key] ||= node.children.select(&:begin_type?).map(&:source_range) 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_constants.rb
lib/rubocop/cop/lint/deprecated_constants.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for deprecated constants. # # It has `DeprecatedConstants` config. If there is an alternative method, you can set # alternative value as `Alternative`. And you can set the deprecated version as # `DeprecatedVersion`. These options can be omitted if they are not needed. # # DeprecatedConstants: # 'DEPRECATED_CONSTANT': # Alternative: 'alternative_value' # DeprecatedVersion: 'deprecated_version' # # By default, `NIL`, `TRUE`, `FALSE`, `Net::HTTPServerException, `Random::DEFAULT`, # `Struct::Group`, and `Struct::Passwd` are configured. # # @example # # # bad # NIL # TRUE # FALSE # Net::HTTPServerException # Random::DEFAULT # Return value of Ruby 2 is `Random` instance, Ruby 3.0 is `Random` class. # Struct::Group # Struct::Passwd # # # good # nil # true # false # Net::HTTPClientException # Random.new # `::DEFAULT` has been deprecated in Ruby 3, `.new` is compatible with Ruby 2. # Etc::Group # Etc::Passwd # class DeprecatedConstants < Base extend AutoCorrector SUGGEST_GOOD_MSG = 'Use `%<good>s` instead of `%<bad>s`%<deprecated_message>s.' DO_NOT_USE_MSG = 'Do not use `%<bad>s`%<deprecated_message>s.' def on_const(node) # FIXME: Workaround for "`undefined method `expression' for nil:NilClass`" when processing # `__ENCODING__`. It is better to be able to work without this condition. # Maybe further investigation of RuboCop AST will lead to an essential solution. return unless node.loc constant = node.absolute? ? constant_name(node, node.short_name) : node.source return unless (deprecated_constant = deprecated_constants[constant]) alternative = deprecated_constant['Alternative'] version = deprecated_constant['DeprecatedVersion'] return if target_ruby_version < version.to_f add_offense(node, message: message(alternative, node.source, version)) do |corrector| corrector.replace(node, alternative) end end private def constant_name(node, nested_constant_name) return nested_constant_name.to_s unless node.namespace.const_type? constant_name(node.namespace, "#{node.namespace.short_name}::#{nested_constant_name}") end def message(good, bad, deprecated_version) deprecated_message = ", deprecated since Ruby #{deprecated_version}" if deprecated_version if good format(SUGGEST_GOOD_MSG, good: good, bad: bad, deprecated_message: deprecated_message) else format(DO_NOT_USE_MSG, bad: bad, deprecated_message: deprecated_message) end end def deprecated_constants cop_config.fetch('DeprecatedConstants', {}) 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_rescue_exception.rb
lib/rubocop/cop/lint/duplicate_rescue_exception.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks that there are no repeated exceptions # used in 'rescue' expressions. # # @example # # bad # begin # something # rescue FirstException # handle_exception # rescue FirstException # handle_other_exception # end # # # good # begin # something # rescue FirstException # handle_exception # rescue SecondException # handle_other_exception # end # class DuplicateRescueException < Base include RescueNode MSG = 'Duplicate `rescue` exception detected.' def on_rescue(node) return if rescue_modifier?(node) node.resbody_branches.each_with_object(Set.new) do |resbody, previous| rescued_exceptions = resbody.exceptions rescued_exceptions.each do |exception| add_offense(exception) unless previous.add?(exception) 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/constant_resolution.rb
lib/rubocop/cop/lint/constant_resolution.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Check that certain constants are fully qualified. # # This is not enabled by default because it would mark a lot of offenses # unnecessarily. # # Generally, gems should fully qualify all constants to avoid conflicts with # the code that uses the gem. Enable this cop without using `Only`/`Ignore` # # Large projects will over time end up with one or two constant names that # are problematic because of a conflict with a library or just internally # using the same name a namespace and a class. To avoid too many unnecessary # offenses, Enable this cop with `Only: [The, Constant, Names, Causing, Issues]` # # NOTE: `Style/RedundantConstantBase` cop is disabled if this cop is enabled to prevent # conflicting rules. Because it respects user configurations that want to enable # this cop which is disabled by default. # # @example # # By default checks every constant # # # bad # User # # # bad # User::Login # # # good # ::User # # # good # ::User::Login # # @example Only: ['Login'] # # Restrict this cop to only being concerned about certain constants # # # bad # Login # # # good # ::Login # # # good # User::Login # # @example Ignore: ['Login'] # # Restrict this cop not being concerned about certain constants # # # bad # User # # # good # ::User::Login # # # good # Login # class ConstantResolution < Base MSG = 'Fully qualify this constant to avoid possibly ambiguous resolution.' # @!method unqualified_const?(node) def_node_matcher :unqualified_const?, <<~PATTERN (const nil? #const_name?) PATTERN def on_const(node) return if !unqualified_const?(node) || node.parent&.defined_module || node.loc.nil? add_offense(node) end private def const_name?(name) name = name.to_s (allowed_names.empty? || allowed_names.include?(name)) && !ignored_names.include?(name) end def allowed_names cop_config['Only'] end def ignored_names cop_config['Ignore'] 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/lambda_without_literal_block.rb
lib/rubocop/cop/lint/lambda_without_literal_block.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks uses of lambda without a literal block. # It emulates the following warning in Ruby 3.0: # # $ ruby -vwe 'lambda(&proc {})' # ruby 3.0.0p0 (2020-12-25 revision 95aff21468) [x86_64-darwin19] # -e:1: warning: lambda without a literal block is deprecated; use the proc without # lambda instead # # This way, proc object is never converted to lambda. # Autocorrection replaces with compatible proc argument. # # @example # # # bad # lambda(&proc { do_something }) # lambda(&Proc.new { do_something }) # # # good # proc { do_something } # Proc.new { do_something } # lambda { do_something } # If you use lambda. # class LambdaWithoutLiteralBlock < Base extend AutoCorrector MSG = 'lambda without a literal block is deprecated; use the proc without lambda instead.' RESTRICT_ON_SEND = %i[lambda].freeze # @!method lambda_with_symbol_proc?(node) def_node_matcher :lambda_with_symbol_proc?, <<~PATTERN (send nil? :lambda (block_pass (sym _))) PATTERN def on_send(node) if node.parent&.block_type? || !node.first_argument || lambda_with_symbol_proc?(node) return end add_offense(node) do |corrector| corrector.replace(node, node.first_argument.source.delete('&')) 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_block_association.rb
lib/rubocop/cop/lint/ambiguous_block_association.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for ambiguous block association with method # when param passed without parentheses. # # This cop can customize allowed methods with `AllowedMethods`. # By default, there are no methods to allowed. # # @example # # # bad # some_method a { |val| puts val } # # # good # # With parentheses, there's no ambiguity. # some_method(a { |val| puts val }) # # or (different meaning) # some_method(a) { |val| puts val } # # # good # # Operator methods require no disambiguation # foo == bar { |b| b.baz } # # # good # # Lambda arguments require no disambiguation # foo = ->(bar) { bar.baz } # # @example AllowedMethods: [] (default) # # # bad # expect { do_something }.to change { object.attribute } # # @example AllowedMethods: [change] # # # good # expect { do_something }.to change { object.attribute } # # @example AllowedPatterns: [] (default) # # # bad # expect { do_something }.to change { object.attribute } # # @example AllowedPatterns: ['change'] # # # good # expect { do_something }.to change { object.attribute } # expect { do_something }.to not_change { object.attribute } # class AmbiguousBlockAssociation < Base extend AutoCorrector include AllowedMethods include AllowedPattern MSG = 'Parenthesize the param `%<param>s` to make sure that the ' \ 'block will be associated with the `%<method>s` method ' \ 'call.' def on_send(node) return unless node.arguments? return unless ambiguous_block_association?(node) return if node.parenthesized? || node.last_argument.lambda_or_proc? || allowed_method_pattern?(node) message = message(node) add_offense(node, message: message) do |corrector| wrap_in_parentheses(corrector, node) end end alias on_csend on_send private def ambiguous_block_association?(send_node) send_node.last_argument.any_block_type? && !send_node.last_argument.send_node.arguments? end def allowed_method_pattern?(node) node.assignment? || node.operator_method? || node.method?(:[]) || allowed_method?(node.last_argument.method_name) || matches_allowed_pattern?(node.last_argument.send_node.source) end def message(send_node) block_param = send_node.last_argument format(MSG, param: block_param.source, method: block_param.send_node.source) end def wrap_in_parentheses(corrector, node) range = node.loc.selector.end.join(node.first_argument.source_range.begin) corrector.remove(range) corrector.insert_before(range, '(') corrector.insert_after(node.last_argument, ')') 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/format_parameter_mismatch.rb
lib/rubocop/cop/lint/format_parameter_mismatch.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # This lint sees if there is a mismatch between the number of # expected fields for format/sprintf/#% and what is actually # passed as arguments. # # In addition, it checks whether different formats are used in the same # format string. Do not mix numbered, unnumbered, and named formats in # the same format string. # # @example # # # bad # format('A value: %s and another: %i', a_value) # # # good # format('A value: %s and another: %i', a_value, another) # # # bad # format('Unnumbered format: %s and numbered: %2$s', a_value, another) # # # good # format('Numbered format: %1$s and numbered %2$s', a_value, another) class FormatParameterMismatch < Base # http://rubular.com/r/CvpbxkcTzy MSG = "Number of arguments (%<arg_num>i) to `%<method>s` doesn't " \ 'match the number of fields (%<field_num>i).' MSG_INVALID = 'Format string is invalid because formatting sequence types ' \ '(numbered, named or unnumbered) are mixed.' KERNEL = 'Kernel' SHOVEL = '<<' STRING_TYPES = %i[str dstr].freeze RESTRICT_ON_SEND = %i[format sprintf %].freeze def on_send(node) return unless format_string?(node) if invalid_format_string?(node) add_offense(node.loc.selector, message: MSG_INVALID) return end return unless offending_node?(node) add_offense(node.loc.selector, message: message(node)) end private def format_string?(node) called_on_string?(node) && method_with_format_args?(node) end def invalid_format_string?(node) string = if sprintf?(node) || format?(node) node.first_argument.source else node.receiver.source end !RuboCop::Cop::Utils::FormatString.new(string).valid? end def offending_node?(node) return false if splat_args?(node) num_of_format_args, num_of_expected_fields = count_matches(node) return false if num_of_format_args == :unknown first_arg = node.first_argument return false if num_of_expected_fields.zero? && first_arg.type?(:dstr, :array) matched_arguments_count?(num_of_expected_fields, num_of_format_args) end def matched_arguments_count?(expected, passed) if passed.negative? expected < passed.abs else expected != passed end end # @!method called_on_string?(node) def_node_matcher :called_on_string?, <<~PATTERN {(send {nil? const_type?} _ {str dstr} ...) (send {str dstr} ...)} PATTERN def method_with_format_args?(node) sprintf?(node) || format?(node) || percent?(node) end def splat_args?(node) return false if percent?(node) node.arguments.drop(1).any?(&:splat_type?) end def heredoc?(node) node.first_argument.source[0, 2] == SHOVEL end def count_matches(node) if countable_format?(node) count_format_matches(node) elsif countable_percent?(node) count_percent_matches(node) else [:unknown] * 2 end end def countable_format?(node) (sprintf?(node) || format?(node)) && !heredoc?(node) end def countable_percent?(node) percent?(node) && node.first_argument.array_type? end def count_format_matches(node) [node.arguments.count - 1, expected_fields_count(node.first_argument)] end def count_percent_matches(node) [node.first_argument.child_nodes.count, expected_fields_count(node.receiver)] end def format_method?(name, node) return false if node.const_receiver? && !node.receiver.loc.name.is?(KERNEL) return false unless node.method?(name) node.arguments.size > 1 && string_type?(node.first_argument) end def expected_fields_count(node) return :unknown unless string_type?(node) format_string = RuboCop::Cop::Utils::FormatString.new(node.source) return 1 if format_string.named_interpolation? max_digit_dollar_num = format_string.max_digit_dollar_num return max_digit_dollar_num if max_digit_dollar_num&.nonzero? format_string .format_sequences .reject(&:percent?) .reduce(0) { |acc, seq| acc + seq.arity } end def format?(node) format_method?(:format, node) end def sprintf?(node) format_method?(:sprintf, node) end def percent?(node) receiver = node.receiver percent = node.method?(:%) && (string_type?(receiver) || node.first_argument.array_type?) return false if percent && string_type?(receiver) && heredoc?(node) percent end def message(node) num_args_for_format, num_expected_fields = count_matches(node) method_name = node.method?(:%) ? 'String#%' : node.method_name format(MSG, arg_num: num_args_for_format, method: method_name, field_num: num_expected_fields) end def string_type?(node) STRING_TYPES.include?(node.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/empty_conditional_body.rb
lib/rubocop/cop/lint/empty_conditional_body.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for the presence of `if`, `elsif` and `unless` branches without a body. # # NOTE: empty `else` branches are handled by `Style/EmptyElse`. # # @example # # bad # if condition # end # # # bad # unless condition # end # # # bad # if condition # do_something # elsif other_condition # end # # # good # if condition # do_something # end # # # good # unless condition # do_something # end # # # good # if condition # do_something # elsif other_condition # nil # end # # # good # if condition # do_something # elsif other_condition # do_something_else # end # # @example AllowComments: true (default) # # good # if condition # do_something # elsif other_condition # # noop # end # # @example AllowComments: false # # bad # if condition # do_something # elsif other_condition # # noop # end # class EmptyConditionalBody < Base extend AutoCorrector include CommentsHelp MSG = 'Avoid `%<keyword>s` branches without a body.' def on_if(node) return if node.body || same_line?(node.loc.begin, node.loc.end) return if cop_config['AllowComments'] && contains_comments?(node) range = offense_range(node) add_offense(range, message: format(MSG, keyword: node.keyword)) do |corrector| next unless can_simplify_conditional?(node) flip_orphaned_else(corrector, node) end end private def offense_range(node) if node.loc.else node.source_range.begin.join(node.loc.else.begin) else node.source_range end end def can_simplify_conditional?(node) node.else_branch && node.loc.else.source == 'else' end def remove_empty_branch(corrector, node) range = if empty_if_branch?(node) && else_branch?(node) branch_range(node) else deletion_range(branch_range(node)) end corrector.remove(range) end def flip_orphaned_else(corrector, node) corrector.replace(node.loc.else, "#{node.inverse_keyword} #{node.condition.source}") remove_empty_branch(corrector, node) end def empty_if_branch?(node) return false unless (parent = node.parent) return true unless parent.if_type? return true unless (if_branch = parent.if_branch) if_branch.if_type? && !if_branch.body end def else_branch?(node) node.else_branch && !node.else_branch.if_type? end def branch_range(node) if empty_if_branch?(node) && else_branch?(node) node.source_range.with(end_pos: node.loc.else.begin_pos) elsif node.loc.else node.source_range.with(end_pos: node.condition.source_range.end_pos) end end def deletion_range(range) # Collect a range between the start of the `if` node and the next relevant node, # including final new line. # Based on `RangeHelp#range_by_whole_lines` but allows the `if` to not start # on the first column. buffer = @processed_source.buffer last_line = buffer.source_line(range.last_line) end_offset = last_line.length - range.last_column + 1 range.adjust(end_pos: end_offset).intersect(buffer.source_range) 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/erb_new_arguments.rb
lib/rubocop/cop/lint/erb_new_arguments.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Emulates the following Ruby warnings in Ruby 2.6. # # [source,console] # ---- # $ cat example.rb # ERB.new('hi', nil, '-', '@output_buffer') # $ ruby -rerb example.rb # example.rb:1: warning: Passing safe_level with the 2nd argument of ERB.new is # deprecated. Do not use it, and specify other arguments as keyword arguments. # example.rb:1: warning: Passing trim_mode with the 3rd argument of ERB.new is # deprecated. Use keyword argument like ERB.new(str, trim_mode:...) instead. # example.rb:1: warning: Passing eoutvar with the 4th argument of ERB.new is # deprecated. Use keyword argument like ERB.new(str, eoutvar: ...) instead. # ---- # # Now non-keyword arguments other than first one are softly deprecated # and will be removed when Ruby 2.5 becomes EOL. # `ERB.new` with non-keyword arguments is deprecated since ERB 2.2.0. # Use `:trim_mode` and `:eoutvar` keyword arguments to `ERB.new`. # This cop identifies places where `ERB.new(str, trim_mode, eoutvar)` can # be replaced by `ERB.new(str, :trim_mode: trim_mode, eoutvar: eoutvar)`. # # @example # # Target codes supports Ruby 2.6 and higher only # # bad # ERB.new(str, nil, '-', '@output_buffer') # # # good # ERB.new(str, trim_mode: '-', eoutvar: '@output_buffer') # # # Target codes supports Ruby 2.5 and lower only # # good # ERB.new(str, nil, '-', '@output_buffer') # # # Target codes supports Ruby 2.6, 2.5 and lower # # bad # ERB.new(str, nil, '-', '@output_buffer') # # # good # # Ruby standard library style # # https://github.com/ruby/ruby/commit/3406c5d # if ERB.instance_method(:initialize).parameters.assoc(:key) # Ruby 2.6+ # ERB.new(str, trim_mode: '-', eoutvar: '@output_buffer') # else # ERB.new(str, nil, '-', '@output_buffer') # end # # # good # # Use `RUBY_VERSION` style # if RUBY_VERSION >= '2.6' # ERB.new(str, trim_mode: '-', eoutvar: '@output_buffer') # else # ERB.new(str, nil, '-', '@output_buffer') # end # class ErbNewArguments < Base include RangeHelp extend AutoCorrector extend TargetRubyVersion minimum_target_ruby_version 2.6 MESSAGE_SAFE_LEVEL = 'Passing safe_level with the 2nd argument of `ERB.new` is ' \ 'deprecated. Do not use it, and specify other arguments as ' \ 'keyword arguments.' MESSAGE_TRIM_MODE = 'Passing trim_mode with the 3rd argument of `ERB.new` is ' \ 'deprecated. Use keyword argument like ' \ '`ERB.new(str, trim_mode: %<arg_value>s)` instead.' MESSAGE_EOUTVAR = 'Passing eoutvar with the 4th argument of `ERB.new` is ' \ 'deprecated. Use keyword argument like ' \ '`ERB.new(str, eoutvar: %<arg_value>s)` instead.' RESTRICT_ON_SEND = %i[new].freeze # @!method erb_new_with_non_keyword_arguments(node) def_node_matcher :erb_new_with_non_keyword_arguments, <<~PATTERN (send (const {nil? cbase} :ERB) :new $...) PATTERN def on_send(node) erb_new_with_non_keyword_arguments(node) do |arguments| return if arguments.empty? || correct_arguments?(arguments) arguments[1..3].each_with_index do |argument, i| next if !argument || argument.hash_type? add_offense( argument, message: message(i, argument.source) ) do |corrector| autocorrect(corrector, node) end end end end private def message(positional_argument_index, arg_value) case positional_argument_index when 0 MESSAGE_SAFE_LEVEL when 1 format(MESSAGE_TRIM_MODE, arg_value: arg_value) when 2 format(MESSAGE_EOUTVAR, arg_value: arg_value) end end def autocorrect(corrector, node) str_arg = node.first_argument.source kwargs = build_kwargs(node) overridden_kwargs = override_by_legacy_args(kwargs, node) good_arguments = [str_arg, overridden_kwargs].flatten.compact.join(', ') corrector.replace(arguments_range(node), good_arguments) end def correct_arguments?(arguments) arguments.size == 1 || (arguments.size == 2 && arguments[1].hash_type?) end def build_kwargs(node) return [nil, nil] unless node.last_argument.hash_type? trim_mode_arg, eoutvar_arg = nil node.last_argument.pairs.each do |pair| case pair.key.source when 'trim_mode' trim_mode_arg = "trim_mode: #{pair.value.source}" when 'eoutvar' eoutvar_arg = "eoutvar: #{pair.value.source}" end end [trim_mode_arg, eoutvar_arg] end def override_by_legacy_args(kwargs, node) arguments = node.arguments overridden_kwargs = kwargs.dup overridden_kwargs[0] = "trim_mode: #{arguments[2].source}" if arguments[2] if arguments[3] && !arguments[3].hash_type? overridden_kwargs[1] = "eoutvar: #{arguments[3].source}" end overridden_kwargs 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/multiple_comparison.rb
lib/rubocop/cop/lint/multiple_comparison.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # In math and Python, we can use `x < y < z` style comparison to compare # multiple value. However, we can't use the comparison in Ruby. However, # the comparison is not syntax error. This cop checks the bad usage of # comparison operators. # # @example # # # bad # x < y < z # 10 <= x <= 20 # # # good # x < y && y < z # 10 <= x && x <= 20 class MultipleComparison < Base extend AutoCorrector MSG = 'Use the `&&` operator to compare multiple values.' COMPARISON_METHODS = %i[< > <= >=].freeze SET_OPERATION_OPERATORS = %i[& | ^].freeze RESTRICT_ON_SEND = COMPARISON_METHODS # @!method multiple_compare?(node) def_node_matcher :multiple_compare?, <<~PATTERN (send (send _ {:< :> :<= :>=} $_) {:#{COMPARISON_METHODS.join(' :')}} _) PATTERN def on_send(node) return unless (center = multiple_compare?(node)) # It allows multiple comparison using `&`, `|`, and `^` set operation operators. # e.g. `x >= y & y < z` return if center.send_type? && SET_OPERATION_OPERATORS.include?(center.method_name) add_offense(node) do |corrector| new_center = "#{center.source} && #{center.source}" corrector.replace(center, new_center) 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/interpolation_check.rb
lib/rubocop/cop/lint/interpolation_check.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for interpolation in a single quoted string. # # @safety # This cop's autocorrection is unsafe because although it always replaces single quotes as # if it were miswritten double quotes, it is not always the case. For example, # `'#{foo} bar'` would be replaced by `"#{foo} bar"`, so the replaced code would evaluate # the expression `foo`. # # @example # # # bad # foo = 'something with #{interpolation} inside' # # # good # foo = "something with #{interpolation} inside" class InterpolationCheck < Base extend AutoCorrector MSG = 'Interpolation in single quoted string detected. ' \ 'Use double quoted strings if you need interpolation.' # rubocop:disable Metrics/CyclomaticComplexity def on_str(node) return if node.parent&.regexp_type? return unless /(?<!\\)#\{.*\}/.match?(node.source) return if heredoc?(node) return unless node.loc.begin && node.loc.end return unless valid_syntax?(node) add_offense(node) { |corrector| autocorrect(corrector, node) } end # rubocop:enable Metrics/CyclomaticComplexity private def autocorrect(corrector, node) starting_token, ending_token = if node.source.include?('"') ['%{', '}'] else ['"', '"'] end corrector.replace(node.loc.begin, starting_token) corrector.replace(node.loc.end, ending_token) end def heredoc?(node) node.loc.is_a?(Parser::Source::Map::Heredoc) || (node.parent && heredoc?(node.parent)) end def valid_syntax?(node) double_quoted_string = node.source.gsub(/\A'|'\z/, '"') parse(double_quoted_string).valid_syntax? 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/unused_method_argument.rb
lib/rubocop/cop/lint/unused_method_argument.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for unused method arguments. # # @example # # bad # def some_method(used, unused, _unused_but_allowed) # puts used # end # # # good # def some_method(used, _unused, _unused_but_allowed) # puts used # end # # @example AllowUnusedKeywordArguments: false (default) # # bad # def do_something(used, unused: 42) # used # end # # @example AllowUnusedKeywordArguments: true # # good # def do_something(used, unused: 42) # used # end # # @example IgnoreEmptyMethods: true (default) # # good # def do_something(unused) # end # # @example IgnoreEmptyMethods: false # # bad # def do_something(unused) # end # # @example IgnoreNotImplementedMethods: true (default) # # with default value of `NotImplementedExceptions: ['NotImplementedError']` # # # good # def do_something(unused) # raise NotImplementedError # end # # def do_something_else(unused) # fail "TODO" # end # # @example IgnoreNotImplementedMethods: true # # with `NotImplementedExceptions: ['AbstractMethodError']` # # # good # def do_something(unused) # raise AbstractMethodError # end # # @example IgnoreNotImplementedMethods: false # # bad # def do_something(unused) # raise NotImplementedError # end # # def do_something_else(unused) # fail "TODO" # end class UnusedMethodArgument < Base include UnusedArgument extend AutoCorrector # @!method not_implemented?(node) def_node_matcher :not_implemented?, <<~PATTERN {(send nil? :raise #allowed_exception_class? ...) (send nil? :fail ...)} PATTERN def self.autocorrect_incompatible_with [Style::ExplicitBlockArgument] end def self.joining_forces VariableForce end private def autocorrect(corrector, node) UnusedArgCorrector.correct(corrector, processed_source, node) end def check_argument(variable) return unless variable.method_argument? return if variable.keyword_argument? && cop_config['AllowUnusedKeywordArguments'] return if ignored_method?(variable.scope.node.body) super end def ignored_method?(body) (cop_config['IgnoreEmptyMethods'] && body.nil?) || (cop_config['IgnoreNotImplementedMethods'] && not_implemented?(body)) end def message(variable) message = +"Unused method argument - `#{variable.name}`." unless variable.keyword_argument? message << " If it's necessary, use `_` or `_#{variable.name}` " \ "as an argument name to indicate that it won't be used. " \ "If it's unnecessary, remove it." end scope = variable.scope all_arguments = scope.variables.each_value.select(&:method_argument?) if all_arguments.none?(&:referenced?) message << " You can also write as `#{scope.name}(*)` " \ 'if you want the method to accept any arguments ' \ "but don't care about them." end message end def allowed_exception_class?(node) return false unless node.const_type? allowed_class_names = Array(cop_config.fetch('NotImplementedExceptions', [])) allowed_class_names.include?(node.const_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/shadowed_argument.rb
lib/rubocop/cop/lint/shadowed_argument.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for shadowed arguments. # # This cop has `IgnoreImplicitReferences` configuration option. # It means argument shadowing is used in order to pass parameters # to zero arity `super` when `IgnoreImplicitReferences` is `true`. # # @example # # # bad # do_something do |foo| # foo = 42 # puts foo # end # # def do_something(foo) # foo = 42 # puts foo # end # # # good # do_something do |foo| # foo = foo + 42 # puts foo # end # # def do_something(foo) # foo = foo + 42 # puts foo # end # # def do_something(foo) # puts foo # end # # @example IgnoreImplicitReferences: false (default) # # # bad # def do_something(foo) # foo = 42 # super # end # # def do_something(foo) # foo = super # bar # end # # @example IgnoreImplicitReferences: true # # # good # def do_something(foo) # foo = 42 # super # end # # def do_something(foo) # foo = super # bar # end # class ShadowedArgument < Base MSG = 'Argument `%<argument>s` was shadowed by a local variable before it was used.' # @!method uses_var?(node) def_node_search :uses_var?, '(lvar %)' def self.joining_forces VariableForce end def after_leaving_scope(scope, _variable_table) scope.variables.each_value { |variable| check_argument(variable) } end private def check_argument(argument) return unless argument.method_argument? || argument.block_argument? # Block local variables, i.e., variables declared after ; inside # |...| aren't really arguments. return if argument.explicit_block_local_variable? shadowing_assignment(argument) do |node| message = format(MSG, argument: argument.name) add_offense(node, message: message) end end def shadowing_assignment(argument) return unless argument.referenced? assignment_without_argument_usage(argument) do |node, location_known| assignment_without_usage_pos = node.source_range.begin_pos references = argument_references(argument) # If argument was referenced before it was reassigned # then it's not shadowed next if references.any? do |reference| next true if !reference.explicit? && ignore_implicit_references? reference_pos(reference.node) <= assignment_without_usage_pos end yield location_known ? node : argument.declaration_node end end # Find the first argument assignment, which doesn't reference the # argument at the rhs. If the assignment occurs inside a branch or # block, it is impossible to tell whether it's executed, so precise # shadowing location is not known. # def assignment_without_argument_usage(argument) argument.assignments.reduce(true) do |location_known, assignment| assignment_node = assignment.meta_assignment_node || assignment.node # Shorthand assignments always use their arguments next false if assignment_node.shorthand_asgn? next false unless assignment_node.parent conditional_assignment = conditional_assignment?(assignment_node.parent, argument.scope.node) unless uses_var?(assignment_node, argument.name) # It's impossible to decide whether a branch or block is executed, # so the precise reassignment location is undecidable. next false if conditional_assignment yield(assignment.node, location_known) break end location_known end end def reference_pos(node) node = node.parent if node.parent.masgn_type? node.source_range.begin_pos end # Check whether the given node is always executed or not # def conditional_assignment?(node, stop_search_node) return false if node == stop_search_node node.conditional? || node.type?(:block, :rescue) || conditional_assignment?(node.parent, stop_search_node) end # Get argument references without assignments' references # def argument_references(argument) assignment_references = argument.assignments.flat_map(&:references).map(&:source_range) argument.references.reject do |ref| next false unless ref.explicit? assignment_references.include?(ref.node.source_range) end end def ignore_implicit_references? cop_config['IgnoreImplicitReferences'] 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/ensure_return.rb
lib/rubocop/cop/lint/ensure_return.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for `return` from an `ensure` block. # `return` from an ensure block is a dangerous code smell as it # will take precedence over any exception being raised, # and the exception will be silently thrown away as if it were rescued. # # If you want to rescue some (or all) exceptions, best to do it explicitly # # @example # # # bad # def foo # do_something # ensure # cleanup # return self # end # # # good # def foo # do_something # self # ensure # cleanup # end # # # good # def foo # begin # do_something # rescue SomeException # # Let's ignore this exception # end # self # ensure # cleanup # end class EnsureReturn < Base MSG = 'Do not return from an `ensure` block.' def on_ensure(node) node.branch&.each_node(:return) { |return_node| add_offense(return_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/mixed_case_range.rb
lib/rubocop/cop/lint/mixed_case_range.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for mixed-case character ranges since they include likely unintended characters. # # Offenses are registered for regexp character classes like `/[A-z]/` # as well as range objects like `('A'..'z')`. # # NOTE: `Range` objects cannot be autocorrected. # # @safety # The cop autocorrects regexp character classes # by replacing one character range with two: `A-z` becomes `A-Za-z`. # In most cases this is probably what was originally intended # but it changes the regexp to no longer match symbols it used to include. # For this reason, this cop's autocorrect is unsafe (it will # change the behavior of the code). # # @example # # # bad # r = /[A-z]/ # # # good # r = /[A-Za-z]/ class MixedCaseRange < Base extend AutoCorrector include RangeHelp MSG = 'Ranges from upper to lower case ASCII letters may include unintended ' \ 'characters. Instead of `A-z` (which also includes several symbols) ' \ 'specify each range individually: `A-Za-z` and individually specify any symbols.' RANGES = [('a'..'z').freeze, ('A'..'Z').freeze].freeze def on_irange(node) return unless node.children.compact.all?(&:str_type?) return if node.begin.nil? || node.end.nil? add_offense(node) if unsafe_range?(node.begin.value, node.end.value) end alias on_erange on_irange def on_regexp(node) each_unsafe_regexp_range(node) do |loc| next unless (replacement = regexp_range(loc.source)) add_offense(loc) do |corrector| corrector.replace(loc, replacement) end end end def each_unsafe_regexp_range(node) node.parsed_tree&.each_expression do |expr| next if skip_expression?(expr) range_pairs(expr).reject do |range_start, range_end| next if skip_range?(range_start, range_end) next unless unsafe_range?(range_start.text, range_end.text) yield(build_source_range(range_start, range_end)) end end end private def build_source_range(range_start, range_end) range_between(range_start.expression.begin_pos, range_end.expression.end_pos) end def range_for(char) RANGES.detect do |range| range.include?(char) end end def range_pairs(expr) expr.expressions.filter_map { |e| [e.expressions[0], e.expressions[1]] if e.type == :set } end def unsafe_range?(range_start, range_end) return false if range_start.length != 1 || range_end.length != 1 range_for(range_start) != range_for(range_end) end def skip_expression?(expr) !(expr.type == :set && expr.token == :character) end def skip_range?(range_start, range_end) [range_start, range_end].any? do |bound| bound&.type != :literal end end def regexp_range(source) open, close = source.split('-') return unless (open_range = range_for(open)) return unless (close_range = range_for(close)) first = [open, open_range.end] second = [close_range.begin, close] "#{first.uniq.join('-')}#{second.uniq.join('-')}" 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_dir_glob_sort.rb
lib/rubocop/cop/lint/redundant_dir_glob_sort.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Sort globbed results by default in Ruby 3.0. # This cop checks for redundant `sort` method to `Dir.glob` and `Dir[]`. # # @safety # This cop is unsafe, in case of having a file and a directory with # identical names, since directory will be loaded before the file, which # will break `exe/files.rb` that rely on `exe.rb` file. # # @example # # # bad # Dir.glob('./lib/**/*.rb').sort.each do |file| # end # # Dir['./lib/**/*.rb'].sort.each do |file| # end # # # good # Dir.glob('./lib/**/*.rb').each do |file| # end # # Dir['./lib/**/*.rb'].each do |file| # end # class RedundantDirGlobSort < Base extend AutoCorrector extend TargetRubyVersion minimum_target_ruby_version 3.0 MSG = 'Remove redundant `sort`.' RESTRICT_ON_SEND = %i[sort].freeze GLOB_METHODS = %i[glob []].freeze def on_send(node) return unless (receiver = node.receiver) return unless receiver.receiver&.const_type? && receiver.receiver.short_name == :Dir return unless GLOB_METHODS.include?(receiver.method_name) return if multiple_argument?(receiver) selector = node.loc.selector add_offense(selector) do |corrector| corrector.remove(selector) corrector.remove(node.loc.dot) end end private def multiple_argument?(glob_method) glob_method.arguments.count >= 2 || glob_method.first_argument&.splat_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/debugger.rb
lib/rubocop/cop/lint/debugger.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for debug calls (such as `debugger` or `binding.pry`) that should # not be kept for production code. # # The cop can be configured using `DebuggerMethods`. By default, a number of gems # debug entrypoints are configured (`Kernel`, `Byebug`, `Capybara`, `debug.rb`, # `Pry`, `Rails`, `RubyJard`, and `WebConsole`). Additional methods can be added. # # Specific default groups can be disabled if necessary: # # [source,yaml] # ---- # Lint/Debugger: # DebuggerMethods: # WebConsole: ~ # ---- # # You can also add your own methods by adding a new category: # # [source,yaml] # ---- # Lint/Debugger: # DebuggerMethods: # MyDebugger: # MyDebugger.debug_this # ---- # # Some gems also ship files that will start a debugging session when required, # for example `require 'debug/start'` from `ruby/debug`. These requires can # be configured through `DebuggerRequires`. It has the same structure as # `DebuggerMethods`, which you can read about above. # # @example # # # bad (ok during development) # # # using pry # def some_method # binding.pry # do_something # end # # # bad (ok during development) # # # using byebug # def some_method # byebug # do_something # end # # # good # # def some_method # do_something # end # # @example DebuggerMethods: [my_debugger] # # # bad (ok during development) # # def some_method # my_debugger # end # # @example DebuggerRequires: [my_debugger/start] # # # bad (ok during development) # # require 'my_debugger/start' class Debugger < Base MSG = 'Remove debugger entry point `%<source>s`.' BLOCK_TYPES = %i[block numblock itblock kwbegin].freeze def on_send(node) return if assumed_usage_context?(node) add_offense(node) if debugger_method?(node) || debugger_require?(node) end private def message(node) format(MSG, source: node.source) end def debugger_methods @debugger_methods ||= begin config = cop_config.fetch('DebuggerMethods', []) config.is_a?(Array) ? config : config.values.flatten end end def debugger_requires @debugger_requires ||= begin config = cop_config.fetch('DebuggerRequires', []) config.is_a?(Array) ? config : config.values.flatten end end def debugger_method?(send_node) debugger_methods.include?(chained_method_name(send_node)) end def debugger_require?(send_node) return false unless send_node.method?(:require) && send_node.arguments.one? return false unless (argument = send_node.first_argument).str_type? debugger_requires.include?(argument.value) end def assumed_usage_context?(node) # Basically, debugger methods are not used as a method argument without arguments. return false unless node.arguments.empty? && node.each_ancestor(:call).any? return true if assumed_argument?(node) node.each_ancestor.none? do |ancestor| ancestor.type?(:any_block, :kwbegin) || ancestor.lambda_or_proc? end end def chained_method_name(send_node) chained_method_name = send_node.method_name.to_s receiver = send_node.receiver while receiver name = receiver.send_type? ? receiver.method_name : receiver.const_name chained_method_name = "#{name}.#{chained_method_name}" receiver = receiver.receiver end chained_method_name end def assumed_argument?(node) parent = node.parent parent.call_type? || parent.literal? || parent.pair_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/empty_class.rb
lib/rubocop/cop/lint/empty_class.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for classes and metaclasses without a body. # Such empty classes and metaclasses are typically an oversight or we should provide a comment # to be clearer what we're aiming for. # # @example # # bad # class Foo # end # # class Bar # class << self # end # end # # class << obj # end # # # good # class Foo # def do_something # # ... code # end # end # # class Bar # class << self # attr_reader :bar # end # end # # class << obj # attr_reader :bar # end # # @example AllowComments: false (default) # # bad # class Foo # # TODO: implement later # end # # class Bar # class << self # # TODO: implement later # end # end # # class << obj # # TODO: implement later # end # # @example AllowComments: true # # good # class Foo # # TODO: implement later # end # # class Bar # class << self # # TODO: implement later # end # end # # class << obj # # TODO: implement later # end # class EmptyClass < Base CLASS_MSG = 'Empty class detected.' METACLASS_MSG = 'Empty metaclass detected.' def on_class(node) add_offense(node, message: CLASS_MSG) unless body_or_allowed_comment_lines?(node) || node.parent_class end def on_sclass(node) add_offense(node, message: METACLASS_MSG) unless body_or_allowed_comment_lines?(node) end private def body_or_allowed_comment_lines?(node) return true if node.body cop_config['AllowComments'] && processed_source.contains_comment?(node.source_range) 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_relative_self_path.rb
lib/rubocop/cop/lint/require_relative_self_path.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for uses a file requiring itself with `require_relative`. # # @example # # # bad # # # foo.rb # require_relative 'foo' # require_relative 'bar' # # # good # # # foo.rb # require_relative 'bar' # class RequireRelativeSelfPath < Base include RangeHelp extend AutoCorrector MSG = 'Remove the `require_relative` that requires itself.' RESTRICT_ON_SEND = %i[require_relative].freeze def on_send(node) return unless (required_feature = node.first_argument) return unless required_feature.respond_to?(:value) return unless same_file?(processed_source.file_path, required_feature.value) add_offense(node) do |corrector| corrector.remove(range_by_whole_lines(node.source_range, include_final_newline: true)) end end private def same_file?(file_path, required_feature) file_path == required_feature || remove_ext(file_path) == required_feature end def remove_ext(file_path) File.basename(file_path, File.extname(file_path)) 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_method_definition.rb
lib/rubocop/cop/lint/useless_method_definition.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for useless method definitions, specifically: empty constructors # and methods just delegating to `super`. # # @safety # This cop is unsafe as it can register false positives for cases when an empty # constructor just overrides the parent constructor, which is bad anyway. # # @example # # bad # def initialize # super # end # # def method # super # end # # # good - with default arguments # def initialize(x = Object.new) # super # end # # # good # def initialize # super # initialize_internals # end # # def method(*args) # super(:extra_arg, *args) # end # class UselessMethodDefinition < Base extend AutoCorrector MSG = 'Useless method definition detected.' def on_def(node) return if method_definition_with_modifier?(node) || use_rest_or_optional_args?(node) return unless delegating?(node.body, node) add_offense(node) do |corrector| range = node.parent&.send_type? ? node.parent : node corrector.remove(range) end end alias on_defs on_def private def method_definition_with_modifier?(node) node.parent&.send_type? && !node.parent&.non_bare_access_modifier? end def use_rest_or_optional_args?(node) node.arguments.any? { |arg| arg.type?(:restarg, :optarg, :kwoptarg) } end def delegating?(node, def_node) if node&.zsuper_type? true elsif node&.super_type? node.arguments.map(&:source) == def_node.arguments.map(&:source) else false 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/script_permission.rb
lib/rubocop/cop/lint/script_permission.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks if a file which has a shebang line as # its first line is granted execute permission. # # @example # # bad # # # A file which has a shebang line as its first line is not # # granted execute permission. # # #!/usr/bin/env ruby # puts 'hello, world' # # # good # # # A file which has a shebang line as its first line is # # granted execute permission. # # #!/usr/bin/env ruby # puts 'hello, world' # # # good # # # A file which has not a shebang line as its first line is not # # granted execute permission. # # puts 'hello, world' # class ScriptPermission < Base extend AutoCorrector MSG = "Script file %<file>s doesn't have execute permission." SHEBANG = '#!' def on_new_investigation return if @options.key?(:stdin) return if Platform.windows? return unless processed_source.start_with?(SHEBANG) return if executable?(processed_source) comment = processed_source.comments[0] message = format_message_from(processed_source) add_offense(comment, message: message) do autocorrect if autocorrect_requested? end end private def autocorrect FileUtils.chmod('+x', processed_source.file_path) end def executable?(processed_source) # Returns true if stat is executable or if the operating system # doesn't distinguish executable files from nonexecutable files. # See at: https://github.com/ruby/ruby/blob/ruby_2_4/file.c#L5362 File.stat(processed_source.file_path).executable? end def format_message_from(processed_source) basename = File.basename(processed_source.file_path) format(MSG, file: basename) 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_methods.rb
lib/rubocop/cop/lint/duplicate_methods.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for duplicated instance (or singleton) method # definitions. # # NOTE: Aliasing a method to itself is allowed, as it indicates that # the developer intends to suppress Ruby's method redefinition warnings. # See https://bugs.ruby-lang.org/issues/13574. # # @example # # # bad # def foo # 1 # end # # def foo # 2 # end # # # bad # def foo # 1 # end # # alias foo bar # # # good # def foo # 1 # end # # def bar # 2 # end # # # good # def foo # 1 # end # # alias bar foo # # # good # alias foo foo # def foo # 1 # end # # # good # alias_method :foo, :foo # def foo # 1 # end # # @example AllCops:ActiveSupportExtensionsEnabled: false (default) # # # good # def foo # 1 # end # # delegate :foo, to: :bar # # @example AllCops:ActiveSupportExtensionsEnabled: true # # # bad # def foo # 1 # end # # delegate :foo, to: :bar # # # good # def foo # 1 # end # # delegate :baz, to: :bar # # # good - delegate with splat arguments is ignored # def foo # 1 # end # # delegate :foo, **options # # # good - delegate inside a condition is ignored # def foo # 1 # end # # if cond # delegate :foo, to: :bar # end # class DuplicateMethods < Base MSG = 'Method `%<method>s` is defined at both %<defined>s and %<current>s.' RESTRICT_ON_SEND = %i[alias_method attr_reader attr_writer attr_accessor attr delegate].freeze def initialize(config = nil, options = nil) super @definitions = {} @scopes = Hash.new { |hash, key| hash[key] = [] } end def on_def(node) # if a method definition is inside an if, it is very likely # that a different definition is used depending on platform, etc. return if node.each_ancestor.any?(&:if_type?) found_instance_method(node, node.method_name) end def on_defs(node) return if node.each_ancestor.any?(&:if_type?) if node.receiver.const_type? _, const_name = *node.receiver check_const_receiver(node, node.method_name, const_name) elsif node.receiver.self_type? check_self_receiver(node, node.method_name) end end # @!method method_alias?(node) def_node_matcher :method_alias?, <<~PATTERN (alias (sym $_name) (sym $_original_name)) PATTERN def on_alias(node) name, original_name = method_alias?(node) return unless name && original_name return if name == original_name return if node.ancestors.any?(&:if_type?) found_instance_method(node, name) end # @!method alias_method?(node) def_node_matcher :alias_method?, <<~PATTERN (send nil? :alias_method (sym $_name) (sym $_original_name)) PATTERN # @!method delegate_method?(node) def_node_matcher :delegate_method?, <<~PATTERN (send nil? :delegate ({sym str} $_)+ (hash <(pair (sym :to) {sym str}) ...>) ) PATTERN # @!method sym_name(node) def_node_matcher :sym_name, '(sym $_name)' def on_send(node) # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity name, original_name = alias_method?(node) if name && original_name return if name == original_name return if node.ancestors.any?(&:if_type?) found_instance_method(node, name) elsif (attr = node.attribute_accessor?) on_attr(node, *attr) elsif active_support_extensions_enabled? && (names = delegate_method?(node)) return if node.ancestors.any?(&:if_type?) on_delegate(node, names) end end private def check_const_receiver(node, name, const_name) qualified = lookup_constant(node, const_name) return unless qualified found_method(node, "#{qualified}.#{name}") end def check_self_receiver(node, name) enclosing = node.parent_module_name return unless enclosing found_method(node, "#{enclosing}.#{name}") end def message_for_dup(node, method_name, key) format(MSG, method: method_name, defined: source_location(@definitions[key]), current: source_location(node)) end def on_delegate(node, method_names) name_prefix = delegate_prefix(node) method_names.each do |name| name = "#{name_prefix}_#{name}" if name_prefix found_instance_method(node, name) end end def delegate_prefix(node) kwargs_node = node.last_argument return unless (prefix = hash_value(kwargs_node, :prefix)) if prefix.true_type? hash_value(kwargs_node, :to).value elsif prefix.type?(:sym, :str) prefix.value end end def hash_value(node, key) node.pairs.find { |pair| pair.key.value == key }&.value end def found_instance_method(node, name) return found_sclass_method(node, name) unless (scope = node.parent_module_name) # Humanize the scope scope = scope.sub( /(?:(?<name>.*)::)#<Class:\k<name>>|#<Class:(?<name>.*)>(?:::)?/, '\k<name>.' ) scope << '#' unless scope.end_with?('.') found_method(node, "#{scope}#{name}") end def found_sclass_method(node, name) singleton_ancestor = node.each_ancestor.find(&:sclass_type?) return unless singleton_ancestor singleton_receiver_node = singleton_ancestor.children[0] return unless singleton_receiver_node.send_type? found_method(node, "#{singleton_receiver_node.method_name}.#{name}") end def found_method(node, method_name) key = method_key(node, method_name) scope = node.each_ancestor(:rescue, :ensure).first&.type if @definitions.key?(key) if scope && !@scopes[scope].include?(key) @definitions[key] = node @scopes[scope] << key return end message = message_for_dup(node, method_name, key) add_offense(location(node), message: message) else @definitions[key] = node end end def method_key(node, method_name) if (ancestor_def = node.each_ancestor(:any_def).first) "#{ancestor_def.method_name}.#{method_name}" else method_name end end def location(node) if node.any_def_type? node.loc.keyword.join(node.loc.name) else node.source_range end end def on_attr(node, attr_name, args) case attr_name when :attr writable = args.size == 2 && args.last.true_type? found_attr(node, [args.first], readable: true, writable: writable) when :attr_reader found_attr(node, args, readable: true) when :attr_writer found_attr(node, args, writable: true) when :attr_accessor found_attr(node, args, readable: true, writable: true) end end def found_attr(node, args, readable: false, writable: false) args.each do |arg| name = sym_name(arg) next unless name found_instance_method(node, name) if readable found_instance_method(node, "#{name}=") if writable end end def lookup_constant(node, const_name) # this method is quite imperfect and can be fooled # to do much better, we would need to do global analysis of the whole # codebase node.each_ancestor(:class, :module, :casgn) do |ancestor| namespace, mod_name = *ancestor.defined_module loop do if mod_name == const_name return qualified_name(ancestor.parent_module_name, namespace, mod_name) end break if namespace.nil? namespace, mod_name = *namespace end end end def qualified_name(enclosing, namespace, mod_name) if enclosing != 'Object' if namespace "#{enclosing}::#{namespace.const_name}::#{mod_name}" else "#{enclosing}::#{mod_name}" end elsif namespace "#{namespace.const_name}::#{mod_name}" else mod_name end end def source_location(node) range = node.source_range path = smart_path(range.source_buffer.name) "#{path}:#{range.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/empty_block.rb
lib/rubocop/cop/lint/empty_block.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for blocks without a body. # Such empty blocks are typically an oversight or we should provide a comment # to clarify what we're aiming for. # # Empty lambdas and procs are ignored by default. # # NOTE: For backwards compatibility, the configuration that allows/disallows # empty lambdas and procs is called `AllowEmptyLambdas`, even though it also # applies to procs. # # @example # # bad # items.each { |item| } # # # good # items.each { |item| puts item } # # @example AllowComments: true (default) # # good # items.each do |item| # # TODO: implement later (inner comment) # end # # items.each { |item| } # TODO: implement later (inline comment) # # @example AllowComments: false # # bad # items.each do |item| # # TODO: implement later (inner comment) # end # # items.each { |item| } # TODO: implement later (inline comment) # # @example AllowEmptyLambdas: true (default) # # good # allow(subject).to receive(:callable).and_return(-> {}) # # placeholder = lambda do # end # (callable || placeholder).call # # proc { } # # Proc.new { } # # @example AllowEmptyLambdas: false # # bad # allow(subject).to receive(:callable).and_return(-> {}) # # placeholder = lambda do # end # (callable || placeholder).call # # proc { } # # Proc.new { } # class EmptyBlock < Base MSG = 'Empty block detected.' def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler return if node.body return if allow_empty_lambdas? && node.lambda_or_proc? return if cop_config['AllowComments'] && allow_comment?(node) add_offense(node) end private def allow_comment?(node) return false unless processed_source.contains_comment?(node.source_range) line_comment = processed_source.comment_at_line(node.source_range.line) !line_comment || !comment_disables_cop?(line_comment.source) end def allow_empty_lambdas? cop_config['AllowEmptyLambdas'] end def comment_disables_cop?(comment) regexp_pattern = "# rubocop : (disable|todo) ([^,],)* (all|#{cop_name})" Regexp.new(regexp_pattern.gsub(' ', '\s*')).match?(comment) 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_operator_precedence.rb
lib/rubocop/cop/lint/ambiguous_operator_precedence.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Looks for expressions containing multiple binary operators # where precedence is ambiguous due to lack of parentheses. For example, # in `1 + 2 * 3`, the multiplication will happen before the addition, but # lexically it appears that the addition will happen first. # # The cop does not consider unary operators (ie. `!a` or `-b`) or comparison # operators (ie. `a =~ b`) because those are not ambiguous. # # NOTE: Ranges are handled by `Lint/AmbiguousRange`. # # @example # # bad # a + b * c # a || b && c # a ** b + c # # # good (different precedence) # a + (b * c) # a || (b && c) # (a ** b) + c # # # good (same precedence) # a + b + c # a * b / c % d class AmbiguousOperatorPrecedence < Base extend AutoCorrector # See https://ruby-doc.org/core-3.0.2/doc/syntax/precedence_rdoc.html PRECEDENCE = [ %i[**], %i[* / %], %i[+ -], %i[<< >>], %i[&], %i[| ^], %i[&&], %i[||] ].freeze RESTRICT_ON_SEND = PRECEDENCE.flatten.freeze MSG = 'Wrap expressions with varying precedence with parentheses to avoid ambiguity.' def on_new_investigation # Cache the precedence of each node being investigated # so that we only need to calculate it once @node_precedences = {} super end def on_and(node) return unless (parent = node.parent) return if parent.begin_type? # if the `and` is in a `begin`, it's parenthesized already return unless parent.or_type? add_offense(node) do |corrector| autocorrect(corrector, node) end end def on_send(node) return if node.parenthesized? return unless (parent = node.parent) return unless operator?(parent) return unless greater_precedence?(node, parent) add_offense(node) do |corrector| autocorrect(corrector, node) end end private def precedence(node) @node_precedences.fetch(node) do PRECEDENCE.index { |operators| operators.include?(operator_name(node)) } end end def operator?(node) (node.send_type? && RESTRICT_ON_SEND.include?(node.method_name)) || node.operator_keyword? end def greater_precedence?(node1, node2) node1_precedence = precedence(node1) node2_precedence = precedence(node2) return false unless node1_precedence && node2_precedence node2_precedence > node1_precedence end def operator_name(node) if node.send_type? node.method_name else node.operator.to_sym end end def autocorrect(corrector, node) corrector.wrap(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_ruby2_keywords.rb
lib/rubocop/cop/lint/useless_ruby2_keywords.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Looks for `ruby2_keywords` calls for methods that do not need it. # # `ruby2_keywords` should only be called on methods that accept an argument splat # (`\*args`) but do not explicit keyword arguments (`k:` or `k: true`) or # a keyword splat (`**kwargs`). # # @example # # good (splat argument without keyword arguments) # ruby2_keywords def foo(*args); end # # # bad (no arguments) # ruby2_keywords def foo; end # # # good # def foo; end # # # bad (positional argument) # ruby2_keywords def foo(arg); end # # # good # def foo(arg); end # # # bad (double splatted argument) # ruby2_keywords def foo(**args); end # # # good # def foo(**args); end # # # bad (keyword arguments) # ruby2_keywords def foo(i:, j:); end # # # good # def foo(i:, j:); end # # # bad (splat argument with keyword arguments) # ruby2_keywords def foo(*args, i:, j:); end # # # good # def foo(*args, i:, j:); end # # # bad (splat argument with double splat) # ruby2_keywords def foo(*args, **kwargs); end # # # good # def foo(*args, **kwargs); end # # # bad (ruby2_keywords given a symbol) # def foo; end # ruby2_keywords :foo # # # good # def foo; end # # # bad (ruby2_keywords with dynamic method) # define_method(:foo) { |arg| } # ruby2_keywords :foo # # # good # define_method(:foo) { |arg| } # class UselessRuby2Keywords < Base MSG = '`ruby2_keywords` is unnecessary for method `%<method_name>s`.' RESTRICT_ON_SEND = %i[ruby2_keywords].freeze # Looks for statically or dynamically defined methods with a given name # @!method method_definition(node, method_name) def_node_matcher :method_definition, <<~PATTERN { (def %1 ...) (any_block (send _ :define_method (sym %1)) ...) } PATTERN def on_send(node) return unless (first_argument = node.first_argument) if first_argument.def_type? inspect_def(node, first_argument) elsif node.first_argument.sym_type? inspect_sym(node, first_argument) end end private def inspect_def(node, def_node) return if allowed_arguments?(def_node.arguments) add_offense(node.loc.selector, message: format(MSG, method_name: def_node.method_name)) end def inspect_sym(node, sym_node) return unless node.parent method_name = sym_node.value definition = find_method_definition(node, method_name) return unless definition return if allowed_arguments?(definition.arguments) add_offense(node, message: format(MSG, method_name: method_name)) end def find_method_definition(node, method_name) node.each_ancestor.lazy.map do |ancestor| ancestor.each_child_node(:def, :any_block).find do |child| method_definition(child, method_name) end end.find(&:itself) end # `ruby2_keywords` is only allowed if there's a `restarg` and no keyword arguments def allowed_arguments?(arguments) return false if arguments.empty? arguments.each_child_node(:restarg).any? && arguments.each_child_node(:kwarg, :kwoptarg, :kwrestarg).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/redundant_with_index.rb
lib/rubocop/cop/lint/redundant_with_index.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for redundant `with_index`. # # @example # # bad # ary.each_with_index do |v| # v # end # # # good # ary.each do |v| # v # end # # # bad # ary.each.with_index do |v| # v # end # # # good # ary.each do |v| # v # end # class RedundantWithIndex < Base include RangeHelp extend AutoCorrector MSG_EACH_WITH_INDEX = 'Use `each` instead of `each_with_index`.' MSG_WITH_INDEX = 'Remove redundant `with_index`.' # rubocop:disable Metrics/AbcSize def on_block(node) return unless node.receiver return if node.method?(:with_index) && !node.receiver.receiver return unless (send = redundant_with_index?(node)) range = with_index_range(send) add_offense(range, message: message(send)) do |corrector| if send.method?(:each_with_index) corrector.replace(send.loc.selector, 'each') else corrector.remove(range) corrector.remove(send.loc.dot) end end end # rubocop:enable Metrics/AbcSize alias on_numblock on_block alias on_itblock on_block private # @!method redundant_with_index?(node) def_node_matcher :redundant_with_index?, <<~PATTERN { (block $(call _ {:each_with_index :with_index} ...) (args (arg _)) ...) (numblock $(call _ {:each_with_index :with_index} ...) 1 ...) (itblock $(call _ {:each_with_index :with_index} ...) _ ...) } PATTERN def message(node) if node.method?(:each_with_index) MSG_EACH_WITH_INDEX else MSG_WITH_INDEX end end def with_index_range(send) range_between(send.loc.selector.begin_pos, send.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/lint/top_level_return_with_argument.rb
lib/rubocop/cop/lint/top_level_return_with_argument.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for top level return with arguments. If there is a # top-level return statement with an argument, then the argument is # always ignored. This is detected automatically since Ruby 2.7. # # @example # # bad # return 1 # # # good # return class TopLevelReturnWithArgument < Base extend AutoCorrector MSG = 'Top level return with argument detected.' def on_return(return_node) return unless top_level_return_with_any_argument?(return_node) add_offense(return_node) do |corrector| remove_arguments(corrector, return_node) end end private def top_level_return_with_any_argument?(return_node) top_level_return?(return_node) && return_node.arguments? end def remove_arguments(corrector, return_node) corrector.replace(return_node, 'return') end # This cop works by validating the ancestors of the return node. A # top-level return node's ancestors should not be of block, def, or # defs type. def top_level_return?(return_node) return_node.each_ancestor(:block, :any_def).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/ineffective_access_modifier.rb
lib/rubocop/cop/lint/ineffective_access_modifier.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for `private` or `protected` access modifiers which are # applied to a singleton method. These access modifiers do not make # singleton methods private/protected. `private_class_method` can be # used for that. # # @example # # # bad # class C # private # # def self.method # puts 'hi' # end # end # # # good # class C # def self.method # puts 'hi' # end # # private_class_method :method # end # # # good # class C # class << self # private # # def method # puts 'hi' # end # end # end class IneffectiveAccessModifier < Base MSG = '`%<modifier>s` (on line %<line>d) does not make singleton ' \ 'methods %<modifier>s. Use %<alternative>s instead.' ALTERNATIVE_PRIVATE = '`private_class_method` or `private` inside a `class << self` block' ALTERNATIVE_PROTECTED = '`protected` inside a `class << self` block' # @!method private_class_methods(node) def_node_search :private_class_methods, <<~PATTERN (send nil? :private_class_method $...) PATTERN def on_class(node) check_node(node.body) end alias on_module on_class private def check_node(node) return unless node&.begin_type? ineffective_modifier(node) do |defs_node, modifier| add_offense(defs_node.loc.keyword, message: format_message(modifier)) end end def private_class_method_names(node) private_class_methods(node).to_a.flatten.select(&:basic_literal?).map(&:value) end def format_message(modifier) visibility = modifier.method_name alternative = if visibility == :private ALTERNATIVE_PRIVATE else ALTERNATIVE_PROTECTED end format(MSG, modifier: visibility, line: modifier.source_range.line, alternative: alternative) end # rubocop:disable Metrics/CyclomaticComplexity def ineffective_modifier(node, ignored_methods = nil, modifier = nil, &block) node.each_child_node do |child| case child.type when :send modifier = child if access_modifier?(child) when :defs ignored_methods ||= private_class_method_names(node) next if correct_visibility?(child, modifier, ignored_methods) yield child, modifier when :kwbegin ignored_methods ||= private_class_method_names(node) ineffective_modifier(child, ignored_methods, modifier, &block) end end end # rubocop:enable Metrics/CyclomaticComplexity def access_modifier?(node) node.bare_access_modifier? && !node.method?(:module_function) end def correct_visibility?(node, modifier, ignored_methods) return true if modifier.nil? || modifier.method?(:public) ignored_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/rescue_exception.rb
lib/rubocop/cop/lint/rescue_exception.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for `rescue` blocks targeting the `Exception` class. # # @example # # # bad # begin # do_something # rescue Exception # handle_exception # end # # # good # begin # do_something # rescue ArgumentError # handle_exception # end class RescueException < Base MSG = 'Avoid rescuing the `Exception` class. Perhaps you meant to rescue `StandardError`?' def on_resbody(node) return unless node.exceptions.any? { |exception| targets_exception?(exception) } add_offense(node) end def targets_exception?(rescue_arg_node) rescue_arg_node.const_name == 'Exception' 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_set_element.rb
lib/rubocop/cop/lint/duplicate_set_element.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for duplicate literal, constant, or variable elements in `Set` and `SortedSet`. # # @example # # # bad # Set[:foo, :bar, :foo] # # # good # Set[:foo, :bar] # # # bad # Set.new([:foo, :bar, :foo]) # # # good # Set.new([:foo, :bar]) # # # bad # [:foo, :bar, :foo].to_set # # # good # [:foo, :bar].to_set # # # bad # SortedSet[:foo, :bar, :foo] # # # good # SortedSet[:foo, :bar] # # # bad # SortedSet.new([:foo, :bar, :foo]) # # # good # SortedSet.new([:foo, :bar]) class DuplicateSetElement < Base extend AutoCorrector MSG = 'Remove the duplicate element in %<class_name>s.' RESTRICT_ON_SEND = %i[\[\] new to_set].freeze # @!method set_init_elements(node) def_node_matcher :set_init_elements, <<~PATTERN { (send (const {nil? cbase} {:Set :SortedSet}) :[] $...) (send (const {nil? cbase} {:Set :SortedSet}) :new (array $...)) (call (array $...) :to_set) } PATTERN def on_send(node) return unless (set_elements = set_init_elements(node)) seen_elements = Set[] set_elements.each_with_index do |set_element, index| # NOTE: Skip due to the possibility of corner cases where Set elements # may have changing return values if they are not literals, constants, or variables. next if !set_element.literal? && !set_element.const_type? && !set_element.variable? if seen_elements.include?(set_element) register_offense(set_element, set_elements[index - 1], node) else seen_elements << set_element end end end alias on_csend on_send private def register_offense(current_element, prev_element, node) class_name = node.receiver.const_type? ? node.receiver.const_name : 'Set' add_offense(current_element, message: format(MSG, class_name: class_name)) do |corrector| range = prev_element.source_range.end.join(current_element.source_range.end) corrector.remove(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/redundant_safe_navigation.rb
lib/rubocop/cop/lint/redundant_safe_navigation.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for redundant safe navigation calls. # Use cases where a constant, named in camel case for classes and modules is `nil` are rare, # and an offense is not detected when the receiver is a constant. The detection also applies # to `self`, and to literal receivers, except for `nil`. # # For all receivers, the `instance_of?`, `kind_of?`, `is_a?`, `eql?`, `respond_to?`, # and `equal?` methods are checked by default. # These are customizable with `AllowedMethods` option. # # The `AllowedMethods` option specifies nil-safe methods, # in other words, it is a method that is allowed to skip safe navigation. # Note that the `AllowedMethod` option is not an option that specifies methods # for which to suppress (allow) this cop's check. # # In the example below, the safe navigation operator (`&.`) is unnecessary # because `NilClass` has methods like `respond_to?` and `is_a?`. # # The `InferNonNilReceiver` option specifies whether to look into previous code # paths to infer if the receiver can't be nil. This check is unsafe because the receiver # can be redefined between the safe navigation call and previous regular method call. # It does the inference only in the current scope, e.g. within the same method definition etc. # # The `AdditionalNilMethods` option specifies additional custom methods which are # defined on `NilClass`. When `InferNonNilReceiver` is set, they are used to determine # whether the receiver can be nil. # # @safety # This cop is unsafe, because autocorrection can change the return type of # the expression. An offending expression that previously could return `nil` # will be autocorrected to never return `nil`. # # @example # # bad # CamelCaseConst&.do_something # # # good # CamelCaseConst.do_something # # # bad # foo.to_s&.strip # foo.to_i&.zero? # foo.to_f&.zero? # foo.to_a&.size # foo.to_h&.size # # # good # foo.to_s.strip # foo.to_i.zero? # foo.to_f.zero? # foo.to_a.size # foo.to_h.size # # # bad # do_something if attrs&.respond_to?(:[]) # # # good # do_something if attrs.respond_to?(:[]) # # # bad # while node&.is_a?(BeginNode) # node = node.parent # end # # # good # while node.is_a?(BeginNode) # node = node.parent # end # # # good - without `&.` this will always return `true` # foo&.respond_to?(:to_a) # # # bad - for `nil`s conversion methods return default values for the type # foo&.to_h || {} # foo&.to_h { |k, v| [k, v] } || {} # foo&.to_a || [] # foo&.to_i || 0 # foo&.to_f || 0.0 # foo&.to_s || '' # # # good # foo.to_h # foo.to_h { |k, v| [k, v] } # foo.to_a # foo.to_i # foo.to_f # foo.to_s # # # bad # self&.foo # # # good # self.foo # # @example AllowedMethods: [nil_safe_method] # # bad # do_something if attrs&.nil_safe_method(:[]) # # # good # do_something if attrs.nil_safe_method(:[]) # do_something if attrs&.not_nil_safe_method(:[]) # # @example InferNonNilReceiver: false (default) # # good # foo.bar # foo&.baz # # @example InferNonNilReceiver: true # # bad # foo.bar # foo&.baz # would raise on previous line if `foo` is nil # # # good # foo.bar # foo.baz # # # bad # if foo.condition? # foo&.bar # end # # # good # if foo.condition? # foo.bar # end # # # good (different scopes) # def method1 # foo.bar # end # # def method2 # foo&.bar # end # # @example AdditionalNilMethods: [present?] # # good # foo.present? # foo&.bar # class RedundantSafeNavigation < Base include AllowedMethods extend AutoCorrector MSG = 'Redundant safe navigation detected, use `.` instead.' MSG_LITERAL = 'Redundant safe navigation with default literal detected.' MSG_NON_NIL = 'Redundant safe navigation on non-nil receiver (detected by analyzing ' \ 'previous code/method invocations).' NIL_SPECIFIC_METHODS = (nil.methods - Object.new.methods).to_set.freeze SNAKE_CASE = /\A[[:digit:][:upper:]_]+\z/.freeze GUARANTEED_INSTANCE_METHODS = %i[to_s to_i to_f to_a to_h].freeze # @!method respond_to_nil_specific_method?(node) def_node_matcher :respond_to_nil_specific_method?, <<~PATTERN (csend _ :respond_to? (sym %NIL_SPECIFIC_METHODS)) PATTERN # @!method conversion_with_default?(node) def_node_matcher :conversion_with_default?, <<~PATTERN { (or $(csend _ :to_h) (hash)) (or (block $(csend _ :to_h) ...) (hash)) (or $(csend _ :to_a) (array)) (or $(csend _ :to_i) (int 0)) (or $(csend _ :to_f) (float 0.0)) (or $(csend _ :to_s) (str empty?)) } PATTERN # rubocop:disable Metrics/AbcSize def on_csend(node) range = node.loc.dot if infer_non_nil_receiver? checker = Lint::Utils::NilReceiverChecker.new(node.receiver, additional_nil_methods) if checker.cant_be_nil? add_offense(range, message: MSG_NON_NIL) { |corrector| corrector.replace(range, '.') } return end end unless assume_receiver_instance_exists?(node.receiver) return if !guaranteed_instance?(node.receiver) && !check?(node) return if respond_to_nil_specific_method?(node) end add_offense(range) { |corrector| corrector.replace(range, '.') } end # rubocop:enable Metrics/AbcSize # rubocop:disable Metrics/AbcSize def on_or(node) conversion_with_default?(node) do |send_node| range = send_node.loc.dot.begin.join(node.source_range.end) add_offense(range, message: MSG_LITERAL) do |corrector| corrector.replace(send_node.loc.dot, '.') range_with_default = node.lhs.source_range.end.begin.join(node.source_range.end) corrector.remove(range_with_default) end end end # rubocop:enable Metrics/AbcSize private def assume_receiver_instance_exists?(receiver) return true if receiver.const_type? && !receiver.short_name.match?(SNAKE_CASE) receiver.self_type? || (receiver.literal? && !receiver.nil_type?) end def guaranteed_instance?(node) receiver = if node.any_block_type? node.send_node else node end return false unless receiver.send_type? GUARANTEED_INSTANCE_METHODS.include?(receiver.method_name) end def check?(node) return false unless allowed_method?(node.method_name) parent = node.parent return false unless parent condition?(parent, node) || parent.operator_keyword? || (parent.send_type? && parent.negation_method?) end def condition?(parent, node) (parent.conditional? || parent.post_condition_loop?) && parent.condition == node end def infer_non_nil_receiver? cop_config['InferNonNilReceiver'] end def additional_nil_methods @additional_nil_methods ||= Array(cop_config.fetch('AdditionalNilMethods', []).map(&:to_sym)) 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_expression.rb
lib/rubocop/cop/lint/empty_expression.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for the presence of empty expressions. # # @example # # # bad # # foo = () # if () # bar # end # # # good # # foo = (some_expression) # if (some_expression) # bar # end class EmptyExpression < Base MSG = 'Avoid empty expressions.' def on_begin(node) return unless empty_expression?(node) add_offense(node) end private def empty_expression?(begin_node) begin_node.children.empty? 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/flip_flop.rb
lib/rubocop/cop/lint/flip_flop.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Looks for uses of flip-flop operator # based on the Ruby Style Guide. # # Here is the history of flip-flops in Ruby. # flip-flop operator is deprecated in Ruby 2.6.0 and # the deprecation has been reverted by Ruby 2.7.0 and # backported to Ruby 2.6. # See: https://bugs.ruby-lang.org/issues/5400 # # @example # # bad # (1..20).each do |x| # puts x if (x == 5) .. (x == 10) # end # # # good # (1..20).each do |x| # puts x if (x >= 5) && (x <= 10) # end class FlipFlop < Base MSG = 'Avoid the use of flip-flop operators.' def on_iflipflop(node) add_offense(node) end def on_eflipflop(node) 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/useless_defined.rb
lib/rubocop/cop/lint/useless_defined.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for calls to `defined?` with strings or symbols as the argument. # Such calls will always return `'expression'`, you probably meant to # check for the existence of a constant, method, or variable instead. # # `defined?` is part of the Ruby syntax and doesn't behave like normal methods. # You can safely pass in what you are checking for directly, without encountering # a `NameError`. # # When interpolation is used, oftentimes it is not possible to write the # code with `defined?`. In these cases, switch to one of the more specific methods: # # * `class_variable_defined?` # * `const_defined?` # * `method_defined?` # * `instance_variable_defined?` # * `binding.local_variable_defined?` # # @example # # # bad # defined?('FooBar') # defined?(:FooBar) # defined?(:foo_bar) # defined?('foo_bar') # # # good # defined?(FooBar) # defined?(foo_bar) # # # bad - interpolation # bar = 'Bar' # defined?("Foo::#{bar}::Baz") # # # good # bar = 'Bar' # defined?(Foo) && Foo.const_defined?(bar) && Foo.const_get(bar).const_defined?(:Baz) class UselessDefined < Base MSG = 'Calling `defined?` with a %<type>s argument will always return a truthy value.' TYPES = { str: 'string', dstr: 'string', sym: 'symbol', dsym: 'symbol' }.freeze def on_defined?(node) # NOTE: `defined?` always takes one argument. Anything else is a syntax error. return unless (type = TYPES[node.first_argument.type]) add_offense(node, message: format(MSG, type: 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/redundant_with_object.rb
lib/rubocop/cop/lint/redundant_with_object.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for redundant `with_object`. # # @example # # bad # ary.each_with_object([]) do |v| # v # end # # # good # ary.each do |v| # v # end # # # bad # ary.each.with_object([]) do |v| # v # end # # # good # ary.each do |v| # v # end # class RedundantWithObject < Base include RangeHelp extend AutoCorrector MSG_EACH_WITH_OBJECT = 'Use `each` instead of `each_with_object`.' MSG_WITH_OBJECT = 'Remove redundant `with_object`.' def on_block(node) return unless (send = redundant_with_object?(node)) range = with_object_range(send) add_offense(range, message: message(send)) do |corrector| if send.method?(:each_with_object) corrector.replace(range, 'each') else corrector.remove(range) corrector.remove(send.loc.dot) end end end alias on_numblock on_block alias on_itblock on_block private # @!method redundant_with_object?(node) def_node_matcher :redundant_with_object?, <<~PATTERN { (block $(call _ {:each_with_object :with_object} _) (args (arg _)) ...) (numblock $(call _ {:each_with_object :with_object} _) 1 ...) (itblock $(call _ {:each_with_object :with_object} _) _ ...) } PATTERN def message(node) if node.method?(:each_with_object) MSG_EACH_WITH_OBJECT else MSG_WITH_OBJECT end end def with_object_range(send) range_between(send.loc.selector.begin_pos, send.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/lint/redundant_cop_enable_directive.rb
lib/rubocop/cop/lint/redundant_cop_enable_directive.rb
# frozen_string_literal: true # The Lint/RedundantCopEnableDirective and Lint/RedundantCopDisableDirective # cops need to be disabled so as to be able to provide a (bad) example of an # unneeded enable. # rubocop:disable Lint/RedundantCopEnableDirective # rubocop:disable Lint/RedundantCopDisableDirective module RuboCop module Cop module Lint # Detects instances of rubocop:enable comments that can be # removed. # # When comment enables all cops at once `rubocop:enable all` # that cop checks whether any cop was actually enabled. # # @example # # # bad # foo = 1 # # rubocop:enable Layout/LineLength # # # good # foo = 1 # # # bad # # rubocop:disable Style/StringLiterals # foo = "1" # # rubocop:enable Style/StringLiterals # baz # # rubocop:enable all # # # good # # rubocop:disable Style/StringLiterals # foo = "1" # # rubocop:enable all # baz class RedundantCopEnableDirective < Base include RangeHelp include SurroundingSpace extend AutoCorrector MSG = 'Unnecessary enabling of %<cop>s.' def on_new_investigation return if processed_source.blank? || !processed_source.raw_source.include?('enable') offenses = processed_source.comment_config.extra_enabled_comments offenses.each { |comment, cop_names| register_offense(comment, cop_names) } end private def register_offense(comment, cop_names) directive = DirectiveComment.new(comment) cop_names.each do |name| name = name.split('/').first if department?(directive, name) add_offense( range_of_offense(comment, name), message: format(MSG, cop: all_or_name(name)) ) do |corrector| if directive.match?(cop_names) corrector.remove(range_with_surrounding_space(directive.range, side: :right)) else corrector.remove(range_with_comma(comment, name)) end end end end def range_of_offense(comment, name) start_pos = comment_start(comment) + cop_name_indention(comment, name) range_between(start_pos, start_pos + name.size) end def comment_start(comment) comment.source_range.begin_pos end def cop_name_indention(comment, name) comment.text.index(name) end def range_with_comma(comment, name) source = comment.source begin_pos = cop_name_indention(comment, name) end_pos = begin_pos + name.size begin_pos = reposition(source, begin_pos, -1) end_pos = reposition(source, end_pos, 1) range_to_remove(begin_pos, end_pos, comment) end def range_to_remove(begin_pos, end_pos, comment) start = comment_start(comment) source = comment.source if source[begin_pos - 1] == ',' range_with_comma_before(start, begin_pos, end_pos) elsif source[end_pos] == ',' range_with_comma_after(comment, start, begin_pos, end_pos) else range_between(start, comment.source_range.end_pos) end end def range_with_comma_before(start, begin_pos, end_pos) range_between(start + begin_pos - 1, start + end_pos) end # If the list of cops is comma-separated, but without an empty space after the comma, # we should **not** remove the prepending empty space, thus begin_pos += 1 def range_with_comma_after(comment, start, begin_pos, end_pos) begin_pos += 1 if comment.source[end_pos + 1] != ' ' range_between(start + begin_pos, start + end_pos + 1) end def all_or_name(name) name == 'all' ? 'all cops' : name end def department?(directive, name) directive.in_directive_department?(name) && !directive.overridden_by_department?(name) end end end end end # rubocop:enable Lint/RedundantCopDisableDirective # rubocop:enable Lint/RedundantCopEnableDirective
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/unescaped_bracket_in_regexp.rb
lib/rubocop/cop/lint/unescaped_bracket_in_regexp.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for Regexpes (both literals and via `Regexp.new` / `Regexp.compile`) # that contain unescaped `]` characters. # # It emulates the following Ruby warning: # # [source,ruby] # ---- # $ ruby -e '/abc]123/' # -e:1: warning: regular expression has ']' without escape: /abc]123/ # ---- # # @example # # bad # /abc]123/ # %r{abc]123} # Regexp.new('abc]123') # Regexp.compile('abc]123') # # # good # /abc\]123/ # %r{abc\]123} # Regexp.new('abc\]123') # Regexp.compile('abc\]123') # class UnescapedBracketInRegexp < Base extend AutoCorrector MSG = 'Regular expression has `]` without escape.' RESTRICT_ON_SEND = %i[new compile].freeze # @!method regexp_constructor(node) def_node_search :regexp_constructor, <<~PATTERN (send (const {nil? cbase} :Regexp) {:new :compile} $str ... ) PATTERN def on_regexp(node) RuboCop::Util.silence_warnings do node.parsed_tree&.each_expression do |expr| detect_offenses(node, expr) end end end def on_send(node) # Ignore nodes that contain interpolation return if node.each_descendant(:dstr).any? regexp_constructor(node) do |text| parse_regexp(text.value)&.each_expression do |expr| detect_offenses(text, expr) end end end private def detect_offenses(node, expr) return unless expr.type?(:literal) expr.text.scan(/(?<!\\)\]/) do pos = Regexp.last_match.begin(0) next if pos.zero? # if the unescaped bracket is the first character, Ruby does not warn location = range_at_index(node, expr.ts, pos) add_offense(location) do |corrector| corrector.replace(location, '\]') end end end def range_at_index(node, index, offset) adjustment = index + offset node.loc.begin.end.adjust(begin_pos: adjustment, end_pos: adjustment + 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/ambiguous_assignment.rb
lib/rubocop/cop/lint/ambiguous_assignment.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for mistyped shorthand assignments. # # @example # # bad # x =- y # x =+ y # x =* y # x =! y # # # good # x -= y # or x = -y # x += y # or x = +y # x *= y # or x = *y # x != y # or x = !y # class AmbiguousAssignment < Base include RangeHelp MSG = 'Suspicious assignment detected. Did you mean `%<op>s`?' SIMPLE_ASSIGNMENT_TYPES = %i[lvasgn ivasgn cvasgn gvasgn casgn].freeze MISTAKES = { '=-' => '-=', '=+' => '+=', '=*' => '*=', '=!' => '!=' }.freeze def on_asgn(node) return unless (rhs = rhs(node)) range = range_between(node.loc.operator.end_pos - 1, rhs.source_range.begin_pos + 1) source = range.source return unless MISTAKES.key?(source) add_offense(range, message: format(MSG, op: MISTAKES[source])) end SIMPLE_ASSIGNMENT_TYPES.each { |asgn_type| alias_method :"on_#{asgn_type}", :on_asgn } private def rhs(node) if node.casgn_type? node.children[2] else node.children[1] 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/useless_default_value_argument.rb
lib/rubocop/cop/lint/useless_default_value_argument.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for usage of method `fetch` or `Array.new` with default value argument # and block. In such cases, block will always be used as default value. # # This cop emulates Ruby warning "block supersedes default value argument" which # applies to `Array.new`, `Array#fetch`, `Hash#fetch`, `ENV.fetch` and # `Thread#fetch`. # # A `fetch` call without a receiver is considered a custom method and does not register # an offense. # # @safety # This cop is unsafe because the receiver could have nonstandard implementation # of `fetch`, or be a class other than the one listed above. # # It is also unsafe because default value argument could have side effects: # # [source,ruby] # ---- # def x(a) = puts "side effect" # Array.new(5, x(1)) { 2 } # ---- # # so removing it would change behavior. # # @example # # bad # x.fetch(key, default_value) { block_value } # Array.new(size, default_value) { block_value } # # # good # x.fetch(key) { block_value } # Array.new(size) { block_value } # # # also good - in case default value argument is desired instead # x.fetch(key, default_value) # Array.new(size, default_value) # # # good - keyword arguments aren't registered as offenses # x.fetch(key, keyword: :arg) { block_value } # # @example AllowedReceivers: ['Rails.cache'] # # good # Rails.cache.fetch(name, options) { block } # class UselessDefaultValueArgument < Base include AllowedReceivers extend AutoCorrector MSG = 'Block supersedes default value argument.' RESTRICT_ON_SEND = %i[fetch new].freeze # @!method default_value_argument_and_block(node) def_node_matcher :default_value_argument_and_block, <<~PATTERN (any_block { (call !nil? :fetch $_key $_default_value) (send (const _ :Array) :new $_size $_default_value) } _args _block_body) PATTERN def on_send(node) unless (prev_arg_node, default_value_node = default_value_argument_and_block(node.parent)) return end return if allowed_receiver?(node.receiver) return if hash_without_braces?(default_value_node) add_offense(default_value_node) do |corrector| corrector.remove(prev_arg_node.source_range.end.join(default_value_node.source_range)) end end alias on_csend on_send private def hash_without_braces?(node) node.hash_type? && !node.braces? 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/no_return_in_begin_end_blocks.rb
lib/rubocop/cop/lint/no_return_in_begin_end_blocks.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for the presence of a `return` inside a `begin..end` block # in assignment contexts. # In this situation, the `return` will result in an exit from the current # method, possibly leading to unexpected behavior. # # @example # # # bad # @some_variable ||= begin # return some_value if some_condition_is_met # # do_something # end # # # good # @some_variable ||= begin # if some_condition_is_met # some_value # else # do_something # end # end # # # good # some_variable = if some_condition_is_met # return if another_condition_is_met # # some_value # else # do_something # end # class NoReturnInBeginEndBlocks < Base MSG = 'Do not `return` in `begin..end` blocks in assignment contexts.' def on_lvasgn(node) node.each_node(:kwbegin) do |kwbegin_node| kwbegin_node.each_node(:return) do |return_node| add_offense(return_node) end end end alias on_ivasgn on_lvasgn alias on_cvasgn on_lvasgn alias on_gvasgn on_lvasgn alias on_casgn on_lvasgn alias on_or_asgn on_lvasgn alias on_op_asgn on_lvasgn 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/rescue_type.rb
lib/rubocop/cop/lint/rescue_type.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for arguments to `rescue` that will result in a `TypeError` # if an exception is raised. # # @example # # bad # begin # bar # rescue nil # baz # end # # # bad # def foo # bar # rescue 1, 'a', "#{b}", 0.0, [], {} # baz # end # # # good # begin # bar # rescue # baz # end # # # good # def foo # bar # rescue NameError # baz # end class RescueType < Base extend AutoCorrector MSG = 'Rescuing from `%<invalid_exceptions>s` will raise a ' \ '`TypeError` instead of catching the actual exception.' INVALID_TYPES = %i[array dstr float hash nil int str sym].freeze def on_resbody(node) invalid_exceptions = invalid_exceptions(node.exceptions) return if invalid_exceptions.empty? add_offense( node.loc.keyword.join(node.children.first.source_range), message: format(MSG, invalid_exceptions: invalid_exceptions.map(&:source).join(', ')) ) do |corrector| autocorrect(corrector, node) end end def autocorrect(corrector, node) rescued = node.children.first range = node.loc.keyword.end.join(rescued.source_range.end) corrector.replace(range, correction(*rescued)) end private def correction(*exceptions) correction = valid_exceptions(exceptions).map(&:source).join(', ') correction = " #{correction}" unless correction.empty? correction end def valid_exceptions(exceptions) exceptions - invalid_exceptions(exceptions) end def invalid_exceptions(exceptions) exceptions.select { |exception| INVALID_TYPES.include?(exception.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/useless_constant_scoping.rb
lib/rubocop/cop/lint/useless_constant_scoping.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for useless constant scoping. Private constants must be defined using # `private_constant`. Even if `private` access modifier is used, it is public scope despite # its appearance. # # It does not support autocorrection due to behavior change and multiple ways to fix it. # Or a public constant may be intended. # # @example # # # bad # class Foo # private # PRIVATE_CONST = 42 # end # # # good # class Foo # PRIVATE_CONST = 42 # private_constant :PRIVATE_CONST # end # # # good # class Foo # PUBLIC_CONST = 42 # If private scope is not intended. # end # class UselessConstantScoping < Base MSG = 'Useless `private` access modifier for constant scope.' # @!method private_constants(node) def_node_matcher :private_constants, <<~PATTERN (send nil? :private_constant $...) PATTERN def on_casgn(node) return unless after_private_modifier?(node.left_siblings) return if private_constantize?(node.right_siblings, node.name) add_offense(node) end private def after_private_modifier?(left_siblings) access_modifier_candidates = left_siblings.compact.select do |left_sibling| left_sibling.respond_to?(:send_type?) && left_sibling.send_type? end access_modifier_candidates.any? do |candidate| candidate.command?(:private) && candidate.arguments.none? end end def private_constantize?(right_siblings, const_value) private_constant_arguments = right_siblings.map { |node| private_constants(node) } private_constant_values = private_constant_arguments.flatten.filter_map do |constant| constant.value.to_sym if constant.respond_to?(:value) end private_constant_values.include?(const_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/non_atomic_file_operation.rb
lib/rubocop/cop/lint/non_atomic_file_operation.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for non-atomic file operation. # And then replace it with a nearly equivalent and atomic method. # # These can cause problems that are difficult to reproduce, # especially in cases of frequent file operations in parallel, # such as test runs with parallel_rspec. # # For examples: creating a directory if there is none, has the following problems # # An exception occurs when the directory didn't exist at the time of `exist?`, # but someone else created it before `mkdir` was executed. # # Subsequent processes are executed without the directory that should be there # when the directory existed at the time of `exist?`, # but someone else deleted it shortly afterwards. # # @safety # This cop is unsafe, because autocorrection change to atomic processing. # The atomic processing of the replacement destination is not guaranteed # to be strictly equivalent to that before the replacement. # # @example # # bad - race condition with another process may result in an error in `mkdir` # unless Dir.exist?(path) # FileUtils.mkdir(path) # end # # # good - atomic and idempotent creation # FileUtils.mkdir_p(path) # # # bad - race condition with another process may result in an error in `remove` # if File.exist?(path) # FileUtils.remove(path) # end # # # good - atomic and idempotent removal # FileUtils.rm_f(path) # class NonAtomicFileOperation < Base extend AutoCorrector MSG_REMOVE_FILE_EXIST_CHECK = 'Remove unnecessary existence check ' \ '`%<receiver>s.%<method_name>s`.' MSG_CHANGE_FORCE_METHOD = 'Use atomic file operation method `FileUtils.%<method_name>s`.' MAKE_FORCE_METHODS = %i[makedirs mkdir_p mkpath].freeze MAKE_METHODS = %i[mkdir].freeze REMOVE_FORCE_METHODS = %i[rm_f rm_rf].freeze REMOVE_METHODS = %i[remove delete unlink remove_file rm rmdir safe_unlink].freeze RECURSIVE_REMOVE_METHODS = %i[remove_dir remove_entry remove_entry_secure].freeze RESTRICT_ON_SEND = ( MAKE_METHODS + MAKE_FORCE_METHODS + REMOVE_METHODS + RECURSIVE_REMOVE_METHODS + REMOVE_FORCE_METHODS ).freeze # @!method send_exist_node(node) def_node_search :send_exist_node, <<~PATTERN $(send (const {cbase nil?} {:FileTest :File :Dir :Shell}) {:exist? :exists?} ...) PATTERN # @!method receiver_and_method_name(node) def_node_matcher :receiver_and_method_name, <<~PATTERN (send (const {cbase nil?} $_) $_ ...) PATTERN # @!method force?(node) def_node_search :force?, <<~PATTERN (pair (sym :force) (:true)) PATTERN # @!method explicit_not_force?(node) def_node_search :explicit_not_force?, <<~PATTERN (pair (sym :force) (:false)) PATTERN def on_send(node) return unless node.receiver&.const_type? return unless if_node_child?(node) return if explicit_not_force?(node) return unless (exist_node = send_exist_node(node.parent).first) return unless exist_node.first_argument == node.first_argument register_offense(node, exist_node) end private def if_node_child?(node) return false unless (parent = node.parent) parent.if_type? && !allowable_use_with_if?(parent) end def allowable_use_with_if?(if_node) if_node.condition.operator_keyword? || if_node.else_branch end def register_offense(node, exist_node) add_offense(node, message: message_change_force_method(node)) unless force_method?(node) parent = node.parent range = parent.loc.keyword.begin.join(parent.condition.source_range.end) add_offense(range, message: message_remove_file_exist_check(exist_node)) do |corrector| autocorrect(corrector, node, range) unless parent.elsif? end end def message_change_force_method(node) format(MSG_CHANGE_FORCE_METHOD, method_name: replacement_method(node)) end def message_remove_file_exist_check(node) receiver, method_name = receiver_and_method_name(node) format(MSG_REMOVE_FILE_EXIST_CHECK, receiver: receiver, method_name: method_name) end def autocorrect(corrector, node, range) corrector.remove(range) autocorrect_replace_method(corrector, node) if node.parent.modifier_form? corrector.remove(node.source_range.end.join(node.parent.loc.keyword.begin)) else corrector.remove(node.parent.loc.end) end end def autocorrect_replace_method(corrector, node) return if force_method?(node) corrector.replace(node.child_nodes.first.loc.name, 'FileUtils') corrector.replace(node.loc.selector, replacement_method(node)) corrector.insert_before(node.last_argument, 'mode: ') if require_mode_keyword?(node) end def replacement_method(node) if MAKE_METHODS.include?(node.method_name) 'mkdir_p' elsif REMOVE_METHODS.include?(node.method_name) 'rm_f' elsif RECURSIVE_REMOVE_METHODS.include?(node.method_name) 'rm_rf' else node.method_name end end def force_method?(node) force_method_name?(node) || force_option?(node) end def require_mode_keyword?(node) return false unless node.receiver.const_name == 'Dir' replacement_method(node) == 'mkdir_p' && node.arguments.length == 2 end def force_option?(node) node.arguments.any? { |arg| force?(arg) } end def force_method_name?(node) (MAKE_FORCE_METHODS + REMOVE_FORCE_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/empty_when.rb
lib/rubocop/cop/lint/empty_when.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for the presence of `when` branches without a body. # # @example # # # bad # case foo # when bar # do_something # when baz # end # # # good # case condition # when foo # do_something # when bar # nil # end # # @example AllowComments: true (default) # # # good # case condition # when foo # do_something # when bar # # noop # end # # @example AllowComments: false # # # bad # case condition # when foo # do_something # when bar # # do nothing # end # class EmptyWhen < Base include CommentsHelp MSG = 'Avoid `when` branches without a body.' def on_case(node) node.when_branches.each do |when_node| next if when_node.body next if cop_config['AllowComments'] && contains_comments?(when_node) add_offense(when_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/lint/loop.rb
lib/rubocop/cop/lint/loop.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for uses of `begin...end while/until something`. # # @safety # The cop is unsafe because behavior can change in some cases, including # if a local variable inside the loop body is accessed outside of it, or if the # loop body raises a `StopIteration` exception (which `Kernel#loop` rescues). # # @example # # # bad # # # using while # begin # do_something # end while some_condition # # # good # # # while replacement # loop do # do_something # break unless some_condition # end # # # bad # # # using until # begin # do_something # end until some_condition # # # good # # # until replacement # loop do # do_something # break if some_condition # end class Loop < Base extend AutoCorrector MSG = 'Use `Kernel#loop` with `break` rather than `begin/end/until`(or `while`).' def on_while_post(node) register_offense(node) end def on_until_post(node) register_offense(node) end private def register_offense(node) body = node.body add_offense(node.loc.keyword) do |corrector| corrector.replace(body.loc.begin, 'loop do') corrector.remove(keyword_and_condition_range(node)) corrector.insert_before(body.loc.end, build_break_line(node)) end end def keyword_and_condition_range(node) node.body.loc.end.end.join(node.source_range.end) end def build_break_line(node) conditional_keyword = node.while_post_type? ? 'unless' : 'if' "break #{conditional_keyword} #{node.condition.source}\n#{indent(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/float_comparison.rb
lib/rubocop/cop/lint/float_comparison.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for the presence of precise comparison of floating point numbers. # # Floating point values are inherently inaccurate, and comparing them for exact equality # is almost never the desired semantics. Comparison via the `==/!=` operators checks # floating-point value representation to be exactly the same, which is very unlikely # if you perform any arithmetic operations involving precision loss. # # @example # # bad # x == 0.1 # x != 0.1 # # # bad # case value # when 1.0 # foo # when 2.0 # bar # end # # # good - using BigDecimal # x.to_d == 0.1.to_d # # # good - comparing against zero # x == 0.0 # x != 0.0 # # # good # (x - 0.1).abs < Float::EPSILON # # # good # tolerance = 0.0001 # (x - 0.1).abs < tolerance # # # good - comparing against nil # Float(x, exception: false) == nil # # # good - using epsilon comparison in case expression # case # when (value - 1.0).abs < Float::EPSILON # foo # when (value - 2.0).abs < Float::EPSILON # bar # end # # # Or some other epsilon based type of comparison: # # https://www.embeddeduse.com/2019/08/26/qt-compare-two-floats/ # class FloatComparison < Base MSG_EQUALITY = 'Avoid equality comparisons of floats as they are unreliable.' MSG_INEQUALITY = 'Avoid inequality comparisons of floats as they are unreliable.' MSG_CASE = 'Avoid float literal comparisons in case statements as they are unreliable.' EQUALITY_METHODS = %i[== != eql? equal?].freeze FLOAT_RETURNING_METHODS = %i[to_f Float fdiv].freeze FLOAT_INSTANCE_METHODS = %i[@- abs magnitude modulo next_float prev_float quo].to_set.freeze RESTRICT_ON_SEND = EQUALITY_METHODS def on_send(node) return unless node.arguments.one? lhs = node.receiver rhs = node.first_argument return if literal_safe?(lhs) || literal_safe?(rhs) message = node.method?(:!=) ? MSG_INEQUALITY : MSG_EQUALITY add_offense(node, message: message) if float?(lhs) || float?(rhs) end alias on_csend on_send def on_case(node) node.when_branches.each do |when_branch| when_branch.each_condition do |condition| next if !float?(condition) || literal_safe?(condition) add_offense(condition, message: MSG_CASE) end end end private def float?(node) return false unless node case node.type when :float true when :send float_send?(node) when :begin float?(node.children.first) else false end end def literal_safe?(node) return false unless node (node.numeric_type? && node.value.zero?) || node.nil_type? end def float_send?(node) if node.arithmetic_operation? float?(node.receiver) || float?(node.first_argument) elsif FLOAT_RETURNING_METHODS.include?(node.method_name) true elsif node.receiver&.float_type? FLOAT_INSTANCE_METHODS.include?(node.method_name) || numeric_returning_method?(node) end end def numeric_returning_method?(node) return false unless node.receiver case node.method_name when :angle, :arg, :phase Float(node.receiver.source).negative? when :ceil, :floor, :round, :truncate precision = node.first_argument precision&.int_type? && Integer(precision.source).positive? 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_match_pattern.rb
lib/rubocop/cop/lint/duplicate_match_pattern.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks that there are no repeated patterns used in `in` keywords. # # @example # # # bad # case x # in 'first' # do_something # in 'first' # do_something_else # end # # # good # case x # in 'first' # do_something # in 'second' # do_something_else # end # # # bad - repeated alternate patterns with the same conditions don't depend on the order # case x # in 0 | 1 # first_method # in 1 | 0 # second_method # end # # # good # case x # in 0 | 1 # first_method # in 2 | 3 # second_method # end # # # bad - repeated hash patterns with the same conditions don't depend on the order # case x # in foo: a, bar: b # first_method # in bar: b, foo: a # second_method # end # # # good # case x # in foo: a, bar: b # first_method # in bar: b, baz: c # second_method # end # # # bad - repeated array patterns with elements in the same order # case x # in [foo, bar] # first_method # in [foo, bar] # second_method # end # # # good # case x # in [foo, bar] # first_method # in [bar, foo] # second_method # end # # # bad - repeated the same patterns and guard conditions # case x # in foo if bar # first_method # in foo if bar # second_method # end # # # good # case x # in foo if bar # first_method # in foo if baz # second_method # end # class DuplicateMatchPattern < Base extend TargetRubyVersion MSG = 'Duplicate `in` pattern detected.' minimum_target_ruby_version 2.7 def on_case_match(case_node) case_node.in_pattern_branches.each_with_object(Set.new) do |in_pattern_node, previous| pattern = in_pattern_node.pattern next if previous.add?(pattern_identity(pattern)) add_offense(pattern) end end private def pattern_identity(pattern) pattern_source = if pattern.type?(:hash_pattern, :match_alt) pattern.children.map(&:source).sort.to_s else pattern.source end return pattern_source unless (guard = pattern.parent.children[1]) pattern_source + guard.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/constant_overwritten_in_rescue.rb
lib/rubocop/cop/lint/constant_overwritten_in_rescue.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for overwriting an exception with an exception result by use ``rescue =>``. # # You intended to write as `rescue StandardError`. # However, you have written `rescue => StandardError`. # In that case, the result of `rescue` will overwrite `StandardError`. # # @example # # # bad # begin # something # rescue => StandardError # end # # # good # begin # something # rescue StandardError # end # class ConstantOverwrittenInRescue < Base extend AutoCorrector include RangeHelp MSG = '`%<constant>s` is overwritten by `rescue =>`.' # @!method overwritten_constant(node) def_node_matcher :overwritten_constant, <<~PATTERN (resbody nil? $(casgn _ _) nil?) PATTERN def self.autocorrect_incompatible_with [Naming::RescuedExceptionsVariableName, Style::RescueStandardError] end def on_resbody(node) return unless (constant = overwritten_constant(node)) message = format(MSG, constant: constant.source) add_offense(node.loc.assoc, message: message) do |corrector| corrector.remove(range_between(node.loc.keyword.end_pos, node.loc.assoc.end_pos)) 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/safe_navigation_chain.rb
lib/rubocop/cop/lint/safe_navigation_chain.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # The safe navigation operator returns nil if the receiver is # nil. If you chain an ordinary method call after a safe # navigation operator, it raises NoMethodError. We should use a # safe navigation operator after a safe navigation operator. # This cop checks for the problem outlined above. # # @example # # # bad # x&.foo.bar # x&.foo + bar # x&.foo[bar] # # # good # x&.foo&.bar # x&.foo || bar class SafeNavigationChain < Base include NilMethods extend AutoCorrector extend TargetRubyVersion minimum_target_ruby_version 2.3 MSG = 'Do not chain ordinary method call after safe navigation operator.' PLUS_MINUS_METHODS = %i[+@ -@].freeze # @!method bad_method?(node) def_node_matcher :bad_method?, <<~PATTERN { (send $(csend ...) $_ ...) (send $(any_block (csend ...) ...) $_ ...) } PATTERN def on_send(node) return unless require_safe_navigation?(node) bad_method?(node) do |safe_nav, method| return if nil_methods.include?(method) || PLUS_MINUS_METHODS.include?(node.method_name) begin_range = node.loc.dot || safe_nav.source_range.end location = begin_range.join(node.source_range.end) add_offense(location) do |corrector| autocorrect(corrector, offense_range: location, send_node: node) end end end private def require_safe_navigation?(node) parent = node.parent return true unless parent&.and_type? parent.rhs != node || parent.lhs.receiver != parent.rhs.receiver end # @param [Parser::Source::Range] offense_range # @param [RuboCop::AST::SendNode] send_node # @return [String] def add_safe_navigation_operator(offense_range:, send_node:) source = if brackets?(send_node) format( '%<method_name>s(%<arguments>s)%<method_chain>s', arguments: send_node.arguments.map(&:source).join(', '), method_name: send_node.method_name, method_chain: send_node.source_range.end.join(send_node.source_range.end).source ) else offense_range.source end source.prepend('.') unless source.start_with?('.') source.prepend('&') end # @param [RuboCop::Cop::Corrector] corrector # @param [Parser::Source::Range] offense_range # @param [RuboCop::AST::SendNode] send_node def autocorrect(corrector, offense_range:, send_node:) corrector.replace( offense_range, add_safe_navigation_operator(offense_range: offense_range, send_node: send_node) ) corrector.wrap(send_node, '(', ')') if require_parentheses?(send_node) end def brackets?(send_node) send_node.method?(:[]) || send_node.method?(:[]=) end def require_parentheses?(send_node) return true if operator_inside_collection_literal?(send_node) return false unless send_node.comparison_method? return false unless (node = send_node.parent) (node.respond_to?(:logical_operator?) && node.logical_operator?) || (node.respond_to?(:comparison_method?) && node.comparison_method?) end def operator_inside_collection_literal?(send_node) # If an operator call (without a dot) is inside an array or a hash, it needs # to be parenthesized when converted to safe navigation. send_node.parent&.type?(:array, :pair) && !send_node.loc.dot 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_require_statement.rb
lib/rubocop/cop/lint/redundant_require_statement.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for unnecessary `require` statement. # # The following features are unnecessary `require` statement because # they are already loaded. e.g. Ruby 2.2: # # ruby -ve 'p $LOADED_FEATURES.reject { |feature| %r|/| =~ feature }' # ruby 2.2.8p477 (2017-09-14 revision 59906) [x86_64-darwin13] # ["enumerator.so", "rational.so", "complex.so", "thread.rb"] # # Below are the features that each `TargetRubyVersion` targets. # # * 2.0+ ... `enumerator` # * 2.1+ ... `thread` # * 2.2+ ... Add `rational` and `complex` above # * 2.7+ ... Add `ruby2_keywords` above # * 3.1+ ... Add `fiber` above # * 3.2+ ... Add `set` above # * 4.0+ ... Add `pathname` above # # This cop target those features. # # @example # # bad # require 'unloaded_feature' # require 'thread' # # # good # require 'unloaded_feature' class RedundantRequireStatement < Base include RangeHelp extend AutoCorrector MSG = 'Remove unnecessary `require` statement.' RESTRICT_ON_SEND = %i[require].freeze RUBY_22_LOADED_FEATURES = %w[rational complex].freeze # @!method redundant_require_statement?(node) def_node_matcher :redundant_require_statement?, <<~PATTERN (send nil? :require (str #redundant_feature?)) PATTERN def on_send(node) return unless redundant_require_statement?(node) add_offense(node) do |corrector| if node.parent.respond_to?(:modifier_form?) && node.parent.modifier_form? corrector.insert_after(node.parent, "\nend") range = range_with_surrounding_space(node.source_range, side: :right) else range = range_by_whole_lines(node.source_range, include_final_newline: true) end corrector.remove(range) end end private # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity def redundant_feature?(feature_name) feature_name == 'enumerator' || (target_ruby_version >= 2.1 && feature_name == 'thread') || (target_ruby_version >= 2.2 && RUBY_22_LOADED_FEATURES.include?(feature_name)) || (target_ruby_version >= 2.7 && feature_name == 'ruby2_keywords') || (target_ruby_version >= 3.1 && feature_name == 'fiber') || (target_ruby_version >= 3.2 && feature_name == 'set') || (target_ruby_version >= 4.0 && feature_name == 'pathname') end # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity 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/unexpected_block_arity.rb
lib/rubocop/cop/lint/unexpected_block_arity.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for a block that is known to need more positional # block arguments than are given (by default this is configured for # `Enumerable` methods needing 2 arguments). Optional arguments are allowed, # although they don't generally make sense as the default value will # be used. Blocks that have no receiver, or take splatted arguments # (ie. `*args`) are always accepted. # # Keyword arguments (including `**kwargs`) do not get counted towards # this, as they are not used by the methods in question. # # Method names and their expected arity can be configured like this: # # [source,yaml] # ---- # Methods: # inject: 2 # reduce: 2 # ---- # # @safety # This cop matches for method names only and hence cannot tell apart # methods with same name in different classes, which may lead to a # false positive. # # @example # # bad # values.reduce {} # values.min { |a| a } # values.sort { |a; b| a + b } # # # good # values.reduce { |memo, obj| memo << obj } # values.min { |a, b| a <=> b } # values.sort { |*x| x[0] <=> x[1] } # class UnexpectedBlockArity < Base MSG = '`%<method>s` expects at least %<expected>i positional arguments, got %<actual>i.' def on_block(node) return if acceptable?(node) expected = expected_arity(node.method_name) actual = arg_count(node) return if actual >= expected message = format(MSG, method: node.method_name, expected: expected, actual: actual) add_offense(node, message: message) end alias on_numblock on_block alias on_itblock on_block private def methods cop_config.fetch('Methods', []) end def acceptable?(node) !(included_method?(node.method_name) && node.receiver) end def included_method?(name) methods.key?(name.to_s) end def expected_arity(method) cop_config['Methods'][method.to_s] end def arg_count(node) return node.children[1] if node.numblock_type? # the maximum numbered param for the block return 1 if node.itblock_type? # `it` block parameter is always one # Only `arg`, `optarg` and `mlhs` (destructuring) count as arguments that # can be used. Keyword arguments are not used for these methods so are # ignored. node.arguments.count do |arg| return Float::INFINITY if arg.restarg_type? arg.type?(:arg, :optarg, :mlhs) 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/array_literal_in_regexp.rb
lib/rubocop/cop/lint/array_literal_in_regexp.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for an array literal interpolated inside a regexp. # # When interpolating an array literal, it is converted to a string. This means # that when inside a regexp, it acts as a character class but with additional # quotes, spaces and commas that are likely not intended. For example, # `/#{%w[a b c]}/` parses as `/["a", "b", "c"]/` (or `/["a, bc]/` without # repeated characters). # # The cop can autocorrect to a character class (if all items in the array are a # single character) or alternation (if the array contains longer items). # # NOTE: This only considers interpolated arrays that contain only strings, symbols, # integers, and floats. Any other type is not easily convertible to a character class # or regexp alternation. # # @safety # Autocorrection is unsafe because it will change the regexp pattern, by # removing the additional quotes, spaces and commas from the character class. # # @example # # bad # /#{%w[a b c]}/ # # # good # /[abc]/ # # # bad # /#{%w[foo bar baz]}/ # # # good # /(?:foo|bar|baz)/ # # # bad - construct a regexp rather than interpolate an array of identifiers # /#{[foo, bar]}/ # class ArrayLiteralInRegexp < Base include Interpolation extend AutoCorrector LITERAL_TYPES = %i[str sym int float true false nil].freeze private_constant :LITERAL_TYPES MSG_CHARACTER_CLASS = 'Use a character class instead of interpolating an array in a regexp.' MSG_ALTERNATION = 'Use alternation instead of interpolating an array in a regexp.' MSG_UNKNOWN = 'Use alternation or a character class instead of interpolating an array ' \ 'in a regexp.' def on_interpolation(begin_node) return unless (final_node = begin_node.children.last) return unless final_node.array_type? return unless begin_node.parent.regexp_type? if array_of_literal_values?(final_node) register_array_of_literal_values(begin_node, final_node) else register_array_of_nonliteral_values(begin_node) end end private def array_of_literal_values?(node) node.each_value.all? { |value| value.type?(*LITERAL_TYPES) } end def register_array_of_literal_values(begin_node, node) array_values = array_values(node) if character_class?(array_values) message = MSG_CHARACTER_CLASS replacement = character_class_for(array_values) else message = MSG_ALTERNATION replacement = alternation_for(array_values) end add_offense(begin_node, message: message) do |corrector| corrector.replace(begin_node, replacement) end end def register_array_of_nonliteral_values(node) # Add offense but do not correct if the array contains any nonliteral values. add_offense(node, message: MSG_UNKNOWN) end def array_values(node) node.each_value.map do |value| value.respond_to?(:value) ? value.value : value.source end end def character_class?(values) values.all? { |v| v.to_s.length == 1 } end def character_class_for(values) "[#{escape_values(values).join}]" end def alternation_for(values) "(?:#{escape_values(values).join('|')})" end def escape_values(values) # This may add extraneous escape characters, but they can be cleaned up # by `Style/RedundantRegexpEscape`. values.map { |value| Regexp.escape(value.to_s) } 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/struct_new_override.rb
lib/rubocop/cop/lint/struct_new_override.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks unexpected overrides of the `Struct` built-in methods # via `Struct.new`. # # @example # # bad # Bad = Struct.new(:members, :clone, :count) # b = Bad.new([], true, 1) # b.members #=> [] (overriding `Struct#members`) # b.clone #=> true (overriding `Object#clone`) # b.count #=> 1 (overriding `Enumerable#count`) # # # good # Good = Struct.new(:id, :name) # g = Good.new(1, "foo") # g.members #=> [:id, :name] # g.clone #=> #<struct Good id=1, name="foo"> # g.count #=> 2 # class StructNewOverride < Base MSG = '`%<member_name>s` member overrides `Struct#%<method_name>s` ' \ 'and it may be unexpected.' RESTRICT_ON_SEND = %i[new].freeze STRUCT_METHOD_NAMES = Struct.instance_methods STRUCT_MEMBER_NAME_TYPES = %i[sym str].freeze # @!method struct_new(node) def_node_matcher :struct_new, <<~PATTERN (send (const {nil? cbase} :Struct) :new ...) PATTERN def on_send(node) return unless struct_new(node) node.arguments.each_with_index do |arg, index| # Ignore if the first argument is a class name next if index.zero? && arg.str_type? # Ignore if the argument is not a member name next unless STRUCT_MEMBER_NAME_TYPES.include?(arg.type) member_name = arg.value next unless STRUCT_METHOD_NAMES.include?(member_name.to_sym) message = format(MSG, member_name: member_name.inspect, method_name: member_name.to_s) add_offense(arg, 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/binary_operator_with_identical_operands.rb
lib/rubocop/cop/lint/binary_operator_with_identical_operands.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for places where binary operator has identical operands. # # It covers comparison operators: `==`, `===`, `=~`, `>`, `>=`, `<`, ``<=``; # bitwise operators: `|`, `^`, `&`; # boolean operators: `&&`, `||` # and "spaceship" operator - ``<=>``. # # Simple arithmetic operations are allowed by this cop: `+`, `*`, `**`, `<<` and `>>`. # Although these can be rewritten in a different way, it should not be necessary to # do so. Operations such as `-` or `/` where the result will always be the same # (`x - x` will always be 0; `x / x` will always be 1) are offenses, but these # are covered by `Lint/NumericOperationWithConstantResult` instead. # # @safety # This cop is unsafe as it does not consider side effects when calling methods # and thus can generate false positives, for example: # # [source,ruby] # ---- # if wr.take_char == '\0' && wr.take_char == '\0' # # ... # end # ---- # # @example # # bad # x.top >= x.top # # if a.x != 0 && a.x != 0 # do_something # end # # def child? # left_child || left_child # end # # # good # x + x # 1 << 1 # class BinaryOperatorWithIdenticalOperands < Base MSG = 'Binary operator `%<op>s` has identical operands.' RESTRICT_ON_SEND = %i[== != === <=> =~ && || > >= < <= | ^].freeze def on_send(node) return unless node.binary_operation? return unless node.receiver == node.first_argument add_offense(node, message: format(MSG, op: node.method_name)) end def on_and(node) return unless node.lhs == node.rhs add_offense(node, message: format(MSG, op: node.operator)) end alias on_or on_and 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_or.rb
lib/rubocop/cop/lint/useless_or.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for useless OR (`||` and `or`) expressions. # # Some methods always return a truthy value, even when called # on `nil` (e.g. `nil.to_i` evaluates to `0`). Therefore, OR expressions # appended after these methods will never evaluate. # # @safety # As shown in the examples below, there are generally two possible ways to correct the # offense, but this cop’s autocorrection always chooses the option that preserves the # current behavior. While this does not change how the code behaves, that option is not # necessarily the appropriate fix in every situation. For this reason, the autocorrection # provided by this cop is considered unsafe. # # @example # # # bad # x.to_a || fallback # x.to_c || fallback # x.to_d || fallback # x.to_i || fallback # x.to_f || fallback # x.to_h || fallback # x.to_r || fallback # x.to_s || fallback # x.to_sym || fallback # x.intern || fallback # x.inspect || fallback # x.hash || fallback # x.object_id || fallback # x.__id__ || fallback # # x.to_s or fallback # # # good - if fallback is same as return value of method called on nil # x.to_a # nil.to_a returns [] # x.to_c # nil.to_c returns (0+0i) # x.to_d # nil.to_d returns 0.0 # x.to_i # nil.to_i returns 0 # x.to_f # nil.to_f returns 0.0 # x.to_h # nil.to_h returns {} # x.to_r # nil.to_r returns (0/1) # x.to_s # nil.to_s returns '' # x.to_sym # nil.to_sym raises an error # x.intern # nil.intern raises an error # x.inspect # nil.inspect returns "nil" # x.hash # nil.hash returns an Integer # x.object_id # nil.object_id returns an Integer # x.__id__ # nil.object_id returns an Integer # # # good - if the intention is not to call the method on nil # x&.to_a || fallback # x&.to_c || fallback # x&.to_d || fallback # x&.to_i || fallback # x&.to_f || fallback # x&.to_h || fallback # x&.to_r || fallback # x&.to_s || fallback # x&.to_sym || fallback # x&.intern || fallback # x&.inspect || fallback # x&.hash || fallback # x&.object_id || fallback # x&.__id__ || fallback # # x&.to_s or fallback # class UselessOr < Base extend AutoCorrector MSG = '`%<rhs>s` will never evaluate because `%<lhs>s` always returns a truthy value.' TRUTHY_RETURN_VALUE_METHODS = Set[:to_a, :to_c, :to_d, :to_i, :to_f, :to_h, :to_r, :to_s, :to_sym, :intern, :inspect, :hash, :object_id, :__id__].freeze # @!method truthy_return_value_method?(node) def_node_matcher :truthy_return_value_method?, <<~PATTERN (send _ %TRUTHY_RETURN_VALUE_METHODS) PATTERN def on_or(node) if truthy_return_value_method?(node.lhs) report_offense(node, node.lhs) elsif truthy_return_value_method?(node.rhs) parent = node.parent parent = parent.parent if parent&.begin_type? report_offense(parent, node.rhs) if parent&.or_type? end end private def report_offense(or_node, truthy_node) add_offense( or_node.loc.operator.join(or_node.rhs.source_range), message: format(MSG, lhs: truthy_node.source, rhs: or_node.rhs.source) ) do |corrector| corrector.replace(or_node, or_node.lhs.source) 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/constant_reassignment.rb
lib/rubocop/cop/lint/constant_reassignment.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for constant reassignments. # # Emulates Ruby's runtime warning "already initialized constant X" # when a constant is reassigned in the same file and namespace using the # `NAME = value` syntax. # # The cop cannot catch all offenses, like, for example, when a constant # is reassigned in another file, or when using metaprogramming (`Module#const_set`). # # The cop only takes into account constants assigned in a "simple" way: directly # inside class/module definition, or within another constant. Other type of assignments # (e.g., inside a conditional) are disregarded. # # The cop also tracks constant removal using `Module#remove_const` with symbol # or string argument. # # @example # # bad # X = :foo # X = :bar # # # bad # class A # X = :foo # X = :bar # end # # # bad # module A # X = :foo # X = :bar # end # # # good - keep only one assignment # X = :bar # # class A # X = :bar # end # # module A # X = :bar # end # # # good - use OR assignment # X = :foo # X ||= :bar # # # good - use conditional assignment # X = :foo # X = :bar unless defined?(X) # # # good - remove the assigned constant first # class A # X = :foo # remove_const :X # X = :bar # end # class ConstantReassignment < Base MSG = 'Constant `%<constant>s` is already assigned in this namespace.' RESTRICT_ON_SEND = %i[remove_const].freeze # @!method remove_constant(node) def_node_matcher :remove_constant, <<~PATTERN (send _ :remove_const ({sym str} $_)) PATTERN def on_casgn(node) return unless fixed_constant_path?(node) return unless simple_assignment?(node) return if constant_names.add?(fully_qualified_constant_name(node)) add_offense(node, message: format(MSG, constant: node.name)) end def on_send(node) constant = remove_constant(node) return unless constant namespaces = ancestor_namespaces(node) return if namespaces.none? constant_names.delete(fully_qualified_name_for(namespaces, constant)) end private def fixed_constant_path?(node) node.each_path.all? { |path| path.type?(:cbase, :const, :self) } end def simple_assignment?(node) node.ancestors.all? do |ancestor| return true if ancestor.type?(:module, :class) ancestor.begin_type? || ancestor.literal? || ancestor.casgn_type? || freeze_method?(ancestor) end end def freeze_method?(node) node.send_type? && node.method?(:freeze) end def fully_qualified_constant_name(node) if node.absolute? namespace = node.namespace.const_type? ? node.namespace.source : nil "#{namespace}::#{node.name}" else constant_namespaces = ancestor_namespaces(node) + constant_namespaces(node) fully_qualified_name_for(constant_namespaces, node.name) end end def fully_qualified_name_for(namespaces, constant) ['', *namespaces, constant].join('::') end def constant_namespaces(node) node.each_path.select(&:const_type?).map(&:short_name) end def ancestor_namespaces(node) node .each_ancestor(:class, :module) .map { |ancestor| ancestor.identifier.short_name } .reverse end def constant_names @constant_names ||= Set.new 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/boolean_symbol.rb
lib/rubocop/cop/lint/boolean_symbol.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for `:true` and `:false` symbols. # In most cases it would be a typo. # # @safety # Autocorrection is unsafe for this cop because code relying # on `:true` or `:false` symbols will break when those are # changed to actual booleans. # # @example # # # bad # :true # # # good # true # # # bad # :false # # # good # false class BooleanSymbol < Base extend AutoCorrector MSG = 'Symbol with a boolean name - you probably meant to use `%<boolean>s`.' # @!method boolean_symbol?(node) def_node_matcher :boolean_symbol?, '(sym {:true :false})' def on_sym(node) return unless boolean_symbol?(node) parent = node.parent return if parent&.array_type? && parent.percent_literal?(:symbol) add_offense(node, message: format(MSG, boolean: node.value)) do |corrector| autocorrect(corrector, node) end end private def autocorrect(corrector, node) boolean_literal = node.source.delete(':') parent = node.parent if parent&.pair_type? && parent.colon? && node.equal?(parent.children[0]) corrector.remove(parent.loc.operator) boolean_literal = "#{node.source} =>" end corrector.replace(node, boolean_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/incompatible_io_select_with_fiber_scheduler.rb
lib/rubocop/cop/lint/incompatible_io_select_with_fiber_scheduler.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for `IO.select` that is incompatible with Fiber Scheduler since Ruby 3.0. # # When an array of IO objects waiting for an exception (the third argument of `IO.select`) # is used as an argument, there is no alternative API, so offenses are not registered. # # NOTE: When the method is successful the return value of `IO.select` is `[[IO]]`, # and the return value of `io.wait_readable` and `io.wait_writable` are `self`. # They are not autocorrected when assigning a return value because these types are different. # It's up to user how to handle the return value. # # @safety # This cop's autocorrection is unsafe because `NoMethodError` occurs # if `require 'io/wait'` is not called. # # @example # # # bad # IO.select([io], [], [], timeout) # # # good # io.wait_readable(timeout) # # # bad # IO.select([], [io], [], timeout) # # # good # io.wait_writable(timeout) # class IncompatibleIoSelectWithFiberScheduler < Base extend AutoCorrector MSG = 'Use `%<preferred>s` instead of `%<current>s`.' RESTRICT_ON_SEND = %i[select].freeze # @!method io_select(node) def_node_matcher :io_select, <<~PATTERN (send (const {nil? cbase} :IO) :select $...) PATTERN def on_send(node) read, write, excepts, timeout = *io_select(node) return if excepts && !excepts.children.empty? return unless scheduler_compatible?(read, write) || scheduler_compatible?(write, read) preferred = preferred_method(read, write, timeout) message = format(MSG, preferred: preferred, current: node.source) add_offense(node, message: message) do |corrector| next if node.parent&.assignment? corrector.replace(node, preferred) end end private def scheduler_compatible?(io1, io2) return false unless io1&.array_type? && io1.values.size == 1 io2&.array_type? ? io2.values.empty? : (io2.nil? || io2.nil_type?) end def preferred_method(read, write, timeout) timeout_argument = timeout.nil? ? '' : "(#{timeout.source})" if read.array_type? && read.values[0] "#{read.values[0].source}.wait_readable#{timeout_argument}" else "#{write.values[0].source}.wait_writable#{timeout_argument}" 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/suppressed_exception.rb
lib/rubocop/cop/lint/suppressed_exception.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for `rescue` blocks with no body. # # @example # # # bad # def some_method # do_something # rescue # end # # # bad # begin # do_something # rescue # end # # # good # def some_method # do_something # rescue # handle_exception # end # # # good # begin # do_something # rescue # handle_exception # end # # @example AllowComments: true (default) # # # good # def some_method # do_something # rescue # # do nothing # end # # # good # begin # do_something # rescue # # do nothing # end # # @example AllowComments: false # # # bad # def some_method # do_something # rescue # # do nothing # end # # # bad # begin # do_something # rescue # # do nothing # end # # @example AllowNil: true (default) # # # good # def some_method # do_something # rescue # nil # end # # # good # begin # do_something # rescue # # do nothing # end # # # good # do_something rescue nil # # @example AllowNil: false # # # bad # def some_method # do_something # rescue # nil # end # # # bad # begin # do_something # rescue # nil # end # # # bad # do_something rescue nil class SuppressedException < Base MSG = 'Do not suppress exceptions.' def on_resbody(node) return if node.body && !nil_body?(node) return if cop_config['AllowComments'] && comment_between_rescue_and_end?(node) return if cop_config['AllowNil'] && nil_body?(node) add_offense(node) end private def comment_between_rescue_and_end?(node) ancestor = node.each_ancestor(:kwbegin, :any_def, :any_block).first return false unless ancestor end_line = ancestor.loc.end&.line || ancestor.loc.last_line processed_source[node.first_line...end_line].any? { |line| comment_line?(line) } end def nil_body?(node) node.body&.nil_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/safe_navigation_with_empty.rb
lib/rubocop/cop/lint/safe_navigation_with_empty.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks to make sure safe navigation isn't used with `empty?` in # a conditional. # # While the safe navigation operator is generally a good idea, when # checking `foo&.empty?` in a conditional, `foo` being `nil` will actually # do the opposite of what the author intends. # # @example # # bad # return if foo&.empty? # return unless foo&.empty? # # # good # return if foo && foo.empty? # return unless foo && foo.empty? # class SafeNavigationWithEmpty < Base extend AutoCorrector MSG = 'Avoid calling `empty?` with the safe navigation operator in conditionals.' # @!method safe_navigation_empty_in_conditional?(node) def_node_matcher :safe_navigation_empty_in_conditional?, <<~PATTERN (if (csend (send ...) :empty?) ...) PATTERN def on_if(node) return unless safe_navigation_empty_in_conditional?(node) condition = node.condition add_offense(condition) do |corrector| receiver = condition.receiver.source corrector.replace(condition, "#{receiver} && #{receiver}.#{condition.method_name}") 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/hash_new_with_keyword_arguments_as_default.rb
lib/rubocop/cop/lint/hash_new_with_keyword_arguments_as_default.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for the deprecated use of keyword arguments as a default in `Hash.new`. # # This usage raises a warning in Ruby 3.3 and results in an error in Ruby 3.4. # In Ruby 3.4, keyword arguments will instead be used to change the behavior of a hash. # For example, the capacity option can be passed to create a hash with a certain size # if you know it in advance, for better performance. # # NOTE: The following corner case may result in a false negative when upgrading from Ruby 3.3 # or earlier, but it is intentionally not detected to respect the expected usage in Ruby 3.4. # # [source,ruby] # ---- # Hash.new(capacity: 42) # ---- # # @example # # # bad # Hash.new(key: :value) # # # good # Hash.new({key: :value}) # class HashNewWithKeywordArgumentsAsDefault < Base extend AutoCorrector MSG = 'Use a hash literal instead of keyword arguments.' RESTRICT_ON_SEND = %i[new].freeze # @!method hash_new(node) def_node_matcher :hash_new, <<~PATTERN (send (const {nil? (cbase)} :Hash) :new $[hash !braces?]) PATTERN def on_send(node) return unless (first_argument = hash_new(node)) if first_argument.pairs.one? key = first_argument.pairs.first.key return if key.respond_to?(:value) && key.value == :capacity end add_offense(first_argument) do |corrector| corrector.wrap(first_argument, '{', '}') 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_in_interpolation.rb
lib/rubocop/cop/lint/literal_in_interpolation.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for interpolated literals. # # NOTE: Array literals interpolated in regexps are not handled by this cop, but # by `Lint/ArrayLiteralInRegexp` instead. # # @example # # # bad # "result is #{10}" # # # good # "result is 10" class LiteralInInterpolation < Base include Interpolation include RangeHelp include PercentLiteral extend AutoCorrector MSG = 'Literal interpolation detected.' COMPOSITE = %i[array hash pair irange erange].freeze # rubocop:disable Metrics/AbcSize def on_interpolation(begin_node) final_node = begin_node.children.last return unless offending?(final_node) # %W and %I split the content into words before expansion # treating each interpolation as a word component, so # interpolation should not be removed if the expanded value # contains a space character. expanded_value = autocorrected_value(final_node) expanded_value = handle_special_regexp_chars(begin_node, expanded_value) return if in_array_percent_literal?(begin_node) && /\s|\A\z/.match?(expanded_value) add_offense(final_node) do |corrector| next if final_node.dstr_type? # nested, fixed in next iteration replacement = if final_node.str_type? && !final_node.value.valid_encoding? final_node.source.delete_prefix('"').delete_suffix('"') else expanded_value end corrector.replace(final_node.parent, replacement) end end # rubocop:enable Metrics/AbcSize private def offending?(node) node && !special_keyword?(node) && prints_as_self?(node) && # Special case for `Layout/TrailingWhitespace` !(space_literal?(node) && ends_heredoc_line?(node)) && # Handled by `Lint/ArrayLiteralInRegexp` !array_in_regexp?(node) end def special_keyword?(node) # handle strings like __FILE__ (node.str_type? && !node.loc?(:begin)) || node.source_range.is?('__LINE__') end def array_in_regexp?(node) grandparent = node.parent.parent node.array_type? && grandparent.regexp_type? end # rubocop:disable Metrics/MethodLength, Metrics/CyclomaticComplexity def autocorrected_value(node) case node.type when :int node.children.last.to_i.to_s when :float node.children.last.to_f.to_s when :str autocorrected_value_for_string(node) when :sym autocorrected_value_for_symbol(node) when :array autocorrected_value_for_array(node) when :hash autocorrected_value_for_hash(node) when :nil '' else node.source.gsub('"', '\"') end end # rubocop:enable Metrics/MethodLength, Metrics/CyclomaticComplexity def handle_special_regexp_chars(begin_node, value) parent_node = begin_node.parent return value unless parent_node.regexp_type? && parent_node.slash_literal? && value['/'] # When a literal string containing a forward slash preceded by backslashes # is interpolated inside a regexp, the number of resultant backslashes in the # compiled Regexp is `(2(n+1) / 4)+1`, where `n` is the number of backslashes # inside the interpolation. # ie. 0-2 backslashes is compiled to 1, 3-6 is compiled to 3, etc. # This maintains that same behavior in order to ensure the Regexp behavior # does not change upon removing the interpolation. value.gsub(%r{(\\*)/}) do backslashes = Regexp.last_match[1] backslash_count = backslashes.length needed_backslashes = (2 * ((backslash_count + 1) / 4)) + 1 "#{'\\' * needed_backslashes}/" end end def autocorrected_value_for_string(node) if node.source.start_with?("'", '%q') node.children.last.inspect[1..-2] else node.children.last end end def autocorrected_value_for_symbol(node) end_pos = node.loc.end ? node.loc.end.begin_pos : node.source_range.end_pos range_between(node.loc.begin.end_pos, end_pos).source.gsub('"', '\"') end def autocorrected_value_in_hash_for_symbol(node) # TODO: We need to detect symbol unacceptable names more correctly if / |"|'/.match?(node.value.to_s) ":\\\"#{node.value.to_s.gsub('"') { '\\\\\"' }}\\\"" else ":#{node.value}" end end def autocorrected_value_for_array(node) return node.source.gsub('"', '\"') unless node.percent_literal? contents_range(node).source.split.to_s.gsub('"', '\"') end def autocorrected_value_for_hash(node) hash_string = node.children.map do |child| key = autocorrected_value_in_hash(child.key) value = autocorrected_value_in_hash(child.value) "#{key}=>#{value}" end.join(', ') "{#{hash_string}}" end # rubocop:disable Metrics/MethodLength, Metrics/AbcSize def autocorrected_value_in_hash(node) case node.type when :int node.children.last.to_i.to_s when :float node.children.last.to_f.to_s when :str "\\\"#{node.value.to_s.gsub('"') { '\\\\\"' }}\\\"" when :sym autocorrected_value_in_hash_for_symbol(node) when :array autocorrected_value_for_array(node) when :hash autocorrected_value_for_hash(node) else node.source.gsub('"', '\"') end end # rubocop:enable Metrics/MethodLength, Metrics/AbcSize # Does node print its own source when converted to a string? def prints_as_self?(node) node.basic_literal? || (COMPOSITE.include?(node.type) && node.children.all? { |child| prints_as_self?(child) }) end def space_literal?(node) node.str_type? && node.value.valid_encoding? && node.value.blank? end def ends_heredoc_line?(node) grandparent = node.parent.parent return false unless grandparent&.dstr_type? && grandparent.heredoc? line = processed_source.lines[node.last_line - 1] line.size == node.loc.last_column + 1 end def in_array_percent_literal?(node) parent = node.parent return false unless parent.type?(:dstr, :dsym) grandparent = parent.parent grandparent&.array_type? && grandparent.percent_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/empty_in_pattern.rb
lib/rubocop/cop/lint/empty_in_pattern.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for the presence of `in` pattern branches without a body. # # @example # # # bad # case condition # in [a] # do_something # in [a, b] # end # # # good # case condition # in [a] # do_something # in [a, b] # nil # end # # @example AllowComments: true (default) # # # good # case condition # in [a] # do_something # in [a, b] # # noop # end # # @example AllowComments: false # # # bad # case condition # in [a] # do_something # in [a, b] # # noop # end # class EmptyInPattern < Base extend TargetRubyVersion include CommentsHelp MSG = 'Avoid `in` branches without a body.' minimum_target_ruby_version 2.7 def on_case_match(node) node.in_pattern_branches.each do |branch| next if branch.body next if cop_config['AllowComments'] && contains_comments?(branch) add_offense(branch) 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_operator.rb
lib/rubocop/cop/lint/ambiguous_operator.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for ambiguous operators in the first argument of a # method invocation without parentheses. # # @example # # # bad # # # The `*` is interpreted as a splat operator but it could possibly be # # a `*` method invocation (i.e. `do_something.*(some_array)`). # do_something *some_array # # # good # # # With parentheses, there's no ambiguity. # do_something(*some_array) class AmbiguousOperator < Base extend AutoCorrector AMBIGUITIES = { '+' => { actual: 'positive number', possible: 'an addition' }, '-' => { actual: 'negative number', possible: 'a subtraction' }, '*' => { actual: 'splat', possible: 'a multiplication' }, '&' => { actual: 'block', possible: 'a binary AND' }, '**' => { actual: 'keyword splat', possible: 'an exponent' } }.each do |key, hash| hash[:operator] = key end MSG_FORMAT = 'Ambiguous %<actual>s operator. Parenthesize the method ' \ "arguments if it's surely a %<actual>s operator, or add " \ 'a whitespace to the right of the `%<operator>s` if it ' \ 'should be %<possible>s.' def self.autocorrect_incompatible_with [Naming::BlockForwarding] end def on_new_investigation processed_source.diagnostics.each do |diagnostic| next unless diagnostic.reason == :ambiguous_prefix offense_node = find_offense_node_by(diagnostic) next unless offense_node message = message(diagnostic) add_offense( diagnostic.location, message: message, severity: diagnostic.level ) do |corrector| add_parentheses(offense_node, corrector) end end end private def find_offense_node_by(diagnostic) ast = processed_source.ast ast.each_node(:splat, :block_pass, :kwsplat) do |node| next unless offense_position?(node, diagnostic) offense_node = offense_node(node) return offense_node if offense_node end ast.each_node(:send).find do |send_node| first_argument = send_node.first_argument first_argument && offense_position?(first_argument, diagnostic) && unary_operator?(first_argument, diagnostic) end end def message(diagnostic) operator = diagnostic.location.source hash = AMBIGUITIES[operator] format(MSG_FORMAT, hash) end def offense_position?(node, diagnostic) node.source_range.begin_pos == diagnostic.location.begin_pos end def offense_node(node) case node.type when :splat, :block_pass node.parent when :kwsplat node.parent.parent end end def unary_operator?(node, diagnostic) node.source.start_with?(diagnostic.arguments[:prefix]) 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/cop_directive_syntax.rb
lib/rubocop/cop/lint/cop_directive_syntax.rb
# frozen_string_literal: true # rubocop:disable Lint/RedundantCopDisableDirective # rubocop:disable Style/DoubleCopDisableDirective module RuboCop module Cop module Lint # Checks that `# rubocop:enable ...` and `# rubocop:disable ...` statements # are strictly formatted. # # A comment can be added to the directive by prefixing it with `--`. # # @example # # bad # # rubocop:disable Layout/LineLength Style/Encoding # # # good # # rubocop:disable Layout/LineLength, Style/Encoding # # # bad # # rubocop:disable # # # good # # rubocop:disable all # # # bad # # rubocop:disable Layout/LineLength # rubocop:disable Style/Encoding # # # good # # rubocop:disable Layout/LineLength # # rubocop:disable Style/Encoding # # # bad # # rubocop:wrongmode Layout/LineLength # # # good # # rubocop:disable Layout/LineLength # # # bad # # rubocop:disable Layout/LineLength comment # # # good # # rubocop:disable Layout/LineLength -- comment # class CopDirectiveSyntax < Base COMMON_MSG = 'Malformed directive comment detected.' MISSING_MODE_NAME_MSG = 'The mode name is missing.' INVALID_MODE_NAME_MSG = 'The mode name must be one of `enable`, `disable`, `todo`, `push`, or `pop`.' # rubocop:disable Layout/LineLength MISSING_COP_NAME_MSG = 'The cop name is missing.' MALFORMED_COP_NAMES_MSG = 'Cop names must be separated by commas. ' \ 'Comment in the directive must start with `--`.' def on_new_investigation processed_source.comments.each do |comment| directive_comment = DirectiveComment.new(comment) next unless directive_comment.start_with_marker? next unless directive_comment.malformed? message = offense_message(directive_comment) add_offense(comment, message: message) end end private # rubocop:disable Metrics/MethodLength def offense_message(directive_comment) comment = directive_comment.comment after_marker = comment.text.sub(DirectiveComment::DIRECTIVE_MARKER_REGEXP, '') mode = after_marker.split(' ', 2).first additional_msg = if mode.nil? MISSING_MODE_NAME_MSG elsif !DirectiveComment::AVAILABLE_MODES.include?(mode) INVALID_MODE_NAME_MSG elsif directive_comment.missing_cop_name? MISSING_COP_NAME_MSG else MALFORMED_COP_NAMES_MSG end "#{COMMON_MSG} #{additional_msg}" end # rubocop:enable Metrics/MethodLength end end end end # rubocop:enable Lint/RedundantCopDisableDirective # rubocop:enable Style/DoubleCopDisableDirective
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/lint/percent_string_array.rb
lib/rubocop/cop/lint/percent_string_array.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for quotes and commas in %w, e.g. `%w('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 strings. # # @safety # The cop is unsafe because the correction changes the values in the array # and that might have been done purposely. # # [source,ruby] # ---- # %w('foo', "bar") #=> ["'foo',", '"bar"'] # %w(foo bar) #=> ['foo', 'bar'] # ---- # # @example # # # bad # %w('foo', "bar") # # # good # %w(foo bar) class PercentStringArray < Base include PercentLiteral extend AutoCorrector QUOTES_AND_COMMAS = [/,$/, /^'.*'$/, /^".*"$/].freeze LEADING_QUOTE = /^['"]/.freeze TRAILING_QUOTE = /['"]?,?$/.freeze MSG = "Within `%w`/`%W`, quotes and ',' are unnecessary and may be " \ 'unwanted in the resulting strings.' def on_array(node) process(node, '%w', '%W') end def on_percent_literal(node) return unless contains_quotes_or_commas?(node) add_offense(node) do |corrector| node.each_value do |value| range = value.source_range match = range.source.match(TRAILING_QUOTE) corrector.remove_trailing(range, match[0].length) if match corrector.remove_leading(range, 1) if LEADING_QUOTE.match?(range.source) end end end private def contains_quotes_or_commas?(node) node.values.any? do |value| literal = value.children.first.to_s.scrub # To avoid likely false positives (e.g. a single ' or ") next if literal.gsub(/[^[[:alnum:]]]/, '').empty? QUOTES_AND_COMMAS.any? { |pat| literal.match?(pat) } 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/raise_exception.rb
lib/rubocop/cop/lint/raise_exception.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for `raise` or `fail` statements which raise `Exception` or # `Exception.new`. Use `StandardError` or a specific exception class instead. # # If you have defined your own namespaced `Exception` class, it is possible # to configure the cop to allow it by setting `AllowedImplicitNamespaces` to # an array with the names of the namespaces to allow. By default, this is set to # `['Gem']`, which allows `Gem::Exception` to be raised without an explicit namespace. # If not allowed, a false positive may be registered if `raise Exception` is called # within the namespace. # # Alternatively, use a fully qualified name with `raise`/`fail` # (eg. `raise Namespace::Exception`). # # @safety # This cop is unsafe because it will change the exception class being # raised, which is a change in behavior. # # @example # # bad # raise Exception, 'Error message here' # raise Exception.new('Error message here') # # # good # raise StandardError, 'Error message here' # raise MyError.new, 'Error message here' # # @example AllowedImplicitNamespaces: ['Gem'] (default) # # bad - `Foo` is not an allowed implicit namespace # module Foo # def self.foo # raise Exception # This is qualified to `Foo::Exception`. # end # end # # # good # module Gem # def self.foo # raise Exception # This is qualified to `Gem::Exception`. # end # end # # # good # module Foo # def self.foo # raise Foo::Exception # end # end class RaiseException < Base extend AutoCorrector MSG = 'Use `StandardError` over `Exception`.' RESTRICT_ON_SEND = %i[raise fail].freeze # @!method exception?(node) def_node_matcher :exception?, <<~PATTERN (send nil? {:raise :fail} $(const ${cbase nil?} :Exception) ... ) PATTERN # @!method exception_new_with_message?(node) def_node_matcher :exception_new_with_message?, <<~PATTERN (send nil? {:raise :fail} (send $(const ${cbase nil?} :Exception) :new ... )) PATTERN def on_send(node) exception?(node, &check(node)) || exception_new_with_message?(node, &check(node)) end private def check(node) lambda do |exception_class, cbase| return if cbase.nil? && implicit_namespace?(node) add_offense(exception_class) do |corrector| prefer_exception = if exception_class.children.first&.cbase_type? '::StandardError' else 'StandardError' end corrector.replace(exception_class, prefer_exception) end end end def implicit_namespace?(node) return false unless (parent = node.parent) if parent.module_type? namespace = parent.identifier.source return allow_implicit_namespaces.include?(namespace) end implicit_namespace?(parent) end def allow_implicit_namespaces cop_config['AllowedImplicitNamespaces'] || [] 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/uri_regexp.rb
lib/rubocop/cop/lint/uri_regexp.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Identifies places where `URI.regexp` is obsolete and should not be used. # # For Ruby 3.3 or lower, use `URI::DEFAULT_PARSER.make_regexp`. # For Ruby 3.4 or higher, use `URI::RFC2396_PARSER.make_regexp`. # # NOTE: If you need to support both Ruby 3.3 and lower as well as Ruby 3.4 and higher, # consider manually changing the code as follows: # # [source,ruby] # ---- # defined?(URI::RFC2396_PARSER) ? URI::RFC2396_PARSER : URI::DEFAULT_PARSER # ---- # # @example # # bad # URI.regexp('http://example.com') # # # good - Ruby 3.3 or lower # URI::DEFAULT_PARSER.make_regexp('http://example.com') # # # good - Ruby 3.4 or higher # URI::RFC2396_PARSER.make_regexp('http://example.com') # class UriRegexp < Base extend AutoCorrector MSG = '`%<current>s` is obsolete and should not be used. Instead, use `%<preferred>s`.' RESTRICT_ON_SEND = %i[regexp].freeze # @!method uri_constant?(node) def_node_matcher :uri_constant?, <<~PATTERN (const {cbase nil?} :URI) PATTERN def on_send(node) return unless uri_constant?(node.receiver) parser = target_ruby_version >= 3.4 ? 'RFC2396_PARSER' : 'DEFAULT_PARSER' argument = node.first_argument ? "(#{node.first_argument.source})" : '' preferred_method = "#{node.receiver.source}::#{parser}.make_regexp#{argument}" message = format(MSG, current: node.source, preferred: preferred_method) add_offense(node.loc.selector, message: message) do |corrector| corrector.replace(node, preferred_method) 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_require.rb
lib/rubocop/cop/lint/duplicate_require.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for duplicate ``require``s and ``require_relative``s. # # @safety # This cop's autocorrection is unsafe because it may break the dependency order # of `require`. # # @example # # bad # require 'foo' # require 'bar' # require 'foo' # # # good # require 'foo' # require 'bar' # # # good # require 'foo' # require_relative 'foo' # class DuplicateRequire < Base include RangeHelp extend AutoCorrector MSG = 'Duplicate `%<method>s` detected.' REQUIRE_METHODS = Set.new(%i[require require_relative]).freeze RESTRICT_ON_SEND = REQUIRE_METHODS # @!method require_call?(node) def_node_matcher :require_call?, <<~PATTERN (send {nil? (const _ :Kernel)} %REQUIRE_METHODS _) PATTERN def on_new_investigation # Holds the known required files for a given parent node (used as key) @required = Hash.new { |h, k| h[k] = Set.new }.compare_by_identity super end def on_send(node) return unless require_call?(node) return if @required[node.parent].add?("#{node.method_name}#{node.first_argument}") add_offense(node, message: format(MSG, method: node.method_name)) do |corrector| corrector.remove(range_by_whole_lines(node.source_range, 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/lint/unmodified_reduce_accumulator.rb
lib/rubocop/cop/lint/unmodified_reduce_accumulator.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Looks for `reduce` or `inject` blocks where the value returned (implicitly or # explicitly) does not include the accumulator. A block is considered valid as # long as at least one return value includes the accumulator. # # If the accumulator is not included in the return value, then the entire # block will just return a transformation of the last element value, and # could be rewritten as such without a loop. # # Also catches instances where an index of the accumulator is returned, as # this may change the type of object being retained. # # NOTE: For the purpose of reducing false positives, this cop only flags # returns in `reduce` blocks where the element is the only variable in # the expression (since we will not be able to tell what other variables # relate to via static analysis). # # @example # # # bad # (1..4).reduce(0) do |acc, el| # el * 2 # end # # # bad, may raise a NoMethodError after the first iteration # %w(a b c).reduce({}) do |acc, letter| # acc[letter] = true # end # # # good # (1..4).reduce(0) do |acc, el| # acc + el * 2 # end # # # good, element is returned but modified using the accumulator # values.reduce do |acc, el| # el << acc # el # end # # # good, returns the accumulator instead of the index # %w(a b c).reduce({}) do |acc, letter| # acc[letter] = true # acc # end # # # good, at least one branch returns the accumulator # values.reduce(nil) do |result, value| # break result if something? # value # end # # # good, recursive # keys.reduce(self) { |result, key| result[key] } # # # ignored as the return value cannot be determined # enum.reduce do |acc, el| # x = foo(acc, el) # bar(x) # end class UnmodifiedReduceAccumulator < Base MSG = 'Ensure the accumulator `%<accum>s` will be modified by `%<method>s`.' MSG_INDEX = 'Do not return an element of the accumulator in `%<method>s`.' # @!method reduce_with_block?(node) def_node_matcher :reduce_with_block?, <<~PATTERN { (block (call _recv {:reduce :inject} ...) args ...) (numblock (call _recv {:reduce :inject} ...) ...) } PATTERN # @!method accumulator_index?(node, accumulator_name) def_node_matcher :accumulator_index?, <<~PATTERN (send (lvar %1) {:[] :[]=} ...) PATTERN # @!method element_modified?(node, element_name) def_node_search :element_modified?, <<~PATTERN { (send _receiver !{:[] :[]=} <`(lvar %1) `_ ...>) # method(el, ...) (send (lvar %1) _message <{ivar gvar cvar lvar send} ...>) # el.method(...) (lvasgn %1 _) # el = ... (%RuboCop::AST::Node::SHORTHAND_ASSIGNMENTS (lvasgn %1) ... _) # el += ... } PATTERN # @!method lvar_used?(node, name) def_node_matcher :lvar_used?, <<~PATTERN { (lvar %1) (lvasgn %1 ...) (send (lvar %1) :<< ...) (dstr (begin (lvar %1))) (%RuboCop::AST::Node::SHORTHAND_ASSIGNMENTS (lvasgn %1)) } PATTERN # @!method expression_values(node) def_node_search :expression_values, <<~PATTERN { (%RuboCop::AST::Node::VARIABLES $_) (%RuboCop::AST::Node::EQUALS_ASSIGNMENTS $_ ...) (send (%RuboCop::AST::Node::VARIABLES $_) :<< ...) $(send _ _) (dstr (begin {(%RuboCop::AST::Node::VARIABLES $_)})) (%RuboCop::AST::Node::SHORTHAND_ASSIGNMENTS (%RuboCop::AST::Node::EQUALS_ASSIGNMENTS $_) ...) } PATTERN def on_block(node) return unless node.body return unless reduce_with_block?(node) return unless node.argument_list.length >= 2 check_return_values(node) end alias on_numblock on_block private # Return values in a block are either the value given to next, # the last line of a multiline block, or the only line of the block def return_values(block_body_node) nodes = [block_body_node.begin_type? ? block_body_node.child_nodes.last : block_body_node] block_body_node.each_descendant(:next, :break) do |n| # Ignore `next`/`break` inside an inner block next if n.each_ancestor(:any_block).first != block_body_node.parent next unless n.first_argument nodes << n.first_argument end nodes end def check_return_values(block_node) return_values = return_values(block_node.body) accumulator_name = block_arg_name(block_node, 0) element_name = block_arg_name(block_node, 1) message_opts = { method: block_node.method_name, accum: accumulator_name } if (node = returned_accumulator_index(return_values, accumulator_name, element_name)) add_offense(node, message: format(MSG_INDEX, message_opts)) elsif potential_offense?(return_values, block_node.body, element_name, accumulator_name) return_values.each do |return_val| unless acceptable_return?(return_val, element_name) add_offense(return_val, message: format(MSG, message_opts)) end end end end def block_arg_name(node, index) node.argument_list[index].name end # Look for an index of the accumulator being returned, except where the index # is the element. # This is always an offense, in order to try to catch potential exceptions # due to type mismatches def returned_accumulator_index(return_values, accumulator_name, element_name) return_values.detect do |val| next unless accumulator_index?(val, accumulator_name) next true if val.method?(:[]=) val.arguments.none? { |arg| lvar_used?(arg, element_name) } end end def potential_offense?(return_values, block_body, element_name, accumulator_name) !(element_modified?(block_body, element_name) || returns_accumulator_anywhere?(return_values, accumulator_name)) end # If the accumulator is used in any return value, the node is acceptable since # the accumulator has a chance to change each iteration def returns_accumulator_anywhere?(return_values, accumulator_name) return_values.any? { |node| lvar_used?(node, accumulator_name) } end # Determine if a return value is acceptable for the purposes of this cop # If it is an expression containing the accumulator, it is acceptable # Otherwise, it is only unacceptable if it contains the iterated element, since we # otherwise do not have enough information to prevent false positives. def acceptable_return?(return_val, element_name) vars = expression_values(return_val).uniq return true if vars.none? || (vars - [element_name]).any? false end # Exclude `begin` nodes inside a `dstr` from being collected by `return_values` def allowed_type?(parent_node) !parent_node.dstr_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/return_in_void_context.rb
lib/rubocop/cop/lint/return_in_void_context.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for the use of a return with a value in a context # where the value will be ignored. (initialize and setter methods) # # @example # # # bad # def initialize # foo # return :qux if bar? # baz # end # # def foo=(bar) # return 42 # end # # # good # def initialize # foo # return if bar? # baz # end # # def foo=(bar) # return # end class ReturnInVoidContext < Base MSG = 'Do not return a value in `%<method>s`.' # Returning out of these methods only exits the block itself. SCOPE_CHANGING_METHODS = %i[lambda define_method define_singleton_method].freeze def on_return(return_node) return unless return_node.descendants.any? def_node = return_node.each_ancestor(:any_def).first return unless def_node&.void_context? return if return_node.each_ancestor(:any_block).any? do |block_node| SCOPE_CHANGING_METHODS.include?(block_node.method_name) end add_offense( return_node.loc.keyword, message: format(message, method: def_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/underscore_prefixed_variable_name.rb
lib/rubocop/cop/lint/underscore_prefixed_variable_name.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for underscore-prefixed variables that are actually # used. # # Since block keyword arguments cannot be arbitrarily named at call # sites, the `AllowKeywordBlockArguments` will allow use of underscore- # prefixed block keyword arguments. # # @example AllowKeywordBlockArguments: false (default) # # # bad # # [1, 2, 3].each do |_num| # do_something(_num) # end # # query(:sales) do |_id:, revenue:, cost:| # {_id: _id, profit: revenue - cost} # end # # # good # # [1, 2, 3].each do |num| # do_something(num) # end # # [1, 2, 3].each do |_num| # do_something # not using `_num` # end # # @example AllowKeywordBlockArguments: true # # # good # # query(:sales) do |_id:, revenue:, cost:| # {_id: _id, profit: revenue - cost} # end # class UnderscorePrefixedVariableName < Base MSG = 'Do not use prefix `_` for a variable that is used.' def self.joining_forces VariableForce end def after_leaving_scope(scope, _variable_table) scope.variables.each_value { |variable| check_variable(variable) } end def check_variable(variable) return unless variable.should_be_unused? return if variable.references.none?(&:explicit?) return if allowed_keyword_block_argument?(variable) node = variable.declaration_node location = if node.match_with_lvasgn_type? node.children.first.source_range else node.loc.name end add_offense(location) end private def allowed_keyword_block_argument?(variable) variable.block_argument? && variable.keyword_argument? && cop_config['AllowKeywordBlockArguments'] 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_regexp_quantifiers.rb
lib/rubocop/cop/lint/redundant_regexp_quantifiers.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for redundant quantifiers inside `Regexp` literals. # # It is always allowed when interpolation is used in a regexp literal, # because it's unknown what kind of string will be expanded as a result: # # [source,ruby] # ---- # /(?:a*#{interpolation})?/x # ---- # # @example # # bad # /(?:x+)+/ # # # good # /(?:x)+/ # # # good # /(?:x+)/ # # # bad # /(?:x+)?/ # # # good # /(?:x)*/ # # # good # /(?:x*)/ class RedundantRegexpQuantifiers < Base include RangeHelp extend AutoCorrector MSG_REDUNDANT_QUANTIFIER = 'Replace redundant quantifiers ' \ '`%<inner_quantifier>s` and `%<outer_quantifier>s` ' \ 'with a single `%<replacement>s`.' def on_regexp(node) return if node.interpolation? each_redundantly_quantified_pair(node) do |group, child| replacement = merged_quantifier(group, child) add_offense( quantifier_range(group, child), message: message(group, child, replacement) ) do |corrector| # drop outer quantifier corrector.replace(group.loc.quantifier, '') # replace inner quantifier corrector.replace(child.loc.quantifier, replacement) end end end private def each_redundantly_quantified_pair(node) seen = Set.new node.parsed_tree&.each_expression do |(expr)| next if seen.include?(expr) || !redundant_group?(expr) || !mergeable_quantifier(expr) expr.each_expression do |(subexp)| seen << subexp break unless redundantly_quantifiable?(subexp) yield(expr, subexp) if mergeable_quantifier(subexp) end end end def redundant_group?(expr) expr.is?(:passive, :group) && expr.one? { |child| child.type != :free_space } end def redundantly_quantifiable?(node) redundant_group?(node) || character_set?(node) || node.terminal? end def character_set?(expr) expr.is?(:character, :set) end def mergeable_quantifier(expr) # Merging reluctant or possessive quantifiers would be more complex, # and Ruby does not emit warnings for these cases. return unless expr.quantifier&.greedy? # normalize quantifiers, e.g. "{1,}" => "+" case expr.quantity when [0, -1] '*' when [0, 1] '?' when [1, -1] '+' end end def merged_quantifier(exp1, exp2) quantifier1 = mergeable_quantifier(exp1) quantifier2 = mergeable_quantifier(exp2) if quantifier1 == quantifier2 # (?:a+)+ equals (?:a+) ; (?:a*)* equals (?:a*) ; # (?:a?)? equals (?:a?) quantifier1 else # (?:a+)*, (?:a+)?, (?:a*)+, (?:a*)?, (?:a?)+, (?:a?)* - all equal (?:a*) '*' end end def quantifier_range(group, child) range_between(child.loc.quantifier.begin_pos, group.loc.quantifier.end_pos) end def message(group, child, replacement) format( MSG_REDUNDANT_QUANTIFIER, inner_quantifier: child.quantifier.to_s, outer_quantifier: group.quantifier.to_s, replacement: replacement ) 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/shared_mutable_default.rb
lib/rubocop/cop/lint/shared_mutable_default.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for `Hash` creation with a mutable default value. # Creating a `Hash` in such a way will share the default value # across all keys, causing unexpected behavior when modifying it. # # For example, when the `Hash` was created with an `Array` as the argument, # calling `hash[:foo] << 'bar'` will also change the value of all # other keys that have not been explicitly assigned to. # # @example # # bad # Hash.new([]) # Hash.new({}) # Hash.new(Array.new) # Hash.new(Hash.new) # # # okay -- In rare cases that intentionally have this behavior, # # without disabling the cop, you can set the default explicitly. # h = Hash.new # h.default = [] # h[:a] << 1 # h[:b] << 2 # h # => {:a => [1, 2], :b => [1, 2]} # # # okay -- beware this will discard mutations and only remember assignments # Hash.new { Array.new } # Hash.new { Hash.new } # Hash.new { {} } # Hash.new { [] } # # # good - frozen solution will raise an error when mutation attempted # Hash.new([].freeze) # Hash.new({}.freeze) # # # good - using a proc will create a new object for each key # h = Hash.new # h.default_proc = ->(h, k) { [] } # h.default_proc = ->(h, k) { {} } # # # good - using a block will create a new object for each key # Hash.new { |h, k| h[k] = [] } # Hash.new { |h, k| h[k] = {} } class SharedMutableDefault < Base MSG = 'Do not create a Hash with a mutable default value ' \ 'as the default value can accidentally be changed.' RESTRICT_ON_SEND = %i[new].freeze # @!method hash_initialized_with_mutable_shared_object?(node) def_node_matcher :hash_initialized_with_mutable_shared_object?, <<~PATTERN { (send (const {nil? cbase} :Hash) :new [ {array hash (send (const {nil? cbase} {:Array :Hash}) :new)} !#capacity_keyword_argument? ]) (send (const {nil? cbase} :Hash) :new hash #capacity_keyword_argument?) } PATTERN # @!method capacity_keyword_argument?(node) def_node_matcher :capacity_keyword_argument?, <<~PATTERN (hash (pair (sym :capacity) _)) PATTERN def on_send(node) return unless hash_initialized_with_mutable_shared_object?(node) 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/useless_rescue.rb
lib/rubocop/cop/lint/useless_rescue.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for useless ``rescue``s, which only reraise rescued exceptions. # # @example # # bad # def foo # do_something # rescue # raise # end # # # bad # def foo # do_something # rescue => e # raise # or 'raise e', or 'raise $!', or 'raise $ERROR_INFO' # end # # # good # def foo # do_something # rescue # do_cleanup # raise # end # # # bad (latest rescue) # def foo # do_something # rescue ArgumentError # # noop # rescue # raise # end # # # good (not the latest rescue) # def foo # do_something # rescue ArgumentError # raise # rescue # # noop # end # class UselessRescue < Base MSG = 'Useless `rescue` detected.' def on_rescue(node) resbody_node = node.resbody_branches.last add_offense(resbody_node) if only_reraising?(resbody_node) end private # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity def only_reraising?(resbody_node) return false if use_exception_variable_in_ensure?(resbody_node) body = resbody_node.body return false if body.nil? || !body.send_type? || !body.method?(:raise) || body.receiver return true unless body.arguments? return false if body.arguments.size > 1 exception_name = body.first_argument.source exception_objects(resbody_node).include?(exception_name) end # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity def use_exception_variable_in_ensure?(resbody_node) return false unless (exception_variable = resbody_node.exception_variable) return false unless (ensure_node = resbody_node.each_ancestor(:ensure).first) return false unless (ensure_body = ensure_node.branch) ensure_body.each_descendant(:lvar).map(&:source).include?(exception_variable.source) end def exception_objects(resbody_node) [resbody_node.exception_variable&.source, '$!', '$ERROR_INFO'] 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_interpolation.rb
lib/rubocop/cop/lint/empty_interpolation.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for empty interpolation. # # @example # # # bad # "result is #{}" # # # good # "result is #{some_result}" class EmptyInterpolation < Base include Interpolation extend AutoCorrector MSG = 'Empty interpolation detected.' def on_interpolation(begin_node) return if in_percent_literal_array?(begin_node) node_children = begin_node.children.dup node_children.delete_if { |e| e.nil_type? || (e.basic_literal? && e.str_content&.empty?) } return unless node_children.empty? add_offense(begin_node) { |corrector| corrector.remove(begin_node) } end private def in_percent_literal_array?(begin_node) array_node = begin_node.each_ancestor(:array).first return false unless array_node array_node.percent_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/rand_one.rb
lib/rubocop/cop/lint/rand_one.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for `rand(1)` calls. # Such calls always return `0`. # # @example # # # bad # rand 1 # Kernel.rand(-1) # rand 1.0 # rand(-1.0) # # # good # 0 # just use 0 instead class RandOne < Base MSG = '`%<method>s` always returns `0`. Perhaps you meant `rand(2)` or `rand`?' RESTRICT_ON_SEND = %i[rand].freeze # @!method rand_one?(node) def_node_matcher :rand_one?, <<~PATTERN (send {(const {nil? cbase} :Kernel) nil?} :rand {(int {-1 1}) (float {-1.0 1.0})}) PATTERN def on_send(node) return unless rand_one?(node) add_offense(node) end private def message(node) format(MSG, method: node.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/out_of_range_regexp_ref.rb
lib/rubocop/cop/lint/out_of_range_regexp_ref.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Looks for references of `Regexp` captures that are out of range # and thus always returns nil. # # @safety # This cop is unsafe because it is naive in how it determines what # references are available based on the last encountered regexp, but # it cannot handle some cases, such as conditional regexp matches, which # leads to false positives, such as: # # [source,ruby] # ---- # foo ? /(c)(b)/ =~ str : /(b)/ =~ str # do_something if $2 # # $2 is defined for the first condition but not the second, however # # the cop will mark this as an offense. # ---- # # This might be a good indication of code that should be refactored, # however. # # @example # # /(foo)bar/ =~ 'foobar' # # # bad - always returns nil # # puts $2 # => nil # # # good # # puts $1 # => foo # class OutOfRangeRegexpRef < Base MSG = '$%<backref>s is out of range (%<count>s regexp capture %<group>s detected).' REGEXP_RECEIVER_METHODS = %i[=~ === match].to_set.freeze REGEXP_ARGUMENT_METHODS = %i[=~ match grep gsub gsub! sub sub! [] slice slice! index rindex scan partition rpartition start_with? end_with?].to_set.freeze REGEXP_CAPTURE_METHODS = (REGEXP_RECEIVER_METHODS + REGEXP_ARGUMENT_METHODS).freeze RESTRICT_ON_SEND = REGEXP_CAPTURE_METHODS def on_new_investigation @valid_ref = 0 end def on_match_with_lvasgn(node) check_regexp(node.children.first) end def after_send(node) @valid_ref = nil if regexp_first_argument?(node) check_regexp(node.first_argument) elsif regexp_receiver?(node) check_regexp(node.receiver) end end alias after_csend after_send def on_when(node) regexp_conditions = node.conditions.select(&:regexp_type?) @valid_ref = regexp_conditions.filter_map { |condition| check_regexp(condition) }.max end def on_in_pattern(node) regexp_patterns = regexp_patterns(node) @valid_ref = regexp_patterns.filter_map { |pattern| check_regexp(pattern) }.max end def on_nth_ref(node) backref = node.children.first return if @valid_ref.nil? || backref <= @valid_ref message = format( MSG, backref: backref, count: @valid_ref.zero? ? 'no' : @valid_ref, group: @valid_ref == 1 ? 'group' : 'groups' ) add_offense(node, message: message) end private def regexp_patterns(in_node) pattern = in_node.pattern if pattern.regexp_type? [pattern] else pattern.each_descendant(:regexp).to_a end end def check_regexp(node) return if node.interpolation? named_capture = node.each_capture(named: true).count @valid_ref = if named_capture.positive? named_capture else node.each_capture(named: false).count end end def regexp_first_argument?(send_node) send_node.first_argument&.regexp_type? \ && REGEXP_ARGUMENT_METHODS.include?(send_node.method_name) end def regexp_receiver?(send_node) send_node.receiver&.regexp_type? end def nth_ref_receiver?(send_node) send_node.receiver&.nth_ref_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/nested_percent_literal.rb
lib/rubocop/cop/lint/nested_percent_literal.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for nested percent literals. # # @example # # # bad # # # The percent literal for nested_attributes is parsed as four tokens, # # yielding the array [:name, :content, :"%i[incorrectly", :"nested]"]. # attributes = { # valid_attributes: %i[name content], # nested_attributes: %i[name content %i[incorrectly nested]] # } # # # good # # # Neither is incompatible with the bad case, but probably the intended code. # attributes = { # valid_attributes: %i[name content], # nested_attributes: [:name, :content, %i[incorrectly nested]] # } # # attributes = { # valid_attributes: %i[name content], # nested_attributes: [:name, :content, [:incorrectly, :nested]] # } # class NestedPercentLiteral < Base include PercentLiteral MSG = 'Within percent literals, nested percent literals do not ' \ 'function and may be unwanted in the result.' # The array of regular expressions representing percent literals that, # if found within a percent literal expression, will cause a # NestedPercentLiteral violation to be emitted. PERCENT_LITERAL_TYPES = PreferredDelimiters::PERCENT_LITERAL_TYPES REGEXES = PERCENT_LITERAL_TYPES.map { |percent_literal| /\A#{percent_literal}\W/ }.freeze def on_array(node) process(node, *PERCENT_LITERAL_TYPES) end def on_percent_literal(node) add_offense(node) if contains_percent_literals?(node) end private def contains_percent_literals?(node) node.each_child_node.any? do |child| literal = child.children.first.to_s.scrub REGEXES.any? { |regex| literal.match?(regex) } 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/useless_else_without_rescue.rb
lib/rubocop/cop/lint/useless_else_without_rescue.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for useless `else` in `begin..end` without `rescue`. # # NOTE: This syntax is no longer valid on Ruby 2.6 or higher. # # @example # # # bad # begin # do_something # else # do_something_else # This will never be run. # end # # # good # begin # do_something # rescue # handle_errors # else # do_something_else # end class UselessElseWithoutRescue < Base extend TargetRubyVersion MSG = '`else` without `rescue` is useless.' maximum_target_ruby_version 2.5 def on_new_investigation processed_source.diagnostics.each do |diagnostic| next unless diagnostic.reason == :useless_else add_offense(diagnostic.location, severity: diagnostic.level) 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_magic_comment.rb
lib/rubocop/cop/lint/duplicate_magic_comment.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for duplicated magic comments. # # @example # # # bad # # # encoding: ascii # # encoding: ascii # # # good # # # encoding: ascii # # # bad # # # frozen_string_literal: true # # frozen_string_literal: true # # # good # # # frozen_string_literal: true # class DuplicateMagicComment < Base include FrozenStringLiteral include RangeHelp extend AutoCorrector MSG = 'Duplicate magic comment detected.' def on_new_investigation return if processed_source.buffer.source.empty? magic_comment_lines.each_value do |comment_lines| next if comment_lines.count <= 1 comment_lines[1..].each do |comment_line| range = processed_source.buffer.line_range(comment_line + 1) register_offense(range) end end end private def magic_comment_lines comment_lines = { encoding_magic_comments: [], frozen_string_literal_magic_comments: [] } leading_magic_comments.each.with_index do |magic_comment, index| if magic_comment.encoding_specified? comment_lines[:encoding_magic_comments] << index elsif magic_comment.frozen_string_literal_specified? comment_lines[:frozen_string_literal_magic_comments] << index end end comment_lines end def register_offense(range) add_offense(range) do |corrector| corrector.remove(range_by_whole_lines(range, 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/lint/unreachable_code.rb
lib/rubocop/cop/lint/unreachable_code.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Checks for unreachable code. # The check are based on the presence of flow of control # statement in non-final position in `begin` (implicit) blocks. # # @example # # # bad # def some_method # return # do_something # end # # # bad # def some_method # if cond # return # else # return # end # do_something # end # # # good # def some_method # do_something # end class UnreachableCode < Base MSG = 'Unreachable code detected.' def initialize(config = nil, options = nil) super @redefined = [] @instance_eval_count = 0 end def on_block(node) @instance_eval_count += 1 if instance_eval_block?(node) end alias on_numblock on_block alias on_itblock on_block def after_block(node) @instance_eval_count -= 1 if instance_eval_block?(node) end def on_begin(node) expressions = *node expressions.each_cons(2) do |expression1, expression2| next unless flow_expression?(expression1) add_offense(expression2) end end alias on_kwbegin on_begin private def redefinable_flow_method?(method) %i[raise fail throw exit exit! abort].include? method end # @!method flow_command?(node) def_node_matcher :flow_command?, <<~PATTERN { return next break retry redo (send {nil? (const {nil? cbase} :Kernel)} #redefinable_flow_method? ...) } PATTERN # rubocop:disable Metrics/MethodLength def flow_expression?(node) return report_on_flow_command?(node) if flow_command?(node) case node.type when :begin, :kwbegin expressions = *node expressions.any? { |expr| flow_expression?(expr) } when :if check_if(node) when :case, :case_match check_case(node) when :def, :defs register_redefinition(node) false else false end end # rubocop:enable Metrics/MethodLength def check_if(node) if_branch = node.if_branch else_branch = node.else_branch if_branch && else_branch && flow_expression?(if_branch) && flow_expression?(else_branch) end def check_case(node) else_branch = node.else_branch return false unless else_branch return false unless flow_expression?(else_branch) branches = node.case_type? ? node.when_branches : node.in_pattern_branches branches.all? { |branch| branch.body && flow_expression?(branch.body) } end def register_redefinition(node) @redefined << node.method_name if redefinable_flow_method?(node.method_name) end def instance_eval_block?(node) node.any_block_type? && node.method?(:instance_eval) end def report_on_flow_command?(node) return true unless node.send_type? # By the contract of this function, this case means that # the method is called on `Kernel` in which case we # always want to report a warning. return true if node.receiver # Inside an `instance_eval` we have no way to tell the # type of `self` just by looking at the AST, so we can't # tell if the give function that's called has been # redefined or not, so to avoid false positives, we silence # the warning. return false if @instance_eval_count.positive? !@redefined.include? node.method_name end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false