Skip to content

D60: a tail assignment under a declared non-Unit return yields a read of its place; the implicit default applies only to a Unit tail (§9.1, §4.10) - #1536

Merged
ehartford merged 2 commits into
mainfrom
d60-tail-assignment
Sep 24, 2026
Merged

ehartford merged 2 commits into
mainfrom
d60-tail-assignment

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

Implements D60.

The rule (landed in #1469)

§9.1: "An assignment place = value is an expression whose type is the type of place. In statement position its value is discarded. As the tail of a body whose declared return type is not Unit, the body yields a read of place after the store, under the ordinary copy and move rules."

§4.10: "The implicit default applies only when the tail's own type is Unit. A tail of any other type is the body's value: it must match the declared return type or it is a type error. The compiler never discards a tail's value to substitute T.default()."

D60: "In fn inc -> i32: g += 1, the body yields a read of g after the store, under the ordinary copy and move rules. §4.10's implicit T.default() applies only when the tail's own type is Unit; a tail of any other type must match the declared return type or is a type error." … "fn inc -> i32: g += 1 returns 6 because i32 is Copy; fn f -> str: g += 1 is a type error; fn f -> str: name = compute() with a global name is a move-out-of-global error, not a silent clone."

Root cause (the exact lines)

  1. Sema: assignment tails are discarded (#1296) and with … as mut bodies are statements (#1298) #1319's discard. SemaCheck.discard_body_tail discarded a body's own assignment tail at every site that asks it (the fn body in check_fn_body_with_sig_at, check_block for body_tail_block, the closure body in check_closure), whatever the declared return. MirLower.lower_tail_expr and lower_block_mode then lowered those tails in discard mode, and lower_fn_with_sig substituted T.default(). Now the discard applies only when the body has no declared return (D43) or declares Unit (body_tail_discards); the closure's expected function type is its declared return.
  2. The arm value was the right-hand operand. MirLower.lower_expr's NK_ASSIGN arm returned rhs after moving it into the place (finish_assignment_to_place). For i32 that equals the read; for str it was a second owner (fn f(p: bool) -> str: var s = ""; if p: s = a() else: s = b() double-freed on main). A returned assignment now lowers through lower_assign(.., read_back: true): the store exactly as a statement, then read_assigned_place reads the place it stored to (evaluated once: compound ops, str append, IndexPlace stores included). Sema's record_tail_reads records every assignment the returned value reaches — the body tail and, through blocks, the arms of a tail if/match — so body tail and arm tail are one rule. check_tail_read_place applies the ordinary rules to the read: D52 (global), D32 (field), D27 (element); a whole local moves. Under a Unit return — declared, or a trait contract such as Drop.drop — nothing is returned and nothing is recorded. ComptimeEval does the same.
  3. closure_default_from_side_effect (check_closure) accepted a mismatched non-Unit closure tail whenever the body mutated a capture and let MIR default it (() => xs.pop() under fn() -> i32 then failed the MIR validator). Removed: a mismatch is an error.
  4. lower_fn_with_sig chose the default by the lowered operand's type (operand_type(body_result) == ty_void), not the tail's. place_local_type has no type for a str's .len projection, so fn view_len(v: &str) -> i64: v.len (std.string) returned 0. The default now follows the body's Sema type (as the closure path already did); a value tail that lowers to the Unit constant is a loud phase bug. That check also caught comptime_error(..) typed as TypeKind.TY_NEVER as TypeId — the kind number read as a type id, which is usize (SemaCheck); it is ty_never now.
  5. An unsafe fn body is its source body inside the parser's unsafe wrapper; the discard verdict now reads the source body (fn_body_inner). On main unsafe fn f(p: *mut i32) -> i32: *p = 77 kept its value while the safe spelling was defaulted.

Matrix (origin/main 5848ae9 stage1 → this branch)

Values (print of the call):

cell main D60
-> i32 over a global: = += -= *= /= %= &= |= ^= <<= >>= +%= -%= *%= +|= -|= *|= 0 each 9 10 8 24 12 2 2 10 9 36 18 19 18 36 37 36 72
local i32 / bool / Option[i32] block tail 0 / false / None 42 / true / Some(3)
global i32 / bool / Option[i32] 0 / false / None 7 / true / Some(11)
field of a local struct, p.y += 5 0 7
element v[1] = 20, v[0] *= 3, array a[2] = 9 0, 0, 0 20, 12, 9
field of self in mut fn: self.n += 10, self.flag = not self.flag 0, false 11, true
whole self (Copy) in mut fn "does not implement Default" 7
raw pointee *p = 77 in unsafe fn 77 77
-> i64 over an i32 global 0 8
local str / Vec / Option[str] / struct with str (moved out) "" / len 0 / None / "does not implement Default" hi! / 2 / hi! / 2 hi!, leak count=0
-> Result[i32, E]: g += 1; block after return Err Ok(0); "missing return" Ok(6); Ok(42)
arms of a tail if/match over an i32 global 1 6 100 200 199 same
arms over a local str yes!, then DOUBLE FREE yes! no!, leak count=0
closure fn() -> i32 = () => n += 1 (x2), block, argument 0 0 0 0 1 2 24 99
trait impl without -> under fn bump -> i32 0 the stored value
async fn -> i32 / -> str 0 / "" 6 / hi!
-> Unit and unannotated bodies (block and single statement) discarded discarded (unchanged)
fn f(v: &str) -> i64: v.len 0 5

Errors:

cell main D60
fn f -> str: g += 1 (i32 global), block spelling, -> bool ran, returned "" / false return type mismatch (help names the read)
-> Result[Unit, E]: self.n += 1 Ok(()) return type mismatch
fn f -> str: name = compute(), global name "" cannot move out of global name (D52)
global Vec / Option[str] / struct 0 / None / "does not implement Default" D52 error
mut fn f -> str: self.name = s / Vec field / field of a local "" / 0 / "" a field never moves out implicitly (D32)
-> str: v[0] = s "" cannot move out of element v[0] (D27)
whole non-Copy self in mut fn "does not implement Default" mut receiver is too weak (as -> P: self)
arm of a tail if over a global str, declared and unannotated "yes" (double owner) D52 error
closure fn() -> i32 = () => flag = true 0 closure return type mismatch
closure fn() -> i32 = () => xs.pop() invalid MIR closure return type mismatch
closure fn() -> str = () => name = s, global "" D52 error

One consequence to confirm

Result[Unit, E] is not Unit, so under the blessed text mut fn bump() -> Result[Unit, E]: self.cur = next()? is a type error again — #1296's case, which #1319 made an implicit Ok(()). err_d60_result_unit_tail.w pins the literal reading; §4.10 forbids the alternative ("never discards a tail's value to substitute T.default()", and Ok(()) is §4.10's Ok(T.default())). Nothing in the tree, examples or blog relies on it; behav_1296_assignment_tail_discarded.w pinned #1319's defaults and is replaced.

Sweep

  • Candidates: a line scanner over src/, lib/, tools/, test/, examples/, build/ (3,352 files) for functions whose body tail, tail-arm chain or => body holds a top-level assignment: 248 hits in 72 files. The ones outside the compiler, with build.w and every single-file example and example test (70 files), were checked (or run through with test) by both compilers: 69 identical, 1 differing — behav_d43_arm_assignment_keeps_value.w, which pinned Sema: assignment tails are discarded (#1296) and with … as mut bodies are statements (#1298) #1319's body/closure-tail defaults (updated: 50, 11) — plus behav_1296_assignment_tail_discarded.w (replaced). src/: the stage1 self-check (check src/main.w) is clean and the build self-hosts.
  • Examples: the single-file examples and example tests are in the 70 above (identical); the packages build and run under :examples-tests (below). No example changes meaning; none updated.
  • Release UAT fixtures (build/release_uat_fixtures/) and blog posts (docs/blog_posts/): no affected function.
  • Lanes, run locally on the final commit with its release compiler (driven by the pinned seed): :behavior-tests 1188 files ok, :native-compile-error-tests 952 ok, :native-spec-tests 210 ok, :debug-alloc-tests 101 PASS (incl. da_d60_tail_assignment_moves), :examples-tests 20 steps green. (On the way, the spec lane caught the mutex/rwlock Drop impls reading a global under a Unit contract; fixed before this run.)

Audits

:drop-audit: 176 cells, 0 non-PASS, 0 regressions vs baseline. :move-audit: 73 cells, 0 vs-expected FAIL; its 42 candidate-vs-baseline DIFFs are the D32 field_* cells (#1395), where the pinned seed predates the rule — the candidate matches the expectation in every cell.

Filed while doing this (not fixed here)

Draft until the seed-driven battery is green.

Eric Hartford added 2 commits September 23, 2026 17:20
… of its place; the implicit default applies only to a Unit tail (§9.1, §4.10)

§9.1: "An assignment `place = value` is an expression whose type is the
type of `place`. In statement position its value is discarded. As the tail
of a body whose declared return type is not `Unit`, the body yields a read
of `place` after the store, under the ordinary copy and move rules."
§4.10: "The implicit default applies only when the tail's own type is
`Unit`. ... The compiler never discards a tail's value to substitute
`T.default()`."

#1319 discarded every body's own assignment tail (SemaCheck
discard_body_tail at the fn body, check_block's body_tail_block tail and
the closure body; MirLower.lower_tail_expr and lower_block_mode lowered the
recorded tails in discard mode), and §4.10 then substituted T.default():
`fn inc -> i32: g += 1` returned 0. Now:

- Sema: discard_body_tail discards only when the body declares no return
  (D43) or `Unit` (body_tail_discards). Otherwise record_tail_reads records
  every assignment the returned value reaches — the body's own tail and,
  through blocks and groupings, the arms of a tail if/match (D43 already
  kept their value): body tail and arm tail are one rule.
  check_tail_read_place holds the read to the ordinary rules: a global that
  needs drop is never moved out of (D52), a field never moves implicitly
  (D32), an element is never moved out of its collection (D27); a whole
  local moves. A mismatched tail is "return type mismatch" at the
  assignment, with the read it yields named.
- The closure body's closure_default_from_side_effect exemption discarded
  a mismatched non-Unit tail whenever the body mutated a capture (and then
  lowered an Option into an i32 slot: invalid MIR); it is removed.
- MirLower: lower_assign(.., read_back) stores as a statement does, then
  read_assigned_place reads the place back once (compound, str append and
  IndexPlace stores evaluate the place once). The arm value is no longer
  the right-hand operand the place already owns (#1339's arm with a str
  local double-freed).
- ComptimeEval: a recorded tail assignment evaluates to the place's value.
- An `unsafe fn` body is its source body inside the parser's unsafe wrapper
  (fn_body_inner); the discard verdict reads the source body.

Consequence the ruling's text decides: `-> Result[Unit, E]` is not `Unit`,
so `mut fn bump() -> Result[Unit, E]: self.n += 1` is a type error again
(#1296's case); err_d60_result_unit_tail pins it.

behav_1296_assignment_tail_discarded pinned #1319's defaults and is
replaced by the D60 fixtures; behav_d43_arm_assignment_keeps_value's body
and closure tails now read their places (50, 11).

A Unit return — declared, or a trait's contract such as Drop.drop —
returns nothing, so no read is recorded under it, whatever a nested block
of the body ends in (behav_d60_unit_return_nested_tail; the spec_ss14_17
mutex/rwlock Drop impls end in an `unsafe:` block assigning a global str).
…e lowered operand's; a str's `.len` tail returned 0

§4.10: "The implicit default applies only when the tail's own type is
`Unit`. ... The compiler never discards a tail's value to substitute
`T.default()`."

lower_fn_with_sig chose the default when `operand_type(body_result)` was
Unit. place_local_type has no type for a str's `.len` projection
(struct_field_type of str is 0), so `fn view_len(v: &str) -> i64: v.len`
(std.string) and any `-> i64: v.len` body discarded the value and returned
i64.default(): 0, no diagnostic. The default now follows the body's Sema
type (expr_type, as the closure body already does); a value tail that
lowered to the Unit constant is a loud phase bug, not a fallback. Found by
that check, added at this line for D60: the stage1 self-check tripped it on
view_len.

behav_d60_value_tail_not_defaulted: 5 5 / 5 false (was 0 0 / 0 false).

The same check caught issue155_dead_comptime_error: Sema typed
`comptime_error(..)` as `TypeKind.TY_NEVER as TypeId`, the kind number read
as a type id — usize — so `fn dead_stub() -> i32: comptime_error("..")` had
a usize tail. It is `ty_never` now; after a diverging tail the return slot
is still filled in the block nothing reaches.
@ehartford

Copy link
Copy Markdown
Contributor Author

Battery (seed-driven, new seed, cold c_import cache, with :drop-audit/:move-audit) rebased on main (0377bb9, pushed): build ok, :fixpoint ok, :drop-audit ok, :move-audit ok, :test ok (no reds), :test-green ok, :last-green ok. Eric confirmed g += 1 yields g after the store; the -> Result[Unit, E]: self.n += 1 type error stands (drop the annotation and it infers). Follow-up: make that error's fix-it say so.

@ehartford
ehartford marked this pull request as ready for review September 23, 2026 21:50
@ehartford
ehartford merged commit 3de6386 into main Sep 24, 2026
@ehartford
ehartford deleted the d60-tail-assignment branch September 24, 2026 00:04
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