Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fix #10227] Fix a false positive for Style/ParenthesesAroundCondition #10228

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -0,0 +1 @@
* [#10227](https://github.com/rubocop/rubocop/issues/10227): Fix a false positive for `Style/ParenthesesAroundCondition` when parentheses in multiple expressions separated by semicolon. ([@koic][])
14 changes: 12 additions & 2 deletions lib/rubocop/cop/style/parentheses_around_condition.rb
Expand Up @@ -56,6 +56,7 @@ module Style
class ParenthesesAroundCondition < Base
include SafeAssignment
include Parentheses
include RangeHelp
extend AutoCorrector

def on_if(node)
Expand All @@ -73,13 +74,14 @@ def on_while(node)

# @!method control_op_condition(node)
def_node_matcher :control_op_condition, <<~PATTERN
(begin $_ ...)
(begin $_ $...)
PATTERN

def process_control_op(node)
cond = node.condition

control_op_condition(cond) do |first_child|
control_op_condition(cond) do |first_child, rest_children|
return if semicolon_separated_expressions?(first_child, rest_children)
return if modifier_op?(first_child)
return if parens_allowed?(cond)

Expand All @@ -90,6 +92,14 @@ def process_control_op(node)
end
end

def semicolon_separated_expressions?(first_exp, rest_exps)
return false unless (second_exp = rest_exps.first)

range = range_between(first_exp.source_range.end_pos, second_exp.source_range.begin_pos)

range.source.include?(';')
end

def modifier_op?(node)
return false if node.if_type? && node.ternary?
return true if node.rescue_type?
Expand Down
8 changes: 8 additions & 0 deletions spec/rubocop/cop/style/parentheses_around_condition_spec.rb
Expand Up @@ -102,6 +102,14 @@
RUBY
end

it 'does not register an offense when parentheses in multiple expressions separated by semicolon' do
expect_no_offenses(<<~RUBY)
if (foo; bar)
do_something
end
RUBY
end

context 'safe assignment is allowed' do
it 'accepts variable assignment in condition surrounded with parentheses' do
expect_no_offenses(<<~RUBY)
Expand Down