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
+7
View File
@@ -297,6 +297,7 @@ Parenthesised forms:
(loop (NAME TYPE INIT)* BODY-TERM+) ; strict iteration block (loop-recur)
(recur ARG*) ; re-enter enclosing loop (loop-recur)
(new TYPE-NAME ARG+) ; functional construction (kernel-extension prep.2)
(intrinsic) ; compiler-supplied body (kernel-tier only; fills a fn/lam body slot)
```
Notes:
@@ -337,6 +338,12 @@ Notes:
`new-type-not-constructible` (T's home module has no `new` def),
`new-arg-kind-mismatch` (arg's kind disagrees with the sig at that
position). Codegen lands in the raw-buf milestone.
- `(intrinsic)` fills the single body slot of a `fn` def (in place of
`(body TERM)`) or a `lam`. It marks the definition as
compiler-supplied: the typechecker validates only the signature and
codegen routes the body through the intercept registry. It is legal
only in a `(kernel)`-tier module or the prelude — elsewhere it is
rejected with `intrinsic-outside-kernel-tier`.
## Patterns
+12
View File
@@ -604,6 +604,18 @@ pub enum Term {
type_name: String,
args: Vec<NewArg>,
},
/// The body of a compiler-supplied ("intrinsic") definition. Legal
/// only as the body of a `FnDef` or a `Term::Lam`, and only in a
/// `(kernel)`-tier module or the prelude (enforced at typecheck,
/// `IntrinsicOutsideKernelTier`). Never reduces to a value: codegen
/// consumes it via `intercepts::lookup` on the def's mangled name;
/// the typechecker treats a def with this body as signature-only.
/// A def is intrinsic iff `matches!(body, Term::Intrinsic)`. Additive
/// `"t":"intrinsic"` tag (unit variant via the enum's
/// `rename_all = "lowercase"`); pre-existing fixtures hash
/// bit-identically — none carry the tag. Precedent: `Term::Recur`
/// (a non-reducing control-transfer leaf).
Intrinsic,
}
/// One positional arg to a `(new T args...)` call. Either a `Type`
+9
View File
@@ -366,6 +366,7 @@ fn collect_used_in_term(t: &Term, used: &mut BTreeSet<String>) {
}
}
}
Term::Intrinsic => {}
}
}
@@ -932,6 +933,7 @@ impl Desugarer {
})
.collect(),
},
Term::Intrinsic => t.clone(),
}
}
@@ -1250,6 +1252,7 @@ pub fn free_vars_in_term(t: &Term, bound: &BTreeSet<String>, out: &mut BTreeSet<
}
}
}
Term::Intrinsic => {}
}
}
@@ -1440,6 +1443,7 @@ pub fn subst_var(t: &Term, from: &str, to: &str) -> Term {
})
.collect(),
},
Term::Intrinsic => t.clone(),
}
}
@@ -1590,6 +1594,7 @@ pub fn subst_call_with_extras(t: &Term, name: &str, lifted: &str, extras: &[Stri
})
.collect(),
},
Term::Intrinsic => t.clone(),
}
}
@@ -1655,6 +1660,7 @@ pub fn find_non_callee_use(t: &Term, name: &str) -> Option<Term> {
NewArg::Value(v) => find_non_callee_use(v, name),
NewArg::Type(_) => None,
}),
Term::Intrinsic => None,
}
}
@@ -1705,6 +1711,7 @@ mod tests {
NewArg::Value(v) => any_nested_ctor(v),
NewArg::Type(_) => false,
}),
Term::Intrinsic => false,
}
}
@@ -1738,6 +1745,7 @@ mod tests {
NewArg::Value(v) => any_let_rec(v),
NewArg::Type(_) => false,
}),
Term::Intrinsic => false,
}
}
@@ -2893,6 +2901,7 @@ mod tests {
NewArg::Value(v) => any_lit_pattern(v),
NewArg::Type(_) => false,
}),
Term::Intrinsic => false,
}
}
+2
View File
@@ -1291,6 +1291,7 @@ where
}
Ok(())
}
Term::Intrinsic => Ok(()),
}
}
@@ -1434,6 +1435,7 @@ where
}
Ok(())
}
Term::Intrinsic => Ok(()),
}
}
@@ -167,6 +167,7 @@ fn design_md_anchors_every_term_variant() {
args: vec![],
},
),
(r#""t": "intrinsic""#, Term::Intrinsic),
];
for (anchor, term) in exemplars {
@@ -189,6 +190,7 @@ fn design_md_anchors_every_term_variant() {
Term::Loop { .. } => "loop",
Term::Recur { .. } => "recur",
Term::New { .. } => "new",
Term::Intrinsic => "intrinsic",
};
assert!(
anchor_in_jsonc_block(DATA_MODEL, anchor),
@@ -49,6 +49,7 @@ enum VariantTag {
TermReuseAs,
TermLoop,
TermRecur,
TermIntrinsic,
// Pattern
PatternWild,
PatternVar,
@@ -96,6 +97,7 @@ const EXPECTED_VARIANTS: &[VariantTag] = &[
VariantTag::TermReuseAs,
VariantTag::TermLoop,
VariantTag::TermRecur,
VariantTag::TermIntrinsic,
VariantTag::PatternWild,
VariantTag::PatternVar,
VariantTag::PatternLit,
@@ -261,6 +263,9 @@ fn visit_term(t: &Term, observed: &mut HashSet<VariantTag>) {
}
}
}
Term::Intrinsic => {
observed.insert(VariantTag::TermIntrinsic);
}
}
}
+2
View File
@@ -136,6 +136,7 @@ fn spec_mentions_every_term_variant() {
})],
},
),
("(intrinsic", Term::Intrinsic),
];
for (anchor, term) in exemplars {
@@ -160,6 +161,7 @@ fn spec_mentions_every_term_variant() {
Term::Loop { .. } => "loop",
Term::Recur { .. } => "recur",
Term::New { .. } => "new",
Term::Intrinsic => "intrinsic",
};
assert!(
FORM_A_SPEC.contains(anchor),