Issue #18035 has been updated by ioquatix (Samuel Williams).


After discussing it, we found some good ideas regarding immutability in Ruby.

Firstly, we need some definition for immutability. There appear to be two options.

(1) We can assume that `RB_FL_FREEZE | RB_FL_SHAREABLE` implies immutable objects. `RB_FL_FREEZE` implies the current object is frozen and `RB_FL_SHAREABLE` implies it was applied recursively (since only a completely frozen object-graph is considered shareable). The nice thing about this definition is that it works with existing objects that are frozen and shareable, including any sub-object within that.

(2) We can introduce a new flag, e.g. `RB_FL_IMMUTABLE` which implies immutable objects. `RB_FL_IMMUTABLE` would need to be applied and cached, and even if we introduced such a flag, unless care was taken, it would not be compatible with the frozen/shareable objects implicitly.

The biggest issue with (1) is that `rb_ractor_shareable_p` can update the `RB_FL_SHAREABLE` flag even though it presents the interface of being a predicate check (https://bugs.ruby-lang.org/issues/18258). We need to consider this carefully.

Regarding the interface changes, I see two important ones:

(1) Introduce `module Immutable` which is used by `class` to create immutable instances. Implementation is given already.

(2) Introduce `def Immutable(object)` which returns an immutable object (as yet not discussed).

Let's aim to implement (1) as discussed in this proposal, and we can discuss (2) later.

Regarding (1), there are only a few issues which need to be addressed, notably how `#dup` and `#clone` behave. For any immutable object, we need to be concerned about whether `#dup` and `#clone` can return mutable versions or not. We can check the current behaviour by assuming `Ractor.make_shareable(T_OBJECT)` returns immutable objects.

(1) Implementation of `#dup`. Traditional implementation returns mutable copy for normal object, and self for "immutable" objects. Overall, there are three possible implementations:

``` ruby
# (1)
immutable.dup()               # returns frozen, but not sharable (current)

# (2)
immutable.dup()               # raises an exception

# (3)
immutable.dup()               # returns self
```

Right now, we have some precedent (implemented in `object.c#special_object_p`), e.g.

``` ruby
5.dup # still immutable, return self.
:footer.dup # still immutable, return self.
```

Therefore, for immutable objects (3) makes the most sense (also most efficient option).

(2) Implementation of `#clone(freeze: true/false)`. It's similar to `#dup` but argument must be considered:

```
# (1)
immutable.clone()               # returns frozen, but not sharable (current)
immutable.clone(freeze: false) # returns unfrozen, not sharable (current)

# (2)
immutable.clone()               # returns frozen, and sharable
immutable.clone(freeze: false) # raises an exception

# (3)
immutable.clone()               # returns self
immutable.clone(freeze: false) # raises an exception
```

There is a precedent for this too:

```ruby
irb(main):001:0> :foo.clone(freeze: true)
=> :foo
irb(main):002:0> :foo.clone(freeze: false)
<internal:kernel>:48:in `clone': can't unfreeze Symbol (ArgumentError)
```

I believe (3) is the right approach because once a user object is frozen, un-freezing the top level is unlikely to create a working object, since all the internal state would still be frozen.

----------------------------------------
Feature #18035: Introduce general model/semantic for immutable by default.
https://bugs.ruby-lang.org/issues/18035#change-94207

* Author: ioquatix (Samuel Williams)
* Status: Open
* Priority: Normal
----------------------------------------
It would be good to establish some rules around mutability, immutability, frozen, and deep frozen in Ruby.

I see time and time again, incorrect assumptions about how this works in production code. Constants that aren't really constant, people using `#freeze` incorrectly, etc.

I don't have any particular preference but:

- We should establish consistent patterns where possible, e.g.
  - Objects created by `new` are mutable.
  - Objects created by literal are immutable.

We have problems with how `freeze` works on composite data types, e.g. `Hash#freeze` does not impact children keys/values, same for Array. Do we need to introduce `freeze(true)` or `#deep_freeze` or some other method?

Because of this, frozen does not necessarily correspond to immutable. This is an issue which causes real world problems.

I also propose to codify this where possible, in terms of "this class of object is immutable" should be enforced by the language/runtime, e.g.


```ruby
module Immutable
  def new(...)
    super.freeze
  end
end

class MyImmutableObject
  extend Immutable

  def initialize(x)
    @x = x
  end
  
  def freeze
    return self if frozen?
    
    @x.freeze
    
    super
  end
end

o = MyImmutableObject.new([1, 2, 3])
puts o.frozen?
```

Finally, this area has an impact to thread and fiber safe programming, so it is becoming more relevant and I believe that the current approach which is rather adhoc is insufficient.

I know that it's non-trivial to retrofit existing code, but maybe it can be done via magic comment, etc, which we already did for frozen string literals.



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>