Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make String#freeze spec-compliant #2160

Merged
merged 2 commits into from
Jun 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/natalie/compiler/backends/cpp_backend/transform.rb
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ def intern(symbol)

def interned_string(str, encoding)
index = @interned_strings[[str, encoding]] ||= @interned_strings.size
"#{interned_strings_var_name}[#{index}]"
"#{interned_strings_var_name}[#{index}]/*#{str.inspect.gsub(%r{\*/|\\}, '?')}*/"
end

def set_file(file)
Expand Down
2 changes: 2 additions & 0 deletions lib/natalie/compiler/instructions/push_string_instruction.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ def initialize(string, bytesize: string.bytesize, encoding: Encoding::UTF_8, fro
@frozen = frozen
end

attr_accessor :frozen

def to_s
"push_string #{@string.inspect}, #{@bytesize}, #{@encoding.name}#{@frozen ? ', frozen' : ''}"
end
Expand Down
9 changes: 8 additions & 1 deletion lib/natalie/compiler/pass1.rb
Original file line number Diff line number Diff line change
Expand Up @@ -490,7 +490,14 @@ def transform_call_node(node, used:, with_block: false)
if receiver.nil?
instructions << PushSelfInstruction.new
else
instructions << transform_expression(receiver, used: true)
inst = transform_expression(receiver, used: true)

if node.name == :freeze && !node.safe_navigation? && !with_block && inst.size == 1 && inst.first.is_a?(PushStringInstruction)
# "foo".freeze get special treatment so we can intern the string at compile time
inst.first.frozen = true
end

instructions << inst
end

if node.safe_navigation?
Expand Down
18 changes: 18 additions & 0 deletions spec/core/string/freeze_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# frozen_string_literal: false
require_relative '../../spec_helper'

describe "String#freeze" do

it "produces the same object whenever called on an instance of a literal in the source" do
"abc".freeze.should equal "abc".freeze
end

it "doesn't produce the same object for different instances of literals in the source" do
"abc".should_not equal "abc"
end

it "being a special form doesn't change the value of defined?" do
defined?("abc".freeze).should == "method"
end

end
Loading