Files
AILang/crates/ail/tests/roundtrip_cli.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

181 lines
6.5 KiB
Rust

//! CLI-pipeline idempotency gate: every `examples/*.ail` survives
//! `ail parse | ail render | ail parse` with byte identity on the
//! canonical JSON output.
//!
//! This is the user-facing-surface defence line. Crate-internal
//! roundtrip tests in `ailang-surface` cover the same property
//! at the library level; this test additionally protects the
//! `ail parse` and `ail render` CLI wrappers from drift (output
//! formatting, exit codes, stdout framing).
//!
//! Pure reader: the test writes only to a `tempfile::TempDir`
//! that lives outside the repo and is cleaned up by Drop. No
//! committed content is mutated.
//!
//! Retired iter form-a.1 T9:
//! `cli_render_then_parse_preserves_canonical_bytes_on_every_fixture`
//! (walked `.ail.json` corpus; replaced by the corpus-flipped
//! `cli_parse_then_render_then_parse_is_idempotent` below, added in
//! T1). The `list_json_fixtures` helper and `roundtrip_one` helper
//! were the only consumers of `.ail.json` walks and are retired
//! alongside.
use std::path::{Path, PathBuf};
use std::process::Command;
fn ail_bin() -> &'static str {
env!("CARGO_BIN_EXE_ail")
}
fn workspace_root() -> PathBuf {
let manifest_dir = env!("CARGO_MANIFEST_DIR");
Path::new(manifest_dir).parent().unwrap().parent().unwrap().to_path_buf()
}
fn examples_dir() -> PathBuf {
workspace_root().join("examples")
}
/// Fixtures that intentionally do NOT parse — the `#55` cutover
/// reject corpus. These are negative fixtures whose whole point is
/// that the parser rejects them, so `parse∘render∘parse` is not a
/// meaningful property for them and the harness must skip them.
///
/// Scope is deliberately minimal: only fixtures that fail at the
/// PARSE stage belong here. The other `*reject*.ail` cutover
/// fixtures (`borrow_return_reject`, `borrow_value_reject`,
/// `own_return_provenance_reject`, the `embed_export_*_rejected`
/// set, …) parse cleanly and are rejected only later at CHECK time,
/// so they round-trip fine and are NOT excluded.
///
/// - `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
}
/// CLI-pipeline idempotency (post-form-a-default-authoring §C3): for
/// every `.ail` fixture, the user-facing pipeline
/// `ail parse <ail> | ail render | ail parse` is byte-identical
/// to direct `ail parse <ail>`. Pins drift internal tests cannot see.
#[test]
fn cli_parse_then_render_then_parse_is_idempotent() {
let fixtures = list_ail_fixtures();
assert!(
!fixtures.is_empty(),
"no .ail fixtures found under {}",
examples_dir().display()
);
let tmpdir = tempfile::TempDir::new().expect("create tempdir");
let mut checked = 0usize;
let mut failures = Vec::<String>::new();
for ail_path in &fixtures {
// Direct parse → JSON tempfile.
let json1 = tmpdir.path().join(format!("v1_{checked}.ail.json"));
let parse1 = Command::new(ail_bin())
.args([
"parse",
ail_path.to_str().unwrap(),
"-o",
json1.to_str().unwrap(),
])
.output()
.expect("spawn ail parse #1");
if !parse1.status.success() {
failures.push(format!(
"{}: first ail parse exit={:?}\nstderr: {}",
ail_path.display(),
parse1.status.code(),
String::from_utf8_lossy(&parse1.stderr),
));
checked += 1;
continue;
}
// Render that JSON → .ail tempfile.
let ail_round = tmpdir.path().join(format!("round_{checked}.ail"));
let rendered = Command::new(ail_bin())
.args(["render", json1.to_str().unwrap()])
.output()
.expect("spawn ail render");
if !rendered.status.success() {
failures.push(format!(
"{}: ail render exit={:?}\nstderr: {}",
ail_path.display(),
rendered.status.code(),
String::from_utf8_lossy(&rendered.stderr),
));
checked += 1;
continue;
}
std::fs::write(&ail_round, &rendered.stdout)
.expect("write ail_round tempfile");
// Re-parse → second JSON tempfile.
let json2 = tmpdir.path().join(format!("v2_{checked}.ail.json"));
let parse2 = Command::new(ail_bin())
.args([
"parse",
ail_round.to_str().unwrap(),
"-o",
json2.to_str().unwrap(),
])
.output()
.expect("spawn ail parse #2");
if !parse2.status.success() {
failures.push(format!(
"{}: second ail parse exit={:?}\nstderr: {}",
ail_path.display(),
parse2.status.code(),
String::from_utf8_lossy(&parse2.stderr),
));
checked += 1;
continue;
}
// Assert the two canonical JSONs are byte-equal.
let b1 = std::fs::read(&json1).expect("read json1");
let b2 = std::fs::read(&json2).expect("read json2");
if b1 != b2 {
let s1 = String::from_utf8_lossy(&b1).into_owned();
let s2 = String::from_utf8_lossy(&b2).into_owned();
failures.push(format!(
"{}: CLI parse|render|parse non-idempotent.\n v1: {s1}\n v2: {s2}",
ail_path.display(),
));
}
checked += 1;
}
if !failures.is_empty() {
panic!(
"CLI parse|render|parse non-idempotent on {} of {} fixtures:\n{}",
failures.len(),
checked,
failures.join("\n\n")
);
}
assert!(checked > 0, "no .ail fixtures found");
eprintln!("CLI parse|render|parse idempotent for {checked} fixtures");
}