Repository navigation
spec §15.4.7/§11.9 / D61: Debug is recursive, quoted and escaped; maps print sorted - #1480
Merged
Merged
Conversation
…licit impl Debug honored at every depth; maps print sorted Blessed by Eric 2026-09-23 (option a as written, plus sorted map keys; :? needs no derive per 'Available for all types').
This was referenced Sep 23, 2026
ehartford
pushed a commit
that referenced
this pull request
Sep 27, 2026
…no value (Maybe) is rejected (#1559) A synthesized enum formatter (D61, #1480) registered its per-arm payload temps in one statement frame and dropped them at the join; on the arm that never wrote the temp the drop freed stack garbage (`with run test/behavior/derive_enum_debug_clone.w`: "invalid free addr=..."). `--validate-all` said ok, and `--dump-drop-plan` classified the drop as `state_before=Maybe action=conditional`. Root cause: the drop-state join of Init and Uninit is Maybe, and validate_ownership_body treated a Maybe drop as a guarded (reset-on-move) drop. It is not: Uninit is storage never written (a StorageLive without the zero flag — LLVM allocas are not zeroed), dead after StorageDead, or already dropped (a drop does not blank), and the null guard protects only the reset blank. #1111 rejected a drop that is Uninit on every path; the Uninit-on-one-path case passed. (#1414 already split MaybeMoved out of Maybe, so Maybe now means exactly this.) Fix: - mir_whole_drop_verdict rejects a whole-place drop in state Maybe of a type with drop glue: "drop of X reaches a path where it holds no value — written on one path, never written, dead or already dropped on another (Maybe); only a reset blank is safe to drop (§2.5.1)". A reset blank beside a value joins to Init, and zero-initialized storage is Init, so both stay legal. Glue is sema_dropped_types, a new snapshot of the drop-glue types of every dropped place (a place need not be moved for a drop of garbage to free it). - A sub-place drop no longer joins Uninit into the whole place (MirDropStateMap.mark_place): the drop-before-overwrite of a field (`drop(_4.selected_target); _4.selected_target = move _6`) leaves the whole value there, and the join made every such struct Maybe — 19 of the first sweep's 20 Maybe verdicts over src/main.w. What that join used to catch — a field dropped and not written again, then the whole dropped — is now its own rule (mir_drop_redropped_subplace: "drop of X frees X.f again: a path reaching it dropped that part and nothing wrote it since"). Sweep: `with-stage1 check src/main.w --validate-all` is ok. The rule's remaining finding in the compiler was a real defect — ConanPatch.cp_patched_text's `if ...: let _last = file.pop()`, whose binding dropped at function exit on the path that skipped the arm — fixed in the previous commit (a body that is no block is its own scope). Tests (each fails against the MirCore.w of the previous commit): - MirValidationTests.mir_test_maybe_uninit_drop (test/internals/mir_maybe_uninit_drop_test.w): storage written on one arm and dropped at the join (Maybe, rejected); the same with zero-initialized storage, and with no drop glue (ok). Panic at src/MirValidationTests.w:974 before. - MirValidationTests.mir_test_field_redrop (test/internals/mir_field_redrop_test.w): a field dropped and rewritten, then the whole dropped (ok — the old join said Maybe); a field dropped and not rewritten (rejected). Fixes #1559
ehartford
added a commit
that referenced
this pull request
Sep 27, 2026
…double-drop rules, view liveness across blocks, 12 drop fixes (#1791) * Sema: a `break` in a let-else's else branch exits its loop — fall-through reads Sema's break targets, not a syntax walk (#1733) `while true: let Some(x) = e else: break` returned garbage from its function (`count_to(3)` printed 17448976 on the base stage1) and a returned Vec came back empty with its buffer leaked. Root cause: Sema.body_can_fall_through decided whether a `while true`, `loop` or `do`-`while` exits with body_contains_break, a hand-written walk that descended into blocks, `if`s and `match`es only. A `break` in a let-else's else branch (or in a `let x = y ?? break`, or a labeled `break 'outer` from a nested loop) was invisible, so the loop read as never exiting and the function body as never falling through. MIR (lower_fn_body, `body_falls_through`) then skipped `_0 = <tail>`: the base MIR of count_to computes the tail into `_15` and returns without storing it (bb13: `_15 = cast(copy _14 as ty3); drop(_3); return;`), so LLVM saw an undefined return value. body_contains_break_to_label had the same gap for a labeled block (`'parse: let Some(x) = v else: break 'parse`), typing the block Never. Fix (D65, one owner): check_expr's NK_BREAK arm already resolves every break to its target frame; it now records the target's node in Sema.break_target_nodes, and body_can_fall_through and the labeled-block typing in check_block read that fact (is_break_target). The two syntax walkers are deleted. Test: test/behavior/behav_let_else_break_exits_loop.w — a `while true`, a `loop` returning a Vec[str], and a labeled block, each exited by a let-else `break`. Base stage1: prints `while 3 51` and then nothing, rc=0 (the undefined return value let LLVM discard the rest of main). Fixes #1733 * MIR: a comprehension drops each iteration's temporaries in that iteration, moves map keys and values into the map once, and traverses a &Vec (#1736) Three comprehension bugs (§13.6, §2.5), plus the filter's form of the first, all on the base stage1: 1. `[f"a{i}" for i in 0..3]` — `run --debug-alloc`: leak count=2. Base MIR of main: the formatted `i` (`_9 = sym13555(copy _6)`) is written on every iteration and dropped once, after the loop (bb5: `drop(_9)`). Root cause: lower_comprehension_body lowered the element (through lower_comprehension_next_or_push) with no statement frame, so its temps registered in the enclosing statement's frame. The generic-iterator and generator clauses already framed their leaf; the range, range-var, slice and Vec clauses (which all go through lower_comprehension_body) did not. The filter had the same gap in every clause kind: `[i for i in 0..3 if f"{i}" != "1"]` leaked 5 blocks. 2. `let hm: HashMap[str, i32] = [f"k{i}": i for i in 0..3]` — DOUBLE FREE (first_drop=__drop_struct_16, second_drop=__drop_struct_1803). Base MIR: `call sym245(copy _2, move _11, copy _6)` inserts the key, then bb5 drops `_11` again at the comprehension's end. Root cause: lower_comprehension_leaf's map branch passed the key and value operands without consume_moved_operand; only the Vec/set branch registered the move (D33/#912). 3. `[check(w)? for w in ws]` with `ws: &Vec[str]` — "MIR lowering failed for function 'all_checked'" ([mir-lower-fail] kind=64, the comprehension). Not the `?`: `[check(w) for w in ws]` fails the same way. Root cause: lower_comprehension_clause dispatched on the written type, and a `&Vec[T]` is a TY_REF, so it fell through to lower_comprehension_generic_iter, which cannot lower it. Fix: lower_comprehension_iteration frames one iteration's next-clause-or-push, and lower_comprehension_filter frames the filter condition (used by every clause kind); the filter's pass branch keeps its moves and resets on its own path, as the generic-iterator clause's does (#1501). move_into_comprehension_output is the one registration of a value moved into the output, used for Vec/set elements and now for map keys and values. The clause dispatch peels the reference (sequence_iter_type) and lower_comprehension_vec reads a `&Vec` through one deref, as lower_for_iter_ref does. Test: test/debug_alloc/da_comprehension_iteration_temps.w (f-string elements, a str-keyed HashMap, filter temporaries, and `?` and a plain element over `&Vec[str]` parameters; leak count=0 and exact output). Base stage1: FAIL (exit 1, the MIR lowering failure); the leak and double free above are from the base stage1 on the separate repros. Fixes #1736 * validate-all: a body whose MIR lowering failed is a failure, not a skipped body (#1736 tool gap) `with check --validate-all` printed `validate-all: ok` for #1736's `[check(w)? for w in ws]` (ws: &Vec[str]), whose MIR lowering failed; the build then refused it ("MIR lowering failed for function 'all_checked'"). CLAUDE.md: a tool that stayed silent is a bug. Root cause: validate_typed_mir_module and validate_ownership_mir_module both `continue` past a body with `lowering_failed != 0`, and validate_all_mir_module ran only those two after the shape check, so a failed body was never looked at. Codegen (gen_function_dispatch_at) fails on exactly that body. Fix: validate_all_mir_module refuses a module holding a body whose lowering failed, naming the body: "fn symN: MIR lowering failed; the body was not validated and codegen cannot compile it". Test: MirValidationTests.mir_test_lowering_failed_body (test/internals/mir_lowering_failed_body_test.w) plants a one-block body with and without `lowering_failed`. Against the base MirCore.w the first assertion fails (panic at src/MirValidationTests.w:891). Refs #1736 * MIR: a cast reads its source — `s as []u8` twice is not a double move (#1719) `let a = input as []u8; let b = input as []u8` failed `check --validate-all`: "move of _1, which a path reaching it already moved out (Moved) and nothing re-initialized: two owners free one value (§2.5.1)", while `run --debug-alloc` printed the right answer with leak count=0. Base MIR: `_6 = cast(move _1 as ty294); ... _8 = cast(move _1 as ty294); ... drop(_1)`. Root cause: MirLower.lower_cast took its operand from lower_expr, which spells a non-Copy local as OK_MOVE, and kept that operand for every cast. Only the std Box reinterpret (`self as *mut T`) consumes its source (consume_moved_operand); for every other cast nothing registered the move and no reset followed, so the move existed only in the MIR record. Sema records no move for a cast either (the second cast is not a use after move). The drop-state dataflow believed the record. Fix: lower_cast re-spells a non-Box cast's OK_MOVE operand as OK_COPY of the same place. Codegen reads OK_COPY and OK_MOVE operands of a cast alike (CodegenDispatch RK_CAST), so no generated code changes; the MIR now says what runs. Test: test/phase/validate_str_cast_reads_source.w (`--validate-all` over a local, a parameter and a field each cast twice). Base stage1: validate-all failed on the local (fn sym13380) and the parameter (fn sym13379). Fixes #1719 * MIR: a borrowed receiver is lowered as a read; validate-ownership judges call arguments for a second move (#1505) Two lowerings passed a receiver the callee borrows as an OK_MOVE call argument, so every consumer of MIR ownership believed the receiver left at the first call. Base stage1 `--dump-drop-plan`: `ch in s` (spec_ss09_9 shape): call <unknown>(move _2, const 64ty3) ... call <unknown>(move _2, const 33ty3) bb11.stmt14 place=_2 ... state_before=Moved action=skip "drop(_2) ... scope-exit _2" `g[i] += 100` over a user IndexPlace (behav_index_place_user): call sym13379(move _1, ...) // get(self: &Self) call sym13380(move _1, ...) // set(mut self: Self) bb14.stmt26 place=_2 ty=ty239 state_before=Moved action=skip while codegen borrowed the receiver each time (with_str_contains_char_ref; the `&Self` reference and the IndirectPlace in-place receiver) and ran the final drop — `run --debug-alloc` is clean. Because of it, #1414's "move of an already-moved place" rule judged statement moves only. Root cause: MirLower.lower_str_contains_char took its receiver from lower_receiver_with_method_autoderef, and the IndexPlace get (lower_expr's NK_INDEX user-IndexPlace arm) and set (lower_assign's user-IndexPlace arm) from lower_expr; for a non-Copy local with no deref to take, both return lower_expr's OK_MOVE. Fix: borrowed_receiver_operand re-spells such a receiver as OK_COPY of its place, and the three sites use it. The generator `next()` receiver the issue also names is gone: under D69 a pulled generator's next() lowers `call sym810(copy _1)` on the base already. With no borrowed receiver left spelled as a move, validate_ownership_body applies mir_move_of_moved_place to a call terminator's operands too. Tests: - MirValidationTests.mir_test_move_of_moved_place, shape 4 (moved on one arm, passed by move to a call at the join) is now MaybeMoved and rejected; against the base MirCore.w the assertion fails (panic at src/MirValidationTests.w:593). - test/phase/validate_borrowed_receivers_are_reads.w: `ch in s` twice and IndexPlace compound assignments pass `--validate-all` with the call rule on. Fixes #1505 * Compiler sources: a view of `self` is not held across a `mut fn` call that reaches its next use (§21.1; #1722 conformance) With #1722 a view's liveness reaches the blocks enclosing a write and a loop's next iteration. Checking src/main.w with that rule (stage1 of the #1722 change) refused bindings in 12 compiler files and one in the embedded std, each a `let` that names a place in `self` (or in a Vec the loop pushes to) and is read again after a `mut fn` call on the same place: let start = self.stmt_temp_starts[frame_idx] while i >= start: self.emit_drop_entry(...) // may grow self.stmt_temp_starts `start` views the element (D27: a binding names what's there), and the next iteration's condition reads it after a call that may have reallocated the buffer. The base compiler accepted every one of them only because it looked for the next use in the innermost block. - Copy elements (i32/i64 indices, counts, node ids): the binding takes an independent value, `let start: i32 = ...` (the fix-it the diagnostic names), 72 in the compiler; `Option[&i32]` lookups take `.copied()` (the resolved_call_sigs lookups x6, Sema.scope_set_state). - str views of the intern pool held across mutating calls in MirLower (try_resolve_module_const_type, mark_unsupported, the `iter` method probes, lower_method_call's method_name): an owned `.clone()`. - Parser.recover_to_statement reads `self.source` in place instead of a view held across `self.advance()`. - Lexer.lex_ident scanned a raw string with the `mut fn` lex_raw_string_prefixed while `src`/`text` viewed self.source; the scan is now the pure lex_raw_string_end(src, pos) and the lexer stores the end in `self.pos` (a field write, disjoint from `self.source`). - lib/std/cfg/stackify.w: `let blk: i32 = stack_block.get(top)` (the loop pushes to `stack_block`). Every change is valid under the old rule too; this commit comes before the rule so each commit self-compiles. * Sema: a view is live through the blocks enclosing a write and a loop's next iteration (#1722) On the base stage1 `check` accepts, and `run` prints `zzzz` for: let p = x.s var k = 0 while k < 2: if k == 1: x.s = "zz" ++ "zz" k += 1 print(p) and for `for i in 0..2: print(p); x.s = "zz" ++ "zz"` (the next iteration reads `p`): `p` reads the replacement string after the one it viewed was dropped (§21.1 Rules 1 and 4). The issue's single-statement `for` body is refused on the base; it worked only because a one-statement body is no block, so the "current block" was still the one holding `print(p)`. Root cause: check_mutation_against_views (and check_read_against_views) ask view_last_use for the view's next use, and view_last_use scanned only current_block_* — the innermost block being checked. With no use there, the borrow was removed (remove_borrow_at) and the write accepted. Fix: check_block keeps a stack of the blocks being checked (live_block_*: start, count, statement index — stmt_count at the tail — tail, scope depth), and every loop a stack of what runs again (live_loop_*: a `while` or `do`-`while` whole, a `loop` or `for` body, with the scope depth at the loop). later_use_of keeps the current block's scan as it was, then walks outward while control can fall out of it: stmt_exit_kind reads how each block is left (`return` reaches nothing more; `break` leaves the innermost loop without running it again; `continue` runs it again), each enclosing block is scanned from its next statement, and a loop that is fallen through or continued is used again anywhere in its re-run part. The walk stops at the block holding the view (the borrow's borrow_scope_depths). A function, closure, `async` or scope body starts its own stacks (push_label_boundary / pop_label_frame keep a floor), so a generic callee checked in the middle of its caller never scans the caller's blocks. The compiler's own sources held views of `self` across such writes; the previous commit conforms them. `with-stage1 check src/main.w` is clean with both. Tests (base stage1: both compile_errors tests are accepted, i.e. fail): - test/compile_errors/err_loop_write_under_view_used_after_loop.w - test/compile_errors/err_loop_write_under_view_used_next_iteration.w - test/behavior/behav_view_dead_across_loop_blocks.w (passes on base and after): a view dead before the loop, a write followed by `break`, and a view declared inside the loop body stay accepted. Fixes #1722 * MIR, codegen: a closure handed to a scope's spawn is moved into the task, and the worker runs that closure (#1539 finding) let v = f"x{k}" let a = scope s =>: let h = s.spawn(move () => v.len() as i32 + 7) h.join() printed 7 for k = 1 and k = 22 on the base stage1 (want 9 and 10): the thread saw `v` empty. #1539's rule (a drop of a Moved place) flagged the MIR of test/phase/validate_all_scope_cleanup_calls.w: _5 = const closure(node578340); call spawn(copy _3, move _5) -> [return: _6, next: bb2]; drop(_5) @ drop#6 scope-exit _5; // state_before=Moved Root cause, two halves: - MirLower.lower_method_call's generic-call path lowered a closure argument with lower_closure (an OK_MOVE of a registered statement temp, D63: "handed on by MOVE so the receiver owns it") but never registered the move, so the temp's statement-end drop ran after the move. - CodegenDispatch's `spawn` arm ignored that argument when the worker was written as a closure at the call: it re-registered the MIR locals by name and built the closure a second time from the AST (gen_closure). A `move ()` closure's second build captured `v` after the first build had moved it out, so the worker read the blank. Fix: lower_method_call registers the move (consume_moved_operand) of a closure argument of a machinery-dispatch call (the scope's `spawn`), so its temp is blanked, not dropped; the `spawn` arm always runs the worker from the MIR operand (mir_eval_operand), the closure MIR built and moved. The by-place closure of the existing tests is unchanged at runtime. Test: test/debug_alloc/da_scope_spawn_move_closure.w (a `move ()` closure and a by-place closure spawned in a scope; exact values and leak count=0). Base stage1: prints 7, 7 (the test fails). * validate-ownership: a drop of a place moved out and not yet reset is rejected (#1539) `--validate-ownership` accepted a `drop` of a place whose drop state is Moved (moved out, not yet reset). Drop flags are retired and codegen emits every drop statement (mir_elaborate_dead_drops has no caller), so that drop frees the value its new owner holds. #1412's generator next body did `_5 = move _10; drop(_10) @ drop#6 scope-exit _10; _10 = const zst(ty16)` — `run --debug-alloc`: DOUBLE FREE — and validate-ownership printed `ok`; `--dump-drop-plan` even labelled the drop `skip`. Root cause: validate_ownership_body judged a whole-place drop only for MaybeGarbage and Uninit (the #729 class); Moved and MaybeMoved (#1414's "moved on some path") passed. Fix: mir_whole_drop_verdict is the one judgement of a whole-place drop (the Drop statement and TK_DROP_AND_GOTO both call it): the #729 states as before, and Moved / MaybeMoved of a type with drop glue (sema_moved_drop_types: the place was moved, so its type is there when it has glue) as "drop of X after a path reaching it moved it out and before its reset (state): this frees the value its new owner holds (§2.5.1)". A path that moved the value and reset the place arrives as Reset, which joins with Init to Init, so a reset-on-move blank before the drop stays legal; a moved CStr view (`Some(move _5); drop(_5)` in cstr_option_from_ptr) has no glue and frees nothing. Sweep: `with-stage1 check src/main.w --validate-all` is ok. Before the glue check the rule also named three glue-free moves (a C-like enum parameter, the CStr view); and on test/phase/validate_all_scope_cleanup_calls.w it named a real defect — a closure moved into a scope's `spawn` and then dropped by the caller — fixed in the previous commit. Test: MirValidationTests.mir_test_moved_drop (test/internals/mir_moved_drop_test.w): moved then dropped (Moved, rejected); moved, reset, dropped (ok); moved on one arm without a reset, dropped at the join (MaybeMoved, rejected); moved and reset on one arm (ok); the first shape with no drop glue (ok). Against the base MirCore.w the first assertion fails (panic at src/MirValidationTests.w:968). Fixes #1539 * MirLower.lower_method_call: the static-constructor fallback runs only when the receiver type is unknown if recv_type == 0 or recv_type == self.sema.ty_void: // Fall back to call's return type for static constructors (Vec.new()) let ret_type = self.method_call_result_type(node) let ret_name_sym = self.sema.get_type_name(ret_type) if self.ast.kind(self_expr) == NodeKind.NK_IDENT: ... recv_type = ret_type The `let` was indented one level deeper than the lines after it. The parser takes the `if` body's indentation from its first line and accepts the dedent to a level no enclosing block has, so the body was the `let` alone and the four lines after it ran on every method call, reading `ret_type` when the arm had not run (uninitialized: its storage holds whatever the stack held). The next commit makes a one-statement body its own scope, and stage1 then reports `undefined variable` at the `get_type_name(ret_type)` line — the evidence that the fallback sat outside its `if`. (The same parser shape, standalone: `if c:` / a line at 12 spaces / a line at 8 spaces runs the second line with c false.) Fix: indent the `let` with the rest of the fallback, so the whole fallback is the arm. * Sema, MIR: a body that is no block is its own scope — a `let` in a one-statement `if`/`else`/`while` body drops there (#1559 finding) An indented body of one statement is parsed as that statement, not as a block, and neither Sema nor MIR opened a scope for it. So in if c: let _t = T { id } print(f"after arm {dropped}") `_t` joined the enclosing scope: Sema let the code after the `if` name it (uninitialized when the arm did not run), and MIR scheduled its drop at the enclosing scope's exit — after the `print`, and on the path that never ran the arm too, where the storage was never written. The base stage1 runs T's destructor over stale stack: test/behavior/ behav_let_in_one_statement_body_scoped.w prints `after arm 0`, `after loop -1`, `after else -235077277`, `total -235077270` instead of 5, 205, 212, 212. #1559's Maybe-drop rule found it in the compiler itself (ConanPatch.cp_patched_text: `if file.len() > 0 and ...: let _last = file.pop()`, whose `drop(_25)` at return reached the path that skipped the arm). Root cause: Sema.check_if_expr checked each arm, and the NK_WHILE and NK_DO_WHILE arms of check_expr the body, with check_expr on the bare statement (check_block, which opens a scope, never ran); MirLower.lower_if and the loop lowerings lowered it with lower_expr/lower_expr_discard in the enclosing drop scope. Fix: enter_body_scope / leave_body_scope, in Sema and in MirLower, open a scope around a body that is no block: Sema's `if`/`else` arms and `while`/`do`-`while` bodies (`loop` and `for` already open one), MIR's `if`/`else` arms and every loop body. A block body is unchanged (it opens its own). Test: test/behavior/behav_let_in_one_statement_body_scoped.w (a `Drop` T counted into a global, created in a one-statement `if` arm, `else` arm and `while` body): each drops at its body's end, once. Refs #1559 * validate-ownership: a drop that reaches a path where the place holds no value (Maybe) is rejected (#1559) A synthesized enum formatter (D61, #1480) registered its per-arm payload temps in one statement frame and dropped them at the join; on the arm that never wrote the temp the drop freed stack garbage (`with run test/behavior/derive_enum_debug_clone.w`: "invalid free addr=..."). `--validate-all` said ok, and `--dump-drop-plan` classified the drop as `state_before=Maybe action=conditional`. Root cause: the drop-state join of Init and Uninit is Maybe, and validate_ownership_body treated a Maybe drop as a guarded (reset-on-move) drop. It is not: Uninit is storage never written (a StorageLive without the zero flag — LLVM allocas are not zeroed), dead after StorageDead, or already dropped (a drop does not blank), and the null guard protects only the reset blank. #1111 rejected a drop that is Uninit on every path; the Uninit-on-one-path case passed. (#1414 already split MaybeMoved out of Maybe, so Maybe now means exactly this.) Fix: - mir_whole_drop_verdict rejects a whole-place drop in state Maybe of a type with drop glue: "drop of X reaches a path where it holds no value — written on one path, never written, dead or already dropped on another (Maybe); only a reset blank is safe to drop (§2.5.1)". A reset blank beside a value joins to Init, and zero-initialized storage is Init, so both stay legal. Glue is sema_dropped_types, a new snapshot of the drop-glue types of every dropped place (a place need not be moved for a drop of garbage to free it). - A sub-place drop no longer joins Uninit into the whole place (MirDropStateMap.mark_place): the drop-before-overwrite of a field (`drop(_4.selected_target); _4.selected_target = move _6`) leaves the whole value there, and the join made every such struct Maybe — 19 of the first sweep's 20 Maybe verdicts over src/main.w. What that join used to catch — a field dropped and not written again, then the whole dropped — is now its own rule (mir_drop_redropped_subplace: "drop of X frees X.f again: a path reaching it dropped that part and nothing wrote it since"). Sweep: `with-stage1 check src/main.w --validate-all` is ok. The rule's remaining finding in the compiler was a real defect — ConanPatch.cp_patched_text's `if ...: let _last = file.pop()`, whose binding dropped at function exit on the path that skipped the arm — fixed in the previous commit (a body that is no block is its own scope). Tests (each fails against the MirCore.w of the previous commit): - MirValidationTests.mir_test_maybe_uninit_drop (test/internals/mir_maybe_uninit_drop_test.w): storage written on one arm and dropped at the join (Maybe, rejected); the same with zero-initialized storage, and with no drop glue (ok). Panic at src/MirValidationTests.w:974 before. - MirValidationTests.mir_test_field_redrop (test/internals/mir_field_redrop_test.w): a field dropped and rewritten, then the whole dropped (ok — the old join said Maybe); a field dropped and not rewritten (rejected). Fixes #1559 * validate-ownership: a reset-on-move blank of a place no path moved (still Init) is rejected (#1487) `--validate-ownership` accepted a reset-on-move blank (`_N = const zst`) of a place whose drop state is Init: a value no path moved is overwritten without a drop, so it is lost (a leak) and every later read sees the blank. On #1383's branch the let-else in let keep = "keep".clone() let Ok(v) = vec_or_err(k) else: return consume(keep) - 100 keep.len() as i32 + v.len() as i32 blanked `keep` on the matching path (`--trace-ownership h:_2`: `bb5.stmt20 event=assign before=_2=Init after=_2=Init "_2 = const zst(ty16);"`), the program printed `-96 1` instead of `-96 5` and leaked keep's buffer, and validate-ownership printed `ok`. (The lowering was fixed in the #1383 PR; the base stage1 prints `-96 5`.) Root cause: validate_ownership_body judged a statement's moves and a drop's state, never a zero-fill's target; MirDropStateMap.transfer_stmt even keeps an Init place Init across the blank. Fix: before the transfer, an Assign whose rvalue is the zero fill (mir_rvalue_is_zero_fill) into a place that is Init and whose type has drop glue (sema_moved_drop_types: every type a body moves, which a reset target's type is) is "reset of X on a path where it was never moved: the value it holds is lost (§2.5.1)". Moved, MaybeMoved, Reset, Uninit, Maybe and MaybeGarbage stay legal. Test: MirValidationTests.mir_test_reset_of_init (test/internals/mir_reset_of_init_test.w): written then reset (rejected); written, moved, reset (ok); storage without a value reset (ok); the first shape with no drop glue (ok). Against the MirCore.w of the previous commit the first assertion fails (panic at src/MirValidationTests.w:979). Fixes #1487 * validate-ownership: a copy of a local the body drops, passed to a parameter that takes ownership, is rejected (#1742) On gen-push-pull (#1725), `g.pull()` resolved to the free generic `std.task.gen_pull(g: impl Gen[T])`, and MIR's lower_method_call GENERIC_CALL path lowered the receiver as a method receiver (lower_generic_receiver_arg: `OK_COPY` of the caller's place). The callee took ownership while the caller still dropped the temporary at scope exit: `--debug-alloc` DOUBLE FREE of the generator's Vec, and both `check --validate-all` ("validate-all: ok") and `analyze … audit:all` ("violations=0 ok") passed the MIR. The lowering is fixed (#1748: receiver_arg_call_nodes), so the program no longer produces that MIR; the validator gap remained. Root cause: no validator knew a callee's parameter modes. MIR carries a callee's parameter types only when its body is in the module, and never whether a plain `T` parameter is an in-place receiver (value_ref_abi) — that is Sema's fact. Fix (D65: Sema decides, MIR propagates): snapshot_sema_callables records, for each name's canonical signature (get_sig), its parameter types and which parameters take ownership (a plain `T`, not `&T`, not a raw pointer, not value_ref_abi) in MirModule.sema_sig_param_starts/data. validate_ownership_body rejects a call whose argument is an OK_COPY of a whole local, at a consuming parameter of a direct `const fn` or of a generic call's specialization, when a drop of that local is reachable from the call's continuation before anything writes it (mir_drop_reachable_before_write) and the callee returns (a signature returning Never — with_panic — has no continuation; sema_never_returning_syms): "copy of X into parameter N of fn symM, which takes ownership of it, while this body drops X too: two owners free one value (§2.5.1)". Machinery dispatch and generic templates are not judged (their callee name is no signature). Test: MirValidationTests.mir_test_copy_into_consuming_param (test/internals/mir_copy_into_consuming_param_test.w): a copy into a consuming parameter of a local the body drops (rejected); the same into a borrowing parameter, a move with its reset, a copy of a local the body does not drop, and a callee that returns Never (ok). The sweep over src/main.w first named std.regex's `with_panic(msg, ...)`, whose caller drops `msg` only on the path the panic never returns to; the Never and reachability conditions come from it. With the rule's call removed from validate_ownership_body the first assertion fails (panic at src/MirValidationTests.w:1033). Fixes #1742 * validate-all: a body's parameter locals are checked against its Sema signature (#1735) On gen-push-fixes (#1724) the generator constructor for `gen mut fn tick(times: i32)` allocated a temporary between its parameter locals (`_1: ty236 // self`, `_2: ty971 // a &Counter temp`, `_3: ty3 // times`, n_params = 2), so `times` was read from the `&Counter` slot and the loop ran zero times. `with check --validate-all` printed `validate-all: ok` and `with analyze … audit:all` reported `violations=0`. (The constructor is fixed in 06957a94 on that branch; the tool gap remained.) Root cause: the typed validator checks a generic call's missing borrow and an indirect call's arity, but no validator compared a body's parameter locals (local_type_ids[1..=n_params]) with the signature it implements: MirCore has no Sema to ask. Fix: validate_typed_mir_body calls mir_validate_body_params, which reads the signature snapshot the previous commit propagates from Sema (sema_sig_param_starts: each name's canonical signature). A body whose parameter count differs, or whose parameter local N is not the signature's parameter N (after aliases), fails: "parameter 1 is local _2 of ty=…, but the signature's parameter 1 is ty=…". A closure (anonymous body) or a body with no Sema signature by its name is not judged. Test: MirValidationTests.mir_test_body_params_match_signature (test/internals/mir_body_params_match_signature_test.w): locals as the signature says (ok); a temporary between the parameters — #1735's layout (rejected); one parameter local fewer (rejected). With the call removed from validate_typed_mir_body the second assertion fails (panic at src/MirValidationTests.w:1071). Fixes #1735 * std.string: cstr_option_from_ptr is an `unsafe fn` — its caller vouches for the pointer (#1473 finding) `pub fn cstr_option_from_ptr(p: *const i8) -> Option[CStr]` dereferences an arbitrary raw pointer (`unsafe { CStr.from_ptr(p) }`) from a safe function: any caller could pass a dangling pointer and read freed memory without writing `unsafe`. Sema's rule for that ("safe function relies on caller-guaranteed raw pointer validity for parameter 'p'; declare it unsafe fn or model a safe pointer contract", check_fn_body_with_sig_at) never fired only because of declaration order: CStr.from_ptr (line 200) is declared after it (line 143), so its body — which records EFF_RAW_PTR_VALIDITY on `ptr` — had not been checked when this call read its summary. With #1473 (a function returning a view, CStr, is checked before its callers) the summary is complete and the rule fires on every program that uses the prelude. The function is the compiler's conversion for a presented C string (MirLower.lower_call applies it to a facade call's result; the facade clause is what vouches for the pointer), so its contract is the library-maintainer tier's: `unsafe fn`, with the inner `unsafe { }` block dropped (the body is already unsafe). No user code calls it. * Sema: a function returning a view is checked before its callers — returned-view origins do not depend on declaration order (#1473) fn main: var v: Vec[i32] = Vec.new() v.push(1) let r = first(v) v.push(2) // may reallocate: `r` dangles print(f"{r}") fn first(xs: &Vec[i32]) -> &i32: &xs[0] `with check` printed `ok` on the base stage1 (and it ran); with `first` declared above `main` it is refused ("cannot mutate `v` while `r` is a live view into it"). The same holds for `-> Option[&i32]`. Declaration order must not change whether a program is accepted (§22; §21.1 Rule 6). Root cause: a call ties its result to its arguments through the callee's effect summary — record_call_view_origins reads EFF_ESCAPE_VIEW and sig_param_view_origin — which check_fn_body_with_sig_at writes when the callee's body is checked. check_bodies checks bodies in declaration order, except that #1196 checks an unannotated function before the first declaration that calls it; a function with a declared view return got no such treatment, so a caller above it read an empty summary. Fix: prepare_body_order puts a function whose declared return is a view (decl_returns_view: a TY_REF, or a type type_is_ephemeral_value calls ephemeral, such as Option[&T]) in the same call-driven order as the unannotated ones, so check_decl_body_in_order checks it before the first declaration that calls it by name. Generic functions (checked per specialization) and entry points are excluded as before. A call inside a recursion cycle still reads the summary as far as it is known; the order cannot break a cycle. Tests (base stage1: both accepted, i.e. fail): - test/compile_errors/err_view_returning_fn_declared_after_caller.w - test/compile_errors/err_option_view_fn_declared_after_caller.w Fixes #1473 * MIR: a string appended after an `if` grows in place — lower_if joins the arms' string facts, and a discarded assignment does not mark its place copied (#1491) The renderer shape var out = "[" for i in 0..count: if i > 0: out = out ++ ", " out = out ++ elem(i) lowered the append after the `if` to the copying concat on the base stage1: `_10 = str_concat_n([copy _2, copy _9])` (with_str_concat_n: a fresh exact-size buffer and a copy of all of `out`), so the loop was quadratic — lit(64000) runs 1.41 s built by the base stage1, 0.15 s after this change (the issue measured 9.47 s at n=64000, 117.6 s at n=256000). Two causes, both in MirLower: - lower_if ended with forget_string_flow_facts() at its join, marking every str place may-alias, so try_lower_string_self_concat_assign refused the in-place append (with_str_concat_n_move_first) for the rest of the loop body. With a two-statement arm, that alone made the append copy. - A one-statement arm is lowered with lower_expr_discard, which lowered an assignment through lower_expr's NK_ASSIGN arm; that arm yields the assignment's value as a copy of the place and marks it copied (mark_string_place_copied) — so even a correct join would see `out` aliased. A block statement is lowered with lower_assign instead. Fix: lower_if saves the facts at the condition (save_string_flow_facts), lowers each arm from them, and at the join restores the facts of the one arm that falls through, or joins both (join_string_flow_facts: a place may alias if it may on either arm, is owned only if owned on both); an entry made in one arm reads as it would with no entry (a local 0, a field may-alias). The else arm no longer starts from the then arm's facts — it did, which let it trust a then-arm "owned" that its own path never established. lower_expr_discard lowers an assignment as the statement it is (lower_assign), except a D60 tail read. The other forget sites (loops, `if let`, `match`) are unchanged: conservative, not wrong. This is aliasing-safety code (move_first frees the old buffer when it grows); the battery's drop audit covers it. Tests: - test/phase/mir_str_append_after_if_in_place.w: `--dump-mir` of the loop contains `_2 = str_concat_n([move _2, copy _9]);` (the post-`if` append); base stage1: the line is absent (the test fails). - test/behavior/behav_str_append_after_if.w: the loop's and an if/else join's output, and a 20000-element join's exact length. Fixes #1491 * Sema.copy_sig_alias: the parameter count is an independent value, not a view held across add_sig (§21.1; #1722 conformance) `let param_count = self.sig_param_counts[source_sig]` views the element, and `self.add_sig(...)` (a `mut fn`) runs before the `for pi in 0..param_count` that reads it again. The #1722 rule reports it once the next commit's Sema additions precede this function in check order (the site was accepted before and after only by check-order luck: the same shape in a fresh file is refused by the base compiler too). The Copy value is taken as the fix-it says. * D72: a `Drop` struct whose all-zero storage is a live value carries a hidden liveness byte (#1431) `Fd { n: 0 }` in a Vec, in an enum payload, or moved, was never closed: the reset sentinel is zeroed storage (§2.5.1), and the guarded drop (rt_value_is_zero over the value) could not tell a blanked value from a live one whose bytes are all zero. Base stage1 on the new fixture: `vec closed 1`, no `payload close 0`, `total 2` (want 2, the payload's close, and 4). Ruling (D72, spec §2.5.1): the compiler adds one hidden liveness byte to such a type; the reset clears it and the guard reads it. A type with an owning non-null field keeps the storage test and pays nothing; the programmer writes nothing either way. - Sema decides the fact (D65): struct_needs_liveness_byte(name_sym) is 1 for a struct with its own `impl Drop` whose every field's declared type has a live zero — an integer, float, bool, enum, or an array, tuple or non-Drop struct of those; a type parameter counts as one (the byte is added, never withheld, when the answer depends on the argument), so every instance of a generic struct agrees. A str, a container (Vec, HashMap, HashSet, SlotMap, Box, Rc, Arc, a channel endpoint), a raw pointer or reference, a callable, a slice, a trait object or another Drop value is non-zero whenever it holds a value, so a struct with such a field keeps the storage test: Box, Rc, Arc and a facade resource's `repr` gain nothing. Explicit layouts (packed, bitpacked, repr(C), aligned fields), unions, distinct types and facade resources (whose `live` field is this byte, D51) are never changed. The decision is cached per declaration (liveness_byte_cache), filled by the eager layout pass, read frozen by codegen. - TypeLayout places it: the byte follows the last field, inside the size rounding (Fd: 4 -> 8; Two { a, b }: 8 -> 12); alignment is unchanged. - Codegen appends an i8 to the LLVM struct body (source field indices unchanged, liveness_byte_indices records the slot), a struct aggregate and a constant struct literal store 1 into it, and the existing reset (a zero fill of the whole value) and guard (rt_value_is_zero / the 8- and 16-byte word tests over the LLVM size) see it with no change. The validator's Reset state is untouched: the blank is still the zero fill. ABI: the struct layout convention changed for this class of types, so WITH_ABI_VERSION is 6 (docs/with-abi.md §2 and the version history say what moved) and docs/with-abi.sha256 is re-recorded for src/FnAbi.w and src/TypeLayout.w. Tests: - test/debug_alloc/da_zero_value_drop_liveness_byte.w: `Fd { n: 0 }` passed by value, in a Vec, in an enum payload, and moved out — each closed exactly once (a counter and the destructor's own output), leak count=0. Base stage1: fails as above. - test/behavior/behav_liveness_byte_sizeof.w: size_of pins — Fd 8 (base 4), a two-field Drop struct 12 (base 8), the same struct without Drop 4, and Drop structs holding a str (16), a Vec (32) and a Box (8) unchanged. Fixes #1431 * D73: an assignment in any value position yields a view of its place after the store (#1479) var s = "".clone() let t = (s = compute("x")) // DOUBLE FREE on the base stage1 a = b = compute("x") // `a` empty: it received the blanked operand MirLower's NK_ASSIGN arm lowered the value of `lhs = rhs` as the rhs operand — "the value just stored" — which the place had already taken: a second owner for a non-Copy value. §9.1 defined an assignment's value only in statement position and at a body's tail (D60). Ruling (D73, spec §9.1): an assignment is an expression whose value is a read of `place` after the store, C's rule (C11 §6.5.16) under With's view semantics — a read of a place yields a view of it (§3.8, D22): a Copy demand copies, an owned demand on a non-Copy view is refused with the clone/move fix-it, and the stored value is never duplicated. D60's tail rule is this rule at the tail and stands unchanged. One mechanism, D60's, generalized (tail_read_assigns; no second one): - Sema.check_assign marks every assignment that is not the statement being checked (assign_in_statement_position: current_statement_expr_root through groupings) as a value-position read, mode 2; record_tail_reads still marks a body's tail assignment mode 1 and discard_body_tail still removes a discarded one. A non-Copy place's read is recorded as a view projection (view_projection_exprs, D22 §13.6), so an owned demand — `a = b = s`, `let t: str = (s = e)`, a `var` binding — is refused at the demand site ("cannot take ownership of a non-Copy value through a borrow (str is not Copy); borrow it, clone it, ..."); the demand check and check_let_binding see the assignment through a grouping. - `let t = (s = e)` binds the view: the binding is view-bound, its origin is `s` (assign_view_targets; collect_expr_view_deps), so a write to `s` while `t` is live is refused (§21.1 Rule 1) and reads of `s` are not. place_root_sym and borrow_root_place see through such an assignment to its target. - An `if`/`match` whose arms assign the same non-Copy place joins as a view of it, as a join of field views does (join_field_view_candidate admits an assignment arm; MirLower's lower_join_field_view lowers it through lower_expr_place, the store then the place). The tail join of an unannotated body keeps joining as values (join_assign_arms_as_views is off there): D43/D60's `if p: name = a else: name = b` still returns a read of the global, which D52 refuses. - MirLower.lower_assign's read_back is the mode: 1 reads the place as before (a whole local moves out — the tail), 2 yields the place itself as a view operand (read_assigned_place: OK_COPY of the place, no temp, nothing moved); lower_binding_alias_place binds `let t = (s = e)` to `s`'s place after the store; lower_expr_discard lowers a mode-2 assignment as the statement it is in that position. Tests: - test/debug_alloc/da_d73_assignment_value_positions.w: `a = b = 3` prints `3 3`; `while (n = next()) != 0:` loops; `let t = (s = e)` binds a view (`t` and `s` both read `x!`, `s` stays the owner and is reassigned after `t`'s last use); `q = p.n = 7`; leak count=0. Base stage1: DOUBLE FREE. - test/debug_alloc/da_d73_assignment_arm_join.w: the issue's second repro, `let t = if p: s = e1 else: s = e2`, binds a view of `s` on both arms; leak count=0. Base stage1: DOUBLE FREE. - test/compile_errors/err_d73_nested_assign_owned_str.w (the issue's `a = b = compute("x")`), err_d73_typed_let_assign_owned_str.w, err_d73_view_binding_then_write.w, err_d73_assignment_arm_join_then_write.w: each accepted on the base. - The six err_d60_* and nine behav_d60_* tests pass unchanged. Fixes #1479 * Conform the stack's save/restore bindings to the nested-block view-liveness rule (#1722) With the batch-2 stack folded (rulings-lang, rulings-facade, emitc, sema, ownership), `with-stage1 check src/main.w` from the stack top reported 187 "cannot mutate `self` while `X` is a live view into it": 24 distinct bindings, each a `let` that names a Copy element in `self` (a saved field for a save/restore pair — saved_ret, saved_file_id, saved_infer_tail, saved_block_index —, a count, a symbol, an LLVM type handle) and is read again after a `mut fn` call on `self`. Every one is the shape the #1722 rule refuses, and every one is the fix-it the diagnostic names: the binding takes an independent Copy value (`let saved_ret: i32 = ...`). Applied mechanically from the check log (the annotation script of the first conformance commit), in two rounds (the second round's two sites were hidden behind the first's errors). Per file: SemaCheck.w 11, SemaDecl.w 3, Codegen.w 3, MirLower.w 2, CodegenDispatch.w 1, CodegenTraits.w 1, ComptimeTransform.w 1, SemaFacade.w 1, compiler/Frontend.w 1. Gate: fresh `:dev` rc=0; `with-stage1 check src/main.w` ok; `check src/main.w --validate-all` ok. * Sema: a facade-declared view summary survives the rendered body's check (#1473 finding) facade_declare_view_of_param puts `returns borrow … from param N` and a constructor's dependency facts on the rendered method's signature as EFF_ESCAPE_VIEW with a parameter origin. check_fn_body_with_sig_at then wrote the body's own inferred summary over it: the rendered body reads a raw pointer and derives no origin, so the summary became "no view". It never mattered while the caller happened to be checked first; #1473 checks every view-returning function before its callers, so every facade text, record and dependency view lost its origin and ten facade tests compiled (err_c_facade_view_invalidated_by_lend and the others: `bind t deps=0` under WITH_DEBUG_BORROWS, deps=1 on the base). The facade's fact is the owner (D65): facade_declare_view_of_param registers the signature, and the body check merges its findings into a declared summary instead of replacing it. The three declaration sites (dependency facts, record views, text views) share the one helper. * MIR: a carrier eliminator reads the mapper it calls — `map`'s Ok arm had moved the closure out while the scope-exit drop ran on every path (#1539 validator finding) The inlined `Option.map`/`Result.map` (and `and_then`, `inspect`) lowering handed the mapper temp's `move` operand to the call as its callee; a call reads its callee (`f(1); f(2)` is `call copy _f` twice), so on the Some/Ok arm the closure was moved out with no reset while `drop(_mapper)` still ran at scope exit — MaybeMoved to validate-ownership, which #1539's check now rejects (deep-debug-tool-tests/analyze-audit-carriers went red on the batch-2 stack). The mapper is read like any callee and its temp is dropped once, on both arms; a capturing mapper over a Drop value drops it once under the debug allocator. --------- 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.
Eric's blessed ruling (2026-09-23): recursive Debug, quoted/escaped strings (printable non-ASCII as itself), explicit
impl Debughonored at every depth (§11.9's contradiction removed), rows for enum/Option/Result/collections, HashMap entries ordered by their keys' Debug text, BTreeMap in key order;:?needs no derive. D61 records why. Docs-only::spec-inventory-checkgreen.