feat(codegen): switch the lowering walk from &Term to typed &MTerm (mir.1b)

Atomic completion of spec iteration mir.1 (docs/specs/0060-typed-mir.md):
codegen now consumes the typed MIR produced by `lower_to_mir` instead of
re-deriving types from the bare `ast::Term`. Every codegen helper that
took `&Term` (lower_term, lower_app, drop.rs, match_lower.rs) takes
`&MTerm` and reads each node's checker-proved type off `MTerm::ty()`.
The build path is `Workspace -> elaborate_workspace -> MirWorkspace ->
lower_workspace`; the public `lower_workspace*` entry points and their 18
call sites thread `&MirWorkspace`. The codegen-side type re-derivers
`synth_with_extras` + `synth_arg_type` (and the `builtin_ail_type` /
`builtin_effect_op_ret` mirror tables) are deleted — grep-clean. The
three re-derivers the spec keeps until mir.2/mir.3 (`type_home_module`,
`is_static_callee`, the second `infer_module_with_cross`) stay.

The mechanical Term->MTerm match-arm conversion was straightforward and
compiler-enforced. The substance was a set of producer-side correctness
gaps that only surface once codegen reads `MTerm::ty()` and once the
build path re-synthesises the post-mono AST through the canonical
`synth` (which, unlike the old codegen, fully re-unifies). Each was
root-caused against a failing e2e fixture:

1. `qualify_local_types` stripped fn-type modes (rebuilt `Type::Fn` with
   empty `param_modes` / `Implicit` `ret_mode`), so a monomorphised
   polymorphic intrinsic (`RawBuf.set`) lost its `Own` ret-mode and the
   owned temporary leaked at the call site. Made mode-preserving, like
   its sister `qualify_workspace_types` and `Subst::apply` (449df13).

2. `lower_to_mir::synth_pure` synthesises each node in isolation, so a
   nullary polymorphic ctor (`Nil : List<a>`) left its element type an
   unbound `$m` metavar that the canonical synth never pins. Codegen's
   mono unifier (`unify_for_subst`) already has a wildcard for exactly
   this — `$u`, the spelling the now-deleted codegen synth used — so the
   typed-MIR boundary normalises every residual `$m` to `$u` once
   (`wildcard_residual_metavars`), rather than teaching each consumer to
   tolerate a raw metavar.

3. The class-method mono arm (`synthesise_mono_fn`) substituted the
   registry-canonical *qualified* instance type into a method appended to
   the instance's own module, minting a `show_user_adt.IntBox` param
   against a bare-`IntBox` body. Localised to bare before substitution,
   symmetric to the free-fn arm (600565d).

4. Monomorphisation synthesises *downward* class-dispatch references —
   prelude's `print__<IntBox>` names the instance module `show_user_adt`
   that prelude never imports. The post-mono re-synth in `lower_module`
   seeds every workspace module name as an identity import (excluding the
   current module, to keep own types bare) so the qualified-var path
   resolves these; the canonical `synth` used by `check_workspace` stays
   strict.

5. Post-mono, a cross-module callee can name the consumer's *own* ADT
   qualified (`show_user_adt.IntBox`) where the consumer synthesises it
   bare — a spelling split that cannot exist pre-mono (the param is
   polymorphic there). synth's App arm strips the current module's own
   qualifier from both sides before unifying (`strip_own_module_qual`),
   a no-op pre-mono.

Acceptance: whole workspace suite green (698 tests); `e2e` 98/98 and
`show_print_e2e` 3/3; `synth_with_extras`/`synth_arg_type` grep-clean in
codegen; #51/#53 fixtures build and run; lower_to_mir_ty pins green. The
#49 heap-Str loop-binder leak remains ignored (lifts at mir.4).

Builds on the standalone producer fix (600565d, free-fn own-ADT
localisation) and the two standalone mode-preservation fixes
(449df13 Subst::apply); those landed separately as they are
independently correct and inert on the old codegen.
This commit is contained in:
2026-05-31 18:29:36 +02:00
parent 449df13c9c
commit 895ba846e8
18 changed files with 819 additions and 1142 deletions
+69 -149
View File
@@ -648,53 +648,10 @@ fn main() -> Result<()> {
// workspace lowering. For single-module programs the
// workspace is effectively a trivial workspace with one module.
let ws = load_workspace_human(&path)?;
let diags = ailang_check::check_workspace(&ws);
if !diags.is_empty() {
for d in &diags {
eprintln!(
"{}: [{}] {}{}",
match d.severity {
ailang_check::Severity::Error => "error",
ailang_check::Severity::Warning => "warning",
},
d.code,
d.def
.as_ref()
.map(|n| format!("{n}: "))
.unwrap_or_default(),
d.message,
);
}
// only Error-severity blocks codegen.
if diags
.iter()
.any(|d| matches!(d.severity, ailang_check::Severity::Error))
{
std::process::exit(1);
}
}
// emit-ir must run the same pre-codegen pipeline
// as `build` — `lift_letrecs` per module, then
// `monomorphise_workspace`. Pre-iter-23.4 this was implicit:
// codegen's poly-call path handled specialisation internally.
// With that path removed, emit-ir must produce the
// post-mono workspace explicitly, same shape as `build`.
let mut lifted_modules = std::collections::BTreeMap::new();
for (mname, m) in &ws.modules {
let desugared = ailang_core::desugar::desugar_module(m);
let lifted = ailang_check::lift_letrecs(&desugared)
.map_err(|e| anyhow::anyhow!("lift_letrecs in module `{mname}`: {e}"))?;
lifted_modules.insert(mname.clone(), lifted);
}
let ws = ailang_core::Workspace {
entry: ws.entry.clone(),
modules: lifted_modules,
root_dir: ws.root_dir.clone(),
registry: ws.registry.clone(),
};
let ws = ailang_check::monomorphise_workspace(&ws)
.map_err(|e| anyhow::anyhow!("monomorphise_workspace: {e}"))?;
let ir = if emit == "staticlib" {
// staticlib needs ≥1 export — checked on the source AST
// (structural; survives elaborate). Done before elaborate so
// the message is clear rather than a missing-main lowering.
if emit == "staticlib" {
let has_export = ws.modules.values().any(|m| m.defs.iter().any(|d|
matches!(d, ailang_core::Def::Fn(f) if f.export.is_some())));
if !has_export {
@@ -702,9 +659,22 @@ fn main() -> Result<()> {
"staticlib target needs at least one `(export \"<sym>\")` fn"
);
}
ailang_codegen::lower_workspace_staticlib(&ws)?
}
// mir.1b OQ4: emit-ir runs the same single front-end as
// `build` via `elaborate_workspace` (check → desugar+lift →
// mono → lower_to_mir), driving error diagnostics from its
// `Err` rather than a separate `check_workspace` call.
let mir = match ailang_check::elaborate_workspace(&ws) {
Ok(mir) => mir,
Err(diags) => {
print_build_diagnostics(&diags);
std::process::exit(1);
}
};
let ir = if emit == "staticlib" {
ailang_codegen::lower_workspace_staticlib(&mir)?
} else {
ailang_codegen::lower_workspace(&ws)?
ailang_codegen::lower_workspace(&mir)?
};
match out {
Some(p) => {
@@ -2264,19 +2234,35 @@ fn locate_str_runtime() -> Result<PathBuf> {
)
}
/// print build-time diagnostics to stderr in the `ail check` human
/// format (severity / code / optional def name / message). Used by the
/// build paths to surface the `Err(diags)` from `elaborate_workspace`
/// before exiting with code 1.
fn print_build_diagnostics(diags: &[ailang_check::Diagnostic]) {
for d in diags {
eprintln!(
"{}: [{}] {}{}",
match d.severity {
ailang_check::Severity::Error => "error",
ailang_check::Severity::Warning => "warning",
},
d.code,
d.def
.as_ref()
.map(|n| format!("{n}: "))
.unwrap_or_default(),
d.message,
);
}
}
/// shared build helper for `Cmd::Build` and `Cmd::Run`.
/// Loads the workspace, runs the typechecker, emits IR, and links via
/// clang. On typecheck failure, prints diagnostics to stderr and exits
/// the process with code 1. On clang failure, returns a Result error
/// Loads the workspace, elaborates it to MIR (check → desugar+lift →
/// monomorphise → lower_to_mir), emits IR, and links via clang. On
/// typecheck failure, prints diagnostics to stderr and exits the
/// process with code 1. On clang failure, returns a Result error
/// (the .ll path is preserved for post-mortem inspection).
///
/// between `check_workspace` and `lower_workspace` we run
/// `ailang_check::lift_letrecs` per module. The lift eliminates any
/// `Term::LetRec` that the desugar pass left in place (specifically:
/// LetRecs that capture `Term::Let`-bound names, whose types are
/// only known after typecheck). The lifted workspace then goes to
/// codegen unchanged.
///
/// `alloc` selects the heap allocator the emitted IR targets.
/// Default `Rc` is the canonical production path: declares
/// `@ailang_rc_alloc` (with `ailang_rc_inc` / `ailang_rc_dec`
@@ -2290,62 +2276,20 @@ fn build_to(
alloc: ailang_codegen::AllocStrategy,
) -> Result<PathBuf> {
let ws = load_workspace_human(path)?;
let diags = ailang_check::check_workspace(&ws);
if !diags.is_empty() {
for d in &diags {
eprintln!(
"{}: [{}] {}{}",
match d.severity {
ailang_check::Severity::Error => "error",
ailang_check::Severity::Warning => "warning",
},
d.code,
d.def
.as_ref()
.map(|n| format!("{n}: "))
.unwrap_or_default(),
d.message,
);
}
// only Error-severity blocks the build. Warning-
// severity diagnostics (e.g. `over-strict-mode`) print but
// do not abort.
if diags
.iter()
.any(|d| matches!(d.severity, ailang_check::Severity::Error))
{
// mir.1b OQ4: one check, not two. `elaborate_workspace` runs the
// full front-end (check → desugar+lift → monomorphise →
// lower_to_mir) and returns `Err(diags)` on a type error; the
// build path no longer runs its own `check_workspace`. The error
// diagnostics drive the same human-format print + exit(1) the
// separate check used to.
let mir = match ailang_check::elaborate_workspace(&ws) {
Ok(mir) => mir,
Err(diags) => {
print_build_diagnostics(&diags);
std::process::exit(1);
}
}
// run `lift_letrecs` per module on the post-desugar
// form. Codegen's internal desugar pass is idempotent on a
// module that contains no `Term::LetRec`, so the lifted output
// can be handed directly to `lower_workspace`.
let mut lifted_modules = std::collections::BTreeMap::new();
for (mname, m) in &ws.modules {
let desugared = ailang_core::desugar::desugar_module(m);
let lifted = ailang_check::lift_letrecs(&desugared)
.map_err(|e| anyhow::anyhow!("lift_letrecs in module `{mname}`: {e}"))?;
lifted_modules.insert(mname.clone(), lifted);
}
let ws = ailang_core::Workspace {
entry: ws.entry.clone(),
modules: lifted_modules,
root_dir: ws.root_dir.clone(),
// pass the registry through the lift pass. Lift
// only rewrites `Term::LetRec` into top-level fns; it does
// not touch class/instance defs, so the registry built at
// load-time remains valid.
registry: ws.registry.clone(),
};
// monomorphisation pass. After `lift_letrecs` and
// before codegen, every (class-method, concrete-type) call-site
// pair becomes a synthesised top-level fn; user call sites are
// rewritten to target those names. Class-free workspaces flow
// through bit-identically; see `ailang_check::monomorphise_workspace`.
let ws = ailang_check::monomorphise_workspace(&ws)
.map_err(|e| anyhow::anyhow!("monomorphise_workspace: {e}"))?;
let ir = ailang_codegen::lower_workspace_with_alloc(&ws, alloc)?;
let ir = ailang_codegen::lower_workspace_with_alloc(&mir, alloc)?;
let tmpdir = std::env::temp_dir().join(format!("ailang-{}", std::process::id()));
std::fs::create_dir_all(&tmpdir)?;
let ll_path = tmpdir.join(format!("{}.ll", ws.entry));
@@ -2459,43 +2403,12 @@ fn build_staticlib(
opt: &str,
alloc: ailang_codegen::AllocStrategy,
) -> Result<(PathBuf, PathBuf)> {
// ---- shared front matter: identical to build_to:2239-2294 ----
// ---- shared front matter: elaborate to MIR (one check) ----
let ws = load_workspace_human(path)?;
let diags = ailang_check::check_workspace(&ws);
if !diags.is_empty() {
for d in &diags {
eprintln!(
"{}: [{}] {}{}",
match d.severity {
ailang_check::Severity::Error => "error",
ailang_check::Severity::Warning => "warning",
},
d.code,
d.def.as_ref().map(|n| format!("{n}: ")).unwrap_or_default(),
d.message,
);
}
if diags.iter().any(|d| matches!(d.severity, ailang_check::Severity::Error)) {
std::process::exit(1);
}
}
let mut lifted_modules = std::collections::BTreeMap::new();
for (mname, m) in &ws.modules {
let desugared = ailang_core::desugar::desugar_module(m);
let lifted = ailang_check::lift_letrecs(&desugared)
.map_err(|e| anyhow::anyhow!("lift_letrecs in module `{mname}`: {e}"))?;
lifted_modules.insert(mname.clone(), lifted);
}
let ws = ailang_core::Workspace {
entry: ws.entry.clone(),
modules: lifted_modules,
root_dir: ws.root_dir.clone(),
registry: ws.registry.clone(),
};
let ws = ailang_check::monomorphise_workspace(&ws)
.map_err(|e| anyhow::anyhow!("monomorphise_workspace: {e}"))?;
// ---- staticlib-specific: require ≥1 export, then lower ----
// require ≥1 export on the source AST (structural; export survives
// desugar/lift/mono unchanged). Checked before elaborate so a
// no-export staticlib fails with the clear message rather than on a
// missing-`@main`-free lowering.
let has_export = ws.modules.values().any(|m| m.defs.iter().any(|d|
matches!(d, ailang_core::Def::Fn(f) if f.export.is_some())));
if !has_export {
@@ -2509,7 +2422,14 @@ fn build_staticlib(
leak-only bench instrument, not swarm-safe; use `--alloc=rc`"
);
}
let ir = ailang_codegen::lower_workspace_staticlib_with_alloc(&ws, alloc)?;
let mir = match ailang_check::elaborate_workspace(&ws) {
Ok(mir) => mir,
Err(diags) => {
print_build_diagnostics(&diags);
std::process::exit(1);
}
};
let ir = ailang_codegen::lower_workspace_staticlib_with_alloc(&mir, alloc)?;
let tmpdir = std::env::temp_dir().join(format!("ailang-{}", std::process::id()));
std::fs::create_dir_all(&tmpdir)?;