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/style/colon_method_definition.rb | lib/rubocop/cop/style/colon_method_definition.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for class methods that are defined using the `::`
# operator instead of the `.` operator.
#
# @example
# # bad
# class Foo
# def self::bar
# end
# end
#
# # good
# class Foo
# def self.bar
# end
# end
#
class ColonMethodDefinition < Base
extend AutoCorrector
MSG = 'Do not use `::` for defining class methods.'
def on_defs(node)
return unless node.loc.operator.source == '::'
add_offense(node.loc.operator) do |corrector|
corrector.replace(node.loc.operator, '.')
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/guard_clause.rb | lib/rubocop/cop/style/guard_clause.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Use a guard clause instead of wrapping the code inside a conditional
# expression
#
# A condition with an `elsif` or `else` branch is allowed unless
# one of `return`, `break`, `next`, `raise`, or `fail` is used
# in the body of the conditional expression.
#
# NOTE: Autocorrect works in most cases except with if-else statements
# that contain logical operators such as `foo || raise('exception')`
#
# @example
# # bad
# def test
# if something
# work
# end
# end
#
# # good
# def test
# return unless something
#
# work
# end
#
# # also good
# def test
# work if something
# end
#
# # bad
# if something
# raise 'exception'
# else
# ok
# end
#
# # good
# raise 'exception' if something
# ok
#
# # bad
# define_method(:test) do
# if something
# work
# end
# end
#
# # good
# define_method(:test) do
# return unless something
#
# work
# end
#
# # also good
# define_method(:test) do
# work if something
# end
#
# @example AllowConsecutiveConditionals: false (default)
# # bad
# def test
# if foo?
# work
# end
#
# if bar? # <- reports an offense
# work
# end
# end
#
# @example AllowConsecutiveConditionals: true
# # good
# def test
# if foo?
# work
# end
#
# if bar?
# work
# end
# end
#
# # bad
# def test
# if foo?
# work
# end
#
# do_something
#
# if bar? # <- reports an offense
# work
# end
# end
#
class GuardClause < Base
extend AutoCorrector
include RangeHelp
include MinBodyLength
include StatementModifier
MSG = 'Use a guard clause (`%<example>s`) instead of wrapping the ' \
'code inside a conditional expression.'
def on_def(node)
body = node.body
return unless body
check_ending_body(body)
end
alias on_defs on_def
def on_block(node)
return unless node.method?(:define_method) || node.method?(:define_singleton_method)
on_def(node)
end
alias on_numblock on_block
alias on_itblock on_block
def on_if(node)
return if accepted_form?(node)
if (guard_clause = node.if_branch&.guard_clause?)
kw = node.loc.keyword.source
guard = :if
elsif (guard_clause = node.else_branch&.guard_clause?)
kw = node.inverse_keyword
guard = :else
else
return
end
guard = nil if and_or_guard_clause?(guard_clause)
register_offense(node, guard_clause_source(guard_clause), kw, guard)
end
private
def check_ending_body(body)
return if body.nil?
if body.if_type?
check_ending_if(body)
elsif body.begin_type?
final_expression = body.children.last
check_ending_if(final_expression) if final_expression&.if_type?
end
end
def check_ending_if(node)
return if accepted_form?(node, ending: true) || !min_body_length?(node)
return if allowed_consecutive_conditionals? &&
consecutive_conditionals?(node.parent, node)
register_offense(node, 'return', node.inverse_keyword)
check_ending_body(node.if_branch)
end
def consecutive_conditionals?(parent, node)
parent.each_child_node.inject(false) do |if_type, child|
break if_type if node == child
child.if_type?
end
end
def register_offense(node, scope_exiting_keyword, conditional_keyword, guard = nil)
condition, = node.node_parts
example = [scope_exiting_keyword, conditional_keyword, condition.source].join(' ')
if too_long_for_single_line?(node, example)
return if trivial?(node)
example = "#{conditional_keyword} #{condition.source}; #{scope_exiting_keyword}; end"
replacement = <<~RUBY.chomp
#{conditional_keyword} #{condition.source}
#{scope_exiting_keyword}
end
RUBY
end
add_offense(node.loc.keyword, message: format(MSG, example: example)) do |corrector|
next if node.else? && guard.nil?
autocorrect(corrector, node, condition, replacement || example, guard)
end
end
# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def autocorrect(corrector, node, condition, replacement, guard)
corrector.replace(node.loc.keyword.join(condition.source_range), replacement)
if_branch = node.if_branch
else_branch = node.else_branch
corrector.replace(node.loc.begin, "\n") if node.then?
if if_branch&.send_type? && heredoc?(if_branch.last_argument)
autocorrect_heredoc_argument(corrector, node, if_branch, else_branch, guard)
elsif else_branch&.send_type? && heredoc?(else_branch.last_argument)
autocorrect_heredoc_argument(corrector, node, else_branch, if_branch, guard)
else
corrector.remove(node.loc.end)
return unless node.else?
corrector.remove(node.loc.else)
corrector.remove(range_of_branch_to_remove(node, guard))
end
end
# rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def heredoc?(argument)
argument.respond_to?(:heredoc?) && argument.heredoc?
end
def autocorrect_heredoc_argument(corrector, node, heredoc_branch, leave_branch, guard)
remove_whole_lines(corrector, node.loc.end)
return unless node.else?
remove_whole_lines(corrector, leave_branch.source_range)
remove_whole_lines(corrector, node.loc.else)
remove_whole_lines(corrector, range_of_branch_to_remove(node, guard))
corrector.insert_after(
heredoc_branch.last_argument.loc.heredoc_end, "\n#{leave_branch.source}"
)
end
def range_of_branch_to_remove(node, guard)
branch = case guard
when :if then node.if_branch
when :else then node.else_branch
end
branch.source_range
end
def guard_clause_source(guard_clause)
if and_or_guard_clause?(guard_clause)
guard_clause.parent.source
else
guard_clause.source
end
end
def and_or_guard_clause?(guard_clause)
parent = guard_clause.parent
parent.operator_keyword?
end
def too_long_for_single_line?(node, example)
max = max_line_length
max && node.source_range.column + example.length > max
end
def accepted_form?(node, ending: false)
accepted_if?(node, ending) || node.condition.multiline? || node.parent&.assignment?
end
def trivial?(node)
return false unless node.if_branch
node.branches.one? && !node.if_branch.if_type? && !node.if_branch.begin_type?
end
def accepted_if?(node, ending)
return true if node.modifier_form? || node.ternary? || node.elsif_conditional? ||
assigned_lvar_used_in_if_branch?(node)
if ending
node.else?
else
!node.else? || node.elsif?
end
end
def assigned_lvar_used_in_if_branch?(node)
return false unless (if_branch = node.if_branch)
assigned_lvars_in_condition = node.condition.each_descendant(:lvasgn).map do |lvasgn|
lvar_name, = *lvasgn
lvar_name.to_s
end
used_lvars_in_branch = if_branch.each_descendant(:lvar).map(&:source) || []
(assigned_lvars_in_condition & used_lvars_in_branch).any?
end
def remove_whole_lines(corrector, range)
corrector.remove(range_by_whole_lines(range, include_final_newline: true))
end
def allowed_consecutive_conditionals?
cop_config.fetch('AllowConsecutiveConditionals', false)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/not.rb | lib/rubocop/cop/style/not.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for uses of the keyword `not` instead of `!`.
#
# @example
#
# # bad - parentheses are required because of op precedence
# x = (not something)
#
# # good
# x = !something
#
class Not < Base
include RangeHelp
extend AutoCorrector
MSG = 'Use `!` instead of `not`.'
RESTRICT_ON_SEND = %i[!].freeze
OPPOSITE_METHODS = {
:== => :!=,
:!= => :==,
:<= => :>,
:> => :<=,
:< => :>=,
:>= => :<
}.freeze
def on_send(node)
return unless node.prefix_not?
add_offense(node.loc.selector) do |corrector|
range = range_with_surrounding_space(node.loc.selector, side: :right)
if opposite_method?(node.receiver)
correct_opposite_method(corrector, range, node.receiver)
elsif requires_parens?(node.receiver)
correct_with_parens(corrector, range, node)
else
correct_without_parens(corrector, range)
end
end
end
private
def opposite_method?(child)
child.send_type? && OPPOSITE_METHODS.key?(child.method_name)
end
def requires_parens?(child)
child.operator_keyword? ||
(child.send_type? && child.binary_operation?) ||
(child.if_type? && child.ternary?)
end
def correct_opposite_method(corrector, range, child)
corrector.remove(range)
corrector.replace(child.loc.selector, OPPOSITE_METHODS[child.method_name].to_s)
end
def correct_with_parens(corrector, range, node)
corrector.replace(range, '!(')
corrector.insert_after(node, ')')
end
def correct_without_parens(corrector, range)
corrector.replace(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/style/hash_conversion.rb | lib/rubocop/cop/style/hash_conversion.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks the usage of pre-2.1 `Hash[args]` method of converting enumerables and
# sequences of values to hashes.
#
# Correction code from splat argument (`Hash[*ary]`) is not simply determined. For example,
# `Hash[*ary]` can be replaced with `ary.each_slice(2).to_h` but it will be complicated.
# So, `AllowSplatArgument` option is true by default to allow splat argument for simple code.
#
# @safety
# This cop's autocorrection is unsafe because `ArgumentError` occurs
# if the number of elements is odd:
#
# [source,ruby]
# ----
# Hash[[[1, 2], [3]]] #=> {1=>2, 3=>nil}
# [[1, 2], [5]].to_h #=> wrong array length at 1 (expected 2, was 1) (ArgumentError)
# ----
#
# @example
# # bad
# Hash[ary]
#
# # good
# ary.to_h
#
# # bad
# Hash[key1, value1, key2, value2]
#
# # good
# {key1 => value1, key2 => value2}
#
# @example AllowSplatArgument: true (default)
# # good
# Hash[*ary]
#
# @example AllowSplatArgument: false
# # bad
# Hash[*ary]
#
class HashConversion < Base
extend AutoCorrector
MSG_TO_H = 'Prefer `ary.to_h` to `Hash[ary]`.'
MSG_LITERAL_MULTI_ARG = 'Prefer literal hash to `Hash[arg1, arg2, ...]`.'
MSG_LITERAL_HASH_ARG = 'Prefer literal hash to `Hash[key: value, ...]`.'
MSG_SPLAT = 'Prefer `array_of_pairs.to_h` to `Hash[*array]`.'
RESTRICT_ON_SEND = %i[[]].freeze
# @!method hash_from_array?(node)
def_node_matcher :hash_from_array?, '(send (const {nil? cbase} :Hash) :[] ...)'
def on_send(node)
return if part_of_ignored_node?(node) || !hash_from_array?(node)
# There are several cases:
# If there is one argument:
# Hash[ary] => ary.to_h
# Hash[*ary] => don't suggest corrections
# If there is 0 or 2+ arguments:
# Hash[a1, a2, a3, a4] => {a1 => a2, a3 => a4}
# ...but don't suggest correction if there is odd number of them (it is a bug)
node.arguments.one? ? single_argument(node) : multi_argument(node)
ignore_node(node)
end
private
def single_argument(node)
first_argument = node.first_argument
if first_argument.hash_type?
register_offense_for_hash(node, first_argument)
elsif first_argument.splat_type?
add_offense(node, message: MSG_SPLAT) unless allowed_splat_argument?
elsif use_zip_method_without_argument?(first_argument)
register_offense_for_zip_method(node, first_argument)
else
add_offense(node, message: MSG_TO_H) do |corrector|
replacement = first_argument.source
replacement = "(#{replacement})" if requires_parens?(first_argument)
corrector.replace(node, "#{replacement}.to_h")
end
end
end
def use_zip_method_without_argument?(first_argument)
return false unless first_argument&.send_type?
first_argument.method?(:zip) && first_argument.arguments.empty?
end
def register_offense_for_hash(node, hash_argument)
add_offense(node, message: MSG_LITERAL_HASH_ARG) do |corrector|
corrector.replace(node, "{#{hash_argument.source}}")
parent = node.parent
add_parentheses(parent, corrector) if parent&.send_type? && !parent.parenthesized?
end
end
def register_offense_for_zip_method(node, zip_method)
add_offense(node, message: MSG_TO_H) do |corrector|
if zip_method.parenthesized?
corrector.insert_before(zip_method.loc.end, '[]')
else
corrector.insert_after(zip_method, '([])')
end
end
end
def requires_parens?(node)
if node.call_type?
return false if node.method?(:[])
return true if node.arguments.any? && !node.parenthesized?
end
node.operator_keyword?
end
def multi_argument(node)
if node.arguments.count.odd?
add_offense(node, message: MSG_LITERAL_MULTI_ARG)
else
add_offense(node, message: MSG_LITERAL_MULTI_ARG) do |corrector|
corrector.replace(node, args_to_hash(node.arguments))
parent = node.parent
if parent&.send_type? && !parent.method?(:to_h) && !parent.parenthesized?
add_parentheses(parent, corrector)
end
end
end
end
def args_to_hash(args)
content = args.each_slice(2)
.map { |arg1, arg2| "#{arg1.source} => #{arg2.source}" }
.join(', ')
"{#{content}}"
end
def allowed_splat_argument?
cop_config.fetch('AllowSplatArgument', true)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/implicit_runtime_error.rb | lib/rubocop/cop/style/implicit_runtime_error.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for `raise` or `fail` statements which do not specify an
# explicit exception class. (This raises a `RuntimeError`. Some projects
# might prefer to use exception classes which more precisely identify the
# nature of the error.)
#
# @example
# # bad
# raise 'Error message here'
#
# # good
# raise ArgumentError, 'Error message here'
class ImplicitRuntimeError < Base
MSG = 'Use `%<method>s` with an explicit exception class and message, ' \
'rather than just a message.'
RESTRICT_ON_SEND = %i[raise fail].freeze
# @!method implicit_runtime_error_raise_or_fail(node)
def_node_matcher :implicit_runtime_error_raise_or_fail,
'(send nil? ${:raise :fail} {str dstr})'
def on_send(node)
implicit_runtime_error_raise_or_fail(node) do |method|
add_offense(node, message: format(MSG, method: 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/style/redundant_file_extension_in_require.rb | lib/rubocop/cop/style/redundant_file_extension_in_require.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for the presence of superfluous `.rb` extension in
# the filename provided to `require` and `require_relative`.
#
# NOTE: If the extension is omitted, Ruby tries adding '.rb', '.so',
# and so on to the name until found. If the file named cannot be found,
# a `LoadError` will be raised.
# There is an edge case where `foo.so` file is loaded instead of a `LoadError`
# if `foo.so` file exists when `require 'foo.rb'` will be changed to `require 'foo'`,
# but that seems harmless.
#
# @example
# # bad
# require 'foo.rb'
# require_relative '../foo.rb'
#
# # good
# require 'foo'
# require 'foo.so'
# require_relative '../foo'
# require_relative '../foo.so'
#
class RedundantFileExtensionInRequire < Base
include RangeHelp
extend AutoCorrector
MSG = 'Redundant `.rb` file extension detected.'
RESTRICT_ON_SEND = %i[require require_relative].freeze
# @!method require_call?(node)
def_node_matcher :require_call?, <<~PATTERN
(send nil? {:require :require_relative} $str_type?)
PATTERN
def on_send(node)
require_call?(node) do |name_node|
return unless name_node.value.end_with?('.rb')
extension_range = extension_range(name_node)
add_offense(extension_range) do |corrector|
corrector.remove(extension_range)
end
end
end
private
def extension_range(name_node)
end_of_path_string = name_node.source_range.end_pos
range_between(end_of_path_string - 4, end_of_path_string - 1)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/file_empty.rb | lib/rubocop/cop/style/file_empty.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Prefer to use `File.empty?('path/to/file')` when checking if a file is empty.
#
# @safety
# This cop is unsafe, because `File.size`, `File.read`, and `File.binread`
# raise `ENOENT` exception when there is no file corresponding to the path,
# while `File.empty?` does not raise an exception.
#
# @example
# # bad
# File.zero?('path/to/file')
# File.size('path/to/file') == 0
# File.size('path/to/file') >= 0
# File.size('path/to/file').zero?
# File.read('path/to/file').empty?
# File.binread('path/to/file') == ''
# FileTest.zero?('path/to/file')
#
# # good
# File.empty?('path/to/file')
# FileTest.empty?('path/to/file')
#
class FileEmpty < Base
extend AutoCorrector
extend TargetRubyVersion
MSG = 'Use `%<file_class>s.empty?(%<arg>s)` instead.'
RESTRICT_ON_SEND = %i[>= != == zero? empty?].freeze
minimum_target_ruby_version 2.4
# @!method offensive?(node)
def_node_matcher :offensive?, <<~PATTERN
{
(send $(const {nil? cbase} {:File :FileTest}) :zero? $_)
(send (send $(const {nil? cbase} {:File :FileTest}) :size $_) {:== :>=} (int 0))
(send (send (send $(const {nil? cbase} {:File :FileTest}) :size $_) :!) {:== :>=} (int 0))
(send (send $(const {nil? cbase} {:File :FileTest}) :size $_) :zero?)
(send (send $(const {nil? cbase} {:File :FileTest}) {:read :binread} $_) {:!= :==} (str empty?))
(send (send (send $(const {nil? cbase} {:File :FileTest}) {:read :binread} $_) :!) {:!= :==} (str empty?))
(send (send $(const {nil? cbase} {:File :FileTest}) {:read :binread} $_) :empty?)
}
PATTERN
def on_send(node)
offensive?(node) do |const_node, arg_node|
add_offense(node,
message: format(MSG, file_class: const_node.source,
arg: arg_node.source)) do |corrector|
corrector.replace(node,
"#{bang(node)}#{const_node.source}.empty?(#{arg_node.source})")
end
end
end
private
def bang(node)
if (node.method?(:==) && node.child_nodes.first.method?(:!)) ||
(%i[>= !=].include?(node.method_name) && !node.child_nodes.first.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/style/trailing_body_on_module.rb | lib/rubocop/cop/style/trailing_body_on_module.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for trailing code after the module definition.
#
# @example
# # bad
# module Foo extend self
# end
#
# # good
# module Foo
# extend self
# end
#
class TrailingBodyOnModule < Base
include Alignment
include TrailingBody
extend AutoCorrector
MSG = 'Place the first line of module body on its own line.'
def on_module(node)
return unless trailing_body?(node)
add_offense(first_part_of(node.to_a.last)) do |corrector|
LineBreakCorrector.correct_trailing_body(
configured_width: configured_indentation_width,
corrector: corrector,
node: node,
processed_source: processed_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/style/empty_heredoc.rb | lib/rubocop/cop/style/empty_heredoc.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for using empty heredoc to reduce redundancy.
#
# @example
#
# # bad
# <<~EOS
# EOS
#
# <<-EOS
# EOS
#
# <<EOS
# EOS
#
# # good
# ''
#
# # bad
# do_something(<<~EOS)
# EOS
#
# do_something(<<-EOS)
# EOS
#
# do_something(<<EOS)
# EOS
#
# # good
# do_something('')
#
class EmptyHeredoc < Base
include Heredoc
include RangeHelp
include StringLiteralsHelp
extend AutoCorrector
MSG = 'Use an empty string literal instead of heredoc.'
def on_heredoc(node)
heredoc_body = node.loc.heredoc_body
return unless heredoc_body.source.empty?
add_offense(node) do |corrector|
heredoc_end = node.loc.heredoc_end
corrector.replace(node, preferred_string_literal)
corrector.remove(range_by_whole_lines(heredoc_body, include_final_newline: true))
corrector.remove(range_by_whole_lines(heredoc_end, include_final_newline: true))
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/signal_exception.rb | lib/rubocop/cop/style/signal_exception.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for uses of `fail` and `raise`.
#
# @example EnforcedStyle: only_raise (default)
# # The `only_raise` style enforces the sole use of `raise`.
# # bad
# begin
# fail
# rescue Exception
# # handle it
# end
#
# def watch_out
# fail
# rescue Exception
# # handle it
# end
#
# Kernel.fail
#
# # good
# begin
# raise
# rescue Exception
# # handle it
# end
#
# def watch_out
# raise
# rescue Exception
# # handle it
# end
#
# Kernel.raise
#
# @example EnforcedStyle: only_fail
# # The `only_fail` style enforces the sole use of `fail`.
# # bad
# begin
# raise
# rescue Exception
# # handle it
# end
#
# def watch_out
# raise
# rescue Exception
# # handle it
# end
#
# Kernel.raise
#
# # good
# begin
# fail
# rescue Exception
# # handle it
# end
#
# def watch_out
# fail
# rescue Exception
# # handle it
# end
#
# Kernel.fail
#
# @example EnforcedStyle: semantic
# # The `semantic` style enforces the use of `fail` to signal an
# # exception, then will use `raise` to trigger an offense after
# # it has been rescued.
# # bad
# begin
# raise
# rescue Exception
# # handle it
# end
#
# def watch_out
# # Error thrown
# rescue Exception
# fail
# end
#
# Kernel.fail
# Kernel.raise
#
# # good
# begin
# fail
# rescue Exception
# # handle it
# end
#
# def watch_out
# fail
# rescue Exception
# raise 'Preferably with descriptive message'
# end
#
# explicit_receiver.fail
# explicit_receiver.raise
class SignalException < Base
include ConfigurableEnforcedStyle
extend AutoCorrector
FAIL_MSG = 'Use `fail` instead of `raise` to signal exceptions.'
RAISE_MSG = 'Use `raise` instead of `fail` to rethrow exceptions.'
RESTRICT_ON_SEND = %i[raise fail].freeze
# @!method kernel_call?(node, name)
def_node_matcher :kernel_call?, '(send (const {nil? cbase} :Kernel) %1 ...)'
# @!method custom_fail_methods(node)
def_node_search :custom_fail_methods, '{(def :fail ...) (defs _ :fail ...)}'
def on_rescue(node)
return unless style == :semantic
check_scope(:raise, node.body)
node.resbody_branches.each do |rescue_node|
check_scope(:fail, rescue_node)
allow(:raise, rescue_node)
end
end
def on_send(node)
case style
when :semantic
check_send(:raise, node) unless ignored_node?(node)
when :only_raise
return if custom_fail_defined?
check_send(:fail, node)
when :only_fail
check_send(:raise, node)
end
end
private
def custom_fail_defined?
return @custom_fail_defined if defined?(@custom_fail_defined)
ast = processed_source.ast
@custom_fail_defined = ast && custom_fail_methods(ast).any?
end
def message(method_name)
case style
when :semantic
method_name == :fail ? RAISE_MSG : FAIL_MSG
when :only_raise
'Always use `raise` to signal exceptions.'
when :only_fail
'Always use `fail` to signal exceptions.'
end
end
def check_scope(method_name, node)
return unless node
each_command_or_kernel_call(method_name, node) do |send_node|
next if ignored_node?(send_node)
add_offense(send_node.loc.selector, message: message(method_name)) do |corrector|
autocorrect(corrector, send_node)
end
ignore_node(send_node)
end
end
def check_send(method_name, node)
return unless node && command_or_kernel_call?(method_name, node)
add_offense(node.loc.selector, message: message(method_name)) do |corrector|
autocorrect(corrector, node)
end
end
def autocorrect(corrector, node)
name =
case style
when :semantic
command_or_kernel_call?(:raise, node) ? 'fail' : 'raise'
when :only_raise then 'raise'
when :only_fail then 'fail'
end
corrector.replace(node.loc.selector, name)
end
def command_or_kernel_call?(name, node)
return false unless node.method?(name)
node.command?(name) || kernel_call?(node, name)
end
def allow(method_name, node)
each_command_or_kernel_call(method_name, node) { |send_node| ignore_node(send_node) }
end
def each_command_or_kernel_call(method_name, node)
on_node(:send, node, :rescue) do |send_node|
yield send_node if command_or_kernel_call?(method_name, send_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/style/single_line_do_end_block.rb | lib/rubocop/cop/style/single_line_do_end_block.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for single-line `do`...`end` block.
#
# In practice a single line `do`...`end` is autocorrected when `EnforcedStyle: semantic`
# is configured for `Style/BlockDelimiters`. The autocorrection maintains the
# `do` ... `end` syntax to preserve semantics and does not change it to `{`...`}` block.
#
# NOTE: If `InspectBlocks` is set to `true` for `Layout/RedundantLineBreak`, blocks will
# be autocorrected to be on a single line if possible. This cop respects that configuration
# by not registering an offense if it would subsequently cause a
# `Layout/RedundantLineBreak` offense.
#
# @example
#
# # bad
# foo do |arg| bar(arg) end
#
# # good
# foo do |arg|
# bar(arg)
# end
#
# # bad
# ->(arg) do bar(arg) end
#
# # good
# ->(arg) { bar(arg) }
#
class SingleLineDoEndBlock < Base
extend AutoCorrector
include CheckSingleLineSuitability
MSG = 'Prefer multiline `do`...`end` block.'
# rubocop:disable Metrics/AbcSize
def on_block(node)
return if !node.single_line? || node.braces?
return if single_line_blocks_preferred? && suitable_as_single_line?(node)
add_offense(node) do |corrector|
corrector.insert_after(do_line(node), "\n")
node_body = node.body
if node_body.respond_to?(:heredoc?) && node_body.heredoc?
corrector.remove(node.loc.end)
corrector.insert_after(node_body.loc.heredoc_end, "\nend")
else
corrector.insert_before(node.loc.end, "\n")
end
end
end
# rubocop:enable Metrics/AbcSize
alias on_numblock on_block
alias on_itblock on_block
private
def do_line(node)
if node.type?(:numblock, :itblock) ||
node.arguments.children.empty? || node.send_node.lambda_literal?
node.loc.begin
else
node.arguments
end
end
def single_line_blocks_preferred?
@config.for_enabled_cop('Layout/RedundantLineBreak')['InspectBlocks']
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/map_compact_with_conditional_block.rb | lib/rubocop/cop/style/map_compact_with_conditional_block.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Prefer `select` or `reject` over `map { ... }.compact`.
# This cop also handles `filter_map { ... }`, similar to `map { ... }.compact`.
#
# @example
#
# # bad
# array.map { |e| some_condition? ? e : next }.compact
#
# # bad
# array.filter_map { |e| some_condition? ? e : next }
#
# # bad
# array.map do |e|
# if some_condition?
# e
# else
# next
# end
# end.compact
#
# # bad
# array.map do |e|
# next if some_condition?
#
# e
# end.compact
#
# # bad
# array.map do |e|
# e if some_condition?
# end.compact
#
# # good
# array.select { |e| some_condition? }
#
# # good
# array.reject { |e| some_condition? }
#
class MapCompactWithConditionalBlock < Base
extend AutoCorrector
MSG = 'Replace `%<current>s` with `%<method>s`.'
RESTRICT_ON_SEND = %i[compact filter_map].freeze
# @!method conditional_block(node)
def_node_matcher :conditional_block, <<~RUBY
(block
(call _ {:map :filter_map})
(args
$(arg _))
{
(if $_ $(lvar _) {next nil?})
(if $_ {next nil?} $(lvar _))
(if $_ (next $(lvar _)) {next nil nil?})
(if $_ {next nil nil?} (next $(lvar _)))
(begin
{
(if $_ next nil?)
(if $_ nil? next)
}
$(lvar _))
(begin
{
(if $_ (next $(lvar _)) nil?)
(if $_ nil? (next $(lvar _)))
}
(nil))
})
RUBY
def on_send(node)
map_candidate = node.children.first
if (block_argument, condition, return_value = conditional_block(map_candidate))
return unless node.method?(:compact) && node.arguments.empty?
range = map_with_compact_range(node)
elsif (block_argument, condition, return_value = conditional_block(node.parent))
return unless node.method?(:filter_map)
range = filter_map_range(node)
else
return
end
inspect(node, block_argument, condition, return_value, range)
end
alias on_csend on_send
private
def inspect(node, block_argument_node, condition_node, return_value_node, range)
return unless returns_block_argument?(block_argument_node, return_value_node)
return if condition_node.parent.elsif?
method = truthy_branch?(return_value_node) ? 'select' : 'reject'
current = current(node)
add_offense(range, message: format(MSG, current: current, method: method)) do |corrector|
return if part_of_ignored_node?(node) || ignored_node?(node)
corrector.replace(
range, "#{method} { |#{block_argument_node.source}| #{condition_node.source} }"
)
ignore_node(node)
end
end
def returns_block_argument?(block_argument_node, return_value_node)
block_argument_node.name == return_value_node.children.first
end
def truthy_branch?(node)
if node.parent.begin_type?
truthy_branch_for_guard?(node)
elsif node.parent.next_type?
truthy_branch_for_if?(node.parent)
else
truthy_branch_for_if?(node)
end
end
def truthy_branch_for_if?(node)
if_node = node.parent
if if_node.if? || if_node.ternary?
if_node.if_branch == node
elsif if_node.unless?
if_node.else_branch == node
end
end
def truthy_branch_for_guard?(node)
if_node = node.left_sibling
if if_node.if?
if_node.if_branch.arguments.any?
else
if_node.if_branch.arguments.none?
end
end
def current(node)
if node.method?(:compact)
map_or_filter_map_method = node.children.first
"#{map_or_filter_map_method.method_name} { ... }.compact"
else
'filter_map { ... }'
end
end
def map_with_compact_range(node)
node.receiver.send_node.loc.selector.begin.join(node.source_range.end)
end
def filter_map_range(node)
node.loc.selector.join(node.parent.source_range.end)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/disable_cops_within_source_code_directive.rb | lib/rubocop/cop/style/disable_cops_within_source_code_directive.rb | # frozen_string_literal: true
# rubocop:disable Lint/RedundantCopDisableDirective
module RuboCop
module Cop
module Style
# Detects comments to enable/disable RuboCop.
# This is useful if want to make sure that every RuboCop error gets fixed
# and not quickly disabled with a comment.
#
# Specific cops can be allowed with the `AllowedCops` configuration. Note that
# if this configuration is set, `rubocop:disable all` is still disallowed.
#
# @example
# # bad
# # rubocop:disable Metrics/AbcSize
# def foo
# end
# # rubocop:enable Metrics/AbcSize
#
# # good
# def foo
# end
#
# @example AllowedCops: [Metrics/AbcSize]
# # good
# # rubocop:disable Metrics/AbcSize
# def foo
# end
# # rubocop:enable Metrics/AbcSize
#
class DisableCopsWithinSourceCodeDirective < Base
extend AutoCorrector
# rubocop:enable Lint/RedundantCopDisableDirective
MSG = 'RuboCop disable/enable directives are not permitted.'
MSG_FOR_COPS = 'RuboCop disable/enable directives for %<cops>s are not permitted.'
def on_new_investigation
processed_source.comments.each do |comment|
directive_cops = directive_cops(comment)
disallowed_cops = directive_cops - allowed_cops
next unless disallowed_cops.any?
register_offense(comment, directive_cops, disallowed_cops)
end
end
private
def register_offense(comment, directive_cops, disallowed_cops)
message = if any_cops_allowed?
format(MSG_FOR_COPS, cops: "`#{disallowed_cops.join('`, `')}`")
else
MSG
end
add_offense(comment, message: message) do |corrector|
replacement = ''
if directive_cops.length != disallowed_cops.length
replacement = comment.text.sub(/#{Regexp.union(disallowed_cops)},?\s*/, '')
.sub(/,\s*$/, '')
end
corrector.replace(comment, replacement)
end
end
def directive_cops(comment)
match_captures = DirectiveComment.new(comment).match_captures
match_captures && match_captures[1] ? match_captures[1].split(',').map(&:strip) : []
end
def allowed_cops
Array(cop_config['AllowedCops'])
end
def any_cops_allowed?
allowed_cops.any?
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/string_chars.rb | lib/rubocop/cop/style/string_chars.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for uses of `String#split` with empty string or regexp literal argument.
#
# @safety
# This cop is unsafe because it cannot be guaranteed that the receiver
# is actually a string. If another class has a `split` method with
# different behavior, it would be registered as a false positive.
#
# @example
# # bad
# string.split(//)
# string.split('')
#
# # good
# string.chars
#
class StringChars < Base
include RangeHelp
extend AutoCorrector
MSG = 'Use `chars` instead of `%<current>s`.'
RESTRICT_ON_SEND = %i[split].freeze
BAD_ARGUMENTS = %w[// '' ""].freeze
def on_send(node)
return unless node.arguments.one? && BAD_ARGUMENTS.include?(node.first_argument.source)
range = range_between(node.loc.selector.begin_pos, node.source_range.end_pos)
add_offense(range, message: format(MSG, current: range.source)) do |corrector|
corrector.replace(range, 'chars')
end
end
alias on_csend on_send
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/global_std_stream.rb | lib/rubocop/cop/style/global_std_stream.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Enforces the use of `$stdout/$stderr/$stdin` instead of `STDOUT/STDERR/STDIN`.
# `STDOUT/STDERR/STDIN` are constants, and while you can actually
# reassign (possibly to redirect some stream) constants in Ruby, you'll get
# an interpreter warning if you do so.
#
# Additionally, `$stdout/$stderr/$stdin` can safely be accessed in a Ractor because they
# are ractor-local, while `STDOUT/STDERR/STDIN` will raise `Ractor::IsolationError`.
#
# @safety
# Autocorrection is unsafe because `STDOUT` and `$stdout` may point to different
# objects, for example.
#
# @example
# # bad
# STDOUT.puts('hello')
#
# hash = { out: STDOUT, key: value }
#
# def m(out = STDOUT)
# out.puts('hello')
# end
#
# # good
# $stdout.puts('hello')
#
# hash = { out: $stdout, key: value }
#
# def m(out = $stdout)
# out.puts('hello')
# end
#
class GlobalStdStream < Base
extend AutoCorrector
MSG = 'Use `%<gvar_name>s` instead of `%<const_name>s`.'
STD_STREAMS = %i[STDIN STDOUT STDERR].to_set.freeze
# @!method const_to_gvar_assignment?(node, name)
def_node_matcher :const_to_gvar_assignment?, <<~PATTERN
(gvasgn %1 (const nil? _))
PATTERN
def on_const(node)
return if namespaced?(node)
const_name = node.short_name
return unless STD_STREAMS.include?(const_name)
gvar_name = gvar_name(const_name).to_sym
return if const_to_gvar_assignment?(node.parent, gvar_name)
add_offense(node, message: message(const_name)) do |corrector|
corrector.replace(node, gvar_name)
end
end
private
def message(const_name)
format(MSG, gvar_name: gvar_name(const_name), const_name: const_name)
end
def namespaced?(node)
!node.namespace.nil? && (node.relative? || !node.namespace.cbase_type?)
end
def gvar_name(const_name)
"$#{const_name.to_s.downcase}"
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/it_block_parameter.rb | lib/rubocop/cop/style/it_block_parameter.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for blocks with one argument where `it` block parameter can be used.
#
# It provides four `EnforcedStyle` options:
#
# 1. `allow_single_line` (default) ... Always uses the `it` block parameter in a single line.
# 2. `only_numbered_parameters` ... Detects only numbered block parameters.
# 3. `always` ... Always uses the `it` block parameter.
# 4. `disallow` ... Disallows the `it` block parameter.
#
# A single numbered parameter is detected when `allow_single_line`,
# `only_numbered_parameters`, or `always`.
#
# @example EnforcedStyle: allow_single_line (default)
# # bad
# block do
# do_something(it)
# end
# block { do_something(_1) }
#
# # good
# block { do_something(it) }
# block { |named_param| do_something(named_param) }
#
# @example EnforcedStyle: only_numbered_parameters
# # bad
# block { do_something(_1) }
#
# # good
# block { do_something(it) }
# block { |named_param| do_something(named_param) }
#
# @example EnforcedStyle: always
# # bad
# block { do_something(_1) }
# block { |named_param| do_something(named_param) }
#
# # good
# block { do_something(it) }
#
# @example EnforcedStyle: disallow
# # bad
# block { do_something(it) }
#
# # good
# block { do_something(_1) }
# block { |named_param| do_something(named_param) }
#
class ItBlockParameter < Base
include ConfigurableEnforcedStyle
extend TargetRubyVersion
extend AutoCorrector
MSG_USE_IT_PARAMETER = 'Use `it` block parameter.'
MSG_AVOID_IT_PARAMETER = 'Avoid using `it` block parameter.'
MSG_AVOID_IT_PARAMETER_MULTILINE = 'Avoid using `it` block parameter for multi-line blocks.'
minimum_target_ruby_version 3.4
def on_block(node)
return unless style == :always
return unless node.arguments.one?
# `restarg`, `kwrestarg`, `blockarg` nodes can return early.
return unless node.first_argument.arg_type?
variables = find_block_variables(node, node.first_argument.source)
variables.each do |variable|
add_offense(variable, message: MSG_USE_IT_PARAMETER) do |corrector|
corrector.remove(node.arguments)
corrector.replace(variable, 'it')
end
end
end
def on_numblock(node)
return if style == :disallow
return unless node.children[1] == 1
variables = find_block_variables(node, '_1')
variables.each do |variable|
add_offense(variable, message: MSG_USE_IT_PARAMETER) do |corrector|
corrector.replace(variable, 'it')
end
end
end
def on_itblock(node)
case style
when :allow_single_line
return if node.single_line?
add_offense(node, message: MSG_AVOID_IT_PARAMETER_MULTILINE)
when :disallow
variables = find_block_variables(node, 'it')
variables.each do |variable|
add_offense(variable, message: MSG_AVOID_IT_PARAMETER)
end
end
end
private
def find_block_variables(node, block_argument_name)
return [] unless node.body
node.body.each_descendant(:lvar).select do |descendant|
descendant.source == block_argument_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/style/min_max.rb | lib/rubocop/cop/style/min_max.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for potential uses of `Enumerable#minmax`.
#
# @example
#
# # bad
# bar = [foo.min, foo.max]
# return foo.min, foo.max
#
# # good
# bar = foo.minmax
# return foo.minmax
class MinMax < Base
extend AutoCorrector
MSG = 'Use `%<receiver>s.minmax` instead of `%<offender>s`.'
def on_array(node)
min_max_candidate(node) do |receiver|
offender = offending_range(node)
add_offense(offender, message: message(offender, receiver)) do |corrector|
receiver = node.children.first.receiver
corrector.replace(offending_range(node), "#{receiver.source}.minmax")
end
end
end
alias on_return on_array
private
# @!method min_max_candidate(node)
def_node_matcher :min_max_candidate, <<~PATTERN
({array return} (send [$_receiver !nil?] :min) (send [$_receiver !nil?] :max))
PATTERN
def message(offender, receiver)
format(MSG, offender: offender.source, receiver: receiver.source)
end
def offending_range(node)
case node.type
when :return
argument_range(node)
else
node.source_range
end
end
def argument_range(node)
first_argument_range = node.children.first.source_range
last_argument_range = node.children.last.source_range
first_argument_range.join(last_argument_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/style/redundant_begin.rb | lib/rubocop/cop/style/redundant_begin.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for redundant `begin` blocks.
#
# Currently it checks for code like this:
#
# @example
#
# # bad
# def redundant
# begin
# ala
# bala
# rescue StandardError => e
# something
# end
# end
#
# # good
# def preferred
# ala
# bala
# rescue StandardError => e
# something
# end
#
# # bad
# begin
# do_something
# end
#
# # good
# do_something
#
# # bad
# # When using Ruby 2.5 or later.
# do_something do
# begin
# something
# rescue => ex
# anything
# end
# end
#
# # good
# # In Ruby 2.5 or later, you can omit `begin` in `do-end` block.
# do_something do
# something
# rescue => ex
# anything
# end
#
# # good
# # Stabby lambdas don't support implicit `begin` in `do-end` blocks.
# -> do
# begin
# foo
# rescue Bar
# baz
# end
# end
class RedundantBegin < Base
include RangeHelp
extend AutoCorrector
MSG = 'Redundant `begin` block detected.'
def self.autocorrect_incompatible_with
[Style::BlockDelimiters]
end
# @!method offensive_kwbegins(node)
def_node_search :offensive_kwbegins, <<~PATTERN
[(kwbegin ...) !#allowable_kwbegin?]
PATTERN
def on_def(node)
return unless node.body&.kwbegin_type?
return if node.endless?
register_offense(node.body)
end
alias on_defs on_def
def on_if(node)
return if node.modifier_form?
inspect_branches(node)
end
def on_case(node)
inspect_branches(node)
end
alias on_case_match on_case
def on_while(node)
return if node.modifier_form?
body = node.body
return unless body&.kwbegin_type?
return if body.rescue_node || body.ensure_node
register_offense(body)
end
alias on_until on_while
def on_block(node)
return if target_ruby_version < 2.5
return if node.send_node.lambda_literal?
return if node.braces?
return unless node.body&.kwbegin_type?
register_offense(node.body)
end
alias on_numblock on_block
alias on_itblock on_block
def on_kwbegin(node)
return unless (target_node = offensive_kwbegins(node).to_a.last)
register_offense(target_node)
end
private
def allowable_kwbegin?(node)
empty_begin?(node) ||
begin_block_has_multiline_statements?(node) ||
contain_rescue_or_ensure?(node) ||
valid_context_using_only_begin?(node)
end
def register_offense(node)
offense_range = node.loc.begin
add_offense(offense_range) do |corrector|
if node.parent&.assignment?
replace_begin_with_statement(corrector, offense_range, node)
else
remove_begin(corrector, offense_range, node)
end
if use_modifier_form_after_multiline_begin_block?(node)
correct_modifier_form_after_multiline_begin_block(corrector, node)
end
corrector.remove(node.loc.end)
end
end
def replace_begin_with_statement(corrector, offense_range, node)
first_child = node.children.first
source = first_child.source
source = "(#{source})" if first_child.if_type? && first_child.modifier_form?
corrector.replace(offense_range, source)
corrector.remove(range_between(offense_range.end_pos, first_child.source_range.end_pos))
restore_removed_comments(corrector, offense_range, node, first_child)
end
def remove_begin(corrector, offense_range, node)
if node.parent.respond_to?(:endless?) && node.parent.endless?
offense_range = range_with_surrounding_space(offense_range, newlines: true)
end
corrector.remove(offense_range)
end
# Restore comments that occur between "begin" and "first_child".
# These comments will be moved to above the assignment line.
def restore_removed_comments(corrector, offense_range, node, first_child)
comments_range = range_between(offense_range.end_pos, first_child.source_range.begin_pos)
comments = comments_range.source
corrector.insert_before(node.parent, comments) unless comments.blank?
end
def use_modifier_form_after_multiline_begin_block?(node)
return false unless (parent = node.parent)
node.multiline? && parent.if_type? && parent.modifier_form?
end
def correct_modifier_form_after_multiline_begin_block(corrector, node)
condition_range = condition_range(node.parent)
corrector.insert_after(node.children.first, " #{condition_range.source}")
corrector.remove(range_by_whole_lines(condition_range, include_final_newline: true))
end
def condition_range(node)
range_between(node.loc.keyword.begin_pos, node.condition.source_range.end_pos)
end
def empty_begin?(node)
node.children.empty?
end
def begin_block_has_multiline_statements?(node)
return false unless node.parent
node.children.count >= 2
end
def contain_rescue_or_ensure?(node)
first_child = node.children.first
first_child.type?(:rescue, :ensure)
end
def valid_context_using_only_begin?(node)
parent = node.parent
valid_begin_assignment?(node) || parent&.post_condition_loop? ||
parent&.send_type? || parent&.operator_keyword?
end
def valid_begin_assignment?(node)
node.parent&.assignment? && !node.children.one?
end
def inspect_branches(node)
node.branches.each do |branch|
next unless branch&.kwbegin_type?
next if branch.rescue_node || branch.ensure_node
register_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/style/stabby_lambda_parentheses.rb | lib/rubocop/cop/style/stabby_lambda_parentheses.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for parentheses around stabby lambda arguments.
# There are two different styles. Defaults to `require_parentheses`.
#
# @example EnforcedStyle: require_parentheses (default)
# # bad
# ->a,b,c { a + b + c }
#
# # good
# ->(a,b,c) { a + b + c}
#
# @example EnforcedStyle: require_no_parentheses
# # bad
# ->(a,b,c) { a + b + c }
#
# # good
# ->a,b,c { a + b + c}
class StabbyLambdaParentheses < Base
include ConfigurableEnforcedStyle
extend AutoCorrector
MSG_REQUIRE = 'Wrap stabby lambda arguments with parentheses.'
MSG_NO_REQUIRE = 'Do not wrap stabby lambda arguments with parentheses.'
def on_send(node)
return unless stabby_lambda_with_args?(node)
return unless redundant_parentheses?(node) || missing_parentheses?(node)
arguments = node.block_node.arguments
add_offense(arguments) do |corrector|
case style
when :require_parentheses
missing_parentheses_corrector(corrector, arguments)
when :require_no_parentheses
unwanted_parentheses_corrector(corrector, arguments)
end
end
end
private
def missing_parentheses?(node)
style == :require_parentheses && !parentheses?(node)
end
def redundant_parentheses?(node)
style == :require_no_parentheses && parentheses?(node)
end
def message(_node)
style == :require_parentheses ? MSG_REQUIRE : MSG_NO_REQUIRE
end
def missing_parentheses_corrector(corrector, node)
corrector.wrap(node, '(', ')')
end
def unwanted_parentheses_corrector(corrector, node)
args_loc = node.loc
corrector.replace(args_loc.begin, '')
corrector.remove(args_loc.end)
end
def stabby_lambda_with_args?(node)
node.lambda_literal? && node.block_node.arguments?
end
def parentheses?(node)
node.block_node.arguments.loc.begin
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_format.rb | lib/rubocop/cop/style/redundant_format.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for calls to `Kernel#format` or `Kernel#sprintf` that are redundant.
#
# Calling `format` with only a single string or constant argument is redundant,
# as it can be replaced by the string or constant itself.
#
# Also looks for `format` calls where the arguments are literals that can be
# inlined into a string easily. This applies to the `%s`, `%d`, `%i`, `%u`, and
# `%f` format specifiers.
#
# @safety
# This cop's autocorrection is unsafe because string object returned by
# `format` and `sprintf` are never frozen. If `format('string')` is autocorrected to
# `'string'`, `FrozenError` may occur when calling a destructive method like `String#<<`.
# Consider using `'string'.dup` instead of `format('string')`.
# Additionally, since the necessity of `dup` cannot be determined automatically,
# this autocorrection is inherently unsafe.
#
# [source,ruby]
# ----
# # frozen_string_literal: true
#
# format('template').frozen? # => false
# 'template'.frozen? # => true
# ----
#
# @example
#
# # bad
# format('the quick brown fox jumps over the lazy dog.')
# sprintf('the quick brown fox jumps over the lazy dog.')
#
# # good
# 'the quick brown fox jumps over the lazy dog.'
#
# # bad
# format(MESSAGE)
# sprintf(MESSAGE)
#
# # good
# MESSAGE
#
# # bad
# format('%s %s', 'foo', 'bar')
# sprintf('%s %s', 'foo', 'bar')
#
# # good
# 'foo bar'
#
class RedundantFormat < Base
extend AutoCorrector
MSG = 'Use `%<prefer>s` directly instead of `%<method_name>s`.'
RESTRICT_ON_SEND = %i[format sprintf].to_set.freeze
ACCEPTABLE_LITERAL_TYPES = %i[str dstr sym dsym numeric boolean nil].freeze
# @!method format_without_additional_args?(node)
def_node_matcher :format_without_additional_args?, <<~PATTERN
(send {(const {nil? cbase} :Kernel) nil?} %RESTRICT_ON_SEND ${str dstr const})
PATTERN
# @!method rational_number?(node)
def_node_matcher :rational_number?, <<~PATTERN
{rational (send int :/ rational) (begin rational) (begin (send int :/ rational))}
PATTERN
# @!method complex_number?(node)
def_node_matcher :complex_number?, <<~PATTERN
{complex (send int :+ complex) (begin complex) (begin (send int :+ complex))}
PATTERN
# @!method find_hash_value_node(node, name)
def_node_search :find_hash_value_node, <<~PATTERN
(pair (sym %1) $_)
PATTERN
# @!method splatted_arguments?(node)
def_node_matcher :splatted_arguments?, <<~PATTERN
(send _ %RESTRICT_ON_SEND <{
splat
(hash <kwsplat ...>)
} ...>)
PATTERN
def on_send(node)
format_without_additional_args?(node) do |value|
replacement = escape_control_chars(value.source)
add_offense(node, message: message(node, replacement)) do |corrector|
corrector.replace(node, replacement)
end
return
end
detect_unnecessary_fields(node)
end
private
def message(node, prefer)
format(MSG, prefer: prefer, method_name: node.method_name)
end
def detect_unnecessary_fields(node)
return unless node.first_argument&.str_type?
string = node.first_argument.value
arguments = node.arguments[1..]
return unless string && arguments.any?
return if splatted_arguments?(node)
register_all_fields_literal(node, string, arguments)
end
def register_all_fields_literal(node, string, arguments)
return unless all_fields_literal?(string, arguments.dup)
format_arguments = argument_values(arguments)
begin
formatted_string = format(string, *format_arguments)
rescue ArgumentError
return
end
replacement = quote(formatted_string, node)
add_offense(node, message: message(node, replacement)) do |corrector|
corrector.replace(node, replacement)
end
end
# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def all_fields_literal?(string, arguments)
count = 0
sequences = RuboCop::Cop::Utils::FormatString.new(string).format_sequences
return false unless sequences.any?
sequences.each do |sequence|
next if sequence.percent?
next if unknown_variable_width?(sequence, arguments)
hash = arguments.detect(&:hash_type?)
next unless (argument = find_argument(sequence, arguments, hash))
next unless matching_argument?(sequence, argument)
next if (sequence.width || sequence.precision) && argument.dstr_type?
count += 1
end
sequences.size == count
end
# rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
# If the sequence has a variable (`*`) width, it cannot be autocorrected
# if the width is not given as a numeric literal argument
def unknown_variable_width?(sequence, arguments)
return false unless sequence.variable_width?
argument = arguments[sequence.variable_width_argument_number - 1]
!numeric?(argument)
end
# rubocop:disable Metrics/AbcSize
def find_argument(sequence, arguments, hash)
if hash && (sequence.annotated? || sequence.template?)
find_hash_value_node(hash, sequence.name.to_sym).first
elsif sequence.variable_width?
# If the specifier contains `*`, the argument for the width can be ignored.
arguments.delete_at(sequence.variable_width_argument_number - 1)
arguments.shift
elsif sequence.arg_number
arguments[sequence.arg_number.to_i - 1]
else
arguments.shift
end
end
# rubocop:enable Metrics/AbcSize
def matching_argument?(sequence, argument)
# Template specifiers don't give a type, any acceptable literal type is ok.
return argument.type?(*ACCEPTABLE_LITERAL_TYPES) if sequence.template?
# An argument matches a specifier if it can be easily converted
# to that type.
case sequence.type
when 's'
argument.type?(*ACCEPTABLE_LITERAL_TYPES)
when 'd', 'i', 'u'
integer?(argument)
when 'f'
float?(argument)
else
false
end
end
def numeric?(argument)
argument.type?(:numeric, :str) ||
rational_number?(argument) ||
complex_number?(argument)
end
def integer?(argument)
numeric?(argument) && Integer(argument_value(argument), exception: false)
end
def float?(argument)
numeric?(argument) && Float(argument_value(argument), exception: false)
end
# Add correct quotes to the formatted string, preferring retaining the existing
# quotes if possible.
def quote(string, node)
str_node = node.first_argument
start_delimiter = str_node.loc.begin.source
end_delimiter = str_node.loc.end.source
# If there is any interpolation, the delimiters need to be changed potentially
if node.each_descendant(:dstr, :dsym).any?
case start_delimiter
when "'"
start_delimiter = end_delimiter = '"'
when /\A%q(.)/
start_delimiter = "%Q#{Regexp.last_match[1]}"
end
end
"#{start_delimiter}#{escape_control_chars(string)}#{end_delimiter}"
end
# Escape any control characters in the string (eg. `\t` or `\n` become `\\t` or `\\n`)
def escape_control_chars(string)
string.gsub(/\p{Cc}/) { |s| s.dump[1..-2] }
end
def argument_values(arguments)
arguments.map { |argument| argument_value(argument) }
end
def argument_value(argument)
argument = argument.children.first if argument.begin_type?
if argument.dsym_type?
dsym_value(argument)
elsif argument.hash_type?
hash_value(argument)
elsif rational_number?(argument)
rational_value(argument)
elsif complex_number?(argument)
complex_value(argument)
elsif argument.respond_to?(:value)
argument.value
else
argument.source
end
end
def dsym_value(dsym_node)
dsym_node.children.first.source
end
def hash_value(hash_node)
hash_node.each_pair.with_object({}) do |pair, hash|
hash[pair.key.value] = argument_value(pair.value)
end
end
def rational_value(rational_node)
rational_node.source.to_r
end
def complex_value(complex_node)
Complex(complex_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/style/empty_case_condition.rb | lib/rubocop/cop/style/empty_case_condition.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for case statements with an empty condition.
#
# @example
#
# # bad:
# case
# when x == 0
# puts 'x is 0'
# when y == 0
# puts 'y is 0'
# else
# puts 'neither is 0'
# end
#
# # good:
# if x == 0
# puts 'x is 0'
# elsif y == 0
# puts 'y is 0'
# else
# puts 'neither is 0'
# end
#
# # good: (the case condition node is not empty)
# case n
# when 0
# puts 'zero'
# when 1
# puts 'one'
# else
# puts 'more'
# end
class EmptyCaseCondition < Base
include RangeHelp
extend AutoCorrector
MSG = 'Do not use empty `case` condition, instead use an `if` expression.'
NOT_SUPPORTED_PARENT_TYPES = %i[return break next send csend].freeze
# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def on_case(case_node)
if case_node.condition || NOT_SUPPORTED_PARENT_TYPES.include?(case_node.parent&.type)
return
end
branch_bodies = [*case_node.when_branches.map(&:body), case_node.else_branch].compact
return if branch_bodies.any? do |body|
body.return_type? || body.each_descendant.any?(&:return_type?)
end
add_offense(case_node.loc.keyword) { |corrector| autocorrect(corrector, case_node) }
end
# rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
private
def autocorrect(corrector, case_node)
when_branches = case_node.when_branches
correct_case_when(corrector, case_node, when_branches)
correct_when_conditions(corrector, when_branches)
end
def correct_case_when(corrector, case_node, when_nodes)
case_range = case_node.loc.keyword.join(when_nodes.first.loc.keyword)
corrector.replace(case_range, 'if')
keep_first_when_comment(case_range, corrector)
when_nodes[1..].each do |when_node|
corrector.replace(when_node.loc.keyword, 'elsif')
end
end
def correct_when_conditions(corrector, when_nodes)
when_nodes.each do |when_node|
conditions = when_node.conditions
replace_then_with_line_break(corrector, conditions, when_node)
next unless conditions.size > 1
range = range_between(conditions.first.source_range.begin_pos,
conditions.last.source_range.end_pos)
corrector.replace(range, conditions.map(&:source).join(' || '))
end
end
def keep_first_when_comment(case_range, corrector)
indent = ' ' * case_range.column
comments = processed_source.each_comment_in_lines(
case_range.first_line...case_range.last_line
).map { |comment| "#{indent}#{comment.text}\n" }.join
line_beginning = case_range.adjust(begin_pos: -case_range.column)
corrector.insert_before(line_beginning, comments)
end
def replace_then_with_line_break(corrector, conditions, when_node)
return unless when_node.parent.parent && when_node.then?
range = range_between(conditions.last.source_range.end_pos, when_node.loc.begin.end_pos)
corrector.replace(range, "\n")
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/module_function.rb | lib/rubocop/cop/style/module_function.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for use of `extend self` or `module_function` in a module.
#
# Supported styles are: `module_function` (default), `extend_self` and `forbidden`.
#
# A couple of things to keep in mind:
#
# - `forbidden` style prohibits the usage of both styles
# - in default mode (`module_function`), the cop won't be activated when the module
# contains any private methods
#
# @safety
# Autocorrection is unsafe (and is disabled by default) because `extend self`
# and `module_function` do not behave exactly the same.
#
# @example EnforcedStyle: module_function (default)
# # bad
# module Test
# extend self
# # ...
# end
#
# # good
# module Test
# module_function
# # ...
# end
#
# # good
# module Test
# extend self
# # ...
# private
# # ...
# end
#
# # good
# module Test
# class << self
# # ...
# end
# end
#
# @example EnforcedStyle: extend_self
# # bad
# module Test
# module_function
# # ...
# end
#
# # good
# module Test
# extend self
# # ...
# end
#
# # good
# module Test
# class << self
# # ...
# end
# end
#
# @example EnforcedStyle: forbidden
# # bad
# module Test
# module_function
# # ...
# end
#
# # bad
# module Test
# extend self
# # ...
# end
#
# # bad
# module Test
# extend self
# # ...
# private
# # ...
# end
#
# # good
# module Test
# class << self
# # ...
# end
# end
class ModuleFunction < Base
include ConfigurableEnforcedStyle
extend AutoCorrector
MODULE_FUNCTION_MSG = 'Use `module_function` instead of `extend self`.'
EXTEND_SELF_MSG = 'Use `extend self` instead of `module_function`.'
FORBIDDEN_MSG = 'Do not use `module_function` or `extend self`.'
# @!method module_function_node?(node)
def_node_matcher :module_function_node?, '(send nil? :module_function)'
# @!method extend_self_node?(node)
def_node_matcher :extend_self_node?, '(send nil? :extend self)'
# @!method private_directive?(node)
def_node_matcher :private_directive?, '(send nil? :private ...)'
def on_module(node)
return unless node.body&.begin_type?
each_wrong_style(node.body.children) do |child_node|
add_offense(child_node) do |corrector|
next if style == :forbidden
if extend_self_node?(child_node)
corrector.replace(child_node, 'module_function')
else
corrector.replace(child_node, 'extend self')
end
end
end
end
private
def each_wrong_style(nodes, &block)
case style
when :module_function
check_module_function(nodes, &block)
when :extend_self
check_extend_self(nodes, &block)
when :forbidden
check_forbidden(nodes, &block)
end
end
def check_module_function(nodes)
return if nodes.any? { |node| private_directive?(node) }
nodes.each do |node|
yield node if extend_self_node?(node)
end
end
def check_extend_self(nodes)
nodes.each do |node|
yield node if module_function_node?(node)
end
end
def check_forbidden(nodes)
nodes.each do |node|
yield node if extend_self_node?(node)
yield node if module_function_node?(node)
end
end
def message(_range)
return FORBIDDEN_MSG if style == :forbidden
style == :module_function ? MODULE_FUNCTION_MSG : EXTEND_SELF_MSG
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/sample.rb | lib/rubocop/cop/style/sample.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Identifies usages of `shuffle.first`,
# `shuffle.last`, and `shuffle[]` and change them to use
# `sample` instead.
#
# @example
# # bad
# [1, 2, 3].shuffle.first
# [1, 2, 3].shuffle.first(2)
# [1, 2, 3].shuffle.last
# [2, 1, 3].shuffle.at(0)
# [2, 1, 3].shuffle.slice(0)
# [1, 2, 3].shuffle[2]
# [1, 2, 3].shuffle[0, 2] # sample(2) will do the same
# [1, 2, 3].shuffle[0..2] # sample(3) will do the same
# [1, 2, 3].shuffle(random: Random.new).first
#
# # good
# [1, 2, 3].shuffle
# [1, 2, 3].sample
# [1, 2, 3].sample(3)
# [1, 2, 3].shuffle[1, 3] # sample(3) might return a longer Array
# [1, 2, 3].shuffle[1..3] # sample(3) might return a longer Array
# [1, 2, 3].shuffle[foo, bar]
# [1, 2, 3].shuffle(random: Random.new)
class Sample < Base
extend AutoCorrector
MSG = 'Use `%<correct>s` instead of `%<incorrect>s`.'
RESTRICT_ON_SEND = %i[first last [] at slice].freeze
# @!method sample_candidate?(node)
def_node_matcher :sample_candidate?, <<~PATTERN
(call $(call _ :shuffle $...) ${:#{RESTRICT_ON_SEND.join(' :')}} $...)
PATTERN
def on_send(node)
sample_candidate?(node) do |shuffle_node, shuffle_arg, method, method_args|
return unless offensive?(method, method_args)
range = source_range(shuffle_node, node)
message = message(shuffle_arg, method, method_args, range)
add_offense(range, message: message) do |corrector|
corrector.replace(
source_range(shuffle_node, node), correction(shuffle_arg, method, method_args)
)
end
end
end
alias on_csend on_send
private
def offensive?(method, method_args)
case method
when :first, :last
true
when :[], :at, :slice
sample_size(method_args) != :unknown
else
false
end
end
def sample_size(method_args)
case method_args.size
when 1
sample_size_for_one_arg(method_args.first)
when 2
sample_size_for_two_args(*method_args)
end
end
def sample_size_for_one_arg(arg)
if arg.range_type?
range_size(arg)
elsif arg.int_type?
[0, -1].include?(arg.to_a.first) ? nil : :unknown
else
:unknown
end
end
def sample_size_for_two_args(first, second)
return :unknown unless first.int_type? && first.to_a.first.zero?
second.int_type? ? second.to_a.first : :unknown
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def range_size(range_node)
vals = range_node.to_a
return :unknown unless vals.all? { |val| val.nil? || val.int_type? }
low, high = vals.map { |val| val.nil? ? 0 : val.children[0] }
return :unknown unless low.zero? && high >= 0
case range_node.type
when :erange
(low...high).size
when :irange
(low..high).size
end
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def source_range(shuffle_node, node)
shuffle_node.loc.selector.join(node.source_range.end)
end
def message(shuffle_arg, method, method_args, range)
format(MSG,
correct: correction(shuffle_arg, method, method_args),
incorrect: range.source)
end
def correction(shuffle_arg, method, method_args)
shuffle_arg = extract_source(shuffle_arg)
sample_arg = sample_arg(method, method_args)
args = [sample_arg, shuffle_arg].compact.join(', ')
args.empty? ? 'sample' : "sample(#{args})"
end
def sample_arg(method, method_args)
case method
when :first, :last
extract_source(method_args)
when :[], :slice
sample_size(method_args)
end
end
def extract_source(args)
args.empty? ? nil : args.first.source
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/double_cop_disable_directive.rb | lib/rubocop/cop/style/double_cop_disable_directive.rb | # frozen_string_literal: true
# rubocop:disable Lint/RedundantCopDisableDirective
# rubocop:disable Style/DoubleCopDisableDirective
module RuboCop
module Cop
module Style
# Detects double disable comments on one line. This is mostly to catch
# automatically generated comments that need to be regenerated.
#
# @example
# # bad
# def f # rubocop:disable Style/For # rubocop:disable Metrics/AbcSize
# end
#
# # good
# # rubocop:disable Metrics/AbcSize
# def f # rubocop:disable Style/For
# end
# # rubocop:enable Metrics/AbcSize
#
# # if both fit on one line
# def f # rubocop:disable Style/For, Metrics/AbcSize
# end
#
class DoubleCopDisableDirective < Base
extend AutoCorrector
# rubocop:enable Style/For, Style/DoubleCopDisableDirective
# rubocop:enable Lint/RedundantCopDisableDirective, Metrics/AbcSize
MSG = 'More than one disable comment on one line.'
def on_new_investigation
processed_source.comments.each do |comment|
next unless comment.text.scan(/# rubocop:(?:disable|todo)/).size > 1
add_offense(comment) do |corrector|
corrector.replace(comment, comment.text.gsub(%r{ # rubocop:(disable|todo)}, ','))
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/style/multiline_if_modifier.rb | lib/rubocop/cop/style/multiline_if_modifier.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for uses of if/unless modifiers with multiple-lines bodies.
#
# @example
#
# # bad
# {
# result: 'this should not happen'
# } unless cond
#
# # good
# { result: 'ok' } if cond
class MultilineIfModifier < Base
include StatementModifier
include Alignment
extend AutoCorrector
MSG = 'Favor a normal %<keyword>s-statement over a modifier ' \
'clause in a multiline statement.'
def on_if(node)
return if part_of_ignored_node?(node)
return unless node.modifier_form? && node.body.multiline?
add_offense(node, message: format(MSG, keyword: node.keyword)) do |corrector|
corrector.replace(node, to_normal_if(node))
end
ignore_node(node)
end
private
def to_normal_if(node)
indented_body = indented_body(node.body, node)
condition = "#{node.keyword} #{node.condition.source}"
indented_end = "#{offset(node)}end"
[condition, indented_body, indented_end].join("\n")
end
def indented_body(body, node)
body_source = "#{offset(node)}#{body.source}"
body_source.each_line.map do |line|
if line == "\n"
line
else
line.sub(/^\s{#{offset(node).length}}/, indentation(node))
end
end.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/style/empty_block_parameter.rb | lib/rubocop/cop/style/empty_block_parameter.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for pipes for empty block parameters. Pipes for empty
# block parameters do not cause syntax errors, but they are redundant.
#
# @example
# # bad
# a do ||
# do_something
# end
#
# # bad
# a { || do_something }
#
# # good
# a do
# end
#
# # good
# a { do_something }
class EmptyBlockParameter < Base
include EmptyParameter
include RangeHelp
extend AutoCorrector
MSG = 'Omit pipes for the empty block parameters.'
def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
send_node = node.send_node
check(node) unless send_node.send_type? && send_node.lambda_literal?
end
private
def autocorrect(corrector, node)
block = node.parent
range = range_between(block.loc.begin.end_pos, node.source_range.end_pos)
corrector.remove(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/style/redundant_freeze.rb | lib/rubocop/cop/style/redundant_freeze.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for uses of `Object#freeze` on immutable objects.
#
# NOTE: `Regexp` and `Range` literals are frozen objects since Ruby 3.0.
#
# NOTE: From Ruby 3.0, this cop allows explicit freezing of interpolated
# string literals when `# frozen-string-literal: true` is used.
#
# @example
# # bad
# CONST = 1.freeze
#
# # good
# CONST = 1
class RedundantFreeze < Base
extend AutoCorrector
include FrozenStringLiteral
MSG = 'Do not freeze immutable objects, as freezing them has no effect.'
RESTRICT_ON_SEND = %i[freeze].freeze
def on_send(node)
return unless node.receiver &&
(immutable_literal?(node.receiver) ||
operation_produces_immutable_object?(node.receiver))
add_offense(node) do |corrector|
corrector.remove(node.loc.dot)
corrector.remove(node.loc.selector)
end
end
private
def immutable_literal?(node)
node = strip_parenthesis(node)
return true if node.immutable_literal?
return true if frozen_string_literal?(node)
target_ruby_version >= 3.0 && node.type?(:regexp, :range)
end
def strip_parenthesis(node)
if node.begin_type? && node.children.first
node.children.first
else
node
end
end
# @!method operation_produces_immutable_object?(node)
def_node_matcher :operation_produces_immutable_object?, <<~PATTERN
{
(begin (send {float int} {:+ :- :* :** :/ :% :<<} _))
(begin (send !{(str _) array} {:+ :- :* :** :/ :%} {float int}))
(begin (send _ {:== :=== :!= :<= :>= :< :>} _))
(send _ {:count :length :size} ...)
(any_block (send _ {:count :length :size} ...) ...)
}
PATTERN
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_interpolation.rb | lib/rubocop/cop/style/redundant_interpolation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for strings that are just an interpolated expression.
#
# @safety
# Autocorrection is unsafe because when calling a destructive method to string,
# the resulting string may have different behavior or raise `FrozenError`.
#
# [source,ruby]
# ----
# x = 'a'
# y = "#{x}"
# y << 'b' # return 'ab'
# x # return 'a'
# y = x.to_s
# y << 'b' # return 'ab'
# x # return 'ab'
#
# x = 'a'.freeze
# y = "#{x}"
# y << 'b' # return 'ab'.
# y = x.to_s
# y << 'b' # raise `FrozenError`.
# ----
#
# @example
#
# # bad
# "#{@var}"
#
# # good
# @var.to_s
#
# # good if @var is already a String
# @var
class RedundantInterpolation < Base
include PercentLiteral
extend AutoCorrector
MSG = 'Prefer `to_s` over string interpolation.'
def self.autocorrect_incompatible_with
[Style::LineEndConcatenation]
end
def on_dstr(node)
return unless single_interpolation?(node)
embedded_node = node.children.first
return if use_match_pattern?(embedded_node)
add_offense(node) do |corrector|
if variable_interpolation?(embedded_node)
autocorrect_variable_interpolation(corrector, embedded_node, node)
elsif single_variable_interpolation?(embedded_node)
autocorrect_single_variable_interpolation(corrector, embedded_node, node)
else
autocorrect_other(corrector, embedded_node, node)
end
end
end
private
def single_interpolation?(node)
node.children.one? &&
interpolation?(node.children.first) &&
!implicit_concatenation?(node) &&
!embedded_in_percent_array?(node)
end
def use_match_pattern?(node)
return false if target_ruby_version <= 2.7
node.children.any? do |child|
child.respond_to?(:match_pattern_type?) && child.match_pattern_type?
end
end
def single_variable_interpolation?(node)
return false unless node.children.one?
first_child = node.children.first
variable_interpolation?(first_child) ||
(first_child.send_type? && !first_child.operator_method?)
end
def interpolation?(node)
variable_interpolation?(node) || node.begin_type?
end
def variable_interpolation?(node)
node.variable? || node.reference?
end
def implicit_concatenation?(node)
node.parent&.dstr_type?
end
def embedded_in_percent_array?(node)
node.parent&.array_type? && percent_literal?(node.parent)
end
def autocorrect_variable_interpolation(corrector, embedded_node, node)
replacement = "#{embedded_node.source}.to_s"
corrector.replace(node, replacement)
end
def autocorrect_single_variable_interpolation(corrector, embedded_node, node)
embedded_var = embedded_node.children.first
source = if require_parentheses?(embedded_var)
receiver = range_between(
embedded_var.source_range.begin_pos, embedded_var.loc.selector.end_pos
)
arguments = embedded_var.arguments.map(&:source).join(', ')
"#{receiver.source}(#{arguments})"
else
embedded_var.source
end
corrector.replace(node, "#{source}.to_s")
end
def autocorrect_other(corrector, embedded_node, node)
loc = node.loc
embedded_loc = embedded_node.loc
corrector.replace(loc.begin, '')
corrector.replace(loc.end, '')
corrector.replace(embedded_loc.begin, '(')
corrector.replace(embedded_loc.end, ').to_s')
end
def require_parentheses?(node)
node.send_type? && node.arguments.any? && !node.parenthesized_call?
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_sort.rb | lib/rubocop/cop/style/redundant_sort.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Identifies instances of sorting and then
# taking only the first or last element. The same behavior can
# be accomplished without a relatively expensive sort by using
# `Enumerable#min` instead of sorting and taking the first
# element and `Enumerable#max` instead of sorting and taking the
# last element. Similarly, `Enumerable#min_by` and
# `Enumerable#max_by` can replace `Enumerable#sort_by` calls
# after which only the first or last element is used.
#
# @safety
# This cop is unsafe, because `sort...last` and `max` may not return the
# same element in all cases.
#
# In an enumerable where there are multiple elements where ``a <=> b == 0``,
# or where the transformation done by the `sort_by` block has the
# same result, `sort.last` and `max` (or `sort_by.last` and `max_by`)
# will return different elements. `sort.last` will return the last
# element but `max` will return the first element.
#
# For example:
#
# [source,ruby]
# ----
# class MyString < String; end
# strings = [MyString.new('test'), 'test']
# strings.sort.last.class #=> String
# strings.max.class #=> MyString
# ----
#
# [source,ruby]
# ----
# words = %w(dog horse mouse)
# words.sort_by { |word| word.length }.last #=> 'mouse'
# words.max_by { |word| word.length } #=> 'horse'
# ----
#
# @example
# # bad
# [2, 1, 3].sort.first
# [2, 1, 3].sort[0]
# [2, 1, 3].sort.at(0)
# [2, 1, 3].sort.slice(0)
#
# # good
# [2, 1, 3].min
#
# # bad
# [2, 1, 3].sort.last
# [2, 1, 3].sort[-1]
# [2, 1, 3].sort.at(-1)
# [2, 1, 3].sort.slice(-1)
#
# # good
# [2, 1, 3].max
#
# # bad
# arr.sort_by(&:foo).first
# arr.sort_by(&:foo)[0]
# arr.sort_by(&:foo).at(0)
# arr.sort_by(&:foo).slice(0)
#
# # good
# arr.min_by(&:foo)
#
# # bad
# arr.sort_by(&:foo).last
# arr.sort_by(&:foo)[-1]
# arr.sort_by(&:foo).at(-1)
# arr.sort_by(&:foo).slice(-1)
#
# # good
# arr.max_by(&:foo)
#
class RedundantSort < Base
include RangeHelp
extend AutoCorrector
MSG = 'Use `%<suggestion>s` instead of `%<sorter>s...%<accessor_source>s`.'
RESTRICT_ON_SEND = %i[sort sort_by].freeze
# @!method redundant_sort?(node)
def_node_matcher :redundant_sort?, <<~MATCHER
{
(call $(call _ $:sort) ${:last :first})
(call $(call _ $:sort) ${:[] :at :slice} {(int 0) (int -1)})
(call $(call _ $:sort_by _) ${:last :first})
(send $(send _ $:sort_by _) ${:[] :at :slice} {(int 0) (int -1)})
(call (any_block $(call _ ${:sort_by :sort}) ...) ${:last :first})
(call
(any_block $(call _ ${:sort_by :sort}) ...)
${:[] :at :slice} {(int 0) (int -1)}
)
}
MATCHER
def on_send(node)
ancestor, sort_node, sorter, accessor =
find_redundant_sort(node.parent, node.parent&.parent)
return unless ancestor
register_offense(ancestor, sort_node, sorter, accessor)
end
alias on_csend on_send
private
def find_redundant_sort(*nodes)
nodes.each do |node|
if (sort_node, sorter, accessor = redundant_sort?(node))
return [node, sort_node, sorter, accessor]
end
end
nil
end
def register_offense(node, sort_node, sorter, accessor)
message = message(node, sorter, accessor)
add_offense(offense_range(sort_node, node), message: message) do |corrector|
autocorrect(corrector, node, sort_node, sorter, accessor)
end
end
def offense_range(sort_node, node)
range_between(sort_node.loc.selector.begin_pos, node.source_range.end_pos)
end
def message(node, sorter, accessor)
accessor_source = range_between(
node.loc.selector.begin_pos,
node.source_range.end_pos
).source
format(MSG,
suggestion: suggestion(sorter, accessor, arg_value(node)),
sorter: sorter,
accessor_source: accessor_source)
end
def autocorrect(corrector, node, sort_node, sorter, accessor)
# Remove accessor, e.g. `first` or `[-1]`.
corrector.remove(range_between(accessor_start(node), node.source_range.end_pos))
# Replace "sort" or "sort_by" with the appropriate min/max method.
corrector.replace(sort_node.loc.selector, suggestion(sorter, accessor, arg_value(node)))
# Replace to avoid syntax errors when followed by a logical operator.
replace_with_logical_operator(corrector, node) if with_logical_operator?(node)
end
def replace_with_logical_operator(corrector, node)
corrector.insert_after(node.child_nodes.first, " #{node.parent.loc.operator.source}")
corrector.remove(node.parent.loc.operator)
end
def suggestion(sorter, accessor, arg)
base(accessor, arg) + suffix(sorter)
end
def base(accessor, arg)
if accessor == :first || arg&.zero?
'min'
elsif accessor == :last || arg == -1
'max'
end
end
def suffix(sorter)
case sorter
when :sort
''
when :sort_by
'_by'
end
end
def arg_node(node)
node.first_argument
end
def arg_value(node)
arg_node(node)&.node_parts&.first
end
# This gets the start of the accessor whether it has a dot
# (e.g. `.first`) or doesn't (e.g. `[0]`)
def accessor_start(node)
if node.loc.dot
node.loc.dot.begin_pos
else
node.loc.selector.begin_pos
end
end
def with_logical_operator?(node)
return false unless (parent = node.parent)
parent.operator_keyword?
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/dig_chain.rb | lib/rubocop/cop/style/dig_chain.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for chained `dig` calls that can be collapsed into a single `dig`.
#
# @safety
# This cop is unsafe because it cannot be guaranteed that the receiver
# is an `Enumerable` or does not have a nonstandard implementation
# of `dig`.
#
# @example
# # bad
# x.dig(:foo).dig(:bar).dig(:baz)
# x.dig(:foo, :bar).dig(:baz)
# x.dig(:foo, :bar)&.dig(:baz)
#
# # good
# x.dig(:foo, :bar, :baz)
#
# # good - `dig`s cannot be combined
# x.dig(:foo).bar.dig(:baz)
#
class DigChain < Base
extend AutoCorrector
include CommentsHelp
include DigHelp
MSG = 'Use `%<replacement>s` instead of chaining.'
RESTRICT_ON_SEND = %i[dig].freeze
def on_send(node)
return if ignored_node?(node)
return unless node.loc.dot
return unless dig?(node)
range, arguments = inspect_chain(node)
return if invalid_arguments?(arguments)
return unless range
register_offense(node, range, arguments)
end
alias on_csend on_send
private
# Walk up the method chain while the receiver is `dig` with arguments.
def inspect_chain(node)
arguments = node.arguments.dup
end_range = node.source_range.end
while dig?(node = node.receiver)
begin_range = node.loc.selector
arguments.unshift(*node.arguments)
ignore_node(node)
end
return unless begin_range
[begin_range.join(end_range), arguments]
end
def invalid_arguments?(arguments)
# If any of the arguments are arguments forwarding (`...`), it can only be the
# first argument, or else the resulting code will have a syntax error.
return false unless arguments&.any?
forwarded_args_index = arguments.index(&:forwarded_args_type?)
forwarded_args_index && forwarded_args_index < (arguments.size - 1)
end
def register_offense(node, range, arguments)
arguments = arguments.map(&:source).join(', ')
replacement = "dig(#{arguments})"
add_offense(range, message: format(MSG, replacement: replacement)) do |corrector|
corrector.replace(range, replacement)
comments_in_range(node).reverse_each do |comment|
corrector.insert_before(node, "#{comment.source}\n")
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/style/string_literals_in_interpolation.rb | lib/rubocop/cop/style/string_literals_in_interpolation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks that quotes inside string, symbol, and regexp interpolations
# match the configured preference.
#
# @example EnforcedStyle: single_quotes (default)
# # bad
# string = "Tests #{success ? "PASS" : "FAIL"}"
# symbol = :"Tests #{success ? "PASS" : "FAIL"}"
# heredoc = <<~TEXT
# Tests #{success ? "PASS" : "FAIL"}
# TEXT
# regexp = /Tests #{success ? "PASS" : "FAIL"}/
#
# # good
# string = "Tests #{success ? 'PASS' : 'FAIL'}"
# symbol = :"Tests #{success ? 'PASS' : 'FAIL'}"
# heredoc = <<~TEXT
# Tests #{success ? 'PASS' : 'FAIL'}
# TEXT
# regexp = /Tests #{success ? 'PASS' : 'FAIL'}/
#
# @example EnforcedStyle: double_quotes
# # bad
# string = "Tests #{success ? 'PASS' : 'FAIL'}"
# symbol = :"Tests #{success ? 'PASS' : 'FAIL'}"
# heredoc = <<~TEXT
# Tests #{success ? 'PASS' : 'FAIL'}
# TEXT
# regexp = /Tests #{success ? 'PASS' : 'FAIL'}/
#
# # good
# string = "Tests #{success ? "PASS" : "FAIL"}"
# symbol = :"Tests #{success ? "PASS" : "FAIL"}"
# heredoc = <<~TEXT
# Tests #{success ? "PASS" : "FAIL"}
# TEXT
# regexp = /Tests #{success ? "PASS" : "FAIL"}/
class StringLiteralsInInterpolation < Base
include ConfigurableEnforcedStyle
include StringLiteralsHelp
include StringHelp
extend AutoCorrector
def autocorrect(corrector, node)
StringLiteralCorrector.correct(corrector, node, style)
end
# Cop classes that include the StringHelp module usually ignore regexp
# nodes. Not so for this cop, which is why we override the on_regexp
# definition with an empty one.
def on_regexp(node); end
private
def message(_node)
# single_quotes -> single-quoted
kind = style.to_s.sub(/_(.*)s/, '-\1d')
"Prefer #{kind} strings inside interpolations."
end
def offense?(node)
# If it's not a string within an interpolation, then it's not an
# offense for this cop.
return false unless inside_interpolation?(node)
wrong_quotes?(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/style/redundant_heredoc_delimiter_quotes.rb | lib/rubocop/cop/style/redundant_heredoc_delimiter_quotes.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for redundant heredoc delimiter quotes.
#
# @example
#
# # bad
# do_something(<<~'EOS')
# no string interpolation style text
# EOS
#
# # good
# do_something(<<~EOS)
# no string interpolation style text
# EOS
#
# do_something(<<~'EOS')
# #{string_interpolation_style_text_not_evaluated}
# EOS
#
# do_something(<<~'EOS')
# Preserve \
# newlines
# EOS
#
class RedundantHeredocDelimiterQuotes < Base
include Heredoc
extend AutoCorrector
MSG = 'Remove the redundant heredoc delimiter quotes, use `%<replacement>s` instead.'
STRING_INTERPOLATION_OR_ESCAPED_CHARACTER_PATTERN = /#(\{|@|\$)|\\/.freeze
def on_heredoc(node)
return if need_heredoc_delimiter_quotes?(node)
replacement = "#{heredoc_type(node)}#{delimiter_string(node)}"
add_offense(node, message: format(MSG, replacement: replacement)) do |corrector|
corrector.replace(node, replacement)
end
end
private
def need_heredoc_delimiter_quotes?(node)
heredoc_delimiter = node.source.delete(heredoc_type(node))
return true unless heredoc_delimiter.start_with?("'", '"')
node.loc.heredoc_end.source.strip.match?(/\W/) ||
node.loc.heredoc_body.source.match?(STRING_INTERPOLATION_OR_ESCAPED_CHARACTER_PATTERN)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_line_continuation.rb | lib/rubocop/cop/style/redundant_line_continuation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for redundant line continuation.
#
# This cop marks a line continuation as redundant if removing the backslash
# does not result in a syntax error.
# However, a backslash at the end of a comment or
# for string concatenation is not redundant and is not considered an offense.
#
# @example
# # bad
# foo. \
# bar
# foo \
# &.bar \
# .baz
#
# # good
# foo.
# bar
# foo
# &.bar
# .baz
#
# # bad
# [foo, \
# bar]
# {foo: \
# bar}
#
# # good
# [foo,
# bar]
# {foo:
# bar}
#
# # bad
# foo(bar, \
# baz)
#
# # good
# foo(bar,
# baz)
#
# # also good - backslash in string concatenation is not redundant
# foo('bar' \
# 'baz')
#
# # also good - backslash at the end of a comment is not redundant
# foo(bar, # \
# baz)
#
# # also good - backslash at the line following the newline begins with a + or -,
# # it is not redundant
# 1 \
# + 2 \
# - 3
#
# # also good - backslash with newline between the method name and its arguments,
# # it is not redundant.
# some_method \
# (argument)
#
class RedundantLineContinuation < Base
include MatchRange
extend AutoCorrector
MSG = 'Redundant line continuation.'
LINE_CONTINUATION = '\\'
LINE_CONTINUATION_PATTERN = /(\\\n)/.freeze
ALLOWED_STRING_TOKENS = %i[tSTRING tSTRING_CONTENT].freeze
ARGUMENT_TYPES = %i[
kDEF kDEFINED kFALSE kNIL kSELF kTRUE tAMPER tBANG tCARET tCHARACTER tCOLON3 tCONSTANT
tCVAR tDOT2 tDOT3 tFLOAT tGVAR tIDENTIFIER tINTEGER tIVAR tLAMBDA tLBRACK tLCURLY
tLPAREN_ARG tPIPE tQSYMBOLS_BEG tQWORDS_BEG tREGEXP_BEG tSTAR tSTRING tSTRING_BEG tSYMBEG
tSYMBOL tSYMBOLS_BEG tTILDE tUMINUS tUNARY_NUM tUPLUS tWORDS_BEG tXSTRING_BEG
].freeze
ARGUMENT_TAKING_FLOW_TOKEN_TYPES = %i[
tIDENTIFIER kBREAK kNEXT kRETURN kSUPER kYIELD
].freeze
ARITHMETIC_OPERATOR_TOKENS = %i[tDIVIDE tDSTAR tMINUS tPERCENT tPLUS tSTAR2].freeze
def on_new_investigation
return unless processed_source.ast
each_match_range(processed_source.ast.source_range, LINE_CONTINUATION_PATTERN) do |range|
next if require_line_continuation?(range)
next unless redundant_line_continuation?(range)
add_offense(range) do |corrector|
corrector.remove_leading(range, 1)
end
end
inspect_end_of_ruby_code_line_continuation
end
private
def require_line_continuation?(range)
!ends_with_uncommented_backslash?(range) ||
string_concatenation?(range.source_line) ||
start_with_arithmetic_operator?(range) ||
inside_string_literal_or_method_with_argument?(range) ||
leading_dot_method_chain_with_blank_line?(range)
end
def ends_with_uncommented_backslash?(range)
# A line continuation always needs to be the last character on the line, which
# means that it is impossible to have a comment following a continuation.
# Therefore, if the line contains a comment, it cannot end with a continuation.
return false if processed_source.line_with_comment?(range.line)
range.source_line.end_with?(LINE_CONTINUATION)
end
def string_concatenation?(source_line)
/["']\s*\\\z/.match?(source_line)
end
def inside_string_literal_or_method_with_argument?(range)
line_range = range_by_whole_lines(range)
processed_source.tokens.each_cons(2).any? do |token, next_token|
next if token.line == next_token.line
inside_string_literal?(range, token) ||
method_with_argument?(line_range, token, next_token)
end
end
def leading_dot_method_chain_with_blank_line?(range)
return false unless range.source_line.strip.start_with?('.', '&.')
processed_source[range.line].strip.empty?
end
def redundant_line_continuation?(range)
return true unless (node = find_node_for_line(range.last_line))
return false if argument_newline?(node)
# Check if source is still valid without the continuation
source = processed_source.raw_source.dup
source[range.begin_pos, range.length] = "\n"
parse(source).valid_syntax?
end
def inspect_end_of_ruby_code_line_continuation
last_line = processed_source.lines[processed_source.ast.last_line - 1]
return unless code_ends_with_continuation?(last_line)
last_column = last_line.length
line_continuation_range = range_between(last_column - 1, last_column)
add_offense(line_continuation_range) do |corrector|
corrector.remove_trailing(line_continuation_range, 1)
end
end
def code_ends_with_continuation?(last_line)
return false if processed_source.line_with_comment?(processed_source.ast.last_line)
last_line.end_with?(LINE_CONTINUATION)
end
def inside_string_literal?(range, token)
ALLOWED_STRING_TOKENS.include?(token.type) && token.pos.overlaps?(range)
end
# A method call without parentheses such as the following cannot remove `\`:
#
# do_something \
# argument
def method_with_argument?(line_range, current_token, next_token)
return false unless ARGUMENT_TAKING_FLOW_TOKEN_TYPES.include?(current_token.type)
return false unless current_token.pos.overlaps?(line_range)
ARGUMENT_TYPES.include?(next_token.type)
end
def argument_newline?(node)
return false if node.parenthesized_call?
node = node.children.first if node.root? && node.begin_type?
if argument_is_method?(node)
argument_newline?(node.first_argument)
else
return false unless method_call_with_arguments?(node)
node.loc.selector.line != node.first_argument.loc.line
end
end
def find_node_for_line(last_line)
processed_source.ast.each_node do |node|
return node if same_line?(node, last_line)
end
end
def same_line?(node, line)
return false unless (source_range = node.source_range)
if node.is_a?(AST::StrNode)
if node.heredoc?
(node.loc.heredoc_body.line..node.loc.heredoc_body.last_line).cover?(line)
else
(source_range.line..source_range.last_line).cover?(line)
end
else
source_range.line == line
end
end
def argument_is_method?(node)
return false unless node.send_type?
return false unless (first_argument = node.first_argument)
method_call_with_arguments?(first_argument)
end
def method_call_with_arguments?(node)
node.call_type? && !node.arguments.empty?
end
def start_with_arithmetic_operator?(range)
line_range = processed_source.buffer.line_range(range.line + 1)
ARITHMETIC_OPERATOR_TOKENS.include?(processed_source.first_token_of(line_range).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/style/explicit_block_argument.rb | lib/rubocop/cop/style/explicit_block_argument.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Enforces the use of explicit block argument to avoid writing
# block literal that just passes its arguments to another block.
#
# NOTE: This cop only registers an offense if the block args match the
# yield args exactly.
#
# @example
# # bad
# def with_tmp_dir
# Dir.mktmpdir do |tmp_dir|
# Dir.chdir(tmp_dir) { |dir| yield dir } # block just passes arguments
# end
# end
#
# # bad
# def nine_times
# 9.times { yield }
# end
#
# # good
# def with_tmp_dir(&block)
# Dir.mktmpdir do |tmp_dir|
# Dir.chdir(tmp_dir, &block)
# end
# end
#
# with_tmp_dir do |dir|
# puts "dir is accessible as a parameter and pwd is set: #{dir}"
# end
#
# # good
# def nine_times(&block)
# 9.times(&block)
# end
#
class ExplicitBlockArgument < Base
include RangeHelp
extend AutoCorrector
MSG = 'Consider using explicit block argument in the ' \
"surrounding method's signature over `yield`."
# @!method yielding_block?(node)
def_node_matcher :yielding_block?, <<~PATTERN
(block $_ (args $...) (yield $...))
PATTERN
def self.autocorrect_incompatible_with
[Lint::UnusedMethodArgument]
end
def initialize(config = nil, options = nil)
super
@def_nodes = Set.new.compare_by_identity
end
def on_yield(node)
block_node = node.parent
yielding_block?(block_node) do |send_node, block_args, yield_args|
return unless yielding_arguments?(block_args, yield_args)
def_node = block_node.each_ancestor(:any_def).first
# if `yield` is being called outside of a method context, ignore
# this is not a valid ruby pattern, but can happen in haml or erb,
# so this can cause crashes in haml_lint
return unless def_node
block_name = extract_block_name(def_node)
add_offense(block_node) do |corrector|
corrector.remove(block_body_range(block_node, send_node))
add_block_argument(send_node, corrector, block_name)
add_block_argument(def_node, corrector, block_name) if @def_nodes.add?(def_node)
end
end
end
private
def extract_block_name(def_node)
if def_node.block_argument?
def_node.last_argument.name
else
'block'
end
end
def yielding_arguments?(block_args, yield_args)
yield_args = yield_args.dup.fill(
nil,
yield_args.length, block_args.length - yield_args.length
)
yield_args.zip(block_args).all? do |yield_arg, block_arg|
next false unless yield_arg && block_arg
block_arg && yield_arg.children.first == block_arg.children.first
end
end
def add_block_argument(node, corrector, block_name)
if node.arguments?
insert_argument(node, corrector, block_name)
elsif empty_arguments?(node)
corrector.replace(node.arguments, "(&#{block_name})")
elsif call_like?(node)
correct_call_node(node, corrector, block_name)
else
corrector.insert_after(node.loc.name, "(&#{block_name})")
end
end
def empty_arguments?(node)
# Is there an arguments node with only parentheses?
node.arguments.is_a?(RuboCop::AST::Node) && node.arguments.loc.begin
end
def call_like?(node)
node.type?(:call, :zsuper, :super)
end
def insert_argument(node, corrector, block_name)
last_arg = node.last_argument
arg_range = range_with_surrounding_comma(last_arg.source_range, :right)
replacement = " &#{block_name}"
replacement = ",#{replacement}" unless arg_range.source.end_with?(',')
corrector.insert_after(arg_range, replacement) unless last_arg.blockarg_type?
end
def correct_call_node(node, corrector, block_name)
new_arguments = if node.zsuper_type?
args = build_new_arguments_for_zsuper(node) << "&#{block_name}"
args.join(', ')
else
"&#{block_name}"
end
corrector.insert_after(node, "(#{new_arguments})")
return unless node.parenthesized?
args_begin = Util.args_begin(node)
args_end = Util.args_end(node)
range = range_between(args_begin.begin_pos, args_end.end_pos)
corrector.remove(range)
end
def build_new_arguments_for_zsuper(node)
def_node = node.each_ancestor(:any_def).first
def_node.arguments.map do |arg|
arg.optarg_type? ? arg.node_parts[0] : arg.source
end
end
def block_body_range(block_node, send_node)
range_between(send_node.source_range.end_pos, block_node.loc.end.end_pos)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/multiline_memoization.rb | lib/rubocop/cop/style/multiline_memoization.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks expressions wrapping styles for multiline memoization.
#
# @example EnforcedStyle: keyword (default)
# # bad
# foo ||= (
# bar
# baz
# )
#
# # good
# foo ||= begin
# bar
# baz
# end
#
# @example EnforcedStyle: braces
# # bad
# foo ||= begin
# bar
# baz
# end
#
# # good
# foo ||= (
# bar
# baz
# )
class MultilineMemoization < Base
include Alignment
include ConfigurableEnforcedStyle
extend AutoCorrector
KEYWORD_MSG = 'Wrap multiline memoization blocks in `begin` and `end`.'
BRACES_MSG = 'Wrap multiline memoization blocks in `(` and `)`.'
def on_or_asgn(node)
rhs = node.expression
return unless bad_rhs?(rhs)
add_offense(node) do |corrector|
if style == :keyword
keyword_autocorrect(rhs, corrector)
else
corrector.replace(rhs.loc.begin, '(')
corrector.replace(rhs.loc.end, ')')
end
end
end
def message(_node)
style == :braces ? BRACES_MSG : KEYWORD_MSG
end
private
def bad_rhs?(rhs)
return false unless rhs.multiline?
if style == :keyword
rhs.begin_type?
else
rhs.kwbegin_type?
end
end
def keyword_autocorrect(node, corrector)
node_buf = node.source_range.source_buffer
corrector.replace(node.loc.begin, keyword_begin_str(node, node_buf))
corrector.replace(node.loc.end, keyword_end_str(node, node_buf))
end
def keyword_begin_str(node, node_buf)
if node_buf.source[node.loc.begin.end_pos] == "\n"
'begin'
else
"begin\n#{' ' * (node.loc.column + configured_indentation_width)}"
end
end
def keyword_end_str(node, node_buf)
if /[^\s)]/.match?(node_buf.source_line(node.loc.end.line))
"\n#{' ' * node.loc.column}end"
else
'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/style/when_then.rb | lib/rubocop/cop/style/when_then.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for `when;` uses in `case` expressions.
#
# @example
# # bad
# case foo
# when 1; 'baz'
# when 2; 'bar'
# end
#
# # good
# case foo
# when 1 then 'baz'
# when 2 then 'bar'
# end
class WhenThen < Base
extend AutoCorrector
MSG = 'Do not use `when %<expression>s;`. Use `when %<expression>s then` instead.'
def on_when(node)
return if node.multiline? || node.then? || !node.body
message = format(MSG, expression: node.conditions.map(&:source).join(', '))
add_offense(node.loc.begin, message: message) do |corrector|
corrector.replace(node.loc.begin, ' then')
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/top_level_method_definition.rb | lib/rubocop/cop/style/top_level_method_definition.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Newcomers to ruby applications may write top-level methods,
# when ideally they should be organized in appropriate classes or modules.
# This cop looks for definitions of top-level methods and warns about them.
#
# However for ruby scripts it is perfectly fine to use top-level methods.
# Hence this cop is disabled by default.
#
# @example
# # bad
# def some_method
# end
#
# # bad
# def self.some_method
# end
#
# # bad
# define_method(:foo) { puts 1 }
#
# # good
# module Foo
# def some_method
# end
# end
#
# # good
# class Foo
# def self.some_method
# end
# end
#
# # good
# Struct.new do
# def some_method
# end
# end
#
# # good
# class Foo
# define_method(:foo) { puts 1 }
# end
class TopLevelMethodDefinition < Base
MSG = 'Do not define methods at the top-level.'
RESTRICT_ON_SEND = %i[define_method].freeze
def on_def(node)
return unless top_level_method_definition?(node)
add_offense(node)
end
alias on_defs on_def
alias on_send on_def
def on_block(node)
return unless define_method_block?(node) && top_level_method_definition?(node)
add_offense(node)
end
alias on_numblock on_block
alias on_itblock on_block
private
def top_level_method_definition?(node)
if node.parent&.begin_type?
node.parent.root?
else
node.root?
end
end
# @!method define_method_block?(node)
def_node_matcher :define_method_block?, <<~PATTERN
(any_block (send _ :define_method _) ...)
PATTERN
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/unpack_first.rb | lib/rubocop/cop/style/unpack_first.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for accessing the first element of `String#unpack`
# which can be replaced with the shorter method `unpack1`.
#
# @example
#
# # bad
# 'foo'.unpack('h*').first
# 'foo'.unpack('h*')[0]
# 'foo'.unpack('h*').slice(0)
# 'foo'.unpack('h*').at(0)
#
# # good
# 'foo'.unpack1('h*')
#
class UnpackFirst < Base
extend AutoCorrector
extend TargetRubyVersion
minimum_target_ruby_version 2.4
MSG = 'Use `unpack1(%<format>s)` instead of `%<current>s`.'
RESTRICT_ON_SEND = %i[first [] slice at].freeze
# @!method unpack_and_first_element?(node)
def_node_matcher :unpack_and_first_element?, <<~PATTERN
{
(call $(call (...) :unpack $(...)) :first)
(call $(call (...) :unpack $(...)) {:[] :slice :at} (int 0))
}
PATTERN
def on_send(node)
unpack_and_first_element?(node) do |unpack_call, unpack_arg|
first_element_range = first_element_range(node, unpack_call)
offense_range = unpack_call.loc.selector.join(node.source_range.end)
message = format(MSG, format: unpack_arg.source, current: offense_range.source)
add_offense(offense_range, message: message) do |corrector|
corrector.remove(first_element_range)
corrector.replace(unpack_call.loc.selector, 'unpack1')
end
end
end
alias on_csend on_send
private
def first_element_range(node, unpack_call)
unpack_call.source_range.end.join(node.source_range.end)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/attr.rb | lib/rubocop/cop/style/attr.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for uses of Module#attr.
#
# @example
# # bad - creates a single attribute accessor (deprecated in Ruby 1.9)
# attr :something, true
# attr :one, :two, :three # behaves as attr_reader
#
# # good
# attr_accessor :something
# attr_reader :one, :two, :three
#
class Attr < Base
include RangeHelp
extend AutoCorrector
MSG = 'Do not use `attr`. Use `%<replacement>s` instead.'
RESTRICT_ON_SEND = %i[attr].freeze
def on_send(node)
return unless node.command?(:attr) && node.arguments?
# check only for method definitions in class/module body
return if allowed_context?(node)
message = message(node)
add_offense(node.loc.selector, message: message) do |corrector|
autocorrect(corrector, node)
end
end
private
def allowed_context?(node)
return false unless (class_node = node.each_ancestor(:class, :block).first)
(!class_node.class_type? && !class_eval?(class_node)) || define_attr_method?(class_node)
end
def define_attr_method?(node)
node.each_descendant(:def).any? { |def_node| def_node.method?(:attr) }
end
def autocorrect(corrector, node)
attr_name, setter = *node.arguments
node_expr = node.source_range
attr_expr = attr_name.source_range
remove = range_between(attr_expr.end_pos, node_expr.end_pos) if setter&.boolean_type?
corrector.replace(node.loc.selector, replacement_method(node))
corrector.remove(remove) if remove
end
def message(node)
format(MSG, replacement: replacement_method(node))
end
def replacement_method(node)
setter = node.last_argument
if setter&.boolean_type?
setter.true_type? ? 'attr_accessor' : 'attr_reader'
else
'attr_reader'
end
end
# @!method class_eval?(node)
def_node_matcher :class_eval?, <<~PATTERN
(block (send _ {:class_eval :module_eval}) ...)
PATTERN
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/auto_resource_cleanup.rb | lib/rubocop/cop/style/auto_resource_cleanup.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for cases when you could use a block
# accepting version of a method that does automatic
# resource cleanup.
#
# @example
#
# # bad
# f = File.open('file')
#
# # good
# File.open('file') do |f|
# # ...
# end
#
# # bad
# f = Tempfile.open('temp')
#
# # good
# Tempfile.open('temp') do |f|
# # ...
# end
class AutoResourceCleanup < Base
MSG = 'Use the block version of `%<current>s`.'
RESTRICT_ON_SEND = %i[open].freeze
# @!method file_open_method?(node)
def_node_matcher :file_open_method?, <<~PATTERN
(send (const {nil? cbase} {:File :Tempfile}) :open ...)
PATTERN
def on_send(node)
return if !file_open_method?(node) || cleanup?(node)
current = node.receiver.source_range.begin.join(node.selector.end).source
add_offense(node, message: format(MSG, current: current))
end
private
def cleanup?(node)
return true if node.block_argument?
return false unless (parent = node.parent)
parent.block_type? || !parent.lvasgn_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/style/if_with_semicolon.rb | lib/rubocop/cop/style/if_with_semicolon.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for uses of semicolon in if statements.
#
# @example
#
# # bad
# result = if some_condition; something else another_thing end
#
# # good
# result = some_condition ? something : another_thing
#
class IfWithSemicolon < Base
include OnNormalIfUnless
extend AutoCorrector
MSG_IF_ELSE = 'Do not use `if %<expr>s;` - use `if/else` instead.'
MSG_NEWLINE = 'Do not use `if %<expr>s;` - use a newline instead.'
MSG_TERNARY = 'Do not use `if %<expr>s;` - use a ternary operator instead.'
def on_normal_if_unless(node)
return if node.parent&.if_type?
return if part_of_ignored_node?(node)
beginning = node.loc.begin
return unless beginning&.is?(';')
message = message(node)
add_offense(node, message: message) do |corrector|
autocorrect(corrector, node)
end
ignore_node(node)
end
private
def message(node)
template = if require_newline?(node)
MSG_NEWLINE
elsif node.else_branch&.type?(:if, :begin) ||
use_masgn_or_block_in_branches?(node)
MSG_IF_ELSE
else
MSG_TERNARY
end
format(template, expr: node.condition.source)
end
def autocorrect(corrector, node)
if require_newline?(node) || use_masgn_or_block_in_branches?(node)
corrector.replace(node.loc.begin, "\n")
else
corrector.replace(node, replacement(node))
end
end
def require_newline?(node)
node.branches.compact.any?(&:begin_type?) || use_return_with_argument?(node)
end
def use_masgn_or_block_in_branches?(node)
node.branches.compact.any? do |branch|
branch.type?(:masgn, :any_block)
end
end
def use_return_with_argument?(node)
node.if_branch&.return_type? && node.if_branch&.arguments&.any?
end
def replacement(node)
return correct_elsif(node) if node.else_branch&.if_type?
then_code = node.if_branch ? build_expression(node.if_branch) : 'nil'
else_code = node.else_branch ? build_expression(node.else_branch) : 'nil'
"#{node.condition.source} ? #{then_code} : #{else_code}"
end
def correct_elsif(node)
<<~RUBY.chop
if #{node.condition.source}
#{node.if_branch&.source}
#{build_else_branch(node.else_branch).chop}
end
RUBY
end
def build_expression(expr)
return expr.source unless require_argument_parentheses?(expr)
method = expr.source_range.begin.join(expr.loc.selector.end)
arguments = expr.first_argument.source_range.begin.join(expr.source_range.end)
"#{method.source}(#{arguments.source})"
end
def build_else_branch(second_condition)
result = <<~RUBY
elsif #{second_condition.condition.source}
#{second_condition.if_branch&.source}
RUBY
if second_condition.else_branch
result += if second_condition.else_branch.if_type?
build_else_branch(second_condition.else_branch)
else
<<~RUBY
else
#{second_condition.else_branch.source}
RUBY
end
end
result
end
def require_argument_parentheses?(node)
return false if !node.call_type? || node.arithmetic_operation?
!node.parenthesized? && node.arguments.any? && !node.method?(:[]) && !node.method?(:[]=)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/while_until_modifier.rb | lib/rubocop/cop/style/while_until_modifier.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for while and until statements that would fit on one line
# if written as a modifier while/until. The maximum line length is
# configured in the `Layout/LineLength` cop.
#
# @example
# # bad
# while x < 10
# x += 1
# end
#
# # good
# x += 1 while x < 10
#
# # bad
# until x > 10
# x += 1
# end
#
# # good
# x += 1 until x > 10
#
# # bad
# x += 100 while x < 500 # a long comment that makes code too long if it were a single line
#
# # good
# while x < 500 # a long comment that makes code too long if it were a single line
# x += 100
# end
class WhileUntilModifier < Base
include StatementModifier
extend AutoCorrector
MSG = 'Favor modifier `%<keyword>s` usage when having a single-line body.'
def on_while(node)
return unless single_line_as_modifier?(node)
add_offense(node.loc.keyword, message: format(MSG, keyword: node.keyword)) do |corrector|
corrector.replace(node, to_modifier_form(node))
end
end
alias on_until on_while
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/stderr_puts.rb | lib/rubocop/cop/style/stderr_puts.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Identifies places where `$stderr.puts` can be replaced by
# `warn`. The latter has the advantage of easily being disabled by,
# the `-W0` interpreter flag or setting `$VERBOSE` to `nil`.
#
# @example
# # bad
# $stderr.puts('hello')
#
# # good
# warn('hello')
#
class StderrPuts < Base
include RangeHelp
extend AutoCorrector
MSG = 'Use `warn` instead of `%<bad>s` to allow such output to be disabled.'
RESTRICT_ON_SEND = %i[puts].freeze
# @!method stderr_puts?(node)
def_node_matcher :stderr_puts?, <<~PATTERN
(send
{(gvar #stderr_gvar?) (const {nil? cbase} :STDERR)}
:puts $_
...)
PATTERN
def on_send(node)
return unless stderr_puts?(node)
message = message(node)
add_offense(stderr_puts_range(node), message: message) do |corrector|
corrector.replace(stderr_puts_range(node), 'warn')
end
end
private
def message(node)
format(MSG, bad: "#{node.receiver.source}.#{node.method_name}")
end
def stderr_gvar?(sym)
sym == :$stderr
end
def stderr_puts_range(send)
range_between(send.source_range.begin_pos, send.loc.selector.end_pos)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/super_with_args_parentheses.rb | lib/rubocop/cop/style/super_with_args_parentheses.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Enforces the presence of parentheses in `super` containing arguments.
#
# `super` is a keyword and is provided as a distinct cop from those designed for method call.
#
# @example
#
# # bad
# super name, age
#
# # good
# super(name, age)
#
class SuperWithArgsParentheses < Base
extend AutoCorrector
MSG = 'Use parentheses for `super` with arguments.'
def on_super(node)
return if node.parenthesized?
add_offense(node) do |corrector|
range = node.loc.keyword.end.join(node.first_argument.source_range.begin)
corrector.replace(range, '(')
corrector.insert_after(node.last_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/style/array_intersect.rb | lib/rubocop/cop/style/array_intersect.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# In Ruby 3.1, `Array#intersect?` has been added.
#
# This cop identifies places where:
#
# * `(array1 & array2).any?`
# * `(array1.intersection(array2)).any?`
# * `array1.any? { |elem| array2.member?(elem) }`
# * `(array1 & array2).count > 0`
# * `(array1 & array2).size > 0`
#
# can be replaced with `array1.intersect?(array2)`.
#
# `array1.intersect?(array2)` is faster and more readable.
#
# In cases like the following, compatibility is not ensured,
# so it will not be detected when using block argument.
#
# [source,ruby]
# ----
# ([1] & [1,2]).any? { |x| false } # => false
# [1].intersect?([1,2]) { |x| false } # => true
# ----
#
# NOTE: Although `Array#intersection` can take zero or multiple arguments,
# only cases where exactly one argument is provided can be replaced with
# `Array#intersect?` and are handled by this cop.
#
# @safety
# This cop cannot guarantee that `array1` and `array2` are
# actually arrays while method `intersect?` is for arrays only.
#
# @example
# # bad
# (array1 & array2).any?
# (array1 & array2).empty?
# (array1 & array2).none?
#
# # bad
# array1.intersection(array2).any?
# array1.intersection(array2).empty?
# array1.intersection(array2).none?
#
# # bad
# array1.any? { |elem| array2.member?(elem) }
# array1.none? { |elem| array2.member?(elem) }
#
# # good
# array1.intersect?(array2)
# !array1.intersect?(array2)
#
# # bad
# (array1 & array2).count > 0
# (array1 & array2).count.positive?
# (array1 & array2).count != 0
#
# (array1 & array2).count == 0
# (array1 & array2).count.zero?
#
# # good
# array1.intersect?(array2)
#
# !array1.intersect?(array2)
#
# @example AllCops:ActiveSupportExtensionsEnabled: false (default)
# # good
# (array1 & array2).present?
# (array1 & array2).blank?
#
# @example AllCops:ActiveSupportExtensionsEnabled: true
# # bad
# (array1 & array2).present?
# (array1 & array2).blank?
#
# # good
# array1.intersect?(array2)
# !array1.intersect?(array2)
class ArrayIntersect < Base
extend AutoCorrector
extend TargetRubyVersion
minimum_target_ruby_version 3.1
PREDICATES = %i[any? empty? none?].to_set.freeze
ACTIVE_SUPPORT_PREDICATES = (PREDICATES + %i[present? blank?]).freeze
ARRAY_SIZE_METHODS = %i[count length size].to_set.freeze
# @!method bad_intersection_check?(node, predicates)
def_node_matcher :bad_intersection_check?, <<~PATTERN
$(call
{
(begin (send $_ :& $_))
(call $!nil? :intersection $_)
}
$%1
)
PATTERN
# @!method intersection_size_check?(node, predicates)
def_node_matcher :intersection_size_check?, <<~PATTERN
(call
$(call
{
(begin (send $_ :& $_))
(call $!nil? :intersection $_)
}
%ARRAY_SIZE_METHODS
)
{$:> (int 0) | $:positive? | $:!= (int 0) | $:== (int 0) | $:zero?}
)
PATTERN
# @!method any_none_block_intersection(node)
def_node_matcher :any_none_block_intersection, <<~PATTERN
{
(block
(call $_receiver ${:any? :none?})
(args (arg _key))
(send $_argument :member? (lvar _key))
)
(numblock
(call $_receiver ${:any? :none?}) 1
(send $_argument :member? (lvar :_1))
)
(itblock
(call $_receiver ${:any? :none?}) :it
(send $_argument :member? (lvar :it))
)
}
PATTERN
MSG = 'Use `%<replacement>s` instead of `%<existing>s`.'
STRAIGHT_METHODS = %i[present? any? > positive? !=].freeze
NEGATED_METHODS = %i[blank? empty? none? == zero?].freeze
RESTRICT_ON_SEND = (STRAIGHT_METHODS + NEGATED_METHODS).freeze
def on_send(node)
return if node.block_literal?
return unless (dot_node, receiver, argument, method_name = bad_intersection?(node))
dot = dot_node.loc.dot.source
bang = straight?(method_name) ? '' : '!'
replacement = "#{bang}#{receiver.source}#{dot}intersect?(#{argument.source})"
register_offense(node, replacement)
end
alias on_csend on_send
def on_block(node)
return unless (receiver, method_name, argument = any_none_block_intersection(node))
dot = node.send_node.loc.dot.source
bang = method_name == :any? ? '' : '!'
replacement = "#{bang}#{receiver.source}#{dot}intersect?(#{argument.source})"
register_offense(node, replacement)
end
alias on_numblock on_block
alias on_itblock on_block
private
def bad_intersection?(node)
bad_intersection_check?(node, bad_intersection_predicates) ||
intersection_size_check?(node)
end
def bad_intersection_predicates
if active_support_extensions_enabled?
ACTIVE_SUPPORT_PREDICATES
else
PREDICATES
end
end
def straight?(method_name)
STRAIGHT_METHODS.include?(method_name.to_sym)
end
def register_offense(node, replacement)
message = format(MSG, replacement: replacement, existing: node.source)
add_offense(node, message: message) do |corrector|
corrector.replace(node, replacement)
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/super_arguments.rb | lib/rubocop/cop/style/super_arguments.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for redundant argument forwarding when calling super with arguments identical to
# the method definition.
#
# Using zero arity `super` within a `define_method` block results in `RuntimeError`:
#
# [source,ruby]
# ----
# def m
# define_method(:foo) { super() } # => OK
# end
#
# def m
# define_method(:foo) { super } # => RuntimeError
# end
# ----
#
# Furthermore, any arguments accompanied by a block may potentially be delegating to
# `define_method`, therefore, `super` used within these blocks will be allowed.
# This approach might result in false negatives, yet ensuring safe detection takes precedence.
#
# NOTE: When forwarding the same arguments but replacing the block argument with a new inline
# block, it is not necessary to explicitly list the non-block arguments. As such, an offense
# will be registered in this case.
#
# @example
# # bad
# def method(*args, **kwargs)
# super(*args, **kwargs)
# end
#
# # good - implicitly passing all arguments
# def method(*args, **kwargs)
# super
# end
#
# # good - forwarding a subset of the arguments
# def method(*args, **kwargs)
# super(*args)
# end
#
# # good - forwarding no arguments
# def method(*args, **kwargs)
# super()
# end
#
# # bad - forwarding with overridden block
# def method(*args, **kwargs, &block)
# super(*args, **kwargs) { do_something }
# end
#
# # good - implicitly passing all non-block arguments
# def method(*args, **kwargs, &block)
# super { do_something }
# end
#
# # good - assigning to the block variable before calling super
# def method(&block)
# # Assigning to the block variable would pass the old value to super,
# # under this circumstance the block must be referenced explicitly.
# block ||= proc { 'fallback behavior' }
# super(&block)
# end
class SuperArguments < Base
extend AutoCorrector
ASSIGN_TYPES = %i[or_asgn lvasgn].freeze
MSG = 'Call `super` without arguments and parentheses when the signature is identical.'
MSG_INLINE_BLOCK = 'Call `super` without arguments and parentheses when all positional ' \
'and keyword arguments are forwarded.'
def on_super(super_node)
return unless (def_node = find_def_node(super_node))
def_node_args = def_node.arguments.argument_list
super_args = preprocess_super_args(super_node.arguments)
return unless arguments_identical?(def_node, super_node, def_node_args, super_args)
# If the number of arguments to the def node and super node are different here,
# it's because the block argument is not forwarded.
message = def_node_args.size == super_args.size ? MSG : MSG_INLINE_BLOCK
add_offense(super_node, message: message) do |corrector|
corrector.replace(super_node, 'super')
end
end
private
def find_def_node(super_node)
super_node.ancestors.find do |node|
# When defining dynamic methods, implicitly calling `super` is not possible.
# Since there is a possibility of delegation to `define_method`,
# `super` used within the block is always allowed.
break if node.any_block_type? && !block_sends_to_super?(super_node, node)
break node if node.any_def_type?
end
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def arguments_identical?(def_node, super_node, def_args, super_args)
return false if argument_list_size_differs?(def_args, super_args, super_node)
def_args.zip(super_args).each do |def_arg, super_arg|
next if positional_arg_same?(def_arg, super_arg)
next if positional_rest_arg_same?(def_arg, super_arg)
next if keyword_arg_same?(def_arg, super_arg)
next if keyword_rest_arg_same?(def_arg, super_arg)
next if block_arg_same?(def_node, super_node, def_arg, super_arg)
next if forward_arg_same?(def_arg, super_arg)
return false
end
true
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def argument_list_size_differs?(def_args, super_args, super_node)
# If the def node has a block argument and the super node has an explicit block,
# the number of arguments is the same, so ignore the def node block arg.
def_args_size = def_args.size
def_args_size -= 1 if def_args.any?(&:blockarg_type?) && block_sends_to_super?(super_node)
def_args_size != super_args.size
end
def block_sends_to_super?(super_node, parent_node = super_node.parent)
# Checks if the send node of a block is the given super node,
# or a method chain containing it.
return false unless parent_node
return false unless parent_node.any_block_type?
parent_node.send_node.each_node(:super).any?(super_node)
end
def positional_arg_same?(def_arg, super_arg)
return false unless def_arg.type?(:arg, :optarg)
return false unless super_arg.lvar_type?
def_arg.name == super_arg.children.first
end
def positional_rest_arg_same?(def_arg, super_arg)
return false unless def_arg.restarg_type?
# anonymous forwarding
return true if def_arg.name.nil? && super_arg.forwarded_restarg_type?
return false unless super_arg.splat_type?
return false unless (lvar_node = super_arg.children.first).lvar_type?
def_arg.name == lvar_node.children.first
end
def keyword_arg_same?(def_arg, super_arg)
return false unless def_arg.type?(:kwarg, :kwoptarg)
return false unless (pair_node = super_arg).pair_type?
return false unless (sym_node = pair_node.key).sym_type?
return false unless (lvar_node = pair_node.value).lvar_type?
return false unless sym_node.source == lvar_node.source
def_arg.name == sym_node.value
end
def keyword_rest_arg_same?(def_arg, super_arg)
return false unless def_arg.kwrestarg_type?
# anonymous forwarding
return true if def_arg.name.nil? && super_arg.forwarded_kwrestarg_type?
return false unless super_arg.kwsplat_type?
return false unless (lvar_node = super_arg.children.first).lvar_type?
def_arg.name == lvar_node.children.first
end
def block_arg_same?(def_node, super_node, def_arg, super_arg)
return false unless def_arg.blockarg_type?
return true if block_sends_to_super?(super_node)
return false unless super_arg.block_pass_type?
# anonymous forwarding
return true if (block_pass_child = super_arg.children.first).nil? && def_arg.name.nil?
block_arg_name = block_pass_child.children.first
def_arg.name == block_arg_name && !block_reassigned?(def_node, block_arg_name)
end
# Reassigning the block argument will still pass along the original block to super
# https://bugs.ruby-lang.org/issues/20505
def block_reassigned?(def_node, block_arg_name)
def_node.each_node(*ASSIGN_TYPES).any? do |assign_node|
# TODO: Since `Symbol#name` is supported from Ruby 3.0, the inheritance check for
# `AST::Node` can be removed when requiring Ruby 3.0+.
lhs = assign_node.node_parts[0]
next if lhs.is_a?(AST::Node) && !lhs.respond_to?(:name)
assign_node.name == block_arg_name
end
end
def forward_arg_same?(def_arg, super_arg)
def_arg.forward_arg_type? && super_arg.forwarded_args_type?
end
def preprocess_super_args(super_args)
super_args.flat_map do |node|
if node.hash_type? && !node.braces?
node.children
else
node
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/style/redundant_double_splat_hash_braces.rb | lib/rubocop/cop/style/redundant_double_splat_hash_braces.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for redundant uses of double splat hash braces.
#
# @example
#
# # bad
# do_something(**{foo: bar, baz: qux})
#
# # good
# do_something(foo: bar, baz: qux)
#
# # bad
# do_something(**{foo: bar, baz: qux}.merge(options))
#
# # good
# do_something(foo: bar, baz: qux, **options)
#
class RedundantDoubleSplatHashBraces < Base
extend AutoCorrector
MSG = 'Remove the redundant double splat and braces, use keyword arguments directly.'
MERGE_METHODS = %i[merge merge!].freeze
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def on_hash(node)
return if node.pairs.empty? || node.pairs.any?(&:hash_rocket?)
return unless (parent = node.parent)
return unless parent.type?(:call, :kwsplat)
return unless mergeable?(parent)
return unless (kwsplat = node.each_ancestor(:kwsplat).first)
return if !node.braces? || allowed_double_splat_receiver?(kwsplat)
add_offense(kwsplat) do |corrector|
autocorrect(corrector, node, kwsplat)
end
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
private
def allowed_double_splat_receiver?(kwsplat)
first_child = kwsplat.children.first
return true if first_child.any_block_type?
return false unless first_child.call_type?
root_receiver = root_receiver(first_child)
!root_receiver&.hash_type?
end
def autocorrect(corrector, node, kwsplat)
corrector.remove(kwsplat.loc.operator)
corrector.remove(opening_brace(node))
corrector.remove(closing_brace(node))
merge_methods = select_merge_method_nodes(kwsplat)
return if merge_methods.empty?
autocorrect_merge_methods(corrector, merge_methods, kwsplat)
end
def root_receiver(node)
receiver = node.receiver
if receiver&.receiver
root_receiver(receiver)
else
receiver
end
end
def select_merge_method_nodes(kwsplat)
kwsplat.each_descendant(:call).select do |node|
mergeable?(node)
end
end
def opening_brace(node)
node.loc.begin.join(node.children.first.source_range.begin)
end
def closing_brace(node)
node.children.last.source_range.end.join(node.loc.end)
end
def autocorrect_merge_methods(corrector, merge_methods, kwsplat)
range = range_of_merge_methods(merge_methods)
new_kwsplat_arguments = kwsplat.each_descendant(:call).map do |descendant|
convert_to_new_arguments(descendant)
end
new_source = new_kwsplat_arguments.compact.reverse.unshift('').join(', ')
corrector.replace(range, new_source)
end
def range_of_merge_methods(merge_methods)
begin_merge_method = merge_methods.last
end_merge_method = merge_methods.first
begin_merge_method.loc.dot.begin.join(end_merge_method.source_range.end)
end
def convert_to_new_arguments(node)
return unless mergeable?(node)
node.arguments.map do |arg|
if arg.hash_type?
arg.source
else
"**#{arg.source}"
end
end
end
def mergeable?(node)
return true unless node.call_type?
return false unless MERGE_METHODS.include?(node.method_name)
return true unless (parent = node.parent)
mergeable?(parent)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/while_until_do.rb | lib/rubocop/cop/style/while_until_do.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for uses of `do` in multi-line `while/until` statements.
#
# @example
#
# # bad
# while x.any? do
# do_something(x.pop)
# end
#
# # good
# while x.any?
# do_something(x.pop)
# end
#
# # bad
# until x.empty? do
# do_something(x.pop)
# end
#
# # good
# until x.empty?
# do_something(x.pop)
# end
class WhileUntilDo < Base
extend AutoCorrector
MSG = 'Do not use `do` with multi-line `%<keyword>s`.'
def on_while(node)
return unless node.multiline? && node.do?
add_offense(node.loc.begin, message: format(MSG, keyword: node.keyword)) do |corrector|
do_range = node.condition.source_range.end.join(node.loc.begin)
corrector.remove(do_range)
end
end
alias on_until on_while
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/numbered_parameters.rb | lib/rubocop/cop/style/numbered_parameters.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for numbered parameters.
#
# It can either restrict the use of numbered parameters to
# single-lined blocks, or disallow completely numbered parameters.
#
# @example EnforcedStyle: allow_single_line (default)
# # bad
# collection.each do
# puts _1
# end
#
# # good
# collection.each { puts _1 }
#
# @example EnforcedStyle: disallow
# # bad
# collection.each { puts _1 }
#
# # good
# collection.each { |item| puts item }
#
class NumberedParameters < Base
include ConfigurableEnforcedStyle
extend TargetRubyVersion
MSG_DISALLOW = 'Avoid using numbered parameters.'
MSG_MULTI_LINE = 'Avoid using numbered parameters for multi-line blocks.'
minimum_target_ruby_version 2.7
def on_numblock(node)
if style == :disallow
add_offense(node, message: MSG_DISALLOW)
elsif node.multiline?
add_offense(node, message: MSG_MULTI_LINE)
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_capital_w.rb | lib/rubocop/cop/style/redundant_capital_w.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for usage of the %W() syntax when %w() would do.
#
# @example
# # bad
# %W(cat dog pig)
# %W[door wall floor]
#
# # good
# %w/swim run bike/
# %w[shirt pants shoes]
# %W(apple #{fruit} grape)
class RedundantCapitalW < Base
include PercentLiteral
extend AutoCorrector
MSG = 'Do not use `%W` unless interpolation is needed. If not, use `%w`.'
def on_array(node)
process(node, '%W')
end
private
def on_percent_literal(node)
return if requires_interpolation?(node)
add_offense(node) do |corrector|
src = node.loc.begin.source
corrector.replace(node.loc.begin, src.tr('W', 'w'))
end
end
def requires_interpolation?(node)
node.child_nodes.any? do |string|
string.dstr_type? || double_quotes_required?(string.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/style/zero_length_predicate.rb | lib/rubocop/cop/style/zero_length_predicate.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for numeric comparisons that can be replaced
# by a predicate method, such as `receiver.length == 0`,
# `receiver.length > 0`, and `receiver.length != 0`,
# `receiver.length < 1` and `receiver.size == 0` that can be
# replaced by `receiver.empty?` and `!receiver.empty?`.
#
# NOTE: `File`, `Tempfile`, and `StringIO` do not have `empty?`
# so allow `size == 0` and `size.zero?`.
#
# @safety
# This cop is unsafe because it cannot be guaranteed that the receiver
# has an `empty?` method that is defined in terms of `length`. If there
# is a non-standard class that redefines `length` or `empty?`, the cop
# may register a false positive.
#
# @example
# # bad
# [1, 2, 3].length == 0
# 0 == "foobar".length
# array.length < 1
# {a: 1, b: 2}.length != 0
# string.length > 0
# hash.size > 0
#
# # good
# [1, 2, 3].empty?
# "foobar".empty?
# array.empty?
# !{a: 1, b: 2}.empty?
# !string.empty?
# !hash.empty?
class ZeroLengthPredicate < Base
extend AutoCorrector
ZERO_MSG = 'Use `empty?` instead of `%<current>s`.'
NONZERO_MSG = 'Use `!empty?` instead of `%<current>s`.'
RESTRICT_ON_SEND = %i[size length].freeze
def on_send(node)
check_zero_length_predicate(node)
check_zero_length_comparison(node)
check_nonzero_length_comparison(node)
end
def on_csend(node)
check_zero_length_predicate(node)
check_zero_length_comparison(node)
end
private
def check_zero_length_predicate(node)
return unless zero_length_predicate?(node.parent)
return if non_polymorphic_collection?(node.parent)
offense = node.loc.selector.join(node.parent.source_range.end)
message = format(ZERO_MSG, current: offense.source)
add_offense(offense, message: message) do |corrector|
corrector.replace(offense, 'empty?')
end
end
def check_zero_length_comparison(node)
zero_length_comparison = zero_length_comparison(node.parent)
return unless zero_length_comparison
lhs, opr, rhs = zero_length_comparison
return if non_polymorphic_collection?(node.parent)
add_offense(
node.parent, message: format(ZERO_MSG, current: "#{lhs} #{opr} #{rhs}")
) do |corrector|
corrector.replace(node.parent, replacement(node.parent))
end
end
def check_nonzero_length_comparison(node)
nonzero_length_comparison = nonzero_length_comparison(node.parent)
return unless nonzero_length_comparison
lhs, opr, rhs = nonzero_length_comparison
return if non_polymorphic_collection?(node.parent)
add_offense(
node.parent, message: format(NONZERO_MSG, current: "#{lhs} #{opr} #{rhs}")
) do |corrector|
corrector.replace(node.parent, replacement(node.parent))
end
end
# @!method zero_length_predicate?(node)
def_node_matcher :zero_length_predicate?, <<~PATTERN
(call (call (...) {:length :size}) :zero?)
PATTERN
# @!method zero_length_comparison(node)
def_node_matcher :zero_length_comparison, <<~PATTERN
{(call (call (...) ${:length :size}) $:== (int $0))
(call (int $0) $:== (call (...) ${:length :size}))
(call (call (...) ${:length :size}) $:< (int $1))
(call (int $1) $:> (call (...) ${:length :size}))}
PATTERN
# @!method nonzero_length_comparison(node)
def_node_matcher :nonzero_length_comparison, <<~PATTERN
{(call (call (...) ${:length :size}) ${:> :!=} (int $0))
(call (int $0) ${:< :!=} (call (...) ${:length :size}))}
PATTERN
def replacement(node)
length_node = zero_length_node(node)
if length_node&.receiver
return "#{length_node.receiver.source}#{length_node.loc.dot.source}empty?"
end
other_length_node = other_length_node(node)
"!#{other_length_node.receiver.source}#{other_length_node.loc.dot.source}empty?"
end
# @!method zero_length_node(node)
def_node_matcher :zero_length_node, <<~PATTERN
{(send $(call _ _) :== (int 0))
(send (int 0) :== $(call _ _))
(send $(call _ _) :< (int 1))
(send (int 1) :> $(call _ _))}
PATTERN
# @!method other_length_node(node)
def_node_matcher :other_length_node, <<~PATTERN
{(call $(call _ _) _ _)
(call _ _ $(call _ _))}
PATTERN
# Some collection like objects in the Ruby standard library
# implement `#size`, but not `#empty`. We ignore those to
# reduce false positives.
# @!method non_polymorphic_collection?(node)
def_node_matcher :non_polymorphic_collection?, <<~PATTERN
{(send (send (send (const {nil? cbase} :File) :stat _) ...) ...)
(send (send (send (const {nil? cbase} {:File :Tempfile :StringIO}) {:new :open} ...) ...) ...)}
PATTERN
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_self.rb | lib/rubocop/cop/style/redundant_self.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for redundant uses of `self`.
#
# The usage of `self` is only needed when:
#
# * Sending a message to same object with zero arguments in
# presence of a method name clash with an argument or a local
# variable.
#
# * Calling an attribute writer to prevent a local variable assignment.
#
# Note, with using explicit self you can only send messages with public or
# protected scope, you cannot send private messages this way.
#
# Note we allow uses of `self` with operators because it would be awkward
# otherwise. Also allows the use of `self.it` without arguments in blocks,
# as in `0.times { self.it }`, following `Lint/ItWithoutArgumentsInBlock` cop.
#
# @example
#
# # bad
# def foo(bar)
# self.baz
# end
#
# # good
# def foo(bar)
# self.bar # Resolves name clash with the argument.
# end
#
# def foo
# bar = 1
# self.bar # Resolves name clash with the local variable.
# end
#
# def foo
# %w[x y z].select do |bar|
# self.bar == bar # Resolves name clash with argument of the block.
# end
# end
class RedundantSelf < Base
extend AutoCorrector
MSG = 'Redundant `self` detected.'
KERNEL_METHODS = Kernel.methods(false)
KEYWORDS = %i[alias and begin break case class def defined? do
else elsif end ensure false for if in module
next nil not or redo rescue retry return self
super then true undef unless until when while
yield __FILE__ __LINE__ __ENCODING__].freeze
def self.autocorrect_incompatible_with
[ColonMethodCall, Layout::DotPosition]
end
def initialize(config = nil, options = nil)
super
@allowed_send_nodes = []
@local_variables_scopes = Hash.new { |hash, key| hash[key] = [] }.compare_by_identity
end
# Assignment of self.x
def on_or_asgn(node)
allow_self(node.lhs)
lhs_name = node.lhs.lvasgn_type? ? node.lhs.name : node.lhs
add_lhs_to_local_variables_scopes(node.rhs, lhs_name)
end
alias on_and_asgn on_or_asgn
def on_op_asgn(node)
allow_self(node.lhs)
end
# Using self.x to distinguish from local variable x
def on_def(node)
add_scope(node)
end
alias on_defs on_def
def on_args(node)
node.children.each { |arg| on_argument(arg) }
end
def on_blockarg(node)
on_argument(node)
end
def on_masgn(node)
add_masgn_lhs_variables(node.rhs, node.lhs)
end
def on_lvasgn(node)
add_lhs_to_local_variables_scopes(node.rhs, node.lhs)
end
def on_in_pattern(node)
add_match_var_scopes(node)
end
def on_send(node)
return unless node.self_receiver? && regular_method_call?(node)
return if node.parent&.mlhs_type?
return if allowed_send_node?(node)
return if it_method_in_block?(node)
add_offense(node.receiver) do |corrector|
corrector.remove(node.receiver)
corrector.remove(node.loc.dot)
end
end
def on_block(node)
add_scope(node, @local_variables_scopes[node])
end
alias on_numblock on_block
alias on_itblock on_block
def on_if(node)
# Allow conditional nodes to use `self` in the condition if that variable
# name is used in an `lvasgn` or `masgn` within the `if`.
node.each_descendant(:lvasgn, :masgn) do |descendant_node|
if descendant_node.lvasgn_type?
add_lhs_to_local_variables_scopes(node.condition, descendant_node.lhs)
else
add_masgn_lhs_variables(node.condition, descendant_node.lhs)
end
end
end
alias on_while on_if
alias on_until on_if
private
def add_scope(node, local_variables = [])
node.each_descendant do |child_node|
@local_variables_scopes[child_node] = local_variables
end
end
def allowed_send_node?(node)
@allowed_send_nodes.include?(node) ||
@local_variables_scopes[node].include?(node.method_name) ||
node.each_ancestor.any? do |ancestor|
@local_variables_scopes[ancestor].include?(node.method_name)
end ||
KERNEL_METHODS.include?(node.method_name)
end
# Respects `Lint/ItWithoutArgumentsInBlock` cop and the following Ruby 3.3's warning:
#
# $ ruby -e '0.times { begin; it; end }'
# -e:1: warning: `it` calls without arguments will refer to the first block param in
# Ruby 3.4; use it() or self.it
#
def it_method_in_block?(node)
return false unless node.method?(:it)
return false unless (block_node = node.each_ancestor(:block).first)
return false unless block_node.arguments.empty_and_without_delimiters?
node.arguments.empty? && !node.block_literal?
end
def regular_method_call?(node)
!(node.operator_method? ||
KEYWORDS.include?(node.method_name) ||
node.camel_case_method? ||
node.setter_method? ||
node.implicit_call?)
end
def on_argument(node)
if node.mlhs_type?
on_args(node)
elsif node.respond_to?(:name)
@local_variables_scopes[node] << node.name
end
end
def allow_self(node)
return unless node.send_type? && node.self_receiver?
@allowed_send_nodes << node
end
def add_lhs_to_local_variables_scopes(rhs, lhs)
if rhs&.send_type? && !rhs.arguments.empty?
rhs.arguments.each { |argument| @local_variables_scopes[argument] << lhs }
else
@local_variables_scopes[rhs] << lhs
end
end
def add_masgn_lhs_variables(rhs, lhs)
lhs.children.each do |child|
add_lhs_to_local_variables_scopes(rhs, child.to_a.first)
end
end
def add_match_var_scopes(in_pattern_node)
in_pattern_node.each_descendant(:match_var) do |match_var_node|
@local_variables_scopes[in_pattern_node] << match_var_node.children.first
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/negated_if.rb | lib/rubocop/cop/style/negated_if.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for uses of if with a negated condition. Only ifs
# without else are considered. There are three different styles:
#
# * both
# * prefix
# * postfix
#
# @example EnforcedStyle: both (default)
# # enforces `unless` for `prefix` and `postfix` conditionals
#
# # bad
#
# if !foo
# bar
# end
#
# # good
#
# unless foo
# bar
# end
#
# # bad
#
# bar if !foo
#
# # good
#
# bar unless foo
#
# @example EnforcedStyle: prefix
# # enforces `unless` for just `prefix` conditionals
#
# # bad
#
# if !foo
# bar
# end
#
# # good
#
# unless foo
# bar
# end
#
# # good
#
# bar if !foo
#
# @example EnforcedStyle: postfix
# # enforces `unless` for just `postfix` conditionals
#
# # bad
#
# bar if !foo
#
# # good
#
# bar unless foo
#
# # good
#
# if !foo
# bar
# end
class NegatedIf < Base
include ConfigurableEnforcedStyle
include NegativeConditional
extend AutoCorrector
def on_if(node)
return if node.unless? || node.elsif? || node.ternary?
return if correct_style?(node)
message = message(node)
check_negative_conditional(node, message: message) do |corrector|
ConditionCorrector.correct_negative_condition(corrector, node)
end
end
private
def message(node)
format(MSG, inverse: node.inverse_keyword, current: node.keyword)
end
def correct_style?(node)
(style == :prefix && node.modifier_form?) || (style == :postfix && !node.modifier_form?)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/document_dynamic_eval_definition.rb | lib/rubocop/cop/style/document_dynamic_eval_definition.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# When using `class_eval` (or other `eval`) with string interpolation,
# add a comment block showing its appearance if interpolated (a practice used in Rails code).
#
# @example
# # from activesupport/lib/active_support/core_ext/string/output_safety.rb
#
# # bad
# UNSAFE_STRING_METHODS.each do |unsafe_method|
# if 'String'.respond_to?(unsafe_method)
# class_eval <<-EOT, __FILE__, __LINE__ + 1
# def #{unsafe_method}(*params, &block)
# to_str.#{unsafe_method}(*params, &block)
# end
#
# def #{unsafe_method}!(*params)
# @dirty = true
# super
# end
# EOT
# end
# end
#
# # good, inline comments in heredoc
# UNSAFE_STRING_METHODS.each do |unsafe_method|
# if 'String'.respond_to?(unsafe_method)
# class_eval <<-EOT, __FILE__, __LINE__ + 1
# def #{unsafe_method}(*params, &block) # def capitalize(*params, &block)
# to_str.#{unsafe_method}(*params, &block) # to_str.capitalize(*params, &block)
# end # end
#
# def #{unsafe_method}!(*params) # def capitalize!(*params)
# @dirty = true # @dirty = true
# super # super
# end # end
# EOT
# end
# end
#
# # good, block comments in heredoc
# class_eval <<-EOT, __FILE__, __LINE__ + 1
# # def capitalize!(*params)
# # @dirty = true
# # super
# # end
#
# def #{unsafe_method}!(*params)
# @dirty = true
# super
# end
# EOT
#
# # good, block comments before heredoc
# class_eval(
# # def capitalize!(*params)
# # @dirty = true
# # super
# # end
#
# <<-EOT, __FILE__, __LINE__ + 1
# def #{unsafe_method}!(*params)
# @dirty = true
# super
# end
# EOT
# )
#
# # bad - interpolated string without comment
# class_eval("def #{unsafe_method}!(*params); end")
#
# # good - with inline comment or replace it with block comment using heredoc
# class_eval("def #{unsafe_method}!(*params); end # def capitalize!(*params); end")
class DocumentDynamicEvalDefinition < Base
BLOCK_COMMENT_REGEXP = /^\s*#(?!{)/.freeze
COMMENT_REGEXP = /\s*#(?!{).*/.freeze
MSG = 'Add a comment block showing its appearance if interpolated.'
RESTRICT_ON_SEND = %i[eval class_eval module_eval instance_eval].freeze
def on_send(node)
arg_node = node.first_argument
return unless arg_node&.dstr_type? && interpolated?(arg_node)
return if inline_comment_docs?(arg_node) ||
(arg_node.heredoc? && comment_block_docs?(arg_node))
add_offense(node.loc.selector)
end
private
def interpolated?(arg_node)
arg_node.each_child_node(:begin).any?
end
def inline_comment_docs?(node)
node.each_child_node(:begin).all? do |begin_node|
source_line = processed_source.lines[begin_node.first_line - 1]
source_line.match?(COMMENT_REGEXP)
end
end
def comment_block_docs?(arg_node)
comments = heredoc_comment_blocks(arg_node.loc.heredoc_body.line_span)
.concat(preceding_comment_blocks(arg_node.parent))
return false if comments.none?
regexp = comment_regexp(arg_node)
comments.any?(regexp) || regexp.match?(comments.join)
end
def preceding_comment_blocks(node)
# Collect comments in the method call, but outside the heredoc
comments = processed_source.each_comment_in_lines(node.source_range.line_span)
comments.each_with_object({}) do |comment, hash|
merge_adjacent_comments(comment.text, comment.loc.line, hash)
end.values
end
def heredoc_comment_blocks(heredoc_body)
# Collect comments inside the heredoc
line_range = (heredoc_body.begin - 1)..(heredoc_body.end - 1)
lines = processed_source.lines[line_range]
lines.each_with_object({}).with_index(line_range.begin) do |(line, hash), index|
merge_adjacent_comments(line, index, hash)
end.values
end
def merge_adjacent_comments(line, index, hash)
# Combine adjacent comment lines into a single string
return unless (line = line.dup.gsub!(BLOCK_COMMENT_REGEXP, ''))
hash[index] = if hash.keys.last == index - 1
[hash.delete(index - 1), line].join("\n")
else
line
end
end
def comment_regexp(arg_node)
# Replace the interpolations with wildcards
regexp_parts = arg_node.child_nodes.map do |n|
n.begin_type? ? /.+/ : source_to_regexp(n.source)
end
Regexp.new(regexp_parts.join)
end
def source_to_regexp(source)
# Get the source in the heredoc being `eval`ed, without any comments
# and turn it into a regexp
return /\s+/ if source.blank?
source = source.gsub(COMMENT_REGEXP, '')
return if source.blank?
/\s*#{Regexp.escape(source.strip)}/
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/special_global_vars.rb | lib/rubocop/cop/style/special_global_vars.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Looks for uses of Perl-style global variables.
# Correcting to global variables in the 'English' library
# will add a require statement to the top of the file if
# enabled by RequireEnglish config.
#
# @safety
# Autocorrection is marked as unsafe because if `RequireEnglish` is not
# true, replacing perl-style variables with english variables will break.
#
# @example EnforcedStyle: use_english_names (default)
# # good
# require 'English' # or this could be in another file.
#
# puts $LOAD_PATH
# puts $LOADED_FEATURES
# puts $PROGRAM_NAME
# puts $ERROR_INFO
# puts $ERROR_POSITION
# puts $FIELD_SEPARATOR # or $FS
# puts $OUTPUT_FIELD_SEPARATOR # or $OFS
# puts $INPUT_RECORD_SEPARATOR # or $RS
# puts $OUTPUT_RECORD_SEPARATOR # or $ORS
# puts $INPUT_LINE_NUMBER # or $NR
# puts $LAST_READ_LINE
# puts $DEFAULT_OUTPUT
# puts $DEFAULT_INPUT
# puts $PROCESS_ID # or $PID
# puts $CHILD_STATUS
# puts $LAST_MATCH_INFO
# puts $IGNORECASE
# puts $ARGV # or ARGV
#
# @example EnforcedStyle: use_perl_names
# # good
# puts $:
# puts $"
# puts $0
# puts $!
# puts $@
# puts $;
# puts $,
# puts $/
# puts $\
# puts $.
# puts $_
# puts $>
# puts $<
# puts $$
# puts $?
# puts $~
# puts $=
# puts $*
#
# @example EnforcedStyle: use_builtin_english_names
#
# # good
# # Like `use_perl_names` but allows builtin global vars.
# puts $LOAD_PATH
# puts $LOADED_FEATURES
# puts $PROGRAM_NAME
# puts ARGV
# puts $:
# puts $"
# puts $0
# puts $!
# puts $@
# puts $;
# puts $,
# puts $/
# puts $\
# puts $.
# puts $_
# puts $>
# puts $<
# puts $$
# puts $?
# puts $~
# puts $=
# puts $*
#
class SpecialGlobalVars < Base
include ConfigurableEnforcedStyle
include RangeHelp
include RequireLibrary
extend AutoCorrector
MSG_BOTH = 'Prefer `%<prefer>s` from the stdlib \'English\' ' \
'module (don\'t forget to require it) or `%<regular>s` over ' \
'`%<global>s`.'
MSG_ENGLISH = 'Prefer `%<prefer>s` from the stdlib \'English\' ' \
'module (don\'t forget to require it) over `%<global>s`.'
MSG_REGULAR = 'Prefer `%<prefer>s` over `%<global>s`.'
ENGLISH_VARS = { # rubocop:disable Style/MutableConstant
:$: => [:$LOAD_PATH],
:$" => [:$LOADED_FEATURES],
:$0 => [:$PROGRAM_NAME],
:$! => [:$ERROR_INFO],
:$@ => [:$ERROR_POSITION],
:$; => %i[$FIELD_SEPARATOR $FS],
:$, => %i[$OUTPUT_FIELD_SEPARATOR $OFS],
:$/ => %i[$INPUT_RECORD_SEPARATOR $RS],
:$\ => %i[$OUTPUT_RECORD_SEPARATOR $ORS],
:$. => %i[$INPUT_LINE_NUMBER $NR],
:$_ => [:$LAST_READ_LINE],
:$> => [:$DEFAULT_OUTPUT],
:$< => [:$DEFAULT_INPUT],
:$$ => %i[$PROCESS_ID $PID],
:$? => [:$CHILD_STATUS],
:$~ => [:$LAST_MATCH_INFO],
:$= => [:$IGNORECASE],
:$* => %i[$ARGV ARGV]
}
# Anything *not* in this set is provided by the English library.
NON_ENGLISH_VARS = Set.new(%i[$LOAD_PATH $LOADED_FEATURES $PROGRAM_NAME ARGV]).freeze
PERL_VARS = ENGLISH_VARS.flat_map { |k, vs| vs.map { |v| [v, [k]] } }.to_h
ENGLISH_VARS.merge!(ENGLISH_VARS.flat_map { |_, vs| vs.map { |v| [v, [v]] } }.to_h)
PERL_VARS.merge!(PERL_VARS.flat_map { |_, vs| vs.map { |v| [v, [v]] } }.to_h)
BUILTIN_VARS = PERL_VARS.merge(
NON_ENGLISH_VARS
.select { |v| v.to_s.start_with?('$') }
.flat_map { |v| [[v, [v]], PERL_VARS[v].flat_map { |a| [a, [v]] }] }
.to_h
)
ENGLISH_VARS.each_value(&:freeze).freeze
PERL_VARS.each_value(&:freeze).freeze
BUILTIN_VARS.each_value(&:freeze).freeze
STYLE_VARS_MAP = {
use_english_names: ENGLISH_VARS,
use_perl_names: PERL_VARS,
use_builtin_english_names: BUILTIN_VARS
}.freeze
LIBRARY_NAME = 'English'
def on_new_investigation
super
@required_english = false
end
def on_gvar(node)
global_var = node.name
return unless (preferred = preferred_names(global_var))
if preferred.include?(global_var)
correct_style_detected
else
style_detected(matching_styles(global_var))
add_offense(node, message: message(global_var)) do |corrector|
autocorrect(corrector, node, global_var)
end
end
end
def message(global_var)
if style == :use_english_names
format_english_message(global_var)
else
format(MSG_REGULAR, prefer: preferred_names(global_var).first, global: global_var)
end
end
def autocorrect(corrector, node, global_var)
node = node.parent while node.parent&.begin_type? && node.parent.children.one?
if should_require_english?(global_var)
ensure_required(corrector, node, LIBRARY_NAME)
@required_english = true
end
corrector.replace(node, replacement(node, global_var))
end
private
def format_english_message(global_var)
regular, english = ENGLISH_VARS[global_var].partition do |var|
NON_ENGLISH_VARS.include? var
end
format_message(english, regular, global_var)
end
def format_message(english, regular, global)
if regular.empty?
format(MSG_ENGLISH, prefer: format_list(english), global: global)
elsif english.empty?
format(MSG_REGULAR, prefer: format_list(regular), global: global)
else
format(MSG_BOTH,
prefer: format_list(english),
regular: format_list(regular),
global: global)
end
end
# For now, we assume that lists are 2 items or less. Easy grammar!
def format_list(items)
items.join('` or `')
end
def replacement(node, global_var)
parent_type = node.parent&.type
preferred_name = preferred_names(global_var).first
return preferred_name.to_s unless %i[dstr xstr regexp].include?(parent_type)
return english_name_replacement(preferred_name, node) if style == :use_english_names
"##{preferred_name}"
end
def preferred_names(global)
vars = STYLE_VARS_MAP.fetch(style) do
raise ArgumentError, "Invalid style: #{style.inspect}"
end
vars[global]
end
def matching_styles(global)
STYLE_VARS_MAP.filter_map do |style, vars|
style if vars.values.flatten(1).include? global
end
end
def english_name_replacement(preferred_name, node)
return "\#{#{preferred_name}}" if node.begin_type?
"{#{preferred_name}}"
end
def add_require_english?
cop_config['RequireEnglish']
end
def should_require_english?(global_var)
style == :use_english_names &&
add_require_english? &&
!@required_english &&
!NON_ENGLISH_VARS.include?(preferred_names(global_var).first)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/safe_navigation.rb | lib/rubocop/cop/style/safe_navigation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Transforms usages of a method call safeguarded by a non `nil`
# check for the variable whose method is being called to
# safe navigation (`&.`). If there is a method chain, all of the methods
# in the chain need to be checked for safety, and all of the methods will
# need to be changed to use safe navigation.
#
# The default for `ConvertCodeThatCanStartToReturnNil` is `false`.
# When configured to `true`, this will
# check for code in the format `!foo.nil? && foo.bar`. As it is written,
# the return of this code is limited to `false` and whatever the return
# of the method is. If this is converted to safe navigation,
# `foo&.bar` can start returning `nil` as well as what the method
# returns.
#
# The default for `MaxChainLength` is `2`.
# We have limited the cop to not register an offense for method chains
# that exceed this option's value.
#
# NOTE: This cop will recognize offenses but not autocorrect code when the
# right hand side (RHS) of the `&&` statement is an `||` statement
# (eg. `foo && (foo.bar? || foo.baz?)`). It can be corrected
# manually by removing the `foo &&` and adding `&.` to each `foo` on the RHS.
#
# @safety
# Autocorrection is unsafe because if a value is `false`, the resulting
# code will have different behavior or raise an error.
#
# [source,ruby]
# ----
# x = false
# x && x.foo # return false
# x&.foo # raises NoMethodError
# ----
#
# @example
# # bad
# foo.bar if foo
# foo.bar.baz if foo
# foo.bar(param1, param2) if foo
# foo.bar { |e| e.something } if foo
# foo.bar(param) { |e| e.something } if foo
#
# foo.bar if !foo.nil?
# foo.bar unless !foo
# foo.bar unless foo.nil?
#
# foo && foo.bar
# foo && foo.bar.baz
# foo && foo.bar(param1, param2)
# foo && foo.bar { |e| e.something }
# foo && foo.bar(param) { |e| e.something }
#
# foo ? foo.bar : nil
# foo.nil? ? nil : foo.bar
# !foo.nil? ? foo.bar : nil
# !foo ? nil : foo.bar
#
# # good
# foo&.bar
# foo&.bar&.baz
# foo&.bar(param1, param2)
# foo&.bar { |e| e.something }
# foo&.bar(param) { |e| e.something }
# foo && foo.bar.baz.qux # method chain with more than 2 methods
# foo && foo.nil? # method that `nil` responds to
#
# # Method calls that do not use `.`
# foo && foo < bar
# foo < bar if foo
#
# # When checking `foo&.empty?` in a conditional, `foo` being `nil` will actually
# # do the opposite of what the author intends.
# foo && foo.empty?
#
# # This could start returning `nil` as well as the return of the method
# foo.nil? || foo.bar
# !foo || foo.bar
#
# # Methods that are used on assignment, arithmetic operation or
# # comparison should not be converted to use safe navigation
# foo.baz = bar if foo
# foo.baz + bar if foo
# foo.bar > 2 if foo
#
# foo ? foo[index] : nil # Ignored `foo&.[](index)` due to unclear readability benefit.
# foo ? foo[idx] = v : nil # Ignored `foo&.[]=(idx, v)` due to unclear readability benefit.
# foo ? foo * 42 : nil # Ignored `foo&.*(42)` due to unclear readability benefit.
class SafeNavigation < Base # rubocop:disable Metrics/ClassLength
include NilMethods
include RangeHelp
extend AutoCorrector
extend TargetRubyVersion
MSG = 'Use safe navigation (`&.`) instead of checking if an object ' \
'exists before calling the method.'
LOGIC_JUMP_KEYWORDS = %i[break fail next raise return throw yield].freeze
minimum_target_ruby_version 2.3
# if format: (if checked_variable body nil)
# unless format: (if checked_variable nil body)
# @!method modifier_if_safe_navigation_candidate(node)
def_node_matcher :modifier_if_safe_navigation_candidate, <<~PATTERN
{
(if {
(send $_ {:nil? :!})
$_
} nil? $_)
(if {
(send (send $_ :nil?) :!)
$_
} $_ nil?)
}
PATTERN
# @!method ternary_safe_navigation_candidate(node)
def_node_matcher :ternary_safe_navigation_candidate, <<~PATTERN
{
(if (send $_ {:nil? :!}) nil $_)
(if (send (send $_ :nil?) :!) $_ nil)
(if $_ $_ nil)
}
PATTERN
# @!method and_with_rhs_or?(node)
def_node_matcher :and_with_rhs_or?, '(and _ {or (begin or)})'
# @!method not_nil_check?(node)
def_node_matcher :not_nil_check?, '(send (send $_ :nil?) :!)'
# @!method and_inside_begin?(node)
def_node_matcher :and_inside_begin?, '`(begin and ...)'
# @!method strip_begin(node)
def_node_matcher :strip_begin, '{ (begin $!begin) $!(begin) }'
# rubocop:disable Metrics/AbcSize
def on_if(node)
return if allowed_if_condition?(node)
checked_variable, receiver, method_chain, _method = extract_parts_from_if(node)
return unless offending_node?(node, checked_variable, method_chain, receiver)
body = extract_if_body(node)
method_call = receiver.parent
return if dotless_operator_call?(method_call) || method_call.double_colon?
removal_ranges = [begin_range(node, body), end_range(node, body)]
report_offense(node, method_chain, method_call, *removal_ranges) do |corrector|
corrector.replace(receiver, checked_variable.source) if checked_variable.csend_type?
corrector.insert_before(method_call.loc.dot, '&') unless method_call.safe_navigation?
end
end
# rubocop:enable Metrics/AbcSize
def on_and(node) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength
collect_and_clauses(node).each do |(lhs, lhs_operator_range), (rhs, _rhs_operator_range)|
lhs_not_nil_check = not_nil_check?(lhs)
lhs_receiver = lhs_not_nil_check || lhs
rhs_receiver = find_matching_receiver_invocation(strip_begin(rhs), lhs_receiver)
next if !cop_config['ConvertCodeThatCanStartToReturnNil'] && lhs_not_nil_check
next unless offending_node?(node, lhs_receiver, rhs, rhs_receiver)
# Since we are evaluating every clause in potentially a complex chain of `and` nodes,
# we need to ensure that there isn't an object check happening
lhs_method_chain = find_method_chain(lhs_receiver)
next unless lhs_method_chain == lhs_receiver || lhs_not_nil_check
report_offense(
node,
rhs, rhs_receiver,
range_with_surrounding_space(range: lhs.source_range, side: :right),
range_with_surrounding_space(range: lhs_operator_range, side: :right),
offense_range: range_between(lhs.source_range.begin_pos, rhs.source_range.end_pos)
) do |corrector|
corrector.replace(rhs_receiver, lhs_receiver.source)
end
ignore_node(node)
end
end
private
def report_offense(node, rhs, rhs_receiver, *removal_ranges, offense_range: node)
add_offense(offense_range) do |corrector|
next if ignored_node?(node)
# If the RHS is an `or` we cannot safely autocorrect because in order to remove
# the non-nil check we need to add safe-navs to all clauses where the receiver is used
next if and_with_rhs_or?(node)
removal_ranges.each { |range| corrector.remove(range) }
yield corrector if block_given?
handle_comments(corrector, node, rhs)
add_safe_nav_to_all_methods_in_chain(corrector, rhs_receiver, rhs)
end
end
def find_method_chain(node)
return node unless node&.parent&.call_type?
find_method_chain(node.parent)
end
def collect_and_clauses(node)
# Collect the lhs, operator and rhs of all `and` nodes
# `and` nodes can be nested and can contain `begin` nodes
# This gives us a source-ordered list of clauses that is then used to look
# for matching receivers as well as operator locations for offense and corrections
node.each_descendant(:and)
.inject(and_parts(node)) { |nodes, and_node| concat_nodes(nodes, and_node) }
.sort_by { |a| a.is_a?(RuboCop::AST::Node) ? a.source_range.begin_pos : a.begin_pos }
.each_slice(2)
.each_cons(2)
end
def concat_nodes(nodes, and_node)
return nodes if and_node.each_ancestor(:block).any?
nodes.concat(and_parts(and_node))
end
def and_parts(node)
parts = [node.loc.operator]
parts << node.rhs unless and_inside_begin?(node.rhs)
parts << node.lhs unless node.lhs.and_type? || and_inside_begin?(node.lhs)
parts
end
def offending_node?(node, lhs_receiver, rhs, rhs_receiver) # rubocop:disable Metrics/CyclomaticComplexity
return false if !matching_nodes?(lhs_receiver, rhs_receiver) || rhs_receiver.nil?
return false if use_var_only_in_unless_modifier?(node, lhs_receiver)
return false if chain_length(rhs, rhs_receiver) > max_chain_length
return false if unsafe_method_used?(node, rhs, rhs_receiver.parent)
return false if rhs.send_type? && rhs.method?(:empty?)
true
end
def use_var_only_in_unless_modifier?(node, variable)
node.if_type? && node.unless? && !method_called?(variable)
end
def extract_if_body(node)
if node.ternary?
node.branches.find { |branch| !branch.nil_type? }
else
node.node_parts[1]
end
end
def dotless_operator_call?(method_call)
return true if dotless_operator_method?(method_call)
method_call = method_call.parent while method_call.parent.send_type?
dotless_operator_method?(method_call)
end
def dotless_operator_method?(method_call)
return false if method_call.loc.dot
method_call.method?(:[]) || method_call.method?(:[]=) || method_call.operator_method?
end
def handle_comments(corrector, node, method_call)
comments = comments(node)
return if comments.empty?
corrector.insert_before(method_call, "#{comments.map(&:text).join("\n")}\n")
end
def comments(node)
relevant_comment_ranges(node).each.with_object([]) do |range, comments|
comments.concat(processed_source.each_comment_in_lines(range).to_a)
end
end
def relevant_comment_ranges(node)
# Get source lines ranges inside the if node that aren't inside an inner node
# Comments inside an inner node should remain attached to that node, and not
# moved.
begin_pos = node.loc.first_line
end_pos = node.loc.last_line
node.child_nodes.each.with_object([]) do |child, ranges|
ranges << (begin_pos...child.loc.first_line)
begin_pos = child.loc.last_line
end << (begin_pos...end_pos)
end
def allowed_if_condition?(node)
node.else? || node.elsif?
end
def extract_parts_from_if(node)
variable, receiver =
if node.ternary?
ternary_safe_navigation_candidate(node)
else
modifier_if_safe_navigation_candidate(node)
end
checked_variable, matching_receiver, method = extract_common_parts(receiver, variable)
matching_receiver = nil if receiver && LOGIC_JUMP_KEYWORDS.include?(receiver.type)
[checked_variable, matching_receiver, receiver, method]
end
def extract_common_parts(method_chain, checked_variable)
matching_receiver = find_matching_receiver_invocation(method_chain, checked_variable)
method = matching_receiver.parent if matching_receiver
[checked_variable, matching_receiver, method]
end
def find_matching_receiver_invocation(method_chain, checked_variable)
return nil unless method_chain.respond_to?(:receiver)
receiver = method_chain.receiver
return receiver if matching_nodes?(receiver, checked_variable)
find_matching_receiver_invocation(receiver, checked_variable)
end
def matching_nodes?(left, right)
left == right || matching_call_nodes?(left, right)
end
def matching_call_nodes?(left, right)
return false unless left && right.respond_to?(:call_type?)
return false unless left.call_type? && right.call_type?
# Compare receiver and method name, but ignore the difference between
# safe navigation method call (`&.`) and dot method call (`.`).
left_receiver, left_method, *left_args = left.children
right_receiver, right_method, *right_args = right.children
left_method == right_method &&
matching_nodes?(left_receiver, right_receiver) &&
left_args == right_args
end
def chain_length(method_chain, method)
method.each_ancestor(:call).inject(0) do |total, ancestor|
break total + 1 if ancestor == method_chain
total + 1
end
end
def unsafe_method_used?(node, method_chain, method)
return true if unsafe_method?(node, method)
method.each_ancestor(:send).any? do |ancestor|
break true unless config.cop_enabled?('Lint/SafeNavigationChain')
break true if unsafe_method?(node, ancestor)
break true if nil_methods.include?(ancestor.method_name)
break false if ancestor == method_chain
end
end
def unsafe_method?(node, send_node)
return true if negated?(send_node)
return false if node.respond_to?(:ternary?) && node.ternary?
send_node.assignment? ||
(!send_node.dot? && !send_node.safe_navigation?)
end
def negated?(send_node)
if method_called?(send_node)
negated?(send_node.parent)
else
send_node.send_type? && send_node.method?(:!)
end
end
def method_called?(send_node)
send_node&.parent&.send_type?
end
def begin_range(node, method_call)
range_between(node.source_range.begin_pos, method_call.source_range.begin_pos)
end
def end_range(node, method_call)
range_between(method_call.source_range.end_pos, node.source_range.end_pos)
end
def add_safe_nav_to_all_methods_in_chain(corrector,
start_method,
method_chain)
start_method.each_ancestor do |ancestor|
break unless %i[send block].include?(ancestor.type)
next if !ancestor.send_type? || ancestor.operator_method?
corrector.insert_before(ancestor.loc.dot, '&')
break if ancestor == method_chain
end
end
def max_chain_length
cop_config.fetch('MaxChainLength', 2)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/trailing_method_end_statement.rb | lib/rubocop/cop/style/trailing_method_end_statement.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for trailing code after the method definition.
#
# @example
# # bad
# def some_method
# do_stuff; end
#
# def do_this(x)
# baz.map { |b| b.this(x) } end
#
# def foo
# block do
# bar
# end end
#
# # good
# def some_method
# do_stuff
# end
#
# def do_this(x)
# baz.map { |b| b.this(x) }
# end
#
# def foo
# block do
# bar
# end
# end
#
class TrailingMethodEndStatement < Base
extend AutoCorrector
MSG = 'Place the end statement of a multi-line method on its own line.'
def on_def(node)
return if node.endless? || !trailing_end?(node)
add_offense(node.loc.end) do |corrector|
corrector.insert_before(node.loc.end, "\n#{' ' * node.loc.keyword.column}")
end
end
private
def trailing_end?(node)
node.body && node.multiline? && body_and_end_on_same_line?(node)
end
def body_and_end_on_same_line?(node)
last_child = node.children.last
last_child.loc.last_line == node.loc.end.last_line
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_self_assignment.rb | lib/rubocop/cop/style/redundant_self_assignment.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for places where redundant assignments are made for in place
# modification methods.
#
# @safety
# This cop is unsafe, because it can produce false positives for
# user defined methods having one of the expected names, but not modifying
# its receiver in place.
#
# @example
# # bad
# args = args.concat(ary)
# hash = hash.merge!(other)
#
# # good
# args.concat(foo)
# args += foo
# hash.merge!(other)
#
# # good
# foo.concat(ary)
#
class RedundantSelfAssignment < Base
include RangeHelp
extend AutoCorrector
MSG = 'Redundant self assignment detected. ' \
'Method `%<method_name>s` modifies its receiver in place.'
METHODS_RETURNING_SELF = %i[
append clear collect! compare_by_identity concat delete_if
fill initialize_copy insert keep_if map! merge! prepend push
rehash replace reverse! rotate! shuffle! sort! sort_by!
transform_keys! transform_values! unshift update
].to_set.freeze
ASSIGNMENT_TYPE_TO_RECEIVER_TYPE = {
lvasgn: :lvar,
ivasgn: :ivar,
cvasgn: :cvar,
gvasgn: :gvar
}.freeze
# @!method redundant_self_assignment?
def_node_matcher :redundant_self_assignment?, <<~PATTERN
(call
%1 _
(call
(call
%1 %2) #method_returning_self?
...))
PATTERN
# rubocop:disable Metrics/AbcSize
def on_lvasgn(node)
return unless (rhs = node.rhs)
return unless rhs.type?(:any_block, :call) && method_returning_self?(rhs.method_name)
return unless (receiver = rhs.receiver)
receiver_type = ASSIGNMENT_TYPE_TO_RECEIVER_TYPE[node.type]
return unless receiver.type == receiver_type && receiver.children.first == node.lhs
message = format(MSG, method_name: rhs.method_name)
add_offense(node.loc.operator, message: message) do |corrector|
corrector.replace(node, rhs.source)
end
end
# rubocop:enable Metrics/AbcSize
alias on_ivasgn on_lvasgn
alias on_cvasgn on_lvasgn
alias on_gvasgn on_lvasgn
def on_send(node)
return unless node.assignment_method?
return unless redundant_assignment?(node)
message = format(MSG, method_name: node.first_argument.method_name)
add_offense(node.loc.operator, message: message) do |corrector|
corrector.remove(correction_range(node))
end
end
alias on_csend on_send
private
def method_returning_self?(method_name)
METHODS_RETURNING_SELF.include?(method_name)
end
def redundant_assignment?(node)
receiver_name = node.method_name.to_s.delete_suffix('=').to_sym
redundant_self_assignment?(node, node.receiver, receiver_name)
end
def correction_range(node)
range_between(node.source_range.begin_pos, node.first_argument.source_range.begin_pos)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/ambiguous_endless_method_definition.rb | lib/rubocop/cop/style/ambiguous_endless_method_definition.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Looks for endless methods inside operations of lower precedence (`and`, `or`, and
# modifier forms of `if`, `unless`, `while`, `until`) that are ambiguous due to
# lack of parentheses. This may lead to unexpected behavior as the code may appear
# to use these keywords as part of the method but in fact they modify
# the method definition itself.
#
# In these cases, using a normal method definition is more clear.
#
# @example
#
# # bad
# def foo = true if bar
#
# # good - using a non-endless method is more explicit
# def foo
# true
# end if bar
#
# # ok - method body is explicit
# def foo = (true if bar)
#
# # ok - method definition is explicit
# (def foo = true) if bar
class AmbiguousEndlessMethodDefinition < Base
extend TargetRubyVersion
extend AutoCorrector
include EndlessMethodRewriter
include RangeHelp
minimum_target_ruby_version 3.0
MSG = 'Avoid using `%<keyword>s` statements with endless methods.'
# @!method ambiguous_endless_method_body(node)
def_node_matcher :ambiguous_endless_method_body, <<~PATTERN
^${
(if _ <def _>)
({and or} def _)
({while until} _ def)
}
PATTERN
def on_def(node)
return unless node.endless?
operation = ambiguous_endless_method_body(node)
return unless operation
return unless modifier_form?(operation)
add_offense(operation, message: format(MSG, keyword: keyword(operation))) do |corrector|
correct_to_multiline(corrector, node)
end
end
private
def modifier_form?(operation)
return true if operation.operator_keyword?
operation.modifier_form?
end
def keyword(operation)
if operation.respond_to?(:keyword)
operation.keyword
else
operation.operator
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/file_touch.rb | lib/rubocop/cop/style/file_touch.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for usage of `File.open` in append mode with empty block.
#
# Such a usage only creates a new file, but it doesn't update
# timestamps for an existing file, which might have been the intention.
#
# For example, for an existing file `foo.txt`:
#
# ruby -e "puts File.mtime('foo.txt')"
# # 2024-11-26 12:17:23 +0100
#
# ruby -e "File.open('foo.txt', 'a') {}"
#
# ruby -e "puts File.mtime('foo.txt')"
# # 2024-11-26 12:17:23 +0100 -> unchanged
#
# If the intention was to update timestamps, `FileUtils.touch('foo.txt')`
# should be used instead.
#
# @safety
# Autocorrection is unsafe for this cop because unlike `File.open`,
# `FileUtils.touch` updates an existing file's timestamps.
#
# @example
# # bad
# File.open(filename, 'a') {}
# File.open(filename, 'a+') {}
#
# # good
# FileUtils.touch(filename)
#
class FileTouch < Base
extend AutoCorrector
MSG = 'Use `FileUtils.touch(%<argument>s)` instead of `File.open` in ' \
'append mode with empty block.'
RESTRICT_ON_SEND = %i[open].freeze
APPEND_FILE_MODES = %w[a a+ ab a+b at a+t].to_set.freeze
# @!method file_open?(node)
def_node_matcher :file_open?, <<~PATTERN
(send
(const {nil? cbase} :File) :open
$(...)
(str %APPEND_FILE_MODES))
PATTERN
def on_send(node)
filename = file_open?(node)
parent = node.parent
return unless filename
return unless parent && empty_block?(parent)
message = format(MSG, argument: filename.source)
add_offense(parent, message: message) do |corrector|
corrector.replace(parent, "FileUtils.touch(#{filename.source})")
end
end
private
def empty_block?(node)
node.block_type? && !node.body
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/parallel_assignment.rb | lib/rubocop/cop/style/parallel_assignment.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for simple usages of parallel assignment.
# This will only complain when the number of variables
# being assigned matched the number of assigning variables.
#
# @example
# # bad
# a, b, c = 1, 2, 3
# a, b, c = [1, 2, 3]
#
# # good
# one, two = *foo
# a, b = foo
# a, b = b, a
#
# a = 1
# b = 2
# c = 3
class ParallelAssignment < Base
include RescueNode
extend AutoCorrector
MSG = 'Do not use parallel assignment.'
def on_masgn(node) # rubocop:disable Metrics/AbcSize
return if part_of_ignored_node?(node)
rhs = node.rhs
rhs = rhs.body if rhs.rescue_type?
rhs_elements = Array(rhs).compact # edge case for one constant
return if allowed_lhs?(node.assignments) || allowed_rhs?(rhs) ||
allowed_masign?(node.assignments, rhs_elements)
range = node.source_range.begin.join(rhs.source_range.end)
add_offense(range) do |corrector|
autocorrect(corrector, node, rhs)
end
ignore_node(node)
end
private
def autocorrect(corrector, node, rhs)
order = find_valid_order(node.assignments, Array(rhs).compact)
correction = assignment_corrector(node, rhs, order)
corrector.replace(correction.correction_range, correction.correction)
end
def allowed_masign?(lhs_elements, rhs_elements)
lhs_elements.size != rhs_elements.size ||
!find_valid_order(lhs_elements,
add_self_to_getters(rhs_elements))
end
def allowed_lhs?(elements)
# Account for edge cases using one variable with a comma
# E.g.: `foo, = *bar`
elements.one? || elements.any?(&:splat_type?)
end
def allowed_rhs?(node)
# Edge case for one constant
elements = Array(node).compact
# Account for edge case of `Constant::CONSTANT`
!node.array_type? || elements.any?(&:splat_type?)
end
def assignment_corrector(node, rhs, order)
if node.parent&.rescue_type?
_assignment, modifier = *node.parent
else
_assignment, modifier = *rhs.parent
end
if modifier_statement?(node.parent)
ModifierCorrector.new(node, rhs, modifier, config, order)
elsif rescue_modifier?(modifier)
RescueCorrector.new(node, rhs, modifier, config, order)
else
GenericCorrector.new(node, rhs, modifier, config, order)
end
end
def find_valid_order(left_elements, right_elements)
# arrange left_elements in an order such that no corresponding right
# element refers to a left element earlier in the sequence
assignments = left_elements.zip(right_elements)
AssignmentSorter.new(assignments).tsort
end
# Converts (send nil :something) nodes to (send (:self) :something).
# This makes the sorting algorithm work for expressions such as
# `self.a, self.b = b, a`.
def add_self_to_getters(right_elements)
right_elements.map do |e|
implicit_self_getter?(e) { |var| s(:send, s(:self), var) } || e
end
end
# @!method implicit_self_getter?(node)
def_node_matcher :implicit_self_getter?, '(send nil? $_)'
# Topologically sorts the assignments with Kahn's algorithm.
# https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm
class AssignmentSorter
extend RuboCop::NodePattern::Macros
# @!method var_name(node)
def_node_matcher :var_name, '{(casgn _ $_) (_ $_)}'
# @!method uses_var?(node)
def_node_search :uses_var?, '{({lvar ivar cvar gvar} %) (const _ %)}'
# @!method matching_calls(node, receiver, method_name)
def_node_search :matching_calls, '(send %1 %2 $...)'
def initialize(assignments)
@assignments = assignments
end
def tsort
dependencies = @assignments.to_h do |assignment|
[assignment, dependencies_for_assignment(assignment)]
end
result = []
while (matched_node, = dependencies.find { |_node, edges| edges.empty? })
dependencies.delete(matched_node)
result.push(matched_node)
dependencies.each do |node, edges|
dependencies[node].delete(matched_node) if edges.include?(matched_node)
end
end
# Cyclic dependency
return nil if dependencies.any?
result
end
# Returns all the assignments which must come after `assignment`
# (due to dependencies on the previous value of the assigned var)
def dependencies_for_assignment(assignment)
my_lhs, _my_rhs = *assignment
@assignments.filter_map do |other|
# Exclude self, there are no dependencies in cases such as `a, b = a, b`.
next if other == assignment
_other_lhs, other_rhs = *other
next unless dependency?(my_lhs, other_rhs)
other
end
end
def dependency?(lhs, rhs)
uses_var?(rhs, var_name(lhs)) ||
(lhs.send_type? && lhs.assignment_method? && accesses?(rhs, lhs))
end
# `lhs` is an assignment method call like `obj.attr=` or `ary[idx]=`.
# Does `rhs` access the same value which is assigned by `lhs`?
def accesses?(rhs, lhs)
if lhs.method?(:[]=)
# FIXME: Workaround `rubocop:disable` comment for JRuby.
# rubocop:disable Performance/RedundantEqualityComparisonBlock
matching_calls(rhs, lhs.receiver, :[]).any? { |args| args == lhs.arguments }
# rubocop:enable Performance/RedundantEqualityComparisonBlock
else
access_method = lhs.method_name.to_s.chop.to_sym
matching_calls(rhs, lhs.receiver, access_method).any?
end
end
end
def modifier_statement?(node)
return false unless node
node.basic_conditional? && node.modifier_form?
end
# An internal class for correcting parallel assignment
class GenericCorrector
include Alignment
attr_reader :node, :rhs, :rescue_result, :config
def initialize(node, rhs, modifier, config, new_elements)
@node = node
@rhs = rhs
_, _, @rescue_result = *modifier
@config = config
@new_elements = new_elements
end
def correction
assignment.join("\n#{offset(node)}")
end
def correction_range
node.source_range
end
protected
def assignment
@new_elements.map { |lhs, rhs| "#{lhs.source} = #{source(rhs, rhs.loc)}" }
end
private
def source(node, loc)
# __FILE__ is treated as a StrNode but has no begin
if node.str_type? && loc.respond_to?(:begin) && loc.begin.nil?
"'#{node.source}'"
elsif node.sym_type? && !node.loc?(:begin)
":#{node.source}"
else
node.source
end
end
def extract_sources(node)
node.children.map(&:source)
end
def cop_config
@config.for_cop('Style/ParallelAssignment')
end
end
# An internal class for correcting parallel assignment
# protected by rescue
class RescueCorrector < GenericCorrector
def correction
# If the parallel assignment uses a rescue modifier and it is the
# only contents of a method, then we want to make use of the
# implicit begin
if rhs.parent.parent.parent&.def_type?
super + def_correction(rescue_result)
else
begin_correction(rescue_result)
end
end
def correction_range
rhs.parent.parent.source_range
end
private
def def_correction(rescue_result)
"\nrescue" \
"\n#{offset(node)}#{rescue_result.source}"
end
def begin_correction(rescue_result)
"begin\n" \
"#{indentation(node)}" \
"#{assignment.join("\n#{indentation(node)}")}" \
"\n#{offset(node)}rescue\n" \
"#{indentation(node)}#{rescue_result.source}" \
"\n#{offset(node)}end"
end
end
# An internal class for correcting parallel assignment
# guarded by if, unless, while, or until
class ModifierCorrector < GenericCorrector
def correction
parent = node.parent
"#{modifier_range(parent).source}\n" \
"#{indentation(node)}" \
"#{assignment.join("\n#{indentation(node)}")}" \
"\n#{offset(node)}end"
end
def correction_range
node.parent.source_range
end
private
def modifier_range(node)
node.loc.keyword.join(node.source_range.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/style/array_coercion.rb | lib/rubocop/cop/style/array_coercion.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Enforces the use of `Array()` instead of explicit `Array` check or `[*var]`.
#
# The cop is disabled by default due to safety concerns.
#
# @safety
# This cop is unsafe because a false positive may occur if
# the argument of `Array()` is (or could be) nil or depending
# on how the argument is handled by `Array()` (which can be
# different than just wrapping the argument in an array).
#
# For example:
#
# [source,ruby]
# ----
# [nil] #=> [nil]
# Array(nil) #=> []
#
# [{a: 'b'}] #= [{a: 'b'}]
# Array({a: 'b'}) #=> [[:a, 'b']]
#
# [Time.now] #=> [#<Time ...>]
# Array(Time.now) #=> [14, 16, 14, 16, 9, 2021, 4, 259, true, "EDT"]
# ----
#
# @example
# # bad
# paths = [paths] unless paths.is_a?(Array)
# paths.each { |path| do_something(path) }
#
# # bad (always creates a new Array instance)
# [*paths].each { |path| do_something(path) }
#
# # good (and a bit more readable)
# Array(paths).each { |path| do_something(path) }
#
class ArrayCoercion < Base
extend AutoCorrector
SPLAT_MSG = 'Use `Array(%<arg>s)` instead of `[*%<arg>s]`.'
CHECK_MSG = 'Use `Array(%<arg>s)` instead of explicit `Array` check.'
# @!method array_splat?(node)
def_node_matcher :array_splat?, <<~PATTERN
(array (splat $_))
PATTERN
# @!method unless_array?(node)
def_node_matcher :unless_array?, <<~PATTERN
(if
(send
(lvar $_) :is_a?
(const nil? :Array)) nil?
(lvasgn $_
(array
(lvar $_))))
PATTERN
def on_array(node)
return unless node.square_brackets?
array_splat?(node) do |arg_node|
message = format(SPLAT_MSG, arg: arg_node.source)
add_offense(node, message: message) do |corrector|
corrector.replace(node, "Array(#{arg_node.source})")
end
end
end
def on_if(node)
unless_array?(node) do |var_a, var_b, var_c|
if var_a == var_b && var_c == var_b
message = format(CHECK_MSG, arg: var_a)
add_offense(node, message: message) do |corrector|
corrector.replace(node, "#{var_a} = Array(#{var_a})")
end
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/style/next.rb | lib/rubocop/cop/style/next.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Use `next` to skip iteration instead of a condition at the end.
#
# @example EnforcedStyle: skip_modifier_ifs (default)
# # bad
# [1, 2].each do |a|
# if a == 1
# puts a
# end
# end
#
# # good
# [1, 2].each do |a|
# next unless a == 1
# puts a
# end
#
# # good
# [1, 2].each do |a|
# puts a if a == 1
# end
#
# @example EnforcedStyle: always
# # With `always` all conditions at the end of an iteration needs to be
# # replaced by next - with `skip_modifier_ifs` the modifier if like
# # this one are ignored: `[1, 2].each { |a| puts a if a == 1 }`
#
# # bad
# [1, 2].each do |a|
# puts a if a == 1
# end
#
# # bad
# [1, 2].each do |a|
# if a == 1
# puts a
# end
# end
#
# # good
# [1, 2].each do |a|
# next unless a == 1
# puts a
# end
#
# @example AllowConsecutiveConditionals: false (default)
# # bad
# [1, 2].each do |a|
# if a == 1
# puts a
# end
# if a == 2
# puts a
# end
# end
#
# # good
# [1, 2].each do |a|
# if a == 1
# puts a
# end
# next unless a == 2
# puts a
# end
#
# @example AllowConsecutiveConditionals: true
# # good
# [1, 2].each do |a|
# if a == 1
# puts a
# end
# if a == 2
# puts a
# end
# end
#
class Next < Base
include ConfigurableEnforcedStyle
include MinBodyLength
include RangeHelp
extend AutoCorrector
MSG = 'Use `next` to skip iteration.'
EXIT_TYPES = %i[break return].freeze
def self.autocorrect_incompatible_with
[Style::SafeNavigation]
end
def on_new_investigation
# When correcting nested offenses, we need to keep track of how much
# we have adjusted the indentation of each line
@reindented_lines = Hash.new(0)
end
def on_block(node)
return unless node.send_node.call_type? && node.send_node.enumerator_method?
check(node)
end
alias on_numblock on_block
alias on_itblock on_block
def on_while(node)
check(node)
end
alias on_until on_while
alias on_for on_while
private
def check(node)
return unless node.body && ends_with_condition?(node.body)
offending_node = offense_node(node.body)
return if allowed_consecutive_conditionals? &&
consecutive_conditionals?(offending_node)
add_offense(offense_location(offending_node)) do |corrector|
if offending_node.modifier_form?
autocorrect_modifier(corrector, offending_node)
else
autocorrect_block(corrector, offending_node)
end
end
end
def ends_with_condition?(body)
return true if simple_if_without_break?(body)
body.begin_type? && simple_if_without_break?(body.children.last)
end
def simple_if_without_break?(node)
return false unless if_without_else?(node)
return false if if_else_children?(node)
return false if allowed_modifier_if?(node)
!exit_body_type?(node)
end
def allowed_modifier_if?(node)
if node.modifier_form?
style == :skip_modifier_ifs
else
!min_body_length?(node)
end
end
def if_else_children?(node)
node.each_child_node(:if).any?(&:else?)
end
def if_without_else?(node)
node&.if_type? && !node.ternary? && !node.else?
end
def exit_body_type?(node)
return false unless node.if_branch
EXIT_TYPES.include?(node.if_branch.type)
end
def offense_node(body)
*_, condition = *body
condition&.if_type? ? condition : body
end
def offense_location(offense_node)
offense_begin_pos = offense_node.source_range.begin
offense_begin_pos.join(offense_node.condition.source_range)
end
def autocorrect_modifier(corrector, node)
body = node.if_branch || node.else_branch
replacement =
"next #{node.inverse_keyword} #{node.condition.source}\n" \
"#{' ' * node.source_range.column}#{body.source}"
corrector.replace(node, replacement)
end
def autocorrect_block(corrector, node)
next_code = "next #{node.inverse_keyword} #{node.condition.source}"
corrector.insert_before(node, next_code)
corrector.remove(cond_range(node, node.condition))
corrector.remove(end_range(node))
lines = reindentable_lines(node)
return if lines.empty?
reindent(lines, node.condition, corrector)
end
def cond_range(node, cond)
end_pos = if node.loc.begin
node.loc.begin.end_pos # after "then"
else
cond.source_range.end_pos
end
range_between(node.source_range.begin_pos, end_pos)
end
def end_range(node)
source_buffer = node.source_range.source_buffer
end_pos = node.loc.end.end_pos
begin_pos = node.loc.end.begin_pos - node.loc.end.column
begin_pos -= 1 if end_followed_by_whitespace_only?(source_buffer, end_pos)
range_between(begin_pos, end_pos)
end
def end_followed_by_whitespace_only?(source_buffer, end_pos)
/\A\s*$/.match?(source_buffer.source[end_pos..])
end
def reindentable_lines(node)
buffer = node.source_range.source_buffer
# end_range starts with the final newline of the if body
lines = (node.source_range.line + 1)...node.loc.end.line
lines = lines.to_a - heredoc_lines(node)
# Skip blank lines
lines.reject { |lineno| /\A\s*\z/.match?(buffer.source_line(lineno)) }
end
# Adjust indentation of `lines` to match `node`
def reindent(lines, node, corrector)
range = node.source_range
buffer = range.source_buffer
target_indent = range.source_line =~ /\S/
delta = actual_indent(lines, buffer) - target_indent
lines.each { |lineno| reindent_line(corrector, lineno, delta, buffer) }
end
def actual_indent(lines, buffer)
lines.map { |lineno| buffer.source_line(lineno) =~ /\S/ }.min
end
def heredoc_lines(node)
node.each_node(:dstr)
.select(&:heredoc?)
.map { |n| n.loc.heredoc_body }
.flat_map { |b| (b.line...b.last_line).to_a }
end
def reindent_line(corrector, lineno, delta, buffer)
adjustment = delta + @reindented_lines[lineno]
@reindented_lines[lineno] = adjustment
corrector.remove_leading(buffer.line_range(lineno), adjustment) if adjustment.positive?
end
def consecutive_conditionals?(if_node)
if_node.parent&.begin_type? && if_node.left_sibling&.if_type?
end
def allowed_consecutive_conditionals?
cop_config.fetch('AllowConsecutiveConditionals', false)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/mutable_constant.rb | lib/rubocop/cop/style/mutable_constant.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks whether some constant value isn't a
# mutable literal (e.g. array or hash).
#
# Strict mode can be used to freeze all constants, rather than
# just literals.
# Strict mode is considered an experimental feature. It has not been
# updated with an exhaustive list of all methods that will produce
# frozen objects so there is a decent chance of getting some false
# positives. Luckily, there is no harm in freezing an already
# frozen object.
#
# From Ruby 3.0, this cop honours the magic comment
# 'shareable_constant_value'. When this magic comment is set to any
# acceptable value other than none, it will suppress the offenses
# raised by this cop. It enforces frozen state.
#
# NOTE: `Regexp` and `Range` literals are frozen objects since Ruby 3.0.
#
# NOTE: From Ruby 3.0, interpolated strings are not frozen when
# `# frozen-string-literal: true` is used, so this cop enforces explicit
# freezing for such strings.
#
# NOTE: From Ruby 3.0, this cop allows explicit freezing of constants when
# the `shareable_constant_value` directive is used.
#
# @safety
# This cop's autocorrection is unsafe since any mutations on objects that
# are made frozen will change from being accepted to raising `FrozenError`,
# and will need to be manually refactored.
#
# @example EnforcedStyle: literals (default)
# # bad
# CONST = [1, 2, 3]
#
# # good
# CONST = [1, 2, 3].freeze
#
# # good
# CONST = <<~TESTING.freeze
# This is a heredoc
# TESTING
#
# # good
# CONST = Something.new
#
#
# @example EnforcedStyle: strict
# # bad
# CONST = Something.new
#
# # bad
# CONST = Struct.new do
# def foo
# puts 1
# end
# end
#
# # good
# CONST = Something.new.freeze
#
# # good
# CONST = Struct.new do
# def foo
# puts 1
# end
# end.freeze
#
# @example
# # Magic comment - shareable_constant_value: literal
#
# # bad
# CONST = [1, 2, 3]
#
# # good
# # shareable_constant_value: literal
# CONST = [1, 2, 3]
#
class MutableConstant < Base
# Handles magic comment shareable_constant_value with O(n ^ 2) complexity
# n - number of lines in the source
# Iterates over all lines before a CONSTANT
# until it reaches shareable_constant_value
module ShareableConstantValue
module_function
def recent_shareable_value?(node)
shareable_constant_comment = magic_comment_in_scope node
return false if shareable_constant_comment.nil?
shareable_constant_value = MagicComment.parse(shareable_constant_comment)
.shareable_constant_value
shareable_constant_value_enabled? shareable_constant_value
end
# Identifies the most recent magic comment with valid shareable constant values
# that's in scope for this node
def magic_comment_in_scope(node)
processed_source_till_node(node).reverse_each.find do |line|
MagicComment.parse(line).valid_shareable_constant_value?
end
end
private
def processed_source_till_node(node)
processed_source.lines[0..(node.last_line - 1)]
end
def shareable_constant_value_enabled?(value)
%w[literal experimental_everything experimental_copy].include? value
end
end
private_constant :ShareableConstantValue
include ShareableConstantValue
include FrozenStringLiteral
include ConfigurableEnforcedStyle
extend AutoCorrector
MSG = 'Freeze mutable objects assigned to constants.'
def on_casgn(node)
if node.expression.nil? # This is only the case for `CONST += ...` or similarg66
parent = node.parent
return unless parent.or_asgn_type? # We only care about `CONST ||= ...`
on_assignment(parent.children.last)
else
on_assignment(node.expression)
end
end
private
def on_assignment(value)
if style == :strict
strict_check(value)
else
check(value)
end
end
def strict_check(value)
return if immutable_literal?(value)
return if operation_produces_immutable_object?(value)
return if frozen_string_literal?(value)
return if shareable_constant_value?(value)
add_offense(value) { |corrector| autocorrect(corrector, value) }
end
def check(value)
range_enclosed_in_parentheses = range_enclosed_in_parentheses?(value)
return unless mutable_literal?(value) ||
(target_ruby_version <= 2.7 && range_enclosed_in_parentheses)
return if frozen_string_literal?(value)
return if shareable_constant_value?(value)
add_offense(value) { |corrector| autocorrect(corrector, value) }
end
def autocorrect(corrector, node)
expr = node.source_range
splat_value = splat_value(node)
if splat_value
correct_splat_expansion(corrector, expr, splat_value)
elsif node.array_type? && !node.bracketed?
corrector.wrap(expr, '[', ']')
elsif requires_parentheses?(node)
corrector.wrap(expr, '(', ')')
end
corrector.insert_after(expr, '.freeze')
end
def mutable_literal?(value)
return false if frozen_regexp_or_range_literals?(value)
value.mutable_literal?
end
def immutable_literal?(node)
frozen_regexp_or_range_literals?(node) || node.immutable_literal?
end
def shareable_constant_value?(node)
return false if target_ruby_version < 3.0
recent_shareable_value? node
end
def frozen_regexp_or_range_literals?(node)
target_ruby_version >= 3.0 && node.type?(:regexp, :range)
end
def requires_parentheses?(node)
node.range_type? || (node.send_type? && node.loc.dot.nil?)
end
def correct_splat_expansion(corrector, expr, splat_value)
if range_enclosed_in_parentheses?(splat_value)
corrector.replace(expr, "#{splat_value.source}.to_a")
else
corrector.replace(expr, "(#{splat_value.source}).to_a")
end
end
# @!method splat_value(node)
def_node_matcher :splat_value, <<~PATTERN
(array (splat $_))
PATTERN
# Some of these patterns may not actually return an immutable object,
# but we want to consider them immutable for this cop.
# @!method operation_produces_immutable_object?(node)
def_node_matcher :operation_produces_immutable_object?, <<~PATTERN
{
(const _ _)
(send (const {nil? cbase} :Struct) :new ...)
(block (send (const {nil? cbase} :Struct) :new ...) ...)
(send _ :freeze)
(send {float int} {:+ :- :* :** :/ :% :<<} _)
(send _ {:+ :- :* :** :/ :%} {float int})
(send _ {:== :=== :!= :<= :>= :< :>} _)
(send (const {nil? cbase} :ENV) :[] _)
(or (send (const {nil? cbase} :ENV) :[] _) _)
(send _ {:count :length :size} ...)
(block (send _ {:count :length :size} ...) ...)
}
PATTERN
# @!method range_enclosed_in_parentheses?(node)
def_node_matcher :range_enclosed_in_parentheses?, <<~PATTERN
(begin (range _ _))
PATTERN
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/nil_lambda.rb | lib/rubocop/cop/style/nil_lambda.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for lambdas and procs that always return nil,
# which can be replaced with an empty lambda or proc instead.
#
# @example
# # bad
# -> { nil }
#
# lambda do
# next nil
# end
#
# proc { nil }
#
# Proc.new do
# break nil
# end
#
# # good
# -> {}
#
# lambda do
# end
#
# -> (x) { nil if x }
#
# proc {}
#
# Proc.new { nil if x }
#
class NilLambda < Base
extend AutoCorrector
include RangeHelp
MSG = 'Use an empty %<type>s instead of always returning nil.'
# @!method nil_return?(node)
def_node_matcher :nil_return?, <<~PATTERN
{ ({return next break} nil) (nil) }
PATTERN
def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
return unless node.lambda_or_proc?
return unless nil_return?(node.body)
message = format(MSG, type: node.lambda? ? 'lambda' : 'proc')
add_offense(node, message: message) do |corrector|
autocorrect(corrector, node)
end
end
private
def autocorrect(corrector, node)
range = if node.single_line?
range_with_surrounding_space(node.body.source_range)
else
range_by_whole_lines(node.body.source_range, include_final_newline: true)
end
corrector.remove(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/style/eval_with_location.rb | lib/rubocop/cop/style/eval_with_location.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Ensures that eval methods (`eval`, `instance_eval`, `class_eval`
# and `module_eval`) are given filename and line number values (`+__FILE__+`
# and `+__LINE__+`). This data is used to ensure that any errors raised
# within the evaluated code will be given the correct identification
# in a backtrace.
#
# The cop also checks that the line number given relative to `+__LINE__+` is
# correct.
#
# This cop will autocorrect incorrect or missing filename and line number
# values. However, if `eval` is called without a binding argument, the cop
# will not attempt to automatically add a binding, or add filename and
# line values.
#
# NOTE: This cop works only when a string literal is given as a code string.
# No offense is reported if a string variable is given as below:
#
# [source,ruby]
# ----
# code = <<-RUBY
# def do_something
# end
# RUBY
# eval code # not checked.
# ----
#
# @example
# # bad
# eval <<-RUBY
# def do_something
# end
# RUBY
#
# # bad
# C.class_eval <<-RUBY
# def do_something
# end
# RUBY
#
# # good
# eval <<-RUBY, binding, __FILE__, __LINE__ + 1
# def do_something
# end
# RUBY
#
# # good
# C.class_eval <<-RUBY, __FILE__, __LINE__ + 1
# def do_something
# end
# RUBY
#
class EvalWithLocation < Base
extend AutoCorrector
MSG = 'Pass `__FILE__` and `__LINE__` to `%<method_name>s`.'
MSG_EVAL = 'Pass a binding, `__FILE__`, and `__LINE__` to `eval`.'
MSG_INCORRECT_FILE = 'Incorrect file for `%<method_name>s`; ' \
'use `%<expected>s` instead of `%<actual>s`.'
MSG_INCORRECT_LINE = 'Incorrect line number for `%<method_name>s`; ' \
'use `%<expected>s` instead of `%<actual>s`.'
RESTRICT_ON_SEND = %i[eval class_eval module_eval instance_eval].freeze
# @!method valid_eval_receiver?(node)
def_node_matcher :valid_eval_receiver?, <<~PATTERN
{ nil? (const {nil? cbase} :Kernel) }
PATTERN
# @!method line_with_offset?(node, sign, num)
def_node_matcher :line_with_offset?, <<~PATTERN
{
(send #special_line_keyword? %1 (int %2))
(send (int %2) %1 #special_line_keyword?)
}
PATTERN
def on_send(node)
# Classes should not redefine eval, but in case one does, it shouldn't
# register an offense. Only `eval` without a receiver and `Kernel.eval`
# are considered.
return if node.method?(:eval) && !valid_eval_receiver?(node.receiver)
code = node.first_argument
return unless code&.type?(:str, :dstr)
check_location(node, code)
end
private
def check_location(node, code)
file, line = file_and_line(node)
if line
check_file(node, file)
check_line(node, code)
elsif file
check_file(node, file)
add_offense_for_missing_line(node, code)
else
add_offense_for_missing_location(node, code)
end
end
def register_offense(node, &block)
msg = node.method?(:eval) ? MSG_EVAL : format(MSG, method_name: node.method_name)
add_offense(node, message: msg, &block)
end
def special_file_keyword?(node)
node.str_type? && node.source == '__FILE__'
end
def special_line_keyword?(node)
node.int_type? && node.source == '__LINE__'
end
def file_and_line(node)
base = node.method?(:eval) ? 2 : 1
[node.arguments[base], node.arguments[base + 1]]
end
def with_binding?(node)
node.method?(:eval) ? node.arguments.size >= 2 : true
end
def add_offense_for_incorrect_line(method_name, line_node, sign, line_diff)
expected = expected_line(sign, line_diff)
message = format(MSG_INCORRECT_LINE,
method_name: method_name,
actual: line_node.source,
expected: expected)
add_offense(line_node, message: message) do |corrector|
corrector.replace(line_node, expected)
end
end
def check_file(node, file_node)
return if special_file_keyword?(file_node)
message = format(MSG_INCORRECT_FILE,
method_name: node.method_name,
expected: '__FILE__',
actual: file_node.source)
add_offense(file_node, message: message) do |corrector|
corrector.replace(file_node, '__FILE__')
end
end
def check_line(node, code)
line_node = node.last_argument
return if line_node.variable? || (line_node.send_type? && !line_node.method?(:+))
line_diff = line_difference(line_node, code)
if line_diff.zero?
add_offense_for_same_line(node, line_node)
else
add_offense_for_different_line(node, line_node, line_diff)
end
end
def line_difference(line_node, code)
string_first_line(code) - line_node.source_range.first_line
end
def string_first_line(str_node)
if str_node.heredoc?
str_node.loc.heredoc_body.first_line
else
str_node.source_range.first_line
end
end
def add_offense_for_same_line(node, line_node)
return if special_line_keyword?(line_node)
add_offense_for_incorrect_line(node.method_name, line_node, nil, 0)
end
def add_offense_for_different_line(node, line_node, line_diff)
sign = line_diff.positive? ? :+ : :-
return if line_with_offset?(line_node, sign, line_diff.abs)
add_offense_for_incorrect_line(node.method_name, line_node, sign, line_diff.abs)
end
def expected_line(sign, line_diff)
if line_diff.zero?
'__LINE__'
else
"__LINE__ #{sign} #{line_diff.abs}"
end
end
def add_offense_for_missing_line(node, code)
register_offense(node) do |corrector|
line_str = missing_line(node, code)
corrector.insert_after(node.last_argument.source_range.end, ", #{line_str}")
end
end
def add_offense_for_missing_location(node, code)
if node.method?(:eval) && !with_binding?(node)
register_offense(node)
return
end
register_offense(node) do |corrector|
line_str = missing_line(node, code)
corrector.insert_after(node.last_argument.source_range.end, ", __FILE__, #{line_str}")
end
end
def missing_line(node, code)
line_diff = line_difference(node.last_argument, code)
sign = line_diff.positive? ? :+ : :-
expected_line(sign, line_diff)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/yoda_expression.rb | lib/rubocop/cop/style/yoda_expression.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Forbids Yoda expressions, i.e. binary operations (using `*`, `+`, `&`, `|`,
# and `^` operators) where the order of expression is reversed, eg. `1 + x`.
# This cop complements `Style/YodaCondition` cop, which has a similar purpose.
#
# This cop is disabled by default to respect user intentions such as:
#
# [source,ruby]
# ----
# config.server_port = 9000 + ENV["TEST_ENV_NUMBER"].to_i
# ----
#
# @safety
# This cop is unsafe because binary operators can be defined
# differently on different classes, and are not guaranteed to
# have the same result if reversed.
#
# @example SupportedOperators: ['*', '+', '&', '|', '^'] (default)
# # bad
# 10 * y
# 1 + x
# 1 & z
# 1 | x
# 1 ^ x
# 1 + CONST
#
# # good
# y * 10
# x + 1
# z & 1
# x | 1
# x ^ 1
# CONST + 1
# 60 * 24
#
class YodaExpression < Base
extend AutoCorrector
MSG = 'Non-literal operand (`%<source>s`) should be first.'
RESTRICT_ON_SEND = %i[* + & | ^].freeze
def on_new_investigation
@offended_nodes = nil
end
def on_send(node)
return unless supported_operators.include?(node.method_name.to_s)
return unless node.arguments?
lhs = node.receiver
rhs = node.first_argument
return unless yoda_expression_constant?(lhs, rhs)
return if offended_ancestor?(node)
message = format(MSG, source: rhs.source)
add_offense(node, message: message) do |corrector|
corrector.swap(lhs, rhs)
end
offended_nodes.add(node)
end
private
def yoda_expression_constant?(lhs, rhs)
constant_portion?(lhs) && !constant_portion?(rhs)
end
def constant_portion?(node)
node.type?(:numeric, :const)
end
def supported_operators
Array(cop_config['SupportedOperators'])
end
def offended_ancestor?(node)
node.each_ancestor(:send).any? { |ancestor| @offended_nodes&.include?(ancestor) }
end
def offended_nodes
@offended_nodes ||= Set.new.compare_by_identity
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/rescue_modifier.rb | lib/rubocop/cop/style/rescue_modifier.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for uses of `rescue` in its modifier form is added for following
# reasons:
#
# * The syntax of modifier form `rescue` can be misleading because it
# might lead us to believe that `rescue` handles the given exception
# but it actually rescue all exceptions to return the given rescue
# block. In this case, value returned by handle_error or
# SomeException.
#
# * Modifier form `rescue` would rescue all the exceptions. It would
# silently skip all exception or errors and handle the error.
# Example: If `NoMethodError` is raised, modifier form rescue would
# handle the exception.
#
# @example
# # bad
# some_method rescue handle_error
#
# # bad
# some_method rescue SomeException
#
# # good
# begin
# some_method
# rescue
# handle_error
# end
#
# # good
# begin
# some_method
# rescue SomeException
# handle_error
# end
class RescueModifier < Base
include Alignment
include RangeHelp
include RescueNode
extend AutoCorrector
MSG = 'Avoid using `rescue` in its modifier form.'
def self.autocorrect_incompatible_with
[Style::MethodCallWithArgsParentheses]
end
def on_resbody(node)
return unless rescue_modifier?(node)
rescue_node = node.parent
add_offense(rescue_node) do |corrector|
parenthesized = parenthesized?(rescue_node)
correct_rescue_block(corrector, rescue_node, parenthesized)
ParenthesesCorrector.correct(corrector, rescue_node.parent) if parenthesized
end
end
private
def parenthesized?(node)
node.parent && parentheses?(node.parent)
end
# rubocop:disable Metrics/AbcSize
def correct_rescue_block(corrector, node, parenthesized)
operation = node.body
node_indentation, node_offset = indentation_and_offset(node, parenthesized)
corrector.wrap(operation, '[', ']') if operation.array_type? && !operation.bracketed?
corrector.remove(range_between(operation.source_range.end_pos, node.source_range.end_pos))
corrector.insert_before(operation, "begin\n#{node_indentation}")
corrector.insert_after(heredoc_end(operation) || operation, <<~RESCUE_CLAUSE.chop)
#{node_offset}rescue
#{node_indentation}#{node.resbody_branches.first.body.source}
#{node_offset}end
RESCUE_CLAUSE
end
# rubocop:enable Metrics/AbcSize
def indentation_and_offset(node, parenthesized)
node_indentation = indentation(node)
node_offset = offset(node)
if parenthesized
node_indentation = node_indentation[0...-1]
node_offset = node_offset[0...-1]
end
[node_indentation, node_offset]
end
def heredoc_end(node)
return unless node.call_type?
heredoc = node.arguments.reverse.find do |argument|
argument.respond_to?(:heredoc?) && argument.heredoc?
end
return unless heredoc
heredoc.loc.heredoc_end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/map_to_hash.rb | lib/rubocop/cop/style/map_to_hash.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Looks for uses of `map.to_h` or `collect.to_h` that could be
# written with just `to_h` in Ruby >= 2.6.
#
# NOTE: `Style/HashTransformKeys` and `Style/HashTransformValues` will
# also change this pattern if only hash keys or hash values are being
# transformed.
#
# @safety
# This cop is unsafe, as it can produce false positives if the receiver
# is not an `Enumerable`.
#
# @example
# # bad
# something.map { |v| [v, v * 2] }.to_h
#
# # good
# something.to_h { |v| [v, v * 2] }
#
# # bad
# {foo: bar}.collect { |k, v| [k.to_s, v.do_something] }.to_h
#
# # good
# {foo: bar}.to_h { |k, v| [k.to_s, v.do_something] }
#
class MapToHash < Base
extend AutoCorrector
extend TargetRubyVersion
include RangeHelp
minimum_target_ruby_version 2.6
MSG = 'Pass a block to `to_h` instead of calling `%<method>s%<dot>sto_h`.'
RESTRICT_ON_SEND = %i[to_h].freeze
# @!method map_to_h(node)
def_node_matcher :map_to_h, <<~PATTERN
{
$(call (any_block $(call _ {:map :collect}) ...) :to_h)
$(call $(call _ {:map :collect} (block_pass sym)) :to_h)
}
PATTERN
# @!method destructuring_argument(node)
def_node_matcher :destructuring_argument, <<~PATTERN
(args $(mlhs (arg _)+))
PATTERN
def self.autocorrect_incompatible_with
[Layout::SingleLineBlockChain]
end
def on_send(node)
return unless (to_h_node, map_node = map_to_h(node))
return if to_h_node.block_literal?
message = format(MSG, method: map_node.loc.selector.source, dot: to_h_node.loc.dot.source)
add_offense(map_node.loc.selector, message: message) do |corrector|
autocorrect(corrector, to_h_node, map_node)
end
end
alias on_csend on_send
private
# rubocop:disable Metrics/AbcSize
def autocorrect(corrector, to_h, map)
removal_range = range_between(to_h.loc.dot.begin_pos, to_h.loc.selector.end_pos)
corrector.remove(range_with_surrounding_space(removal_range, side: :left))
if (map_dot = map.loc.dot)
corrector.replace(map_dot, to_h.loc.dot.source)
end
corrector.replace(map.loc.selector, 'to_h')
return unless map.parent.block_type?
if (argument = destructuring_argument(map.parent.arguments))
corrector.replace(argument, argument.source[1..-2])
end
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/style/string_methods.rb | lib/rubocop/cop/style/string_methods.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Enforces the use of consistent method names
# from the `String` class.
#
# @example
# # bad
# 'name'.intern
# 'var'.unfavored_method
#
# # good
# 'name'.to_sym
# 'var'.preferred_method
class StringMethods < Base
include MethodPreference
extend AutoCorrector
MSG = 'Prefer `%<prefer>s` over `%<current>s`.'
def on_send(node)
return unless (preferred_method = preferred_method(node.method_name))
message = format(MSG, prefer: preferred_method, current: node.method_name)
add_offense(node.loc.selector, message: message) do |corrector|
corrector.replace(node.loc.selector, preferred_method(node.method_name))
end
end
alias on_csend on_send
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_array_flatten.rb | lib/rubocop/cop/style/redundant_array_flatten.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for redundant calls of `Array#flatten`.
#
# `Array#join` joins nested arrays recursively, so flattening an array
# beforehand is redundant.
#
# @safety
# Cop is unsafe because the receiver of `flatten` method might not
# be an `Array`, so it's possible it won't respond to `join` method,
# or the end result would be different.
# Also, if the global variable `$,` is set to a value other than the default `nil`,
# false positives may occur.
#
# @example
# # bad
# x.flatten.join
# x.flatten(1).join
#
# # good
# x.join
#
class RedundantArrayFlatten < Base
extend AutoCorrector
MSG = 'Remove the redundant `flatten`.'
RESTRICT_ON_SEND = %i[flatten].freeze
# @!method flatten_join?(node)
def_node_matcher :flatten_join?, <<~PATTERN
(call (call !nil? :flatten _?) :join (nil)?)
PATTERN
def on_send(node)
return unless flatten_join?(node.parent)
range = node.loc.dot.begin.join(node.source_range.end)
add_offense(range) do |corrector|
corrector.remove(range)
end
end
alias on_csend on_send
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/string_concatenation.rb | lib/rubocop/cop/style/string_concatenation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for places where string concatenation
# can be replaced with string interpolation.
#
# The cop can autocorrect simple cases but will skip autocorrecting
# more complex cases where the resulting code would be harder to read.
# In those cases, it might be useful to extract statements to local
# variables or methods which you can then interpolate in a string.
#
# NOTE: When concatenation between two strings is broken over multiple
# lines, this cop does not register an offense; instead,
# `Style/LineEndConcatenation` will pick up the offense if enabled.
#
# Two modes are supported:
# 1. `aggressive` style checks and corrects all occurrences of `+` where
# either the left or right side of `+` is a string literal.
# 2. `conservative` style on the other hand, checks and corrects only if
# left side (receiver of `+` method call) is a string literal.
# This is useful when the receiver is some expression that returns string like `Pathname`
# instead of a string literal.
#
# @safety
# This cop is unsafe in `aggressive` mode, as it cannot be guaranteed that
# the receiver is actually a string, which can result in a false positive.
#
# @example Mode: aggressive (default)
# # bad
# email_with_name = user.name + ' <' + user.email + '>'
# Pathname.new('/') + 'test'
#
# # good
# email_with_name = "#{user.name} <#{user.email}>"
# email_with_name = format('%s <%s>', user.name, user.email)
# "#{Pathname.new('/')}test"
#
# # accepted, line-end concatenation
# name = 'First' +
# 'Last'
#
# @example Mode: conservative
# # bad
# 'Hello' + user.name
#
# # good
# "Hello #{user.name}"
# user.name + '!!'
# Pathname.new('/') + 'test'
#
class StringConcatenation < Base
extend AutoCorrector
MSG = 'Prefer string interpolation to string concatenation.'
RESTRICT_ON_SEND = %i[+].freeze
# @!method string_concatenation?(node)
def_node_matcher :string_concatenation?, <<~PATTERN
{
(send str_type? :+ _)
(send _ :+ str_type?)
}
PATTERN
def on_new_investigation
@corrected_nodes = nil
end
def on_send(node)
return unless string_concatenation?(node)
return if line_end_concatenation?(node)
topmost_plus_node = find_topmost_plus_node(node)
parts = collect_parts(topmost_plus_node)
return if mode == :conservative && !parts.first.str_type?
register_offense(topmost_plus_node, parts)
end
private
def register_offense(topmost_plus_node, parts)
add_offense(topmost_plus_node) do |corrector|
correctable_parts = parts.none? { |part| uncorrectable?(part) }
if correctable_parts && !corrected_ancestor?(topmost_plus_node)
corrector.replace(topmost_plus_node, replacement(parts))
@corrected_nodes ||= Set.new.compare_by_identity
@corrected_nodes.add(topmost_plus_node)
end
end
end
def line_end_concatenation?(node)
# If the concatenation happens at the end of the line,
# and both the receiver and argument are strings, allow
# `Style/LineEndConcatenation` to handle it instead.
node.receiver.str_type? &&
node.first_argument.str_type? &&
node.multiline? &&
node.source.match?(/\+\s*\n/)
end
def find_topmost_plus_node(node)
current = node
while (parent = current.parent) && plus_node?(parent)
current = parent
end
current
end
def collect_parts(node, parts = [])
return unless node
if plus_node?(node)
collect_parts(node.receiver, parts)
collect_parts(node.first_argument, parts)
else
parts << node
end
end
def plus_node?(node)
node.send_type? && node.method?(:+)
end
def uncorrectable?(part)
part.multiline? || heredoc?(part) || part.each_descendant(:any_block).any?
end
def heredoc?(node)
return false unless node.type?(:str, :dstr)
node.heredoc?
end
def corrected_ancestor?(node)
node.each_ancestor(:send).any? { |ancestor| @corrected_nodes&.include?(ancestor) }
end
def replacement(parts)
interpolated_parts = parts.map { |part| adjust_str(part) }
"\"#{handle_quotes(interpolated_parts).join}\""
end
def adjust_str(part)
case part.type
when :str
if single_quoted?(part)
part.value.gsub(/(\\|"|#\{|#@|#\$)/, '\\\\\&')
else
part.value.inspect[1..-2]
end
when :dstr, :begin
part.children.map do |child|
adjust_str(child)
end.join
else
"\#{#{part.source}}"
end
end
def handle_quotes(parts)
parts.map do |part|
part == '"' ? '\"' : part
end
end
def single_quoted?(str_node)
str_node.source.start_with?("'")
end
def mode
cop_config['Mode'].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/style/redundant_regexp_character_class.rb | lib/rubocop/cop/style/redundant_regexp_character_class.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for unnecessary single-element `Regexp` character classes.
#
# @example
#
# # bad
# r = /[x]/
#
# # good
# r = /x/
#
# # bad
# r = /[\s]/
#
# # good
# r = /\s/
#
# # bad
# r = %r{/[b]}
#
# # good
# r = %r{/b}
#
# # good
# r = /[ab]/
class RedundantRegexpCharacterClass < Base
extend AutoCorrector
REQUIRES_ESCAPE_OUTSIDE_CHAR_CLASS_CHARS = '.*+?{}()|$'.chars.freeze
MSG_REDUNDANT_CHARACTER_CLASS = 'Redundant single-element character class, ' \
'`%<char_class>s` can be replaced with `%<element>s`.'
def on_regexp(node)
each_redundant_character_class(node) do |loc|
add_offense(
loc, message: format(
MSG_REDUNDANT_CHARACTER_CLASS,
char_class: loc.source,
element: without_character_class(loc)
)
) do |corrector|
corrector.replace(loc, without_character_class(loc))
end
end
end
private
def each_redundant_character_class(node)
each_single_element_character_class(node) do |char_class|
next unless redundant_single_element_character_class?(node, char_class)
yield char_class.loc.body
end
end
def each_single_element_character_class(node)
node.parsed_tree&.each_expression do |expr|
next if expr.type != :set || expr.expressions.size != 1
next if expr.negative?
next if %i[set posixclass nonposixclass].include?(expr.expressions.first.type)
next if multiple_codepoints?(expr.expressions.first)
yield expr
end
end
def redundant_single_element_character_class?(node, char_class)
class_elem = char_class.expressions.first.text
non_redundant =
whitespace_in_free_space_mode?(node, class_elem) ||
backslash_b?(class_elem) || octal_requiring_char_class?(class_elem) ||
requires_escape_outside_char_class?(class_elem)
!non_redundant
end
def multiple_codepoints?(expression)
expression.respond_to?(:codepoints) && expression.codepoints.count >= 2
end
def without_character_class(loc)
without_character_class = loc.source[1..-2]
# Adds `\` to prevent autocorrection that changes to an interpolated string when `[#]`.
# e.g. From `/[#]{0}/` to `/#{0}/`
loc.source == '[#]' ? "\\#{without_character_class}" : without_character_class
end
def whitespace_in_free_space_mode?(node, elem)
return false unless node.extended?
/\s/.match?(elem)
end
def backslash_b?(elem)
# \b's behavior is different inside and outside of a character class, matching word
# boundaries outside but backspace (0x08) when inside.
elem == '\b'
end
def octal_requiring_char_class?(elem)
# The octal escapes \1 to \7 only work inside a character class
# because they would be a backreference outside it.
elem.match?(/\A\\[1-7]\z/)
end
def requires_escape_outside_char_class?(elem)
REQUIRES_ESCAPE_OUTSIDE_CHAR_CLASS_CHARS.include?(elem)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/begin_block.rb | lib/rubocop/cop/style/begin_block.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for BEGIN blocks.
#
# @example
# # bad
# BEGIN { test }
#
class BeginBlock < Base
MSG = 'Avoid the use of `BEGIN` blocks.'
def on_preexe(node)
add_offense(node.loc.keyword)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/single_argument_dig.rb | lib/rubocop/cop/style/single_argument_dig.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Sometimes using `dig` method ends up with just a single
# argument. In such cases, dig should be replaced with `[]`.
#
# Since replacing `hash&.dig(:key)` with `hash[:key]` could potentially lead to error,
# calls to the `dig` method using safe navigation will be ignored.
#
# @safety
# This cop is unsafe because it cannot be guaranteed that the receiver
# is an `Enumerable` or does not have a nonstandard implementation
# of `dig`.
#
# @example
# # bad
# { key: 'value' }.dig(:key)
# [1, 2, 3].dig(0)
#
# # good
# { key: 'value' }[:key]
# [1, 2, 3][0]
#
# # good
# { key1: { key2: 'value' } }.dig(:key1, :key2)
# [1, [2, [3]]].dig(1, 1)
#
# # good
# keys = %i[key1 key2]
# { key1: { key2: 'value' } }.dig(*keys)
#
class SingleArgumentDig < Base
extend AutoCorrector
include DigHelp
MSG = 'Use `%<receiver>s[%<argument>s]` instead of `%<original>s`.'
RESTRICT_ON_SEND = %i[dig].freeze
IGNORED_ARGUMENT_TYPES = %i[block_pass forwarded_restarg forwarded_args hash].freeze
def on_send(node)
return unless node.receiver
expression = single_argument_dig?(node)
return unless expression
return if IGNORED_ARGUMENT_TYPES.include?(expression.type)
return if ignore_dig_chain?(node)
receiver = node.receiver.source
argument = expression.source
message = format(MSG, receiver: receiver, argument: argument, original: node.source)
add_offense(node, message: message) do |corrector|
next if part_of_ignored_node?(node)
correct_access = "#{receiver}[#{argument}]"
corrector.replace(node, correct_access)
end
ignore_node(node)
end
private
def ignore_dig_chain?(node)
dig_chain_enabled? &&
(dig?(node.receiver) || dig?(node.parent))
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/commented_keyword.rb | lib/rubocop/cop/style/commented_keyword.rb | # frozen_string_literal: true
require_relative '../../directive_comment'
module RuboCop
module Cop
module Style
# Checks for comments put on the same line as some keywords.
# These keywords are: `class`, `module`, `def`, `begin`, `end`.
#
# Note that some comments
# (`:nodoc:`, `:yields:`, `rubocop:disable` and `rubocop:todo`),
# RBS::Inline annotation, and Steep annotation (`steep:ignore`) are allowed.
#
# Autocorrection removes comments from `end` keyword and keeps comments
# for `class`, `module`, `def` and `begin` above the keyword.
#
# @safety
# Autocorrection is unsafe because it may remove a comment that is
# meaningful.
#
# @example
# # bad
# if condition
# statement
# end # end if
#
# # bad
# class X # comment
# statement
# end
#
# # bad
# def x; end # comment
#
# # good
# if condition
# statement
# end
#
# # good
# class X # :nodoc:
# y
# end
class CommentedKeyword < Base
include RangeHelp
extend AutoCorrector
MSG = 'Do not place comments on the same line as the `%<keyword>s` keyword.'
KEYWORDS = %w[begin class def end module].freeze
KEYWORD_REGEXES = KEYWORDS.map { |w| /^\s*#{w}\s/ }.freeze
ALLOWED_COMMENTS = %w[:nodoc: :yields:].freeze
ALLOWED_COMMENT_REGEXES = (ALLOWED_COMMENTS.map { |c| /#\s*#{c}/ } +
[DirectiveComment::DIRECTIVE_COMMENT_REGEXP]).freeze
REGEXP = /(?<keyword>\S+).*#/.freeze
SUBCLASS_DEFINITION = /\A\s*class\s+(\w|::)+\s*<\s*(\w|::)+/.freeze
METHOD_OR_END_DEFINITIONS = /\A\s*(def\s|end)/.freeze
STEEP_REGEXP = /#\ssteep:ignore(\s|\z)/.freeze
def on_new_investigation
processed_source.comments.each do |comment|
next unless offensive?(comment) && (match = source_line(comment).match(REGEXP))
register_offense(comment, match[:keyword])
end
end
private
def register_offense(comment, matched_keyword)
add_offense(comment, message: format(MSG, keyword: matched_keyword)) do |corrector|
range = range_with_surrounding_space(comment.source_range, newlines: false)
corrector.remove(range)
unless matched_keyword == 'end'
corrector.insert_before(
range.source_buffer.line_range(comment.loc.line), "#{comment.text}\n"
)
end
end
end
def offensive?(comment)
line = source_line(comment)
return false if rbs_inline_annotation?(line, comment)
return false if steep_annotation?(comment)
KEYWORD_REGEXES.any? { |r| r.match?(line) } &&
ALLOWED_COMMENT_REGEXES.none? { |r| r.match?(line) }
end
def source_line(comment)
comment.source_range.source_line
end
def rbs_inline_annotation?(line, comment)
case line
when SUBCLASS_DEFINITION
comment.text.start_with?(/#\[.+\]/)
when METHOD_OR_END_DEFINITIONS
comment.text.start_with?('#:')
else
false
end
end
def steep_annotation?(comment)
comment.text.match?(STEEP_REGEXP)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_regexp_constructor.rb | lib/rubocop/cop/style/redundant_regexp_constructor.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for the instantiation of regexp using redundant `Regexp.new` or `Regexp.compile`.
# Autocorrect replaces to regexp literal which is the simplest and fastest.
#
# @example
#
# # bad
# Regexp.new(/regexp/)
# Regexp.compile(/regexp/)
#
# # good
# /regexp/
# Regexp.new('regexp')
# Regexp.compile('regexp')
#
class RedundantRegexpConstructor < Base
extend AutoCorrector
MSG = 'Remove the redundant `Regexp.%<method>s`.'
RESTRICT_ON_SEND = %i[new compile].freeze
# @!method redundant_regexp_constructor(node)
def_node_matcher :redundant_regexp_constructor, <<~PATTERN
(send
(const {nil? cbase} :Regexp) {:new :compile}
(regexp $... (regopt $...)))
PATTERN
def on_send(node)
return unless (regexp, regopt = redundant_regexp_constructor(node))
add_offense(node, message: format(MSG, method: node.method_name)) do |corrector|
pattern = regexp.map(&:source).join
regopt = regopt.join
corrector.replace(node, "/#{pattern}/#{regopt}")
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/file_null.rb | lib/rubocop/cop/style/file_null.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Use `File::NULL` instead of hardcoding the null device (`/dev/null` on Unix-like
# OSes, `NUL` or `NUL:` on Windows), so that code is platform independent.
# Only looks for full string matches, substrings within a longer string are not
# considered.
#
# However, only files that use the string `'/dev/null'` are targeted for detection.
# This is because the string `'NUL'` is not limited to the null device.
# This behavior results in false negatives when the `'/dev/null'` string is not used,
# but it is a trade-off to avoid false positives. `NULL:`
# Unlike `'NUL'`, `'NUL:'` is regarded as something like `C:` and is always detected.
#
# NOTE: Uses inside arrays and hashes are ignored.
#
# @safety
# It is possible for a string value to be changed if code is being run
# on multiple platforms and was previously hardcoded to a specific null device.
#
# For example, the following string will change on Windows when changed to
# `File::NULL`:
#
# [source,ruby]
# ----
# path = "/dev/null"
# ----
#
# @example
# # bad
# '/dev/null'
# 'NUL'
# 'NUL:'
#
# # good
# File::NULL
#
# # ok - inside an array
# null_devices = %w[/dev/null nul]
#
# # ok - inside a hash
# { unix: "/dev/null", windows: "nul" }
class FileNull < Base
extend AutoCorrector
REGEXP = %r{\A(/dev/null|NUL:?)\z}i.freeze
MSG = 'Use `File::NULL` instead of `%<source>s`.'
def on_new_investigation
return unless (ast = processed_source.ast)
@contain_dev_null_string_in_file = ast.each_descendant(:str).any? do |str|
content = str.str_content
valid_string?(content) && content.downcase == '/dev/null' # rubocop:disable Style/FileNull
end
end
def on_str(node)
value = node.value
return unless valid_string?(value)
return if acceptable?(node)
return if value.downcase == 'nul' && !@contain_dev_null_string_in_file # rubocop:disable Style/FileNull
return unless REGEXP.match?(value)
add_offense(node, message: format(MSG, source: value)) do |corrector|
corrector.replace(node, 'File::NULL')
end
end
private
def valid_string?(value)
!value.empty? && value.valid_encoding?
end
def acceptable?(node)
# Using a hardcoded null device is acceptable when inside an array or
# inside a hash to ensure behavior doesn't change.
return false unless node.parent
node.parent.type?(:array, :pair)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/method_def_parentheses.rb | lib/rubocop/cop/style/method_def_parentheses.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for parentheses around the arguments in method
# definitions. Both instance and class/singleton methods are checked.
#
# Regardless of style, parentheses are necessary for:
#
# 1. Endless methods
# 2. Argument lists containing a `forward-arg` (`...`)
# 3. Argument lists containing an anonymous rest arguments forwarding (`*`)
# 4. Argument lists containing an anonymous keyword rest arguments forwarding (`**`)
# 5. Argument lists containing an anonymous block forwarding (`&`)
#
# Removing the parens would be a syntax error here.
#
# @example EnforcedStyle: require_parentheses (default)
# # The `require_parentheses` style requires method definitions
# # to always use parentheses
#
# # bad
# def bar num1, num2
# num1 + num2
# end
#
# def foo descriptive_var_name,
# another_descriptive_var_name,
# last_descriptive_var_name
# do_something
# end
#
# # good
# def bar(num1, num2)
# num1 + num2
# end
#
# def foo(descriptive_var_name,
# another_descriptive_var_name,
# last_descriptive_var_name)
# do_something
# end
#
# @example EnforcedStyle: require_no_parentheses
# # The `require_no_parentheses` style requires method definitions
# # to never use parentheses
#
# # bad
# def bar(num1, num2)
# num1 + num2
# end
#
# def foo(descriptive_var_name,
# another_descriptive_var_name,
# last_descriptive_var_name)
# do_something
# end
#
# # good
# def bar num1, num2
# num1 + num2
# end
#
# def foo descriptive_var_name,
# another_descriptive_var_name,
# last_descriptive_var_name
# do_something
# end
#
# @example EnforcedStyle: require_no_parentheses_except_multiline
# # The `require_no_parentheses_except_multiline` style prefers no
# # parentheses when method definition arguments fit on single line,
# # but prefers parentheses when arguments span multiple lines.
#
# # bad
# def bar(num1, num2)
# num1 + num2
# end
#
# def foo descriptive_var_name,
# another_descriptive_var_name,
# last_descriptive_var_name
# do_something
# end
#
# # good
# def bar num1, num2
# num1 + num2
# end
#
# def foo(descriptive_var_name,
# another_descriptive_var_name,
# last_descriptive_var_name)
# do_something
# end
class MethodDefParentheses < Base
include ConfigurableEnforcedStyle
include RangeHelp
extend AutoCorrector
MSG_PRESENT = 'Use def without parentheses.'
MSG_MISSING = 'Use def with parentheses when there are parameters.'
def on_def(node)
return if forced_parentheses?(node)
args = node.arguments
if require_parentheses?(args)
if arguments_without_parentheses?(node)
missing_parentheses(node)
else
correct_style_detected
end
elsif parentheses?(args)
unwanted_parentheses(args)
else
correct_style_detected
end
end
alias on_defs on_def
private
def correct_arguments(arg_node, corrector)
corrector.replace(arg_node.loc.begin, ' ')
corrector.remove(arg_node.loc.end)
end
def forced_parentheses?(node)
# Regardless of style, parentheses are necessary for:
# 1. Endless methods
# 2. Argument lists containing a `forward-arg` (`...`)
# 3. Argument lists containing an anonymous rest arguments forwarding (`*`)
# 4. Argument lists containing an anonymous keyword rest arguments forwarding (`**`)
# 5. Argument lists containing an anonymous block forwarding (`&`)
# Removing the parens would be a syntax error here.
node.endless? || anonymous_arguments?(node)
end
def require_parentheses?(args)
style == :require_parentheses ||
(style == :require_no_parentheses_except_multiline && args.multiline?)
end
def arguments_without_parentheses?(node)
node.arguments? && !parentheses?(node.arguments)
end
def missing_parentheses(node)
location = node.arguments.source_range
add_offense(location, message: MSG_MISSING) do |corrector|
add_parentheses(node.arguments, corrector)
unexpected_style_detected 'require_no_parentheses'
end
end
def unwanted_parentheses(args)
add_offense(args, message: MSG_PRESENT) do |corrector|
# offense is registered on args node when parentheses are unwanted
correct_arguments(args, corrector)
unexpected_style_detected 'require_parentheses'
end
end
def anonymous_arguments?(node)
return true if node.arguments.any? do |arg|
arg.type?(:forward_arg, :restarg, :kwrestarg)
end
return false unless (last_argument = node.last_argument)
last_argument.blockarg_type? && last_argument.name.nil?
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/inline_comment.rb | lib/rubocop/cop/style/inline_comment.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for trailing inline comments.
#
# @example
#
# # good
# foo.each do |f|
# # Standalone comment
# f.bar
# end
#
# # bad
# foo.each do |f|
# f.bar # Trailing inline comment
# end
class InlineComment < Base
MSG = 'Avoid trailing inline comments.'
def on_new_investigation
processed_source.comments.each do |comment|
next if comment_line?(processed_source[comment.loc.line - 1]) ||
comment.text.match?(/\A# rubocop:(enable|disable)/)
add_offense(comment)
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/yaml_file_read.rb | lib/rubocop/cop/style/yaml_file_read.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for the use of `YAML.load`, `YAML.safe_load`, and `YAML.parse` with
# `File.read` argument.
#
# NOTE: `YAML.safe_load_file` was introduced in Ruby 3.0.
#
# @example
#
# # bad
# YAML.load(File.read(path))
# YAML.parse(File.read(path))
#
# # good
# YAML.load_file(path)
# YAML.parse_file(path)
#
# # bad
# YAML.safe_load(File.read(path)) # Ruby 3.0 and newer
#
# # good
# YAML.safe_load_file(path) # Ruby 3.0 and newer
#
class YAMLFileRead < Base
extend AutoCorrector
MSG = 'Use `%<prefer>s` instead.'
RESTRICT_ON_SEND = %i[load safe_load parse].freeze
# @!method yaml_file_read?(node)
def_node_matcher :yaml_file_read?, <<~PATTERN
(send
(const {cbase nil?} :YAML) _
(send
(const {cbase nil?} :File) :read $_) $...)
PATTERN
def on_send(node)
return if node.method?(:safe_load) && target_ruby_version <= 2.7
return unless (file_path, rest_arguments = yaml_file_read?(node))
range = offense_range(node)
rest_arguments = if rest_arguments.empty?
''
else
", #{rest_arguments.map(&:source).join(', ')}"
end
prefer = "#{node.method_name}_file(#{file_path.source}#{rest_arguments})"
add_offense(range, message: format(MSG, prefer: prefer)) do |corrector|
corrector.replace(range, prefer)
end
end
private
def offense_range(node)
node.loc.selector.join(node.source_range.end)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/alias.rb | lib/rubocop/cop/style/alias.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Enforces the use of either `#alias` or `#alias_method`
# depending on configuration.
# It also flags uses of `alias :symbol` rather than `alias bareword`.
#
# However, it will always enforce `method_alias` when used `alias`
# in an instance method definition and in a singleton method definition.
# If used in a block, always enforce `alias_method`
# unless it is an `instance_eval` block.
#
# @example EnforcedStyle: prefer_alias (default)
# # bad
# alias_method :bar, :foo
# alias :bar :foo
#
# # good
# alias bar foo
#
# @example EnforcedStyle: prefer_alias_method
# # bad
# alias :bar :foo
# alias bar foo
#
# # good
# alias_method :bar, :foo
#
class Alias < Base
include ConfigurableEnforcedStyle
extend AutoCorrector
MSG_ALIAS = 'Use `alias_method` instead of `alias`.'
MSG_ALIAS_METHOD = 'Use `alias` instead of `alias_method` %<current>s.'
MSG_SYMBOL_ARGS = 'Use `alias %<prefer>s` instead of `alias %<current>s`.'
RESTRICT_ON_SEND = %i[alias_method].freeze
def on_send(node)
return unless node.command?(:alias_method)
return unless style == :prefer_alias && alias_keyword_possible?(node)
return unless node.arguments.count == 2
msg = format(MSG_ALIAS_METHOD, current: lexical_scope_type(node))
add_offense(node.loc.selector, message: msg) do |corrector|
autocorrect(corrector, node)
end
end
def on_alias(node)
return unless alias_method_possible?(node)
if scope_type(node) == :dynamic || style == :prefer_alias_method
add_offense(node.loc.keyword, message: MSG_ALIAS) do |corrector|
autocorrect(corrector, node)
end
elsif node.children.none? { |arg| bareword?(arg) }
add_offense_for_args(node) { |corrector| autocorrect(corrector, node) }
end
end
private
def autocorrect(corrector, node)
if node.send_type?
correct_alias_method_to_alias(corrector, node)
elsif scope_type(node) == :dynamic || style == :prefer_alias_method
correct_alias_to_alias_method(corrector, node)
else
correct_alias_with_symbol_args(corrector, node)
end
end
def alias_keyword_possible?(node)
scope_type(node) != :dynamic && node.arguments.all?(&:sym_type?)
end
def alias_method_possible?(node)
scope_type(node) != :instance_eval &&
node.children.none?(&:gvar_type?) &&
node.each_ancestor(:def).none?
end
def add_offense_for_args(node, &block)
existing_args = node.children.map(&:source).join(' ')
preferred_args = node.children.map { |a| a.source[1..] }.join(' ')
arg_ranges = node.children.map(&:source_range)
msg = format(MSG_SYMBOL_ARGS, prefer: preferred_args, current: existing_args)
add_offense(arg_ranges.reduce(&:join), message: msg, &block)
end
# In this expression, will `self` be the same as the innermost enclosing
# class or module block (:lexical)? Or will it be something else
# (:dynamic)? If we're in an instance_eval block, return that.
def scope_type(node)
while (parent = node.parent)
case parent.type
when :class, :module
return :lexical
when :def, :defs
return :dynamic
when :block
return :instance_eval if parent.method?(:instance_eval)
return :dynamic
end
node = parent
end
:lexical
end
def lexical_scope_type(node)
ancestor = node.each_ancestor(:class, :module).first
if ancestor.nil?
'at the top level'
elsif ancestor.class_type?
'in a class body'
else
'in a module body'
end
end
def bareword?(sym_node)
!sym_node.source.start_with?(':') || sym_node.dsym_type?
end
def correct_alias_method_to_alias(corrector, send_node)
new, old = *send_node.arguments
replacement = "alias #{identifier(new)} #{identifier(old)}"
corrector.replace(send_node, replacement)
end
def correct_alias_to_alias_method(corrector, node)
replacement =
"alias_method #{identifier(node.new_identifier)}, #{identifier(node.old_identifier)}"
corrector.replace(node, replacement)
end
def correct_alias_with_symbol_args(corrector, node)
corrector.replace(node.new_identifier, node.new_identifier.source[1..])
corrector.replace(node.old_identifier, node.old_identifier.source[1..])
end
def identifier(node)
if node.sym_type?
":#{node.children.first}"
else
node.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/style/quoted_symbols.rb | lib/rubocop/cop/style/quoted_symbols.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks if the quotes used for quoted symbols match the configured defaults.
# By default uses the same configuration as `Style/StringLiterals`; if that
# cop is not enabled, the default `EnforcedStyle` is `single_quotes`.
#
# String interpolation is always kept in double quotes.
#
# NOTE: `Lint/SymbolConversion` can be used in parallel to ensure that symbols
# are not quoted that don't need to be. This cop is for configuring the quoting
# style to use for symbols that require quotes.
#
# @example EnforcedStyle: same_as_string_literals (default) / single_quotes
# # bad
# :"abc-def"
#
# # good
# :'abc-def'
# :"#{str}"
# :"a\'b"
#
# @example EnforcedStyle: double_quotes
# # bad
# :'abc-def'
#
# # good
# :"abc-def"
# :"#{str}"
# :"a\'b"
class QuotedSymbols < Base
include ConfigurableEnforcedStyle
include SymbolHelp
include StringLiteralsHelp
extend AutoCorrector
MSG_SINGLE = "Prefer single-quoted symbols when you don't need string interpolation " \
'or special symbols.'
MSG_DOUBLE = 'Prefer double-quoted symbols unless you need single quotes to ' \
'avoid extra backslashes for escaping.'
def on_sym(node)
return unless quoted?(node)
message = style == :single_quotes ? MSG_SINGLE : MSG_DOUBLE
if wrong_quotes?(node) || invalid_double_quotes?(node.source)
add_offense(node, message: message) do |corrector|
opposite_style_detected
autocorrect(corrector, node)
end
else
correct_style_detected
end
end
private
def invalid_double_quotes?(source)
return false unless style == :double_quotes
# The string needs single quotes if:
# 1. It contains a double quote
# 2. It contains text that would become an escape sequence with double quotes
# 3. It contains text that would become an interpolation with double quotes
!/" | (?<!\\)\\[aAbcdefkMnprsStuUxzZ0-7] | \#[@{$]/x.match?(source)
end
def autocorrect(corrector, node)
str = if hash_colon_key?(node)
# strip quotes
correct_quotes(node.source[1..-2])
else
# strip leading `:` and quotes
":#{correct_quotes(node.source[2..-2])}"
end
corrector.replace(node, str)
end
def hash_colon_key?(node)
# Is the node a hash key with the colon style?
hash_key?(node) && node.parent.colon?
end
def correct_quotes(str)
correction = if style == :single_quotes
to_string_literal(str)
else
str.gsub("\\'", "'").inspect
end
# The conversion process doubles escaped slashes, so they have to be reverted
correction.gsub('\\\\', '\\').gsub('\"', '"')
end
def style
return super unless super == :same_as_string_literals
return :single_quotes unless config.cop_enabled?('Style/StringLiterals')
string_literals_config['EnforcedStyle'].to_sym
end
def alternative_style
(supported_styles - [style, :same_as_string_literals]).first
end
def quoted?(sym_node)
sym_node.source.match?(/\A:?(['"]).*?\1\z/m)
end
def wrong_quotes?(node)
return super if hash_key?(node)
super(node.source[1..])
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/multiline_block_chain.rb | lib/rubocop/cop/style/multiline_block_chain.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for chaining of a block after another block that spans
# multiple lines.
#
# @example
#
# # bad
# Thread.list.select do |t|
# t.alive?
# end.map do |t|
# t.object_id
# end
#
# # good
# alive_threads = Thread.list.select do |t|
# t.alive?
# end
# alive_threads.map do |t|
# t.object_id
# end
class MultilineBlockChain < Base
include RangeHelp
MSG = 'Avoid multi-line chains of blocks.'
def on_block(node)
node.send_node.each_node(:call) do |send_node|
receiver = send_node.receiver
next unless receiver&.any_block_type? && receiver.multiline?
range = range_between(receiver.loc.end.begin_pos, node.send_node.source_range.end_pos)
add_offense(range)
# Done. If there are more blocks in the chain, they will be
# found by subsequent calls to on_block.
break
end
end
alias on_numblock on_block
alias on_itblock on_block
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_interpolation_unfreeze.rb | lib/rubocop/cop/style/redundant_interpolation_unfreeze.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Before Ruby 3.0, interpolated strings followed the frozen string literal
# magic comment which sometimes made it necessary to explicitly unfreeze them.
# Ruby 3.0 changed interpolated strings to always be unfrozen which makes
# unfreezing them redundant.
#
# @example
# # bad
# +"#{foo} bar"
#
# # bad
# "#{foo} bar".dup
#
# # good
# "#{foo} bar"
#
class RedundantInterpolationUnfreeze < Base
include FrozenStringLiteral
extend AutoCorrector
extend TargetRubyVersion
MSG = "Don't unfreeze interpolated strings as they are already unfrozen."
RESTRICT_ON_SEND = %i[+@ dup].freeze
minimum_target_ruby_version 3.0
def on_send(node)
return if node.arguments?
return unless (receiver = node.receiver)
return unless receiver.dstr_type?
return if uninterpolated_string?(receiver) || uninterpolated_heredoc?(receiver)
add_offense(node.loc.selector) do |corrector|
corrector.remove(node.loc.selector)
corrector.remove(node.loc.dot) unless node.unary_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/style/redundant_argument.rb | lib/rubocop/cop/style/redundant_argument.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for a redundant argument passed to certain methods.
#
# NOTE: This cop is limited to methods with single parameter.
#
# Method names and their redundant arguments can be configured like this:
#
# [source,yaml]
# ----
# Methods:
# join: ''
# sum: 0
# split: ' '
# chomp: "\n"
# chomp!: "\n"
# foo: 2
# ----
#
# @safety
# This cop is unsafe because of the following limitations:
#
# 1. This cop matches by method names only and hence cannot tell apart
# methods with same name in different classes.
# 2. This cop may be unsafe if certain special global variables (e.g. `$;`, `$/`) are set.
# That depends on the nature of the target methods, of course. For example, the default
# argument to join is `$OUTPUT_FIELD_SEPARATOR` (or `$,`) rather than `''`, and if that
# global is changed, `''` is no longer a redundant argument.
#
# @example
# # bad
# array.join('')
# [1, 2, 3].join("")
# array.sum(0)
# exit(true)
# exit!(false)
# string.to_i(10)
# string.split(" ")
# "first\nsecond".split(" ")
# string.chomp("\n")
# string.chomp!("\n")
# A.foo(2)
#
# # good
# array.join
# [1, 2, 3].join
# array.sum
# exit
# exit!
# string.to_i
# string.split
# "first second".split
# string.chomp
# string.chomp!
# A.foo
class RedundantArgument < Base
include RangeHelp
extend AutoCorrector
MSG = 'Argument %<arg>s is redundant because it is implied by default.'
NO_RECEIVER_METHODS = %i[exit exit!].freeze
def on_send(node)
return if !NO_RECEIVER_METHODS.include?(node.method_name) && node.receiver.nil?
return if node.arguments.count != 1
return unless redundant_argument?(node)
offense_range = argument_range(node)
message = format(MSG, arg: node.first_argument.source)
add_offense(offense_range, message: message) do |corrector|
corrector.remove(offense_range)
end
end
alias on_csend on_send
private
def redundant_argument?(node)
redundant_argument = redundant_arg_for_method(node.method_name.to_s)
return false if redundant_argument.nil?
target_argument = if node.first_argument.respond_to?(:value)
node.first_argument.value
else
node.first_argument
end
argument_matched?(target_argument, redundant_argument)
end
def redundant_arg_for_method(method_name)
arg = cop_config['Methods'].fetch(method_name) { return }
@mem ||= {}
@mem[method_name] ||= arg.inspect
end
def argument_range(node)
if node.parenthesized?
range_between(node.loc.begin.begin_pos, node.loc.end.end_pos)
else
range_with_surrounding_space(node.first_argument.source_range, newlines: false)
end
end
def argument_matched?(target_argument, redundant_argument)
argument = if target_argument.is_a?(AST::Node)
target_argument.source
elsif exclude_cntrl_character?(target_argument, redundant_argument)
target_argument.inspect
else
target_argument.to_s
end
argument == redundant_argument
end
def exclude_cntrl_character?(target_argument, redundant_argument)
return true unless (target_argument_string = target_argument.to_s).valid_encoding?
!target_argument_string.sub(/\A'/, '"').sub(/'\z/, '"').match?(/[[:cntrl:]]/) ||
!redundant_argument.match?(/[[:cntrl:]]/)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/class_check.rb | lib/rubocop/cop/style/class_check.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Enforces consistent use of `Object#is_a?` or `Object#kind_of?`.
#
# @example EnforcedStyle: is_a? (default)
# # bad
# var.kind_of?(Date)
# var.kind_of?(Integer)
#
# # good
# var.is_a?(Date)
# var.is_a?(Integer)
#
# @example EnforcedStyle: kind_of?
# # bad
# var.is_a?(Time)
# var.is_a?(String)
#
# # good
# var.kind_of?(Time)
# var.kind_of?(String)
#
class ClassCheck < Base
include ConfigurableEnforcedStyle
extend AutoCorrector
MSG = 'Prefer `Object#%<prefer>s` over `Object#%<current>s`.'
RESTRICT_ON_SEND = %i[is_a? kind_of?].freeze
def on_send(node)
return if style == node.method_name
message = message(node)
add_offense(node.loc.selector, message: message) do |corrector|
replacement = node.method?(:is_a?) ? 'kind_of?' : 'is_a?'
corrector.replace(node.loc.selector, replacement)
end
end
alias on_csend on_send
def message(node)
if node.method?(:is_a?)
format(MSG, prefer: 'kind_of?', current: 'is_a?')
else
format(MSG, prefer: 'is_a?', current: 'kind_of?')
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/method_call_without_args_parentheses.rb | lib/rubocop/cop/style/method_call_without_args_parentheses.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for unwanted parentheses in parameterless method calls.
#
# This cop's allowed methods can be customized with `AllowedMethods`.
# By default, there are no allowed methods.
#
# NOTE: This cop allows the use of `it()` without arguments in blocks,
# as in `0.times { it() }`, following `Lint/ItWithoutArgumentsInBlock` cop.
#
# @example
# # bad
# object.some_method()
#
# # good
# object.some_method
#
# @example AllowedMethods: [] (default)
# # bad
# object.foo()
#
# @example AllowedMethods: [foo]
# # good
# object.foo()
#
class MethodCallWithoutArgsParentheses < Base
include AllowedMethods
include AllowedPattern
extend AutoCorrector
MSG = 'Do not use parentheses for method calls with no arguments.'
# rubocop:disable Metrics/CyclomaticComplexity
def on_send(node)
return unless !node.arguments? && node.parenthesized?
return if ineligible_node?(node)
return if default_argument?(node)
return if allowed_method_name?(node.method_name)
return if same_name_assignment?(node)
return if parenthesized_it_method_in_block?(node)
register_offense(node)
end
# rubocop:enable Metrics/CyclomaticComplexity
alias on_csend on_send
private
def register_offense(node)
add_offense(offense_range(node)) do |corrector|
corrector.remove(node.loc.begin)
corrector.remove(node.loc.end)
end
end
def ineligible_node?(node)
node.camel_case_method? || node.implicit_call? || node.prefix_not?
end
def default_argument?(node)
node.parent&.optarg_type?
end
def allowed_method_name?(name)
allowed_method?(name) || matches_allowed_pattern?(name)
end
def same_name_assignment?(node)
return false if node.receiver
any_assignment?(node) do |asgn_node|
if asgn_node.masgn_type?
variable_in_mass_assignment?(node.method_name, asgn_node)
else
asgn_node.loc.name.source == node.method_name.to_s
end
end
end
# Respects `Lint/ItWithoutArgumentsInBlock` cop and the following Ruby 3.3's warning:
#
# $ ruby -e '0.times { begin; it; end }'
# -e:1: warning: `it` calls without arguments will refer to the first block param in
# Ruby 3.4; use it() or self.it
#
def parenthesized_it_method_in_block?(node)
return false unless node.method?(:it)
return false unless (block_node = node.each_ancestor(:block).first)
return false unless block_node.arguments.empty_and_without_delimiters?
!node.receiver && node.arguments.empty? && !node.block_literal?
end
def any_assignment?(node)
node.each_ancestor(*AST::Node::ASSIGNMENTS).any? do |asgn_node|
# `obj.method = value` parses as (send ... :method= ...), and will
# not be returned as an `asgn_node` here, however,
# `obj.method ||= value` parses as (or-asgn (send ...) ...)
# which IS an `asgn_node`. Similarly, `obj.method += value` parses
# as (op-asgn (send ...) ...), which is also an `asgn_node`.
next if asgn_node.shorthand_asgn? && asgn_node.lhs.call_type?
yield asgn_node
end
end
def variable_in_mass_assignment?(variable_name, node)
node.assignments.reject(&:send_type?).any? { |n| n.name == variable_name }
end
def offense_range(node)
node.loc.begin.join(node.loc.end)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/yoda_condition.rb | lib/rubocop/cop/style/yoda_condition.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Enforces or forbids Yoda conditions,
# i.e. comparison operations where the order of expression is reversed.
# eg. `5 == x`
#
# @safety
# This cop is unsafe because comparison operators can be defined
# differently on different classes, and are not guaranteed to
# have the same result if reversed.
#
# For example:
#
# [source,ruby]
# ----
# class MyKlass
# def ==(other)
# true
# end
# end
#
# obj = MyKlass.new
# obj == 'string' #=> true
# 'string' == obj #=> false
# ----
#
# @example EnforcedStyle: forbid_for_all_comparison_operators (default)
# # bad
# 99 == foo
# "bar" != foo
# 42 >= foo
# 10 < bar
# 99 == CONST
#
# # good
# foo == 99
# foo == "bar"
# foo <= 42
# bar > 10
# CONST == 99
# "#{interpolation}" == foo
# /#{interpolation}/ == foo
#
# @example EnforcedStyle: forbid_for_equality_operators_only
# # bad
# 99 == foo
# "bar" != foo
#
# # good
# 99 >= foo
# 3 < a && a < 5
#
# @example EnforcedStyle: require_for_all_comparison_operators
# # bad
# foo == 99
# foo == "bar"
# foo <= 42
# bar > 10
#
# # good
# 99 == foo
# "bar" != foo
# 42 >= foo
# 10 < bar
#
# @example EnforcedStyle: require_for_equality_operators_only
# # bad
# 99 >= foo
# 3 < a && a < 5
#
# # good
# 99 == foo
# "bar" != foo
class YodaCondition < Base
include ConfigurableEnforcedStyle
include RangeHelp
extend AutoCorrector
MSG = 'Reverse the order of the operands `%<source>s`.'
REVERSE_COMPARISON = { '<' => '>', '<=' => '>=', '>' => '<', '>=' => '<=' }.freeze
EQUALITY_OPERATORS = %i[== !=].freeze
NONCOMMUTATIVE_OPERATORS = %i[===].freeze
PROGRAM_NAMES = %i[$0 $PROGRAM_NAME].freeze
RESTRICT_ON_SEND = RuboCop::AST::Node::COMPARISON_OPERATORS
ENFORCE_YODA_STYLES = %i[
require_for_all_comparison_operators require_for_equality_operators_only
].freeze
EQUALITY_ONLY_STYLES = %i[
forbid_for_equality_operators_only require_for_equality_operators_only
].freeze
# @!method file_constant_equal_program_name?(node)
def_node_matcher :file_constant_equal_program_name?, <<~PATTERN
(send #source_file_path_constant? {:== :!=} (gvar #program_name?))
PATTERN
def on_send(node)
return unless yoda_compatible_condition?(node)
return if (equality_only? && non_equality_operator?(node)) ||
file_constant_equal_program_name?(node) ||
valid_yoda?(node)
add_offense(node) do |corrector|
corrector.replace(actual_code_range(node), corrected_code(node))
end
end
private
def enforce_yoda?
ENFORCE_YODA_STYLES.include?(style)
end
def equality_only?
EQUALITY_ONLY_STYLES.include?(style)
end
def yoda_compatible_condition?(node)
node.comparison_method? && !noncommutative_operator?(node)
end
# rubocop:disable Metrics/CyclomaticComplexity
def valid_yoda?(node)
return true unless (rhs = node.first_argument)
lhs = node.receiver
return true if (constant_portion?(lhs) && constant_portion?(rhs)) ||
(!constant_portion?(lhs) && !constant_portion?(rhs)) ||
interpolation?(lhs)
enforce_yoda? ? constant_portion?(lhs) : constant_portion?(rhs)
end
# rubocop:enable Metrics/CyclomaticComplexity
def message(node)
format(MSG, source: node.source)
end
def corrected_code(node)
lhs = node.receiver
rhs = node.first_argument
"#{rhs.source} #{reverse_comparison(node.method_name)} #{lhs.source}"
end
def constant_portion?(node)
node.literal? || node.const_type?
end
def actual_code_range(node)
range_between(node.source_range.begin_pos, node.source_range.end_pos)
end
def reverse_comparison(operator)
REVERSE_COMPARISON.fetch(operator.to_s, operator)
end
def non_equality_operator?(node)
!EQUALITY_OPERATORS.include?(node.method_name)
end
def noncommutative_operator?(node)
NONCOMMUTATIVE_OPERATORS.include?(node.method_name)
end
def source_file_path_constant?(node)
node.source == '__FILE__'
end
def program_name?(name)
PROGRAM_NAMES.include?(name)
end
def interpolation?(node)
return true if node.dstr_type?
node.regexp_type? && node.interpolation?
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/option_hash.rb | lib/rubocop/cop/style/option_hash.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for options hashes and discourages them if the
# current Ruby version supports keyword arguments.
#
# @example
#
# # bad
# def fry(options = {})
# temperature = options.fetch(:temperature, 300)
# # ...
# end
#
#
# # good
# def fry(temperature: 300)
# # ...
# end
class OptionHash < Base
MSG = 'Prefer keyword arguments to options hashes.'
# @!method option_hash(node)
def_node_matcher :option_hash, <<~PATTERN
(args ... $(optarg [#suspicious_name? _] (hash)))
PATTERN
def on_args(node)
return if super_used?(node)
return if allowlist.include?(node.parent.method_name.to_s)
option_hash(node) { |options| add_offense(options) }
end
private
def allowlist
cop_config['Allowlist'] || []
end
def suspicious_name?(arg_name)
cop_config.key?('SuspiciousParamNames') &&
cop_config['SuspiciousParamNames'].include?(arg_name.to_s)
end
def super_used?(node)
node.parent.each_node(:zsuper).any?
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/semicolon.rb | lib/rubocop/cop/style/semicolon.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for multiple expressions placed on the same line.
# It also checks for lines terminated with a semicolon.
#
# This cop has `AllowAsExpressionSeparator` configuration option.
# It allows `;` to separate several expressions on the same line.
#
# @example
# # bad
# foo = 1; bar = 2;
# baz = 3;
#
# # good
# foo = 1
# bar = 2
# baz = 3
#
# @example AllowAsExpressionSeparator: false (default)
# # bad
# foo = 1; bar = 2
#
# @example AllowAsExpressionSeparator: true
# # good
# foo = 1; bar = 2
class Semicolon < Base
include RangeHelp
extend AutoCorrector
MSG = 'Do not use semicolons to terminate expressions.'
def self.autocorrect_incompatible_with
[Style::SingleLineMethods]
end
def on_new_investigation
return if processed_source.blank? || !processed_source.raw_source.include?(';')
check_for_line_terminator_or_opener
end
def on_begin(node)
return if cop_config['AllowAsExpressionSeparator']
return unless node.source.include?(';')
exprs = node.children
return if exprs.size < 2
expressions_per_line(exprs).each do |line, expr_on_line|
# Every line with more than one expression on it is a
# potential offense
next unless expr_on_line.size > 1
find_semicolon_positions(line) { |pos| register_semicolon(line, pos, true) }
end
end
private
def check_for_line_terminator_or_opener
each_semicolon do |line, column, token_before_semicolon|
register_semicolon(line, column, false, token_before_semicolon)
end
end
def each_semicolon
tokens_for_lines.each do |line, tokens|
next unless (semicolon_pos = semicolon_position(tokens))
after_expr_pos = semicolon_pos == -1 ? -2 : semicolon_pos
yield line, tokens[semicolon_pos].column, tokens[after_expr_pos]
end
end
def tokens_for_lines
processed_source.tokens.group_by(&:line)
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def semicolon_position(tokens)
if tokens.last.semicolon?
-1
elsif tokens.first.semicolon?
0
elsif exist_semicolon_before_right_curly_brace?(tokens)
-3
elsif exist_semicolon_after_left_curly_brace?(tokens) ||
exist_semicolon_after_left_string_interpolation_brace?(tokens)
2
elsif exist_semicolon_after_left_lambda_curly_brace?(tokens)
3
elsif exist_semicolon_before_right_string_interpolation_brace?(tokens)
-4
end
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def exist_semicolon_before_right_curly_brace?(tokens)
tokens[-2]&.right_curly_brace? && tokens[-3]&.semicolon?
end
def exist_semicolon_after_left_curly_brace?(tokens)
tokens[1]&.left_curly_brace? && tokens[2]&.semicolon?
end
def exist_semicolon_after_left_lambda_curly_brace?(tokens)
tokens[2]&.type == :tLAMBEG && tokens[3]&.semicolon?
end
def exist_semicolon_before_right_string_interpolation_brace?(tokens)
tokens[-3]&.type == :tSTRING_DEND && tokens[-4]&.semicolon?
end
def exist_semicolon_after_left_string_interpolation_brace?(tokens)
tokens[1]&.type == :tSTRING_DBEG && tokens[2]&.semicolon?
end
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength
def register_semicolon(line, column, after_expression, token_before_semicolon = nil)
range = source_range(processed_source.buffer, line, column)
add_offense(range) do |corrector|
if after_expression
corrector.replace(range, "\n")
else
# Prevents becoming one range instance with subsequent line when endless range
# without parentheses.
# See: https://github.com/rubocop/rubocop/issues/10791
if token_before_semicolon&.regexp_dots?
node = find_node(range_nodes, token_before_semicolon)
elsif token_before_semicolon&.type == :tLABEL
node = find_node(value_omission_pair_nodes, token_before_semicolon).parent
space = node.parent.loc.selector.end.join(node.source_range.begin)
corrector.remove(space)
end
corrector.wrap(node, '(', ')') if node
corrector.remove(range)
end
end
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength
def expressions_per_line(exprs)
# create a map matching lines to the number of expressions on them
exprs_lines = exprs.map(&:last_line)
exprs_lines.group_by(&:itself)
end
def find_semicolon_positions(line)
# Scan for all the semicolons on the line
semicolons = processed_source[line - 1].enum_for(:scan, ';')
semicolons.each do
yield Regexp.last_match.begin(0)
end
end
def find_node(nodes, token_before_semicolon)
nodes.detect do |node|
node.source_range.overlaps?(token_before_semicolon.pos)
end
end
def range_nodes
return @range_nodes if instance_variable_defined?(:@range_nodes)
ast = processed_source.ast
@range_nodes = ast.range_type? ? [ast] : []
@range_nodes.concat(ast.each_descendant(:range).to_a)
end
def value_omission_pair_nodes
if instance_variable_defined?(:@value_omission_pair_nodes)
return @value_omission_pair_nodes
end
ast = processed_source.ast
@value_omission_pair_nodes = ast.each_descendant(:pair).to_a.select(&:value_omission?)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_conditional.rb | lib/rubocop/cop/style/redundant_conditional.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for redundant returning of true/false in conditionals.
#
# @example
# # bad
# x == y ? true : false
#
# # bad
# if x == y
# true
# else
# false
# end
#
# # good
# x == y
#
# # bad
# x == y ? false : true
#
# # good
# x != y
class RedundantConditional < Base
include Alignment
extend AutoCorrector
operators = RuboCop::AST::Node::COMPARISON_OPERATORS.to_a
COMPARISON_OPERATOR_MATCHER = "{:#{operators.join(' :')}}"
MSG = 'This conditional expression can just be replaced by `%<msg>s`.'
def on_if(node)
return unless offense?(node)
message = message(node)
add_offense(node, message: message) do |corrector|
corrector.replace(node, replacement_condition(node))
end
end
private
def message(node)
replacement = replacement_condition(node)
msg = node.elsif? ? "\n#{replacement}" : replacement
format(MSG, msg: msg)
end
# @!method redundant_condition?(node)
def_node_matcher :redundant_condition?, <<~RUBY
(if (send _ #{COMPARISON_OPERATOR_MATCHER} _) true false)
RUBY
# @!method redundant_condition_inverted?(node)
def_node_matcher :redundant_condition_inverted?, <<~RUBY
(if (send _ #{COMPARISON_OPERATOR_MATCHER} _) false true)
RUBY
def offense?(node)
return false if node.modifier_form?
redundant_condition?(node) || redundant_condition_inverted?(node)
end
def replacement_condition(node)
condition = node.condition.source
expression = redundant_condition_inverted?(node) ? "!(#{condition})" : condition
node.elsif? ? indented_else_node(expression, node) : expression
end
def indented_else_node(expression, node)
"else\n#{indentation(node)}#{expression}"
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/file_write.rb | lib/rubocop/cop/style/file_write.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Favor `File.(bin)write` convenience methods.
#
# NOTE: There are different method signatures between `File.write` (class method)
# and `File#write` (instance method). The following case will be allowed because
# static analysis does not know the contents of the splat argument:
#
# [source,ruby]
# ----
# File.open(filename, 'w') do |f|
# f.write(*objects)
# end
# ----
#
# @example
# # bad - text mode
# File.open(filename, 'w').write(content)
# File.open(filename, 'w') do |f|
# f.write(content)
# end
#
# # good
# File.write(filename, content)
#
# # bad - binary mode
# File.open(filename, 'wb').write(content)
# File.open(filename, 'wb') do |f|
# f.write(content)
# end
#
# # good
# File.binwrite(filename, content)
#
class FileWrite < Base
extend AutoCorrector
include RangeHelp
MSG = 'Use `File.%<write_method>s`.'
RESTRICT_ON_SEND = %i[open].to_set.freeze
TRUNCATING_WRITE_MODES = %w[w wt wb w+ w+t w+b].to_set.freeze
# @!method file_open?(node)
def_node_matcher :file_open?, <<~PATTERN
(send
(const {nil? cbase} :File)
:open
$_
(str $%TRUNCATING_WRITE_MODES)
(block-pass (sym :write))?
)
PATTERN
# @!method send_write?(node)
def_node_matcher :send_write?, <<~PATTERN
(send _ :write $_)
PATTERN
# @!method block_write?(node)
def_node_matcher :block_write?, <<~PATTERN
(block _ (args (arg $_)) (send (lvar $_) :write $_))
PATTERN
def on_send(node)
evidence(node) do |filename, mode, content, write_node|
message = format(MSG, write_method: write_method(mode))
add_offense(write_node, message: message) do |corrector|
range = range_between(node.loc.selector.begin_pos, write_node.source_range.end_pos)
replacement = replacement(mode, filename, content, write_node)
corrector.replace(range, replacement)
end
end
end
def evidence(node)
file_open?(node) do |filename, mode|
file_open_write?(node.parent) do |content|
yield(filename, mode, content, node.parent)
end
end
end
private
def file_open_write?(node)
content = send_write?(node) || block_write?(node) do |block_arg, lvar, write_arg|
write_arg if block_arg == lvar
end
return false if content&.splat_type?
yield(content) if content
end
def write_method(mode)
mode.end_with?('b') ? :binwrite : :write
end
def replacement(mode, filename, content, write_node)
replacement = "#{write_method(mode)}(#{filename.source}, #{content.source})"
if heredoc?(write_node)
first_argument = write_node.body.first_argument
<<~REPLACEMENT.chomp
#{replacement}
#{heredoc_range(first_argument).source}
REPLACEMENT
else
replacement
end
end
def heredoc?(write_node)
write_node.block_type? && (first_argument = write_node.body.first_argument) &&
first_argument.respond_to?(:heredoc?) && first_argument.heredoc?
end
def heredoc_range(first_argument)
range_between(
first_argument.loc.heredoc_body.begin_pos, first_argument.loc.heredoc_end.end_pos
)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/command_literal.rb | lib/rubocop/cop/style/command_literal.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Enforces using `` or %x around command literals.
#
# @example EnforcedStyle: backticks (default)
# # bad
# folders = %x(find . -type d).split
#
# # bad
# %x(
# ln -s foo.example.yml foo.example
# ln -s bar.example.yml bar.example
# )
#
# # good
# folders = `find . -type d`.split
#
# # good
# `
# ln -s foo.example.yml foo.example
# ln -s bar.example.yml bar.example
# `
#
# @example EnforcedStyle: mixed
# # bad
# folders = %x(find . -type d).split
#
# # bad
# `
# ln -s foo.example.yml foo.example
# ln -s bar.example.yml bar.example
# `
#
# # good
# folders = `find . -type d`.split
#
# # good
# %x(
# ln -s foo.example.yml foo.example
# ln -s bar.example.yml bar.example
# )
#
# @example EnforcedStyle: percent_x
# # bad
# folders = `find . -type d`.split
#
# # bad
# `
# ln -s foo.example.yml foo.example
# ln -s bar.example.yml bar.example
# `
#
# # good
# folders = %x(find . -type d).split
#
# # good
# %x(
# ln -s foo.example.yml foo.example
# ln -s bar.example.yml bar.example
# )
#
# @example AllowInnerBackticks: false (default)
# # If `false`, the cop will always recommend using `%x` if one or more
# # backticks are found in the command string.
#
# # bad
# `echo \`ls\``
#
# # good
# %x(echo `ls`)
#
# @example AllowInnerBackticks: true
# # good
# `echo \`ls\``
class CommandLiteral < Base
include ConfigurableEnforcedStyle
extend AutoCorrector
MSG_USE_BACKTICKS = 'Use backticks around command string.'
MSG_USE_PERCENT_X = 'Use `%x` around command string.'
def on_xstr(node)
return if node.heredoc?
if backtick_literal?(node)
check_backtick_literal(node, MSG_USE_PERCENT_X)
else
check_percent_x_literal(node, MSG_USE_BACKTICKS)
end
end
private
def check_backtick_literal(node, message)
return if allowed_backtick_literal?(node)
add_offense(node, message: message) { |corrector| autocorrect(corrector, node) }
end
def check_percent_x_literal(node, message)
return if allowed_percent_x_literal?(node)
add_offense(node, message: message) { |corrector| autocorrect(corrector, node) }
end
def autocorrect(corrector, node)
return if contains_backtick?(node)
replacement = if backtick_literal?(node)
['%x', ''].zip(preferred_delimiter).map(&:join)
else
%w[` `]
end
corrector.replace(node.loc.begin, replacement.first)
corrector.replace(node.loc.end, replacement.last)
end
def allowed_backtick_literal?(node)
case style
when :backticks
!contains_disallowed_backtick?(node)
when :mixed
node.single_line? && !contains_disallowed_backtick?(node)
end
end
def allowed_percent_x_literal?(node)
case style
when :backticks
contains_disallowed_backtick?(node)
when :mixed
node.multiline? || contains_disallowed_backtick?(node)
when :percent_x
true
end
end
def contains_disallowed_backtick?(node)
!allow_inner_backticks? && contains_backtick?(node)
end
def allow_inner_backticks?
cop_config['AllowInnerBackticks']
end
def contains_backtick?(node)
node_body(node).include?('`')
end
def node_body(node)
loc = node.loc
loc.expression.source[loc.begin.length...-loc.end.length]
end
def backtick_literal?(node)
node.loc.begin.source == '`'
end
def preferred_delimiter
(command_delimiter || default_delimiter).chars
end
def command_delimiter
preferred_delimiters_config['%x']
end
def default_delimiter
preferred_delimiters_config['default']
end
def preferred_delimiters_config
config.for_cop('Style/PercentLiteralDelimiters')['PreferredDelimiters']
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/negated_while.rb | lib/rubocop/cop/style/negated_while.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for uses of while with a negated condition.
#
# @example
# # bad
# while !foo
# bar
# end
#
# # good
# until foo
# bar
# end
#
# # bad
# bar until !foo
#
# # good
# bar while foo
# bar while !foo && baz
class NegatedWhile < Base
include NegativeConditional
extend AutoCorrector
def on_while(node)
message = format(MSG, inverse: node.inverse_keyword, current: node.keyword)
check_negative_conditional(node, message: message) do |corrector|
ConditionCorrector.correct_negative_condition(corrector, node)
end
end
alias on_until on_while
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_constant_base.rb | lib/rubocop/cop/style/redundant_constant_base.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Avoid redundant `::` prefix on constant.
#
# How Ruby searches constant is a bit complicated, and it can often be difficult to
# understand from the code whether the `::` is intended or not. Where `Module.nesting`
# is empty, there is no need to prepend `::`, so it would be nice to consistently
# avoid such meaningless `::` prefix to avoid confusion.
#
# NOTE: This cop is disabled if `Lint/ConstantResolution` cop is enabled to prevent
# conflicting rules. Because it respects user configurations that want to enable
# `Lint/ConstantResolution` cop which is disabled by default.
#
# @example
# # bad
# ::Const
#
# # good
# Const
#
# # bad
# class << self
# ::Const
# end
#
# # good
# class << self
# Const
# end
#
# # good
# class A
# ::Const
# end
#
# # good
# module A
# ::Const
# end
class RedundantConstantBase < Base
extend AutoCorrector
MSG = 'Remove redundant `::`.'
def on_cbase(node)
return if lint_constant_resolution_cop_enabled?
return unless bad?(node)
add_offense(node) do |corrector|
corrector.remove(node)
end
end
private
def lint_constant_resolution_cop_enabled?
lint_constant_resolution_config.fetch('Enabled', false)
end
def lint_constant_resolution_config
config.for_cop('Lint/ConstantResolution')
end
def bad?(node)
module_nesting_ancestors_of(node).none?
end
def module_nesting_ancestors_of(node)
node.each_ancestor(:class, :module).reject do |ancestor|
ancestor.class_type? && used_in_super_class_part?(node, class_node: ancestor)
end
end
def used_in_super_class_part?(node, class_node:)
class_node.parent_class&.each_descendant(:cbase)&.any? do |descendant|
descendant.equal?(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/style/colon_method_call.rb | lib/rubocop/cop/style/colon_method_call.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for methods invoked via the `::` operator instead
# of the `.` operator (like `FileUtils::rmdir` instead of `FileUtils.rmdir`).
#
# @example
# # bad
# Timeout::timeout(500) { do_something }
# FileUtils::rmdir(dir)
# Marshal::dump(obj)
#
# # good
# Timeout.timeout(500) { do_something }
# FileUtils.rmdir(dir)
# Marshal.dump(obj)
#
class ColonMethodCall < Base
extend AutoCorrector
MSG = 'Do not use `::` for method calls.'
# @!method java_type_node?(node)
def_node_matcher :java_type_node?, <<~PATTERN
(send
(const nil? :Java) _)
PATTERN
def self.autocorrect_incompatible_with
[RedundantSelf]
end
def on_send(node)
return unless node.receiver && node.double_colon?
return if node.camel_case_method?
# ignore Java interop code like Java::int
return if java_type_node?(node)
add_offense(node.loc.dot) { |corrector| corrector.replace(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/style/block_delimiters.rb | lib/rubocop/cop/style/block_delimiters.rb | # frozen_string_literal: true
# rubocop:disable Metrics/ClassLength
module RuboCop
module Cop
module Style
# Checks for uses of braces or do/end around single line or
# multi-line blocks.
#
# Methods that can be either procedural or functional and cannot be
# categorised from their usage alone is ignored.
# `lambda`, `proc`, and `it` are their defaults.
# Additional methods can be added to the `AllowedMethods`.
#
# @example EnforcedStyle: line_count_based (default)
# # bad - single line block
# items.each do |item| item / 5 end
#
# # good - single line block
# items.each { |item| item / 5 }
#
# # bad - multi-line block
# things.map { |thing|
# something = thing.some_method
# process(something)
# }
#
# # good - multi-line block
# things.map do |thing|
# something = thing.some_method
# process(something)
# end
#
# @example EnforcedStyle: semantic
# # Prefer `do...end` over `{...}` for procedural blocks.
#
# # return value is used/assigned
# # bad
# foo = map do |x|
# x
# end
# puts (map do |x|
# x
# end)
#
# # return value is not used out of scope
# # good
# map do |x|
# x
# end
#
# # Prefer `{...}` over `do...end` for functional blocks.
#
# # return value is not used out of scope
# # bad
# each { |x|
# x
# }
#
# # return value is used/assigned
# # good
# foo = map { |x|
# x
# }
# map { |x|
# x
# }.inspect
#
# # The AllowBracesOnProceduralOneLiners option is allowed unless the
# # EnforcedStyle is set to `semantic`. If so:
#
# # If the AllowBracesOnProceduralOneLiners option is unspecified, or
# # set to `false` or any other falsey value, then semantic purity is
# # maintained, so one-line procedural blocks must use do-end, not
# # braces.
#
# # bad
# collection.each { |element| puts element }
#
# # good
# collection.each do |element| puts element end
#
# # If the AllowBracesOnProceduralOneLiners option is set to `true`, or
# # any other truthy value, then one-line procedural blocks may use
# # either style. (There is no setting for requiring braces on them.)
#
# # good
# collection.each { |element| puts element }
#
# # also good
# collection.each do |element| puts element end
#
# @example EnforcedStyle: braces_for_chaining
# # bad
# words.each do |word|
# word.flip.flop
# end.join("-")
#
# # good
# words.each { |word|
# word.flip.flop
# }.join("-")
#
# @example EnforcedStyle: always_braces
# # bad
# words.each do |word|
# word.flip.flop
# end
#
# # good
# words.each { |word|
# word.flip.flop
# }
#
# @example BracesRequiredMethods: ['sig']
#
# # Methods listed in the BracesRequiredMethods list, such as 'sig'
# # in this example, will require `{...}` braces. This option takes
# # precedence over all other configurations except AllowedMethods.
#
# # bad
# sig do
# params(
# foo: string,
# ).void
# end
# def bar(foo)
# puts foo
# end
#
# # good
# sig {
# params(
# foo: string,
# ).void
# }
# def bar(foo)
# puts foo
# end
#
# @example AllowedMethods: ['lambda', 'proc', 'it' ] (default)
#
# # good
# foo = lambda do |x|
# puts "Hello, #{x}"
# end
#
# foo = lambda do |x|
# x * 100
# end
#
# @example AllowedPatterns: [] (default)
#
# # bad
# things.map { |thing|
# something = thing.some_method
# process(something)
# }
#
# @example AllowedPatterns: ['map']
#
# # good
# things.map { |thing|
# something = thing.some_method
# process(something)
# }
#
class BlockDelimiters < Base
include ConfigurableEnforcedStyle
include AllowedMethods
include AllowedPattern
include RangeHelp
extend AutoCorrector
ALWAYS_BRACES_MESSAGE = 'Prefer `{...}` over `do...end` for blocks.'
BRACES_REQUIRED_MESSAGE = "Brace delimiters `{...}` required for '%<method_name>s' method."
def self.autocorrect_incompatible_with
[Style::RedundantBegin]
end
def on_send(node)
return unless node.arguments?
return if node.parenthesized?
return if node.assignment_method?
return if single_argument_operator_method?(node)
node.arguments.each do |arg|
get_blocks(arg) do |block|
# If there are no parentheses around the arguments, then braces
# and do-end have different meaning due to how they bind, so we
# allow either.
ignore_node(block)
end
end
end
alias on_csend on_send
def on_block(node)
return if ignored_node?(node)
return if proper_block_style?(node)
message = message(node)
add_offense(node.loc.begin, message: message) do |corrector|
autocorrect(corrector, node)
end
end
alias on_numblock on_block
alias on_itblock on_block
private
def autocorrect(corrector, node)
return if correction_would_break_code?(node)
if node.braces?
replace_braces_with_do_end(corrector, node.loc)
else
replace_do_end_with_braces(corrector, node)
end
end
def line_count_based_message(node)
if node.multiline?
'Avoid using `{...}` for multi-line blocks.'
else
'Prefer `{...}` over `do...end` for single-line blocks.'
end
end
def semantic_message(node)
block_begin = node.loc.begin.source
if block_begin == '{'
'Prefer `do...end` over `{...}` for procedural blocks.'
else
'Prefer `{...}` over `do...end` for functional blocks.'
end
end
def braces_for_chaining_message(node)
if node.multiline?
if node.chained?
'Prefer `{...}` over `do...end` for multi-line chained blocks.'
else
'Prefer `do...end` for multi-line blocks without chaining.'
end
else
'Prefer `{...}` over `do...end` for single-line blocks.'
end
end
def braces_required_message(node)
format(BRACES_REQUIRED_MESSAGE, method_name: node.method_name.to_s)
end
def message(node)
return braces_required_message(node) if braces_required_method?(node.method_name)
case style
when :line_count_based then line_count_based_message(node)
when :semantic then semantic_message(node)
when :braces_for_chaining then braces_for_chaining_message(node)
when :always_braces then ALWAYS_BRACES_MESSAGE
end
end
def replace_braces_with_do_end(corrector, loc)
b = loc.begin
e = loc.end
corrector.insert_before(b, ' ') unless whitespace_before?(b)
corrector.insert_before(e, ' ') unless whitespace_before?(e)
corrector.insert_after(b, ' ') unless whitespace_after?(b)
corrector.replace(b, 'do')
if (comment = processed_source.comment_at_line(e.line))
move_comment_before_block(corrector, comment, loc.node, e)
end
corrector.replace(e, 'end')
end
def replace_do_end_with_braces(corrector, node)
loc = node.loc
b = loc.begin
e = loc.end
corrector.insert_after(b, ' ') unless whitespace_after?(b, 2)
corrector.replace(b, '{')
corrector.replace(e, '}')
corrector.wrap(node.body, "begin\n", "\nend") if begin_required?(node)
end
def whitespace_before?(range)
/\s/.match?(range.source_buffer.source[range.begin_pos - 1, 1])
end
def whitespace_after?(range, length = 1)
/\s/.match?(range.source_buffer.source[range.begin_pos + length, 1])
end
def move_comment_before_block(corrector, comment, block_node, closing_brace)
range = block_node.chained? ? end_of_chain(block_node.parent).source_range : closing_brace
# It is possible that there is code between the block and the comment
# which needs to be preserved and trimmed.
pre_comment_range = source_range_before_comment(range, comment)
corrector.remove(range_with_surrounding_space(comment.source_range, side: :right))
remove_trailing_whitespace(corrector, pre_comment_range, comment)
corrector.insert_after(pre_comment_range, "\n")
corrector.insert_before(block_node, "#{comment.text}\n")
end
def source_range_before_comment(range, comment)
range = range.end.join(comment.source_range.begin)
# End the range before any whitespace that precedes the comment
trailing_whitespace_count = range.source[/\s+\z/]&.length
range = range.adjust(end_pos: -trailing_whitespace_count) if trailing_whitespace_count
range
end
def end_of_chain(node)
return end_of_chain(node.block_node) if with_block?(node)
return node unless node.chained?
end_of_chain(node.parent)
end
def remove_trailing_whitespace(corrector, range, comment)
range_of_trailing = range.end.join(comment.source_range.begin)
corrector.remove(range_of_trailing) if range_of_trailing.source.match?(/\A\s+\z/)
end
def with_block?(node)
node.respond_to?(:block_node) && node.block_node
end
# rubocop:disable Metrics/CyclomaticComplexity
def get_blocks(node, &block)
case node.type
when :block, :numblock, :itblock
yield node
when :send, :csend
# When a method has an argument which is another method with a block,
# that block needs braces, otherwise a syntax error will be introduced
# for subsequent arguments.
# Additionally, even without additional arguments, changing `{...}` to
# `do...end` will change the binding of the block to the outer method.
get_blocks(node.receiver, &block) if node.receiver
node.arguments.each { |argument| get_blocks(argument, &block) }
when :hash
# A hash which is passed as method argument may have no braces
# In that case, one of the K/V pairs could contain a block node
# which could change in meaning if `do...end` is replaced with `{...}`
return if node.braces?
node.each_child_node { |child| get_blocks(child, &block) }
when :pair
node.each_child_node { |child| get_blocks(child, &block) }
end
end
# rubocop:enable Metrics/CyclomaticComplexity
def proper_block_style?(node)
return true if require_do_end?(node)
return special_method_proper_block_style?(node) if special_method?(node.method_name)
case style
when :line_count_based then line_count_based_block_style?(node)
when :semantic then semantic_block_style?(node)
when :braces_for_chaining then braces_for_chaining_style?(node)
when :always_braces then braces_style?(node)
end
end
def require_do_end?(node)
return false if node.braces? || node.multiline?
return false unless (resbody = node.each_descendant(:resbody).first)
resbody.children.first&.array_type?
end
def special_method?(method_name)
allowed_method?(method_name) ||
matches_allowed_pattern?(method_name) ||
braces_required_method?(method_name)
end
def special_method_proper_block_style?(node)
method_name = node.method_name
return true if allowed_method?(method_name) || matches_allowed_pattern?(method_name)
node.braces? if braces_required_method?(method_name)
end
def braces_required_method?(method_name)
braces_required_methods.include?(method_name.to_s)
end
def braces_required_methods
cop_config.fetch('BracesRequiredMethods', [])
end
def line_count_based_block_style?(node)
node.multiline? ^ node.braces?
end
def semantic_block_style?(node)
method_name = node.method_name
if node.braces?
functional_method?(method_name) || functional_block?(node) ||
(procedural_oneliners_may_have_braces? && !node.multiline?)
else
procedural_method?(method_name) || !return_value_used?(node)
end
end
def braces_for_chaining_style?(node)
block_begin = node.loc.begin.source
block_begin == if node.multiline?
(node.chained? ? '{' : 'do')
else
'{'
end
end
def braces_style?(node)
node.loc.begin.source == '{'
end
def correction_would_break_code?(node)
return false unless node.keywords?
node.send_node.arguments? && !node.send_node.parenthesized?
end
def functional_method?(method_name)
cop_config['FunctionalMethods'].map(&:to_sym).include?(method_name)
end
def functional_block?(node)
return_value_used?(node) || return_value_of_scope?(node)
end
def procedural_oneliners_may_have_braces?
cop_config['AllowBracesOnProceduralOneLiners']
end
def procedural_method?(method_name)
cop_config['ProceduralMethods'].map(&:to_sym).include?(method_name)
end
def return_value_used?(node)
return false unless node.parent
# If there are parentheses around the block, check if that
# is being used.
if node.parent.begin_type?
return_value_used?(node.parent)
else
node.parent.assignment? || node.parent.call_type?
end
end
def return_value_of_scope?(node)
return false unless (parent = node.parent)
parent.conditional? || parent.operator_keyword? || array_or_range?(parent) ||
parent.children.last == node
end
def array_or_range?(node)
node.type?(:array, :range)
end
def begin_required?(block_node)
# If the block contains `rescue` or `ensure`, it needs to be wrapped in
# `begin`...`end` when changing `do-end` to `{}`.
block_node.each_child_node(:rescue, :ensure).any? && !block_node.single_line?
end
def single_argument_operator_method?(node)
return false unless node.operator_method?
node.arguments.one? && node.first_argument.block_type?
end
end
end
end
end
# rubocop:enable Metrics/ClassLength
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/optional_boolean_parameter.rb | lib/rubocop/cop/style/optional_boolean_parameter.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for places where keyword arguments can be used instead of
# boolean arguments when defining methods. `respond_to_missing?` method is allowed by default.
# These are customizable with `AllowedMethods` option.
#
# @safety
# This cop is unsafe because changing a method signature will
# implicitly change behavior.
#
# @example
# # bad
# def some_method(bar = false)
# puts bar
# end
#
# # bad - common hack before keyword args were introduced
# def some_method(options = {})
# bar = options.fetch(:bar, false)
# puts bar
# end
#
# # good
# def some_method(bar: false)
# puts bar
# end
#
# @example AllowedMethods: ['some_method']
# # good
# def some_method(bar = false)
# puts bar
# end
#
class OptionalBooleanParameter < Base
include AllowedMethods
MSG = 'Prefer keyword arguments for arguments with a boolean default value; ' \
'use `%<replacement>s` instead of `%<original>s`.'
def on_def(node)
return if allowed_method?(node.method_name)
node.arguments.each do |arg|
next unless arg.optarg_type?
add_offense(arg, message: format_message(arg)) if arg.default_value.boolean_type?
end
end
alias on_defs on_def
private
def format_message(argument)
replacement = "#{argument.name}: #{argument.default_value.source}"
format(MSG, original: argument.source, 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/style/trailing_comma_in_arguments.rb | lib/rubocop/cop/style/trailing_comma_in_arguments.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for trailing comma in argument lists.
# The supported styles are:
#
# * `consistent_comma`: Requires a comma after the last argument,
# for all parenthesized multi-line method calls with arguments.
# * `comma`: Requires a comma after the last argument, but only for
# parenthesized method calls where each argument is on its own line.
# * `diff_comma`: Requires a comma after the last argument, but only
# when that argument is followed by an immediate newline, even if
# there is an inline comment on the same line.
# * `no_comma`: Requires that there is no comma after the last
# argument.
#
# Regardless of style, trailing commas are not allowed in
# single-line method calls.
#
# @example EnforcedStyleForMultiline: consistent_comma
# # bad
# method(1, 2,)
#
# # good
# method(1, 2)
#
# # good
# method(
# 1, 2,
# 3,
# )
#
# # good
# method(
# 1, 2, 3,
# )
#
# # good
# method(
# 1,
# 2,
# )
#
# @example EnforcedStyleForMultiline: comma
# # bad
# method(1, 2,)
#
# # good
# method(1, 2)
#
# # bad
# method(
# 1, 2,
# 3,
# )
#
# # good
# method(
# 1, 2,
# 3
# )
#
# # bad
# method(
# 1, 2, 3,
# )
#
# # good
# method(
# 1, 2, 3
# )
#
# # good
# method(
# 1,
# 2,
# )
#
# @example EnforcedStyleForMultiline: diff_comma
# # bad
# method(1, 2,)
#
# # good
# method(1, 2)
#
# # good
# method(
# 1, 2,
# 3,
# )
#
# # good
# method(
# 1, 2, 3,
# )
#
# # good
# method(
# 1,
# 2,
# )
#
# # bad
# method(1, [
# 2,
# ],)
#
# # good
# method(1, [
# 2,
# ])
#
# # bad
# object[1, 2,
# 3, 4,]
#
# # good
# object[1, 2,
# 3, 4]
#
# @example EnforcedStyleForMultiline: no_comma (default)
# # bad
# method(1, 2,)
#
# # bad
# object[1, 2,]
#
# # good
# method(1, 2)
#
# # good
# object[1, 2]
#
# # good
# method(
# 1,
# 2
# )
class TrailingCommaInArguments < Base
include TrailingComma
extend AutoCorrector
def self.autocorrect_incompatible_with
[Layout::HeredocArgumentClosingParenthesis]
end
def on_send(node)
return unless node.arguments? && (node.parenthesized? || node.method?(:[]))
check(node, node.arguments, 'parameter of %<article>s method call',
node.last_argument.source_range.end_pos,
node.source_range.end_pos)
end
alias on_csend on_send
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.