Skip to content

Sema/MIR: for over a non-iterable is refused; one-clause for over Option/Result is a comprehension (§13.6a); &dyn over str/int/float/bool; empty f-string spec; caller-place parameters; D65 loop/range/callable facts (#1828 #1823 #1818 #1822) - #1893

Merged
ehartford merged 8 commits into
ex-cinteropfrom
fix-misc
Sep 29, 2026

Conversation

@ehartford

@ehartford ehartford commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Stack #1898, layer 8. Closes #1828, #1823, #1818, #1822. Plus three D65 moves: a function used as a callable value is Sema's fact (fn_callable_values); MIR reads every range's and loop's element type from Sema instead of re-deriving. Pre-existing defects found and filed: #1837, #1856, #1857, #1858, #1859. Gate, :deep-debug-tool-tests (violations=0) and :drop-audit (213 cells, 0 regressions) green on the layer before folding; the fold's keep-both resolutions re-verified by :dev and the callable/comprehension/#1829/#1831 tests. Open question for Eric: for x in opt with an index binding or as a collection-comprehension clause is refused per §13.6a; making [x for x in opt] mean zero-or-one is a spec addition. Draft until the stack battery is green and posted.

@ehartford
ehartford added this pull request to stack #1898 September 29, 2026 05:03
@ehartford ehartford changed the title fix misc Sema/MIR: for over a non-iterable is refused; one-clause for over Option/Result is a comprehension (§13.6a); &dyn over str/int/float/bool; empty f-string spec; caller-place parameters; D65 loop/range/callable facts (#1828 #1823 #1818 #1822) Sep 29, 2026
Eric Hartford added 8 commits September 29, 2026 14:40
SemaCheck.infer_for_element_type ended in `self.ty_i32 as i32`: any
iterable it did not recognize — a str, an integer, a struct, Option, a
&str — bound the loop variable as i32, check passed, and MIR lowering
failed (NK_FOR, "MIR lowering failed ... AST codegen was removed"). A
type whose next() returns no Option (a `next() -> i32`) stepped through
the same fallback and the loop printed nothing.

The query now answers 0 (not iterable), and check_for and comprehension
clauses report it (§13.5): a named error for a next() that returns no
Option (§13.2), and for a type with an `.iter()` method a loud "not
implemented yet (#1837)" for §13.5's implicit .iter(), which only Vec,
HashMap and BTreeMap get today (filed as #1837; previously the same MIR
failure). The spec defines no iteration over str, so Sema refusing is the
conforming answer.

Tests: test/compile_errors/err_1828_{for_over_str,next_without_option,
comprehension_over_str}.w, each failing on 355c20b (check ok) and
passing on stage1. Custom next(), iterator bindings, range bindings,
generic bodies over `I: Iter[str]` and explicit `.iter()` still run.

Fixes #1828
…pec text is refused (#1823)

Parser.parse_format_spec_text returned poisoned_expr() for an empty spec
with no diagnostic, against its own contract ("or 0 if empty"); the
f-string lowering read the poisoned node as an NK_FSTRING_SPEC, so `{h:}`
formatted a str with precision 0 (printed nothing) and `{n:}` was refused
as "precision requires float or string type".

§15.4.1: `spec := [[fill]align][sign]['#']['0'][width]['.' precision][mode]`,
"All fields are optional"; each field's default is the default display,
so `{x:}` is `{x}` (Rust: format!("{:}", 1.0f32) == "1"; Zig's
Placeholder.parse takes `{:}` with every option null). The empty spec now
returns 0, the no-spec node.

The same function silently dropped any text past the grammar (`{h:q}`,
`{h:>8s!}` printed as if the spec ended early); that text is now a named
error at its span. A sweep of every tracked .w file found no spec outside
the grammar and no `{x:}`. Boy-scouted the function's byte chains to char
literals.

Tests: test/behavior/behav_1823_fstring_empty_spec.w (str, int, float,
bool, enum) and test/compile_errors/err_1823_format_spec_unknown_mode.w,
both failing on 355c20b and passing on stage1.

Fixes #1823
… pointer (#1818)

MIR lowers `show_dyn(&a)` as `_2 = ref(shared, _1)` into a `&dyn Speak`
local; codegen's RK_REF branch builds the fat pointer in
mir_build_dyn_trait_value_from_ref_place, which asks
mir_dyn_arg_info_from_sema_type for the concrete impl type. That answer
came only from mir_nominal_sym_from_sema_type (structs, enums, generic
insts), and its LLVM-type fallbacks found nothing for a builtin, so the
function returned the thin pointer; the store into the {ptr, ptr} local
then went through coerce_value_to_type, which read pointer -> {ptr, ptr}
as a fn -> closure coercion and aborted in gen_fn_to_fat_ptr_thunk ("BUG:
function-value adapter has no FnAbi descriptor").

mir_dyn_concrete_sym_from_sema_type answers the nominal symbol, else, for
str/integer/float/bool, the symbol Sema selected the impl with
(type_symbol_for_bounds, the key of Sema's own dyn obligation check); the
impl's vtable is keyed by that name. Both dyn-info derivations read it.
When Sema typed the destination `&dyn`, a thin pointer falling out of the
ref-place builder is now a named BUG instead of the adapter's.

lldb could not launch in this session (debugserver attach blocked), so the
path is shown by the MIR dump and the only RK_REF codegen branch.

Test: test/behavior/behav_1818_dyn_over_builtin.w (&dyn Speak over str
and i32, &dyn Display over str and i32, a `let d: &dyn Speak = &a`
binding): aborts on 355c20b; on stage1 prints the expected lines,
audit:all ok, debug-alloc leak count=0.

Fixes #1818
…f re-deriving ownership (#1822)

validate_ownership_body's #1488 rule treats a local as owned when any
drop targets it and reports it still Init at return as a leak. A `mut fn`
receiver replaced whole (`self = self ++ "!"`) drops the old value, so its
local has a drop, and is Init at return: that is the contract, since the
receiver is the caller's place (SHARE-PLACE in --dump-abi) and the caller
drops it. audit:all reported the leak for str and struct receivers alike;
`run --debug-alloc` shows leak count=0.

MirLower.lower_fn_with_sig already decides per parameter that the callee
does not own it (borrowed receiver, share-place param, Drop body's self)
and schedules no drop. That decision is now recorded on the body
(MirBody.local_is_caller_place, set by mark_caller_place_local, shown as
[caller-place] in --dump-mir) and the leak rule skips those locals, the
way it skips closure captures and global proxies: one owner of the fact.

Test: test/behavior/behav_1822_mut_receiver_replaced_whole.w (str and
struct receivers), with an audit:all "violations=0 ok" expectation in
deep-debug-tool-tests. audit:all fails on 355c20b and passes on stage1.

Fixes #1822
… the yield re-wraps in its own carrier

§13.6a: "The first clause determines the carrier family ... The statement
form omits `yield` and runs its body only when every clause succeeds."
Nothing requires a second clause, so `for x in opt:` is a one-clause
comprehension: the body runs once on Some/Ok and not at all on None/Err,
and `for x in opt: yield e` is the expression form. It was refused as not
iterable (#1828; before that it passed check and failed MIR lowering).

Only Sema knows the iterable's type. The parser records, beside every
single-clause `for` whose iterable is not a range literal (and binds no
index), the one-clause reading built by the same builder the multi-clause
form now uses (AstPool.build_comprehension_match; the comptime transform
copies it and rebuilds it over a cloned loop). check_for adopts it for an
Option/Result iterable (for_carrier_matches) and checks that match with the
iterable already typed (prechecked_match_subject), so the comprehension is
the match it is equivalent to: consumption, views, D32 field refusals and
the `_` drop of a failed clause are match's own. MirLower lowers the match
Sema recorded.

The expression form was broken for the multi-clause form too: the failure
arm re-returned the clause's own value, which joined the result only when
the yield kept the payload's type (the spec's own `User` -> profile ->
`str` example did not compile), and without an expectation `_Payload(e)`
became Some even in a Result comprehension. Sema now records each
comprehension's chain (root clause, inner clauses, yield wrap) with its
carrier and shared Err type, types the yield wrap as Some(E)/Ok(E) of that
carrier, and types each clause's failure value as the result carrier; MIR
re-wraps it (None, or Err moving the clause's error). Clauses must share
one Err type; a refutable Result clause pattern is refused (an unmatched Ok
has no Err, the reason Result comprehensions take no guard). This replaces
the dynamic current_for_comprehension_carrier, which would also have leaked
into a comprehension nested in a statement body.

Tests: test/behavior/behav_for_one_clause_comprehension.w (Option/Result x
statement/expression x Some/None/Ok/Err, a yield of another type, a place,
Option[&V] from a map, a tuple pattern, for-else),
test/behavior/behav_for_comprehension_yield_types.w (the spec example,
Result chains), test/compile_errors/err_for_one_clause_{consumes,index}.w,
err_for_comprehension_{err_types_differ,result_refutable}.w: all fail on
d6d71611, pass on stage1; debug-alloc leak count=0; audit:all and
audit:resolution clean. The not-iterable refusal still fires for
non-carrier types (err_1828_*).
…onger reads it off LLVM shapes

Codegen.coerce_value_to_type turned any pointer meeting an LLVM `{ptr, ptr}`
into a function-to-closure thunk (gen_fn_to_fat_ptr_thunk), and the CK_FN
constant evaluator coerced a function to whatever struct type was expected.
That reads a meaning off LLVM representation (D65); it is how #1818's `&dyn`
data pointer became a function thunk.

Sema decides it where a function name is checked as an expression
(check_ident; a callee resolves in check_call and never gets here): typed
its With callable `fn(...)` it records fn_callable_values, typed an
expected `extern "C" fn` it does not. MirLower marks that constant
(CK_FN d1 = 1, `const callable fn` in --dump-mir), and codegen builds the
FnAbi adapter where the constant is evaluated. A pointer coerced to a
`{ptr, ptr}` with no such fact is now a named BUG.

Test: test/behavior/behav_fn_item_callable_values.w (a function as a `fn`
argument, a let with and without annotation, a struct field, an
`extern "C" fn` argument, Vec[fn] elements): passes on d6d71611 and on
stage1 — a representation change, so no output differs; debug-alloc leak
count=0; audit:all and audit:resolution clean; #1818's &dyn test still
passes. A generic function as a value (`apply(identity, 3)`) is invalid MIR
on d6d71611 and still is: filed separately.
…ounds is a phase bug

check_expr now records each range expression's type (4b582299, #1828).
MirLower.fallback_expr_type still rebuilt a range type from its bounds
(find_range_type of the start's type); over `&T` element-view bounds that
found no range, answered void, and a loop counter took the old i32
for-element fallback. With Sema recording every range, reaching that
rebuild means a range Sema never typed reached MIR: a named phase bug.

The range-value lowering in lower_expr took its element type (the implicit
0 of an omitted start) from a bound's own type, `&T` over an element view;
it now takes Sema's range type's element type.

No output changes — the observable fix landed with #1828
(test/behavior/behav_1828_range_over_element_views.w, which passes here);
audit:resolution clean on the loop and range programs.
…e-deriving one

check_for bound each loop's pattern to for_loop_element_type (which
special-cases `v.iter()`), and each comprehension clause's likewise; MIR
then recomputed an element type from whatever type each lowering held
(infer_for_element_type_frozen over the iterable, a map, a storage Vec, a
range), and lower_for_iter_ref_place rebuilt `&T` and fell back to i32 when
it found none. Two derivations of one fact (D65).

Sema now records it (for_elem_types: keyed by the NK_FOR node, and by a
comprehension clause's iterable node), and every loop lowering reads it
(loop_element_type / clause_element_type, a named phase bug when missing).
The frozen twin infer_for_element_type_frozen, its per-type cache and that
cache's coverage audit are gone; preregistration still calls
infer_for_element_type for each type, because the element views it builds
(`&T`, map traversal tuples) are types MIR looks up later.

No output changes; the for/range/comprehension/closure behavior tests pass
and audit:resolution and audit:all stay clean on them.

docs/with-abi.sha256 is re-recorded: TypeLayout.w lost the frozen twin, a
query, not a layout rule, so the ABI convention (WITH_ABI_VERSION) is
unchanged; every .wo bundle rebuilds once.
@ehartford
ehartford marked this pull request as ready for review September 29, 2026 18:57
@ehartford
ehartford merged commit cd9a52d into main Sep 29, 2026
@ehartford
ehartford deleted the fix-misc branch September 29, 2026 19:03
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.

for r in s over a str passes check and fails MIR lowering (NK_FOR)

1 participant