Skip to content

Commit

Permalink
Fix an incorrect auto-correct for Layout/LineLength
Browse files Browse the repository at this point in the history
This PR fixes an incorrect auto-correct for `Layout/LineLength` when
using heredoc as the first method argument and omitting parentheses.

```console
% cat example.rb
foo <<~RUBY, arg
RUBY

% bundle exec rubocop --only Layout/LineLength -a
(snip)

Inspecting 1 file
C

Offenses:

example.rb:1:16: C: [Corrected] Layout/LineLength: Line is too long. [16/15]
foo <<~RUBY, arg
               ^

1 file inspected, 1 offense detected, 1 offense corrected

% cat example.rb
foo <<~RUBY,
arg
RUBY

% ruby -c example.rb
example.rb:1: syntax error, unexpected end-of-input
```
  • Loading branch information
koic committed Jun 17, 2021
1 parent f2edbfa commit f729a3e
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#9882](https://github.com/rubocop/rubocop/pull/9882): Fix an incorrect auto-correct for `Layout/LineLength` when using heredoc as the first method argument and omitting parentheses. ([@koic][])
11 changes: 10 additions & 1 deletion lib/rubocop/cop/mixin/check_line_breakable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,9 @@ def extract_first_element_over_column_limit(node, elements, max)

# If a `send` node is not parenthesized, don't move the first element, because it
# can result in changed behavior or a syntax error.
elements = elements.drop(1) if node.send_type? && !node.parenthesized?
if node.send_type? && !node.parenthesized? && !first_argument_is_heredoc?(node)
elements = elements.drop(1)
end

i = 0
i += 1 while within_column_limit?(elements[i], max, line)
Expand All @@ -84,6 +86,13 @@ def extract_first_element_over_column_limit(node, elements, max)
elements[i - 1]
end

# @api private
def first_argument_is_heredoc?(node)
first_argument = node.first_argument

first_argument.respond_to?(:heredoc?) && first_argument.heredoc?
end

# @api private
# If a send node contains a heredoc argument, splitting cannot happen
# after the heredoc or else it will cause a syntax error.
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/layout/line_length_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -768,6 +768,17 @@ def baz(bar)
expect_no_corrections
end

it 'does not break up the line when parentheses are omitted' do
args = 'x' * 25
expect_offense(<<~RUBY, args: args)
foo <<~STRING, #{args}xxx
_{args}^^^ Line is too long. [43/40]
STRING
RUBY

expect_no_corrections
end

context 'and other arguments before the heredoc' do
it 'can break up the line before the heredoc argument' do
args = 'x' * 20
Expand Down

0 comments on commit f729a3e

Please sign in to comment.