Iter 16b.5: LetRec name as value (in_term only) via eta-Lam wrapper

Drops the direct-call-only restriction on the LetRec name when it
appears in `in_term`. No new ABI: the lift wraps the in-term in
`(let f (lam P (app f$lr_N P CAPTURES)) in_term')` so codegen's
existing Iter-8b closure-pair machinery handles it. Body-position
name-as-value still rejected (deferred — eta-of-self is harder).

- desugar.rs / lift.rs: split find_non_callee_use into body
  (panic) and in_term (wrap).
- examples/local_rec_as_value.{ailx,ail.json}: no-capture path
  (factorial passed to apply5 → 120).
- examples/local_rec_as_value_capture.{ailx,ail.json}: capture
  path; lifted fn has captures, eta-Lam picks them up via 8b.
- e2e + desugar tests: 113 → 116 (+3).

Codegen Lam machinery handled the wrapped form on the first try.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-07 22:27:21 +02:00
parent c0668178bb
commit ca507c9f52
8 changed files with 509 additions and 45 deletions
+32
View File
@@ -505,6 +505,38 @@ fn local_rec_match_capture_demo() {
assert_eq!(lines, vec!["0", "5", "9"]);
}
/// Iter 16b.5: LetRec name as a value in the in-clause (no capture).
/// Property protected: the desugar pass detects a non-callee use of
/// the LetRec name in `in_term` and wraps the rewritten in-term in
/// `(let factorial (lam ...) ...)` whose lam eta-expands the lifted
/// fn. The LetRec name then resolves to a closure-pair value usable
/// anywhere a `Fn(Int) -> Int` is expected (here: passed to a HOF
/// `apply5`). Without 16b.5, the desugar would panic with the
/// "name-as-value not supported" message and the build would fail.
/// Expected stdout: 120 (= apply5 factorial = factorial 5).
#[test]
fn local_rec_as_value_demo() {
let stdout = build_and_run("local_rec_as_value.ail.json");
let lines: Vec<&str> = stdout.lines().collect();
assert_eq!(lines, vec!["120"]);
}
/// Iter 16b.5: LetRec name as a value in the in-clause WITH capture.
/// Property protected: the eta-Lam wrap composes correctly with the
/// 16b.2 capture-augmentation. The lifted fn has signature
/// `factorial_plus$lr_N(n: Int, base: Int) -> Int`; the eta-Lam
/// wrap binds `factorial_plus` to a `(lam (n) (app
/// factorial_plus$lr_N n base))` whose free var `base` becomes a
/// standard 8b closure-env capture. This is the dynamic-env path:
/// the lifted fn has extra params, the eta-Lam captures them.
/// Expected stdout: 1320 (= 5*4*3*2*(1+10)), 12120 (= 5*4*3*2*(1+100)).
#[test]
fn local_rec_as_value_capture_demo() {
let stdout = build_and_run("local_rec_as_value_capture.ail.json");
let lines: Vec<&str> = stdout.lines().collect();
assert_eq!(lines, vec!["1320", "12120"]);
}
/// Guards `ail diff`: a modified body changes the hash of `sum`, while
/// `main` stays unchanged. Expects exit code 1, `changed` contains exactly
/// `sum`, `unchanged` contains `main`, `added`/`removed` empty.
+52 -15
View File
@@ -379,23 +379,19 @@ impl<'a> Lifter<'a> {
}
}
// Defensive non-callee-use check (the desugar pass
// already ran this on the original LetRec, but
// post-lifting of inner LetRecs may have rewritten
// sub-terms — we re-run on the lifted body/in_term to
// be safe).
// 16b.5: name-as-value INSIDE the body remains rejected
// (would require an eta-Lam that calls the unlifted name —
// chicken-and-egg with the call-site rewrite).
if find_non_callee_use(&lifted_body, name).is_some() {
panic!(
"Iter 16b.3 invariant: LetRec `{name}` used as a value in its own \
body after sub-term lift; should have been rejected at desugar"
);
}
if find_non_callee_use(&lifted_in, name).is_some() {
panic!(
"Iter 16b.3 invariant: LetRec `{name}` used as a value in its \
in-clause after sub-term lift; should have been rejected at desugar"
"Iter 16b.5: LetRec `{name}` appears as a value INSIDE its own \
body; name-as-value of a LetRec inside its own body is not yet \
supported."
);
}
// 16b.5: name-as-value in in_term IS supported. The wrap
// is built below after we know `lifted_name` and `extras`.
let in_has_value_use = find_non_callee_use(&lifted_in, name).is_some();
// Recompute captures of the lifted body against the
// current `locals` (deterministic order via BTreeSet).
@@ -465,10 +461,51 @@ impl<'a> Lifter<'a> {
subst_call_with_extras(&lifted_body, name, &lifted_name, &extras);
let body_full = subst_var(&body_call_rw, name, &lifted_name);
// In-clause rewrite: same shape.
// In-clause: rewrite call sites, but skip subst_var so that
// bare `Var{name}` references (16b.5: name-as-value uses)
// can resolve to the eta-Lam binding we wrap below.
let in_call_rw =
subst_call_with_extras(&lifted_in, name, &lifted_name, &extras);
let in_full = subst_var(&in_call_rw, name, &lifted_name);
// 16b.5: extract effects, param types, ret type from the
// LetRec's declared type to mirror them on the eta-Lam.
let (orig_param_tys, orig_ret_ty, lr_effects): (Vec<Type>, Type, Vec<String>) =
match ty {
Type::Fn { params: ps, ret, effects } => {
(ps.clone(), (**ret).clone(), effects.clone())
}
Type::Forall { .. } => unreachable!("rejected above"),
_ => unreachable!("rejected above"),
};
let in_full = if in_has_value_use {
let lam_args: Vec<Term> = params
.iter()
.map(|p| Term::Var { name: p.clone() })
.chain(extras.iter().map(|c| Term::Var { name: c.clone() }))
.collect();
let lam_body = Term::App {
callee: Box::new(Term::Var { name: lifted_name.clone() }),
args: lam_args,
tail: false,
};
let eta_lam = Term::Lam {
params: params.clone(),
param_tys: orig_param_tys,
ret_ty: Box::new(orig_ret_ty),
effects: lr_effects,
body: Box::new(lam_body),
};
Term::Let {
name: name.clone(),
value: Box::new(eta_lam),
body: Box::new(in_call_rw),
}
} else {
// No name-as-value uses: defensive subst_var keeps
// the historical zero-capture symmetry intact.
subst_var(&in_call_rw, name, &lifted_name)
};
// Append the lifted FnDef. The doc string makes
// post-mortem debugging easier — anything containing
+189 -30
View File
@@ -529,28 +529,32 @@ impl Desugarer {
in_scope.insert(name.clone(), ScopeEntry::EnclosingLetRec);
let desugared_in = self.desugar_term(in_term, &in_scope);
// 16b.2/16b.5: validate that `name` is only ever used as
// the callee of a Term::App in body and in_term — never
// as a Term::Var in any value position. Run BEFORE
// capture classification so the diagnostic fires
// regardless of whether we end up lifting here or
// deferring to the post-typecheck pass.
// 16b.2: validate that `name` is only ever used as the
// callee of a Term::App in `body` — never as a value.
// Body-side name-as-value would require an eta-Lam inside
// the body that references the LetRec's own pre-lift name;
// that's a non-trivial extension (the Lam's body would need
// to call the unlifted name, which by then is already
// rewritten to the lifted callee — chicken-and-egg). Stays
// rejected.
//
// 16b.5: in_term-side name-as-value is now SUPPORTED. We
// detect it here but DO NOT panic; instead, the lift logic
// below wraps `in_term'` in a `Let { f, lam(...), in_term' }`
// whose lam eta-expands the lifted fn, supplying the
// captures positionally. Bare-`f` references in `in_term'`
// then resolve to the let-bound lam value. Callee-position
// references in `in_term'` go directly to the lifted fn
// (efficient; no closure indirection).
if let Some(violation) = find_non_callee_use(&desugared_body, name) {
panic!(
"Iter 16b.3: LetRec `{}` is used as a value in its own body \
(not as the callee of `app`); not supported. Queued for 16b.5 \
(closure conversion). Offending term: {:?}",
name, violation
);
}
if let Some(violation) = find_non_callee_use(&desugared_in, name) {
panic!(
"Iter 16b.3: LetRec `{}` is used as a value in the in-clause \
(not as the callee of `app`); not supported. Queued for 16b.5. \
Offending term: {:?}",
"Iter 16b.5: LetRec `{}` appears as a value INSIDE its own body \
(not as the callee of `app`); name-as-value of a LetRec inside \
its own body is not yet supported. Offending term: {:?}",
name, violation
);
}
let in_has_value_use = find_non_callee_use(&desugared_in, name).is_some();
// Capture detection (against the *outer* scope, before
// the body-scope extension).
@@ -666,19 +670,75 @@ impl Desugarer {
let lifted_name = self.fresh_lifted(name);
// Rewrite (app name args) to (app lifted_name args... cap0
// cap1 ...) FIRST, then substitute name -> lifted_name
// everywhere (handles non-call references, but in 16b.2
// those are now ruled out by `find_non_callee_use` —
// the second pass remains for symmetry with 16b.1 and
// for the case where there are zero captures).
// cap1 ...) FIRST in body, then substitute name ->
// lifted_name everywhere (handles non-call references,
// but body name-as-value is rejected above so this is
// a defensive belt-and-braces pass).
let extras: Vec<String> =
capture_types.iter().map(|(n, _)| n.clone()).collect();
let body_call_rw =
subst_call_with_extras(&desugared_body, name, &lifted_name, &extras);
let body_full = subst_var(&body_call_rw, name, &lifted_name);
// 16b.5: rewrite call sites in `in_term` to the lifted
// name with captures appended. Do NOT run `subst_var` on
// `in_term` if there's a name-as-value use — we want
// those bare `Var{name}` references to resolve to the
// eta-Lam binding we add below. If there is no
// name-as-value use, we still skip subst_var (no leftover
// bare references exist after subst_call_with_extras).
let in_call_rw =
subst_call_with_extras(&desugared_in, name, &lifted_name, &extras);
let in_full = subst_var(&in_call_rw, name, &lifted_name);
// Effects on the LetRec's declared type — the eta-Lam
// inherits them so its body can call the lifted fn (which
// carries the same effects).
let lr_effects: Vec<String> = match peel_forall_to_fn(ty) {
Some(Type::Fn { effects: es, .. }) => es.clone(),
_ => vec![],
};
// Original LetRec param types and ret type — the eta-Lam's
// signature mirrors the LetRec's declared type so a value
// bound by `(let f (lam ...) ...)` has type Fn(t1..tk) -> tr.
let (orig_param_tys, orig_ret_ty): (Vec<Type>, Type) =
match peel_forall_to_fn(ty) {
Some(Type::Fn { params: ps, ret, .. }) => {
(ps.clone(), (**ret).clone())
}
_ => unreachable!("ty shape validated above"),
};
let in_full = if in_has_value_use {
// Build the eta-Lam: `(lam (params P1..Pk -> RT) [effects]
// (app f$lr_N P1..Pk c1..cm))`. Param names reuse the
// LetRec's original param names — fine because they
// shadow only inside the Lam body.
let lam_args: Vec<Term> = params
.iter()
.map(|p| Term::Var { name: p.clone() })
.chain(extras.iter().map(|c| Term::Var { name: c.clone() }))
.collect();
let lam_body = Term::App {
callee: Box::new(Term::Var { name: lifted_name.clone() }),
args: lam_args,
tail: false,
};
let eta_lam = Term::Lam {
params: params.clone(),
param_tys: orig_param_tys,
ret_ty: Box::new(orig_ret_ty),
effects: lr_effects,
body: Box::new(lam_body),
};
Term::Let {
name: name.clone(),
value: Box::new(eta_lam),
body: Box::new(in_call_rw),
}
} else {
in_call_rw
};
self.lifted.push(Def::Fn(FnDef {
name: lifted_name,
@@ -1818,16 +1878,16 @@ mod tests {
);
}
/// Iter 16b.2: if the LetRec name is used as a value (not as
/// the callee of an `app`), the lifter rejects with a `16b.5`
/// pointer (closure conversion). Here `(let g f ...)` binds the
/// LetRec name `f` to a let-bound name `g`, which is a value
/// position — not a callee.
/// Iter 16b.5: name-as-value INSIDE the LetRec's own body is
/// still rejected (would require an eta-Lam that calls the
/// pre-lift name — chicken-and-egg with the call-site rewrite).
/// Here `(let g f ...)` binds the LetRec name `f` to a let-bound
/// name `g`, which is a value position — not a callee.
#[test]
#[should_panic(expected = "16b.5")]
fn let_rec_name_as_value_panics() {
fn let_rec_name_as_value_in_body_panics() {
// (let-rec f (params x) (type Int->Int)
// (body (let g f (app g x))) -- f used as a value
// (body (let g f (app g x))) -- f used as a value INSIDE body
// (in (app f 1)))
let letrec = Term::LetRec {
name: "f".into(),
@@ -1871,6 +1931,105 @@ mod tests {
let _ = desugar_module(&m);
}
/// Iter 16b.5: name-as-value in the in-clause is now SUPPORTED.
/// The desugar pass lifts the LetRec to a synthetic top-level fn
/// AND wraps the rewritten in-term in `(let f (lam ...) ...)`
/// whose lam eta-expands the lifted fn. After desugar, the
/// surviving term tree contains:
/// - one lifted fn `f$lr_N`
/// - inside `main`, a `Term::Let { name: "f", value: Term::Lam,
/// body: <rewritten in_term> }` where the Lam's body calls
/// `f$lr_N` positionally.
#[test]
fn let_rec_name_as_value_in_in_term_wraps_to_eta_lam() {
// (let-rec f (params x) (type Int->Int)
// (body (app f x)) -- only callee uses (legal)
// (in (let g f (app g 1)))) -- f used as a value
let letrec = Term::LetRec {
name: "f".into(),
ty: Type::Fn {
params: vec![Type::int()],
ret: Box::new(Type::int()),
effects: vec![],
},
params: vec!["x".into()],
body: Box::new(Term::App {
callee: Box::new(Term::Var { name: "f".into() }),
args: vec![Term::Var { name: "x".into() }],
tail: false,
}),
in_term: Box::new(Term::Let {
name: "g".into(),
value: Box::new(Term::Var { name: "f".into() }),
body: Box::new(Term::App {
callee: Box::new(Term::Var { name: "g".into() }),
args: vec![Term::Lit { lit: Literal::Int { value: 1 } }],
tail: false,
}),
}),
};
let m = Module {
schema: crate::SCHEMA.to_string(),
name: "t".into(),
imports: vec![],
defs: vec![Def::Fn(FnDef {
name: "main".into(),
ty: Type::Fn {
params: vec![],
ret: Box::new(Type::int()),
effects: vec![],
},
params: vec![],
body: letrec,
doc: None,
})],
};
let out = desugar_module(&m);
// Two defs: original `main` + lifted `f$lr_0`.
assert_eq!(
out.defs.len(),
2,
"expected one lifted fn appended; got {:?}",
out.defs.iter().map(|d| d.name()).collect::<Vec<_>>()
);
let lifted_name = out.defs[1].name().to_string();
assert!(
lifted_name.starts_with("f$lr_"),
"unexpected lifted-name shape: {lifted_name}"
);
// main's body must be wrapped in `Let { name: "f", value: Lam, ... }`.
let main_body = match &out.defs[0] {
Def::Fn(fd) => &fd.body,
_ => unreachable!(),
};
match main_body {
Term::Let { name, value, .. } => {
assert_eq!(name, "f", "wrap name must be the original LetRec name");
match value.as_ref() {
Term::Lam { params, body, .. } => {
assert_eq!(params, &vec!["x".to_string()]);
// The lam's body is `(app f$lr_0 x)` (no captures
// here, so just original-params).
match body.as_ref() {
Term::App { callee, args, .. } => {
match callee.as_ref() {
Term::Var { name: cn } => {
assert_eq!(cn, &lifted_name);
}
other => panic!("expected callee Var, got {other:?}"),
}
assert_eq!(args.len(), 1, "no captures expected");
}
other => panic!("expected lam body App, got {other:?}"),
}
}
other => panic!("expected wrap value Lam, got {other:?}"),
}
}
other => panic!("expected wrap Let at main body, got {other:?}"),
}
}
/// Iter 16c: walks a term, returns true iff any [`Pattern::Lit`] is
/// reachable in any [`Term::Match`] arm. After 16c desugaring, the
/// invariant is `false` for every desugared output — `Pattern::Lit`