From 9ccc23063191cac3a252b704346b464868b5ce85 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:22:32 +0000 Subject: [PATCH 1/5] Checker rewrite R5a-2a: the variable tables of an item TypeVars::reset forgets the declared, used and universal variables of an item head by head (no table is filled whole) and sets the global level one above the given level (reset_type_variables, typetexp.ml:213-216; reset_global_level, ctype.ml:157). Annot::univar, Annot::declared and Annot::add_declared look up and enter rows by Name through dense head tables; univar answers at once when no binder is open. No test is un-ignored: they are reached through later commits. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-e9265965-2056-785e-9365-c3bd2347e914 Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- changes/checker-rewrite-r5a-2a.internal.md | 1 + compiler-rust/src/tc/walk/typetexp.rs | 48 ++++++++++++++++++++-- 2 files changed, 45 insertions(+), 4 deletions(-) create mode 100644 changes/checker-rewrite-r5a-2a.internal.md diff --git a/changes/checker-rewrite-r5a-2a.internal.md b/changes/checker-rewrite-r5a-2a.internal.md new file mode 100644 index 0000000000..dfc46d76f2 --- /dev/null +++ b/changes/checker-rewrite-r5a-2a.internal.md @@ -0,0 +1 @@ +- Checker rewrite R5a-2a: the new checker translates aliases, universal variables, the parameters of a type without plain parameters and the variables of an item (`globalize_used_variables`, `transl_simple_type`, `transl_type_scheme`). diff --git a/compiler-rust/src/tc/walk/typetexp.rs b/compiler-rust/src/tc/walk/typetexp.rs index 5dde1aed37..1f454aac10 100644 --- a/compiler-rust/src/tc/walk/typetexp.rs +++ b/compiler-rust/src/tc/walk/typetexp.rs @@ -147,7 +147,29 @@ impl TypeVars { /// the graph's current level. O(variables of the item). No /// allocation. (R5a-2) pub fn reset(&mut self, level: u32) { - todo!("R5a-2") + for declared in &self.declared { + #[cfg(test)] + super::super::steps::tick(); + self.declared_heads[declared.name.0 as usize] = NONE; + } + self.declared.clear(); + self.forget_used(); + self.drop_univars(); + self.global_level = level + 1; + } + + /// `univars () := []` (compiler/ml/typetexp.ml:737, 745): forget the + /// universal variables of every open binder. O(rows of `univars`), 1 + /// step each: the head of each row's name taken back, then `univars` + /// cleared. Every head is [`NONE`] afterwards: a head that is not + /// names a row. No allocation. + fn drop_univars(&mut self) { + for univar in &self.univars { + #[cfg(test)] + super::super::steps::tick(); + self.univar_heads[univar.name.0 as usize] = NONE; + } + self.univars.clear(); } } @@ -439,7 +461,14 @@ impl Annot<'_> { /// two loads. (R5a-2) #[inline] pub fn univar(&self, name: Name) -> Ty { - todo!("R5a-2") + let vars = &self.st.vars; + if vars.univars.is_empty() { + return Ty(NONE); + } + match vars.univar_heads.get(name.0 as usize) { + Some(&row) if row != NONE => vars.univars[row as usize].ty, + _ => Ty(NONE), + } } /// `Tbl.find name !(type_variables ())` (compiler/ml/typetexp.ml: @@ -449,7 +478,11 @@ impl Annot<'_> { /// (R5a-2) #[inline] pub fn declared(&self, name: Name) -> Ty { - todo!("R5a-2") + let vars = &self.st.vars; + match vars.declared_heads.get(name.0 as usize) { + Some(&row) if row != NONE => vars.declared[row as usize].ty, + _ => Ty(NONE), + } } /// `type_variables () := Tbl.add name v` (compiler/ml/typetexp.ml: @@ -459,7 +492,14 @@ impl Annot<'_> { /// `Already_bound` first, 250-251; R5a-3 tests it with /// [`Annot::declared`]). (R5a-2) pub fn add_declared(&mut self, name: Name, ty: Ty, loc: u32) { - todo!("R5a-2") + let vars = &mut self.st.vars; + let at = name.0 as usize; + if at >= vars.declared_heads.len() { + vars.declared_heads.resize(at + 1, NONE); + } + debug_assert_eq!(vars.declared_heads[at], NONE, "a declared variable is added once"); + vars.declared_heads[at] = vars.declared.len() as u32; + vars.declared.push(UsedVar { name, ty, loc }); } } From 2fea0bb759041a2fc4a4a41de790afc13288ced8 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:24:05 +0000 Subject: [PATCH 2/5] Checker rewrite R5a-2a: the alias arm Annot::transl_type translates `t as 'a` (typetexp.ml:394-428) as one frame. When the alias node is entered its variable is found (a universal variable as it is, a used variable through its instance) or made and entered in the used variables at the alias node's location, BEFORE the aliased type, so `array<'b> as 'b` is refused by the kernel's unify_var as OCaml refuses it. The variable, and for a new alias its Name (one NameTable::intern), wait on the value stack below the aliased type's result; when the frame is left the variable is unified with the aliased type (Alias_type_mismatch is Stop::Error) and a new alias names its proxy without validate_name. The variable arm looks up the universal variables before the used ones; the copy of a generic node is one helper for both arms. The row ("int as 'a", AliasType) of r5a_tests::DECLINED goes; the eight alias tests of r5a2_tests are no longer ignored. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-e9265965-2056-785e-9365-c3bd2347e914 Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/tc/r5a2_tests.rs | 8 --- compiler-rust/src/tc/r5a_tests.rs | 3 +- compiler-rust/src/tc/walk/typetexp.rs | 98 ++++++++++++++++++++++++--- 3 files changed, 88 insertions(+), 21 deletions(-) diff --git a/compiler-rust/src/tc/r5a2_tests.rs b/compiler-rust/src/tc/r5a2_tests.rs index 4ab529db64..5b201959c5 100644 --- a/compiler-rust/src/tc/r5a2_tests.rs +++ b/compiler-rust/src/tc/r5a2_tests.rs @@ -561,7 +561,6 @@ fn value_line(w: &mut World, root: Ty) -> String { /// new (second branch), the proxy named or not, an alias inside an /// alias, an alias used again as an argument. #[test] -#[ignore = "R5a-2 build"] fn aliases_agree_with_todays_checker() { for (annotation, line) in ALIASES { let mut w = world(); @@ -580,7 +579,6 @@ fn aliases_agree_with_todays_checker() { /// and leaves the two stacks empty. A body that does not unify the /// alias's variable with the aliased type accepts both. #[test] -#[ignore = "R5a-2 build"] fn an_alias_bound_to_two_types_is_an_error() { for annotation in ALIAS_CLASHES { let mut w = world(); @@ -605,7 +603,6 @@ fn an_alias_bound_to_two_types_is_an_error() { /// deep_occur t1 t2 -> unify`, ctype.ml:2753, and `unify` expands): /// `id<'b> as 'b` is a variable named `b` (OCaml prints `'a => int`). #[test] -#[ignore = "R5a-2 build"] fn a_self_alias_is_refused_as_in_ocaml() { for annotation in SELF_ALIASES_OCAML_REFUSES { let mut w = world(); @@ -631,7 +628,6 @@ fn a_self_alias_is_refused_as_in_ocaml() { /// ends on it (`@1`), `Checker::generalize` and `Checker::copy` end on /// it, and the copy is again one node that names itself. #[test] -#[ignore = "R5a-2 build"] fn a_phantom_self_alias_is_a_type_that_names_itself() { let mut w = world(); w.c.g.begin_def(); @@ -654,7 +650,6 @@ fn a_phantom_self_alias_is_a_type_that_names_itself() { /// of the alias node holds the aliased type's node; every node is at /// the current level; and no node is made for the second use of `'b`. #[test] -#[ignore = "R5a-2 build"] fn an_alias_enters_its_variable_first_at_the_alias_location() { let mut w = world(); w.c.g.begin_def(); @@ -1141,7 +1136,6 @@ fn extensible(w: &mut World, arena: &ParseArena, root: CoreTypeIdx) { /// reading the variable back follows its link (measured on the /// prototype: 70,001 at 10,000). #[test] -#[ignore = "R5a-2 build"] fn ten_thousand_aliases() { let make = |n: usize| format!("({})", (0..n).map(|i| format!("int as 'v{i}")).collect::>().join(", ")); linear("aliases", make, extensible, 7); @@ -1155,7 +1149,6 @@ fn ten_thousand_aliases() { /// no node, where a body that takes an instance or unifies at every /// use pays the aliased type each time. #[test] -#[ignore = "R5a-2 build"] fn ten_thousand_uses_of_one_alias() { let make = |n: usize| format!("(k as 'a, {})", vec!["'a"; n].join(", ")); linear("uses of an alias", make, extensible, 2); @@ -1184,7 +1177,6 @@ fn ten_thousand_uses_of_one_alias() { /// followed to the node inside). The parse runs on a thread with a large stack (the /// parser recurses; the translation does not). #[test] -#[ignore = "R5a-2 build"] fn aliases_nested_ten_thousand_deep() { let steps_at = |n: usize| { let mut annotation = String::from("int"); diff --git a/compiler-rust/src/tc/r5a_tests.rs b/compiler-rust/src/tc/r5a_tests.rs index d8b335c99a..4c85e2169f 100644 --- a/compiler-rust/src/tc/r5a_tests.rs +++ b/compiler-rust/src/tc/r5a_tests.rs @@ -91,10 +91,9 @@ const REJECTED: [&str; 5] = [ ]; /// Annotations R5a-1 declines, with the variant (CHECKER_REWRITE 10.5). -const DECLINED: [(&str, Declined); 6] = [ +const DECLINED: [(&str, Declined); 5] = [ ("{\"x\": int}", Declined::ObjectType), ("[#a | #b]", Declined::PolyVariantType), - ("int as 'a", Declined::AliasType), ("M.t", Declined::TypePath), ("module(S)", Declined::PackageType), ("(@as(\"x\") int) => int", Declined::TypeAttribute), diff --git a/compiler-rust/src/tc/walk/typetexp.rs b/compiler-rust/src/tc/walk/typetexp.rs index 1f454aac10..a6b5bb3b81 100644 --- a/compiler-rust/src/tc/walk/typetexp.rs +++ b/compiler-rust/src/tc/walk/typetexp.rs @@ -620,16 +620,15 @@ impl Annot<'_> { return Err(Stop::Error); } let name = self.st.strs.name(arena, &mut self.scopes.names, *text); - let used = self.st.vars.used(name); - if used.0 != NONE { - // `instance env`: a node that is not generic is - // itself (`copy`, compiler/ml/ctype.ml:744-797). - let repr = self.c.g.repr(used); - if self.c.g.nodes[repr.0 as usize].level == GENERIC { - self.c.copy(used) - } else { - used - } + // A universal variable first, then a used one (308-310). + let universal = self.univar(name); + let found = if universal.0 != NONE { + universal + } else { + self.st.vars.used(name) + }; + if found.0 != NONE { + self.instance(found) } else { // `newvar ~name` drops a name that `validate_name` // refuses (typetexp.ml:224-231, 231): its first @@ -672,7 +671,39 @@ impl Annot<'_> { return Ok(()); } CoreTypeDesc::Ptyp_object(_) => return Err(Stop::Declined(Declined::ObjectType)), - CoreTypeDesc::Ptyp_alias(_) => return Err(Stop::Declined(Declined::AliasType)), + // typetexp.ml:394-428 up to the aliased type: the alias's + // variable is found or made BEFORE the aliased type is + // translated (409-411), so the aliased type's uses of the name + // are that variable. It goes on the value stack above `base`, + // and for a new alias its `Name` above it: the frame's leave + // tells the two branches apart by its count of slots. + CoreTypeDesc::Ptyp_alias(alias) => { + let name = self.scopes.names.intern(&alias.1); + // 398: a universal variable is taken as it is, no instance. + let universal = self.univar(name); + let (var, new) = if universal.0 != NONE { + (universal, false) + } else { + let used = self.st.vars.used(name); + if used.0 != NONE { + // 400: `instance env` of the used variable's node. + (self.instance(used), false) + } else { + // 409-411: a variable without a name, entered at the + // alias node's location. + let var = self.new_var(NONE); + self.st.vars.add_used(name, var, core.ptyp_loc.0); + (var, true) + } + }; + self.set_row(node, NO_ROW); + self.push_frame(node); + self.st.values.push(var); + if new { + self.st.values.push(Ty(name.0)); + } + return Ok(()); + } CoreTypeDesc::Ptyp_variant(_) => return Err(Stop::Declined(Declined::PolyVariantType)), CoreTypeDesc::Ptyp_poly(_) => return Err(Stop::Declined(Declined::PolyType)), CoreTypeDesc::Ptyp_package(_) => return Err(Stop::Declined(Declined::PackageType)), @@ -705,6 +736,7 @@ impl Annot<'_> { let arena = self.arena; let next = frame.next as usize; Ok(match &arena.get_core_type(CoreTypeIdx(frame.node)).ptyp_desc { + CoreTypeDesc::Ptyp_alias(alias) => (next == 0).then_some(alias.0), CoreTypeDesc::Ptyp_tuple(list) => arena.type_list(*list).get(next).copied(), CoreTypeDesc::Ptyp_constr((_, list)) => match arena.type_list(*list) { // One `_`: as many times as the type has parameters (the @@ -826,9 +858,53 @@ impl Annot<'_> { b, }) } + // typetexp.ml:402-427 after the aliased type: the slots are + // the variable, for a new alias its `Name`, then the aliased + // type's node. + CoreTypeDesc::Ptyp_alias(_) => { + let var = self.st.values[base]; + let ty = self.st.values[self.st.values.len() - 1]; + // 403, 413: a clash is `Alias_type_mismatch`. + self.c.unify_var(var, ty).map_err(|_clash| Stop::Error)?; + if count == 2 { + // 407: the used name's branch answers the aliased type. + ty + } else { + // 417-426: `instance env t`, and its proxy, when it is + // a variable without a name, takes the alias's name as + // written (no `validate_name`). `Btype.proxy` is the + // node itself but for an object or a variant, which + // decline. A `Tunivar None` proxy (424) needs a + // universal variable of a closed binder reached by a + // later part of the same annotation, which only an + // object can hold: it declines in R5a. + let name = self.st.values[base + 1].0; + let var = self.instance(var); + let proxy = self.c.g.repr(var); + let found = self.c.g.nodes[proxy.0 as usize]; + if found.tag() == VAR && found.a == NONE { + self.c.g.write(proxy, Node { a: name, ..found }); + } + var + } + } _ => return Err(NOT_A_FRAME), }) } + + /// `instance env ty` of a variable's node (compiler/ml/ctype.ml: + /// 879-887): a generic node is copied with `Checker::copy`, any + /// other is itself (`copy`, 744-797). The variable arm and the alias + /// arm share it. O(1) plus the representative's links, and the copy + /// of a generic node. + fn instance(&mut self, ty: Ty) -> Ty { + let repr = self.c.g.repr(ty); + if self.c.g.nodes[repr.0 as usize].level == GENERIC { + self.c.copy(ty) + } else { + ty + } + } } #[cfg(test)] From 93b52a6e142496fc0e79bc5ae2aa48d1ea032a99 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:25:10 +0000 Subject: [PATCH 3/5] Checker rewrite R5a-2a: the polymorphic arm and the way out on Err Annot::transl_type translates `'a 'b. t` (typetexp.ml:545-571): when the node is entered, begin_def and one variable a name (validate_name with a leading underscore allowed, 548), each a row of TypeVars::univars, the heads written from the last variable to the first so that the first of two of one name is found. When the frame is left the heads are put back from the first to the last, end_def and generalize of the body; ONE marking walk of the body (fresh_marks, work, children) answers deep_occur for every variable of the binder; a marked generic variable becomes a universal variable in place, any other marked one is Cannot_quantify; the Poly node (body, then the bound variables in the binder's order) is generic and lowered to the current level with Checker::lower. validate_name is one helper for the variable arm and the binder. On Err, transl_type now also puts the graph's level back and drops the open binders' universal variables (10.12, decision 21). A new test counts the steps of that drop at 1,000 and 10,000 variables. Four tests of r5a2_tests are no longer ignored. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-e9265965-2056-785e-9365-c3bd2347e914 Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/tc/r5a2_tests.rs | 4 - compiler-rust/src/tc/walk/typetexp.rs | 167 +++++++++++++++++++++++++- 2 files changed, 161 insertions(+), 10 deletions(-) diff --git a/compiler-rust/src/tc/r5a2_tests.rs b/compiler-rust/src/tc/r5a2_tests.rs index 5b201959c5..979ae8527b 100644 --- a/compiler-rust/src/tc/r5a2_tests.rs +++ b/compiler-rust/src/tc/r5a2_tests.rs @@ -742,7 +742,6 @@ fn polymorphic_fields_agree_with_todays_checker() { /// variable was made (`Extras::univars`), named `a`, in slot 1 of the /// node; `'b`, which does not occur, is still a variable. #[test] -#[ignore = "R5a-2 build"] fn a_polymorphic_type_binds_the_variables_that_occur() { let mut w = world(); let (arena, root) = parse_field("'a 'b. 'a => int"); @@ -780,7 +779,6 @@ fn a_polymorphic_type_binds_the_variables_that_occur() { /// `'a` again: the first and the third are one variable node, and the /// field's bound variable is another node. #[test] -#[ignore = "R5a-2 build"] fn a_universal_variable_hides_a_used_variable_inside_its_binder() { let mut w = world(); let (arena, root) = parse("'a"); @@ -808,7 +806,6 @@ fn a_universal_variable_hides_a_used_variable_inside_its_binder() { /// empty, and the next annotation of the worker translates: `'a` after /// it is a used variable, not the dead binder's. #[test] -#[ignore = "R5a-2 build"] fn an_error_inside_a_binder_leaves_no_binder() { let mut w = world(); w.c.g.begin_def(); @@ -1249,7 +1246,6 @@ fn ten_thousand_variables_globalized() { /// ty` as written, typetexp.ml:560) is quadratic and fails here. /// Measured on the prototype: 70,006 at 10,000. #[test] -#[ignore = "R5a-2 build"] fn ten_thousand_universal_variables() { let make = |n: usize| { let names: Vec = (0..n).map(|i| format!("'v{i}")).collect(); diff --git a/compiler-rust/src/tc/walk/typetexp.rs b/compiler-rust/src/tc/walk/typetexp.rs index a6b5bb3b81..54e780314b 100644 --- a/compiler-rust/src/tc/walk/typetexp.rs +++ b/compiler-rust/src/tc/walk/typetexp.rs @@ -13,6 +13,7 @@ use super::super::expand::PLAIN_PARAMS; use super::super::graph::{ARROW, CONSTR, GENERIC, NONE, Node, Param, TUPLE, Ty, VAR}; use super::super::name_table::{Name, NameTable}; use super::super::scope::{BinderKind, Key, Namespace, Resolved, ResolvedKind, Scopes, USED}; +use super::super::segment::{EXTENDED, ExtraDescriptor}; use super::super::unify::Checker; use super::super::{Declined, Stop}; use crate::intern::StrIdx; @@ -324,10 +325,15 @@ impl Annot<'_> { /// nested in another. No recursion: an annotation 10,000 deep uses the two /// stacks. No allocation beyond the growth of the pools. (R5a-1) pub fn transl_type(&mut self, root: CoreTypeIdx, policy: Policy) -> Result { + let level = self.c.g.level; let result = self.walk(root, policy); if result.is_err() { self.st.frames.clear(); self.st.values.clear(); + // CHECKER_REWRITE 10.12, decision 21: the level a binder + // raised, and the binders still open. + self.c.g.level = level; + self.st.vars.drop_univars(); } result } @@ -510,6 +516,16 @@ impl Annot<'_> { /// it; the helpers stay total without a panic. const NOT_A_FRAME: Stop = Stop::Declined(Declined::NotBuilt); +/// `validate_name` (compiler/ml/typetexp.ml:224-231): whether a variable +/// written `text` keeps its name: its first byte is `_` or an ASCII +/// letter (`strict_ident`). The variable arm refuses a leading `_` before +/// it asks (308-309); a binder's variable does not (548). O(1). +fn valid_name(text: &str) -> bool { + text.as_bytes() + .first() + .is_some_and(|&first| first == b'_' || first.is_ascii_alphabetic()) +} + /// The parameters of an arrow node's description: the list the parser /// grouped (one read of the arena's table of grouped arrows, /// `ParseArena::nary_arrow_args_slice`), or the one parameter. O(1) @@ -631,11 +647,9 @@ impl Annot<'_> { self.instance(found) } else { // `newvar ~name` drops a name that `validate_name` - // refuses (typetexp.ml:224-231, 231): its first - // character is `_` (refused above) or an ASCII letter. - // The used variable has the name as written (316-317). - let named = spelled.as_bytes().first().is_some_and(u8::is_ascii_alphabetic); - let ty = self.new_var(if named { name.0 } else { NONE }); + // refuses (typetexp.ml:224-231, 231). The used variable + // has the name as written (316-317). + let ty = self.new_var(if valid_name(spelled) { name.0 } else { NONE }); self.st.vars.add_used(name, ty, core.ptyp_loc.0); ty } @@ -705,7 +719,36 @@ impl Annot<'_> { return Ok(()); } CoreTypeDesc::Ptyp_variant(_) => return Err(Stop::Declined(Declined::PolyVariantType)), - CoreTypeDesc::Ptyp_poly(_) => return Err(Stop::Declined(Declined::PolyType)), + // typetexp.ml:545-550 up to the body: `begin_def`, then a + // variable a name (through `validate_name`, 548), each a row of + // `univars`; then the heads, from the last variable to the + // first, so that the first of two variables of one name is the + // one found (`List.assoc`, 308). + CoreTypeDesc::Ptyp_poly(poly) => { + self.c.g.begin_def(); + let first = self.st.vars.univars.len(); + for var in &poly.0 { + #[cfg(test)] + super::super::steps::tick(); + let name = self.st.strs.name(arena, &mut self.scopes.names, var.txt); + let named = valid_name(arena.get_string(var.txt)); + let ty = self.new_var(if named { name.0 } else { NONE }); + // `loc` is written with the head the row replaces below. + self.st.vars.univars.push(UsedVar { name, ty, loc: NONE }); + } + let vars = &mut self.st.vars; + for row in (first..vars.univars.len()).rev() { + let at = vars.univars[row].name.0 as usize; + if at >= vars.univar_heads.len() { + vars.univar_heads.resize(at + 1, NONE); + } + vars.univars[row].loc = vars.univar_heads[at]; + vars.univar_heads[at] = row as u32; + } + self.set_row(node, NO_ROW); + self.push_frame(node); + return Ok(()); + } CoreTypeDesc::Ptyp_package(_) => return Err(Stop::Declined(Declined::PackageType)), CoreTypeDesc::Ptyp_extension(_) => return Err(Stop::Declined(Declined::ExtensionType)), }; @@ -737,6 +780,7 @@ impl Annot<'_> { let next = frame.next as usize; Ok(match &arena.get_core_type(CoreTypeIdx(frame.node)).ptyp_desc { CoreTypeDesc::Ptyp_alias(alias) => (next == 0).then_some(alias.0), + CoreTypeDesc::Ptyp_poly(poly) => (next == 0).then_some(poly.1), CoreTypeDesc::Ptyp_tuple(list) => arena.type_list(*list).get(next).copied(), CoreTypeDesc::Ptyp_constr((_, list)) => match arena.type_list(*list) { // One `_`: as many times as the type has parameters (the @@ -888,10 +932,93 @@ impl Annot<'_> { var } } + CoreTypeDesc::Ptyp_poly(poly) => self.leave_poly(base, poly.0.len())?, _ => return Err(NOT_A_FRAME), }) } + /// typetexp.ml:550-571, the polymorphic arm after its body, whose + /// node is `values[base]`; the binder's `count` variables are the last + /// rows of `TypeVars::univars`. The heads are put back from the first + /// variable to the last (553), `end_def` and `Checker::generalize` of + /// the body (554-555); then `deep_occur v ty` for every variable of + /// the binder (560) is ONE walk of the body that marks every node it + /// reaches (`Checker::fresh_marks`, `Graph::work` as the stack), and + /// per variable one load of its representative's mark: a marked + /// generic variable becomes a universal variable in place (561-563), + /// marked and anything else is `Cannot_quantify` (`Stop::Error`, + /// 565), unmarked is dropped. One `Poly` node, generic, slot 0 the + /// body and then the bound variables in the binder's order (569), + /// lowered to the current level with `Checker::lower`: what + /// `unify_var env (newvar ()) ty'` (570) does, without the variable + /// nothing holds. Cost: 1 step a node of the body in the marking + /// walk, 1 step a variable of the binder, plus `generalize` and the + /// lowering (1 step a node each) and one `Extras::univar` a bound + /// variable; no allocation beyond the growth of the pools. + fn leave_poly(&mut self, base: usize, count: usize) -> Result { + let body = self.st.values[base]; + let vars = &mut self.st.vars; + let first = vars.univars.len() - count; + for univar in &vars.univars[first..] { + vars.univar_heads[univar.name.0 as usize] = univar.loc; + } + self.c.g.end_def(); + self.c.generalize(body); + let generation = self.c.fresh_marks(); + self.c.g.work.clear(); + self.c.g.work.push(body); + while let Some(ty) = self.c.g.work.pop() { + let ty = self.c.g.repr(ty); + if self.c.marks[ty.0 as usize] == generation { + continue; + } + #[cfg(test)] + super::super::steps::tick(); + self.c.marks[ty.0 as usize] = generation; + let reached = self.c.g.nodes[ty.0 as usize]; + self.c.g.children(reached, false); + } + let b = self.c.g.lists.len() as u32; + self.c.g.lists.push(body); + let mut bound = 0; + for row in first..self.st.vars.univars.len() { + #[cfg(test)] + super::super::steps::tick(); + let var = self.c.g.repr(self.st.vars.univars[row].ty); + if self.c.marks[var.0 as usize] != generation { + continue; + } + let found = self.c.g.nodes[var.0 as usize]; + if found.tag() != VAR || found.level != GENERIC { + return Err(Stop::Error); + } + let a = self.c.extras.univar(found.a); + self.c.g.write( + var, + Node { + head: TUPLE | EXTENDED, + level: GENERIC, + a, + b: 0, + }, + ); + self.c.g.lists.push(var); + bound += 1; + } + self.st.vars.univars.truncate(first); + let a = self.c.extras.descriptors.len() as u32; + self.c.extras.descriptors.push(ExtraDescriptor::Poly); + let poly = self.c.g.push(Node { + head: TUPLE | EXTENDED | (bound + 1) << 8, + level: GENERIC, + a, + b, + }); + let level = self.c.g.level; + self.c.lower(poly, level).map_err(|_clash| Stop::Error)?; + Ok(poly) + } + /// `instance env ty` of a variable's node (compiler/ml/ctype.ml: /// 879-887): a generic node is copied with `Checker::copy`, any /// other is itself (`copy`, 744-797). The variable arm and the alias @@ -921,4 +1048,32 @@ mod tests { // and the policy, 5 bytes. assert!(std::mem::size_of::<(CoreTypeIdx, Policy)>() <= 16); } + + /// The loop of `TypeVars::drop_univars`, which `TypeVars::reset` and + /// the way out of `Annot::transl_type` on `Err` run: 1 step a + /// universal variable of the open binders, n of them at 1,000 and at + /// 10,000. + #[test] + fn ten_thousand_universal_variables_dropped() { + let steps_at = |n: u32| { + let mut vars = TypeVars::default(); + vars.univar_heads.resize(n as usize, NONE); + for at in 0..n { + vars.univar_heads[at as usize] = at; + vars.univars.push(UsedVar { + name: Name(at), + ty: Ty(at), + loc: NONE, + }); + } + let steps = crate::tc::steps::scope(|| vars.reset(1)); + assert!(vars.univars.is_empty()); + assert!(vars.univar_heads.iter().all(|&head| head == NONE)); + steps + }; + let (small, large) = (steps_at(1_000), steps_at(10_000)); + assert!(small >= 1_000, "{small} steps at 1,000"); + assert!(large <= 11 * small, "{small} at 1,000, {large} at 10,000"); + assert!(large <= 10_000 + 100, "{large} steps at 10,000"); + } } From 29b1fc16aafcbb5c4680522eca62ac0e69c0f69a Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:26:33 +0000 Subject: [PATCH 4/5] Checker rewrite R5a-2a: globalize, transl_simple_type, transl_type_scheme Annot::globalize is globalize_used_variables (typetexp.ml:705-734) as two loops over TypeVars::used, sorted in place by the bytes of the names when it has two rows or more (decision 8). The first loop, in that order, unifies a new variable at the global level with each used variable inside one speculation, kept on success; on failure it is restored and the unit declines with Declined::PolyType where OCaml skips silently (10.12, decision 16). Then the declared variable of the name, or under the fixed policy Unbound_type_variable, or a second global variable entered as declared. The second loop, from the last row to the first, unifies each used node with its declared variable. The used variables are forgotten on every way out. transl_simple_type empties the universal and used variables, translates and globalizes; transl_type_scheme resets the item's variables, translates one level up, gives the level back on Err too and generalizes. Eight tests of r5a2_tests are no longer ignored. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-e9265965-2056-785e-9365-c3bd2347e914 Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/tc/r5a2_tests.rs | 8 --- compiler-rust/src/tc/walk/typetexp.rs | 88 +++++++++++++++++++++++++-- 2 files changed, 84 insertions(+), 12 deletions(-) diff --git a/compiler-rust/src/tc/r5a2_tests.rs b/compiler-rust/src/tc/r5a2_tests.rs index 979ae8527b..8a07b0a1bd 100644 --- a/compiler-rust/src/tc/r5a2_tests.rs +++ b/compiler-rust/src/tc/r5a2_tests.rs @@ -711,7 +711,6 @@ fn field_type(w: &mut World, annotation: &str, declared: &[&str]) -> Result Vec<&str> { /// afterwards; a second annotation of the item finds `'b` and is one /// node with the first's. #[test] -#[ignore = "R5a-2 build"] fn used_variables_are_globalized_in_the_order_of_their_names() { let mut w = world(); let level = w.c.g.level; @@ -885,7 +883,6 @@ fn used_variables_are_globalized_in_the_order_of_their_names() { /// `transl_simple_type` empties the used variables first (738): `'q`, /// used by a translation before it, is not globalized. #[test] -#[ignore = "R5a-2 build"] fn globalized_variables_are_at_the_global_level() { let mut w = world(); w.st.vars.reset(1); @@ -913,7 +910,6 @@ fn globalized_variables_are_at_the_global_level() { /// by an alias is no error (`fixed && is_Tvar (repr ty)`): `(int as 'c, /// 'c)` passes under the fixed policy and enters `c`. #[test] -#[ignore = "R5a-2 build"] fn the_fixed_policy_refuses_a_variable_that_is_not_declared() { let mut w = world(); assert_eq!(field_type(&mut w, "('b, 'a)", &[]), Err(Stop::Error)); @@ -945,7 +941,6 @@ fn the_fixed_policy_refuses_a_variable_that_is_not_declared() { /// today's checker and `.. y: int as 'a}` accepted: /// `old_checker_globalize_programs_are_pinned`). #[test] -#[ignore = "R5a-2 build"] fn a_name_bound_to_two_types_by_two_annotations_is_an_error() { let mut w = world(); let level = w.c.g.level; @@ -974,7 +969,6 @@ fn a_name_bound_to_two_types_by_two_annotations_is_an_error() { /// type); the variables of the item before are forgotten (`'a` of an /// earlier scheme is not this one's). An error gives the level back. #[test] -#[ignore = "R5a-2 build"] fn a_scheme_is_generalized() { let mut w = world(); let level = w.c.g.level; @@ -1021,7 +1015,6 @@ fn a_scheme_is_generalized() { /// whole), the used variables with them, and the global level is one /// above the level given (`reset_global_level`, ctype.ml:157). #[test] -#[ignore = "R5a-2 build"] fn reset_forgets_the_declared_variables() { let mut w = world(); let (arena, root) = parse("('x, 'y)"); @@ -1214,7 +1207,6 @@ fn aliases_nested_ten_thousand_deep() { /// declared names come out increasing. Measured on the prototype: /// 60,001 at 10,000. #[test] -#[ignore = "R5a-2 build"] fn ten_thousand_variables_globalized() { let make = |n: usize| format!("({})", (0..n).rev().map(|i| format!("'v{i:05}")).collect::>().join(", ")); let run = |w: &mut World, arena: &ParseArena, root: CoreTypeIdx| { diff --git a/compiler-rust/src/tc/walk/typetexp.rs b/compiler-rust/src/tc/walk/typetexp.rs index 54e780314b..b86a854701 100644 --- a/compiler-rust/src/tc/walk/typetexp.rs +++ b/compiler-rust/src/tc/walk/typetexp.rs @@ -435,7 +435,11 @@ impl Annot<'_> { /// allocation: the second half reads the rows the first sorted. /// (R5a-2) pub fn globalize(&mut self, fixed: bool) -> Result<(), Stop> { - todo!("R5a-2") + let result = self.globalize_rows(fixed); + // On every way out: the sort left `TypeVars::heads` naming rows + // by their old order, and `forget_used` goes by the names. + self.st.vars.forget_used(); + result } /// `transl_simple_type env fixed styp` (compiler/ml/typetexp.ml: @@ -447,7 +451,13 @@ impl Annot<'_> { /// nothing is done for it before R6b. O(1) plus /// [`Annot::transl_type`] and [`Annot::globalize`]. (R5a-2) pub fn transl_simple_type(&mut self, root: CoreTypeIdx, fixed: bool) -> Result { - todo!("R5a-2") + // 737-738. + self.st.vars.drop_univars(); + self.st.vars.forget_used(); + let policy = if fixed { Policy::Fixed } else { Policy::Extensible }; + let ty = self.transl_type(root, policy)?; + self.globalize(fixed)?; + Ok(ty) } /// `transl_type_scheme env styp` (compiler/ml/typetexp.ml:751-756): @@ -457,7 +467,13 @@ impl Annot<'_> { /// `Err` too. O(1) plus [`Annot::transl_simple_type`] and /// `Checker::generalize`. (R5a-2) pub fn transl_type_scheme(&mut self, root: CoreTypeIdx) -> Result { - todo!("R5a-2") + self.st.vars.reset(self.c.g.level); + self.c.g.begin_def(); + let result = self.transl_simple_type(root, false); + self.c.g.end_def(); + let ty = result?; + self.c.generalize(ty); + Ok(ty) } /// `List.assoc name !(univars ())` (compiler/ml/typetexp.ml:308, @@ -581,8 +597,16 @@ impl Annot<'_> { /// the current level whose serial is its index, named by the [`Name`] /// in `name` or by none ([`NONE`]). O(1): one node. fn new_var(&mut self, name: u32) -> Ty { - let serial = self.c.g.nodes.len() as u32; let level = self.c.g.level; + self.var_at(name, level) + } + + /// A variable at `level` whose serial is its index, named by the + /// [`Name`] in `name` or by none ([`NONE`]): [`Annot::new_var`], and + /// `new_global_var ()` (compiler/ml/ctype.ml:213) at + /// `TypeVars::global_level`. O(1): one node. + fn var_at(&mut self, name: u32, level: u32) -> Ty { + let serial = self.c.g.nodes.len() as u32; self.c.g.push(Node { head: VAR, level, @@ -1019,6 +1043,62 @@ impl Annot<'_> { Ok(poly) } + /// The two loops of [`Annot::globalize`] (typetexp.ml:707-733), without + /// its last `TypeVars::forget_used`. The rows are sorted in place by + /// their names' bytes when there are two or more (`Tbl.iter`; + /// CHECKER_REWRITE 10.2, decision 8; `sort_unstable_by` allocates + /// nothing, and no two rows have one name). First loop, a row in that + /// order: a new global variable unified with the row's node inside + /// one speculation, kept on success and restored on failure + /// (`Declined::PolyType`, 10.12 decision 16); then the declared + /// variable of the name, or under `fixed` with the node still a + /// variable `Stop::Error` (721-722), or a second new global variable + /// entered as declared (723-725). Second loop, the rows from the last + /// to the first (`!r`, consed in the first loop's order): the row's + /// node unified with the declared variable of its name, a clash + /// `Stop::Error` (731). Cost: [`Annot::globalize`]'s; 1 step a row in + /// each loop. + fn globalize_rows(&mut self, fixed: bool) -> Result<(), Stop> { + if self.st.vars.used.len() > 1 { + let names = &self.scopes.names; + self.st + .vars + .used + .sort_unstable_by(|left, right| names.text(left.name).as_bytes().cmp(names.text(right.name).as_bytes())); + } + let global = self.st.vars.global_level; + for row in 0..self.st.vars.used.len() { + #[cfg(test)] + super::super::steps::tick(); + let used = self.st.vars.used[row]; + // 709-717: `unify env v ty` under a snapshot. + let var = self.var_at(NONE, global); + let token = self.c.g.speculate(); + if self.c.unify(var, used.ty).is_err() { + self.c.restore(token); + return Err(Stop::Declined(Declined::PolyType)); + } + self.c.g.keep(token); + if self.declared(used.name).0 != NONE { + continue; + } + let repr = self.c.g.repr(used.ty); + if fixed && self.c.g.nodes[repr.0 as usize].tag() == VAR { + return Err(Stop::Error); + } + let declared = self.var_at(NONE, global); + self.add_declared(used.name, declared, used.loc); + } + for row in (0..self.st.vars.used.len()).rev() { + #[cfg(test)] + super::super::steps::tick(); + let used = self.st.vars.used[row]; + let declared = self.declared(used.name); + self.c.unify(used.ty, declared).map_err(|_clash| Stop::Error)?; + } + Ok(()) + } + /// `instance env ty` of a variable's node (compiler/ml/ctype.ml: /// 879-887): a generic node is copied with `Checker::copy`, any /// other is itself (`copy`, 744-797). The variable arm and the alias From c4ba58324353aa5b62aa4b1bef05308c6be3a207 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:28:39 +0000 Subject: [PATCH 5/5] Checker rewrite R5a-2a: unify_params and the road of a type without PLAIN_PARAMS A constructor of a type whose row has no PLAIN_PARAMS is no longer declined: its arguments are translated, its node made, and Annot::unify_params runs typetexp.ml:372-389. ONE copy session of all the declared parameters (instance_list, ctype.ml:891-894: copy_begin, a copy_ref each, copy_drain, then the pass Checker::copy runs after its own session), unify_var of each instance with its argument; then enforce_constraints (ctype.ml:1333-1342): a second session at the node's level and unify_var again, `subst`'s `!unify'` being unify_var (1129-1130, 2767). The instances leave the value stack on both ways out. The doc comment of Annot::transl_type now has the alias, the polymorphic and the constructor arms as 10.12 builds them, and the costs of 10.12.3. r5a_tests::a_type_without_plain_parameters_is_declined goes; arguments_of_shared_parameters_are_unified and three tests of r5a2_tests are no longer ignored. The walk module keeps only the dead_code allowance. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-e9265965-2056-785e-9365-c3bd2347e914 Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/tc/mod.rs | 2 +- compiler-rust/src/tc/r5a2_tests.rs | 3 - compiler-rust/src/tc/r5a_tests.rs | 21 ---- compiler-rust/src/tc/walk/typetexp.rs | 165 ++++++++++++++++++++------ 4 files changed, 131 insertions(+), 60 deletions(-) diff --git a/compiler-rust/src/tc/mod.rs b/compiler-rust/src/tc/mod.rs index 35c2574f75..bdbd84db58 100644 --- a/compiler-rust/src/tc/mod.rs +++ b/compiler-rust/src/tc/mod.rs @@ -101,7 +101,7 @@ pub mod scope; // from the module it completes (CHECKER_REWRITE.md, "R5a as designed"). #[allow(dead_code, unused_variables)] pub(crate) mod decl; -#[allow(dead_code, unused_variables)] +#[allow(dead_code)] pub(crate) mod walk; // The old environment's report of its bindings, opens and lookups, for the diff --git a/compiler-rust/src/tc/r5a2_tests.rs b/compiler-rust/src/tc/r5a2_tests.rs index 8a07b0a1bd..708224f890 100644 --- a/compiler-rust/src/tc/r5a2_tests.rs +++ b/compiler-rust/src/tc/r5a2_tests.rs @@ -1041,7 +1041,6 @@ fn reset_forgets_the_declared_variables() { /// that is the same instance unifies the two arguments; an instance /// that is not a variable is unified (`cl`). #[test] -#[ignore = "R5a-2 build"] fn parameters_without_plain_params_agree_with_todays_checker() { for (annotation, line) in PARAMETERS { let mut w = world(); @@ -1070,7 +1069,6 @@ fn parameters_without_plain_params_agree_with_todays_checker() { /// (`update_level env t1.level t2`, 2758): `'x`, first used one level /// deeper, is at the annotation's level afterwards. #[test] -#[ignore = "R5a-2 build"] fn the_declared_parameters_are_instantiated_not_bound() { let mut w = world(); let (arena, root) = parse("sh"); @@ -1263,7 +1261,6 @@ fn ten_thousand_universal_variables() { /// two `int` nodes after the first (measured on the prototype: 139,995 /// at 10,000). #[test] -#[ignore = "R5a-2 build"] fn ten_thousand_shared_parameters() { let steps_at = |n: usize| { let mut w = world(); diff --git a/compiler-rust/src/tc/r5a_tests.rs b/compiler-rust/src/tc/r5a_tests.rs index 4c85e2169f..e72dacaf97 100644 --- a/compiler-rust/src/tc/r5a_tests.rs +++ b/compiler-rust/src/tc/r5a_tests.rs @@ -559,26 +559,6 @@ fn old_checker_unifies_arguments_of_shared_parameters() { } } -/// R5a-1. Reaches the same bodies as `annotations_agree_with_todays_ -/// checker`, and no other slice. -/// -/// A type whose row has no `PLAIN_PARAMS` is not R5a-1's: the -/// constructor stops with `Declined::NotBuilt` before an argument is -/// translated (no node is made), where a body that only lowers the -/// arguments would accept `t`. -#[test] -fn a_type_without_plain_parameters_is_declined() { - let mut w = world(); - declare_shared(&mut w, "t"); - let (arena, root) = parse("t"); - let nodes = w.c.g.nodes.len(); - assert_eq!( - translate(&mut w, &arena, root, Policy::Extensible), - Err(Stop::Declined(Declined::NotBuilt)) - ); - assert_eq!(w.c.g.nodes.len(), nodes); -} - /// R5a-2. Reaches `Annot::unify_params` (R5a-2) and the bodies of R5a-1. /// /// Decision 5's shared case: with the two parameters of `t` one @@ -589,7 +569,6 @@ fn a_type_without_plain_parameters_is_declined() { /// k<'v>>` makes its two arguments one node: both list slots of the /// constructor resolve to the `k<'v>` node. #[test] -#[ignore = "R5a-2 build"] fn arguments_of_shared_parameters_are_unified() { let mut w = world(); declare_shared(&mut w, "t"); diff --git a/compiler-rust/src/tc/walk/typetexp.rs b/compiler-rust/src/tc/walk/typetexp.rs index b86a854701..c478a9fd73 100644 --- a/compiler-rust/src/tc/walk/typetexp.rs +++ b/compiler-rust/src/tc/walk/typetexp.rs @@ -266,14 +266,15 @@ impl Annot<'_> { /// the node of annotation `root`, every node made at the current /// level, the row of every annotation node written. /// - /// The arms R5a-1 builds, each as OCaml has it: + /// The arms, each as OCaml has it: /// /// - `_` (296-303): a new variable without a name; `Stop::Error` /// under [`Policy::Fixed`]. /// - a variable (304-320): `Stop::Error` when the name starts with - /// `_`; the node of [`TypeVars::used`] when the item used the name - /// (a node that is generic is copied with `Checker::copy`, - /// `instance env`); else a new variable, added with + /// `_`; the node of [`Annot::univar`] when a binder that is open + /// has the name, else of [`TypeVars::used`] when the item used the + /// name (either one, when it is generic, copied with + /// `Checker::copy`, `instance env`); else a new variable, added with /// [`TypeVars::add_used`] under its name at the node's location. /// The new variable holds the name only when the name's first /// character is `_` or an ASCII letter (`validate_name`, 224-231; @@ -295,26 +296,50 @@ impl Annot<'_> { /// parameters stands for each of them and is translated once per /// parameter (360-365); another count than the type's arity is /// `Stop::Error` (366-371), before any argument is translated; - /// a type whose row has no `expand::PLAIN_PARAMS` stops here with - /// `Declined::NotBuilt` (its road is [`Annot::unify_params`], - /// R5a-2), before any argument is translated; then the arguments - /// in order; then, per argument, `Checker::lower` to the current - /// level (CHECKER_REWRITE 10.2, decision 5; a clash is - /// `Stop::Error`); then one constructor node with an empty memo - /// slot. + /// then the arguments in order. For a type whose row has + /// `expand::PLAIN_PARAMS` (one bit of the `TypeInfo` row, loaded + /// again when the node is left), per argument `Checker::lower` to + /// the current level (CHECKER_REWRITE 10.2, decision 5; a clash is + /// `Stop::Error`), then one constructor node with an empty memo + /// slot; for any other type the node, then + /// [`Annot::unify_params`] (372-389; 10.12, decision 19). + /// - an alias (394-428; 10.12, decision 14): when the node is + /// entered, the alias's variable is the universal variable of its + /// name (no instance, 398), or the instance of the used variable + /// (400), or a new variable without a name entered with + /// [`TypeVars::add_used`] at the ALIAS node's location (409-411), + /// before the aliased type; then the aliased type, the frame's one + /// child; when the frame is left, `Checker::unify_var` of the + /// variable with the aliased type's node (a clash, a self-alias + /// the occurrence test refuses included, is `Stop::Error`, + /// `Alias_type_mismatch`). A used name answers the aliased type's + /// node; a new alias answers its variable and gives the + /// representative, when it is a variable without a name, the + /// alias's name as written (417-426, no `validate_name`). + /// - a polymorphic type (545-571; 10.12, decision 18): when the node + /// is entered, `Graph::begin_def` and a variable a name of the + /// binder (named when `validate_name` keeps it), each a row of + /// [`TypeVars::univars`] found through [`TypeVars::univar_heads`]; + /// then the body, the frame's one child; when the frame is left + /// the heads put back, `Graph::end_def`, `Checker::generalize` of + /// the body, one marking walk of the body for the `deep_occur` of + /// every variable of the binder, each variable that occurs made a + /// universal variable (one that is not a generic variable is + /// `Stop::Error`, `Cannot_quantify`), one generic `Poly` node of + /// the body and the bound variables, lowered to the current level. /// /// Everything else stops with the `Declined` variant of /// CHECKER_REWRITE 10.5 when the node is ENTERED, before its children: - /// [`Policy::Univars`] and a polymorphic type (`PolyType`), an alias - /// (`AliasType`), a path of more than one component (`TypePath`), an - /// object, a polymorphic variant, a package, an extension, a node or - /// a parameter with an attribute (`TypeAttribute`), and a constructor - /// whose type's row has no `expand::PLAIN_PARAMS` (`NotBuilt`: R5a-2). - /// The test is one bit of the `TypeInfo` row the arm has loaded for - /// the arity, whatever the number of parameters. + /// [`Policy::Univars`] (`PolyType`; 10.12, decision 20), a path of + /// more than one component (`TypePath`), an object, a polymorphic + /// variant, a package, an extension, and a node or a parameter with + /// an attribute (`TypeAttribute`). /// - /// On `Err` the two stacks are emptied; nodes and rows made so far - /// stay (the unit is dropped). + /// On `Err` the two stacks are emptied, the graph's level is put back + /// to what it was at entry (a binder raised it) and the universal + /// variables of the binders still open are dropped with their heads + /// (10.12, decision 21); nodes and rows made so far stay (the unit is + /// dropped). /// /// Cost: 1 step an annotation node entered (a repeated `_` counts /// each time), plus per arrow parameter one `Param` and one read of @@ -322,8 +347,17 @@ impl Annot<'_> { /// and per constructor one [`Annot::find_type`] (3 steps) and one /// level test an argument (1 step in `Checker::lower`): 4 steps a /// constructor without arguments, 5 a constructor of one argument - /// nested in another. No recursion: an annotation 10,000 deep uses the two - /// stacks. No allocation beyond the growth of the pools. (R5a-1) + /// nested in another. An alias: 1 step entered, one + /// `NameTable::intern` and one `Checker::unify_var` (a new variable + /// against a node without a child walks nothing); a use of an + /// alias's name: 1 step and one link followed. A variable or an alias + /// inside or outside a binder pays the test `univars.is_empty()`. A + /// binder of u variables over a body of n nodes: 1 step a variable + /// entered, n for `generalize`, n for the marking walk, 1 a variable + /// to bind, n for the last lowering. A constructor of a type without + /// `PLAIN_PARAMS`: [`Annot::unify_params`]. No recursion: an + /// annotation 10,000 deep uses the two stacks. No allocation beyond + /// the growth of the pools. (R5a-1, R5a-2) pub fn transl_type(&mut self, root: CoreTypeIdx, policy: Policy) -> Result { let level = self.c.g.level; let result = self.walk(root, policy); @@ -380,8 +414,9 @@ impl Annot<'_> { /// group has, and a stub's row has `PLAIN_PARAMS`: CHECKER_REWRITE /// 10.12, decision 19), then `enforce_constraints` on the node /// (387-389; ctype.ml:1333-1342): a second copy session of the - /// parameters at the node's level and `Checker::unify` of each - /// instance with its argument. + /// parameters at the node's level and `Checker::unify_var` of each + /// instance with its argument (`subst`'s `!unify'`, ctype.ml:1129-1130, + /// which is `unify_var`, 2767). /// /// The declared parameters are the `arity` nodes of /// [`AnnotState::params`] from `AnnotState::params_of[type_index]` @@ -400,7 +435,25 @@ impl Annot<'_> { /// the unifications. No allocation beyond the growth of the pools. /// (R5a-2) pub fn unify_params(&mut self, type_index: u32, args: u32, node: Ty) -> Result<(), Stop> { - todo!("R5a-2") + let start = match self.st.params_of.get(type_index as usize) { + Some(&start) if start != NONE => start, + _ => return Err(Stop::Declined(Declined::NotBuilt)), + }; + let arity = u32::from(self.c.types.info(type_index).arity); + let mark = self.st.values.len(); + // typetexp.ml:373-385: `instance_list decl.type_params`, then + // `unify_var` of each instance with its argument. + let result = self.unify_instances(start, arity, args); + self.st.values.truncate(mark); + result?; + // `enforce_constraints` (ctype.ml:1333-1342): `subst` at the + // node's level (1115-1116), whose `!unify'` is `unify_var` + // (1129-1130, 2767). + let level = std::mem::replace(&mut self.c.g.level, self.c.g.nodes[node.0 as usize].level); + let result = self.unify_instances(start, arity, args); + self.c.g.level = level; + self.st.values.truncate(mark); + result } /// `globalize_used_variables env fixed` (compiler/ml/typetexp.ml: @@ -694,11 +747,6 @@ impl Annot<'_> { if !repeated && args.len() != arity as usize { return Err(Stop::Error); } - // CHECKER_REWRITE 10.2, decision 5: without the bit the - // road is `Annot::unify_params` (R5a-2). - if info.reserved & PLAIN_PARAMS == 0 { - return Err(Stop::Declined(Declined::NotBuilt)); - } self.set_row(node, CoreTypeRow { ty: Ty(NONE), resolved }); self.push_frame(node); return Ok(()); @@ -874,21 +922,31 @@ impl Annot<'_> { // `unify_var` of it with the argument is `update_level` // (compiler/ml/ctype.ml:2748-2767, 584-640). No node is made // for the instance (CHECKER_REWRITE 10.2, decision 5). + // Without the bit (CHECKER_REWRITE 10.2, decision 5) the node + // is made and then `Annot::unify_params` runs (typetexp.ml: + // 373-389). CoreTypeDesc::Ptyp_constr(_) => { let type_index = self.type_index(frame.node)?; - for at in base..self.st.values.len() { - let arg = self.st.values[at]; - self.c.lower(arg, level).map_err(|_clash| Stop::Error)?; + let plain = self.c.types.info(type_index).reserved & PLAIN_PARAMS != 0; + if plain { + for at in base..self.st.values.len() { + let arg = self.st.values[at]; + self.c.lower(arg, level).map_err(|_clash| Stop::Error)?; + } } let b = self.c.g.lists.len() as u32; self.c.g.lists.push(Ty(NONE)); self.c.g.lists.extend_from_slice(&self.st.values[base..]); - self.c.g.push(Node { + let constr = self.c.g.push(Node { head: CONSTR | count << 8, level, a: type_index, b, - }) + }); + if !plain { + self.unify_params(type_index, base as u32, constr)?; + } + constr } CoreTypeDesc::Ptyp_arrow(arrow) => { let (first, _, _) = &**arrow; @@ -1099,6 +1157,43 @@ impl Annot<'_> { Ok(()) } + /// One loop of [`Annot::unify_params`]: `instance_list` of the + /// `arity` declared parameters from `start` (compiler/ml/ctype.ml: + /// 891-894: ONE copy session, `Graph::copy_begin`, a + /// `Graph::copy_ref` a parameter, `Graph::copy_drain`, then the pass + /// `Checker::copy` runs after its own session), the instances pushed + /// on [`AnnotState::values`]; then `Checker::unify_var` of each + /// instance with the argument at `args + i` of the value stack, a + /// clash `Stop::Error`. The caller takes the instances off. Cost: 1 + /// step a generic node copied, 1 step a parameter, and the + /// unifications; no allocation beyond the growth of the pools. + fn unify_instances(&mut self, start: u32, arity: u32, args: u32) -> Result<(), Stop> { + let first = self.c.g.nodes.len(); + let mark = self.st.values.len(); + self.c.g.copy_begin(); + for at in start..start + arity { + let param = self.st.params[at as usize]; + let copy = self.c.g.copy_ref(param); + self.st.values.push(copy); + } + self.c.g.copy_drain(); + // `Checker::copy` after `Graph::copy` (expand.rs). + let cells = !self.c.extras.descriptors.is_empty(); + if self.c.memo.live != 0 || cells { + self.c.extras.copying = true; + self.c.link_memorized(first, NONE, cells); + self.c.extras.copying = false; + } + for at in 0..arity as usize { + #[cfg(test)] + super::super::steps::tick(); + let param = self.st.values[mark + at]; + let arg = self.st.values[args as usize + at]; + self.c.unify_var(param, arg).map_err(|_clash| Stop::Error)?; + } + Ok(()) + } + /// `instance env ty` of a variable's node (compiler/ml/ctype.ml: /// 879-887): a generic node is copied with `Checker::copy`, any /// other is itself (`copy`, 744-797). The variable arm and the alias