iter 23.4: mono-pass unification — class methods + polymorphic free fns in one fixpoint
Restructure ailang-check/src/mono.rs::monomorphise_workspace into a single specialiser over every Type::Forall-quantified Def::Fn, covering both class-method residuals AND polymorphic free-fn call sites in one fixpoint pass. Remove the codegen-time specialiser (lower_polymorphic_call, module_polymorphic_fns, mono_queue, mono_emitted, emit_specialised_fn, plus the now-dead helpers apply_subst_to_term, descriptor_for_subst, type_descriptor) entirely. Codegen sees only monomorphic Def::Fns after this iter — no polymorphic call sites, no codegen-time queue. Architecture changes: - MonoTarget: struct → enum with ClassMethod / FreeFn variants; dedup keys are guaranteed-disjoint via 'class'/'free' first component. - collect_mono_targets: new FreeFnCall channel through synth (cleaner than the plan's separate-walker proposal — one less data flow, substitution tracking comes 'for free' via fresh metavars + post-synth subst.apply). Plan Step 4.4 (polymorphic_free_fns env field) consequently obsolete. - synthesise_mono_fn_for_free_fn: new free-fn entry point; substitutes rigid vars in BOTH the type AND the body (body substitution required because free-fn bodies carry inner Lams whose param_tys reference outer Forall vars — adapted from plan's 'body unchanged' sketch). - mono_symbol_n: N-ary extension of mono_symbol; bit-stable for the single-type-var case (hash-stability pin Task 1 fires zero times through all eight refactor tasks). - rewrite_class_method_calls → rewrite_mono_calls; interleaved-slot collector preserves the positional-cursor invariant across both channels. - workspace_has_typeclasses → workspace_has_specialisable_targets (principled correctness; old predicate happened to already be true for every user workspace because the prelude is auto-injected). Codegen cleanup: - Two call sites of lower_polymorphic_call deleted (codegen/src/lib.rs lines ~1939-1945, ~1965-1973). - lower_polymorphic_call body, module_polymorphic_fns field + population + Emitter wiring, mono_queue / mono_emitted, drain loop, emit_specialised_fn — all removed. - is_static_callee collapsed to module_user_fns-only. - subst.rs apply_subst_to_term + descriptor_for_subst removed; synth.rs type_descriptor removed (all dead post-removal). - ail emit-ir command pipeline gains lift_letrecs + monomorphise_workspace pre-passes (pre-iter-23.4 the codegen-time poly path was masking this dependency — emit-ir is now consistent with build). - Net codegen reduction: -285 lines lib.rs, -93 lines subst.rs. Tests: - mono_hash_stability.rs (new): regression pin for six primitive Eq/Ord mono-symbol body hashes; stayed bit-stable through all eight refactor tasks. - mono_unification.rs (new): six tests covering variant-key disjointness, free-fn target emission, free-fn synthesis with rigid substitution, rewrite walker on free fns, identity for poly-free-fn-only workspaces, end-to-end cmp_max_smoke runtime correctness. - typeclass_22b3.rs: three test sites updated to MonoTarget::ClassMethod enum form. - 73 e2e + 18 typeclass + 81 codegen tests all green workspace-wide. DESIGN.md §'Monomorphisation (post-typecheck, pre-codegen)' amended: two-arm fixpoint described, disjoint-keyed dedup, cursor-aligned walker, removed codegen-time path. Bench check (all exit 0, 112 metrics stable): bench/check.py + compile_check.py + cross_lang.py. Plan parent: docs/plans/2026-05-11-iter-23.4.md (fab1685). Spec parent: docs/specs/2026-05-11-23-eq-ord-prelude.md (841d65d). Per-iter journal documents two adapted deviations from the plan (synth-channel vs separate walker; body substitution; emit-ir fix); no spec defects.
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
//! Regression pin for primitive Eq/Ord mono-symbol body hashes.
|
||||
//!
|
||||
//! Locks the six primitive mono symbols (`eq__Int`, `eq__Bool`, `eq__Str`,
|
||||
//! `compare__Int`, `compare__Bool`, `compare__Str`) to their pre-iter-23.4
|
||||
//! body hashes. The unified mono pass MUST produce bit-identical bodies.
|
||||
|
||||
use ailang_core::ast::Def;
|
||||
use ailang_core::hash::def_hash;
|
||||
use ailang_core::workspace::load_workspace;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn fixture_path() -> PathBuf {
|
||||
let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
d.pop();
|
||||
d.pop();
|
||||
d.join("examples").join("mono_hash_pin_smoke.ail.json")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn primitive_eq_ord_mono_symbol_hashes_stay_bit_identical() {
|
||||
let ws = load_workspace(&fixture_path()).expect("workspace loads");
|
||||
let diags = ailang_check::check_workspace(&ws);
|
||||
assert!(diags.is_empty(), "typecheck diagnostics: {diags:?}");
|
||||
let post_mono = ailang_check::monomorphise_workspace(&ws).expect("mono green");
|
||||
|
||||
// Mono symbols for class methods are appended to the instance's
|
||||
// `defining_module` — i.e. the prelude module, since all six
|
||||
// primitive Eq/Ord instances live there.
|
||||
let prelude_mod = post_mono
|
||||
.modules
|
||||
.get("prelude")
|
||||
.expect("prelude module present");
|
||||
|
||||
let pins: &[(&str, &str)] = &[
|
||||
("eq__Int", "81d59ac38ab3663d"),
|
||||
("eq__Bool", "11da98a358b5979b"),
|
||||
("eq__Str", "277516bb7f195b2a"),
|
||||
("compare__Int", "d5d3f66b86c7e758"),
|
||||
("compare__Bool", "676e3ea0298a8795"),
|
||||
("compare__Str", "a532710899cf14fe"),
|
||||
];
|
||||
|
||||
for (sym, pin) in pins {
|
||||
let def = prelude_mod
|
||||
.defs
|
||||
.iter()
|
||||
.find(|d| matches!(d, Def::Fn(f) if f.name == *sym))
|
||||
.unwrap_or_else(|| panic!("mono symbol {sym} not found in prelude module"));
|
||||
let h = def_hash(def);
|
||||
assert_eq!(&h, pin, "{sym} body hash drifted");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
//! Tests for the unified mono pass over polymorphic free fns (iter 23.4).
|
||||
//!
|
||||
//! These tests assert workspace-level invariants AFTER
|
||||
//! `monomorphise_workspace` has run: synthesised mono `Def::Fn`s for
|
||||
//! both class-method residuals AND polymorphic free-fn calls live in
|
||||
//! the post-mono workspace.
|
||||
|
||||
use ailang_check::mono::{mono_target_key, MonoTarget};
|
||||
use ailang_core::ast::{Def, Type};
|
||||
use ailang_core::workspace::load_workspace;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn fixture(name: &str) -> PathBuf {
|
||||
let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
d.pop();
|
||||
d.pop();
|
||||
d.join("examples").join(name)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmp_max_smoke_produces_both_mono_symbols_in_one_fixpoint() {
|
||||
let ws = load_workspace(&fixture("cmp_max_smoke.ail.json"))
|
||||
.expect("workspace loads");
|
||||
let diags = ailang_check::check_workspace(&ws);
|
||||
assert!(diags.is_empty(), "typecheck diagnostics: {diags:?}");
|
||||
let post_mono = ailang_check::monomorphise_workspace(&ws).expect("mono green");
|
||||
|
||||
// Free-fn mono symbols are appended to their owner module
|
||||
// (where the polymorphic Def::Fn lives) — for cmp_max, that is
|
||||
// `cmp_max_smoke`. Class-method mono symbols (compare__Int) are
|
||||
// appended to the instance's defining module (`prelude`).
|
||||
let main_mod = post_mono
|
||||
.modules
|
||||
.get("cmp_max_smoke")
|
||||
.expect("main module present");
|
||||
let prelude_mod = post_mono
|
||||
.modules
|
||||
.get("prelude")
|
||||
.expect("prelude module present");
|
||||
|
||||
let main_names: Vec<&str> = main_mod
|
||||
.defs
|
||||
.iter()
|
||||
.filter_map(|d| if let Def::Fn(f) = d { Some(f.name.as_str()) } else { None })
|
||||
.collect();
|
||||
let prelude_names: Vec<&str> = prelude_mod
|
||||
.defs
|
||||
.iter()
|
||||
.filter_map(|d| if let Def::Fn(f) = d { Some(f.name.as_str()) } else { None })
|
||||
.collect();
|
||||
|
||||
assert!(
|
||||
main_names.contains(&"cmp_max__Int"),
|
||||
"post-mono workspace must contain free-fn mono symbol cmp_max__Int in module cmp_max_smoke; got {main_names:?}"
|
||||
);
|
||||
assert!(
|
||||
prelude_names.contains(&"compare__Int"),
|
||||
"post-mono workspace must contain class-method mono symbol compare__Int in prelude (closed transitively from cmp_max__Int body); got {prelude_names:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collect_mono_targets_emits_free_fn_target_for_cmp_max_at_int() {
|
||||
use ailang_check::mono::collect_mono_targets;
|
||||
let ws = load_workspace(&fixture("cmp_max_smoke.ail.json")).expect("workspace loads");
|
||||
let diags = ailang_check::check_workspace(&ws);
|
||||
assert!(diags.is_empty(), "typecheck diagnostics: {diags:?}");
|
||||
let env = ailang_check::build_check_env(&ws);
|
||||
|
||||
let main_mod = ws.modules.get("cmp_max_smoke").expect("main module");
|
||||
let main_fn = main_mod.defs.iter().find_map(|d| {
|
||||
if let Def::Fn(f) = d { (f.name == "main").then_some(f) } else { None }
|
||||
}).expect("main fn");
|
||||
|
||||
let targets = collect_mono_targets(main_fn, "cmp_max_smoke", &env)
|
||||
.expect("collector runs");
|
||||
|
||||
let has_free_fn_target = targets.iter().any(|t| matches!(
|
||||
t, MonoTarget::FreeFn { name, type_args, .. }
|
||||
if name == "cmp_max" && type_args.len() == 1
|
||||
&& matches!(&type_args[0], Type::Con { name, args } if name == "Int" && args.is_empty())
|
||||
));
|
||||
assert!(
|
||||
has_free_fn_target,
|
||||
"expected MonoTarget::FreeFn {{ name: \"cmp_max\", type_args: [Int] }}; got {targets:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmp_max_smoke_runs_end_to_end() {
|
||||
// Compile + run the cmp_max_smoke fixture, prove it prints 7
|
||||
// (cmp_max(3, 7) at Int via Ord Int).
|
||||
use std::process::Command;
|
||||
let manifest_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let workspace = manifest_dir.parent().unwrap().parent().unwrap();
|
||||
let src = workspace.join("examples").join("cmp_max_smoke.ail.json");
|
||||
let tmp = std::env::temp_dir().join(format!(
|
||||
"ailang_cmp_max_smoke_{}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::create_dir_all(&tmp).unwrap();
|
||||
let out = tmp.join("bin");
|
||||
let status = Command::new(env!("CARGO_BIN_EXE_ail"))
|
||||
.args(["build", src.to_str().unwrap(), "-o"])
|
||||
.arg(&out)
|
||||
.status()
|
||||
.expect("ail build failed to run");
|
||||
assert!(status.success(), "ail build failed for cmp_max_smoke");
|
||||
let output = Command::new(&out).output().expect("run cmp_max_smoke binary");
|
||||
assert!(output.status.success(), "binary exited non-zero");
|
||||
let stdout = String::from_utf8(output.stdout).expect("stdout utf8");
|
||||
assert_eq!(stdout.trim(), "7", "cmp_max(3, 7) at Int prints 7");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_with_only_poly_free_fn_and_no_classes_still_monomorphises() {
|
||||
// poly_id has a Type::Forall free fn and NO class/instance defs
|
||||
// in the user module. The prelude (auto-injected) has classes,
|
||||
// but for early-out purposes we test the user-module gate.
|
||||
// Today the workspace-has-typeclasses early-out checks the
|
||||
// WHOLE workspace including the prelude, so it actually fires
|
||||
// on every user workspace. The Task-7 generalisation widens
|
||||
// the predicate to also include `Def::Fn` with `Type::Forall`
|
||||
// as a specialisable target — which makes the predicate true
|
||||
// for any workspace with poly free fns (regardless of classes).
|
||||
let ws = load_workspace(&fixture("poly_id.ail.json")).expect("workspace loads");
|
||||
let diags = ailang_check::check_workspace(&ws);
|
||||
assert!(diags.is_empty(), "typecheck diagnostics: {diags:?}");
|
||||
let post_mono = ailang_check::monomorphise_workspace(&ws).expect("mono green");
|
||||
|
||||
// After the unified pass, the workspace contains synthesised
|
||||
// mono fn defs for `id` at Int and at Bool — both invoked from
|
||||
// `main`.
|
||||
let names: Vec<String> = post_mono.modules.values()
|
||||
.flat_map(|m| m.defs.iter().filter_map(|d| {
|
||||
if let Def::Fn(f) = d { Some(f.name.clone()) } else { None }
|
||||
}))
|
||||
.collect();
|
||||
assert!(names.iter().any(|n| n == "id__Int"),
|
||||
"poly_id must produce id__Int via unified mono; got {names:?}");
|
||||
assert!(names.iter().any(|n| n == "id__Bool"),
|
||||
"poly_id must produce id__Bool via unified mono; got {names:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrite_mono_calls_rewrites_bare_poly_free_fn_to_mono_symbol() {
|
||||
let ws = load_workspace(&fixture("cmp_max_smoke.ail.json")).expect("workspace loads");
|
||||
let diags = ailang_check::check_workspace(&ws);
|
||||
assert!(diags.is_empty(), "typecheck diagnostics: {diags:?}");
|
||||
let post_mono = ailang_check::monomorphise_workspace(&ws).expect("mono green");
|
||||
|
||||
let main_mod = post_mono.modules.get("cmp_max_smoke").expect("main module");
|
||||
let main_fn = main_mod.defs.iter().find_map(|d| {
|
||||
if let Def::Fn(f) = d { (f.name == "main").then_some(f) } else { None }
|
||||
}).expect("main fn");
|
||||
|
||||
let body_str = format!("{:?}", main_fn.body);
|
||||
assert!(
|
||||
body_str.contains("cmp_max__Int"),
|
||||
"main body must call cmp_max__Int after rewrite; got: {body_str}"
|
||||
);
|
||||
// The bare-name `cmp_max` (as a Term::Var.name) must NOT appear
|
||||
// anywhere in main's body post-rewrite.
|
||||
assert!(
|
||||
!body_str.contains("Var { name: \"cmp_max\""),
|
||||
"main body must NOT still call bare cmp_max after rewrite; got: {body_str}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synthesise_mono_fn_free_fn_arm_substitutes_rigid_vars() {
|
||||
use ailang_check::mono::synthesise_mono_fn_for_free_fn;
|
||||
let ws = load_workspace(&fixture("cmp_max_smoke.ail.json")).expect("workspace loads");
|
||||
let diags = ailang_check::check_workspace(&ws);
|
||||
assert!(diags.is_empty(), "typecheck diagnostics: {diags:?}");
|
||||
|
||||
let int_ty = Type::Con { name: "Int".into(), args: vec![] };
|
||||
let target = MonoTarget::FreeFn {
|
||||
name: "cmp_max".into(),
|
||||
type_args: vec![int_ty.clone()],
|
||||
defining_module: "cmp_max_smoke".into(),
|
||||
};
|
||||
let synth = synthesise_mono_fn_for_free_fn(&target, &ws)
|
||||
.expect("synthesis succeeds");
|
||||
|
||||
assert_eq!(synth.name, "cmp_max__Int");
|
||||
// Body must still reference `compare` (pre-rewrite); Task 6
|
||||
// rewrites it to `compare__Int` during the walker pass.
|
||||
let body_str = format!("{:?}", synth.body);
|
||||
assert!(body_str.contains("compare"), "body still references compare bare-name pre-rewrite: {body_str}");
|
||||
// Param types must be Int after rigid substitution.
|
||||
assert!(matches!(
|
||||
&synth.ty,
|
||||
Type::Fn { params, ret, .. }
|
||||
if params.len() == 2
|
||||
&& matches!(¶ms[0], Type::Con { name, args } if name == "Int" && args.is_empty())
|
||||
&& matches!(¶ms[1], Type::Con { name, args } if name == "Int" && args.is_empty())
|
||||
&& matches!(ret.as_ref(), Type::Con { name, args } if name == "Int" && args.is_empty())
|
||||
), "synth.ty = {:?}", synth.ty);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mono_target_free_fn_variant_keys_distinctly_from_class_method() {
|
||||
let int_ty = Type::Con { name: "Int".into(), args: vec![] };
|
||||
let class_tgt = MonoTarget::ClassMethod {
|
||||
class: "Eq".into(),
|
||||
method: "eq".into(),
|
||||
type_: int_ty.clone(),
|
||||
defining_module: "prelude".into(),
|
||||
};
|
||||
let free_tgt = MonoTarget::FreeFn {
|
||||
name: "cmp_max".into(),
|
||||
type_args: vec![int_ty.clone()],
|
||||
defining_module: "prelude".into(),
|
||||
};
|
||||
assert_ne!(
|
||||
mono_target_key(&class_tgt),
|
||||
mono_target_key(&free_tgt),
|
||||
"class-method and free-fn targets must have distinct dedup keys"
|
||||
);
|
||||
}
|
||||
@@ -146,14 +146,19 @@ fn collect_mono_targets_single_concrete_call_site() {
|
||||
|
||||
assert_eq!(targets.len(), 1, "one target expected: {:?}", targets);
|
||||
let t = &targets[0];
|
||||
assert_eq!(t.class, "Show");
|
||||
assert_eq!(t.method, "show");
|
||||
assert!(
|
||||
matches!(&t.type_, ailang_core::ast::Type::Con { name, args } if name == "Int" && args.is_empty()),
|
||||
"type must be Int, got {:?}",
|
||||
t.type_
|
||||
);
|
||||
assert_eq!(t.defining_module, "test_22b2_instance_present");
|
||||
match t {
|
||||
ailang_check::mono::MonoTarget::ClassMethod { class, method, type_, defining_module } => {
|
||||
assert_eq!(class, "Show");
|
||||
assert_eq!(method, "show");
|
||||
assert!(
|
||||
matches!(type_, ailang_core::ast::Type::Con { name, args } if name == "Int" && args.is_empty()),
|
||||
"type must be Int, got {:?}",
|
||||
type_
|
||||
);
|
||||
assert_eq!(defining_module, "test_22b2_instance_present");
|
||||
}
|
||||
other => panic!("expected ClassMethod target, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -223,7 +228,7 @@ fn synthesise_mono_fn_uses_instance_body_lam() {
|
||||
}],
|
||||
doc: None,
|
||||
};
|
||||
let target = MonoTarget {
|
||||
let target = MonoTarget::ClassMethod {
|
||||
class: "Foo".into(),
|
||||
method: "bar".into(),
|
||||
type_: Type::int(),
|
||||
@@ -292,7 +297,7 @@ fn synthesise_mono_fn_falls_back_to_class_default() {
|
||||
methods: vec![],
|
||||
doc: None,
|
||||
};
|
||||
let target = MonoTarget {
|
||||
let target = MonoTarget::ClassMethod {
|
||||
class: "Greet".into(),
|
||||
method: "hello".into(),
|
||||
type_: Type::int(),
|
||||
@@ -344,7 +349,7 @@ fn synthesise_mono_fn_zero_arg_method_uses_body_verbatim() {
|
||||
}],
|
||||
doc: None,
|
||||
};
|
||||
let target = MonoTarget {
|
||||
let target = MonoTarget::ClassMethod {
|
||||
class: "Foo".into(),
|
||||
method: "bar".into(),
|
||||
type_: Type::int(),
|
||||
|
||||
Reference in New Issue
Block a user