diff --git a/changelog/fix_a_false_positive_for_style_redundant_parentheses.md b/changelog/fix_a_false_positive_for_style_redundant_parentheses.md new file mode 100644 index 00000000000..c626a6cc565 --- /dev/null +++ b/changelog/fix_a_false_positive_for_style_redundant_parentheses.md @@ -0,0 +1 @@ +* [#10979](https://github.com/rubocop/rubocop/issues/10979): Fix a false positive for `Style/Style/RedundantParentheses` when using parentheses in method call with pin operator. ([@koic][]) diff --git a/lib/rubocop/cop/style/redundant_parentheses.rb b/lib/rubocop/cop/style/redundant_parentheses.rb index 184b3ab6eaf..242845571f1 100644 --- a/lib/rubocop/cop/style/redundant_parentheses.rb +++ b/lib/rubocop/cop/style/redundant_parentheses.rb @@ -58,7 +58,8 @@ def allowed_expression?(node) allowed_ancestor?(node) || allowed_method_call?(node) || allowed_multiple_expression?(node) || - allowed_ternary?(node) + allowed_ternary?(node) || + allowed_pin_operator?(node) end def allowed_ancestor?(node) @@ -86,6 +87,10 @@ def allowed_ternary?(node) node.parent.ternary? && ternary_parentheses_required? end + def allowed_pin_operator?(node) + node&.parent&.pin_type? && node.children.first.call_type? + end + def ternary_parentheses_required? config = @config.for_cop('Style/TernaryParentheses') allowed_styles = %w[require_parentheses require_parentheses_when_complex] diff --git a/spec/rubocop/cop/style/redundant_parentheses_spec.rb b/spec/rubocop/cop/style/redundant_parentheses_spec.rb index 34332aa5b4d..c381e875746 100644 --- a/spec/rubocop/cop/style/redundant_parentheses_spec.rb +++ b/spec/rubocop/cop/style/redundant_parentheses_spec.rb @@ -626,4 +626,33 @@ def x ] RUBY end + + context 'pin operator', :ruby31 do + it 'does not register an offense when using parentheses in method call with pin operator' do + expect_no_offenses(<<~RUBY) + foo in { bar: ^(baz.to_i) } + RUBY + end + + it 'does not register an offense when using parentheses in safe navigation method call with pin operator' do + expect_no_offenses(<<~RUBY) + foo in { bar: ^(baz&.to_i) } + RUBY + end + + it 'registers an offense when using parentheses in lvar with pin operator' do + expect_offense(<<~RUBY) + baz = 42 + + foo in { bar: ^(baz) } + ^^^^^ Don't use parentheses around a variable. + RUBY + + expect_correction(<<~RUBY) + baz = 42 + + foo in { bar: ^baz } + RUBY + end + end end