Skip to content

Commit

Permalink
Fix a crash in Lint/EmptyConditionalBody
Browse files Browse the repository at this point in the history
```ruby
var =
  unless object.action value:, other:
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid `unless` branches without a body.
    condition || other_condition # This is the value of `other:`, like so:
                                 # `other: condition || other_condition`
  end
```

In the condition above, the variable assignment is tricking the
`CommentsHelp#find_end_line` method into calling an end method of
`Parser::Source::Map::Variable`. Other `Parser::Source::Map` subclasses
do not respond to respond to the `#end` method as well, won't hurt to
check.
  • Loading branch information
gsamokovarov authored and bbatsov committed Mar 19, 2023
1 parent 18430bb commit adffde1
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#11712](https://github.com/rubocop/rubocop/pull/11712): Fix a crash in `Lint/EmptyConditionalBody`. ([@gsamokovarov][])
2 changes: 1 addition & 1 deletion lib/rubocop/cop/mixin/comments_help.rb
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def find_end_line(node)
elsif (next_sibling = node.right_sibling) && next_sibling.is_a?(AST::Node)
next_sibling.loc.line
elsif (parent = node.parent)
parent.loc.end ? parent.loc.end.line : parent.loc.line
parent.loc.respond_to?(:end) && parent.loc.end ? parent.loc.end.line : parent.loc.line
else
node.loc.end.line
end
Expand Down
13 changes: 13 additions & 0 deletions spec/rubocop/cop/lint/empty_conditional_body_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,19 @@ class Foo
RUBY
end

context '>= Ruby 3.1', :ruby31 do
it 'registers an offense for multi-line value omission in `unless`' do
expect_offense(<<~RUBY)
var =
unless object.action value:, other:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Avoid `unless` branches without a body.
condition || other_condition # This is the value of `other:`, like so:
# `other: condition || other_condition`
end
RUBY
end
end

context 'when AllowComments is false' do
let(:cop_config) { { 'AllowComments' => false } }

Expand Down

0 comments on commit adffde1

Please sign in to comment.