From ccb9241796cba9943ddc436c2f07881dcb97e4ca Mon Sep 17 00:00:00 2001 From: viralpraxis Date: Wed, 11 Dec 2024 16:26:37 +0300 Subject: [PATCH] Fix `Performance/RedundantStringChars` cop error in case of implicit receiver ```console echo 'chars.size' | be rubocop --only Performance/RedundantStringChars --stdin bug.rb -d Inspecting 1 file Scanning /bug.rb An error occurred while Performance/RedundantStringChars cop was inspecting /bug.rb:1:0. undefined method `begin_pos' for nil /lib/rubocop/cop/performance/redundant_string_chars.rb:76:in `correction_range' /lib/rubocop/cop/performance/redundant_string_chars.rb:62:in `block in on_send' ``` --- ...t_string_chars_cop_error_in_case_of_implicit_receiver.md | 1 + lib/rubocop/cop/performance/redundant_string_chars.rb | 2 +- spec/rubocop/cop/performance/redundant_string_chars_spec.rb | 6 ++++++ 3 files changed, 8 insertions(+), 1 deletion(-) create mode 100644 changelog/fix_performance_redundant_string_chars_cop_error_in_case_of_implicit_receiver.md diff --git a/changelog/fix_performance_redundant_string_chars_cop_error_in_case_of_implicit_receiver.md b/changelog/fix_performance_redundant_string_chars_cop_error_in_case_of_implicit_receiver.md new file mode 100644 index 0000000000..2697173959 --- /dev/null +++ b/changelog/fix_performance_redundant_string_chars_cop_error_in_case_of_implicit_receiver.md @@ -0,0 +1 @@ +* [#478](https://github.com/rubocop/rubocop-performance/pull/478): Fix `Performance/RedundantStringChars` cop error in case of implicit receiver. ([@viralpraxis][]) diff --git a/lib/rubocop/cop/performance/redundant_string_chars.rb b/lib/rubocop/cop/performance/redundant_string_chars.rb index 4fd4b0422a..0a00e8127b 100644 --- a/lib/rubocop/cop/performance/redundant_string_chars.rb +++ b/lib/rubocop/cop/performance/redundant_string_chars.rb @@ -48,7 +48,7 @@ class RedundantStringChars < Base RESTRICT_ON_SEND = %i[[] slice first last take length size empty?].freeze def_node_matcher :redundant_chars_call?, <<~PATTERN - (send $(send _ :chars) $_ $...) + (send $(send !nil? :chars) $_ $...) PATTERN def on_send(node) diff --git a/spec/rubocop/cop/performance/redundant_string_chars_spec.rb b/spec/rubocop/cop/performance/redundant_string_chars_spec.rb index 920bc6d914..f9d7bdb02b 100644 --- a/spec/rubocop/cop/performance/redundant_string_chars_spec.rb +++ b/spec/rubocop/cop/performance/redundant_string_chars_spec.rb @@ -139,4 +139,10 @@ str.chars.max RUBY end + + it 'does not register an offense with implicit receiver' do + expect_no_offenses(<<~RUBY) + chars.size + RUBY + end end