diff --git a/changelog/fix_performance_squeeze_cop_error_on_frozen_ast_string_node_value.md b/changelog/fix_performance_squeeze_cop_error_on_frozen_ast_string_node_value.md new file mode 100644 index 000000000..491548f93 --- /dev/null +++ b/changelog/fix_performance_squeeze_cop_error_on_frozen_ast_string_node_value.md @@ -0,0 +1 @@ +* [#480](https://github.com/rubocop/rubocop-performance/pull/480): Fix `Performance/Squeeze` cop error on frozen AST string node value. ([@viralpraxis][]) diff --git a/lib/rubocop/cop/performance/squeeze.rb b/lib/rubocop/cop/performance/squeeze.rb index 3176154f8..bf2766a13 100644 --- a/lib/rubocop/cop/performance/squeeze.rb +++ b/lib/rubocop/cop/performance/squeeze.rb @@ -46,7 +46,11 @@ def on_send(node) message = format(MSG, current: bad_method, prefer: good_method) add_offense(node.loc.selector, message: message) do |corrector| - string_literal = to_string_literal(replace_str) + # FIXME: When requiring only RuboCop 1.70.0 and above, + # `dup` in `replace_str.dup` becomes unnecessary, as + # frozen strings are handled in the `to_string_literal` + # implementation. Please remove it. + string_literal = to_string_literal(replace_str.dup) new_code = "#{receiver.source}#{node.loc.dot.source}#{good_method}(#{string_literal})" corrector.replace(node, new_code) diff --git a/spec/rubocop/cop/performance/squeeze_spec.rb b/spec/rubocop/cop/performance/squeeze_spec.rb index 02f73fdc2..8bbdb1b2e 100644 --- a/spec/rubocop/cop/performance/squeeze_spec.rb +++ b/spec/rubocop/cop/performance/squeeze_spec.rb @@ -51,4 +51,15 @@ str.gsub(/a+/, 'b') RUBY end + + it 'registers an offense when AST string literal might be frozen' do + expect_offense(<<~'RUBY') + str.gsub(/\n+/, ?\n) + ^^^^ Use `squeeze` instead of `gsub`. + RUBY + + expect_correction(<<~'RUBY') + str.squeeze("\n") + RUBY + end end