Repository navigation
Sema: assignment tails are discarded (#1296) and with … as mut bodies are statements (#1298) - #1319
Merged
Merged
Conversation
added 2 commits
September 22, 2026 11:53
…eds no `else` (§7.2, #1298) §7.2 Form 2 always returns the builder regardless of the body's last expression; MirLower already discards the body (lower_with_binding). Sema still typed the body's tail as the block value, so the natural last line of a conditional builder, an else-less `if`, was rejected with "if expression requires an else branch". check_with_expr and check_with_tuple now check a `mut` builder body in statement context.
… is Unit (§9.1, #1296) §9.1 (D43): an assignment is an expression typed as its place, but in statement or tail position its value is discarded. Sema typed an assignment tail as the place's type, so `-> Result[Unit, E]` bodies ending in `self.x = y?` / `n += 1` got "return type mismatch" instead of §4.9's implicit `Ok(())`, and `fn f -> i32: n += 1` returned the assigned value instead of §4.10's `i32.default()`. One predicate, expr_is_assignment, decides it at every tail site: the block tail in check_block, the single-statement fn body, and the closure body (the recorded body type is what MirLower reads for the implicit default). MirLower's lower_block_mode, the fn root and the closure root consult the same predicate and lower the tail in discard mode. The unannotated-only special case (tail_expr_is_assignment in infer_unannotated_function_return_type) is subsumed and removed. Test covers both body spellings, `=`/`+=`, Result[Unit, E], `-> i32` and `-> str` defaults, the unannotated Unit case, and a typed closure. (A closure over a global still panics MirLower: #1313, pre-existing.)
This was referenced Sep 22, 2026
Discard a bare assignment if/match arm (#1319's missed case) — fixes red behav_distinct_compat
#1332
Closed
ehartford
added a commit
that referenced
this pull request
Sep 22, 2026
…mpiler defects (#1338) * examples: ephemerality-and-lowering stores the element directly, store(order[2], ...) (#1287 fixed in #1311) The typed-binding detour around #1287 (Atomic intrinsics passed an element view's address as the value) is gone with its comment. Package test output unchanged on a release compiler built from ae609cd. * examples: json-parser matches byte literals as patterns and returns &entry.value inline (#1295, #1297 fixed) Byte arms are Some(b'{') patterns, not guards (#1295, fixed in #1312); json_get_field returns Some(&entry.value) from a for loop over the entries, and the kv_value helper is gone (#1297, fixed in #1327). Workaround comments removed. Demo and package test output unchanged on a release compiler built from ae609cd. * examples: nebula's Status and Telemetry carry @[derive(Debug, Clone)] again (§11.8; #1288, #1289 fixed in #1311) The parking comment is removed. Demo and package test output unchanged on a release compiler built from ae609cd. * examples: service builds its change list and SET clause with the §7.2 builder (#1298 fixed in #1319) describe_changes and PgUserRepo.update spell with Vec.new() as mut ...: with a trailing if; the var desugaring and its comments are gone. Demo and package test output unchanged on a release compiler built from ae609cd (neither function is reached by the demo; the same shape was run separately under --debug-alloc: correct result, zero leaks). * examples: ecs cites D43 for DenseStorage.insert's -> Unit, not #1296 insert's tail if has an assignment arm (a value of type T) and a push arm (Unit): two meanings remain, so -> Unit is the spelling D43 requires, not a workaround. The compiler currently infers Unit without it because the assignment arm is a multi-statement block (#1337); the one-statement spellings of the same arm are rejected as D43 requires. --------- Co-authored-by: Eric Hartford <[email protected]>
ehartford
pushed a commit
that referenced
this pull request
Sep 22, 2026
…keeps its value (D43, #1337) Eric's ruling (2026-09-22): D43 as blessed decides. §9.1 "an assignment `place = value` is an expression whose type is the type of `place`; in statement or tail position its value is discarded", read with D43's pinned test err_d43_cannot_infer_match.w: "tail position" is a function's or closure's OWN body tail (single-statement body or last statement of the body block). A written arm of a tail if/match, bare or as an arm block's tail, keeps the place's type and joins under D43. #1319 (980474c) consulted expr_is_assignment at every block tail in check_block and lower_block_mode, so an arm block whose last statement was an assignment became Unit. The verdict then depended on statement count: `if p: seen = 1` and `if p: { seen = 1 }` were "cannot infer", while the same arm with a preceding `let` inferred Unit (#1337), and behav_distinct_compat's `check` (both arms end in `x = x + 1`) was rejected. Sema now marks the body node (body_tail_block) at the fn body and closure body; check_block discards a tail only for that block, and discard_body_tail records each discarded tail. MirLower's lower_tail_expr and lower_block_mode lower exactly the recorded tails in discard mode, so Sema and MirLower share one verdict. #1319's #1296 cases (Result[Unit, E] bodies ending in `x = y?` / `n += 1`, `-> i32` / `-> str` defaults, closure bodies) and #1298 (with ... as mut bodies) are unchanged. Tests: err_d43_cannot_infer_if_multi_stmt_arm (the #1337 repro), err_d43_cannot_infer_match_block_arm and _braced_arm (arm-block spellings of the pinned test), behav_d43_arm_assignment_keeps_value (arms return the assigned value; body and closure-body tails are still discarded). Fixes #1337.
ehartford
added a commit
that referenced
this pull request
Sep 22, 2026
…keeps its value (D43, #1337) (#1339) Eric's ruling (2026-09-22): D43 as blessed decides. §9.1 "an assignment `place = value` is an expression whose type is the type of `place`; in statement or tail position its value is discarded", read with D43's pinned test err_d43_cannot_infer_match.w: "tail position" is a function's or closure's OWN body tail (single-statement body or last statement of the body block). A written arm of a tail if/match, bare or as an arm block's tail, keeps the place's type and joins under D43. #1319 (980474c) consulted expr_is_assignment at every block tail in check_block and lower_block_mode, so an arm block whose last statement was an assignment became Unit. The verdict then depended on statement count: `if p: seen = 1` and `if p: { seen = 1 }` were "cannot infer", while the same arm with a preceding `let` inferred Unit (#1337), and behav_distinct_compat's `check` (both arms end in `x = x + 1`) was rejected. Sema now marks the body node (body_tail_block) at the fn body and closure body; check_block discards a tail only for that block, and discard_body_tail records each discarded tail. MirLower's lower_tail_expr and lower_block_mode lower exactly the recorded tails in discard mode, so Sema and MirLower share one verdict. #1319's #1296 cases (Result[Unit, E] bodies ending in `x = y?` / `n += 1`, `-> i32` / `-> str` defaults, closure bodies) and #1298 (with ... as mut bodies) are unchanged. Tests: err_d43_cannot_infer_if_multi_stmt_arm (the #1337 repro), err_d43_cannot_infer_match_block_arm and _braced_arm (arm-block spellings of the pinned test), behav_d43_arm_assignment_keeps_value (arms return the assigned value; body and closure-body tails are still discarded). Fixes #1337. Co-authored-by: Eric Hartford <[email protected]>
ehartford
pushed a commit
that referenced
this pull request
Sep 23, 2026
…ger needs blocks × keys cells (#1343, #1315, #1282) Root cause. mir_drop_state_blocks_new (src/MirCore.w) allocated one dense out-state row per block, `for _ in 0..bb_count * keys.len(): rows.push(...)`, and every visit copied, joined and compared whole key-width rows (load_block / input / equal / store_block). lldb on the hanging stage1 (`check hello.w --validate-all`, break after mir_drop_state_keys_new with the condition bb_count > 10000) read bb_count = 0xa35a (41,818) and keys.len() = 0xa8ba (43,194): 1.8 G i32 cells, the 7.3 GB RSS of every report, then O(blocks × keys) work per sweep. The body is pcre2's `match_` (`--dump-mir`: "body too large locals=39712 bbs=41818 stmts=45104"). Why only stage1. Not a miscompile: a stage1 embeds no .wo bundles, so the prelude's std.regex resolves std.re.* to lib/std/re source and every program lowers all of pcre2 (stage1 `--dump-mir` of hello.w: 428 bodies; the release binary: 160). The release binary has the same defect on any body that size: `with check lib/std/re/pcre2_match.w --validate-all` on the installed release compiler ran for 300 s before timeout killed it. Why #1319. #1319's code is not involved: before it, `analyze` on a stage1 failed earlier on hello world, so it never reached the driver; `check --validate-all` already hung on stage1 before #1319 (#1282, #1315; reproduced on a stage1 built before #1319 merged). Fix. A state is stored in chunks of up to 128 keys, and stored chunks are hash-consed in the key table's chunk store, so equal content always has one id. A block row is one chunk id per chunk; a map copies a chunk only on the first write that changes it; the join of two stored chunks is memoized on the id pair; the fixpoint loop reuses one scratch map; the entry state is interned once. The join is not associative, so input() still folds predecessors in CSR order, chunk by chunk — the same computation per key, and the driver visits blocks in the same order, so every state matches the dense version exactly. Evidence (fresh :dev stage1): - `analyze examples/hello.w audit:all`: facts=639634 violations=0 ok in 17.7 s (was: never returned). - `check examples/hello.w --validate-all`: ok in 12.8 s, 472 MB peak (was: never returned, 7.3 GB); #1315's repro: validate-all and validate-ownership ok in 11.9 s. - Old stage1 (ae609cd) vs this stage1, both with --link-bundle out/wo/pcre2 so the old one finishes, over 101 files (every 12th test/behavior file plus examples/*.w): --dump-drop-state, --dump-drop-plan and --validate-all output byte-identical, 303/303, including one ownership-verdict failure that both report the same way. - validate-all verdicts match out/release/bin/with on hello.w and five behavior tests. (cherry picked from commit 6a176f8)
ehartford
added a commit
that referenced
this pull request
Sep 23, 2026
…ger needs blocks × keys cells (#1343, #1315, #1282) (#1353) Root cause. mir_drop_state_blocks_new (src/MirCore.w) allocated one dense out-state row per block, `for _ in 0..bb_count * keys.len(): rows.push(...)`, and every visit copied, joined and compared whole key-width rows (load_block / input / equal / store_block). lldb on the hanging stage1 (`check hello.w --validate-all`, break after mir_drop_state_keys_new with the condition bb_count > 10000) read bb_count = 0xa35a (41,818) and keys.len() = 0xa8ba (43,194): 1.8 G i32 cells, the 7.3 GB RSS of every report, then O(blocks × keys) work per sweep. The body is pcre2's `match_` (`--dump-mir`: "body too large locals=39712 bbs=41818 stmts=45104"). Why only stage1. Not a miscompile: a stage1 embeds no .wo bundles, so the prelude's std.regex resolves std.re.* to lib/std/re source and every program lowers all of pcre2 (stage1 `--dump-mir` of hello.w: 428 bodies; the release binary: 160). The release binary has the same defect on any body that size: `with check lib/std/re/pcre2_match.w --validate-all` on the installed release compiler ran for 300 s before timeout killed it. Why #1319. #1319's code is not involved: before it, `analyze` on a stage1 failed earlier on hello world, so it never reached the driver; `check --validate-all` already hung on stage1 before #1319 (#1282, #1315; reproduced on a stage1 built before #1319 merged). Fix. A state is stored in chunks of up to 128 keys, and stored chunks are hash-consed in the key table's chunk store, so equal content always has one id. A block row is one chunk id per chunk; a map copies a chunk only on the first write that changes it; the join of two stored chunks is memoized on the id pair; the fixpoint loop reuses one scratch map; the entry state is interned once. The join is not associative, so input() still folds predecessors in CSR order, chunk by chunk — the same computation per key, and the driver visits blocks in the same order, so every state matches the dense version exactly. Evidence (fresh :dev stage1): - `analyze examples/hello.w audit:all`: facts=639634 violations=0 ok in 17.7 s (was: never returned). - `check examples/hello.w --validate-all`: ok in 12.8 s, 472 MB peak (was: never returned, 7.3 GB); #1315's repro: validate-all and validate-ownership ok in 11.9 s. - Old stage1 (ae609cd) vs this stage1, both with --link-bundle out/wo/pcre2 so the old one finishes, over 101 files (every 12th test/behavior file plus examples/*.w): --dump-drop-state, --dump-drop-plan and --validate-all output byte-identical, 303/303, including one ownership-verdict failure that both report the same way. - validate-all verdicts match out/release/bin/with on hello.w and five behavior tests. (cherry picked from commit 6a176f8) Co-authored-by: Eric Hartford <[email protected]>
ehartford
added a commit
that referenced
this pull request
Sep 23, 2026
…ds a read of its place; the implicit default applies only to a Unit tail (#1469) Blessed by Eric 2026-09-23 (option a with the narrowing; §9.1 in his words). Records #1319's silent inc()=6->0 change as a defect. Co-authored-by: Eric Hartford <[email protected]>
ehartford
pushed a commit
that referenced
this pull request
Sep 23, 2026
… 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).
ehartford
added a commit
that referenced
this pull request
Sep 24, 2026
… of its place; the implicit default applies only to a Unit tail (§9.1, §4.10) (#1536) * 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) §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). * MIR: §4.10's implicit default follows Sema's type of the body, not the 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. --------- Co-authored-by: Eric Hartford <[email protected]>
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.
Fixes #1296 and #1298 — two Sema tail-typing defects, one rule each.
#1296 — assignment in tail position is discarded (§9.1, D43)
Spec §9.1: "An assignment
place = valueis an expression whose type is the type ofplace; in statement or tail position its value is discarded." Sema typed an assignment tail as the place's type, so:mut fn bump() -> Result[Unit, E]: self.cur = next(self.n)?(andself.n += 1) → "return type mismatch" instead of §4.9's implicitOk(()).fn inc -> i32: g += 1silently returned1; §9.1 makes the tail Unit and §4.10 then returnsi32.default()=0. Same for-> str→"". (A-> Twith noDefaultis the usual §4.10 mismatch.)Fix: one predicate
Sema.expr_is_assignment, asked at every tail site —check_block's tail, the single-statement fn body, the closure body — and read by MirLower at the same three sites (lower_block_mode, fn root, closure root vialower_tail_expr) so the lowering agrees with the verdict. The unannotated-only special case (tail_expr_is_assignmentininfer_unannotated_function_return_type) is subsumed and removed; D43 inference keeps its answer through the same path.#1298 —
with expr as mut x:body is statements (§7.2)§7.2: the builder "always returns
xregardless of the type of the body's last expression".MirLower.lower_with_bindingalready discards the body; Sema still typed its tail as the block value, rejecting a trailing else-lessif.check_with_expr/check_with_tuplenow check amutbuilder body in statement context.Tests
test/behavior/behav_1296_assignment_tail_discarded.w— block and single-statement bodies,=and+=,Result[Unit, E],-> i32/-> strdefaults, unannotated Unit, grouped tail, typed closure.test/behavior/behav_1298_builder_trailing_if.w— block and single-line trailingif, bound and returned builders. Observes throughi32fields only: heap-owning builder contents are lost on return (Spec test spec_ss04_8_unit_elision fails: §4.8 unit elision unimplemented #723 — concretestr-field repro added there).Verification (iterate tier)
with check src/main.wok;WITH=$PWD/src/main src/main build :devok; underout/bootstrap/bin/with-stage1: both new tests,test/spec/spec_ss09_1*,test/spec/spec_ss07_*, every*tail*/behav_d43_*/ closure / builder behavior test, and every test expecting "return type mismatch", "requires an else branch", "cannot infer return type", "missing return" or "does not implement Default" (108 files): exit 0; the only reds arespec_ss07_1/spec_ss07_2,known-issue #723, red as expected and identical on the seed.:fixpoint/:testnot run — battery pending.Found on the way
varpanics MirLower: "anonymous capture lacks a concrete local type" #1313: any closure that names a globalvarpanics MirLower ("anonymous capture lacks a concrete local type") — pre-existing on the installed compiler; the closure case in the test uses a captured local.str-field builder repro.