Files
AILang/crates/ailang-core/tests/schema_coverage.rs
T
Brummel 76b21c00eb feat(lang): eliminate the Implicit ownership default — totality + the drop-soundness it demasks (#55)
Deletes `ParamMode::Implicit`. `ParamMode` is now `{Own, Borrow}`:
every fn-type slot on every signature carries an explicit `own` or
`borrow`, no defaulted position survives anywhere (model 0008 §2,
spec 0062). The parser rejects a bare fn-type slot; `borrow-return`
and `borrow-over-value` reject at the signature; the corpus is
migrated to minimal-ownership modes (consumed ⇒ own, read-only-heap
⇒ borrow, value ⇒ trivial-own). The documented `Implicit`-ret-mode
leak is fixed: an owned heap return now drops exactly once (live=0,
acceptance criterion 5).

This was the easy half. Removing the default ACTIVATED a family of
drop paths that `Implicit` had silently skipped — the pre-cutover
language was leaking (and in places mis-dropping) here rather than
crashing, because an Implicit scrutinee turned the drop off. Making
the modes explicit (Own) turned those paths on and exposed two
latent-bug clusters, all fixed RED-first as part of this cutover:

Drop-soundness family (four legs):
  A. lit-sub-pattern double-free — the desugar re-matched the same
     owned scrutinee in the lit fall-through; fixed by grouping
     consecutive same-ctor arms into one match (bind fields once),
     in ailang-core desugar.
  B. Cons-husk leak on non-tail arm bodies — the lit-sub-pattern
     desugar rebound the owned scrutinee via `Let $mp = xs`, which
     bumped consume_count and suppressed the existing fn-return
     partial_drop. Fixed by not rebinding a bare-Var scrutinee
     (one husk-freeing mechanism, not two).
  C. polymorphic `drop_<T>` rc_dec'd monomorphised value fields —
     the per-ADT drop fn was emitted once from the polymorphic
     TypeDef, defaulting type-var fields to ptr and rc_dec'ing
     inline Ints (segfault). Fixed with per-monomorph drop
     functions (new ailang-codegen::dropmono): the drop set is
     collected from the lowered MIR, value-type fields are skipped,
     heap fields still freed once; monomorphic-concrete ADTs keep
     their byte-identical un-suffixed drop symbol.
  D. static Str literal passed to an `(own Str)` param — the
     literal lowers to a header-less rodata constant; the callee's
     now-active rc_dec read its length field as a refcount and
     freed a static address (segfault). Fixed with the missing
     fourth StrRep::Static→Heap promotion in lower_to_mir's App arm,
     gated on Own mode (borrow args stay static, no regression).

over-strict-mode lint over-fired: it suggested `(borrow V)` for
value-typed params (which `borrow-over-value` rejects — own is the
only legal mode there) and fired on `(intrinsic)` bodies (whose
consumption the linearity walk cannot observe). Tightened to skip
both; contract 0008 updated to the narrowed firing scope.

Irreversible step — canonical-form hash reset (model 0008 §6,
acceptance criterion 6). Every signature now carries explicit modes,
so the hashable canonical JSON changed for every module. RATIFY:
the corpus-wide hash-pin reset (hash_pin, prelude_module_hash_pin,
mono_hash_stability, eq_ord_e2e, embed_export_hash_stable, the
ct4/iter*/loop_recur schema-extension pins) and the list ir_snapshot
golden were regenerated once, deliberately, as the intended one-time
consequence of removing the mode elision from the canonical form —
not a regression. Each regenerated hash verified deterministic across
two runs.

Also fixes a pre-existing latent failure surfaced by the verification
gate, unrelated to this cutover: the `every_contract_names_a_resolvable_
ratifying_test` resolver (design_index_pin) could not resolve the
" + " dual-link ratifying-test form (`uniqueness.rs + linearity.rs`)
that the #57 audit-close (dfdc65f) introduced — it shipped red on that
commit. Resolver taught the dual-link form, mirroring its sibling.

Verification: cargo test --workspace = 731 passed, 0 failed (twice,
stable); e2e 102 passed, no binary exits non-zero (corpus crash-free);
grep-clean for Implicit/fn_implicit/mode_eq across crates; every drop
fix confirmed via emitted IR + AILANG_RC_STATS balance on the head==K,
head!=K, and Nil paths. Three BLOCKEDs en route (the unsound first
husk-dec attempt, the over-strict derivation premise, the leg-B fix
direction) were each treated as a real design/spec gap and rediagnosed,
not patched over.

Supersedes #54 (return-position-only leak patch). Precondition #57
(linearity hardening) was already met. Spec docs/specs/0062, plan
docs/plans/0121.

closes #55
2026-06-02 00:03:46 +02:00

444 lines
14 KiB
Rust

//! Schema-coverage audit: every AST enum variant of `Def`, `Term`,
//! `Pattern`, `Literal`, `Type`, `ParamMode` is exercised by at
//! least one fixture under `examples/`.
//!
//! Why this exists: the round-trip tests in `ailang-surface` are
//! only as strong as the fixture corpus that drives them. A schema
//! variant with zero fixture coverage round-trips trivially — there
//! is nothing to round-trip. This test makes the corpus's coverage
//! observable, so a gap surfaces as a fail-loud test, not as silent
//! confidence.
//!
//! How it stays in sync with the AST: every match arm below is
//! exhaustive (no `_ => ...` wildcard). When a new AST variant
//! lands, the compiler rejects this file until the visitor and the
//! `VariantTag` enum are extended in lockstep.
//!
//! Pure reader: this test loads fixtures but does not modify any
//! committed content. A failure means a fixture must be added (in
//! a separate iteration); the test must not be relaxed.
use std::collections::HashSet;
use std::path::PathBuf;
use ailang_core::ast::{
Def, InstanceMethod, Literal, Module, NewArg, ParamMode, Pattern, Term, Type,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum VariantTag {
// Def
DefFn,
DefConst,
DefType,
DefClass,
DefInstance,
// Term
TermLit,
TermVar,
TermApp,
TermLet,
TermLetRec,
TermIf,
TermDo,
TermCtor,
TermMatch,
TermLam,
TermSeq,
TermClone,
TermReuseAs,
TermLoop,
TermRecur,
TermIntrinsic,
// Pattern
PatternWild,
PatternVar,
PatternLit,
PatternCtor,
// Literal
LiteralInt,
LiteralBool,
LiteralStr,
LiteralUnit,
LiteralFloat,
// Type
TypeCon,
TypeFn,
TypeVar,
TypeForall,
// ParamMode
ParamModeOwn,
ParamModeBorrow,
}
/// Lists every expected variant. Stored as a const array so that
/// adding a new `VariantTag` here and forgetting to add the
/// corresponding match arm in the visitor is a Rust compile error
/// (and vice versa).
const EXPECTED_VARIANTS: &[VariantTag] = &[
VariantTag::DefFn,
VariantTag::DefConst,
VariantTag::DefType,
VariantTag::DefClass,
VariantTag::DefInstance,
VariantTag::TermLit,
VariantTag::TermVar,
VariantTag::TermApp,
VariantTag::TermLet,
VariantTag::TermLetRec,
VariantTag::TermIf,
VariantTag::TermDo,
VariantTag::TermCtor,
VariantTag::TermMatch,
VariantTag::TermLam,
VariantTag::TermSeq,
VariantTag::TermClone,
VariantTag::TermReuseAs,
VariantTag::TermLoop,
VariantTag::TermRecur,
VariantTag::TermIntrinsic,
VariantTag::PatternWild,
VariantTag::PatternVar,
VariantTag::PatternLit,
VariantTag::PatternCtor,
VariantTag::LiteralInt,
VariantTag::LiteralBool,
VariantTag::LiteralStr,
VariantTag::LiteralUnit,
VariantTag::LiteralFloat,
VariantTag::TypeCon,
VariantTag::TypeFn,
VariantTag::TypeVar,
VariantTag::TypeForall,
VariantTag::ParamModeOwn,
VariantTag::ParamModeBorrow,
];
fn visit_def(def: &Def, observed: &mut HashSet<VariantTag>) {
match def {
Def::Fn(fd) => {
observed.insert(VariantTag::DefFn);
visit_type(&fd.ty, observed);
visit_term(&fd.body, observed);
}
Def::Const(cd) => {
observed.insert(VariantTag::DefConst);
visit_type(&cd.ty, observed);
visit_term(&cd.value, observed);
}
Def::Type(td) => {
observed.insert(VariantTag::DefType);
for ctor in &td.ctors {
for field_ty in &ctor.fields {
visit_type(field_ty, observed);
}
}
}
Def::Class(cd) => {
observed.insert(VariantTag::DefClass);
for m in &cd.methods {
visit_type(&m.ty, observed);
if let Some(body) = &m.default {
visit_term(body, observed);
}
}
}
Def::Instance(id) => {
observed.insert(VariantTag::DefInstance);
visit_type(&id.type_, observed);
for m in &id.methods {
visit_instance_method(m, observed);
}
}
}
}
fn visit_instance_method(m: &InstanceMethod, observed: &mut HashSet<VariantTag>) {
visit_term(&m.body, observed);
}
fn visit_term(t: &Term, observed: &mut HashSet<VariantTag>) {
match t {
Term::Lit { lit } => {
observed.insert(VariantTag::TermLit);
visit_literal(lit, observed);
}
Term::Var { .. } => {
observed.insert(VariantTag::TermVar);
}
Term::App { callee, args, .. } => {
observed.insert(VariantTag::TermApp);
visit_term(callee, observed);
for a in args {
visit_term(a, observed);
}
}
Term::Let { value, body, .. } => {
observed.insert(VariantTag::TermLet);
visit_term(value, observed);
visit_term(body, observed);
}
Term::LetRec { ty, body, in_term, .. } => {
observed.insert(VariantTag::TermLetRec);
visit_type(ty, observed);
visit_term(body, observed);
visit_term(in_term, observed);
}
Term::If { cond, then, else_ } => {
observed.insert(VariantTag::TermIf);
visit_term(cond, observed);
visit_term(then, observed);
visit_term(else_, observed);
}
Term::Do { args, .. } => {
observed.insert(VariantTag::TermDo);
for a in args {
visit_term(a, observed);
}
}
Term::Ctor { args, .. } => {
observed.insert(VariantTag::TermCtor);
for a in args {
visit_term(a, observed);
}
}
Term::Match { scrutinee, arms } => {
observed.insert(VariantTag::TermMatch);
visit_term(scrutinee, observed);
for arm in arms {
visit_pattern(&arm.pat, observed);
visit_term(&arm.body, observed);
}
}
Term::Lam { param_tys, ret_ty, body, .. } => {
observed.insert(VariantTag::TermLam);
for ty in param_tys {
visit_type(ty, observed);
}
visit_type(ret_ty, observed);
visit_term(body, observed);
}
Term::Seq { lhs, rhs } => {
observed.insert(VariantTag::TermSeq);
visit_term(lhs, observed);
visit_term(rhs, observed);
}
Term::Clone { value } => {
observed.insert(VariantTag::TermClone);
visit_term(value, observed);
}
Term::ReuseAs { source, body } => {
observed.insert(VariantTag::TermReuseAs);
visit_term(source, observed);
visit_term(body, observed);
}
Term::Loop { binders, body } => {
observed.insert(VariantTag::TermLoop);
for b in binders {
visit_type(&b.ty, observed);
visit_term(&b.init, observed);
}
visit_term(body, observed);
}
Term::Recur { args } => {
observed.insert(VariantTag::TermRecur);
for a in args {
visit_term(a, observed);
}
}
Term::New { args, .. } => {
// prep.2 (kernel-extension-mechanics): functional construction.
// The variant is intentionally NOT added to `VariantTag` /
// `EXPECTED_VARIANTS` in prep.2 — no .ail fixture in the
// current corpus emits `"t": "new"` (per the iter's
// out-of-scope note), so an EXPECTED entry would fail the
// coverage check. A future milestone that ships a Term::New
// fixture extends both the enum and the expected list.
for arg in args {
match arg {
NewArg::Type(t) => visit_type(t, observed),
NewArg::Value(v) => visit_term(v, observed),
}
}
}
Term::Intrinsic => {
observed.insert(VariantTag::TermIntrinsic);
}
}
}
fn visit_pattern(p: &Pattern, observed: &mut HashSet<VariantTag>) {
match p {
Pattern::Wild => {
observed.insert(VariantTag::PatternWild);
}
Pattern::Var { .. } => {
observed.insert(VariantTag::PatternVar);
}
Pattern::Lit { lit } => {
observed.insert(VariantTag::PatternLit);
visit_literal(lit, observed);
}
Pattern::Ctor { fields, .. } => {
observed.insert(VariantTag::PatternCtor);
for f in fields {
visit_pattern(f, observed);
}
}
}
}
fn visit_literal(l: &Literal, observed: &mut HashSet<VariantTag>) {
match l {
Literal::Int { .. } => {
observed.insert(VariantTag::LiteralInt);
}
Literal::Bool { .. } => {
observed.insert(VariantTag::LiteralBool);
}
Literal::Str { .. } => {
observed.insert(VariantTag::LiteralStr);
}
Literal::Unit => {
observed.insert(VariantTag::LiteralUnit);
}
Literal::Float { .. } => {
observed.insert(VariantTag::LiteralFloat);
}
}
}
fn visit_type(t: &Type, observed: &mut HashSet<VariantTag>) {
match t {
Type::Con { args, .. } => {
observed.insert(VariantTag::TypeCon);
for a in args {
visit_type(a, observed);
}
}
Type::Fn { params, param_modes, ret, ret_mode, .. } => {
observed.insert(VariantTag::TypeFn);
for p in params {
visit_type(p, observed);
}
for m in param_modes {
visit_param_mode(m, observed);
}
visit_type(ret, observed);
visit_param_mode(ret_mode, observed);
}
Type::Var { .. } => {
observed.insert(VariantTag::TypeVar);
}
Type::Forall { body, .. } => {
observed.insert(VariantTag::TypeForall);
visit_type(body, observed);
}
}
}
fn visit_param_mode(m: &ParamMode, observed: &mut HashSet<VariantTag>) {
match m {
ParamMode::Own => {
observed.insert(VariantTag::ParamModeOwn);
}
ParamMode::Borrow => {
observed.insert(VariantTag::ParamModeBorrow);
}
}
}
fn visit_module(m: &Module, observed: &mut HashSet<VariantTag>) {
for def in &m.defs {
visit_def(def, observed);
}
}
fn examples_dir() -> PathBuf {
let crate_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
crate_dir.parent().unwrap().parent().unwrap().join("examples")
}
/// Fixtures that intentionally do NOT parse — the `#55` cutover
/// reject corpus. Negative fixtures whose whole point is that the
/// parser rejects them, so they have no AST to scan for variant
/// coverage and the scan must skip them. Mirrors the same list in
/// `crates/ail/tests/roundtrip_cli.rs`.
///
/// - `bare_slot_reject.ail`: a bare fn-type slot with no mode. The
/// binary-ParamMode parser rejects it ("fn-type slot requires a
/// mode: write (own T) or (borrow T)").
const NON_PARSEABLE_FIXTURES: &[&str] = &["bare_slot_reject.ail"];
fn list_ail_fixtures() -> Vec<PathBuf> {
let dir = examples_dir();
let mut paths: Vec<PathBuf> = std::fs::read_dir(&dir)
.unwrap_or_else(|e| panic!("read_dir({}): {e}", dir.display()))
.filter_map(|entry| entry.ok())
.map(|e| e.path())
.filter(|p| {
p.file_name()
.and_then(|n| n.to_str())
.map(|n| n.ends_with(".ail") && !NON_PARSEABLE_FIXTURES.contains(&n))
.unwrap_or(false)
})
.collect();
paths.sort();
paths
}
#[test]
fn every_ast_variant_is_observed_in_the_fixture_corpus() {
let fixtures = list_ail_fixtures();
assert!(
!fixtures.is_empty(),
"no .ail fixtures found under {}",
examples_dir().display()
);
let mut observed: HashSet<VariantTag> = HashSet::new();
let mut load_failures = Vec::<String>::new();
for path in &fixtures {
match ailang_surface::load_module(path) {
Ok(m) => visit_module(&m, &mut observed),
Err(e) => load_failures.push(format!("{}: {e}", path.display())),
}
}
// Load failures fail the test on their own — a fixture that
// does not load is a corpus bug, surface it loud.
if !load_failures.is_empty() {
panic!(
"{} fixture(s) failed to load during coverage scan:\n{}",
load_failures.len(),
load_failures.join("\n")
);
}
let missing: Vec<VariantTag> = EXPECTED_VARIANTS
.iter()
.copied()
.filter(|v| !observed.contains(v))
.collect();
if !missing.is_empty() {
let names: Vec<String> = missing.iter().map(|v| format!("{v:?}")).collect();
panic!(
"{} AST variant(s) have NO fixture coverage in {}:\n {}\n\n\
every variant must be exercised by at least one fixture; \
add a fixture that uses each missing variant (do NOT \
weaken this test).",
missing.len(),
examples_dir().display(),
names.join("\n ")
);
}
eprintln!(
"schema coverage ok: {} variants observed across {} fixtures",
observed.len(),
fixtures.len()
);
}