Skip to content

feat: a write through ?. happens only when every ?. receiver is not null - #175

Merged
heyJordanParker merged 8 commits into
masterfrom
feat/null-safe-writes
Oct 18, 2026
Merged

heyJordanParker merged 8 commits into
masterfrom
feat/null-safe-writes

Conversation

@heyJordanParker

@heyJordanParker heyJordanParker commented Oct 18, 2026 •

Copy link
Copy Markdown
Owner

Problem

On master, a write through ?. fails in three ways:

  • order?.note = "gift" and order?.total += this.fee() get "This write target is not supported yet in PHP#."
  • order?.items.add(item) gets "Invalid assignment to property App.Order.items: cannot assign value of type List<Item>? to expected type List<Item>."
  • order?.customer.name = "Ada" compiles. Then PHP refuses the file at load with "Can't use nullsafe operator in write context".

Solution

Spec section 14.4 now holds the approved block, as an example that sharp/bin/spec checks:

Order? order = this.orders.find(id);                 // null when no order has this id
order?.note = "gift";                                // compiles: sets note when order exists, does nothing when it's null
order?.items.add(item);                              // compiles: already allowed today, a call through ?.
order?.total += this.fee();                          // compiles: fee() runs only when order exists
order?.customer.name = "Ada";                        // compiles: skips when order is null; customer is not nullable

A write through ?. happens only when every ?. receiver on its left is not null, as in C# 14, Kotlin and Swift. When one is null, nothing is written, and neither the right side nor a set body runs. Each receiver runs once. This covers =, every compound assignment including ??=, ++, -- and index writes.

Assignment is already a value on master, so a null-safe write is one too. Its value is the written value or null, typed nullable.

The analyzer checks the write against the member exactly as it checks object.name. A private set, a value of the wrong type, and a ?. on a receiver that is never null are refused as before.

The lowering writes this PHP:

(($nullsafe#1 = $this->next()) === null ? null : $nullsafe#1->total += 1);

A local receiver is tested as itself. A plain PHP array written to a Map property through ?. crosses as it does through .. An index write into a hooked Map property calls put, as it does through ..

#166 merged first. Its checker refused a null-safe write in enter. This branch merges master once and drops that arm, so one code path decides the form.

The review's four problems

Each has a row that failed before its fix.

  1. A read after a write through ?. may be null again. After a?.name = "x", the read a?.name was typed never null, because the write remembered its value under the read's place. A write whose place goes through ?. now forgets that place, in property_assignment::analyze and at an index write's root. Row: a_read_through_null_safe_access_after_a_write_through_it_may_be_null, which covers =, +=, ++, ??=, a List index, items.add, a?.next?.name, nodes[0]?.name and the checks ?? "-" and == null.
  2. ?. skips the rest of its chain through an index. Past a ?., an index reads the collection's own element and carries the ?. null, as a member read does. check_redundant_nullsafe counts that null as no null for a later link of the same chain, so h?.inner?.name and a?.items[0]?.name are refused when inner and the element are never null. Rows: null_safe_access_skips_the_rest_of_its_chain_through_an_index, and the engine row "a write past ?. through an index".
  3. A local receiver is written as it was tested. A write through ?. holds its receiver in $nullsafe#N even when it is a local, so a?.next = (a = null) writes the object a held. Row: the engine row "a local receiver is written as it was tested", which threw "Attempt to assign property on null" before.
  4. An index into a collection that may be null is an error. PHP reports it only as a warning, so a read and a write of o.items[0] on a List<int>? both compiled. In PHP# both are now errors, through one report the read and the write share. An append keeps its own refusal. Row: a_write_into_a_collection_that_may_be_null_is_refused_as_a_read_is.

Two fixtures wrote a second ?. on a link that is never null. Link.further would have become a copy of Link.skipped, so it is gone. Nulls.through now reads other?.either(7, null), which returns what it returned before for every input null_safe.phpt runs.

Verification

  • On master, the spec example fails with the three errors above, and mago compile refuses the new fixture with 29 errors.
  • With master's mago, order?.customer.name = "Ada" compiles and then fails at load: "Fatal error: Can't use nullsafe operator in write context".
  • cargo test -p mago-semantics --test sharp: 430 passed.
  • cargo test -p mago-analyzer: 1044 PHP# and 2578 PHP tests passed.
  • cargo test -p mago-sharp-bridge: 453 lowering tests passed.
  • cargo clippy on the changed crates with -D warnings: clean. cargo fmt --all -- --check: clean.
  • Patch coverage against master: 175 lines, 0 missing.
  • sharp/bin/spec: "Checked 240 examples, ignored 1, and 0 fail." sharp/bin/spec --base origin/master: "0 entries join sharp/baseline/spec, 0 leave it."
  • sharp/bin/test --opcache --repeat --passes on the six null_safe_writes*.phpt: all 6 pass in all 22 modes. The modes are no JIT, the function JIT and the tracing JIT, each with and without opcache preloading, plus every optimizer pass.
  • sharp/bin/test --opcache --repeat on opcodes, null_safe, null_coalesce, null_coalesce_assign, null_equality, nullable_types, typed_for_counter, typed_locals and the three collection_methods tests: 11 of 11 pass in every mode.

Each engine row runs on no order and on an order:

the block of spec section 14.4: [{"finds":1,"fees":0,"order":null},{"finds":1,"fees":1,"order":{"note":"gift",…,"total":15,…,"items":1,…,"customer":"Ada",…}}]
every compound assignment: [null,{"note":"!","gift":"card","total":9,"ratio":2,"bits":14,…}]
++ and --: [null,{…,"total":12,…}]
index writes: [null,{…,"counts":[6,3],"tags":{"vip":true},"stock":{"a":1,"b":2},…}]
a receiver with a side effect runs once: [{"finds":2,"fees":0,"order":null},{"finds":2,"fees":1,"order":{"note":"found",…,"total":15,…}}]
a set body runs only when the write happens: [{"sets":0,"order":null},{"sets":2,"order":{…,"label":"L!"}}]
a local receiver is written as it was tested: [null,{"note":"cleared",…}]
a write past ?. through an index: [null,{"sku":"renamed"}]
the value of a write: [[null,null],["kept",10]]
php-sharp/
├── docs/spec.md                                section 14.4: the bullet, the rule and the block
├── Zend/tests/sharp/
│   ├── NullSafeWrites/                         Customer, Item, Order, Orders and Writes
│   ├── null_safe_writes.inc                    the rows, each on no order and on an order
│   ├── null_safe_writes{,_jit_function,_jit_tracing}.phpt
│   ├── null_safe_writes_preload.inc            the files opcache preloads
│   └── null_safe_writes_preload{,_jit_function,_jit_tracing}.phpt
└── sharp/mago/crates/
    ├── semantics/
    │   ├── src/internal/checker/sharp.rs       is_slice_target takes `object?.name`; #166's arm is gone
    │   └── tests/sharp.rs                      every write form through `?.` passes the checker
    ├── analyzer/
    │   ├── src/artifacts.rs                    null_safe_write_target
    │   ├── src/expression/mod.rs               the target's read drops the `?.` null
    │   ├── src/expression/assignment/          the write arm, write_value, the index write-back
    │   ├── src/expression/call/method_call.rs  a changed collection drops the `?.` null
    │   ├── src/expression/unary.rs             `++` and `--` through `?.`
    │   ├── src/resolver/method.rs              the declared type of `object?.name`
    │   └── tests/sharp.rs                      every form, and what stays refused
    └── sharp-bridge/
        ├── src/lower.rs                        untested_link, target, and the hooked index write
        ├── src/lower/types.rs                  accessed_property takes `object?.name`
        └── tests/lower.rs                      the conditional, the crossing and the hooked Map

…ot null

Problem

PHP# refused `order?.note = "gift"` and `order?.total += fee()` as
"This write target is not supported yet in PHP#.". The analyzer read
`order?.items.add(item)` as storing a `List<Item>?` into a
`List<Item>` property and refused it. `order?.customer.name = "Ada"`
compiled, then PHP refused it at load with "Can't use nullsafe operator
in write context".

Solution

Spec section 14.4 now has the approved block, which sharp/bin/spec
checks. A write through `?.` is `=`, a compound assignment, `??=`, `++`,
`--` or an index write. It happens only when every `?.` receiver on its
left is not null. Otherwise neither the right side nor a `set` body
runs. Each receiver runs once, and the write's value is the written
value or null, typed nullable.

The checker takes `object?.name` as a write target. The analyzer
checks the write against the member as it checks `object.name`, so a
private `set`, a wrong value type and a `?.` on a receiver that is never
null are refused as before. The read of a compound assignment or a step
never holds the null the `?.` links give. The lowering writes
`($nullsafe#N = receiver) === null ? null : $nullsafe#N->name = value`.
A local receiver is tested as itself. A plain PHP array written to a
`Map` property through `?.` crosses as it does through `.`. An index
write into a hooked `Map` property puts the key as it does through `.`.

#166 merged first and refused a null-safe write in the checker's
`enter`. This branch merges master once and drops that arm, so one
path decides the form.

php-sharp/
├── docs/spec.md                                section 14.4: the bullet, the rule and the block
├── Zend/tests/sharp/
│   ├── NullSafeWrites/                         Customer, Item, Order, Orders and Writes
│   ├── null_safe_writes.inc                    the rows, each on no order and on an order
│   ├── null_safe_writes.phpt                   no JIT, and the function and tracing JIT
│   ├── null_safe_writes_jit_*.phpt
│   ├── null_safe_writes_preload.inc            the files opcache preloads
│   └── null_safe_writes_preload*.phpt          the same rows with preloading
└── sharp/mago/crates/
    ├── semantics/
    │   ├── src/internal/checker/sharp.rs       is_slice_target takes `object?.name`
    │   └── tests/sharp.rs                      every write form through `?.` passes
    ├── analyzer/
    │   ├── src/artifacts.rs                    null_safe_write_target
    │   ├── src/expression/mod.rs               the target's read drops the `?.` null
    │   ├── src/expression/assignment/          the write arm, write_value, the index write-back
    │   ├── src/expression/call/method_call.rs  a changed collection drops the `?.` null
    │   ├── src/expression/unary.rs             `++` and `--` through `?.`
    │   ├── src/resolver/method.rs              the declared type of `object?.name`
    │   └── tests/sharp.rs                      the forms, and what stays refused
    └── sharp-bridge/
        ├── src/lower.rs                        untested_link, target and the hooked index write
        ├── src/lower/types.rs                  accessed_property takes `object?.name`
        └── tests/lower.rs                      the conditional, the crossing and the hooked Map
#166 refused `object?.name` as a write target in the checker's `enter`.
is_slice_target now takes it, so that arm never runs. One path decides
the form.

php-sharp/sharp/mago/crates/semantics/
└── src/internal/checker/sharp.rs   the NullSafeProperty arm of the refused write target
The null-safe write arm of assign_to_expression checked a redundant `?.`
only when the object had a type, and no test reaches an object without
one: the write analyzes the object first. The check now reads the
object's type, or `mixed` when it has none, which is never redundant.

php-sharp/sharp/mago/crates/analyzer/
└── src/expression/assignment/mod.rs   the redundant `?.` check of a null-safe write
Problem

- After `a?.name = "x"`, the read `a?.name` was typed never null, so
  `return a?.name;` from a `string` method compiled and returned null,
  and `a?.name ?? "-"` was refused as redundant. The write remembered
  its value, with no null, under the place the read uses.
- `?.` did not skip the rest of its chain through an index:
  `a?.items[0].name` read or written reported a possibly-null access
  although `items` is never null, and `h?.inner?.name` was accepted
  where `inner` is never null.
- `Node? a = start; a?.next = (a = null);` threw "Attempt to assign
  property on null": the write tested the local, then read it again
  after its value ran.
- `o.tags["k"] = 1` on a `Map<string, int>?` and `o.items[0] = 1` on a
  `List<int>?` compiled, and so did the read `o.items[0]`, which PHP
  reports only as a warning.

Solution

- A PHP# write whose place goes through `?.` forgets the place, in
  property_assignment and in an index write's root, so a later read is
  what it is with no write before it.
- Past a `?.`, an index reads the collection's own element and carries
  the `?.` null, as a member read does. check_redundant_nullsafe treats
  that null as no null for a later link of the same chain.
- A write through `?.` holds its receiver in `$nullsafe#N` even when it
  is a local, so it writes the object it tested. written_place names
  the write forms untested_link and null_safe_chain share.
- An index on a collection that may be null is an error in PHP#, read
  or written, through report_null_array_access, which the read and the
  write share. An append keeps its own refusal.

Spec section 14.4 states the chain rule, the tested object and the
nullable index. Two fixtures wrote a second `?.` on a link that is
never null: Link.further, a copy of Link.skipped once fixed, is gone,
and Nulls.through reads `other?.either(7, null)`, which gives what it
gave before for every input null_safe.phpt runs.

php-sharp/
├── docs/spec.md                                   section 14.4: the chain, the tested object, the nullable index
├── Zend/tests/sharp/
│   ├── NullSafeWrites/                            Item.sku is writable; Writes.cleared, inline and chained
│   ├── null_safe_writes.inc and *.phpt            the local receiver and the write past `?.` through an index
│   ├── CollectionMethods/Link.sharp               Link.further is gone
│   ├── collection_methods.inc and *.phpt          its two rows are gone
│   ├── Nulls.sharp and Nulls.inc                  through reads `other?.either`; itself is gone
│   └── opcodes.phpt                               Nulls has 16 op arrays
└── sharp/mago/crates/
    ├── analyzer/
    │   ├── src/expression/array_access.rs         the `?.` null past an index
    │   ├── src/expression/assignment/             a place through `?.` is forgotten; the nullable root is refused
    │   ├── src/resolver/property.rs               a second `?.` on a never-null link is redundant
    │   ├── src/utils/expression/array.rs          report_null_array_access, an error in PHP#
    │   └── tests/sharp.rs                         a row for each problem
    └── sharp-bridge/
        ├── src/lower.rs                           written_place; a write holds a local receiver
        └── tests/lower.rs                         the receiver in `$nullsafe#1`
Problem

In a `.sharp` file, an index into a collection that is null or may be
null said "Cannot perform array access on possibly `null` value." and
"Ensure the variable holds an array before accessing it.". PHP# has no
arrays or variables in those words.

Solution

In PHP#, report_null_array_access names the collection as written, as
"`o.items` may be null, so it has no index." and "`o.items` is null, so
it has no index.", notes that an index on `null` throws, and keeps the
help `if (value != null)`. A `.php` file keeps stock mago's text.

php-sharp/sharp/mago/crates/analyzer/
├── src/utils/expression/array.rs   report_null_array_access in PHP#'s words
└── tests/sharp.rs                  the read row, and a row for a read, a write and a definite null
# Conflicts:
#	sharp/mago/crates/semantics/src/internal/checker/sharp.rs
@heyJordanParker
heyJordanParker merged commit 5c2ddae into master Oct 18, 2026
24 checks passed
@heyJordanParker
heyJordanParker deleted the feat/null-safe-writes branch November 3, 2026 22:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant