From ed5c108802bab7c5baaf04298da7f8f369c28f48 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Sat, 19 Aug 2023 14:44:12 +0900 Subject: [PATCH] [Fix #365] Fix false positives for `Performance/ArraySemiInfiniteRangeSlice` Fixes #365. This PR fixes false positives for `Performance/ArraySemiInfiniteRangeSlice` when using `[]` with string literals. What this can do is accept string literals, as they are already marked as unsafe. --- ...formance_array_semi_infinite_range_slice.md | 1 + .../array_semi_infinite_range_slice.rb | 2 +- .../array_semi_infinite_range_slice_spec.rb | 18 ++++++++++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 changelog/fix_false_positives_for_performance_array_semi_infinite_range_slice.md diff --git a/changelog/fix_false_positives_for_performance_array_semi_infinite_range_slice.md b/changelog/fix_false_positives_for_performance_array_semi_infinite_range_slice.md new file mode 100644 index 0000000000..27fa490e5d --- /dev/null +++ b/changelog/fix_false_positives_for_performance_array_semi_infinite_range_slice.md @@ -0,0 +1 @@ +* [#365](https://github.com/rubocop/rubocop-performance/issues/365): Fix false positives for `Performance/ArraySemiInfiniteRangeSlice` when using `[]` with string literals. ([@koic][]) diff --git a/lib/rubocop/cop/performance/array_semi_infinite_range_slice.rb b/lib/rubocop/cop/performance/array_semi_infinite_range_slice.rb index eaee567d77..3658ab3e79 100644 --- a/lib/rubocop/cop/performance/array_semi_infinite_range_slice.rb +++ b/lib/rubocop/cop/performance/array_semi_infinite_range_slice.rb @@ -39,7 +39,7 @@ class ArraySemiInfiniteRangeSlice < Base RESTRICT_ON_SEND = SLICE_METHODS def_node_matcher :endless_range_slice?, <<~PATTERN - (call $_ $%SLICE_METHODS $#endless_range?) + (call $!{str dstr xstr} $%SLICE_METHODS $#endless_range?) PATTERN def_node_matcher :endless_range?, <<~PATTERN diff --git a/spec/rubocop/cop/performance/array_semi_infinite_range_slice_spec.rb b/spec/rubocop/cop/performance/array_semi_infinite_range_slice_spec.rb index fe528119dd..399d299a73 100644 --- a/spec/rubocop/cop/performance/array_semi_infinite_range_slice_spec.rb +++ b/spec/rubocop/cop/performance/array_semi_infinite_range_slice_spec.rb @@ -77,5 +77,23 @@ array[-2..] RUBY end + + it 'does not registers an offense when using `[]` with endless range for string literal' do + expect_no_offenses(<<~RUBY) + 'str'[3..] + RUBY + end + + it 'does not registers an offense when using `[]` with endless range for interpolated string literal' do + expect_no_offenses(<<~'RUBY') + "string#{interpolation}"[3..] + RUBY + end + + it 'does not registers an offense when using `[]` with endless range for backquote string literal' do + expect_no_offenses(<<~RUBY) + `str`[3..] + RUBY + end end end