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.
This commit is contained in:
2026-05-29 17:21:32 +02:00
parent ce0374ac0c
commit 52ff8738b8
33 changed files with 373 additions and 12 deletions
+25 -4
View File
@@ -614,12 +614,18 @@ impl<'a> Parser<'a> {
}
body = Some(self.parse_body_attr()?);
}
Some("intrinsic") => {
if body.is_some() {
return Err(self.duplicate_clause_err("fn-def", &format!("fn `{name}`"), "body"));
}
body = Some(self.parse_intrinsic_attr()?);
}
Some(other) => {
let pos = self.peek().map(|t| t.span.start).unwrap_or(0);
return Err(ParseError::Production {
production: "fn-def",
message: format!(
"unknown fn attribute `{other}`; expected `doc`, `export`, `suppress`, `type`, `params`, or `body`"
"unknown fn attribute `{other}`; expected `doc`, `export`, `suppress`, `type`, `params`, `body`, or `intrinsic`"
),
pos,
});
@@ -640,7 +646,7 @@ impl<'a> Parser<'a> {
})?;
let body = body.ok_or_else(|| ParseError::Production {
production: "fn-def",
message: format!("fn `{name}` is missing required `(body ...)` attribute"),
message: format!("fn `{name}` is missing required `(body ...)` or `(intrinsic)` attribute"),
pos: 0,
})?;
Ok(FnDef {
@@ -767,6 +773,17 @@ impl<'a> Parser<'a> {
Ok(t)
}
/// Parse an `(intrinsic)` body clause into [`Term::Intrinsic`]. It
/// fills the same single body slot a `(body ...)` clause fills; a
/// def carrying it is compiler-supplied (signature-only at
/// typecheck, routed through the intercept registry at codegen).
fn parse_intrinsic_attr(&mut self) -> Result<Term, ParseError> {
self.expect_lparen("intrinsic-attr")?;
self.expect_keyword("intrinsic")?;
self.expect_rparen("intrinsic-attr")?;
Ok(Term::Intrinsic)
}
// ---- const def ------------------------------------------------------
fn parse_const(&mut self) -> Result<ConstDef, ParseError> {
@@ -1526,8 +1543,12 @@ impl<'a> Parser<'a> {
if let Some("effects") = self.peek_head_ident() {
effects = self.parse_effects_clause()?;
}
// (body term)
let body = self.parse_body_attr()?;
// (body term) — or (intrinsic) for a compiler-supplied body
let body = if let Some("intrinsic") = self.peek_head_ident() {
self.parse_intrinsic_attr()?
} else {
self.parse_body_attr()?
};
self.expect_rparen("lam-term")?;
Ok(Term::Lam {
params,
+19 -6
View File
@@ -209,9 +209,13 @@ fn write_fn_def(out: &mut String, fd: &FnDef, level: usize) {
out.push(')');
out.push('\n');
indent(out, level + 1);
out.push_str("(body ");
write_term(out, &fd.body, level + 2);
out.push(')');
if matches!(fd.body, Term::Intrinsic) {
out.push_str("(intrinsic)");
} else {
out.push_str("(body ");
write_term(out, &fd.body, level + 2);
out.push(')');
}
out.push(')');
}
@@ -549,9 +553,13 @@ fn write_term(out: &mut String, t: &Term, level: usize) {
}
out.push(')');
}
out.push_str(" (body ");
write_term(out, body, level);
out.push_str("))");
if matches!(**body, Term::Intrinsic) {
out.push_str(" (intrinsic))");
} else {
out.push_str(" (body ");
write_term(out, body, level);
out.push_str("))");
}
}
Term::Seq { lhs, rhs } => {
out.push_str("(seq ");
@@ -636,6 +644,11 @@ fn write_term(out: &mut String, t: &Term, level: usize) {
}
out.push(')');
}
// A general term-printer only reaches Term::Intrinsic via a
// fn/lam body slot, which the fn-def and lam printers above
// already special-case; emitting `(intrinsic)` here keeps the
// exhaustive match correct.
Term::Intrinsic => out.push_str("(intrinsic)"),
}
}