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
This commit is contained in:
@@ -76,10 +76,6 @@ enum Cmd {
|
||||
/// `render | parse` reproduces the input's canonical bytes
|
||||
/// (gated by `crates/ailang-surface/tests/round_trip.rs`).
|
||||
Render { path: PathBuf },
|
||||
/// THROWAWAY (spec 0062): rewrite every bare fn-type slot in a
|
||||
/// `.ail` file as `(own …)`, preserving explicit `(own)`/`(borrow)`.
|
||||
/// Removed in the Implicit-deletion cutover.
|
||||
MigrateModes { path: PathBuf },
|
||||
/// Prints a single definition as JSON or pretty text.
|
||||
Describe {
|
||||
path: PathBuf,
|
||||
@@ -444,22 +440,6 @@ fn main() -> Result<()> {
|
||||
let m = ailang_surface::load_module(&path)?;
|
||||
print!("{}", ailang_surface::print(&m));
|
||||
}
|
||||
Cmd::MigrateModes { path } => {
|
||||
let src = std::fs::read_to_string(&path)?;
|
||||
let mut m = ailang_surface::parse(&src)?;
|
||||
ailang_core::ast::for_each_fn_type_mut(&mut m, &mut |n, pm, rm| {
|
||||
pm.resize(n, ailang_core::ast::ParamMode::Own);
|
||||
for x in pm.iter_mut() {
|
||||
if matches!(x, ailang_core::ast::ParamMode::Implicit) {
|
||||
*x = ailang_core::ast::ParamMode::Own;
|
||||
}
|
||||
}
|
||||
if matches!(rm, ailang_core::ast::ParamMode::Implicit) {
|
||||
*rm = ailang_core::ast::ParamMode::Own;
|
||||
}
|
||||
});
|
||||
std::fs::write(&path, ailang_surface::print(&m))?;
|
||||
}
|
||||
Cmd::Prose { path } => {
|
||||
// load via `load_module` (single-module mode,
|
||||
// matching how `render` / `parse` work). Workspace-wide
|
||||
|
||||
@@ -39,7 +39,7 @@ fn tempdir_with_missing_import() -> PathBuf {
|
||||
let mut f = std::fs::File::create(&entry).expect("create entry .ail");
|
||||
writeln!(
|
||||
f,
|
||||
"(module test_missing_import\n (import this_module_does_not_exist)\n (fn main\n (type (fn-type (params) (ret (con Unit)) (effects IO)))\n (params)\n (body (do io/print_str \"hello\"))))"
|
||||
"(module test_missing_import\n (import this_module_does_not_exist)\n (fn main\n (type (fn-type (params) (ret (own (con Unit))) (effects IO)))\n (params)\n (body (do io/print_str \"hello\"))))"
|
||||
).expect("write fixture");
|
||||
entry
|
||||
}
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
//! RED-pin for leg (C) of the drop-soundness bug family the
|
||||
//! Implicit-cutover (#55) surfaced: a polymorphic ctor's per-type
|
||||
//! drop fn rc_dec's a type-parameter field even when the field is
|
||||
//! monomorphised at a value type (Int/Bool/Float/Unit).
|
||||
//!
|
||||
//! Property protected: under `--alloc=rc`, dropping a value of a
|
||||
//! polymorphic ADT whose ctor field is monomorphised at a value type
|
||||
//! must NOT emit `ailang_rc_dec` on that field. The field is stored
|
||||
//! inline as a raw scalar (an i64 `7`, not a heap pointer), so an
|
||||
//! `rc_dec` dereferences the scalar-as-pointer and crashes. The
|
||||
//! binary must run to completion, print the inner value, and the
|
||||
//! runtime RC stats line must report `live == 0` (the single ADT
|
||||
//! slab is freed exactly once, with no spurious dec of the inline
|
||||
//! value field).
|
||||
//!
|
||||
//! Root cause: `crates/ailang-codegen/src/drop.rs`
|
||||
//! `emit_drop_fn_for_type` (mirrored in `emit_iterative_drop_fn_for_type`
|
||||
//! and `emit_partial_drop_fn_for_type`) emits the per-type drop fn ONCE
|
||||
//! from the polymorphic `Def::Type` declaration — never per-monomorph.
|
||||
//! For each ctor field it computes `llvm_type(fty)` where `fty` is the
|
||||
//! declared field type. For a type-parameter field that type is a
|
||||
//! `Type::Var`, which `llvm_type` rejects (synth.rs returns `Err`); the
|
||||
//! `.unwrap_or_else(|_| "ptr".into())` at the field loop then silently
|
||||
//! treats the var-typed field as a boxed pointer and emits `rc_dec`.
|
||||
//! At the `Box Int` monomorph the field is an inline `i64`, so the
|
||||
//! emitted `rc_dec` dereferences the integer value -> SIGSEGV.
|
||||
//!
|
||||
//! As of HEAD (the in-flight Implicit cutover) this test fails: the
|
||||
//! binary exits 139 (SIGSEGV) before printing anything. Pre-cutover
|
||||
//! the bug was latent — Implicit scrutinees skipped the drop path
|
||||
//! entirely, so the mistyped drop never ran (it leaked instead of
|
||||
//! crashing).
|
||||
//!
|
||||
//! A single-field `Box a` at `Int` is the minimal trigger. The fix
|
||||
//! must still dec genuinely-heap fields (e.g. a `Box Str` field must
|
||||
//! free its slab exactly once) and must hold for the partial-drop and
|
||||
//! nested-monomorph variants — see the debugger handoff for the fix
|
||||
//! locus and soundness reasoning.
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
fn ail_bin() -> &'static str {
|
||||
env!("CARGO_BIN_EXE_ail")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alloc_rc_value_type_field_is_not_rc_dec_dropped() {
|
||||
let manifest_dir = env!("CARGO_MANIFEST_DIR");
|
||||
let workspace = Path::new(manifest_dir).parent().unwrap().parent().unwrap();
|
||||
let src = workspace
|
||||
.join("examples")
|
||||
.join("drop_value_field_no_segfault_pin.ail");
|
||||
let tmp = std::env::temp_dir().join(format!(
|
||||
"ailang_drop_value_field_no_segfault_pin_{}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::create_dir_all(&tmp).unwrap();
|
||||
let out = tmp.join("bin");
|
||||
let status = Command::new(ail_bin())
|
||||
.args(["build", src.to_str().unwrap(), "--alloc=rc", "-o"])
|
||||
.arg(&out)
|
||||
.status()
|
||||
.expect("ail build failed to run");
|
||||
assert!(
|
||||
status.success(),
|
||||
"ail build --alloc=rc failed for drop_value_field_no_segfault_pin.ail"
|
||||
);
|
||||
let output = Command::new(&out)
|
||||
.env("AILANG_RC_STATS", "1")
|
||||
.output()
|
||||
.expect("execute binary");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"binary exited non-zero (status {:?}): the polymorphic drop fn \
|
||||
drop_<m>_Box rc_dec's the type-parameter field, which at the \
|
||||
Box Int monomorph is the inline i64 `7` (not a heap pointer), \
|
||||
so rc_dec(7) dereferences the scalar-as-pointer and SIGSEGVs. \
|
||||
Fix in crates/ailang-codegen/src/drop.rs: do not dec a field \
|
||||
whose monomorphised type is a value type.",
|
||||
output.status
|
||||
);
|
||||
let stdout = String::from_utf8(output.stdout).expect("stdout utf8");
|
||||
assert_eq!(
|
||||
stdout.trim_end(),
|
||||
"7",
|
||||
"unboxing MkBox 7 at Int must print 7; got {stdout:?}"
|
||||
);
|
||||
let stderr = String::from_utf8(output.stderr).expect("stderr utf8");
|
||||
let stats_line = stderr
|
||||
.lines()
|
||||
.find(|l| l.starts_with("ailang_rc_stats:"))
|
||||
.unwrap_or_else(|| {
|
||||
panic!("missing ailang_rc_stats line in stderr; stderr was:\n{stderr}")
|
||||
});
|
||||
let mut allocs: Option<u64> = None;
|
||||
let mut frees: Option<u64> = None;
|
||||
let mut live: Option<i64> = None;
|
||||
for tok in stats_line.split_whitespace() {
|
||||
if let Some(v) = tok.strip_prefix("allocs=") {
|
||||
allocs = v.parse().ok();
|
||||
} else if let Some(v) = tok.strip_prefix("frees=") {
|
||||
frees = v.parse().ok();
|
||||
} else if let Some(v) = tok.strip_prefix("live=") {
|
||||
live = v.parse().ok();
|
||||
}
|
||||
}
|
||||
let allocs = allocs.expect("missing allocs= field");
|
||||
let frees = frees.expect("missing frees= field");
|
||||
let live = live.expect("missing live= field");
|
||||
assert_eq!(
|
||||
live, 0,
|
||||
"RC imbalance after dropping a value-type-field ADT \
|
||||
(allocs={allocs} frees={frees} live={live}); the Box slab \
|
||||
must be freed exactly once and the inline Int field must \
|
||||
never be dec'd."
|
||||
);
|
||||
assert_eq!(
|
||||
allocs, frees,
|
||||
"alloc/free mismatch (allocs={allocs} frees={frees} live={live})"
|
||||
);
|
||||
}
|
||||
+180
-26
@@ -82,6 +82,80 @@ fn sum_1_to_10_is_55() {
|
||||
assert_eq!(stdout.trim(), "55");
|
||||
}
|
||||
|
||||
/// Property: a static `Str` literal passed by value into an `(own Str)`
|
||||
/// parameter that the callee drops must be RC-sound — dropped exactly
|
||||
/// once, no double-free, no leak.
|
||||
///
|
||||
/// RED for the #55-cutover drop-soundness crash. The literal lowers to
|
||||
/// `StrRep::Static` (a header-less rodata constant), but the cutover
|
||||
/// activates the Own-param drop path, which emits `ailang_rc_dec` on
|
||||
/// the unused param. `rc_dec` reads `payload - 8` as a refcount and
|
||||
/// `free()`s a static address -> SIGSEGV. `lower_to_mir`'s `Term::App`
|
||||
/// arm must flip such an argument to `StrRep::Heap` (str_clone into an
|
||||
/// owned slab), the same promotion mir.4 applies to loop-carried Str
|
||||
/// literals. Distinct root from legs A/B (the lit-pattern desugar); the
|
||||
/// match in eq_demo merely happens to drop its owned Str scrutinee too.
|
||||
///
|
||||
/// The assertion is robust against the stats-path masking leg A showed:
|
||||
/// it runs the binary on the NON-stats path (catching the SIGSEGV via
|
||||
/// the exit status) AND on the stats path asserting `live=0` /
|
||||
/// `frees==allocs`.
|
||||
#[test]
|
||||
fn own_str_literal_arg_is_dropped_exactly_once() {
|
||||
let manifest_dir = env!("CARGO_MANIFEST_DIR");
|
||||
let workspace = Path::new(manifest_dir).parent().unwrap().parent().unwrap();
|
||||
let src = workspace.join("examples").join("own_str_arg_drop.ail");
|
||||
let tmp = std::env::temp_dir().join(format!(
|
||||
"ailang_e2e_own_str_arg_drop_{}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::create_dir_all(&tmp).unwrap();
|
||||
let out = tmp.join("bin");
|
||||
|
||||
let status = Command::new(ail_bin())
|
||||
.args(["build", src.to_str().unwrap(), "-o"])
|
||||
.arg(&out)
|
||||
.status()
|
||||
.expect("ail build failed to run");
|
||||
assert!(status.success(), "ail build failed for own_str_arg_drop.ail");
|
||||
|
||||
// NON-stats path: this is the crashing path (SIGSEGV / double-free).
|
||||
let plain = Command::new(&out).output().expect("execute binary");
|
||||
assert!(
|
||||
plain.status.success(),
|
||||
"binary {} exited non-zero (expected success; got {:?}) — \
|
||||
the owned Str literal was dropped on a header-less static",
|
||||
out.display(),
|
||||
plain.status.code()
|
||||
);
|
||||
assert_eq!(
|
||||
String::from_utf8(plain.stdout).expect("stdout utf8").trim(),
|
||||
"0"
|
||||
);
|
||||
|
||||
// Stats path: RC balance must close — no leaked or double-freed Str.
|
||||
let stats = Command::new(&out)
|
||||
.env("AILANG_RC_STATS", "1")
|
||||
.output()
|
||||
.expect("execute binary with RC stats");
|
||||
assert!(
|
||||
stats.status.success(),
|
||||
"binary {} (RC stats) exited non-zero (expected success; got {:?})",
|
||||
out.display(),
|
||||
stats.status.code()
|
||||
);
|
||||
let stderr = String::from_utf8(stats.stderr).expect("stderr utf8");
|
||||
let line = stderr
|
||||
.lines()
|
||||
.find(|l| l.starts_with("ailang_rc_stats:"))
|
||||
.unwrap_or_else(|| panic!("no ailang_rc_stats line in stderr: {stderr:?}"));
|
||||
// Format: `ailang_rc_stats: allocs=N frees=M live=K`
|
||||
assert!(
|
||||
line.contains("live=0"),
|
||||
"RC balance not closed: {line:?} (live != 0 means leak or double-free)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loop_recur_sum_to_runs_to_value() {
|
||||
let stdout = build_and_run("loop_sum_to_run.ail");
|
||||
@@ -1294,7 +1368,7 @@ fn intrinsic_in_user_module_is_rejected() {
|
||||
let src = tmp.join("intr_user.ail");
|
||||
std::fs::write(
|
||||
&src,
|
||||
"(module intr_user (fn f (type (fn-type (params (con Int)) (ret (con Int)))) (params n) (intrinsic)))",
|
||||
"(module intr_user (fn f (type (fn-type (params (own (con Int))) (ret (own (con Int))))) (params n) (intrinsic)))",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
@@ -1344,6 +1418,88 @@ fn lit_pat_demo() {
|
||||
assert_eq!(lines, vec!["100", "200", "999", "-1", "0", "7"]);
|
||||
}
|
||||
|
||||
/// RED (refs #55, Implicit-cutover double-drop). Property protected:
|
||||
/// a ctor arm with a literal sub-pattern in a non-tail field —
|
||||
/// `(Cons (pat-lit K) _)` — drops the matched value's owned children
|
||||
/// EXACTLY ONCE, on both the head==K and head!=K paths.
|
||||
///
|
||||
/// The 16c lit-sub-pattern desugar lowers the arm into an outer
|
||||
/// Cons-match (binding the fields) wrapping `if (== head K) body
|
||||
/// else fall_k`; `fall_k` re-matches the same owned scrutinee, re-
|
||||
/// binding its children. Post-#55 the param mode is `Own`, so the
|
||||
/// match_lower.rs arm-close Iter-A drop (gated on `scrutinee_is_owned`)
|
||||
/// fires on the tail child in BOTH the re-match arm AND the enclosing
|
||||
/// lit-arm's join — `arg_xs+16` is dropped twice → double-free →
|
||||
/// SIGSEGV on the head!=K path.
|
||||
///
|
||||
/// Two assertions, so the symptom is pinned independently of the
|
||||
/// stats-drop masking divergence:
|
||||
/// 1. `build_and_run` (no AILANG_RC_STATS): asserts the binary exits
|
||||
/// 0 AND prints `0` then `7` — surfaces the segfault directly.
|
||||
/// 2. rc-stats: `live == 0` and `frees == allocs` — pins single-drop
|
||||
/// (a double-free would over-count frees / corrupt the heap)
|
||||
/// rather than mere exit-0.
|
||||
#[test]
|
||||
fn lit_pat_ctor_tail_drop_single_drop() {
|
||||
let stdout = build_and_run("lit_pat_ctor_tail_drop.ail");
|
||||
let lines: Vec<&str> = stdout.lines().collect();
|
||||
assert_eq!(lines, vec!["0", "7"]);
|
||||
|
||||
let (stats_stdout, allocs, frees, live) =
|
||||
build_and_run_with_rc_stats("lit_pat_ctor_tail_drop.ail");
|
||||
assert_eq!(
|
||||
stats_stdout.lines().collect::<Vec<_>>(),
|
||||
vec!["0", "7"],
|
||||
"stdout under rc-stats must match the non-stats run"
|
||||
);
|
||||
assert_eq!(live, 0, "owned IntList children must all be freed (no leak)");
|
||||
assert_eq!(
|
||||
frees, allocs,
|
||||
"every alloc freed exactly once — a double-free over-counts frees"
|
||||
);
|
||||
}
|
||||
|
||||
/// RED (refs #55, Implicit-cutover husk leak — leg B, Nil sub-case).
|
||||
/// Property protected: an owned scrutinee threaded through the
|
||||
/// lit-sub-pattern chain desugar has its OUTER cell freed exactly once
|
||||
/// on the Nil return path — the path that matches the Nil arm and
|
||||
/// touches neither inner Cons re-match.
|
||||
///
|
||||
/// The 16c desugar takes `first_or_default` off the `is_flat`
|
||||
/// fast-path (it has a lit sub-pattern arm), let-binds the owned
|
||||
/// scrutinee into a fresh `$mp` var, and chains single-level matches.
|
||||
/// Post-#55 the `Let $mp = xs` consumes `xs` (consume_count := 1),
|
||||
/// which trips the codegen fn-return gate (lib.rs ~1522, `if
|
||||
/// consume_count != 0 { continue }`) and suppresses the husk free a
|
||||
/// single-match owned fn would emit as `partial_drop_<T>(arg_xs, _)`.
|
||||
/// The husk obligation also moves to the internal `$mp` binder the
|
||||
/// gate never inspects. The Nil cell leaks -> live=1.
|
||||
///
|
||||
/// Distinct from `lit_pat_ctor_tail_drop_single_drop`, which only
|
||||
/// drives the Cons path: a fix that frees the husk on the Cons path
|
||||
/// but forgets the Nil path passes that test while still leaking here.
|
||||
#[test]
|
||||
fn lit_pat_nil_scrutinee_single_drop() {
|
||||
let stdout = build_and_run("lit_pat_nil_scrutinee_drop.ail");
|
||||
assert_eq!(stdout.lines().collect::<Vec<_>>(), vec!["-1"]);
|
||||
|
||||
let (stats_stdout, allocs, frees, live) =
|
||||
build_and_run_with_rc_stats("lit_pat_nil_scrutinee_drop.ail");
|
||||
assert_eq!(
|
||||
stats_stdout.lines().collect::<Vec<_>>(),
|
||||
vec!["-1"],
|
||||
"stdout under rc-stats must match the non-stats run"
|
||||
);
|
||||
assert_eq!(
|
||||
live, 0,
|
||||
"the Nil scrutinee's outer cell must be freed (no husk leak)"
|
||||
);
|
||||
assert_eq!(
|
||||
frees, allocs,
|
||||
"every alloc freed exactly once — a double-free over-counts frees"
|
||||
);
|
||||
}
|
||||
|
||||
/// `__unreachable__` as an explicit user-callable
|
||||
/// primitive. Property protected: a polymorphic `forall a. a` value
|
||||
/// reference (a) typechecks against any expected type at the use
|
||||
@@ -2395,43 +2551,41 @@ fn alloc_rc_let_binder_for_owned_returning_app_drops_at_scope_close() {
|
||||
);
|
||||
}
|
||||
|
||||
/// a let-binder whose value is the
|
||||
/// result of an `Implicit`-ret-mode (default, unannotated) call must
|
||||
/// NOT be trackable. Implicit is the back-compat lane that 18c.3
|
||||
/// documented as "params don't get any dec — leak rather than mis-
|
||||
/// dec"; the symmetric carve-out for ret-modes is "Implicit-returning
|
||||
/// calls do not flow ownership to the caller, the caller must NOT
|
||||
/// dec".
|
||||
/// a let-binder whose value is the result of an `(own T)`-ret-mode
|
||||
/// call IS trackable for scope-close drop. ParamMode is binary
|
||||
/// `{Own, Borrow}`: an unannotated return defaults to `Own`, the
|
||||
/// callee's `(own T)` return signs the static contract that the
|
||||
/// caller now owns the returned cell, and the let-scope close emits
|
||||
/// the caller dec so the cell frees exactly once.
|
||||
///
|
||||
/// If `is_rc_heap_allocated` were mistakenly to fire on this shape,
|
||||
/// the let-scope close would emit an unjustified dec — refcount
|
||||
/// underflow at runtime (the cell's RC reaches zero before any other
|
||||
/// owner had a chance to dec). The fixture under `--alloc=rc` must:
|
||||
/// The fixture under `--alloc=rc` must:
|
||||
///
|
||||
/// (1) Build cleanly (no consume-while-borrowed false positive,
|
||||
/// parse error, or unimplemented).
|
||||
/// (2) Exit cleanly with stdout `7` — the unboxed Int from the cell.
|
||||
/// (3) Report `live = 1` — the one MkT cell leaks. The leak is the
|
||||
/// intentional Implicit-mode behaviour; if codegen ever started
|
||||
/// dec'ing this shape it would crash with refcount underflow
|
||||
/// before the leak number could even be observed.
|
||||
/// (3) Report `live = 0` — the one MkT cell frees. The own-return
|
||||
/// contract flows ownership to the caller, which dec's the
|
||||
/// binder at scope close. This is the typed-MIR leak fix spec
|
||||
/// 0062 delivers (acceptance criterion 5): the legacy `Implicit`
|
||||
/// back-compat lane that left this shape leaked (`live = 1`) is
|
||||
/// gone, so the owned-ret binder is dropped exactly once.
|
||||
///
|
||||
/// This test is the negative-side companion to
|
||||
/// This test is the positive companion to
|
||||
/// `alloc_rc_let_binder_for_owned_returning_app_drops_at_scope_close`:
|
||||
/// the asymmetry between (own)-ret-mode (live=0) and Implicit-ret-mode
|
||||
/// (live=1) is the documented contract.
|
||||
/// both `(own)`-ret-mode shapes free at scope close (`live = 0`).
|
||||
#[test]
|
||||
fn alloc_rc_let_binder_for_implicit_returning_app_does_not_drop() {
|
||||
fn alloc_rc_let_binder_for_owned_returning_app_drops_exactly_once() {
|
||||
let (stdout, allocs, frees, live) =
|
||||
build_and_run_with_rc_stats("rc_let_implicit_returning_app.ail");
|
||||
assert_eq!(stdout.trim(), "7", "alloc(7) -> unbox should print 7");
|
||||
assert_eq!(
|
||||
live, 1,
|
||||
"Implicit-ret-mode App must leak (not crash with refcount \
|
||||
underflow); allocs={allocs} frees={frees} live={live}. \
|
||||
A live count of 0 means is_rc_heap_allocated mistakenly \
|
||||
marked Implicit-ret-mode App as trackable; a non-zero exit \
|
||||
means the unjustified dec triggered the underflow guard."
|
||||
live, 0,
|
||||
"owned-ret-mode App binder must drop exactly once at scope \
|
||||
close (post-cutover: no Implicit leak lane); allocs={allocs} \
|
||||
frees={frees} live={live}. A live count of 1 would mean \
|
||||
is_rc_heap_allocated failed to mark the owned-ret App as \
|
||||
trackable; a non-zero exit means an unjustified dec triggered \
|
||||
the underflow guard."
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -136,7 +136,7 @@ fn eq_ord_user_adt_eq_intbox_hash_stable() {
|
||||
// sweep — the call site symbol name shifts, body hash follows.
|
||||
let h = def_hash(&Def::Fn(eq_intbox.clone()));
|
||||
assert_eq!(
|
||||
h, "ceb466964df0e8d1",
|
||||
h, "e639d41fc49b1524",
|
||||
"eq__IntBox body hash drifted — see mono_hash_stability.rs for the resolution pattern; captured: {h}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ fn migrate_canonical_types_rewrites_bare_xmod_term_ctor() {
|
||||
"imports": [{ "module": "other" }],
|
||||
"defs": [{
|
||||
"kind": "fn", "name": "f",
|
||||
"type": { "k": "fn", "params": [], "ret": { "k": "con", "name": "Unit" }, "effects": [] },
|
||||
"type": { "k": "fn", "params": [], "param_modes": [], "ret": { "k": "con", "name": "Unit" }, "ret_mode": "own", "effects": [] },
|
||||
"params": [],
|
||||
"body": { "t": "ctor", "type": "Foo", "ctor": "MkFoo", "args": [] }
|
||||
}],
|
||||
@@ -111,7 +111,7 @@ fn migrate_canonical_types_rewrites_bare_xmod_type_con() {
|
||||
"imports": [{ "module": "other" }],
|
||||
"defs": [{
|
||||
"kind": "fn", "name": "f",
|
||||
"type": { "k": "fn", "params": [], "ret": { "k": "con", "name": "Foo" }, "effects": [] },
|
||||
"type": { "k": "fn", "params": [], "param_modes": [], "ret": { "k": "con", "name": "Foo" }, "ret_mode": "own", "effects": [] },
|
||||
"params": [],
|
||||
"body": { "t": "lit", "lit": { "kind": "unit" } }
|
||||
}],
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
//! Throwaway migration-tool test (spec 0062). Asserts the
|
||||
//! parse→Implicit↦Own→print pass materialises bare slots as `(own …)`
|
||||
//! and leaves explicit `(borrow …)` untouched. Deleted in the cutover.
|
||||
use ailang_surface::{parse, print};
|
||||
use ailang_core::ast::ParamMode;
|
||||
|
||||
/// Re-implements the tool's core transform for the unit test so the
|
||||
/// assertion does not depend on the CLI I/O wrapper.
|
||||
fn migrate_text(src: &str) -> String {
|
||||
let mut m = parse(src).expect("parse");
|
||||
ailang_core::ast::for_each_fn_type_mut(&mut m, &mut |params_len, pm, rm| {
|
||||
pm.resize(params_len, ParamMode::Own);
|
||||
for x in pm.iter_mut() {
|
||||
if matches!(x, ParamMode::Implicit) { *x = ParamMode::Own; }
|
||||
}
|
||||
if matches!(rm, ParamMode::Implicit) { *rm = ParamMode::Own; }
|
||||
});
|
||||
print(&m)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_slot_becomes_own_borrow_preserved() {
|
||||
let src = "(module m\n (fn f\n (doc \"d\")\n (type (fn-type (params (con Int) (borrow (con Int))) (ret (con Int))))\n (params x y)\n (body x)))\n";
|
||||
let out = migrate_text(src);
|
||||
assert!(out.contains("(params (own (con Int)) (borrow (con Int)))"), "got: {out}");
|
||||
assert!(out.contains("(ret (own (con Int)))"), "got: {out}");
|
||||
}
|
||||
@@ -25,3 +25,23 @@ fn check_rejects_with(fixture: &str, code: &str) {
|
||||
fn borrow_return_is_rejected() {
|
||||
check_rejects_with("borrow_return_reject.ail", "borrow-return-not-permitted");
|
||||
}
|
||||
|
||||
/// `(borrow value-type)` is rejected with code `borrow-over-value`.
|
||||
#[test]
|
||||
fn borrow_over_value_is_rejected() {
|
||||
check_rejects_with("borrow_value_reject.ail", "borrow-over-value");
|
||||
}
|
||||
|
||||
/// The own-return-provenance / regime-A shapes stay rejected by
|
||||
/// `consume-while-borrowed` after the schema deletion (spec 0062
|
||||
/// already-green pins — these are NOT new checks).
|
||||
#[test]
|
||||
fn own_return_provenance_still_rejected() {
|
||||
for f in [
|
||||
"own_return_provenance_reject.ail",
|
||||
"own_return_provenance_let.ail",
|
||||
"own_return_provenance_ctor.ail",
|
||||
] {
|
||||
check_rejects_with(f, "consume-while-borrowed");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,12 +60,12 @@ fn primitive_eq_ord_mono_symbol_hashes_stay_bit_identical() {
|
||||
// by name; the body is signature-only. The four show__* pins
|
||||
// below do NOT move (Show instance bodies are real, unchanged).
|
||||
let pins: &[(&str, &str)] = &[
|
||||
("eq__Int", "cc7b99b63d1e44ae"),
|
||||
("eq__Bool", "fd0412f127986512"),
|
||||
("eq__Str", "fa269285754a52da"),
|
||||
("compare__Int", "0a02bd9effc9746c"),
|
||||
("compare__Bool", "d0dc108dacf4e543"),
|
||||
("compare__Str", "d1419595dc52a456"),
|
||||
("eq__Int", "85be5c2de568b58d"),
|
||||
("eq__Bool", "851b24fb1b513bf9"),
|
||||
("eq__Str", "ead456ddde7c0cbd"),
|
||||
("compare__Int", "f99b792409ee8417"),
|
||||
("compare__Bool", "bdf90cb462351564"),
|
||||
("compare__Str", "752b08fdd12c6a67"),
|
||||
];
|
||||
|
||||
for (sym, pin) in pins {
|
||||
|
||||
@@ -12,29 +12,14 @@
|
||||
//! `ailang_rc_dec(s)`. The runtime stats line at exit must report
|
||||
//! `live == 0` (equivalently `allocs == frees`).
|
||||
//!
|
||||
//! As of commit 301cbc3 this test fails: stderr reports
|
||||
//! `ailang_rc_stats: allocs=1 frees=0 live=1`. The IR for the post-
|
||||
//! mono `ail_prelude_print__Int` body contains a `call ptr
|
||||
//! @ail_prelude_show__Int(...)` followed by `getelementptr +8` +
|
||||
//! `@fputs` + `ret i8 0` — there is no `ailang_rc_dec` on the
|
||||
//! show-result before return. Root cause sits at codegen's
|
||||
//! `is_rc_heap_allocated` App-arm: it reads the callee's
|
||||
//! `Type::Fn.ret_mode` via `synth_callee_ret_mode` and requires
|
||||
//! `Own`. The mono'ed `show__Int` inherits its `Type::Fn` from the
|
||||
//! `Show` class method declaration in `examples/prelude.ail.json`,
|
||||
//! whose `methods[0].type` omits the `ret_mode` key — `serde` defaults
|
||||
//! the missing field to `ParamMode::Implicit`. So
|
||||
//! `synth_callee_ret_mode(show__Int) == Implicit`, the let-binder is
|
||||
//! not flagged trackable, and `drop_symbol_for_binder` is never
|
||||
//! called for it.
|
||||
//!
|
||||
//! Once the underlying issue is fixed (the canonical move is to
|
||||
//! recognise that any class-method whose declared `ret` is `Str` /
|
||||
//! any pointer-typed user type should round-trip as Own through
|
||||
//! mono, OR to install the Show class declaration with explicit
|
||||
//! `ret_mode: "own"`, OR to widen `is_rc_heap_allocated`'s App-arm
|
||||
//! to also consult the callee's ret type-via-Str-carve-out), this
|
||||
//! test must flip GREEN without weakening the assertion.
|
||||
//! Codegen's `is_rc_heap_allocated` App-arm reads the callee's
|
||||
//! `Type::Fn.ret_mode` via `synth_callee_ret_mode` and tracks the
|
||||
//! let-binder iff it is `Own`. The mono'ed `show__Int` inherits its
|
||||
//! `Type::Fn` from the `Show` class method declaration in
|
||||
//! `examples/prelude.ail.json`, whose `show` carries `ret_mode: own`
|
||||
//! (every fn-type slot is moded — spec 0062). So `show__Int` returns
|
||||
//! `Own`, the let-binder for the show-result is trackable, and
|
||||
//! `drop_symbol_for_binder` emits the scope-close dec — `live == 0`.
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
@@ -107,10 +92,9 @@ fn alloc_rc_print_int_does_not_leak_show_result_str() {
|
||||
live, 0,
|
||||
"`(app print 42)` under --alloc=rc leaks {live} heap-Str cell(s) \
|
||||
(allocs={allocs} frees={frees}); print's let-binder for the \
|
||||
show-result must drop at let-scope-close. Show class method \
|
||||
`show` in prelude.ail.json omits `ret_mode`, so mono-synthesised \
|
||||
`show__Int` inherits ret_mode=Implicit and `is_rc_heap_allocated` \
|
||||
declines to track the let-binder."
|
||||
show-result must drop at let-scope-close. The Show class method \
|
||||
`show` carries `ret_mode: own`, so mono-synthesised `show__Int` \
|
||||
is `Own`-returning and `is_rc_heap_allocated` tracks the binder."
|
||||
);
|
||||
assert_eq!(
|
||||
allocs, frees,
|
||||
|
||||
@@ -36,6 +36,23 @@ 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)
|
||||
@@ -45,7 +62,9 @@ fn list_ail_fixtures() -> Vec<PathBuf> {
|
||||
.filter(|p| {
|
||||
p.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.map(|n| n.ends_with(".ail"))
|
||||
.map(|n| {
|
||||
n.ends_with(".ail") && !NON_PARSEABLE_FIXTURES.contains(&n)
|
||||
})
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -53,6 +53,7 @@ mdefault.2:
|
||||
unreachable
|
||||
mjoin.2:
|
||||
%v9 = phi i64 [ 0, %marm.2.0 ], [ %v8, %marm.2.1 ]
|
||||
call void @partial_drop_list_IntList(ptr %arg_xs, i64 2)
|
||||
ret i64 %v9
|
||||
}
|
||||
|
||||
|
||||
@@ -208,7 +208,7 @@ fn synthesise_mono_fn_uses_instance_body_lam() {
|
||||
ret: Box::new(Type::int()),
|
||||
effects: vec![],
|
||||
param_modes: vec![],
|
||||
ret_mode: ailang_core::ast::ParamMode::Implicit,
|
||||
ret_mode: ailang_core::ast::ParamMode::Own,
|
||||
},
|
||||
default: None,
|
||||
}],
|
||||
@@ -277,7 +277,7 @@ fn synthesise_mono_fn_falls_back_to_class_default() {
|
||||
ret: Box::new(Type::str_()),
|
||||
effects: vec![],
|
||||
param_modes: vec![],
|
||||
ret_mode: ailang_core::ast::ParamMode::Implicit,
|
||||
ret_mode: ailang_core::ast::ParamMode::Own,
|
||||
},
|
||||
default: Some(Term::Lam {
|
||||
params: vec!["_x".into()],
|
||||
|
||||
@@ -54,12 +54,12 @@ const PROG: &str = r#"(module user_adt_new_mono
|
||||
|
||||
(fn new
|
||||
(doc "Build a Counter initialised to the given value.")
|
||||
(type (fn-type (params (con Int)) (ret (con Counter))))
|
||||
(type (fn-type (params (own (con Int))) (ret (own (con Counter)))))
|
||||
(params n)
|
||||
(body (term-ctor Counter MkCounter n)))
|
||||
|
||||
(fn main
|
||||
(type (fn-type (params) (ret (con Unit)) (effects IO)))
|
||||
(type (fn-type (params) (ret (own (con Unit))) (effects IO)))
|
||||
(params)
|
||||
(body
|
||||
(let c (new Counter 42)
|
||||
|
||||
Reference in New Issue
Block a user