Files
AILang/crates/ail/tests/codegen_import_map_fallback_pin.rs
T
Brummel 52ff8738b8 iter intrinsic-bodies.1-mechanism (DONE 8/8): Term::Intrinsic leaf + cross-crate wiring (refs #9)
First iteration of the intrinsic-bodies milestone. Introduces the
Form-A `(intrinsic)` body marker as a new leaf AST term and wires it
through surface, checker, codegen, and a kernel_stub ratifier. The
prelude migration + hard-lockstep pin + dead-path removal are .2.

What landed (8 tasks):

  Task 1 — Term::Intrinsic unit variant (ast.rs), tag "t":"intrinsic"
    via the enum's rename_all=lowercase. Additive: no existing fixture
    carries it, hashes bit-identical. In-core exhaustive-match arms
    (canonical/hash/visit/pretty/desugar/workspace) added as leaves.
  Task 2 — surface parse + print: (intrinsic) as a fn body-slot clause
    and a lambda positional body, mapped to/from Term::Intrinsic.
  Task 3 — cross-crate walker sweep (check/codegen/prose/ail-main):
    leaf no-op/identity arms at every no-wildcard Term match the
    compiler flagged.
  Task 4 — checker: new Env.current_module_kernel_tier flag (m.kernel
    || m.name=="prelude"), set alongside current_module. A def whose
    body is intrinsic (top-level fn OR instance-method lambda, via the
    shared is_intrinsic_body helper) is checked signature-only; an
    intrinsic body outside kernel-tier/prelude is rejected with
    intrinsic-outside-kernel-tier.
  Task 5 — codegen: an intrinsic-bodied fn routes through the existing
    try_emit_primitive_instance_body / intercepts::lookup path; if no
    intercept fired it is an internal error, never a lower_term
    fallthrough. lower_term and the synth walker get Term::Intrinsic
    internal-error arms (an intrinsic body reaching either is an
    escape bug).
  Task 6 — answer intercept (ret i64 42) registered in INTERCEPTS;
    the `answer : () -> Int` intrinsic added to STUB_AIL;
    examples/kernel_intrinsic_smoke.ail added so schema_coverage
    observes Term::Intrinsic in the examples/ corpus.
  Task 7 — E2E ratifier: examples/kernel_answer.ail calls
    kernel_stub.answer and prints 42; answer_intrinsic_builds_and_runs_printing_42
    asserts it end-to-end (source → native).
  Task 8 — design/contracts/0002-data-model.md gains the
    { "t": "intrinsic" } Term entry + fn/lam prose; form_a.md grammar
    note updated.

Verification:
  cargo test --workspace → 669 passed, 0 failed (baseline 667 +2:
    intrinsic_in_user_module_is_rejected, answer_intrinsic_builds_and_runs_printing_42).
  bench/check.py + bench/compile_check.py → 0 regressed.
  Reject E2E (subprocess ail check --json, exit 1, code
    intrinsic-outside-kernel-tier) GREEN.
  Round-trip + hash pins GREEN — Term::Intrinsic is additive, no
    existing fixture carries it, no hash moved.

Three implementation completions beyond the plan (all behaviour-
preserving, surfaced during execution):

1. The signature-only skip had to apply at the mono pass's two
   synth-on-body re-entry sites (collect_mono_targets,
   collect_residuals_ordered), not only check_fn — else an intrinsic
   body hits synth's Term::Intrinsic internal-error guard. Repaired by
   extracting the shared crate::is_intrinsic_body helper and applying
   it at all three synth-on-body paths. Not a representation surprise:
   the same signature-only treatment, more call sites.

2. The compiler-enumerated exhaustive-match set was broader than the
   plan's named grep set (the plan anticipated this and made the sweep
   compile-driven). Extra leaf arms in core desugar/workspace, check
   reuse-as + qualify_workspace_term, codegen synth_with_extras,
   ail/src/main.rs, and four test targets.

3. Fixture corrections: emit_answer needed the body-close
   (block terminator) the plan snippet omitted; kernel_answer.ail's
   main is (ret Unit)(effects IO) using (app print ...) since
   io/print_int does not exist (the plan flagged this for the
   implementer to resolve against real effect-op names).

IR snapshots (hello/sum/list/max3/ws_main.ll) refreshed: purely
additive @ail_kernel_stub_answer fn+adapter+closure, emitted into
every workspace exactly as the pre-existing @ail_kernel_stub_new
already was (kernel_stub is auto-injected; confirmed new was present
in the pre-iter hello.ll baseline). No user-fn IR changed.

The .2 iteration migrates the 18 prelude dummy bodies to (intrinsic),
upgrades registry_contains_all_legacy_arms to a source<->registry
bijection pin, and removes the dead body-lowering path.
2026-05-29 17:21:32 +02:00

140 lines
5.8 KiB
Rust

//! Pin for the iter-24.3 codegen `import_map`-fallback path
//! (design/contracts/0013-typeclasses.md, "Cross-module references in
//! synthesised bodies" invariant 2).
//!
//! Property protected: post-mono synthesised body cross-module
//! references resolve at codegen via the fallback to
//! `module_user_fns` / `module_def_ail_types` when the prefix is
//! NOT in the current module's `import_map`. Specifically, the
//! synthesised `prelude.print__<UserType>` body references
//! `<user_module>.show__<UserType>` even though `prelude` does not
//! import user modules.
//!
//! Failure mode this pin catches: a future codegen refactor
//! tightens `resolve_top_level_fn` or `lower_app`'s cross-module
//! arm or `synth_with_extras`'s Var arm back to `import_map`-only.
//! Without this pin, the regression surfaces only at the
//! `show_user_adt` E2E (which builds + runs a binary, slow to
//! bisect).
use ailang_check::{check_workspace, monomorphise_workspace};
use ailang_core::ast::{Def, Term};
use ailang_surface::load_workspace;
use std::path::PathBuf;
fn fixture_path() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../examples")
.join("show_user_adt.ail")
}
#[test]
fn synthesised_print_uses_user_module_show_via_fallback() {
// Step 1: workspace loads + typechecks clean.
let ws = load_workspace(&fixture_path()).expect("workspace loads");
let diags = check_workspace(&ws);
assert!(
diags.is_empty(),
"typecheck diagnostics in show_user_adt fixture: {diags:?}"
);
// Step 2: mono synthesis produces `prelude.print__<IntBox>` whose
// body references `show_user_adt.show__<IntBox>` (cross-module).
let post_mono = monomorphise_workspace(&ws).expect("mono green");
let prelude_mod = post_mono
.modules
.get("prelude")
.expect("prelude post-mono module present");
let print_def = prelude_mod
.defs
.iter()
.find_map(|d| match d {
Def::Fn(f) if f.name.starts_with("print__") => Some(f),
_ => None,
})
.expect("synthesised print__<UserType> not found in prelude post-mono module");
// Step 3: recursively walk `print_def.body` looking for a Var
// whose name carries the `show_user_adt.` prefix (the cross-
// module reference invariant 2 protects).
fn contains_xmod_show_var(t: &Term) -> bool {
match t {
Term::Var { name } => {
name.starts_with("show_user_adt.") && name.contains("show__")
}
Term::Let { value, body, .. } => {
contains_xmod_show_var(value) || contains_xmod_show_var(body)
}
Term::LetRec { body, in_term, .. } => {
contains_xmod_show_var(body) || contains_xmod_show_var(in_term)
}
Term::App { callee, args, .. } => {
contains_xmod_show_var(callee) || args.iter().any(contains_xmod_show_var)
}
Term::Do { args, .. } => args.iter().any(contains_xmod_show_var),
Term::Lam { body, .. } => contains_xmod_show_var(body),
Term::If { cond, then, else_ } => {
contains_xmod_show_var(cond)
|| contains_xmod_show_var(then)
|| contains_xmod_show_var(else_)
}
Term::Match { scrutinee, arms } => {
contains_xmod_show_var(scrutinee)
|| arms.iter().any(|a| contains_xmod_show_var(&a.body))
}
Term::Ctor { args, .. } => args.iter().any(contains_xmod_show_var),
Term::Seq { lhs, rhs } => {
contains_xmod_show_var(lhs) || contains_xmod_show_var(rhs)
}
Term::Clone { value } => contains_xmod_show_var(value),
Term::ReuseAs { source, body } => {
contains_xmod_show_var(source) || contains_xmod_show_var(body)
}
// loop-recur iter 1: a `Term::Loop` cannot itself host a
// synthesised cross-module reference, but recurse
// defensively through binder inits / body / recur args.
Term::Loop { binders, body } => {
binders.iter().any(|b| contains_xmod_show_var(&b.init))
|| contains_xmod_show_var(body)
}
Term::Recur { args } => args.iter().any(contains_xmod_show_var),
// prep.2 (kernel-extension-mechanics): recurse through
// NewArg::Value subterms; type-args do not carry a Var.
Term::New { args, .. } => args.iter().any(|arg| match arg {
ailang_core::ast::NewArg::Value(v) => contains_xmod_show_var(v),
ailang_core::ast::NewArg::Type(_) => false,
}),
Term::Lit { .. } => false,
Term::Intrinsic => false,
}
}
assert!(
contains_xmod_show_var(&print_def.body),
"synthesised print body should contain a `show_user_adt.<suffix>` Var \
referencing the user-module's show__<IntBox> mono symbol — \
this is the cross-module reference codegen resolves via the \
import_map-fallback path. Body: {:?}",
print_def.body
);
// Step 4: confirm prelude module's `imports` does NOT contain
// `show_user_adt` — the resolution at codegen time genuinely
// bypasses the source template's import_map.
let prelude_src = ws
.modules
.get("prelude")
.expect("prelude source module present");
assert!(
prelude_src
.imports
.iter()
.all(|imp| imp.module != "show_user_adt"),
"prelude must not import show_user_adt (the invariant is that \
codegen resolves the cross-module ref WITHOUT going through \
import_map). Got imports: {:?}",
prelude_src.imports
);
}