fix(codegen): replay loop binders in synth_with_extras (closes #47)

A `let`-bound `loop` whose body references one of its own loop binders on
the non-recur exit passed `ail check` but failed `ail build` with
`unknown variable`. The fieldtest surfaced this with an owned RawBuf loop
binder, but the trigger is element-type-independent.

Root cause: the Term::Loop arm of synth_with_extras (the type-replay walk
the let-lowering runs via synth_arg_type on every let value) descended
into the loop body WITHOUT adding the loop binders to `extras`, unlike the
Term::Let arm which pushes its binder. A loop binder referenced on the
non-recur exit then resolved to UnknownVar during the type replay.

Fix: clone `extras`, push each loop binder's (name, ty), and thread the
augmented extras into the recursive synth of the body — mirroring the
Term::Let arm exactly. General fix; a plain Int let-bound loop that
references its binder also builds now.

This restores check<->codegen agreement for the natural fill-loop (thread
an owned buffer of runtime length through a loop/recur, one RawBuf.set per
iteration) — the way to populate a buffer whose length is not a fixed set
of literal indices.

Surfaced by the raw-buf fieldtest (finding B2, docs/specs/0058).
RED-first: loop_let_bound_binder_reference_builds.
This commit is contained in:
2026-05-30 17:14:07 +02:00
parent 744ad41e47
commit db710b1a73
3 changed files with 58 additions and 1 deletions
+16
View File
@@ -119,6 +119,22 @@ fn loop_recur_infinite_loop_compiles() {
);
}
/// RED for fieldtest finding B2 (raw-buf milestone, Gitea #7):
/// a `loop` whose result is `let`-bound and whose body references one
/// of its own binders on the non-recur exit must BUILD, not only
/// `check`. The `Term::Let` codegen lowering replays the value's
/// AILang type via `synth_arg_type`; that replay walk
/// (`synth_with_extras`) must descend through `Term::Loop` with the
/// loop binders in scope — as it already does for `Term::Let` — or the
/// binder reference resolves to `UnknownVar`, breaking check↔codegen
/// agreement. Element-type-independent: the fieldtest hit it with an
/// owned `RawBuf` binder; a plain `Int` binder is the minimal trigger.
#[test]
fn loop_let_bound_binder_reference_builds() {
let stdout = build_and_run("loop_let_bound_binder_ref.ail");
assert_eq!(stdout.trim(), "3");
}
/// Guards block tracking in codegen: max3 has nested `if`s, and wrong
/// phi block tracking would produce a wrong result here.
#[test]