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/correctors/parentheses_corrector.rb | lib/rubocop/cop/correctors/parentheses_corrector.rb | # frozen_string_literal: true
module RuboCop
module Cop
# This autocorrects parentheses
class ParenthesesCorrector
class << self
include RangeHelp
COMMA_REGEXP = /(?<=\))\s*,/.freeze
def correct(corrector, node)
buffer = node.source_range.source_buffer
corrector.remove(range_with_surrounding_space(range: node.loc.begin, buffer: buffer,
side: :right, whitespace: true))
corrector.remove(range_with_surrounding_space(range: node.loc.end, buffer: buffer,
side: :left))
handle_orphaned_comma(corrector, node)
return unless ternary_condition?(node) && next_char_is_question_mark?(node)
corrector.insert_after(node.loc.end, ' ')
end
private
def ternary_condition?(node)
node.parent&.if_type? && node.parent.ternary?
end
def next_char_is_question_mark?(node)
node.loc.last_column == node.parent.loc.question.column
end
def only_closing_paren_before_comma?(node)
source_buffer = node.source_range.source_buffer
line_range = source_buffer.line_range(node.loc.end.line)
line_range.source.start_with?(/\s*\)\s*,/)
end
# If removing parentheses leaves a comma on its own line, remove all the whitespace
# preceding it to prevent a syntax error.
def handle_orphaned_comma(corrector, node)
return unless only_closing_paren_before_comma?(node)
range = extend_range_for_heredoc(node, parens_range(node))
corrector.remove(range)
add_heredoc_comma(corrector, node)
end
# Get a range for the closing parenthesis and all whitespace to the left of it
def parens_range(node)
range_with_surrounding_space(
range: node.loc.end,
buffer: node.source_range.source_buffer,
side: :left,
newlines: true,
whitespace: true,
continuations: true
)
end
# If the node contains a heredoc, remove the comma too
# It'll be added back in the right place later
def extend_range_for_heredoc(node, range)
return range unless heredoc?(node)
comma_line = range_by_whole_lines(node.loc.end, buffer: node.source_range.source_buffer)
offset = comma_line.source.match(COMMA_REGEXP)[0]&.size || 0
range.adjust(end_pos: offset)
end
# Add a comma back after the heredoc identifier
def add_heredoc_comma(corrector, node)
return unless heredoc?(node)
corrector.insert_after(node.child_nodes.last, ',')
end
def heredoc?(node)
node.child_nodes.last.loc.is_a?(Parser::Source::Map::Heredoc)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/correctors/percent_literal_corrector.rb | lib/rubocop/cop/correctors/percent_literal_corrector.rb | # frozen_string_literal: true
module RuboCop
module Cop
# This autocorrects percent literals
class PercentLiteralCorrector
include Util
attr_reader :config, :preferred_delimiters
def initialize(config, preferred_delimiters)
@config = config
@preferred_delimiters = preferred_delimiters
end
def correct(corrector, node, char)
escape = escape_words?(node)
char = char.upcase if escape
delimiters = delimiters_for("%#{char}")
contents = new_contents(node, escape, delimiters)
wrap_contents(corrector, node, contents, char, delimiters)
end
private
def wrap_contents(corrector, node, contents, char, delimiters)
corrector.replace(node, "%#{char}#{delimiters[0]}#{contents}#{delimiters[1]}")
end
def escape_words?(node)
node.children.any? { |w| needs_escaping?(w.children[0]) }
end
def delimiters_for(type)
PreferredDelimiters.new(type, config, preferred_delimiters).delimiters
end
def new_contents(node, escape, delimiters)
if node.multiline?
autocorrect_multiline_words(node, escape, delimiters)
else
autocorrect_words(node, escape, delimiters)
end
end
def autocorrect_multiline_words(node, escape, delimiters)
contents = process_multiline_words(node, escape, delimiters)
contents << end_content(node.source)
contents.join
end
def autocorrect_words(node, escape, delimiters)
node.children.map do |word_node|
fix_escaped_content(word_node, escape, delimiters)
end.join(' ')
end
def process_multiline_words(node, escape, delimiters)
base_line_num = node.first_line
prev_line_num = base_line_num
node.children.map.with_index do |word_node, index|
line_breaks = line_breaks(word_node, node.source, prev_line_num, base_line_num, index)
prev_line_num = word_node.last_line
content = fix_escaped_content(word_node, escape, delimiters)
line_breaks + content
end
end
def line_breaks(node, source, previous_line_num, base_line_num, node_index)
source_in_lines = source.split("\n")
if first_line?(node, previous_line_num)
node_index.zero? && node.first_line == base_line_num ? '' : ' '
else
process_lines(node, previous_line_num, base_line_num, source_in_lines)
end
end
def first_line?(node, previous_line_num)
node.first_line == previous_line_num
end
def process_lines(node, previous_line_num, base_line_num, source_in_lines)
begin_line_num = previous_line_num - base_line_num + 1
end_line_num = node.first_line - base_line_num + 1
lines = source_in_lines[begin_line_num...end_line_num]
"\n#{lines.join("\n").split(node.source).first || ''}"
end
def fix_escaped_content(word_node, escape, delimiters)
content = +word_node.children.first.to_s
content = escape_string(content) if escape
substitute_escaped_delimiters(content, delimiters)
content
end
def substitute_escaped_delimiters(content, delimiters)
if delimiters.first != delimiters.last
# With different delimiters (eg. `[]`, `()`), if there are the same
# number of each, escaping is not necessary
delimiter_counts = delimiters.each_with_object({}) do |delimiter, counts|
counts[delimiter] = content.count(delimiter)
end
return content if delimiter_counts[delimiters.first] == delimiter_counts[delimiters.last]
end
delimiters.each { |delim| content.gsub!(delim, "\\#{delim}") }
end
def end_content(source)
result = /\A(\s*)\]/.match(source.split("\n").last)
"\n#{result[1]}" if result
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/correctors/punctuation_corrector.rb | lib/rubocop/cop/correctors/punctuation_corrector.rb | # frozen_string_literal: true
module RuboCop
module Cop
# This autocorrects punctuation
class PunctuationCorrector
class << self
def remove_space(corrector, space_before)
corrector.remove(space_before)
end
def add_space(corrector, token)
corrector.replace(token.pos, "#{token.pos.source} ")
end
def swap_comma(corrector, range)
return unless range
case range.source
when ',' then corrector.remove(range)
else corrector.insert_after(range, ',')
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/correctors/unused_arg_corrector.rb | lib/rubocop/cop/correctors/unused_arg_corrector.rb | # frozen_string_literal: true
module RuboCop
module Cop
# This autocorrects unused arguments.
class UnusedArgCorrector
extend RangeHelp
class << self
attr_reader :processed_source
def correct(corrector, processed_source, node)
return if %i[kwarg kwoptarg].include?(node.type)
@processed_source = processed_source
if node.blockarg_type?
correct_for_blockarg_type(corrector, node)
else
variable_name = if node.optarg_type?
node.node_parts[0]
else
# Extract only a var name without splat (`*`)
node.source.gsub(/\A\*+/, '')
end
corrector.replace(node.loc.name, "_#{variable_name}")
end
end
def correct_for_blockarg_type(corrector, node)
range = range_with_surrounding_space(node.source_range, side: :left)
range = range_with_surrounding_comma(range, :left)
corrector.remove(range)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/correctors/each_to_for_corrector.rb | lib/rubocop/cop/correctors/each_to_for_corrector.rb | # frozen_string_literal: true
module RuboCop
module Cop
# This class autocorrects `#each` enumeration to `for` iteration.
class EachToForCorrector
extend NodePattern::Macros
CORRECTION_WITH_ARGUMENTS = 'for %<variables>s in %<collection>s do'
CORRECTION_WITHOUT_ARGUMENTS = 'for _ in %<enumerable>s do'
def initialize(block_node)
@block_node = block_node
@collection_node = block_node.receiver
@argument_node = block_node.arguments
end
def call(corrector)
corrector.replace(offending_range, correction)
end
private
attr_reader :block_node, :collection_node, :argument_node
def correction
if block_node.arguments?
format(CORRECTION_WITH_ARGUMENTS,
collection: collection_node.source,
variables: argument_node.children.first.source)
else
format(CORRECTION_WITHOUT_ARGUMENTS, enumerable: collection_node.source)
end
end
def offending_range
begin_range = block_node.source_range.begin
if block_node.arguments?
begin_range.join(argument_node.source_range.end)
else
begin_range.join(block_node.loc.begin.end)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/correctors/string_literal_corrector.rb | lib/rubocop/cop/correctors/string_literal_corrector.rb | # frozen_string_literal: true
module RuboCop
module Cop
# This autocorrects string literals
class StringLiteralCorrector
extend Util
class << self
def correct(corrector, node, style)
return if node.dstr_type?
str = node.str_content
if style == :single_quotes
corrector.replace(node, to_string_literal(str))
else
corrector.replace(node, str.inspect)
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/correctors/for_to_each_corrector.rb | lib/rubocop/cop/correctors/for_to_each_corrector.rb | # frozen_string_literal: true
module RuboCop
module Cop
# This class autocorrects `for` iteration to `#each` enumeration.
class ForToEachCorrector
extend NodePattern::Macros
CORRECTION = '%<collection>s%<dot>seach do |%<argument>s|'
def initialize(for_node)
@for_node = for_node
@variable_node = for_node.variable
@collection_node = for_node.collection
end
def call(corrector)
offending_range = for_node.source_range.begin.join(end_range)
corrector.replace(offending_range, correction)
end
private
attr_reader :for_node, :variable_node, :collection_node
def correction
format(
CORRECTION,
collection: collection_source,
dot: collection_node.csend_type? ? '&.' : '.',
argument: variable_node.source
)
end
def collection_source
if requires_parentheses?
"(#{collection_node.source})"
else
collection_node.source
end
end
def requires_parentheses?
return true if collection_node.send_type? && collection_node.operator_method?
collection_node.range_type? || collection_node.operator_keyword?
end
def end_range
if for_node.do?
keyword_begin.end
else
collection_end.end
end
end
def keyword_begin
for_node.loc.begin
end
def collection_end
if collection_node.begin_type?
collection_node.loc.end
else
collection_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/correctors/line_break_corrector.rb | lib/rubocop/cop/correctors/line_break_corrector.rb | # frozen_string_literal: true
module RuboCop
module Cop
# This class handles autocorrection for code that needs to be moved
# to new lines.
class LineBreakCorrector
extend Alignment
extend TrailingBody
extend Util
class << self
attr_reader :processed_source
def correct_trailing_body(configured_width:, corrector:, node:,
processed_source:)
@processed_source = processed_source
range = first_part_of(node.to_a.last)
eol_comment = processed_source.comment_at_line(node.source_range.line)
break_line_before(range: range, node: node, corrector: corrector,
configured_width: configured_width)
move_comment(eol_comment: eol_comment, node: node, corrector: corrector)
remove_semicolon(node, corrector)
end
def break_line_before(range:, node:, corrector:, configured_width:,
indent_steps: 1)
corrector.insert_before(
range,
"\n#{' ' * (node.loc.keyword.column + (indent_steps * configured_width))}"
)
end
def move_comment(eol_comment:, node:, corrector:)
return unless eol_comment
text = eol_comment.source
corrector.insert_before(node, "#{text}\n#{' ' * node.loc.keyword.column}")
corrector.remove(eol_comment)
end
private
def remove_semicolon(node, corrector)
return unless semicolon(node)
corrector.remove(semicolon(node).pos)
end
def semicolon(node)
@semicolon ||= {}.compare_by_identity
@semicolon[node] ||= processed_source.sorted_tokens.select(&:semicolon?).find do |token|
next if token.pos.end_pos <= node.source_range.begin_pos
same_line?(token, node.body) && trailing_class_definition?(token, node.body)
end
end
def trailing_class_definition?(token, body)
token.column < body.loc.column
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/correctors/if_then_corrector.rb | lib/rubocop/cop/correctors/if_then_corrector.rb | # frozen_string_literal: true
module RuboCop
module Cop
# This class autocorrects `if...then` structures to a multiline `if` statement
class IfThenCorrector
DEFAULT_INDENTATION_WIDTH = 2
def initialize(if_node, indentation: nil)
@if_node = if_node
@indentation = indentation || DEFAULT_INDENTATION_WIDTH
end
def call(corrector)
corrector.replace(if_node, replacement)
end
private
attr_reader :if_node, :indentation
def replacement(node = if_node, indentation = nil)
indentation = ' ' * node.source_range.column if indentation.nil?
if_branch_source = node.if_branch&.source || 'nil'
elsif_indentation = indentation if node.respond_to?(:elsif?) && node.elsif?
if_branch = <<~RUBY
#{elsif_indentation}#{node.keyword} #{node.condition.source}
#{indentation}#{branch_body_indentation}#{if_branch_source}
RUBY
else_branch = rewrite_else_branch(node.else_branch, indentation)
if_branch + else_branch
end
def rewrite_else_branch(else_branch, indentation)
if else_branch.nil?
'end'
elsif else_branch.if_type? && else_branch.elsif?
replacement(else_branch, indentation)
else
<<~RUBY.chomp
#{indentation}else
#{indentation}#{branch_body_indentation}#{else_branch.source}
#{indentation}end
RUBY
end
end
def branch_body_indentation
@branch_body_indentation ||= (' ' * indentation).freeze
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/correctors/multiline_literal_brace_corrector.rb | lib/rubocop/cop/correctors/multiline_literal_brace_corrector.rb | # frozen_string_literal: true
module RuboCop
module Cop
# Autocorrection logic for the closing brace of a literal either
# on the same line as the last contained elements, or a new line.
class MultilineLiteralBraceCorrector
include MultilineLiteralBraceLayout
include RangeHelp
def self.correct(corrector, node, processed_source)
new(corrector, node, processed_source).call
end
def initialize(corrector, node, processed_source)
@corrector = corrector
@node = node
@processed_source = processed_source
end
def call
if closing_brace_on_same_line?(node)
correct_same_line_brace(corrector)
else
# When a comment immediately before the closing brace gets in the
# way of an easy correction, the offense is reported but not auto-
# corrected. The user must handle the delicate decision of where to
# put the comment.
return if new_line_needed_before_closing_brace?(node)
end_range = last_element_range_with_trailing_comma(node).end
correct_next_line_brace(corrector, end_range)
correct_heredoc_argument_method_chain(corrector, end_range)
end
end
private
attr_reader :corrector, :node, :processed_source
def correct_same_line_brace(corrector)
corrector.insert_before(node.loc.end, "\n")
end
def correct_next_line_brace(corrector, end_range)
corrector.remove(range_with_surrounding_space(node.loc.end, side: :left))
corrector.insert_before(end_range, content_if_comment_present(corrector, node))
end
def correct_heredoc_argument_method_chain(corrector, end_range)
return unless (parent = node.parent)
return unless use_heredoc_argument_method_chain?(parent)
chained_method = range_between(parent.loc.dot.begin_pos, parent.source_range.end_pos)
corrector.remove(chained_method)
corrector.insert_after(end_range, chained_method.source)
end
def content_if_comment_present(corrector, node)
range = range_with_surrounding_space(
children(node).last.source_range,
side: :right
).end.resize(1)
if range.source == '#'
select_content_to_be_inserted_after_last_element(corrector, node)
else
node.loc.end.source
end
end
def use_heredoc_argument_method_chain?(parent)
return false unless node.respond_to?(:first_argument)
return false unless (first_argument = node.first_argument)
parent.call_type? && first_argument.str_type? && first_argument.heredoc?
end
def select_content_to_be_inserted_after_last_element(corrector, node)
range = range_between(
node.loc.end.begin_pos,
range_by_whole_lines(node.source_range).end.end_pos
)
remove_trailing_content_of_comment(corrector, range)
range.source
end
def remove_trailing_content_of_comment(corrector, range)
corrector.remove(range)
end
def last_element_range_with_trailing_comma(node)
trailing_comma_range = last_element_trailing_comma_range(node)
if trailing_comma_range
children(node).last.source_range.join(trailing_comma_range)
else
children(node).last.source_range
end
end
def last_element_trailing_comma_range(node)
range = range_with_surrounding_space(
children(node).last.source_range,
side: :right
).end.resize(1)
range.source == ',' ? range : nil
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/correctors/lambda_literal_to_method_corrector.rb | lib/rubocop/cop/correctors/lambda_literal_to_method_corrector.rb | # frozen_string_literal: true
module RuboCop
module Cop
# This class autocorrects lambda literal to method notation.
class LambdaLiteralToMethodCorrector
def initialize(block_node)
@block_node = block_node
@method = block_node.send_node
@arguments = block_node.arguments
end
def call(corrector)
# Check for unparenthesized args' preceding and trailing whitespaces.
remove_unparenthesized_whitespace(corrector)
if block_node.block_type?
# Avoid correcting to `lambdado` by inserting whitespace
# if none exists before or after the lambda arguments.
insert_separating_space(corrector)
remove_arguments(corrector)
end
replace_selector(corrector)
replace_delimiters(corrector)
insert_arguments(corrector)
end
private
attr_reader :block_node, :method, :arguments
def remove_unparenthesized_whitespace(corrector)
return if arguments.empty? || arguments.parenthesized_call?
remove_leading_whitespace(corrector)
remove_trailing_whitespace(corrector)
end
def insert_separating_space(corrector)
return unless needs_separating_space?
corrector.insert_before(block_begin, ' ')
end
def replace_selector(corrector)
corrector.replace(method, 'lambda')
end
def remove_arguments(corrector)
return if arguments.empty_and_without_delimiters?
corrector.remove(arguments)
end
def insert_arguments(corrector)
return if arguments.empty?
arg_str = " |#{lambda_arg_string}|"
corrector.insert_after(block_node.loc.begin, arg_str)
end
def remove_leading_whitespace(corrector)
corrector.remove_preceding(
arguments,
arguments.source_range.begin_pos -
block_node.send_node.source_range.end_pos
)
end
def remove_trailing_whitespace(corrector)
size = block_begin.begin_pos - arguments.source_range.end_pos - 1
corrector.remove_preceding(block_begin, size) if size.positive?
end
def replace_delimiters(corrector)
return if block_node.braces? || !arg_to_unparenthesized_call?
corrector.insert_after(block_begin, ' ') unless separating_space?
corrector.replace(block_begin, '{')
corrector.replace(block_end, '}')
end
def lambda_arg_string
arguments.children.map(&:source).join(', ')
end
def needs_separating_space?
(block_begin.begin_pos == arguments_end_pos &&
selector_end.end_pos == arguments_begin_pos) ||
block_begin.begin_pos == selector_end.end_pos
end
def arguments_end_pos
arguments.loc.end&.end_pos
end
def arguments_begin_pos
arguments.loc.begin&.begin_pos
end
def block_end
block_node.loc.end
end
def block_begin
block_node.loc.begin
end
def selector_end
method.loc.selector.end
end
def arg_to_unparenthesized_call?
current_node = block_node
parent = current_node.parent
if parent&.pair_type?
current_node = parent.parent
parent = current_node.parent
end
return false unless parent&.send_type?
return false if parent.parenthesized_call?
current_node.sibling_index > 1
end
def separating_space?
block_begin.source_buffer.source[block_begin.begin_pos + 2].match?(/\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/correctors/require_library_corrector.rb | lib/rubocop/cop/correctors/require_library_corrector.rb | # frozen_string_literal: true
module RuboCop
module Cop
# This class ensures a require statement is present for a standard library
# determined by the variable library_name
class RequireLibraryCorrector
extend RangeHelp
class << self
def correct(corrector, node, library_name)
node = node.parent while node.parent?
node = node.children.first if node.begin_type?
corrector.insert_before(node, require_statement(library_name))
end
def require_statement(library_name)
"require '#{library_name}'\n"
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/correctors/condition_corrector.rb | lib/rubocop/cop/correctors/condition_corrector.rb | # frozen_string_literal: true
module RuboCop
module Cop
# This class does condition autocorrection
class ConditionCorrector
class << self
def correct_negative_condition(corrector, node)
condition = negated_condition(node)
corrector.replace(node.loc.keyword, node.inverse_keyword)
corrector.replace(condition, condition.children.first.source)
end
private
def negated_condition(node)
condition = node.condition
condition = condition.children.first while condition.begin_type?
condition
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/utils/format_string.rb | lib/rubocop/cop/utils/format_string.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Utils
# Parses {Kernel#sprintf} format strings.
class FormatString
# Escaping the `#` in `INTERPOLATION` and `TEMPLATE_NAME` is necessary to
# avoid a bug in Ruby 3.2.0
# See: https://bugs.ruby-lang.org/issues/19379
DIGIT_DOLLAR = /(?<arg_number>\d+)\$/.freeze
INTERPOLATION = /\#\{.*?\}/.freeze
FLAG = /[ #0+-]|#{DIGIT_DOLLAR}/.freeze
NUMBER_ARG = /\*#{DIGIT_DOLLAR}?/.freeze
NUMBER = /\d+|#{NUMBER_ARG}|#{INTERPOLATION}/.freeze
WIDTH = /(?<width>#{NUMBER})/.freeze
PRECISION = /\.(?<precision>#{NUMBER}?)/.freeze
TYPE = /(?<type>[bBdiouxXeEfgGaAcps])/.freeze
NAME = /<(?<name>\w+)>/.freeze
TEMPLATE_NAME = /(?<!\#)\{(?<name>\w+)\}/.freeze
SEQUENCE = /
% (?<type>%)
| % (?<flags>#{FLAG}*)
(?:
(?: #{WIDTH}? #{PRECISION}? #{NAME}?
| #{WIDTH}? #{NAME} #{PRECISION}?
| #{NAME} (?<more_flags>#{FLAG}*) #{WIDTH}? #{PRECISION}?
) #{TYPE}
| #{WIDTH}? #{PRECISION}? #{TEMPLATE_NAME}
)
/x.freeze
# The syntax of a format sequence is as follows.
#
# ```
# %[flags][width][.precision]type
# ```
#
# A format sequence consists of a percent sign, followed by optional
# flags, width, and precision indicators, then terminated with a field
# type character.
#
# For more complex formatting, Ruby supports a reference by name.
#
# @see https://ruby-doc.org/core-2.6.3/Kernel.html#method-i-format
class FormatSequence
attr_reader :begin_pos, :end_pos, :flags, :width, :precision, :name, :type, :arg_number
def initialize(match)
@source = match[0]
@begin_pos = match.begin(0)
@end_pos = match.end(0)
@flags = match[:flags].to_s + match[:more_flags].to_s
@width = match[:width]
@precision = match[:precision]
@name = match[:name]
@type = match[:type]
@arg_number = match[:arg_number]
end
def percent?
type == '%'
end
def annotated?
name && @source.include?('<')
end
def template?
name && @source.include?('{')
end
def variable_width?
!!width&.start_with?('*')
end
def variable_width_argument_number
return unless variable_width?
width == '*' ? 1 : width.match(DIGIT_DOLLAR)['arg_number'].to_i
end
# Number of arguments required for the format sequence
def arity
@source.scan('*').count + 1
end
def max_digit_dollar_num
@source.scan(DIGIT_DOLLAR).map { |(digit_dollar_num)| digit_dollar_num.to_i }.max
end
def style
if annotated?
:annotated
elsif template?
:template
else
:unannotated
end
end
end
def initialize(string)
@source = string
end
def format_sequences
@format_sequences ||= parse
end
def valid?
!mixed_formats?
end
def named_interpolation?
format_sequences.any?(&:name)
end
def max_digit_dollar_num
format_sequences.map(&:max_digit_dollar_num).max
end
private
def parse
matches = []
@source.scan(SEQUENCE) { matches << FormatSequence.new(Regexp.last_match) }
matches
end
def mixed_formats?
formats = format_sequences.reject(&:percent?).map do |seq|
if seq.name
:named
elsif seq.max_digit_dollar_num
:numbered
else
:unnumbered
end
end
formats.uniq.size > 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/end_alignment.rb | lib/rubocop/cop/layout/end_alignment.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks whether the end keywords are aligned properly.
#
# Three modes are supported through the `EnforcedStyleAlignWith`
# configuration parameter:
#
# If it's set to `keyword` (which is the default), the `end`
# shall be aligned with the start of the keyword (if, class, etc.).
#
# If it's set to `variable` the `end` shall be aligned with the
# left-hand-side of the variable assignment, if there is one.
#
# If it's set to `start_of_line`, the `end` shall be aligned with the
# start of the line where the matching keyword appears.
#
# This `Layout/EndAlignment` cop aligns with keywords (e.g. `if`, `while`, `case`)
# by default. On the other hand, `Layout/BeginEndAlignment` cop aligns with
# `EnforcedStyleAlignWith: start_of_line` by default due to `||= begin` tends
# to align with the start of the line. `Layout/DefEndAlignment` cop also aligns with
# `EnforcedStyleAlignWith: start_of_line` by default.
# These style can be configured by each cop.
#
# @example EnforcedStyleAlignWith: keyword (default)
# # bad
#
# variable = if true
# end
#
# # good
#
# variable = if true
# end
#
# variable =
# if true
# end
#
# @example EnforcedStyleAlignWith: variable
# # bad
#
# variable = if true
# end
#
# # good
#
# variable = if true
# end
#
# variable =
# if true
# end
#
# @example EnforcedStyleAlignWith: start_of_line
# # bad
#
# variable = if true
# end
#
# puts(if true
# end)
#
# # good
#
# variable = if true
# end
#
# puts(if true
# end)
#
# variable =
# if true
# end
class EndAlignment < Base
include CheckAssignment
include EndKeywordAlignment
include RangeHelp
extend AutoCorrector
def on_class(node)
check_other_alignment(node)
end
def on_sclass(node)
if node.parent&.assignment?
check_asgn_alignment(node.parent, node)
else
check_other_alignment(node)
end
end
def on_module(node)
check_other_alignment(node)
end
def on_if(node)
check_other_alignment(node) unless node.ternary?
end
def on_while(node)
check_other_alignment(node)
end
def on_until(node)
check_other_alignment(node)
end
def on_case(node)
if node.argument?
check_asgn_alignment(node.parent, node)
else
check_other_alignment(node)
end
end
alias on_case_match on_case
private
def autocorrect(corrector, node)
AlignmentCorrector.align_end(corrector, processed_source, node, alignment_node(node))
end
def check_assignment(node, rhs)
# If there are method calls chained to the right hand side of the
# assignment, we let rhs be the receiver of those method calls before
# we check if it's an if/unless/while/until.
return unless (rhs = first_part_of_call_chain(rhs))
# If `rhs` is a `begin` node, find the first non-`begin` child.
rhs = rhs.child_nodes.first while rhs.begin_type?
return unless rhs.conditional?
return if rhs.if_type? && rhs.ternary?
check_asgn_alignment(node, rhs)
end
def check_asgn_alignment(outer_node, inner_node)
align_with = {
keyword: inner_node.loc.keyword,
start_of_line: start_line_range(inner_node),
variable: asgn_variable_align_with(outer_node, inner_node)
}
check_end_kw_alignment(inner_node, align_with)
ignore_node(inner_node)
end
def asgn_variable_align_with(outer_node, inner_node)
expr = outer_node.source_range
if line_break_before_keyword?(expr, inner_node)
inner_node.loc.keyword
else
range_between(expr.begin_pos, inner_node.loc.keyword.end_pos)
end
end
def check_other_alignment(node)
align_with = {
keyword: node.loc.keyword,
variable: node.loc.keyword,
start_of_line: start_line_range(node)
}
check_end_kw_alignment(node, align_with)
end
def alignment_node(node)
case style
when :keyword
node
when :variable
align_to = alignment_node_for_variable_style(node)
while (parent = align_to.parent) && parent.send_type? && same_line?(align_to, parent)
align_to = parent
end
align_to
else
start_line_range(node)
end
end
def alignment_node_for_variable_style(node)
if node.type?(:case, :case_match) && node.argument? &&
same_line?(node, node.parent)
return node.parent
end
assignment = assignment_or_operator_method(node)
if assignment && !line_break_before_keyword?(assignment.source_range, node)
assignment
else
# Fall back to 'keyword' style if this node is not on the RHS of an
# assignment, or if it is but there's a line break between LHS and
# RHS.
node
end
end
def assignment_or_operator_method(node)
node.ancestors.find do |ancestor|
ancestor.assignment_or_similar? || (ancestor.send_type? && ancestor.operator_method?)
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/first_hash_element_line_break.rb | lib/rubocop/cop/layout/first_hash_element_line_break.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for a line break before the first element in a
# multi-line hash.
#
# @example
#
# # bad
# { a: 1,
# b: 2}
#
# # good
# {
# a: 1,
# b: 2 }
#
# # good
# {
# a: 1, b: {
# c: 3
# }}
#
# @example AllowMultilineFinalElement: false (default)
#
# # bad
# { a: 1, b: {
# c: 3
# }}
#
# @example AllowMultilineFinalElement: true
#
# # bad
# { a: 1,
# b: {
# c: 3
# }}
#
# # good
# { a: 1, b: {
# c: 3
# }}
#
class FirstHashElementLineBreak < Base
include FirstElementLineBreak
extend AutoCorrector
MSG = 'Add a line break before the first element of a multi-line hash.'
def on_hash(node)
# node.loc.begin tells us whether the hash opens with a {
# If it doesn't, Layout/FirstMethodArgumentLineBreak will handle it
return unless node.loc.begin
check_children_line_break(node, node.children, ignore_last: ignore_last_element?)
end
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/leading_empty_lines.rb | lib/rubocop/cop/layout/leading_empty_lines.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for unnecessary leading blank lines at the beginning
# of a file.
#
# @example
#
# # bad
# # (start of file)
#
# class Foo
# end
#
# # bad
# # (start of file)
#
# # a comment
#
# # good
# # (start of file)
# class Foo
# end
#
# # good
# # (start of file)
# # a comment
class LeadingEmptyLines < Base
extend AutoCorrector
MSG = 'Unnecessary blank line at the beginning of the source.'
def on_new_investigation
token = processed_source.tokens[0]
return unless token && token.line > 1
add_offense(token.pos) do |corrector|
range = Parser::Source::Range.new(processed_source.buffer, 0, token.begin_pos)
corrector.remove(range)
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/first_method_argument_line_break.rb | lib/rubocop/cop/layout/first_method_argument_line_break.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for a line break before the first argument in a
# multi-line method call.
#
# @example
#
# # bad
# method(foo, bar,
# baz)
#
# # good
# method(
# foo, bar,
# baz)
#
# # ignored
# method foo, bar,
# baz
#
# @example AllowMultilineFinalElement: false (default)
#
# # bad
# method(foo, bar, {
# baz: "a",
# qux: "b",
# })
#
# # good
# method(
# foo, bar, {
# baz: "a",
# qux: "b",
# })
#
# @example AllowMultilineFinalElement: true
#
# # bad
# method(foo,
# bar,
# {
# baz: "a",
# qux: "b",
# }
# )
#
# # good
# method(foo, bar, {
# baz: "a",
# qux: "b",
# })
#
# # good
# method(
# foo,
# bar,
# {
# baz: "a",
# qux: "b",
# }
# )
#
# @example AllowedMethods: ['some_method']
#
# # good
# some_method(foo, bar,
# baz)
class FirstMethodArgumentLineBreak < Base
include FirstElementLineBreak
include AllowedMethods
extend AutoCorrector
MSG = 'Add a line break before the first argument of a multi-line method argument list.'
def on_send(node)
return if allowed_method?(node.method_name)
args = node.arguments.dup
# 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.concat(args.pop.children) if last_arg&.hash_type? && !last_arg&.braces?
check_method_line_break(node, args, ignore_last: ignore_last_element?)
end
alias on_csend on_send
alias on_super on_send
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/argument_alignment.rb | lib/rubocop/cop/layout/argument_alignment.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Check that the arguments on a multi-line method call are aligned.
#
# @example EnforcedStyle: with_first_argument (default)
# # good
#
# foo :bar,
# :baz,
# key: value
#
# foo(
# :bar,
# :baz,
# key: value
# )
#
# # bad
#
# foo :bar,
# :baz,
# key: value
#
# foo(
# :bar,
# :baz,
# key: value
# )
#
# @example EnforcedStyle: with_fixed_indentation
# # good
#
# foo :bar,
# :baz,
# key: value
#
# # bad
#
# foo :bar,
# :baz,
# key: value
class ArgumentAlignment < Base
include Alignment
extend AutoCorrector
ALIGN_PARAMS_MSG = 'Align the arguments of a method call if they span more than one line.'
FIXED_INDENT_MSG = 'Use one level of indentation for arguments ' \
'following the first line of a multi-line method call.'
def on_send(node)
return if !multiple_arguments?(node) || (node.send_type? && node.method?(:[]=)) ||
autocorrect_incompatible_with_other_cops?
items = flattened_arguments(node)
check_alignment(items, base_column(node, items.first))
end
alias on_csend on_send
private
def autocorrect_incompatible_with_other_cops?
with_first_argument_style? && enforce_hash_argument_with_separator?
end
def flattened_arguments(node)
if fixed_indentation?
arguments_with_last_arg_pairs(node)
else
arguments_or_first_arg_pairs(node)
end
end
def arguments_with_last_arg_pairs(node)
items = node.arguments[0..-2]
last_arg = node.last_argument
if last_arg.hash_type? && !last_arg.braces?
items += last_arg.pairs
else
items << last_arg
end
items
end
def arguments_or_first_arg_pairs(node)
first_arg = node.first_argument
if first_arg.hash_type? && !first_arg.braces?
first_arg.pairs
else
node.arguments
end
end
def multiple_arguments?(node)
return true if node.arguments.size >= 2
first_argument = node.first_argument
first_argument&.hash_type? && first_argument.pairs.count >= 2
end
def autocorrect(corrector, node)
AlignmentCorrector.correct(corrector, processed_source, node, column_delta)
end
def message(_node)
fixed_indentation? ? FIXED_INDENT_MSG : ALIGN_PARAMS_MSG
end
def fixed_indentation?
cop_config['EnforcedStyle'] == 'with_fixed_indentation'
end
def with_first_argument_style?
cop_config['EnforcedStyle'] == 'with_first_argument'
end
def base_column(node, first_argument)
if fixed_indentation? || first_argument.nil?
lineno = target_method_lineno(node)
line = node.source_range.source_buffer.source_line(lineno)
indentation_of_line = /\S.*/.match(line).begin(0)
indentation_of_line + configured_indentation_width
else
display_column(first_argument.source_range)
end
end
def target_method_lineno(node)
if node.loc.selector
node.loc.selector.line
else
# l.(1) has no selector, so we use the opening parenthesis instead
node.loc.begin.line
end
end
def enforce_hash_argument_with_separator?
RuboCop::Cop::Layout::HashAlignment::SEPARATOR_ALIGNMENT_STYLES.any? do |style|
config.for_enabled_cop('Layout/HashAlignment')[style]&.include?('separator')
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/space_inside_hash_literal_braces.rb | lib/rubocop/cop/layout/space_inside_hash_literal_braces.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks that braces used for hash literals have or don't have
# surrounding space depending on configuration.
#
# Hash pattern matching is handled in the same way.
#
# @example EnforcedStyle: space (default)
# # The `space` style enforces that hash literals have
# # surrounding space.
#
# # bad
# h = {a: 1, b: 2}
# foo = {{ a: 1 } => { b: { c: 2 }}}
#
# # good
# h = { a: 1, b: 2 }
# foo = { { a: 1 } => { b: { c: 2 } } }
#
# @example EnforcedStyle: no_space
# # The `no_space` style enforces that hash literals have
# # no surrounding space.
#
# # bad
# h = { a: 1, b: 2 }
# foo = {{ a: 1 } => { b: { c: 2 }}}
#
# # good
# h = {a: 1, b: 2}
# foo = {{a: 1} => {b: {c: 2}}}
#
# @example EnforcedStyle: compact
# # The `compact` style normally requires a space inside
# # hash braces, with the exception that successive left
# # braces or right braces are collapsed together in nested hashes.
#
# # bad
# h = { a: { b: 2 } }
# foo = { { a: 1 } => { b: { c: 2 } } }
#
# # good
# h = { a: { b: 2 }}
# foo = {{ a: 1 } => { b: { c: 2 }}}
#
# @example EnforcedStyleForEmptyBraces: no_space (default)
# # The `no_space` EnforcedStyleForEmptyBraces style enforces that
# # empty hash braces do not contain spaces.
#
# # bad
# foo = { }
# bar = { }
# baz = {
# }
#
# # good
# foo = {}
# bar = {}
# baz = {}
#
# @example EnforcedStyleForEmptyBraces: space
# # The `space` EnforcedStyleForEmptyBraces style enforces that
# # empty hash braces contain space.
#
# # bad
# foo = {}
#
# # good
# foo = { }
# foo = { }
# foo = {
# }
#
class SpaceInsideHashLiteralBraces < Base
include SurroundingSpace
include ConfigurableEnforcedStyle
include RangeHelp
extend AutoCorrector
MSG = 'Space inside %<problem>s.'
def on_hash(node)
tokens = processed_source.tokens_within(node)
return unless tokens.first.left_brace? && tokens.last.right_curly_brace?
check(tokens[0], tokens[1])
check(tokens[-2], tokens[-1]) if tokens.size > 2
check_whitespace_only_hash(node) if enforce_no_space_style_for_empty_braces?
end
alias on_hash_pattern on_hash
private
def check(token1, token2)
# No offense if line break inside.
return if token1.line < token2.line
return if token2.comment? # Also indicates there's a line break.
is_empty_braces = token1.left_brace? && token2.right_curly_brace?
expect_space = expect_space?(token1, token2)
if offense?(token1, expect_space)
incorrect_style_detected(token1, token2, expect_space, is_empty_braces)
else
correct_style_detected
end
end
def expect_space?(token1, token2)
is_same_braces = token1.type == token2.type
is_empty_braces = token1.left_brace? && token2.right_curly_brace?
if is_same_braces && style == :compact
false
elsif is_empty_braces
!enforce_no_space_style_for_empty_braces?
else
style != :no_space
end
end
def incorrect_style_detected(token1, token2,
expect_space, is_empty_braces)
brace = (token1.left_brace? ? token1 : token2).pos
range = expect_space ? brace : space_range(brace)
detected_style = expect_space ? 'no_space' : 'space'
add_offense(range, message: message(brace, is_empty_braces, expect_space)) do |corrector|
autocorrect(corrector, range)
ambiguous_or_unexpected_style_detected(detected_style, token1.text == token2.text)
end
end
def autocorrect(corrector, range)
case range.source
when /\s/ then corrector.remove(range)
when '{' then corrector.insert_after(range, ' ')
else corrector.insert_before(range, ' ')
end
end
def ambiguous_or_unexpected_style_detected(style, is_match)
if is_match
ambiguous_style_detected(style, :compact)
else
unexpected_style_detected(style)
end
end
def offense?(token1, expect_space)
has_space = token1.space_after?
expect_space ? !has_space : has_space
end
def message(brace, is_empty_braces, expect_space)
inside_what = if is_empty_braces
'empty hash literal braces'
else
brace.source
end
problem = expect_space ? 'missing' : 'detected'
format(MSG, problem: "#{inside_what} #{problem}")
end
def space_range(token_range)
if token_range.source == '{'
range_of_space_to_the_right(token_range)
else
range_of_space_to_the_left(token_range)
end
end
def range_of_space_to_the_right(range)
src = range.source_buffer.source
end_pos = range.end_pos
end_pos += 1 while /[ \t]/.match?(src[end_pos])
range_between(range.begin_pos + 1, end_pos)
end
def range_of_space_to_the_left(range)
src = range.source_buffer.source
begin_pos = range.begin_pos
begin_pos -= 1 while /[ \t]/.match?(src[begin_pos - 1])
range_between(begin_pos, range.end_pos - 1)
end
def check_whitespace_only_hash(node)
range = range_inside_hash(node)
return unless range.source.match?(/\A\s+\z/m)
add_offense(
range,
message: format(MSG, problem: 'empty hash literal braces detected')
) do |corrector|
corrector.remove(range)
end
end
def range_inside_hash(node)
return node.source_range if node.location.begin.nil?
range_between(node.location.begin.end_pos, node.location.end.begin_pos)
end
def enforce_no_space_style_for_empty_braces?
cop_config['EnforcedStyleForEmptyBraces'] == 'no_space'
end
end
end
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_module_body.rb | lib/rubocop/cop/layout/empty_lines_around_module_body.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks if empty lines around the bodies of modules match
# the configuration.
#
# @example EnforcedStyle: no_empty_lines (default)
# # good
#
# module Foo
# def bar
# # ...
# end
# end
#
# @example EnforcedStyle: empty_lines
# # good
#
# module Foo
#
# def bar
# # ...
# end
#
# end
#
# @example EnforcedStyle: empty_lines_except_namespace
# # good
#
# module Foo
# module Bar
#
# # ...
#
# end
# end
#
# @example EnforcedStyle: empty_lines_special
# # good
# module Foo
#
# def bar; end
#
# end
class EmptyLinesAroundModuleBody < Base
include EmptyLinesAroundBody
extend AutoCorrector
KIND = 'module'
def on_module(node)
check(node, node.body)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/space_before_first_arg.rb | lib/rubocop/cop/layout/space_before_first_arg.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks that exactly one space is used between a method name and the
# first argument for method calls without parentheses.
#
# Alternatively, extra spaces can be added to align the argument with
# something on a preceding or following line, if the AllowForAlignment
# config parameter is true.
#
# @example
# # bad
# something x
# something y, z
# something'hello'
#
# # good
# something x
# something y, z
# something 'hello'
#
class SpaceBeforeFirstArg < Base
include PrecedingFollowingAlignment
include RangeHelp
extend AutoCorrector
MSG = 'Put one space between the method name and the first argument.'
def self.autocorrect_incompatible_with
[Style::MethodCallWithArgsParentheses]
end
def on_send(node)
return unless regular_method_call_with_arguments?(node)
return if node.parenthesized?
first_arg = node.first_argument.source_range
first_arg_with_space = range_with_surrounding_space(first_arg, side: :left)
space = range_between(first_arg_with_space.begin_pos, first_arg.begin_pos)
return if space.length == 1
return unless expect_params_after_method_name?(node)
add_offense(space) { |corrector| corrector.replace(space, ' ') }
end
alias on_csend on_send
private
def regular_method_call_with_arguments?(node)
node.arguments? && !node.operator_method? && !node.setter_method?
end
def expect_params_after_method_name?(node)
return true if no_space_between_method_name_and_first_argument?(node)
first_arg = node.first_argument
same_line?(first_arg, node) &&
!(allow_for_alignment? && aligned_with_something?(first_arg.source_range))
end
def no_space_between_method_name_and_first_argument?(node)
end_pos_of_method_name = node.loc.selector.end_pos
begin_pos_of_argument = node.first_argument.source_range.begin_pos
end_pos_of_method_name == begin_pos_of_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/class_structure.rb | lib/rubocop/cop/layout/class_structure.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks if the code style follows the `ExpectedOrder` configuration:
#
# `Categories` allows us to map macro names into a category.
#
# Consider an example of code style that covers the following order:
#
# * Module inclusion (`include`, `prepend`, `extend`)
# * Constants
# * Associations (`has_one`, `has_many`)
# * Public attribute macros (`attr_accessor`, `attr_writer`, `attr_reader`)
# * Other macros (`validates`, `validate`)
# * Public class methods
# * Initializer
# * Public instance methods
# * Protected attribute macros (`attr_accessor`, `attr_writer`, `attr_reader`)
# * Protected instance methods
# * Private attribute macros (`attr_accessor`, `attr_writer`, `attr_reader`)
# * Private instance methods
#
# NOTE: Simply enabling the cop with `Enabled: true` will not use
# the example order shown below.
# To enforce the order of macros like `attr_reader`,
# you must define both `ExpectedOrder` *and* `Categories`.
#
# You can configure the following order:
#
# [source,yaml]
# ----
# Layout/ClassStructure:
# ExpectedOrder:
# - module_inclusion
# - constants
# - association
# - public_attribute_macros
# - public_delegate
# - macros
# - public_class_methods
# - initializer
# - public_methods
# - protected_attribute_macros
# - protected_methods
# - private_attribute_macros
# - private_delegate
# - private_methods
# ----
#
# Instead of putting all literals in the expected order, is also
# possible to group categories of macros. Visibility levels are handled
# automatically.
#
# [source,yaml]
# ----
# Layout/ClassStructure:
# Categories:
# association:
# - has_many
# - has_one
# attribute_macros:
# - attr_accessor
# - attr_reader
# - attr_writer
# macros:
# - validates
# - validate
# module_inclusion:
# - include
# - prepend
# - extend
# ----
#
# If you only set `ExpectedOrder`
# without defining `Categories`,
# macros such as `attr_reader` or `has_many`
# will not be recognized as part of a category, and their order will not be validated.
# For example, the following will NOT raise any offenses, even if the order is incorrect:
#
# [source,yaml]
# ----
# Layout/ClassStructure:
# Enabled: true
# ExpectedOrder:
# - public_attribute_macros
# - initializer
# ----
#
# To make it work as expected, you must also specify `Categories` like this:
#
# [source,yaml]
# ----
# Layout/ClassStructure:
# ExpectedOrder:
# - public_attribute_macros
# - initializer
# Categories:
# attribute_macros:
# - attr_reader
# - attr_writer
# - attr_accessor
# ----
#
# @safety
# Autocorrection is unsafe because class methods and module inclusion
# can behave differently, based on which methods or constants have
# already been defined.
#
# Constants will only be moved when they are assigned with literals.
#
# @example
# # bad
# # Expect extend be before constant
# class Person < ApplicationRecord
# has_many :orders
# ANSWER = 42
#
# extend SomeModule
# include AnotherModule
# end
#
# # good
# class Person
# # extend and include go first
# extend SomeModule
# include AnotherModule
#
# # inner classes
# CustomError = Class.new(StandardError)
#
# # constants are next
# SOME_CONSTANT = 20
#
# # afterwards we have public attribute macros
# attr_reader :name
#
# # followed by other macros (if any)
# validates :name
#
# # then we have public delegate macros
# delegate :to_s, to: :name
#
# # public class methods are next in line
# def self.some_method
# end
#
# # initialization goes between class methods and instance methods
# def initialize
# end
#
# # followed by other public instance methods
# def some_method
# end
#
# # protected attribute macros and methods go next
# protected
#
# attr_reader :protected_name
#
# def some_protected_method
# end
#
# # private attribute macros, delegate macros and methods
# # are grouped near the end
# private
#
# attr_reader :private_name
#
# delegate :some_private_delegate, to: :name
#
# def some_private_method
# end
# end
#
class ClassStructure < Base
include VisibilityHelp
include CommentsHelp
extend AutoCorrector
HUMANIZED_NODE_TYPE = {
casgn: :constants,
defs: :public_class_methods,
def: :public_methods,
sclass: :class_singleton
}.freeze
MSG = '`%<category>s` is supposed to appear before `%<previous>s`.'
# Validates code style on class declaration.
# Add offense when find a node out of expected order.
def on_class(class_node)
previous = -1
walk_over_nested_class_definition(class_node) do |node, category|
index = expected_order.index(category)
if index < previous
message = format(MSG, category: category, previous: expected_order[previous])
add_offense(node, message: message) { |corrector| autocorrect(corrector, node) }
end
previous = index
end
end
alias on_sclass on_class
private
# Autocorrect by swapping between two nodes autocorrecting them
def autocorrect(corrector, node)
previous = node.left_siblings.reverse.find do |sibling|
!ignore_for_autocorrect?(node, sibling)
end
return unless previous
current_range = source_range_with_comment(node)
previous_range = source_range_with_comment(previous)
corrector.insert_before(previous_range, current_range.source)
corrector.remove(current_range)
end
# Classifies a node to match with something in the {expected_order}
# @param node to be analysed
# @return String when the node type is a `:block` then
# {classify} recursively with the first children
# @return String when the node type is a `:send` then {find_category}
# by method name
# @return String otherwise trying to {humanize_node} of the current node
def classify(node)
return node.to_s unless node.respond_to?(:type)
case node.type
when :block
classify(node.send_node)
when :send
find_category(node)
else
humanize_node(node)
end.to_s
end
# Categorize a node according to the {expected_order}
# Try to match {categories} values against the node's method_name given
# also its visibility.
# @param node to be analysed.
# @return [String] with the key category or the `method_name` as string
def find_category(node)
name = node.method_name.to_s
category, = categories.find { |_, names| names.include?(name) }
key = category || name
visibility_key =
if node.def_modifier?
"#{name}_methods"
else
"#{node_visibility(node)}_#{key}"
end
expected_order.include?(visibility_key) ? visibility_key : key
end
def walk_over_nested_class_definition(class_node)
class_elements(class_node).each do |node|
classification = classify(node)
next if ignore?(node, classification)
yield node, classification
end
end
def class_elements(class_node)
class_def = class_node.body
return [] unless class_def
if class_def.type?(:def, :send)
[class_def]
else
class_def.children.compact
end
end
def ignore?(node, classification)
classification.nil? ||
classification.to_s.end_with?('=') ||
expected_order.index(classification).nil? ||
private_constant?(node)
end
def ignore_for_autocorrect?(node, sibling)
classification = classify(node)
sibling_class = classify(sibling)
ignore?(sibling, sibling_class) ||
classification == sibling_class ||
dynamic_constant?(node)
end
def humanize_node(node)
if node.def_type?
return :initializer if node.method?(:initialize)
return "#{node_visibility(node)}_methods"
end
HUMANIZED_NODE_TYPE[node.type] || node.type
end
def dynamic_constant?(node)
return false unless node.casgn_type? && node.namespace.nil?
expression = node.expression
expression.send_type? &&
!(expression.method?(:freeze) && expression.receiver&.recursive_basic_literal?)
end
def private_constant?(node)
return false unless node.casgn_type? && node.namespace.nil?
return false unless (parent = node.parent)
parent.each_child_node(:send) do |child_node|
return true if marked_as_private_constant?(child_node, node.name)
end
false
end
def marked_as_private_constant?(node, name)
return false unless node.method?(:private_constant)
node.arguments.any? { |arg| arg.type?(:sym, :str) && arg.value == name }
end
def end_position_for(node)
if node.casgn_type?
heredoc = find_heredoc(node)
return heredoc.location.heredoc_end.end_pos + 1 if heredoc
end
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 = nil
(node.first_line - 1).downto(1) do |annotation_line|
break unless (comment = processed_source.comment_at_line(annotation_line))
first_comment = comment if whole_line_comment_at_line?(annotation_line)
end
start_line_position(first_comment || node)
end
def whole_line_comment_at_line?(line)
/\A\s*#/.match?(processed_source.lines[line - 1])
end
def start_line_position(node)
buffer.line_range(node.loc.line).begin_pos - 1
end
def find_heredoc(node)
node.each_node(:any_str).find(&:heredoc?)
end
def buffer
processed_source.buffer
end
# Load expected order from `ExpectedOrder` config.
# Define new terms in the expected order by adding new {categories}.
def expected_order
cop_config['ExpectedOrder']
end
# Setting categories hash allow you to group methods in group to match
# in the {expected_order}.
def categories
cop_config['Categories']
end
end
end
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/assignment_indentation.rb | lib/rubocop/cop/layout/assignment_indentation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks the indentation of the first line of the
# right-hand-side of a multi-line assignment.
#
# The indentation of the remaining lines can be corrected with
# other cops such as `Layout/IndentationConsistency` and `Layout/EndAlignment`.
#
# @example
# # bad
# value =
# if foo
# 'bar'
# end
#
# # good
# value =
# if foo
# 'bar'
# end
#
class AssignmentIndentation < Base
include CheckAssignment
include Alignment
extend AutoCorrector
MSG = 'Indent the first line of the right-hand-side of a multi-line assignment.'
private
def check_assignment(node, rhs)
return unless rhs
return unless node.loc.operator
return if same_line?(node.loc.operator, rhs)
base = display_column(leftmost_multiple_assignment(node).source_range)
check_alignment([rhs], base + configured_indentation_width)
end
def autocorrect(corrector, node)
AlignmentCorrector.correct(corrector, processed_source, node, column_delta)
end
def leftmost_multiple_assignment(node)
return node unless same_line?(node, node.parent) && node.parent.assignment?
leftmost_multiple_assignment(node.parent)
node.parent
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/empty_line_after_guard_clause.rb | lib/rubocop/cop/layout/empty_line_after_guard_clause.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Enforces empty line after guard clause.
#
# This cop allows `# :nocov:` directive after guard clause because
# SimpleCov excludes code from the coverage report by wrapping it in `# :nocov:`:
#
# [source,ruby]
# ----
# def foo
# # :nocov:
# return if condition
# # :nocov:
# bar
# end
# ----
#
# Refer to SimpleCov's documentation for more details:
# https://github.com/simplecov-ruby/simplecov#ignoringskipping-code
#
# @example
#
# # bad
# def foo
# return if need_return?
# bar
# end
#
# # good
# def foo
# return if need_return?
#
# bar
# end
#
# # good
# def foo
# return if something?
# return if something_different?
#
# bar
# end
#
# # also good
# def foo
# if something?
# do_something
# return if need_return?
# end
# end
class EmptyLineAfterGuardClause < Base
include RangeHelp
extend AutoCorrector
extend Util
MSG = 'Add empty line after guard clause.'
END_OF_HEREDOC_LINE = 1
SIMPLE_DIRECTIVE_COMMENT_PATTERN = /\A# *:nocov:\z/.freeze
def on_if(node)
return if correct_style?(node)
return if multiple_statements_on_line?(node)
if node.modifier_form? && (heredoc_node = last_heredoc_argument(node))
if next_line_empty_or_allowed_directive_comment?(heredoc_line(node, heredoc_node))
return
end
add_offense(heredoc_node.loc.heredoc_end) do |corrector|
autocorrect(corrector, heredoc_node)
end
else
return if next_line_empty_or_allowed_directive_comment?(node.last_line)
add_offense(offense_location(node)) { |corrector| autocorrect(corrector, node) }
end
end
private
def autocorrect(corrector, node)
node_range = if heredoc?(node)
range_by_whole_lines(node.loc.heredoc_body)
else
range_by_whole_lines(node.source_range)
end
next_line = node_range.last_line + 1
if next_line_allowed_directive_comment?(next_line)
node_range = processed_source.comment_at_line(next_line)
end
corrector.insert_after(node_range, "\n")
end
def correct_style?(node)
!contains_guard_clause?(node) ||
next_line_rescue_or_ensure?(node) ||
next_sibling_parent_empty_or_else?(node) ||
next_sibling_empty_or_guard_clause?(node)
end
def contains_guard_clause?(node)
node.if_branch&.guard_clause?
end
def next_line_empty_or_allowed_directive_comment?(line)
return true if next_line_empty?(line)
next_line = line + 1
next_line_allowed_directive_comment?(next_line) && next_line_empty?(next_line)
end
def next_line_empty?(line)
processed_source[line].blank?
end
def next_line_allowed_directive_comment?(line)
return false unless (comment = processed_source.comment_at_line(line))
DirectiveComment.new(comment).enabled? || simplecov_directive_comment?(comment)
end
def next_line_rescue_or_ensure?(node)
parent = node.parent
parent.nil? || parent.rescue_type? || parent.ensure_type?
end
def next_sibling_parent_empty_or_else?(node)
next_sibling = node.right_sibling
return true unless next_sibling.is_a?(AST::Node)
parent = next_sibling.parent
parent&.if_type? && parent.else?
end
def next_sibling_empty_or_guard_clause?(node)
next_sibling = node.right_sibling
return true if next_sibling.nil?
next_sibling.if_type? && contains_guard_clause?(next_sibling)
end
# rubocop:disable Metrics/CyclomaticComplexity
def last_heredoc_argument(node)
n = last_heredoc_argument_node(node)
n = n.children.first while n.respond_to?(:begin_type?) && n.begin_type?
return n if heredoc?(n)
return unless n.respond_to?(:arguments)
n.arguments.each do |argument|
node = last_heredoc_argument(argument)
return node if node
end
last_heredoc_argument(n.receiver) if n.respond_to?(:receiver)
end
# rubocop:enable Metrics/CyclomaticComplexity
def last_heredoc_argument_node(node)
return node unless node.respond_to?(:if_branch)
if node.if_branch.and_type?
node.if_branch.children.first
elsif use_heredoc_in_condition?(node.condition)
node.condition
else
node.if_branch.children.last
end
end
def heredoc_line(node, heredoc_node)
heredoc_body = heredoc_node.loc.heredoc_body
num_of_heredoc_lines = heredoc_body.last_line - heredoc_body.first_line
node.last_line + num_of_heredoc_lines + END_OF_HEREDOC_LINE
end
def heredoc?(node)
node.respond_to?(:heredoc?) && node.heredoc?
end
def use_heredoc_in_condition?(condition)
condition.descendants.any? do |descendant|
descendant.respond_to?(:heredoc?) && descendant.heredoc?
end
end
def offense_location(node)
if node.loc?(:end)
node.loc.end
else
node
end
end
def multiple_statements_on_line?(node)
parent = node.parent
return false unless parent
parent.begin_type? && same_line?(node, node.right_sibling)
end
# SimpleCov excludes code from the coverage report by wrapping it in `# :nocov:`:
# https://github.com/simplecov-ruby/simplecov#ignoringskipping-code
def simplecov_directive_comment?(comment)
SIMPLE_DIRECTIVE_COMMENT_PATTERN.match?(comment.text)
end
end
end
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/block_end_newline.rb | lib/rubocop/cop/layout/block_end_newline.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks whether the end statement of a do..end block
# is on its own line.
#
# @example
# # bad
# blah do |i|
# foo(i) end
#
# # good
# blah do |i|
# foo(i)
# end
#
# # bad
# blah { |i|
# foo(i) }
#
# # good
# blah { |i|
# foo(i)
# }
class BlockEndNewline < Base
include Alignment
extend AutoCorrector
MSG = 'Expression at %<line>d, %<column>d should be on its own line.'
def on_block(node)
return if node.single_line?
# If the end is on its own line, there is no offense
return if begins_its_line?(node.loc.end)
offense_range = offense_range(node)
return if offense_range.source.lstrip.start_with?(';')
register_offense(node, offense_range)
end
alias on_numblock on_block
alias on_itblock on_block
private
def register_offense(node, offense_range)
add_offense(node.loc.end, message: message(node)) do |corrector|
replacement = "\n#{offense_range.source.lstrip}"
if (heredoc = last_heredoc_argument(node.body))
corrector.remove(offense_range)
corrector.insert_after(heredoc.loc.heredoc_end, replacement)
else
corrector.replace(offense_range, replacement)
end
end
end
def message(node)
format(MSG, line: node.loc.end.line, column: node.loc.end.column + 1)
end
def last_heredoc_argument(node)
return unless node&.call_type?
return unless (arguments = node&.arguments)
heredoc = arguments.reverse.detect { |arg| arg.str_type? && arg.heredoc? }
return heredoc if heredoc
last_heredoc_argument(node.children.first)
end
def offense_range(node)
node.children.compact.last.source_range.end.join(node.loc.end)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/closing_parenthesis_indentation.rb | lib/rubocop/cop/layout/closing_parenthesis_indentation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks the indentation of hanging closing parentheses in
# method calls, method definitions, and grouped expressions. A hanging
# closing parenthesis means `)` preceded by a line break.
#
# @example
#
# # bad
# some_method(
# a,
# b
# )
#
# some_method(
# a, b
# )
#
# some_method(a, b, c
# )
#
# some_method(a,
# b,
# c
# )
#
# some_method(a,
# x: 1,
# y: 2
# )
#
# # Scenario 1: When First Parameter Is On Its Own Line
#
# # good: when first param is on a new line, right paren is *always*
# # outdented by IndentationWidth
# some_method(
# a,
# b
# )
#
# # good
# some_method(
# a, b
# )
#
# # Scenario 2: When First Parameter Is On The Same Line
#
# # good: when all other params are also on the same line, outdent
# # right paren by IndentationWidth
# some_method(a, b, c
# )
#
# # good: when all other params are on multiple lines, but are lined
# # up, align right paren with left paren
# some_method(a,
# b,
# c
# )
#
# # good: when other params are not lined up on multiple lines, outdent
# # right paren by IndentationWidth
# some_method(a,
# x: 1,
# y: 2
# )
#
#
class ClosingParenthesisIndentation < Base
include Alignment
extend AutoCorrector
MSG_INDENT = 'Indent `)` to column %<expected>d (not %<actual>d)'
MSG_ALIGN = 'Align `)` with `(`.'
def on_send(node)
check(node, node.arguments)
end
alias on_csend on_send
def on_begin(node)
check(node, node.children)
end
def on_def(node)
check(node.arguments, node.arguments)
end
alias on_defs on_def
private
def autocorrect(corrector, node)
AlignmentCorrector.correct(corrector, processed_source, node, @column_delta)
end
def check(node, elements)
if elements.empty?
check_for_no_elements(node)
else
check_for_elements(node, elements)
end
end
def check_for_elements(node, elements)
left_paren = node.loc.begin
right_paren = node.loc.end
return unless right_paren && begins_its_line?(right_paren)
correct_column = expected_column(left_paren, elements)
@column_delta = correct_column - right_paren.column
return if @column_delta.zero?
message = message(correct_column, left_paren, right_paren)
add_offense(right_paren, message: message) do |corrector|
autocorrect(corrector, right_paren)
end
end
def check_for_no_elements(node)
left_paren = node.loc.begin
right_paren = node.loc.end
return unless right_paren && begins_its_line?(right_paren)
candidates = correct_column_candidates(node, left_paren)
return if candidates.include?(right_paren.column)
# Although there are multiple choices for a correct column,
# select the first one of candidates to determine a specification.
correct_column = candidates.first
@column_delta = correct_column - right_paren.column
message = message(correct_column, left_paren, right_paren)
add_offense(right_paren, message: message) do |corrector|
autocorrect(corrector, right_paren)
end
end
def expected_column(left_paren, elements)
if line_break_after_left_paren?(left_paren, elements)
source_indent = processed_source.line_indentation(first_argument_line(elements))
new_indent = source_indent - configured_indentation_width
new_indent.negative? ? 0 : new_indent
elsif all_elements_aligned?(elements)
left_paren.column
else
processed_source.line_indentation(first_argument_line(elements))
end
end
def all_elements_aligned?(elements)
if elements.first.hash_type?
elements.first.each_child_node.map { |child| child.loc.column }
else
elements.flat_map do |e|
e.loc.column
end
end.uniq.one?
end
def first_argument_line(elements)
elements.first.loc.first_line
end
def correct_column_candidates(node, left_paren)
[
processed_source.line_indentation(left_paren.line),
left_paren.column,
node.loc.column
]
end
def message(correct_column, left_paren, right_paren)
if correct_column == left_paren.column
MSG_ALIGN
else
format(MSG_INDENT, expected: correct_column, actual: right_paren.column)
end
end
def line_break_after_left_paren?(left_paren, elements)
elements.first && elements.first.loc.line > left_paren.line
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/indentation_width.rb | lib/rubocop/cop/layout/indentation_width.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for indentation that doesn't use the specified number of spaces.
# The indentation width can be configured using the `Width` setting. The default width is 2.
#
# See also the `Layout/IndentationConsistency` cop which is the companion to this one.
#
# @example Width: 2 (default)
# # bad
# class A
# def test
# puts 'hello'
# end
# end
#
# # good
# class A
# def test
# puts 'hello'
# end
# end
#
# @example AllowedPatterns: ['^\s*module']
# # bad
# module A
# class B
# def test
# puts 'hello'
# end
# end
# end
#
# # good
# module A
# class B
# def test
# puts 'hello'
# end
# end
# end
class IndentationWidth < Base # rubocop:disable Metrics/ClassLength
include EndKeywordAlignment
include Alignment
include CheckAssignment
include AllowedPattern
include RangeHelp
extend AutoCorrector
MSG = 'Use %<configured_indentation_width>d (not %<indentation>d) ' \
'spaces for%<name>s indentation.'
# @!method access_modifier?(node)
def_node_matcher :access_modifier?, <<~PATTERN
[(send ...) access_modifier?]
PATTERN
def on_rescue(node)
check_indentation(node.loc.else, node.else_branch)
end
def on_resbody(node)
check_indentation(node.loc.keyword, node.body)
end
alias on_for on_resbody
def on_ensure(node)
check_indentation(node.loc.keyword, node.branch)
end
def on_kwbegin(node)
# Check indentation against end keyword but only if it's first on its
# line.
return unless begins_its_line?(node.loc.end)
check_indentation(node.loc.end, node.children.first)
end
def on_block(node)
end_loc = node.loc.end
return unless begins_its_line?(end_loc)
# For blocks where the dot is on a new line, use the dot position as the base.
# Otherwise, use the end keyword position as the base.
base_loc = dot_on_new_line?(node) ? node.send_node.loc.dot : end_loc
check_indentation(base_loc, node.body)
return unless indented_internal_methods_style?
return unless contains_access_modifier?(node.body)
check_members(end_loc, [node.body])
end
alias on_numblock on_block
alias on_itblock on_block
def on_class(node)
base = node.loc.keyword
return if same_line?(base, node.body)
check_members(base, [node.body])
end
alias on_sclass on_class
alias on_module on_class
def on_send(node)
super
return unless node.adjacent_def_modifier?
def_end_config = config.for_cop('Layout/DefEndAlignment')
style = def_end_config['EnforcedStyleAlignWith'] || 'start_of_line'
base = if style == 'def'
node.first_argument
else
leftmost_modifier_of(node) || node
end
check_indentation(base.source_range, node.first_argument.body)
ignore_node(node.first_argument)
end
alias on_csend on_send
def on_def(node)
return if ignored_node?(node)
check_indentation(node.loc.keyword, node.body)
end
alias on_defs on_def
def on_while(node, base = node)
return if ignored_node?(node)
return unless node.single_line_condition?
check_indentation(base.loc, node.body)
end
alias on_until on_while
def on_case(case_node)
case_node.when_branches.each do |when_node|
check_indentation(when_node.loc.keyword, when_node.body)
end
check_indentation(case_node.when_branches.last.loc.keyword, case_node.else_branch)
end
def on_case_match(case_match)
case_match.each_in_pattern do |in_pattern_node|
check_indentation(in_pattern_node.loc.keyword, in_pattern_node.body)
end
else_branch = case_match.else_branch&.empty_else_type? ? nil : case_match.else_branch
check_indentation(case_match.in_pattern_branches.last.loc.keyword, else_branch)
end
def on_if(node, base = node)
return if ignored_node?(node)
return if node.ternary? || node.modifier_form?
check_if(node, node.body, node.else_branch, base.loc)
end
private
def autocorrect(corrector, node)
AlignmentCorrector.correct(corrector, processed_source, node, @column_delta)
end
def check_members(base, members)
check_indentation(base, select_check_member(members.first))
return unless members.any? && members.first.begin_type?
if indentation_consistency_style == 'indented_internal_methods'
check_members_for_indented_internal_methods_style(members)
else
check_members_for_normal_style(base, members)
end
end
def select_check_member(member)
return unless member
if access_modifier?(member.children.first)
return if access_modifier_indentation_style == 'outdent'
member.children.first
else
member
end
end
def check_members_for_indented_internal_methods_style(members)
each_member(members) do |member, previous_modifier|
check_indentation(previous_modifier, member, indentation_consistency_style)
end
end
def check_members_for_normal_style(base, members)
members.first.children.each do |member|
next if member.send_type? && member.access_modifier?
check_indentation(base, member)
end
end
def each_member(members)
previous_modifier = nil
members.first.children.each do |member|
if member.send_type? && member.special_modifier?
previous_modifier = member
elsif previous_modifier
yield member, previous_modifier.source_range
previous_modifier = nil
end
end
end
def indented_internal_methods_style?
indentation_consistency_style == 'indented_internal_methods'
end
def special_modifier?(node)
node.bare_access_modifier? && SPECIAL_MODIFIERS.include?(node.source)
end
def access_modifier_indentation_style
config.for_cop('Layout/AccessModifierIndentation')['EnforcedStyle']
end
def indentation_consistency_style
config.for_cop('Layout/IndentationConsistency')['EnforcedStyle']
end
def check_assignment(node, rhs)
# If there are method calls chained to the right hand side of the
# assignment, we let rhs be the receiver of those method calls before
# we check its indentation.
rhs = first_part_of_call_chain(rhs)
return unless rhs
end_config = config.for_cop('Layout/EndAlignment')
style = end_config['EnforcedStyleAlignWith'] || 'keyword'
base = variable_alignment?(node.loc, rhs, style.to_sym) ? node : rhs
case rhs.type
when :if then on_if(rhs, base)
when :while, :until then on_while(rhs, base)
else return
end
ignore_node(rhs)
end
def check_if(node, body, else_clause, base_loc)
return if node.ternary?
check_indentation(base_loc, body)
return unless else_clause
# If the else clause is an elsif, it will get its own on_if call so
# we don't need to process it here.
return if else_clause.if_type? && else_clause.elsif?
check_indentation(node.loc.else, else_clause)
end
def check_indentation(base_loc, body_node, style = 'normal')
return unless indentation_to_check?(base_loc, body_node)
indentation = column_offset_between(body_node.loc, base_loc)
@column_delta = configured_indentation_width - indentation
return if @column_delta.zero?
offense(body_node, indentation, style)
end
def offense(body_node, indentation, style)
# This cop only autocorrects the first statement in a def body, for
# example.
body_node = body_node.children.first if body_node.begin_type? && !parentheses?(body_node)
# Since autocorrect changes a number of lines, and not only the line
# where the reported offending range is, we avoid autocorrection if
# this cop has already found other offenses is the same
# range. Otherwise, two corrections can interfere with each other,
# resulting in corrupted code.
node = if autocorrect? && other_offense_in_same_range?(body_node)
nil
else
body_node
end
name = style == 'normal' ? '' : " #{style}"
message = message(configured_indentation_width, indentation, name)
add_offense(offending_range(body_node, indentation), message: message) do |corrector|
autocorrect(corrector, node)
end
end
def message(configured_indentation_width, indentation, name)
format(
MSG,
configured_indentation_width: configured_indentation_width,
indentation: indentation,
name: name
)
end
# Returns true if the given node is within another node that has
# already been marked for autocorrection by this cop.
def other_offense_in_same_range?(node)
expr = node.source_range
@offense_ranges ||= []
return true if @offense_ranges.any? { |r| within?(expr, r) }
@offense_ranges << expr
false
end
def indentation_to_check?(base_loc, body_node)
return false if skip_check?(base_loc, body_node)
if body_node.rescue_type?
check_rescue?(body_node)
elsif body_node.ensure_type?
block_body, = *body_node # rubocop:disable InternalAffairs/NodeDestructuring
if block_body&.rescue_type?
check_rescue?(block_body)
else
!block_body.nil?
end
else
true
end
end
def check_rescue?(rescue_node)
rescue_node.body
end
def skip_check?(base_loc, body_node)
return true if allowed_line?(base_loc)
return true unless body_node
# Don't check if expression is on same line as "then" keyword, etc.
return true if same_line?(body_node, base_loc)
return true if starts_with_access_modifier?(body_node)
# Don't check indentation if the line doesn't start with the body.
# For example, lines like "else do_something".
first_char_pos_on_line = body_node.source_range.source_line =~ /\S/
body_node.loc.column != first_char_pos_on_line
end
def offending_range(body_node, indentation)
expr = body_node.source_range
begin_pos = expr.begin_pos
ind = expr.begin_pos - indentation
pos = indentation >= 0 ? ind..begin_pos : begin_pos..ind
range_between(pos.begin, pos.end)
end
def starts_with_access_modifier?(body_node)
return false unless body_node.begin_type?
starting_node = body_node.children.first
return false unless starting_node
starting_node.send_type? && starting_node.bare_access_modifier?
end
def contains_access_modifier?(body_node)
return false unless body_node.begin_type?
body_node.children.any? { |child| child.send_type? && child.bare_access_modifier? }
end
def configured_indentation_width
cop_config['Width']
end
def leftmost_modifier_of(node)
return node unless node.parent&.send_type?
leftmost_modifier_of(node.parent)
end
def dot_on_new_line?(node)
send_node = node.send_node
return false unless send_node.loc?(:dot)
receiver = send_node.receiver
receiver && receiver.last_line < send_node.loc.dot.line
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/space_inside_array_percent_literal.rb | lib/rubocop/cop/layout/space_inside_array_percent_literal.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for unnecessary additional spaces inside array percent literals
# (i.e. %i/%w).
#
# Note that blank percent literals (e.g. `%i( )`) are checked by
# `Layout/SpaceInsidePercentLiteralDelimiters`.
#
# @example
#
# # bad
# %w(foo bar baz)
# # good
# %i(foo bar baz)
class SpaceInsideArrayPercentLiteral < Base
include MatchRange
include PercentLiteral
extend AutoCorrector
MSG = 'Use only a single space inside array percent literal.'
MULTIPLE_SPACES_BETWEEN_ITEMS_REGEX = /(?:[\S&&[^\\]](?:\\ )*)( {2,})(?=\S)/.freeze
def on_array(node)
process(node, '%i', '%I', '%w', '%W')
end
def on_percent_literal(node)
each_unnecessary_space_match(node) do |range|
add_offense(range) do |corrector|
corrector.replace(range, ' ')
end
end
end
private
def each_unnecessary_space_match(node, &blk)
each_match_range(contents_range(node), MULTIPLE_SPACES_BETWEEN_ITEMS_REGEX, &blk)
end
end
end
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/access_modifier_indentation.rb | lib/rubocop/cop/layout/access_modifier_indentation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Bare access modifiers (those not applying to specific methods) should be
# indented as deep as method definitions, or as deep as the `class`/`module`
# keyword, depending on configuration.
#
# @example EnforcedStyle: indent (default)
# # bad
# class Plumbus
# private
# def smooth; end
# end
#
# # good
# class Plumbus
# private
# def smooth; end
# end
#
# @example EnforcedStyle: outdent
# # bad
# class Plumbus
# private
# def smooth; end
# end
#
# # good
# class Plumbus
# private
# def smooth; end
# end
class AccessModifierIndentation < Base
include Alignment
include ConfigurableEnforcedStyle
include RangeHelp
extend AutoCorrector
MSG = '%<style>s access modifiers like `%<node>s`.'
def on_class(node)
return unless node.body&.begin_type?
check_body(node.body, node)
end
alias on_sclass on_class
alias on_module on_class
alias on_block on_class
private
def autocorrect(corrector, node)
AlignmentCorrector.correct(corrector, processed_source, node, @column_delta)
end
def check_body(body, node)
modifiers = body.each_child_node(:send).select(&:bare_access_modifier?)
end_range = node.loc.end
modifiers.each do |modifier|
next if same_line?(node, modifier)
check_modifier(modifier, end_range)
end
end
def check_modifier(send_node, end_range)
offset = column_offset_between(send_node.source_range, end_range)
@column_delta = expected_indent_offset - offset
if @column_delta.zero?
correct_style_detected
else
add_offense(send_node) do |corrector|
if offset == unexpected_indent_offset
opposite_style_detected
else
unrecognized_style_detected
end
autocorrect(corrector, send_node)
end
end
end
def message(range)
format(MSG, style: style.capitalize, node: range.source)
end
def expected_indent_offset
style == :outdent ? 0 : configured_indentation_width
end
# An offset that is not expected, but correct if the configuration is
# changed.
def unexpected_indent_offset
configured_indentation_width - expected_indent_offset
end
end
end
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/redundant_line_break.rb | lib/rubocop/cop/layout/redundant_line_break.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks whether certain expressions, e.g. method calls, that could fit
# completely on a single line, are broken up into multiple lines unnecessarily.
#
# @example
# # bad
# foo(
# a,
# b
# )
#
# # good
# foo(a, b)
#
# # bad
# puts 'string that fits on ' \
# 'a single line'
#
# # good
# puts 'string that fits on a single line'
#
# # bad
# things
# .select { |thing| thing.cond? }
# .join('-')
#
# # good
# things.select { |thing| thing.cond? }.join('-')
#
# @example InspectBlocks: false (default)
# # good
# foo(a) do |x|
# puts x
# end
#
# @example InspectBlocks: true
# # bad
# foo(a) do |x|
# puts x
# end
#
# # good
# foo(a) { |x| puts x }
#
class RedundantLineBreak < Base
include CheckAssignment
include CheckSingleLineSuitability
extend AutoCorrector
MSG = 'Redundant line break detected.'
def on_lvasgn(node)
super unless end_with_percent_blank_string?(processed_source)
end
def on_send(node)
# Include "the whole expression".
node = node.parent while node.parent&.send_type? ||
convertible_block?(node) ||
node.parent.is_a?(RuboCop::AST::BinaryOperatorNode)
return unless offense?(node) && !part_of_ignored_node?(node)
register_offense(node)
end
alias on_csend on_send
private
def end_with_percent_blank_string?(processed_source)
processed_source.buffer.source.end_with?("%\n\n")
end
def check_assignment(node, _rhs)
return unless offense?(node)
register_offense(node)
end
def register_offense(node)
add_offense(node) do |corrector|
corrector.replace(node, to_single_line(node.source).strip)
end
ignore_node(node)
end
def offense?(node)
return false unless node.multiline? && suitable_as_single_line?(node)
return require_backslash?(node) if node.operator_keyword?
!index_access_call_chained?(node) && !configured_to_not_be_inspected?(node)
end
def require_backslash?(node)
processed_source.lines[node.loc.operator.line - 1].end_with?('\\')
end
def index_access_call_chained?(node)
return false unless node.send_type? && node.method?(:[])
node.children.first.send_type? && node.children.first.method?(:[])
end
def configured_to_not_be_inspected?(node)
return true if other_cop_takes_precedence?(node)
return false if cop_config['InspectBlocks']
node.any_block_type? || any_descendant?(node, :any_block, &:multiline?)
end
def other_cop_takes_precedence?(node)
single_line_block_chain_enabled? && any_descendant?(node, :any_block) do |block_node|
block_node.parent.send_type? && block_node.parent.loc.dot && !block_node.multiline?
end
end
def single_line_block_chain_enabled?
@config.cop_enabled?('Layout/SingleLineBlockChain')
end
def convertible_block?(node)
return false unless (parent = node.parent)
parent.any_block_type? && node == parent.send_node &&
(node.parenthesized? || !node.arguments?)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/empty_lines_after_module_inclusion.rb | lib/rubocop/cop/layout/empty_lines_after_module_inclusion.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for an empty line after a module inclusion method (`extend`,
# `include` and `prepend`), or a group of them.
#
# @example
# # bad
# class Foo
# include Bar
# attr_reader :baz
# end
#
# # good
# class Foo
# include Bar
#
# attr_reader :baz
# end
#
# # also good - multiple module inclusions grouped together
# class Foo
# extend Bar
# include Baz
# prepend Qux
# end
#
class EmptyLinesAfterModuleInclusion < Base
include RangeHelp
extend AutoCorrector
MSG = 'Add an empty line after module inclusion.'
MODULE_INCLUSION_METHODS = %i[include extend prepend].freeze
RESTRICT_ON_SEND = MODULE_INCLUSION_METHODS
def on_send(node)
return if node.receiver || node.arguments.empty?
return if node.parent&.type?(:send, :any_block)
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 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)
line_empty?(line) || (enable_directive_comment?(line + 1) && line_empty?(line + 1))
end
def enable_directive_comment?(line)
return false unless (comment = processed_source.comment_at_line(line))
DirectiveComment.new(comment).enabled?
end
def line_empty?(line)
processed_source[line].nil? || processed_source[line].blank?
end
def require_empty_line?(node)
return false unless node
!allowed_method?(node)
end
def allowed_method?(node)
node = node.body if node.respond_to?(:modifier_form?) && node.modifier_form?
return false unless node.send_type?
MODULE_INCLUSION_METHODS.include?(node.method_name)
end
def next_line_node(node)
return if node.parent.if_type?
node.right_sibling
end
end
end
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_definition_brace_layout.rb | lib/rubocop/cop/layout/multiline_method_definition_brace_layout.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks that the closing brace in a method definition is either
# on the same line as the last method parameter, or a new line.
#
# When using the `symmetrical` (default) style:
#
# If a method definition's opening brace is on the same line as the
# first parameter of the definition, then the closing brace should be
# on the same line as the last parameter of the definition.
#
# If a method definition's opening brace is on the line above the first
# parameter of the definition, then the closing brace should be on the
# line below the last parameter of the definition.
#
# When using the `new_line` style:
#
# The closing brace of a multi-line method definition must be on the line
# after the last parameter of the definition.
#
# When using the `same_line` style:
#
# The closing brace of a multi-line method definition must be on the same
# line as the last parameter of the definition.
#
# @example EnforcedStyle: symmetrical (default)
# # bad
# def foo(a,
# b
# )
# end
#
# # bad
# def foo(
# a,
# b)
# end
#
# # good
# def foo(a,
# b)
# end
#
# # good
# def foo(
# a,
# b
# )
# end
#
# @example EnforcedStyle: new_line
# # bad
# def foo(
# a,
# b)
# end
#
# # bad
# def foo(a,
# b)
# end
#
# # good
# def foo(a,
# b
# )
# end
#
# # good
# def foo(
# a,
# b
# )
# end
#
# @example EnforcedStyle: same_line
# # bad
# def foo(a,
# b
# )
# end
#
# # bad
# def foo(
# a,
# b
# )
# end
#
# # good
# def foo(
# a,
# b)
# end
#
# # good
# def foo(a,
# b)
# end
class MultilineMethodDefinitionBraceLayout < Base
include MultilineLiteralBraceLayout
extend AutoCorrector
SAME_LINE_MESSAGE = 'Closing method definition brace must be on the ' \
'same line as the last parameter when opening brace is on the same ' \
'line as the first parameter.'
NEW_LINE_MESSAGE = 'Closing method definition brace must be on the ' \
'line after the last parameter when opening brace is on a separate ' \
'line from the first parameter.'
ALWAYS_NEW_LINE_MESSAGE = 'Closing method definition brace must be ' \
'on the line after the last parameter.'
ALWAYS_SAME_LINE_MESSAGE = 'Closing method definition brace must be ' \
'on the same line as the last parameter.'
def on_def(node)
check_brace_layout(node.arguments)
end
alias on_defs on_def
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/space_before_comma.rb | lib/rubocop/cop/layout/space_before_comma.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for comma (`,`) preceded by space.
#
# @example
# # bad
# [1 , 2 , 3]
# a(1 , 2)
# each { |a , b| }
#
# # good
# [1, 2, 3]
# a(1, 2)
# each { |a, b| }
#
class SpaceBeforeComma < Base
include SpaceBeforePunctuation
extend AutoCorrector
def kind(token)
'comma' if token.comma?
end
end
end
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/def_end_alignment.rb | lib/rubocop/cop/layout/def_end_alignment.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks whether the end keywords of method definitions are
# 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 `def`
# keyword is. If it's set to `def`, the `end` shall be aligned with the
# `def` keyword.
#
# @example EnforcedStyleAlignWith: start_of_line (default)
# # bad
#
# private def foo
# end
#
# # good
#
# private def foo
# end
#
# @example EnforcedStyleAlignWith: def
# # bad
#
# private def foo
# end
#
# # good
#
# private def foo
# end
class DefEndAlignment < Base
include EndKeywordAlignment
include RangeHelp
extend AutoCorrector
MSG = '`end` at %d, %d is not aligned with `%s` at %d, %d.'
def on_def(node)
check_end_kw_in_node(node)
end
alias on_defs on_def
def on_send(node)
return unless node.def_modifier?
method_def = node.each_descendant(:any_def).first
expr = node.source_range
line_start = range_between(expr.begin_pos, method_def.loc.keyword.end_pos)
align_with = { def: method_def.loc.keyword, start_of_line: line_start }
check_end_kw_alignment(method_def, align_with)
ignore_node(method_def) # Don't check the same `end` again.
end
private
def autocorrect(corrector, node)
if style == :start_of_line && node.parent&.send_type?
AlignmentCorrector.align_end(corrector, processed_source, node, node.parent)
else
AlignmentCorrector.align_end(corrector, processed_source, node, 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/first_argument_indentation.rb | lib/rubocop/cop/layout/first_argument_indentation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks the indentation of the first argument in a method call.
# Arguments after the first one are checked by `Layout/ArgumentAlignment`,
# not by this cop.
#
# For indenting the first parameter of method _definitions_, check out
# `Layout/FirstParameterIndentation`.
#
# This cop will respect `Layout/ArgumentAlignment` and will not work when
# `EnforcedStyle: with_fixed_indentation` is specified for `Layout/ArgumentAlignment`.
#
# @example
#
# # bad
# some_method(
# first_param,
# second_param)
#
# foo = some_method(
# first_param,
# second_param)
#
# foo = some_method(nested_call(
# nested_first_param),
# second_param)
#
# foo = some_method(
# nested_call(
# nested_first_param),
# second_param)
#
# some_method nested_call(
# nested_first_param),
# second_param
#
# @example EnforcedStyle: special_for_inner_method_call_in_parentheses (default)
# # Same as `special_for_inner_method_call` except that the special rule
# # only applies if the outer method call encloses its arguments in
# # parentheses.
#
# # good
# some_method(
# first_param,
# second_param)
#
# foo = some_method(
# first_param,
# second_param)
#
# foo = some_method(nested_call(
# nested_first_param),
# second_param)
#
# foo = some_method(
# nested_call(
# nested_first_param),
# second_param)
#
# some_method nested_call(
# nested_first_param),
# second_param
#
# @example EnforcedStyle: consistent
# # The first argument should always be indented one step more than the
# # preceding line.
#
# # good
# some_method(
# first_param,
# second_param)
#
# foo = some_method(
# first_param,
# second_param)
#
# foo = some_method(nested_call(
# nested_first_param),
# second_param)
#
# foo = some_method(
# nested_call(
# nested_first_param),
# second_param)
#
# some_method nested_call(
# nested_first_param),
# second_param
#
# @example EnforcedStyle: consistent_relative_to_receiver
# # The first argument should always be indented one level relative to
# # the parent that is receiving the argument
#
# # good
# some_method(
# first_param,
# second_param)
#
# foo = some_method(
# first_param,
# second_param)
#
# foo = some_method(nested_call(
# nested_first_param),
# second_param)
#
# foo = some_method(
# nested_call(
# nested_first_param),
# second_param)
#
# some_method nested_call(
# nested_first_param),
# second_params
#
# @example EnforcedStyle: special_for_inner_method_call
# # The first argument should normally be indented one step more than
# # the preceding line, but if it's an argument for a method call that
# # is itself an argument in a method call, then the inner argument
# # should be indented relative to the inner method.
#
# # good
# some_method(
# first_param,
# second_param)
#
# foo = some_method(
# first_param,
# second_param)
#
# foo = some_method(nested_call(
# nested_first_param),
# second_param)
#
# foo = some_method(
# nested_call(
# nested_first_param),
# second_param)
#
# some_method nested_call(
# nested_first_param),
# second_param
#
class FirstArgumentIndentation < Base
include Alignment
include ConfigurableEnforcedStyle
include RangeHelp
extend AutoCorrector
MSG = 'Indent the first argument one step more than %<base>s.'
def on_send(node)
return unless should_check?(node)
return if same_line?(node, node.first_argument)
return if enforce_first_argument_with_fixed_indentation? &&
!enable_layout_first_method_argument_line_break?
indent = base_indentation(node) + configured_indentation_width
check_alignment([node.first_argument], indent)
end
alias on_csend on_send
alias on_super on_send
private
def should_check?(node)
node.arguments? && !bare_operator?(node) && !node.setter_method?
end
def autocorrect(corrector, node)
AlignmentCorrector.correct(corrector, processed_source, node, column_delta)
end
def bare_operator?(node)
node.operator_method? && !node.dot?
end
def message(arg_node)
return 'Bad indentation of the first argument.' unless arg_node
send_node = arg_node.parent
text = base_range(send_node, arg_node).source.strip
base = if !text.include?("\n") && special_inner_call_indentation?(send_node)
"`#{text}`"
elsif comment_line?(text.lines.reverse_each.first)
'the start of the previous line (not counting the comment)'
else
'the start of the previous line'
end
format(MSG, base: base)
end
def base_indentation(node)
if special_inner_call_indentation?(node)
column_of(base_range(node, node.first_argument))
else
previous_code_line(node.first_argument.first_line) =~ /\S/
end
end
def special_inner_call_indentation?(node)
return false if style == :consistent
return true if style == :consistent_relative_to_receiver
parent = node.parent
return false unless eligible_method_call?(parent)
return false if !parent.parenthesized? &&
style == :special_for_inner_method_call_in_parentheses
# The node must begin inside the parent, otherwise node is the first
# part of a chained method call.
node.source_range.begin_pos > parent.source_range.begin_pos
end
# @!method eligible_method_call?(node)
def_node_matcher :eligible_method_call?, <<~PATTERN
(send _ !:[]= ...)
PATTERN
def base_range(send_node, arg_node)
parent = send_node.parent
start_node = if parent&.type?(:splat, :kwsplat)
send_node.parent
else
send_node
end
range_between(start_node.source_range.begin_pos, arg_node.source_range.begin_pos)
end
# Returns the column of the given range. For single line ranges, this
# is simple. For ranges with line breaks, we look a the last code line.
def column_of(range)
source = range.source.strip
if source.include?("\n")
previous_code_line(range.line + source.count("\n") + 1) =~ /\S/
else
display_column(range)
end
end
# Takes the line number of a given code line and returns a string
# containing the previous line that's not a comment line or a blank
# line.
def previous_code_line(line_number)
line = ''
while line.blank? || comment_lines.include?(line_number)
line_number -= 1
line = processed_source.lines[line_number - 1]
end
line
end
def comment_lines
@comment_lines ||=
processed_source
.comments
.select { |c| begins_its_line?(c.source_range) }
.map { |c| c.loc.line }
end
def on_new_investigation
@comment_lines = nil
end
def enforce_first_argument_with_fixed_indentation?
argument_alignment_config = config.for_enabled_cop('Layout/ArgumentAlignment')
argument_alignment_config['EnforcedStyle'] == 'with_fixed_indentation'
end
def enable_layout_first_method_argument_line_break?
config.cop_enabled?('Layout/FirstMethodArgumentLineBreak')
end
end
end
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_parameter_line_breaks.rb | lib/rubocop/cop/layout/multiline_method_parameter_line_breaks.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Ensures that each parameter in a multi-line method definition
# starts on a separate line.
#
# NOTE: This cop does not move the first argument, if you want that to
# be on a separate line, see `Layout/FirstMethodParameterLineBreak`.
#
# @example
#
# # bad
# def foo(a, b,
# c
# )
# end
#
# # good
# def foo(
# a,
# b,
# c
# )
# end
#
# # good
# def foo(
# a,
# b = {
# foo: "bar",
# }
# )
# end
#
# # good
# def foo(a, b, c)
# end
#
# @example AllowMultilineFinalElement: false (default)
#
# # bad
# def foo(a, b = {
# foo: "bar",
# })
# end
#
# @example AllowMultilineFinalElement: true
#
# # good
# def foo(a, b = {
# foo: "bar",
# })
# end
#
class MultilineMethodParameterLineBreaks < Base
include MultilineElementLineBreaks
extend AutoCorrector
MSG = 'Each parameter in a multi-line method definition must start on a separate line.'
def on_def(node)
return if node.arguments.empty?
check_line_breaks(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/first_array_element_indentation.rb | lib/rubocop/cop/layout/first_array_element_indentation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks the indentation of the first element in an array literal
# where the opening bracket and the first element are on separate lines.
# The other elements' indentations are handled by `Layout/ArrayAlignment` cop.
#
# This cop will respect `Layout/ArrayAlignment` and will not work when
# `EnforcedStyle: with_fixed_indentation` is specified for `Layout/ArrayAlignment`.
#
# By default, array literals that are arguments in a method call with
# parentheses, and where the opening square bracket of the array is on the
# same line as the opening parenthesis of the method call, shall have
# their first element indented one step (two spaces) more than the
# position inside the opening parenthesis.
#
# Other array literals shall have their first element indented one step
# more than the start of the line where the opening square bracket is.
#
# This default style is called 'special_inside_parentheses'. Alternative
# styles are 'consistent' and 'align_brackets'. Here are examples:
#
# @example EnforcedStyle: special_inside_parentheses (default)
# # The `special_inside_parentheses` style enforces that the first
# # element in an array literal where the opening bracket and first
# # element are on separate lines is indented one step (two spaces) more
# # than the position inside the opening parenthesis.
#
# # bad
# array = [
# :value
# ]
# and_in_a_method_call([
# :no_difference
# ])
#
# # good
# array = [
# :value
# ]
# but_in_a_method_call([
# :its_like_this
# ])
#
# @example EnforcedStyle: consistent
# # The `consistent` style enforces that the first element in an array
# # literal where the opening bracket and the first element are on
# # separate lines is indented the same as an array literal which is not
# # defined inside a method call.
#
# # bad
# array = [
# :value
# ]
# but_in_a_method_call([
# :its_like_this
# ])
#
# # good
# array = [
# :value
# ]
# and_in_a_method_call([
# :no_difference
# ])
#
# @example EnforcedStyle: align_brackets
# # The `align_brackets` style enforces that the opening and closing
# # brackets are indented to the same position.
#
# # bad
# and_now_for_something = [
# :completely_different
# ]
#
# # good
# and_now_for_something = [
# :completely_different
# ]
class FirstArrayElementIndentation < Base
include Alignment
include ConfigurableEnforcedStyle
include MultilineElementIndentation
extend AutoCorrector
MSG = 'Use %<configured_indentation_width>d spaces for indentation ' \
'in an array, relative to %<base_description>s.'
def on_array(node)
return if style != :consistent && enforce_first_argument_with_fixed_indentation?
check(node, nil) if node.loc.begin
end
def on_send(node)
return if style != :consistent && enforce_first_argument_with_fixed_indentation?
each_argument_node(node, :array) do |array_node, left_parenthesis|
check(array_node, left_parenthesis)
end
end
alias on_csend on_send
private
def autocorrect(corrector, node)
AlignmentCorrector.correct(corrector, processed_source, node, @column_delta)
end
def brace_alignment_style
:align_brackets
end
def check(array_node, left_parenthesis)
return if ignored_node?(array_node)
left_bracket = array_node.loc.begin
first_elem = array_node.values.first
if first_elem
return if same_line?(first_elem, left_bracket)
check_first(first_elem, left_bracket, left_parenthesis, 0)
end
check_right_bracket(array_node.loc.end, first_elem, left_bracket, left_parenthesis)
end
def check_right_bracket(right_bracket, first_elem, left_bracket, left_parenthesis)
# if the right bracket is on the same line as the last value, accept
return if /\S/.match?(right_bracket.source_line[0...right_bracket.column])
expected_column, indent_base_type = indent_base(left_bracket, first_elem,
left_parenthesis)
@column_delta = expected_column - right_bracket.column
return if @column_delta.zero?
msg = message_for_right_bracket(indent_base_type)
add_offense(right_bracket, message: msg) do |corrector|
autocorrect(corrector, right_bracket)
end
end
# Returns the description of what the correct indentation is based on.
def base_description(indent_base_type)
case indent_base_type
when :left_brace_or_bracket
'the position of the opening bracket'
when :first_column_after_left_parenthesis
'the first position after the preceding left parenthesis'
when :parent_hash_key
'the parent hash key'
else
'the start of the line where the left square bracket is'
end
end
def message(base_description)
format(
MSG,
configured_indentation_width: configured_indentation_width,
base_description: base_description
)
end
def message_for_right_bracket(indent_base_type)
case indent_base_type
when :left_brace_or_bracket
'Indent the right bracket the same as the left bracket.'
when :first_column_after_left_parenthesis
'Indent the right bracket the same as the first position ' \
'after the preceding left parenthesis.'
when :parent_hash_key
'Indent the right bracket the same as the parent hash key.' \
else
'Indent the right bracket the same as the start of the line ' \
'where the left bracket is.'
end
end
def enforce_first_argument_with_fixed_indentation?
argument_alignment_config = config.for_enabled_cop('Layout/ArrayAlignment')
argument_alignment_config['EnforcedStyle'] == 'with_fixed_indentation'
end
end
end
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_begin_body.rb | lib/rubocop/cop/layout/empty_lines_around_begin_body.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks if empty lines exist around the bodies of begin-end
# blocks.
#
# @example
#
# # bad
# begin
#
# # ...
#
# end
#
# # good
# begin
# # ...
# end
#
class EmptyLinesAroundBeginBody < Base
include EmptyLinesAroundBody
extend AutoCorrector
KIND = '`begin`'
def on_kwbegin(node)
check(node, nil)
end
private
def 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/layout/space_after_method_name.rb | lib/rubocop/cop/layout/space_after_method_name.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for space between a method name and a left parenthesis in defs.
#
# @example
#
# # bad
# def func (x) end
# def method= (y) end
#
# # good
# def func(x) end
# def method=(y) end
class SpaceAfterMethodName < Base
include RangeHelp
extend AutoCorrector
MSG = 'Do not put a space between a method name and the opening parenthesis.'
def on_def(node)
args = node.arguments
return unless args.parenthesized_call?
expr = args.source_range
pos_before_left_paren = range_between(expr.begin_pos - 1, expr.begin_pos)
return unless pos_before_left_paren.source.start_with?(' ')
add_offense(pos_before_left_paren) do |corrector|
corrector.remove(pos_before_left_paren)
end
end
alias on_defs on_def
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/multiline_hash_key_line_breaks.rb | lib/rubocop/cop/layout/multiline_hash_key_line_breaks.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Ensures that each key in a multi-line hash
# starts on a separate line.
#
# @example
#
# # bad
# {
# a: 1, b: 2,
# c: 3
# }
#
# # good
# {
# a: 1,
# b: 2,
# c: 3
# }
#
# # good
# {
# a: 1,
# b: {
# c: 3,
# }
# }
#
# @example AllowMultilineFinalElement: false (default)
#
# # bad
# { a: 1, b: {
# c: 3,
# }}
#
# @example AllowMultilineFinalElement: true
#
# # good
# { a: 1, b: {
# c: 3,
# }}
#
class MultilineHashKeyLineBreaks < Base
include MultilineElementLineBreaks
extend AutoCorrector
MSG = 'Each key in a multi-line hash must start on a separate line.'
def on_hash(node)
# This cop only deals with hashes wrapped by a set of curly
# braces like {foo: 1}. That is, not a kwargs hashes.
# Layout/MultilineMethodArgumentLineBreaks handles those.
return unless starts_with_curly_brace?(node)
return unless node.loc.begin
check_line_breaks(node, node.children, ignore_last: ignore_last_element?)
end
private
def starts_with_curly_brace?(node)
node.loc.begin
end
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_before_semicolon.rb | lib/rubocop/cop/layout/space_before_semicolon.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for semicolon (`;`) preceded by space.
#
# @example
# # bad
# x = 1 ; y = 2
#
# # good
# x = 1; y = 2
class SpaceBeforeSemicolon < Base
include SpaceBeforePunctuation
extend AutoCorrector
def kind(token)
'semicolon' if token.semicolon?
end
end
end
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_block_braces.rb | lib/rubocop/cop/layout/space_inside_block_braces.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks that block braces have or don't have surrounding space inside
# them on configuration. For blocks taking parameters, it checks that the
# left brace has or doesn't have trailing space depending on
# configuration.
#
# @example EnforcedStyle: space (default)
# # The `space` style enforces that block braces have
# # surrounding space.
#
# # bad
# some_array.each {puts e}
#
# # good
# some_array.each { puts e }
#
# @example EnforcedStyle: no_space
# # The `no_space` style enforces that block braces don't
# # have surrounding space.
#
# # bad
# some_array.each { puts e }
#
# # good
# some_array.each {puts e}
#
#
# @example EnforcedStyleForEmptyBraces: no_space (default)
# # The `no_space` EnforcedStyleForEmptyBraces style enforces that
# # block braces don't have a space in between when empty.
#
# # bad
# some_array.each { }
# some_array.each { }
# some_array.each { }
#
# # good
# some_array.each {}
#
# @example EnforcedStyleForEmptyBraces: space
# # The `space` EnforcedStyleForEmptyBraces style enforces that
# # block braces have at least a space in between when empty.
#
# # bad
# some_array.each {}
#
# # good
# some_array.each { }
# some_array.each { }
# some_array.each { }
#
#
# @example SpaceBeforeBlockParameters: true (default)
# # The SpaceBeforeBlockParameters style set to `true` enforces that
# # there is a space between `{` and `|`. Overrides `EnforcedStyle`
# # if there is a conflict.
#
# # bad
# [1, 2, 3].each {|n| n * 2 }
#
# # good
# [1, 2, 3].each { |n| n * 2 }
#
# @example SpaceBeforeBlockParameters: false
# # The SpaceBeforeBlockParameters style set to `false` enforces that
# # there is no space between `{` and `|`. Overrides `EnforcedStyle`
# # if there is a conflict.
#
# # bad
# [1, 2, 3].each { |n| n * 2 }
#
# # good
# [1, 2, 3].each {|n| n * 2 }
#
class SpaceInsideBlockBraces < Base
include ConfigurableEnforcedStyle
include SurroundingSpace
include RangeHelp
extend AutoCorrector
def self.autocorrect_incompatible_with
[Style::BlockDelimiters]
end
def on_block(node)
return if node.keywords?
# Do not register an offense for multi-line empty braces. That means
# preventing autocorrection to single-line empty braces. It will
# conflict with autocorrection by `Layout/SpaceInsideBlockBraces` cop
# if autocorrected to a single-line empty braces.
# See: https://github.com/rubocop/rubocop/issues/7363
return if node.body.nil? && node.multiline?
left_brace = node.loc.begin
right_brace = node.loc.end
check_inside(node, left_brace, right_brace)
end
alias on_numblock on_block
alias on_itblock on_block
private
def check_inside(node, left_brace, right_brace)
if left_brace.end_pos == right_brace.begin_pos
adjacent_braces(left_brace, right_brace)
else
range = range_between(left_brace.end_pos, right_brace.begin_pos)
inner = range.source
if /\S/.match?(inner)
braces_with_contents_inside(node, inner)
elsif style_for_empty_braces == :no_space
offense(range.begin_pos, range.end_pos,
'Space inside empty braces detected.',
'EnforcedStyleForEmptyBraces')
end
end
end
def adjacent_braces(left_brace, right_brace)
return if style_for_empty_braces != :space
offense(left_brace.begin_pos, right_brace.end_pos,
'Space missing inside empty braces.',
'EnforcedStyleForEmptyBraces')
end
def braces_with_contents_inside(node, inner)
args_delimiter = node.arguments.loc.begin if node.block_type? # Can be ( | or nil.
check_left_brace(inner, node.loc.begin, args_delimiter)
check_right_brace(node, inner, node.loc.begin, node.loc.end, node.single_line?)
end
def check_left_brace(inner, left_brace, args_delimiter)
if /\A\S/.match?(inner)
no_space_inside_left_brace(left_brace, args_delimiter)
else
space_inside_left_brace(left_brace, args_delimiter)
end
end
def check_right_brace(node, inner, left_brace, right_brace, single_line)
if single_line && /\S$/.match?(inner)
no_space(right_brace.begin_pos, right_brace.end_pos, 'Space missing inside }.')
else
column = node.source_range.column
return if multiline_block?(left_brace, right_brace) &&
aligned_braces?(inner, right_brace, column)
space_inside_right_brace(inner, right_brace, column)
end
end
def multiline_block?(left_brace, right_brace)
left_brace.first_line != right_brace.first_line
end
def aligned_braces?(inner, right_brace, column)
column == right_brace.column || column == inner_last_space_count(inner)
end
def inner_last_space_count(inner)
inner.split("\n").last.count(' ')
end
def no_space_inside_left_brace(left_brace, args_delimiter)
if pipe?(args_delimiter)
if left_brace.end_pos == args_delimiter.begin_pos &&
cop_config['SpaceBeforeBlockParameters']
offense(left_brace.begin_pos, args_delimiter.end_pos,
'Space between { and | missing.')
else
correct_style_detected
end
else
# We indicate the position after the left brace. Otherwise it's
# difficult to distinguish between space missing to the left and to
# the right of the brace in autocorrect.
no_space(left_brace.end_pos, left_brace.end_pos + 1, 'Space missing inside {.')
end
end
def space_inside_left_brace(left_brace, args_delimiter)
if pipe?(args_delimiter)
if cop_config['SpaceBeforeBlockParameters']
correct_style_detected
else
offense(left_brace.end_pos, args_delimiter.begin_pos,
'Space between { and | detected.')
end
else
brace_with_space = range_with_surrounding_space(left_brace, side: :right)
space(brace_with_space.begin_pos + 1, brace_with_space.end_pos,
'Space inside { detected.')
end
end
def pipe?(args_delimiter)
args_delimiter&.is?('|')
end
def space_inside_right_brace(inner, right_brace, column)
brace_with_space = range_with_surrounding_space(right_brace, side: :left)
begin_pos = brace_with_space.begin_pos
end_pos = brace_with_space.end_pos - 1
if brace_with_space.source.match?(/\R/)
begin_pos = end_pos - (right_brace.column - column)
end
if inner.end_with?(']')
end_pos -= 1
begin_pos = end_pos - (inner_last_space_count(inner) - column)
end
space(begin_pos, end_pos, 'Space inside } detected.')
end
def no_space(begin_pos, end_pos, msg)
if style == :space
offense(begin_pos, end_pos, msg)
else
correct_style_detected
end
end
def space(begin_pos, end_pos, msg)
if style == :no_space
offense(begin_pos, end_pos, msg)
else
correct_style_detected
end
end
def offense(begin_pos, end_pos, msg, style_param = 'EnforcedStyle')
return if begin_pos > end_pos
range = range_between(begin_pos, end_pos)
add_offense(range, message: msg) do |corrector|
case range.source
when /\s/ then corrector.remove(range)
when '{}' then corrector.replace(range, '{ }')
when '{|' then corrector.replace(range, '{ |')
else corrector.insert_before(range, ' ')
end
opposite_style_detected if style_param == 'EnforcedStyle'
end
end
def style_for_empty_braces
case cop_config['EnforcedStyleForEmptyBraces']
when 'space' then :space
when 'no_space' then :no_space
else raise 'Unknown EnforcedStyleForEmptyBraces selected!'
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/space_after_not.rb | lib/rubocop/cop/layout/space_after_not.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for space after `!`.
#
# @example
# # bad
# ! something
#
# # good
# !something
class SpaceAfterNot < Base
include RangeHelp
extend AutoCorrector
MSG = 'Do not leave space between `!` and its argument.'
RESTRICT_ON_SEND = %i[!].freeze
def on_send(node)
return unless node.prefix_bang? && whitespace_after_operator?(node)
add_offense(node) do |corrector|
corrector.remove(
range_between(node.loc.selector.end_pos, node.receiver.source_range.begin_pos)
)
end
end
private
def whitespace_after_operator?(node)
node.receiver.source_range.begin_pos - node.source_range.begin_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/comment_indentation.rb | lib/rubocop/cop/layout/comment_indentation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks the indentation of comments.
#
# @example
# # bad
# # comment here
# def method_name
# end
#
# # comment here
# a = 'hello'
#
# # yet another comment
# if true
# true
# end
#
# # good
# # comment here
# def method_name
# end
#
# # comment here
# a = 'hello'
#
# # yet another comment
# if true
# true
# end
#
# @example AllowForAlignment: false (default)
# # bad
# a = 1 # A really long comment
# # spanning two lines.
#
# # good
# # A really long comment spanning one line.
# a = 1
#
# @example AllowForAlignment: true
# # good
# a = 1 # A really long comment
# # spanning two lines.
class CommentIndentation < Base
include Alignment
extend AutoCorrector
MSG = 'Incorrect indentation detected (column %<column>d ' \
'instead of %<correct_comment_indentation>d).'
def on_new_investigation
processed_source.comments.each_with_index { |comment, ix| check(comment, ix) }
end
private
def autocorrect(corrector, comment)
autocorrect_preceding_comments(corrector, comment)
autocorrect_one(corrector, comment)
end
# Corrects all comment lines that occur immediately before the given
# comment and have the same indentation. This is to avoid a long chain
# of correcting, saving the file, parsing and inspecting again, and
# then correcting one more line, and so on.
def autocorrect_preceding_comments(corrector, comment)
comments = processed_source.comments
index = comments.index(comment)
comments[0..index]
.reverse_each
.each_cons(2)
.take_while { |below, above| should_correct?(above, below) }
.map { |_, above| autocorrect_one(corrector, above) }
end
def should_correct?(preceding_comment, reference_comment)
loc = preceding_comment.loc
ref_loc = reference_comment.loc
loc.line == ref_loc.line - 1 && loc.column == ref_loc.column
end
def autocorrect_one(corrector, comment)
AlignmentCorrector.correct(corrector, processed_source, comment, @column_delta)
end
def check(comment, comment_index)
return unless own_line_comment?(comment)
next_line = line_after_comment(comment)
correct_comment_indentation = correct_indentation(next_line)
column = comment.loc.column
@column_delta = correct_comment_indentation - column
return if @column_delta.zero?
if two_alternatives?(next_line)
# Try the other
correct_comment_indentation += configured_indentation_width
# We keep @column_delta unchanged so that autocorrect changes to
# the preferred style of aligning the comment with the keyword.
return if column == correct_comment_indentation
end
return if correctly_aligned_with_preceding_comment?(comment_index, column)
add_offense(comment, message: message(column, correct_comment_indentation)) do |corrector|
autocorrect(corrector, comment)
end
end
# Returns true if:
# a) the cop is configured to allow extra indentation for alignment, and
# b) the currently inspected comment is aligned with the nearest preceding end-of-line
# comment.
def correctly_aligned_with_preceding_comment?(comment_index, column)
return false unless cop_config['AllowForAlignment']
processed_source.comments[0...comment_index].reverse_each do |other_comment|
return other_comment.loc.column == column unless own_line_comment?(other_comment)
end
false
end
def message(column, correct_comment_indentation)
format(MSG, column: column, correct_comment_indentation: correct_comment_indentation)
end
def own_line_comment?(comment)
own_line = processed_source.lines[comment.loc.line - 1]
/\A\s*#/.match?(own_line)
end
def line_after_comment(comment)
lines = processed_source.lines
lines[comment.loc.line..].find { |line| !line.blank? }
end
def correct_indentation(next_line)
return 0 unless next_line
indentation_of_next_line = next_line =~ /\S/
indentation_of_next_line + if less_indented?(next_line)
configured_indentation_width
else
0
end
end
def less_indented?(line)
rule = config.for_cop('Layout/AccessModifierIndentation')['EnforcedStyle'] == 'outdent'
access_modifier = 'private|protected|public'
/\A\s*(end\b|[)}\]])/.match?(line) || (rule && /\A\s*(#{access_modifier})\b/.match?(line))
end
def two_alternatives?(line)
/^\s*(else|elsif|when|in|rescue|ensure)\b/.match?(line)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/space_around_keyword.rb | lib/rubocop/cop/layout/space_around_keyword.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks the spacing around the keywords.
#
# @example
#
# # bad
# something 'test'do|x|
# end
#
# while(something)
# end
#
# something = 123if test
#
# return(foo + bar)
#
# # good
# something 'test' do |x|
# end
#
# while (something)
# end
#
# something = 123 if test
#
# return (foo + bar)
#
class SpaceAroundKeyword < Base
extend AutoCorrector
MSG_BEFORE = 'Space before keyword `%<range>s` is missing.'
MSG_AFTER = 'Space after keyword `%<range>s` is missing.'
DO = 'do'
SAFE_NAVIGATION = '&.'
NAMESPACE_OPERATOR = '::'
ACCEPT_LEFT_PAREN = %w[break defined? next not rescue super yield].freeze
ACCEPT_LEFT_SQUARE_BRACKET = %w[super yield].freeze
ACCEPT_NAMESPACE_OPERATOR = 'super'
RESTRICT_ON_SEND = %i[!].freeze
def on_and(node)
check(node, [:operator].freeze) if node.keyword?
end
def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
check(node, %i[begin end].freeze)
end
def on_break(node)
check(node, [:keyword].freeze)
end
def on_case(node)
check(node, %i[keyword else].freeze)
end
def on_case_match(node)
check(node, %i[keyword else].freeze)
end
def on_ensure(node)
check(node, [:keyword].freeze)
end
def on_for(node)
check(node, %i[begin end].freeze)
end
def on_if(node)
check(node, %i[keyword else begin end].freeze, 'then')
end
def on_if_guard(node)
check(node, [:keyword].freeze)
end
def on_in_pattern(node)
check(node, [:keyword].freeze)
end
def on_kwbegin(node)
check(node, %i[begin end].freeze, nil)
end
# Handle one-line pattern matching syntax (`in`) with `Parser::Ruby27`.
def on_match_pattern(node)
return if target_ruby_version >= 3.0
check(node, [:operator].freeze)
end
# Handle one-line pattern matching syntax (`in`) with `Parser::Ruby30`.
def on_match_pattern_p(node)
check(node, [:operator].freeze)
end
def on_next(node)
check(node, [:keyword].freeze)
end
def on_or(node)
check(node, [:operator].freeze) if node.keyword?
end
def on_postexe(node)
check(node, [:keyword].freeze)
end
def on_preexe(node)
check(node, [:keyword].freeze)
end
def on_resbody(node)
check(node, [:keyword].freeze)
end
def on_rescue(node)
check(node, [:else].freeze)
end
def on_return(node)
check(node, [:keyword].freeze)
end
def on_send(node)
check(node, [:selector].freeze) if node.prefix_not?
end
def on_super(node)
check(node, [:keyword].freeze)
end
def on_zsuper(node)
check(node, [:keyword].freeze)
end
def on_unless_guard(node)
check(node, [:keyword].freeze)
end
def on_until(node)
check(node, %i[begin end keyword].freeze)
end
def on_when(node)
check(node, [:keyword].freeze)
end
def on_while(node)
check(node, %i[begin end keyword].freeze)
end
def on_yield(node)
check(node, [:keyword].freeze)
end
def on_defined?(node)
check(node, [:keyword].freeze)
end
private
def check(node, locations, begin_keyword = DO)
locations.each do |loc|
next unless node.loc?(loc)
range = node.loc.public_send(loc)
next unless range
case loc
when :begin then check_begin(node, range, begin_keyword)
when :end then check_end(node, range, begin_keyword)
else check_keyword(node, range)
end
end
end
def check_begin(node, range, begin_keyword)
return if begin_keyword && !range.is?(begin_keyword)
check_keyword(node, range)
end
def check_end(node, range, begin_keyword)
return if begin_keyword == DO && !do?(node)
return unless space_before_missing?(range)
add_offense(range, message: format(MSG_BEFORE, range: range.source)) do |corrector|
corrector.insert_before(range, ' ')
end
end
def do?(node)
node.loc.begin&.is?(DO)
end
def check_keyword(node, range)
if space_before_missing?(range) && !preceded_by_operator?(node, range)
add_offense(range, message: format(MSG_BEFORE, range: range.source)) do |corrector|
corrector.insert_before(range, ' ')
end
end
return unless space_after_missing?(range)
add_offense(range, message: format(MSG_AFTER, range: range.source)) do |corrector|
corrector.insert_after(range, ' ')
end
end
def space_before_missing?(range)
pos = range.begin_pos - 1
return false if pos.negative?
!/[\s(|{\[;,*=]/.match?(range.source_buffer.source[pos])
end
def space_after_missing?(range)
pos = range.end_pos
char = range.source_buffer.source[pos]
return false if accepted_opening_delimiter?(range, char)
return false if safe_navigation_call?(range, pos)
return false if accept_namespace_operator?(range) && namespace_operator?(range, pos)
!/[\s;,#\\)}\].]/.match?(char)
end
def accepted_opening_delimiter?(range, char)
return true unless char
(accept_left_square_bracket?(range) && char == '[') ||
(accept_left_parenthesis?(range) && char == '(')
end
def accept_left_parenthesis?(range)
ACCEPT_LEFT_PAREN.include?(range.source)
end
def accept_left_square_bracket?(range)
ACCEPT_LEFT_SQUARE_BRACKET.include?(range.source)
end
def accept_namespace_operator?(range)
range.source == ACCEPT_NAMESPACE_OPERATOR
end
def safe_navigation_call?(range, pos)
range.source_buffer.source[pos, 2].start_with?(SAFE_NAVIGATION)
end
def namespace_operator?(range, pos)
range.source_buffer.source[pos, 2].start_with?(NAMESPACE_OPERATOR)
end
def preceded_by_operator?(node, _range)
# regular dotted method calls bind more tightly than operators
# so we need to climb up the AST past them
node.each_ancestor do |ancestor|
return true if ancestor.operator_keyword? || ancestor.range_type?
return false unless ancestor.send_type?
return true if ancestor.operator_method?
end
false
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/initial_indentation.rb | lib/rubocop/cop/layout/initial_indentation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for indentation of the first non-blank non-comment
# line in a file.
#
# @example
# # bad
# class A
# def foo; end
# end
#
# # good
# class A
# def foo; end
# end
#
class InitialIndentation < Base
include RangeHelp
extend AutoCorrector
MSG = 'Indentation of first line in file detected.'
def on_new_investigation
space_before(first_token) do |space|
add_offense(first_token.pos) do |corrector|
corrector.remove(space)
end
end
end
private
def first_token
processed_source.tokens.find { |t| !t.text.start_with?('#') }
end
def space_before(token)
return unless token
return if token.column.zero?
space_range = range_with_surrounding_space(token.pos, side: :left, newlines: false)
# If the file starts with a byte order mark (BOM), the column can be
# non-zero, but then we find out here if there's no space to the left
# of the first token.
return if space_range == token.pos
yield range_between(space_range.begin_pos, token.begin_pos)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/empty_lines_around_access_modifier.rb | lib/rubocop/cop/layout/empty_lines_around_access_modifier.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Access modifiers should be surrounded by blank lines.
#
# @example EnforcedStyle: around (default)
#
# # bad
# class Foo
# def bar; end
# private
# def baz; end
# end
#
# # good
# class Foo
# def bar; end
#
# private
#
# def baz; end
# end
#
# @example EnforcedStyle: only_before
#
# # bad
# class Foo
# def bar; end
# private
# def baz; end
# end
#
# # good
# class Foo
# def bar; end
#
# private
# def baz; end
# end
#
class EmptyLinesAroundAccessModifier < Base
include ConfigurableEnforcedStyle
include RangeHelp
extend AutoCorrector
MSG_AFTER = 'Keep a blank line after `%<modifier>s`.'
MSG_BEFORE_AND_AFTER = 'Keep a blank line before and after `%<modifier>s`.'
MSG_BEFORE_FOR_ONLY_BEFORE = 'Keep a blank line before `%<modifier>s`.'
MSG_AFTER_FOR_ONLY_BEFORE = 'Remove a blank line after `%<modifier>s`.'
RESTRICT_ON_SEND = %i[public protected private module_function].freeze
def initialize(config = nil, options = nil)
super
@block_line = nil
end
def on_class(node)
@class_or_module_def_first_line = if node.parent_class
node.parent_class.first_line
else
node.source_range.first_line
end
@class_or_module_def_last_line = node.source_range.last_line
end
def on_module(node)
@class_or_module_def_first_line = node.source_range.first_line
@class_or_module_def_last_line = node.source_range.last_line
end
def on_sclass(node)
@class_or_module_def_first_line = node.identifier.source_range.first_line
@class_or_module_def_last_line = node.source_range.last_line
end
def on_block(node)
@block_line = node.source_range.first_line
end
alias on_numblock on_block
alias on_itblock on_block
def on_send(node)
return unless node.bare_access_modifier? && !node.block_literal?
return if same_line?(node, node.right_sibling)
return if expected_empty_lines?(node)
message = message(node)
add_offense(node, message: message) do |corrector|
line = range_by_whole_lines(node.source_range)
corrector.insert_before(line, "\n") if should_insert_line_before?(node)
correct_next_line_if_denied_style(corrector, node, line)
end
end
private
def expected_empty_lines?(node)
case style
when :around
return true if empty_lines_around?(node)
when :only_before
return true if allowed_only_before_style?(node)
end
false
end
def allowed_only_before_style?(node)
if node.special_modifier?
return true if processed_source[node.last_line] == 'end'
return false if next_line_empty_and_exists?(node.last_line)
end
previous_line_empty?(node.first_line)
end
def correct_next_line_if_denied_style(corrector, node, line)
return unless should_insert_line_after?(node)
case style
when :around
corrector.insert_after(line, "\n") unless next_line_empty?(node.last_line)
when :only_before
if next_line_empty_and_exists?(node.last_line)
range = next_empty_line_range(node)
corrector.remove(range)
end
end
end
def previous_line_ignoring_comments(processed_source, send_line)
processed_source[0..(send_line - 2)].reverse.find { |line| !comment_line?(line) }
end
def previous_line_empty?(send_line)
previous_line = previous_line_ignoring_comments(processed_source, send_line)
return true unless previous_line
block_start?(send_line) || class_def?(send_line) || previous_line.blank?
end
def next_line_empty?(last_send_line)
next_line = processed_source[last_send_line]
body_end?(last_send_line) || next_line.blank?
end
def next_line_empty_and_exists?(last_send_line)
next_line_empty?(last_send_line) && last_send_line.next != processed_source.lines.size
end
def empty_lines_around?(node)
previous_line_empty?(node.first_line) && next_line_empty?(node.last_line)
end
def class_def?(line)
return false unless @class_or_module_def_first_line
line == @class_or_module_def_first_line + 1
end
def block_start?(line)
return false unless @block_line
line == @block_line + 1
end
def body_end?(line)
return false unless @class_or_module_def_last_line
line == @class_or_module_def_last_line - 1
end
def next_empty_line_range(node)
source_range(processed_source.buffer, node.last_line + 1, 0)
end
def message(node)
case style
when :around
message_for_around_style(node)
when :only_before
message_for_only_before_style(node)
end
end
def message_for_around_style(node)
send_line = node.first_line
if block_start?(send_line) || class_def?(send_line)
format(MSG_AFTER, modifier: node.loc.selector.source)
else
format(MSG_BEFORE_AND_AFTER, modifier: node.loc.selector.source)
end
end
def message_for_only_before_style(node)
modifier = node.loc.selector.source
if next_line_empty?(node.last_line)
format(MSG_AFTER_FOR_ONLY_BEFORE, modifier: modifier)
else
format(MSG_BEFORE_FOR_ONLY_BEFORE, modifier: modifier)
end
end
def should_insert_line_before?(node)
return false if previous_line_empty?(node.first_line)
return true unless inside_block?(node) && no_empty_lines_around_block_body?
return true unless node.parent.begin_type?
node.parent.children.first != node
end
def should_insert_line_after?(node)
return true unless inside_block?(node) && no_empty_lines_around_block_body?
node.parent.children.last != node
end
def inside_block?(node)
node.parent.block_type? || (node.parent.begin_type? && node.parent.parent&.block_type?)
end
def no_empty_lines_around_block_body?
config.for_enabled_cop('Layout/EmptyLinesAroundBlockBody')['EnforcedStyle'] ==
'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/layout/extra_spacing.rb | lib/rubocop/cop/layout/extra_spacing.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for extra/unnecessary whitespace.
#
# @example
#
# # good if AllowForAlignment is true
# name = "RuboCop"
# # Some comment and an empty line
#
# website += "/rubocop/rubocop" unless cond
# puts "rubocop" if debug
#
# # bad for any configuration
# set_app("RuboCop")
# website = "https://github.com/rubocop/rubocop"
#
# # good only if AllowBeforeTrailingComments is true
# object.method(arg) # this is a comment
#
# # good even if AllowBeforeTrailingComments is false or not set
# object.method(arg) # this is a comment
#
# # good with either AllowBeforeTrailingComments or AllowForAlignment
# object.method(arg) # this is a comment
# another_object.method(arg) # this is another comment
# some_object.method(arg) # this is some comment
class ExtraSpacing < Base
extend AutoCorrector
include PrecedingFollowingAlignment
include RangeHelp
MSG_UNNECESSARY = 'Unnecessary spacing detected.'
MSG_UNALIGNED_ASGN = '`=` is not aligned with the %<location>s assignment.'
def on_new_investigation
return if processed_source.blank?
@aligned_comments = aligned_locations(processed_source.comments.map(&:loc))
@corrected = Set.new if force_equal_sign_alignment?
processed_source.tokens.each_cons(2) do |token1, token2|
check_tokens(processed_source.ast, token1, token2)
end
end
private
def aligned_locations(locs)
return [] if locs.empty?
aligned = Set.new
locs.each_cons(2) do |loc1, loc2|
aligned << loc1.line << loc2.line if loc1.column == loc2.column
end
aligned
end
def check_tokens(ast, token1, token2)
return if token2.type == :tNL
if force_equal_sign_alignment? && assignment_tokens.include?(token2)
check_assignment(token2)
else
check_other(token1, token2, ast)
end
end
def check_assignment(token)
return unless aligned_with_preceding_equals_operator(token) == :no
message = format(MSG_UNALIGNED_ASGN, location: 'preceding')
add_offense(token.pos, message: message) do |corrector|
align_equal_signs(token.pos, corrector)
end
end
def check_other(token1, token2, ast)
return false if allow_for_trailing_comments? && token2.text.start_with?('#')
extra_space_range(token1, token2) do |range|
next if ignored_range?(ast, range.begin_pos)
add_offense(range, message: MSG_UNNECESSARY) { |corrector| corrector.remove(range) }
end
end
def extra_space_range(token1, token2)
return if token1.line != token2.line
start_pos = token1.end_pos
end_pos = token2.begin_pos - 1
return if end_pos <= start_pos
return if allow_for_alignment? && aligned_tok?(token2)
yield range_between(start_pos, end_pos)
end
def aligned_tok?(token)
if token.comment?
@aligned_comments.include?(token.line)
else
aligned_with_something?(token.pos)
end
end
def ignored_range?(ast, start_pos)
ignored_ranges(ast).any? { |r| r.include?(start_pos) }
end
# Returns an array of ranges that should not be reported. It's the
# extra spaces between the keys and values in a multiline hash,
# since those are handled by the Layout/HashAlignment cop.
def ignored_ranges(ast)
return [] unless ast
@ignored_ranges ||= begin
ranges = []
on_node(:pair, ast) do |pair|
next if pair.parent.single_line?
key, value = *pair
ranges << (key.source_range.end_pos...value.source_range.begin_pos)
end
ranges
end
end
def force_equal_sign_alignment?
cop_config['ForceEqualSignAlignment']
end
def align_equal_signs(range, corrector)
lines = all_relevant_assignment_lines(range.line)
tokens = assignment_tokens.select { |t| lines.include?(t.line) }
columns = tokens.map { |t| align_column(t) }
align_to = columns.max
tokens.each { |token| align_equal_sign(corrector, token, align_to) }
end
def align_equal_sign(corrector, token, align_to)
return unless @corrected.add?(token)
diff = align_to - token.pos.last_column
if diff.positive?
corrector.insert_before(token.pos, ' ' * diff)
elsif diff.negative?
corrector.remove_preceding(token.pos, -diff)
end
end
def all_relevant_assignment_lines(line_number)
last_line_number = processed_source.lines.size
(
relevant_assignment_lines(line_number.downto(1)) +
relevant_assignment_lines(line_number.upto(last_line_number))
)
.uniq
.sort
end
def align_column(asgn_token)
# if we removed unneeded spaces from the beginning of this =,
# what column would it end from?
line = processed_source.lines[asgn_token.line - 1]
leading = line[0...asgn_token.column]
spaces = leading.size - (leading =~ / *\Z/)
asgn_token.pos.last_column - spaces + 1
end
def allow_for_trailing_comments?
cop_config['AllowBeforeTrailingComments']
end
end
end
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_block_body.rb | lib/rubocop/cop/layout/empty_lines_around_block_body.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks if empty lines around the bodies of blocks match
# the configuration.
#
# @example EnforcedStyle: no_empty_lines (default)
# # good
#
# foo do |bar|
# # ...
# end
#
# @example EnforcedStyle: empty_lines
# # good
#
# foo do |bar|
#
# # ...
#
# end
class EmptyLinesAroundBlockBody < Base
include EmptyLinesAroundBody
extend AutoCorrector
KIND = 'block'
def on_block(node)
first_line = node.send_node.last_line
check(node, node.body, adjusted_first_line: first_line)
end
alias on_numblock on_block
alias on_itblock on_block
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/space_around_block_parameters.rb | lib/rubocop/cop/layout/space_around_block_parameters.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks the spacing inside and after block parameters pipes. Line breaks
# inside parameter pipes are checked by `Layout/MultilineBlockLayout` and
# not by this cop.
#
# @example EnforcedStyleInsidePipes: no_space (default)
# # bad
# {}.each { | x, y |puts x }
# ->( x, y ) { puts x }
#
# # good
# {}.each { |x, y| puts x }
# ->(x, y) { puts x }
#
# @example EnforcedStyleInsidePipes: space
# # bad
# {}.each { |x, y| puts x }
# ->(x, y) { puts x }
#
# # good
# {}.each { | x, y | puts x }
# ->( x, y ) { puts x }
class SpaceAroundBlockParameters < Base
include ConfigurableEnforcedStyle
include RangeHelp
extend AutoCorrector
def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
arguments = node.arguments
return unless node.arguments? && pipes?(arguments)
check_inside_pipes(arguments)
check_after_closing_pipe(arguments) if node.body
check_each_arg(arguments)
end
private
def pipes(arguments)
[arguments.loc.begin, arguments.loc.end]
end
def pipes?(arguments)
pipes(arguments).none?(&:nil?)
end
def style_parameter_name
'EnforcedStyleInsidePipes'
end
def check_inside_pipes(arguments)
case style
when :no_space
check_no_space_style_inside_pipes(arguments)
when :space
check_space_style_inside_pipes(arguments)
end
end
def check_after_closing_pipe(arguments)
_opening_pipe, closing_pipe = pipes(arguments)
block = arguments.parent
check_space(closing_pipe.end_pos, block.body.source_range.begin_pos,
closing_pipe, 'after closing `|`')
end
def check_no_space_style_inside_pipes(arguments)
args = arguments.children
opening_pipe, closing_pipe = pipes(arguments)
first = args.first.source_range
last = args.last.source_range
check_no_space(opening_pipe.end_pos, first.begin_pos, 'Space before first')
check_no_space(last_end_pos_inside_pipes(arguments, last),
closing_pipe.begin_pos, 'Space after last')
end
def check_space_style_inside_pipes(arguments)
opening_pipe, closing_pipe = pipes(arguments)
check_opening_pipe_space(arguments, opening_pipe)
check_closing_pipe_space(arguments, closing_pipe)
end
def check_opening_pipe_space(arguments, opening_pipe)
args = arguments.children
first_arg = args.first
range = first_arg.source_range
check_space(opening_pipe.end_pos, range.begin_pos, range,
'before first block parameter', first_arg)
check_no_space(opening_pipe.end_pos, range.begin_pos - 1, 'Extra space before first')
end
def check_closing_pipe_space(arguments, closing_pipe)
args = arguments.children
last = args.last.source_range
last_end_pos = last_end_pos_inside_pipes(arguments, last)
check_space(last_end_pos, closing_pipe.begin_pos, last, 'after last block parameter')
check_no_space(last_end_pos + 1, closing_pipe.begin_pos, 'Extra space after last')
end
def last_end_pos_inside_pipes(arguments, range)
pos = range.end_pos
num = pos - arguments.source_range.begin_pos
trailing_comma_index = arguments.source[num..].index(',')
trailing_comma_index ? pos + trailing_comma_index + 1 : pos
end
def check_each_arg(args)
args.children.each { |arg| check_arg(arg) }
end
def check_arg(arg)
arg.children.each { |a| check_arg(a) } if arg.mlhs_type?
expr = arg.source_range
check_no_space(
range_with_surrounding_space(expr, side: :left).begin_pos,
expr.begin_pos - 1,
'Extra space before'
)
end
def check_space(space_begin_pos, space_end_pos, range, msg, node = nil)
return if space_begin_pos != space_end_pos
target = node || range
message = "Space #{msg} missing."
add_offense(target, message: message) do |corrector|
if node
corrector.insert_before(node, ' ')
else
corrector.insert_after(target, ' ')
end
end
end
def check_no_space(space_begin_pos, space_end_pos, msg)
return if space_begin_pos >= space_end_pos
range = range_between(space_begin_pos, space_end_pos)
return if range.source.include?("\n")
message = "#{msg} block parameter detected."
add_offense(range, message: message) { |corrector| corrector.remove(range) }
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/trailing_whitespace.rb | lib/rubocop/cop/layout/trailing_whitespace.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Looks for trailing whitespace in the source code.
#
# @example
# # The line in this example contains spaces after the 0.
# # bad
# x = 0
#
# # The line in this example ends directly after the 0.
# # good
# x = 0
#
# @example AllowInHeredoc: false (default)
# # The line in this example contains spaces after the 0.
# # bad
# code = <<~RUBY
# x = 0
# RUBY
#
# # ok
# code = <<~RUBY
# x = 0 #{}
# RUBY
#
# # good
# trailing_whitespace = ' '
# code = <<~RUBY
# x = 0#{trailing_whitespace}
# RUBY
#
# @example AllowInHeredoc: true
# # The line in this example contains spaces after the 0.
# # good
# code = <<~RUBY
# x = 0
# RUBY
#
class TrailingWhitespace < Base
include RangeHelp
include Heredoc
extend AutoCorrector
MSG = 'Trailing whitespace detected.'
def on_new_investigation
processed_source.lines.each_with_index do |line, index|
next unless line.match?(/[[:blank:]]\z/)
process_line(line, index + 1)
end
end
def on_heredoc(_node); end
private
def process_line(line, lineno)
heredoc = find_heredoc(lineno)
return if skip_heredoc? && heredoc
range = offense_range(lineno, line)
add_offense(range) do |corrector|
if heredoc
process_line_in_heredoc(corrector, range, heredoc)
else
corrector.remove(range)
end
end
end
def process_line_in_heredoc(corrector, range, heredoc)
indent_level = indent_level(find_heredoc(range.line).loc.heredoc_body.source)
whitespace_only = whitespace_only?(range)
if whitespace_only && whitespace_is_indentation?(range, indent_level)
corrector.remove(range)
elsif !static?(heredoc)
range = range_between(range.begin_pos + indent_level, range.end_pos) if whitespace_only
corrector.wrap(range, "\#{'", "'}")
end
end
def whitespace_is_indentation?(range, level)
range.source[/[[:blank:]]+/].length <= level
end
def whitespace_only?(range)
source = range_with_surrounding_space(range).source
source.start_with?("\n") && source.end_with?("\n")
end
def static?(heredoc)
heredoc.source.end_with? "'"
end
def skip_heredoc?
cop_config.fetch('AllowInHeredoc', false)
end
def find_heredoc(line_number)
heredocs.each { |node, r| return node if r.include?(line_number) }
nil
end
def heredocs
@heredocs ||= extract_heredocs(processed_source.ast)
end
def extract_heredocs(ast)
return [] unless ast
heredocs = []
ast.each_node(:any_str) do |node|
next unless node.heredoc?
body = node.location.heredoc_body
heredocs << [node, body.first_line...body.last_line]
end
heredocs
end
def offense_range(lineno, line)
source_range(
processed_source.buffer, lineno, (line.sub(/[[:blank:]]+\z/, '').length)...(line.length)
)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/multiline_array_brace_layout.rb | lib/rubocop/cop/layout/multiline_array_brace_layout.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks that the closing brace in an array literal is either
# on the same line as the last array element or on a new line.
#
# When using the `symmetrical` (default) style:
#
# If an array's opening brace is on the same line as the first element
# of the array, then the closing brace should be on the same line as
# the last element of the array.
#
# If an array's opening brace is on the line above the first element
# of the array, then the closing brace should be on the line below
# the last element of the array.
#
# When using the `new_line` style:
#
# The closing brace of a multi-line array literal must be on the line
# after the last element of the array.
#
# When using the `same_line` style:
#
# The closing brace of a multi-line array literal must be on the same
# line as the last element of the array.
#
# @example EnforcedStyle: symmetrical (default)
# # bad
# [ :a,
# :b
# ]
#
# # bad
# [
# :a,
# :b ]
#
# # good
# [ :a,
# :b ]
#
# # good
# [
# :a,
# :b
# ]
#
# @example EnforcedStyle: new_line
# # bad
# [
# :a,
# :b ]
#
# # bad
# [ :a,
# :b ]
#
# # good
# [ :a,
# :b
# ]
#
# # good
# [
# :a,
# :b
# ]
#
# @example EnforcedStyle: same_line
# # bad
# [ :a,
# :b
# ]
#
# # bad
# [
# :a,
# :b
# ]
#
# # good
# [
# :a,
# :b ]
#
# # good
# [ :a,
# :b ]
class MultilineArrayBraceLayout < Base
include MultilineLiteralBraceLayout
extend AutoCorrector
SAME_LINE_MESSAGE = 'The closing array brace must be on the same ' \
'line as the last array element when the opening brace is on the ' \
'same line as the first array element.'
NEW_LINE_MESSAGE = 'The closing array brace must be on the line ' \
'after the last array element when the opening brace is on a ' \
'separate line from the first array element.'
ALWAYS_NEW_LINE_MESSAGE = 'The closing array brace must be on the ' \
'line after the last array element.'
ALWAYS_SAME_LINE_MESSAGE = 'The closing array brace must be on the ' \
'same line as the last array element.'
def on_array(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_in_lambda_literal.rb | lib/rubocop/cop/layout/space_in_lambda_literal.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for spaces between `->` and opening parameter
# parenthesis (`(`) in lambda literals.
#
# @example EnforcedStyle: require_no_space (default)
# # bad
# a = -> (x, y) { x + y }
#
# # good
# a = ->(x, y) { x + y }
#
# @example EnforcedStyle: require_space
# # bad
# a = ->(x, y) { x + y }
#
# # good
# a = -> (x, y) { x + y }
class SpaceInLambdaLiteral < Base
include ConfigurableEnforcedStyle
include RangeHelp
extend AutoCorrector
MSG_REQUIRE_SPACE = 'Use a space between `->` and `(` in lambda literals.'
MSG_REQUIRE_NO_SPACE = 'Do not use spaces between `->` and `(` in lambda literals.'
def on_send(node)
return unless arrow_lambda_with_args?(node)
if style == :require_space && !space_after_arrow?(node)
lambda_node = range_of_offense(node)
add_offense(lambda_node, message: MSG_REQUIRE_SPACE) do |corrector|
corrector.insert_before(lambda_arguments(node), ' ')
end
elsif style == :require_no_space && space_after_arrow?(node)
space = space_after_arrow(node)
add_offense(space, message: MSG_REQUIRE_NO_SPACE) do |corrector|
corrector.remove(space)
end
end
end
private
def arrow_lambda_with_args?(node)
node.lambda_literal? && node.parent.arguments?
end
def space_after_arrow?(lambda_node)
!space_after_arrow(lambda_node).empty?
end
def space_after_arrow(lambda_node)
arrow = lambda_node.parent.children[0].source_range
parentheses = lambda_node.parent.children[1].source_range
arrow.end.join(parentheses.begin)
end
def range_of_offense(node)
range_between(
node.parent.source_range.begin_pos,
node.parent.arguments.source_range.end_pos
)
end
def lambda_arguments(node)
node.parent.children[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_lines_around_exception_handling_keywords.rb | lib/rubocop/cop/layout/empty_lines_around_exception_handling_keywords.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks if empty lines exist around the bodies of `begin`
# sections. This cop doesn't check empty lines at `begin` body
# beginning/end and around method definition body.
# `Layout/EmptyLinesAroundBeginBody` or `Layout/EmptyLinesAroundMethodBody`
# can be used for this purpose.
#
# @example
#
# # good
#
# begin
# do_something
# rescue
# do_something2
# else
# do_something3
# ensure
# do_something4
# end
#
# # good
#
# def foo
# do_something
# rescue
# do_something2
# end
#
# # bad
#
# begin
# do_something
#
# rescue
#
# do_something2
#
# else
#
# do_something3
#
# ensure
#
# do_something4
# end
#
# # bad
#
# def foo
# do_something
#
# rescue
#
# do_something2
# end
class EmptyLinesAroundExceptionHandlingKeywords < Base
include EmptyLinesAroundBody
extend AutoCorrector
MSG = 'Extra empty line detected %<location>s the `%<keyword>s`.'
def on_def(node)
check_body(node.body, node.loc.line)
end
alias on_defs on_def
alias on_block on_def
alias on_numblock on_def
def on_kwbegin(node)
check_body(node.children.first, node.loc.line)
end
private
def check_body(body, line_of_def_or_kwbegin)
locations = keyword_locations(body)
locations.each do |loc|
line = loc.line
next if line == line_of_def_or_kwbegin || last_body_and_end_on_same_line?(body)
keyword = loc.source
# below the keyword
check_line(style, line, message('after', keyword), &:empty?)
# above the keyword
check_line(style, line - 2, message('before', keyword), &:empty?)
end
end
def last_body_and_end_on_same_line?(body)
end_keyword_line = body.parent.loc.end.line
return body.loc.last_line == end_keyword_line unless body.rescue_type?
last_body_line = body.else? ? body.loc.else.line : body.resbody_branches.last.loc.line
last_body_line == end_keyword_line
end
def message(location, keyword)
format(MSG, location: location, keyword: keyword)
end
def style
:no_empty_lines
end
def keyword_locations(node)
return [] unless node
case node.type
when :rescue
keyword_locations_in_rescue(node)
when :ensure
keyword_locations_in_ensure(node)
else
[]
end
end
def keyword_locations_in_rescue(node)
[node.loc.else, *node.resbody_branches.map { |body| body.loc.keyword }].compact
end
def keyword_locations_in_ensure(node)
rescue_body_without_ensure = node.children.first
[
node.loc.keyword,
*keyword_locations(rescue_body_without_ensure)
]
end
end
end
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/line_continuation_spacing.rb | lib/rubocop/cop/layout/line_continuation_spacing.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks that the backslash of a line continuation is separated from
# preceding text by exactly one space (default) or zero spaces.
#
# @example EnforcedStyle: space (default)
# # bad
# 'a'\
# 'b' \
# 'c'
#
# # good
# 'a' \
# 'b' \
# 'c'
#
# @example EnforcedStyle: no_space
# # bad
# 'a' \
# 'b' \
# 'c'
#
# # good
# 'a'\
# 'b'\
# 'c'
class LineContinuationSpacing < Base
include RangeHelp
extend AutoCorrector
def on_new_investigation
return unless processed_source.raw_source.include?('\\')
last_line = last_line(processed_source)
processed_source.raw_source.lines.each_with_index do |line, index|
break if index >= last_line
line_number = index + 1
investigate(line, line_number)
end
end
private
def investigate(line, line_number)
offensive_spacing = find_offensive_spacing(line)
return unless offensive_spacing
range = source_range(
processed_source.buffer,
line_number,
line.length - offensive_spacing.length - 1,
offensive_spacing.length
)
return if ignore_range?(range)
add_offense(range) { |corrector| autocorrect(corrector, range) }
end
def find_offensive_spacing(line)
if no_space_style?
line[/\s+\\$/, 0]
elsif space_style?
line[/((?<!\s)|\s{2,})\\$/, 0]
end
end
def message(_range)
if no_space_style?
'Use zero spaces in front of backslash.'
elsif space_style?
'Use one space in front of backslash.'
end
end
def autocorrect(corrector, range)
correction = if no_space_style?
'\\'
elsif space_style?
' \\'
end
corrector.replace(range, correction)
end
# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def ignored_literal_ranges(ast)
# which lines start inside a string literal?
return [] if ast.nil?
ast.each_node(:str, :dstr, :array).with_object(Set.new) do |literal, ranges|
loc = literal.location
if literal.array_type?
next unless literal.percent_literal?
ranges << loc.expression
elsif literal.heredoc?
ranges << loc.heredoc_body
elsif literal.loc?(:begin) || ignored_parent?(literal)
ranges << loc.expression
end
end
end
# rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def comment_ranges(comments)
comments.map(&:source_range)
end
def last_line(processed_source)
last_token = processed_source.tokens.last
last_token ? last_token.line : processed_source.lines.length
end
def ignore_range?(backtick_range)
ignored_ranges.any? { |range| range.contains?(backtick_range) }
end
def ignored_ranges
@ignored_ranges ||= ignored_literal_ranges(processed_source.ast) +
comment_ranges(processed_source.comments)
end
def ignored_parent?(node)
return false unless node.parent
node.parent.type?(:regexp, :xstr)
end
def no_space_style?
cop_config['EnforcedStyle'] == 'no_space'
end
def space_style?
cop_config['EnforcedStyle'] == 'space'
end
end
end
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_string_interpolation.rb | lib/rubocop/cop/layout/space_inside_string_interpolation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for whitespace within string interpolations.
#
# @example EnforcedStyle: no_space (default)
# # bad
# var = "This is the #{ space } example"
#
# # good
# var = "This is the #{no_space} example"
#
# @example EnforcedStyle: space
# # bad
# var = "This is the #{no_space} example"
#
# # good
# var = "This is the #{ space } example"
class SpaceInsideStringInterpolation < Base
include Interpolation
include SurroundingSpace
include ConfigurableEnforcedStyle
extend AutoCorrector
MSG = '%<command>s space inside string interpolation.'
def on_interpolation(begin_node)
return if begin_node.multiline?
tokens = processed_source.tokens_within(begin_node)
left, right = delimiters(begin_node)
return if empty_brackets?(left, right, tokens: tokens)
if style == :no_space
no_space_offenses(begin_node, left, right, MSG)
else
space_offenses(begin_node, left, right, MSG)
end
end
private
def autocorrect(corrector, begin_node)
delims = delimiters(begin_node)
if style == :no_space
SpaceCorrector.remove_space(processed_source, corrector, *delims)
else
SpaceCorrector.add_space(processed_source, corrector, *delims)
end
end
def delimiters(begin_node)
left = processed_source.first_token_of(begin_node)
right = processed_source.last_token_of(begin_node)
[left, right]
end
end
end
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/single_line_block_chain.rb | lib/rubocop/cop/layout/single_line_block_chain.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks if method calls are chained onto single line blocks. It considers that a
# line break before the dot improves the readability of the code.
#
# @example
# # bad
# example.select { |item| item.cond? }.join('-')
#
# # good
# example.select { |item| item.cond? }
# .join('-')
#
# # good (not a concern for this cop)
# example.select do |item|
# item.cond?
# end.join('-')
#
class SingleLineBlockChain < Base
include RangeHelp
extend AutoCorrector
MSG = 'Put method call on a separate line if chained to a single line block.'
def self.autocorrect_incompatible_with
[Style::MapToHash]
end
def on_send(node)
range = offending_range(node)
add_offense(range) { |corrector| corrector.insert_before(range, "\n") } if range
end
alias on_csend on_send
private
def offending_range(node)
receiver = node.receiver
return unless receiver&.any_block_type?
receiver_location = receiver.loc
closing_block_delimiter_line_num = receiver_location.end.line
return if receiver_location.begin.line < closing_block_delimiter_line_num
node_location = node.loc
dot_range = node_location.dot
return unless dot_range
return unless call_method_after_block?(node, dot_range, closing_block_delimiter_line_num)
range_between(dot_range.begin_pos, selector_range(node).end_pos)
end
def call_method_after_block?(node, dot_range, closing_block_delimiter_line_num)
return false if dot_range.line > closing_block_delimiter_line_num
dot_range.column < selector_range(node).column
end
def selector_range(node)
# l.(1) has no selector, so we use the opening parenthesis instead
node.loc.selector || node.loc.begin
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/space_before_brackets.rb | lib/rubocop/cop/layout/space_before_brackets.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for space between the name of a receiver and a left
# brackets.
#
# @example
#
# # bad
# collection [index_or_key]
#
# # good
# collection[index_or_key]
#
class SpaceBeforeBrackets < Base
include RangeHelp
extend AutoCorrector
MSG = 'Remove the space before the opening brackets.'
RESTRICT_ON_SEND = %i[[] []=].freeze
def on_send(node)
return if node.loc.dot
receiver_end_pos = node.receiver.source_range.end_pos
selector_begin_pos = node.loc.selector.begin_pos
return if receiver_end_pos >= selector_begin_pos
range = range_between(receiver_end_pos, selector_begin_pos)
add_offense(range) do |corrector|
corrector.remove(range)
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/condition_position.rb | lib/rubocop/cop/layout/condition_position.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for conditions that are not on the same line as
# if/while/until.
#
# @example
#
# # bad
# if
# some_condition
# do_something
# end
#
# # good
# if some_condition
# do_something
# end
class ConditionPosition < Base
include RangeHelp
extend AutoCorrector
MSG = 'Place the condition on the same line as `%<keyword>s`.'
def on_if(node)
return if node.ternary?
check(node)
end
def on_while(node)
check(node)
end
alias on_until on_while
private
def check(node)
return if node.modifier_form? || node.single_line_condition?
condition = node.condition
message = message(condition)
add_offense(condition, message: message) do |corrector|
range = range_by_whole_lines(condition.source_range, include_final_newline: true)
corrector.insert_after(condition.parent.loc.keyword, " #{condition.source}")
corrector.remove(range)
end
end
def message(condition)
format(MSG, keyword: condition.parent.keyword)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/line_continuation_leading_space.rb | lib/rubocop/cop/layout/line_continuation_leading_space.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks that strings broken over multiple lines (by a backslash) contain
# trailing spaces instead of leading spaces (default) or leading spaces
# instead of trailing spaces.
#
# @example EnforcedStyle: trailing (default)
# # bad
# 'this text contains a lot of' \
# ' spaces'
#
# # good
# 'this text contains a lot of ' \
# 'spaces'
#
# # bad
# 'this text is too' \
# ' long'
#
# # good
# 'this text is too ' \
# 'long'
#
# @example EnforcedStyle: leading
# # bad
# 'this text contains a lot of ' \
# 'spaces'
#
# # good
# 'this text contains a lot of' \
# ' spaces'
#
# # bad
# 'this text is too ' \
# 'long'
#
# # good
# 'this text is too' \
# ' long'
class LineContinuationLeadingSpace < Base
include RangeHelp
extend AutoCorrector
LINE_1_ENDING = /['"]\s*\\\n/.freeze
LINE_2_BEGINNING = /\A\s*['"]/.freeze
LEADING_STYLE_OFFENSE = /(?<trailing_spaces>\s+)(?<ending>#{LINE_1_ENDING})/.freeze
TRAILING_STYLE_OFFENSE = /(?<beginning>#{LINE_2_BEGINNING})(?<leading_spaces>\s+)/.freeze
private_constant :LINE_1_ENDING, :LINE_2_BEGINNING,
:LEADING_STYLE_OFFENSE, :TRAILING_STYLE_OFFENSE
# When both cops are activated and run in the same iteration of the correction loop,
# `Style/StringLiterals` undoes the moving of spaces that
# `Layout/LineContinuationLeadingSpace` performs. This is because `Style/StringLiterals`
# takes the original string content and transforms it, rather than just modifying the
# delimiters, in order to handle escaping for quotes within the string.
def self.autocorrect_incompatible_with
[Style::StringLiterals]
end
def on_dstr(node)
# Quick check if we possibly have line continuations.
return unless node.source.include?('\\')
end_of_first_line = node.source_range.begin_pos - node.source_range.column
lines = raw_lines(node)
lines.each_cons(2).with_index(node.first_line) do |(raw_line_one, raw_line_two), line_num|
end_of_first_line += raw_line_one.length
next unless continuation?(raw_line_one, line_num, node)
investigate(raw_line_one, raw_line_two, end_of_first_line)
end
end
private
def raw_lines(node)
processed_source.raw_source.lines[node.first_line - 1, line_range(node).size]
end
def investigate(first_line, second_line, end_of_first_line)
if enforced_style_leading?
investigate_leading_style(first_line, second_line, end_of_first_line)
else
investigate_trailing_style(first_line, second_line, end_of_first_line)
end
end
def investigate_leading_style(first_line, second_line, end_of_first_line)
matches = first_line.match(LEADING_STYLE_OFFENSE)
return if matches.nil?
offense_range = leading_offense_range(end_of_first_line, matches)
add_offense(offense_range) do |corrector|
insert_pos = end_of_first_line + second_line[LINE_2_BEGINNING].length
autocorrect(corrector, offense_range, insert_pos, matches[:trailing_spaces])
end
end
def investigate_trailing_style(first_line, second_line, end_of_first_line)
matches = second_line.match(TRAILING_STYLE_OFFENSE)
return if matches.nil?
offense_range = trailing_offense_range(end_of_first_line, matches)
add_offense(offense_range) do |corrector|
insert_pos = end_of_first_line - first_line[LINE_1_ENDING].length
autocorrect(corrector, offense_range, insert_pos, matches[:leading_spaces])
end
end
def continuation?(line, line_num, node)
return false unless line.end_with?("\\\n")
# Ensure backslash isn't part of a token spanning to the next line.
node.children.none? { |c| (c.first_line...c.last_line).cover?(line_num) && c.multiline? }
end
def autocorrect(corrector, offense_range, insert_pos, spaces)
corrector.remove(offense_range)
corrector.replace(range_between(insert_pos, insert_pos), spaces)
end
def leading_offense_range(end_of_first_line, matches)
end_pos = end_of_first_line - matches[:ending].length
begin_pos = end_pos - matches[:trailing_spaces].length
range_between(begin_pos, end_pos)
end
def trailing_offense_range(end_of_first_line, matches)
begin_pos = end_of_first_line + matches[:beginning].length
end_pos = begin_pos + matches[:leading_spaces].length
range_between(begin_pos, end_pos)
end
def message(_range)
if enforced_style_leading?
'Move trailing spaces to the start of the next line.'
else
'Move leading spaces to the end of the previous line.'
end
end
def enforced_style_leading?
cop_config['EnforcedStyle'] == 'leading'
end
end
end
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_after_comma.rb | lib/rubocop/cop/layout/space_after_comma.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for comma (`,`) not followed by some kind of space.
#
# @example
#
# # bad
# [1,2]
# { foo:bar,}
#
# # good
# [1, 2]
# { foo:bar, }
class SpaceAfterComma < Base
include SpaceAfterPunctuation
extend AutoCorrector
def space_style_before_rcurly
cfg = config.for_cop('Layout/SpaceInsideHashLiteralBraces')
cfg['EnforcedStyle'] || 'space'
end
def kind(token, next_token)
'comma' if token.comma? && !next_token.semicolon?
end
end
end
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_after_multiline_condition.rb | lib/rubocop/cop/layout/empty_line_after_multiline_condition.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Enforces empty line after multiline condition.
#
# @example
# # bad
# if multiline &&
# condition
# do_something
# end
#
# # good
# if multiline &&
# condition
#
# do_something
# end
#
# # bad
# case x
# when foo,
# bar
# do_something
# end
#
# # good
# case x
# when foo,
# bar
#
# do_something
# end
#
# # bad
# begin
# do_something
# rescue FooError,
# BarError
# handle_error
# end
#
# # good
# begin
# do_something
# rescue FooError,
# BarError
#
# handle_error
# end
#
class EmptyLineAfterMultilineCondition < Base
include RangeHelp
extend AutoCorrector
MSG = 'Use empty line after multiline condition.'
def on_if(node)
return if node.ternary?
if node.modifier_form?
check_condition(node.condition) if node.right_sibling
else
check_condition(node.condition)
end
end
def on_while(node)
check_condition(node.condition)
end
alias on_until on_while
def on_while_post(node)
return unless node.right_sibling
check_condition(node.condition)
end
alias on_until_post on_while_post
def on_case(node)
node.when_branches.each do |when_node|
last_condition = when_node.conditions.last
next if !multiline_when_condition?(when_node) ||
next_line_empty?(last_condition.last_line)
add_offense(when_node, &autocorrect(last_condition))
end
end
def on_rescue(node)
node.resbody_branches.each do |resbody|
rescued_exceptions = resbody.exceptions
next if !multiline_rescue_exceptions?(rescued_exceptions) ||
next_line_empty?(rescued_exceptions.last.last_line)
add_offense(resbody, &autocorrect(rescued_exceptions.last))
end
end
private
def check_condition(condition)
return unless condition.multiline?
return if next_line_empty?(condition.last_line)
add_offense(condition, &autocorrect(condition))
end
def next_line_empty?(line)
processed_source[line].blank?
end
def multiline_when_condition?(when_node)
when_node.conditions.first.first_line != when_node.conditions.last.last_line
end
def multiline_rescue_exceptions?(exception_nodes)
return false if exception_nodes.size <= 1
first, *_rest, last = *exception_nodes
first.first_line != last.last_line
end
def autocorrect(node)
lambda do |corrector|
range = range_by_whole_lines(node.source_range)
corrector.insert_after(range, "\n")
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/heredoc_indentation.rb | lib/rubocop/cop/layout/heredoc_indentation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks the indentation of the here document bodies. The bodies
# are indented one step.
#
# NOTE: When ``Layout/LineLength``'s `AllowHeredoc` is false (not default),
# this cop does not add any offenses for long here documents to
# avoid ``Layout/LineLength``'s offenses.
#
# @example
# # bad
# <<-RUBY
# something
# RUBY
#
# # good
# <<~RUBY
# something
# RUBY
#
class HeredocIndentation < Base
include Alignment
include Heredoc
extend AutoCorrector
extend TargetRubyVersion
minimum_target_ruby_version 2.3
TYPE_MSG = 'Use %<indentation_width>d spaces for indentation in a ' \
'heredoc by using `<<~` instead of `%<current_indent_type>s`.'
WIDTH_MSG = 'Use %<indentation_width>d spaces for indentation in a heredoc.'
def on_heredoc(node)
body = heredoc_body(node)
return if body.strip.empty?
body_indent_level = indent_level(body)
heredoc_indent_type = heredoc_indent_type(node)
if heredoc_indent_type == '~'
expected_indent_level = base_indent_level(node) + configured_indentation_width
return if expected_indent_level == body_indent_level
else
return unless body_indent_level.zero?
end
return if line_too_long?(node)
register_offense(node, heredoc_indent_type)
end
private
def register_offense(node, heredoc_indent_type)
message = message(heredoc_indent_type)
add_offense(node.loc.heredoc_body, message: message) do |corrector|
if heredoc_indent_type == '~'
adjust_squiggly(corrector, node)
else
adjust_minus(corrector, node)
end
end
end
def message(heredoc_indent_type)
current_indent_type = "<<#{heredoc_indent_type}"
if current_indent_type == '<<~'
width_message(configured_indentation_width)
else
type_message(configured_indentation_width, current_indent_type)
end
end
def type_message(indentation_width, current_indent_type)
format(
TYPE_MSG,
indentation_width: indentation_width,
current_indent_type: current_indent_type
)
end
def width_message(indentation_width)
format(WIDTH_MSG, indentation_width: indentation_width)
end
def line_too_long?(node)
return false unless max_line_length
return false if unlimited_heredoc_length?
body = heredoc_body(node)
expected_indent = base_indent_level(node) + configured_indentation_width
actual_indent = indent_level(body)
increase_indent_level = expected_indent - actual_indent
longest_line(body).size + increase_indent_level >= max_line_length
end
def longest_line(lines)
lines.each_line.max_by { |line| line.chomp.size }.chomp
end
def unlimited_heredoc_length?
config.for_cop('Layout/LineLength')['AllowHeredoc']
end
def adjust_squiggly(corrector, node)
corrector.replace(node.loc.heredoc_body, indented_body(node))
corrector.replace(node.loc.heredoc_end, indented_end(node))
end
def adjust_minus(corrector, node)
heredoc_beginning = node.source
corrected = heredoc_beginning.sub(/<<-?/, '<<~')
corrector.replace(node, corrected)
end
def indented_body(node)
body = heredoc_body(node)
body_indent_level = indent_level(body)
correct_indent_level = base_indent_level(node) + configured_indentation_width
body.gsub(/^[^\S\r\n]{#{body_indent_level}}/, ' ' * correct_indent_level)
end
def indented_end(node)
end_ = heredoc_end(node)
end_indent_level = indent_level(end_)
correct_indent_level = base_indent_level(node)
if end_indent_level < correct_indent_level
end_.gsub(/^\s{#{end_indent_level}}/, ' ' * correct_indent_level)
else
end_
end
end
def base_indent_level(node)
base_line_num = node.source_range.line
base_line = processed_source.lines[base_line_num - 1]
indent_level(base_line)
end
# Returns '~', '-' or nil
def heredoc_indent_type(node)
node.source[/^<<([~-])/, 1]
end
def heredoc_body(node)
node.loc.heredoc_body.source
end
def heredoc_end(node)
node.loc.heredoc_end.source
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/block_alignment.rb | lib/rubocop/cop/layout/block_alignment.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks whether the end keywords are aligned properly for do
# end blocks.
#
# Three modes are supported through the `EnforcedStyleAlignWith`
# configuration parameter:
#
# `start_of_block` : the `end` shall be aligned with the
# start of the line where the `do` appeared.
#
# `start_of_line` : the `end` shall be aligned with the
# start of the line where the expression started.
#
# `either` (which is the default) : the `end` is allowed to be in either
# location. The autocorrect will default to `start_of_line`.
#
# @example EnforcedStyleAlignWith: either (default)
# # bad
#
# foo.bar
# .each do
# baz
# end
#
# # good
#
# foo.bar
# .each do
# baz
# end
#
# @example EnforcedStyleAlignWith: start_of_block
# # bad
#
# foo.bar
# .each do
# baz
# end
#
# # good
#
# foo.bar
# .each do
# baz
# end
#
# @example EnforcedStyleAlignWith: start_of_line
# # bad
#
# foo.bar
# .each do
# baz
# end
#
# # good
#
# foo.bar
# .each do
# baz
# end
#
class BlockAlignment < Base
include ConfigurableEnforcedStyle
include RangeHelp
extend AutoCorrector
MSG = '%<current>s is not aligned with %<prefer>s%<alt_prefer>s.'
# @!method block_end_align_target?(node, child)
def_node_matcher :block_end_align_target?, <<~PATTERN
{assignment?
any_def
splat
and
or
(send _ :<< ...)
(send equal?(%1) !:[] ...)}
PATTERN
def on_block(node)
check_block_alignment(start_for_block_node(node), node)
end
alias on_numblock on_block
alias on_itblock on_block
def style_parameter_name
'EnforcedStyleAlignWith'
end
private
def block_end_align_target(node)
lineage = [node, *node.ancestors]
lineage.each_cons(2) do |current, parent|
return current if end_align_target?(current, parent)
end
lineage.last
end
def end_align_target?(node, parent)
disqualified_parent?(parent, node) || !block_end_align_target?(parent, node)
end
def disqualified_parent?(parent, node)
parent&.loc && parent.first_line != node.first_line && !parent.masgn_type?
end
def check_block_alignment(start_node, block_node)
end_loc = block_node.loc.end
return unless begins_its_line?(end_loc)
start_loc = start_node.source_range
return unless start_loc.column != end_loc.column || style == :start_of_block
do_source_line_column = compute_do_source_line_column(block_node, end_loc)
return unless do_source_line_column
register_offense(block_node, start_loc, end_loc, do_source_line_column)
end
def register_offense(block_node,
start_loc,
end_loc,
do_source_line_column)
error_source_line_column = if style == :start_of_block
do_source_line_column
else
loc_to_source_line_column(start_loc)
end
message = format_message(start_loc, end_loc, do_source_line_column,
error_source_line_column)
add_offense(end_loc, message: message) do |corrector|
autocorrect(corrector, block_node)
end
end
def autocorrect(corrector, node)
ancestor_node = if style == :start_of_block
start_for_block_node(node)
else
start_for_line_node(node)
end
start_col = compute_start_col(ancestor_node, node)
loc_end = node.loc.end
delta = start_col - loc_end.column
if delta.positive?
add_space_before(corrector, loc_end, delta)
elsif delta.negative?
remove_space_before(corrector, loc_end.begin_pos, -delta)
end
end
def format_message(start_loc, end_loc, do_source_line_column,
error_source_line_column)
format(
MSG,
current: format_source_line_column(loc_to_source_line_column(end_loc)),
prefer: format_source_line_column(error_source_line_column),
alt_prefer: alt_start_msg(start_loc, do_source_line_column)
)
end
def start_for_block_node(block_node)
# Which node should we align the 'end' with?
start_node = block_end_align_target(block_node)
find_lhs_node(start_node)
end
def start_for_line_node(block_node)
start_node = start_for_block_node(block_node)
start_node = start_node.each_ancestor.to_a.reverse.find do |node|
same_line?(start_node, node)
end || start_node
find_lhs_node(start_node)
end
# In offense message, we want to show the assignment LHS rather than
# the entire assignment.
def find_lhs_node(node)
node = node.lhs while node.type?(:op_asgn, :masgn)
node
end
def compute_do_source_line_column(node, end_loc)
do_loc = node.loc.begin # Actually it's either do or {.
# We've found that "end" is not aligned with the start node (which
# can be a block, a variable assignment, etc). But we also allow
# the "end" to be aligned with the start of the line where the "do"
# is, which is a style some people use in multi-line chains of
# blocks.
match = /\S.*/.match(do_loc.source_line)
indentation_of_do_line = match.begin(0)
return unless end_loc.column != indentation_of_do_line || style == :start_of_line
{
source: match[0],
line: do_loc.line,
column: indentation_of_do_line
}
end
def loc_to_source_line_column(loc)
{
source: loc.source.lines.to_a.first.chomp,
line: loc.line,
column: loc.column
}
end
def alt_start_msg(start_loc, source_line_column)
if style != :either ||
(start_loc.line == source_line_column[:line] &&
start_loc.column == source_line_column[:column])
''
else
" or #{format_source_line_column(source_line_column)}"
end
end
def format_source_line_column(source_line_column)
"`#{source_line_column[:source]}` at #{source_line_column[:line]}, " \
"#{source_line_column[:column]}"
end
def compute_start_col(ancestor_node, node)
if style == :start_of_block
do_loc = node.loc.begin
return do_loc.source_line =~ /\S/
end
(ancestor_node || node).source_range.column
end
def add_space_before(corrector, loc, delta)
corrector.insert_before(loc, ' ' * delta)
end
def remove_space_before(corrector, end_pos, delta)
range = range_between(end_pos - delta, end_pos)
corrector.remove(range)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/empty_lines_around_method_body.rb | lib/rubocop/cop/layout/empty_lines_around_method_body.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks if empty lines exist around the bodies of methods.
#
# @example
#
# # good
#
# def foo
# # ...
# end
#
# # bad
#
# def bar
#
# # ...
#
# end
class EmptyLinesAroundMethodBody < Base
include EmptyLinesAroundBody
extend AutoCorrector
KIND = 'method'
def on_def(node)
if node.endless?
return unless offending_endless_method?(node)
register_offense_for_endless_method(node)
else
first_line = node.arguments.source_range&.last_line
check(node, node.body, adjusted_first_line: first_line)
end
end
alias on_defs on_def
private
def style
:no_empty_lines
end
def offending_endless_method?(node)
node.body.first_line > node.loc.assignment.line + 1 &&
processed_source.lines[node.loc.assignment.line].empty?
end
def register_offense_for_endless_method(node)
range = processed_source.buffer.line_range(node.loc.assignment.line + 1).resize(1)
msg = message(MSG_EXTRA, 'beginning')
add_offense(range, message: msg) do |corrector|
corrector.remove(range)
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/space_before_comment.rb | lib/rubocop/cop/layout/space_before_comment.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for missing space between a token and a comment on the
# same line.
#
# @example
# # bad
# 1 + 1# this operation does ...
#
# # good
# 1 + 1 # this operation does ...
class SpaceBeforeComment < Base
extend AutoCorrector
MSG = 'Put a space before an end-of-line comment.'
def on_new_investigation
processed_source.sorted_tokens.each_cons(2) do |token1, token2|
next unless token2.comment?
next unless same_line?(token1, token2)
next unless token1.pos.end == token2.pos.begin
range = token2.pos
add_offense(range) { |corrector| corrector.insert_before(range, ' ') }
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/space_around_method_call_operator.rb | lib/rubocop/cop/layout/space_around_method_call_operator.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks method call operators to not have spaces around them.
#
# @example
# # bad
# foo. bar
# foo .bar
# foo . bar
# foo. bar .buzz
# foo
# . bar
# . buzz
# foo&. bar
# foo &.bar
# foo &. bar
# foo &. bar&. buzz
# RuboCop:: Cop
# RuboCop:: Cop:: Base
# :: RuboCop::Cop
#
# # good
# foo.bar
# foo.bar.buzz
# foo
# .bar
# .buzz
# foo&.bar
# foo&.bar&.buzz
# RuboCop::Cop
# RuboCop::Cop::Base
# ::RuboCop::Cop
#
class SpaceAroundMethodCallOperator < Base
include RangeHelp
extend AutoCorrector
SPACES_REGEXP = /\A[ \t]+\z/.freeze
MSG = 'Avoid using spaces around a method call operator.'
def on_send(node)
return unless node.dot? || node.safe_navigation?
check_space_before_dot(node)
check_space_after_dot(node)
end
alias on_csend on_send
def on_const(node)
return unless node.loc?(:double_colon)
check_space_after_double_colon(node)
end
private
def check_space_before_dot(node)
receiver_pos = node.receiver.source_range.end_pos
dot_pos = node.loc.dot.begin_pos
check_space(receiver_pos, dot_pos)
end
def check_space_after_dot(node)
dot_pos = node.loc.dot.end_pos
selector_pos =
# `Proc#call` shorthand syntax
if node.method?(:call) && !node.loc.selector
node.loc.begin.begin_pos
else
node.loc.selector.begin_pos
end
check_space(dot_pos, selector_pos)
end
def check_space_after_double_colon(node)
double_colon_pos = node.loc.double_colon.end_pos
name_pos = node.loc.name.begin_pos
check_space(double_colon_pos, name_pos)
end
def check_space(begin_pos, end_pos)
return if end_pos <= begin_pos
range = range_between(begin_pos, end_pos)
return unless range.source.match?(SPACES_REGEXP)
add_offense(range) { |corrector| corrector.remove(range) }
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/end_of_line.rb | lib/rubocop/cop/layout/end_of_line.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for Windows-style line endings in the source code.
#
# @example EnforcedStyle: native (default)
# # The `native` style means that CR+LF (Carriage Return + Line Feed) is
# # enforced on Windows, and LF is enforced on other platforms.
#
# # bad
# puts 'Hello' # Return character is LF on Windows.
# puts 'Hello' # Return character is CR+LF on other than Windows.
#
# # good
# puts 'Hello' # Return character is CR+LF on Windows.
# puts 'Hello' # Return character is LF on other than Windows.
#
# @example EnforcedStyle: lf
# # The `lf` style means that LF (Line Feed) is enforced on
# # all platforms.
#
# # bad
# puts 'Hello' # Return character is CR+LF on all platforms.
#
# # good
# puts 'Hello' # Return character is LF on all platforms.
#
# @example EnforcedStyle: crlf
# # The `crlf` style means that CR+LF (Carriage Return + Line Feed) is
# # enforced on all platforms.
#
# # bad
# puts 'Hello' # Return character is LF on all platforms.
#
# # good
# puts 'Hello' # Return character is CR+LF on all platforms.
#
class EndOfLine < Base
include ConfigurableEnforcedStyle
include RangeHelp
MSG_DETECTED = 'Carriage return character detected.'
MSG_MISSING = 'Carriage return character missing.'
def on_new_investigation
last_line = last_line(processed_source)
processed_source.raw_source.each_line.with_index do |line, index|
break if index >= last_line
msg = offense_message(line)
next unless msg
next if unimportant_missing_cr?(index, last_line, line)
range = source_range(processed_source.buffer, index + 1, 0, line.length)
add_offense(range, message: msg)
# Usually there will be carriage return characters on all or none
# of the lines in a file, so we report only one offense.
break
end
end
# If there is no LF on the last line, we don't care if there's no CR.
def unimportant_missing_cr?(index, last_line, line)
style == :crlf && index == last_line - 1 && !line.end_with?("\n")
end
def offense_message(line)
effective_style = if style == :native
Platform.windows? ? :crlf : :lf
else
style
end
case effective_style
when :lf then MSG_DETECTED if line.end_with?("\r", "\r\n")
else MSG_MISSING unless line.end_with?("\r\n")
end
end
private
def last_line(processed_source)
last_token = processed_source.tokens.last
last_token ? last_token.line : processed_source.lines.length
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/multiline_array_line_breaks.rb | lib/rubocop/cop/layout/multiline_array_line_breaks.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Ensures that each item in a multi-line array
# starts on a separate line.
#
# @example
#
# # bad
# [
# a, b,
# c
# ]
#
# # good
# [
# a,
# b,
# c
# ]
#
# # good
# [
# a,
# b,
# foo(
# bar
# )
# ]
#
# @example AllowMultilineFinalElement: false (default)
#
# # bad
# [a, b, foo(
# bar
# )]
#
# @example AllowMultilineFinalElement: true
#
# # good
# [a, b, foo(
# bar
# )]
#
class MultilineArrayLineBreaks < Base
include MultilineElementLineBreaks
extend AutoCorrector
MSG = 'Each item in a multi-line array must start on a separate line.'
def on_array(node)
check_line_breaks(node, node.children, ignore_last: ignore_last_element?)
end
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_inside_reference_brackets.rb | lib/rubocop/cop/layout/space_inside_reference_brackets.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks that reference brackets have or don't have
# surrounding space depending on configuration.
#
# @example EnforcedStyle: no_space (default)
# # The `no_space` style enforces that reference brackets have
# # no surrounding space.
#
# # bad
# hash[ :key ]
# array[ index ]
#
# # good
# hash[:key]
# array[index]
#
# @example EnforcedStyle: space
# # The `space` style enforces that reference brackets have
# # surrounding space.
#
# # bad
# hash[:key]
# array[index]
#
# # good
# hash[ :key ]
# array[ index ]
#
#
# @example EnforcedStyleForEmptyBrackets: no_space (default)
# # The `no_space` EnforcedStyleForEmptyBrackets style enforces that
# # empty reference brackets do not contain spaces.
#
# # bad
# foo[ ]
# foo[ ]
# foo[
# ]
#
# # good
# foo[]
#
# @example EnforcedStyleForEmptyBrackets: space
# # The `space` EnforcedStyleForEmptyBrackets style enforces that
# # empty reference brackets contain exactly one space.
#
# # bad
# foo[]
# foo[ ]
# foo[
# ]
#
# # good
# foo[ ]
#
class SpaceInsideReferenceBrackets < Base
include SurroundingSpace
include ConfigurableEnforcedStyle
extend AutoCorrector
MSG = '%<command>s space inside reference brackets.'
EMPTY_MSG = '%<command>s space inside empty reference brackets.'
RESTRICT_ON_SEND = %i[[] []=].freeze
def on_send(node)
tokens = processed_source.tokens_within(node)
left_token = left_ref_bracket(node, tokens)
return unless left_token
right_token = closing_bracket(tokens, left_token)
if empty_brackets?(left_token, right_token, tokens: tokens)
return empty_offenses(node, left_token, right_token, EMPTY_MSG)
end
return if node.multiline?
if style == :no_space
no_space_offenses(node, left_token, right_token, MSG)
else
space_offenses(node, left_token, right_token, MSG)
end
end
private
def autocorrect(corrector, node)
tokens, left, right = reference_brackets(node)
if empty_brackets?(left, right, tokens: tokens)
SpaceCorrector.empty_corrections(processed_source, corrector, empty_config, left, right)
elsif style == :no_space
SpaceCorrector.remove_space(processed_source, corrector, left, right)
else
SpaceCorrector.add_space(processed_source, corrector, left, right)
end
end
def reference_brackets(node)
tokens = processed_source.tokens_within(node)
left = left_ref_bracket(node, tokens)
[tokens, left, closing_bracket(tokens, left)]
end
def left_ref_bracket(node, tokens)
current_token = tokens.reverse.find(&:left_ref_bracket?)
previous_token = previous_token(current_token)
if node.method?(:[]=) || (previous_token && !previous_token.right_bracket?)
tokens.find(&:left_ref_bracket?)
else
current_token
end
end
def closing_bracket(tokens, opening_bracket)
i = tokens.index(opening_bracket)
inner_left_brackets_needing_closure = 0
tokens[i..].each do |token|
inner_left_brackets_needing_closure += 1 if token.left_bracket?
inner_left_brackets_needing_closure -= 1 if token.right_bracket?
return token if inner_left_brackets_needing_closure.zero? && token.right_bracket?
end
end
def previous_token(current_token)
index = processed_source.tokens.index(current_token)
index.nil? || index.zero? ? nil : processed_source.tokens[index - 1]
end
def empty_config
cop_config['EnforcedStyleForEmptyBrackets']
end
end
end
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_after_colon.rb | lib/rubocop/cop/layout/space_after_colon.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for colon (`:`) not followed by some kind of space.
# N.B. this cop does not handle spaces after a ternary operator, which are
# instead handled by `Layout/SpaceAroundOperators`.
#
# @example
# # bad
# def f(a:, b:2); {a:3}; end
#
# # good
# def f(a:, b: 2); {a: 3}; end
class SpaceAfterColon < Base
extend AutoCorrector
MSG = 'Space missing after colon.'
def on_pair(node)
return if !node.colon? || node.value_omission?
colon = node.loc.operator
register_offense(colon) unless followed_by_space?(colon)
end
def on_kwoptarg(node)
# We have no direct reference to the colon source range following an
# optional keyword argument's name, so must construct one.
colon = node.loc.name.end.resize(1)
register_offense(colon) unless followed_by_space?(colon)
end
private
def register_offense(colon)
add_offense(colon) { |corrector| corrector.insert_after(colon, ' ') }
end
def followed_by_space?(colon)
/\s/.match?(colon.source_buffer.source[colon.end_pos])
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/hash_alignment.rb | lib/rubocop/cop/layout/hash_alignment.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Check that the keys, separators, and values of a multi-line hash
# literal are aligned according to configuration. The configuration
# options are:
#
# * key (left align keys, one space before hash rockets and values)
# * separator (align hash rockets and colons, right align keys)
# * table (left align keys, hash rockets, and values)
#
# The treatment of hashes passed as the last argument to a method call
# can also be configured. The options are:
#
# * always_inspect
# * always_ignore
# * ignore_implicit (without curly braces)
#
# Alternatively you can specify multiple allowed styles. That's done by
# passing a list of styles to EnforcedHashRocketStyle and EnforcedColonStyle.
#
# @example EnforcedHashRocketStyle: key (default)
# # bad
# {
# :foo => bar,
# :ba => baz
# }
# {
# :foo => bar,
# :ba => baz
# }
#
# # good
# {
# :foo => bar,
# :ba => baz
# }
#
# @example EnforcedHashRocketStyle: separator
# # bad
# {
# :foo => bar,
# :ba => baz
# }
# {
# :foo => bar,
# :ba => baz
# }
#
# # good
# {
# :foo => bar,
# :ba => baz
# }
#
# @example EnforcedHashRocketStyle: table
# # bad
# {
# :foo => bar,
# :ba => baz
# }
#
# # good
# {
# :foo => bar,
# :ba => baz
# }
#
# @example EnforcedColonStyle: key (default)
# # bad
# {
# foo: bar,
# ba: baz
# }
# {
# foo: bar,
# ba: baz
# }
#
# # good
# {
# foo: bar,
# ba: baz
# }
#
# @example EnforcedColonStyle: separator
# # bad
# {
# foo: bar,
# ba: baz
# }
#
# # good
# {
# foo: bar,
# ba: baz
# }
#
# @example EnforcedColonStyle: table
# # bad
# {
# foo: bar,
# ba: baz
# }
#
# # good
# {
# foo: bar,
# ba: baz
# }
#
# @example EnforcedLastArgumentHashStyle: always_inspect (default)
# # Inspect both implicit and explicit hashes.
#
# # bad
# do_something(foo: 1,
# bar: 2)
#
# # bad
# do_something({foo: 1,
# bar: 2})
#
# # good
# do_something(foo: 1,
# bar: 2)
#
# # good
# do_something(
# foo: 1,
# bar: 2
# )
#
# # good
# do_something({foo: 1,
# bar: 2})
#
# # good
# do_something({
# foo: 1,
# bar: 2
# })
#
# @example EnforcedLastArgumentHashStyle: always_ignore
# # Ignore both implicit and explicit hashes.
#
# # good
# do_something(foo: 1,
# bar: 2)
#
# # good
# do_something({foo: 1,
# bar: 2})
#
# @example EnforcedLastArgumentHashStyle: ignore_implicit
# # Ignore only implicit hashes.
#
# # bad
# do_something({foo: 1,
# bar: 2})
#
# # good
# do_something(foo: 1,
# bar: 2)
#
# @example EnforcedLastArgumentHashStyle: ignore_explicit
# # Ignore only explicit hashes.
#
# # bad
# do_something(foo: 1,
# bar: 2)
#
# # good
# do_something({foo: 1,
# bar: 2})
#
class HashAlignment < Base
include HashAlignmentStyles
include RangeHelp
extend AutoCorrector
MESSAGES = {
KeyAlignment => 'Align the keys of a hash literal if they span more than one line.',
SeparatorAlignment => 'Align the separators of a hash literal if they span more than ' \
'one line.',
TableAlignment => 'Align the keys and values of a hash literal if they span more than ' \
'one line.',
KeywordSplatAlignment => 'Align keyword splats with the rest of the hash if it spans ' \
'more than one line.'
}.freeze
SEPARATOR_ALIGNMENT_STYLES = %w[EnforcedColonStyle EnforcedHashRocketStyle].freeze
def on_send(node)
return unless node.arguments?
last_argument = node.last_argument
return unless last_argument.hash_type? && ignore_hash_argument?(last_argument)
ignore_node(last_argument)
end
alias on_csend on_send
alias on_super on_send
alias on_yield on_send
def on_hash(node)
return if autocorrect_incompatible_with_other_cops?(node) || ignored_node?(node) ||
node.pairs.empty? || node.single_line?
proc = ->(a) { a.checkable_layout?(node) }
return unless alignment_for_hash_rockets.any?(proc) && alignment_for_colons.any?(proc)
check_pairs(node)
end
attr_accessor :offenses_by, :column_deltas
private
def autocorrect_incompatible_with_other_cops?(node)
return false unless enforce_first_argument_with_fixed_indentation? &&
node.pairs.any? &&
node.parent&.call_type?
left_sibling = argument_before_hash(node)
parent_loc = node.parent.loc
selector = left_sibling || parent_loc.selector || parent_loc.expression
same_line?(selector, node.pairs.first)
end
def argument_before_hash(hash_node)
return hash_node.children.first.children.first if hash_node.children.first.kwsplat_type?
hash_node.left_sibling.respond_to?(:loc) ? hash_node.left_sibling : nil
end
def reset!
self.offenses_by = {}
self.column_deltas = Hash.new { |hash, key| hash[key] = {} }
end
def check_pairs(node)
first_pair = node.pairs.first
reset!
alignment_for(first_pair).each do |alignment|
delta = alignment.deltas_for_first_pair(first_pair)
check_delta delta, node: first_pair, alignment: alignment
end
node.children.each do |current|
alignment_for(current).each do |alignment|
delta = alignment.deltas(first_pair, current)
check_delta delta, node: current, alignment: alignment
end
end
add_offenses
end
def add_offenses
kwsplat_offenses = offenses_by.delete(KeywordSplatAlignment)
register_offenses_with_format(kwsplat_offenses, KeywordSplatAlignment)
format, offenses = offenses_by.min_by { |_, v| v.length }
register_offenses_with_format(offenses, format)
end
def register_offenses_with_format(offenses, format)
(offenses || []).each do |offense|
add_offense(offense, message: MESSAGES[format]) do |corrector|
delta = column_deltas[alignment_for(offense).first.class][offense]
correct_node(corrector, offense, delta) unless delta.nil?
end
end
end
def check_delta(delta, node:, alignment:)
offenses_by[alignment.class] ||= []
return if good_alignment? delta
column_deltas[alignment.class][node] = delta
offenses_by[alignment.class].push(node)
end
def ignore_hash_argument?(node)
case cop_config['EnforcedLastArgumentHashStyle']
when 'always_inspect' then false
when 'always_ignore' then true
when 'ignore_explicit' then node.braces?
when 'ignore_implicit' then !node.braces?
end
end
def alignment_for(pair)
if pair.kwsplat_type?
[KeywordSplatAlignment.new]
elsif pair.hash_rocket?
alignment_for_hash_rockets
else
alignment_for_colons
end
end
def alignment_for_hash_rockets
@alignment_for_hash_rockets ||= new_alignment('EnforcedHashRocketStyle')
end
def alignment_for_colons
@alignment_for_colons ||= new_alignment('EnforcedColonStyle')
end
def correct_node(corrector, node, delta)
# We can't use the instance variable inside the lambda. That would
# just give each lambda the same reference and they would all get the
# last value of each. A local variable fixes the problem.
if node.value && node.respond_to?(:value_omission?) && !node.value_omission?
correct_key_value(corrector, delta, node.key.source_range,
node.value.source_range,
node.loc.operator)
else
delta_value = delta[:key] || 0
correct_no_value(corrector, delta_value, node.source_range)
end
end
def correct_no_value(corrector, key_delta, key)
adjust(corrector, key_delta, key)
end
def correct_key_value(corrector, delta, key, value, separator)
# We can't use the instance variable inside the lambda. That would
# just give each lambda the same reference and they would all get the
# last value of each. Some local variables fix the problem.
separator_delta = delta[:separator] || 0
value_delta = delta[:value] || 0
key_delta = delta[:key] || 0
key_column = key.column
key_delta = -key_column if key_delta < -key_column
adjust(corrector, key_delta, key)
adjust(corrector, separator_delta, separator)
adjust(corrector, value_delta, value)
end
def new_alignment(key)
formats = cop_config[key]
formats = [formats] if formats.is_a? String
formats.uniq.map do |format|
case format
when 'key'
KeyAlignment.new
when 'table'
TableAlignment.new
when 'separator'
SeparatorAlignment.new
else
raise "Unknown #{key}: #{formats}"
end
end
end
def adjust(corrector, delta, range)
if delta.positive?
corrector.insert_before(range, ' ' * delta)
elsif delta.negative?
range = range_between(range.begin_pos - delta.abs, range.begin_pos)
corrector.remove(range)
end
end
def good_alignment?(column_deltas)
column_deltas.values.all?(&:zero?)
end
def enforce_first_argument_with_fixed_indentation?
argument_alignment_config = config.for_enabled_cop('Layout/ArgumentAlignment')
argument_alignment_config['EnforcedStyle'] == 'with_fixed_indentation'
end
def same_line?(node1, node2)
# Override `Util#same_line?`
super || node1.last_line == line(node2)
end
end
end
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/line_length.rb | lib/rubocop/cop/layout/line_length.rb | # frozen_string_literal: true
require 'uri'
module RuboCop
module Cop
module Layout
# Checks the length of lines in the source code.
# The maximum length is configurable.
# The tab size is configured in the `IndentationWidth`
# of the `Layout/IndentationStyle` cop.
# It also ignores a shebang line by default.
#
# This cop has some autocorrection capabilities.
# It can programmatically shorten certain long lines by
# inserting line breaks into expressions that can be safely
# split across lines. These include arrays, hashes, and
# method calls with argument lists.
#
# If autocorrection is enabled, the following cops
# are recommended to further format the broken lines.
# (Many of these are enabled by default.)
#
# * `Layout/ArgumentAlignment`
# * `Layout/ArrayAlignment`
# * `Layout/BlockAlignment`
# * `Layout/BlockEndNewline`
# * `Layout/ClosingParenthesisIndentation`
# * `Layout/FirstArgumentIndentation`
# * `Layout/FirstArrayElementIndentation`
# * `Layout/FirstHashElementIndentation`
# * `Layout/FirstParameterIndentation`
# * `Layout/HashAlignment`
# * `Layout/IndentationWidth`
# * `Layout/MultilineArrayLineBreaks`
# * `Layout/MultilineBlockLayout`
# * `Layout/MultilineHashBraceLayout`
# * `Layout/MultilineHashKeyLineBreaks`
# * `Layout/MultilineMethodArgumentLineBreaks`
# * `Layout/MultilineMethodParameterLineBreaks`
# * `Layout/ParameterAlignment`
# * `Style/BlockDelimiters`
#
# Together, these cops will pretty print hashes, arrays,
# method calls, etc. For example, let's say the max columns
# is 25:
#
# @example
#
# # bad
# {foo: "0000000000", bar: "0000000000", baz: "0000000000"}
#
# # good
# {foo: "0000000000",
# bar: "0000000000", baz: "0000000000"}
#
# # good (with recommended cops enabled)
# {
# foo: "0000000000",
# bar: "0000000000",
# baz: "0000000000",
# }
class LineLength < Base # rubocop:disable Metrics/ClassLength
include CheckLineBreakable
include AllowedPattern
include RangeHelp
include LineLengthHelp
extend AutoCorrector
exclude_limit 'Max'
MSG = 'Line is too long. [%<length>d/%<max>d]'
def on_block(node)
check_for_breakable_block(node)
end
alias on_numblock on_block
alias on_itblock on_block
def on_str(node)
check_for_breakable_str(node)
end
def on_dstr(node)
check_for_breakable_dstr(node)
end
def on_potential_breakable_node(node)
check_for_breakable_node(node)
end
alias on_array on_potential_breakable_node
alias on_hash on_potential_breakable_node
alias on_send on_potential_breakable_node
alias on_csend on_potential_breakable_node
alias on_def on_potential_breakable_node
alias on_defs on_potential_breakable_node
def on_new_investigation
return unless processed_source.raw_source.include?(';')
check_for_breakable_semicolons(processed_source)
end
def on_investigation_end
processed_source.lines.each_with_index do |line, line_index|
check_line(line, line_index)
end
end
private
attr_accessor :breakable_range
def check_for_breakable_node(node)
breakable_node = extract_breakable_node(node, max)
return if breakable_node.nil?
line_index = breakable_node.first_line - 1
range = breakable_node.source_range
existing = breakable_range_by_line_index[line_index]
return if existing
breakable_range_by_line_index[line_index] = range
end
def check_for_breakable_semicolons(processed_source)
tokens = processed_source.tokens.select { |t| t.type == :tSEMI }
tokens.reverse_each do |token|
range = breakable_range_after_semicolon(token)
breakable_range_by_line_index[range.line - 1] = range if range
end
end
def check_for_breakable_block(block_node)
return unless block_node.single_line?
return if receiver_contains_heredoc?(block_node)
line_index = block_node.loc.line - 1
range = breakable_block_range(block_node)
pos = range.begin_pos + 1
breakable_range_by_line_index[line_index] = range_between(pos, pos + 1)
end
def check_for_breakable_str(node)
line_index = node.loc.line - 1
return if breakable_range_by_line_index[line_index]
return unless breakable_string?(node)
return unless (delimiter = string_delimiter(node))
return unless (pos = breakable_string_position(node))
breakable_range_by_line_index[line_index] = range_between(pos, pos + 1)
breakable_string_delimiters[line_index] = delimiter
end
def check_for_breakable_dstr(node) # rubocop:disable Metrics/AbcSize
line_index = node.loc.line - 1
return if breakable_range_by_line_index[line_index]
return unless breakable_dstr?(node)
return unless (delimiter = string_delimiter(node))
node.each_child_node(:begin).detect do |begin_node|
next unless (pos = breakable_dstr_begin_position(begin_node))
breakable_range_by_line_index[line_index] = range_between(pos, pos + 1)
breakable_string_delimiters[line_index] = delimiter
end
end
def breakable_string?(node)
allow_string_split? &&
node.single_line? &&
!node.heredoc? &&
# TODO: strings inside hashes, kwargs and arrays are currently ignored,
# but could be considered in the future
!node.parent&.type?(:pair, :kwoptarg, :array)
end
def breakable_block_range(block_node)
if block_node.arguments? && !block_node.lambda?
block_node.arguments.loc.end
else
block_node.braces? ? block_node.loc.begin : block_node.loc.begin.adjust(begin_pos: 1)
end
end
def breakable_range_after_semicolon(semicolon_token)
range = semicolon_token.pos
end_pos = range.end_pos
next_range = range_between(end_pos, end_pos + 1)
return nil unless same_line?(next_range, range)
next_char = next_range.source
return nil if /[\r\n]/.match?(next_char)
return nil if next_char == ';'
next_range
end
def breakable_string_position(node)
source_range = node.source_range
return if source_range.last_column < max
return unless (pos = breakable_string_range(node))
pos.end_pos unless pos.end_pos == source_range.begin_pos
end
# Locate where to break a string that is too long, ensuring that escape characters
# are not bisected.
# If the string contains spaces, use them to determine a place for a clean break;
# otherwise, the string will be broken at the line length limit.
def breakable_string_range(node)
source_range = node.source_range
relevant_substr = largest_possible_string(node)
if (space_pos = relevant_substr.rindex(/\s/))
source_range.resize(space_pos + 1)
elsif (escape_pos = relevant_substr.rindex(/\\(u[\da-f]{0,4}|x[\da-f]{0,2})?\z/))
source_range.resize(escape_pos)
else
adjustment = max - source_range.last_column - 3
return if adjustment.abs > source_range.size
source_range.adjust(end_pos: adjustment)
end
end
def breakable_dstr_begin_position(node)
source_range = node.source_range
source_range.begin_pos if source_range.column < max && source_range.last_column >= max
end
def breakable_range_by_line_index
@breakable_range_by_line_index ||= {}
end
def breakable_string_delimiters
@breakable_string_delimiters ||= {}
end
def heredocs
@heredocs ||= extract_heredocs(processed_source.ast)
end
def highlight_start(line)
# TODO: The max with 0 is a quick fix to avoid crashes when a line
# begins with many tabs, but getting a correct highlighting range
# when tabs are used for indentation doesn't work currently.
[max - indentation_difference(line), 0].max
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def check_line(line, line_index)
return if line_length(line) <= max
return if allowed_line?(line, line_index)
if allow_rbs_inline_annotation? && rbs_inline_annotation_on_source_line?(line_index)
return
end
if allow_cop_directives? && directive_on_source_line?(line_index)
return check_directive_line(line, line_index)
end
return check_line_for_exemptions(line, line_index) if allow_uri? || allow_qualified_name?
register_offense(excess_range(nil, line, line_index), line, line_index)
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def allowed_line?(line, line_index)
matches_allowed_pattern?(line) ||
shebang?(line, line_index) ||
(heredocs && line_in_permitted_heredoc?(line_index.succ))
end
def shebang?(line, line_index)
line_index.zero? && line.start_with?('#!')
end
def register_offense(loc, line, line_index, length: line_length(line))
message = format(MSG, length: length, max: max)
self.breakable_range = breakable_range_by_line_index[line_index]
add_offense(loc, message: message) do |corrector|
self.max = line_length(line)
insertion = if (delimiter = breakable_string_delimiters[line_index])
[delimiter, " \\\n", delimiter].join
else
"\n"
end
corrector.insert_before(breakable_range, insertion) unless breakable_range.nil?
end
end
def excess_range(uri_range, line, line_index)
excessive_position = if uri_range && uri_range.begin < max
uri_range.end
else
highlight_start(line)
end
source_range(processed_source.buffer, line_index + 1,
excessive_position...(line_length(line)))
end
def max
cop_config['Max']
end
alias max_line_length max
def allow_heredoc?
allowed_heredoc
end
def allowed_heredoc
cop_config['AllowHeredoc']
end
def allow_string_split?
cop_config['SplitStrings']
end
def extract_heredocs(ast)
return [] unless ast
ast.each_node(:any_str).select(&:heredoc?).map do |node|
body = node.location.heredoc_body
delimiter = node.location.heredoc_end.source.strip
[body.first_line...body.last_line, delimiter]
end
end
def line_in_permitted_heredoc?(line_number)
return false unless allowed_heredoc
heredocs.any? do |range, delimiter|
range.cover?(line_number) &&
(allowed_heredoc == true || allowed_heredoc.include?(delimiter))
end
end
def line_in_heredoc?(line_number)
heredocs.any? { |range, _delimiter| range.cover?(line_number) }
end
def receiver_contains_heredoc?(node)
return false unless (receiver = node.receiver)
return true if receiver.any_str_type? && receiver.heredoc?
receiver.each_descendant(:any_str).any?(&:heredoc?)
end
def check_directive_line(line, line_index)
length_without_directive = line_length_without_directive(line)
return if length_without_directive <= max
range = max..(length_without_directive - 1)
register_offense(
source_range(
processed_source.buffer,
line_index + 1,
range
),
line,
line_index,
length: length_without_directive
)
end
def check_line_for_exemptions(line, line_index)
uri_range = range_if_applicable(line, :uri)
qualified_name_range = range_if_applicable(line, :qualified_name)
return if allowed_combination?(line, uri_range, qualified_name_range)
range = uri_range || qualified_name_range
register_offense(excess_range(range, line, line_index), line, line_index)
end
def range_if_applicable(line, type)
return unless type == :uri ? allow_uri? : allow_qualified_name?
find_excessive_range(line, type)
end
def allowed_combination?(line, uri_range, qualified_name_range)
if uri_range && qualified_name_range
allowed_position?(line, uri_range) && allowed_position?(line, qualified_name_range)
elsif uri_range
allowed_position?(line, uri_range)
elsif qualified_name_range
allowed_position?(line, qualified_name_range)
else
false
end
end
def breakable_dstr?(node)
# If the `dstr` only contains one child, it cannot be broken
breakable_string?(node) && !node.child_nodes.one?
end
def string_delimiter(node)
delimiter = node.loc.begin
delimiter ||= node.parent.loc.begin if node.parent&.dstr_type? && node.parent.loc?(:begin)
delimiter = delimiter&.source
delimiter if %w[' "].include?(delimiter)
end
# Find the largest possible substring of a string node to retain before a break
def largest_possible_string(node)
# The maximum allowed length of a string value is:
# `Max` - end delimiter (quote) - continuation characters (space and slash)
max_length = max - 3
# If the string doesn't start at the beginning of the line, the max length is offset
max_length -= column_offset_between(node.loc, node.parent.loc) if node.parent
node.source[0...(max_length)]
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/array_alignment.rb | lib/rubocop/cop/layout/array_alignment.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Check that the elements of a multi-line array literal are
# aligned.
#
# @example EnforcedStyle: with_first_element (default)
# # good
#
# array = [1, 2, 3,
# 4, 5, 6]
# array = ['run',
# 'forrest',
# 'run']
#
# # bad
#
# array = [1, 2, 3,
# 4, 5, 6]
# array = ['run',
# 'forrest',
# 'run']
#
# @example EnforcedStyle: with_fixed_indentation
# # good
#
# array = [1, 2, 3,
# 4, 5, 6]
#
# # bad
#
# array = [1, 2, 3,
# 4, 5, 6]
class ArrayAlignment < Base
include Alignment
extend AutoCorrector
ALIGN_ELEMENTS_MSG = 'Align the elements of an array literal ' \
'if they span more than one line.'
FIXED_INDENT_MSG = 'Use one level of indentation for elements ' \
'following the first line of a multi-line array.'
def on_array(node)
return if node.children.size < 2
return if node.parent&.masgn_type?
check_alignment(node.children, base_column(node, node.children))
end
private
def autocorrect(corrector, node)
AlignmentCorrector.correct(corrector, processed_source, node, column_delta)
end
def message(_range)
fixed_indentation? ? FIXED_INDENT_MSG : ALIGN_ELEMENTS_MSG
end
def fixed_indentation?
cop_config['EnforcedStyle'] == 'with_fixed_indentation'
end
def base_column(node, args)
if fixed_indentation?
lineno = target_method_lineno(node)
line = node.source_range.source_buffer.source_line(lineno)
indentation_of_line = /\S.*/.match(line).begin(0)
indentation_of_line + configured_indentation_width
else
display_column(args.first.source_range)
end
end
def target_method_lineno(node)
node.bracketed? ? node.loc.line : node.parent.loc.line
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/space_around_equals_in_parameter_default.rb | lib/rubocop/cop/layout/space_around_equals_in_parameter_default.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks that the equals signs in parameter default assignments
# have or don't have surrounding space depending on configuration.
#
# @example EnforcedStyle: space (default)
# # bad
# def some_method(arg1=:default, arg2=nil, arg3=[])
# # do something...
# end
#
# # good
# def some_method(arg1 = :default, arg2 = nil, arg3 = [])
# # do something...
# end
#
# @example EnforcedStyle: no_space
# # bad
# def some_method(arg1 = :default, arg2 = nil, arg3 = [])
# # do something...
# end
#
# # good
# def some_method(arg1=:default, arg2=nil, arg3=[])
# # do something...
# end
class SpaceAroundEqualsInParameterDefault < Base
include SurroundingSpace
include ConfigurableEnforcedStyle
include RangeHelp
extend AutoCorrector
MSG = 'Surrounding space %<type>s in default value assignment.'
def on_optarg(node)
tokens = processed_source.tokens_within(node)
arg, equals, value = tokens.take(3)
check_optarg(arg, equals, value)
end
private
def check_optarg(arg, equals, value)
space_on_both_sides = space_on_both_sides?(arg, equals)
no_surrounding_space = no_surrounding_space?(arg, equals)
if (style == :space && space_on_both_sides) ||
(style == :no_space && no_surrounding_space)
correct_style_detected
else
incorrect_style_detected(arg, value)
end
end
def incorrect_style_detected(arg, value)
range = range_between(arg.end_pos, value.begin_pos)
add_offense(range) do |corrector|
autocorrect(corrector, range)
opposite_style_detected
end
end
def autocorrect(corrector, range)
m = range.source.match(/=\s*(\S+)/)
rest = m ? m.captures[0] : ''
replacement = style == :space ? ' = ' : '='
corrector.replace(range, replacement + rest)
end
def space_on_both_sides?(arg, equals)
arg.space_after? && equals.space_after?
end
def no_surrounding_space?(arg, equals)
!arg.space_after? && !equals.space_after?
end
def message(_node)
format(MSG, type: style == :space ? 'missing' : 'detected')
end
end
end
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_after_magic_comment.rb | lib/rubocop/cop/layout/empty_line_after_magic_comment.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for a newline after the final magic comment.
#
# @example
# # good
# # frozen_string_literal: true
#
# # Some documentation for Person
# class Person
# # Some code
# end
#
# # bad
# # frozen_string_literal: true
# # Some documentation for Person
# class Person
# # Some code
# end
class EmptyLineAfterMagicComment < Base
include RangeHelp
extend AutoCorrector
MSG = 'Add an empty line after magic comments.'
def on_new_investigation
return unless (last_magic_comment = last_magic_comment(processed_source))
return unless (next_line = processed_source[last_magic_comment.loc.line])
return if next_line.strip.empty?
offending_range = offending_range(last_magic_comment)
add_offense(offending_range) do |corrector|
corrector.insert_before(offending_range, "\n")
end
end
private
def offending_range(last_magic_comment)
source_range(processed_source.buffer, last_magic_comment.loc.line + 1, 0)
end
# Find the last magic comment in the source file.
#
# Take all comments that precede the first line of code (or just take
# them all in the case when there is no code), select the
# magic comments, and return the last magic comment in the file.
#
# @return [Parser::Source::Comment] if magic comments exist before code
# @return [nil] otherwise
def last_magic_comment(source)
comments_before_code(source)
.reverse
.find { |comment| MagicComment.parse(comment.text).any? }
end
def comments_before_code(source)
if source.ast
source.comments.take_while { |comment| comment.loc.line < source.ast.loc.line }
else
source.comments
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/heredoc_argument_closing_parenthesis.rb | lib/rubocop/cop/layout/heredoc_argument_closing_parenthesis.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for the placement of the closing parenthesis
# in a method call that passes a HEREDOC string as an argument.
# It should be placed at the end of the line containing the
# opening HEREDOC tag.
#
# @example
# # bad
#
# foo(<<-SQL
# bar
# SQL
# )
#
# foo(<<-SQL, 123, <<-NOSQL,
# bar
# SQL
# baz
# NOSQL
# )
#
# foo(
# bar(<<-SQL
# baz
# SQL
# ),
# 123,
# )
#
# # good
#
# foo(<<-SQL)
# bar
# SQL
#
# foo(<<-SQL, 123, <<-NOSQL)
# bar
# SQL
# baz
# NOSQL
#
# foo(
# bar(<<-SQL),
# baz
# SQL
# 123,
# )
#
class HeredocArgumentClosingParenthesis < Base
include RangeHelp
extend AutoCorrector
MSG = 'Put the closing parenthesis for a method call with a ' \
'HEREDOC parameter on the same line as the HEREDOC opening.'
def self.autocorrect_incompatible_with
[Style::TrailingCommaInArguments]
end
def on_send(node)
heredoc_arg = extract_heredoc_argument(node)
return unless heredoc_arg
outermost_send = outermost_send_on_same_line(heredoc_arg)
return unless outermost_send
return if end_keyword_before_closing_parenthesis?(node)
return if subsequent_closing_parentheses_in_same_line?(outermost_send)
return if exist_argument_between_heredoc_end_and_closing_parentheses?(node)
add_offense(outermost_send.loc.end) do |corrector|
autocorrect(corrector, outermost_send)
end
end
alias on_csend on_send
private
# Autocorrection note:
#
# Commas are a bit tricky to handle when the method call is
# embedded in another expression. Here's an example:
#
# [
# first_array_value,
# foo(<<-SQL, 123, 456,
# SELECT * FROM db
# SQL
# ),
# third_array_value,
# ]
#
# The "internal" trailing comma is after `456`.
# The "external" trailing comma is after `)`.
#
# To autocorrect, we remove the latter, and move the former up:
#
# [
# first_array_value,
# foo(<<-SQL, 123, 456),
# SELECT * FROM db
# SQL
# third_array_value,
# ]
def autocorrect(corrector, node)
fix_closing_parenthesis(node, corrector)
remove_internal_trailing_comma(node, corrector) if internal_trailing_comma?(node)
fix_external_trailing_comma(node, corrector) if external_trailing_comma?(node)
end
def outermost_send_on_same_line(heredoc)
previous = heredoc
current = previous.parent
until send_missing_closing_parens?(current, previous, heredoc)
previous = current
current = current.parent
return unless previous && current
end
current
end
def send_missing_closing_parens?(parent, child, heredoc)
parent&.call_type? &&
parent.arguments.include?(child) &&
parent.loc.begin &&
parent.loc.end.line != heredoc.last_line
end
def extract_heredoc_argument(node)
node.arguments.find { |arg_node| extract_heredoc(arg_node) }
end
def extract_heredoc(node)
return node if heredoc_node?(node)
return node.receiver if single_line_send_with_heredoc_receiver?(node)
return unless node.hash_type?
node.values.find do |v|
heredoc = extract_heredoc(v)
return heredoc if heredoc
end
end
def heredoc_node?(node)
node.respond_to?(:heredoc?) && node.heredoc?
end
def single_line_send_with_heredoc_receiver?(node)
return false unless node.send_type?
return false unless heredoc_node?(node.receiver)
node.receiver.location.heredoc_end.end_pos > node.source_range.end_pos
end
# Closing parenthesis helpers.
def end_keyword_before_closing_parenthesis?(parenthesized_send_node)
parenthesized_send_node.ancestors.any? do |ancestor|
ancestor.loc_is?(:end, 'end')
end
end
def subsequent_closing_parentheses_in_same_line?(outermost_send)
last_arg_of_outer_send = outermost_send.last_argument
return false unless last_arg_of_outer_send&.loc?(:end) &&
(end_of_last_arg_of_outer_send = last_arg_of_outer_send.loc.end)
end_of_outer_send = outermost_send.loc.end
same_line?(end_of_outer_send, end_of_last_arg_of_outer_send) &&
end_of_outer_send.column == end_of_last_arg_of_outer_send.column + 1
end
def fix_closing_parenthesis(node, corrector)
remove_incorrect_closing_paren(node, corrector)
add_correct_closing_paren(node, corrector)
end
def add_correct_closing_paren(node, corrector)
corrector.insert_after(node.last_argument, ')')
end
def remove_incorrect_closing_paren(node, corrector)
corrector.remove(
range_between(
incorrect_parenthesis_removal_begin(node),
incorrect_parenthesis_removal_end(node)
)
)
end
def incorrect_parenthesis_removal_begin(node)
end_pos = node.source_range.end_pos
if safe_to_remove_line_containing_closing_paren?(node)
last_line_length = node.source.scan(/\n(.*)$/).last[0].size
end_pos - last_line_length - 1 # Add one for the line break itself.
else
end_pos - 1 # Just the `)` at the end of the string
end
end
def safe_to_remove_line_containing_closing_paren?(node)
last_line = processed_source[node.loc.end.line - 1]
# Safe to remove if last line only contains `)`, `,`, and whitespace.
last_line.match?(/^ *\) {0,20},{0,1} *$/)
end
def incorrect_parenthesis_removal_end(node)
end_pos = node.source_range.end_pos
if processed_source.buffer.source[end_pos] == ','
end_pos + 1
else
end_pos
end
end
def exist_argument_between_heredoc_end_and_closing_parentheses?(node)
return true unless node.loc.end
return false unless (heredoc_end = find_most_bottom_of_heredoc_end(node.arguments))
heredoc_end < node.loc.end.begin_pos &&
range_between(heredoc_end, node.loc.end.begin_pos).source.strip != ''
end
def find_most_bottom_of_heredoc_end(arguments)
arguments.filter_map do |argument|
argument.loc.heredoc_end.end_pos if argument.loc?(:heredoc_end)
end.max
end
# Internal trailing comma helpers.
def remove_internal_trailing_comma(node, corrector)
offset = internal_trailing_comma_offset_from_last_arg(node)
last_arg_end_pos = node.children.last.source_range.end_pos
corrector.remove(range_between(last_arg_end_pos, last_arg_end_pos + offset))
end
def internal_trailing_comma?(node)
!internal_trailing_comma_offset_from_last_arg(node).nil?
end
# Returns nil if no trailing internal comma.
def internal_trailing_comma_offset_from_last_arg(node)
source_after_last_arg = range_between(
node.children.last.source_range.end_pos,
node.loc.end.begin_pos
).source
first_comma_offset = source_after_last_arg.index(',')
first_new_line_offset = source_after_last_arg.index("\n")
return if first_comma_offset.nil?
return if first_new_line_offset.nil?
return if first_comma_offset > first_new_line_offset
first_comma_offset + 1
end
# External trailing comma helpers.
def fix_external_trailing_comma(node, corrector)
remove_incorrect_external_trailing_comma(node, corrector)
add_correct_external_trailing_comma(node, corrector)
end
def add_correct_external_trailing_comma(node, corrector)
return unless external_trailing_comma?(node)
corrector.insert_after(node.last_argument, ',')
end
def remove_incorrect_external_trailing_comma(node, corrector)
end_pos = node.source_range.end_pos
return unless external_trailing_comma?(node)
corrector.remove(
range_between(
end_pos,
end_pos + external_trailing_comma_offset_from_loc_end(node)
)
)
end
def external_trailing_comma?(node)
!external_trailing_comma_offset_from_loc_end(node).nil?
end
# Returns nil if no trailing external comma.
def external_trailing_comma_offset_from_loc_end(node)
end_pos = node.source_range.end_pos
offset = 0
limit = 20
offset += 1 while offset < limit && space?(end_pos + offset)
char = processed_source.buffer.source[end_pos + offset]
return unless char == ','
offset + 1 # Add one to include the comma.
end
def space?(pos)
processed_source.buffer.source[pos] == ' '
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/first_parameter_indentation.rb | lib/rubocop/cop/layout/first_parameter_indentation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks the indentation of the first parameter in a method
# definition. Parameters after the first one are checked by
# `Layout/ParameterAlignment`, not by this cop.
#
# For indenting the first argument of method _calls_, check out
# `Layout/FirstArgumentIndentation`, which supports options related to
# nesting that are irrelevant for method _definitions_.
#
# @example
#
# # bad
# def some_method(
# first_param,
# second_param)
# 123
# end
#
# @example EnforcedStyle: consistent (default)
# # The first parameter should always be indented one step more than the
# # preceding line.
#
# # good
# def some_method(
# first_param,
# second_param)
# 123
# end
#
# @example EnforcedStyle: align_parentheses
# # The first parameter should always be indented one step more than the
# # opening parenthesis.
#
# # good
# def some_method(
# first_param,
# second_param)
# 123
# end
class FirstParameterIndentation < Base
include Alignment
include ConfigurableEnforcedStyle
include MultilineElementIndentation
extend AutoCorrector
MSG = 'Use %<configured_indentation_width>d spaces for indentation ' \
'in method args, relative to %<base_description>s.'
def on_def(node)
return if node.arguments.empty?
return if node.arguments.loc.begin.nil?
check(node)
end
alias on_defs on_def
private
def autocorrect(corrector, node)
AlignmentCorrector.correct(corrector, processed_source, node, @column_delta)
end
def brace_alignment_style
:align_parentheses
end
def check(def_node)
return if ignored_node?(def_node)
left_parenthesis = def_node.arguments.loc.begin
first_elem = def_node.first_argument
return unless first_elem
return if same_line?(first_elem, left_parenthesis)
check_first(first_elem, left_parenthesis, nil, 0)
end
# Returns the description of what the correct indentation is based on.
def base_description(_)
if style == brace_alignment_style
'the position of the opening parenthesis'
else
'the start of the line where the left parenthesis is'
end
end
def message(base_description)
format(
MSG,
configured_indentation_width: configured_indentation_width,
base_description: base_description
)
end
end
end
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/case_indentation.rb | lib/rubocop/cop/layout/case_indentation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks how the `when` and ``in``s of a `case` expression
# are indented in relation to its `case` or `end` keyword.
#
# It will register a separate offense for each misaligned `when` and `in`.
#
# @example
# # If Layout/EndAlignment is set to keyword style (default)
# # *case* and *end* should always be aligned to same depth,
# # and therefore *when* should always be aligned to both -
# # regardless of configuration.
#
# # bad for all styles
# case n
# when 0
# x * 2
# else
# y / 3
# end
#
# case n
# in pattern
# x * 2
# else
# y / 3
# end
#
# # good for all styles
# case n
# when 0
# x * 2
# else
# y / 3
# end
#
# case n
# in pattern
# x * 2
# else
# y / 3
# end
#
# @example EnforcedStyle: case (default)
# # if EndAlignment is set to other style such as
# # start_of_line (as shown below), then *when* alignment
# # configuration does have an effect.
#
# # bad
# a = case n
# when 0
# x * 2
# else
# y / 3
# end
#
# a = case n
# in pattern
# x * 2
# else
# y / 3
# end
#
# # good
# a = case n
# when 0
# x * 2
# else
# y / 3
# end
#
# a = case n
# in pattern
# x * 2
# else
# y / 3
# end
#
# @example EnforcedStyle: end
# # bad
# a = case n
# when 0
# x * 2
# else
# y / 3
# end
#
# a = case n
# in pattern
# x * 2
# else
# y / 3
# end
#
# # good
# a = case n
# when 0
# x * 2
# else
# y / 3
# end
#
# a = case n
# in pattern
# x * 2
# else
# y / 3
# end
class CaseIndentation < Base
include Alignment
include ConfigurableEnforcedStyle
include RangeHelp
extend AutoCorrector
MSG = 'Indent `%<branch_type>s` %<depth>s `%<base>s`.'
def on_case(case_node)
return if case_node.single_line?
return if enforced_style_end? && end_and_last_conditional_same_line?(case_node)
case_node.when_branches.each { |when_node| check_when(when_node, 'when') }
end
def on_case_match(case_match_node)
return if case_match_node.single_line?
return if enforced_style_end? && end_and_last_conditional_same_line?(case_match_node)
case_match_node.each_in_pattern { |in_pattern_node| check_when(in_pattern_node, 'in') }
end
private
def end_and_last_conditional_same_line?(node)
end_line = node.loc.end&.line
last_conditional_line = if node.loc.else
node.loc.else.line
else
node.child_nodes.last.loc.begin&.line
end
end_line && last_conditional_line && end_line == last_conditional_line
end
def enforced_style_end?
cop_config[style_parameter_name] == 'end'
end
def check_when(when_node, branch_type)
when_column = when_node.loc.keyword.column
base_column = base_column(when_node.parent, style)
if when_column == base_column + indentation_width
correct_style_detected
else
incorrect_style(when_node, branch_type)
end
end
def indent_one_step?
cop_config['IndentOneStep']
end
def indentation_width
indent_one_step? ? configured_indentation_width : 0
end
def incorrect_style(when_node, branch_type)
depth = indent_one_step? ? 'one step more than' : 'as deep as'
message = format(MSG, branch_type: branch_type, depth: depth, base: style)
add_offense(when_node.loc.keyword, message: message) do |corrector|
detect_incorrect_style(when_node)
whitespace = whitespace_range(when_node)
corrector.replace(whitespace, replacement(when_node)) if whitespace.source.strip.empty?
end
end
def detect_incorrect_style(when_node)
when_column = when_node.loc.keyword.column
base_column = base_column(when_node.parent, alternative_style)
if when_column == base_column
opposite_style_detected
else
unrecognized_style_detected
end
end
def base_column(case_node, base)
case base
when :case then case_node.location.keyword.column
when :end then case_node.location.end.column
end
end
def whitespace_range(node)
when_column = node.location.keyword.column
begin_pos = node.loc.keyword.begin_pos
range_between(begin_pos - when_column, begin_pos)
end
def replacement(node)
case_node = node.each_ancestor(:case, :case_match).first
base_type = cop_config[style_parameter_name] == 'end' ? :end : :case
column = base_column(case_node, base_type)
column += indentation_width
' ' * column
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/closing_heredoc_indentation.rb | lib/rubocop/cop/layout/closing_heredoc_indentation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks the indentation of here document closings.
#
# @example
#
# # bad
# class Foo
# def bar
# <<~SQL
# 'Hi'
# SQL
# end
# end
#
# # good
# class Foo
# def bar
# <<~SQL
# 'Hi'
# SQL
# end
# end
#
# # bad
#
# # heredoc contents is before closing heredoc.
# foo arg,
# <<~EOS
# Hi
# EOS
#
# # good
# foo arg,
# <<~EOS
# Hi
# EOS
#
# # good
# foo arg,
# <<~EOS
# Hi
# EOS
#
class ClosingHeredocIndentation < Base
include Heredoc
extend AutoCorrector
SIMPLE_HEREDOC = '<<'
MSG = '`%<closing>s` is not aligned with `%<opening>s`.'
MSG_ARG = '`%<closing>s` is not aligned with `%<opening>s` or ' \
'beginning of method definition.'
def on_heredoc(node)
return if heredoc_type(node) == SIMPLE_HEREDOC ||
opening_indentation(node) == closing_indentation(node) ||
argument_indentation_correct?(node)
message = message(node)
add_offense(node.loc.heredoc_end, message: message) do |corrector|
corrector.replace(node.loc.heredoc_end, indented_end(node))
end
end
private
def opening_indentation(node)
indent_level(heredoc_opening(node))
end
def argument_indentation_correct?(node)
return false unless node.argument? || node.chained?
opening_indentation(
find_node_used_heredoc_argument(node.parent)
) == closing_indentation(node)
end
def closing_indentation(node)
indent_level(heredoc_closing(node))
end
def heredoc_opening(node)
node.source_range.source_line
end
def heredoc_closing(node)
node.loc.heredoc_end.source_line
end
def indented_end(node)
closing_indent = closing_indentation(node)
opening_indent = opening_indentation(node)
closing_text = heredoc_closing(node)
closing_text.gsub(/^\s{#{closing_indent}}/, ' ' * opening_indent)
end
def find_node_used_heredoc_argument(node)
if node.parent&.send_type?
find_node_used_heredoc_argument(node.parent)
else
node
end
end
def message(node)
format(
node.argument? ? MSG_ARG : MSG,
closing: heredoc_closing(node).strip,
opening: heredoc_opening(node).strip
)
end
def indent_level(source_line)
source_line[/\A */].length
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/else_alignment.rb | lib/rubocop/cop/layout/else_alignment.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks the alignment of else keywords. Normally they should
# be aligned with an if/unless/while/until/begin/def/rescue keyword, but there
# are special cases when they should follow the same rules as the
# alignment of end.
#
# @example
# # bad
# if something
# code
# else
# code
# end
#
# # bad
# if something
# code
# elsif something
# code
# end
#
# # good
# if something
# code
# else
# code
# end
class ElseAlignment < Base
include EndKeywordAlignment
include Alignment
include CheckAssignment
extend AutoCorrector
MSG = 'Align `%<else_range>s` with `%<base_range>s`.'
def on_if(node, base = nil)
return if ignored_node?(node)
return unless node.else? && begins_its_line?(node.loc.else)
check_alignment(base_range_of_if(node, base), node.loc.else)
return unless node.elsif_conditional?
check_nested(node.else_branch, base)
end
def on_rescue(node)
return unless node.loc?(:else)
check_alignment(base_range_of_rescue(node), node.loc.else)
end
def on_case(node)
return unless node.else?
check_alignment(node.when_branches.last.loc.keyword, node.loc.else)
end
def on_case_match(node)
return unless node.else?
check_alignment(node.in_pattern_branches.last.loc.keyword, node.loc.else)
end
private
def autocorrect(corrector, node)
AlignmentCorrector.correct(corrector, processed_source, node, column_delta)
end
def check_nested(node, base)
on_if(node, base)
ignore_node(node)
end
def base_range_of_if(node, base)
if base
base.source_range
else
lineage = [node, *node.each_ancestor(:if)]
lineage.find { |parent| parent.if? || parent.unless? }.loc.keyword
end
end
def base_range_of_rescue(node)
parent = node.parent
parent = parent.parent if parent.ensure_type?
case parent.type
when :def, :defs then base_for_method_definition(parent)
when :kwbegin then parent.loc.begin
when :block, :numblock, :itblock
assignment_node = assignment_node(parent)
if same_line?(parent, assignment_node)
assignment_node.source_range
else
parent.send_node.source_range
end
else node.loc.keyword
end
end
def base_for_method_definition(node)
parent = node.parent
if parent&.send_type?
parent.loc.selector # For example "private def ..."
else
node.loc.keyword
end
end
def check_assignment(node, rhs)
# If there are method calls chained to the right hand side of the
# assignment, we let rhs be the receiver of those method calls before
# we check its indentation.
rhs = first_part_of_call_chain(rhs)
return unless rhs
end_config = config.for_cop('Layout/EndAlignment')
style = end_config['EnforcedStyleAlignWith'] || 'keyword'
base = variable_alignment?(node.loc, rhs, style.to_sym) ? node : rhs
return unless rhs.if_type?
check_nested(rhs, base)
end
def check_alignment(base_range, else_range)
return unless begins_its_line?(else_range)
@column_delta = column_offset_between(base_range, else_range)
return if @column_delta.zero?
message = format(
MSG,
else_range: else_range.source,
base_range: base_range.source[/^\S*/]
)
add_offense(else_range, message: message) do |corrector|
autocorrect(corrector, else_range)
end
end
def assignment_node(node)
assignment_node = node.ancestors.first
return unless assignment_node&.assignment?
assignment_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/multiline_block_layout.rb | lib/rubocop/cop/layout/multiline_block_layout.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks whether the multiline do end blocks have a newline
# after the start of the block. Additionally, it checks whether the block
# arguments, if any, are on the same line as the start of the
# block. Putting block arguments on separate lines, because the whole
# line would otherwise be too long, is accepted.
#
# @example
# # bad
# blah do |i| foo(i)
# bar(i)
# end
#
# # bad
# blah do
# |i| foo(i)
# bar(i)
# end
#
# # good
# blah do |i|
# foo(i)
# bar(i)
# end
#
# # bad
# blah { |i| foo(i)
# bar(i)
# }
#
# # good
# blah { |i|
# foo(i)
# bar(i)
# }
#
# # good
# blah { |
# long_list,
# of_parameters,
# that_would_not,
# fit_on_one_line
# |
# foo(i)
# bar(i)
# }
class MultilineBlockLayout < Base
include RangeHelp
extend AutoCorrector
MSG = 'Block body expression is on the same line as the block start.'
ARG_MSG = 'Block argument expression is not on the same line as the block start.'
PIPE_SIZE = '|'.length
def on_block(node)
return if node.single_line?
unless args_on_beginning_line?(node) || line_break_necessary_in_args?(node)
add_offense_for_expression(node, node.arguments, ARG_MSG)
end
return unless node.body && same_line?(node.loc.begin, node.body)
add_offense_for_expression(node, node.body, MSG)
end
alias on_numblock on_block
alias on_itblock on_block
private
def args_on_beginning_line?(node)
!node.arguments? || node.loc.begin.line == node.arguments.loc.last_line
end
def line_break_necessary_in_args?(node)
return false unless max_line_length
needed_length_for_args(node) > max_line_length
end
def needed_length_for_args(node)
node.source_range.column +
characters_needed_for_space_and_pipes(node) +
node.source.lines.first.chomp.length +
block_arg_string(node, node.arguments).length
end
def characters_needed_for_space_and_pipes(node)
if node.source.lines.first.end_with?("|\n")
PIPE_SIZE
else
(PIPE_SIZE * 2) + 1
end
end
def add_offense_for_expression(node, expr, msg)
expression = expr.source_range
range = range_between(expression.begin_pos, expression.end_pos)
add_offense(range, message: msg) { |corrector| autocorrect(corrector, node) }
end
def autocorrect(corrector, node)
unless args_on_beginning_line?(node)
autocorrect_arguments(corrector, node)
expr_before_body = node.arguments.source_range.end
end
return unless node.body
expr_before_body ||= node.loc.begin
return unless same_line?(expr_before_body, node.body)
autocorrect_body(corrector, node, node.body)
end
def autocorrect_arguments(corrector, node)
end_pos = range_with_surrounding_space(
node.arguments.source_range,
side: :right,
newlines: false
).end_pos
range = range_between(node.loc.begin.end.begin_pos, end_pos)
corrector.replace(range, " |#{block_arg_string(node, node.arguments)}|")
end
def autocorrect_body(corrector, node, block_body)
first_node = if block_body.begin_type? && !block_body.source.start_with?('(')
block_body.children.first
else
block_body
end
block_start_col = node.source_range.column
corrector.insert_before(first_node, "\n #{' ' * block_start_col}")
end
def block_arg_string(node, args)
arg_string = args.children.map do |arg|
if arg.mlhs_type?
"(#{block_arg_string(node, arg)})"
else
arg.source
end
end.join(', ')
arg_string += ',' if include_trailing_comma?(node.arguments)
arg_string
end
def include_trailing_comma?(args)
arg_count = args.each_descendant(:arg).to_a.size
arg_count == 1 && args.source.include?(',')
end
end
end
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_hash_element_indentation.rb | lib/rubocop/cop/layout/first_hash_element_indentation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks the indentation of the first key in a hash literal
# where the opening brace and the first key are on separate lines. The
# other keys' indentations are handled by the HashAlignment cop.
#
# By default, `Hash` literals that are arguments in a method call with
# parentheses, and where the opening curly brace of the hash is on the
# same line as the opening parenthesis of the method call, shall have
# their first key indented one step (two spaces) more than the position
# inside the opening parenthesis.
#
# Other hash literals shall have their first key indented one step more
# than the start of the line where the opening curly brace is.
#
# This default style is called 'special_inside_parentheses'. Alternative
# styles are 'consistent' and 'align_braces'. Here are examples:
#
# @example EnforcedStyle: special_inside_parentheses (default)
# # The `special_inside_parentheses` style enforces that the first key
# # in a hash literal where the opening brace and the first key are on
# # separate lines is indented one step (two spaces) more than the
# # position inside the opening parentheses.
#
# # bad
# hash = {
# key: :value
# }
# and_in_a_method_call({
# no: :difference
# })
# takes_multi_pairs_hash(x: {
# a: 1,
# b: 2
# },
# y: {
# c: 1,
# d: 2
# })
#
# # good
# special_inside_parentheses
# hash = {
# key: :value
# }
# but_in_a_method_call({
# its_like: :this
# })
# takes_multi_pairs_hash(x: {
# a: 1,
# b: 2
# },
# y: {
# c: 1,
# d: 2
# })
#
# @example EnforcedStyle: consistent
# # The `consistent` style enforces that the first key in a hash
# # literal where the opening brace and the first key are on
# # separate lines is indented the same as a hash literal which is not
# # defined inside a method call.
#
# # bad
# hash = {
# key: :value
# }
# but_in_a_method_call({
# its_like: :this
# })
#
# # good
# hash = {
# key: :value
# }
# and_in_a_method_call({
# no: :difference
# })
#
#
# @example EnforcedStyle: align_braces
# # The `align_brackets` style enforces that the opening and closing
# # braces are indented to the same position.
#
# # bad
# and_now_for_something = {
# completely: :different
# }
# takes_multi_pairs_hash(x: {
# a: 1,
# b: 2
# },
# y: {
# c: 1,
# d: 2
# })
#
# # good
# and_now_for_something = {
# completely: :different
# }
# takes_multi_pairs_hash(x: {
# a: 1,
# b: 2
# },
# y: {
# c: 1,
# d: 2
# })
class FirstHashElementIndentation < Base
include Alignment
include ConfigurableEnforcedStyle
include MultilineElementIndentation
extend AutoCorrector
MSG = 'Use %<configured_indentation_width>d spaces for indentation ' \
'in a hash, relative to %<base_description>s.'
def on_hash(node)
check(node, nil) if node.loc.begin
end
def on_send(node)
return if enforce_first_argument_with_fixed_indentation?
each_argument_node(node, :hash) do |hash_node, left_parenthesis|
check(hash_node, left_parenthesis)
end
end
alias on_csend on_send
private
def autocorrect(corrector, node)
AlignmentCorrector.correct(corrector, processed_source, node, @column_delta)
end
def brace_alignment_style
:align_braces
end
def check(hash_node, left_parenthesis)
return if ignored_node?(hash_node)
left_brace = hash_node.loc.begin
first_pair = hash_node.pairs.first
if first_pair
return if same_line?(first_pair, left_brace)
if separator_style?(first_pair)
check_based_on_longest_key(hash_node, left_brace, left_parenthesis)
else
check_first(first_pair, left_brace, left_parenthesis, 0)
end
end
check_right_brace(hash_node.loc.end, first_pair, left_brace, left_parenthesis)
end
def check_right_brace(right_brace, first_pair, left_brace, left_parenthesis)
# if the right brace is on the same line as the last value, accept
return if /\S/.match?(right_brace.source_line[0...right_brace.column])
expected_column, indent_base_type = indent_base(left_brace, first_pair, left_parenthesis)
@column_delta = expected_column - right_brace.column
return if @column_delta.zero?
message = message_for_right_brace(indent_base_type)
add_offense(right_brace, message: message) do |corrector|
autocorrect(corrector, right_brace)
end
end
def separator_style?(first_pair)
separator = first_pair.loc.operator
key = "Enforced#{separator.is?(':') ? 'Colon' : 'HashRocket'}Style"
config.for_cop('Layout/HashAlignment')[key] == 'separator'
end
def check_based_on_longest_key(hash_node, left_brace, left_parenthesis)
key_lengths = hash_node.keys.map { |key| key.source_range.length }
check_first(hash_node.pairs.first, left_brace, left_parenthesis,
key_lengths.max - key_lengths.first)
end
# Returns the description of what the correct indentation is based on.
def base_description(indent_base_type)
case indent_base_type
when :left_brace_or_bracket
'the position of the opening brace'
when :first_column_after_left_parenthesis
'the first position after the preceding left parenthesis'
when :parent_hash_key
'the parent hash key'
else
'the start of the line where the left curly brace is'
end
end
def message(base_description)
format(
MSG,
configured_indentation_width: configured_indentation_width,
base_description: base_description
)
end
def message_for_right_brace(indent_base_type)
case indent_base_type
when :left_brace_or_bracket
'Indent the right brace the same as the left brace.'
when :first_column_after_left_parenthesis
'Indent the right brace the same as the first position ' \
'after the preceding left parenthesis.'
when :parent_hash_key
'Indent the right brace the same as the parent hash key.'
else
'Indent the right brace the same as the start of the line ' \
'where the left brace is.'
end
end
def enforce_first_argument_with_fixed_indentation?
argument_alignment_config = config.for_enabled_cop('Layout/ArgumentAlignment')
argument_alignment_config['EnforcedStyle'] == 'with_fixed_indentation'
end
end
end
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_argument_line_breaks.rb | lib/rubocop/cop/layout/multiline_method_argument_line_breaks.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Ensures that each argument in a multi-line method call
# starts on a separate line.
#
# NOTE: This cop does not move the first argument, if you want that to
# be on a separate line, see `Layout/FirstMethodArgumentLineBreak`.
#
# @example
#
# # bad
# foo(a, b,
# c
# )
#
# # bad
# foo(a, b, {
# foo: "bar",
# })
#
# # good
# foo(
# a,
# b,
# c
# )
#
# # good
# foo(a, b, c)
#
# @example AllowMultilineFinalElement: false (default)
#
# # bad
# foo(a, b,
# c
# )
#
# # bad
# foo(
# a, b, {
# foo: "bar",
# }
# )
#
# # good
# foo(
# a,
# b,
# {
# foo: "bar",
# }
# )
#
# @example AllowMultilineFinalElement: true
#
# # bad
# foo(a, b,
# c
# )
#
# # good
# foo(
# a, b, {
# foo: "bar",
# }
# )
#
# # good
# foo(
# a,
# b,
# {
# foo: "bar",
# }
# )
#
class MultilineMethodArgumentLineBreaks < Base
include MultilineElementLineBreaks
extend AutoCorrector
MSG = 'Each argument in a multi-line method call must start on a separate line.'
def on_send(node)
return if node.method?(:[]=)
args = node.arguments
# 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?
check_line_breaks(node, args, ignore_last: ignore_last_element?)
end
alias on_csend on_send
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/empty_lines.rb | lib/rubocop/cop/layout/empty_lines.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for two or more consecutive blank lines.
#
# @example
#
# # bad - It has two empty lines.
# some_method
# # one empty line
# # two empty lines
# some_method
#
# # good
# some_method
# # one empty line
# some_method
#
class EmptyLines < Base
include RangeHelp
extend AutoCorrector
MSG = 'Extra blank line detected.'
LINE_OFFSET = 2
def on_new_investigation
return if processed_source.tokens.empty?
# Quick check if we possibly have consecutive blank lines.
return unless processed_source.raw_source.include?("\n\n\n")
lines = Set.new
processed_source.tokens.each { |token| lines << token.line }
each_extra_empty_line(lines.sort) do |range|
add_offense(range) do |corrector|
corrector.remove(range)
end
end
end
private
def each_extra_empty_line(lines)
prev_line = 1
lines.each do |cur_line|
if exceeds_line_offset?(cur_line - prev_line)
# we need to be wary of comments since they
# don't show up in the tokens
((prev_line + 1)...cur_line).each do |line|
next unless previous_and_current_lines_empty?(line)
yield source_range(processed_source.buffer, line, 0)
end
end
prev_line = cur_line
end
end
def exceeds_line_offset?(line_diff)
line_diff > LINE_OFFSET
end
def previous_and_current_lines_empty?(line)
processed_source[line - 2].empty? && processed_source[line - 1].empty?
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/line_end_string_concatenation_indentation.rb | lib/rubocop/cop/layout/line_end_string_concatenation_indentation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks the indentation of the next line after a line that ends with a string
# literal and a backslash.
#
# If `EnforcedStyle: aligned` is set, the concatenated string parts shall be aligned with the
# first part. There are some exceptions, such as implicit return values, where the
# concatenated string parts shall be indented regardless of `EnforcedStyle` configuration.
#
# If `EnforcedStyle: indented` is set, it's the second line that shall be indented one step
# more than the first line. Lines 3 and forward shall be aligned with line 2.
#
# @example
# # bad
# def some_method
# 'x' \
# 'y' \
# 'z'
# end
#
# my_hash = {
# first: 'a message' \
# 'in two parts'
# }
#
# # good
# def some_method
# 'x' \
# 'y' \
# 'z'
# end
#
# @example EnforcedStyle: aligned (default)
# # bad
# puts 'x' \
# 'y'
#
# my_hash = {
# first: 'a message' \
# 'in two parts'
# }
#
# # good
# puts 'x' \
# 'y'
#
# my_hash = {
# first: 'a message' \
# 'in two parts'
# }
#
# @example EnforcedStyle: indented
# # bad
# result = 'x' \
# 'y'
#
# my_hash = {
# first: 'a message' \
# 'in two parts'
# }
#
# # good
# result = 'x' \
# 'y'
#
# my_hash = {
# first: 'a message' \
# 'in two parts'
# }
#
class LineEndStringConcatenationIndentation < Base
include ConfigurableEnforcedStyle
include Alignment
extend AutoCorrector
MSG_ALIGN = 'Align parts of a string concatenated with backslash.'
MSG_INDENT = 'Indent the first part of a string concatenated with backslash.'
PARENT_TYPES_FOR_INDENTED = [nil, :block, :begin, :def, :defs, :if].freeze
def on_dstr(node)
return unless strings_concatenated_with_backslash?(node)
children = node.children
return if children.empty?
if style == :aligned && !always_indented?(node)
check_aligned(children, 1)
else
check_indented(children)
check_aligned(children, 2)
end
end
def autocorrect(corrector, node)
AlignmentCorrector.correct(corrector, processed_source, node, @column_delta)
end
private
def strings_concatenated_with_backslash?(dstr_node)
dstr_node.multiline? &&
dstr_node.children.all? { |c| c.type?(:str, :dstr) } &&
dstr_node.children.none?(&:multiline?)
end
def always_indented?(dstr_node)
PARENT_TYPES_FOR_INDENTED.include?(dstr_node.parent&.type)
end
def check_aligned(children, start_index)
base_column = children[start_index - 1].loc.column
children[start_index..].each do |child|
@column_delta = base_column - child.loc.column
add_offense_and_correction(child, MSG_ALIGN) if @column_delta != 0
base_column = child.loc.column
end
end
def check_indented(children)
@column_delta = base_column(children[0]) + configured_indentation_width -
children[1].loc.column
add_offense_and_correction(children[1], MSG_INDENT) if @column_delta != 0
end
def base_column(child)
grandparent = child.parent.parent
if grandparent&.pair_type?
grandparent.loc.column
else
child.source_range.source_line =~ /\S/
end
end
def add_offense_and_correction(node, message)
add_offense(node, message: message) { |corrector| autocorrect(corrector, 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_percent_literal_delimiters.rb | lib/rubocop/cop/layout/space_inside_percent_literal_delimiters.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for unnecessary additional spaces inside the delimiters of
# %i/%w/%x literals.
#
# @example
#
# # bad
# %i( foo bar baz )
#
# # good
# %i(foo bar baz)
#
# # bad
# %w( foo bar baz )
#
# # good
# %w(foo bar baz)
#
# # bad
# %x( ls -l )
#
# # good
# %x(ls -l)
#
# # bad
# %w( )
# %w(
# )
#
# # good
# %w()
class SpaceInsidePercentLiteralDelimiters < Base
include MatchRange
include PercentLiteral
extend AutoCorrector
MSG = 'Do not use spaces inside percent literal delimiters.'
BEGIN_REGEX = /\A( +)/.freeze
END_REGEX = /(?<!\\)( +)\z/.freeze
def on_array(node)
process(node, '%i', '%I', '%w', '%W')
end
def on_xstr(node)
process(node, '%x')
end
def on_percent_literal(node)
add_offenses_for_blank_spaces(node)
add_offenses_for_unnecessary_spaces(node)
end
private
def add_offenses_for_blank_spaces(node)
range = body_range(node)
return if range.source.empty? || !range.source.strip.empty?
add_offense(range) do |corrector|
corrector.remove(range)
end
end
def add_offenses_for_unnecessary_spaces(node)
return unless node.single_line?
regex_matches(node) do |match_range|
add_offense(match_range) do |corrector|
corrector.remove(match_range)
end
end
end
def regex_matches(node, &blk)
[BEGIN_REGEX, END_REGEX].each do |regex|
each_match_range(contents_range(node), regex, &blk)
end
end
def body_range(node)
node.source_range.with(
begin_pos: node.location.begin.end_pos,
end_pos: node.location.end.begin_pos
)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/space_inside_array_literal_brackets.rb | lib/rubocop/cop/layout/space_inside_array_literal_brackets.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks that brackets used for array literals have or don't have
# surrounding space depending on configuration.
#
# Array pattern matching is handled in the same way.
#
# @example EnforcedStyle: no_space (default)
# # The `no_space` style enforces that array literals have
# # no surrounding space.
#
# # bad
# array = [ a, b, c, d ]
# array = [ a, [ b, c ]]
#
# # good
# array = [a, b, c, d]
# array = [a, [b, c]]
#
# @example EnforcedStyle: space
# # The `space` style enforces that array literals have
# # surrounding space.
#
# # bad
# array = [a, b, c, d]
# array = [ a, [ b, c ]]
#
# # good
# array = [ a, b, c, d ]
# array = [ a, [ b, c ] ]
#
# @example EnforcedStyle: compact
# # The `compact` style normally requires a space inside
# # array brackets, with the exception that successive left
# # or right brackets are collapsed together in nested arrays.
#
# # bad
# array = [a, b, c, d]
# array = [ a, [ b, c ] ]
# array = [
# [ a ],
# [ b, c ]
# ]
#
# # good
# array = [ a, b, c, d ]
# array = [ a, [ b, c ]]
# array = [[ a ],
# [ b, c ]]
#
# @example EnforcedStyleForEmptyBrackets: no_space (default)
# # The `no_space` EnforcedStyleForEmptyBrackets style enforces that
# # empty array brackets do not contain spaces.
#
# # bad
# foo = [ ]
# bar = [ ]
#
# # good
# foo = []
# bar = []
#
# @example EnforcedStyleForEmptyBrackets: space
# # The `space` EnforcedStyleForEmptyBrackets style enforces that
# # empty array brackets contain exactly one space.
#
# # bad
# foo = []
# bar = [ ]
#
# # good
# foo = [ ]
# bar = [ ]
#
class SpaceInsideArrayLiteralBrackets < Base
include SurroundingSpace
include ConfigurableEnforcedStyle
extend AutoCorrector
MSG = '%<command>s space inside array brackets.'
EMPTY_MSG = '%<command>s space inside empty array brackets.'
def on_array(node)
return if node.array_type? && !node.square_brackets?
node = find_node_with_brackets(node)
tokens, left, right = array_brackets(node)
return unless left && right
if empty_brackets?(left, right, tokens: tokens)
return empty_offenses(node, left, right, EMPTY_MSG)
end
start_ok = next_to_newline?(node, left)
end_ok = node.single_line? ? false : end_has_own_line?(right)
issue_offenses(node, left, right, start_ok, end_ok)
end
alias on_array_pattern on_array
private
def find_node_with_brackets(node)
node.ancestors.find(&:const_pattern_type?) || node
end
def autocorrect(corrector, node)
tokens, left, right = array_brackets(node)
if empty_brackets?(left, right, tokens: tokens)
SpaceCorrector.empty_corrections(processed_source, corrector, empty_config, left, right)
elsif style == :no_space
SpaceCorrector.remove_space(processed_source, corrector, left, right)
elsif style == :space
SpaceCorrector.add_space(processed_source, corrector, left, right)
else
compact_corrections(corrector, node, left, right)
end
end
def array_brackets(node)
tokens = processed_source.tokens_within(node)
left = tokens.find(&:left_bracket?)
right = tokens.reverse_each.find(&:right_bracket?)
[tokens, left, right]
end
def empty_config
cop_config['EnforcedStyleForEmptyBrackets']
end
def next_to_newline?(node, token)
processed_source.tokens_within(node)[index_for(node, token) + 1].line != token.line
end
def end_has_own_line?(token)
line, col = line_and_column_for(token)
return true if col == -1
!/\S/.match?(processed_source.lines[line][0..col])
end
def index_for(node, token)
processed_source.tokens_within(node).index(token)
end
def line_and_column_for(token)
[token.line - 1, token.column - 1]
end
def issue_offenses(node, left, right, start_ok, end_ok)
case style
when :no_space
start_ok = next_to_comment?(node, left)
no_space_offenses(node, left, right, MSG, start_ok: start_ok, end_ok: end_ok)
when :space
space_offenses(node, left, right, MSG, start_ok: start_ok, end_ok: end_ok)
else
compact_offenses(node, left, right, start_ok, end_ok)
end
end
def next_to_comment?(node, token)
processed_source.tokens_within(node)[index_for(node, token) + 1].comment?
end
def compact_offenses(node, left, right, start_ok, end_ok)
if qualifies_for_compact?(node, left, side: :left)
compact_offense(node, left, side: :left)
elsif !multi_dimensional_array?(node, left, side: :left)
space_offenses(node, left, nil, MSG, start_ok: start_ok, end_ok: true)
end
if qualifies_for_compact?(node, right)
compact_offense(node, right)
elsif !multi_dimensional_array?(node, right)
space_offenses(node, nil, right, MSG, start_ok: true, end_ok: end_ok)
end
end
def qualifies_for_compact?(node, token, side: :right)
if side == :right
multi_dimensional_array?(node, token) && token.space_before?
else
multi_dimensional_array?(node, token, side: :left) && token.space_after?
end
end
def multi_dimensional_array?(node, token, side: :right)
offset = side == :right ? -1 : +1
i = index_for(node, token) + offset
i += offset while processed_source.tokens_within(node)[i].new_line?
if side == :right
processed_source.tokens_within(node)[i].right_bracket?
else
processed_source.tokens_within(node)[i].left_bracket?
end
end
def next_to_bracket?(token, side: :right)
line_index, col = line_and_column_for(token)
line = processed_source.lines[line_index]
side == :right ? line[col] == ']' : line[col + 2] == '['
end
def compact_offense(node, token, side: :right)
if side == :right
space_offense(node, token, :left, MSG, NO_SPACE_COMMAND)
else
space_offense(node, token, :right, MSG, NO_SPACE_COMMAND)
end
end
def compact_corrections(corrector, node, left, right)
if multi_dimensional_array?(node, left, side: :left)
compact(corrector, left, :right)
elsif !left.space_after?
corrector.insert_after(left.pos, ' ')
end
if multi_dimensional_array?(node, right)
compact(corrector, right, :left)
elsif !right.space_before?
corrector.insert_before(right.pos, ' ')
end
end
def compact(corrector, bracket, side)
range = side_space_range(range: bracket.pos, side: side, include_newlines: true)
corrector.remove(range)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/leading_comment_space.rb | lib/rubocop/cop/layout/leading_comment_space.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks whether comments have a leading space after the
# `#` denoting the start of the comment. The leading space is not
# required for some RDoc special syntax, like `#++`, `#--`,
# `#:nodoc`, `=begin`- and `=end` comments, "shebang" directives,
# or rackup options.
#
# @example
#
# # bad
# #Some comment
#
# # good
# # Some comment
#
# @example AllowDoxygenCommentStyle: false (default)
#
# # bad
#
# #**
# # Some comment
# # Another line of comment
# #*
#
# @example AllowDoxygenCommentStyle: true
#
# # good
#
# #**
# # Some comment
# # Another line of comment
# #*
#
# @example AllowGemfileRubyComment: false (default)
#
# # bad
#
# #ruby=2.7.0
# #ruby-gemset=myproject
#
# @example AllowGemfileRubyComment: true
#
# # good
#
# #ruby=2.7.0
# #ruby-gemset=myproject
#
# @example AllowRBSInlineAnnotation: false (default)
#
# # bad
#
# include Enumerable #[Integer]
#
# attr_reader :name #: String
# attr_reader :age #: Integer?
#
# #: (
# #| Integer,
# #| String
# #| ) -> void
# def foo; end
#
# @example AllowRBSInlineAnnotation: true
#
# # good
#
# include Enumerable #[Integer]
#
# attr_reader :name #: String
# attr_reader :age #: Integer?
#
# #: (
# #| Integer,
# #| String
# #| ) -> void
# def foo; end
#
# @example AllowSteepAnnotation: false (default)
#
# # bad
# [1, 2, 3].each_with_object([]) do |n, list| #$ Array[Integer]
# list << n
# end
#
# name = 'John' #: String
#
# @example AllowSteepAnnotation: true
#
# # good
#
# [1, 2, 3].each_with_object([]) do |n, list| #$ Array[Integer]
# list << n
# end
#
# name = 'John' #: String
#
class LeadingCommentSpace < Base
include RangeHelp
extend AutoCorrector
MSG = 'Missing space after `#`.'
def on_new_investigation # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
processed_source.comments.each do |comment|
next unless /\A(?!#\+\+|#--)(#+[^#\s=])/.match?(comment.text)
next if comment.loc.line == 1 && allowed_on_first_line?(comment)
next if shebang_continuation?(comment)
next if doxygen_comment_style?(comment)
next if gemfile_ruby_comment?(comment)
next if rbs_inline_annotation?(comment)
next if steep_annotation?(comment)
add_offense(comment) do |corrector|
expr = comment.source_range
corrector.insert_after(hash_mark(expr), ' ')
end
end
end
private
def hash_mark(expr)
range_between(expr.begin_pos, expr.begin_pos + 1)
end
def allowed_on_first_line?(comment)
shebang?(comment) || (rackup_config_file? && rackup_options?(comment))
end
def shebang?(comment)
comment.text.start_with?('#!')
end
def shebang_continuation?(comment)
return false unless shebang?(comment)
return true if comment.loc.line == 1
previous_line_comment = processed_source.comment_at_line(comment.loc.line - 1)
return false unless previous_line_comment
# If the comment is a shebang but not on the first line, check if the previous
# line has a shebang comment that wasn't marked as an offense; if so, this comment
# continues the shebang and is acceptable.
shebang?(previous_line_comment) &&
!current_offense_locations.include?(previous_line_comment.source_range)
end
def rackup_options?(comment)
comment.text.start_with?('#\\')
end
def rackup_config_file?
File.basename(processed_source.file_path).eql?('config.ru')
end
def allow_doxygen_comment?
cop_config['AllowDoxygenCommentStyle']
end
def doxygen_comment_style?(comment)
allow_doxygen_comment? && comment.text.start_with?('#*')
end
def allow_gemfile_ruby_comment?
cop_config['AllowGemfileRubyComment']
end
def gemfile?
File.basename(processed_source.file_path).eql?('Gemfile')
end
def ruby_comment_in_gemfile?(comment)
gemfile? && comment.text.start_with?('#ruby')
end
def gemfile_ruby_comment?(comment)
allow_gemfile_ruby_comment? && ruby_comment_in_gemfile?(comment)
end
def allow_rbs_inline_annotation?
cop_config['AllowRBSInlineAnnotation']
end
def rbs_inline_annotation?(comment)
allow_rbs_inline_annotation? && comment.text.start_with?(/#:|#\[.+\]|#\|/)
end
def allow_steep_annotation?
cop_config['AllowSteepAnnotation']
end
def steep_annotation?(comment)
allow_steep_annotation? && comment.text.start_with?(/#[$:]/)
end
end
end
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/parameter_alignment.rb | lib/rubocop/cop/layout/parameter_alignment.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Check that the parameters on a multi-line method call or definition are aligned.
#
# To set the alignment of the first argument, use the
# `Layout/FirstParameterIndentation` cop.
#
# @example EnforcedStyle: with_first_parameter (default)
# # good
#
# def foo(bar,
# baz)
# 123
# end
#
# def foo(
# bar,
# baz
# )
# 123
# end
#
# # bad
#
# def foo(bar,
# baz)
# 123
# end
#
# # bad
#
# def foo(
# bar,
# baz)
# 123
# end
#
# @example EnforcedStyle: with_fixed_indentation
# # good
#
# def foo(bar,
# baz)
# 123
# end
#
# def foo(
# bar,
# baz
# )
# 123
# end
#
# # bad
#
# def foo(bar,
# baz)
# 123
# end
#
# # bad
#
# def foo(
# bar,
# baz)
# 123
# end
class ParameterAlignment < Base
include Alignment
extend AutoCorrector
ALIGN_PARAMS_MSG = 'Align the parameters of a method definition if ' \
'they span more than one line.'
FIXED_INDENT_MSG = 'Use one level of indentation for parameters ' \
'following the first line of a multi-line method definition.'
def on_def(node)
return if node.arguments.size < 2
check_alignment(node.arguments, base_column(node, node.arguments))
end
alias on_defs on_def
private
def autocorrect(corrector, node)
AlignmentCorrector.correct(corrector, processed_source, node, column_delta)
end
def message(_node)
fixed_indentation? ? FIXED_INDENT_MSG : ALIGN_PARAMS_MSG
end
def fixed_indentation?
cop_config['EnforcedStyle'] == 'with_fixed_indentation'
end
def base_column(node, args)
if fixed_indentation?
lineno = target_method_lineno(node)
line = node.source_range.source_buffer.source_line(lineno)
indentation_of_line = /\S.*/.match(line).begin(0)
indentation_of_line + configured_indentation_width
else
display_column(args.first.source_range)
end
end
def target_method_lineno(node)
node.loc.keyword.line
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/space_before_block_braces.rb | lib/rubocop/cop/layout/space_before_block_braces.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks that block braces have or don't have a space before the opening
# brace depending on configuration.
#
# @example EnforcedStyle: space (default)
# # bad
# foo.map{ |a|
# a.bar.to_s
# }
#
# # good
# foo.map { |a|
# a.bar.to_s
# }
#
# @example EnforcedStyle: no_space
# # bad
# foo.map { |a|
# a.bar.to_s
# }
#
# # good
# foo.map{ |a|
# a.bar.to_s
# }
#
# @example EnforcedStyleForEmptyBraces: space (default)
# # bad
# 7.times{}
#
# # good
# 7.times {}
#
# @example EnforcedStyleForEmptyBraces: no_space
# # bad
# 7.times {}
#
# # good
# 7.times{}
class SpaceBeforeBlockBraces < Base
include ConfigurableEnforcedStyle
include RangeHelp
extend AutoCorrector
MISSING_MSG = 'Space missing to the left of {.'
DETECTED_MSG = 'Space detected to the left of {.'
def self.autocorrect_incompatible_with
[Style::SymbolProc]
end
def on_block(node)
return if node.keywords?
# Do not register an offense for multi-line braces when specifying
# `EnforcedStyle: no_space`. It will conflict with autocorrection
# by `EnforcedStyle: line_count_based` of `Style/BlockDelimiters` cop.
# That means preventing autocorrection to incorrect autocorrected
# code.
# See: https://github.com/rubocop/rubocop/issues/7534
return if conflict_with_block_delimiters?(node)
left_brace = node.loc.begin
space_plus_brace = range_with_surrounding_space(left_brace)
used_style =
space_plus_brace.source.start_with?('{') ? :no_space : :space
if empty_braces?(node.loc)
check_empty(left_brace, space_plus_brace, used_style)
else
check_non_empty(left_brace, space_plus_brace, used_style)
end
end
alias on_numblock on_block
alias on_itblock on_block
private
def check_empty(left_brace, space_plus_brace, used_style)
if style_for_empty_braces == used_style
handle_different_styles_for_empty_braces(used_style)
return
elsif !config_to_allow_offenses.key?('Enabled')
config_to_allow_offenses['EnforcedStyleForEmptyBraces'] = used_style.to_s
end
if style_for_empty_braces == :space
range = left_brace
msg = MISSING_MSG
else
range = range_between(space_plus_brace.begin_pos, left_brace.begin_pos)
msg = DETECTED_MSG
end
add_offense(range, message: msg) { |corrector| autocorrect(corrector, range) }
end
def handle_different_styles_for_empty_braces(used_style)
if config_to_allow_offenses['EnforcedStyleForEmptyBraces'] &&
config_to_allow_offenses['EnforcedStyleForEmptyBraces'].to_sym != used_style
config_to_allow_offenses.clear
config_to_allow_offenses['Enabled'] = false
end
end
def check_non_empty(left_brace, space_plus_brace, used_style)
case used_style
when style then correct_style_detected
when :space then space_detected(left_brace, space_plus_brace)
else space_missing(left_brace)
end
end
def space_missing(left_brace)
add_offense(left_brace, message: MISSING_MSG) do |corrector|
autocorrect(corrector, left_brace)
opposite_style_detected
end
end
def space_detected(left_brace, space_plus_brace)
space = range_between(space_plus_brace.begin_pos, left_brace.begin_pos)
add_offense(space, message: DETECTED_MSG) do |corrector|
autocorrect(corrector, space)
opposite_style_detected
end
end
def autocorrect(corrector, range)
case range.source
when /\s/ then corrector.remove(range)
else corrector.insert_before(range, ' ')
end
end
def style_for_empty_braces
case cop_config['EnforcedStyleForEmptyBraces']
when 'space' then :space
when 'no_space' then :no_space
when nil then style
else raise 'Unknown EnforcedStyleForEmptyBraces selected!'
end
end
def conflict_with_block_delimiters?(node)
block_delimiters_style == 'line_count_based' && style == :no_space && node.multiline?
end
def block_delimiters_style
config.for_cop('Style/BlockDelimiters')['EnforcedStyle']
end
def empty_braces?(loc)
loc.begin.end_pos == loc.end.begin_pos
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/multiline_method_call_brace_layout.rb | lib/rubocop/cop/layout/multiline_method_call_brace_layout.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks that the closing brace in a method call is either
# on the same line as the last method argument, or a new line.
#
# When using the `symmetrical` (default) style:
#
# If a method call's opening brace is on the same line as the first
# argument of the call, then the closing brace should be on the same
# line as the last argument of the call.
#
# If a method call's opening brace is on the line above the first
# argument of the call, then the closing brace should be on the line
# below the last argument of the call.
#
# When using the `new_line` style:
#
# The closing brace of a multi-line method call must be on the line
# after the last argument of the call.
#
# When using the `same_line` style:
#
# The closing brace of a multi-line method call must be on the same
# line as the last argument of the call.
#
# @example EnforcedStyle: symmetrical (default)
# # bad
# foo(a,
# b
# )
#
# # bad
# foo(
# a,
# b)
#
# # good
# foo(a,
# b)
#
# # good
# foo(
# a,
# b
# )
#
# @example EnforcedStyle: new_line
# # bad
# foo(
# a,
# b)
#
# # bad
# foo(a,
# b)
#
# # good
# foo(a,
# b
# )
#
# # good
# foo(
# a,
# b
# )
#
# @example EnforcedStyle: same_line
# # bad
# foo(a,
# b
# )
#
# # bad
# foo(
# a,
# b
# )
#
# # good
# foo(
# a,
# b)
#
# # good
# foo(a,
# b)
class MultilineMethodCallBraceLayout < Base
include MultilineLiteralBraceLayout
extend AutoCorrector
SAME_LINE_MESSAGE = 'Closing method call brace must be on the ' \
'same line as the last argument when opening brace is on the same ' \
'line as the first argument.'
NEW_LINE_MESSAGE = 'Closing method call brace must be on the ' \
'line after the last argument when opening brace is on a separate ' \
'line from the first argument.'
ALWAYS_NEW_LINE_MESSAGE = 'Closing method call brace must be on ' \
'the line after the last argument.'
ALWAYS_SAME_LINE_MESSAGE = 'Closing method call brace must be on ' \
'the same line as the last argument.'
def on_send(node)
check_brace_layout(node)
end
alias on_csend on_send
private
def children(node)
node.arguments
end
def ignored_literal?(node)
single_line_ignoring_receiver?(node) || super
end
def single_line_ignoring_receiver?(node)
return false unless node.loc.begin && node.loc.end
node.loc.begin.line == node.loc.end.line
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/dot_position.rb | lib/rubocop/cop/layout/dot_position.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks the . position in multi-line method calls.
#
# @example EnforcedStyle: leading (default)
# # bad
# something.
# method
#
# # good
# something
# .method
#
# @example EnforcedStyle: trailing
# # bad
# something
# .method
#
# # good
# something.
# method
class DotPosition < Base
include ConfigurableEnforcedStyle
include RangeHelp
extend AutoCorrector
def self.autocorrect_incompatible_with
[Style::RedundantSelf]
end
def on_send(node)
return unless node.dot? || node.safe_navigation?
return correct_style_detected if proper_dot_position?(node)
opposite_style_detected
dot = node.loc.dot
message = message(dot)
add_offense(dot, message: message) { |corrector| autocorrect(corrector, dot, node) }
end
alias on_csend on_send
private
def autocorrect(corrector, dot, node)
dot_range = if processed_source[dot.line - 1].strip == '.'
range_by_whole_lines(dot, include_final_newline: true)
else
dot
end
corrector.remove(dot_range)
case style
when :leading
corrector.insert_before(selector_range(node), dot.source)
when :trailing
corrector.insert_after(node.receiver, dot.source)
end
end
def message(dot)
"Place the #{dot.source} on the " +
case style
when :leading
'next line, together with the method name.'
when :trailing
'previous line, together with the method call receiver.'
end
end
def proper_dot_position?(node)
selector_range = selector_range(node)
return true if same_line?(selector_range, end_range(node.receiver))
selector_line = selector_range.line
receiver_line = receiver_end_line(node.receiver)
dot_line = node.loc.dot.line
# don't register an offense if there is a line comment between the
# dot and the selector otherwise, we might break the code while
# "correcting" it (even if there is just an extra blank line, treat
# it the same)
# Also, in the case of a heredoc, the receiver will end after the dot,
# because the heredoc body is on subsequent lines, so use the highest
# line to compare to.
return true if line_between?(selector_line, [receiver_line, dot_line].max)
correct_dot_position_style?(dot_line, selector_line)
end
def line_between?(first_line, second_line)
(first_line - second_line) > 1
end
def correct_dot_position_style?(dot_line, selector_line)
case style
when :leading then dot_line == selector_line
when :trailing then dot_line != selector_line
end
end
def receiver_end_line(node)
if (line = last_heredoc_line(node))
line
else
node.source_range.end.line
end
end
def last_heredoc_line(node)
if node.send_type?
node.arguments.select { |arg| heredoc?(arg) }.map { |arg| arg.loc.heredoc_end.line }.max
elsif heredoc?(node)
node.loc.heredoc_end.line
end
end
def heredoc?(node)
node.any_str_type? && node.heredoc?
end
def end_range(node)
node.source_range.end
end
def selector_range(node)
return node unless node.call_type?
# l.(1) has no selector, so we use the opening parenthesis instead
node.loc.selector || node.loc.begin
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/space_after_semicolon.rb | lib/rubocop/cop/layout/space_after_semicolon.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for semicolon (`;`) not followed by some kind of space.
#
# @example
# # bad
# x = 1;y = 2
#
# # good
# x = 1; y = 2
class SpaceAfterSemicolon < Base
include SpaceAfterPunctuation
extend AutoCorrector
def space_style_before_rcurly
cfg = config.for_cop('Layout/SpaceInsideBlockBraces')
cfg['EnforcedStyle'] || 'space'
end
def kind(token, _next_token)
'semicolon' if token.semicolon?
end
def space_missing?(token1, token2)
super && !semicolon_sequence?(token1, token2)
end
private
def semicolon_sequence?(token, next_token)
token.semicolon? && next_token.semicolon?
end
end
end
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_class_body.rb | lib/rubocop/cop/layout/empty_lines_around_class_body.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks if empty lines around the bodies of classes match
# the configuration.
#
# @example EnforcedStyle: no_empty_lines (default)
# # good
#
# class Foo
# def bar
# # ...
# end
# end
#
# @example EnforcedStyle: empty_lines
# # good
#
# class Foo
#
# def bar
# # ...
# end
#
# end
#
# @example EnforcedStyle: empty_lines_except_namespace
# # good
#
# class Foo
# class Bar
#
# # ...
#
# end
# end
#
# @example EnforcedStyle: empty_lines_special
# # good
# class Foo
#
# def bar; end
#
# end
#
# @example EnforcedStyle: beginning_only
# # good
#
# class Foo
#
# def bar
# # ...
# end
# end
#
# @example EnforcedStyle: ending_only
# # good
#
# class Foo
# def bar
# # ...
# end
#
# end
class EmptyLinesAroundClassBody < Base
include EmptyLinesAroundBody
extend AutoCorrector
KIND = 'class'
def on_class(node)
first_line = node.parent_class.last_line if node.parent_class
check(node, node.body, adjusted_first_line: first_line)
end
def on_sclass(node)
check(node, node.body)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/layout/space_inside_parens.rb | lib/rubocop/cop/layout/space_inside_parens.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for spaces inside ordinary round parentheses.
#
# @example EnforcedStyle: no_space (default)
# # The `no_space` style enforces that parentheses do not have spaces.
#
# # bad
# f( 3)
# g = (a + 3 )
# f( )
#
# # good
# f(3)
# g = (a + 3)
# f()
#
# @example EnforcedStyle: space
# # The `space` style enforces that parentheses have a space at the
# # beginning and end.
# # Note: Empty parentheses should not have spaces.
#
# # bad
# f(3)
# g = (a + 3)
# y( )
#
# # good
# f( 3 )
# g = ( a + 3 )
# y()
#
# @example EnforcedStyle: compact
# # The `compact` style enforces that parentheses have a space at the
# # beginning with the exception that successive parentheses are allowed.
# # Note: Empty parentheses should not have spaces.
#
# # bad
# f(3)
# g = (a + 3)
# y( )
# g( f( x ) )
# g( f( x( 3 ) ), 5 )
# g( ( ( 3 + 5 ) * f) ** x, 5 )
#
# # good
# f( 3 )
# g = ( a + 3 )
# y()
# g( f( x ))
# g( f( x( 3 )), 5 )
# g((( 3 + 5 ) * f ) ** x, 5 )
#
class SpaceInsideParens < Base
include SurroundingSpace
include RangeHelp
include ConfigurableEnforcedStyle
extend AutoCorrector
MSG = 'Space inside parentheses detected.'
MSG_SPACE = 'No space inside parentheses detected.'
def on_new_investigation
tokens = processed_source.sorted_tokens
case style
when :space
process_with_space_style(tokens)
when :compact
process_with_compact_style(tokens)
else
correct_extraneous_space(tokens)
end
end
private
def process_with_space_style(tokens)
tokens.each_cons(2) do |token1, token2|
correct_extraneous_space_in_empty_parens(token1, token2)
correct_missing_space(token1, token2)
end
end
def process_with_compact_style(tokens)
tokens.each_cons(2) do |token1, token2|
correct_extraneous_space_in_empty_parens(token1, token2)
if !left_parens?(token1, token2) && !right_parens?(token1, token2)
correct_missing_space(token1, token2)
else
correct_extraneous_space_between_consecutive_parens(token1, token2)
end
end
end
def correct_extraneous_space(tokens)
tokens.each_cons(2) do |token1, token2|
next unless parens?(token1, token2)
# If the second token is a comment, that means that a line break
# follows, and that the rules for space inside don't apply.
next if token2.comment?
next unless same_line?(token1, token2) && token1.space_after?
range = range_between(token1.end_pos, token2.begin_pos)
add_offense(range) do |corrector|
corrector.remove(range)
end
end
end
def correct_extraneous_space_between_consecutive_parens(token1, token2)
return if range_between(token1.end_pos, token2.begin_pos).source != ' '
range = range_between(token1.end_pos, token2.begin_pos)
add_offense(range) do |corrector|
corrector.remove(range)
end
end
def correct_extraneous_space_in_empty_parens(token1, token2)
return unless token1.left_parens? && token2.right_parens?
return if range_between(token1.begin_pos, token2.end_pos).source == '()'
range = range_between(token1.end_pos, token2.begin_pos)
add_offense(range) do |corrector|
corrector.remove(range)
end
end
def correct_missing_space(token1, token2)
return if can_be_ignored?(token1, token2)
range = if token1.left_parens?
range_between(token2.begin_pos, token2.begin_pos + 1)
elsif token2.right_parens?
range_between(token2.begin_pos, token2.end_pos)
end
add_offense(range, message: MSG_SPACE) do |corrector|
corrector.insert_before(range, ' ')
end
end
def parens?(token1, token2)
token1.left_parens? || token2.right_parens?
end
def left_parens?(token1, token2)
token1.left_parens? && token2.left_parens?
end
def right_parens?(token1, token2)
token1.right_parens? && token2.right_parens?
end
def can_be_ignored?(token1, token2)
return true unless parens?(token1, token2)
# Ignore empty parentheses.
return true if range_between(token1.begin_pos, token2.end_pos).source == '()'
# If the second token is a comment, that means that a line break
# follows, and that the rules for space inside don't apply.
return true if token2.comment?
!same_line?(token1, token2) || token1.space_after?
end
end
end
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_style.rb | lib/rubocop/cop/layout/indentation_style.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks that the indentation method is consistent.
# Either tabs only or spaces only are used for indentation.
#
# @example EnforcedStyle: spaces (default)
# # bad
# # This example uses a tab to indent bar.
# def foo
# bar
# end
#
# # good
# # This example uses spaces to indent bar.
# def foo
# bar
# end
#
# @example EnforcedStyle: tabs
# # bad
# # This example uses spaces to indent bar.
# def foo
# bar
# end
#
# # good
# # This example uses a tab to indent bar.
# def foo
# bar
# end
class IndentationStyle < Base
include Alignment
include ConfigurableEnforcedStyle
include RangeHelp
extend AutoCorrector
MSG = '%<type>s detected in indentation.'
def on_new_investigation
str_ranges = nil
processed_source.lines.each.with_index(1) do |line, lineno|
next unless (range = find_offense(line, lineno))
# Perform costly calculation only when needed.
str_ranges ||= string_literal_ranges(processed_source.ast)
next if in_string_literal?(str_ranges, range)
add_offense(range) { |corrector| autocorrect(corrector, range) }
end
end
private
def autocorrect(corrector, range)
if range.source.include?("\t")
autocorrect_lambda_for_tabs(corrector, range)
else
autocorrect_lambda_for_spaces(corrector, range)
end
end
def find_offense(line, lineno)
match = if style == :spaces
line.match(/\A\s*\t+/)
else
line.match(/\A\s* +/)
end
return unless match
source_range(processed_source.buffer, lineno, match.begin(0)...match.end(0))
end
def autocorrect_lambda_for_tabs(corrector, range)
spaces = ' ' * configured_indentation_width
corrector.replace(range, range.source.gsub("\t", spaces))
end
def autocorrect_lambda_for_spaces(corrector, range)
corrector.replace(range, range.source.gsub(/\A\s+/) do |match|
"\t" * (match.size / configured_indentation_width)
end)
end
def in_string_literal?(ranges, tabs_range)
ranges.any? { |range| range.contains?(tabs_range) }
end
def string_literal_ranges(ast)
# which lines start inside a string literal?
return [] if ast.nil?
ranges = Set.new
ast.each_node(:str, :dstr) do |str|
loc = str.location
if str.heredoc?
ranges << loc.heredoc_body
elsif str.loc?(:begin)
ranges << loc.expression
end
end
ranges
end
def message(_node)
format(MSG, type: style == :spaces ? 'Tab' : 'Space')
end
end
end
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_operation_indentation.rb | lib/rubocop/cop/layout/multiline_operation_indentation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks the indentation of the right hand side operand in binary operations that
# span more than one line.
#
# The `aligned` style checks that operators are aligned if they are part of an `if` or `while`
# condition, an explicit `return` statement, etc. In other contexts, the second operand should
# be indented regardless of enforced style.
#
# In both styles, operators should be aligned when an assignment begins on the next line.
#
# @example EnforcedStyle: aligned (default)
# # bad
# if a +
# b
# something &&
# something_else
# end
#
# # good
# if a +
# b
# something &&
# something_else
# end
#
# @example EnforcedStyle: indented
# # bad
# if a +
# b
# something &&
# something_else
# end
#
# # good
# if a +
# b
# something &&
# something_else
# end
#
class MultilineOperationIndentation < Base
include ConfigurableEnforcedStyle
include Alignment
include MultilineExpressionIndentation
extend AutoCorrector
def on_and(node)
check_and_or(node)
end
def on_or(node)
check_and_or(node)
end
def validate_config
return unless style == :aligned && cop_config['IndentationWidth']
raise ValidationError, 'The `Layout/MultilineOperationIndentation` ' \
'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?(node)
return false if node.send_type? && node.unary_operation?
!node.loc.dot # Don't check method calls with dot operator.
end
def check_and_or(node)
range = offending_range(node, node.lhs, node.rhs.source_range, style)
check(range, node, node.lhs, node.rhs.source_range)
end
def offending_range(node, lhs, rhs, given_style)
return false unless begins_its_line?(rhs)
return false if not_for_this_cop?(node)
correct_column = if should_align?(node, rhs, given_style)
node.loc.column
else
indentation(lhs) + correct_indentation(node)
end
@column_delta = correct_column - rhs.column
rhs if @column_delta.nonzero?
end
def should_align?(node, rhs, given_style)
assignment_node = part_of_assignment_rhs(node, rhs)
if assignment_node
assignment_rhs = CheckAssignment.extract_rhs(assignment_node)
return true if begins_its_line?(assignment_rhs.source_range)
end
return false unless given_style == :aligned
return true if kw_node_with_special_indentation(node) || assignment_node
node = argument_in_method_call(node, :with_or_without_parentheses)
node.respond_to?(:def_modifier?) && !node.def_modifier?
end
def message(node, lhs, rhs)
what = operation_description(node, rhs)
if should_align?(node, rhs, style)
"Align the operands of #{what} spanning multiple lines."
else
used_indentation = rhs.column - indentation(lhs)
"Use #{correct_indentation(node)} (not #{used_indentation}) " \
"spaces for indenting #{what} spanning multiple lines."
end
end
def right_hand_side(send_node)
send_node.first_argument&.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/layout/first_array_element_line_break.rb | lib/rubocop/cop/layout/first_array_element_line_break.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# Checks for a line break before the first element in a
# multi-line array.
#
# @example
#
# # bad
# [ :a,
# :b]
#
# # good
# [
# :a,
# :b]
#
# # good
# [:a, :b]
#
# @example AllowMultilineFinalElement: false (default)
#
# # bad
# [ :a, {
# :b => :c
# }]
#
# # good
# [
# :a, {
# :b => :c
# }]
#
# @example AllowMultilineFinalElement: true
#
# # good
# [:a, {
# :b => :c
# }]
#
class FirstArrayElementLineBreak < Base
include FirstElementLineBreak
extend AutoCorrector
MSG = 'Add a line break before the first element of a multi-line array.'
def on_array(node)
return if !node.loc.begin && !assignment_on_same_line?(node)
check_children_line_break(node, node.children, ignore_last: ignore_last_element?)
end
private
def assignment_on_same_line?(node)
source = node.source_range.source_line[0...node.loc.column]
/\s*=\s*$/.match?(source)
end
def ignore_last_element?
!!cop_config['AllowMultilineFinalElement']
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.