Skip to content

Commit

Permalink
Merge pull request #10228 from koic/fix_false_positive_for_style_pare…
Browse files Browse the repository at this point in the history
…ntheses_around_condition

[Fix #10227] Fix a false positive for `Style/ParenthesesAroundCondition`
  • Loading branch information
koic committed Nov 2, 2021
2 parents 48e163d + 93d5087 commit a1104cd
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
@@ -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

0 comments on commit a1104cd

Please sign in to comment.