Skip to content

[GR-18163] Fix Struct setters to raise FrozenError when a struct is frozen #3876

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

Merged
merged 1 commit into from
May 21, 2025
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Compatibility:
* Fix `Kernel#raise` and don't override `cause` at exception re-raising (#3831, @andrykonchin).
* Return a pointer with `#type_size` of 1 for `Pointer#read_pointer` (@eregon).
* Fix `rb_str_locktmp()` and `rb_str_unlocktmp()` to raise `FrozenError` when string argument is frozen (#3752, @andrykonchin).
* Fix Struct setters to raise `FrozenError` when a struct is frozen (#3850, @andrykonchin).

Performance:

Expand Down
7 changes: 7 additions & 0 deletions spec/ruby/core/struct/element_set_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,11 @@
-> { car[-4] = true }.should raise_error(IndexError)
-> { car[Object.new] = true }.should raise_error(TypeError)
end

it "raises a FrozenError on a frozen struct" do
car = StructClasses::Car.new('Ford', 'Ranger')
car.freeze

-> { car[:model] = 'Escape' }.should raise_error(FrozenError)
end
end
7 changes: 7 additions & 0 deletions spec/ruby/core/struct/struct_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@
car['model'].should == 'F150'
car[1].should == 'F150'
end

it "writer methods raise a FrozenError on a frozen struct" do
car = StructClasses::Car.new('Ford', 'Ranger')
car.freeze

-> { car.model = 'Escape' }.should raise_error(FrozenError)
end
end

describe "Struct subclasses" do
Expand Down
5 changes: 4 additions & 1 deletion src/main/ruby/truffleruby/core/struct.rb
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,10 @@ def self.new(*attrs, keyword_init: nil, &block)

attrs.each do |a|
define_method(a) { Primitive.object_hidden_var_get(self, a) }
define_method(:"#{a}=") { |value| Primitive.object_hidden_var_set(self, a, value) }
define_method(:"#{a}=") do |value|
Primitive.check_frozen self
Primitive.object_hidden_var_set(self, a, value)
end
end

def self.new(...)
Expand Down
Loading