Repository navigation
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
Conversation
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
force-pushed
the
d60-tail-assignment
branch
from
September 23, 2026 21:50
44748ea to
0377bb9
Compare
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Implements D60.
The rule (landed in #1469)
§9.1: "An assignment
place = valueis an expression whose type is the type ofplace. In statement position its value is discarded. As the tail of a body whose declared return type is notUnit, the body yields a read ofplaceafter 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 substituteT.default()."D60: "In
fn inc -> i32: g += 1, the body yields a read ofgafter the store, under the ordinary copy and move rules. §4.10's implicitT.default()applies only when the tail's own type isUnit; a tail of any other type must match the declared return type or is a type error." … "fn inc -> i32: g += 1returns 6 becausei32isCopy;fn f -> str: g += 1is a type error;fn f -> str: name = compute()with a globalnameis a move-out-of-global error, not a silent clone."Root cause (the exact lines)
with … as mutbodies are statements (#1298) #1319's discard.SemaCheck.discard_body_taildiscarded a body's own assignment tail at every site that asks it (the fn body incheck_fn_body_with_sig_at,check_blockforbody_tail_block, the closure body incheck_closure), whatever the declared return.MirLower.lower_tail_exprandlower_block_modethen lowered those tails in discard mode, andlower_fn_with_sigsubstitutedT.default(). Now the discard applies only when the body has no declared return (D43) or declaresUnit(body_tail_discards); the closure's expected function type is its declared return.MirLower.lower_expr'sNK_ASSIGNarm returnedrhsafter moving it into the place (finish_assignment_to_place). Fori32that equals the read; forstrit 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 throughlower_assign(.., read_back: true): the store exactly as a statement, thenread_assigned_placereads the place it stored to (evaluated once: compound ops,strappend,IndexPlacestores included). Sema'srecord_tail_readsrecords every assignment the returned value reaches — the body tail and, through blocks, the arms of a tailif/match— so body tail and arm tail are one rule.check_tail_read_placeapplies the ordinary rules to the read: D52 (global), D32 (field), D27 (element); a whole local moves. Under aUnitreturn — declared, or a trait contract such asDrop.drop— nothing is returned and nothing is recorded. ComptimeEval does the same.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()underfn() -> i32then failed the MIR validator). Removed: a mismatch is an error.lower_fn_with_sigchose the default by the lowered operand's type (operand_type(body_result) == ty_void), not the tail's.place_local_typehas no type for astr's.lenprojection, sofn 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 caughtcomptime_error(..)typed asTypeKind.TY_NEVER as TypeId— the kind number read as a type id, which isusize(SemaCheck); it isty_nevernow.unsafe fnbody is its source body inside the parser's unsafe wrapper; the discard verdict now reads the source body (fn_body_inner). On mainunsafe fn f(p: *mut i32) -> i32: *p = 77kept its value while the safe spelling was defaulted.Matrix (origin/main 5848ae9 stage1 → this branch)
Values (
printof the call):-> i32over a global:=+=-=*=/=%=&=|=^=<<=>>=+%=-%=*%=+|=-|=*|=i32/bool/Option[i32]block taili32/bool/Option[i32]p.y += 5v[1] = 20,v[0] *= 3, arraya[2] = 9selfinmut fn:self.n += 10,self.flag = not self.flagself(Copy) inmut fn*p = 77inunsafe fn-> i64over ani32globalstr/Vec/Option[str]/ struct withstr(moved out)-> Result[i32, E]:g += 1; block afterreturn Errif/matchover ani32globalstrfn() -> i32 = () => n += 1(x2), block, argument->underfn bump -> i32async fn -> i32/-> str-> Unitand unannotated bodies (block and single statement)fn f(v: &str) -> i64: v.lenErrors:
fn f -> str: g += 1(i32 global), block spelling,-> bool-> Result[Unit, E]: self.n += 1fn f -> str: name = compute(), globalnamename(D52)Vec/Option[str]/ structmut fn f -> str: self.name = s/Vecfield / field of a local-> str: v[0] = sv[0](D27)selfinmut fn-> P: self)ifover a globalstr, declared and unannotatedfn() -> i32 = () => flag = truefn() -> i32 = () => xs.pop()fn() -> str = () => name = s, globalOne consequence to confirm
Result[Unit, E]is notUnit, so under the blessed textmut fn bump() -> Result[Unit, E]: self.cur = next()?is a type error again — #1296's case, which #1319 made an implicitOk(()).err_d60_result_unit_tail.wpins the literal reading; §4.10 forbids the alternative ("never discards a tail's value to substituteT.default()", andOk(())is §4.10'sOk(T.default())). Nothing in the tree, examples or blog relies on it;behav_1296_assignment_tail_discarded.wpinned #1319's defaults and is replaced.Sweep
=>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 throughwith test) by both compilers: 69 identical, 1 differing —behav_d43_arm_assignment_keeps_value.w, which pinned Sema: assignment tails are discarded (#1296) andwith … as mutbodies are statements (#1298) #1319's body/closure-tail defaults (updated: 50, 11) — plusbehav_1296_assignment_tail_discarded.w(replaced). src/: the stage1 self-check (check src/main.w) is clean and the build self-hosts.:examples-tests(below). No example changes meaning; none updated.build/release_uat_fixtures/) and blog posts (docs/blog_posts/): no affected function.:behavior-tests1188 files ok,:native-compile-error-tests952 ok,:native-spec-tests210 ok,:debug-alloc-tests101 PASS (incl.da_d60_tail_assignment_moves),:examples-tests20 steps green. (On the way, the spec lane caught the mutex/rwlockDropimpls 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 D32field_*cells (#1395), where the pinned seed predates the rule — the candidate matches the expectation in every cell.Filed while doing this (not fixed here)
rhsoperand, inlet t = (s = x)anda = b = x.strcapture segfaults,i32capture's mutation is lost.-> Neverpasses Sema and fails the MIR validator.return vfalls off intoT.default()instead of "missing return" (§4.10, D43).ifarm is destroyed at function exit, not at the end of its scope (found writing a fixture)..lenfield projection reads 0;std.iter.count(unused in the tree) returned 0 through the old default and now returns that broken read.??,unwrap_orand.await.Draft until the seed-driven battery is green.