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/layout/trailing_empty_lines.rb
lib/rubocop/cop/layout/trailing_empty_lines.rb
# frozen_string_literal: true module RuboCop module Cop module Layout # Looks for trailing blank lines and a final newline in the # source code. # # @example EnforcedStyle: final_newline (default) # # `final_newline` looks for one newline at the end of files. # # # bad # class Foo; end # # # EOF # # # bad # class Foo; end # EOF # # # good # class Foo; end # # EOF # # @example EnforcedStyle: final_blank_line # # `final_blank_line` looks for one blank line followed by a new line # # at the end of files. # # # bad # class Foo; end # # EOF # # # bad # class Foo; end # EOF # # # good # class Foo; end # # # EOF # class TrailingEmptyLines < Base include ConfigurableEnforcedStyle include RangeHelp extend AutoCorrector def on_new_investigation buffer = processed_source.buffer return if buffer.source.empty? # The extra text that comes after the last token could be __END__ # followed by some data to read. If so, we don't check it because # there could be good reasons why it needs to end with a certain # number of newlines. return if ends_in_end?(processed_source) return if end_with_percent_blank_string?(processed_source) whitespace_at_end = buffer.source[/\s*\Z/] blank_lines = whitespace_at_end.count("\n") - 1 wanted_blank_lines = style == :final_newline ? 0 : 1 return unless blank_lines != wanted_blank_lines offense_detected(buffer, wanted_blank_lines, blank_lines, whitespace_at_end) end private def offense_detected(buffer, wanted_blank_lines, blank_lines, whitespace_at_end) begin_pos = buffer.source.length - whitespace_at_end.length autocorrect_range = range_between(begin_pos, buffer.source.length) begin_pos += 1 unless whitespace_at_end.empty? report_range = range_between(begin_pos, buffer.source.length) add_offense( report_range, message: message(wanted_blank_lines, blank_lines) ) do |corrector| corrector.replace(autocorrect_range, style == :final_newline ? "\n" : "\n\n") end end def ends_in_end?(processed_source) buffer = processed_source.buffer return true if buffer.source.match?(/\s*__END__/) return false if processed_source.tokens.empty? extra = buffer.source[processed_source.tokens.last.end_pos..] extra&.strip&.start_with?('__END__') end def end_with_percent_blank_string?(processed_source) processed_source.buffer.source.end_with?("%\n\n") end def message(wanted_blank_lines, blank_lines) case blank_lines when -1 'Final newline missing.' when 0 'Trailing blank line missing.' else instead_of = if wanted_blank_lines.zero? '' else "instead of #{wanted_blank_lines} " end format('%<current>d trailing blank lines %<prefer>sdetected.', current: blank_lines, prefer: instead_of) end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/multiline_hash_brace_layout.rb
lib/rubocop/cop/layout/multiline_hash_brace_layout.rb
# frozen_string_literal: true module RuboCop module Cop module Layout # Checks that the closing brace in a hash literal is either # on the same line as the last hash element, or a new line. # # When using the `symmetrical` (default) style: # # If a hash's opening brace is on the same line as the first element # of the hash, then the closing brace should be on the same line as # the last element of the hash. # # If a hash's opening brace is on the line above the first element # of the hash, then the closing brace should be on the line below # the last element of the hash. # # When using the `new_line` style: # # The closing brace of a multi-line hash literal must be on the line # after the last element of the hash. # # When using the `same_line` style: # # The closing brace of a multi-line hash literal must be on the same # line as the last element of the hash. # # @example EnforcedStyle: symmetrical (default) # # # bad # { a: 1, # b: 2 # } # # bad # { # a: 1, # b: 2 } # # # good # { a: 1, # b: 2 } # # # good # { # a: 1, # b: 2 # } # # @example EnforcedStyle: new_line # # bad # { # a: 1, # b: 2 } # # # bad # { a: 1, # b: 2 } # # # good # { a: 1, # b: 2 # } # # # good # { # a: 1, # b: 2 # } # # @example EnforcedStyle: same_line # # bad # { a: 1, # b: 2 # } # # # bad # { # a: 1, # b: 2 # } # # # good # { # a: 1, # b: 2 } # # # good # { a: 1, # b: 2 } class MultilineHashBraceLayout < Base include MultilineLiteralBraceLayout extend AutoCorrector SAME_LINE_MESSAGE = 'Closing hash brace must be on the same line as ' \ 'the last hash element when opening brace is on the same line as ' \ 'the first hash element.' NEW_LINE_MESSAGE = 'Closing hash brace must be on the line after ' \ 'the last hash element when opening brace is on a separate line ' \ 'from the first hash element.' ALWAYS_NEW_LINE_MESSAGE = 'Closing hash brace must be on the line ' \ 'after the last hash element.' ALWAYS_SAME_LINE_MESSAGE = 'Closing hash brace must be on the same ' \ 'line as the last hash element.' def on_hash(node) check_brace_layout(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/layout/space_inside_range_literal.rb
lib/rubocop/cop/layout/space_inside_range_literal.rb
# frozen_string_literal: true module RuboCop module Cop module Layout # Checks for spaces inside range literals. # # @example # # bad # 1 .. 3 # # # good # 1..3 # # # bad # 'a' .. 'z' # # # good # 'a'..'z' class SpaceInsideRangeLiteral < Base extend AutoCorrector MSG = 'Space inside range literal.' def on_irange(node) check(node) end def on_erange(node) check(node) end private def check(node) expression = node.source op = node.loc.operator.source escaped_op = op.gsub('.', '\.') # account for multiline range literals expression.sub!(/#{escaped_op}\n\s*/, op) return unless /(\s#{escaped_op})|(#{escaped_op}\s)/.match?(expression) add_offense(node) do |corrector| corrector.replace( node, expression.sub(/\s+#{escaped_op}/, op).sub(/#{escaped_op}\s+/, op) ) 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/layout/multiline_assignment_layout.rb
lib/rubocop/cop/layout/multiline_assignment_layout.rb
# frozen_string_literal: true module RuboCop module Cop module Layout # Checks whether the multiline assignments have a newline # after the assignment operator. # # @example EnforcedStyle: new_line (default) # # bad # foo = if expression # 'bar' # end # # # good # foo = # if expression # 'bar' # end # # # good # foo = # begin # compute # rescue => e # nil # end # # @example EnforcedStyle: same_line # # good # foo = if expression # 'bar' # end # # @example SupportedTypes: ['block', 'case', 'class', 'if', 'kwbegin', 'module'] (default) # # good # foo = # if expression # 'bar' # end # # # good # foo = # [1].map do |i| # i + 1 # end # # @example SupportedTypes: ['block'] # # good # foo = if expression # 'bar' # end # # # good # foo = # [1].map do |i| # 'bar' * i # end # class MultilineAssignmentLayout < Base include CheckAssignment include ConfigurableEnforcedStyle include RangeHelp extend AutoCorrector NEW_LINE_OFFENSE = 'Right hand side of multi-line assignment is on ' \ 'the same line as the assignment operator `=`.' SAME_LINE_OFFENSE = 'Right hand side of multi-line assignment is not ' \ 'on the same line as the assignment operator `=`.' def check_assignment(node, rhs) return if node.send_type? && node.loc.operator&.source != '=' return unless rhs return unless supported_types.include?(rhs.type) return if rhs.single_line? check_by_enforced_style(node, rhs) end def check_by_enforced_style(node, rhs) case style when :new_line check_new_line_offense(node, rhs) when :same_line check_same_line_offense(node, rhs) end end def check_new_line_offense(node, rhs) return unless same_line?(node.loc.operator, rhs) add_offense(node, message: NEW_LINE_OFFENSE) do |corrector| corrector.insert_after(node.loc.operator, "\n") end end def check_same_line_offense(node, rhs) return unless node.loc.operator.line != rhs.first_line add_offense(node, message: SAME_LINE_OFFENSE) do |corrector| range = range_between( node.loc.operator.end_pos, extract_rhs(node).source_range.begin_pos ) corrector.replace(range, ' ') end end private def supported_types @supported_types ||= cop_config['SupportedTypes'].map(&:to_sym) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/begin_end_alignment.rb
lib/rubocop/cop/layout/begin_end_alignment.rb
# frozen_string_literal: true module RuboCop module Cop module Layout # Checks whether the end keyword of `begin` is aligned properly. # # Two modes are supported through the `EnforcedStyleAlignWith` configuration # parameter. If it's set to `start_of_line` (which is the default), the # `end` shall be aligned with the start of the line where the `begin` # keyword is. If it's set to `begin`, the `end` shall be aligned with the # `begin` keyword. # # `Layout/EndAlignment` cop aligns with keywords (e.g. `if`, `while`, `case`) # by default. On the other hand, `||= begin` that this cop targets tends to # align with the start of the line, it defaults to `EnforcedStyleAlignWith: start_of_line`. # These style can be configured by each cop. # # @example EnforcedStyleAlignWith: start_of_line (default) # # bad # foo ||= begin # do_something # end # # # good # foo ||= begin # do_something # end # # @example EnforcedStyleAlignWith: begin # # bad # foo ||= begin # do_something # end # # # good # foo ||= begin # do_something # end # class BeginEndAlignment < Base include EndKeywordAlignment extend AutoCorrector MSG = '`end` at %d, %d is not aligned with `%s` at %d, %d.' def on_kwbegin(node) check_begin_alignment(node) end private def check_begin_alignment(node) align_with = { begin: node.loc.begin, start_of_line: start_line_range(node) } check_end_kw_alignment(node, align_with) end def autocorrect(corrector, node) AlignmentCorrector.align_end(corrector, processed_source, node, alignment_node(node)) end def alignment_node(node) case style when :begin node else start_line_range(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/layout/indentation_consistency.rb
lib/rubocop/cop/layout/indentation_consistency.rb
# frozen_string_literal: true module RuboCop module Cop module Layout # Checks for inconsistent indentation. # # The difference between `indented_internal_methods` and `normal` is # that the `indented_internal_methods` style prescribes that in # classes and modules the `protected` and `private` modifier keywords # shall be indented the same as public methods and that protected and # private members shall be indented one step more than the modifiers. # Other than that, both styles mean that entities on the same logical # depth shall have the same indentation. # # @example EnforcedStyle: normal (default) # # bad # class A # def test # puts 'hello' # puts 'world' # end # end # # # bad # class A # def test # puts 'hello' # puts 'world' # end # # protected # # def foo # end # # private # # def bar # end # end # # # good # class A # def test # puts 'hello' # puts 'world' # end # end # # # good # class A # def test # puts 'hello' # puts 'world' # end # # protected # # def foo # end # # private # # def bar # end # end # # @example EnforcedStyle: indented_internal_methods # # bad # class A # def test # puts 'hello' # puts 'world' # end # end # # # bad # class A # def test # puts 'hello' # puts 'world' # end # # protected # # def foo # end # # private # # def bar # end # end # # # good # class A # def test # puts 'hello' # puts 'world' # end # end # # # good # class A # def test # puts 'hello' # puts 'world' # end # # protected # # def foo # end # # private # # def bar # end # end class IndentationConsistency < Base include Alignment include ConfigurableEnforcedStyle extend AutoCorrector MSG = 'Inconsistent indentation detected.' def on_begin(node) check(node) end def on_kwbegin(node) check(node) end private def autocorrect(corrector, node) AlignmentCorrector.correct(corrector, processed_source, node, column_delta) end # Not all nodes define `bare_access_modifier?` (for example, # `RuboCop::AST::DefNode` does not), so we must check `send_type?` first # to avoid a NoMethodError. def bare_access_modifier?(node) node.send_type? && node.bare_access_modifier? end # Returns an integer representing the correct indentation, or nil to # indicate that the correct indentation is that of the first child that # is not an access modifier. def base_column_for_normal_style(node) first_child = node.children.first return unless first_child && bare_access_modifier?(first_child) # If, as is most common, the access modifier is indented deeper than # the module (`access_modifier_indent > module_indent`) then the # indentation of the access modifier determines the correct # indentation. # # Otherwise, in the rare event that the access modifier is outdented # to the level of the module (see `AccessModifierIndentation` cop) we # return nil so that `check_alignment` will derive the correct # indentation from the first child that is not an access modifier. access_modifier_indent = display_column(first_child.source_range) return access_modifier_indent unless node.parent module_indent = display_column(node.parent.source_range) access_modifier_indent if access_modifier_indent > module_indent end def check(node) if style == :indented_internal_methods check_indented_internal_methods_style(node) else check_normal_style(node) end end def check_normal_style(node) check_alignment( node.children.reject { |child| bare_access_modifier?(child) }, base_column_for_normal_style(node) ) end def check_indented_internal_methods_style(node) children_to_check = [[]] node.children.each do |child| # Modifier nodes have special indentation and will be checked by # the AccessModifierIndentation cop. This cop uses them as dividers # in indented_internal_methods mode. Then consistency is checked # only within each section delimited by a modifier node. if bare_access_modifier?(child) children_to_check << [] else children_to_check.last << child end end children_to_check.each { |group| check_alignment(group) } end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/empty_line_between_defs.rb
lib/rubocop/cop/layout/empty_line_between_defs.rb
# frozen_string_literal: true module RuboCop module Cop module Layout # Checks whether class/module/method definitions are # separated by one or more empty lines. # # `NumberOfEmptyLines` can be an integer (default is 1) or # an array (e.g. [1, 2]) to specify a minimum and maximum # number of empty lines permitted. # # `AllowAdjacentOneLineDefs` configures whether adjacent # one-line definitions are considered an offense. # # @example EmptyLineBetweenMethodDefs: true (default) # # checks for empty lines between method definitions. # # # bad # def a # end # def b # end # # # good # def a # end # # def b # end # # @example EmptyLineBetweenClassDefs: true (default) # # checks for empty lines between class definitions. # # # bad # class A # end # class B # end # def b # end # # # good # class A # end # # class B # end # # def b # end # # @example EmptyLineBetweenModuleDefs: true (default) # # checks for empty lines between module definitions. # # # bad # module A # end # module B # end # def b # end # # # good # module A # end # # module B # end # # def b # end # # @example AllowAdjacentOneLineDefs: true (default) # # # good # class ErrorA < BaseError; end # class ErrorB < BaseError; end # # # good # class ErrorA < BaseError; end # # class ErrorB < BaseError; end # # # good - DefLikeMacros: [memoize] # memoize :attribute_a # memoize :attribute_b # # # good # memoize :attribute_a # # memoize :attribute_b # # @example AllowAdjacentOneLineDefs: false # # # bad # class ErrorA < BaseError; end # class ErrorB < BaseError; end # # # good # class ErrorA < BaseError; end # # class ErrorB < BaseError; end # # # bad - DefLikeMacros: [memoize] # memoize :attribute_a # memoize :attribute_b # # # good # memoize :attribute_a # # memoize :attribute_b # class EmptyLineBetweenDefs < Base include RangeHelp extend AutoCorrector MSG = 'Expected %<expected>s between %<type>s definitions; found %<actual>d.' def self.autocorrect_incompatible_with [Layout::EmptyLines] end # We operate on `begin` nodes, instead of using `OnMethodDef`, # so that we can walk over pairs of consecutive nodes and # efficiently access a node's predecessor; #prev_node ends up # doing a linear scan over siblings, so we don't want to call # it on each def. def on_begin(node) node.children.each_cons(2) do |prev, n| nodes = [prev, n] check_defs(nodes) if nodes.all? { |def_candidate| candidate?(def_candidate) } end end def check_defs(nodes) count = blank_lines_count_between(*nodes) return if line_count_allowed?(count) return if multiple_blank_lines_groups?(*nodes) return if nodes.all?(&:single_line?) && cop_config['AllowAdjacentOneLineDefs'] correction_node = nodes.last location = def_location(correction_node) add_offense(location, message: message(correction_node, count: count)) do |corrector| autocorrect(corrector, *nodes, count) end end def autocorrect(corrector, prev_def, node, count) # finds position of first newline end_pos = end_loc(prev_def).end_pos source_buffer = end_loc(prev_def).source_buffer newline_pos = source_buffer.source.index("\n", end_pos) # Handle the case when multiple one-liners are on the same line. begin_pos = node.source_range.begin_pos newline_pos = begin_pos - 1 if newline_pos > begin_pos if count > maximum_empty_lines autocorrect_remove_lines(corrector, newline_pos, count) else autocorrect_insert_lines(corrector, newline_pos, count) end end private def def_location(correction_node) if correction_node.any_block_type? correction_node.source_range.join(correction_node.children.first.source_range) elsif correction_node.send_type? correction_node.source_range else correction_node.loc.keyword.join(correction_node.loc.name) end end def candidate?(node) return false unless node method_candidate?(node) || class_candidate?(node) || module_candidate?(node) || macro_candidate?(node) end def empty_line_between_macros cop_config.fetch('DefLikeMacros', []).map(&:to_sym) end def macro_candidate?(node) macro_candidate = if node.any_block_type? node.send_node elsif node.send_type? node end return false unless macro_candidate macro_candidate.macro? && empty_line_between_macros.include?(macro_candidate.method_name) end def method_candidate?(node) cop_config['EmptyLineBetweenMethodDefs'] && node.any_def_type? end def class_candidate?(node) cop_config['EmptyLineBetweenClassDefs'] && node.class_type? end def module_candidate?(node) cop_config['EmptyLineBetweenModuleDefs'] && node.module_type? end def message(node, count: nil) type = node_type(node) format(MSG, type: type, expected: expected_lines, actual: count) end def expected_lines if allowance_range? "#{minimum_empty_lines..maximum_empty_lines} empty lines" else lines = maximum_empty_lines == 1 ? 'line' : 'lines' "#{maximum_empty_lines} empty #{lines}" end end def multiple_blank_lines_groups?(first_def_node, second_def_node) lines = lines_between_defs(first_def_node, second_def_node) blank_start = lines.each_index.select { |i| lines[i].blank? }.max non_blank_end = lines.each_index.reject { |i| lines[i].blank? }.min return false if blank_start.nil? || non_blank_end.nil? blank_start > non_blank_end end def line_count_allowed?(count) (minimum_empty_lines..maximum_empty_lines).cover?(count) end def blank_lines_count_between(first_def_node, second_def_node) lines_between_defs(first_def_node, second_def_node).count(&:blank?) end def minimum_empty_lines Array(cop_config['NumberOfEmptyLines']).first end def maximum_empty_lines Array(cop_config['NumberOfEmptyLines']).last end def lines_between_defs(first_def_node, second_def_node) begin_line_num = def_end(first_def_node) end_line_num = def_start(second_def_node) - 2 return [] if end_line_num.negative? processed_source.lines[begin_line_num..end_line_num] end def def_start(node) node = node.send_node if node.any_block_type? if node.send_type? node.source_range.line else node.loc.keyword.line end end def def_end(node) end_loc(node).line end def end_loc(node) node.source_range.end end def autocorrect_remove_lines(corrector, newline_pos, count) difference = count - maximum_empty_lines range_to_remove = range_between(newline_pos, newline_pos + difference) corrector.remove(range_to_remove) end def autocorrect_insert_lines(corrector, newline_pos, count) difference = minimum_empty_lines - count where_to_insert = range_between(newline_pos, newline_pos + 1) corrector.insert_after(where_to_insert, "\n" * difference) end def node_type(node) case node.type when :def, :defs :method when :numblock, :itblock :block else node.type end end def allowance_range? minimum_empty_lines != maximum_empty_lines end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/empty_lines_around_attribute_accessor.rb
lib/rubocop/cop/layout/empty_lines_around_attribute_accessor.rb
# frozen_string_literal: true module RuboCop module Cop module Layout # Checks for a newline after an attribute accessor or a group of them. # `alias` syntax and `alias_method`, `public`, `protected`, and `private` methods are allowed # by default. These are customizable with `AllowAliasSyntax` and `AllowedMethods` options. # # @example # # bad # attr_accessor :foo # def do_something # end # # # good # attr_accessor :foo # # def do_something # end # # # good # attr_accessor :foo # attr_reader :bar # attr_writer :baz # attr :qux # # def do_something # end # # @example AllowAliasSyntax: true (default) # # good # attr_accessor :foo # alias :foo? :foo # # def do_something # end # # @example AllowAliasSyntax: false # # bad # attr_accessor :foo # alias :foo? :foo # # def do_something # end # # # good # attr_accessor :foo # # alias :foo? :foo # # def do_something # end # # @example AllowedMethods: ['private'] # # good # attr_accessor :foo # private :foo # # def do_something # end # class EmptyLinesAroundAttributeAccessor < Base include RangeHelp include AllowedMethods extend AutoCorrector MSG = 'Add an empty line after attribute accessor.' def on_send(node) return unless node.attribute_accessor? return if next_line_empty?(node.last_line) return if next_line_empty_or_enable_directive_comment?(node.last_line) next_line_node = next_line_node(node) return unless require_empty_line?(next_line_node) add_offense(node) { |corrector| autocorrect(corrector, node) } end private def autocorrect(corrector, node) node_range = range_by_whole_lines(node.source_range) next_line = node_range.last_line + 1 if next_line_enable_directive_comment?(next_line) node_range = processed_source.comment_at_line(next_line) end corrector.insert_after(node_range, "\n") end def next_line_empty_or_enable_directive_comment?(line) return true if next_line_empty?(line) next_line = line + 1 next_line_enable_directive_comment?(next_line) && next_line_empty?(next_line) end def next_line_enable_directive_comment?(line) return false unless (comment = processed_source.comment_at_line(line)) DirectiveComment.new(comment).enabled? end def next_line_empty?(line) processed_source[line].nil? || processed_source[line].blank? end def require_empty_line?(node) return false unless node.respond_to?(:type) !allow_alias?(node) && !attribute_or_allowed_method?(node) end def next_line_node(node) return if node.parent.if_type? node.right_sibling end def allow_alias?(node) allow_alias_syntax? && node.alias_type? end def attribute_or_allowed_method?(node) return false unless node.send_type? node.attribute_accessor? || allowed_method?(node.method_name) end def allow_alias_syntax? cop_config.fetch('AllowAliasSyntax', 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/layout/multiline_method_call_indentation.rb
lib/rubocop/cop/layout/multiline_method_call_indentation.rb
# frozen_string_literal: true module RuboCop module Cop module Layout # Checks the indentation of the method name part in method calls # that span more than one line. # # @example EnforcedStyle: aligned (default) # # bad # while myvariable # .b # # do something # end # # # good # while myvariable # .b # # do something # end # # # good # Thing.a # .b # .c # # @example EnforcedStyle: indented # # good # while myvariable # .b # # # do something # end # # @example EnforcedStyle: indented_relative_to_receiver # # good # while myvariable # .a # .b # # # do something # end # # # good # myvariable = Thing # .a # .b # .c class MultilineMethodCallIndentation < Base include ConfigurableEnforcedStyle include Alignment include MultilineExpressionIndentation extend AutoCorrector def validate_config return unless style == :aligned && cop_config['IndentationWidth'] raise ValidationError, 'The `Layout/MultilineMethodCallIndentation` ' \ 'cop only accepts an `IndentationWidth` ' \ 'configuration parameter when ' \ '`EnforcedStyle` is `indented`.' end private def autocorrect(corrector, node) AlignmentCorrector.correct(corrector, processed_source, node, @column_delta) end def relevant_node?(send_node) send_node.loc.dot # Only check method calls with dot operator end def right_hand_side(send_node) dot = send_node.loc.dot selector = send_node.loc.selector if (send_node.dot? || send_node.safe_navigation?) && selector && same_line?(dot, selector) dot.join(selector) elsif selector selector elsif send_node.implicit_call? dot.join(send_node.loc.begin) end end # rubocop:disable Metrics/AbcSize def offending_range(node, lhs, rhs, given_style) return false unless begins_its_line?(rhs) return false if not_for_this_cop?(node) @base = alignment_base(node, rhs, given_style) correct_column = if @base parent = node.parent parent = parent.parent if parent&.any_block_type? @base.column + extra_indentation(given_style, parent) else indentation(lhs) + correct_indentation(node) end @column_delta = correct_column - rhs.column rhs if @column_delta.nonzero? end # rubocop:enable Metrics/AbcSize def extra_indentation(given_style, parent) if given_style == :indented_relative_to_receiver if parent&.type?(:splat, :kwsplat) configured_indentation_width - parent.loc.operator.length else configured_indentation_width end else 0 end end def message(node, lhs, rhs) if should_indent_relative_to_receiver? relative_to_receiver_message(rhs) elsif should_align_with_base? align_with_base_message(rhs) else no_base_message(lhs, rhs, node) end end def should_indent_relative_to_receiver? @base && style == :indented_relative_to_receiver end def should_align_with_base? @base && style != :indented_relative_to_receiver end def relative_to_receiver_message(rhs) "Indent `#{rhs.source}` #{configured_indentation_width} spaces " \ "more than `#{base_source}` on line #{@base.line}." end def align_with_base_message(rhs) "Align `#{rhs.source}` with `#{base_source}` on line #{@base.line}." end def base_source @base.source[/[^\n]*/] end def no_base_message(lhs, rhs, node) used_indentation = rhs.column - indentation(lhs) what = operation_description(node, rhs) "Use #{correct_indentation(node)} (not #{used_indentation}) " \ "spaces for indenting #{what} spanning multiple lines." end def alignment_base(node, rhs, given_style) case given_style when :aligned semantic_alignment_base(node, rhs) || syntactic_alignment_base(node, rhs) when :indented nil when :indented_relative_to_receiver receiver_alignment_base(node) end end def syntactic_alignment_base(lhs, rhs) # a if b # .c kw_node_with_special_indentation(lhs) do |base| return indented_keyword_expression(base).source_range end # a = b # .c part_of_assignment_rhs(lhs, rhs) { |base| return assignment_rhs(base).source_range } # a + b # .c operation_rhs(lhs) { |base| return base.source_range } end # a.b # .c def semantic_alignment_base(node, rhs) return unless rhs.source.start_with?('.', '&.') node = semantic_alignment_node(node) return unless node&.loc&.selector && node.loc.dot node.loc.dot.join(node.loc.selector) end # a # .b # .c def receiver_alignment_base(node) node = node.receiver while node.receiver node = node.parent node = node.parent until node.loc.dot node&.receiver&.source_range end def semantic_alignment_node(node) return if argument_in_method_call(node, :with_parentheses) dot_right_above = get_dot_right_above(node) return dot_right_above if dot_right_above if (multiline_block_chain_node = find_multiline_block_chain_node(node)) return multiline_block_chain_node end node = first_call_has_a_dot(node) return if node.loc.dot.line != node.first_line node end def get_dot_right_above(node) node.each_ancestor.find do |a| dot = a.loc.dot if a.loc?(:dot) next unless dot dot.line == node.loc.dot.line - 1 && dot.column == node.loc.dot.column end end def find_multiline_block_chain_node(node) return unless (block_node = node.each_descendant(:any_block).first) return unless block_node.multiline? && block_node.parent.call_type? if node.receiver.call_type? node.receiver else block_node.parent end end def first_call_has_a_dot(node) # descend to root of method chain node = node.receiver while node.receiver # ascend to first call which has a dot node = node.parent node = node.parent until node.loc?(:dot) node end def operation_rhs(node) operation_rhs = node.receiver.each_ancestor(:send).find do |rhs| operator_rhs?(rhs, node.receiver) end return unless operation_rhs yield operation_rhs.first_argument end def operator_rhs?(node, receiver) node.operator_method? && node.arguments? && within_node?(receiver, node.first_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/layout/first_method_parameter_line_break.rb
lib/rubocop/cop/layout/first_method_parameter_line_break.rb
# frozen_string_literal: true module RuboCop module Cop module Layout # Checks for a line break before the first parameter in a # multi-line method parameter definition. # # @example # # # bad # def method(foo, bar, # baz) # do_something # end # # # good # def method( # foo, bar, # baz) # do_something # end # # # ignored # def method foo, # bar # do_something # end # # @example AllowMultilineFinalElement: false (default) # # # bad # def method(foo, bar, baz = { # :a => "b", # }) # do_something # end # # # good # def method( # foo, bar, baz = { # :a => "b", # }) # do_something # end # # @example AllowMultilineFinalElement: true # # # good # def method(foo, bar, baz = { # :a => "b", # }) # do_something # end # class FirstMethodParameterLineBreak < Base include FirstElementLineBreak extend AutoCorrector MSG = 'Add a line break before the first parameter of a multi-line method parameter list.' def on_def(node) check_method_line_break(node, node.arguments, ignore_last: ignore_last_element?) end alias on_defs on_def private def ignore_last_element? !!cop_config['AllowMultilineFinalElement'] end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/space_around_operators.rb
lib/rubocop/cop/layout/space_around_operators.rb
# frozen_string_literal: true module RuboCop module Cop module Layout # Checks that operators have space around them, except for ** which # should or shouldn't have surrounding space depending on configuration. # It allows vertical alignment consisting of one or more whitespace # around operators. # # This cop has `AllowForAlignment` option. When `true`, allows most # uses of extra spacing if the intent is to align with an operator on # the previous or next line, not counting empty lines or comment lines. # # @example # # bad # total = 3*4 # "apple"+"juice" # my_number = 38/4 # # # good # total = 3 * 4 # "apple" + "juice" # my_number = 38 / 4 # # @example AllowForAlignment: true (default) # # good # { # 1 => 2, # 11 => 3 # } # # @example AllowForAlignment: false # # bad # { # 1 => 2, # 11 => 3 # } # # @example EnforcedStyleForExponentOperator: no_space (default) # # bad # a ** b # # # good # a**b # # @example EnforcedStyleForExponentOperator: space # # bad # a**b # # # good # a ** b # # @example EnforcedStyleForRationalLiterals: no_space (default) # # bad # 1 / 48r # # # good # 1/48r # # @example EnforcedStyleForRationalLiterals: space # # bad # 1/48r # # # good # 1 / 48r class SpaceAroundOperators < Base include PrecedingFollowingAlignment include RangeHelp include RationalLiteral extend AutoCorrector IRREGULAR_METHODS = %i[[] ! []=].freeze EXCESSIVE_SPACE = ' ' def self.autocorrect_incompatible_with [Style::SelfAssignment] end def on_sclass(node) check_operator(:sclass, node.loc.operator, node) end def on_pair(node) return unless node.hash_rocket? return if hash_table_style? && !node.parent.pairs_on_same_line? check_operator(:pair, node.loc.operator, node) end def on_if(node) return unless node.ternary? check_operator(:if, node.loc.question, node.if_branch) check_operator(:if, node.loc.colon, node.else_branch) end def on_resbody(node) return unless node.loc.assoc check_operator(:resbody, node.loc.assoc, node.exception_variable) end def on_send(node) return if rational_literal?(node) if node.setter_method? on_setter_method(node) elsif regular_operator?(node) check_operator(:send, node.loc.selector, node.first_argument) end end def on_assignment(node) rhs = node.rhs return unless rhs type = node.op_asgn_type? ? :special_asgn : :assignment check_operator(type, node.loc.operator, rhs) end def on_class(node) rhs = node.parent_class return unless rhs check_operator(:class, node.loc.operator, rhs) end def on_binary(node) rhs = node.rhs return unless rhs check_operator(:binary, node.loc.operator, rhs) end def on_setter_method(node) rhs = node.first_argument return unless rhs check_operator(:special_asgn, node.loc.operator, node.first_argument) end def on_match_pattern(node) return if target_ruby_version < 3.0 check_operator(:match_pattern, node.loc.operator, node) end def on_match_alt(node) check_operator(:match_alt, node.loc.operator, node) end def on_match_as(node) check_operator(:match_as, node.loc.operator, node) end alias on_or on_binary alias on_and on_binary alias on_lvasgn on_assignment alias on_casgn on_assignment alias on_masgn on_assignment alias on_ivasgn on_assignment alias on_cvasgn on_assignment alias on_gvasgn on_assignment alias on_or_asgn on_assignment alias on_and_asgn on_assignment alias on_op_asgn on_assignment private def regular_operator?(send_node) return false if send_node.unary_operation? || send_node.dot? || send_node.double_colon? operator_with_regular_syntax?(send_node) end def operator_with_regular_syntax?(send_node) send_node.operator_method? && !IRREGULAR_METHODS.include?(send_node.method_name) end def check_operator(type, operator, right_operand) with_space = range_with_surrounding_space(operator) return if with_space.source.start_with?("\n") comment = processed_source.comment_at_line(operator.line) return if comment && with_space.last_column == comment.loc.column offense(type, operator, with_space, right_operand) do |msg| add_offense(operator, message: msg) do |corrector| autocorrect(corrector, with_space, right_operand) end end end def offense(type, operator, with_space, right_operand) msg = offense_message(type, operator, with_space, right_operand) yield msg if msg end def autocorrect(corrector, range, right_operand) range_source = range.source if range_source.include?('**') && !space_around_exponent_operator? corrector.replace(range, '**') elsif range_source.include?('/') && !space_around_slash_operator?(right_operand) corrector.replace(range, '/') elsif range_source.end_with?("\n") corrector.replace(range, " #{range_source.strip}\n") else enclose_operator_with_space(corrector, range) end end def enclose_operator_with_space(corrector, range) operator = range.source # If `ForceEqualSignAlignment` is true, `Layout/ExtraSpacing` cop # inserts spaces before operator. If `Layout/SpaceAroundOperators` cop # inserts a space, it collides and raises the infinite loop error. if force_equal_sign_alignment? && !operator.end_with?(' ') corrector.insert_after(range, ' ') else corrector.replace(range, " #{operator.strip} ") end end def offense_message(type, operator, with_space, right_operand) if should_not_have_surrounding_space?(operator, right_operand) return if with_space.is?(operator.source) "Space around operator `#{operator.source}` detected." elsif !/^\s.*\s$/.match?(with_space.source) "Surrounding space missing for operator `#{operator.source}`." elsif excess_leading_space?(type, operator, with_space) || excess_trailing_space?(right_operand.source_range, with_space) "Operator `#{operator.source}` should be surrounded " \ 'by a single space.' end end def excess_leading_space?(type, operator, with_space) return false unless allow_for_alignment? return false unless with_space.source.start_with?(EXCESSIVE_SPACE) return !aligned_with_operator?(operator) unless type == :assignment token = Token.new(operator, nil, operator.source) align_preceding = aligned_with_preceding_equals_operator(token) return false if align_preceding == :yes || aligned_with_subsequent_equals_operator(token) == :none aligned_with_subsequent_equals_operator(token) != :yes end def excess_trailing_space?(right_operand, with_space) with_space.source.end_with?(EXCESSIVE_SPACE) && (!allow_for_alignment? || !aligned_with_something?(right_operand)) end def align_hash_cop_config config.for_cop('Layout/HashAlignment') end def hash_table_style? return false unless align_hash_cop_config enforced_styles = Array(align_hash_cop_config['EnforcedHashRocketStyle']) enforced_styles.include?('table') end def space_around_exponent_operator? cop_config['EnforcedStyleForExponentOperator'] == 'space' end def space_around_slash_operator?(right_operand) return true unless right_operand.rational_type? cop_config['EnforcedStyleForRationalLiterals'] == 'space' end def force_equal_sign_alignment? config.for_cop('Layout/ExtraSpacing')['ForceEqualSignAlignment'] end def should_not_have_surrounding_space?(operator, right_operand) if operator.is?('**') !space_around_exponent_operator? elsif operator.is?('/') !space_around_slash_operator?(right_operand) else false end end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/rescue_ensure_alignment.rb
lib/rubocop/cop/layout/rescue_ensure_alignment.rb
# frozen_string_literal: true module RuboCop module Cop module Layout # Checks whether the rescue and ensure keywords are aligned # properly. # # @example # # # bad # begin # something # rescue # puts 'error' # end # # # good # begin # something # rescue # puts 'error' # end class RescueEnsureAlignment < Base include RangeHelp include EndKeywordAlignment extend AutoCorrector MSG = '`%<kw_loc>s` at %<kw_loc_line>d, %<kw_loc_column>d is not ' \ 'aligned with `%<beginning>s` at ' \ '%<begin_loc_line>d, %<begin_loc_column>d.' ANCESTOR_TYPES = %i[kwbegin any_def class module sclass any_block].freeze ALTERNATIVE_ACCESS_MODIFIERS = %i[public_class_method private_class_method].freeze def on_resbody(node) check(node) unless modifier?(node) end def on_ensure(node) check(node) end def on_new_investigation @modifier_locations = processed_source.tokens.each_with_object([]) do |token, locations| next unless token.rescue_modifier? locations << token.pos end end private # Check alignment of node with rescue or ensure modifiers. def check(node) alignment_node = alignment_node(node) return if alignment_node.nil? alignment_loc = alignment_location(alignment_node) kw_loc = node.loc.keyword return if alignment_loc.column == kw_loc.column || same_line?(alignment_loc, kw_loc) add_offense( kw_loc, message: format_message(alignment_node, alignment_loc, kw_loc) ) do |corrector| autocorrect(corrector, node, alignment_loc) end end def autocorrect(corrector, node, alignment_location) whitespace = whitespace_range(node) # Some inline node is sitting before current node. return nil unless whitespace.source.strip.empty? new_column = alignment_location.column corrector.replace(whitespace, ' ' * new_column) end def format_message(alignment_node, alignment_loc, kw_loc) format( MSG, kw_loc: kw_loc.source, kw_loc_line: kw_loc.line, kw_loc_column: kw_loc.column, beginning: alignment_source(alignment_node, alignment_loc), begin_loc_line: alignment_loc.line, begin_loc_column: alignment_loc.column ) end # rubocop:disable Metrics/AbcSize, Metrics/MethodLength def alignment_source(node, starting_loc) ending_loc = case node.type when :block, :numblock, :itblock, :kwbegin node.loc.begin when :def, :defs, :class, :module, :lvasgn, :ivasgn, :cvasgn, :gvasgn, :casgn node.loc.name when :sclass node.identifier.source_range when :masgn node.lhs.source_range else # It is a wrapper with receiver of object attribute or access modifier. node.receiver&.source_range || node.child_nodes.first.loc.name end range_between(starting_loc.begin_pos, ending_loc.end_pos).source end # rubocop:enable Metrics/AbcSize, Metrics/MethodLength # We will use ancestor or wrapper with access modifier. def alignment_node(node) ancestor_node = ancestor_node(node) return ancestor_node if ancestor_node.nil? || ancestor_node.kwbegin_type? return if ancestor_node.respond_to?(:send_node) && aligned_with_line_break_method?(ancestor_node, node) assignment_node = assignment_node(ancestor_node) return assignment_node if same_line?(ancestor_node, assignment_node) access_modifier_node = access_modifier_node(ancestor_node) return access_modifier_node unless access_modifier_node.nil? ancestor_node end def ancestor_node(node) node.each_ancestor(*ANCESTOR_TYPES).first end def aligned_with_line_break_method?(ancestor_node, node) send_node_loc = ancestor_node.send_node.loc do_keyword_line = ancestor_node.loc.begin.line rescue_keyword_column = node.loc.keyword.column selector = send_node_loc.respond_to?(:selector) ? send_node_loc.selector : send_node_loc if aligned_with_leading_dot?(do_keyword_line, send_node_loc, rescue_keyword_column) return true end do_keyword_line == selector&.line && rescue_keyword_column == selector.column end def aligned_with_leading_dot?(do_keyword_line, send_node_loc, rescue_keyword_column) return false unless send_node_loc.respond_to?(:dot) && (dot = send_node_loc.dot) do_keyword_line == dot.line && rescue_keyword_column == dot.column end def assignment_node(node) assignment_node = node.ancestors.first return nil unless assignment_node&.assignment? assignment_node end def access_modifier_node(node) return nil unless node.any_def_type? access_modifier_node = node.ancestors.first return nil unless access_modifier?(access_modifier_node) access_modifier_node end def modifier?(node) return false unless @modifier_locations.respond_to?(:include?) @modifier_locations.include?(node.loc.keyword) end def whitespace_range(node) begin_pos = node.loc.keyword.begin_pos current_column = node.loc.keyword.column range_between(begin_pos - current_column, begin_pos) end def access_modifier?(node) return true if node.respond_to?(:access_modifier?) && node.access_modifier? return true if node.respond_to?(:method_name) && ALTERNATIVE_ACCESS_MODIFIERS.include?(node.method_name) false end def alignment_location(alignment_node) if begin_end_alignment_style == 'start_of_line' start_line_range(alignment_node) elsif alignment_node.any_block_type? # If the alignment node is a block, the `rescue`/`ensure` keyword should # be aligned to the start of the block. It is possible that the block's # `send_node` spans multiple lines, in which case it should align to the # start of the last line. send_node = alignment_node.send_node range = processed_source.buffer.line_range(send_node.last_line) range.adjust(begin_pos: range.source =~ /\S/) else alignment_node.source_range end end def begin_end_alignment_style begin_end_alignment_conf = config.for_cop('Layout/BeginEndAlignment') begin_end_alignment_conf['Enabled'] && begin_end_alignment_conf['EnforcedStyleAlignWith'] end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/empty_lines_around_arguments.rb
lib/rubocop/cop/layout/empty_lines_around_arguments.rb
# frozen_string_literal: true module RuboCop module Cop module Layout # Checks if empty lines exist around the arguments # of a method invocation. # # @example # # bad # do_something( # foo # # ) # # process(bar, # # baz: qux, # thud: fred) # # some_method( # # [1,2,3], # x: y # ) # # # good # do_something( # foo # ) # # process(bar, # baz: qux, # thud: fred) # # some_method( # [1,2,3], # x: y # ) # class EmptyLinesAroundArguments < Base include RangeHelp extend AutoCorrector MSG = 'Empty line detected around arguments.' def on_send(node) return if node.single_line? || node.arguments.empty? || receiver_and_method_call_on_different_lines?(node) extra_lines(node) do |range| add_offense(range) do |corrector| corrector.remove(range) end end end alias on_csend on_send private def receiver_and_method_call_on_different_lines?(node) node.receiver && node.receiver.loc.last_line != node.loc.selector&.line end def extra_lines(node, &block) node.arguments.each do |arg| empty_range_for_starting_point(arg.source_range.begin, &block) end empty_range_for_starting_point(node.loc.end.begin, &block) if node.loc.end end def empty_range_for_starting_point(start) range = range_with_surrounding_space(start, whitespace: true, side: :left) return unless range.last_line - range.first_line > 1 yield range.source_buffer.line_range(range.last_line - 1).adjust(end_pos: 1) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/empty_comment.rb
lib/rubocop/cop/layout/empty_comment.rb
# frozen_string_literal: true module RuboCop module Cop module Layout # Checks empty comment. # # @example # # bad # # # # class Foo # end # # # good # # # # # Description of `Foo` class. # # # class Foo # end # # @example AllowBorderComment: true (default) # # good # # def foo # end # # ################# # # def bar # end # # @example AllowBorderComment: false # # bad # # def foo # end # # ################# # # def bar # end # # @example AllowMarginComment: true (default) # # good # # # # # Description of `Foo` class. # # # class Foo # end # # @example AllowMarginComment: false # # bad # # # # # Description of `Foo` class. # # # class Foo # end # class EmptyComment < Base include RangeHelp extend AutoCorrector MSG = 'Source code comment is empty.' def on_new_investigation if allow_margin_comment? comments = concat_consecutive_comments(processed_source.comments) investigate(comments) else processed_source.comments.each do |comment| next unless empty_comment_only?(comment_text(comment)) add_offense(comment) { |corrector| autocorrect(corrector, comment) } end end end private def investigate(comments) comments.each do |comment| next unless empty_comment_only?(comment[0]) comment[1].each do |offense_comment| add_offense(offense_comment) do |corrector| autocorrect(corrector, offense_comment) end end end end def autocorrect(corrector, node) previous_token = previous_token(node) range = if previous_token && same_line?(node, previous_token) range_with_surrounding_space(node.source_range, newlines: false) else range_by_whole_lines(node.source_range, include_final_newline: true) end corrector.remove(range) end def concat_consecutive_comments(comments) consecutive_comments = comments.chunk_while do |i, j| i.loc.line.succ == j.loc.line && i.loc.column == j.loc.column end consecutive_comments.map do |chunk| joined_text = chunk.map { |c| comment_text(c) }.join [joined_text, chunk] end end def empty_comment_only?(comment_text) empty_comment_pattern = if allow_border_comment? /\A(#\n)+\z/ else /\A(#+\n)+\z/ end empty_comment_pattern.match?(comment_text) end def comment_text(comment) "#{comment.text.strip}\n" end def allow_border_comment? cop_config['AllowBorderComment'] end def allow_margin_comment? cop_config['AllowMarginComment'] end def current_token(comment) processed_source.tokens.find { |token| token.pos == comment.source_range } end def previous_token(node) current_token = current_token(node) index = processed_source.tokens.index(current_token) index.zero? ? nil : processed_source.tokens[index - 1] end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/nil_methods.rb
lib/rubocop/cop/mixin/nil_methods.rb
# frozen_string_literal: true module RuboCop module Cop # This module provides a list of methods that are: # 1. In the NilClass by default # 2. Added to NilClass by explicitly requiring any standard libraries # 3. Cop's configuration parameter AllowedMethods. module NilMethods include AllowedMethods private def nil_methods nil.methods + other_stdlib_methods + allowed_methods.map(&:to_sym) end def other_stdlib_methods [:to_d] end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/hash_alignment_styles.rb
lib/rubocop/cop/mixin/hash_alignment_styles.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for checking hash alignment. module HashAlignmentStyles # Handles calculation of deltas when the enforced style is 'key'. class KeyAlignment def checkable_layout?(_node) true end def deltas_for_first_pair(first_pair) { separator: separator_delta(first_pair), value: value_delta(first_pair) } end def deltas(first_pair, current_pair) if Util.begins_its_line?(current_pair.source_range) key_delta = first_pair.key_delta(current_pair) separator_delta = separator_delta(current_pair) value_delta = value_delta(current_pair) { key: key_delta, separator: separator_delta, value: value_delta } else {} end end private def separator_delta(pair) if pair.hash_rocket? correct_separator_column = pair.key.source_range.end.column + 1 actual_separator_column = pair.loc.operator.column correct_separator_column - actual_separator_column else 0 end end def value_delta(pair) return 0 if pair.value_on_new_line? || pair.value_omission? correct_value_column = pair.loc.operator.end.column + 1 actual_value_column = pair.value.loc.column correct_value_column - actual_value_column end end # Common functionality for checking alignment of hash values. module ValueAlignment def checkable_layout?(node) !node.pairs_on_same_line? && !node.mixed_delimiters? end def deltas(first_pair, current_pair) key_delta = key_delta(first_pair, current_pair) separator_delta = separator_delta(first_pair, current_pair, key_delta) value_delta = value_delta(first_pair, current_pair) - key_delta - separator_delta { key: key_delta, separator: separator_delta, value: value_delta } end private def separator_delta(first_pair, current_pair, key_delta) if current_pair.hash_rocket? hash_rocket_delta(first_pair, current_pair) - key_delta else 0 end end end # Handles calculation of deltas when the enforced style is 'table'. class TableAlignment include ValueAlignment def deltas_for_first_pair(first_pair) separator_delta = separator_delta(first_pair, first_pair, 0) { separator: separator_delta, value: value_delta(first_pair, first_pair) - separator_delta } end private def key_delta(first_pair, current_pair) first_pair.key_delta(current_pair) end def hash_rocket_delta(first_pair, current_pair) first_pair.loc.column + max_key_width(first_pair.parent) + 1 - current_pair.loc.operator.column end def value_delta(first_pair, current_pair) correct_value_column = first_pair.key.loc.column + max_key_width(first_pair.parent) + max_delimiter_width(first_pair.parent) current_pair.value_omission? ? 0 : correct_value_column - current_pair.value.loc.column end def max_key_width(hash_node) hash_node.keys.map { |key| key.source.length }.max end def max_delimiter_width(hash_node) hash_node.pairs.map { |pair| pair.delimiter(true).length }.max end end # Handles calculation of deltas when the enforced style is 'separator'. class SeparatorAlignment include ValueAlignment def deltas_for_first_pair(_first_pair) {} end private def key_delta(first_pair, current_pair) first_pair.key_delta(current_pair, :right) end def hash_rocket_delta(first_pair, current_pair) first_pair.delimiter_delta(current_pair) end def value_delta(first_pair, current_pair) current_pair.value_omission? ? 0 : first_pair.value_delta(current_pair) end end # Handles calculation of deltas for `kwsplat` nodes. # This is a special case that just ensures the kwsplat is aligned with the rest of the hash # since a `kwsplat` does not have a key, separator or value. class KeywordSplatAlignment def deltas(first_pair, current_pair) if Util.begins_its_line?(current_pair.source_range) { key: first_pair.key_delta(current_pair) } else {} 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/mixin/configurable_formatting.rb
lib/rubocop/cop/mixin/configurable_formatting.rb
# frozen_string_literal: true module RuboCop module Cop # Shared functionality between mixins that enforce naming conventions module ConfigurableFormatting include ConfigurableEnforcedStyle def check_name(node, name, name_range) if valid_name?(node, name) correct_style_detected else add_offense(name_range, message: message(style)) { report_opposing_styles(node, name) } end end def report_opposing_styles(node, name) alternative_styles.each do |alternative| return unexpected_style_detected(alternative) if valid_name?(node, name, alternative) end unrecognized_style_detected end def valid_name?(node, name, given_style = style) name.match?(self.class::FORMATS.fetch(given_style)) || class_emitter_method?(node, name) end # A class emitter method is a singleton method in a class/module, where # the method has the same name as a class defined in the class/module. def class_emitter_method?(node, name) return false unless node.parent && node.defs_type? # a class emitter method may be defined inside `def self.included`, # `def self.extended`, etc. node = node.parent while node.parent.defs_type? node.parent.each_child_node(:class).any? { |c| c.loc.name.is?(name.to_s) } end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/multiline_element_indentation.rb
lib/rubocop/cop/mixin/multiline_element_indentation.rb
# frozen_string_literal: true module RuboCop module Cop # Common code for indenting the first elements in multiline # array literals, hash literals, and method definitions. module MultilineElementIndentation private def each_argument_node(node, type) left_parenthesis = node.loc.begin return unless left_parenthesis node.arguments.each do |arg| on_node(type, arg, :send) do |type_node| left_brace = type_node.loc.begin if left_brace && same_line?(left_brace, left_parenthesis) yield type_node, left_parenthesis ignore_node(type_node) end end end end def check_first(first, left_brace, left_parenthesis, offset) actual_column = first.source_range.column indent_base_column, indent_base_type = indent_base(left_brace, first, left_parenthesis) expected_column = indent_base_column + configured_indentation_width + offset @column_delta = expected_column - actual_column styles = detected_styles(actual_column, offset, left_parenthesis, left_brace) if @column_delta.zero? check_expected_style(styles) else incorrect_style_detected(styles, first, indent_base_type) end end def check_expected_style(styles) if styles.size > 1 ambiguous_style_detected(*styles) else correct_style_detected end end def indent_base(left_brace, first, left_parenthesis) return [left_brace.column, :left_brace_or_bracket] if style == brace_alignment_style pair = hash_pair_where_value_beginning_with(left_brace, first) if pair && key_and_value_begin_on_same_line?(pair) && right_sibling_begins_on_subsequent_line?(pair) return [pair.loc.column, :parent_hash_key] end if left_parenthesis && style == :special_inside_parentheses return [left_parenthesis.column + 1, :first_column_after_left_parenthesis] end [left_brace.source_line =~ /\S/, :start_of_line] end def hash_pair_where_value_beginning_with(left_brace, first) return unless first && first.parent.loc.begin == left_brace first.parent&.parent&.pair_type? ? first.parent.parent : nil end def key_and_value_begin_on_same_line?(pair) same_line?(pair.key, pair.value) end def right_sibling_begins_on_subsequent_line?(pair) pair.right_sibling && (pair.last_line < pair.right_sibling.first_line) end def detected_styles(actual_column, offset, left_parenthesis, left_brace) base_column = actual_column - configured_indentation_width - offset detected_styles_for_column(base_column, left_parenthesis, left_brace) end def detected_styles_for_column(column, left_parenthesis, left_brace) styles = [] if column == (left_brace.source_line =~ /\S/) styles << :consistent styles << :special_inside_parentheses unless left_parenthesis end if left_parenthesis && column == left_parenthesis.column + 1 styles << :special_inside_parentheses end styles << brace_alignment_style if column == left_brace.column styles end def incorrect_style_detected(styles, first, base_column_type) msg = message(base_description(base_column_type)) add_offense(first, message: msg) do |corrector| autocorrect(corrector, first) ambiguous_style_detected(*styles) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/range_help.rb
lib/rubocop/cop/mixin/range_help.rb
# frozen_string_literal: true module RuboCop module Cop # Methods that calculate and return Parser::Source::Ranges module RangeHelp BYTE_ORDER_MARK = 0xfeff # The Unicode codepoint NOT_GIVEN = Module.new private def source_range(source_buffer, line_number, column, length = 1) if column.is_a?(Range) column_index = column.begin length = column.size else column_index = column end line_begin_pos = if line_number.zero? 0 else source_buffer.line_range(line_number).begin_pos end begin_pos = line_begin_pos + column_index end_pos = begin_pos + length Parser::Source::Range.new(source_buffer, begin_pos, end_pos) end # A range containing only the contents of a literal with delimiters (e.g. in # `%i{1 2 3}` this will be the range covering `1 2 3` only). def contents_range(node) range_between(node.loc.begin.end_pos, node.loc.end.begin_pos) end # A range containing the first to the last argument # of a method call or method definition. # def foo(a, b:) # ^^^^^ # bar(1, 2, 3, &blk) # ^^^^^^^^^^^^^ # baz { |x, y:, z:| } # ^^^^^^^^^ def arguments_range(node) node.first_argument.source_range.join(node.last_argument.source_range) end def range_between(start_pos, end_pos) Parser::Source::Range.new(processed_source.buffer, start_pos, end_pos) end def range_with_surrounding_comma(range, side = :both) buffer = @processed_source.buffer src = buffer.source go_left, go_right = directions(side) begin_pos = range.begin_pos end_pos = range.end_pos begin_pos = move_pos(src, begin_pos, -1, go_left, /,/) end_pos = move_pos(src, end_pos, 1, go_right, /,/) Parser::Source::Range.new(buffer, begin_pos, end_pos) end def range_with_surrounding_space(range_positional = NOT_GIVEN, # rubocop:disable Metrics/ParameterLists range: NOT_GIVEN, side: :both, newlines: true, whitespace: false, continuations: false, buffer: @processed_source.buffer) range = range_positional unless range_positional == NOT_GIVEN src = buffer.source go_left, go_right = directions(side) begin_pos = range.begin_pos begin_pos = final_pos(src, begin_pos, -1, continuations, newlines, whitespace) if go_left end_pos = range.end_pos end_pos = final_pos(src, end_pos, 1, continuations, newlines, whitespace) if go_right Parser::Source::Range.new(buffer, begin_pos, end_pos) end def range_by_whole_lines(range, include_final_newline: false, buffer: @processed_source.buffer) last_line = buffer.source_line(range.last_line) end_offset = last_line.length - range.last_column end_offset += 1 if include_final_newline range.adjust(begin_pos: -range.column, end_pos: end_offset).intersect(buffer.source_range) end def column_offset_between(base_range, range) effective_column(base_range) - effective_column(range) end ## Helpers for above range methods. Do not use inside Cops. # Returns the column attribute of the range, except if the range is on # the first line and there's a byte order mark at the beginning of that # line, in which case 1 is subtracted from the column value. This gives # the column as it appears when viewing the file in an editor. def effective_column(range) if range.line == 1 && @processed_source.raw_source.codepoints.first == BYTE_ORDER_MARK range.column - 1 else range.column end end def directions(side) if side == :both [true, true] else [side == :left, side == :right] end end # rubocop:disable Metrics/ParameterLists def final_pos(src, pos, increment, continuations, newlines, whitespace) pos = move_pos(src, pos, increment, true, /[ \t]/) pos = move_pos_str(src, pos, increment, continuations, "\\\n") pos = move_pos(src, pos, increment, newlines, /\n/) move_pos(src, pos, increment, whitespace, /\s/) end # rubocop:enable Metrics/ParameterLists def move_pos(src, pos, step, condition, regexp) offset = step == -1 ? -1 : 0 pos += step while condition && regexp.match?(src[pos + offset]) pos.negative? ? 0 : pos end def move_pos_str(src, pos, step, condition, needle) size = needle.length offset = step == -1 ? -size : 0 pos += size * step while condition && src[pos + offset, size] == needle pos.negative? ? 0 : pos end def range_with_comments_and_lines(node) range_by_whole_lines(range_with_comments(node), include_final_newline: true) end def range_with_comments(node) ranges = [node, *@processed_source.ast_with_comments[node]].map(&:source_range) ranges.reduce do |result, range| add_range(result, range) end end def add_range(range1, range2) range1.with( begin_pos: [range1.begin_pos, range2.begin_pos].min, end_pos: [range1.end_pos, range2.end_pos].max ) end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/multiline_literal_brace_layout.rb
lib/rubocop/cop/mixin/multiline_literal_brace_layout.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for checking the closing brace of a literal is # either on the same line as the last contained elements or a new line. module MultilineLiteralBraceLayout include ConfigurableEnforcedStyle private def check_brace_layout(node) return if ignored_literal?(node) # If the last node is or contains a conflicting HEREDOC, we don't want # to adjust the brace layout because this will result in invalid code. return if last_line_heredoc?(node.children.last) check(node) end # Returns true for the case # [a, # b # comment # ].some_method def new_line_needed_before_closing_brace?(node) last_element_line = last_element_range_with_trailing_comma(node).last_line last_element_commented = processed_source.comment_at_line(last_element_line) last_element_commented && (node.chained? || node.argument?) end def check(node) case style when :symmetrical then check_symmetrical(node) when :new_line then check_new_line(node) when :same_line then check_same_line(node) end end def check_new_line(node) return unless closing_brace_on_same_line?(node) add_offense(node.loc.end, message: self.class::ALWAYS_NEW_LINE_MESSAGE) do |corrector| MultilineLiteralBraceCorrector.correct(corrector, node, processed_source) end end def check_same_line(node) return if closing_brace_on_same_line?(node) add_offense(node.loc.end, message: self.class::ALWAYS_SAME_LINE_MESSAGE) do |corrector| MultilineLiteralBraceCorrector.correct(corrector, node, processed_source) end end def check_symmetrical(node) if opening_brace_on_same_line?(node) return if closing_brace_on_same_line?(node) add_offense(node.loc.end, message: self.class::SAME_LINE_MESSAGE) do |corrector| MultilineLiteralBraceCorrector.correct(corrector, node, processed_source) end else return unless closing_brace_on_same_line?(node) add_offense(node.loc.end, message: self.class::NEW_LINE_MESSAGE) do |corrector| MultilineLiteralBraceCorrector.correct(corrector, node, processed_source) end end end def empty_literal?(node) children(node).empty? end def implicit_literal?(node) !node.loc.begin end def ignored_literal?(node) implicit_literal?(node) || empty_literal?(node) || node.single_line? end def children(node) node.children end # This method depends on the fact that we have guarded # against implicit and empty literals. def opening_brace_on_same_line?(node) same_line?(node.loc.begin, children(node).first) end # This method depends on the fact that we have guarded # against implicit and empty literals. def closing_brace_on_same_line?(node) node.loc.end.line == children(node).last.last_line end # Starting with the parent node and recursively for the parent node's # children, check if the node is a HEREDOC and if the HEREDOC ends below # or on the last line of the parent node. # # Example: # # # node is `b: ...` parameter # # last_line_heredoc?(node) => false # foo(a, # b: { # a: 1, # c: <<-EOM # baz # EOM # } # ) # # # node is `b: ...` parameter # # last_line_heredoc?(node) => true # foo(a, # b: <<-EOM # baz # EOM # ) def last_line_heredoc?(node, parent = nil) parent ||= node if node.respond_to?(:loc) && node.loc?(:heredoc_end) && node.loc.heredoc_end.last_line >= parent.last_line return true end return false unless node.respond_to?(:children) node.children.any? { |child| last_line_heredoc?(child, parent) } end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/first_element_line_break.rb
lib/rubocop/cop/mixin/first_element_line_break.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for checking for a line break before the first # element in a multi-line collection. module FirstElementLineBreak private def check_method_line_break(node, children, ignore_last: false) return if children.empty? return unless method_uses_parens?(node, children.first) check_children_line_break(node, children, ignore_last: ignore_last) end def method_uses_parens?(node, limit) source = node.source_range.source_line[0...limit.loc.column] /\s*\(\s*$/.match?(source) end def check_children_line_break(node, children, start = node, ignore_last: false) return if children.empty? line = start.first_line min = first_by_line(children) return if line != min.first_line max_line = last_line(children, ignore_last: ignore_last) return if line == max_line add_offense(min) { |corrector| EmptyLineCorrector.insert_before(corrector, min) } end def first_by_line(nodes) nodes.min_by(&:first_line) end def last_line(nodes, ignore_last:) if ignore_last nodes.map(&:first_line) else nodes.map(&:last_line) end.max end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/check_single_line_suitability.rb
lib/rubocop/cop/mixin/check_single_line_suitability.rb
# frozen_string_literal: true module RuboCop module Cop # Checks for code on multiple lines that could be rewritten on a single line # without changing semantics or exceeding the `Max` parameter of `Layout/LineLength`. module CheckSingleLineSuitability def suitable_as_single_line?(node) !too_long?(node) && !comment_within?(node) && safe_to_split?(node) end private def too_long?(node) return false unless max_line_length lines = processed_source.lines[(node.first_line - 1)...node.last_line] to_single_line(lines.join("\n")).length > max_line_length end def to_single_line(source) source .gsub(/" *\\\n\s*'/, %q(" + ')) # Double quote, backslash, and then single quote .gsub(/' *\\\n\s*"/, %q(' + ")) # Single quote, backslash, and then double quote .gsub(/(["']) *\\\n\s*\1/, '') # Double or single quote, backslash, then same quote .gsub(/\n\s*(?=(&)?\.\w)/, '') # Extra space within method chaining which includes `&.` .gsub(/\s*\\?\n\s*/, ' ') # Any other line break, with or without backslash end def comment_within?(node) comment_line_numbers = processed_source.comments.map { |comment| comment.loc.line } comment_line_numbers.any? do |comment_line_number| comment_line_number.between?(node.first_line, node.last_line) end end def safe_to_split?(node) node.each_descendant(:if, :case, :kwbegin, :any_def).none? && node.each_descendant(:dstr, :str).none? { |n| n.heredoc? || n.value.include?("\n") } && node.each_descendant(:begin, :sym).none? { |b| !b.single_line? } end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/interpolation.rb
lib/rubocop/cop/mixin/interpolation.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for working with string interpolations. # # @abstract Subclasses are expected to implement {#on_interpolation}. module Interpolation def on_dstr(node) on_node_with_interpolations(node) end alias on_xstr on_dstr alias on_dsym on_dstr alias on_regexp on_dstr def on_node_with_interpolations(node) node.each_child_node(:begin) { |begin_node| on_interpolation(begin_node) } end # @!method on_interpolation(begin_node) # Inspect the `:begin` node of an interpolation end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/trailing_comma.rb
lib/rubocop/cop/mixin/trailing_comma.rb
# frozen_string_literal: true module RuboCop module Cop # Common methods shared by Style/TrailingCommaInArguments, # Style/TrailingCommaInArrayLiteral and Style/TrailingCommaInHashLiteral # rubocop:disable Metrics/ModuleLength module TrailingComma include ConfigurableEnforcedStyle include RangeHelp MSG = '%<command>s comma after the last %<unit>s.' private def style_parameter_name 'EnforcedStyleForMultiline' end def check(node, items, kind, begin_pos, end_pos) after_last_item = range_between(begin_pos, end_pos) comma_offset = comma_offset(items, after_last_item) if comma_offset && !inside_comment?(after_last_item, comma_offset) check_comma(node, kind, after_last_item.begin_pos + comma_offset) elsif should_have_comma?(style, node) put_comma(items, kind) end end def comma_offset(items, range) # If there is any heredoc in items, then match the comma succeeding # any whitespace (except newlines), otherwise allow for newlines comma_regex = any_heredoc?(items) ? /\A[^\S\n]*,/ : /\A\s*,/ comma_regex.match?(range.source) && range.source.index(',') end def check_comma(node, kind, comma_pos) return if should_have_comma?(style, node) avoid_comma(kind, comma_pos, extra_avoid_comma_info) end def check_literal(node, kind) return if node.children.empty? # A braceless hash is the last parameter of a method call and will be # checked as such. return unless brackets?(node) check(node, node.children, kind, node.children.last.source_range.end_pos, node.loc.end.begin_pos) end def extra_avoid_comma_info case style when :comma ', unless each item is on its own line' when :consistent_comma ', unless items are split onto multiple lines' when :diff_comma ', unless that item immediately precedes a newline' else '' end end def should_have_comma?(style, node) case style when :comma multiline?(node) && no_elements_on_same_line?(node) when :consistent_comma multiline?(node) && !method_name_and_arguments_on_same_line?(node) when :diff_comma multiline?(node) && last_item_precedes_newline?(node) else false end end def inside_comment?(range, comma_offset) comment = processed_source.comment_at_line(range.line) comment && comment.source_range.begin_pos < range.begin_pos + comma_offset end # Returns true if the node has round/square/curly brackets. def brackets?(node) node.loc.end end # Returns true if the round/square/curly brackets of the given node are # on different lines, each item within is on its own line, and the # closing bracket is on its own line. def multiline?(node) node.multiline? && !allowed_multiline_argument?(node) end # rubocop:disable Metrics/AbcSize def method_name_and_arguments_on_same_line?(node) return false if !node.call_type? || node.last_line != node.last_argument.last_line return true if node.last_argument.hash_type? && node.last_argument.braces? line = node.loc.selector&.line || node.loc.line line == node.last_argument.last_line end # rubocop:enable Metrics/AbcSize # A single argument with the closing bracket on the same line as the end # of the argument is not considered multiline, even if the argument # itself might span multiple lines. def allowed_multiline_argument?(node) elements(node).one? && !Util.begins_its_line?(node_end_location(node)) end def elements(node) return node.children unless node.call_type? node.arguments.flat_map do |argument| # For each argument, if it is a multi-line hash without braces, # then promote the hash elements to method arguments # for the purpose of determining multi-line-ness. if argument.hash_type? && argument.multiline? && !argument.braces? argument.children else argument end end end def no_elements_on_same_line?(node) items = elements(node).map(&:source_range) items << node_end_location(node) items.each_cons(2).none? { |a, b| on_same_line?(a, b) } end def node_end_location(node) node.loc.end || node.source_range.end.adjust(begin_pos: -1) end def on_same_line?(range1, range2) range1.last_line == range2.line end def last_item_precedes_newline?(node) after_last_item = node.children.last.source_range.end.join(node.source_range.end) after_last_item.source.start_with?(/,?\s*(#.*)?\n/) end def avoid_comma(kind, comma_begin_pos, extra_info) range = range_between(comma_begin_pos, comma_begin_pos + 1) article = kind.include?('array') ? 'an' : 'a' msg = format( MSG, command: 'Avoid', unit: format(kind, article: article) + extra_info.to_s ) add_offense(range, message: msg) do |corrector| PunctuationCorrector.swap_comma(corrector, range) end end def put_comma(items, kind) last_item = items.last return if last_item.block_pass_type? range = autocorrect_range(last_item) msg = format(MSG, command: 'Put a', unit: format(kind, article: 'a multiline')) add_offense(range, message: msg) do |corrector| PunctuationCorrector.swap_comma(corrector, range) end end def autocorrect_range(item) expr = item.source_range ix = expr.source.rindex("\n") || 0 ix += expr.source[ix..] =~ /\S/ range_between(expr.begin_pos + ix, expr.end_pos) end def any_heredoc?(items) items.any? { |item| heredoc?(item) } end def heredoc?(node) return false unless node.is_a?(RuboCop::AST::Node) return true if node.loc?(:heredoc_body) return heredoc_send?(node) if node.send_type? # handle hash values # # some_method({ # 'auth' => <<-SOURCE # ... # SOURCE # }) return heredoc?(node.children.last) if node.type?(:pair, :hash) false end def heredoc_send?(node) # handle heredocs with methods # # some_method(<<-CODE.strip.chomp) # ... # CODE return heredoc?(node.children.first) if node.children.size == 2 # handle nested methods # # some_method( # another_method(<<-CODE.strip.chomp) # ... # CODE # ) return heredoc?(node.children.last) if node.children.size > 2 false end end # rubocop:enable Metrics/ModuleLength end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/unused_argument.rb
lib/rubocop/cop/mixin/unused_argument.rb
# frozen_string_literal: true module RuboCop module Cop module Lint # Common functionality for cops handling unused arguments. module UnusedArgument extend NodePattern::Macros def after_leaving_scope(scope, _variable_table) scope.variables.each_value { |variable| check_argument(variable) } end private def check_argument(variable) return if variable.should_be_unused? return if variable.referenced? message = message(variable) add_offense(variable.declaration_node.loc.name, message: message) do |corrector| autocorrect(corrector, variable.declaration_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/mixin/allowed_receivers.rb
lib/rubocop/cop/mixin/allowed_receivers.rb
# frozen_string_literal: true module RuboCop module Cop # This module encapsulates the ability to allow certain receivers in a cop. module AllowedReceivers def allowed_receiver?(receiver) receiver_name = receiver_name(receiver) allowed_receivers.include?(receiver_name) end def receiver_name(receiver) if receiver.receiver && !receiver.receiver.const_type? return receiver_name(receiver.receiver) end if receiver.send_type? if receiver.receiver "#{receiver_name(receiver.receiver)}.#{receiver.method_name}" else receiver.method_name.to_s end else receiver.source end end def allowed_receivers cop_config.fetch('AllowedReceivers', []) end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/min_branches_count.rb
lib/rubocop/cop/mixin/min_branches_count.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for checking minimum branches count. module MinBranchesCount private def min_branches_count?(node) branches = if node.case_type? node.when_branches elsif node.if_type? if_conditional_branches(node) else raise ArgumentError, "Unsupported #{node.type.inspect} node type" end branches.size >= min_branches_count end def min_branches_count length = cop_config['MinBranchesCount'] || 3 return length if length.is_a?(Integer) && length.positive? raise 'MinBranchesCount needs to be a positive integer!' end def if_conditional_branches(node, branches = []) return [] if node.nil? || !node.if_type? branches << node.if_branch else_branch = node.else_branch if_conditional_branches(else_branch, branches) if else_branch&.if_type? branches end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/trailing_body.rb
lib/rubocop/cop/mixin/trailing_body.rb
# frozen_string_literal: true module RuboCop module Cop # Common methods shared by TrailingBody cops module TrailingBody def trailing_body?(node) body = node.to_a.reverse[0] body && node.multiline? && body_on_first_line?(node, body) end def body_on_first_line?(node, body) same_line?(node, body) end def first_part_of(body) if body.begin_type? body.children.first.source_range else body.source_range end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/configurable_enforced_style.rb
lib/rubocop/cop/mixin/configurable_enforced_style.rb
# frozen_string_literal: true module RuboCop module Cop # Handles `EnforcedStyle` configuration parameters. module ConfigurableEnforcedStyle def opposite_style_detected style_detected(alternative_style) end def correct_style_detected style_detected(style) end def unexpected_style_detected(unexpected) style_detected(unexpected) end def ambiguous_style_detected(*possibilities) style_detected(possibilities) end SYMBOL_TO_STRING_CACHE = Hash.new do |hash, key| hash[key] = key.to_s if key.is_a?(Symbol) end private_constant :SYMBOL_TO_STRING_CACHE # rubocop:disable Metrics def style_detected(detected) return if no_acceptable_style? # This logic is more complex than it needs to be # to avoid allocating Arrays in the hot code path. updated_list = if detected_style if detected_style.size == 1 && detected_style.include?(SYMBOL_TO_STRING_CACHE[detected]) detected_style else detected_as_strings = SYMBOL_TO_STRING_CACHE.values_at(*detected) detected_style & detected_as_strings end else # We haven't observed any specific style yet. SYMBOL_TO_STRING_CACHE.values_at(*detected) end if updated_list.empty? no_acceptable_style! else self.detected_style = updated_list config_to_allow_offenses[style_parameter_name] = updated_list.first end end # rubocop:enable Metrics def no_acceptable_style? config_to_allow_offenses['Enabled'] == false end def no_acceptable_style! self.config_to_allow_offenses = { 'Enabled' => false } end def detected_style Formatter::DisabledConfigFormatter.detected_styles[cop_name] ||= nil end def detected_style=(style) Formatter::DisabledConfigFormatter.detected_styles[cop_name] = style end alias conflicting_styles_detected no_acceptable_style! alias unrecognized_style_detected no_acceptable_style! def style_configured? cop_config.key?(style_parameter_name) end def style @style ||= begin s = cop_config[style_parameter_name].to_sym raise "Unknown style #{s} selected!" unless supported_styles.include?(s) s end end def alternative_style if supported_styles.size != 2 raise 'alternative_style can only be used when there are exactly 2 SupportedStyles' end alternative_styles.first end def alternative_styles (supported_styles - [style]) end def supported_styles @supported_styles ||= begin supported_styles = Util.to_supported_styles(style_parameter_name) cop_config[supported_styles].map(&:to_sym) end end def style_parameter_name 'EnforcedStyle' end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/heredoc.rb
lib/rubocop/cop/mixin/heredoc.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for working with heredoc strings. module Heredoc OPENING_DELIMITER = /(<<[~-]?)['"`]?([^'"`]+)['"`]?/.freeze def on_str(node) return unless node.heredoc? on_heredoc(node) end alias on_dstr on_str alias on_xstr on_str def on_heredoc(_node) raise NotImplementedError end private def indent_level(str) indentations = str.lines.map { |line| line[/^\s*/] }.reject { |line| line.end_with?("\n") } indentations.empty? ? 0 : indentations.min_by(&:size).size end def delimiter_string(node) return '' unless (match = node.source.match(OPENING_DELIMITER)) match.captures[1] end def heredoc_type(node) return '' unless (match = node.source.match(OPENING_DELIMITER)) match.captures[0] end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/surrounding_space.rb
lib/rubocop/cop/mixin/surrounding_space.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for checking and correcting surrounding whitespace. module SurroundingSpace include RangeHelp NO_SPACE_COMMAND = 'Do not use' SPACE_COMMAND = 'Use' SINGLE_SPACE_REGEXP = /[ \t]/.freeze private def side_space_range(range:, side:, include_newlines: false) buffer = processed_source.buffer src = buffer.source begin_pos = range.begin_pos end_pos = range.end_pos if side == :left end_pos = begin_pos begin_pos = reposition(src, begin_pos, -1, include_newlines: include_newlines) end if side == :right begin_pos = end_pos end_pos = reposition(src, end_pos, 1, include_newlines: include_newlines) end Parser::Source::Range.new(buffer, begin_pos, end_pos) end def on_new_investigation @token_table = nil super end def no_space_offenses(node, # rubocop:disable Metrics/ParameterLists left_token, right_token, message, start_ok: false, end_ok: false) if extra_space?(left_token, :left) && !start_ok space_offense(node, left_token, :right, message, NO_SPACE_COMMAND) end return if (!extra_space?(right_token, :right) || end_ok) || (autocorrect_with_disable_uncorrectable? && !start_ok) space_offense(node, right_token, :left, message, NO_SPACE_COMMAND) end def space_offenses(node, # rubocop:disable Metrics/ParameterLists left_token, right_token, message, start_ok: false, end_ok: false) unless extra_space?(left_token, :left) || start_ok space_offense(node, left_token, :none, message, SPACE_COMMAND) end return if (extra_space?(right_token, :right) || end_ok) || (autocorrect_with_disable_uncorrectable? && !start_ok) space_offense(node, right_token, :none, message, SPACE_COMMAND) end def extra_space?(token, side) return false unless token if side == :left SINGLE_SPACE_REGEXP.match?(String(token.space_after?)) else SINGLE_SPACE_REGEXP.match?(String(token.space_before?)) end end def reposition(src, pos, step, include_newlines: false) offset = step == -1 ? -1 : 0 pos += step while SINGLE_SPACE_REGEXP.match?(src[pos + offset]) || (include_newlines && src[pos + offset] == "\n") pos.negative? ? 0 : pos end def space_offense(node, token, side, message, command) range = side_space_range(range: token.pos, side: side) add_offense(range, message: format(message, command: command)) do |corrector| autocorrect(corrector, node) unless ignored_node?(node) ignore_node(node) end end def empty_offenses(node, left, right, message) range = range_between(left.begin_pos, right.end_pos) if offending_empty_space?(empty_config, left, right) empty_offense(node, range, message, 'Use one') end return unless offending_empty_no_space?(empty_config, left, right) empty_offense(node, range, message, 'Do not use') end def empty_offense(node, range, message, command) add_offense(range, message: format(message, command: command)) do |corrector| autocorrect(corrector, node) end end def empty_brackets?(left_bracket_token, right_bracket_token, tokens: processed_source.tokens) left_index = tokens.index(left_bracket_token) right_index = tokens.index(right_bracket_token) right_index && left_index == right_index - 1 end def offending_empty_space?(config, left_token, right_token) config == 'space' && !space_between?(left_token, right_token) end def offending_empty_no_space?(config, left_token, right_token) config == 'no_space' && !no_character_between?(left_token, right_token) end def space_between?(left_bracket_token, right_bracket_token) left_bracket_token.end_pos + 1 == right_bracket_token.begin_pos && processed_source.buffer.source[left_bracket_token.end_pos] == ' ' end def no_character_between?(left_bracket_token, right_bracket_token) left_bracket_token.end_pos == right_bracket_token.begin_pos end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/on_normal_if_unless.rb
lib/rubocop/cop/mixin/on_normal_if_unless.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for cops checking if and unless expressions. module OnNormalIfUnless def on_if(node) return if node.modifier_form? || node.ternary? on_normal_if_unless(node) end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/percent_literal.rb
lib/rubocop/cop/mixin/percent_literal.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for handling percent literals. module PercentLiteral include RangeHelp private def percent_literal?(node) return false unless (begin_source = begin_source(node)) begin_source.start_with?('%') end def process(node, *types) return unless percent_literal?(node) && types.include?(type(node)) on_percent_literal(node) end def begin_source(node) node.loc.begin.source if node.loc?(:begin) end def type(node) node.loc.begin.source[0..-2] end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/allowed_identifiers.rb
lib/rubocop/cop/mixin/allowed_identifiers.rb
# frozen_string_literal: true module RuboCop module Cop # This module encapsulates the ability to allow certain identifiers in a cop. module AllowedIdentifiers SIGILS = '@$' # if a variable starts with a sigil it will be removed def allowed_identifier?(name) !allowed_identifiers.empty? && allowed_identifiers.include?(name.to_s.delete(SIGILS)) end def allowed_identifiers cop_config.fetch('AllowedIdentifiers') { [] } end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/string_literals_help.rb
lib/rubocop/cop/mixin/string_literals_help.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for cops checking single/double quotes. module StringLiteralsHelp private def wrong_quotes?(src_or_node) src = src_or_node.is_a?(RuboCop::AST::Node) ? src_or_node.source : src_or_node return false if src.start_with?('%', '?') if style == :single_quotes !double_quotes_required?(src) else !/" | \\[^'\\] | \#[@{$]/x.match?(src) end end def preferred_string_literal enforce_double_quotes? ? '""' : "''" end def enforce_double_quotes? string_literals_config['EnforcedStyle'] == 'double_quotes' end def string_literals_config config.for_enabled_cop('Style/StringLiterals') end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/array_syntax.rb
lib/rubocop/cop/mixin/array_syntax.rb
# frozen_string_literal: true module RuboCop module Cop # Common code for ordinary arrays with [] that can be written with % # syntax. module ArraySyntax private def bracketed_array_of?(element_type, node) return false unless node.square_brackets? && !node.values.empty? node.values.all? { |value| value.type == element_type } end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/uncommunicative_name.rb
lib/rubocop/cop/mixin/uncommunicative_name.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality shared by Uncommunicative cops module UncommunicativeName CASE_MSG = 'Only use lowercase characters for %<name_type>s.' NUM_MSG = 'Do not end %<name_type>s with a number.' LENGTH_MSG = '%<name_type>s must be at least %<min>s characters long.' FORBIDDEN_MSG = 'Do not use %<name>s as a name for a %<name_type>s.' def check(node, args) args.each do |arg| # Argument names might be "_" or prefixed with "_" to indicate they # are unused. Trim away this prefix and only analyse the basename. name_child = arg.children.first next if name_child.nil? full_name = name_child.to_s next if full_name == '_' name = full_name.gsub(/\A(_+)/, '') next if allowed_names.include?(name) length = full_name.size length += 1 if arg.restarg_type? length += 2 if arg.kwrestarg_type? range = arg_range(arg, length) issue_offenses(node, range, name) end end private def issue_offenses(node, range, name) forbidden_offense(node, range, name) if forbidden_names.include?(name) case_offense(node, range) if uppercase?(name) length_offense(node, range) unless long_enough?(name) return if allow_nums num_offense(node, range) if ends_with_num?(name) end def case_offense(node, range) add_offense(range, message: format(CASE_MSG, name_type: name_type(node))) end def uppercase?(name) /[[:upper:]]/.match?(name) end def name_type(node) @name_type ||= case node.type when :block then 'block parameter' when :def, :defs then 'method parameter' end end def num_offense(node, range) add_offense(range, message: format(NUM_MSG, name_type: name_type(node))) end def ends_with_num?(name) /\d/.match?(name[-1]) end def length_offense(node, range) message = format(LENGTH_MSG, name_type: name_type(node).capitalize, min: min_length) add_offense(range, message: message) end def long_enough?(name) name.size >= min_length end def arg_range(arg, length) begin_pos = arg.source_range.begin_pos Parser::Source::Range.new(processed_source.buffer, begin_pos, begin_pos + length) end def forbidden_offense(node, range, name) add_offense(range, message: format(FORBIDDEN_MSG, name: name, name_type: name_type(node))) end def allowed_names cop_config['AllowedNames'] end def forbidden_names cop_config['ForbiddenNames'] end def allow_nums cop_config['AllowNamesEndingInNumbers'] end def min_length cop_config['MinNameLength'] end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/empty_parameter.rb
lib/rubocop/cop/mixin/empty_parameter.rb
# frozen_string_literal: true module RuboCop module Cop # Common code for empty parameter cops. module EmptyParameter extend NodePattern::Macros private # @!method empty_arguments?(node) def_node_matcher :empty_arguments?, <<~PATTERN (block _ $(args) _) PATTERN def check(node) empty_arguments?(node) do |args| return if args.empty_and_without_delimiters? add_offense(args) { |corrector| autocorrect(corrector, args) } end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/gemspec_help.rb
lib/rubocop/cop/mixin/gemspec_help.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for checking gem declarations. module GemspecHelp extend NodePattern::Macros # @!method gem_specification?(node) def_node_matcher :gem_specification?, <<~PATTERN (block (send (const (const {cbase nil?} :Gem) :Specification) :new) (args (arg $_)) ...) PATTERN # @!method gem_specification(node) def_node_search :gem_specification, <<~PATTERN (block (send (const (const {cbase nil?} :Gem) :Specification) :new) (args (arg $_)) ...) PATTERN # @!method assignment_method_declarations(node) def_node_search :assignment_method_declarations, <<~PATTERN (send (lvar {#match_block_variable_name? :_1 :it}) _ ...) PATTERN # @!method indexed_assignment_method_declarations(node) def_node_search :indexed_assignment_method_declarations, <<~PATTERN (send (send (lvar {#match_block_variable_name? :_1 :it}) _) :[]= literal? _ ) PATTERN def match_block_variable_name?(receiver_name) gem_specification(processed_source.ast) do |block_variable_name| return block_variable_name == receiver_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/mixin/parentheses.rb
lib/rubocop/cop/mixin/parentheses.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for handling parentheses. module Parentheses private def parens_required?(node) range = node.source_range source = range.source_buffer.source /[a-z]/.match?(source[range.begin_pos - 1]) || /[a-z]/.match?(source[range.end_pos]) end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/negative_conditional.rb
lib/rubocop/cop/mixin/negative_conditional.rb
# frozen_string_literal: true module RuboCop module Cop # Some common code shared between `NegatedIf` and # `NegatedWhile` cops. module NegativeConditional extend NodePattern::Macros MSG = 'Favor `%<inverse>s` over `%<current>s` for negative conditions.' private # @!method single_negative?(node) def_node_matcher :single_negative?, '(send !(send _ :!) :!)' # @!method empty_condition?(node) def_node_matcher :empty_condition?, '(begin)' def check_negative_conditional(node, message:, &block) condition = node.condition return if empty_condition?(condition) condition = condition.children.last while condition.begin_type? return unless single_negative?(condition) return if node.if_type? && node.else? add_offense(node, message: message, &block) end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/rescue_node.rb
lib/rubocop/cop/mixin/rescue_node.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for checking `rescue` nodes. module RescueNode def modifier_locations @modifier_locations ||= processed_source.tokens.select(&:rescue_modifier?).map!(&:pos) end private def rescue_modifier?(node) return false unless node.respond_to?(:resbody_type?) node.resbody_type? && modifier_locations.include?(node.loc.keyword) end # @deprecated Use ResbodyNode#exceptions instead def rescued_exceptions(resbody) warn Rainbow(<<~WARNING).yellow, uplevel: 1 `rescued_exceptions` is deprecated. Use `ResbodyNode#exceptions` instead. WARNING rescue_group, = *resbody if rescue_group rescue_group.values else [] end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/gem_declaration.rb
lib/rubocop/cop/mixin/gem_declaration.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for checking gem declarations. module GemDeclaration extend NodePattern::Macros # @!method gem_declaration?(node) def_node_matcher :gem_declaration?, '(send nil? :gem str ...)' end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/space_before_punctuation.rb
lib/rubocop/cop/mixin/space_before_punctuation.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for cops checking for space before # punctuation. module SpaceBeforePunctuation include RangeHelp MSG = 'Space found before %<token>s.' def on_new_investigation each_missing_space(processed_source.sorted_tokens) do |token, pos_before| add_offense(pos_before, message: format(MSG, token: kind(token))) do |corrector| PunctuationCorrector.remove_space(corrector, pos_before) end end end private def each_missing_space(tokens) tokens.each_cons(2) do |token1, token2| next unless kind(token2) next unless space_missing?(token1, token2) next if space_required_after?(token1) pos_before_punctuation = range_between(token1.end_pos, token2.begin_pos) yield token2, pos_before_punctuation end end def space_missing?(token1, token2) same_line?(token1, token2) && token2.begin_pos > token1.end_pos end def space_required_after?(token) token.left_curly_brace? && space_required_after_lcurly? end def space_required_after_lcurly? cfg = config.for_cop('Layout/SpaceInsideBlockBraces') style = cfg['EnforcedStyle'] || 'space' style == 'space' end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/allowed_methods.rb
lib/rubocop/cop/mixin/allowed_methods.rb
# frozen_string_literal: true module RuboCop module Cop # This module encapsulates the ability to allow certain methods when # parsing. Even if the code is in offense, if it contains methods # that are allowed. This module is equivalent to the IgnoredMethods module, # which will be deprecated in RuboCop 2.0. module AllowedMethods private # @api public def allowed_method?(name) allowed_methods.include?(name.to_s) end # @deprecated Use allowed_method? instead def ignored_method? warn Rainbow(<<~WARNING).yellow, uplevel: 1 `ignored_method?` is deprecated. Use `allowed_method?` instead. WARNING allowed_method? end # @api public def allowed_methods if cop_config_deprecated_values.any?(Regexp) cop_config_allowed_methods else cop_config_allowed_methods + cop_config_deprecated_values end end def cop_config_allowed_methods @cop_config_allowed_methods ||= Array(cop_config.fetch('AllowedMethods', [])) end def cop_config_deprecated_values @cop_config_deprecated_values ||= Array(cop_config.fetch('IgnoredMethods', [])) + Array(cop_config.fetch('ExcludedMethods', [])) end end # @deprecated IgnoredMethods class has been replaced with AllowedMethods. IgnoredMethods = AllowedMethods end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/safe_assignment.rb
lib/rubocop/cop/mixin/safe_assignment.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality 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." module SafeAssignment extend NodePattern::Macros private # @!method empty_condition?(node) def_node_matcher :empty_condition?, '(begin)' # @!method setter_method?(node) def_node_matcher :setter_method?, '[(call ...) setter_method?]' # @!method safe_assignment?(node) def_node_matcher :safe_assignment?, '(begin {equals_asgn? #setter_method?})' def safe_assignment_allowed? cop_config['AllowSafeAssignment'] end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/code_length.rb
lib/rubocop/cop/mixin/code_length.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for checking length of code segments. module CodeLength extend ExcludeLimit MSG = '%<label>s has too many lines. [%<length>d/%<max>d]' exclude_limit 'Max' private def message(length, max_length) format(MSG, label: cop_label, length: length, max: max_length) end def max_length cop_config['Max'] end def count_comments? cop_config['CountComments'] end def count_as_one Array(cop_config['CountAsOne']).map(&:to_sym) end def check_code_length(node) # Skip costly calculation when definitely not needed return if node.line_count <= max_length calculator = build_code_length_calculator(node) length = calculator.calculate return if length <= max_length location = location(node) add_offense(location, message: message(length, max_length)) { self.max = length } 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 build_code_length_calculator(node) Metrics::Utils::CodeLengthCalculator.new( node, processed_source, count_comments: count_comments?, foldable_types: count_as_one ) end def location(node) return node.loc.name if node.casgn_type? if LSP.enabled? end_range = node.loc?(:name) ? node.loc.name : node.loc.begin node.source_range.begin.join(end_range) else node.source_range end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/target_ruby_version.rb
lib/rubocop/cop/mixin/target_ruby_version.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for checking target ruby version. module TargetRubyVersion def required_minimum_ruby_version @minimum_target_ruby_version end def required_maximum_ruby_version @maximum_target_ruby_version end def minimum_target_ruby_version(version) @minimum_target_ruby_version = version end def maximum_target_ruby_version(version) @maximum_target_ruby_version = version end def support_target_ruby_version?(version) # By default, no minimum or maximum versions of ruby are required # to run any cop. In order to do a simple numerical comparison of # the requested version against any requirements, we use 0 and # Infinity as the default values to indicate no minimum (0) and no # maximum (Infinity). min = required_minimum_ruby_version || 0 max = required_maximum_ruby_version || Float::INFINITY version.between?(min, max) end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/duplication.rb
lib/rubocop/cop/mixin/duplication.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for dealing with duplication. module Duplication private # Whether the `collection` contains any duplicates. # # @param [Array] collection an array to check for duplicates # @return [Boolean] whether the array contains any duplicates def duplicates?(collection) collection.size > 1 && collection.size > collection.uniq.size end # Returns all duplicates, including the first instance of the duplicated # elements. # # @param [Array] collection an array to return duplicates for # @return [Array] all the duplicates def duplicates(collection) grouped_duplicates(collection).flatten end # Returns the consecutive duplicates, leaving out the first instance of # the duplicated elements. # # @param [Array] collection an array to return consecutive duplicates for # @return [Array] the consecutive duplicates def consecutive_duplicates(collection) grouped_duplicates(collection).flat_map { |items| items[1..] } end # Returns a hash of grouped duplicates. The key will be the first # instance of the element, and the value an `array` of the initial # element and all duplicate instances. # # @param [Array] collection an array to group duplicates for # @return [Array] the grouped duplicates def grouped_duplicates(collection) collection.group_by { |item| item }.values.reject(&:one?) end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/alignment.rb
lib/rubocop/cop/mixin/alignment.rb
# frozen_string_literal: true module RuboCop module Cop # This module checks for nodes that should be aligned to the left or right. # This amount is determined by the instance variable @column_delta. module Alignment SPACE = ' ' private attr_reader :column_delta def configured_indentation_width cop_config['IndentationWidth'] || config.for_cop('Layout/IndentationWidth')['Width'] || 2 end def indentation(node) offset(node) + (SPACE * configured_indentation_width) end def offset(node) SPACE * node.loc.column end def check_alignment(items, base_column = nil) base_column ||= display_column(items.first.source_range) unless items.empty? each_bad_alignment(items, base_column) do |current| expr = current.source_range if @current_offenses&.any? { |o| within?(expr, o.location) } # If this offense is within a line range that is already being # realigned by autocorrect, we report the offense without # autocorrecting it. Two rewrites in the same area by the same # cop cannot be handled. The next iteration will find the # offense again and correct it. register_offense(expr, nil) else register_offense(current, current) end end end # @api private def each_bad_alignment(items, base_column) prev_line = -1 items.each do |current| if current.loc.line > prev_line && begins_its_line?(current.source_range) @column_delta = base_column - display_column(current.source_range) yield current if @column_delta.nonzero? end prev_line = current.loc.line end end # @api public def display_column(range) line = processed_source.lines[range.line - 1] Unicode::DisplayWidth.of(line[0, range.column]) end # @api public def within?(inner, outer) inner.begin_pos >= outer.begin_pos && inner.end_pos <= outer.end_pos end # @deprecated Use processed_source.line_with_comment?(line) def end_of_line_comment(line) # rubocop:disable Naming/PredicateMethod warn Rainbow(<<~WARNING).yellow, uplevel: 1 `end_of_line_comment` is deprecated. Use `processed_source.line_with_comment?` instead. WARNING processed_source.line_with_comment?(line) end # @api private def register_offense(offense_node, message_node) add_offense(offense_node, message: message(message_node)) do |corrector| autocorrect(corrector, message_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/mixin/percent_array.rb
lib/rubocop/cop/mixin/percent_array.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for handling percent arrays. module PercentArray private # Ruby does not allow percent arrays in an ambiguous block context. # # @example # # foo %i[bar baz] { qux } def invalid_percent_array_context?(node) parent = node.parent parent&.send_type? && parent.arguments.include?(node) && !parent.parenthesized? && parent.block_literal? end # Override to determine values that are invalid in a percent array def invalid_percent_array_contents?(_node) false end def allowed_bracket_array?(node) comments_in_array?(node) || below_array_length?(node) || invalid_percent_array_context?(node) end def comments_in_array?(node) line_span = node.source_range.first_line...node.source_range.last_line processed_source.each_comment_in_lines(line_span).any? end def check_percent_array(node) array_style_detected(:percent, node.values.size) brackets_required = invalid_percent_array_contents?(node) return unless style == :brackets || brackets_required # If in percent style but brackets are required due to # string content, the file should be excluded in auto-gen-config no_acceptable_style! if brackets_required bracketed_array = build_bracketed_array(node) message = build_message_for_bracketed_array(bracketed_array) add_offense(node, message: message) do |corrector| corrector.replace(node, bracketed_array) end end # @param [String] preferred_array_code # @return [String] def build_message_for_bracketed_array(preferred_array_code) format( self.class::ARRAY_MSG, prefer: if preferred_array_code.include?("\n") 'an array literal `[...]`' else "`#{preferred_array_code}`" end ) end def check_bracketed_array(node, literal_prefix) return if allowed_bracket_array?(node) array_style_detected(:brackets, node.values.size) return unless style == :percent add_offense(node, message: self.class::PERCENT_MSG) do |corrector| percent_literal_corrector = PercentLiteralCorrector.new(@config, @preferred_delimiters) percent_literal_corrector.correct(corrector, node, literal_prefix) end end # @param [RuboCop::AST::ArrayNode] node # @param [Array<String>] elements # @return [String] def build_bracketed_array_with_appropriate_whitespace(elements:, node:) [ '[', whitespace_leading(node), elements.join(",#{whitespace_between(node)}"), whitespace_trailing(node), ']' ].join end # Provides whitespace between elements for building a bracketed array. # %w[ a b c ] # ^^^ # @param [RuboCop::AST::ArrayNode] node # @return [String] def whitespace_between(node) if node.children.length >= 2 node.children[0].source_range.end.join(node.children[1].source_range.begin).source else ' ' end end # Provides leading whitespace for building a bracketed array. # %w[ a b c ] # ^^ # @param [RuboCop::AST::ArrayNode] node # @return [String] def whitespace_leading(node) node.loc.begin.end.join(node.children[0].source_range.begin).source end # Provides trailing whitespace for building a bracketed array. # %w[ a b c ] # ^^^^ # @param [RuboCop::AST::ArrayNode] node # @return [String] def whitespace_trailing(node) node.children[-1].source_range.end.join(node.loc.end.begin).source end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/end_keyword_alignment.rb
lib/rubocop/cop/mixin/end_keyword_alignment.rb
# frozen_string_literal: true module RuboCop module Cop # Functions for checking the alignment of the `end` keyword. module EndKeywordAlignment include ConfigurableEnforcedStyle include RangeHelp MSG = '`end` at %<end_line>d, %<end_col>d is not aligned with ' \ '`%<source>s` at %<align_line>d, %<align_col>d.' private def check_end_kw_in_node(node) check_end_kw_alignment(node, style => node.loc.keyword) end def check_end_kw_alignment(node, align_ranges) return if ignored_node?(node) return unless (end_loc = node.loc.end) matching = matching_ranges(end_loc, align_ranges) if matching.key?(style) correct_style_detected else add_offense_for_misalignment(node, align_ranges[style]) style_detected(matching.keys) end end def matching_ranges(end_loc, align_ranges) align_ranges.select do |_, range| same_line?(range, end_loc) || column_offset_between(range, end_loc).zero? end end def start_line_range(node) expr = node.source_range buffer = expr.source_buffer source = buffer.source_line(expr.line) range = buffer.line_range(expr.line) range_between(range.begin_pos + (source =~ /\S/), range.begin_pos + (source =~ /\s*\z/)) end def add_offense_for_misalignment(node, align_with) end_loc = node.loc.end msg = format(MSG, end_line: end_loc.line, end_col: end_loc.column, source: align_with.source, align_line: align_with.line, align_col: align_with.column) add_offense(end_loc, message: msg) { |corrector| autocorrect(corrector, node) } end def style_parameter_name 'EnforcedStyleAlignWith' end def variable_alignment?(whole_expression, rhs, end_alignment_style) return false if end_alignment_style == :keyword !line_break_before_keyword?(whole_expression, rhs) end def line_break_before_keyword?(whole_expression, rhs) rhs.first_line > whole_expression.line end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/forbidden_pattern.rb
lib/rubocop/cop/mixin/forbidden_pattern.rb
# frozen_string_literal: true module RuboCop module Cop # This module encapsulates the ability to forbid certain patterns in a cop. module ForbiddenPattern def forbidden_pattern?(name) forbidden_patterns.any? { |pattern| Regexp.new(pattern).match?(name) } end def forbidden_patterns cop_config.fetch('ForbiddenPatterns', []) end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/endless_method_rewriter.rb
lib/rubocop/cop/mixin/endless_method_rewriter.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for rewriting endless methods to normal method definitions module EndlessMethodRewriter 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 private def arguments(node, missing = '') node.arguments.any? ? node.arguments.source : missing end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/allowed_pattern.rb
lib/rubocop/cop/mixin/allowed_pattern.rb
# frozen_string_literal: true module RuboCop module Cop # This module encapsulates the ability to ignore certain lines when # parsing. module AllowedPattern private def allowed_line?(line) line = if line.respond_to?(:source_line) line.source_line elsif line.respond_to?(:node) line.node.source_range.source_line end matches_allowed_pattern?(line) end # @deprecated Use allowed_line? instead def ignored_line?(line) warn Rainbow(<<~WARNING).yellow, uplevel: 1 `ignored_line?` is deprecated. Use `allowed_line?` instead. WARNING allowed_line?(line) end def matches_allowed_pattern?(line) allowed_patterns.any? { |pattern| Regexp.new(pattern).match?(line) } end # @deprecated Use matches_allowed_pattern? instead def matches_ignored_pattern?(line) warn Rainbow(<<~WARNING).yellow, uplevel: 1 `matches_ignored_pattern?` is deprecated. Use `matches_allowed_pattern?` instead. WARNING matches_allowed_pattern?(line) end def allowed_patterns # Since there could be a pattern specified in the default config, merge the two # arrays together. if cop_config_deprecated_methods_values.any?(Regexp) cop_config_patterns_values + cop_config_deprecated_methods_values else cop_config_patterns_values end end def cop_config_patterns_values @cop_config_patterns_values ||= Array(cop_config.fetch('AllowedPatterns', [])) + Array(cop_config.fetch('IgnoredPatterns', [])) end def cop_config_deprecated_methods_values @cop_config_deprecated_methods_values ||= Array(cop_config.fetch('IgnoredMethods', [])) + Array(cop_config.fetch('ExcludedMethods', [])) end end # @deprecated IgnoredPattern class has been replaced with AllowedPattern. IgnoredPattern = AllowedPattern end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/ordered_gem_node.rb
lib/rubocop/cop/mixin/ordered_gem_node.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for Bundler/OrderedGems and # Gemspec/OrderedDependencies. module OrderedGemNode private def get_source_range(node, comments_as_separators) unless comments_as_separators first_comment = processed_source.ast_with_comments[node].first return first_comment.source_range unless first_comment.nil? end node.source_range end def gem_canonical_name(name) name = name.tr('-_', '') unless cop_config['ConsiderPunctuation'] name.downcase end def case_insensitive_out_of_order?(string_a, string_b) gem_canonical_name(string_a) < gem_canonical_name(string_b) end def consecutive_lines?(previous, current) first_line = get_source_range(current, treat_comments_as_separators).first_line previous.source_range.last_line == first_line - 1 end def register_offense(previous, current) message = format( self.class::MSG, previous: gem_name(current), current: gem_name(previous) ) add_offense(current, message: message) do |corrector| OrderedGemCorrector.correct( processed_source, current, previous_declaration(current), treat_comments_as_separators ).call(corrector) end end def gem_name(declaration_node) gem_node = declaration_node.first_argument find_gem_name(gem_node) end def find_gem_name(gem_node) return gem_node.str_content if gem_node.str_type? find_gem_name(gem_node.receiver) end def treat_comments_as_separators cop_config['TreatCommentsAsGroupSeparators'] end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/frozen_string_literal.rb
lib/rubocop/cop/mixin/frozen_string_literal.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for dealing with frozen string literals. module FrozenStringLiteral module_function FROZEN_STRING_LITERAL_ENABLED = '# frozen_string_literal: true' FROZEN_STRING_LITERAL_TYPES_RUBY27 = %i[str dstr].freeze private_constant :FROZEN_STRING_LITERAL_TYPES_RUBY27 def frozen_string_literal_comment_exists? leading_comment_lines.any? { |line| MagicComment.parse(line).valid_literal_value? } end private def frozen_string_literal?(node) frozen_string = if target_ruby_version >= 3.0 uninterpolated_string?(node) || uninterpolated_heredoc?(node) else FROZEN_STRING_LITERAL_TYPES_RUBY27.include?(node.type) end frozen_string && frozen_string_literals_enabled? end def uninterpolated_string?(node) node.str_type? || ( node.dstr_type? && node.each_descendant(:begin, :ivar, :cvar, :gvar).none? ) end def uninterpolated_heredoc?(node) return false unless node.dstr_type? && node.heredoc? node.children.all?(&:str_type?) end alias frozen_heredoc? uninterpolated_heredoc? def frozen_string_literals_enabled? ruby_version = processed_source.ruby_version return false unless ruby_version # Check if a magic string literal comment specifies what to do magic_comments = leading_comment_lines.filter_map { |line| MagicComment.parse(line) } if (literal_magic_comment = magic_comments.find(&:frozen_string_literal_specified?)) return literal_magic_comment.frozen_string_literal? end # TODO: Ruby officially abandon making frozen string literals default # for Ruby 3.0. # https://bugs.ruby-lang.org/issues/11473#note-53 # Whether frozen string literals will be the default after Ruby 4.0 # or not is still unclear as of July 2024. # It may be necessary to add this code in the future. # # return ruby_version >= 4.0 if string_literals_frozen_by_default?.nil? # # And the above `ruby_version >= 4.0` is undecided whether it will be # Ruby 4.0 or others. # See https://bugs.ruby-lang.org/issues/20205 for details. # For now, offer a configuration value to override behavior is using RUBYOPT. return false if string_literals_frozen_by_default?.nil? string_literals_frozen_by_default? end def frozen_string_literals_disabled? leading_comment_lines.any? do |line| MagicComment.parse(line).frozen_string_literal == false end end def frozen_string_literal_specified? leading_comment_lines.any? do |line| MagicComment.parse(line).frozen_string_literal_specified? end end def leading_magic_comments leading_comment_lines.map { |line| MagicComment.parse(line) } end def leading_comment_lines first_non_comment_token = processed_source.tokens.find { |token| !token.comment? } if first_non_comment_token # `line` is 1-indexed so we need to subtract 1 to get the array index processed_source.lines[0...(first_non_comment_token.line - 1)] else processed_source.lines end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/check_line_breakable.rb
lib/rubocop/cop/mixin/check_line_breakable.rb
# frozen_string_literal: true module RuboCop module Cop # This mixin detects collections that are safe to "break" # by inserting new lines. This is useful for breaking # up long lines. # # Let's look at hashes as an example: # # We know hash keys are safe to break across lines. We can add # linebreaks into hashes on lines longer than the specified maximum. # Then in further passes cops can clean up the multi-line hash. # For example, say the maximum line length is as indicated below: # # | # v # {foo: "0000000000", bar: "0000000000", baz: "0000000000"} # # In a LineLength autocorrection pass, a line is added before # the first key that exceeds the column limit: # # {foo: "0000000000", bar: "0000000000", # baz: "0000000000"} # # In a MultilineHashKeyLineBreaks pass, lines are inserted # before all keys: # # {foo: "0000000000", # bar: "0000000000", # baz: "0000000000"} # # Then in future passes FirstHashElementLineBreak, # MultilineHashBraceLayout, and TrailingCommaInHashLiteral will # manipulate as well until we get: # # { # foo: "0000000000", # bar: "0000000000", # baz: "0000000000", # } # # (Note: Passes may not happen exactly in this sequence.) module CheckLineBreakable def extract_breakable_node(node, max) if node.call_type? return if chained_to_heredoc?(node) args = process_args(node.arguments) return extract_breakable_node_from_elements(node, args, max) elsif node.any_def_type? return extract_breakable_node_from_elements(node, node.arguments, max) elsif node.type?(:array, :hash) return extract_breakable_node_from_elements(node, node.children, max) end nil end private # @api private def extract_breakable_node_from_elements(node, elements, max) return unless breakable_collection?(node, elements) return if safe_to_ignore?(node) line = processed_source.lines[node.first_line - 1] return if processed_source.line_with_comment?(node.loc.line) return if line.length <= max extract_first_element_over_column_limit(node, elements, max) end # @api private def extract_first_element_over_column_limit(node, elements, max) line = node.first_line # If a `send` or `csend` node is not parenthesized, don't move the first element, because it # can result in changed behavior or a syntax error. if node.call_type? && !node.parenthesized? && !first_argument_is_heredoc?(node) elements = elements.drop(1) end i = 0 i += 1 while within_column_limit?(elements[i], max, line) i = shift_elements_for_heredoc_arg(node, elements, i) return if i.nil? return elements.first if i.zero? elements[i - 1] end # @api private def first_argument_is_heredoc?(node) first_argument = node.first_argument first_argument.respond_to?(:heredoc?) && first_argument.heredoc? end # @api private # If a `send` or `csend` node contains a heredoc argument, splitting cannot happen # after the heredoc or else it will cause a syntax error. def shift_elements_for_heredoc_arg(node, elements, index) return index unless node.type?(:call, :array) heredoc_index = elements.index { |arg| arg.respond_to?(:heredoc?) && arg.heredoc? } return index unless heredoc_index return nil if heredoc_index.zero? heredoc_index >= index ? index : heredoc_index + 1 end # @api private def within_column_limit?(element, max, line) element && element.loc.column <= max && element.loc.line == line end # @api private def safe_to_ignore?(node) return true unless max return true if already_on_multiple_lines?(node) # If there's a containing breakable collection on the same # line, we let that one get broken first. In a separate pass, # this one might get broken as well, but to avoid conflicting # or redundant edits, we only mark one offense at a time. return true if contained_by_breakable_collection_on_same_line?(node) return true if contained_by_multiline_collection_that_could_be_broken_up?(node) false end # @api private def breakable_collection?(node, elements) # For simplicity we only want to insert breaks in normal # hashes wrapped in a set of curly braces like {foo: 1}. # That is, not a kwargs hash. For method calls, this ensures # the method call is made with parens. starts_with_bracket = !node.hash_type? || node.loc.begin # If the call has a second argument, we can insert a line # break before the second argument and the rest of the # argument will get auto-formatted onto separate lines # by other cops. has_second_element = elements.length >= 2 starts_with_bracket && has_second_element end # @api private def contained_by_breakable_collection_on_same_line?(node) node.each_ancestor.find do |ancestor| # Ignore ancestors on different lines. break if ancestor.first_line != node.first_line if ancestor.type?(:hash, :array) elements = ancestor.children elsif ancestor.call_type? elements = process_args(ancestor.arguments) else next end return true if breakable_collection?(ancestor, elements) end false end # @api private def contained_by_multiline_collection_that_could_be_broken_up?(node) node.each_ancestor.find do |ancestor| if ancestor.type?(:hash, :array) && breakable_collection?(ancestor, ancestor.children) return children_could_be_broken_up?(ancestor.children) end next unless ancestor.call_type? args = process_args(ancestor.arguments) return children_could_be_broken_up?(args) if breakable_collection?(ancestor, args) end false end # @api private def children_could_be_broken_up?(children) return false if all_on_same_line?(children) last_seen_line = -1 children.each do |child| return true if last_seen_line >= child.first_line last_seen_line = child.last_line end false end # @api private def all_on_same_line?(nodes) return true if nodes.empty? nodes.first.first_line == nodes.last.last_line end # @api private def process_args(args) # If there is a trailing hash arg without explicit braces, like this: # # method(1, 'key1' => value1, 'key2' => value2) # # ...then each key/value pair is treated as a method 'argument' # when determining where line breaks should appear. last_arg = args.last args = args[0...-1] + last_arg.children if last_arg&.hash_type? && !last_arg&.braces? args end # @api private def already_on_multiple_lines?(node) return node.first_line != node.last_argument.last_line if node.any_def_type? !node.single_line? end def chained_to_heredoc?(node) while (node = node.receiver) return true if node.any_str_type? && node.heredoc? end false end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/empty_lines_around_body.rb
lib/rubocop/cop/mixin/empty_lines_around_body.rb
# frozen_string_literal: true module RuboCop module Cop module Layout # Common functionality for checking if presence/absence of empty lines # around some kind of body matches the configuration. module EmptyLinesAroundBody extend NodePattern::Macros include ConfigurableEnforcedStyle include RangeHelp MSG_EXTRA = 'Extra empty line detected at %<kind>s body %<location>s.' MSG_MISSING = 'Empty line missing at %<kind>s body %<location>s.' MSG_DEFERRED = 'Empty line missing before first %<type>s definition' private # @!method constant_definition?(node) def_node_matcher :constant_definition?, '{class module}' # @!method empty_line_required?(node) def_node_matcher :empty_line_required?, '{any_def class module (send nil? {:private :protected :public})}' def check(node, body, adjusted_first_line: nil) return if valid_body_style?(body) return if node.single_line? first_line = adjusted_first_line || node.source_range.first_line last_line = node.source_range.last_line case style when :empty_lines_except_namespace check_empty_lines_except_namespace(body, first_line, last_line) when :empty_lines_special check_empty_lines_special(body, first_line, last_line) else check_both(style, first_line, last_line) end end def check_empty_lines_except_namespace(body, first_line, last_line) if namespace?(body, with_one_child: true) check_both(:no_empty_lines, first_line, last_line) else check_both(:empty_lines, first_line, last_line) end end def check_empty_lines_special(body, first_line, last_line) return unless body if namespace?(body, with_one_child: true) check_both(:no_empty_lines, first_line, last_line) else if first_child_requires_empty_line?(body) check_beginning(:empty_lines, first_line) else check_beginning(:no_empty_lines, first_line) check_deferred_empty_line(body) end check_ending(:empty_lines, last_line) end end def check_both(style, first_line, last_line) case style when :beginning_only check_beginning(:empty_lines, first_line) check_ending(:no_empty_lines, last_line) when :ending_only check_beginning(:no_empty_lines, first_line) check_ending(:empty_lines, last_line) else check_beginning(style, first_line) check_ending(style, last_line) end end def check_beginning(style, first_line) check_source(style, first_line, 'beginning') end def check_ending(style, last_line) check_source(style, last_line - 2, 'end') end def check_source(style, line_no, desc) case style when :no_empty_lines check_line(style, line_no, message(MSG_EXTRA, desc), &:empty?) when :empty_lines check_line(style, line_no, message(MSG_MISSING, desc)) { |line| !line.empty? } end end def check_line(style, line, msg) return unless yield(processed_source.lines[line]) offset = style == :empty_lines && msg.include?('end.') ? 2 : 1 range = source_range(processed_source.buffer, line + offset, 0) add_offense(range, message: msg) do |corrector| EmptyLineCorrector.correct(corrector, [style, range]) end end def check_deferred_empty_line(body) node = first_empty_line_required_child(body) return unless node line = previous_line_ignoring_comments(node.first_line) return if processed_source[line].empty? range = source_range(processed_source.buffer, line + 2, 0) add_offense(range, message: deferred_message(node)) do |corrector| EmptyLineCorrector.correct(corrector, [:empty_lines, range]) end end def namespace?(body, with_one_child: false) if body.begin_type? return false if with_one_child body.children.all? { |child| constant_definition?(child) } else constant_definition?(body) end end def first_child_requires_empty_line?(body) if body.begin_type? empty_line_required?(body.children.first) else empty_line_required?(body) end end def first_empty_line_required_child(body) if body.begin_type? body.children.find { |child| empty_line_required?(child) } elsif empty_line_required?(body) body end end def previous_line_ignoring_comments(send_line) (send_line - 2).downto(0) do |line| return line unless comment_line?(processed_source[line]) end 0 end def message(type, desc) format(type, kind: self.class::KIND, location: desc) end def deferred_message(node) format(MSG_DEFERRED, type: node.type) end def valid_body_style?(body) # When style is `empty_lines`, if the body is empty, we don't enforce # the presence OR absence of an empty line # But if style is `no_empty_lines`, there must not be an empty line body.nil? && style != :no_empty_lines end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/match_range.rb
lib/rubocop/cop/mixin/match_range.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for obtaining source ranges from regexp matches module MatchRange include RangeHelp private # Return a new `Range` covering the first matching group number for each # match of `regex` inside `range` def each_match_range(range, regex) range.source.scan(regex) { yield match_range(range, Regexp.last_match) } end # For a `match` inside `range`, return a new `Range` covering the match def match_range(range, match) range_between(range.begin_pos + match.begin(1), range.begin_pos + match.end(1)) end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/hash_subset.rb
lib/rubocop/cop/mixin/hash_subset.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for Style/HashExcept and Style/HashSlice cops. # It registers an offense on methods with blocks that are equivalent # to Hash#except or Hash#slice. # rubocop:disable Metrics/ModuleLength module HashSubset include RangeHelp extend NodePattern::Macros RESTRICT_ON_SEND = %i[reject select filter].freeze SUBSET_METHODS = %i[== != eql? include?].freeze ACTIVE_SUPPORT_SUBSET_METHODS = (SUBSET_METHODS + %i[in? exclude?]).freeze MSG = 'Use `%<prefer>s` instead.' # @!method block_with_first_arg_check?(node) def_node_matcher :block_with_first_arg_check?, <<~PATTERN (block (call _ _) (args $(arg _key) $(arg _)) { $(send {(lvar _key) $_ _ | _ $_ (lvar _key)}) (send $(send {(lvar _key) $_ _ | _ $_ (lvar _key)}) :!) }) PATTERN def on_send(node) offense_range, key_source = extract_offense(node) return unless offense_range return unless semantically_subset_method?(node) preferred_method = "#{preferred_method_name}(#{key_source})" add_offense(offense_range, message: format(MSG, prefer: preferred_method)) do |corrector| corrector.replace(offense_range, preferred_method) end end alias on_csend on_send private def semantically_subset_method?(node) raise NotImplementedError end def preferred_method_name raise NotImplementedError end def extract_offense(node) block = node.parent return unless extracts_hash_subset?(block) except_key = except_key(block) return if except_key.nil? || !safe_to_register_offense?(block, except_key) [offense_range(node), except_key_source(except_key)] end def extracts_hash_subset?(block) block_with_first_arg_check?(block) do |key_arg, value_arg, send_node, method| # Only consider methods that have one argument return false unless send_node.arguments.one? return false unless supported_subset_method?(method) return false if range_include?(send_node) case method when :include?, :exclude? slices_key?(send_node, :first_argument, key_arg, value_arg) when :in? slices_key?(send_node, :receiver, key_arg, value_arg) else true end end end def slices_key?(send_node, method, key_arg, value_arg) return false if using_value_variable?(send_node, value_arg) node = method == :receiver ? send_node.receiver : send_node.first_argument node.source == key_arg.source end def range_include?(send_node) # When checking `include?`, `exclude?` and `in?` for offenses, if the receiver # or first argument is a range, an offense should not be registered. # ie. `(1..5).include?(k)` or `k.in?('a'..'z')` return true if send_node.first_argument.range_type? receiver = send_node.receiver receiver = receiver.child_nodes.first while receiver.begin_type? receiver.range_type? end def using_value_variable?(send_node, value_arg) # If the receiver of `include?` or `exclude?`, or the first argument of `in?` is the # hash value block argument, an offense should not be registered. # ie. `v.include?(k)` or `k.in?(v)` (send_node.receiver.lvar_type? && send_node.receiver.name == value_arg.name) || (send_node.first_argument.lvar_type? && send_node.first_argument.name == value_arg.name) end def supported_subset_method?(method) if active_support_extensions_enabled? ACTIVE_SUPPORT_SUBSET_METHODS.include?(method) else SUBSET_METHODS.include?(method) end end def semantically_except_method?(node) block = node.parent body, negated = extract_body_if_negated(block.body) if node.method?('reject') body.method?('==') || body.method?('eql?') || included?(body, negated) else body.method?('!=') || not_included?(body, negated) end end def semantically_slice_method?(node) !semantically_except_method?(node) end def included?(body, negated) if negated body.method?('exclude?') else body.method?('include?') || body.method?('in?') end end def not_included?(body, negated) included?(body, !negated) end def safe_to_register_offense?(block, except_key) body = block.body if body.method?('==') || body.method?('!=') except_key.type?(:sym, :str) else true end end def extract_body_if_negated(body) if body.method?('!') [body.receiver, true] else [body, false] end end def except_key_source(key) if key.array_type? key = if key.percent_literal? key.each_value.map { |v| decorate_source(v) } else key.each_value.map(&:source) end return key.join(', ') end key.literal? ? key.source : "*#{key.source}" end def decorate_source(value) return ":\"#{value.source}\"" if value.dsym_type? return "\"#{value.source}\"" if value.dstr_type? return ":#{value.source}" if value.sym_type? "'#{value.source}'" end def except_key(node) key_arg = node.argument_list.first.source body, = extract_body_if_negated(node.body) lhs, _method_name, rhs = *body lhs.source == key_arg ? rhs : lhs end def offense_range(node) range_between(node.loc.selector.begin_pos, node.parent.loc.end.end_pos) end end # rubocop:enable Metrics/ModuleLength end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/dig_help.rb
lib/rubocop/cop/mixin/dig_help.rb
# frozen_string_literal: true module RuboCop module Cop # Help methods for working with `Enumerable#dig` in cops. # Used by `Style::DigChain` and `Style::SingleArgumentDig` module DigHelp extend NodePattern::Macros # @!method dig?(node) def_node_matcher :dig?, <<~PATTERN (call _ :dig !{hash block_pass}+) PATTERN # @!method single_argument_dig?(node) def_node_matcher :single_argument_dig?, <<~PATTERN (send _ :dig $!splat) PATTERN private def dig_chain_enabled? @config.cop_enabled?('Style/DigChain') end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/multiline_expression_indentation.rb
lib/rubocop/cop/mixin/multiline_expression_indentation.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for checking multiline method calls and binary # operations. module MultilineExpressionIndentation # rubocop:disable Metrics/ModuleLength KEYWORD_ANCESTOR_TYPES = %i[for if while until return].freeze UNALIGNED_RHS_TYPES = %i[if while until for return array kwbegin].freeze DEFAULT_MESSAGE_TAIL = 'an expression' ASSIGNMENT_MESSAGE_TAIL = 'an expression in an assignment' KEYWORD_MESSAGE_TAIL = 'a %<kind>s in %<article>s `%<keyword>s` statement' def on_send(node) return if !node.receiver || node.method?(:[]) return unless relevant_node?(node) lhs = left_hand_side(node.receiver) rhs = right_hand_side(node) return unless rhs range = offending_range(node, lhs, rhs, style) check(range, node, lhs, rhs) end alias on_csend on_send private # In a chain of method calls, we regard the top call node as the base # for indentation of all lines following the first. For example: # a. # b c { block }. <-- b is indented relative to a # d <-- d is indented relative to a def left_hand_side(lhs) while lhs.parent&.call_type? && lhs.parent.loc.dot && !lhs.parent.assignment_method? lhs = lhs.parent end lhs end # The correct indentation of `node` is usually `IndentationWidth`, with # one exception: prefix keywords. # # ``` # while foo && # Here, `while` is called a "prefix keyword" # bar # This is called "special indentation" # baz # end # ``` # # Note that *postfix conditionals* do *not* get "special indentation". # # ``` # next if foo && # bar # normal indentation, not special # ``` def correct_indentation(node) kw_node = kw_node_with_special_indentation(node) if kw_node && !postfix_conditional?(kw_node) # This cop could have its own IndentationWidth configuration configured_indentation_width + @config.for_cop('Layout/IndentationWidth')['Width'] else configured_indentation_width end end def check(range, node, lhs, rhs) if range incorrect_style_detected(range, node, lhs, rhs) else correct_style_detected end end def incorrect_style_detected(range, node, lhs, rhs) add_offense(range, message: message(node, lhs, rhs)) do |corrector| autocorrect(corrector, range) if supported_styles.size > 2 || offending_range(node, lhs, rhs, alternative_style) unrecognized_style_detected else opposite_style_detected end end end def indentation(node) node.source_range.source_line =~ /\S/ end def operation_description(node, rhs) kw_node_with_special_indentation(node) do |ancestor| return keyword_message_tail(ancestor) end part_of_assignment_rhs(node, rhs) { |_node| return ASSIGNMENT_MESSAGE_TAIL } DEFAULT_MESSAGE_TAIL end def keyword_message_tail(node) keyword = node.loc.keyword.source kind = keyword == 'for' ? 'collection' : 'condition' article = keyword.start_with?('i', 'u') ? 'an' : 'a' format(KEYWORD_MESSAGE_TAIL, kind: kind, article: article, keyword: keyword) end def kw_node_with_special_indentation(node) keyword_node = node.each_ancestor(*KEYWORD_ANCESTOR_TYPES).find do |ancestor| next if ancestor.if_type? && ancestor.ternary? within_node?(node, indented_keyword_expression(ancestor)) end if keyword_node && block_given? yield keyword_node else keyword_node end end def indented_keyword_expression(node) if node.for_type? node.collection else node.children.first end end def argument_in_method_call(node, kind) # rubocop:todo Metrics/CyclomaticComplexity node.each_ancestor(:send, :block).find do |a| # If the node is inside a block, it makes no difference if that block # is an argument in a method call. It doesn't count. break false if a.block_type? next if a.setter_method? next unless kind == :with_or_without_parentheses || (kind == :with_parentheses && parentheses?(a)) a.arguments.any? { |arg| within_node?(node, arg) } end end def part_of_assignment_rhs(node, candidate) rhs_node = node.each_ancestor.find do |ancestor| break if disqualified_rhs?(candidate, ancestor) valid_rhs?(candidate, ancestor) end if rhs_node && block_given? yield rhs_node else rhs_node end end def disqualified_rhs?(candidate, ancestor) UNALIGNED_RHS_TYPES.include?(ancestor.type) || (ancestor.block_type? && part_of_block_body?(candidate, ancestor)) end def valid_rhs?(candidate, ancestor) if ancestor.send_type? valid_method_rhs_candidate?(candidate, ancestor) elsif ancestor.assignment? valid_rhs_candidate?(candidate, assignment_rhs(ancestor)) else false end end # The []= operator and setters (a.b = c) are parsed as :send nodes. def valid_method_rhs_candidate?(candidate, node) node.setter_method? && valid_rhs_candidate?(candidate, node.last_argument) end def valid_rhs_candidate?(candidate, node) !candidate || within_node?(candidate, node) end def part_of_block_body?(candidate, block_node) block_node.body && within_node?(candidate, block_node.body) end def assignment_rhs(node) case node.type when :casgn, :op_asgn then node.rhs when :send, :csend then node.last_argument else node.children.last end end def not_for_this_cop?(node) node.ancestors.any? do |ancestor| grouped_expression?(ancestor) || inside_arg_list_parentheses?(node, ancestor) end end def grouped_expression?(node) node.begin_type? && node.loc?(:begin) && node.loc.begin end def inside_arg_list_parentheses?(node, ancestor) return false unless ancestor.send_type? && ancestor.parenthesized? node.source_range.begin_pos > ancestor.loc.begin.begin_pos && node.source_range.end_pos < ancestor.loc.end.end_pos end # Returns true if `node` is a conditional whose `body` and `condition` # begin on the same line. def postfix_conditional?(node) node.if_type? && node.modifier_form? end def within_node?(inner, outer) o = outer.is_a?(AST::Node) ? outer.source_range : outer i = inner.is_a?(AST::Node) ? inner.source_range : inner i.begin_pos >= o.begin_pos && i.end_pos <= o.end_pos end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/def_node.rb
lib/rubocop/cop/mixin/def_node.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for checking def nodes. module DefNode extend NodePattern::Macros include VisibilityHelp private def non_public?(node) non_public_modifier?(node.parent) || preceding_non_public_modifier?(node) end def preceding_non_public_modifier?(node) node_visibility(node) != :public end # @!method non_public_modifier?(node) def_node_matcher :non_public_modifier?, <<~PATTERN (send nil? {:private :protected :private_class_method} (any_def ...)) PATTERN end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/visibility_help.rb
lib/rubocop/cop/mixin/visibility_help.rb
# frozen_string_literal: true require 'set' module RuboCop module Cop # Help methods for determining node visibility. module VisibilityHelp extend NodePattern::Macros VISIBILITY_SCOPES = ::Set[:private, :protected, :public].freeze private def node_visibility(node) node_visibility_from_visibility_inline(node) || node_visibility_from_visibility_block(node) || :public end def node_visibility_from_visibility_inline(node) return unless node.def_type? node_visibility_from_visibility_inline_on_def(node) || node_visibility_from_visibility_inline_on_method_name(node) end def node_visibility_from_visibility_inline_on_def(node) parent = node.parent parent.method_name if visibility_inline_on_def?(parent) end def node_visibility_from_visibility_inline_on_method_name(node) node.right_siblings.reverse.find do |sibling| visibility_inline_on_method_name?(sibling, method_name: node.method_name) end&.method_name end def node_visibility_from_visibility_block(node) find_visibility_start(node)&.method_name end def find_visibility_start(node) node.left_siblings.reverse.find { |sibling| visibility_block?(sibling) } end # Navigate to find the last protected method def find_visibility_end(node) possible_visibilities = VISIBILITY_SCOPES - ::Set[node_visibility(node)] right = node.right_siblings right.find do |child_node| possible_visibilities.include?(node_visibility(child_node)) end || right.last end # @!method visibility_block?(node) def_node_matcher :visibility_block?, <<~PATTERN (send nil? VISIBILITY_SCOPES) PATTERN # @!method visibility_inline_on_def?(node) def_node_matcher :visibility_inline_on_def?, <<~PATTERN (send nil? VISIBILITY_SCOPES def) PATTERN # @!method visibility_inline_on_method_name?(node, method_name:) def_node_matcher :visibility_inline_on_method_name?, <<~PATTERN (send nil? VISIBILITY_SCOPES (sym %method_name)) PATTERN end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/comments_help.rb
lib/rubocop/cop/mixin/comments_help.rb
# frozen_string_literal: true module RuboCop module Cop # Help methods for working with nodes containing comments. module CommentsHelp def source_range_with_comment(node) begin_pos = begin_pos_with_comment(node) end_pos = end_position_for(node) Parser::Source::Range.new(buffer, begin_pos, end_pos) end def contains_comments?(node) comments_in_range(node).any? end def comments_in_range(node) return [] unless node.source_range start_line = node.source_range.line end_line = find_end_line(node) processed_source.each_comment_in_lines(start_line...end_line) end def comments_contain_disables?(node, cop_name) disabled_ranges = processed_source.disabled_line_ranges[cop_name] return false unless disabled_ranges node_range = node.source_range.line...find_end_line(node) disabled_ranges.any? do |disable_range| disable_range.cover?(node_range) || node_range.cover?(disable_range) end end private def end_position_for(node) end_line = buffer.line_for_position(node.source_range.end_pos) buffer.line_range(end_line).end_pos end def begin_pos_with_comment(node) first_comment = processed_source.ast_with_comments[node].first if first_comment && (first_comment.loc.line < node.loc.line) start_line_position(first_comment) else start_line_position(node) end end def start_line_position(node) buffer.line_range(node.loc.line).begin_pos - 1 end def buffer processed_source.buffer end # Returns the end line of a node, which might be a comment and not part of the AST # End line is considered either the line at which another node starts, or # the line at which the parent node ends. # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity def find_end_line(node) if node.if_type? if node.else? node.loc.else.line elsif node.ternary? node.else_branch.loc.line elsif node.elsif? node.each_ancestor(:if).find(&:if?).loc.end.line elsif node.if? && node.parent && parentheses?(node.parent) node.parent.loc.end.line end elsif node.any_block_type? node.loc.end.line elsif (next_sibling = node.right_sibling) && next_sibling.is_a?(AST::Node) && next_sibling.source_range next_sibling.loc.line elsif (parent = node.parent) if parent.loc?(:end) parent.loc.end.line else parent.loc.line end end || node.loc.end.line end # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/min_body_length.rb
lib/rubocop/cop/mixin/min_body_length.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for checking minimum body length. module MinBodyLength private def min_body_length?(node) (node.loc.end.line - node.loc.keyword.line) > min_body_length end def min_body_length length = cop_config['MinBodyLength'] || 1 return length if length.is_a?(Integer) && length.positive? raise 'MinBodyLength needs to be a positive integer!' end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/array_min_size.rb
lib/rubocop/cop/mixin/array_min_size.rb
# frozen_string_literal: true module RuboCop module Cop # Handles the `MinSize` configuration option for array-based cops # `Style/SymbolArray` and `Style/WordArray`, which check for use of the # relevant percent literal syntax such as `%i[...]` and `%w[...]` module ArrayMinSize private def below_array_length?(node) node.values.length < min_size_config end def min_size_config cop_config['MinSize'] end def array_style_detected(style, ary_size) # rubocop:todo Metrics/AbcSize cfg = config_to_allow_offenses return if cfg['Enabled'] == false largest_brackets = largest_brackets_size(style, ary_size) smallest_percent = smallest_percent_size(style, ary_size) if cfg['EnforcedStyle'] == style.to_s # do nothing elsif cfg['EnforcedStyle'].nil? cfg['EnforcedStyle'] = style.to_s elsif smallest_percent <= largest_brackets self.config_to_allow_offenses = { 'Enabled' => false } else cfg['EnforcedStyle'] = 'percent' cfg['MinSize'] = largest_brackets + 1 end end def largest_brackets_size(style, ary_size) self.class.largest_brackets ||= -Float::INFINITY if style == :brackets && ary_size > self.class.largest_brackets self.class.largest_brackets = ary_size end self.class.largest_brackets end def smallest_percent_size(style, ary_size) @smallest_percent ||= Float::INFINITY @smallest_percent = ary_size if style == :percent && ary_size < @smallest_percent @smallest_percent end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/method_complexity.rb
lib/rubocop/cop/mixin/method_complexity.rb
# frozen_string_literal: true module RuboCop module Cop # @api private # # This module handles measurement and reporting of complexity in methods. module MethodComplexity include AllowedMethods include AllowedPattern include Metrics::Utils::RepeatedCsendDiscount extend NodePattern::Macros extend ExcludeLimit exclude_limit 'Max' def on_def(node) return if allowed_method?(node.method_name) || matches_allowed_pattern?(node.method_name) check_complexity(node, node.method_name) end alias on_defs on_def def on_block(node) define_method?(node) do |name| return if allowed_method?(name) || matches_allowed_pattern?(name) check_complexity(node, name) end end alias on_numblock on_block alias on_itblock on_block private # @!method define_method?(node) def_node_matcher :define_method?, <<~PATTERN (any_block (send nil? :define_method ({sym str} $_)) _ _) PATTERN def check_complexity(node, method_name) # Accepts empty methods always. return unless node.body max = cop_config['Max'] reset_repeated_csend complexity, abc_vector = complexity(node.body) return unless complexity > max msg = format( self.class::MSG, method: method_name, complexity: complexity, abc_vector: abc_vector, max: max ) location = location(node) add_offense(location, message: msg) { self.max = complexity.ceil } end def complexity(body) score = 1 body.each_node(:lvasgn, *self.class::COUNTED_NODES) do |node| if node.lvasgn_type? reset_on_lvasgn(node) else score += complexity_score_for(node) end end score end def location(node) if LSP.enabled? end_range = node.loc?(:name) ? node.loc.name : node.loc.begin node.source_range.begin.join(end_range) else node.source_range end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/line_length_help.rb
lib/rubocop/cop/mixin/line_length_help.rb
# frozen_string_literal: true module RuboCop module Cop # Help methods for determining if a line is too long. module LineLengthHelp include Alignment private def allow_rbs_inline_annotation? config.for_cop('Layout/LineLength')['AllowRBSInlineAnnotation'] end def rbs_inline_annotation_on_source_line?(line_index) source_line_number = line_index + processed_source.buffer.first_line comment = processed_source.comment_at_line(source_line_number) return false unless comment comment.text.start_with?(/#:|#\[.+\]|#\|/) end def allow_cop_directives? # TODO: This logic for backward compatibility with deprecated `IgnoreCopDirectives` option. # The following three lines will be removed in RuboCop 2.0. ignore_cop_directives = config.for_cop('Layout/LineLength')['IgnoreCopDirectives'] return true if ignore_cop_directives return false if ignore_cop_directives == false config.for_cop('Layout/LineLength')['AllowCopDirectives'] end def directive_on_source_line?(line_index) source_line_number = line_index + processed_source.buffer.first_line comment = processed_source.comment_at_line(source_line_number) return false unless comment !!DirectiveComment.new(comment).match_captures end def allow_uri? config.for_cop('Layout/LineLength')['AllowURI'] end def allow_qualified_name? config.for_cop('Layout/LineLength')['AllowQualifiedName'] end def allowed_position?(line, range) range.begin < max_line_length && range.end == line_length(line) end def line_length(line) line.length + indentation_difference(line) end def find_excessive_range(line, type) last_match = (type == :uri ? match_uris(line) : match_qualified_names(line)).last return nil unless last_match begin_position, end_position = last_match.offset(0) end_position = extend_end_position(line, end_position) line_indentation_difference = indentation_difference(line) begin_position += line_indentation_difference end_position += line_indentation_difference return nil if begin_position < max_line_length && end_position < max_line_length begin_position...end_position end def match_uris(string) matches = [] string.scan(uri_regexp) do matches << $LAST_MATCH_INFO if valid_uri?($LAST_MATCH_INFO[0]) end matches end def match_qualified_names(string) matches = [] string.scan(qualified_name_regexp) do matches << $LAST_MATCH_INFO end matches end def indentation_difference(line) return 0 unless tab_indentation_width index = if line.match?(/^[^\t]/) 0 else line.index(/[^\t]/) || 0 end index * (tab_indentation_width - 1) end def extend_end_position(line, end_position) # Extend the end position YARD comments with linked URLs of the form {<uri> <title>} if line&.match(/{(\s|\S)*}$/) match = line[end_position..line_length(line)]&.match(/(\s|\S)*}/) end_position += match.offset(0).last end # Extend the end position until the start of the next word, if any. # This allows for URIs that are wrapped in quotes or parens to be handled properly # while not allowing additional words to be added after the URL. if (match = line[end_position..line_length(line)]&.match(/^\S+(?=\s|$)/)) end_position += match.offset(0).last end end_position end def tab_indentation_width config.for_cop('Layout/IndentationStyle')['IndentationWidth'] || configured_indentation_width end def uri_regexp @uri_regexp ||= begin # Ruby 3.4 changes the default parser to RFC3986 which warns on make_regexp. # Additionally, the RFC2396_PARSER alias is only available on 3.4 for now. # Extra info at https://github.com/ruby/uri/issues/118 parser = defined?(URI::RFC2396_PARSER) ? URI::RFC2396_PARSER : URI::DEFAULT_PARSER parser.make_regexp(config.for_cop('Layout/LineLength')['URISchemes']) end end def qualified_name_regexp /\b(?:[A-Z][A-Za-z0-9_]*::)+[A-Za-z_][A-Za-z0-9_]*\b/ end def valid_uri?(uri_ish_string) URI.parse(uri_ish_string) true rescue URI::InvalidURIError, NoMethodError false end def line_length_without_directive(line) DirectiveComment.before_comment(line).rstrip.length end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/integer_node.rb
lib/rubocop/cop/mixin/integer_node.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for checking integer nodes. module IntegerNode private def integer_part(node) node.source.sub(/^[+-]/, '').split(/[eE.]/, 2).first end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/configurable_numbering.rb
lib/rubocop/cop/mixin/configurable_numbering.rb
# frozen_string_literal: true module RuboCop module Cop # This module provides functionality for checking if numbering match the # configured EnforcedStyle. module ConfigurableNumbering include ConfigurableFormatting implicit_param = /\A_\d+\z/ FORMATS = { snake_case: /(?:\D|_\d+|\A\d+)\z/, normalcase: /(?:\D|[^_\d]\d+|\A\d+)\z|#{implicit_param}/, non_integer: /(\D|\A\d+)\z|#{implicit_param}/ }.freeze end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/rational_literal.rb
lib/rubocop/cop/mixin/rational_literal.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for handling Rational literals. module RationalLiteral extend NodePattern::Macros private # @!method rational_literal?(node) def_node_matcher :rational_literal?, <<~PATTERN (send (int _) :/ (rational _)) PATTERN end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/hash_shorthand_syntax.rb
lib/rubocop/cop/mixin/hash_shorthand_syntax.rb
# frozen_string_literal: true module RuboCop module Cop # This module checks for Ruby 3.1's hash value omission syntax. # rubocop:disable Metrics/ModuleLength module HashShorthandSyntax OMIT_HASH_VALUE_MSG = 'Omit the hash value.' EXPLICIT_HASH_VALUE_MSG = 'Include the hash value.' DO_NOT_MIX_MSG_PREFIX = 'Do not mix explicit and implicit hash values.' DO_NOT_MIX_OMIT_VALUE_MSG = "#{DO_NOT_MIX_MSG_PREFIX} #{OMIT_HASH_VALUE_MSG}" DO_NOT_MIX_EXPLICIT_VALUE_MSG = "#{DO_NOT_MIX_MSG_PREFIX} #{EXPLICIT_HASH_VALUE_MSG}" DefNode = Struct.new(:node) do def selector if node.loc?(:selector) node.loc.selector else node.loc.keyword end end def first_argument node.first_argument end def last_argument node.last_argument end end def on_hash_for_mixed_shorthand(hash_node) return if ignore_mixed_hash_shorthand_syntax?(hash_node) hash_value_type_breakdown = breakdown_value_types_of_hash(hash_node) if hash_with_mixed_shorthand_syntax?(hash_value_type_breakdown) mixed_shorthand_syntax_check(hash_value_type_breakdown) else no_mixed_shorthand_syntax_check(hash_value_type_breakdown) end end def on_pair(node) return if ignore_hash_shorthand_syntax?(node) hash_key_source = node.key.source if enforced_shorthand_syntax == 'always' return if node.value_omission? || require_hash_value?(hash_key_source, node) message = OMIT_HASH_VALUE_MSG replacement = "#{hash_key_source}:" self.config_to_allow_offenses = { 'Enabled' => false } else return unless node.value_omission? message = EXPLICIT_HASH_VALUE_MSG replacement = "#{hash_key_source}: #{hash_key_source}" end register_offense(node, message, replacement) end private def register_offense(node, message, replacement) # rubocop:disable Metrics/AbcSize add_offense(node.value, message: message) do |corrector| corrector.replace(node, replacement) next unless (def_node = def_node_that_require_parentheses(node)) last_argument = def_node.last_argument if last_argument.nil? || !last_argument.hash_type? next corrector.replace(node, replacement) end white_spaces = range_between(def_node.selector.end_pos, def_node.first_argument.source_range.begin_pos) next if node.parent.braces? corrector.replace(white_spaces, '(') corrector.insert_after(last_argument, ')') if node == last_argument.pairs.last end end def ignore_mixed_hash_shorthand_syntax?(hash_node) target_ruby_version <= 3.0 || !%w[consistent either_consistent].include?(enforced_shorthand_syntax) || !hash_node.hash_type? end def ignore_hash_shorthand_syntax?(pair_node) target_ruby_version <= 3.0 || enforced_shorthand_syntax == 'either' || %w[consistent either_consistent].include?(enforced_shorthand_syntax) || !pair_node.parent.hash_type? end def enforced_shorthand_syntax cop_config.fetch('EnforcedShorthandSyntax', 'always') end def require_hash_value?(hash_key_source, node) return true if !node.key.sym_type? || require_hash_value_for_around_hash_literal?(node) hash_value = node.value return true unless hash_value.type?(:send, :lvar) hash_key_source != hash_value.source || hash_key_source.end_with?('!', '?') end def require_hash_value_for_around_hash_literal?(node) return false unless (method_dispatch_node = find_ancestor_method_dispatch_node(node)) !node.parent.braces? && !use_element_of_hash_literal_as_receiver?(method_dispatch_node, node.parent) && use_modifier_form_without_parenthesized_method_call?(method_dispatch_node) end # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity def def_node_that_require_parentheses(node) last_pair = node.parent.pairs.last return unless last_pair.key.source == last_pair.value.source return unless (dispatch_node = find_ancestor_method_dispatch_node(node)) return if dispatch_node.assignment_method? return if dispatch_node.parenthesized? return if dispatch_node.parent && parentheses?(dispatch_node.parent) return if last_expression?(dispatch_node) && !method_dispatch_as_argument?(dispatch_node) def_node = node.each_ancestor(:call, :super, :yield).first DefNode.new(def_node) unless def_node && def_node.arguments.empty? end # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity def find_ancestor_method_dispatch_node(node) return unless (ancestor = node.parent.parent) return unless ancestor.type?(:call, :super, :yield) return if brackets?(ancestor) ancestor end def brackets?(method_dispatch_node) method_dispatch_node.method?(:[]) || method_dispatch_node.method?(:[]=) end def use_element_of_hash_literal_as_receiver?(ancestor, parent) # `{value:}.do_something` is a valid syntax. ancestor.send_type? && ancestor.receiver == parent end def use_modifier_form_without_parenthesized_method_call?(ancestor) return false if ancestor.respond_to?(:parenthesized?) && ancestor.parenthesized? ancestor.ancestors.any? { |node| node.respond_to?(:modifier_form?) && node.modifier_form? } end def last_expression?(node) return false if node.right_sibling return true unless (assignment_node = node.each_ancestor.find(&:assignment?)) return last_expression?(assignment_node.parent) if assignment_node.parent&.assignment? !assignment_node.right_sibling end def method_dispatch_as_argument?(method_dispatch_node) parent = method_dispatch_node.parent return false unless parent parent.type?(:call, :super, :yield) end def breakdown_value_types_of_hash(hash_node) hash_node.pairs.group_by do |pair_node| if pair_node.value_omission? :value_omitted elsif require_hash_value?(pair_node.key.source, pair_node) :value_needed else :value_omittable end end end def hash_with_mixed_shorthand_syntax?(hash_value_type_breakdown) hash_value_type_breakdown.keys.size > 1 end def hash_with_values_that_cant_be_omitted?(hash_value_type_breakdown) hash_value_type_breakdown[:value_needed]&.any? end def ignore_explicit_omissible_hash_shorthand_syntax?(hash_value_type_breakdown) hash_value_type_breakdown.keys == [:value_omittable] && enforced_shorthand_syntax == 'either_consistent' end def each_omitted_value_pair(hash_value_type_breakdown, &block) hash_value_type_breakdown[:value_omitted]&.each(&block) end def each_omittable_value_pair(hash_value_type_breakdown, &block) hash_value_type_breakdown[:value_omittable]&.each(&block) end def mixed_shorthand_syntax_check(hash_value_type_breakdown) if hash_with_values_that_cant_be_omitted?(hash_value_type_breakdown) each_omitted_value_pair(hash_value_type_breakdown) do |pair_node| hash_key_source = pair_node.key.source replacement = "#{hash_key_source}: #{hash_key_source}" register_offense(pair_node, DO_NOT_MIX_EXPLICIT_VALUE_MSG, replacement) end else each_omittable_value_pair(hash_value_type_breakdown) do |pair_node| hash_key_source = pair_node.key.source replacement = "#{hash_key_source}:" register_offense(pair_node, DO_NOT_MIX_OMIT_VALUE_MSG, replacement) end end end def no_mixed_shorthand_syntax_check(hash_value_type_breakdown) return if hash_with_values_that_cant_be_omitted?(hash_value_type_breakdown) return if ignore_explicit_omissible_hash_shorthand_syntax?(hash_value_type_breakdown) each_omittable_value_pair(hash_value_type_breakdown) do |pair_node| hash_key_source = pair_node.key.source replacement = "#{hash_key_source}:" register_offense(pair_node, OMIT_HASH_VALUE_MSG, replacement) end end end end # rubocop:enable Metrics/ModuleLength end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/method_preference.rb
lib/rubocop/cop/mixin/method_preference.rb
# frozen_string_literal: true module RuboCop module Cop # Common code for cops that deal with preferred methods. module MethodPreference private def preferred_method(method) preferred_methods[method.to_sym] end def preferred_methods @preferred_methods ||= begin # Make sure default configuration 'foo' => 'bar' is removed from # the total configuration if there is a 'bar' => 'foo' override. default = default_cop_config['PreferredMethods'] merged = cop_config['PreferredMethods'] overrides = merged.values - default.values merged.reject { |key, _| overrides.include?(key) }.transform_keys(&:to_sym) end end def default_cop_config ConfigLoader.default_configuration[cop_name] end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/preferred_delimiters.rb
lib/rubocop/cop/mixin/preferred_delimiters.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for handling percent literal delimiters. class PreferredDelimiters attr_reader :type, :config PERCENT_LITERAL_TYPES = %w[% %i %I %q %Q %r %s %w %W %x].freeze def initialize(type, config, preferred_delimiters) @type = type @config = config @preferred_delimiters = preferred_delimiters end def delimiters preferred_delimiters[type].chars end private def ensure_valid_preferred_delimiters invalid = preferred_delimiters_config.keys - (PERCENT_LITERAL_TYPES + %w[default]) return if invalid.empty? raise ArgumentError, "Invalid preferred delimiter config key: #{invalid.join(', ')}" end def preferred_delimiters @preferred_delimiters ||= begin ensure_valid_preferred_delimiters if preferred_delimiters_config.key?('default') PERCENT_LITERAL_TYPES.to_h do |type| [type, preferred_delimiters_config[type] || preferred_delimiters_config['default']] end else preferred_delimiters_config end end end def preferred_delimiters_config config.for_cop('Style/PercentLiteralDelimiters')['PreferredDelimiters'] end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/require_library.rb
lib/rubocop/cop/mixin/require_library.rb
# frozen_string_literal: true module RuboCop module Cop # Ensure a require statement is present for a standard library determined # by variable library_name module RequireLibrary extend NodePattern::Macros RESTRICT_ON_SEND = [:require].freeze def ensure_required(corrector, node, library_name) node = node.parent while node.parent&.parent? if node.parent&.begin_type? return if @required_libs.include?(library_name) remove_subsequent_requires(corrector, node, library_name) end RequireLibraryCorrector.correct(corrector, node, library_name) end def remove_subsequent_requires(corrector, node, library_name) node.right_siblings.each do |sibling| next unless require_library_name?(sibling, library_name) range = range_by_whole_lines(sibling.source_range, include_final_newline: true) corrector.remove(range) end end def on_send(node) return if node.parent&.parent? name = require_any_library?(node) return if name.nil? @required_libs.add(name) end private def on_new_investigation # Holds the required files at top-level @required_libs = Set.new super end # @!method require_any_library?(node) def_node_matcher :require_any_library?, <<~PATTERN (send {(const {nil? cbase} :Kernel) nil?} :require (str $_)) PATTERN # @!method require_library_name?(node, library_name) def_node_matcher :require_library_name?, <<~PATTERN (send {(const {nil? cbase} :Kernel) nil?} :require (str %1)) PATTERN end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/string_help.rb
lib/rubocop/cop/mixin/string_help.rb
# frozen_string_literal: true module RuboCop module Cop # Classes that include this module just implement functions to determine # what is an offense and how to do autocorrection. They get help with # adding offenses for the faulty string nodes, and with filtering out # nodes. module StringHelp def on_str(node) # Constants like __FILE__ are handled as strings, # but don't respond to begin. return unless node.loc?(:begin) return if part_of_ignored_node?(node) if offense?(node) add_offense(node) do |corrector| opposite_style_detected autocorrect(corrector, node) if respond_to?(:autocorrect, true) end else correct_style_detected end end def on_regexp(node) ignore_node(node) end private def inside_interpolation?(node) # A :begin node inside a :dstr, :dsym, or :regexp node is an interpolation. node.ancestors .drop_while { |a| !a.begin_type? } .any? { |a| a.type?(:dstr, :dsym, :regexp) } end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/forbidden_identifiers.rb
lib/rubocop/cop/mixin/forbidden_identifiers.rb
# frozen_string_literal: true module RuboCop module Cop # This module encapsulates the ability to forbid certain identifiers in a cop. module ForbiddenIdentifiers SIGILS = '@$' # if a variable starts with a sigil it will be removed def forbidden_identifier?(name) name = name.to_s.delete(SIGILS) forbidden_identifiers.any? && forbidden_identifiers.include?(name) end def forbidden_identifiers cop_config.fetch('ForbiddenIdentifiers', []) end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/configurable_naming.rb
lib/rubocop/cop/mixin/configurable_naming.rb
# frozen_string_literal: true module RuboCop module Cop # This module provides functionality for checking if names match the # configured EnforcedStyle. module ConfigurableNaming include ConfigurableFormatting FORMATS = { snake_case: /^@{0,2}[\d[[:lower:]]_]+[!?=]?$/, camelCase: /^@{0,2}(?:_|_?[[[:lower:]]][\d[[:lower:]][[:upper:]]]*)[!?=]?$/ }.freeze end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/symbol_help.rb
lib/rubocop/cop/mixin/symbol_help.rb
# frozen_string_literal: true module RuboCop module Cop # Classes that include this module just implement functions for working # with symbol nodes. module SymbolHelp def hash_key?(node) node.parent&.pair_type? && node == node.parent.child_nodes.first end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/check_assignment.rb
lib/rubocop/cop/mixin/check_assignment.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for checking assignment nodes. module CheckAssignment def on_lvasgn(node) check_assignment(node, extract_rhs(node)) end alias on_ivasgn on_lvasgn alias on_cvasgn on_lvasgn alias on_gvasgn on_lvasgn alias on_casgn on_lvasgn alias on_masgn on_lvasgn alias on_op_asgn on_lvasgn alias on_or_asgn on_lvasgn alias on_and_asgn on_lvasgn def on_send(node) return unless (rhs = extract_rhs(node)) check_assignment(node, rhs) end module_function def extract_rhs(node) if node.call_type? node.last_argument elsif node.assignment? node.expression end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/statement_modifier.rb
lib/rubocop/cop/mixin/statement_modifier.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for modifier cops. module StatementModifier include LineLengthHelp private def single_line_as_modifier?(node) return false if non_eligible_node?(node) || non_eligible_body?(node.body) || non_eligible_condition?(node.condition) modifier_fits_on_single_line?(node) end def non_eligible_node?(node) node.modifier_form? || node.nonempty_line_count > 3 || processed_source.line_with_comment?(node.loc.last_line) || (first_line_comment(node) && code_after(node)) end def non_eligible_body?(body) body.nil? || body.empty_source? || body.begin_type? || processed_source.contains_comment?(body.source_range) end def non_eligible_condition?(condition) condition.each_node.any?(&:lvasgn_type?) end def modifier_fits_on_single_line?(node) return true unless max_line_length length_in_modifier_form(node) <= max_line_length end def length_in_modifier_form(node) keyword_element = node.loc.keyword code_before = keyword_element.source_line[0...keyword_element.column] expression = to_modifier_form(node) line_length("#{code_before}#{expression}#{code_after(node)}") end def to_modifier_form(node) body = if_body_source(node.body) expression = [body, node.keyword, node.condition.source].compact.join(' ') parenthesized = parenthesize?(node) ? "(#{expression})" : expression [parenthesized, first_line_comment(node)].compact.join(' ') end def if_body_source(if_body) if if_body.call_type? && !if_body.method?(:[]=) && omitted_value_in_last_hash_arg?(if_body) "#{method_source(if_body)}(#{if_body.arguments.map(&:source).join(', ')})" else if_body.source end end def omitted_value_in_last_hash_arg?(if_body) return false unless (last_argument = if_body.last_argument) last_argument.hash_type? && last_argument.pairs.last&.value_omission? end def method_source(if_body) end_range = if_body.implicit_call? ? if_body.loc.dot.end : if_body.loc.selector if_body.source_range.begin.join(end_range).source end def first_line_comment(node) comment = processed_source.comments.find { |c| same_line?(c, node) } return unless comment comment_source = comment.source comment_source unless comment_disables_cop?(comment_source) end def code_after(node) end_element = node.loc.end code = end_element.source_line[end_element.last_column..] code unless code.empty? end def parenthesize?(node) # Parenthesize corrected expression if changing to modifier-if form # would change the meaning of the parent expression # (due to the low operator precedence of modifier-if) parent = node.parent return false if parent.nil? return true if parent.assignment? || parent.operator_keyword? return true if %i[array pair].include?(parent.type) node.parent.send_type? end def comment_disables_cop?(comment) regexp_pattern = "# rubocop : (disable|todo) ([^,],)* (all|#{cop_name})" Regexp.new(regexp_pattern.gsub(' ', '\s*')).match?(comment) end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/enforce_superclass.rb
lib/rubocop/cop/mixin/enforce_superclass.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for enforcing a specific superclass. # # IMPORTANT: RuboCop core depended on this module when it supported Rails department. # Rails department has been extracted to RuboCop Rails gem. # # @deprecated This module is deprecated and will be removed by RuboCop 2.0. # It will not be updated to `RuboCop::Cop::Base` v1 API to maintain compatibility # with existing RuboCop Rails 2.8 or lower. # # @api private module EnforceSuperclass def self.included(base) warn Rainbow( '`RuboCop::Cop::EnforceSuperclass` is deprecated and will be removed in RuboCop 2.0. ' \ 'Please upgrade to RuboCop Rails 2.9 or newer to continue.' ).yellow # @!method class_definition(node) base.def_node_matcher :class_definition, <<~PATTERN (class (const _ !:#{base::SUPERCLASS}) #{base::BASE_PATTERN} ...) PATTERN # @!method class_new_definition(node) base.def_node_matcher :class_new_definition, <<~PATTERN [!^(casgn {nil? cbase} :#{base::SUPERCLASS} ...) !^^(casgn {nil? cbase} :#{base::SUPERCLASS} (block ...)) (send (const {nil? cbase} :Class) :new #{base::BASE_PATTERN})] PATTERN end def on_class(node) class_definition(node) { add_offense(node.children[1]) } end def on_send(node) class_new_definition(node) { add_offense(node.children.last) } end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/preceding_following_alignment.rb
lib/rubocop/cop/mixin/preceding_following_alignment.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for checking whether an AST node/token is aligned # with something on a preceding or following line # rubocop:disable Metrics/ModuleLength module PrecedingFollowingAlignment # Tokens that end with an `=`, as well as `<<`, that can be aligned together: # `=`, `==`, `===`, `!=`, `<=`, `>=`, `<<` and operator assignment (`+=`, etc). ASSIGNMENT_OR_COMPARISON_TOKENS = %i[tEQL tEQ tEQQ tNEQ tLEQ tGEQ tOP_ASGN tLSHFT].freeze private def allow_for_alignment? cop_config['AllowForAlignment'] end def aligned_with_something?(range) aligned_with_adjacent_line?(range, method(:aligned_token?)) end def aligned_with_operator?(range) aligned_with_adjacent_line?(range, method(:aligned_operator?)) end # Allows alignment with a preceding operator that ends with an `=`, # including assignment and comparison operators. def aligned_with_preceding_equals_operator(token) preceding_line_range = token.line.downto(1) aligned_with_equals_sign(token, preceding_line_range) end # Allows alignment with a subsequent operator that ends with an `=`, # including assignment and comparison operators. def aligned_with_subsequent_equals_operator(token) subsequent_line_range = token.line.upto(processed_source.lines.length) aligned_with_equals_sign(token, subsequent_line_range) end def aligned_with_adjacent_line?(range, predicate) # minus 2 because node.loc.line is zero-based pre = (range.line - 2).downto(0) post = range.line.upto(processed_source.lines.size - 1) aligned_with_any_line_range?([pre, post], range, &predicate) end def aligned_with_any_line_range?(line_ranges, range, &predicate) return true if aligned_with_any_line?(line_ranges, range, &predicate) # If no aligned token was found, search for an aligned token on the # nearest line with the same indentation as the checked line. base_indentation = processed_source.lines[range.line - 1] =~ /\S/ aligned_with_any_line?(line_ranges, range, base_indentation, &predicate) end def aligned_with_any_line?(line_ranges, range, indent = nil, &predicate) line_ranges.any? { |line_nos| aligned_with_line?(line_nos, range, indent, &predicate) } end def aligned_with_line?(line_nos, range, indent = nil) line_nos.each do |lineno| next if aligned_comment_lines.include?(lineno + 1) line = processed_source.lines[lineno] index = line =~ /\S/ next unless index next if indent && indent != index return yield(range, line, lineno + 1) end false end def aligned_comment_lines @aligned_comment_lines ||= processed_source.comments.map(&:loc).select do |r| begins_its_line?(r.expression) end.map(&:line) end def aligned_token?(range, line, lineno) aligned_words?(range, line) || aligned_equals_operator?(range, lineno) end def aligned_operator?(range, line, lineno) aligned_identical?(range, line) || aligned_equals_operator?(range, lineno) end def aligned_words?(range, line) left_edge = range.column return true if /\s\S/.match?(line[left_edge - 1, 2]) token = range.source token == line[left_edge, token.length] end def aligned_equals_operator?(range, lineno) # Check that the operator is aligned with a previous assignment or comparison operator # ie. an equals sign, an operator assignment (eg. `+=`), a comparison (`==`, `<=`, etc.). # Since append operators (`<<`) are a type of assignment, they are allowed as well, # despite not ending with a literal equals character. line_range = processed_source.buffer.line_range(lineno) return false unless line_range # Find the specific token to avoid matching up to operators inside strings operator_token = processed_source.tokens_within(line_range).detect do |token| ASSIGNMENT_OR_COMPARISON_TOKENS.include?(token.type) end aligned_with_preceding_equals?(range, operator_token) || aligned_with_append_operator?(range, operator_token) end def aligned_with_preceding_equals?(range, token) return false unless token range.source[-1] == '=' && range.last_column == token.pos.last_column end def aligned_with_append_operator?(range, token) return false unless token ((range.source == '<<' && token.equal_sign?) || (range.source[-1] == '=' && token.type == :tLSHFT)) && token && range.last_column == token.pos.last_column end def aligned_identical?(range, line) range.source == line[range.column, range.size] end def aligned_with_equals_sign(token, line_range) token_line_indent = processed_source.line_indentation(token.line) assignment_lines = relevant_assignment_lines(line_range) relevant_line_number = assignment_lines[1] return :none unless relevant_line_number relevant_indent = processed_source.line_indentation(relevant_line_number) return :none if relevant_indent < token_line_indent return :none unless processed_source.lines[relevant_line_number - 1] aligned_equals_operator?(token.pos, relevant_line_number) ? :yes : :no end def assignment_lines @assignment_lines ||= assignment_tokens.map(&:line) end def assignment_tokens @assignment_tokens ||= begin tokens = processed_source.tokens.select(&:equal_sign?) # We don't want to operate on equals signs which are part of an `optarg` in a # method definition, or the separator of an endless method definition. # For example (the equals sign to ignore is highlighted with ^): # def method(optarg = default_val); end # ^ # def method = foo # ^ tokens = remove_equals_in_def(tokens, processed_source) # Only attempt to align the first = on each line Set.new(tokens.uniq(&:line)) end end # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity # rubocop:disable Metrics/PerceivedComplexity, Metrics/MethodLength def relevant_assignment_lines(line_range) result = [] original_line_indent = processed_source.line_indentation(line_range.first) relevant_line_indent_at_level = true line_range.each do |line_number| current_line_indent = processed_source.line_indentation(line_number) blank_line = processed_source.lines[line_number - 1].blank? if (current_line_indent < original_line_indent && !blank_line) || (relevant_line_indent_at_level && blank_line) break end result << line_number if assignment_lines.include?(line_number) && current_line_indent == original_line_indent unless blank_line relevant_line_indent_at_level = current_line_indent == original_line_indent end end result end # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity # rubocop:enable Metrics/PerceivedComplexity, Metrics/MethodLength def remove_equals_in_def(asgn_tokens, processed_source) nodes = processed_source.ast.each_node(:optarg, :def) eqls_to_ignore = nodes.with_object([]) do |node, arr| loc = if node.def_type? node.loc.assignment if node.endless? else node.loc.operator end arr << loc.begin_pos if loc end asgn_tokens.reject { |t| eqls_to_ignore.include?(t.begin_pos) } end end # rubocop:enable Metrics/ModuleLength end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/space_after_punctuation.rb
lib/rubocop/cop/mixin/space_after_punctuation.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for cops checking for missing space after # punctuation. module SpaceAfterPunctuation MSG = 'Space missing after %<token>s.' def on_new_investigation each_missing_space(processed_source.tokens) do |token, kind| add_offense(token.pos, message: format(MSG, token: kind)) do |corrector| PunctuationCorrector.add_space(corrector, token) end end end private def each_missing_space(tokens) tokens.each_cons(2) do |token1, token2| kind = kind(token1, token2) next unless kind next unless space_missing?(token1, token2) next unless space_required_before?(token2) yield token1, kind end end def space_missing?(token1, token2) same_line?(token1, token2) && token2.column == token1.column + offset end def space_required_before?(token) !(allowed_type?(token) || (token.right_curly_brace? && space_forbidden_before_rcurly?)) end def allowed_type?(token) %i[tRPAREN tRBRACK tPIPE tSTRING_DEND].include?(token.type) end def space_forbidden_before_rcurly? style = space_style_before_rcurly style == 'no_space' end # The normal offset, i.e., the distance from the punctuation # token where a space should be, is 1. def offset 1 end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/documentation_comment.rb
lib/rubocop/cop/mixin/documentation_comment.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for checking documentation. module DocumentationComment extend NodePattern::Macros private def documentation_comment?(node) preceding_lines = preceding_lines(node) return false unless preceding_comment?(node, preceding_lines.last) preceding_lines.any? do |comment| !AnnotationComment.new(comment, annotation_keywords).annotation? && !interpreter_directive_comment?(comment) && !rubocop_directive_comment?(comment) end end # The args node1 & node2 may represent a RuboCop::AST::Node # or a Parser::Source::Comment. Both respond to #loc. def preceding_comment?(node1, node2) node1 && node2 && precede?(node2, node1) && comment_line?(node2.source) end # The args node1 & node2 may represent a RuboCop::AST::Node # or a Parser::Source::Comment. Both respond to #loc. def precede?(node1, node2) node2.loc.line - node1.loc.line == 1 end def preceding_lines(node) processed_source.ast_with_comments[node].select { |line| line.loc.line < node.loc.line } end def interpreter_directive_comment?(comment) /^#\s*(frozen_string_literal|encoding):/.match?(comment.text) end def rubocop_directive_comment?(comment) !!DirectiveComment.new(comment).match_captures end def annotation_keywords config.for_cop('Style/CommentAnnotation')['Keywords'] end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/hash_transform_method.rb
lib/rubocop/cop/mixin/hash_transform_method.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for Style/HashTransformKeys and # Style/HashTransformValues module HashTransformMethod extend NodePattern::Macros RESTRICT_ON_SEND = %i[[] to_h].freeze # Internal helper class to hold match data Captures = Struct.new(:transformed_argname, :transforming_body_expr, :unchanged_body_expr) do def noop_transformation? transforming_body_expr.lvar_type? && transforming_body_expr.children == [transformed_argname] end def transformation_uses_both_args? transforming_body_expr.descendants.include?(unchanged_body_expr) end def use_transformed_argname? transforming_body_expr.each_descendant(:lvar).any? do |node| node.source == transformed_argname.to_s end end end # Internal helper class to hold autocorrect data Autocorrection = Struct.new(:match, :block_node, :leading, :trailing) do def self.from_each_with_object(node, match) new(match, node, 0, 0) end def self.from_hash_brackets_map(node, match) new(match, node.children.last, 'Hash['.length, ']'.length) end def self.from_map_to_h(node, match) if node.parent&.block_type? && node.parent.send_node == node strip_trailing_chars = 0 else map_range = node.children.first.source_range node_range = node.source_range strip_trailing_chars = node_range.end_pos - map_range.end_pos end new(match, node.children.first, 0, strip_trailing_chars) end def self.from_to_h(node, match) new(match, node, 0, 0) end def strip_prefix_and_suffix(node, corrector) expression = node.source_range corrector.remove_leading(expression, leading) corrector.remove_trailing(expression, trailing) end def set_new_method_name(new_method_name, corrector) range = block_node.send_node.loc.selector if (send_end = block_node.send_node.loc.end) # If there are arguments (only true in the `each_with_object` # case) range = range.begin.join(send_end) end corrector.replace(range, new_method_name) end def set_new_arg_name(transformed_argname, corrector) corrector.replace(block_node.arguments, "|#{transformed_argname}|") end def set_new_body_expression(transforming_body_expr, corrector) body_source = transforming_body_expr.source if transforming_body_expr.hash_type? && !transforming_body_expr.braces? body_source = "{ #{body_source} }" end corrector.replace(block_node.body, body_source) end end # @!method array_receiver?(node) def_node_matcher :array_receiver?, <<~PATTERN {(array ...) (send _ :each_with_index) (send _ :with_index _ ?) (send _ :zip ...)} PATTERN def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler on_bad_each_with_object(node) do |*match| handle_possible_offense(node, match, 'each_with_object') end return if target_ruby_version < 2.6 on_bad_to_h(node) { |*match| handle_possible_offense(node, match, 'to_h {...}') } end def on_send(node) on_bad_hash_brackets_map(node) do |*match| handle_possible_offense(node, match, 'Hash[_.map {...}]') end on_bad_map_to_h(node) { |*match| handle_possible_offense(node, match, 'map {...}.to_h') } end def on_csend(node) on_bad_map_to_h(node) { |*match| handle_possible_offense(node, match, 'map {...}.to_h') } end private # @abstract Implemented with `def_node_matcher` def on_bad_each_with_object(_node) raise NotImplementedError end # @abstract Implemented with `def_node_matcher` def on_bad_hash_brackets_map(_node) raise NotImplementedError end # @abstract Implemented with `def_node_matcher` def on_bad_map_to_h(_node) raise NotImplementedError end # @abstract Implemented with `def_node_matcher` def on_bad_to_h(_node) raise NotImplementedError end def handle_possible_offense(node, match, match_desc) captures = extract_captures(match) # If key didn't actually change either, this is most likely a false # positive (receiver isn't a hash). return if captures.noop_transformation? # Can't `transform_keys` if key transformation uses value, or # `transform_values` if value transformation uses key. return if captures.transformation_uses_both_args? return unless captures.use_transformed_argname? message = "Prefer `#{new_method_name}` over `#{match_desc}`." add_offense(node, message: message) do |corrector| correction = prepare_correction(node) execute_correction(corrector, node, correction) end end # @abstract # # @return [Captures] def extract_captures(_match) raise NotImplementedError end # @abstract # # @return [String] def new_method_name raise NotImplementedError end def prepare_correction(node) if (match = on_bad_each_with_object(node)) Autocorrection.from_each_with_object(node, match) elsif (match = on_bad_hash_brackets_map(node)) Autocorrection.from_hash_brackets_map(node, match) elsif (match = on_bad_map_to_h(node)) Autocorrection.from_map_to_h(node, match) elsif (match = on_bad_to_h(node)) Autocorrection.from_to_h(node, match) else raise 'unreachable' end end def execute_correction(corrector, node, correction) correction.strip_prefix_and_suffix(node, corrector) correction.set_new_method_name(new_method_name, corrector) captures = extract_captures(correction.match) correction.set_new_arg_name(captures.transformed_argname, corrector) correction.set_new_body_expression(captures.transforming_body_expr, corrector) end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/configurable_max.rb
lib/rubocop/cop/mixin/configurable_max.rb
# frozen_string_literal: true module RuboCop module Cop # Handles `Max` configuration parameters, especially setting them to an # appropriate value with --auto-gen-config. # @deprecated Use `exclude_limit <ParameterName>` instead. module ConfigurableMax private def max=(value) warn Rainbow(<<~WARNING).yellow, uplevel: 1 `max=` is deprecated. Use `exclude_limit <ParameterName>` instead. WARNING cfg = config_to_allow_offenses cfg[:exclude_limit] ||= {} current_max = cfg[:exclude_limit][max_parameter_name] value = [current_max, value].max if current_max cfg[:exclude_limit][max_parameter_name] = value end def max_parameter_name 'Max' end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/auto_corrector.rb
lib/rubocop/cop/mixin/auto_corrector.rb
# frozen_string_literal: true module RuboCop module Cop # extend this module to signal autocorrection support module AutoCorrector def support_autocorrect? true end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/annotation_comment.rb
lib/rubocop/cop/mixin/annotation_comment.rb
# frozen_string_literal: true module RuboCop module Cop # Representation of an annotation comment in source code (eg. `# TODO: blah blah blah`). class AnnotationComment attr_reader :comment, :margin, :keyword, :colon, :space, :note # @param [Parser::Source::Comment] comment # @param [Array<String>] keywords def initialize(comment, keywords) @comment = comment @keywords = keywords @margin, @keyword, @colon, @space, @note = split_comment(comment) end def annotation? keyword_appearance? && !just_keyword_of_sentence? end def correct?(colon:) return false unless keyword && space && note return false unless keyword == keyword.upcase self.colon.nil? == !colon end # Returns the range bounds for just the annotation def bounds start = comment.source_range.begin_pos + margin.length length = [keyword, colon, space].reduce(0) { |len, elem| len + elem.to_s.length } [start, start + length] end private attr_reader :keywords def split_comment(comment) # Sort keywords by reverse length so that if a keyword is in a phrase # but also on its own, both will match properly. match = comment.text.match(regex) return false unless match match.captures end KEYWORDS_REGEX_CACHE = {} # rubocop:disable Style/MutableConstant private_constant :KEYWORDS_REGEX_CACHE def regex KEYWORDS_REGEX_CACHE[keywords] ||= begin keywords_regex = Regexp.new( Regexp.union(keywords.sort_by { |w| -w.length }).source, Regexp::IGNORECASE ) /^(# ?)(\b#{keywords_regex}\b)(\s*:)?(\s+)?(\S+)?/i end end def keyword_appearance? keyword && (colon || space) end def just_keyword_of_sentence? keyword == keyword.capitalize && !colon && space && note end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/mixin/multiline_element_line_breaks.rb
lib/rubocop/cop/mixin/multiline_element_line_breaks.rb
# frozen_string_literal: true module RuboCop module Cop # Common functionality for checking for a line break before each # element in a multi-line collection. module MultilineElementLineBreaks private def check_line_breaks(_node, children, ignore_last: false) return if all_on_same_line?(children, ignore_last: ignore_last) last_seen_line = -1 children.each do |child| if last_seen_line >= child.first_line add_offense(child) { |corrector| EmptyLineCorrector.insert_before(corrector, child) } else last_seen_line = child.last_line end end end def all_on_same_line?(nodes, ignore_last: false) return true if nodes.empty? return same_line?(nodes.first, nodes.last) if ignore_last nodes.first.first_line == nodes.last.last_line end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/gemspec/require_mfa.rb
lib/rubocop/cop/gemspec/require_mfa.rb
# frozen_string_literal: true module RuboCop module Cop module Gemspec # Requires a gemspec to have `rubygems_mfa_required` metadata set. # # This setting tells RubyGems that MFA (Multi-Factor Authentication) is # required for accounts to be able perform privileged operations, such as # (see RubyGems' documentation for the full list of privileged # operations): # # * `gem push` # * `gem yank` # * `gem owner --add/remove` # * adding or removing owners using gem ownership page # # This helps make your gem more secure, as users can be more # confident that gem updates were pushed by maintainers. # # @example # # bad # Gem::Specification.new do |spec| # # no `rubygems_mfa_required` metadata specified # end # # # good # Gem::Specification.new do |spec| # spec.metadata = { # 'rubygems_mfa_required' => 'true' # } # end # # # good # Gem::Specification.new do |spec| # spec.metadata['rubygems_mfa_required'] = 'true' # end # # # bad # Gem::Specification.new do |spec| # spec.metadata = { # 'rubygems_mfa_required' => 'false' # } # end # # # good # Gem::Specification.new do |spec| # spec.metadata = { # 'rubygems_mfa_required' => 'true' # } # end # # # bad # Gem::Specification.new do |spec| # spec.metadata['rubygems_mfa_required'] = 'false' # end # # # good # Gem::Specification.new do |spec| # spec.metadata['rubygems_mfa_required'] = 'true' # end # class RequireMFA < Base include GemspecHelp extend AutoCorrector MSG = "`metadata['rubygems_mfa_required']` must be set to `'true'`." # @!method metadata(node) def_node_matcher :metadata, <<~PATTERN `{ (send _ :metadata= $_) (send (send _ :metadata) :[]= (str "rubygems_mfa_required") $_) } PATTERN # @!method metadata_assignment(node) def_node_search :metadata_assignment, <<~PATTERN `{ (send _ :metadata= _) (send (send _ :metadata) :[]= (str _) _) } PATTERN # @!method rubygems_mfa_required(node) def_node_search :rubygems_mfa_required, <<~PATTERN (pair (str "rubygems_mfa_required") $_) PATTERN # @!method true_string?(node) def_node_matcher :true_string?, <<~PATTERN (str "true") PATTERN def on_block(node) # rubocop:disable Metrics/MethodLength, InternalAffairs/NumblockHandler gem_specification(node) do |block_var| metadata_value = metadata(node) mfa_value = mfa_value(metadata_value) if mfa_value unless true_string?(mfa_value) add_offense(mfa_value) do |corrector| change_value(corrector, mfa_value) end end else add_offense(node) do |corrector| autocorrect(corrector, node, block_var, metadata_value) end end end end private def mfa_value(metadata_value) return unless metadata_value return metadata_value if metadata_value.str_type? rubygems_mfa_required(metadata_value).first end def autocorrect(corrector, node, block_var, metadata) if metadata return unless metadata.hash_type? correct_metadata(corrector, metadata) else insert_mfa_required(corrector, node, block_var) end end def correct_metadata(corrector, metadata) if metadata.pairs.any? corrector.insert_after(metadata.pairs.last, ",\n'rubygems_mfa_required' => 'true'") else corrector.insert_before(metadata.loc.end, "'rubygems_mfa_required' => 'true'") end end def insert_mfa_required(corrector, node, block_var) require_mfa_directive = <<~RUBY.strip #{block_var}.metadata['rubygems_mfa_required'] = 'true' RUBY if (last_assignment = metadata_assignment(processed_source.ast).to_a.last) corrector.insert_after(last_assignment, "\n#{require_mfa_directive}") else corrector.insert_before(node.loc.end, "#{require_mfa_directive}\n") end end def change_value(corrector, value) corrector.replace(value, "'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/gemspec/add_runtime_dependency.rb
lib/rubocop/cop/gemspec/add_runtime_dependency.rb
# frozen_string_literal: true module RuboCop module Cop module Gemspec # Prefer `add_dependency` over `add_runtime_dependency` as the latter is # considered soft-deprecated. # # @example # # # bad # Gem::Specification.new do |spec| # spec.add_runtime_dependency('rubocop') # end # # # good # Gem::Specification.new do |spec| # spec.add_dependency('rubocop') # end # class AddRuntimeDependency < Base extend AutoCorrector MSG = 'Use `add_dependency` instead of `add_runtime_dependency`.' RESTRICT_ON_SEND = %i[add_runtime_dependency].freeze def on_send(node) return if !node.receiver || node.arguments.empty? add_offense(node.loc.selector) do |corrector| corrector.replace(node.loc.selector, 'add_dependency') 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/gemspec/ordered_dependencies.rb
lib/rubocop/cop/gemspec/ordered_dependencies.rb
# frozen_string_literal: true module RuboCop module Cop module Gemspec # Dependencies in the gemspec should be alphabetically sorted. # # @example # # bad # spec.add_dependency 'rubocop' # spec.add_dependency 'rspec' # # # good # spec.add_dependency 'rspec' # spec.add_dependency 'rubocop' # # # good # spec.add_dependency 'rubocop' # # spec.add_dependency 'rspec' # # # bad # spec.add_development_dependency 'rubocop' # spec.add_development_dependency 'rspec' # # # good # spec.add_development_dependency 'rspec' # spec.add_development_dependency 'rubocop' # # # good # spec.add_development_dependency 'rubocop' # # spec.add_development_dependency 'rspec' # # # bad # spec.add_runtime_dependency 'rubocop' # spec.add_runtime_dependency 'rspec' # # # good # spec.add_runtime_dependency 'rspec' # spec.add_runtime_dependency 'rubocop' # # # good # spec.add_runtime_dependency 'rubocop' # # spec.add_runtime_dependency 'rspec' # # @example TreatCommentsAsGroupSeparators: true (default) # # good # # For code quality # spec.add_dependency 'rubocop' # # For tests # spec.add_dependency 'rspec' # # @example TreatCommentsAsGroupSeparators: false # # bad # # For code quality # spec.add_dependency 'rubocop' # # For tests # spec.add_dependency 'rspec' class OrderedDependencies < Base extend AutoCorrector include OrderedGemNode MSG = 'Dependencies should be sorted in an alphabetical order within ' \ 'their section of the gemspec. ' \ 'Dependency `%<previous>s` should appear before `%<current>s`.' def on_new_investigation return if processed_source.blank? dependency_declarations(processed_source.ast).each_cons(2) do |previous, current| next unless consecutive_lines?(previous, current) next unless case_insensitive_out_of_order?(gem_name(current), gem_name(previous)) next unless get_dependency_name(previous) == get_dependency_name(current) register_offense(previous, current) end end private def previous_declaration(node) declarations = dependency_declarations(processed_source.ast) node_index = declarations.find_index(node) declarations.to_a[node_index - 1] end def get_dependency_name(node) node.method_name end # @!method dependency_declarations(node) def_node_search :dependency_declarations, <<~PATTERN (send (lvar _) {:add_dependency :add_runtime_dependency :add_development_dependency} (str _) ...) 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/gemspec/ruby_version_globals_usage.rb
lib/rubocop/cop/gemspec/ruby_version_globals_usage.rb
# frozen_string_literal: true module RuboCop module Cop module Gemspec # Checks that `RUBY_VERSION` and `Ruby::VERSION` constants are not used in gemspec. # Using `RUBY_VERSION` and `Ruby::VERSION` are dangerous because value of the # constant is determined by `rake release`. # It's possible to have dependency based on ruby version used # to execute `rake release` and not user's ruby version. # # @example # # # bad # Gem::Specification.new do |spec| # if RUBY_VERSION >= '3.0' # spec.add_dependency 'gem_a' # else # spec.add_dependency 'gem_b' # end # end # # # good # Gem::Specification.new do |spec| # spec.add_dependency 'gem_a' # end # class RubyVersionGlobalsUsage < Base include GemspecHelp MSG = 'Do not use `%<ruby_version>s` in gemspec file.' # @!method ruby_version?(node) def_node_matcher :ruby_version?, <<~PATTERN { (const {cbase nil?} :RUBY_VERSION) (const (const {cbase nil?} :Ruby) :VERSION) } PATTERN def on_const(node) return unless gem_spec_with_ruby_version?(node) add_offense(node, message: format(MSG, ruby_version: node.source)) end private def gem_spec_with_ruby_version?(node) gem_specification(processed_source.ast) && ruby_version?(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/gemspec/deprecated_attribute_assignment.rb
lib/rubocop/cop/gemspec/deprecated_attribute_assignment.rb
# frozen_string_literal: true module RuboCop module Cop module Gemspec # Checks that deprecated attributes are not set in a gemspec file. # Removing deprecated attributes allows the user to receive smaller packed gems. # # @example # # # bad # Gem::Specification.new do |spec| # spec.name = 'your_cool_gem_name' # spec.test_files = Dir.glob('test/**/*') # end # # # bad # Gem::Specification.new do |spec| # spec.name = 'your_cool_gem_name' # spec.test_files += Dir.glob('test/**/*') # end # # # good # Gem::Specification.new do |spec| # spec.name = 'your_cool_gem_name' # end # class DeprecatedAttributeAssignment < Base include RangeHelp extend AutoCorrector MSG = 'Do not set `%<attribute>s` in gemspec.' # @!method gem_specification(node) def_node_matcher :gem_specification, <<~PATTERN (block (send (const (const {cbase nil?} :Gem) :Specification) :new) ...) PATTERN def on_block(block_node) return unless gem_specification(block_node) block_parameter = block_node.first_argument.source assignment = block_node.descendants.detect do |node| use_deprecated_attributes?(node, block_parameter) end return unless assignment message = format_message_from add_offense(assignment, message: message) do |corrector| range = range_by_whole_lines(assignment.source_range, include_final_newline: true) corrector.remove(range) end end private def node_and_method_name(node, attribute) if node.op_asgn_type? [node.lhs, attribute] else [node, :"#{attribute}="] end end def use_deprecated_attributes?(node, block_parameter) %i[test_files date specification_version rubygems_version].each do |attribute| node, method_name = node_and_method_name(node, attribute) unless node.send_type? && node.receiver&.source == block_parameter && node.method?(method_name) next end @attribute = attribute.to_s return true end false end def format_message_from format(MSG, attribute: @attribute) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/gemspec/development_dependencies.rb
lib/rubocop/cop/gemspec/development_dependencies.rb
# frozen_string_literal: true module RuboCop module Cop module Gemspec # Enforce that development dependencies for a gem are specified in # `Gemfile`, rather than in the `gemspec` using # `add_development_dependency`. Alternatively, using `EnforcedStyle: # gemspec`, enforce that all dependencies are specified in `gemspec`, # rather than in `Gemfile`. # # @example EnforcedStyle: Gemfile (default) # # Specify runtime dependencies in your gemspec, # # but all other dependencies in your Gemfile. # # # bad # # example.gemspec # s.add_development_dependency "foo" # # # good # # Gemfile # gem "foo" # # # good # # gems.rb # gem "foo" # # # good (with AllowedGems: ["bar"]) # # example.gemspec # s.add_development_dependency "bar" # # @example EnforcedStyle: gems.rb # # Specify runtime dependencies in your gemspec, # # but all other dependencies in your Gemfile. # # # # Identical to `EnforcedStyle: Gemfile`, but with a different error message. # # Rely on Bundler/GemFilename to enforce the use of `Gemfile` vs `gems.rb`. # # # bad # # example.gemspec # s.add_development_dependency "foo" # # # good # # Gemfile # gem "foo" # # # good # # gems.rb # gem "foo" # # # good (with AllowedGems: ["bar"]) # # example.gemspec # s.add_development_dependency "bar" # # @example EnforcedStyle: gemspec # # Specify all dependencies in your gemspec. # # # bad # # Gemfile # gem "foo" # # # good # # example.gemspec # s.add_development_dependency "foo" # # # good (with AllowedGems: ["bar"]) # # Gemfile # gem "bar" # class DevelopmentDependencies < Base include ConfigurableEnforcedStyle MSG = 'Specify development dependencies in %<preferred>s.' RESTRICT_ON_SEND = %i[add_development_dependency gem].freeze # @!method add_development_dependency?(node) def_node_matcher :add_development_dependency?, <<~PATTERN (send _ :add_development_dependency (str #forbidden_gem? ...) _? _?) PATTERN # @!method gem?(node) def_node_matcher :gem?, <<~PATTERN (send _ :gem (str #forbidden_gem? ...)) PATTERN def on_send(node) case style when :Gemfile, :'gems.rb' add_offense(node) if add_development_dependency?(node) when :gemspec add_offense(node) if gem?(node) end end private def forbidden_gem?(gem_name) !cop_config['AllowedGems'].include?(gem_name) end def message(_range) format(MSG, preferred: 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/gemspec/required_ruby_version.rb
lib/rubocop/cop/gemspec/required_ruby_version.rb
# frozen_string_literal: true module RuboCop module Cop module Gemspec # Checks that `required_ruby_version` in a gemspec file is set to a valid # value (non-blank) and matches `TargetRubyVersion` as set in RuboCop's # configuration for the gem. # # This ensures that RuboCop is using the same Ruby version as the gem. # # @example # # When `TargetRubyVersion` of .rubocop.yml is `2.5`. # # # bad # Gem::Specification.new do |spec| # # no `required_ruby_version` specified # end # # # bad # Gem::Specification.new do |spec| # spec.required_ruby_version = '>= 2.4.0' # end # # # bad # Gem::Specification.new do |spec| # spec.required_ruby_version = '>= 2.6.0' # end # # # bad # Gem::Specification.new do |spec| # spec.required_ruby_version = '' # end # # # good # Gem::Specification.new do |spec| # spec.required_ruby_version = '>= 2.5.0' # end # # # good # Gem::Specification.new do |spec| # spec.required_ruby_version = '>= 2.5' # end # # # accepted but not recommended # Gem::Specification.new do |spec| # spec.required_ruby_version = ['>= 2.5.0', '< 2.7.0'] # end # # # accepted but not recommended, since # # Ruby does not really follow semantic versioning # Gem::Specification.new do |spec| # spec.required_ruby_version = '~> 2.5' # end class RequiredRubyVersion < Base RESTRICT_ON_SEND = %i[required_ruby_version=].freeze NOT_EQUAL_MSG = '`required_ruby_version` and `TargetRubyVersion` ' \ '(%<target_ruby_version>s, which may be specified in ' \ '.rubocop.yml) should be equal.' MISSING_MSG = '`required_ruby_version` should be specified.' # @!method required_ruby_version?(node) def_node_search :required_ruby_version?, <<~PATTERN (send _ :required_ruby_version= _) PATTERN # @!method defined_ruby_version(node) def_node_matcher :defined_ruby_version, <<~PATTERN { $(str _) $(array (str _) (str _)) (send (const (const nil? :Gem) :Requirement) :new $str+) } PATTERN def on_new_investigation return if processed_source.ast && required_ruby_version?(processed_source.ast) add_global_offense(MISSING_MSG) end def on_send(node) version_def = node.first_argument return if dynamic_version?(version_def) ruby_version = extract_ruby_version(defined_ruby_version(version_def)) return if ruby_version == target_ruby_version.to_s add_offense(version_def, message: not_equal_message(ruby_version, target_ruby_version)) end private def dynamic_version?(node) (node.send_type? && !node.receiver) || node.variable? || node.each_descendant(:send, *RuboCop::AST::Node::VARIABLES).any? end def extract_ruby_version(required_ruby_version) return unless required_ruby_version if required_ruby_version.is_a?(Array) required_ruby_version = required_ruby_version.detect do |v| /[>=]/.match?(v.str_content) end elsif required_ruby_version.array_type? required_ruby_version = required_ruby_version.children.detect do |v| /[>=]/.match?(v.str_content) end end return unless required_ruby_version required_ruby_version.str_content.scan(/\d/).first(2).join('.') end def not_equal_message(required_ruby_version, target_ruby_version) format( NOT_EQUAL_MSG, required_ruby_version: required_ruby_version, gemspec_filename: File.basename(processed_source.file_path), target_ruby_version: target_ruby_version ) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false
rubocop/rubocop
https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/gemspec/dependency_version.rb
lib/rubocop/cop/gemspec/dependency_version.rb
# frozen_string_literal: true module RuboCop module Cop module Gemspec # Enforce that gem dependency version specifications or a commit reference (branch, # ref, or tag) are either required or forbidden. # # @example EnforcedStyle: required (default) # # # bad # Gem::Specification.new do |spec| # spec.add_dependency 'parser' # end # # # bad # Gem::Specification.new do |spec| # spec.add_development_dependency 'parser' # end # # # good # Gem::Specification.new do |spec| # spec.add_dependency 'parser', '>= 2.3.3.1', '< 3.0' # end # # # good # Gem::Specification.new do |spec| # spec.add_development_dependency 'parser', '>= 2.3.3.1', '< 3.0' # end # # @example EnforcedStyle: forbidden # # # bad # Gem::Specification.new do |spec| # spec.add_dependency 'parser', '>= 2.3.3.1', '< 3.0' # end # # # bad # Gem::Specification.new do |spec| # spec.add_development_dependency 'parser', '>= 2.3.3.1', '< 3.0' # end # # # good # Gem::Specification.new do |spec| # spec.add_dependency 'parser' # end # # # good # Gem::Specification.new do |spec| # spec.add_development_dependency 'parser' # end # class DependencyVersion < Base include ConfigurableEnforcedStyle include GemspecHelp REQUIRED_MSG = 'Dependency version specification is required.' FORBIDDEN_MSG = 'Dependency version specification is forbidden.' VERSION_SPECIFICATION_REGEX = /^\s*[~<>=]*\s*[0-9.]+/.freeze ADD_DEPENDENCY_METHODS = %i[ add_dependency add_runtime_dependency add_development_dependency ].freeze RESTRICT_ON_SEND = ADD_DEPENDENCY_METHODS # @!method add_dependency_method_declaration?(node) def_node_matcher :add_dependency_method_declaration?, <<~PATTERN (send (lvar #match_block_variable_name?) #add_dependency_method? ...) PATTERN # @!method includes_version_specification?(node) def_node_matcher :includes_version_specification?, <<~PATTERN (send _ #add_dependency_method? <(str #version_specification?) ...>) PATTERN # @!method includes_commit_reference?(node) def_node_matcher :includes_commit_reference?, <<~PATTERN (send _ #add_dependency_method? <(hash <(pair (sym {:branch :ref :tag}) (str _)) ...>) ...>) PATTERN def on_send(node) return unless add_dependency_method_declaration?(node) return if allowed_gem?(node) if offense?(node) add_offense(node) opposite_style_detected else correct_style_detected end end private def allowed_gem?(node) allowed_gems.include?(node.first_argument.str_content) end def allowed_gems Array(cop_config['AllowedGems']) end def message(_range) if required_style? REQUIRED_MSG elsif forbidden_style? FORBIDDEN_MSG end end def match_block_variable_name?(receiver_name) gem_specification(processed_source.ast) do |block_variable_name| return block_variable_name == receiver_name end end def add_dependency_method?(method_name) ADD_DEPENDENCY_METHODS.include?(method_name) end def offense?(node) required_offense?(node) || forbidden_offense?(node) end def required_offense?(node) return false unless required_style? !includes_version_specification?(node) && !includes_commit_reference?(node) end def forbidden_offense?(node) return false unless forbidden_style? includes_version_specification?(node) || includes_commit_reference?(node) end def forbidden_style? style == :forbidden end def required_style? style == :required end def version_specification?(expression) expression.match?(VERSION_SPECIFICATION_REGEX) end end end end end
ruby
MIT
99fa0fdd0481910d7d052f4c2ed01ad36178f404
2026-01-04T15:37:41.211519Z
false