Skip to content

Sema: one arity check for every call path (#1973); owned ?? / unwrap_or results borrow into &P (#1974); C fn types can't carry arrays (#1975); facade audit reads acceptance's fact (#1977); field read / struct literal on a non-struct T refused at instantiation (#1981, #1982) - #2001

Merged
ehartford merged 10 commits into
mainfrom
wave-sema2
Oct 3, 2026

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

Campaign wave. One commit each; root-cause line in each message; fixtures red→green. Per spec §11.2 ("rely on instantiation-time checking instead") #1981/#1982 fire at the instantiation, not the definition. #1977: the audit now checks facade_param_receives (the fact acceptance's mask is built from) via facade_effect_source_param; acceptance unchanged (st.step(); b.changes() still refused, pinned); also fixed: the producer preserves param N help named the wrong C parameter. #1982 also types a name for a generic struct instance (an alias, or T bound to one) as that instance — std.sync's AtomicI64 { val } had worked only through the silent untyped path. Gate (incl. deep-debug-tool-tests) and drop-audit green; a 241-fixture comparison against the pre-fix stage1 differs only where intended.

Eric Hartford added 8 commits October 3, 2026 00:00
`with check` accepted `self.make(3)` against `mut fn make(a, b)` and the
program failed LLVM verification at build ("Incorrect number of arguments
passed to called function!"). Route: D65 acceptance, `with analyze`.
`analyze repro.w audit:resolution` on the pre-fix stage1:

    violation: resolution: Ev.run at a1973.w:4:26 node 9658: MIR passes 2
    argument(s) to `Ev.make`, Sema's signature takes 3 (D65; #1639's
    silent case)

Lines: SemaCheck.w check_method_call_parts, the `if sig_idx >= 0:` branch
of a method with a registered signature, compared argument types in a
loop that stopped at the parameter count (`if mc_plain_pi >= mc_plain_pc:
break`) and had no count check at all; only check_call's free-call path
compared counts. check_generic_method_call, check_dyn_trait_method_call,
check_concrete_trait_method_call and check_qualified_extension_call each
had their own `arg_count != expected` ("wrong argument count", defaults
ignored). Same class: `fn Item.tag()` (a function of the type) called as
`i.tag()` passed one argument to a zero-parameter function.

Fix: check_call_arity, one rule — supplied arguments (after named and
default resolution) plus the receiver against the signature's
[required, declared] range, implicit parameters named, counts shown
receiver-excluded — read by the free call and all five method paths. A
function of the type called on a value is named as such. And
resolve_method_implicit_default_args no longer stores a partial argument
list when a required parameter has no argument and no default (it stored a
0 slot, settling the arity, and MIR passed Unit: "call argument 1 is Unit
but the callee parameter is not").

Fixtures (red on the pre-fix stage1, green now):
err_1973_method_too_few_args, err_1973_method_too_many_args (pre-fix:
`ok`), err_1973_type_function_on_value (`ok`),
err_1973_method_default_too_few (invalid MIR). `with-stage1 check
src/main.w` is clean under the new rule.
…ef (#1974)

`peek(read_file(p) ?? "")` with `fn peek(s: &str)` was refused: "`??`
expression of type `str` cannot produce `&str`", where `peek(make())` is
accepted (§3.8 auto-ref; D22: an eliminator does not change what the
eliminated value is). Route: Sema join decision, read in place.

Line: every default join — check_binary's OP_DEFAULT, Option/Result
`unwrap_or` (check_method_call_parts) and `unwrap_or_else`
(option/result_combinator_return_type) — took the enclosing expectation
as its demand: `let join_expected = if self.has_expected_type != 0:
self.expected_expr_type ...`. At a `&str` parameter that is `&str`;
resolve_contextual_join then set final_type to it and refused the owned
payload arm in emit_contextual_join_mismatch. The #1754 rule for if/match
joins at a `&T` parameter (join_meets_ref_param) does not cover these
joins, and extending it would refuse `first(&v) ?? ""` (a view payload
with a literal fallback), which is accepted today.

Fix: default_join_demand, read by all five sites: a default join whose
carrier payload is owned produces an owned value, so under a shared `&P`
demand its demand (and its fallback's) is `P`, and the enclosing call
borrows the result as it borrows any owned argument. A view payload keeps
the reference demand, so the view join and its origins are unchanged. No
accepted program changes meaning; only these refusals become borrows.

Fixture behav_1974_eliminator_owned_at_ref_param: red on the pre-fix
stage1 (the error above), green now with `??`, Option/Result `unwrap_or`
and `unwrap_or_else` over owned str and i64 payloads at `&str`/`&i64`
parameters, and the view-payload case; `run --debug-alloc` leak count=0,
as is the issue's `read_file(..) ?? ""` repro.
`let f: extern "C" fn() -> [u16; 2] = arr` checked `ok`; emit-c refused it
because no C function type returns an array (C11 6.7.6.3p1: "a function
declarator shall not specify a return type that is ... an array type"),
and C adjusts an array parameter to a pointer (6.7.6.3p7), so `[T; N]` by
value has no C ABI. Route: Sema type resolution, read in place.

Lines: SemaCheck.w resolve_type_expr, the NK_TYPE_FN/NK_TYPE_EXTERN_FN
branch, resolved an extern fn type's parameter and return types with no
check; SemaDecl.w collect_extern_fn did the same for an `extern fn`
declaration (`extern fn get_pair() -> [u16; 2]` also checked `ok` — the
same C function, so the same rule).

Fix: reject_c_abi_array, one rule read by both: an array return or
parameter is refused at its type node with the fix (return a struct
wrapping the array or take an out-pointer; take `*const T` or a struct for
a parameter). c_import declarations are unaffected: clang hands them the
adjusted pointer types.

Fixtures (pre-fix stage1 printed `ok` for each):
err_1975_extern_fn_type_returns_array, err_1975_extern_fn_type_array_param,
err_1975_extern_fn_decl_returns_array.
… is checked through its C source (#1977)

`with analyze <prog> audit:all` reported, for a program that calls a
method on a borrowed resource (`st.database()` -> BorrowedDatabase,
`b.changes()`):

    violation: contract: the rendered call of 'sqlite3_changes' invalidates
    views of its parameter 0, which holds no modeled resource; the effect
    names the wrong parameter (#1674, §16.2b.14)

while acceptance (correctly, D51 §38 / spec §16.2b.7: no `preserves`,
unknown effect means invalidate) poisons views of that receiver. Route:
`with analyze ... audit:all` on the repro, then the audit's line.

Line: AnalysisContract.w, the rendered-effects audit asked
`facade_type_holds_resource(sig_param_type(e.sig, pi))` — acceptance's
question "is this binding a resource rather than a view" — and a
`Borrowed<R>` (or `Failed<R>`, #1834's case) receiver reads as holding
none. The mask it audits was built from a different fact:
facade_touch_params_mask over the C parameters that receive a resource
(facade_param_receives), projected onto the presented ones.

Fix (D65, one owner): the audit maps each presented bit back to its C
parameter with facade_effect_source_param — the mapping acceptance's
poisoning names — and requires that C parameter to receive a resource.
Acceptance is unchanged: `facade_type_holds_resource` is not touched, and
`let b = st.database().unwrap(); st.step(); b.changes()` is still refused
(err_1977_borrowed_resource_after_step). Whether `step` may leave a
borrowed handle valid is a facade fact the grammar has no clause for
today (only `preserves param N`, which would also keep the column views
alive); briefed, not inferred.

Found doing so: facade_effect_source_param returned the presented index
for every resource operation, so a producer's projection (its out slot
gone, an init's preinit parameters ahead) read as the identity. For
`st_new(db *d, st **out, int flags, other *o)` presented as
`d.st_new(flags, o)`, acceptance's help named `preserves param 2`
(`flags`) for a view of `o` (C param 3), and the audit flagged
ok_effect_projection. The producer loop now records each presented
parameter's C source on its FacadeCallEffect (param_sources), and
facade_effect_source_param reads it first.

Fixtures: contract/ok_borrowed_resource_effect (pre-fix: violations=1
FAILED; now violations=0 ok); compile_errors/err_1977_borrowed_resource_
after_step (acceptance pinned, refused before and after);
err_c_facade_producer_on_parent_effect gains the `preserves param 3`
expectation (pre-fix help said param 2). Every test/contract ok_ fixture
and the three behav_sqlite_facade_* fixtures report violations=0 under
audit:all.
…yped 0 (#1981)

`fn f[T](x: T) -> i32: x.v` called as `f(3)` checked `ok` and printed 0.
Route: `with analyze`: the pre-fix stage1 records the specialization
(`sema specialization f__sema__… T=ty3`, i32) and no diagnostic.

Line: SemaCheck.w check_field_access ends `0` after the struct, generic
instance, tuple, array/slice/str and enum branches: any other receiver
type (an integer, here the i32 instantiation of T) returned the unknown
type without a word, and MIR read a zero.

Fix: that fall-through reports `unknown field 'v' for type 'i32'` (except
for an error type or Never, whose cause is already reported); inside a
generic instantiation the help says the body is checked per
instantiation. Per §11.2 ("Generic functions and types may omit both
inline bounds and where clauses and rely on instantiation-time checking
instead") and §17's deferred checking, the error belongs to the
instantiation; an uncalled `f` still checks, as the spec says.

Fixtures: err_1981_field_of_scalar_instantiation (pre-fix `ok`, now the
error); behav_1981_bounded_generic_accessor (a bounded T through its
trait method, and an instantiation whose type has the field) stays green.
…a generic instance it is typed (#1982)

`fn mk[T](x: T) -> T: T { v: 1 }` called as `mk(3)` passed Sema and
failed as invalid MIR ("place _2.f24 projects component 24 of a scalar
(ty=3)"). Route: the post-Sema MIR validator names it (D65: post-Sema
invalid MIR is a compiler bug), then the Sema line.

Line: SemaCheck.w check_struct_literal, `if tid != 0:` with a resolved
type that is not TY_STRUCT fell to the final `0`: the literal was left
untyped and MIR lowered it by name. The same silent path served a literal
through a name for a generic struct's instance: std.sync's
`AtomicI64 { val: value }` (`AtomicI64 = Atomic[i64]`) — making the
first fall-through loud refused it (behav_container_arg_widening).

Fix: a name for a generic instance (an alias, or a type parameter bound
to one) is rebound to its base struct, as `Self` already was, and the
literal is checked against and typed as that instance; any other non-struct
name is refused at the literal (`struct literal of `T`, which is `i32` in
this instantiation and not a struct`), per instantiation (§11.2).

Fixtures: err_1982_struct_literal_of_type_param (pre-fix invalid MIR, now
the Sema error); behav_1982_generic_instance_name_literal (alias literal,
a type parameter bound to an instance, `atomic_new`) prints `1 7 42`;
behav_container_arg_widening stays green.
…2002)

`b.get()` against `fn get(k: i32 = 2)` in `impl[T] Bx[T]` was refused
("wrong argument count" before #1973, "expects 1 argument(s), found 0"
after); a generic method on a non-generic type was the same. Route: `with
analyze`: the method-registration fact for the call is `Bx.get ...
sig=-1 registry=generic`.

Line: SemaCheck.w resolve_method_implicit_default_args began `if sig_idx
< 0: return arg_count`. A generic method has no registered signature
(its parameters are its declaration's, as check_generic_method_call reads
them), so no default was ever filled; check_method_call_parts also passed
it `lookup_method_fn`, which is 0 for a generic method. And
fn_min_expected_arg_count read only fn_decl_nodes, so the refusal named
the declared count instead of the range the defaults allow.

Fix: for a call with no signature the defaults come from the generic fn
node's meta (lookup_generic_method_fn, generic_fn_node_for_symbol); an
implicit parameter of a generic method has no resolved type to match a
binding against and stays missing (reported). fn_min_expected_arg_count
reads the generic fn node too.

Fixtures: behav_2002_generic_type_method_defaults (with and without the
defaulted argument, on a generic type and as a generic method of a plain
type): red on the pre-fix stage1 ("method 'Bx.get' expects 1 argument(s),
found 0"), prints `2 5 12 30` / `7 9` now, debug-alloc leak count=0.
err_2002_generic_method_default_too_few: `expects 1-2 argument(s), found
0` (pre-fix said `expects 2`). generic_default_args and the #1973
fixtures stay green.
On wave-sema2 rebased onto 0c10fd6, the installed compiler and the pinned
seed refused `with check src/main.w`:

    error: cannot mutate `self` while `count` is a live view into it
     --> src/MirLower.w:4759  (update_string_fields_after_aggregate)

with no line of MirLower.w changed. Route: lldb on with-stage1 (it
reproduces), breakpoints on Sema.later_use_of / scan_block_frame /
find_symbol_use_after_in_span for after_node 1312314. MirBody.new_field_place
and MirBuilder.struct_field_type have the same effects on both trees
(`analyze ... explain:effect`: [write] and [read]), so no effect summary
changed. The use came from a different file: later_use_of reached the
function body's tail, the `for i in 0..count` loop, and
find_symbol_use_after_in_span(root=that for, sym=count, after=251063) —
after the subtree prune passed, because the range does use `count` — swept
every AST node for an NK_IDENT `count` with byte start in (after, root_end].
Offsets are per file; the hit was Sema.types_identical's
`for i in 0..count` (Sema.w:5338, byte 251065), which the four-line
FacadeCallEffect comment added in #1977 moved into MirLower.w's window.

Line: SemaCheck.w find_symbol_use_after_in_span, the window scan
`if self.ast.kind(candidate) != NodeKind.NK_IDENT or ...` compared
offsets without the file. Its comment said nodes carry no file identity;
they do (Ast.file, which diagnostic_node_span already reads).

Fix: the scan keeps only candidates in root's file. The pinned seed and
the installed compiler carry the old scan, so this tree must also not
trigger it until the next seed: the FacadeCallEffect.param_sources comment
in Sema.w is folded onto its line (the original text checks `ok` under the
fixed stage1; verified on 9c9a45ef in a separate worktree).

Fixture: behav_view_use_scan_own_file + lib/phantom_count_peer.w, whose
`count` is padded to land inside the fixture's loop after the mutation:
refused by the installed compiler and the seed, prints 3 under the fixed
stage1; with the peer replaced by a local fn the installed compiler
accepts it (the control).

`with check src/main.w` (installed and seed): ok. `analyze src/main.w
audit:phase`: violations=8, the same eight CCodegen -> Sema
push_specialization_subst/pop_generic_subst/type_layout_* re-entries as
origin/main da08b14 reports; none in this change.
Eric Hartford added 2 commits October 3, 2026 00:20
The battery on stack #2013 read test/compile_errors/
err_1500_producer_lend_renders_constructor_only.w red: it expected "wrong
argument type in call to 'Database.prepare'", and the check now reports

    error: method 'Database.prepare' expects 2 argument(s), found 3
    error: undefined variable        (line 35, `print(rc)`)

The first is #1973's arity rule and is the precise refusal: the fixture
passes an out slot as a third argument to the producer's two-parameter
receiver form `prepare(sql, tail)`, so the count fails before any argument
type is compared. The fixture's intent ("a call passing an out slot is
refused") holds; its expectation becomes the arity message.

The second is a cascade. Line: SemaCheck.w check_method_call_parts,
`if not self.check_call_arity(...): return 0` — the refused call was
untyped, so `let (rc, _) = d.prepare(...)` bound nothing and the later use
of `rc` reported an undefined variable. The free-call path reports and
keeps the callee's type. Fix: the refused method call returns the
method's declared result (substituted for a generic instance receiver);
its dependents type, and the one real error stands alone.

Fixture: err_1500_producer_lend_renders_constructor_only now expects the
arity message and `expect-check-fail-not: undefined variable` (before this
commit the check printed both errors; now exactly the one).
contract-view-tests requires every clean test/contract fixture to carry
its `contract` view as a checked-in .expected file; the #1977 commit added
ok_borrowed_resource_effect.w without one, and the stack's battery
reported "a clean fixture needs a checked-in
test/contract/ok_borrowed_resource_effect.expected snapshot".

Generated the way the target reads it (build.w
run_contract_view_tests_action: `<compiler> analyze
test/contract/<fixture>.w contract` from the project root), with this
tree's stage1, and read: the BorrowedDatabase view from sqlite3_db_handle
dependent on the statement, sqlite3_changes and sqlite3_step invalidating
their receivers' views (no `preserves`), `contract-audit: violations=0 ok`.
@ehartford
ehartford marked this pull request as ready for review October 3, 2026 07:37
@ehartford
ehartford merged commit 376af1d into main Oct 3, 2026
@ehartford
ehartford deleted the wave-sema2 branch October 3, 2026 07:38
ehartford added a commit that referenced this pull request Oct 3, 2026
…orkarounds (#2020)

* Seed: darwin nightly-20261003-local-1-c884c1c2a17c

Cut from main c884c1c (stack #2001/#2010 merged); builds main from a
fresh checkout to a stage2 == stage3 fixpoint. Workflow pins rewritten by
tools/bump_seed_pins.w.

* Sema: restore the FacadeCallEffect.param_sources comment the old seed forced onto one line

#2001 folded it so the c95ae12 seed's cross-file view-use scan would not
refuse src/main.w. The new seed carries #2001's own-file scan:
`src/main check src/main.w` is ok with the original text.

* ComptimeTransform: a user derive's source is moved out, not cloned (stale D32 seed workaround)

The clone stood in for `move` while the seed enforced the retired §2.4
Drop-owner condition. The new seed accepts `move evald.value.text` on a
`var` base (D82). Stage1 (:dev) runs spec_ss17_3_user_defined_derive and
every behav_derive_* / derive_* fixture to its expected output, and still
refuses err_user_derive_bad_output.

* wrap_diag_spans: the splice helper works around #2023, not a frozen seed

Inlining it under the new seed (and its stage1) fails codegen:
`wrong argument type actual=ptr expected=i64 fn=apply_edits` — the
str.slice call path passes a Vec element view where it takes i64. The
comment now names the real bug; the helper stays until #2023 is fixed.

* build: drop the legacy "armv8" arch spelling (stale seed workaround)

comp_arch_is_aarch64 said to delete its "armv8" branch after the next
reseed. Every pinned seed (darwin c884c1c, linux-x86_64 2e8defa,
linux-aarch64 v0.15.2.0, windows-x86_64 bd6e00d, windows-aarch64
v0.15.2.1) routes arch() through with_sysinfo_arch -> rt_sysinfo_arch, and
each of its rt/*_aarch64.w returns "aarch64"; none produces "armv8". So the
predicate and the separate Windows/Linux `armv8 or aarch64` checks in
build.w and build/*.w become plain `== "aarch64"`. build.w and
lib/std/build.w check ok under out/release/bin/with and the seed.

* Sema: loop_break_flat's comment states the design, not a seed limit

The flat Vec[i32] began as seed compatibility (#613, no Vec[Vec[i32]]);
the seed limit is gone (Sema.w already holds Vec[Vec[...]] fields), but the
layout stays: loop regions are strictly LIFO, and loop_entry_flat shares
each frame's offset into the same shape.

---------

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