[php-src] PR #13800: [RFC] Implement data classes (WIP)
| From: | iluuu1994 | Date: | Mon, 25 Mar 2024 01:37:06 +0000 |
| Subject: | [php-src] PR #13800: [RFC] Implement data classes (WIP) | ||
| Groups: | php.git-pulls | ||
| Request: | Send a blank email to git-pulls+get-25536@lists.php.net to get a copy of this message | ||
Pull Request: https://github.com/php/php-src/pull/13800
Author: iluuu1994
This is some early experimentation on data classes, which are objects with value semantics (the same
as arrays and strings). The main motivation is making data structures modeled with classes more
ergonomic. For example, there's a desire for a faster
Vector implementation (like
the one from [php-ds](https://medium.com/p/9dda7af674cd)). However, reference types can lead to
defensive copying to avoid accidental changes at a distance to an owned value, or bugs if copying is
mistakenly omitted. readonly solves the latter by completely disallowing mutation.
However, this essentially just forces a copy, which is bad for performance, especially for big data
structures.
Data classes instead automatically "separate" (clone) themselves from any other reference
only once a modification is made to the object. If it is only referenced from a single place, no
copy is needed. These are also called CoW (copy-on-write) semantics.
Method calls pose an interesting problem: When there is a chain of property accesses, ending in a
method call, the entire chain must be separated to avoid the change from leaking to other
references. However, with the standard method call syntax, it is not clear whether a call will refer
to a self-mutating method call (imagine a Vector::push() method, requiring separation),
or an immutable method (not requiring separation) in advance. To signal to the engine that the chain
needs to be separated, as it would for arrays on $a['b']['c] =
'c';, we use the $parent->children->push!($child); syntax
instead. If $parent is referenced from multiple places, it will be cloned and the clone
will be stored in $parent. The same happens for the children property.
This ensures that any other reference to the same instance as $parent remains
unmodified.
*Side note*: We're looking for a different syntax for method calls, because Bob would like to
use it for macros at some point.
**TODOs**:
- [ ] mutating at decl-site support
- [ ] SplObjectStorage support
- [ ] WeakMap?
- WeakMap is a weird use-case for data values, because their RCs change
unpredictably. It might be best to disallow them as WeakMap keys. Moreover,
WeakMap will not add a refcount for its object key, making it possible to change the
hash by modifying the object in-place, leaving the object in the wrong bucket.
- [ ] Opcache/Optimizer
- [ ] RC inference
- [ ] Aliasing