Repository navigation
Globals: a call, dyn dispatch, stored callable or drop that writes a global refuses a live view of it (#1819 #1827); Box[dyn] drop slot (#1847 #1854); distinct .value (#1846); one-let block scope (#1851) - #1868
Merged
Conversation
ehartford
force-pushed
the
fix-globals
branch
from
September 29, 2026 05:01
27c6686 to
1dc9640
Compare
added 23 commits
September 29, 2026 13:37
…s that local — the race proof counted its accesses as the global's
§9.1c's race proof records every access to a global, and
record_global_data_race_access decided "is a global" from the name alone
(global_value_decl_kind). A function's local may take the name of another
module's private global (shadow_unseen_global, §18.1), and then each read
and write of that local was recorded as an access to the global: in a
concurrent program the local's own lines failed with E0921, and its write
marked the global mutated, so the other module's race-free reads of the
never-mutated global failed too.
var counter = 5 // shadows race_shadowed_global's private counter
counter += 1 // E0921: mutation of global `counter` may race
The fact now asks the scope which binding the name holds: a local binding
is no global access (binding_index_is_global, as
resolve_displaced_global_ident decides). #1819's write-by-call rule reads
the same fact.
Test: test/behavior/behav_global_race_local_shadows_unseen_global.w
(before: four E0921 errors at the local's lines and the global's read;
after: runs, prints 14).
…not views of the globals it writes
CiGotoCfgContext.fail(msg: &str, loc: &str) records its message in
g_ci_bail_message / g_ci_bail_location, and one caller passed it those
very globals:
self.fail(g_ci_bail_message, g_ci_bail_location)
Each argument is a view of a global the callee reassigns while the view
is live (§9.1c: globals are places; §21.1 rule 1). It read the right
bytes only because `fail` clones `msg` before it overwrites the global.
The caller hands it independent copies (ci_get_bail_message /
ci_get_bail_location). Found by #1819's rule: "call to
`CiGotoCfgContext.fail` mutates global `g_ci_bail_message` while its
argument is a live view into it" (src/CImport.w:15539).
… global may not be live across it (§9.1c: globals are places; §21.1 rule 1) A view of a global's storage stayed live across a call whose callee wrote the global: `let r = G[0]; grow(); print(r)` and `show(G[0])` with `show` calling `grow` compiled, and `r` read the element header out of the buffer `grow` reallocated (debug allocator, WITH_ALLOC_NO_REUSE + scribble: `r` printed the freed block's bytes). The same program over a local is refused. Fixes #1819. Root cause: §21.1's rule 1 check (check_mutation_against_views) runs at a direct write only — the sites that also record the race proof's write fact (record_global_place_write). A call site had no write of a global to check: the write fact (record_global_data_race_access) kept the global and the node, never the body it was in, and a signature's effect summary covers its parameters alone. WITH_DEBUG_BORROWS=1 on the callee cell shows the view row still live after the call — `[borrow] read of r ...: entry0 place=G kind=0 ref=r` at `print(r)` — with no check between. The rule, owned by Sema: each write of a global is kept with the body it is in (the function's signature, or the closure being checked), and each resolved call with the bodies it runs — its callee, and every callable it hands the callee (a closure, a named function, or a callable parameter of the caller, bound to whatever its own callers pass). At each call Sema keeps the views of globals live across it, with the liveness a direct write is judged by (borrow_liveness_at, factored out of check_mutation_against_views): named views used after the call or inside it, and arguments or receivers that view a global for the whole call. Once every body is checked (forward references, recursion, mutual recursion), a backward walk from the writes finds every body that writes each global, and a kept view across a call that runs one is refused, naming the call, the path to the write, and the view: error: call to `m2` mutates global `G` while `r` is a live view into it = label `r` views a value stored in `G` = label this call mutates `G`: `m2`, which calls `m1`, which writes it = label `G` is written here = label view is used here after the call Calls covered: free, method, static, qualified extension, generic (the specialization), trait static dispatch, pipeline stages, operators (their method), a `for` over an Iter[T] (`next`) or a Gen (`each`), a closure binding, a callable parameter. The write fact is now recorded for std and runtime bodies too (the race proof still exempts them). Matrix (global kind x view origin x mutation route; before -> after): kinds str, Vec[str], struct{name: str}, HashMap[str, str]; origins &str argument, whole-global argument, `let r = &G`, element view, field view, `for` binding; routes direct, callee, callee's callee, method of another type, `mut fn` on the global, closure run in between, generic callee. 102 cells. Before: 11 refused (every direct write, and `mut fn` on the global), 91 accepted; under the debug allocator the Vec/HashMap element, `for` and argument cells read freed, scribbled storage (printed "" for "first!"/"v!"), the str/struct cells read the global's current header ("wxyz", safe by accident; a use-after-free once #1810 makes `&str` a {ptr, len} view). After: all 102 refused. Extra cells, all accepted before and refused after: a callee's callable parameter run under a view (closure, bound closure calling a writer, forwarded parameter, named function passed), a named function handed to a callee, recursion, mutual recursion, a callee declared after its caller, an operator, a `for` over an Iter[T], a pipeline stage. `for r in G` over a str is n/a: Sema accepts it and MIR lowering refuses it (separate issue). Still accepted, and filed: a call through a callable stored in a field, dyn trait dispatch, an implicit Drop, and a bundle interface function (no body in the compilation; D39 gives callers the declaration alone). Compiler code that relied on the hole: src/CImport.w (previous commit). Tests: test/compile_errors/err_1819_*.w (112 cells; 100 failed on the parent compiler; the 12 that passed there pin the direct writes and a closure literal writing in place), and test/behavior/behav_1819_global_views_across_calls_ok.w (a view dead before the call, a call writing another global, a callee only reading, a recursive callee writing nothing, an argument view of a global the callee never writes, callable parameters run under a view with closures that write another global or write after the view's last use).
…rts — its body is not in this compilation (D39, §9.1c, §21.1 rule 1) #1819 made a call a write of every global its callee's body writes. A bundle function (a `.wi` declaration, D39) has no body in the program: its call counted as writing nothing, so a view of a global the bundle exports stayed live across a call that may rewrite it: use std.c_algorithms.defs let r = &allocation_limit // a `var` the c_algorithms bundle exports let u = to_upper(97) // accepted: no body, no writes print(f"{u} {r}") The bundle's declaration is all a caller has, and it states nothing about globals. D51's test decides the inference: assuming the call writes can only refuse a valid program; assuming it does not can leave a view dangling. So a bundle function counts as writing every global its bundle's interface exports that can be written at all — a `var`, or a `let` whose value can change in place (not a scalar, `str` or pointer, D12). A declared clause waits for a bundle that needs a narrower contract. The registry (compiler.BundleInterfaces) now records which `.wi` each section came from (bundle_interface_bundle_id); Sema keeps each interface declaration it applies (apply_interface_declared_effects) and, once every body is checked, gives it a write record for each exported global some kept view check is about (record_interface_fn_global_writes). The diagnostic points at the declaration: "a bundle function, declared here with no body in this program: it counts as writing every global its bundle exports". Test: test/compile_errors/err_1827_bundle_fn_writes_bundle_globals.w (accepted by the parent compiler).
…o it writes every global any of them writes (§9.1c, §21.1 rule 1) A call through a vtable had no body behind it for #1819's rule, so it wrote no global, and a view stayed live across an impl that reallocates the global: fn run(g: dyn Grow): let r = G[0] g.grow() // W.grow pushes onto G: `r` reads freed storage print(r) (debug allocator, WITH_ALLOC_NO_REUSE + scribble: `r` printed the scribbled bytes.) Which impl runs is decided when the program runs; within one compilation the impls of the method are all known. The call now runs a dispatcher body (global_dispatcher: bodies the running program chooses among), expanded once every body is checked into one call per impl (expand_global_dispatchers): each impl's method and its specializations, or, for an impl that keeps the trait's default, that default checked as the impl's method. A callable handed to the dyn call binds to the matching parameter of every impl. A default method's body is now the impl's signature's body for writes and calls (current_effect_body, generalizing the closure override): it was checked with no function body current, so its writes were kept for nobody. The diagnostic names the dyn method and the impl: "call to `dyn Grow.grow` mutates global `G` while `r` is a live view into it ... `dyn Grow.grow`, which may be `W.grow`, which writes it". Tests: test/compile_errors/err_1827_dyn_call_writes_global.w and err_1827_dyn_default_method_writes_global.w (both accepted by the parent compiler).
… type in this compilation, so it writes every global one of them writes (§9.1c, §21.1 rule 1) #1819 bound a call through a callable to a body only for a closure binding, a callable parameter, or a closure or function handed to the call. A call through any other callable value — a field (`h.f()`), an element (`fs[0]()`), a call's result, a local that is not a closure binding — ran no known body, wrote no global, and a view stayed live across a callable that reallocates the global (debug allocator, WITH_ALLOC_NO_REUSE + scribble: the view printed scribbled bytes). What reached the field is decided by value flow Sema does not track: the stored value's view origins say what it borrows, not which function it is. The callable's type is the tightest fact Sema has about what is stored, so such a call runs a dispatcher (global_dispatcher, kind CALLABLE) that runs every callable value this compilation makes whose type the call's accepts (fn_types_compatible): each closure (-2 - its node, noted by check_closure) and each function named as a value (its signature, noted where the name resolves, check_ident). A callable value of that kind handed to a callee binds to the callee's callable parameter too (`apply(h.f.clone())`), and a callable handed to the stored callable binds to the parameters of every function it may be. Diagnostic: "call to `h.f` mutates global `G` while `r` is a live view into it ... a callable of type `fn() -> Unit`, which may be `grow`, which writes it". Tests: test/compile_errors/err_1827_field_callable_writes_global.w, err_1827_element_callable_writes_global.w, err_1827_stored_callable_passed_writes_global.w (all accepted by the parent compiler).
…e, at the drop points §2.4 fixes (§21.1 rules 1 and 7)
A Drop impl that writes a global ran with no check: a view of the global
stayed live across the end of an inner scope, a reassignment, a
statement's temporary, a `return` — and across a call whose callee
dropped a value it owned:
let r = G[0]
{
let t = Tok { n: 1 } // Tok.drop pushes onto G
} // t drops: G reallocates
print(r) // reads freed storage
(debug allocator, WITH_ALLOC_NO_REUSE + scribble: `r` printed the
scribbled bytes; the same for a temporary, a reassignment, a field's and
a Vec element's drop, and a generic Drop impl.)
Owner split (D65): Sema. The drop points §21.1 is judged against are the
language's: §2.4 fixes them — the end of a binding's scope in reverse
declaration order, a reassignment (the old value, before the store), the
end of the enclosing statement for a temporary — and §21.1 rule 7 makes
each a use. Sema already owns rule 7 at the scope's end (pop_scope,
check_live_views_for_origin) and #962's statement temporaries. MIR owns
where on each path a drop runs (§2.4 conditional drop): it elides a drop
at one of these points on a path that moved the value and adds none
elsewhere, so the lexical points bound it. The alternative — MIR's
ownership validator reporting a view live across a drop — would decide
acceptance downstream of Sema (D65: Sema decides acceptance), and the
call rule needs the drop anyway: a callee whose only write is its own
local's or parameter's drop must count at every call of it, which is
Sema's body summary. So an implicit drop is kept as a call of a drop
dispatcher (global_dispatcher, kind DROP): once every body is checked it
runs the Drop impls of the type's drop glue — the type's own, and each
field's, element's and payload's (the walk type_carries_user_drop
makes), and for a `dyn Trait` value every implementor's (#1847: a
`Box[dyn Trait]` does not run it yet); a generic type's impl is
specialized for it then
(ensure_generic_drop_specialization, factored out of
register_generic_drop_specializations, which MIR lowering still calls).
A binding moved on every path is not dropped at its scope's end, but
Sema's move state joins paths (§21.1 rule 9), so every binding counts:
it can only refuse a program in which a view of a global is live across
a moved value's scope end and that value's Drop impl writes the global.
The sites (note_drop_global_effects): a block's end (its bindings, with
its tail's value outliving them), a function's or closure's end (its
parameters, its value's temporaries, the returned value outliving them),
a `return` (every binding of the body), a reassignment
(check_assign), a statement's end (its temporaries —
collect_drop_temporaries: a value no binding, assignment, return,
aggregate, by-value argument or container store takes). A view used
only inside the block or statement is dead at its end (at_end).
Diagnostics name the drop: "the drop of `t` at the end of its scope
mutates global `G` while `r` is a live view into it ... the drop of
`Tok`, which runs `Tok.drop`, which writes it"; also "the drop of `t`'s
old value at this assignment", "the drop of this temporary at the end of
its statement", "the drop of `t` at this `return`".
Tests: test/compile_errors/err_1827_*_drop.w (15 matrix cells: every
kind and view origin) and err_1827_drop_{dyn_box,generic,nested,param,
reassign,return,tail,temp,vec}.w, all accepted by the parent compiler;
and
test/behavior/behav_1827_global_views_across_drops_and_dispatch_ok.w,
what stays accepted for all four routes: a drop, a dyn call and a stored
callable that write another global, a view dead before the drop that
writes its global, a callable of another type than the global's writer,
a temporary, a reassignment and a generic Drop impl writing another
global.
Fixes #1827
…: the vtable carries the concrete type's drop glue; a dyn call borrows its receiver unless the method consumes it (§2.4, §11.3)
Route: drop/leak bug, debug allocator first. `run --debug-alloc` with
WITH_ALLOC_NO_REUSE=1 on base (23be6bf9, the with-362 stage):
`{ let b: Box[dyn Named] = Box.new(Tok { n: 1 }); print(b.name()) }`
never printed `drop 1` and reported `LEAK size=16 origin=with_alloc`,
`leak count=1`; eight shapes (Drop struct, str-holding struct, Copy
struct, moved out, reassigned, returned, consumed through the vtable)
leaked 7 blocks, and a Box[Concrete] pushed onto a Vec[Box[dyn T]] or
stored in a Box[dyn T] field aborted codegen: "BUG: function-value adapter
has no FnAbi descriptor [Codegen.gen_fn_to_fat_ptr_thunk]".
Three owners were wrong, one fact each:
1. MirLower.w:12920 (the dyn call): `lower_expr(self_expr)` then
`consume_moved_operand` moved every receiver. `--dump-mir`:
`call sym165(move _1)` for `b.name()` and no `drop(_1)` at all, so the
box was never dropped. Only a `move self` method consumes; that is now
Sema's fact (SemaCheck check_dyn_trait_method_call ->
Sema.dyn_consuming_calls), and MirLower passes any other receiver as
the place (`call sym165(copy _1)`, `drop(_1) @ scope-exit _1`).
2. CodegenDispatch.w:5450 (mir_emit_box_drop_place): a dyn box's payload
has no LLVM type, so `payload_ty` stayed 0 and the value was never
dropped, only its cell freed. The type is known only to the vtable,
which had no slot for it (CodegenTraits.w:70). Every vtable now ends in
a drop slot (dyn_drop_slot: an internal `__dyn_drop_<type>` that runs
the concrete type's drop glue in place; null for a type with no drop).
Method offsets are unchanged. The box's drop runs the slot, then frees
(mir_emit_dyn_payload_drop); a dyn box inside a field, element or
payload drops the same way (mir_emit_boxed_dyn_drop_ptr). The
trait-table audit counts the extra slot.
3. CodegenDispatch.w:3809 (struct aggregate field) and :8509 (Vec.push):
the element was coerced to the `{ptr, ptr}` field type by LLVM shape
alone, and a bare box pointer read as a function value reached
gen_fn_to_fat_ptr_thunk (#1818's class). Where Sema's field or element
type names a dyn trait, the concrete value takes the fat pointer
(mir_coerce_operand_to_dyn_trait_target), as a `let` of that type does.
After: all eight shapes plus a Vec and a struct field print each `drop N`
once, at the owner's drop point, with `debug-alloc: leak count=0`, also
under WITH_DEBUG_ALLOC_SCRIBBLE=1. A closure-typed field and a consuming
`move self` call through the box behave as on base.
The drop audit was blind to trait objects (no cell held a `dyn`), so it
stayed green over all of this. tools/drop_audit.w gains the `boxdyn` and
`boxdynfield` shapes across every scope/branch/loop/move/reassign/
return/discard/consume/closure scenario, plus consume_call,
dyn_call_borrow, dyn_call_consume and vec_elem_drop/vecdyn cells.
Tests (each failed on base: codegen abort):
test/behavior/behav_1847_box_dyn_drop_once.w (drop order and count),
test/debug_alloc/da_box_dyn_payload_dropped.w (leak count=0).
Filed while here: #1851 (a block whose only statement is a `let` drops
at function end, §2.4) and #1852 (a by-value `dyn Trait` parameter never
drops its value; the spec does not define one).
Fixes #1847
… at the same address with the underlying type; codegen indexed the underlying type as if it were the wrapper (§4.5, D32)
§4.5 (D75): a distinct type is a zero-cost wrapper with its underlying
type's destructor, and casts into or out of it move or borrow. The §9.5
example (functions.md) spells the wrapped value `self.value`. Sema models a distinct type as
the one-field struct `{ value: T }` and types `n.value` as a field place of
type T: a read views it, `let k = n.value` binds a view (moving `n` while
`k` is live is "view 'k' may outlive its origin 'n'"), and `let s: str =
n.value` is refused ("a field never moves out implicitly", D32). MIR
follows Sema: `_6 = ref(shared, _1.value)`. `check --validate-all: ok`.
Codegen represents a distinct type as its underlying type
(mir_sema_type_to_llvm), but both LLVM place walkers then projected the
field as a struct index into that underlying type:
mir_place_ptr (base CodegenDispatch.w:1417 mir_resolve_field_index, then
:1456 wl_build_struct_gep) and mir_place_projected_type (:1224). For
`Name = distinct str` that GEPs `%str` field 0, the data pointer, and loads
it as a whole `%str`. In `objdump -dr` of `print(n.value)` on base,
str.clone's result (x0, x1) is never stored, and with_println_str receives
whatever x0 holds after the preceding call. So `print(n.value)` printed "",
`let k = n.value; print(k)` exited 139, and `self.value` in an
`extend Name` method aborted codegen ("wrong argument type actual=i32
expected=ptr fn=Name.show"). After the fix: `stp x0, x1, [sp, #0x10]`,
and println gets `add x0, sp, #0x10`.
Both walkers now take a distinct type's field as the identity projection:
the same pointer, typed as the underlying type
(mir_distinct_underlying_sema_type, the rule mir_sema_type_to_llvm
applies, seen through references for `r.value` with `r: &Name` and
`self.value`). The three Sema-type walkers already project to the
underlying type. `analyze audit:all`: violations=0.
Covered, and each prints right on the fixed stage1: read, view binding,
method call through `.value`, `r.value` through `&Name`, `self.value` in
`extend` methods, a distinct Vec (len, index, through a reference), a
distinct struct's fields, a distinct i32, and assignment through `m.value`
(the old value drops at the assignment). The whole distinct value still
leaks at scope exit on this layer: that is #1802's missing drop glue,
fixed by b837b71f on impl-d75.
Test (failed on base: codegen abort; the issue's two-line repro exits
139): test/behavior/behav_1846_distinct_value_place.w.
Fixes #1846
…r and a Box[dyn T] as itself; a &dyn T parameter takes a &dyn T (§3.9, §11.3) Found by the cells #1847 added to tools/drop_audit.w: consume_call/boxdyn and consume_cond_{taken,untaken}/boxdyn were COMPILE-FAIL on the base and on #1847's stage alike. On main (355c20b), `fn eat(x: Box[dyn Held])` accepted no argument: `eat(Box.new(r))` and `eat(a)` with `a: Box[dyn Held]` (let or var, bare or `move`, conditional or not) were "type 'Box' does not implement trait 'Held' required for dyn parameter", and `fn relay(x: &dyn Held): peek(x)` was "argument cannot be converted to dyn trait object". Two owners: 1. SemaCheck.w:21089 (check_dyn_trait_call_compat, base line) asked whether the argument's type implements the trait. For a `Box[C]` that type is `Box`; an argument that already is the trait object has no concrete type. An argument that is the parameter's own trait object (`Box[dyn T]` for `Box[dyn T]`, `&dyn T` for `&dyn T`) now passes as itself, and for a `Box[dyn T]` parameter the implementor checked is the boxed type. `&b` with `b: Box[dyn T]` for a `&dyn T` parameter is still refused, as on main. Wrong trait, non-implementor and `&R`-for-Box stay refused by the argument type check; the non-implementor's second diagnostic now names `Q`, not `Box`. 2. Codegen then refused the Box[C] argument ("cannot lower argument 1 to dyn trait 'Held'", base CodegenDispatch.w:15881, and the win64 spill twin :14387). Those were two copies of one derivation, and neither knew a box. They are now one (mir_dyn_arg_fat_from_value), and it builds a Box[C] with C's vtable through mir_box_to_dyn_value, the construction a `let x: Box[dyn T] = Box.new(c)` already used (factored out of mir_coerce_operand_to_dyn_trait_target). After: all 8 spellings and the concrete box print and drop once, with `debug-alloc: leak count=0`; the six consume cells PASS (FIXED vs the base); `check --validate-all: ok`; `analyze audit:all`: violations=0. Every test naming `dyn` (42 files) passes on stage1. Test (failed on base: four Sema errors): test/behavior/behav_box_dyn_param_accepts_objects.w. Fixes #1854
…; the lone statement was returned in place of the block (§2.4)
Route: drop-point bug. `run --debug-alloc` of
`{ let t = Tok { n: 1 } }; print("end")` printed `end` and then `drop 1`.
`--dump-drop-plan` placed `drop(_1) @ drop#7 scope-exit _1` in main's
return block, after the print. WITH_TRACE_SCOPES showed main's body block
and no block for the braces at all; a two-statement block opens its scope
(`push depth=2`).
Root cause: Parser.w:7927 (parse_brace_expr), `if stmts.len() == 0:
return last_expr`. A brace block of one element was returned as that
element, and for a `let` that element is a binding. It landed in the
enclosing block: Sema kept `t` visible after the `}` (this compiled and
printed `1`), and MIR scheduled its drop at the enclosing scope's end. A
lone `defer:` ran at the function's end too. 87b5553 made one-statement
`if`/`else`/`while` bodies their own scope at the consumers. A statement
brace block's consumer is the enclosing block, which cannot tell, so the
block has to survive parsing. Every other body form (closure, `if`
braced, match arm braced or indented, labeled block) already scopes its
one `let`, before and after.
A brace block whose one element binds a name or schedules scope-exit
work (NK_LET_BINDING for let/var/const, NK_LET_ELSE for pattern lets,
NK_DEFER, NK_ERRDEFER) is now an NK_BLOCK with that element as its tail,
the shape a two-statement block already lowers correctly (a `let`,
pattern `let` or `defer` tail was checked here). A block of one
expression is still that expression's value (`let seven = { 3 + 4 }`).
The drop audit counts drops, not when they run, so it could not see this.
tools/drop_audit.w gains block_scope_exit/<shape> for all ten shapes: a
marker scales the slot right after the block, so a drop at the `}` sums
to 10 and a late one to 1. On base every cell was
VALUE-FAIL(got=1 want=10); now all PASS.
Tests (each failed on base):
- test/behavior/behav_1851_brace_block_one_statement_scope.w: let, var,
pattern let, let-else, defer, inline braces and an expression block, as
one trace line (expect-stdout is substring-matched, #1855).
- test/compile_errors/err_1851_brace_block_binding_escapes.w: the name is
gone after the `}`.
`check --validate-all: ok`, `analyze audit:all`: violations=0; the parser
tests, behav_brace_blocks and behav_let_in_one_statement_body_scoped pass.
Fixes #1851
…one trace line, as expect-stdout matches substrings (#1855) behav_1847_box_dyn_drop_once and behav_box_dyn_param_accepts_objects listed `drop N` lines one per `//! expect-stdout:`. The runner checks each of those as a substring of the whole output (#1855), so the tests pinned neither the order they claimed nor exactly-once: `drop 1` was satisfied by `drop 10`, and a second drop would still pass. Each now records every event into one trace and asserts the whole line. The expected traces are the §2.4 order (reverse declaration order at scope exit), and both runs under the debug allocator report `leak count=0`. The #1854 scenario runs in its own function, so main's locals are dropped before the trace prints. Refs #1847 #1854 #1855
…-value `dyn T` (#1852) The spec defines `&dyn Trait` and `Box[dyn Trait]` (§3.9, §11.3) and says `dyn Trait` is unsized (§11.3); a by-value `dyn T` parameter is not a With type. The next commit refuses it. Nothing in src/, lib/, rt/, tools/ or examples/ used the form. These tests did, and each parameter only calls `&self` methods, so `&dyn T` says what they meant: - the 19 #1827 fixtures and behav_1827_global_views_across_drops_and_ dispatch_ok (`g: dyn Grow` -> `g: &dyn Grow`). The call sites pass a value, which auto-references (§3.8), so each still reports or accepts exactly what it did. - test/behavior/lib/fn_abi_callable_fixture.w: `read_first` and the `fn(dyn ReadFirst) -> i64` callback take `&dyn ReadFirst`. That is the same fat-pointer ABI, which is what behav_fn_abi_callable checks. Each of the 20 tests passes on stage1 before and after. The two sealed- trait tests (sealed_trait_match, err_sealed_not_exhaustive) also match on a by-value `dyn Shape`; their downcast pattern needs a `&dyn` subject first, so they move in their own commit. Refs #1852
…ase kept the lines aef8ade3 replaced with current_effect_body
…re written, with `&dyn T` and `Box[dyn T]` as the fix-its (§11.3, §3.9) The spec defines a trait object borrowed (`&dyn T`, §3.9) and owned (`Box[dyn T]`, §11.3) and says `dyn Trait` is unsized (§11.3). A by-value `dyn T` parameter is defined nowhere, yet it compiled: `fn describe(s: dyn Named)` took a `Tok` and neither side ran its Drop (#1852; a str-holding implementor would have leaked). No Silent Fallbacks: the compiler refuses it loudly at the parameter rather than inventing a meaning (Eric, 2026-09-28; owned by-value matching waits on #724). refuse_dyn_by_value_params walks a declared type and reports every bare `dyn T` in parameter position, once, with both spellings as help; it reaches the parameters of a fn type inside the declared type (`cb: fn(dyn T) -> R`) and looks through references, pointers, Option, slices, arrays, generic arguments and tuples for nested fn types. `impl T` is a generic parameter, not a trait object, and stays. It runs on every parameter list Sema collects: free and generic functions, impl and `extend` methods, extern fns' host, trait method declarations (collect_trait_decl) and annotated closure parameters (check_closure). Test: test/compile_errors/err_1852_dyn_param_by_value.w (compiled on base). The tree's own uses were respelled `&dyn T` in the previous commit; the two sealed-trait tests move with the pattern ruling (#1860). Fixes #1852
…t binds a view of the object; a sealed trait's implementors make the match exhaustive (§9.7, §11.3, D22) Eric, 2026-09-28, option (a): "on a `&dyn T` subject, `c: Circle =>` binds `c: &Circle`, a view of the object; a `@[sealed]` trait's implementor set makes the match exhaustive (a missing implementor is the ordinary non-exhaustive error); a non-sealed trait requires a `_` arm; a subject that is not `&dyn T` (a by-value dyn, or a non-dyn) is refused. With has no `&mut T`; a mutable dyn place (a `var` holding one, a `mut self` receiver) is matched the same way and mutation goes through the trait's `mut fn` methods (§15.1). Owned by-value matching is NOT defined (waits on #724)." The pattern `name: Type` was not in the grammar and its only working subject was the by-value `dyn` #1852 refuses. Its lowering copied the object out (`_3 = copy _2.*`), bound a byte copy of it (DYN_DOWNCAST loaded the struct: a second owner of what it holds, §2.3), resolved the concrete type and the vtable by symbol text in MIR and codegen (D65), and a value matching no arm returned an uninitialized local (#1860). One owner per fact: - Sema (SemaCheck.w:17865, check_pattern's NK_PAT_TYPED_BIND arm) decides the binding: the subject must be a reference to a trait object (a `dyn` value is refused with the `&dyn T` spellings as help; a non-dyn subject keeps #663's error), the named type must be visible and implement the trait, and the binding is `&Type` with the subject reference's mutability (dyn_downcast_binding_types, keyed by the pattern node; record_pattern_view_bindings ties its origin to the subject as for any view binding). An assignment through such a binding is the ordinary read-only-place error, with help that names the trait's `mut fn` methods (dyn_downcast_binding_syms). check_match_exhaustiveness (:16286) reads the object through its reference (exh_shape_type): a sealed trait's implementor set is the domain, a non-sealed trait needs a `_` arm ("`T` is not @[sealed], so its implementors are open"). Every match Sema requires to be exhaustive is recorded (exhaustive_matches). - MirLower (:10590, :11189) reads the trait through the reference and takes the binding's type from Sema; it never looks the name up. lower_match (:11373) gives the last arm of a match Sema proved exhaustive an unreachable failure edge instead of the join: through the join it read a result no path wrote. - Codegen (CodegenDispatch.w:11691, DYN_DOWNCAST) yields the fat pointer's data word, the view; the vtable compare (DYN_VTABLE_CMP) is unchanged and uses the vtables #1847 extended. After: `describe(c)`, a `var` holding the object and a Drop implementor match and drop exactly once (`trace: circle5 rect7 other end drop7 drop5`, `debug-alloc: leak count=0`, `check --validate-all: ok`, `analyze audit:all`: violations=0); `match *s` is refused; a non-sealed match without `_` is refused; `c.radius = 9` is refused with the help. Tests (each failed on base): - test/behavior/sealed_trait_match.w (onto `&dyn Shape`; a `var` too), test/behavior/behav_1860_dyn_downcast_binds_view.w - test/compile_errors/err_sealed_not_exhaustive.w (onto `&dyn Shape`), err_1860_dyn_downcast_by_value_subject.w, err_1860_dyn_match_unsealed_needs_wildcard.w, err_1860_dyn_downcast_assign_help.w Fixes #1860
…that never initialized it; validate-all said ok over a match that returned its unwritten result "A tool that stayed silent is a bug." #1860's sealed match on a `dyn` value ended the program silently with exit 0: the no-arm path fell through to the join and `_0 = copy _4` read the result temp only the arm path wrote. validate_ownership_body (MirCore.w:2554) judged drops of such a place (#729, #1559) and moves of a moved one, never a read. Rule (mir_read_of_uninit_place, at every Assign's rvalue operands and every terminator's operands): a copy or move operand of a whole local whose state is Maybe or MaybeGarbage, some reaching path never having initialized it, is "read of _N reaches a path that never initialized it (Maybe)". Uninit is not judged: StorageDead resets a local to Uninit and the lowering moves a block's tail local out after its scope's StorageDead by contract (`_23 = move _27` after `StorageDead(_27)` in Regex.capture_name_text; materialize_tail_field_move keeps whole-local moves lazy). A projection is not judged: its key is Absent until touched. Globals and the return slot are skipped. The previous commit gave a match Sema proved exhaustive an unreachable last failure edge; with the join edge in place this rule tripped on every value-position match, which is what the rule is for. `check --validate-all` over the 250 behavior, spec and d_acceptance tests that use `match` reports nothing new (out/g1852/sweep2.log). Test: test/internals/mir_uninit_read_test.w (a planted body: a switch whose one edge writes the local and the other does not, then a read at the join; the both-write shape passes). It fails against the validator at f9d0dfc4 (run in a scratch worktree) and passes here. Fixes #1883
…`&dyn T` parameter; it was moved and never dropped (§3.9, §3.8, §2.4) `peek(a)` with `fn peek(s: &dyn Shape)` and `a: Circle` printed no `drop 1`: `--dump-mir` showed `call peek(move _1)` and no `drop(_1)`, while the explicit `peek(&b)` lowered `ref(shared, _4)` and dropped `_4` at scope exit. A str-holding implementor leaked its buffer (#1881; main does the same). Owner: Sema's can_auto_ref_arg (SemaCheck.w:335) and its frozen twin (:360) admitted auto-referencing only into a pointee equal to the actual type (a struct, enum or generic instance), so MirLower's lower_auto_ref_call_arg found no auto-reference for a `&dyn` pointee and the argument went by value; codegen built the fat pointer from the moved value's address (#1847's class: a dyn operand moved where it only borrows). A non-reference actual whose type implements the pointee trait now auto-references, as §3.9 coerces `&T` to `&dyn Trait` and §3.8 auto-references `peek(x)`; the temp is typed `&dyn T`, and the RK_REF assign into a dyn destination already builds the fat pointer. After: `trace: peek1 peek2 peek3 end drop3 drop2 drop1`, `debug-alloc: leak count=0`, `check --validate-all: ok`, `analyze audit:all`: violations=0; every test naming `dyn` passes. Test: test/behavior/behav_dyn_ref_param_autoref_drops.w (on base: `drop3` and `drop1` missing). Fixes #1881
The uninitialized-read validator added for #1883 exposed joins reached from calls Sema typed Never: no result was assigned on that path, yet the call's continuation still reached the join. The earlier validator sweep reported reads of Maybe locals in behav_todo_unreachable_never_type.w and spec_ss18_6_unreachable_todo_assert_matches.w (out/g1852/sweep2.log). lower_expr now materializes the call normally, then terminates its continuation as unreachable using Sema's canonical Never fact. The node guard prevents recursively applying that hook to the same call. The new no-prelude phase test validates a user-defined Never call in an if arm. The existing todo/unreachable behavior test, the Never probe's validate-all, the uninitialized-read validator fixture, sealed-trait behavior/refusal tests, and seed-driven :dev all pass. Full gate and the required deep-debug/drop checks follow after folding onto the stack. Refs #1883
…s agree check_match_expr classified the missing-arm tail as statement position, then kept its written arms' i32 type unless they disagreed. That gave the function an i32 return and MIR a join result no arm wrote on the no-match path. D43 requires Unit whenever an inferred tail has a missing arm. with reduce produced a five-line repro. LLDB at SemaCheck.w:16163 showed stmt_arms_mixed=false and result_type=3; the tbz at 0x10029182c skipped the Unit assignment. The live matrix showed the same i32 Sema signature and MIR locals. Keep the decision in Sema: the already-classified missing-arm inferred tail now takes Unit regardless of the written-arm types. New behavior and phase tests both fail before the fix and pass after. They cover a single match body and a block body, matching and nonmatching paths, explicit Unit demand, and validate-all. The reduced repro's audit:all reports zero violations afterward. Existing D43 and Never behavior, the validator fixture, and sealed-trait tests pass (nine targeted files total). :dev is green; stack gate follows the rebase. Fixes #1889
…ver initialized; the validator now says so (#1860) 50217d6 made validate_ownership_body refuse a copy or move of a whole local whose state is Maybe: some reaching path never initialized it. moved_twice_verdict's shape 3 is exactly that program — `_2` is initialized on the `moving` path only and moved at the join — and the test still pinned the old silence (`== ""`), so internals-tests panicked at src/MirValidationTests.w:592. The assertion now pins both facts: the verdict is not a move-of-moved (nothing moved twice), and it is the never-initialized read. Shape 4's move-of-moved pin is unchanged.
… under an inferred Unit return was kept as a view of the global it assigns (§9.1, D43, D73, §21.1 rule 1) 86dbd35 made an implicit drop write every global its type's Drop impls write, and kept, at a scope's end, the tail value that outlives the drops when it views a global (expr_views_global). It asked that of the tail whether or not the body returns it. Under D73 an assignment in value position is a read of its place, so collect_expr_view_deps says `TEMP_DROP_TRACE = TEMP_DROP_TRACE ++ "x"` views TEMP_DROP_TRACE — and a function such as fn consume(r: TempDropResource): TEMP_DROP_TRACE = TEMP_DROP_TRACE ++ "[in-consume]" was refused: "the drop of `r` at the end of its scope mutates global `TEMP_DROP_TRACE` while a view into it outlives the drop". Nothing outlives that drop: with no annotation (D43) or `-> Unit` the body's assignment tail is a statement (discard_body_tail records it in discarded_tails, check_fn_body_with_sig_at:3473 / check_block:11391 / wrapper_tail_type) and the function returns Unit. The same held through an `unsafe:` wrapper (`impl Drop`'s `unsafe: MUTEX_DROP_TRACE = …`), which broke test/spec/spec_ss02_4_expression_temporaries.w, spec_ss14_17_mutex_generic.w and spec_ss14_17_rwlock_generic.w (native-spec-tests). The fn body, block and closure exit-drop sites now keep a tail view only when the body returns the tail: not a declared `-> Unit`, and not a discarded tail — tail_value_discarded follows the wrappers body_tail_holder_of follows to the holder's recorded tail. The fn-body discard verdict moves before the exit-drop note so a single-statement body is judged the same way; body_ty reads it. A tail that is the body's value still views (err_1827_drop_tail.w, err_1827_drop_return.w keep refusing). Evidence: the three spec fixtures and the reduced repro (a `fn f(r: R): G = G ++ "x"` with `impl Drop for R` writing G) print ok / `x[d]y[d]` on the rebuilt stage1; under the parent compiler they were accepted.
added 2 commits
September 29, 2026 13:37
…s it writes (`writes G`), a bundle build checks the declaration against the body, and a call of a bundle function writes exactly its declared set (§21.1 rule 1, D39, Eric 2026-09-29) 1288aa5 counted any call of a bundle function as writing every global its bundle exports: the `.wi` said nothing about globals. That refused valid programs — lib/std/tommyds/check_.w:292, `tommy_hash_u32(…, HASH32[i].data as *const c_void, …)`, was "call mutates global HASH32 while its argument is a live view into it", though tommy_hash_u32 writes no global (tommyds-test, tommyds-wo-drift red). Eric's ruling (2026-09-29): a global write set is a legality fact, so it is a declared, checked contract, never an inferred fact in an interface (an inferred set would let a bundle author silently break every caller). - Surface: `writes COUNTER, other.TOTAL`, the declaration's last clause (after the return type and the where clause), ending at the body's `:` or `{`. `writes` is contextual: it opens the clause only in that position and only when a name follows (Parser.parse_optional_writes_clause; a `writes` global, field, parameter, local or function stays legal). Entries are whole globals, optionally namespace-qualified; a field path (`writes CONFIG.limit`), a const, a non-global, and a clause on an extern fn are refused (Sema.resolve_declared_global_writes). The parse returns its entries to the declaration, so a nested fn in the body cannot take them. - Bundle build (compiler.BundleInterfaceEmit): each exported function's transitive writes of exported globals — Sema.fn_global_effects over the call graph, dispatchers expanded even when no view check exists — must be a subset of its declared set; no clause declares none. A write outside it fails the build naming the function, the global and the call path, with the literal fix: "add 'writes COUNT' to bump's declaration". Another bundle's function contributes its declared set, so a caller must declare at least its callee's. A declared global the body never writes is a lint. A private global is not part of the interface. - Interface: the `.wi` prints the clause exactly as written; the fingerprint carries the resolved set, so source and interface agree only when the printed contract is the declared one. No `@[writes]` form exists anywhere. - Consumers: a call of a bundle function writes exactly its declared set; a name whose `.wi` line the program never read is no place there and is skipped (the bundle's own build reads the whole `.wi`). - Migrator (CiMigrate): writes the clause for every exported function that writes an exported global, itself or through the corpus functions it calls. It scans its own output with the compiler's Lexer after the whole corpus is written (a write roots an assignment target — the parser's compound-assignment table, now Parser.parser_compound_assign_op — or is taken by `&raw mut`), and fills each exported signature's clause. Exactly four exported bundle functions write exported globals, all in pcre2: pcre2_compile_8 (_pcre2_default_compile_context_8), pcre2_pattern_convert_8 (_pcre2_default_convert_context_8), pcre2_match_8 and pcre2_substitute_8 (_pcre2_default_match_context_8, the latter through pcre2_match_8). zlib, c_algorithms and tommyds export none. The re-migrated corpora carry the migrator's clauses: those four, pcre2posix's pcre2_regcomp/pcre2_regexec and pcre2test's main (harness modules), and the tommyds/c_algorithms harnesses (check_, alloc_testing, framework, test_cpp). Only clause lines were promoted: those corpora already differed from this tree's migrator in unrelated ways (#1905), and every migrate action ends red after publishing its output (#1804). Tests: behav_writes_clause_contextual_keyword.w, behav_writes_identifier_elsewhere.w, err_writes_clause_{field_path,const, not_a_global,extern_fn}.w; behav_1827_bundle_fn_precise_global_writes.w (a view of allocation_limit across `to_upper`, which declares no write); bundle-interface-tests: `bump() writes COUNTER` round-trips through the .wi and a view across it is refused from the interface alone, `reserve`'s superset clause is linted, and wi_refuse_writes.w (a write through a private helper with no clause) fails the bundle build with the path and the fix-it.
…zy interface demand A function whose only mention of a bundle global was its writes clause failed with "is no global": neither Frontend.note_interface_mentions nor SemaDecl.note_mentioned_syms walked the fn_global_write side table, so the global's interface declaration was never loaded (pcre2-wo-drift and wo-drift in the stack battery). Test: behav_writes_clause_only_mention_of_bundle_global.
ehartford
force-pushed
the
fix-globals
branch
from
September 29, 2026 18:56
1dc9640 to
c21cf63
Compare
ehartford
marked this pull request as ready for review
September 29, 2026 18:57
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.
Stack created with GitHub Stacks CLI • Give Feedback 💬