Skip to content

Make semantic verdicts independent of body-check order - #1945

Merged
ehartford merged 22 commits into
mainfrom
parallel-sema
Oct 2, 2026
Merged

ehartford merged 22 commits into
mainfrom
parallel-sema

Conversation

@ehartford

@ehartford ehartford commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Checking the same program in reverse body order changed acceptance, closure
escape checks, dynamic-destructor effects and diagnostic locations. The
compiler now judges parameter and closure effects after propagation, resolves
impl targets and generic unsafe contracts from canonical declarations, and
keeps diagnostic source identity with the node that owns it. Scope-local name
markers and unsafe context expire with the binding/body that owns them.

The order checker now compares child exit status and the two output streams
independently; crashes, capture failures and empty corpora fail loudly. It is
included in the fixed gate. The new regressions cover direct/transitive/cached
generic pointer effects, escaping and observing closures, private dynamic
implementors across modules, diagnostic and generic source provenance,
downcast name reuse, global-read unsafe requirements, and runner false greens.
The completed RAW graph also exposed two engine comparison callbacks whose
safe declarations contradicted their live-pointer requirements. Their library
contracts now match the unsafe callback types the engines already accept;
application fixtures retain their original spelling.

Validation at published head 1ef49d2:
the pinned-seed stage chain, fresh self-check, build.w check, examples,
benchmarks, C migrator and deep-debug checks pass. The repaired checker finds
zero differences and zero runner failures across 1,586 fixtures, with an
empty allowlist. Focused regressions have failing-first evidence; the 11-case
pointer matrix passes within the normal timeout. The drop audit passes all
254 cells, including the 17 facade cells rejected before the callback fix.
Stage2 and stage3 are byte-identical over all 16 compiler units; native debug
line/variable checks pass. The fresh resolution audit reports zero violations
across 3,073,637 facts and 130,280 MIR calls.

The earlier gate was blocked by the command runner's nested sandbox policy.
Network and unrestricted execution access are now restored. The commits are
pushed, and integration with current main plus final verification are in
progress. No final seed battery has run; keep this PR in draft until its
green evidence is posted.

This is the order-independence layer. Per-body overlays, worker scratch,
parallel checking and threaded IR remain subsequent work; there is no
parallel performance claim in this change.

Per-body overlays, worker scratch, parallel checking and threaded IR remain
subsequent campaign steps. The final gate and pinned-seed battery are the
remaining merge-readiness checks for this order-independence layer.

ehartford pushed a commit that referenced this pull request Oct 2, 2026
Read analysis diagnostics from Zcu after Frontend transfers ownership out of
Sema. Locate AST facts from each node's parser file, and expose diagnostic
primary/origin/label file identities. Use one node-span owner for semantic
diagnostics, including deferred receiver and generator-pull judgments.
Resolve a root-file label when its primary belongs to an imported module.

Root evidence: reverse receiver diagnostic facts reported subject-file=7
(std.option) and origin-node-file=0 for Owner.return_receiver. Its AST fact
and effect seed both belonged to the user file. SemaDiag.emit_error used
local_file_id rather than the node's file. emit_pull_error did the same for
both spans. A cross-module regression then rendered a root pull as label
@2:10 against the imported generator: Zcu.render_diag_frontend_with excluded
lab_file=0 even when primary.file differed. The repaired renderer reports
src/main.w:3 for that label.

The silent inspector's exact cause was Frontend's move of sema.diags into
Zcu.diagnostics, followed by Analysis's scan of the emptied source list.
The new inspection regression fails before the repair and passes after it.

Validation: -O1 dev rebuild and compiler self-check; failing-first diagnostic
inspection and deferred diagnostic regressions; five existing error fixtures
match byte-for-byte in forward/reverse order, including correct user files;
cross-module generator primary/label locations verified in both orders.

Not ready: three semantic order discrepancies remain. Final layer gate and
seed-driven stack battery are pending; GitHub publishing is blocked by this
session's never-approval policy.
ehartford pushed a commit that referenced this pull request Oct 2, 2026
…1945)

Carry RAW_PTR_VALIDITY through the one transfer rule used by the effect fixed
point and audit. Pointer/reference parameters still carry no owning effects.
Judge safe wrapper contracts after all bodies are checked. Snapshot pointer
parameter origins through local aliases while scope facts are available, so
copying an address cannot erase its validity requirement. Record direct loads
through borrowed pointer storage as well. Normalize the read category at the
effect owner and expose internal validity bits/provenance in explain:effect.

Root evidence: reverse-order effect facts showed wrapper param[0] -> read_first
param[0] with callee effect 32, but wrapper final=1. effect_edge_transfer omitted
bit 32, and fixpoint_effect_flow skipped pointer/reference callers entirely.
check_fn_body_with_sig_at judged the wrapper before the callee summary existed.
The repaired explanation follows wrapper -> read_first -> the actual load at
err_issue366_safe_wrapper_raw_ptr_precondition.w:4 in either order.

The expanded matrix exposed missing raw validity through **p and local pointer
aliases: the old pointer noter used place_root_sym, which deliberately does not
name pointee storage through a dereference, and ignored binding initializer
facts. Pointer-value origins now remain separate from pointee ownership.

The completed graph also exposed three private std.zip helpers. The effect
chain for zip_current_entry reaches unzGetCurrentFileInfo64, then
unz64local_GetCurrentFileInfoInternal's load at lib/std/zl/unzip.w:1901. Declare
these private raw-handle boundaries unsafe and make the ZipArchive methods'
validated-handle calls explicit. The public API and existing fixture are kept.

Validation: failing-first order regression; five wrapper shapes have equal
forward/reverse diagnostics and direct=1/final=32 effect records; pointer
identity remains safe. -O1 dev rebuilds and fresh source checks. Zip behavior
and final compiler verification run with the re-embedded stdlib.

Not ready: closure-capture and dyn-destructor order discrepancies remain;
layer gate and final seed-driven stack battery are pending. GitHub writes are
blocked by this session's never-approval policy.
ehartford pushed a commit that referenced this pull request Oct 2, 2026
SemaCheck.check_closure read a possibly empty parameter effect summary and
marked a direct reference-capturing argument non-escaping before its callee
was checked. The new analyze closure facts preserve capture types after scope
exit: closure-facts-reverse.txt shows r: &i32, ephemeral=1, non-escaping=1,
and spawn_os final-effects=12. The forward snapshot marks it escaping and
emits the missing error. This locates the wrong direct_arg_escapes == 0
branch in check_closure, rather than inferring it from diagnostic counts.

Remove the early cross-body read. Direct non-move arguments borrow their
captures during the call; finalize_closure_arg_checks judges saved capture
types against final effects and revokes a provisional non-escaping marker.
Sort diagnostics after all deferred judgments, not midway through checking.

The new closure escape regression fails before this change and passes after
it, covering spawn_os, a returning callee and a synchronous observer in both
body orders. The existing callable clone/call-through regression and fresh
compiler self-check pass. The pinned-seed dev build passes in 354.2 seconds;
closure-facts-reverse-after.txt shows non-escaping=0 and the restored error.
Final layer gate and batch battery remain pending; this commit is not ready.
The diagnostic span regression remains red because the preceding raw-effect
slice misclassifies an unsafe generic specialization (pull_yield) as safe;
that newly exposed compiler defect is being fixed next, without changing the
regression or the already-unsafe std.task helper.
ehartford pushed a commit that referenced this pull request Oct 2, 2026
Signature inspection now uses Sema's shared unsafe-declaration helper and
reports both the canonical declaration and generated-name lookup. Native
task-unsafe-declaration-proof.txt proves pull_yield__sema__ resolves to
decl-node=8474, declared-unsafe=1, while name-decl-node=0 and name-unsafe=0.

Global-effect inspection reads recorded writes, kept calls and expanded
targets, live-view checks, cached drop gates, and actual dyn-drop traversal
decisions. It never resolves a name or expands a dispatcher on inspection.
dyn-drop-graph-reverse-proof.txt records Tok's target as 0 from std.option,
branch=skip-target, at push_drop_glue_bodies' lookup_named_type_visible line.
Forward inspection records target=290, branch=enqueue-target and the actual
Box[dyn Named] -> Tok.drop edge. The missing edge is now visible rather than
being inferred from error counts.

Source check and installed-compiler dev build pass (185.5 seconds, compiler
46.2 seconds). Both inspector queries retain facts on failed compilation.
Acceptance fixes, layer gate and battery remain pending.
ehartford pushed a commit that referenced this pull request Oct 2, 2026
push_drop_glue_bodies used lookup_named_type_visible under the last body's
ambient module. Native global-effect inspection in
dyn-drop-graph-reverse-proof.txt shows Tok resolved to 0 from std.option,
branch=skip-target; the live-view check and Tok.drop write both exist, but
Box[dyn Named] has no edge to Tok.drop. Forward inspection resolves Tok to
290 and enqueues it. This locates the failing lookup and conditional enqueue.

Store each impl's resolved target while collect_impl_decl has its declaration
context, including concrete generic targets. The drop graph consumes this
fact and retains the declaration context for inspection, without another
visibility lookup in body checking.

The new regression fails before and passes after, in both body orders and
with a private implementor exposed through a public factory in another
module. dyn-drop-target-reverse-after.txt now records target-type=Tok and
branch=enqueue-target, and the original unsafe global-view program is rejected.
Fresh compiler self-check passes; the combined development build passes in
59.1 seconds. Layer gate and batch battery remain pending.
ehartford pushed a commit that referenced this pull request Oct 2, 2026
The checker discarded with_exec_wait's result at wait(), then compared
concatenated stdout and stderr. A native With probe returning 1 forward and
0 reversed with identical output produced a false green over all 1584
fixtures (order-check-status-before.txt). The repaired checker rejects all
1584 (order-check-status-after.txt), without an allowlist exemption.

Retain each wait result, compare statuses and each stream separately, and
reject spawn/timeout/crash codes regardless of the allowlist. Capture reads
and report writes use std.fs and fail loudly; an empty corpus is an error.
Optional source/allowlist paths support a small checked regression.

behav_sema_order_checker_verdicts fails on the original tool's status probe
(line 33) and passes on the repair. Its six cases cover a matching positive
control, differing acceptance, invalid exits, missing compiler, stream
boundaries that concatenation hides, and an empty corpus. The tool source
check passes. The actual full corpus scan is active; gate/battery pending.
@ehartford ehartford changed the title Order-independent body checking (S2a, toward parallel sema): #1941; D43 callee-first; sema-order-check; WIP diagnostic ordering Make semantic verdicts independent of body-check order Oct 2, 2026
Eric Hartford added 21 commits October 1, 2026 22:14
…the shared tables

sema.bodies.added counts the types, symbols and signatures check_bodies
appends; llvm.unit<k>.symbols_added counts the symbols unit k interns into
the shared pool. Both are numbered in check/unit order, so they size what
a parallel sema or parallel IR generation would have to reproduce
deterministically. Compiling the compiler: bodies add 841 types, 6
symbols, 6 signatures; unit 0 interns 5451 symbols, units 1-15 at most 42
each. Gate green.
…o expose declaration-order dependence

A debug switch for the Sema split: the callee-first dependencies of
prepare_body_order still apply; everything else runs in reverse. Over
test/compile_errors (1560 fixtures, `with check`), 122 change their
diagnostics, 16 in substance. One is a missed @[no_alloc] error that
also happens in normal order when the callee is declared after the
caller (#1941). Gate green.
…d with bodies in reverse, must agree outside a D43 allowlist

`--sema-body-order-reverse` is the CLI front door for
WITH_SEMA_BODY_ORDER=reverse. tools/sema_order_check.w runs the release
compiler over test/compile_errors twice (16 checks in flight, ~40 s) and
fails on any fixture whose output differs unless
test/sema_order_allowlist.txt names it (D43: a return type inferred from
a body declared later is not known at an earlier call). The build target
`:sema-order-check` runs the tool; it joins the gate once the count
reaches the allowlist.

Baseline: 128 of 1579 fixtures differ; the allowlist is empty.
Documented in docs/spec/toolchain/deep-debugging-tools.md; the flag is
registered as an internal/dev flag for spec-inventory-check. Gate green.
…checked (#1941)

`note_allocating_callee` read `fn_may_alloc`, which a body publishes when
its check ends. A caller checked before its callee, i.e. declared first,
read "does not allocate", so an @[no_alloc] function could call an
allocating function declared after it and compile.

Calls are now recorded while bodies are checked, as (owner, callee, node,
in-@[no_alloc]-context, file). `resolve_allocating_callees` runs once all
bodies are done: it takes the fixpoint of "allocates" over the recorded
calls (a function allocates when its body does or when it calls one that
does) and then reports each call an @[no_alloc] context makes to an
allocating function. A body checked afterwards (a concrete generic body
MIR asks for) reads the final summary directly.

Fixtures, both compiling `ok` before the fix:
err_1941_no_alloc_callee_declared_after.w (callee declared after the
caller), err_1941_no_alloc_transitive_callee_after.w (the allocation
reaches the caller through an intermediate function). The existing no_alloc
fixtures and the behav_no_alloc_* programs are unchanged.

sema-order-check: 128 -> 127 of 1581 fixtures differ under reverse order.
Gate green.
…trait before any body is checked

A trait impl method written without `-> T` returns what the trait
declares. That was set on the method's signature when the method's own
body finished checking. A call reached earlier read the placeholder Unit.
For example, `print(P { x: 7 })` goes through `print[P]` to `P.to_str`;
when `main` was checked before the impl, std.builtins reported "wrong
argument type in call to 'with_println_str'". The same happened for every
std `impl Display for i32: fn to_str(): ...`. This is a fact of the
declarations, not of a body.

`publish_trait_contract_returns` runs at the start of check_bodies. For
each non-generic, unannotated impl method with a trait contract, it sets
the contract return on the signature and marks it typed, using the same
Self and associated-type bindings the body check sets up. The body check
still derives the same return from the same contract.

Fixture err_1941_trait_contract_return_order.w: `--sema-body-order-reverse`
added the std error before this change. The two orders now agree.

sema-order-check: 127 -> 20 of 1582 fixtures differ under reverse order.
Gate green.
…st, in any check order (D43, §4.10)

A function written without `-> T` has the type its body gives it
(D43). prepare_body_order found the calls a body makes by name and
checked those callees first. It could not see a function used as a
value (`Rc.new(twice)`) or a call reached inside a generic instance.
Those uses read the placeholder Unit when the callee's body came later
in check order: `fn(i32) -> Unit` for `twice` when `main` came first.

`ensure_body_typed` runs at a function value and at a direct call. When
the callee is an unannotated, non-generic top-level function whose body
has not started, it checks that body on demand, in the callee's own
module context and lexical environment. A body already in progress (a
cycle) stays unknown and is reported by check_bodies as before.

The environment swap check_fn_body_concrete did inline is now
enter_callee_lexical_env / leave_callee_lexical_env over a
SemaLexicalEnv record, one owner for both callers (BindingProvenance is
pub for it). Without it, the on-demand body saw the caller's locals and
reported spurious shadowing inside std.

Fixture err_1941_fn_value_before_body.w (`twice` declared after `main`)
said `fn(i32) -> Unit` before this change and says `fn(i32) -> i32` now.
Forward-order output of test/compile_errors is otherwise unchanged; the
two c_import fixtures whose messages name a random /tmp path differ from
run to run, so they differ in any comparison.

sema-order-check: 20 -> 16 of 1583 fixtures differ under reverse order.
Gate green.
…e>`, not in its random temp file

Source text given to c_import inline is written to a mkstemp file and
parsed from there. An omission diagnostic located the symbol at that
file, `(at /tmp/with_cimport_IdPmcb:2:14)`, so the same program's
diagnostic changed from run to run. sema-order-check caught it as two
fixtures whose output differed between any two checks.
with_ci_cursor_location now names that file `<c_import source>`; the
line and column already count within the given text.

Fixture err_c_import_inline_source_location.w expects
`(at <c_import source>:2:14)`; before this change it printed the temp path.

sema-order-check: 16 -> 15 of 1584 fixtures differ under reverse order
(err_1417_inline_body_over_opaque_record and
err_c_import_omitted_directional_raw are stable now; the new fixture
agrees in both orders). Gate green.
…et, message)

Done: DiagnosticList.sort_from(start) stable-sorts the diagnostics
emitted from `start` on by (primary file, primary start, message).
check_bodies records the list length at entry and sorts from there after
its post-body passes (untyped callees, globals). Bodies are checked
callee-first, and later in parallel; this makes the report follow the
program's order instead.

Measured on a release build of this tree: sema-order-check 15 -> 8 of
1584 fixtures differ under reverse order (the 7 order-only ones agree
now). Forward-order diagnostic *content* over test/compile_errors is
unchanged against the pre-S2a baseline, except the two c_import fixtures
fixed in 22f4c883. The *order* of lines changed in 32 fixtures' forward
output.

UNVERIFIED: gate not run on this commit; whether any test or tool
depends on the old emission order is not checked (the compile_errors
harness matches substrings; LSP/JSON consumers not reviewed). No
fixture added for this step; the evidence is the 7 fixtures that were
order-only in the previous report.
Read analysis diagnostics from Zcu after Frontend transfers ownership out of
Sema. Locate AST facts from each node's parser file, and expose diagnostic
primary/origin/label file identities. Use one node-span owner for semantic
diagnostics, including deferred receiver and generator-pull judgments.
Resolve a root-file label when its primary belongs to an imported module.

Root evidence: reverse receiver diagnostic facts reported subject-file=7
(std.option) and origin-node-file=0 for Owner.return_receiver. Its AST fact
and effect seed both belonged to the user file. SemaDiag.emit_error used
local_file_id rather than the node's file. emit_pull_error did the same for
both spans. A cross-module regression then rendered a root pull as label
@2:10 against the imported generator: Zcu.render_diag_frontend_with excluded
lab_file=0 even when primary.file differed. The repaired renderer reports
src/main.w:3 for that label.

The silent inspector's exact cause was Frontend's move of sema.diags into
Zcu.diagnostics, followed by Analysis's scan of the emptied source list.
The new inspection regression fails before the repair and passes after it.

Validation: -O1 dev rebuild and compiler self-check; failing-first diagnostic
inspection and deferred diagnostic regressions; five existing error fixtures
match byte-for-byte in forward/reverse order, including correct user files;
cross-module generator primary/label locations verified in both orders.

Not ready: three semantic order discrepancies remain. Final layer gate and
seed-driven stack battery are pending; GitHub publishing is blocked by this
session's never-approval policy.
…1945)

Carry RAW_PTR_VALIDITY through the one transfer rule used by the effect fixed
point and audit. Pointer/reference parameters still carry no owning effects.
Judge safe wrapper contracts after all bodies are checked. Snapshot pointer
parameter origins through local aliases while scope facts are available, so
copying an address cannot erase its validity requirement. Record direct loads
through borrowed pointer storage as well. Normalize the read category at the
effect owner and expose internal validity bits/provenance in explain:effect.

Root evidence: reverse-order effect facts showed wrapper param[0] -> read_first
param[0] with callee effect 32, but wrapper final=1. effect_edge_transfer omitted
bit 32, and fixpoint_effect_flow skipped pointer/reference callers entirely.
check_fn_body_with_sig_at judged the wrapper before the callee summary existed.
The repaired explanation follows wrapper -> read_first -> the actual load at
err_issue366_safe_wrapper_raw_ptr_precondition.w:4 in either order.

The expanded matrix exposed missing raw validity through **p and local pointer
aliases: the old pointer noter used place_root_sym, which deliberately does not
name pointee storage through a dereference, and ignored binding initializer
facts. Pointer-value origins now remain separate from pointee ownership.

The completed graph also exposed three private std.zip helpers. The effect
chain for zip_current_entry reaches unzGetCurrentFileInfo64, then
unz64local_GetCurrentFileInfoInternal's load at lib/std/zl/unzip.w:1901. Declare
these private raw-handle boundaries unsafe and make the ZipArchive methods'
validated-handle calls explicit. The public API and existing fixture are kept.

Validation: failing-first order regression; five wrapper shapes have equal
forward/reverse diagnostics and direct=1/final=32 effect records; pointer
identity remains safe. -O1 dev rebuilds and fresh source checks. Zip behavior
and final compiler verification run with the re-embedded stdlib.

Not ready: closure-capture and dyn-destructor order discrepancies remain;
layer gate and final seed-driven stack battery are pending. GitHub writes are
blocked by this session's never-approval policy.
SemaCheck.check_closure read a possibly empty parameter effect summary and
marked a direct reference-capturing argument non-escaping before its callee
was checked. The new analyze closure facts preserve capture types after scope
exit: closure-facts-reverse.txt shows r: &i32, ephemeral=1, non-escaping=1,
and spawn_os final-effects=12. The forward snapshot marks it escaping and
emits the missing error. This locates the wrong direct_arg_escapes == 0
branch in check_closure, rather than inferring it from diagnostic counts.

Remove the early cross-body read. Direct non-move arguments borrow their
captures during the call; finalize_closure_arg_checks judges saved capture
types against final effects and revokes a provisional non-escaping marker.
Sort diagnostics after all deferred judgments, not midway through checking.

The new closure escape regression fails before this change and passes after
it, covering spawn_os, a returning callee and a synchronous observer in both
body orders. The existing callable clone/call-through regression and fresh
compiler self-check pass. The pinned-seed dev build passes in 354.2 seconds;
closure-facts-reverse-after.txt shows non-escaping=0 and the restored error.
Final layer gate and batch battery remain pending; this commit is not ready.
The diagnostic span regression remains red because the preceding raw-effect
slice misclassifies an unsafe generic specialization (pull_yield) as safe;
that newly exposed compiler defect is being fixed next, without changing the
regression or the already-unsafe std.task helper.
Signature inspection now uses Sema's shared unsafe-declaration helper and
reports both the canonical declaration and generated-name lookup. Native
task-unsafe-declaration-proof.txt proves pull_yield__sema__ resolves to
decl-node=8474, declared-unsafe=1, while name-decl-node=0 and name-unsafe=0.

Global-effect inspection reads recorded writes, kept calls and expanded
targets, live-view checks, cached drop gates, and actual dyn-drop traversal
decisions. It never resolves a name or expands a dispatcher on inspection.
dyn-drop-graph-reverse-proof.txt records Tok's target as 0 from std.option,
branch=skip-target, at push_drop_glue_bodies' lookup_named_type_visible line.
Forward inspection records target=290, branch=enqueue-target and the actual
Box[dyn Named] -> Tok.drop edge. The missing edge is now visible rather than
being inferred from error counts.

Source check and installed-compiler dev build pass (185.5 seconds, compiler
46.2 seconds). Both inspector queries retain facts on failed compilation.
Acceptance fixes, layer gate and battery remain pending.
push_drop_glue_bodies used lookup_named_type_visible under the last body's
ambient module. Native global-effect inspection in
dyn-drop-graph-reverse-proof.txt shows Tok resolved to 0 from std.option,
branch=skip-target; the live-view check and Tok.drop write both exist, but
Box[dyn Named] has no edge to Tok.drop. Forward inspection resolves Tok to
290 and enqueues it. This locates the failing lookup and conditional enqueue.

Store each impl's resolved target while collect_impl_decl has its declaration
context, including concrete generic targets. The drop graph consumes this
fact and retains the declaration context for inspection, without another
visibility lookup in body checking.

The new regression fails before and passes after, in both body orders and
with a private implementor exposed through a public factory in another
module. dyn-drop-target-reverse-after.txt now records target-type=Tok and
branch=enqueue-target, and the original unsafe global-view program is rejected.
Fresh compiler self-check passes; the combined development build passes in
59.1 seconds. Layer gate and batch battery remain pending.
The checker discarded with_exec_wait's result at wait(), then compared
concatenated stdout and stderr. A native With probe returning 1 forward and
0 reversed with identical output produced a false green over all 1584
fixtures (order-check-status-before.txt). The repaired checker rejects all
1584 (order-check-status-after.txt), without an allowlist exemption.

Retain each wait result, compare statuses and each stream separately, and
reject spawn/timeout/crash codes regardless of the allowlist. Capture reads
and report writes use std.fs and fail loudly; an empty corpus is an error.
Optional source/allowlist paths support a small checked regression.

behav_sema_order_checker_verdicts fails on the original tool's status probe
(line 33) and passes on the repair. Its six cases cover a matching positive
control, differing acceptance, invalid exits, missing compiler, stream
boundaries that concatenation hides, and an empty corpus. The tool source
check passes. The actual full corpus scan is active; gate/battery pending.
Read unsafe from the canonical declaration for a concrete specialization,
and record the selected generic call's parameter edge through the existing
effect graph. Plain T parameters consume and &T borrows; correct stale
call-path comments that described the superseded SHARE-PLACE contract.

Native evidence: task-unsafe-declaration-proof.txt reports canonical node
8474 unsafe=1 while generated-name lookup returns node 0. LLDB disassembly
in generic-effect-handler-instructions.txt shows the concrete-call handler
at SemaCheck.w:23056 calling closure validation with no record_effect_edge;
the resolved call exists but generic-wrapper-edge-proof.txt has no edge.

The 11-case matrix fails at line 27 when its standalone harness runs with
the saved baseline (generic-effect-matrix-direct-before.txt), and passes
with the candidate (generic-effect-matrix-direct-after.txt). The normal
test runner also passes within its existing timeout. The unsafe generic
positive run prints 42 in both orders; its safe wrapper is rejected in both.
Dev build and fresh compiler self-check pass. Final gate/battery pending.
Imported generic signature, parameter and specialization records had the
caller's path because generated names lack fn_decl_source_paths entries.
Use Sema's existing canonical declaration identity when that map has no row.

LLDB generic-path-native-before.txt locates the wrong branch at Analysis.w:58:
0x1001eea38 jumps from the missing hashmap entry straight to cloning the
fallback. The imported load specialization has canonical node 578008 but
its three declaration records report src/main.w in the baseline snapshot.

behav_analysis_generic_source_path fails before at line 20 and passes after
in both orders, retaining src/helper.w for all three declaration fact kinds.
The dev build passed in 74.8 seconds and the fresh src/main.w check passes.
Final gate/battery pending.
A match's downcast binding left a module-wide name marker after scope exit.
An unrelated reference parameter with the same name therefore received false
trait-object mutation advice, depending on which function was checked first.
The marker is binding scratch; remove it in pop_scope with the binding.

The diagnostic inspector reproduces different help for the same assignment
in downcast-name-{forward,reverse}-before.txt. LLDB locates the branch in
Sema.emit_read_only_place_assign at 0x100120df8 / 0x100120dfc: membership of
the root name in dyn_downcast_binding_syms selects emit_error_with_help.
pop_scope removed the binding and other name facts but never this marker.

The behavior regression fails before at line 14 and passes after. It checks
cross-function name reuse and reuse after a match arm within one function,
plus preservation of specialized help for a live downcast binding. Add the
repro to the order corpus. Dev and fresh compiler self-check pass; final
gate/battery pending.
The repaired checker reports zero differences and zero runner failures over all 1584 fixtures with an empty allowlist (out/sema-order-after-canonical-facts.txt). The build graph checks with the fresh candidate; the pinned-seed layer gate and fresh-release build.w check are next. The added binding-lifetime regression will also be covered by the gated scan.
An immutable/stable global read consulted mutations seen so far, making an
unsafe block vacuous only in reverse order. Keep each read's lexical block
nodes and judge the pending requirement after body checking. Definite unsafe
operations remain immediate evidence; later bodies consume completed facts.

The seven-case regression's unused-block control also exposed a safe generic
callee inheriting its caller's unsafe context. Save/clear/restore that context
per function body, so print's internal runtime call cannot mark a caller's
otherwise unused block as necessary. Record current inventory dispositions.

Native proof: global-unsafe-native-before.txt locates the partial-set lookup
at 0x10004ff40/0x10004ff44 and global-unsafe-block-native-before.txt locates
the immediate verdict at 0x100266520/0x10026652c. The four-spelling matrix has
an extra vacuity error for let/stable global only in reverse order. The safe
print signature has declared-unsafe=0; its MIR calls with_println_str, while
unsafe-callee-context-native-before.txt shows the inherited in_unsafe branch
at 0x1002db0ec selecting note_unsafe_operation at 0x1002db124. Function-body
entry did not isolate that lexical state.

Regression fails before at line 9; deferral alone fails the unused control
at line 27; the completed fix passes all seven cases in both orders. Unsafe
generic positive/negative regression and fresh self-check pass. The existing
unused-unsafe fixture remains rejected. Both dev builds pass. Gate/battery
pending; add the immutable-write repro to the body-order corpus.
The completed RAW effects reject slot_compare at engine_slot.w:21 and hash_slot_compare at hash_index.w:38. The 254-cell pinned drop audit records 17 COMPILE-FAIL regressions. explain:effect identifies direct raw-pointer validity seeds on a/probe; native enforcer proof at 0x10069cd6c and 0x10069ce14 checks canonical unsafe status and RAW bit 5 before emitting the error.

Declare the library callbacks unsafe, as their engine callback types already require, and document the live-slot precondition. Source checks of both corrected modules pass. Existing drop-audit cells retain their original user programs and provide the before/after regression checks.
… va_list key matches its reference

4b1a95e named inline source `<c_import source>` in with_ci_cursor_location
but not in with_ci_cursor_referenced_location, which spelled the same
cursor's location on its own. lower_decl_stmt_structural records a deferred
va_list under the first spelling and lower_va_start_decl looks it up under
the second, so for inline source the key never matched and every
`static inline` variadic body was refused ("va_start's list is not a
va_list declared in an enclosing block of this function"): the #1945
battery on ebcb44f was red on behav_c_import_static_inline_variadic.w,
which passes on main (a header file's name is the same in both).

Both queries now call session_cursor_location, which decides the shown
name once. behav_c_import_static_inline_variadic and
err_c_import_inline_source_location pass on stage1.
@ehartford

Copy link
Copy Markdown
Contributor Author

Battery GREEN on 4de7b7b (seed-driven, with run tools/battery.w, on main 1688728): gate rc=0 wall=214s, battery-checks rc=0 wall=347s. First run on ebcb44f was RED on behav_c_import_static_inline_variadic alone — 4b1a95e renamed inline source <c_import source> in with_ci_cursor_location but not with_ci_cursor_referenced_location, so a va_list's deferred-declaration key never matched its va_start lookup for inline source; fixed in 4de7b7b (one shared session_cursor_location). S2a complete: sema-order-check 0 of 1584 fixtures differ in reverse body order, empty allowlist, and it is now in the gate's fixed list. Ready to merge; independent of the Linux stack.

@ehartford
ehartford marked this pull request as ready for review October 2, 2026 15:25
@ehartford
ehartford merged commit 45cc685 into main Oct 2, 2026
@ehartford
ehartford deleted the parallel-sema branch October 2, 2026 16:13
ehartford added a commit that referenced this pull request Oct 3, 2026
…1861); callable call observes, not moves (#1858); closure literal to &U auto-borrowed (#1904); scoped type bindings win (#1967); test_* inferred return (#1862); Ok/Err join builds Result[A,B] (#1856); generic fn as a value (#1857) (#1980)

* CK_FN constant evaluation: a function constant with no function is a BUG, never undef (#1859)

No Silent Fallbacks. The CK_FN branch of the codegen constant evaluator
printed `warning: [ck-fn] NOT FOUND` and returned wl_get_undef when a
function constant's symbol was in neither fn_values nor the LLVM module:
an undefined function value that compiled and jumped into garbage at run
time. Sema resolved the name and MirLower emitted the constant, so a
missing function here is a compiler defect; it is now a named
sema_phase_bug carrying the symbol and its link name.

Corpus exposure is the battery's to measure (grep its logs for the BUG
line); this branch's #1857 fix routes the one known reacher, a generic
function used as a callable value, to its specialization first.

* Atomic methods with the ordering omitted: MIR materializes SeqCst as the call's own operand (#1861)

Route: codegen/ABI. `with check --dump-mir` on `a.store(3); print(f"x{a.load()}")`
showed `fetch_add(copy _1, const 3)` with two operands and `load(copy _1)`
with one: Sema accepts the ordering as optional (atomic_method_expected_arg_type),
MirLower's lower_intrinsic_call pushed only the written arguments, and both
backends read the ordering by position from the flat operand table
(CodegenDispatch mir_atomic_fiber_intrinsic_call: mir_intrinsic_arg(body,
args_id, 1|2) reads call_arg_operands[arg_start + idx] with no bound against
call_arg_counts). An omitted ordering therefore read the NEXT call's first
operand — the f-string's literal text, "wrong argument type actual=i32
expected=ptr" — or, for a global initializer that is the last call in its
body, ran off the table: "panic: index out of bounds".

The omitted argument is the program's choice of the default (§14.17.1:
SeqCst), fixed in one place: lower_intrinsic_call pads an Atomic intrinsic's
operands to mir_atomic_intrinsic_arg_count with `Order.SeqCst` typed as the
module's Order enum, so every backend sees the full argument list.

behav_1861_atomic_default_ordering.w: the issue's global initializer
(panicked), top-level fetch_add + f-string (codegen error), the in-fn
store/load (codegen error) and the helper fn shape (panicked) now print
4 / x7 / x3 / 2 4, debug-alloc leak count 0.

* Calling a callable temporary reads it in place; the MIR no longer moves then drops it (#1858)

Route: drop/ownership. `with run --debug-alloc` (and WITH_ALLOC_NO_REUSE=1)
on behav_callable_alias_field_call.w and on a capturing variant
(`h.f.clone()(21)` with `f` closing over a heap str) is clean: leak count 0,
no double free. `--dump-mir` of `nested` showed the inconsistency the
ownership validator reported:

    call const fn sym210(copy _1.*.inner.run) -> _5    // .clone()
    call move _5(const 21)
    drop(_5) @ scope-exit _5

So the audit was right and the MIR fact was wrong. D63 (§12.4): calling a
callable observes it, and codegen's indirect call does not consume the
pair, which is why the allocator saw one free. The wrong line was
MirLower.lower_callable_expr: a callee that is not a place (a call result)
fell through to `lower_expr`, which hands a call result back as OK_MOVE of
its statement temp. A callable callee is now read as OK_COPY of that temp,
so the one scheduled drop is the only consumer.

audit:all on behav_callable_alias_field_call.w: violations=1 FAILED ->
violations=0 ok; the capturing repro: violations=1 -> 0; both print the
same values under the debug allocator with leak count 0.

* A closure literal passed to a `&U` parameter of a generic method is auto-borrowed in MIR (#1904)

Route: MIR validator. `with check` on the issue's facade program:
"invalid MIR before codegen: call argument 2 is a value where the callee
parameter is a reference to it (a missing borrow)" at the closure literal
`d.exec(invoke, n => n + 1, 1)`. A facade callback method is generic over
its userdata `U` and lowers through MirLower.lower_method_call's
GENERIC_CALL path, whose argument loop sends every NK_CLOSURE argument
straight to lower_closure and pushes the closure value, skipping
lower_call_arg — the only place the `&U` auto-reference
(lower_auto_ref_call_arg, can_auto_ref_arg_frozen) is applied. A bound
closure (`let f = n => n + 1; d.exec(invoke, f, 1)`) took lower_call_arg
and was borrowed, which is why only the literal spelling failed.

The closure literal is still lowered in place (codegen resolves it through
this body's CK_CLOSURE constant); when the parameter is a `&U` it accepts
by auto-reference, the literal is materialized into its statement temp and
the argument is a shared borrow of it, as lower_auto_ref_call_arg builds.
A by-value closure argument is unchanged and stays registered for the
machinery-dispatch move.

behav_1904_facade_callback_closure_literal_userdata.w: invalid MIR -> 2,
debug-alloc leak count 0.

* Name resolution: a scoped type binding (Self, a generic parameter) wins over a visible module's type (#1967)

Sema.lookup_named_type_filtered walked the module candidates for a name
and returned the first visible one before consulting the scoped tier
(scoped_type_binding: `Self` and generic type parameters, inserted into
named_types directly with no module candidate). A visible module's
`pub type T` therefore shadowed the `T` of `fn d[T: Default]`. Observed on
the installed compiler with `use issue1967.shadow_t`:

    fn d[T: Default](w: T) -> T: T.default()
    error: unknown method 'default' for type 'T'     (T = the module struct)

and without the import the same body prints 0. (The struct-literal
spelling `T { v: 1 }` showed the same misresolution as "return type
mismatch".)

The candidate walk now first notes whether named_types' entry is one of
the recorded candidates, and returns the scoped binding before any module
candidate; the c_import, bridged-std and builtin tiers keep their order
after it.

behav_1967_generic_param_beats_imported_type.w: compile error -> `0 0 4 15`;
the imported struct stays reachable by its short name outside the generic.

* A Unit operand of `++` or arithmetic is a Sema error naming the D43 test_* rule (#1862)

`with analyze r.w 'select:stage=sema,kind=signature,name~test_label'`
shows `test_label` with return=14 (Unit): functions.md fixes it —
"`main`, `@[entry]` and `test_*` functions do not infer: their return
contract is fixed and their tail is statement position" — with no
exception for parameters, so the rule applies and the Unit result is
the program's; the defect is that Sema accepted it as an operand.
SemaCheck.check_binary's OP_CONCAT branch rejects an operand whose kind
is int/float/bool/struct/enum/array/tuple/generic-inst and let TY_VOID
through, so `"x " ++ test_label(0)` passed `check` and died in codegen
("wrong argument type actual=i32 expected=ptr", or "call argument 0 is
Unit" in MIR). Arithmetic had the same hole (`u() + 1`). A call argument
and an annotated binding already reported it.

reject_unit_operand now refuses a Unit operand of `++`, `+ - * / %`,
naming the callee that returns Unit and, for `main`/`test_*`, the D43
rule and the remedy (rename a helper: a `test_` name marks a test).

err_1862_test_fn_unit_result_used.w: `ok` + codegen failure -> the
diagnostic.

* An unannotated join of Ok(a) and Err(b) arms types Result[A, B] (#1856)

`with run` on `let r = if c: Ok(s.len()) else: Err("e" ++ "")` died with
"BUG: `:?` reached MIR for type 0" (MirLower.lower_debug_write_place):
post-Sema type 0. With no outer demand each constructor arm is checked
alone, `Ok(a)` fixes only A and `Err(b)` only B, so both arms are the bare
`Result` enum; SemaCheck.resolve_contextual_join's
merge_contextual_owned_join_types agreed on that bare enum (lhs ==
rhs) and the binding held an uninstantiated type. `Some(x)`/`None` joins
because `Some(x)` alone is already an instance and the
instance-beside-base rule takes it.

resolve_contextual_join now, with no outer demand and a bare-`Result`
join, names `Result[A, B]` from the reaching arms
(infer_result_join_from_variant_arms): A is the join of the `Ok` arms'
payload types, B of the `Err` arms', each by the same owned-join rule;
the arm constructor nodes are retyped to the instance. Any arm that is
not a one-payload Ok/Err call, or arms that fix only one side, leave the
join as before. The payload type comes from check_call, which now
records a variant constructor's checked payload type on the payload node:
check_expr does not self-record every node kind, and a `++` payload read
back as 0 (bisected: `Ok(2) | Err("e")` joined, `Ok(2) | Err("e" ++ "")`
did not).

behav_1856_unannotated_ok_err_join.w: the issue's `if` and `match`
spellings, both arms each -> Ok(2) / Err("e") / Ok(2) / Err("x"),
debug-alloc leak count 0.

* A generic function used as a callable value is instantiated at the expected function type in Sema (#1857)

`with check` on `apply(identity, 3)` (apply: fn(fn(i32) -> i32, i32)) said
"invalid MIR before codegen: call argument 0 is Unit but the callee
parameter is not"; `let g: fn(i32) -> i32 = identity` said "use rvalue type
is incompatible with assign destination". The wrong line was
SemaCheck.check_ident: a visible generic function name in value position
hit `if self.generic_fn_node_for_symbol(sym) != 0 ...: return 0` — no type,
no instantiation, no diagnostic — and MirLower emitted an untyped CK_FN of
the template, which codegen could not find (the #1859 fallback).

§12: the name is instantiated at the expected callable type. check_ident
now, when an expected `fn(P..) -> R` is in force, runs check_generic_call
with the expected parameter types (the one specialization path a call
takes), records the instance on the node (resolved_call_mono_syms), types
the name as the instance's callable type — built from its concrete
signature, since a specialization's sig carries no function type — and
marks it a callable value (D65) after checking assignability. With no
expected function type the name is refused loudly ("needs an expected
function type to instantiate it"), never typed 0. MirLower's identifier
lowering takes the recorded instance for the CK_FN constant, and codegen's
CK_FN branch emits that specialization on demand
(ensure_concrete_mir_function) before the #1859 BUG.

behav_1857_generic_fn_as_callable_value.w: both spellings -> 3 / 7,
debug-alloc leak count 0.

* A type-parameter frame restores its bindings last to first; a parameter listed twice no longer leaks (#1967)

`fn Box.new[T]` binds `T` twice: the owner's `Box[T]` and its own `[T]`
(check_generic_method_body_concrete pushes owner and function parameters,
tp_syms = [T, T, Self]; lldb at SemaCheck.w check_fn_body_concrete's
install loop: `memory read tp_sym` -> 163 163 42). The frame saved each
binding and then installed the concrete one, so the second save read the
first install (Option[str]), and the restore ran first to last: the
caller's `T` came back, then the second save put Option[str] over it.
After `Box.new(Some("maybe".clone()))` the module's `enum T` was bound to
Option[str] in named_types. #1967 rightly put the scoped tier ahead of the
module candidates, which exposed it: lldb on Sema.scoped_type_binding
(condition named_tid != 0, saw_recorded = 1, saw_named_tid = 0) stops at
`let kids: Vec[Box[T]]` in main with sym=163 named_tid=550, and
da_box_pointee_dropped_by_type failed "unknown method 'Leaf' for type
'Option[str]'".

The three frames that install type-parameter bindings into named_types
(SemaCheck.check_fn_body_concrete, ComptimeEvaluator
.restore_generic_substitutions, MirLower's concrete-specialization
lowering) restore last to first, so the first save, the caller's, wins.

behav_1967_type_param_frame_restores_in_reverse.w: "unknown method 'Leaf'
for type 'Option[str]'" -> `some 1 leaf x`. behav_1967 stays `0 0 4 15`;
da_box_pointee_dropped_by_type: leak count=0.

* A default trait method's MIR terminator goes where the builder is, after a statement that ends in its own block

CodegenTraits.generate_default_trait_method_for_impl emits the default
body with its own MIR loop, which tested `wl_get_bb_terminator(dtm_llbb)`
— the MIR block's first LLVM block — before emitting the terminator.
Checked arithmetic ends its statement in `arith.ok`, after terminating that
first block with the overflow branch, so the terminator was skipped and
`fn total(self: &Self) -> i32: self.size() + 1` failed LLVM verification
("Basic Block in function 'P.total' does not have terminator! label
%arith.ok"; main's installed compiler too). The loop now reads the insert
block, as the function, closure and global-initializer emitters do.

Found behind the #1862 regression: with a trait's contract return
published before default bodies are checked, `self.size() + 1` reaches
codegen at all.

behav_trait_default_checked_arith_tail.w: LLVM verification failure ->
`3 6`.

* A trait's contract return is published before default bodies are checked; `self.name() ++ "!"` is not a Unit operand (#1862)

#1945 publishes the return a trait declares onto an impl's unannotated
method "before any body is checked", but from check_bodies, while
collect_declarations had already checked each impl's default bodies
(check_trait_default_method_bodies). There `self.name()` read
Person.name's unpublished signature, Unit, and #1862's
reject_unit_operand rightly refused it (lldb: SemaCheck reject_unit_operand
<- check_binary <- check_trait_default_method_body_for_impl <-
check_trait_default_method_bodies <- collect_declarations). The type was
determined, just not yet published; main's compiler typed the same call
Unit without the check, and `self.size() + 1` there was "arithmetic
operator requires numeric operands".

collect_declarations publishes the contract returns once every signature
exists, before the default bodies; check_bodies no longer does.

behav_1862_trait_default_reads_contract_return.w: "operand of `++` is
Unit" / "operand of `+` is Unit" -> `Ada! 3`. err_1862 still reports
"`test_label` returns Unit"; da_trait_default_tail: leak count=0.

---------

Co-authored-by: Eric Hartford <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant