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/swap_values.rb
lib/rubocop/cop/style/swap_values.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Enforces the use of shorthand-style swapping of 2 variables. # # @safety # Autocorrection is unsafe, because the temporary variable used to # swap variables will be removed, but may be referred to elsewhere. # # @example # # bad # tmp = x # x = y # y = tmp # # # good # x, y = y, x # class SwapValues < Base include RangeHelp extend AutoCorrector MSG = 'Replace this and assignments at lines %<x_line>d ' \ 'and %<y_line>d with `%<replacement>s`.' SIMPLE_ASSIGNMENT_TYPES = %i[lvasgn ivasgn cvasgn gvasgn casgn].to_set.freeze def on_asgn(node) return if allowed_assignment?(node) tmp_assign = node x_assign, y_assign = *node.right_siblings.take(2) return unless x_assign && y_assign && swapping_values?(tmp_assign, x_assign, y_assign) add_offense(node, message: message(x_assign, y_assign)) do |corrector| range = correction_range(tmp_assign, y_assign) corrector.replace(range, replacement(x_assign)) end end SIMPLE_ASSIGNMENT_TYPES.each { |asgn_type| alias_method :"on_#{asgn_type}", :on_asgn } private def allowed_assignment?(node) node.parent&.mlhs_type? || node.parent&.shorthand_asgn? end def swapping_values?(tmp_assign, x_assign, y_assign) simple_assignment?(tmp_assign) && simple_assignment?(x_assign) && simple_assignment?(y_assign) && lhs(x_assign) == rhs(tmp_assign) && lhs(y_assign) == rhs(x_assign) && rhs(y_assign) == lhs(tmp_assign) end def simple_assignment?(node) return false unless node.respond_to?(:type) SIMPLE_ASSIGNMENT_TYPES.include?(node.type) end def message(x_assign, y_assign) format( MSG, x_line: x_assign.first_line, y_line: y_assign.first_line, replacement: replacement(x_assign) ) end def replacement(x_assign) x = lhs(x_assign) y = rhs(x_assign) "#{x}, #{y} = #{y}, #{x}" end def lhs(node) if node.casgn_type? "#{'::' if node.absolute?}#{node.const_name}" else node.name.to_s end end def rhs(node) node.expression.source end def correction_range(tmp_assign, y_assign) range_by_whole_lines( range_between(tmp_assign.source_range.begin_pos, y_assign.source_range.end_pos) ) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_string_escape.rb
lib/rubocop/cop/style/redundant_string_escape.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for redundant escapes in string literals. # # @example # # bad - no need to escape # without following {/$/@ # "\#foo" # # # bad - no need to escape single quotes inside double quoted string # "\'foo\'" # # # bad - heredocs are also checked for unnecessary escapes # <<~STR # \#foo \"foo\" # STR # # # good # "#foo" # # # good # "\#{no_interpolation}" # # # good # "'foo'" # # # good # "foo\ # bar" # # # good # <<~STR # #foo "foo" # STR class RedundantStringEscape < Base include MatchRange extend AutoCorrector MSG = 'Redundant escape of %<char>s inside string literal.' def on_str(node) return if node.parent&.type?(:regexp, :xstr) || node.character_literal? str_contents_range = str_contents_range(node) each_match_range(str_contents_range, /(\\.)/) do |range| next if allowed_escape?(node, range.resize(3)) add_offense(range) do |corrector| corrector.remove_leading(range, 1) end end end private def message(range) format(MSG, char: range.source[-1]) end def str_contents_range(node) if heredoc?(node) node.loc.heredoc_body elsif node.str_type? node.source_range elsif begin_loc_present?(node) contents_range(node) end end def begin_loc_present?(node) # e.g. a __FILE__ literal has no begin loc so we can't query if it's nil node.loc.to_hash.key?(:begin) && !node.loc.begin.nil? end # rubocop:disable Metrics/CyclomaticComplexity def allowed_escape?(node, range) escaped = range.source[(1..-1)] # Inside a single-quoted string, escapes (except \\ and \') do not have special meaning, # and so are not redundant, as they are a literal backslash. return true if interpolation_not_enabled?(node) # Strictly speaking a few single-letter chars are currently unnecessary to "escape", e.g. # d, but enumerating them is rather difficult, and their behavior could change over time # with different versions of Ruby so that e.g. /\d/ != /d/ return true if /[\n\\[[:alnum:]]]/.match?(escaped[0]) return true if escaped[0] == ' ' && (percent_array_literal?(node) || node.heredoc?) return true if disabling_interpolation?(range) return true if delimiter?(node, escaped[0]) false end # rubocop:enable Metrics/CyclomaticComplexity def interpolation_not_enabled?(node) single_quoted?(node) || percent_w_literal?(node) || percent_q_literal?(node) || heredoc_with_disabled_interpolation?(node) end def single_quoted?(node) delimiter?(node, "'") end def percent_q_literal?(node) if literal_in_interpolated_or_multiline_string?(node) percent_q_literal?(node.parent) else node.source.start_with?('%q') end end def array_literal?(node, prefix) if literal_in_interpolated_or_multiline_string?(node) array_literal?(node.parent, prefix) else node.parent&.array_type? && node.parent.source.start_with?(prefix) end end def percent_w_literal?(node) array_literal?(node, '%w') end def percent_w_upper_literal?(node) array_literal?(node, '%W') end def percent_array_literal?(node) percent_w_literal?(node) || percent_w_upper_literal?(node) end def heredoc_with_disabled_interpolation?(node) if heredoc?(node) node.source.end_with?("'") elsif node.parent&.dstr_type? heredoc_with_disabled_interpolation?(node.parent) else false end end def heredoc?(node) node.type?(:str, :dstr) && node.heredoc? end def delimiter?(node, char) return false if heredoc?(node) if literal_in_interpolated_or_multiline_string?(node) || percent_array_literal?(node) return delimiter?(node.parent, char) end return true unless node.loc.begin delimiters = [node.loc.begin.source[-1], node.loc.end.source[0]] delimiters.include?(char) end def literal_in_interpolated_or_multiline_string?(node) node.str_type? && !begin_loc_present?(node) && node.parent&.dstr_type? end def disabling_interpolation?(range) # Allow \#{foo}, \#$foo, \#@foo, and \#@@foo # for escaping local, global, instance and class variable interpolations return true if range.source.match?(/\A\\#[{$@]/) # Also allow #\{foo}, #\$foo, #\@foo and #\@@foo return true if range.adjust(begin_pos: -2).source.match?(/\A[^\\]#\\[{$@]/) # For `\#\{foo} allow `\#` and warn `\{` return true if range.adjust(end_pos: 1).source == '\\#\\{' 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/trailing_body_on_method_definition.rb
lib/rubocop/cop/style/trailing_body_on_method_definition.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for trailing code after the method definition. # # NOTE: It always accepts endless method definitions that are basically on the same line. # # @example # # bad # def some_method; do_stuff # end # # def f(x); b = foo # b[c: x] # end # # # good # def some_method # do_stuff # end # # def f(x) # b = foo # b[c: x] # end # # def endless_method = do_stuff # class TrailingBodyOnMethodDefinition < Base include Alignment include TrailingBody extend AutoCorrector MSG = "Place the first line of a multi-line method definition's body on its own line." def on_def(node) return unless trailing_body?(node) return if node.endless? add_offense(first_part_of(node.body)) do |corrector| LineBreakCorrector.correct_trailing_body( configured_width: configured_indentation_width, corrector: corrector, node: node, processed_source: processed_source ) end end alias on_defs on_def end end 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_escape.rb
lib/rubocop/cop/style/redundant_regexp_escape.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for redundant escapes inside `Regexp` literals. # # @example # # bad # %r{foo\/bar} # # # good # %r{foo/bar} # # # good # /foo\/bar/ # # # good # %r/foo\/bar/ # # # good # %r!foo\!bar! # # # bad # /a\-b/ # # # good # /a-b/ # # # bad # /[\+\-]\d/ # # # good # /[+\-]\d/ class RedundantRegexpEscape < Base include RangeHelp extend AutoCorrector MSG_REDUNDANT_ESCAPE = 'Redundant escape inside regexp literal' ALLOWED_ALWAYS_ESCAPES = " \n[]^\\#".chars.freeze ALLOWED_WITHIN_CHAR_CLASS_METACHAR_ESCAPES = '-'.chars.freeze ALLOWED_OUTSIDE_CHAR_CLASS_METACHAR_ESCAPES = '.*+?{}()|$'.chars.freeze INTERPOLATION_SIGILS = %w[@ $].freeze def on_regexp(node) each_escape(node) do |char, index, within_character_class| next if char.valid_encoding? && allowed_escape?(node, char, index, within_character_class) location = escape_range_at_index(node, index) add_offense(location, message: MSG_REDUNDANT_ESCAPE) do |corrector| corrector.remove_leading(escape_range_at_index(node, index), 1) end end end private def allowed_escape?(node, char, index, within_character_class) # Strictly speaking a few single-letter metachars are currently # unnecessary to "escape", e.g. i, E, F, but enumerating them is # rather difficult, and their behavior could change over time with # different versions of Ruby so that e.g. /\i/ != /i/ return true if /[[:alnum:]]/.match?(char) return true if ALLOWED_ALWAYS_ESCAPES.include?(char) || delimiter?(node, char) return true if requires_escape_to_avoid_interpolation?(node.source[index], char) if within_character_class ALLOWED_WITHIN_CHAR_CLASS_METACHAR_ESCAPES.include?(char) && !char_class_begins_or_ends_with_escaped_hyphen?(node, index) else ALLOWED_OUTSIDE_CHAR_CLASS_METACHAR_ESCAPES.include?(char) end end def char_class_begins_or_ends_with_escaped_hyphen?(node, index) # The hyphen character is allowed to be escaped within a character class # but it's not necessary to escape hyphen if it's the first or last character # within the character class. This method checks if that's the case. # e.g. "[0-9\\-]" or "[\\-0-9]" would return true content = contents_range(node).source if content[index + 2] == ']' true elsif content[index - 1] == '[' index < 2 || content[index - 2] != '\\' else false end end def delimiter?(node, char) delimiters = [node.loc.begin.source[-1], node.loc.end.source[0]] delimiters.include?(char) end def requires_escape_to_avoid_interpolation?(char_before_escape, escaped_char) # Preserve escapes after '#' that would otherwise trigger interpolation: # '#@ivar', '#@@cvar', and '#$gvar'. char_before_escape == '#' && INTERPOLATION_SIGILS.include?(escaped_char) end def each_escape(node) node.parsed_tree&.traverse&.reduce(0) do |char_class_depth, (event, expr)| yield(expr.text[1], expr.ts, !char_class_depth.zero?) if expr.type == :escape if expr.type == :set char_class_depth + (event == :enter ? 1 : -1) else char_class_depth end end end def escape_range_at_index(node, index) regexp_begin = node.loc.begin.end_pos start = regexp_begin + index range_between(start, start + 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/hash_like_case.rb
lib/rubocop/cop/style/hash_like_case.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for places where `case-when` represents a simple 1:1 # mapping and can be replaced with a hash lookup. # # @example MinBranchesCount: 3 (default) # # bad # case country # when 'europe' # 'http://eu.example.com' # when 'america' # 'http://us.example.com' # when 'australia' # 'http://au.example.com' # end # # # good # SITES = { # 'europe' => 'http://eu.example.com', # 'america' => 'http://us.example.com', # 'australia' => 'http://au.example.com' # } # SITES[country] # # @example MinBranchesCount: 4 # # good # case country # when 'europe' # 'http://eu.example.com' # when 'america' # 'http://us.example.com' # when 'australia' # 'http://au.example.com' # end # class HashLikeCase < Base include MinBranchesCount MSG = 'Consider replacing `case-when` with a hash lookup.' # @!method hash_like_case?(node) def_node_matcher :hash_like_case?, <<~PATTERN (case _ (when ${str_type? sym_type?} $[!nil? recursive_basic_literal?])+ nil?) PATTERN def on_case(node) return unless min_branches_count?(node) hash_like_case?(node) do |condition_nodes, body_nodes| if nodes_of_same_type?(condition_nodes) && nodes_of_same_type?(body_nodes) add_offense(node) end end end private def nodes_of_same_type?(nodes) nodes.all? { |node| node.type == nodes.first.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/object_then.rb
lib/rubocop/cop/style/object_then.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Enforces the use of consistent method names # `Object#yield_self` or `Object#then`. # # @example EnforcedStyle: then (default) # # # bad # obj.yield_self { |x| x.do_something } # # # good # obj.then { |x| x.do_something } # # @example EnforcedStyle: yield_self # # # bad # obj.then { |x| x.do_something } # # # good # obj.yield_self { |x| x.do_something } # class ObjectThen < Base include ConfigurableEnforcedStyle extend AutoCorrector extend TargetRubyVersion minimum_target_ruby_version 2.6 MSG = 'Prefer `%<prefer>s` over `%<current>s`.' RESTRICT_ON_SEND = %i[then yield_self].freeze def on_block(node) return unless RESTRICT_ON_SEND.include?(node.method_name) check_method_node(node.send_node) end alias on_numblock on_block alias on_itblock on_block def on_send(node) return unless node.arguments.one? && node.first_argument.block_pass_type? check_method_node(node) end alias on_csend on_send private def check_method_node(node) if preferred_method?(node) correct_style_detected else opposite_style_detected message = message(node) add_offense(node.loc.selector, message: message) do |corrector| prefer = style == :then && node.receiver.nil? ? 'self.then' : style corrector.replace(node.loc.selector, prefer) end end end def preferred_method?(node) node.method?(style) end def message(node) format(MSG, prefer: style.to_s, current: node.method_name) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/access_modifier_declarations.rb
lib/rubocop/cop/style/access_modifier_declarations.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Access modifiers should be declared to apply to a group of methods # or inline before each method, depending on configuration. # EnforcedStyle config covers only method definitions. # Applications of visibility methods to symbols can be controlled # using AllowModifiersOnSymbols config. # Also, the visibility of `attr*` methods can be controlled using # AllowModifiersOnAttrs config. # # In Ruby 3.0, `attr*` methods now return an array of defined method names # as symbols. So we can write the modifier and `attr*` in inline style. # AllowModifiersOnAttrs config allows `attr*` methods to be written in # inline style without modifying applications that have been maintained # for a long time in group style. Furthermore, developers who are not very # familiar with Ruby may know that the modifier applies to `def`, but they # may not know that it also applies to `attr*` methods. It would be easier # to understand if we could write `attr*` methods in inline style. # # @safety # Autocorrection is not safe, because the visibility of dynamically # defined methods can vary depending on the state determined by # the group access modifier. # # @example EnforcedStyle: group (default) # # bad # class Foo # # private def bar; end # private def baz; end # # end # # # good # class Foo # # private # # def bar; end # def baz; end # # end # # @example EnforcedStyle: inline # # bad # class Foo # # private # # def bar; end # def baz; end # # end # # # good # class Foo # # private def bar; end # private def baz; end # # end # # @example AllowModifiersOnSymbols: true (default) # # good # class Foo # # private :bar, :baz # private *%i[qux quux] # private *METHOD_NAMES # private *private_methods # # end # # @example AllowModifiersOnSymbols: false # # bad # class Foo # # private :bar, :baz # private *%i[qux quux] # private *METHOD_NAMES # private *private_methods # # end # # @example AllowModifiersOnAttrs: true (default) # # good # class Foo # # public attr_reader :bar # protected attr_writer :baz # private attr_accessor :qux # private attr :quux # # def public_method; end # # private # # def private_method; end # # end # # @example AllowModifiersOnAttrs: false # # bad # class Foo # # public attr_reader :bar # protected attr_writer :baz # private attr_accessor :qux # private attr :quux # # end # # @example AllowModifiersOnAliasMethod: true (default) # # good # class Foo # # public alias_method :bar, :foo # protected alias_method :baz, :foo # private alias_method :qux, :foo # # end # # @example AllowModifiersOnAliasMethod: false # # bad # class Foo # # public alias_method :bar, :foo # protected alias_method :baz, :foo # private alias_method :qux, :foo # # end class AccessModifierDeclarations < Base extend AutoCorrector include ConfigurableEnforcedStyle include RangeHelp GROUP_STYLE_MESSAGE = [ '`%<access_modifier>s` should not be', 'inlined in method definitions.' ].join(' ') INLINE_STYLE_MESSAGE = [ '`%<access_modifier>s` should be', 'inlined in method definitions.' ].join(' ') RESTRICT_ON_SEND = %i[private protected public module_function].freeze # @!method access_modifier_with_symbol?(node) def_node_matcher :access_modifier_with_symbol?, <<~PATTERN (send nil? {:private :protected :public :module_function} {(sym _)+ (splat {#percent_symbol_array? const send})} ) PATTERN # @!method access_modifier_with_attr?(node) def_node_matcher :access_modifier_with_attr?, <<~PATTERN (send nil? {:private :protected :public :module_function} (send nil? {:attr :attr_reader :attr_writer :attr_accessor} _+)) PATTERN # @!method access_modifier_with_alias_method?, <<~PATTERN def_node_matcher :access_modifier_with_alias_method?, <<~PATTERN (send nil? {:private :protected :public :module_function} (send nil? :alias_method _ _)) PATTERN def on_send(node) return if allowed?(node) if offense?(node) add_offense(node.loc.selector) do |corrector| autocorrect(corrector, node) end opposite_style_detected else correct_style_detected end end private def allowed?(node) !node.access_modifier? || node.parent&.type?(:pair, :any_block) || allow_modifiers_on_symbols?(node) || allow_modifiers_on_attrs?(node) || allow_modifiers_on_alias_method?(node) end def autocorrect(corrector, node) case style when :group autocorrect_group_style(corrector, node) when :inline autocorrect_inline_style(corrector, node) end end def autocorrect_group_style(corrector, node) def_nodes = find_corresponding_def_nodes(node) return unless def_nodes.any? replace_defs(corrector, node, def_nodes) end def autocorrect_inline_style(corrector, node) if node.parent&.begin_type? remove_modifier_node_within_begin(corrector, node, node.parent) else remove_nodes(corrector, node) end select_grouped_def_nodes(node).each do |grouped_def_node| insert_inline_modifier(corrector, grouped_def_node, node.method_name) end end def percent_symbol_array?(node) node.array_type? && node.percent_literal?(:symbol) end def allow_modifiers_on_symbols?(node) cop_config['AllowModifiersOnSymbols'] && access_modifier_with_symbol?(node) end def allow_modifiers_on_attrs?(node) cop_config['AllowModifiersOnAttrs'] && access_modifier_with_attr?(node) end def allow_modifiers_on_alias_method?(node) cop_config['AllowModifiersOnAliasMethod'] && access_modifier_with_alias_method?(node) end def offense?(node) if group_style? return false if node.parent ? node.parent.if_type? : access_modifier_with_symbol?(node) access_modifier_is_inlined?(node) && !right_siblings_same_inline_method?(node) else access_modifier_is_not_inlined?(node) && select_grouped_def_nodes(node).any? end end def correctable_group_offense?(node) return false unless group_style? return false if allowed?(node) access_modifier_is_inlined?(node) && find_corresponding_def_nodes(node).any? end def group_style? style == :group end def inline_style? style == :inline end def access_modifier_is_inlined?(node) node.arguments.any? end def access_modifier_is_not_inlined?(node) !access_modifier_is_inlined?(node) end def right_siblings_same_inline_method?(node) node.right_siblings.any? do |sibling| sibling.send_type? && correctable_group_offense?(sibling) && sibling.method?(node.method_name) && !sibling.arguments.empty? && find_corresponding_def_nodes(sibling).any? end end def message(range) access_modifier = range.source if group_style? format(GROUP_STYLE_MESSAGE, access_modifier: access_modifier) elsif inline_style? format(INLINE_STYLE_MESSAGE, access_modifier: access_modifier) end end def find_corresponding_def_nodes(node) if access_modifier_with_symbol?(node) method_names = node.arguments.filter_map do |argument| next unless argument.sym_type? argument.respond_to?(:value) && argument.value end def_nodes = node.parent.each_child_node(:def).select do |child| method_names.include?(child.method_name) end # If there isn't a `def` node for each symbol, we will skip autocorrection. def_nodes.size == method_names.size ? def_nodes : [] else [node.first_argument] end end def find_argument_less_modifier_node(node) return unless (parent = node.parent) parent.each_child_node(:send).find do |child| child.method?(node.method_name) && child.arguments.empty? end end def select_grouped_def_nodes(node) node.right_siblings.take_while do |sibling| !(sibling.send_type? && sibling.bare_access_modifier_declaration?) end.select(&:def_type?) end def replace_defs(corrector, node, def_nodes) source = def_source(node, def_nodes) argument_less_modifier_node = find_argument_less_modifier_node(node) if argument_less_modifier_node corrector.insert_after(argument_less_modifier_node, "\n\n#{source}") elsif (ancestor = node.each_ancestor(:class, :module, :sclass).first) corrector.insert_before(ancestor.loc.end, "#{node.method_name}\n\n#{source}\n") else corrector.replace(node, "#{node.method_name}\n\n#{source}") return end remove_nodes(corrector, *def_nodes, node) end def insert_inline_modifier(corrector, node, modifier_name) corrector.insert_before(node, "#{modifier_name} ") end def remove_nodes(corrector, *nodes) nodes.each do |node| corrector.remove(range_with_comments_and_lines(node)) end end def remove_modifier_node_within_begin(corrector, modifier_node, begin_node) def_node = begin_node.children[begin_node.children.index(modifier_node) + 1] range = modifier_node.source_range.begin.join(def_node.source_range.begin) corrector.remove(range) end def def_source(node, def_nodes) [ *processed_source.ast_with_comments[node].map(&:text), *def_nodes.map(&:source) ].join("\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/infinite_loop.rb
lib/rubocop/cop/style/infinite_loop.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Use `Kernel#loop` for infinite loops. # # @safety # This cop is unsafe as the rule should not necessarily apply if the loop # body might raise a `StopIteration` exception; contrary to other infinite # loops, `Kernel#loop` silently rescues that and returns `nil`. # # @example # # bad # while true # work # end # # # good # loop do # work # end class InfiniteLoop < Base include Alignment extend AutoCorrector LEADING_SPACE = /\A(\s*)/.freeze MSG = 'Use `Kernel#loop` for infinite loops.' def self.joining_forces VariableForce end def after_leaving_scope(scope, _variable_table) @variables ||= [] @variables.concat(scope.variables.values) end def on_while(node) while_or_until(node) if node.condition.truthy_literal? end def on_until(node) while_or_until(node) if node.condition.falsey_literal? end alias on_while_post on_while alias on_until_post on_until private def while_or_until(node) range = node.source_range # Not every `while true` and `until false` can be turned into a # `loop do` without further modification. The reason is that a # variable that's introduced inside a while/until loop is in scope # outside of that loop too, but a variable that's assigned for the # first time inside a block cannot be accessed after the block. In # those more complicated cases we don't report an offense. return if @variables.any? do |var| assigned_inside_loop?(var, range) && !assigned_before_loop?(var, range) && referenced_after_loop?(var, range) end add_offense(node.loc.keyword) { |corrector| autocorrect(corrector, node) } end def autocorrect(corrector, node) if node.post_condition_loop? replace_begin_end_with_modifier(corrector, node) elsif node.modifier_form? replace_source(corrector, node.source_range, modifier_replacement(node)) else replace_source(corrector, non_modifier_range(node), 'loop do') end end def assigned_inside_loop?(var, range) var.assignments.any? { |a| range.contains?(a.node.source_range) } end def assigned_before_loop?(var, range) b = range.begin_pos var.assignments.any? { |a| a.node.source_range.end_pos < b } end def referenced_after_loop?(var, range) e = range.end_pos var.references.any? { |r| r.node.source_range.begin_pos > e } end def replace_begin_end_with_modifier(corrector, node) corrector.replace(node.body.loc.begin, 'loop do') corrector.remove(node.body.loc.end.end.join(node.source_range.end)) end def replace_source(corrector, range, replacement) corrector.replace(range, replacement) end def modifier_replacement(node) body = node.body if node.single_line? "loop { #{body.source} }" else indentation = body.source_range.source_line[LEADING_SPACE] ['loop do', body.source.gsub(/^/, indentation(node)), 'end'].join("\n#{indentation}") end end def non_modifier_range(node) start_range = node.loc.keyword.begin end_range = if node.do? node.loc.begin.end else node.condition.source_range.end end start_range.join(end_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/constant_visibility.rb
lib/rubocop/cop/style/constant_visibility.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks that constants defined in classes and modules have # an explicit visibility declaration. By default, Ruby makes all class- # and module constants public, which litters the public API of the # class or module. Explicitly declaring a visibility makes intent more # clear, and prevents outside actors from touching private state. # # @example # # # bad # class Foo # BAR = 42 # BAZ = 43 # end # # # good # class Foo # BAR = 42 # private_constant :BAR # # BAZ = 43 # public_constant :BAZ # end # # @example IgnoreModules: false (default) # # bad # class Foo # MyClass = Struct.new # end # # # good # class Foo # MyClass = Struct.new # public_constant :MyClass # end # # @example IgnoreModules: true # # good # class Foo # MyClass = Struct.new # end # class ConstantVisibility < Base MSG = 'Explicitly make `%<constant_name>s` public or private using ' \ 'either `#public_constant` or `#private_constant`.' # @!method visibility_declaration_for(node) def_node_matcher :visibility_declaration_for, <<~PATTERN (send nil? {:public_constant :private_constant} $...) PATTERN def on_casgn(node) return unless class_or_module_scope?(node) return if visibility_declaration?(node) return if ignore_modules? && module?(node) add_offense(node, message: format(MSG, constant_name: node.name)) end private def ignore_modules? cop_config.fetch('IgnoreModules', false) end def module?(node) node.expression.class_constructor? end def class_or_module_scope?(node) return false unless node.parent case node.parent.type when :begin class_or_module_scope?(node.parent) when :class, :module true end end # rubocop:disable Metrics/AbcSize def visibility_declaration?(node) node.parent.each_child_node(:send).any? do |child| next false unless (arguments = visibility_declaration_for(child)) arguments = arguments.first.children.first.to_a if arguments.first&.splat_type? constant_values = arguments.map do |argument| argument.value.to_sym if argument.respond_to?(:value) end constant_values.include?(node.name) 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/one_line_conditional.rb
lib/rubocop/cop/style/one_line_conditional.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for uses of if/then/else/end constructs on a single line. # `AlwaysCorrectToMultiline` config option can be set to true to autocorrect all offenses to # multi-line constructs. When `AlwaysCorrectToMultiline` is false (default case) the # autocorrect will first try converting them to ternary operators. # # @example # # bad # if foo then bar else baz end # # # bad # unless foo then baz else bar end # # # good # foo ? bar : baz # # # good # bar if foo # # # good # if foo then bar end # # # good # if foo # bar # else # baz # end # # @example AlwaysCorrectToMultiline: false (default) # # bad # if cond then run else dont end # # # good # cond ? run : dont # # @example AlwaysCorrectToMultiline: true # # bad # if cond then run else dont end # # # good # if cond # run # else # dont # end # class OneLineConditional < Base include Alignment include ConfigurableEnforcedStyle include OnNormalIfUnless extend AutoCorrector MSG_SUFFIX = 'over single-line `%<keyword>s/then/else/end` constructs.' MSG_TERNARY = "Favor the ternary operator (`?:`) #{MSG_SUFFIX}" MSG_MULTILINE = "Favor multi-line `%<keyword>s` #{MSG_SUFFIX}" def on_normal_if_unless(node) return unless node.single_line? return unless node.else_branch return if node.elsif? || node.if_branch&.begin_type? multiline = multiline?(node) add_offense(node, message: message(node, multiline)) do |corrector| next if part_of_ignored_node?(node) autocorrect(corrector, node, multiline) ignore_node(node) end end private def multiline?(node) always_multiline? || cannot_replace_to_ternary?(node) end def message(node, multiline) template = multiline ? MSG_MULTILINE : MSG_TERNARY format(template, keyword: node.keyword) end def autocorrect(corrector, node, multiline) if multiline IfThenCorrector.new(node, indentation: configured_indentation_width).call(corrector) else corrector.replace(node, ternary_correction(node)) end end def ternary_correction(node) replaced_node = ternary_replacement(node) return replaced_node unless node.parent return "(#{replaced_node})" if node.parent.operator_keyword? return "(#{replaced_node})" if node.parent.send_type? && node.parent.operator_method? replaced_node end def always_multiline? cop_config['AlwaysCorrectToMultiline'] end def cannot_replace_to_ternary?(node) return true if node.elsif_conditional? node.else_branch.begin_type? && node.else_branch.children.compact.count >= 2 end def ternary_replacement(node) condition, if_branch, else_branch = *node # rubocop:disable InternalAffairs/NodeDestructuring "#{expr_replacement(condition)} ? " \ "#{expr_replacement(if_branch)} : " \ "#{expr_replacement(else_branch)}" end def expr_replacement(node) return 'nil' if node.nil? requires_parentheses?(node) ? "(#{node.source})" : node.source end def requires_parentheses?(node) return true if %i[and or if].include?(node.type) return true if node.assignment? return true if method_call_with_changed_precedence?(node) keyword_with_changed_precedence?(node) end def method_call_with_changed_precedence?(node) return false unless node.send_type? && node.arguments? return false if node.parenthesized_call? !node.operator_method? end def keyword_with_changed_precedence?(node) return false unless node.keyword? return true if node.respond_to?(:prefix_not?) && node.prefix_not? node.respond_to?(:arguments?) && node.arguments? && !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/word_array.rb
lib/rubocop/cop/style/word_array.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for array literals made up of word-like # strings, that are not using the %w() syntax. # # Alternatively, it can check for uses of the %w() syntax, in projects # which do not want to include that syntax. # # NOTE: When using the `percent` style, %w() arrays containing a space # will be registered as offenses. # # Configuration option: MinSize # If set, arrays with fewer elements than this value will not trigger the # cop. For example, a `MinSize` of `3` will not enforce a style on an # array of 2 or fewer elements. # # @example EnforcedStyle: percent (default) # # good # %w[foo bar baz] # # # bad # ['foo', 'bar', 'baz'] # # # bad (contains spaces) # %w[foo\ bar baz\ quux] # # # bad # [ # ['one', 'One'], # ['two', 'Two'] # ] # # # good # [ # %w[one One], # %w[two Two] # ] # # # good (2d array containing spaces) # [ # ['one', 'One'], # ['two', 'Two'], # ['forty two', 'Forty Two'] # ] # # @example EnforcedStyle: brackets # # good # ['foo', 'bar', 'baz'] # # # bad # %w[foo bar baz] # # # good (contains spaces) # ['foo bar', 'baz quux'] # # # good # [ # ['one', 'One'], # ['two', 'Two'] # ] # # # bad # [ # %w[one One], # %w[two Two] # ] # class WordArray < Base include ArrayMinSize include ArraySyntax include ConfigurableEnforcedStyle include PercentArray extend AutoCorrector PERCENT_MSG = 'Use `%w` or `%W` for an array of words.' ARRAY_MSG = 'Use %<prefer>s for an array of words.' class << self attr_accessor :largest_brackets end def on_new_investigation super # Prevent O(n2) checks (checking the entire matrix once for each child array) by caching @matrix_of_complex_content_cache = Hash.new do |cache, node| cache[node] = matrix_of_complex_content?(node) end end def on_array(node) if bracketed_array_of?(:str, node) return if complex_content?(node.values) return if within_matrix_of_complex_content?(node) check_bracketed_array(node, 'w') elsif node.percent_literal?(:string) check_percent_array(node) end end private def within_matrix_of_complex_content?(node) return false unless (parent = node.parent) parent.array_type? && @matrix_of_complex_content_cache[parent] end def matrix_of_complex_content?(array) array.values.all?(&:array_type?) && array.values.any? { |subarray| complex_content?(subarray.values) } end def complex_content?(strings, complex_regex: word_regex) strings.any? do |s| next unless s.str_content string = s.str_content.dup.force_encoding(::Encoding::UTF_8) !string.valid_encoding? || (complex_regex && !complex_regex.match?(string)) || string.include?(' ') end end def invalid_percent_array_contents?(node) # Disallow %w() arrays that contain invalid encoding or spaces complex_content?(node.values, complex_regex: false) end def word_regex Regexp.new(cop_config['WordRegex']) end def build_bracketed_array(node) return '[]' if node.children.empty? words = node.children.map do |word| if word.dstr_type? string_literal = to_string_literal(word.source) trim_string_interpolation_escape_character(string_literal) else to_string_literal(word.children[0]) end end build_bracketed_array_with_appropriate_whitespace(elements: words, node: node) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/single_line_methods.rb
lib/rubocop/cop/style/single_line_methods.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for single-line method definitions that contain a body. # It will accept single-line methods with no body. # # Endless methods added in Ruby 3.0 are also accepted by this cop. # # If `Style/EndlessMethod` is enabled with `EnforcedStyle: allow_single_line`, `allow_always`, # `require_single_line`, or `require_always`, single-line methods will be autocorrected # to endless methods if there is only one statement in the body. # # @example # # bad # def some_method; body end # def link_to(url); {:name => url}; end # def @table.columns; super; end # # # good # def self.resource_class=(klass); end # def @table.columns; end # def some_method() = body # # @example AllowIfMethodIsEmpty: true (default) # # good # def no_op; end # # @example AllowIfMethodIsEmpty: false # # bad # def no_op; end # class SingleLineMethods < Base include Alignment extend AutoCorrector MSG = 'Avoid single-line method definitions.' NOT_SUPPORTED_ENDLESS_METHOD_BODY_TYPES = %i[return break next].freeze def on_def(node) return unless node.single_line? return if node.endless? return if allow_empty? && !node.body add_offense(node) { |corrector| autocorrect(corrector, node) } end alias on_defs on_def private def autocorrect(corrector, node) if correct_to_endless?(node.body) correct_to_endless(corrector, node) else correct_to_multiline(corrector, node) end end def allow_empty? cop_config['AllowIfMethodIsEmpty'] end def correct_to_endless?(body_node) return false if target_ruby_version < 3.0 return false if disallow_endless_method_style? return false unless body_node return false if body_node.basic_conditional? || body_node.parent.assignment_method? || NOT_SUPPORTED_ENDLESS_METHOD_BODY_TYPES.include?(body_node.type) !body_node.type?(:begin, :kwbegin) end def correct_to_multiline(corrector, node) if (body = node.body) && body.begin_type? && body.parenthesized_call? break_line_before(corrector, node, body) else each_part(body) do |part| break_line_before(corrector, node, part) end end break_line_before(corrector, node, node.loc.end, indent_steps: 0) move_comment(node, corrector) end def correct_to_endless(corrector, node) receiver = "#{node.receiver.source}." if node.receiver arguments = node.arguments.any? ? node.arguments.source : '()' body_source = method_body_source(node.body) replacement = "def #{receiver}#{node.method_name}#{arguments} = #{body_source}" corrector.replace(node, replacement) end def break_line_before(corrector, node, range, indent_steps: 1) LineBreakCorrector.break_line_before( range: range, node: node, corrector: corrector, configured_width: configured_indentation_width, indent_steps: indent_steps ) end def each_part(body) return unless body if body.begin_type? body.each_child_node { |part| yield part.source_range } else yield body.source_range end end def move_comment(node, corrector) LineBreakCorrector.move_comment( eol_comment: processed_source.comment_at_line(node.source_range.line), node: node, corrector: corrector ) end def method_body_source(method_body) if require_parentheses?(method_body) arguments_source = method_body.arguments.map(&:source).join(', ') body_source = "#{method_body.method_name}(#{arguments_source})" method_body.receiver ? "#{method_body.receiver.source}.#{body_source}" : body_source else method_body.source end end def require_parentheses?(method_body) return false unless method_body.send_type? return false if method_body.arithmetic_operation? !method_body.arguments.empty? && !method_body.comparison_method? end def disallow_endless_method_style? return true unless config.cop_enabled?('Style/EndlessMethod') config.for_cop('Style/EndlessMethod')['EnforcedStyle'] == 'disallow' end end end 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_each.rb
lib/rubocop/cop/style/redundant_each.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for redundant `each`. # # @safety # This cop is unsafe, as it can produce false positives if the receiver # is not an `Enumerator`. # # @example # # # bad # array.each.each { |v| do_something(v) } # # # good # array.each { |v| do_something(v) } # # # bad # array.each.each_with_index { |v, i| do_something(v, i) } # # # good # array.each.with_index { |v, i| do_something(v, i) } # array.each_with_index { |v, i| do_something(v, i) } # # # bad # array.each.each_with_object { |v, o| do_something(v, o) } # # # good # array.each.with_object { |v, o| do_something(v, o) } # array.each_with_object { |v, o| do_something(v, o) } # class RedundantEach < Base extend AutoCorrector MSG = 'Remove redundant `each`.' MSG_WITH_INDEX = 'Use `with_index` to remove redundant `each`.' MSG_WITH_OBJECT = 'Use `with_object` to remove redundant `each`.' RESTRICT_ON_SEND = %i[each each_with_index each_with_object].freeze def on_send(node) return unless (redundant_node = redundant_each_method(node)) range = range(node) add_offense(range, message: message(node)) do |corrector| case node.method_name when :each remove_redundant_each(corrector, range, redundant_node) when :each_with_index corrector.replace(node.loc.selector, 'with_index') when :each_with_object corrector.replace(node.loc.selector, 'with_object') end end end alias on_csend on_send private # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity def redundant_each_method(node) return if node.last_argument&.block_pass_type? if node.method?(:each) && !node.parent&.block_type? ancestor_node = node.each_ancestor(:call).detect do |ancestor| ancestor.receiver == node && (RESTRICT_ON_SEND.include?(ancestor.method_name) || ancestor.method?(:reverse_each)) end return ancestor_node if ancestor_node end return unless (prev_method = node.children.first) return if !prev_method.send_type? || prev_method.parent.block_type? || prev_method.last_argument&.block_pass_type? detected = prev_method.method_name.to_s.start_with?('each_') unless node.method?(:each) prev_method if detected || prev_method.method?(:reverse_each) end # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity def range(node) return node.selector unless node.method?(:each) if node.parent&.call_type? node.selector.join(node.parent.loc.dot) else node.loc.dot.join(node.selector) end end def message(node) case node.method_name when :each MSG when :each_with_index MSG_WITH_INDEX when :each_with_object MSG_WITH_OBJECT end end def remove_redundant_each(corrector, range, redundant_node) corrector.remove(range) if redundant_node.method?(:each_with_index) corrector.replace(redundant_node.loc.selector, 'each.with_index') elsif redundant_node.method?(:each_with_object) corrector.replace(redundant_node.loc.selector, 'each.with_object') 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/parentheses_around_condition.rb
lib/rubocop/cop/style/parentheses_around_condition.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for the presence of superfluous parentheses around the # condition of if/unless/while/until. # # `AllowSafeAssignment` option for safe assignment. # By safe assignment we mean putting parentheses around # an assignment to indicate "I know I'm using an assignment # as a condition. It's not a mistake." # # @example # # bad # x += 1 while (x < 10) # foo unless (bar || baz) # # if (x > 10) # elsif (x < 3) # end # # # good # x += 1 while x < 10 # foo unless bar || baz # # if x > 10 # elsif x < 3 # end # # @example AllowSafeAssignment: true (default) # # good # foo unless (bar = baz) # # @example AllowSafeAssignment: false # # bad # foo unless (bar = baz) # # @example AllowInMultilineConditions: false (default) # # bad # if (x > 10 && # y > 10) # end # # # good # if x > 10 && # y > 10 # end # # @example AllowInMultilineConditions: true # # good # if (x > 10 && # y > 10) # end # class ParenthesesAroundCondition < Base include SafeAssignment include Parentheses include RangeHelp extend AutoCorrector def on_if(node) return if node.ternary? process_control_op(node) end def on_while(node) process_control_op(node) end alias on_until on_while private # @!method control_op_condition(node) def_node_matcher :control_op_condition, <<~PATTERN (begin $_ $...) PATTERN def process_control_op(node) cond = node.condition control_op_condition(cond) do |first_child, rest_children| return if require_parentheses?(node, first_child) return if semicolon_separated_expressions?(first_child, rest_children) return if modifier_op?(first_child) return if parens_allowed?(cond) message = message(cond) add_offense(cond, message: message) do |corrector| ParenthesesCorrector.correct(corrector, cond) end end end def require_parentheses?(node, condition_body) return false unless node.type?(:while, :until) return false unless condition_body.any_block_type? condition_body.send_node.block_literal? && condition_body.keywords? end def semicolon_separated_expressions?(first_exp, rest_exps) return false unless (second_exp = rest_exps.first) range = range_between(first_exp.source_range.end_pos, second_exp.source_range.begin_pos) range.source.include?(';') end def modifier_op?(node) return false if node.if_type? && node.ternary? return true if node.rescue_type? node.basic_conditional? && node.modifier_form? end def message(node) kw = node.parent.keyword article = kw == 'while' ? 'a' : 'an' "Don't use parentheses around the condition of #{article} `#{kw}`." end def parens_allowed?(node) parens_required?(node) || (safe_assignment?(node) && safe_assignment_allowed?) || (node.multiline? && allow_multiline_conditions?) end def allow_multiline_conditions? cop_config['AllowInMultilineConditions'] end end end 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/date_time.rb
lib/rubocop/cop/style/date_time.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for consistent usage of the `DateTime` class over the # `Time` class. This cop is disabled by default since these classes, # although highly overlapping, have particularities that make them not # replaceable in certain situations when dealing with multiple timezones # and/or DST. # # @safety # Autocorrection is not safe, because `DateTime` and `Time` do not have # exactly the same behavior, although in most cases the autocorrection # will be fine. # # @example # # # bad - uses `DateTime` for current time # DateTime.now # # # good - uses `Time` for current time # Time.now # # # bad - uses `DateTime` for modern date # DateTime.iso8601('2016-06-29') # # # good - uses `Time` for modern date # Time.iso8601('2016-06-29') # # # good - uses `DateTime` with start argument for historical date # DateTime.iso8601('1751-04-23', Date::ENGLAND) # # @example AllowCoercion: false (default) # # # bad - coerces to `DateTime` # something.to_datetime # # # good - coerces to `Time` # something.to_time # # @example AllowCoercion: true # # # good # something.to_datetime # # # good # something.to_time class DateTime < Base extend AutoCorrector CLASS_MSG = 'Prefer `Time` over `DateTime`.' COERCION_MSG = 'Do not use `#to_datetime`.' # @!method date_time?(node) def_node_matcher :date_time?, <<~PATTERN (call (const {nil? (cbase)} :DateTime) ...) PATTERN # @!method historic_date?(node) def_node_matcher :historic_date?, <<~PATTERN (send _ _ _ (const (const {nil? (cbase)} :Date) _)) PATTERN # @!method to_datetime?(node) def_node_matcher :to_datetime?, <<~PATTERN (call _ :to_datetime) PATTERN def on_send(node) return unless date_time?(node) || (to_datetime?(node) && disallow_coercion?) return if historic_date?(node) message = to_datetime?(node) ? COERCION_MSG : CLASS_MSG add_offense(node, message: message) { |corrector| autocorrect(corrector, node) } end alias on_csend on_send private def disallow_coercion? !cop_config['AllowCoercion'] end def autocorrect(corrector, node) return if to_datetime?(node) corrector.replace(node.receiver.loc.name, 'Time') end end end 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/lambda_call.rb
lib/rubocop/cop/style/lambda_call.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for use of the lambda.(args) syntax. # # @example EnforcedStyle: call (default) # # bad # lambda.(x, y) # # # good # lambda.call(x, y) # # @example EnforcedStyle: braces # # bad # lambda.call(x, y) # # # good # lambda.(x, y) class LambdaCall < Base include ConfigurableEnforcedStyle extend AutoCorrector MSG = 'Prefer the use of `%<prefer>s` over `%<current>s`.' RESTRICT_ON_SEND = %i[call].freeze def on_send(node) return unless node.receiver if offense?(node) prefer = prefer(node) current = node.source add_offense(node, message: format(MSG, prefer: prefer, current: current)) do |corrector| next if part_of_ignored_node?(node) opposite_style_detected corrector.replace(node, prefer) ignore_node(node) end else correct_style_detected end end alias on_csend on_send private def offense?(node) (explicit_style? && node.implicit_call?) || (implicit_style? && !node.implicit_call?) end def prefer(node) receiver = node.receiver.source dot = node.loc.dot.source call_arguments = if node.arguments.empty? '' else arguments = node.arguments.map(&:source).join(', ') "(#{arguments})" end method = explicit_style? ? "call#{call_arguments}" : "(#{arguments})" "#{receiver}#{dot}#{method}" end def implicit_style? style == :braces end def explicit_style? style == :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/case_equality.rb
lib/rubocop/cop/style/case_equality.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for uses of the case equality operator (`===`). # # If `AllowOnConstant` option is enabled, the cop will ignore violations when the receiver of # the case equality operator is a constant. # # If `AllowOnSelfClass` option is enabled, the cop will ignore violations when the receiver of # the case equality operator is `self.class`. Note intermediate variables are not accepted. # # NOTE: Regexp case equality (`/regexp/ === var`) is allowed because changing it to # `/regexp/.match?(var)` needs to take into account `Regexp.last_match?`, `$~`, `$1`, etc. # This potentially incompatible transformation is handled by `Performance/RegexpMatch` cop. # # @example # # bad # (1..100) === 7 # # # good # (1..100).include?(7) # # @example AllowOnConstant: false (default) # # bad # Array === something # # # good # something.is_a?(Array) # # @example AllowOnConstant: true # # good # Array === something # something.is_a?(Array) # # @example AllowOnSelfClass: false (default) # # bad # self.class === something # # @example AllowOnSelfClass: true # # good # self.class === something # class CaseEquality < Base extend AutoCorrector MSG = 'Avoid the use of the case equality operator `===`.' RESTRICT_ON_SEND = %i[===].freeze # @!method case_equality?(node) def_node_matcher :case_equality?, '(send $#offending_receiver? :=== $_)' # @!method self_class?(node) def_node_matcher :self_class?, '(send (self) :class)' def on_send(node) case_equality?(node) do |lhs, rhs| return if lhs.regexp_type? || (lhs.const_type? && !lhs.module_name?) add_offense(node.loc.selector) do |corrector| replacement = replacement(lhs, rhs) corrector.replace(node, replacement) if replacement end end end private def offending_receiver?(node) return false if node&.const_type? && cop_config.fetch('AllowOnConstant', false) return false if self_class?(node) && cop_config.fetch('AllowOnSelfClass', false) true end def replacement(lhs, rhs) case lhs.type when :begin begin_replacement(lhs, rhs) when :const const_replacement(lhs, rhs) when :send send_replacement(lhs, rhs) end end def begin_replacement(lhs, rhs) return unless lhs.children.first&.range_type? "#{lhs.source}.include?(#{rhs.source})" end def const_replacement(lhs, rhs) "#{rhs.source}.is_a?(#{lhs.source})" end def send_replacement(lhs, rhs) return unless self_class?(lhs) "#{rhs.source}.is_a?(#{lhs.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/comparable_between.rb
lib/rubocop/cop/style/comparable_between.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for logical comparison which can be replaced with `Comparable#between?`. # # NOTE: `Comparable#between?` is on average slightly slower than logical comparison, # although the difference generally isn't observable. If you require maximum # performance, consider using logical comparison. # # @safety # This cop is unsafe because the receiver may not respond to `between?`. # # @example # # # bad # x >= min && x <= max # # # bad # x <= max && x >= min # # # good # x.between?(min, max) # class ComparableBetween < Base extend AutoCorrector MSG = 'Prefer `%<prefer>s` over logical comparison.' # @!method logical_comparison_between_by_min_first?(node) def_node_matcher :logical_comparison_between_by_min_first?, <<~PATTERN (and (send {$_value :>= $_min | $_min :<= $_value}) (send {$_value :<= $_max | $_max :>= $_value})) PATTERN # @!method logical_comparison_between_by_max_first?(node) def_node_matcher :logical_comparison_between_by_max_first?, <<~PATTERN (and (send {$_value :<= $_max | $_max :>= $_value}) (send {$_value :>= $_min | $_min :<= $_value})) PATTERN def on_and(node) logical_comparison_between_by_min_first?(node) do |*args| min_and_value, max_and_value = args.each_slice(2).to_a register_offense(node, min_and_value, max_and_value) end logical_comparison_between_by_max_first?(node) do |*args| max_and_value, min_and_value = args.each_slice(2).to_a register_offense(node, min_and_value, max_and_value) end end private def register_offense(node, min_and_value, max_and_value) value = (min_and_value & max_and_value).first min = min_and_value.find { _1 != value } || value max = max_and_value.find { _1 != value } || value prefer = "#{value.source}.between?(#{min.source}, #{max.source})" add_offense(node, message: format(MSG, prefer: prefer)) do |corrector| corrector.replace(node, prefer) 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/return_nil.rb
lib/rubocop/cop/style/return_nil.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Enforces consistency between `return nil` and `return`. # # This cop is disabled by default. Because there seems to be a perceived semantic difference # between `return` and `return nil`. The former can be seen as just halting evaluation, # while the latter might be used when the return value is of specific concern. # # Supported styles are `return` and `return_nil`. # # @example EnforcedStyle: return (default) # # bad # def foo(arg) # return nil if arg # end # # # good # def foo(arg) # return if arg # end # # @example EnforcedStyle: return_nil # # bad # def foo(arg) # return if arg # end # # # good # def foo(arg) # return nil if arg # end class ReturnNil < Base include ConfigurableEnforcedStyle extend AutoCorrector RETURN_MSG = 'Use `return` instead of `return nil`.' RETURN_NIL_MSG = 'Use `return nil` instead of `return`.' # @!method return_node?(node) def_node_matcher :return_node?, '(return)' # @!method return_nil_node?(node) def_node_matcher :return_nil_node?, '(return nil)' def on_return(node) # Check Lint/NonLocalExitFromIterator first before this cop node.each_ancestor(:block, :any_def) do |n| break if scoped_node?(n) send_node, args_node, _body_node = *n # if a proc is passed to `Module#define_method` or # `Object#define_singleton_method`, `return` will not cause a # non-local exit error break if define_method?(send_node) next if args_node.children.empty? return nil if chained_send?(send_node) end return if correct_style?(node) add_offense(node) do |corrector| corrected = style == :return ? 'return' : 'return nil' corrector.replace(node, corrected) end end private def message(_node) style == :return ? RETURN_MSG : RETURN_NIL_MSG end def correct_style?(node) (style == :return && !return_nil_node?(node)) || (style == :return_nil && !return_node?(node)) end def scoped_node?(node) node.any_def_type? || node.lambda? end # @!method chained_send?(node) def_node_matcher :chained_send?, '(send !nil? ...)' # @!method define_method?(node) def_node_matcher :define_method?, <<~PATTERN (send _ {:define_method :define_singleton_method} _) PATTERN end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/ternary_parentheses.rb
lib/rubocop/cop/style/ternary_parentheses.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for the presence of parentheses around ternary # conditions. It is configurable to enforce inclusion or omission of # parentheses using `EnforcedStyle`. Omission is only enforced when # removing the parentheses won't cause a different behavior. # # `AllowSafeAssignment` option for safe assignment. # By safe assignment we mean putting parentheses around # an assignment to indicate "I know I'm using an assignment # as a condition. It's not a mistake." # # @example EnforcedStyle: require_no_parentheses (default) # # bad # foo = (bar?) ? a : b # foo = (bar.baz?) ? a : b # foo = (bar && baz) ? a : b # # # good # foo = bar? ? a : b # foo = bar.baz? ? a : b # foo = bar && baz ? a : b # # @example EnforcedStyle: require_parentheses # # bad # foo = bar? ? a : b # foo = bar.baz? ? a : b # foo = bar && baz ? a : b # # # good # foo = (bar?) ? a : b # foo = (bar.baz?) ? a : b # foo = (bar && baz) ? a : b # # @example EnforcedStyle: require_parentheses_when_complex # # bad # foo = (bar?) ? a : b # foo = (bar.baz?) ? a : b # foo = bar && baz ? a : b # # # good # foo = bar? ? a : b # foo = bar.baz? ? a : b # foo = (bar && baz) ? a : b # # @example AllowSafeAssignment: true (default) # # good # foo = (bar = baz) ? a : b # # @example AllowSafeAssignment: false # # bad # foo = (bar = baz) ? a : b # class TernaryParentheses < Base include SafeAssignment include ConfigurableEnforcedStyle include SurroundingSpace extend AutoCorrector VARIABLE_TYPES = AST::Node::VARIABLES NON_COMPLEX_TYPES = [*VARIABLE_TYPES, :const, :defined?, :yield].freeze MSG = '%<command>s parentheses for ternary conditions.' MSG_COMPLEX = '%<command>s parentheses for ternary expressions with complex conditions.' def on_if(node) condition = node.condition return if only_closing_parenthesis_is_last_line?(condition) return if condition_as_parenthesized_one_line_pattern_matching?(condition) return unless node.ternary? && offense?(node) message = message(node) add_offense(node, message: message) do |corrector| autocorrect(corrector, node) end end private def only_closing_parenthesis_is_last_line?(condition) condition.source.split("\n").last == ')' end def condition_as_parenthesized_one_line_pattern_matching?(condition) return false unless condition.parenthesized_call? return false unless (first_child = condition.children.first) if target_ruby_version >= 3.0 first_child.match_pattern_p_type? else first_child.match_pattern_type? # For Ruby 2.7's one line pattern matching AST. end end def autocorrect(corrector, node) condition = node.condition return nil if parenthesized?(condition) && (safe_assignment?(condition) || unsafe_autocorrect?(condition)) if parenthesized?(condition) correct_parenthesized(corrector, condition) else correct_unparenthesized(corrector, condition) end end def offense?(node) condition = node.condition if safe_assignment?(condition) !safe_assignment_allowed? else parens = parenthesized?(condition) case style when :require_parentheses_when_complex complex_condition?(condition) ? !parens : parens else require_parentheses? ? !parens : parens end end end # If the condition is parenthesized we recurse and check for any # complex expressions within it. def complex_condition?(condition) if condition.begin_type? condition.to_a.any? { |x| complex_condition?(x) } else !non_complex_expression?(condition) end end # Anything that is not a variable, constant, or method/.method call # will be counted as a complex expression. def non_complex_expression?(condition) NON_COMPLEX_TYPES.include?(condition.type) || non_complex_send?(condition) end def non_complex_send?(node) return false unless node.call_type? !node.operator_method? || node.method?(:[]) end def message(node) if require_parentheses_when_complex? command = parenthesized?(node.condition) ? 'Only use' : 'Use' format(MSG_COMPLEX, command: command) else command = require_parentheses? ? 'Use' : 'Omit' format(MSG, command: command) end end def require_parentheses? style == :require_parentheses end def require_parentheses_when_complex? style == :require_parentheses_when_complex end def parenthesized?(node) node.begin_type? end def unsafe_autocorrect?(condition) condition.children.any? { |child| below_ternary_precedence?(child) } end def unparenthesized_method_call?(child) /^[a-z]/i.match?(method_name(child)) && !child.parenthesized? end def below_ternary_precedence?(child) # Handle English "or", e.g. 'foo or bar ? a : b' (child.or_type? && child.semantic_operator?) || # Handle English "and", e.g. 'foo and bar ? a : b' (child.and_type? && child.semantic_operator?) || # Handle English "not", e.g. 'not foo ? a : b' (child.send_type? && child.prefix_not?) end # @!method method_name(node) def_node_matcher :method_name, <<~PATTERN {($:defined? _ ...) (call {_ nil?} $_ _ ...)} PATTERN def correct_parenthesized(corrector, condition) corrector.remove(condition.loc.begin) corrector.remove(condition.loc.end) # Ruby allows no space between the question mark and parentheses. # If we remove the parentheses, we need to add a space or we'll # generate invalid code. corrector.insert_after(condition.loc.end, ' ') unless whitespace_after?(condition) if (send_node = condition.child_nodes.last) && node_args_need_parens?(send_node) parenthesize_condition_arguments(corrector, send_node) end end def correct_unparenthesized(corrector, condition) corrector.wrap(condition, '(', ')') end def parenthesize_condition_arguments(corrector, send_node) range_start = send_node.defined_type? ? send_node.loc.keyword : send_node.loc.selector opening_range = range_start.end.join(send_node.first_argument.source_range.begin) corrector.replace(opening_range, '(') corrector.insert_after(send_node.last_argument, ')') end def whitespace_after?(node) last_token = processed_source.last_token_of(node) last_token.space_after? end def node_args_need_parens?(send_node) return false unless node_with_args?(send_node) return false if send_node.arguments.none? || send_node.parenthesized? send_node.dot? || send_node.safe_navigation? || unparenthesized_method_call?(send_node) end def node_with_args?(node) node.type?(:call, :defined?) end end end 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_and_module_children.rb
lib/rubocop/cop/style/class_and_module_children.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks that namespaced classes and modules are defined with a consistent style. # # With `nested` style, classes and modules should be defined separately (one constant # on each line, without `::`). With `compact` style, classes and modules should be # defined with fully qualified names (using `::` for namespaces). # # NOTE: The style chosen will affect `Module.nesting` for the class or module. Using # `nested` style will result in each level being added, whereas `compact` style will # only include the fully qualified class or module name. # # By default, `EnforcedStyle` applies to both classes and modules. If desired, separate # styles can be defined for classes and modules by using `EnforcedStyleForClasses` and # `EnforcedStyleForModules` respectively. If not set, or set to nil, the `EnforcedStyle` # value will be used. # # @safety # Autocorrection is unsafe. # # Moving from `compact` to `nested` children requires knowledge of whether the # outer parent is a module or a class. Moving from `nested` to `compact` requires # verification that the outer parent is defined elsewhere. RuboCop does not # have the knowledge to perform either operation safely and thus requires # manual oversight. # # @example EnforcedStyle: nested (default) # # good # # have each child on its own line # class Foo # class Bar # end # end # # @example EnforcedStyle: compact # # good # # combine definitions as much as possible # class Foo::Bar # end # # The compact style is only forced for classes/modules with one child. class ClassAndModuleChildren < Base include Alignment include ConfigurableEnforcedStyle include RangeHelp extend AutoCorrector NESTED_MSG = 'Use nested module/class definitions instead of compact style.' COMPACT_MSG = 'Use compact module/class definition instead of nested style.' def on_class(node) return if node.parent_class && style != :nested check_style(node, node.body, style_for_classes) end def on_module(node) check_style(node, node.body, style_for_modules) end private def nest_or_compact(corrector, node) style = node.class_type? ? style_for_classes : style_for_modules if style == :nested nest_definition(corrector, node) else compact_definition(corrector, node) end end def nest_definition(corrector, node) padding = indentation(node) + leading_spaces(node) padding_for_trailing_end = padding.sub(' ' * node.loc.end.column, '') replace_namespace_keyword(corrector, node) split_on_double_colon(corrector, node, padding) add_trailing_end(corrector, node, padding_for_trailing_end) end def replace_namespace_keyword(corrector, node) class_definition = node.left_sibling&.each_node(:class)&.find do |class_node| class_node.identifier == node.identifier.namespace end namespace_keyword = class_definition ? 'class' : 'module' corrector.replace(node.loc.keyword, namespace_keyword) end def split_on_double_colon(corrector, node, padding) children_definition = node.children.first range = range_between(children_definition.loc.double_colon.begin_pos, children_definition.loc.double_colon.end_pos) replacement = "\n#{padding}#{node.loc.keyword.source} " corrector.replace(range, replacement) end def add_trailing_end(corrector, node, padding) replacement = "#{padding}end\n#{leading_spaces(node)}end" corrector.replace(node.loc.end, replacement) end def compact_definition(corrector, node) compact_node(corrector, node) remove_end(corrector, node.body) unindent(corrector, node) end def compact_node(corrector, node) range = range_between(node.loc.keyword.begin_pos, node.body.loc.name.end_pos) corrector.replace(range, compact_replacement(node)) end def compact_replacement(node) replacement = "#{node.body.type} #{compact_identifier_name(node)}" body_comments = processed_source.ast_with_comments[node.body] unless body_comments.empty? replacement = body_comments.map(&:text).push(replacement).join("\n") end replacement end def compact_identifier_name(node) "#{node.identifier.const_name}::" \ "#{node.body.children.first.const_name}" end # rubocop:disable Metrics/AbcSize def remove_end(corrector, body) remove_begin_pos = if same_line?(body.loc.name, body.loc.end) body.loc.name.end_pos else body.loc.end.begin_pos - leading_spaces(body).size end adjustment = processed_source.raw_source[remove_begin_pos] == ';' ? 0 : 1 range = range_between(remove_begin_pos, body.loc.end.end_pos + adjustment) corrector.remove(range) end # rubocop:enable Metrics/AbcSize def unindent(corrector, node) return unless node.body.children.last last_child_leading_spaces = leading_spaces(node.body.children.last) return if spaces_size(leading_spaces(node)) == spaces_size(last_child_leading_spaces) column_delta = configured_indentation_width - spaces_size(last_child_leading_spaces) return if column_delta.zero? AlignmentCorrector.correct(corrector, processed_source, node, column_delta) end def leading_spaces(node) node.source_range.source_line[/\A\s*/] end def spaces_size(spaces_string) mapping = { "\t" => tab_indentation_width } spaces_string.chars.sum { |character| mapping.fetch(character, 1) } end def tab_indentation_width config.for_cop('Layout/IndentationStyle')['IndentationWidth'] || configured_indentation_width end def check_style(node, body, style) return if node.identifier.namespace&.cbase_type? if style == :nested check_nested_style(node) else check_compact_style(node, body) end end def check_nested_style(node) return unless compact_node_name?(node) return if node.parent&.type?(:class, :module) add_offense(node.loc.name, message: NESTED_MSG) do |corrector| autocorrect(corrector, node) end end def check_compact_style(node, body) parent = node.parent return if parent&.type?(:class, :module) return unless needs_compacting?(body) add_offense(node.loc.name, message: COMPACT_MSG) do |corrector| autocorrect(corrector, node) end end def autocorrect(corrector, node) return if node.class_type? && node.parent_class && style != :nested nest_or_compact(corrector, node) end def needs_compacting?(body) body && %i[module class].include?(body.type) end def compact_node_name?(node) node.identifier.source.include?('::') end def style_for_classes cop_config['EnforcedStyleForClasses'] || style end def style_for_modules cop_config['EnforcedStyleForModules'] || style end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/symbol_literal.rb
lib/rubocop/cop/style/symbol_literal.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks symbol literal syntax. # # @example # # # bad # :"symbol" # # # good # :symbol class SymbolLiteral < Base extend AutoCorrector MSG = 'Do not use strings for word-like symbol literals.' def on_sym(node) return unless /\A:["'][A-Za-z_]\w*["']\z/.match?(node.source) add_offense(node) { |corrector| corrector.replace(node, node.source.delete(%q('"))) } end end end 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_assignment.rb
lib/rubocop/cop/style/redundant_assignment.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for redundant assignment before returning. # # @example # # bad # def test # x = foo # x # end # # # bad # def test # if x # z = foo # z # elsif y # z = bar # z # end # end # # # good # def test # foo # end # # # good # def test # if x # foo # elsif y # bar # end # end # class RedundantAssignment < Base extend AutoCorrector MSG = 'Redundant assignment before returning detected.' # @!method redundant_assignment?(node) def_node_matcher :redundant_assignment?, <<~PATTERN (... $(lvasgn _name _expression) (lvar _name)) PATTERN def on_def(node) check_branch(node.body) end alias on_defs on_def private # rubocop:disable Metrics/CyclomaticComplexity def check_branch(node) return unless node case node.type when :case then check_case_node(node) when :case_match then check_case_match_node(node) when :if then check_if_node(node) when :rescue, :resbody check_rescue_node(node) when :ensure then check_ensure_node(node) when :begin, :kwbegin check_begin_node(node) end end # rubocop:enable Metrics/CyclomaticComplexity def check_case_node(node) node.when_branches.each { |when_node| check_branch(when_node.body) } check_branch(node.else_branch) end def check_case_match_node(node) node.in_pattern_branches.each { |in_pattern_node| check_branch(in_pattern_node.body) } check_branch(node.else_branch) end def check_if_node(node) return if node.modifier_form? || node.ternary? check_branch(node.if_branch) check_branch(node.else_branch) end def check_rescue_node(node) node.child_nodes.each { |child_node| check_branch(child_node) } end def check_ensure_node(node) check_branch(node.branch) end def check_begin_node(node) if (assignment = redundant_assignment?(node)) add_offense(assignment) do |corrector| expression = assignment.children[1] corrector.replace(assignment, expression.source) corrector.remove(assignment.right_sibling) end else last_expr = node.children.last check_branch(last_expr) 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_exception.rb
lib/rubocop/cop/style/redundant_exception.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for `RuntimeError` as the argument of `raise`/`fail`. # # @example # # bad # raise RuntimeError, 'message' # raise RuntimeError.new('message') # # # good # raise 'message' # # # bad - message is not a string # raise RuntimeError, Object.new # raise RuntimeError.new(Object.new) # # # good # raise Object.new.to_s # class RedundantException < Base extend AutoCorrector MSG_1 = 'Redundant `RuntimeError` argument can be removed.' MSG_2 = 'Redundant `RuntimeError.new` call can be replaced with just the message.' RESTRICT_ON_SEND = %i[raise fail].freeze # Switch `raise RuntimeError, 'message'` to `raise 'message'`, and # `raise RuntimeError.new('message')` to `raise 'message'`. def on_send(node) fix_exploded(node) || fix_compact(node) end private def fix_exploded(node) exploded?(node) do |command, message| add_offense(node, message: MSG_1) do |corrector| corrector.replace(node, replaced_exploded(node, command, message)) end end end def replaced_exploded(node, command, message) arg = string_message?(message) ? message.source : "#{message.source}.to_s" arg = node.parenthesized? ? "(#{arg})" : " #{arg}" "#{command}#{arg}" end def string_message?(message) message.any_str_type? end def fix_compact(node) compact?(node) do |new_call, message| add_offense(node, message: MSG_2) do |corrector| corrector.replace(new_call, replaced_compact(message)) end end end def replaced_compact(message) if string_message?(message) message.source else "#{message.source}.to_s" end end # @!method exploded?(node) def_node_matcher :exploded?, <<~PATTERN (send nil? ${:raise :fail} (const {nil? cbase} :RuntimeError) $_) PATTERN # @!method compact?(node) def_node_matcher :compact?, <<~PATTERN (send nil? {:raise :fail} $(send (const {nil? cbase} :RuntimeError) :new $_)) 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/def_with_parentheses.rb
lib/rubocop/cop/style/def_with_parentheses.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for parentheses in the definition of a method, # that does not take any arguments. Both instance and # class/singleton methods are checked. # # @example # # # bad # def foo() # do_something # end # # # good # def foo # do_something # end # # # bad # def foo() = do_something # # # good # def foo = do_something # # # good - without parentheses it's a syntax error # def foo() do_something end # def foo()=do_something # # # bad # def Baz.foo() # do_something # end # # # good # def Baz.foo # do_something # end class DefWithParentheses < Base include RangeHelp extend AutoCorrector MSG = "Omit the parentheses in defs when the method doesn't accept any arguments." def on_def(node) return unless !node.arguments? && (arguments_range = node.arguments.source_range) return if parentheses_required?(node, arguments_range) add_offense(arguments_range) do |corrector| corrector.remove(arguments_range) end end alias on_defs on_def private def parentheses_required?(node, arguments_range) return true if node.single_line? && !node.endless? end_pos = arguments_range.end.end_pos token_after_argument = range_between(end_pos, end_pos + 1).source token_after_argument == '=' end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/optional_arguments.rb
lib/rubocop/cop/style/optional_arguments.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for optional arguments to methods # that do not come at the end of the argument list. # # @safety # This cop is unsafe because changing a method signature will # implicitly change behavior. # # @example # # bad # def foo(a = 1, b, c) # end # # # good # def baz(a, b, c = 1) # end # # def foobar(a = 1, b = 2, c = 3) # end class OptionalArguments < Base MSG = 'Optional arguments should appear at the end of the argument list.' def on_def(node) each_misplaced_optional_arg(node.arguments) { |argument| add_offense(argument) } end private def each_misplaced_optional_arg(arguments) optarg_positions, arg_positions = argument_positions(arguments) return if optarg_positions.empty? || arg_positions.empty? optarg_positions.each do |optarg_position| # there can only be one group of optional arguments break if optarg_position > arg_positions.max yield arguments[optarg_position] end end def argument_positions(arguments) optarg_positions = [] arg_positions = [] arguments.each_with_index do |argument, index| optarg_positions << index if argument.optarg_type? arg_positions << index if argument.arg_type? end [optarg_positions, arg_positions] end end end 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_when_then.rb
lib/rubocop/cop/style/multiline_when_then.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks uses of the `then` keyword # in multi-line when statements. # # @example # # bad # case foo # when bar then # end # # # good # case foo # when bar # end # # # good # case foo # when bar then do_something # end # # # good # case foo # when bar then do_something(arg1, # arg2) # end # class MultilineWhenThen < Base include RangeHelp extend AutoCorrector MSG = 'Do not use `then` for multiline `when` statement.' def on_when(node) return if !node.then? || require_then?(node) range = node.loc.begin add_offense(range) do |corrector| corrector.remove(range_with_surrounding_space(range, side: :left, newlines: false)) end end private # Requires `then` for write `when` and its body on the same line. def require_then?(when_node) unless when_node.conditions.first.first_line == when_node.conditions.last.last_line return true end return false unless when_node.body same_line?(when_node, when_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/each_with_object.rb
lib/rubocop/cop/style/each_with_object.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Looks for inject / reduce calls where the passed in object is # returned at the end and so could be replaced by each_with_object without # the need to return the object at the end. # # However, we can't replace with each_with_object if the accumulator # parameter is assigned to within the block. # # @example # # bad # [1, 2].inject({}) { |a, e| a[e] = e; a } # # # good # [1, 2].each_with_object({}) { |e, a| a[e] = e } class EachWithObject < Base extend AutoCorrector include RangeHelp MSG = 'Use `each_with_object` instead of `%<method>s`.' METHODS = %i[inject reduce].freeze def on_block(node) each_with_object_block_candidate?(node) do |method, args, body| _, method_name, method_arg = *method return if simple_method_arg?(method_arg) return_value = return_value(body) return unless return_value return unless first_argument_returned?(args, return_value) return if accumulator_param_assigned_to?(body, args) message = format(MSG, method: method_name) add_offense(method.loc.selector, message: message) do |corrector| autocorrect_block(corrector, node, return_value) end end end def on_numblock(node) each_with_object_numblock_candidate?(node) do |method, body| _, method_name, method_arg = *method return if simple_method_arg?(method_arg) return unless return_value(body)&.source == '_1' message = format(MSG, method: method_name) add_offense(method.loc.selector, message: message) do |corrector| autocorrect_numblock(corrector, node) end end end private # @!method each_with_object_block_candidate?(node) def_node_matcher :each_with_object_block_candidate?, <<~PATTERN (block $(call _ {:inject :reduce} _) $(args _ _) $_) PATTERN # @!method each_with_object_numblock_candidate?(node) def_node_matcher :each_with_object_numblock_candidate?, <<~PATTERN (numblock $(call _ {:inject :reduce} _) 2 $_) PATTERN def autocorrect_block(corrector, node, return_value) corrector.replace(node.send_node.loc.selector, 'each_with_object') first_arg, second_arg = *node.arguments corrector.swap(first_arg, second_arg) if return_value_occupies_whole_line?(return_value) corrector.remove(whole_line_expression(return_value)) else corrector.remove(return_value) end end def autocorrect_numblock(corrector, node) corrector.replace(node.send_node.loc.selector, 'each_with_object') # We don't remove the return value to avoid a clobbering error. node.body.each_descendant do |var| next unless var.lvar_type? corrector.replace(var, '_2') if var.source == '_1' corrector.replace(var, '_1') if var.source == '_2' end end def simple_method_arg?(method_arg) method_arg&.basic_literal? end # if the accumulator parameter is assigned to in the block, # then we can't convert to each_with_object def accumulator_param_assigned_to?(body, args) first_arg, = *args accumulator_var, = *first_arg body.each_descendant.any? do |n| next unless n.assignment? lhs, _rhs = *n lhs.equal?(accumulator_var) end end def return_value(body) return unless body return_value = body.begin_type? ? body.children.last : body return_value if return_value&.lvar_type? end def first_argument_returned?(args, return_value) first_arg, = *args accumulator_var, = *first_arg return_var, = *return_value accumulator_var == return_var end def return_value_occupies_whole_line?(node) whole_line_expression(node).source.strip == node.source end def whole_line_expression(node) range_by_whole_lines(node.source_range, include_final_newline: 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/sole_nested_conditional.rb
lib/rubocop/cop/style/sole_nested_conditional.rb
# frozen_string_literal: true module RuboCop module Cop module Style # If the branch of a conditional consists solely of a conditional node, # its conditions can be combined with the conditions of the outer branch. # This helps to keep the nesting level from getting too deep. # # @example # # bad # if condition_a # if condition_b # do_something # end # end # # # bad # if condition_b # do_something # end if condition_a # # # good # if condition_a && condition_b # do_something # end # # @example AllowModifier: false (default) # # bad # if condition_a # do_something if condition_b # end # # # bad # if condition_b # do_something # end if condition_a # # @example AllowModifier: true # # good # if condition_a # do_something if condition_b # end # # # good # if condition_b # do_something # end if condition_a class SoleNestedConditional < Base include RangeHelp extend AutoCorrector MSG = 'Consider merging nested conditions into outer `%<conditional_type>s` conditions.' def self.autocorrect_incompatible_with [Style::NegatedIf, Style::NegatedUnless] end def on_if(node) return if node.ternary? || node.else? || node.elsif? if_branch = node.if_branch return if use_variable_assignment_in_condition?(node.condition, if_branch) return unless offending_branch?(node, if_branch) message = format(MSG, conditional_type: node.keyword) add_offense(if_branch.loc.keyword, message: message) do |corrector| autocorrect(corrector, node, if_branch) end end private def use_variable_assignment_in_condition?(condition, if_branch) assigned_variables = assigned_variables(condition) assigned_variables && if_branch&.if_type? && assigned_variables.include?(if_branch.condition.source) end def assigned_variables(condition) assigned_variables = condition.assignment? ? [condition.children.first.to_s] : [] assigned_variables + condition.descendants.select(&:assignment?).map do |node| node.children.first.to_s end end def offending_branch?(node, branch) return false unless branch branch.if_type? && !branch.else? && !branch.ternary? && !((node.modifier_form? || branch.modifier_form?) && allow_modifier?) end def autocorrect(corrector, node, if_branch) if node.modifier_form? autocorrect_outer_condition_modify_form(corrector, node, if_branch) else autocorrect_outer_condition_basic(corrector, node, if_branch) end end def autocorrect_outer_condition_basic(corrector, node, if_branch) correct_node(corrector, node) if if_branch.modifier_form? correct_for_guard_condition_style(corrector, node, if_branch) else correct_for_basic_condition_style(corrector, node, if_branch) correct_for_comment(corrector, node, if_branch) end end def correct_node(corrector, node) corrector.replace(node.loc.keyword, 'if') if node.unless? && !part_of_ignored_node?(node) corrector.replace(node.condition, chainable_condition(node)) ignore_node(node) end def correct_for_guard_condition_style(corrector, node, if_branch) corrector.insert_after(node.condition, " && #{chainable_condition(if_branch)}") range = range_between( if_branch.loc.keyword.begin_pos, if_branch.condition.source_range.end_pos ) corrector.remove(range_with_surrounding_space(range, newlines: false)) end # rubocop:disable Metrics/AbcSize def correct_for_basic_condition_style(corrector, node, if_branch) range = range_between( node.condition.source_range.end_pos, if_branch.condition.source_range.begin_pos ) corrector.replace(range, ' && ') corrector.replace(if_branch.condition, chainable_condition(if_branch)) end_range = if same_line?(node.loc.end, node.if_branch.loc.end) node.loc.end else range_by_whole_lines(node.loc.end, include_final_newline: true) end corrector.remove(end_range) end # rubocop:enable Metrics/AbcSize def autocorrect_outer_condition_modify_form(corrector, node, if_branch) correct_node(corrector, if_branch) corrector.insert_before(if_branch.condition, "#{chainable_condition(node)} && ") range = range_between(node.loc.keyword.begin_pos, node.condition.source_range.end_pos) corrector.remove(range_with_surrounding_space(range, newlines: false)) end def correct_for_comment(corrector, node, if_branch) comments = processed_source.ast_with_comments[if_branch].select do |comment| comment.loc.line < if_branch.condition.first_line end comment_text = comments.map(&:text).join("\n") << "\n" corrector.insert_before(node.loc.keyword, comment_text) unless comments.empty? end def chainable_condition(node) wrapped_condition = add_parentheses_if_needed(node.condition) return wrapped_condition if node.if? node.condition.and_type? ? "!(#{wrapped_condition})" : "!#{wrapped_condition}" end def add_parentheses_if_needed(condition) # Handle `send` and `block` nodes that need to be wrapped in parens # FIXME: autocorrection prevents syntax errors by wrapping the entire node in parens, # but wrapping the argument list would be a more ergonomic correction. node_to_check = condition&.any_block_type? ? condition.send_node : condition return condition.source unless add_parentheses?(node_to_check) if parenthesize_method?(condition) parenthesized_method_arguments(condition) elsif condition.and_type? parenthesized_and(condition) else "(#{condition.source})" end end def parenthesize_method?(node) node.call_type? && node.arguments.any? && !node.parenthesized? && !node.comparison_method? && !node.operator_method? end def add_parentheses?(node) return true if node.assignment? || node.or_type? return true if assignment_in_and?(node) return false unless node.call_type? (node.arguments.any? && !node.parenthesized?) || node.prefix_not? end def assignment_in_and?(node) return false unless node.and_type? node.each_descendant.any?(&:assignment?) end def parenthesized_method_arguments(node) method_call = node.source_range.begin.join(node.loc.selector.end).source arguments = node.first_argument.source_range.begin.join(node.source_range.end).source "#{method_call}(#{arguments})" end def parenthesized_and(node) # We only need to add parentheses around the last clause if it's an assignment, # because other clauses will be unchanged by merging conditionals. lhs = node.lhs.source rhs = parenthesized_and_clause(node.rhs) operator = range_with_surrounding_space(node.loc.operator, whitespace: true).source "#{lhs}#{operator}#{rhs}" end def parenthesized_and_clause(node) if node.and_type? parenthesized_and(node) elsif node.assignment? "(#{node.source})" else node.source end end def allow_modifier? cop_config['AllowModifier'] end end end 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/slicing_with_range.rb
lib/rubocop/cop/style/slicing_with_range.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks that arrays are not sliced with the redundant `ary[0..-1]`, replacing it with `ary`, # and ensures arrays are sliced with endless ranges instead of `ary[start..-1]` on Ruby 2.6+, # and with beginless ranges instead of `ary[nil..end]` on Ruby 2.7+. # # @safety # This cop is unsafe because `x..-1` and `x..` are only guaranteed to # be equivalent for `Array#[]`, `String#[]`, and the cop cannot determine what class # the receiver is. # # For example: # [source,ruby] # ---- # sum = proc { |ary| ary.sum } # sum[-3..-1] # => -6 # sum[-3..] # Hangs forever # ---- # # @example # # bad # items[0..-1] # items[0..nil] # items[0...nil] # # # good # items # # # bad # items[1..-1] # Ruby 2.6+ # items[1..nil] # Ruby 2.6+ # # # good # items[1..] # Ruby 2.6+ # # # bad # items[nil..42] # Ruby 2.7+ # # # good # items[..42] # Ruby 2.7+ # items[0..42] # Ruby 2.7+ # class SlicingWithRange < Base extend AutoCorrector extend TargetRubyVersion minimum_target_ruby_version 2.6 MSG = 'Prefer `%<prefer>s` over `%<current>s`.' MSG_USELESS_RANGE = 'Remove the useless `%<prefer>s`.' RESTRICT_ON_SEND = %i[[]].freeze # @!method range_from_zero_till_minus_one?(node) def_node_matcher :range_from_zero_till_minus_one?, <<~PATTERN { (irange (int 0) {(int -1) nil}) (erange (int 0) nil) } PATTERN # @!method range_till_minus_one?(node) def_node_matcher :range_till_minus_one?, <<~PATTERN { (irange !nil? {(int -1) nil}) (erange !nil? nil) } PATTERN # @!method range_from_zero?(node) def_node_matcher :range_from_zero?, <<~PATTERN (irange nil !nil?) PATTERN def on_send(node) return unless node.arguments.one? range_node = node.first_argument offense_range = find_offense_range(node) return unless (message, removal_range = offense_message_with_removal_range(node, range_node, offense_range)) # Changing the range to beginningless or endless when unparenthesized # changes the semantics of the code, and thus will not be considered # an offense. return if removal_range != offense_range && unparenthesized_call?(node) add_offense(offense_range, message: message) do |corrector| corrector.remove(removal_range) end end alias on_csend on_send private def unparenthesized_call?(node) node.loc.dot && !node.parenthesized? end def find_offense_range(node) if node.loc.dot node.loc.dot.join(node.source_range.end) else node.loc.selector end end def offense_message_with_removal_range(node, range_node, offense_range) if range_from_zero_till_minus_one?(range_node) [format(MSG_USELESS_RANGE, prefer: offense_range.source), offense_range] elsif range_till_minus_one?(range_node) [ offense_message_for_partial_range(node, endless(range_node), offense_range), range_node.end ] elsif range_from_zero?(range_node) && target_ruby_version >= 2.7 [ offense_message_for_partial_range(node, beginless(range_node), offense_range), range_node.begin ] end end def offense_message_for_partial_range(node, prefer, offense_range) current = node.loc.dot ? arguments_source(node) : offense_range.source prefer = "[#{prefer}]" unless node.loc.dot format(MSG, prefer: prefer, current: current) end def endless(range_node) "#{range_node.begin.source}#{range_node.loc.operator.source}" end def beginless(range_node) "#{range_node.loc.operator.source}#{range_node.end.source}" end def arguments_source(node) node.first_argument.source_range.join(node.last_argument.source_range.end).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/class_methods_definitions.rb
lib/rubocop/cop/style/class_methods_definitions.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Enforces using `def self.method_name` or `class << self` to define class methods. # # @example EnforcedStyle: def_self (default) # # bad # class SomeClass # class << self # attr_accessor :class_accessor # # def class_method # # ... # end # end # end # # # good # class SomeClass # def self.class_method # # ... # end # # class << self # attr_accessor :class_accessor # end # end # # # good - contains private method # class SomeClass # class << self # attr_accessor :class_accessor # # private # # def private_class_method # # ... # end # end # end # # @example EnforcedStyle: self_class # # bad # class SomeClass # def self.class_method # # ... # end # end # # # good # class SomeClass # class << self # def class_method # # ... # end # end # end # class ClassMethodsDefinitions < Base include ConfigurableEnforcedStyle include CommentsHelp include VisibilityHelp include RangeHelp extend AutoCorrector MSG = 'Use `%<preferred>s` to define a class method.' MSG_SCLASS = 'Do not define public methods within class << self.' def on_sclass(node) return unless def_self_style? return unless node.identifier.self_type? return unless all_methods_public?(node) add_offense(node, message: MSG_SCLASS) do |corrector| autocorrect_sclass(node, corrector) end end def on_defs(node) return if def_self_style? return unless node.receiver.self_type? message = format(MSG, preferred: 'class << self') add_offense(node, message: message) end private def def_self_style? style == :def_self end def all_methods_public?(sclass_node) def_nodes = def_nodes(sclass_node) return false if def_nodes.empty? def_nodes.all? { |def_node| node_visibility(def_node) == :public } end def def_nodes(sclass_node) sclass_def = sclass_node.body return [] unless sclass_def if sclass_def.def_type? [sclass_def] elsif sclass_def.begin_type? sclass_def.each_child_node(:def).to_a else [] end end def autocorrect_sclass(node, corrector) rewritten_defs = [] def_nodes(node).each do |def_node| next unless node_visibility(def_node) == :public range, source = extract_def_from_sclass(def_node, node) corrector.remove(range) rewritten_defs << source end if sclass_only_has_methods?(node) corrector.remove(node) rewritten_defs.first&.strip! else corrector.insert_after(node, "\n") end corrector.insert_after(node, rewritten_defs.join("\n")) end def sclass_only_has_methods?(node) node.body.def_type? || node.body.each_child_node.all?(&:def_type?) end def extract_def_from_sclass(def_node, sclass_node) range = source_range_with_comment(def_node) source = range.source.sub!( "def #{def_node.method_name}", "def self.#{def_node.method_name}" ) source = source.gsub(/^ {#{indentation_diff(def_node, sclass_node)}}/, '') [range, source.chomp] end def indentation_diff(node1, node2) node1.loc.column - node2.loc.column end end end 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/endless_method.rb
lib/rubocop/cop/style/endless_method.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for endless methods. # # It can enforce endless method definitions whenever possible or with single line methods. # It can also disallow multiline endless method definitions or all endless definitions. # # `require_single_line` style enforces endless method definitions for single line methods. # `require_always` style enforces endless method definitions for single statement methods. # # Other method definition types are not considered by this cop. # # The supported styles are: # # * allow_single_line (default) - only single line endless method definitions are allowed. # * allow_always - all endless method definitions are allowed. # * disallow - all endless method definitions are disallowed. # * require_single_line - endless method definitions are required for single line methods. # * require_always - all endless method definitions are required. # # NOTE: Incorrect endless method definitions will always be # corrected to a multi-line definition. # # @example EnforcedStyle: allow_single_line (default) # # bad, multi-line endless method # def my_method = x.foo # .bar # .baz # # # good # def my_method # x # end # # # good # def my_method = x # # # good # def my_method # x.foo # .bar # .baz # end # # @example EnforcedStyle: allow_always # # good # def my_method # x # end # # # good # def my_method = x # # # good # def my_method = x.foo # .bar # .baz # # # good # def my_method # x.foo # .bar # .baz # end # # @example EnforcedStyle: disallow # # bad # def my_method = x # # # bad # def my_method = x.foo # .bar # .baz # # # good # def my_method # x # end # # # good # def my_method # x.foo # .bar # .baz # end # # @example EnforcedStyle: require_single_line # # bad # def my_method # x # end # # # bad # def my_method = x.foo # .bar # .baz # # # good # def my_method = x # # # good # def my_method # x.foo # .bar # .baz # end # # @example EnforcedStyle: require_always # # bad # def my_method # x # end # # # bad # def my_method # x.foo # .bar # .baz # end # # # good # def my_method = x # # # good # def my_method = x.foo # .bar # .baz # class EndlessMethod < Base include ConfigurableEnforcedStyle include EndlessMethodRewriter extend TargetRubyVersion extend AutoCorrector minimum_target_ruby_version 3.0 CORRECTION_STYLES = %w[multiline single_line].freeze MSG = 'Avoid endless method definitions.' MSG_MULTI_LINE = 'Avoid endless method definitions with multiple lines.' MSG_REQUIRE_SINGLE = 'Use endless method definitions for single line methods.' MSG_REQUIRE_ALWAYS = 'Use endless method definitions.' def on_def(node) return if node.assignment_method? || use_heredoc?(node) case style when :allow_single_line, :allow_always handle_allow_style(node) when :disallow handle_disallow_style(node) when :require_single_line handle_require_single_line_style(node) when :require_always handle_require_always_style(node) end end private def handle_allow_style(node) return unless node.endless? return if node.single_line? || style == :allow_always add_offense(node, message: MSG_MULTI_LINE) do |corrector| correct_to_multiline(corrector, node) end end def handle_require_single_line_style(node) if node.endless? && !node.single_line? add_offense(node, message: MSG_MULTI_LINE) do |corrector| correct_to_multiline(corrector, node) end elsif !node.endless? && can_be_made_endless?(node) && node.body.single_line? return if too_long_when_made_endless?(node) add_offense(node, message: MSG_REQUIRE_SINGLE) do |corrector| corrector.replace(node, endless_replacement(node)) end end end def handle_require_always_style(node) return if node.endless? || !can_be_made_endless?(node) return if too_long_when_made_endless?(node) add_offense(node, message: MSG_REQUIRE_ALWAYS) do |corrector| corrector.replace(node, endless_replacement(node)) end end def handle_disallow_style(node) return unless node.endless? add_offense(node) { |corrector| correct_to_multiline(corrector, node) } end def use_heredoc?(node) return false unless (body = node.body) return true if body.any_str_type? && body.heredoc? body.each_descendant(:str).any?(&:heredoc?) end def correct_to_multiline(corrector, node) replacement = <<~RUBY.strip def #{node.method_name}#{arguments(node)} #{node.body.source} end RUBY corrector.replace(node, replacement) end def endless_replacement(node) <<~RUBY.strip def #{node.method_name}#{arguments(node)} = #{node.body.source} RUBY end def arguments(node, missing = '') node.arguments.any? ? node.arguments.source : missing end def can_be_made_endless?(node) node.body && !node.body.begin_type? && !node.body.kwbegin_type? end def too_long_when_made_endless?(node) return false unless config.cop_enabled?('Layout/LineLength') offset = modifier_offset(node) endless_replacement(node).length + offset > max_line_length end def modifier_offset(node) same_line?(node.parent, node) ? node.loc.column - node.parent.loc.column : 0 end end end 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/raise_args.rb
lib/rubocop/cop/style/raise_args.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks the args passed to `fail` and `raise`. # # Exploded style (default) enforces passing the exception class and message # arguments separately, rather than constructing an instance of the error. # # Compact style enforces constructing an error instance. # # Both styles allow passing just a message, or an error instance when there is more # than one argument. # # The exploded style has an `AllowedCompactTypes` configuration # option that takes an `Array` of exception name Strings. # # @safety # This cop is unsafe because `raise Foo` calls `Foo.exception`, not `Foo.new`. # # @example EnforcedStyle: exploded (default) # # bad # raise StandardError.new('message') # # # good # raise StandardError, 'message' # fail 'message' # raise MyCustomError # raise MyCustomError.new(arg1, arg2, arg3) # raise MyKwArgError.new(key1: val1, key2: val2) # # # With `AllowedCompactTypes` set to ['MyWrappedError'] # raise MyWrappedError.new(obj) # raise MyWrappedError.new(obj), 'message' # # @example EnforcedStyle: compact # # bad # raise StandardError, 'message' # raise RuntimeError, arg1, arg2, arg3 # # # good # raise StandardError.new('message') # raise MyCustomError # raise MyCustomError.new(arg1, arg2, arg3) # fail 'message' class RaiseArgs < Base include ConfigurableEnforcedStyle extend AutoCorrector EXPLODED_MSG = 'Provide an exception class and message as arguments to `%<method>s`.' COMPACT_MSG = 'Provide an exception object as an argument to `%<method>s`.' ACCEPTABLE_ARG_TYPES = %i[ hash forwarded_restarg splat forwarded_restarg forwarded_args ].freeze RESTRICT_ON_SEND = %i[raise fail].freeze def on_send(node) return unless node.command?(:raise) || node.command?(:fail) case style when :compact check_compact(node) when :exploded check_exploded(node) end end private def correction_compact_to_exploded(node) exception_node, _new, message_node = *node.first_argument arguments = [exception_node, message_node].compact.map(&:source).join(', ') if node.parent && requires_parens?(node.parent) "#{node.method_name}(#{arguments})" else "#{node.method_name} #{arguments}" end end def correction_exploded_to_compact(node) exception_node, *message_nodes = *node.arguments return if message_nodes.size > 1 argument = message_nodes.first.source exception_class = exception_node.receiver&.source || exception_node.source if node.parent && requires_parens?(node.parent) "#{node.method_name}(#{exception_class}.new(#{argument}))" else "#{node.method_name} #{exception_class}.new(#{argument})" end end def check_compact(node) if node.arguments.size > 1 exception = node.first_argument return if exception.send_type? && exception.first_argument&.hash_type? add_offense(node, message: format(COMPACT_MSG, method: node.method_name)) do |corrector| replacement = correction_exploded_to_compact(node) corrector.replace(node, replacement) opposite_style_detected end else correct_style_detected end end def check_exploded(node) return correct_style_detected unless node.arguments.one? first_arg = node.first_argument return if !use_new_method?(first_arg) || acceptable_exploded_args?(first_arg.arguments) return if allowed_non_exploded_type?(first_arg) add_offense(node, message: format(EXPLODED_MSG, method: node.method_name)) do |corrector| replacement = correction_compact_to_exploded(node) corrector.replace(node, replacement) opposite_style_detected end end def use_new_method?(first_arg) first_arg.send_type? && first_arg.receiver && first_arg.method?(:new) end def acceptable_exploded_args?(args) # Allow code like `raise Ex.new(arg1, arg2)`. return true if args.size > 1 # Disallow zero arguments. return false if args.empty? arg = args.first # Allow nodes that may forward more than one argument ACCEPTABLE_ARG_TYPES.include?(arg.type) end def allowed_non_exploded_type?(arg) type = arg.receiver.const_name Array(cop_config['AllowedCompactTypes']).include?(type) end def requires_parens?(parent) parent.operator_keyword? || (parent.if_type? && parent.ternary?) end end end 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_by.rb
lib/rubocop/cop/style/redundant_sort_by.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Identifies places where `sort_by { ... }` can be replaced by # `sort`. # # @example # # bad # array.sort_by { |x| x } # array.sort_by do |var| # var # end # # # good # array.sort class RedundantSortBy < Base include RangeHelp extend AutoCorrector MSG_BLOCK = 'Use `sort` instead of `sort_by { |%<var>s| %<var>s }`.' MSG_NUMBLOCK = 'Use `sort` instead of `sort_by { _1 }`.' MSG_ITBLOCK = 'Use `sort` instead of `sort_by { it }`.' def on_block(node) redundant_sort_by_block(node) do |send, var_name| range = sort_by_range(send, node) add_offense(range, message: format(MSG_BLOCK, var: var_name)) do |corrector| corrector.replace(range, 'sort') end end end def on_numblock(node) redundant_sort_by_numblock(node) do |send| range = sort_by_range(send, node) add_offense(range, message: MSG_NUMBLOCK) do |corrector| corrector.replace(range, 'sort') end end end def on_itblock(node) redundant_sort_by_itblock(node) do |send| range = sort_by_range(send, node) add_offense(range, message: MSG_ITBLOCK) do |corrector| corrector.replace(range, 'sort') end end end private # @!method redundant_sort_by_block(node) def_node_matcher :redundant_sort_by_block, <<~PATTERN (block $(call _ :sort_by) (args (arg $_x)) (lvar _x)) PATTERN # @!method redundant_sort_by_numblock(node) def_node_matcher :redundant_sort_by_numblock, <<~PATTERN (numblock $(call _ :sort_by) 1 (lvar :_1)) PATTERN # @!method redundant_sort_by_itblock(node) def_node_matcher :redundant_sort_by_itblock, <<~PATTERN (itblock $(call _ :sort_by) _ (lvar :it)) PATTERN def sort_by_range(send, node) range_between(send.loc.selector.begin_pos, 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/lambda.rb
lib/rubocop/cop/style/lambda.rb
# frozen_string_literal: true module RuboCop module Cop module Style # (by default) checks for uses of the lambda literal syntax for # single line lambdas, and the method call syntax for multiline lambdas. # It is configurable to enforce one of the styles for both single line # and multiline lambdas as well. # # @example EnforcedStyle: line_count_dependent (default) # # bad # f = lambda { |x| x } # f = ->(x) do # x # end # # # good # f = ->(x) { x } # f = lambda do |x| # x # end # # @example EnforcedStyle: lambda # # bad # f = ->(x) { x } # f = ->(x) do # x # end # # # good # f = lambda { |x| x } # f = lambda do |x| # x # end # # @example EnforcedStyle: literal # # bad # f = lambda { |x| x } # f = lambda do |x| # x # end # # # good # f = ->(x) { x } # f = ->(x) do # x # end class Lambda < Base include ConfigurableEnforcedStyle extend AutoCorrector LITERAL_MESSAGE = 'Use the `-> { ... }` lambda literal syntax for %<modifier>s lambdas.' METHOD_MESSAGE = 'Use the `lambda` method for %<modifier>s lambdas.' OFFENDING_SELECTORS = { style: { lambda: { single_line: '->', multiline: '->' }, literal: { single_line: 'lambda', multiline: 'lambda' }, line_count_dependent: { single_line: 'lambda', multiline: '->' } } }.freeze def on_block(node) return unless node.lambda? selector = node.send_node.source return unless offending_selector?(node, selector) add_offense(node.send_node, message: message(node, selector)) do |corrector| if node.send_node.lambda_literal? LambdaLiteralToMethodCorrector.new(node).call(corrector) else autocorrect_method_to_literal(corrector, node) end end end alias on_numblock on_block alias on_itblock on_block private def offending_selector?(node, selector) lines = node.multiline? ? :multiline : :single_line selector == OFFENDING_SELECTORS[:style][style][lines] end def message(node, selector) message = selector == '->' ? METHOD_MESSAGE : LITERAL_MESSAGE format(message, modifier: message_line_modifier(node)) end def message_line_modifier(node) case style when :line_count_dependent node.multiline? ? 'multiline' : 'single line' else 'all' end end def autocorrect_method_to_literal(corrector, node) corrector.replace(node.send_node, '->') return unless node.arguments? arg_str = "(#{lambda_arg_string(node.arguments)})" corrector.insert_after(node.send_node, arg_str) corrector.remove(arguments_with_whitespace(node)) end def arguments_with_whitespace(node) node.loc.begin.end.join(node.arguments.loc.end) end def lambda_arg_string(args) args.children.map(&:source).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/unless_logical_operators.rb
lib/rubocop/cop/style/unless_logical_operators.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Checks for the use of logical operators in an `unless` condition. # It discourages such code, as the condition becomes more difficult # to read and understand. # # This cop supports two styles: # # - `forbid_mixed_logical_operators` (default) # - `forbid_logical_operators` # # `forbid_mixed_logical_operators` style forbids the use of more than one type # of logical operators. This makes the `unless` condition easier to read # because either all conditions need to be met or any condition need to be met # in order for the expression to be truthy or falsey. # # `forbid_logical_operators` style forbids any use of logical operator. # This makes it even more easy to read the `unless` condition as # there is only one condition in the expression. # # @example EnforcedStyle: forbid_mixed_logical_operators (default) # # bad # return unless a || b && c # return unless a && b || c # return unless a && b and c # return unless a || b or c # return unless a && b or c # return unless a || b and c # # # good # return unless a && b && c # return unless a || b || c # return unless a and b and c # return unless a or b or c # return unless a? # # @example EnforcedStyle: forbid_logical_operators # # bad # return unless a || b # return unless a && b # return unless a or b # return unless a and b # # # good # return unless a # return unless a? class UnlessLogicalOperators < Base include ConfigurableEnforcedStyle FORBID_MIXED_LOGICAL_OPERATORS = 'Do not use mixed logical operators in an `unless`.' FORBID_LOGICAL_OPERATORS = 'Do not use any logical operator in an `unless`.' # @!method or_with_and?(node) def_node_matcher :or_with_and?, <<~PATTERN (if (or <`and ...> ) ...) PATTERN # @!method and_with_or?(node) def_node_matcher :and_with_or?, <<~PATTERN (if (and <`or ...> ) ...) PATTERN # @!method logical_operator?(node) def_node_matcher :logical_operator?, <<~PATTERN (if ({and or} ... ) ...) PATTERN def on_if(node) return unless node.unless? if style == :forbid_mixed_logical_operators && mixed_logical_operator?(node) add_offense(node, message: FORBID_MIXED_LOGICAL_OPERATORS) elsif style == :forbid_logical_operators && logical_operator?(node) add_offense(node, message: FORBID_LOGICAL_OPERATORS) end end private def mixed_logical_operator?(node) or_with_and?(node) || and_with_or?(node) || mixed_precedence_and?(node) || mixed_precedence_or?(node) end def mixed_precedence_and?(node) and_sources = node.condition.each_descendant(:and).map(&:operator) and_sources << node.condition.operator if node.condition.and_type? !(and_sources.all?('&&') || and_sources.all?('and')) end def mixed_precedence_or?(node) or_sources = node.condition.each_descendant(:or).map(&:operator) or_sources << node.condition.operator if node.condition.or_type? !(or_sources.all?('||') || or_sources.all?('or')) end end end 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_transform_values.rb
lib/rubocop/cop/style/hash_transform_values.rb
# frozen_string_literal: true module RuboCop module Cop module Style # Looks for uses of `+_.each_with_object({}) {...}+`, # `+_.map {...}.to_h+`, and `+Hash[_.map {...}]+` that are actually just # transforming the values of a hash, and tries to use a simpler & faster # call to `transform_values` instead. # # @safety # This cop is unsafe, as it can produce false positives if we are # transforming an enumerable of key-value-like pairs that isn't actually # a hash, e.g.: `[[k1, v1], [k2, v2], ...]` # # @example # # bad # {a: 1, b: 2}.each_with_object({}) { |(k, v), h| h[k] = foo(v) } # Hash[{a: 1, b: 2}.collect { |k, v| [k, foo(v)] }] # {a: 1, b: 2}.map { |k, v| [k, v * v] }.to_h # {a: 1, b: 2}.to_h { |k, v| [k, v * v] } # # # good # {a: 1, b: 2}.transform_values { |v| foo(v) } # {a: 1, b: 2}.transform_values { |v| v * v } class HashTransformValues < Base include HashTransformMethod extend AutoCorrector extend TargetRubyVersion minimum_target_ruby_version 2.4 # @!method on_bad_each_with_object(node) def_node_matcher :on_bad_each_with_object, <<~PATTERN (block (call !#array_receiver? :each_with_object (hash)) (args (mlhs (arg _key) (arg $_)) (arg _memo)) (call (lvar _memo) :[]= $(lvar _key) $!`_memo)) PATTERN # @!method on_bad_hash_brackets_map(node) def_node_matcher :on_bad_hash_brackets_map, <<~PATTERN (send (const _ :Hash) :[] (block (call !#array_receiver? {:map :collect}) (args (arg _key) (arg $_)) (array $(lvar _key) $_))) PATTERN # @!method on_bad_map_to_h(node) def_node_matcher :on_bad_map_to_h, <<~PATTERN (call (block (call !#array_receiver? {:map :collect}) (args (arg _key) (arg $_)) (array $(lvar _key) $_)) :to_h) PATTERN # @!method on_bad_to_h(node) def_node_matcher :on_bad_to_h, <<~PATTERN (block (call !#array_receiver? :to_h) (args (arg _key) (arg $_)) (array $(lvar _key) $_)) PATTERN private def extract_captures(match) val_argname, key_body_expr, val_body_expr = *match Captures.new(val_argname, val_body_expr, key_body_expr) end def new_method_name 'transform_values' end end end 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_with_args_parentheses/omit_parentheses.rb
lib/rubocop/cop/style/method_call_with_args_parentheses/omit_parentheses.rb
# frozen_string_literal: true module RuboCop module Cop module Style class MethodCallWithArgsParentheses # Style omit_parentheses # rubocop:disable Metrics/ModuleLength, Metrics/CyclomaticComplexity module OmitParentheses include RangeHelp TRAILING_WHITESPACE_REGEX = /\s+\Z/.freeze OMIT_MSG = 'Omit parentheses for method calls with arguments.' private_constant :OMIT_MSG private def omit_parentheses(node) # rubocop:disable Metrics/PerceivedComplexity return unless node.parenthesized? return if inside_endless_method_def?(node) return if require_parentheses_for_hash_value_omission?(node) return if syntax_like_method_call?(node) return if method_call_before_constant_resolution?(node) return if super_call_without_arguments?(node) return if legitimate_call_with_parentheses?(node) return if allowed_camel_case_method_call?(node) return if allowed_string_interpolation_method_call?(node) add_offense(offense_range(node), message: OMIT_MSG) do |corrector| autocorrect(corrector, node) end end def autocorrect(corrector, node) range = args_begin(node) if parentheses_at_the_end_of_multiline_call?(node) # Whitespace after line continuation (`\ `) is a syntax error with_whitespace = range_with_surrounding_space(range, side: :right, newlines: false) corrector.replace(with_whitespace, ' \\') else corrector.replace(range, ' ') end corrector.remove(node.loc.end) end def offense_range(node) node.loc.begin.join(node.loc.end) end def inside_endless_method_def?(node) # parens are required around arguments inside an endless method node.each_ancestor(:any_def).any?(&:endless?) && node.arguments.any? end def require_parentheses_for_hash_value_omission?(node) # rubocop:disable Metrics/PerceivedComplexity return false unless (last_argument = node.last_argument) return false if !last_argument.hash_type? || !last_argument.pairs.last&.value_omission? node.parent&.conditional? || node.parent&.single_line? || !last_expression?(node) end # Require hash value omission be enclosed in parentheses to prevent the following issue: # https://bugs.ruby-lang.org/issues/18396. def last_expression?(node) !(node.parent&.assignment? ? node.parent.right_sibling : node.right_sibling) end def syntax_like_method_call?(node) node.implicit_call? || node.operator_method? end def method_call_before_constant_resolution?(node) node.parent&.const_type? end def super_call_without_arguments?(node) node.super_type? && node.arguments.none? end def allowed_camel_case_method_call?(node) node.camel_case_method? && (node.arguments.none? || cop_config['AllowParenthesesInCamelCaseMethod']) end def allowed_string_interpolation_method_call?(node) cop_config['AllowParenthesesInStringInterpolation'] && inside_string_interpolation?(node) end def parentheses_at_the_end_of_multiline_call?(node) node.multiline? && node.loc.begin.source_line .gsub(TRAILING_WHITESPACE_REGEX, '') .end_with?('(') end def legitimate_call_with_parentheses?(node) # rubocop:disable Metrics/PerceivedComplexity call_in_literals?(node) || node.parent&.when_type? || call_with_ambiguous_arguments?(node) || call_in_logical_operators?(node) || call_in_optional_arguments?(node) || call_in_single_line_inheritance?(node) || allowed_multiline_call_with_parentheses?(node) || allowed_chained_call_with_parentheses?(node) || assignment_in_condition?(node) || forwards_anonymous_rest_arguments?(node) end def call_in_literals?(node) parent = node.parent&.any_block_type? ? node.parent.parent : node.parent return false unless parent parent.type?(:pair, :array, :range) || splat?(parent) || ternary_if?(parent) end def call_in_logical_operators?(node) parent = node.parent&.any_block_type? ? node.parent.parent : node.parent return false unless parent logical_operator?(parent) || (parent.send_type? && parent.arguments.any? { |argument| logical_operator?(argument) }) end def call_in_optional_arguments?(node) node.parent&.type?(:optarg, :kwoptarg) end def call_in_single_line_inheritance?(node) node.parent&.class_type? && node.parent.single_line? end # rubocop:disable Metrics/PerceivedComplexity def call_with_ambiguous_arguments?(node) call_with_braced_block?(node) || call_in_argument_with_block?(node) || call_as_argument_or_chain?(node) || call_in_match_pattern?(node) || hash_literal_in_arguments?(node) || ambiguous_range_argument?(node) || node.descendants.any? do |n| n.type?(:forwarded_args, :any_block) || ambiguous_literal?(n) || logical_operator?(n) end end # rubocop:enable Metrics/PerceivedComplexity def call_with_braced_block?(node) node.type?(:call, :super) && node.block_node&.braces? end def call_in_argument_with_block?(node) parent = node.parent&.any_block_type? && node.parent.parent return false unless parent parent.type?(:call, :super, :yield) end def call_as_argument_or_chain?(node) node.parent&.type?(:call, :super, :yield) && !assigned_before?(node.parent, node) end def call_in_match_pattern?(node) return false unless (parent = node.parent) parent.any_match_pattern_type? end def hash_literal_in_arguments?(node) node.arguments.any? do |n| hash_literal?(n) || (n.send_type? && node.descendants.any? { |descendant| hash_literal?(descendant) }) end end def ambiguous_range_argument?(node) return true if (first_arg = node.first_argument)&.range_type? && first_arg.begin.nil? return true if (last_arg = node.last_argument)&.range_type? && last_arg.end.nil? false end def allowed_multiline_call_with_parentheses?(node) cop_config['AllowParenthesesInMultilineCall'] && node.multiline? end def allowed_chained_call_with_parentheses?(node) return false unless cop_config['AllowParenthesesInChaining'] previous = node.descendants.first return false unless previous&.send_type? previous.parenthesized? || allowed_chained_call_with_parentheses?(previous) end def ambiguous_literal?(node) splat?(node) || ternary_if?(node) || regexp_slash_literal?(node) || unary_literal?(node) end def splat?(node) node.type?(:splat, :kwsplat, :block_pass) end def ternary_if?(node) node.if_type? && node.ternary? end def logical_operator?(node) node.operator_keyword? && node.logical_operator? end def hash_literal?(node) node.hash_type? && node.braces? end def regexp_slash_literal?(node) node.regexp_type? && node.loc.begin.source == '/' end def unary_literal?(node) return true if node.numeric_type? && node.sign? node.parent&.send_type? && node.parent.unary_operation? end def assigned_before?(node, target) node.assignment? && node.loc.operator.begin < target.loc.begin end def inside_string_interpolation?(node) node.ancestors.drop_while { |a| !a.begin_type? }.any?(&:dstr_type?) end def assignment_in_condition?(node) parent = node.parent return false unless parent grandparent = parent.parent return false unless grandparent parent.assignment? && (grandparent.conditional? || grandparent.when_type?) end def forwards_anonymous_rest_arguments?(node) return false unless (last_argument = node.last_argument) return true if last_argument.forwarded_restarg_type? last_argument.hash_type? && last_argument.children.any?(&:forwarded_kwrestarg_type?) end end # rubocop:enable Metrics/ModuleLength, Metrics/CyclomaticComplexity end end 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_with_args_parentheses/require_parentheses.rb
lib/rubocop/cop/style/method_call_with_args_parentheses/require_parentheses.rb
# frozen_string_literal: true module RuboCop module Cop module Style class MethodCallWithArgsParentheses # Style require_parentheses module RequireParentheses REQUIRE_MSG = 'Use parentheses for method calls with arguments.' private_constant :REQUIRE_MSG private def require_parentheses(node) return if allowed_method_name?(node.method_name) return if matches_allowed_pattern?(node.method_name) return if eligible_for_parentheses_omission?(node) return unless node.arguments? && !node.parenthesized? add_offense(node, message: REQUIRE_MSG) do |corrector| corrector.replace(args_begin(node), '(') corrector.insert_after(args_end(node), ')') unless args_parenthesized?(node) end end def allowed_method_name?(name) allowed_method?(name) || matches_allowed_pattern?(name) end def eligible_for_parentheses_omission?(node) node.operator_method? || node.setter_method? || ignored_macro?(node) end def included_macros_list cop_config.fetch('IncludedMacros', []).map(&:to_sym) end def included_macro_patterns cop_config.fetch('IncludedMacroPatterns', []) end def matches_included_macro_pattern?(method_name) included_macro_patterns.any? do |pattern| Regexp.new(pattern).match?(method_name.to_s) end end def ignored_macro?(node) cop_config['IgnoreMacros'] && node.macro? && !included_macros_list.include?(node.method_name) && !matches_included_macro_pattern?(node.method_name) end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/bisected_attr_accessor/macro.rb
lib/rubocop/cop/style/bisected_attr_accessor/macro.rb
# frozen_string_literal: true module RuboCop module Cop module Style class BisectedAttrAccessor # Representation of an `attr_reader`, `attr_writer` or `attr` macro # for use by `Style/BisectedAttrAccessor`. # @api private class Macro include VisibilityHelp attr_reader :node, :attrs, :bisection def self.macro?(node) node.method?(:attr_reader) || node.method?(:attr_writer) || node.method?(:attr) end def initialize(node) @node = node @attrs = node.arguments.to_h { |attr| [attr.source, attr] } @bisection = [] end def bisect(*names) @bisection = attrs.slice(*names).values end def attr_names @attr_names ||= attrs.keys end def bisected_names bisection.map(&:source) end def visibility @visibility ||= node_visibility(node) end def reader? node.method?(:attr_reader) || node.method?(:attr) end def writer? node.method?(:attr_writer) end def all_bisected? rest.none? end def rest @rest ||= attr_names - bisected_names 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/metrics/parameter_lists.rb
lib/rubocop/cop/metrics/parameter_lists.rb
# frozen_string_literal: true module RuboCop module Cop module Metrics # Checks for methods with too many parameters. # # The maximum number of parameters is configurable. # Keyword arguments can optionally be excluded from the total count, # as they add less complexity than positional or optional parameters. # # Any number of arguments for `initialize` method inside a block of # `Struct.new` and `Data.define` like this is always allowed: # # [source,ruby] # ---- # Struct.new(:one, :two, :three, :four, :five, keyword_init: true) do # def initialize(one:, two:, three:, four:, five:) # end # end # ---- # # This is because checking the number of arguments of the `initialize` method # does not make sense. # # NOTE: Explicit block argument `&block` is not counted to prevent # erroneous change that is avoided by making block argument implicit. # # @example Max: 3 # # good # def foo(a, b, c = 1) # end # # @example Max: 2 # # bad # def foo(a, b, c = 1) # end # # @example CountKeywordArgs: true (default) # # counts keyword args towards the maximum # # # bad (assuming Max is 3) # def foo(a, b, c, d: 1) # end # # # good (assuming Max is 3) # def foo(a, b, c: 1) # end # # @example CountKeywordArgs: false # # don't count keyword args towards the maximum # # # good (assuming Max is 3) # def foo(a, b, c, d: 1) # end # # This cop also checks for the maximum number of optional parameters. # This can be configured using the `MaxOptionalParameters` config option. # # @example MaxOptionalParameters: 3 (default) # # good # def foo(a = 1, b = 2, c = 3) # end # # @example MaxOptionalParameters: 2 # # bad # def foo(a = 1, b = 2, c = 3) # end # class ParameterLists < Base exclude_limit 'Max' exclude_limit 'MaxOptionalParameters' MSG = 'Avoid parameter lists longer than %<max>d parameters. [%<count>d/%<max>d]' OPTIONAL_PARAMETERS_MSG = 'Method has too many optional parameters. [%<count>d/%<max>d]' NAMED_KEYWORD_TYPES = %i[kwoptarg kwarg].freeze private_constant :NAMED_KEYWORD_TYPES # @!method struct_new_or_data_define_block?(node) def_node_matcher :struct_new_or_data_define_block?, <<~PATTERN (block { (send (const {nil? cbase} :Struct) :new ...) (send (const {nil? cbase} :Data) :define ...) } (args) ...) PATTERN def on_def(node) optargs = node.arguments.select(&:optarg_type?) return if optargs.count <= max_optional_parameters message = format( OPTIONAL_PARAMETERS_MSG, max: max_optional_parameters, count: optargs.count ) add_offense(node, message: message) { self.max_optional_parameters = optargs.count } end alias on_defs on_def def on_args(node) parent = node.parent return if parent.method?(:initialize) && struct_new_or_data_define_block?(parent.parent) count = args_count(node) return unless count > max_params return if argument_to_lambda_or_proc?(node) add_offense(node, message: format(MSG, max: max_params, count: args_count(node))) do self.max = count end end private # @!method argument_to_lambda_or_proc?(node) def_node_matcher :argument_to_lambda_or_proc?, <<~PATTERN ^lambda_or_proc? PATTERN def args_count(node) if count_keyword_args? node.children.count { |a| !a.blockarg_type? } else node.children.count { |a| !NAMED_KEYWORD_TYPES.include?(a.type) && !a.blockarg_type? } end end def max_params cop_config['Max'] end def max_optional_parameters cop_config['MaxOptionalParameters'] end def count_keyword_args? cop_config['CountKeywordArgs'] end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/metrics/collection_literal_length.rb
lib/rubocop/cop/metrics/collection_literal_length.rb
# frozen_string_literal: true module RuboCop module Cop module Metrics # Checks for literals with extremely many entries. This is indicative of # configuration or data that may be better extracted somewhere else, like # a database, fetched from an API, or read from a non-code file (CSV, # JSON, YAML, etc.). # # @example # # bad # # Huge Array literal # [1, 2, '...', 999_999_999] # # # bad # # Huge Hash literal # { 1 => 1, 2 => 2, '...' => '...', 999_999_999 => 999_999_999} # # # bad # # Huge Set "literal" # Set[1, 2, '...', 999_999_999] # # # good # # Reasonably sized Array literal # [1, 2, '...', 10] # # # good # # Reading huge Array from external data source # # File.readlines('numbers.txt', chomp: true).map!(&:to_i) # # # good # # Reasonably sized Hash literal # { 1 => 1, 2 => 2, '...' => '...', 10 => 10} # # # good # # Reading huge Hash from external data source # CSV.foreach('numbers.csv', headers: true).each_with_object({}) do |row, hash| # hash[row["key"].to_i] = row["value"].to_i # end # # # good # # Reasonably sized Set "literal" # Set[1, 2, '...', 10] # # # good # # Reading huge Set from external data source # SomeFramework.config_for(:something)[:numbers].to_set # class CollectionLiteralLength < Base MSG = 'Avoid hard coding large quantities of data in code. ' \ 'Prefer reading the data from an external source.' RESTRICT_ON_SEND = [:[]].freeze # @!method set_const?(node) def_node_matcher :set_const?, <<~PATTERN (const {cbase nil?} :Set) PATTERN def on_array(node) add_offense(node) if node.children.length >= collection_threshold end alias on_hash on_array def on_index(node) return unless set_const?(node.receiver) add_offense(node) if node.arguments.length >= collection_threshold end def on_send(node) on_index(node) if node.method?(:[]) end private def collection_threshold cop_config.fetch('LengthThreshold', Float::INFINITY) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/metrics/perceived_complexity.rb
lib/rubocop/cop/metrics/perceived_complexity.rb
# frozen_string_literal: true module RuboCop module Cop module Metrics # Tries to produce a complexity score that's a measure of the # complexity the reader experiences when looking at a method. For that # reason it considers `when` nodes as something that doesn't add as much # complexity as an `if` or a `&&`. Except if it's one of those special # `case`/`when` constructs where there's no expression after `case`. Then # the cop treats it as an `if`/`elsif`/`elsif`... and lets all the `when` # nodes count. In contrast to the CyclomaticComplexity cop, this cop # considers `else` nodes as adding complexity. # # @example # # def my_method # 1 # if cond # 1 # case var # 2 (0.8 + 4 * 0.2, rounded) # when 1 then func_one # when 2 then func_two # when 3 then func_three # when 4..10 then func_other # end # else # 1 # do_something until a && b # 2 # end # === # end # 7 complexity points class PerceivedComplexity < CyclomaticComplexity MSG = 'Perceived complexity for `%<method>s` is too high. [%<complexity>d/%<max>d]' COUNTED_NODES = (CyclomaticComplexity::COUNTED_NODES - [:when] + [:case]).freeze private def complexity_score_for(node) case node.type when :case # If cond is nil, that means each when has an expression that # evaluates to true or false. It's just an alternative to # if/elsif/elsif... so the when nodes count. nb_branches = node.when_branches.length + (node.else_branch ? 1 : 0) if node.condition.nil? nb_branches else # Otherwise, the case node gets 0.8 complexity points and each # when gets 0.2. ((nb_branches * 0.2) + 0.8).round end when :if node.else? && !node.elsif? ? 2 : 1 else super 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/metrics/block_length.rb
lib/rubocop/cop/metrics/block_length.rb
# frozen_string_literal: true module RuboCop module Cop module Metrics # Checks if the length of a block exceeds some maximum value. # Comment lines can optionally be ignored. # The maximum allowed length is configurable. # The cop can be configured to ignore blocks passed to certain methods. # # You can set constructs you want to fold with `CountAsOne`. # # Available are: 'array', 'hash', 'heredoc', and 'method_call'. # Each construct will be counted as one line regardless of its actual size. # # NOTE: This cop does not apply for `Struct` definitions. # # NOTE: The `ExcludedMethods` configuration is deprecated and only kept # for backwards compatibility. Please use `AllowedMethods` and `AllowedPatterns` # instead. By default, there are no methods to allowed. # # @example CountAsOne: ['array', 'hash', 'heredoc', 'method_call'] # # something do # array = [ # +1 # 1, # 2 # ] # # hash = { # +1 # key: 'value' # } # # msg = <<~HEREDOC # +1 # Heredoc # content. # HEREDOC # # foo( # +1 # 1, # 2 # ) # end # 4 points # class BlockLength < Base include CodeLength include AllowedMethods include AllowedPattern LABEL = 'Block' def on_block(node) return if allowed_method?(node.method_name) || matches_allowed_pattern?(node.method_name) return if method_receiver_excluded?(node) return if node.class_constructor? check_code_length(node) end alias on_numblock on_block alias on_itblock on_block private def method_receiver_excluded?(node) node_receiver = node.receiver&.source&.gsub(/\s+/, '') node_method = String(node.method_name) allowed_methods.any? do |config| next unless config.is_a?(String) receiver, method = config.split('.') unless method method = receiver receiver = node_receiver end method == node_method && receiver == node_receiver end end def cop_label LABEL end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/metrics/block_nesting.rb
lib/rubocop/cop/metrics/block_nesting.rb
# frozen_string_literal: true module RuboCop module Cop module Metrics # Checks for excessive nesting of conditional and looping constructs. # # You can configure if blocks are considered using the `CountBlocks` and `CountModifierForms` # options. When both are set to `false` (the default) blocks and modifier forms are not # counted towards the nesting level. Set them to `true` to include these in the nesting level # calculation as well. # # The maximum level of nesting allowed is configurable. class BlockNesting < Base NESTING_BLOCKS = %i[case case_match if while while_post until until_post for resbody].freeze exclude_limit 'Max' def on_new_investigation return if processed_source.blank? max = cop_config['Max'] check_nesting_level(processed_source.ast, max, 0) end private def check_nesting_level(node, max, current_level) if consider_node?(node) current_level += 1 if count_if_block?(node) if current_level > max self.max = current_level unless part_of_ignored_node?(node) add_offense(node, message: message(max)) { ignore_node(node) } end end end node.each_child_node do |child_node| check_nesting_level(child_node, max, current_level) end end def count_if_block?(node) return true unless node.if_type? return false if node.elsif? return count_modifier_forms? if node.modifier_form? true end def consider_node?(node) return true if NESTING_BLOCKS.include?(node.type) count_blocks? && node.any_block_type? end def message(max) "Avoid more than #{max} levels of block nesting." end def count_blocks? cop_config.fetch('CountBlocks', false) end def count_modifier_forms? cop_config.fetch('CountModifierForms', 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/metrics/module_length.rb
lib/rubocop/cop/metrics/module_length.rb
# frozen_string_literal: true module RuboCop module Cop module Metrics # Checks if the length of a module exceeds some maximum value. # Comment lines can optionally be ignored. # The maximum allowed length is configurable. # # You can set constructs you want to fold with `CountAsOne`. # # Available are: 'array', 'hash', 'heredoc', and 'method_call'. # Each construct will be counted as one line regardless of its actual size. # # @example CountAsOne: ['array', 'hash', 'heredoc', 'method_call'] # # module M # ARRAY = [ # +1 # 1, # 2 # ] # # HASH = { # +1 # key: 'value' # } # # MSG = <<~HEREDOC # +1 # Heredoc # content. # HEREDOC # # foo( # +1 # 1, # 2 # ) # end # 4 points # class ModuleLength < Base include CodeLength def on_module(node) check_code_length(node) end def on_casgn(node) module_definition?(node) { check_code_length(node) } end private # @!method module_definition?(node) def_node_matcher :module_definition?, <<~PATTERN (casgn nil? _ (any_block (send (const {nil? cbase} :Module) :new) ...)) PATTERN def message(length, max_length) format('Module has too many lines. [%<length>d/%<max>d]', length: length, max: max_length) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/metrics/abc_size.rb
lib/rubocop/cop/metrics/abc_size.rb
# frozen_string_literal: true module RuboCop module Cop module Metrics # Checks that the ABC size of methods is not higher than the # configured maximum. The ABC size is based on assignments, branches # (method calls), and conditions. See http://c2.com/cgi/wiki?AbcMetric # and https://en.wikipedia.org/wiki/ABC_Software_Metric. # # Interpreting ABC size: # # * ``<= 17`` satisfactory # * `18..30` unsatisfactory # * `>` 30 dangerous # # You can have repeated "attributes" calls count as a single "branch". # For this purpose, attributes are any method with no argument; no attempt # is meant to distinguish actual `attr_reader` from other methods. # # @example CountRepeatedAttributes: false (default is true) # # # `model` and `current_user`, referenced 3 times each, # # are each counted as only 1 branch each if # # `CountRepeatedAttributes` is set to 'false' # # def search # @posts = model.active.visible_by(current_user) # .search(params[:q]) # @posts = model.some_process(@posts, current_user) # @posts = model.another_process(@posts, current_user) # # render 'pages/search/page' # end # # This cop also takes into account `AllowedMethods` (defaults to `[]`) # And `AllowedPatterns` (defaults to `[]`) # class AbcSize < Base include MethodComplexity MSG = 'Assignment Branch Condition size for `%<method>s` is too high. ' \ '[%<abc_vector>s %<complexity>.4g/%<max>.4g]' private def complexity(node) Utils::AbcSizeCalculator.calculate( node, discount_repeated_attributes: !cop_config['CountRepeatedAttributes'] ) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/metrics/method_length.rb
lib/rubocop/cop/metrics/method_length.rb
# frozen_string_literal: true module RuboCop module Cop module Metrics # Checks if the length of a method exceeds some maximum value. # Comment lines can optionally be allowed. # The maximum allowed length is configurable. # # You can set constructs you want to fold with `CountAsOne`. # # Available are: 'array', 'hash', 'heredoc', and 'method_call'. # Each construct will be counted as one line regardless of its actual size. # # NOTE: The `ExcludedMethods` and `IgnoredMethods` configuration is # deprecated and only kept for backwards compatibility. # Please use `AllowedMethods` and `AllowedPatterns` instead. # By default, there are no methods to allowed. # # @example CountAsOne: ['array', 'hash', 'heredoc', 'method_call'] # # def m # array = [ # +1 # 1, # 2 # ] # # hash = { # +1 # key: 'value' # } # # <<~HEREDOC # +1 # Heredoc # content. # HEREDOC # # foo( # +1 # 1, # 2 # ) # end # 4 points # class MethodLength < Base include CodeLength include AllowedMethods include AllowedPattern LABEL = 'Method' def on_def(node) return if allowed?(node.method_name) check_code_length(node) end alias on_defs on_def def on_block(node) return unless node.method?(:define_method) method_name = node.send_node.first_argument return if method_name.basic_literal? && allowed?(method_name.value) check_code_length(node) end alias on_numblock on_block alias on_itblock on_block private def cop_label LABEL end def allowed?(method_name) allowed_method?(method_name) || matches_allowed_pattern?(method_name) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/metrics/cyclomatic_complexity.rb
lib/rubocop/cop/metrics/cyclomatic_complexity.rb
# frozen_string_literal: true module RuboCop module Cop module Metrics # Checks that the cyclomatic complexity of methods is not higher # than the configured maximum. The cyclomatic complexity is the number of # linearly independent paths through a method. The algorithm counts # decision points and adds one. # # An if statement (or unless or ?:) increases the complexity by one. An # else branch does not, since it doesn't add a decision point. The && # operator (or keyword and) can be converted to a nested if statement, # and ||/or is shorthand for a sequence of ifs, so they also add one. # Loops can be said to have an exit condition, so they add one. # Blocks that are calls to builtin iteration methods # (e.g. `ary.map{...}`) also add one, others are ignored. # # @example # # def each_child_node(*types) # count begins: 1 # unless block_given? # unless: +1 # return to_enum(__method__, *types) # end # # children.each do |child| # each{}: +1 # next unless child.is_a?(Node) # unless: +1 # # yield child if types.empty? || # if: +1, ||: +1 # types.include?(child.type) # end # # self # end # total: 6 class CyclomaticComplexity < Base include MethodComplexity include Utils::IteratingBlock MSG = 'Cyclomatic complexity for `%<method>s` is too high. [%<complexity>d/%<max>d]' COUNTED_NODES = %i[if while until for csend block block_pass rescue when in_pattern and or or_asgn and_asgn].freeze private def complexity_score_for(node) return 0 if iterating_block?(node) == false return 0 if node.csend_type? && discount_for_repeated_csend?(node) 1 end def count_block?(block) KNOWN_ITERATING_METHODS.include? block.method_name end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/metrics/class_length.rb
lib/rubocop/cop/metrics/class_length.rb
# frozen_string_literal: true module RuboCop module Cop module Metrics # Checks if the length of a class exceeds some maximum value. # Comment lines can optionally be ignored. # The maximum allowed length is configurable. # # You can set constructs you want to fold with `CountAsOne`. # # Available are: 'array', 'hash', 'heredoc', and 'method_call'. # Each construct will be counted as one line regardless of its actual size. # # NOTE: This cop also applies for `Struct` definitions. # # @example CountAsOne: ['array', 'hash', 'heredoc', 'method_call'] # # class Foo # ARRAY = [ # +1 # 1, # 2 # ] # # HASH = { # +1 # key: 'value' # } # # MSG = <<~HEREDOC # +1 # Heredoc # content. # HEREDOC # # foo( # +1 # 1, # 2 # ) # end # 4 points # class ClassLength < Base include CodeLength def on_class(node) check_code_length(node) end def on_sclass(node) return if node.each_ancestor(:class).any? on_class(node) end def on_casgn(node) block_node = node.expression || find_expression_within_parent(node.parent) return unless block_node.respond_to?(:class_definition?) && block_node.class_definition? check_code_length(block_node) end private def message(length, max_length) format('Class has too many lines. [%<length>d/%<max>d]', length: length, max: max_length) end def find_expression_within_parent(parent) if parent&.assignment? parent.expression elsif parent&.parent&.masgn_type? parent.parent.expression 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/metrics/utils/code_length_calculator.rb
lib/rubocop/cop/metrics/utils/code_length_calculator.rb
# frozen_string_literal: true module RuboCop module Cop module Metrics module Utils # Helps to calculate code length for the provided node. class CodeLengthCalculator extend NodePattern::Macros include Util FOLDABLE_TYPES = %i[array hash heredoc method_call].freeze CLASSLIKE_TYPES = %i[class module].freeze private_constant :FOLDABLE_TYPES, :CLASSLIKE_TYPES def initialize(node, processed_source, count_comments: false, foldable_types: []) @node = node @processed_source = processed_source @count_comments = count_comments @foldable_checks = build_foldable_checks(foldable_types) @foldable_types = normalize_foldable_types(foldable_types) end def calculate length = code_length(@node) return length if @foldable_types.empty? each_top_level_descendant(@node, @foldable_types) do |descendant| next unless foldable_node?(descendant) descendant_length = code_length(descendant) length = length - descendant_length + 1 # Subtract length of opening and closing brace if method argument omits hash braces. length -= omit_length(descendant) if descendant.hash_type? && !descendant.braces? end length end private def build_foldable_checks(types) # rubocop:disable Metrics/MethodLength types.map do |type| case type when :array lambda(&:array_type?) when :hash lambda(&:hash_type?) when :heredoc ->(node) { heredoc_node?(node) } when :method_call lambda(&:call_type?) else raise Warning, "Unknown foldable type: #{type.inspect}. " \ "Valid foldable types are: #{FOLDABLE_TYPES.join(', ')}." end end end def normalize_foldable_types(types) types.push(:str, :dstr) if types.delete(:heredoc) types.push(:send, :csend) if types.delete(:method_call) types end def code_length(node) # rubocop:disable Metrics/MethodLength if classlike_node?(node) classlike_code_length(node) elsif heredoc_node?(node) heredoc_length(node) else body = extract_body(node) return 0 unless body source = if node_with_heredoc?(body) source_from_node_with_heredoc(body) else body.source.lines end source.count { |line| !irrelevant_line?(line) } end end def heredoc_node?(node) node.respond_to?(:heredoc?) && node.heredoc? end def classlike_code_length(node) return 0 if namespace_module?(node) body_line_numbers = line_range(node).to_a[1...-1] target_line_numbers = body_line_numbers - line_numbers_of_inner_nodes(node, :module, :class) target_line_numbers.reduce(0) do |length, line_number| source_line = @processed_source[line_number] next length if irrelevant_line?(source_line) length + 1 end end def namespace_module?(node) classlike_node?(node.body) end def line_numbers_of_inner_nodes(node, *types) line_numbers = Set.new node.each_descendant(*types) do |inner_node| line_range = line_range(inner_node) line_numbers.merge(line_range) end line_numbers.to_a end def heredoc_length(node) lines = node.loc.heredoc_body.source.lines lines.count { |line| !irrelevant_line?(line) } + 2 end def each_top_level_descendant(node, types, &block) node.each_child_node do |child| next if classlike_node?(child) if types.include?(child.type) yield child else each_top_level_descendant(child, types, &block) end end end def classlike_node?(node) CLASSLIKE_TYPES.include?(node&.type) end def foldable_node?(node) @foldable_checks.any? { |check| check.call(node) } end def extract_body(node) case node.type when :class, :module, :sclass, :block, :numblock, :itblock, :def, :defs node.body when :casgn extract_body(node.expression) else node end end # Returns true for lines that shall not be included in the count. def irrelevant_line?(source_line) source_line.blank? || (!count_comments? && comment_line?(source_line)) end def count_comments? @count_comments end def omit_length(descendant) parent = descendant.parent return 0 if another_args?(parent) return 0 unless parenthesized?(parent) [ parent.loc.begin.end_pos != descendant.source_range.begin_pos, parent.loc.end.begin_pos != descendant.source_range.end_pos ].count(true) end def parenthesized?(node) node.call_type? && node.parenthesized? end def another_args?(node) node.call_type? && node.arguments.count > 1 end def node_with_heredoc?(node) node.each_descendant(:str, :dstr).any? { |descendant| heredoc_node?(descendant) } end def source_from_node_with_heredoc(node) last_line = -1 node.each_descendant do |descendant| next unless descendant.source descendant_last_line = if heredoc_node?(descendant) descendant.loc.heredoc_end.line else descendant.last_line end last_line = [last_line, descendant_last_line].max end @processed_source[(node.first_line - 1)..(last_line - 1)] end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/metrics/utils/iterating_block.rb
lib/rubocop/cop/metrics/utils/iterating_block.rb
# frozen_string_literal: true module RuboCop module Cop module Metrics module Utils # Used to identify iterating blocks like `.map{}` and `.map(&:...)` module IteratingBlock enumerable = %i[ all? any? chain chunk chunk_while collect collect_concat count cycle detect drop drop_while each each_cons each_entry each_slice each_with_index each_with_object entries filter filter_map find find_all find_index flat_map grep grep_v group_by inject lazy map max max_by min min_by minmax minmax_by none? one? partition reduce reject reverse_each select slice_after slice_before slice_when sort sort_by sum take take_while tally to_h uniq zip ] enumerator = %i[with_index with_object] array = %i[ bsearch bsearch_index collect! combination d_permutation delete_if each_index keep_if map! permutation product reject! repeat repeated_combination select! sort sort! sort_by sort_by ] hash = %i[ each_key each_pair each_value fetch fetch_values has_key? merge merge! transform_keys transform_keys! transform_values transform_values! ] KNOWN_ITERATING_METHODS = (Set.new(enumerable) + enumerator + array + hash).freeze # Returns the name of the method called with a block # if node is a block node, or a block-pass node. def block_method_name(node) case node.type when :block node.method_name when :block_pass node.parent.method_name end end # Returns true iff name is a known iterating type (e.g. :each, :transform_values) def iterating_method?(name) KNOWN_ITERATING_METHODS.include? name end # Returns nil if node is neither a block node or a block-pass node. # Otherwise returns true/false if method call is a known iterating call def iterating_block?(node) name = block_method_name(node) name && iterating_method?(name) end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/metrics/utils/repeated_csend_discount.rb
lib/rubocop/cop/metrics/utils/repeated_csend_discount.rb
# frozen_string_literal: true module RuboCop module Cop module Metrics module Utils # @api private # # Identifies repetitions `&.` on the same variable: # # my_var&.foo # my_var&.bar # => repeated # my_var = baz # => reset # my_var&.qux # => not repeated module RepeatedCsendDiscount def reset_repeated_csend @repeated_csend = {} end def discount_for_repeated_csend?(csend_node) receiver = csend_node.receiver return false unless receiver.lvar_type? var_name = receiver.children.first seen = @repeated_csend.fetch(var_name) do @repeated_csend[var_name] = csend_node return false end !seen.equal?(csend_node) end def reset_on_lvasgn(node) var_name = node.children.first @repeated_csend.delete(var_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/metrics/utils/repeated_attribute_discount.rb
lib/rubocop/cop/metrics/utils/repeated_attribute_discount.rb
# frozen_string_literal: true module RuboCop module Cop module Metrics module Utils # @api private # # Identifies repetitions `{c}send` calls with no arguments: # # foo.bar # foo.bar # => repeated # foo.bar.baz.qux # => inner send repeated # foo.bar.baz.other # => both inner send repeated # foo.bar(2) # => not repeated # # It also invalidates sequences if a receiver is reassigned: # # xx.foo.bar # xx.foo.baz # => inner send repeated # self.xx = any # => invalidates everything so far # xx.foo.baz # => no repetition # self.xx.foo.baz # => all repeated # module RepeatedAttributeDiscount extend NodePattern::Macros include RuboCop::AST::Sexp VAR_SETTER_TO_GETTER = { lvasgn: :lvar, ivasgn: :ivar, cvasgn: :cvar, gvasgn: :gvar }.freeze # Plug into the calculator def initialize(node, discount_repeated_attributes: false) super(node) return unless discount_repeated_attributes self_attributes = {} # Share hash for `(send nil? :foo)` and `(send (self) :foo)` @known_attributes = { s(:self) => self_attributes, nil => self_attributes } # example after running `obj = foo.bar; obj.baz.qux` # { nil => {foo: {bar: {}}}, # s(self) => same hash ^, # s(:lvar, :obj) => {baz: {qux: {}}} # } end def discount_repeated_attributes? defined?(@known_attributes) end def evaluate_branch_nodes(node) return if discount_repeated_attributes? && discount_repeated_attribute?(node) super end def calculate_node(node) update_repeated_attribute(node) if discount_repeated_attributes? super end private # @!method attribute_call?(node) def_node_matcher :attribute_call?, <<~PATTERN (call _receiver _method # and no parameters ) PATTERN def discount_repeated_attribute?(send_node) return false unless attribute_call?(send_node) repeated = true find_attributes(send_node) do |hash, lookup| return false if hash.nil? repeated = false hash[lookup] = {} end repeated end def update_repeated_attribute(node) return unless (receiver, method = setter_to_getter(node)) calls = find_attributes(receiver) { return } if method # e.g. `self.foo = 42` calls.delete(method) else # e.g. `var = 42` calls.clear end end # @!method root_node?(node) def_node_matcher :root_node?, <<~PATTERN { nil? | self # e.g. receiver of `my_method` or `self.my_attr` | lvar | ivar | cvar | gvar # e.g. receiver of `var.my_method` | const } # e.g. receiver of `MyConst.foo.bar` PATTERN # Returns the "known_attributes" for the `node` by walking the receiver tree # If at any step the subdirectory does not exist, it is yielded with the # associated key (method_name) # If the node is not a series of `(c)send` calls with no arguments, # then `nil` is yielded def find_attributes(node, &block) if attribute_call?(node) calls = find_attributes(node.receiver, &block) value = node.method_name elsif root_node?(node) calls = @known_attributes value = node else return yield nil end calls.fetch(value) { yield [calls, value] } end # @returns `[receiver, method | nil]` for the given setter `node` # or `nil` if it is not a setter. def setter_to_getter(node) if (type = VAR_SETTER_TO_GETTER[node.type]) # (lvasgn :my_var (int 42)) => [(lvar my_var), nil] [s(type, node.children.first), nil] elsif node.shorthand_asgn? # (or-asgn (send _receiver :foo) _value) # (or-asgn (send _receiver :foo) _value) => [_receiver, :foo] node.children.first.children elsif node.respond_to?(:setter_method?) && node.setter_method? # (send _receiver :foo= (int 42) ) => [_receiver, :foo] method_name = node.method_name[0...-1].to_sym [node.receiver, method_name] 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/metrics/utils/abc_size_calculator.rb
lib/rubocop/cop/metrics/utils/abc_size_calculator.rb
# frozen_string_literal: true module RuboCop module Cop module Metrics module Utils # > ABC is .. a software size metric .. computed by counting the number # > of assignments, branches and conditions for a section of code. # > http://c2.com/cgi/wiki?AbcMetric # # We separate the *calculator* from the *cop* so that the calculation, # the formula itself, is easier to test. class AbcSizeCalculator include IteratingBlock include RepeatedCsendDiscount prepend RepeatedAttributeDiscount # > Branch -- an explicit forward program branch out of scope -- a # > function call, class method call .. # > http://c2.com/cgi/wiki?AbcMetric BRANCH_NODES = %i[send csend yield].freeze # > Condition -- a logical/Boolean test, == != <= >= < > else case # > default try catch ? and unary conditionals. # > http://c2.com/cgi/wiki?AbcMetric CONDITION_NODES = CyclomaticComplexity::COUNTED_NODES.freeze private_constant :BRANCH_NODES, :CONDITION_NODES def self.calculate(node, discount_repeated_attributes: false) new(node, discount_repeated_attributes: discount_repeated_attributes).calculate end def initialize(node) @assignment = 0 @branch = 0 @condition = 0 @node = node reset_repeated_csend end def calculate visit_depth_last(@node) { |child| calculate_node(child) } [ Math.sqrt((@assignment**2) + (@branch**2) + (@condition**2)).round(2), "<#{@assignment}, #{@branch}, #{@condition}>" ] end def evaluate_branch_nodes(node) if node.comparison_method? @condition += 1 else @branch += 1 @condition += 1 if node.csend_type? && !discount_for_repeated_csend?(node) end end def evaluate_condition_node(node) @condition += 1 if else_branch?(node) @condition += 1 end def else_branch?(node) %i[case if].include?(node.type) && node.else? && node.loc.else.is?('else') end private def visit_depth_last(node, &block) node.each_child_node { |child| visit_depth_last(child, &block) } yield node end def calculate_node(node) @assignment += 1 if assignment?(node) if branch?(node) evaluate_branch_nodes(node) elsif condition?(node) evaluate_condition_node(node) end end def assignment?(node) if node.masgn_type? || node.shorthand_asgn? compound_assignment(node) return false end node.for_type? || (node.respond_to?(:setter_method?) && node.setter_method?) || simple_assignment?(node) || argument?(node) end def compound_assignment(node) # Methods setter cannot be detected for multiple assignments # and shorthand assigns, so we'll count them here instead children = node.masgn_type? ? node.assignments : node.children will_be_miscounted = children.count do |child| child.respond_to?(:setter_method?) && !child.setter_method? end @assignment += will_be_miscounted end def simple_assignment?(node) if !node.equals_asgn? false elsif node.lvasgn_type? reset_on_lvasgn(node) capturing_variable?(node.children.first) else true end end def capturing_variable?(name) name && !name.start_with?('_') end def branch?(node) BRANCH_NODES.include?(node.type) end def argument?(node) node.argument_type? && capturing_variable?(node.children.first) end def condition?(node) return false if iterating_block?(node) == false CONDITION_NODES.include?(node.type) end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/internal_affairs/cop_description.rb
lib/rubocop/cop/internal_affairs/cop_description.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Enforces the cop description to start with a word such as verb. # # @example # # bad # # This cop checks .... # class SomeCop < Base # .... # end # # # bad # # # # Checks ... # class SomeCop < Base # ... # end # # # good # # Checks ... # class SomeCop < Base # ... # end # class CopDescription < Base extend AutoCorrector MSG_STARTS_WITH_WRONG_WORD = 'Description should be started with %<suggestion>s instead of `This cop ...`.' MSG_STARTS_WITH_EMPTY_COMMENT_LINE = 'Description should not start with an empty comment line.' SPECIAL_WORDS = %w[is can could should will would must may].freeze COP_DESC_OFFENSE_REGEX = /^\s+# This cop (?<special>#{SPECIAL_WORDS.join('|')})?\s*(?<word>.+?) .*/.freeze REPLACEMENT_REGEX = /^\s+# This cop (#{SPECIAL_WORDS.join('|')})?\s*(.+?) /.freeze EMPTY_COMMENT_LINE_REGEX = /\A\s*#\s*\n\z/.freeze def on_class(node) return unless (module_node = node.parent) && node.parent_class description_beginning = first_comment_line(module_node) return unless description_beginning if description_beginning.match?(EMPTY_COMMENT_LINE_REGEX) register_offense_for_empty_comment_line(module_node, description_beginning) else start_with_subject = description_beginning.match(COP_DESC_OFFENSE_REGEX) return unless start_with_subject register_offense_for_wrong_word(module_node, description_beginning, start_with_subject) end end private def register_offense_for_empty_comment_line(module_node, description_beginning) range = range(module_node, description_beginning) add_offense(range, message: MSG_STARTS_WITH_EMPTY_COMMENT_LINE) do |corrector| corrector.remove(range) end end def register_offense_for_wrong_word(module_node, description_beginning, start_with_subject) suggestion = start_with_subject['word']&.capitalize range = range(module_node, description_beginning) suggestion_for_message = suggestion_for_message(suggestion, start_with_subject) message = format(MSG_STARTS_WITH_WRONG_WORD, suggestion: suggestion_for_message) add_offense(range, message: message) do |corrector| if suggestion && !start_with_subject['special'] replace_with_suggestion(corrector, range, suggestion, description_beginning) end end end def replace_with_suggestion(corrector, range, suggestion, description_beginning) replacement = description_beginning.gsub(REPLACEMENT_REGEX, "#{suggestion} ") corrector.replace(range, replacement) end def range(node, comment_line) source_buffer = node.source_range.source_buffer begin_pos = node.source_range.begin_pos begin_pos += comment_index(node, comment_line) end_pos = begin_pos + comment_body(comment_line).length Parser::Source::Range.new(source_buffer, begin_pos, end_pos) end def suggestion_for_message(suggestion, match_data) if suggestion && !match_data['special'] "`#{suggestion}`" else 'a word such as verb' end end def first_comment_line(node) node.source.lines.find { |line| comment_line?(line) } end def comment_body(comment_line) comment_line.gsub(/^\s*# /, '') end def comment_index(node, comment_line) body = comment_body(comment_line) node.source.index(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/internal_affairs/lambda_or_proc.rb
lib/rubocop/cop/internal_affairs/lambda_or_proc.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Enforces the use of `node.lambda_or_proc?` instead of `node.lambda? || node.proc?`. # # @example # # bad # node.lambda? || node.proc? # node.proc? || node.lambda? # # # good # node.lambda_or_proc? # class LambdaOrProc < Base extend AutoCorrector MSG = 'Use `%<prefer>s`.' # @!method lambda_or_proc(node) def_node_matcher :lambda_or_proc, <<~PATTERN { (or $(send _node :lambda?) $(send _node :proc?)) (or $(send _node :proc?) $(send _node :lambda?)) (or (or _ $(send _node :lambda?)) $(send _node :proc?)) (or (or _ $(send _node :proc?)) $(send _node :lambda?)) } PATTERN def on_or(node) return unless (lhs, rhs = lambda_or_proc(node)) offense = lhs.receiver.source_range.join(rhs.source_range.end) prefer = "#{lhs.receiver.source}.lambda_or_proc?" add_offense(offense, message: format(MSG, prefer: prefer)) do |corrector| corrector.replace(offense, prefer) 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/internal_affairs/useless_message_assertion.rb
lib/rubocop/cop/internal_affairs/useless_message_assertion.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks that cops are not tested using `described_class::MSG`. # # @example # # # bad # expect(cop.messages).to eq([described_class::MSG]) # # # good # expect(cop.messages).to eq(['Do not write bad code like that.']) # class UselessMessageAssertion < Base MSG = 'Do not specify cop behavior using `described_class::MSG`.' # @!method described_class_msg(node) def_node_search :described_class_msg, <<~PATTERN (const (send nil? :described_class) :MSG) PATTERN # @!method rspec_expectation_on_msg?(node) def_node_matcher :rspec_expectation_on_msg?, <<~PATTERN (send (send nil? :expect #contains_described_class_msg?) :to ...) PATTERN def on_new_investigation return if processed_source.blank? assertions_using_described_class_msg.each { |node| add_offense(node) } end private def contains_described_class_msg?(node) described_class_msg(node).any? end def assertions_using_described_class_msg described_class_msg(processed_source.ast).reject do |node| node.ancestors.any? { |ancestor| rspec_expectation_on_msg?(ancestor) } 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/internal_affairs/numblock_handler.rb
lib/rubocop/cop/internal_affairs/numblock_handler.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks for missing `numblock` handlers. The blocks with numbered # arguments introduced in Ruby 2.7 are parsed with a node type of # `numblock` instead of block. Cops that define `block` handlers # need to define `numblock` handlers or disable this cope for them. # # @example # # # bad # class BlockRelatedCop < Base # def on_block(node) # end # end # # # good # class BlockRelatedCop < Base # def on_block(node) # end # # alias on_numblock on_block # end # # class BlockRelatedCop < Base # def on_block(node) # end # # alias_method :on_numblock, :on_block # end # # class BlockRelatedCop < Base # def on_block(node) # end # # def on_numblock(node) # end # end class NumblockHandler < Base MSG = 'Define on_numblock to handle blocks with numbered arguments.' def on_def(node) return unless block_handler?(node) return unless node.parent add_offense(node) unless numblock_handler?(node.parent) end private # @!method block_handler?(node) def_node_matcher :block_handler?, <<~PATTERN (def :on_block (args (arg :node)) ...) PATTERN # @!method numblock_handler?(node) def_node_matcher :numblock_handler?, <<~PATTERN { `(def :on_numblock (args (arg :node)) ...) `(alias (sym :on_numblock) (sym :on_block)) `(send nil? :alias_method (sym :on_numblock) (sym :on_block)) } 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/internal_affairs/example_description.rb
lib/rubocop/cop/internal_affairs/example_description.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks that RSpec examples that use `expects_offense` # or `expects_no_offenses` do not have conflicting # descriptions. # # @example # # bad # it 'does not register an offense' do # expect_offense('...') # end # # it 'registers an offense' do # expect_no_offenses('...') # end # # # good # it 'registers an offense' do # expect_offense('...') # end # # it 'does not register an offense' do # expect_no_offenses('...') # end class ExampleDescription < Base extend AutoCorrector MSG = 'Description does not match use of `%<method_name>s`.' RESTRICT_ON_SEND = %i[ expect_offense expect_no_offenses expect_correction expect_no_corrections ].to_set.freeze EXPECT_NO_OFFENSES_DESCRIPTION_MAPPING = { /\A(adds|registers|reports|finds) (an? )?offense/ => 'does not register an offense', /\A(flags|handles|works)\b/ => 'does not register' }.freeze EXPECT_OFFENSE_DESCRIPTION_MAPPING = { /\A(does not|doesn't) (register|find|flag|report)/ => 'registers', /\A(does not|doesn't) add (a|an|any )?offense/ => 'registers an offense', /\Aregisters no offense/ => 'registers an offense', /\A(accepts|allows|register)\b/ => 'registers' }.freeze EXPECT_NO_CORRECTIONS_DESCRIPTION_MAPPING = { /\A(auto[- ]?)?corrects?/ => 'does not correct', /\band (auto[- ]?)?corrects/ => 'but does not correct' }.freeze EXPECT_CORRECTION_DESCRIPTION_MAPPING = { /\bbut (does not|doesn't) (auto[- ]?)?correct/ => 'and autocorrects', /\b(does not|doesn't) (auto[- ]?)?correct/ => 'autocorrects' }.freeze EXAMPLE_DESCRIPTION_MAPPING = { expect_no_offenses: EXPECT_NO_OFFENSES_DESCRIPTION_MAPPING, expect_offense: EXPECT_OFFENSE_DESCRIPTION_MAPPING, expect_no_corrections: EXPECT_NO_CORRECTIONS_DESCRIPTION_MAPPING, expect_correction: EXPECT_CORRECTION_DESCRIPTION_MAPPING }.freeze # @!method offense_example(node) def_node_matcher :offense_example, <<~PATTERN (block (send _ {:it :specify :xit :fit} $...) _args `(send nil? %RESTRICT_ON_SEND ...) ) PATTERN def on_send(node) parent = node.each_ancestor(:block).first return unless parent && (current_description = offense_example(parent)&.first) method_name = node.method_name message = format(MSG, method_name: method_name) description_map = EXAMPLE_DESCRIPTION_MAPPING[method_name] check_description(current_description, description_map, message) end private def check_description(current_description, description_map, message) description_text = string_contents(current_description) return unless (new_description = correct_description(description_text, description_map)) quote = current_description.dstr_type? ? '"' : "'" add_offense(current_description, message: message) do |corrector| corrector.replace(current_description, "#{quote}#{new_description}#{quote}") end end def correct_description(current_description, description_map) description_map.each do |incorrect_description_pattern, preferred_description| if incorrect_description_pattern.match?(current_description) return current_description.gsub(incorrect_description_pattern, preferred_description) end end nil end def string_contents(node) node.type?(:str, :dstr) ? node.value : 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/internal_affairs/operator_keyword.rb
lib/rubocop/cop/internal_affairs/operator_keyword.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Enforces the use of `node.operator_keyword?` instead of `node.and_type? || node.or_type?`. # # @example # # bad # node.and_type? || node.or_type? # node.or_type? || node.and_type? # # # good # node.operator_keyword? # class OperatorKeyword < Base extend AutoCorrector MSG = 'Use `%<prefer>s`.' PREFERRED_METHOD = 'operator_keyword?' # @!method and_or_type(node) def_node_matcher :and_or_type, <<~PATTERN { (or $(send _node :and_type?) $(send _node :or_type?)) (or $(send _node :or_type?) $(send _node :and_type?)) (or (or _ $(send _node :and_type?)) $(send _node :or_type?)) (or (or _ $(send _node :or_type?)) $(send _node :and_type?)) } PATTERN def on_or(node) return unless (lhs, rhs = and_or_type(node)) begin_range = lhs.receiver&.source_range || lhs.loc.selector offense = begin_range.join(rhs.source_range.end) prefer = lhs.receiver ? "#{lhs.receiver.source}.#{PREFERRED_METHOD}" : PREFERRED_METHOD add_offense(offense, message: format(MSG, prefer: prefer)) do |corrector| corrector.replace(offense, prefer) 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/internal_affairs/example_heredoc_delimiter.rb
lib/rubocop/cop/internal_affairs/example_heredoc_delimiter.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Use `RUBY` for heredoc delimiter of example Ruby code. # # Some editors may apply better syntax highlighting by using appropriate language names for # the delimiter. # # @example # # bad # expect_offense(<<~CODE) # example_ruby_code # CODE # # # good # expect_offense(<<~RUBY) # example_ruby_code # RUBY class ExampleHeredocDelimiter < Base extend AutoCorrector EXPECTED_HEREDOC_DELIMITER = 'RUBY' MSG = 'Use `RUBY` for heredoc delimiter of example Ruby code.' RESTRICT_ON_SEND = %i[ expect_correction expect_no_corrections expect_no_offenses expect_offense ].freeze # @param node [RuboCop::AST::SendNode] # @return [void] def on_send(node) heredoc_node = heredoc_node_from(node) return unless heredoc_node return if expected_heredoc_delimiter?(heredoc_node) return if expected_heredoc_delimiter_in_body?(heredoc_node) add_offense(heredoc_node) do |corrector| autocorrect(corrector, heredoc_node) end end private # @param corrector [RuboCop::Cop::Corrector] # @param node [RuboCop::AST::StrNode] # @return [void] def autocorrect(corrector, node) [ heredoc_opening_delimiter_range_from(node), heredoc_closing_delimiter_range_from(node) ].each do |range| corrector.replace(range, EXPECTED_HEREDOC_DELIMITER) end end # @param node [RuboCop::AST::StrNode] # @return [Boolean] def expected_heredoc_delimiter_in_body?(node) node.location.heredoc_body.source.lines.any? do |line| line.strip == EXPECTED_HEREDOC_DELIMITER end end # @param node [RuboCop::AST::StrNode] # @return [Boolean] def expected_heredoc_delimiter?(node) heredoc_delimiter_string_from(node) == EXPECTED_HEREDOC_DELIMITER end # @param node [RuboCop::AST::SendNode] # @return [RuboCop::AST::StrNode, nil] def heredoc_node_from(node) return unless node.first_argument.respond_to?(:heredoc?) return unless node.first_argument.heredoc? node.first_argument end # @param node [RuboCop::AST::StrNode] # @return [String] def heredoc_delimiter_string_from(node) node.source[Heredoc::OPENING_DELIMITER, 2] end # @param node [RuboCop::AST::StrNode] # @return [Parser::Source::Range] def heredoc_opening_delimiter_range_from(node) match_data = node.source.match(Heredoc::OPENING_DELIMITER) node.source_range.begin.adjust( begin_pos: match_data.begin(2), end_pos: match_data.end(2) ) end # @param node [RuboCop::AST::StrNode] # @return [Parser::Source::Range] def heredoc_closing_delimiter_range_from(node) node.location.heredoc_end.end.adjust( begin_pos: -heredoc_delimiter_string_from(node).length ) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/internal_affairs/cop_enabled.rb
lib/rubocop/cop/internal_affairs/cop_enabled.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Use `config.cop_enabled?('Department/CopName')` instead of # traversing the config hash. # # @example # # `for_cop(...)['Enabled'] # # # bad # config.for_cop('Department/CopName')['Enabled'] # # # good # config.cop_enabled?('Department/CopName') # # @example # # when keeping a cop's config in a local and then checking the `Enabled` key # # # bad # cop_config = config.for_cop('Department/CopName') # cop_config['Enabled'] && cop_config['Foo'] # # # good # config.for_enabled_cop('Department/CopName')['Foo'] # class CopEnabled < Base extend AutoCorrector MSG = 'Use `%<replacement>s` instead of `%<source>s`.' MSG_HASH = 'Consider replacing uses of `%<hash_name>s` with `config.for_enabled_cop`.' RESTRICT_ON_SEND = [:[]].freeze # @!method for_cop_enabled?(node) def_node_matcher :for_cop_enabled?, <<~PATTERN (send (send ${(send nil? :config) (ivar :@config)} :for_cop $(str _)) :[] (str "Enabled")) PATTERN # @!method config_enabled_lookup?(node) def_node_matcher :config_enabled_lookup?, <<~PATTERN (send {(lvar $_) (ivar $_) (send nil? $_)} :[] (str "Enabled")) PATTERN def on_send(node) if (config_var, cop_name = for_cop_enabled?(node)) handle_for_cop(node, config_var, cop_name) elsif (config_var = config_enabled_lookup?(node)) return unless config_var.end_with?('_config') handle_hash(node, config_var) end end private def handle_for_cop(node, config_var, cop_name) source = node.source quote = cop_name.loc.begin.source cop_name = cop_name.value replacement = "#{config_var.source}.cop_enabled?(#{quote}#{cop_name}#{quote})" message = format(MSG, source: source, replacement: replacement) add_offense(node, message: message) do |corrector| corrector.replace(node, replacement) end end def handle_hash(node, config_var) message = format(MSG_HASH, hash_name: config_var) add_offense(node, message: message) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/internal_affairs/node_pattern_groups.rb
lib/rubocop/cop/internal_affairs/node_pattern_groups.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Use node groups (`any_block`, `argument`, `boolean`, `call`, `numeric`, `range`) # in node patterns instead of a union (`{ ... }`) of the member types of the group. # # @example # # bad # def_node_matcher :my_matcher, <<~PATTERN # {send csend} # PATTERN # # # good # def_node_matcher :my_matcher, <<~PATTERN # call # PATTERN # class NodePatternGroups < Base require_relative 'node_pattern_groups/ast_processor' require_relative 'node_pattern_groups/ast_walker' include RangeHelp extend AutoCorrector MSG = 'Replace `%<names>s` in node pattern union with `%<replacement>s`.' RESTRICT_ON_SEND = %i[def_node_matcher def_node_search].freeze NODE_GROUPS = { any_block: %i[block numblock itblock], any_def: %i[def defs], any_match_pattern: %i[match_pattern match_pattern_p], any_str: %i[str dstr xstr], any_sym: %i[sym dsym], argument: %i[arg optarg restarg kwarg kwoptarg kwrestarg blockarg forward_arg shadowarg], boolean: %i[true false], call: %i[send csend], numeric: %i[int float rational complex], range: %i[irange erange] }.freeze def on_new_investigation @walker = ASTWalker.new end # When a Node Pattern matcher is defined, investigate the pattern string to search # for node types that can be replaced with a node group (ie. `{send csend}` can be # replaced with `call`). # # In order to deal with node patterns in an efficient and non-brittle way, we will # parse the Node Pattern string given to this `send` node using # `RuboCop::AST::NodePattern::Parser::WithMeta`. `WithMeta` is important! We need # location information so that we can calculate the exact locations within the # pattern to report and correct. # # The resulting AST is processed by `NodePatternGroups::ASTProccessor` which rewrites # the AST slightly to handle node sequences (ie. `(send _ :foo ...)`). See the # documentation of that class for more details. # # Then the processed AST is walked, and metadata is collected for node types that # can be replaced with a node group. # # Finally, the metadata is used to register offenses and make corrections, using # the location data captured earlier. The ranges captured while parsing the Node # Pattern are offset using the string argument to this `send` node to ensure # that offenses are registered at the correct location. # def on_send(node) pattern_node = node.arguments[1] return unless acceptable_heredoc?(pattern_node) || pattern_node.str_type? process_pattern(pattern_node) return if node_groups.nil? apply_range_offsets(pattern_node) node_groups.each_with_index do |group, index| register_offense(group, index) end end def after_send(_) @walker.reset! end private def node_groups @walker.node_groups end # rubocop:disable InternalAffairs/RedundantSourceRange -- `node` here is a NodePatternNode def register_offense(group, index) replacement = replacement(group) message = format( MSG, names: group.node_types.map { |node| node.source_range.source }.join('`, `'), replacement: replacement ) add_offense(group.offense_range, message: message) do |corrector| # Only correct one group at a time to avoid clobbering. # Other offenses will be corrected in the subsequent iterations of the # correction loop. next if index.positive? if group.other_elements? replace_types_with_node_group(corrector, group, replacement) else replace_union(corrector, group, replacement) end end end def replacement(group) if group.sequence? # If the original nodes were in a sequence (ie. wrapped in parentheses), # use it to generate the resulting NodePattern syntax. first_node_type = group.node_types.first template = first_node_type.source_range.source template.sub(first_node_type.child.to_s, group.name.to_s) else group.name end end # rubocop:enable InternalAffairs/RedundantSourceRange # When there are other elements in the union, remove the node types that can be replaced. def replace_types_with_node_group(corrector, group, replacement) ranges = group.ranges.map.with_index do |range, index| # Collect whitespace and pipes preceding each element range_for_full_union_element(range, index, group.pipe) end ranges.each { |range| corrector.remove(range) } corrector.insert_before(ranges.first, replacement) end # If the union contains pipes, remove the pipe character as well. # Unfortunately we don't get the location of the pipe in `loc` object, so we have # to find it. def range_for_full_union_element(range, index, pipe) if index.positive? range = if pipe range_with_preceding_pipe(range) else range_with_surrounding_space(range: range, side: :left, newlines: true) end end range end # Collect a preceding pipe and any whitespace left of the pipe def range_with_preceding_pipe(range) pos = range.begin_pos - 1 while pos unless processed_source.buffer.source[pos].match?(/[\s|]/) return range.with(begin_pos: pos + 1) end pos -= 1 end range end # When there are no other elements, the entire union can be replaced def replace_union(corrector, group, replacement) corrector.replace(group.ranges.first, replacement) end # rubocop:disable Metrics/AbcSize # Calculate the ranges for each node within the pattern string that will # be replaced or removed. Takes the offset of the string node into account. def apply_range_offsets(pattern_node) range, offset = range_with_offset(pattern_node) node_groups.each do |node_group| node_group.ranges ||= [] node_group.offense_range = pattern_range(range, node_group.union, offset) if node_group.other_elements? node_group.node_types.each do |node_type| node_group.ranges << pattern_range(range, node_type, offset) end else node_group.ranges << node_group.offense_range end end end # rubocop:enable Metrics/AbcSize def pattern_range(range, node, offset) begin_pos = node.source_range.begin_pos end_pos = node.source_range.end_pos size = end_pos - begin_pos range.adjust(begin_pos: begin_pos + offset).resize(size) end def range_with_offset(pattern_node) if pattern_node.heredoc? [pattern_node.loc.heredoc_body, 0] else [pattern_node.source_range, pattern_node.loc.begin.size] end end # A heredoc can be a `dstr` without interpolation, but if there is interpolation # there'll be a `begin` node, in which case, we cannot evaluate the pattern. def acceptable_heredoc?(node) node.any_str_type? && node.heredoc? && node.each_child_node(:begin).none? end def process_pattern(pattern_node) parser = RuboCop::AST::NodePattern::Parser::WithMeta.new ast = parser.parse(pattern_value(pattern_node)) ast = ASTProcessor.new.process(ast) @walker.walk(ast) rescue RuboCop::AST::NodePattern::Invalid # if the pattern is invalid, no offenses will be registered end def pattern_value(pattern_node) pattern_node.heredoc? ? pattern_node.loc.heredoc_body.source : pattern_node.value end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/internal_affairs/method_name_end_with.rb
lib/rubocop/cop/internal_affairs/method_name_end_with.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks potentially usage of method identifier predicates # defined in rubocop-ast instead of `method_name.end_with?`. # # @example # # bad # node.method_name.to_s.end_with?('=') # # # good # node.assignment_method? # # # bad # node.method_name.to_s.end_with?('?') # # # good # node.predicate_method? # # # bad # node.method_name.to_s.end_with?('!') # # # good # node.bang_method? # class MethodNameEndWith < Base include RangeHelp extend AutoCorrector MSG = 'Use `%<method_name>s` instead of `%<method_suffix>s`.' RESTRICT_ON_SEND = %i[end_with?].freeze SUGGEST_METHOD_FOR_SUFFIX = { '=' => 'assignment_method?', '!' => 'bang_method?', '?' => 'predicate_method?' }.freeze # @!method method_name_end_with?(node) def_node_matcher :method_name_end_with?, <<~PATTERN { (call (call $(... :method_name) :to_s) :end_with? $(str {"=" "?" "!"})) (call $(... :method_name) :end_with? $(str {"=" "?" "!"})) } PATTERN def on_send(node) method_name_end_with?(node) do |method_name_node, end_with_arg| next unless method_name_node.receiver preferred_method = SUGGEST_METHOD_FOR_SUFFIX[end_with_arg.value] range = range(method_name_node, node) message = format(MSG, method_name: preferred_method, method_suffix: range.source) add_offense(range, message: message) do |corrector| corrector.replace(range, preferred_method) end end end alias on_csend on_send private def range(method_name_node, node) range = if method_name_node.call_type? method_name_node.loc.selector else method_name_node.source_range end range_between(range.begin_pos, node.source_range.end_pos) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/internal_affairs/undefined_config.rb
lib/rubocop/cop/internal_affairs/undefined_config.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Looks for references to a cop configuration key that isn't defined in config/default.yml. class UndefinedConfig < Base # `FileFinder` is a private API not intended to be used by cops, # but it's fine for `InternalAffairs`. extend FileFinder ALLOWED_CONFIGURATIONS = %w[ Safe SafeAutoCorrect AutoCorrect Severity StyleGuide Details Reference References Include Exclude ].freeze RESTRICT_ON_SEND = %i[[] fetch].freeze MSG = '`%<name>s` is not defined in the configuration for `%<cop>s` ' \ 'in `config/default.yml`.' CONFIG_PATH = find_file_upwards('config/default.yml', Dir.pwd) CONFIG = if CONFIG_PATH begin original_debug = ConfigLoader.debug ConfigLoader.debug = false ConfigLoader.load_yaml_configuration(CONFIG_PATH) ensure ConfigLoader.debug = original_debug end else {} end # @!method cop_class_def(node) def_node_search :cop_class_def, <<~PATTERN (class _ (const {nil? (const nil? :Cop) (const (const {cbase nil?} :RuboCop) :Cop)} {:Base :Cop}) ...) PATTERN # @!method cop_config_accessor?(node) def_node_matcher :cop_config_accessor?, <<~PATTERN (send (send nil? :cop_config) {:[] :fetch} ${str sym}...) PATTERN def on_new_investigation super return unless processed_source.ast cop_class = cop_class_def(processed_source.ast).first return unless (@cop_class_name = extract_cop_name(cop_class)) @config_for_cop = CONFIG[@cop_class_name] || {} end def on_send(node) return unless cop_class_name return unless (config_name_node = cop_config_accessor?(node)) return if always_allowed?(config_name_node) return if configuration_key_defined?(config_name_node) message = format(MSG, name: config_name_node.value, cop: cop_class_name) add_offense(config_name_node, message: message) end private attr_reader :config_for_cop, :cop_class_name def extract_cop_name(class_node) return unless class_node segments = [class_node].concat( class_node.each_ancestor(:class, :module).take_while do |n| n.identifier.short_name != :Cop end ) segments.reverse_each.map { |s| s.identifier.short_name }.join('/') end def always_allowed?(node) ALLOWED_CONFIGURATIONS.include?(node.value) end def configuration_key_defined?(node) config_for_cop.key?(node.value) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/internal_affairs/empty_line_between_expect_offense_and_correction.rb
lib/rubocop/cop/internal_affairs/empty_line_between_expect_offense_and_correction.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks whether `expect_offense` and correction expectation methods # (i.e. `expect_correction` and `expect_no_corrections`) are separated by empty line. # # @example # # bad # it 'registers and corrects an offense' do # expect_offense(<<~RUBY) # bad_method # ^^^^^^^^^^ Use `good_method`. # RUBY # expect_correction(<<~RUBY) # good_method # RUBY # end # # # good # it 'registers and corrects an offense' do # expect_offense(<<~RUBY) # bad_method # ^^^^^^^^^^ Use `good_method`. # RUBY # # expect_correction(<<~RUBY) # good_method # RUBY # end # class EmptyLineBetweenExpectOffenseAndCorrection < Base extend AutoCorrector MSG = 'Add empty line between `expect_offense` and `%<expect_correction>s`.' RESTRICT_ON_SEND = %i[expect_offense].freeze CORRECTION_EXPECTATION_METHODS = %i[expect_correction expect_no_corrections].freeze def on_send(node) return unless (next_sibling = node.right_sibling) return unless next_sibling.respond_to?(:send_type?) && next_sibling.send_type? method_name = next_sibling.method_name return unless CORRECTION_EXPECTATION_METHODS.include?(method_name) range = offense_range(node) return unless range.last_line + 1 == next_sibling.loc.line add_offense(range, message: format(MSG, expect_correction: method_name)) do |corrector| corrector.insert_after(range, "\n") end end private def offense_range(node) first_argument = node.first_argument if first_argument.respond_to?(:heredoc?) && first_argument.heredoc? first_argument.loc.heredoc_end else 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/internal_affairs/redundant_context_config_parameter.rb
lib/rubocop/cop/internal_affairs/redundant_context_config_parameter.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks for redundant `:config` parameter in the `context` arguments. # # @example # # # bad # context 'foo', :config do # end # # # good # context 'foo' do # end # class RedundantContextConfigParameter < Base include RangeHelp extend AutoCorrector MSG = 'Remove the redundant `:config` parameter.' RESTRICT_ON_SEND = %i[context].freeze def on_send(node) arguments = node.arguments config_node = arguments.detect { |argument| argument.source == ':config' } return unless config_node add_offense(config_node) do |corrector| dup_arguments = arguments.dup dup_arguments.delete(config_node) corrector.replace(offense_range(arguments), dup_arguments.map(&:source).join(', ')) end end private def offense_range(arguments) range_between(arguments.first.source_range.begin_pos, arguments.last.source_range.end_pos) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/internal_affairs/node_matcher_directive.rb
lib/rubocop/cop/internal_affairs/node_matcher_directive.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks that node matcher definitions are tagged with a YARD `@!method` # directive so that editors are able to find the dynamically defined # method. # # @example # # bad # def_node_matcher :foo?, <<~PATTERN # ... # PATTERN # # # good # # @!method foo?(node) # def_node_matcher :foo?, <<~PATTERN # ... # PATTERN # class NodeMatcherDirective < Base extend AutoCorrector include RangeHelp MSG = 'Precede `%<method>s` with a `@!method` YARD directive.' MSG_WRONG_NAME = '`@!method` YARD directive has invalid method name, ' \ 'use `%<expected>s` instead of `%<actual>s`.' MSG_MISSING_SCOPE_SELF = 'Follow the `@!method` YARD directive with ' \ '`@!scope class` if it is a class method.' MSG_WRONG_SCOPE_SELF = 'Do not use the `@!scope class` YARD directive if it ' \ 'is not a class method.' MSG_TOO_MANY = 'Multiple `@!method` YARD directives found for this matcher.' RESTRICT_ON_SEND = %i[def_node_matcher def_node_search].to_set.freeze REGEXP_METHOD = / ^\s*\#\s* @!method\s+(?<receiver>self\.)?(?<method_name>[a-z0-9_]+[?!]?)(?:\((?<args>.*)\))? /x.freeze REGEXP_SCOPE = /^\s*\#\s*@!scope class/.freeze # @!method pattern_matcher?(node) def_node_matcher :pattern_matcher?, <<~PATTERN (send _ %RESTRICT_ON_SEND {str sym} {str dstr}) PATTERN def on_send(node) return unless node.arguments.count == 2 return unless valid_method_name?(node) actual_name = node.first_argument.value.to_s # Ignore cases where the method has a receiver that isn't self return if actual_name.include?('.') && !actual_name.start_with?('self.') directives = method_directives(node) return too_many_directives(node) if directives.size > 1 process_directive(node, actual_name, directives.first) end private def valid_method_name?(node) node.first_argument.type?(:str, :sym) end def method_directives(node) comments = processed_source.ast_with_comments[node] group_comments(comments).filter_map do |comment_method, comment_scope| match = comment_method.text.match(REGEXP_METHOD) next unless match { node_method: comment_method, node_scope: comment_scope, method_name: match[:method_name], args: match[:args], receiver: match[:receiver], has_scope_directive: comment_scope&.text&.match?(REGEXP_SCOPE) } end end def group_comments(comments) result = [] comments.each.with_index do |comment, index| # Grab the scope directive if it is preceded by a method directive if comment.text.include?('@!method') result << if (next_comment = comments[index + 1])&.text&.include?('@!scope') [comment, next_comment] else [comment, nil] end end end result end def too_many_directives(node) add_offense(node, message: MSG_TOO_MANY) end def process_directive(node, actual_name, directive) return unless (offense_type = directive_offense_type(directive, actual_name)) register_offense(offense_type, node, directive, actual_name) end def directive_offense_type(directive, actual_name) return :missing_directive unless directive return :wrong_scope if wrong_scope?(directive, actual_name) return :no_scope if no_scope?(directive, actual_name) # The method directive being prefixed by 'self.' is always an offense. # The matched method_name does not contain the receiver but the # def_node_match method name may so it must be removed. if directive[:method_name] != remove_receiver(actual_name) || directive[:receiver] :wrong_name end end def wrong_scope?(directive, actual_name) !actual_name.start_with?('self.') && directive[:has_scope_directive] end def no_scope?(directive, actual_name) actual_name.start_with?('self.') && !directive[:has_scope_directive] end def register_offense(offense_type, node, directive, actual_name) message = formatted_message(offense_type, directive, actual_name, node.method_name) add_offense(node, message: message) do |corrector| case offense_type when :wrong_name correct_method_directive(corrector, directive, actual_name) when :wrong_scope remove_scope_directive(corrector, directive) when :no_scope insert_scope_directive(corrector, directive[:node_method]) when :missing_directive insert_method_directive(corrector, node, actual_name) end end end # rubocop:disable Metrics/MethodLength def formatted_message(offense_type, directive, actual_name, method_name) case offense_type when :wrong_name # Add the receiver to the name when showing an offense current_name = if directive[:receiver] directive[:receiver] + directive[:method_name] else directive[:method_name] end # The correct name will never include a receiver, remove it format(MSG_WRONG_NAME, expected: remove_receiver(actual_name), actual: current_name) when :wrong_scope MSG_WRONG_SCOPE_SELF when :no_scope MSG_MISSING_SCOPE_SELF when :missing_directive format(MSG, method: method_name) end end # rubocop:enable Metrics/MethodLength def remove_receiver(current) current.delete_prefix('self.') end def insert_method_directive(corrector, node, actual_name) # If the pattern matcher uses arguments (`%1`, `%2`, etc.), include them in the directive arguments = pattern_arguments(node.arguments[1].source) range = range_with_surrounding_space(node.source_range, side: :left, newlines: false) indentation = range.source.match(/^\s*/)[0] directive = "#{indentation}# @!method #{actual_name}(#{arguments.join(', ')})\n" directive = "\n#{directive}" if add_newline?(node) corrector.insert_before(range, directive) end def insert_scope_directive(corrector, node) range = range_with_surrounding_space(node.source_range, side: :left, newlines: false) indentation = range.source.match(/^\s*/)[0] directive = "\n#{indentation}# @!scope class" corrector.insert_after(node, directive) end def pattern_arguments(pattern) arguments = %w[node] max_pattern_var = pattern.scan(/(?<=%)\d+/).map(&:to_i).max max_pattern_var&.times { |i| arguments << "arg#{i + 1}" } arguments end def add_newline?(node) # Determine if a blank line should be inserted before the new directive # in order to spread out pattern matchers return false if node.sibling_index&.zero? return false unless node.parent prev_sibling = node.parent.child_nodes[node.sibling_index - 1] return false unless prev_sibling && pattern_matcher?(prev_sibling) node.loc.line == last_line(prev_sibling) + 1 end def last_line(node) if node.last_argument.heredoc? node.last_argument.loc.heredoc_end.line else node.loc.last_line end end def correct_method_directive(corrector, directive, actual_name) correct = "@!method #{remove_receiver(actual_name)}" current_name = (directive[:receiver] || '') + directive[:method_name] regexp = /@!method\s+#{Regexp.escape(current_name)}/ replacement = directive[:node_method].text.gsub(regexp, correct) corrector.replace(directive[:node_method], replacement) end def remove_scope_directive(corrector, directive) range = range_by_whole_lines( directive[:node_scope].source_range, include_final_newline: true ) 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/internal_affairs/redundant_message_argument.rb
lib/rubocop/cop/internal_affairs/redundant_message_argument.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks for redundant message arguments to `#add_offense`. This method # will automatically use `#message` or `MSG` (in that order of priority) # if they are defined. # # @example # # # bad # add_offense(node, message: MSG) # # # good # add_offense(node) # class RedundantMessageArgument < Base include RangeHelp extend AutoCorrector MSG = 'Redundant message argument to `#add_offense`.' RESTRICT_ON_SEND = %i[add_offense].freeze # @!method node_type_check(node) def_node_matcher :node_type_check, <<~PATTERN (send nil? :add_offense _node $hash) PATTERN # @!method redundant_message_argument(node) def_node_matcher :redundant_message_argument, <<~PATTERN (pair (sym :message) $(const nil? :MSG)) PATTERN def on_send(node) return unless (kwargs = node_type_check(node)) kwargs.pairs.each do |pair| redundant_message_argument(pair) do add_offense(pair) do |corrector| range = offending_range(pair) corrector.remove(range) end end end end private def offending_range(node) with_space = range_with_surrounding_space(node.source_range) range_with_surrounding_comma(with_space, :left) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/internal_affairs/plugin.rb
lib/rubocop/cop/internal_affairs/plugin.rb
# frozen_string_literal: true require 'lint_roller' module RuboCop module InternalAffairs # A Plugin for `InternalAffairs` department, which has internal cops. class Plugin < LintRoller::Plugin def about LintRoller::About.new( name: 'rubocop-internal_affairs', version: Version::STRING, homepage: 'https://github.com/rubocop/rubocop/tree/master/lib/rubocop/cop/internal_affairs', description: 'A collection of RuboCop cops to check for internal affairs.' ) end def supported?(context) context.engine == :rubocop end def rules(_context) require_relative '../internal_affairs' LintRoller::Rules.new( type: :path, config_format: :rubocop, value: Pathname.new(__dir__).join('../../../../config/internal_affairs.yml') ) end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/internal_affairs/node_type_multiple_predicates.rb
lib/rubocop/cop/internal_affairs/node_type_multiple_predicates.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Use `node.type?(:foo, :bar)` instead of `node.foo_type? || node.bar_type?`, # and `!node.type?(:foo, :bar)` instead of `!node.foo_type? && !node.bar_type?`. # # @example # # # bad # node.str_type? || node.sym_type? # # # good # node.type?(:str, :sym) # # # bad # node.type?(:str, :sym) || node.boolean_type? # # # good # node.type?(:str, :sym, :boolean) # # # bad # !node.str_type? && !node.sym_type? # # # good # !node.type?(:str, :sym) # # # bad # !node.type?(:str, :sym) && !node.boolean_type? # # # good # !node.type?(:str, :sym, :boolean) # class NodeTypeMultiplePredicates < Base extend AutoCorrector MSG_OR = 'Use `%<replacement>s` instead of checking for multiple node types.' MSG_AND = 'Use `%<replacement>s` instead of checking against multiple node types.' # @!method one_of_node_types?(node) def_node_matcher :one_of_node_types?, <<~PATTERN (or $(call _receiver #type_predicate?) (call _receiver #type_predicate?)) PATTERN # @!method or_another_type?(node) def_node_matcher :or_another_type?, <<~PATTERN (or { $(call _receiver :type? sym+) (call _receiver #type_predicate?) | (call _receiver #type_predicate?) $(call _receiver :type? sym+) }) PATTERN # @!method none_of_node_types?(node) def_node_matcher :none_of_node_types?, <<~PATTERN (and (send $(call _receiver #type_predicate?) :!) (send (call _receiver #type_predicate?) :!) ) PATTERN # @!method and_not_another_type?(node) def_node_matcher :and_not_another_type?, <<~PATTERN (and { (send $(call _receiver :type? sym+) :!) (send (call _receiver #type_predicate?) :!) | (send (call _receiver #type_predicate?) :!) (send $(call _receiver :type? sym+) :!) }) PATTERN def on_or(node) return unless (send_node = one_of_node_types?(node) || or_another_type?(node)) return unless send_node.receiver replacement = replacement(node, send_node) add_offense(node, message: format(MSG_OR, replacement: replacement)) do |corrector| corrector.replace(node, replacement) end end def on_and(node) return unless (send_node = none_of_node_types?(node) || and_not_another_type?(node)) return unless send_node.receiver replacement = "!#{replacement(node, send_node)}" add_offense(node, message: format(MSG_AND, replacement: replacement)) do |corrector| corrector.replace(node, replacement) end end private def type_predicate?(method_name) method_name.end_with?('_type?') end def replacement(node, send_node) send_node = send_node.children.first if send_node.method?(:!) types = types(node) receiver = send_node.receiver.source dot = send_node.loc.dot.source "#{receiver}#{dot}type?(:#{types.join(', :')})" end def types(node) [types_in_branch(node.lhs), types_in_branch(node.rhs)] end def types_in_branch(branch) branch = branch.children.first if branch.method?(:!) if branch.method?(:type?) branch.arguments.map(&:value) elsif branch.method?(:defined_type?) # `node.defined_type?` relates to `node.type == :defined?` 'defined?' else branch.method_name.to_s.delete_suffix('_type?') end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/internal_affairs/redundant_described_class_as_subject.rb
lib/rubocop/cop/internal_affairs/redundant_described_class_as_subject.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks for redundant `subject(:cop) { described_class.new }`. # # @example # # bad # RSpec.describe RuboCop::Cop::Department::Foo do # subject(:cop) { described_class.new(config) } # end # # # good # RSpec.describe RuboCop::Cop::Department::Foo, :config do # end # class RedundantDescribedClassAsSubject < Base include RangeHelp extend AutoCorrector MSG = 'Remove the redundant `subject`%<additional_message>s.' # @!method described_class_subject?(node) def_node_matcher :described_class_subject?, <<~PATTERN (block (send nil? :subject (sym :cop)) (args) (send (send nil? :described_class) :new $...)) PATTERN def on_block(node) return unless (described_class_arguments = described_class_subject?(node)) return if described_class_arguments.count >= 2 describe = find_describe_method_node(node) should_append_config = describe && describe.last_argument.source != ':config' additional_message = ' and specify `:config` in `describe`' if should_append_config message = format(MSG, additional_message: additional_message) add_offense(node, message: message) do |corrector| corrector.remove(range_by_whole_lines(node.source_range, include_final_newline: true)) corrector.insert_after(describe.last_argument, ', :config') if should_append_config end end private def find_describe_method_node(block_node) block_node.ancestors.find do |node| node.block_type? && node.method?(:describe) end&.send_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/internal_affairs/redundant_let_rubocop_config_new.rb
lib/rubocop/cop/internal_affairs/redundant_let_rubocop_config_new.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks that `let` is `RuboCop::Config.new` with no arguments. # # @example # # bad # RSpec.describe RuboCop::Cop::Department::Foo, :config do # let(:config) { RuboCop::Config.new } # end # # # good # RSpec.describe RuboCop::Cop::Department::Foo, :config do # end # # RSpec.describe RuboCop::Cop::Department::Foo, :config do # let(:config) { RuboCop::Config.new(argument) } # end # class RedundantLetRuboCopConfigNew < Base include RangeHelp extend AutoCorrector MSG = 'Remove `let` that is `RuboCop::Config.new` with no arguments%<additional_message>s.' # @!method let_rubocop_config_new?(node) def_node_matcher :let_rubocop_config_new?, <<~PATTERN (block (send nil? :let (sym :config)) (args) { (send (const (const nil? :RuboCop) :Config) :new) (send (const (const nil? :RuboCop) :Config) :new (hash (pair (send (send (send nil? :described_class) :badge) :to_s) (send nil? :cop_config)))) } ) PATTERN def on_block(node) return unless let_rubocop_config_new?(node) describe = find_describe_method_node(node) unless (exist_config = describe.last_argument.source == ':config') additional_message = ' and specify `:config` in `describe`' end message = format(MSG, additional_message: additional_message) add_offense(node, message: message) do |corrector| corrector.remove(range_by_whole_lines(node.source_range, include_final_newline: true)) corrector.insert_after(describe.last_argument, ', :config') unless exist_config end end private def find_describe_method_node(block_node) block_node.ancestors.find { |node| node.block_type? && node.method?(:describe) }.send_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/internal_affairs/method_name_equal.rb
lib/rubocop/cop/internal_affairs/method_name_equal.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks that method names are checked using `method?` method. # # @example # # bad # node.method_name == :do_something # # # good # node.method?(:do_something) # # # bad # node.method_name != :do_something # # # good # !node.method?(:do_something) # class MethodNameEqual < Base extend AutoCorrector MSG = 'Use `%<prefer>s` instead.' RESTRICT_ON_SEND = %i[== !=].freeze # @!method method_name(node) def_node_matcher :method_name, <<~PATTERN (send (send (...) :method_name) {:== :!=} $_) PATTERN def on_send(node) method_name(node) do |method_name_arg| bang = node.method?(:!=) ? '!' : '' prefer = "#{bang}#{node.receiver.receiver.source}.method?(#{method_name_arg.source})" message = format(MSG, prefer: prefer) add_offense(node, message: message) do |corrector| corrector.replace(node, prefer) 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/internal_affairs/node_type_group.rb
lib/rubocop/cop/internal_affairs/node_type_group.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks that node types are checked against their group when all types of a # group are checked. # # @example # # bad # node.type?(:irange, :erange) # # # good # node.range_type? # # # bad # node.type?(:irange, :erange, :send, :csend) # # # good # node.type?(:range, :call) # class NodeTypeGroup < Base extend AutoCorrector include RangeHelp MSG = 'Use `:%<group>s` instead of individually listing group types.' RESTRICT_ON_SEND = %i[type? each_ancestor each_child_node each_descendant each_node].freeze def on_send(node) return unless node.receiver symbol_args = node.arguments.select(&:sym_type?) return if symbol_args.none? NodePatternGroups::NODE_GROUPS.each do |group_name, group_types| next unless group_satisfied?(group_types, symbol_args) offense_range = arguments_range(node) add_offense(offense_range, message: format(MSG, group: group_name)) do |corrector| autocorrect(corrector, node, symbol_args, group_name, group_types) end end end alias on_csend on_send private def arguments_range(node) range_between( node.first_argument.source_range.begin_pos, node.last_argument.source_range.end_pos ) end def group_satisfied?(group_types, symbol_args) group_types.all? { |type| symbol_args.any? { |arg| arg.value == type } } end def autocorrect(corrector, node, symbol_args, group_name, group_types) if node.method?(:type?) && node.arguments.count == group_types.count autocorrect_to_explicit_predicate(corrector, node, group_name) else autocorrect_keep_method(corrector, symbol_args, group_name, group_types) end end def autocorrect_to_explicit_predicate(corrector, node, group_name) range = node.loc.selector.begin.join(node.source_range.end) corrector.replace(range, "#{group_name}_type?") end def autocorrect_keep_method(corrector, symbol_args, group_name, group_types) first_replaced = false symbol_args.each do |arg| next unless group_types.include?(arg.value) if first_replaced range = range_with_surrounding_space(arg.source_range) range = range_with_surrounding_comma(range, :left) corrector.remove(range) else first_replaced = true corrector.replace(arg, ":#{group_name}") 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/internal_affairs/node_destructuring.rb
lib/rubocop/cop/internal_affairs/node_destructuring.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks that node destructuring is using the node extensions. # # @example Using splat expansion # # # bad # _receiver, method_name, _arguments = send_node.children # # # bad # _receiver, method_name, _arguments = *send_node # # # good # method_name = send_node.method_name class NodeDestructuring < Base MSG = 'Use the methods provided with the node extensions instead ' \ 'of manually destructuring nodes.' # @!method node_variable?(node) def_node_matcher :node_variable?, <<~PATTERN {(lvar [#node_suffix? _]) (send nil? [#node_suffix? _])} PATTERN # @!method node_destructuring?(node) def_node_matcher :node_destructuring?, <<~PATTERN {(masgn (mlhs ...) {(send #node_variable? :children) (array (splat #node_variable?))})} PATTERN def on_masgn(node) node_destructuring?(node) { add_offense(node) } end private def node_suffix?(method_name) method_name.to_s.end_with?('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/internal_affairs/redundant_source_range.rb
lib/rubocop/cop/internal_affairs/redundant_source_range.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks for redundant `source_range`. # # @example # # # bad # node.source_range.source # # # good # node.source # # # bad # add_offense(node.source_range) # # # good # add_offense(node) # # # bad # add_offense(node) { |corrector| corrector.replace(node.source_range, prefer) } # add_offense(node) { |corrector| corrector.insert_before(node.source_range, prefer) } # add_offense(node) { |corrector| corrector.insert_before_multi(node.source_range, prefer) } # add_offense(node) { |corrector| corrector.insert_after(node.source_range, prefer) } # add_offense(node) { |corrector| corrector.insert_after_multi(node.source_range, prefer) } # add_offense(node) { |corrector| corrector.swap(node.source_range, before, after) } # # # good # add_offense(node) { |corrector| corrector.replace(node, prefer) } # add_offense(node) { |corrector| corrector.insert_before(node, prefer) } # add_offense(node) { |corrector| corrector.insert_before_multi(node, prefer) } # add_offense(node) { |corrector| corrector.insert_after(node, prefer) } # add_offense(node) { |corrector| corrector.insert_after_multi(node, prefer) } # add_offense(node) { |corrector| corrector.swap(node, before, after) } # class RedundantSourceRange < Base extend AutoCorrector MSG = 'Remove the redundant `source_range`.' RESTRICT_ON_SEND = %i[ source add_offense replace remove insert_before insert_before_multi insert_after insert_after_multi swap ].freeze # @!method redundant_source_range(node) def_node_matcher :redundant_source_range, <<~PATTERN { (call $(call _ :source_range) :source) (send nil? :add_offense $(send _ :source_range) ...) (send _ { :replace :insert_before :insert_before_multi :insert_after :insert_after_multi } $(send _ :source_range) _) (send _ :remove $(send _ :source_range)) (send _ :swap $(send _ :source_range) _ _) } PATTERN def on_send(node) return unless (source_range = redundant_source_range(node)) return unless source_range.receiver return if source_range.receiver.send_type? && source_range.receiver.method?(:buffer) selector = source_range.loc.selector add_offense(selector) do |corrector| corrector.remove(source_range.loc.dot.join(selector)) 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/internal_affairs/on_send_without_on_csend.rb
lib/rubocop/cop/internal_affairs/on_send_without_on_csend.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks for cops that define `on_send` without define `on_csend`. # # Although in some cases it can be predetermined that safe navigation # will never be used with the code checked by a specific cop, in general # it is good practice to handle safe navigation methods if handling any # `send` node. # # NOTE: It is expected to disable this cop for cops that check for method calls # on receivers that cannot be nil (`self`, a literal, a constant), and # method calls that will never have a receiver (ruby keywords like `raise`, # macros like `attr_reader`, DSL methods, etc.), and other checks that wouldn't # make sense to support safe navigation. # # @example # # bad # class MyCop < RuboCop::Cop:Base # def on_send(node) # # ... # end # end # # # good - explicit method definition # class MyCop < RuboCop::Cop:Base # def on_send(node) # # ... # end # # def on_csend(node) # # ... # end # end # # # good - alias # class MyCop < RuboCop::Cop:Base # def on_send(node) # # ... # end # alias on_csend on_send # end # # # good - alias_method # class MyCop < RuboCop::Cop:Base # def on_send(node) # # ... # end # alias_method :on_csend, :on_send # end class OnSendWithoutOnCSend < Base RESTRICT_ON_SEND = %i[alias_method].freeze MSG = 'Cop defines `on_send` but not `on_csend`.' def on_new_investigation @on_send_definition = nil @on_csend_definition = nil end def on_investigation_end return unless @on_send_definition && !@on_csend_definition add_offense(@on_send_definition) end def on_def(node) @on_send_definition = node if node.method?(:on_send) @on_csend_definition = node if node.method?(:on_csend) end def on_alias(node) @on_send_definition = node if node.new_identifier.value == :on_send @on_csend_definition = node if node.new_identifier.value == :on_csend end def on_send(node) # rubocop:disable InternalAffairs/OnSendWithoutOnCSend return unless (new_identifier = node.first_argument) return unless new_identifier.basic_literal? new_identifier = new_identifier.value @on_send_definition = node if new_identifier == :on_send @on_csend_definition = node if new_identifier == :on_csend end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/internal_affairs/location_expression.rb
lib/rubocop/cop/internal_affairs/location_expression.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Enforces the use of `node.source_range` instead of `node.location.expression`. # # @example # # # bad # node.location.expression # node.loc.expression # # # good # node.source_range # class LocationExpression < Base extend AutoCorrector MSG = 'Use `source_range` instead.' RESTRICT_ON_SEND = %i[loc location].freeze def on_send(node) return unless (parent = node.parent) return unless parent.call_type? && parent.method?(:expression) return unless parent.receiver.receiver offense = node.loc.selector.join(parent.source_range.end) add_offense(offense) do |corrector| corrector.replace(offense, 'source_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/internal_affairs/offense_location_keyword.rb
lib/rubocop/cop/internal_affairs/offense_location_keyword.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks for potential uses of the location keywords which can be used as # shortcut arguments to `#add_offense`. # # @example # # # bad # add_offense(node, location: node.loc.selector) # # # good # add_offense(node, location: :selector) class OffenseLocationKeyword < Base extend AutoCorrector MSG = 'Use `:%<keyword>s` as the location argument to `#add_offense`.' RESTRICT_ON_SEND = %i[add_offense].freeze def on_send(node) node_type_check(node) do |node_arg, kwargs| find_offending_argument(node_arg, kwargs) do |location, keyword| add_offense(location, message: format(MSG, keyword: keyword)) do |corrector| (*, keyword) = offending_location_argument(location.parent) corrector.replace(location, ":#{keyword}") end end end end private # @!method node_type_check(node) def_node_matcher :node_type_check, <<~PATTERN (send nil? :add_offense $_node $hash) PATTERN # @!method offending_location_argument(node) def_node_matcher :offending_location_argument, <<~PATTERN (pair (sym :location) $(send (send $_node :loc) $_keyword)) PATTERN def find_offending_argument(searched_node, kwargs) kwargs.pairs.each do |pair| offending_location_argument(pair) do |location, node, keyword| yield(location, keyword) if searched_node == 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/internal_affairs/node_first_or_last_argument.rb
lib/rubocop/cop/internal_affairs/node_first_or_last_argument.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks for the use of `node.arguments.first` or `node.arguments.last` and # suggests the use of `node.first_argument` or `node.last_argument` instead. # # @example # # bad # node.arguments.first # node.arguments[0] # node.arguments.last # node.arguments[-1] # # # good # node.first_argument # node.last_argument # class NodeFirstOrLastArgument < Base extend AutoCorrector include RangeHelp MSG = 'Use `#%<correct>s` instead of `#%<incorrect>s`.' RESTRICT_ON_SEND = %i[arguments].freeze # @!method arguments_first_or_last?(node) def_node_matcher :arguments_first_or_last?, <<~PATTERN { (call (call !nil? :arguments) ${:first :last}) (call (call !nil? :arguments) :[] (int ${0 -1})) } PATTERN def on_send(node) arguments_first_or_last?(node.parent) do |end_or_index| range = range_between(node.loc.selector.begin_pos, node.parent.source_range.end_pos) correct = case end_or_index when :first, 0 then 'first_argument' when :last, -1 then 'last_argument' else raise "Unknown end_or_index: #{end_or_index}" end message = format(MSG, correct: correct, incorrect: range.source) add_offense(range, message: message) do |corrector| corrector.replace(range, correct) end 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/internal_affairs/redundant_method_dispatch_node.rb
lib/rubocop/cop/internal_affairs/redundant_method_dispatch_node.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks for redundant `send_node` method dispatch node. # # @example # # # bad # node.send_node.method_name # # # good # node.method_name # # # bad # node.send_node.method?(:method_name) # # # good # node.method?(:method_name) # # # bad # node.send_node.receiver # # # good # node.receiver # class RedundantMethodDispatchNode < Base include RangeHelp extend AutoCorrector MSG = 'Remove the redundant `send_node`.' RESTRICT_ON_SEND = %i[method_name method? receiver].freeze # @!method dispatch_method(node) def_node_matcher :dispatch_method, <<~PATTERN { (send $(send _ :send_node) {:method_name :receiver}) (send $(send _ :send_node) :method? _) } PATTERN def on_send(node) return unless (dispatch_node = dispatch_method(node)) return unless (dot = dispatch_node.loc.dot) range = range_between(dot.begin_pos, dispatch_node.loc.selector.end_pos) add_offense(range) do |corrector| corrector.remove(range) end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/internal_affairs/node_type_predicate.rb
lib/rubocop/cop/internal_affairs/node_type_predicate.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks that node types are checked using the predicate helpers. # # @example # # # bad # node.type == :send # # # good # node.send_type? # class NodeTypePredicate < Base extend AutoCorrector MSG = 'Use `#%<type>s_type?` to check node type.' RESTRICT_ON_SEND = %i[==].freeze # @!method node_type_check(node) def_node_matcher :node_type_check, <<~PATTERN (send (call _ :type) :== (sym $_)) PATTERN def on_send(node) node_type_check(node) do |node_type| return unless Parser::Meta::NODE_TYPES.include?(node_type) message = format(MSG, type: node_type) add_offense(node, message: message) do |corrector| range = node.receiver.loc.selector.join(node.source_range.end) corrector.replace(range, "#{node_type}_type?") 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/internal_affairs/processed_source_buffer_name.rb
lib/rubocop/cop/internal_affairs/processed_source_buffer_name.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Enforces the use of `processed_source.file_path` instead of `processed_source.buffer.name`. # # @example # # # bad # processed_source.buffer.name # # # good # processed_source.file_path # class ProcessedSourceBufferName < Base extend AutoCorrector MSG = 'Use `file_path` instead.' RESTRICT_ON_SEND = %i[name].freeze # @!method processed_source_buffer_name?(node) def_node_matcher :processed_source_buffer_name?, <<~PATTERN (send (send {(lvar :processed_source) (send nil? :processed_source)} :buffer) :name) PATTERN def on_send(node) return unless processed_source_buffer_name?(node) offense_range = node.children.first.loc.selector.begin.join(node.source_range.end) add_offense(offense_range) do |corrector| corrector.replace(offense_range, 'file_path') 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/internal_affairs/location_line_equality_comparison.rb
lib/rubocop/cop/internal_affairs/location_line_equality_comparison.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Enforces the use of `same_line?` instead of location line comparison for equality. # # @example # # bad # node.loc.line == node.parent.loc.line # # # bad # node.loc.first_line == node.parent.loc.first_line # # # good # same_line?(node, node.parent) # class LocationLineEqualityComparison < Base extend AutoCorrector MSG = 'Use `%<preferred>s`.' RESTRICT_ON_SEND = [:==].freeze # @!method line_send(node) def_node_matcher :line_send, <<~PATTERN { (send (send _ {:loc :source_range}) {:line :first_line}) (send _ :first_line) } PATTERN # @!method location_line_equality_comparison?(node) def_node_matcher :location_line_equality_comparison?, <<~PATTERN (send #line_send :== #line_send) PATTERN def on_send(node) return unless location_line_equality_comparison?(node) lhs_receiver = extract_receiver(node.receiver) rhs_receiver = extract_receiver(node.first_argument) preferred = "same_line?(#{lhs_receiver}, #{rhs_receiver})" add_offense(node, message: format(MSG, preferred: preferred)) do |corrector| corrector.replace(node, preferred) end end private def extract_receiver(node) receiver = node.receiver if receiver.send_type? && (receiver.method?(:loc) || receiver.method?(:source_range)) receiver = receiver.receiver end receiver.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/internal_affairs/inherit_deprecated_cop_class.rb
lib/rubocop/cop/internal_affairs/inherit_deprecated_cop_class.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # `RuboCop::Cop::Cop` is deprecated and will be removed in RuboCop 2.0. # Your custom cop class should inherit from `RuboCop::Cop::Base` instead of # `RuboCop::Cop::Cop`. # # See "v1 Upgrade Notes" for more details: # https://docs.rubocop.org/rubocop/v1_upgrade_notes.html # # @example # # bad # class Foo < Cop # end # # # good # class Foo < Base # end # class InheritDeprecatedCopClass < Base MSG = 'Use `Base` instead of `Cop`.' def on_class(node) return unless (parent_class = node.parent_class) return unless parent_class.children.last == :Cop add_offense(parent_class) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/internal_affairs/style_detected_api_use.rb
lib/rubocop/cop/internal_affairs/style_detected_api_use.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks for correct use of the style_detected API provided by # `ConfigurableEnforcedStyle`. If `correct_style_detected` is used # then `opposite_style_detected`, `unexpected_style_detected`, # `ambiguous_style_detected`, `conflicting_styles_detected`, # `unrecognized_style_detected` or `no_acceptable_style!` should be # used too, and vice versa. The `xxx_style_detected` methods # should not be used as predicates either. # # @example # # # bad # def on_send(node) # return add_offense(node) if opposite_style_detected # # correct_style_detected # end # # def on_send(node) # if offense? # add_offense(node) # else # correct_style_detected # end # end # # def on_send(node) # return unless offense? # # add_offense(node) # opposite_style_detected # end # # # good # def on_send(node) # if offense? # add_offense(node) # opposite_style_detected # else # correct_style_detected # end # end # # def on_send(node) # add_offense(node) if offense? # end # class StyleDetectedApiUse < Base MSG_FOR_POSITIVE_WITHOUT_NEGATIVE = '`correct_style_detected` method called without ' \ 'calling a negative `*_style_detected` method.' MSG_FOR_NEGATIVE_WITHOUT_POSITIVE = 'negative `*_style_detected` methods called without ' \ 'calling `correct_style_detected` method.' MSG_FOR_CONDITIONAL_USE = '`*_style_detected` method called in conditional.' RESTRICT_ON_SEND = %i[ correct_style_detected opposite_style_detected unexpected_style_detected ambiguous_style_detected conflicting_styles_detected unrecognized_style_detected no_acceptable_style! style_detected ].freeze # @!method correct_style_detected_check(node) def_node_matcher :correct_style_detected_check, <<~PATTERN (send nil? :correct_style_detected) PATTERN # @!method negative_style_detected_method_check(node) def_node_matcher :negative_style_detected_method_check, <<~PATTERN (send nil? /(?:opposite|unexpected|ambiguous|unrecognized)_style_detected|conflicting_styles_detected/ ...) PATTERN # @!method no_acceptable_style_check(node) def_node_matcher :no_acceptable_style_check, <<~PATTERN (send nil? :no_acceptable_style!) PATTERN # @!method style_detected_check(node) def_node_matcher :style_detected_check, <<~PATTERN (send nil? :style_detected ...) PATTERN def on_new_investigation @correct_style_detected_called = false @negative_style_detected_methods_called = false @style_detected_called = false end def on_investigation_end return if style_detected_called return unless correct_style_detected_called ^ negative_style_detected_methods_called add_global_offense(MSG_FOR_POSITIVE_WITHOUT_NEGATIVE) if positive_without_negative? add_global_offense(MSG_FOR_NEGATIVE_WITHOUT_POSITIVE) if negative_without_positive? end def on_send(node) if correct_style_detected_check(node) @correct_style_detected_called = true elsif negative_style_detected_method_check(node) || no_acceptable_style_check(node) @negative_style_detected_methods_called = true elsif style_detected_check(node) @style_detected_called = true end end def on_if(node) traverse_condition(node.condition) do |cond| add_offense(cond, message: MSG_FOR_CONDITIONAL_USE) if style_detected_api_used?(cond) end end private attr_reader :correct_style_detected_called, :negative_style_detected_methods_called, :style_detected_called def positive_without_negative? correct_style_detected_called && !negative_style_detected_methods_called end def negative_without_positive? negative_style_detected_methods_called && !correct_style_detected_called end def style_detected_api_used?(node) correct_style_detected_check(node) || negative_style_detected_method_check(node) || no_acceptable_style_check(node) || style_detected_check(node) end def traverse_condition(condition, &block) yield condition if condition.send_type? condition.each_child_node { |child| traverse_condition(child, &block) } end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/internal_affairs/redundant_location_argument.rb
lib/rubocop/cop/internal_affairs/redundant_location_argument.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks for redundant `location` argument to `#add_offense`. `location` # argument has a default value of `:expression` and this method will # automatically use it. # # @example # # # bad # add_offense(node, location: :expression) # # # good # add_offense(node) # add_offense(node, location: :selector) # class RedundantLocationArgument < Base include RangeHelp extend AutoCorrector MSG = 'Redundant location argument to `#add_offense`.' RESTRICT_ON_SEND = %i[add_offense].freeze # @!method redundant_location_argument(node) def_node_matcher :redundant_location_argument, <<~PATTERN (send nil? :add_offense _ (hash <$(pair (sym :location) (sym :expression)) ...>) ) PATTERN def on_send(node) redundant_location_argument(node) do |argument| add_offense(argument) do |corrector| range = offending_range(argument) corrector.remove(range) end end end private def offending_range(node) with_space = range_with_surrounding_space(node.source_range) range_with_surrounding_comma(with_space, :left) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/internal_affairs/redundant_expect_offense_arguments.rb
lib/rubocop/cop/internal_affairs/redundant_expect_offense_arguments.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks for redundant arguments of `RuboCop::RSpec::ExpectOffense`'s methods. # # @example # # # bad # expect_no_offenses('code', keyword: keyword) # # # good # expect_no_offenses('code') # class RedundantExpectOffenseArguments < Base extend AutoCorrector MSG = 'Remove the redundant arguments.' RESTRICT_ON_SEND = %i[expect_no_offenses].freeze def on_send(node) return if node.arguments.one? || !node.arguments[1]&.hash_type? range = node.first_argument.source_range.end.join(node.last_argument.source_range.end) add_offense(range) do |corrector| corrector.remove(range) end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/internal_affairs/location_exists.rb
lib/rubocop/cop/internal_affairs/location_exists.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # When a node location may not exist, `Node#loc?` or `Node#loc_is?` # can be used instead of calling `Node#respond_to?` before using # the value. # # @example # # bad # node.loc.respond_to?(:begin) # # # good # node.loc?(:begin) # # # bad # node.loc.respond_to?(:begin) && node.loc.begin # # # good # node.loc?(:begin) # # # bad # node.loc.respond_to?(:begin) && node.loc.begin.is?('(') # # # good # node.loc_is?(:begin, '(') # # # bad # node.loc.respond_to?(:begin) && node.loc.begin.source == '(' # # # good # node.loc_is?(:begin, '(') # class LocationExists < Base extend AutoCorrector MSG = 'Use `node.loc?` instead of `loc.respond_to?`.' MSG_CORRECTABLE = 'Use `%<replacement>s` instead of `%<source>s`.' RESTRICT_ON_SEND = %i[respond_to?].freeze # @!method loc_respond_to?(node) def_node_matcher :loc_respond_to?, <<~PATTERN (call (call $_receiver :loc) :respond_to? $(sym _location)) PATTERN # @!method replaceable_with_loc_is(node) def_node_matcher :replaceable_with_loc_is, <<~PATTERN (and (call (call $_receiver :loc) :respond_to? $(sym _location)) { (call (call (call _receiver :loc) _location) :is? $(str _)) (call (call (call (call _receiver :loc) _location) :source) :== $(str _)) }) PATTERN # @!method replaceable_with_loc(node) def_node_matcher :replaceable_with_loc, <<~PATTERN (and (call (call $_receiver :loc) :respond_to? $(sym _location)) (call (call _receiver :loc) _location)) PATTERN def on_and(node) replace_with_loc(node) || replace_with_loc_is(node) end def on_send(node) return if ignored_node?(node.parent) loc_respond_to?(node) do |receiver, location| register_offense(node, replacement(receiver, "loc?(#{location.source})")) end end alias on_csend on_send private def replace_with_loc(node) replaceable_with_loc(node) do |receiver, location| if node.parent&.assignment? register_offense(node, replace_assignment(receiver, location)) else register_offense(node, replacement(receiver, "loc?(#{location.source})")) end end end def replace_with_loc_is(node) replaceable_with_loc_is(node) do |receiver, location, value| replacement = replacement(receiver, "loc_is?(#{location.source}, #{value.source})") register_offense(node, replacement) end end def register_offense(node, replacement) message = format(MSG_CORRECTABLE, replacement: replacement, source: node.source) add_offense(node, message: message) do |corrector| corrector.replace(node, replacement) end ignore_node(node) end def replacement(receiver, rest) "#{replace_receiver(receiver)}#{rest}" end def replace_assignment(receiver, location) prefix = replace_receiver(receiver) "#{prefix}loc#{dot(receiver)}#{location.value} if #{prefix}loc?(#{location.source})" end def replace_receiver(receiver) return '' unless receiver "#{receiver.source}#{dot(receiver)}" end def dot(node) node.parent.loc.dot.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/internal_affairs/single_line_comparison.rb
lib/rubocop/cop/internal_affairs/single_line_comparison.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Enforces the use of `node.single_line?` instead of # comparing `first_line` and `last_line` for equality. # # @example # # bad # node.loc.first_line == node.loc.last_line # # # bad # node.loc.last_line == node.loc.first_line # # # bad # node.loc.line == node.loc.last_line # # # bad # node.loc.last_line == node.loc.line # # # bad # node.first_line == node.last_line # # # good # node.single_line? # class SingleLineComparison < Base extend AutoCorrector MSG = 'Use `%<preferred>s`.' RESTRICT_ON_SEND = %i[== !=].freeze # @!method single_line_comparison(node) def_node_matcher :single_line_comparison, <<~PATTERN { (send (call $_receiver {:line :first_line}) {:== :!=} (call _receiver :last_line)) (send (call $_receiver :last_line) {:== :!=} (call _receiver {:line :first_line})) } PATTERN def on_send(node) return unless (receiver = single_line_comparison(node)) bang = node.method?(:!=) ? '!' : '' dot = receiver.parent.loc.dot.source preferred = "#{bang}#{extract_receiver(receiver)}#{dot}single_line?" add_offense(node, message: format(MSG, preferred: preferred)) do |corrector| corrector.replace(node, preferred) end end private def extract_receiver(node) node = node.receiver if node.call_type? && %i[loc source_range].include?(node.method_name) 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/internal_affairs/create_empty_file.rb
lib/rubocop/cop/internal_affairs/create_empty_file.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks for uses of `create_file` with empty string second argument. # # @example # # # bad # create_file(path, '') # # # good # create_empty_file(path) # class CreateEmptyFile < Base extend AutoCorrector MSG = 'Use `%<replacement>s`.' RESTRICT_ON_SEND = %i[create_file].freeze def on_send(node) return if node.receiver return unless (argument = node.arguments[1]) return unless argument.str_type? && argument.value.empty? replacement = "create_empty_file(#{node.first_argument.source})" message = format(MSG, replacement: replacement) 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/internal_affairs/useless_restrict_on_send.rb
lib/rubocop/cop/internal_affairs/useless_restrict_on_send.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # Checks for useless `RESTRICT_ON_SEND`. # # @example # # bad # class FooCop # RESTRICT_ON_SEND = %i[bad_method].freeze # end # # # good # class FooCop # RESTRICT_ON_SEND = %i[bad_method].freeze # def on_send(node) # # ... # end # end # # # good # class FooCop # RESTRICT_ON_SEND = %i[bad_method].freeze # def after_send(node) # # ... # end # end # class UselessRestrictOnSend < Base extend AutoCorrector MSG = 'Useless `RESTRICT_ON_SEND` is defined.' # @!method defined_send_callback?(node) def_node_search :defined_send_callback?, <<~PATTERN { (def {:on_send :after_send} ...) (alias (sym {:on_send :after_send}) _source ...) (send nil? :alias_method {(sym {:on_send :after_send}) (str {"on_send" "after_send"})} _source ...) } PATTERN def on_casgn(node) return if !restrict_on_send?(node) || defined_send_callback?(node.parent) add_offense(node) do |corrector| corrector.remove(node) end end private def restrict_on_send?(node) node.name == :RESTRICT_ON_SEND end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/internal_affairs/node_pattern_groups/ast_walker.rb
lib/rubocop/cop/internal_affairs/node_pattern_groups/ast_walker.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs # rubocop:disable InternalAffairs/RedundantSourceRange -- node here is a `NodePattern::Node` class NodePatternGroups # Walks an AST that has been processed by `InternalAffairs::NodePatternGroups::Processor` # in order to find `node_type` and `node_sequence` nodes that can be replaced with a node # group in `InternalAffairs/NodePatternGroups`. # # Calling `ASTWalker#walk` sets `node_groups` with an array of `NodeGroup` structs # that contain metadata about nodes that can be replaced, including location data. That # metadata is used by the cop to register offenses and perform corrections. class ASTWalker # Struct to contain data about parts of a node pattern that can be replaced NodeGroup = Struct.new( :name, # The name of the node group that will be inserted :union, # The entire `union` node :node_types, # An array of `node_type` nodes that will be removed :sequence?, # The pattern matches a node type with given attributes :start_index, # The index in the union of the first node type to remove :offense_range, # The range to mark an offense on :ranges, # Range of each element to remove, since they may not be adjacent :pipe, # Is the union delimited by pipes? :other_elements?, # Does the union have other elements other than those to remove? keyword_init: true ) def initialize reset! end def reset! @node_groups = [] end attr_reader :node_groups # Recursively walk the AST in a depth-first manner. # Only `union` nodes are handled further. def walk(node) return if node.nil? on_union(node) if node.type == :union node.child_nodes.each do |child| walk(child) end end # Search `union` nodes for `node_type` and `node_sequence` nodes that can be # collapsed into a node group. # * `node_type` nodes are nodes with no further configuration (ie. `send`) # * `node_sequence` nodes are nodes with further configuration (ie. `(send ...)`) # # Each group of types that can be collapsed will have a `NodeGroup` record added # to `node_groups`, which is then used by the cop. def on_union(node) all_node_types = each_child_node(node, :node_type, :node_sequence).to_a each_node_group(all_node_types) do |group_name, node_types| next unless sequences_match?(node_types) node_groups << node_group_data( group_name, node, node_types, all_node_types.index(node_types.first), (node.children - node_types).any? ) end end private def each_child_node(node, *types) return to_enum(__method__, node, *types) unless block_given? node.children.each do |child| yield child if types.empty? || types.include?(child.type) end self end def each_node_group(types_to_check) # Find all node groups where all of the members are present in the union type_names = types_to_check.map(&:child) NODE_GROUPS.select { |_, group| group & type_names == group }.each_key do |name| nodes = get_relevant_nodes(types_to_check, name) yield name, nodes end end def get_relevant_nodes(node_types, group_name) node_types.each_with_object([]) do |node_type, arr| next unless NODE_GROUPS[group_name].include?(node_type.child) arr << node_type end end def node_group_data(name, union, node_types, start_index, other) NodeGroup.new( name: name, union: union, node_types: node_types, sequence?: node_types.first.type == :node_sequence, start_index: start_index, pipe: union.source_range.source['|'], other_elements?: other ) end def sequences_match?(types) # Ensure all given types have the same type and the same sequence # ie. `(send ...)` and `(csend ...) is a match # `(send)` and `(csend ...)` is not a match # `send` and `(csend ...)` is not a match types.each_cons(2).all? do |left, right| left.type == right.type && left.children[1..] == right.children[1..] end end end end # rubocop:enable InternalAffairs/RedundantSourceRange end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/internal_affairs/node_pattern_groups/ast_processor.rb
lib/rubocop/cop/internal_affairs/node_pattern_groups/ast_processor.rb
# frozen_string_literal: true module RuboCop module Cop module InternalAffairs class NodePatternGroups # AST Processor for NodePattern ASTs, for use with `InternalAffairs/NodePatternGroups`. # # Looks for sequences and subsequences where the first item is a `node_type` node, # and converts them to `node_sequence` nodes (not a true `RuboCop::AST::NodePattern` # node type). # # The resulting AST will be walked by `InternalAffairs::NodePatternGroups::ASTWalker` # in order to find node types in a `union` node that can be rewritten as a node group. # # NOTE: The `on_*` methods in this class relate not to the normal node types but # rather to the Node Pattern node types. Not every node type is handled. # class ASTProcessor include ::AST::Processor::Mixin def handler_missing(node) node.updated(nil, process_children(node)) end # Look for `sequence` and `subsequence` nodes that contain a `node_type` node as # their first child. These are rewritten as `node_sequence` nodes so that it is # possible to compare nodes while looking for replacement candidates for node groups. # This is necessary so that extended patterns can be matched and replaced. # ie. `{(send _ :foo ...) (csend _ :foo ...)}` can become `(call _ :foo ...)` def on_sequence(node) first_child = node.child if first_child.type == :node_type children = [first_child.child, *process_children(node, 1..)] # The `node_sequence` node contains the `node_type` symbol as its first child, # followed by all the other nodes contained in the `sequence` node. # The location is copied from the sequence, so that the entire sequence can # eventually be corrected in the cop. n(:node_sequence, children, location: node.location) else node.updated(nil, process_children(node)) end end alias on_subsequence on_sequence private def n(type, children = [], properties = {}) NodePattern::Node.new(type, children, properties) end def process_children(node, range = 0..-1) node.children[range].map do |child| child.is_a?(::AST::Node) ? process(child) : child 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/correctors/empty_line_corrector.rb
lib/rubocop/cop/correctors/empty_line_corrector.rb
# frozen_string_literal: true module RuboCop module Cop # This class does empty line autocorrection class EmptyLineCorrector class << self def correct(corrector, node) offense_style, range = node case offense_style when :no_empty_lines corrector.remove(range) when :empty_lines corrector.insert_before(range, "\n") end end def insert_before(corrector, node) corrector.insert_before(node, "\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/correctors/space_corrector.rb
lib/rubocop/cop/correctors/space_corrector.rb
# frozen_string_literal: true module RuboCop module Cop # This autocorrects whitespace class SpaceCorrector extend SurroundingSpace class << self attr_reader :processed_source def empty_corrections(processed_source, corrector, empty_config, left_token, right_token) @processed_source = processed_source range = range_between(left_token.end_pos, right_token.begin_pos) if offending_empty_space?(empty_config, left_token, right_token) corrector.remove(range) corrector.insert_after(left_token.pos, ' ') elsif offending_empty_no_space?(empty_config, left_token, right_token) corrector.remove(range) end end def remove_space(processed_source, corrector, left_token, right_token) @processed_source = processed_source if left_token.space_after? range = side_space_range(range: left_token.pos, side: :right) corrector.remove(range) end return unless right_token.space_before? range = side_space_range(range: right_token.pos, side: :left) corrector.remove(range) end def add_space(processed_source, corrector, left_token, right_token) @processed_source = processed_source corrector.insert_after(left_token.pos, ' ') unless left_token.space_after? return if right_token.space_before? corrector.insert_before(right_token.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/correctors/ordered_gem_corrector.rb
lib/rubocop/cop/correctors/ordered_gem_corrector.rb
# frozen_string_literal: true module RuboCop module Cop # This autocorrects gem dependency order class OrderedGemCorrector class << self include OrderedGemNode include RangeHelp attr_reader :processed_source, :comments_as_separators def correct(processed_source, node, previous_declaration, comments_as_separators) @processed_source = processed_source @comments_as_separators = comments_as_separators current_range = declaration_with_comment(node) previous_range = declaration_with_comment(previous_declaration) ->(corrector) { corrector.swap(current_range, previous_range) } end private def declaration_with_comment(node) buffer = processed_source.buffer begin_pos = range_by_whole_lines(get_source_range(node, comments_as_separators)).begin_pos end_line = buffer.line_for_position(node.source_range.end_pos) end_pos = range_by_whole_lines(buffer.line_range(end_line), include_final_newline: true).end_pos range_between(begin_pos, 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/correctors/alignment_corrector.rb
lib/rubocop/cop/correctors/alignment_corrector.rb
# frozen_string_literal: true module RuboCop module Cop # This class does autocorrection of nodes that should just be moved to # the left or to the right, amount being determined by the instance # variable column_delta. class AlignmentCorrector extend RangeHelp extend Alignment class << self attr_reader :processed_source def correct(corrector, processed_source, node, column_delta) return unless node @processed_source = processed_source expr = node.respond_to?(:loc) ? node.source_range : node return if block_comment_within?(expr) taboo_ranges = inside_string_ranges(node) each_line(expr) do |line_begin_pos| autocorrect_line(corrector, line_begin_pos, expr, column_delta, taboo_ranges) end end def align_end(corrector, processed_source, node, align_to) @processed_source = processed_source whitespace = whitespace_range(node) column = alignment_column(align_to) if whitespace.source.strip.empty? corrector.replace(whitespace, ' ' * column) else corrector.insert_after(whitespace, "\n#{' ' * column}") end end private def autocorrect_line(corrector, line_begin_pos, expr, column_delta, taboo_ranges) range = calculate_range(expr, line_begin_pos, column_delta) # We must not change indentation of heredoc strings or inside other # string literals return if taboo_ranges.any? { |t| within?(range, t) } if column_delta.positive? && range.resize(1).source != "\n" corrector.insert_before(range, ' ' * column_delta) elsif /\A[ \t]+\z/.match?(range.source) corrector.remove(range) end end def inside_string_ranges(node) return [] unless node.is_a?(Parser::AST::Node) node.each_node(:any_str).filter_map { |n| inside_string_range(n) } end def inside_string_range(node) loc = node.location if node.heredoc? loc.heredoc_body.join(loc.heredoc_end) elsif delimited_string_literal?(node) loc.begin.end.join(loc.end.begin) end end # Some special kinds of string literals are not composed of literal # characters between two delimiters: # - The source map of `?a` responds to :begin and :end but its end is # nil. # - The source map of `__FILE__` responds to neither :begin nor :end. def delimited_string_literal?(node) node.loc?(:begin) && node.loc?(:end) end def block_comment_within?(expr) processed_source.comments.select(&:document?).any? do |c| within?(c.source_range, expr) end end def calculate_range(expr, line_begin_pos, column_delta) return range_between(line_begin_pos, line_begin_pos) if column_delta.positive? starts_with_space = expr.source_buffer.source[line_begin_pos].start_with?(' ') if starts_with_space range_between(line_begin_pos, line_begin_pos + column_delta.abs) else range_between(line_begin_pos - column_delta.abs, line_begin_pos) end end def each_line(expr) line_begin_pos = expr.begin_pos expr.source.each_line do |line| yield line_begin_pos line_begin_pos += line.length end end def whitespace_range(node) begin_pos = node.loc.end.begin_pos range_between(begin_pos - node.loc.end.column, begin_pos) end def alignment_column(align_to) if !align_to 0 elsif align_to.respond_to?(:loc) align_to.source_range.column else align_to.column end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false