From b257411f81f57da5947f6098ba0c9948293c6e5c Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Thu, 16 Jun 2022 00:52:13 +0900 Subject: [PATCH] Fix a false negative for `Performance/ChainArrayAllocation` This PR fixes a false negative for `Performance/ChainArrayAllocation` when using `array.first(do_something).uniq`. --- ...alse_negative_for_performance_chain_array_allocation.md | 1 + lib/rubocop/cop/performance/chain_array_allocation.rb | 2 +- .../rubocop/cop/performance/chain_array_allocation_spec.rb | 7 +++++++ 3 files changed, 9 insertions(+), 1 deletion(-) create mode 100644 changelog/fix_false_negative_for_performance_chain_array_allocation.md diff --git a/changelog/fix_false_negative_for_performance_chain_array_allocation.md b/changelog/fix_false_negative_for_performance_chain_array_allocation.md new file mode 100644 index 0000000000..622139126a --- /dev/null +++ b/changelog/fix_false_negative_for_performance_chain_array_allocation.md @@ -0,0 +1 @@ +* [#294](https://github.com/rubocop/rubocop-performance/pull/294): Fix a false negative for `Performance/ChainArrayAllocation` when using `array.first(do_something).uniq`. ([@koic][]) diff --git a/lib/rubocop/cop/performance/chain_array_allocation.rb b/lib/rubocop/cop/performance/chain_array_allocation.rb index 84a33f53f7..1c65c96fb3 100644 --- a/lib/rubocop/cop/performance/chain_array_allocation.rb +++ b/lib/rubocop/cop/performance/chain_array_allocation.rb @@ -53,7 +53,7 @@ class ChainArrayAllocation < Base def_node_matcher :chain_array_allocation?, <<~PATTERN (send { - (send _ $%RETURN_NEW_ARRAY_WHEN_ARGS {int lvar ivar cvar gvar}) + (send _ $%RETURN_NEW_ARRAY_WHEN_ARGS {int lvar ivar cvar gvar send}) (block (send _ $%ALWAYS_RETURNS_NEW_ARRAY) ...) (send _ $%RETURNS_NEW_ARRAY ...) } $%HAS_MUTATION_ALTERNATIVE ...) diff --git a/spec/rubocop/cop/performance/chain_array_allocation_spec.rb b/spec/rubocop/cop/performance/chain_array_allocation_spec.rb index d923014ca8..c2f7b1dbc3 100644 --- a/spec/rubocop/cop/performance/chain_array_allocation_spec.rb +++ b/spec/rubocop/cop/performance/chain_array_allocation_spec.rb @@ -23,6 +23,13 @@ ^^^^^ Use unchained `first` and `uniq!` (followed by `return array` if required) instead of chaining `first...uniq`. RUBY end + + it 'registers an offense for `first(do_something).uniq`' do + expect_offense(<<~RUBY) + [1, 2, 3, 4].first(do_something).uniq + ^^^^^ Use unchained `first` and `uniq!` (followed by `return array` if required) instead of chaining `first...uniq`. + RUBY + end end describe 'methods that only return an array with no block' do