From 947fad3d93cf0d5e103e2045d81ae81d41ec4127 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 14:17:29 +0000 Subject: [PATCH 1/4] Checker rewrite R5a-2: the acceptance tests and the skeleton of the variable half src/tc/r5a2_tests.rs: the acceptance tests of aliases, universal variables, globalize, transl_simple_type, transl_type_scheme and unify_params, ignored until the slice is built, beside pins of today's checker on every program they judge (ten aliases, twelve record fields with a polymorphic type, five object programs, eight annotations over types whose parameters share a variable or are constrained). Six step tests relate 1,000 and 10,000 elements. All of them ran against a throw-away prototype that is not committed. src/tc/walk/typetexp.rs, skeleton only: TypeVars gains univar_heads and global_level; TypeVars::reset takes the current level; Annot gains univar, declared and add_declared (todo!("R5a-2")); the doc comments of unify_params, globalize, transl_simple_type and transl_type_scheme say what the prototype showed they do. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-70623c69-2944-7bf2-a162-c8f0b9ef7aeb 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 | 1295 +++++++++++++++++++++++++ compiler-rust/src/tc/walk/typetexp.rs | 136 ++- 3 files changed, 1413 insertions(+), 20 deletions(-) create mode 100644 compiler-rust/src/tc/r5a2_tests.rs diff --git a/compiler-rust/src/tc/mod.rs b/compiler-rust/src/tc/mod.rs index 26624785eb..35c2574f75 100644 --- a/compiler-rust/src/tc/mod.rs +++ b/compiler-rust/src/tc/mod.rs @@ -127,3 +127,5 @@ mod r4_tests; mod decl_oracle; #[cfg(all(test, debug_assertions))] mod r5a_tests; +#[cfg(all(test, debug_assertions))] +mod r5a2_tests; diff --git a/compiler-rust/src/tc/r5a2_tests.rs b/compiler-rust/src/tc/r5a2_tests.rs new file mode 100644 index 0000000000..2a4b7fe36f --- /dev/null +++ b/compiler-rust/src/tc/r5a2_tests.rs @@ -0,0 +1,1295 @@ +//! Tests of slice R5a-2 (CHECKER_REWRITE 10.12): aliases, universal +//! variables, `globalize`, `transl_simple_type`, `transl_type_scheme`, +//! `unify_params`. +//! +//! The first part runs today on today's checker and pins what it answers +//! for every program the second part judges; where the OCaml compiler +//! answers otherwise the constant says so and the test of the new checker +//! follows OCaml. The second part is the acceptance tests of R5a-2, +//! ignored until the slice is built; each names the `todo!` slices it +//! reaches. The new checker's side writes its type table by hand, as +//! `r5a_tests` does. +//! +//! A polymorphic type (`'a. t`) stands in an object field and in a record +//! field. An object declines in R5a and a record is R5a-4's, so the new +//! side reaches the arm through the parse tree of a record field: +//! `type r = {m: }` is parsed and the field's annotation +//! node is translated ([`parse_field`]). + +use super::decl::Decls; +use super::decl_oracle::{Verdict, old_judge}; +use super::expand::{ABBREV, LOCAL, Manifest, PLAIN_PARAMS, TypeInfo, TypeTable}; +use super::graph::{ARROW, CONSTR, GENERIC, Graph, NONE, Node, TUPLE, Ty, VAR}; +use super::name_table::Name; +use super::scope::{BinderKind, Key, Namespace, Scopes}; +use super::segment::{EXTENDED, ExtraDescriptor}; +use super::steps; +use super::unify::Checker; +use super::walk::typetexp::{Annot, AnnotState, Policy}; +use super::{Declined, Stop}; +use crate::parse_arena::{CoreTypeIdx, ParseArena}; +use crate::parser::ast::{StructureItemDesc, TypeKind}; +use crate::parser::{Parser, module}; +use std::fmt::Write; + +/// The types of the hand-written table, as source for today's checker: +/// `k` and `p` abstract, `id` the identity abbreviation, `ph` a phantom +/// abbreviation, `sh` with two parameters that are one variable, `cl` +/// with a parameter that is not a variable. +const PRELUDE: &str = "type k<'a>\ntype p<'a, 'b>\ntype id<'a> = 'a\ntype ph<'a> = int\n\ +type sh<'a, 'b> = int constraint 'a = 'b\ntype cl<'a> = 'b constraint 'a = list<'b>\n"; + +/// An annotation with an alias and the canonical line of `external v: +/// = "v"` after [`PRELUDE`], as today's checker prints it +/// (observed; `old_checker_aliases_are_pinned` keeps it observed). `@n` +/// is a second visit of the node numbered `&n`. The OCaml compiler was +/// put the first, the fourth and the eighth (the coordinator's run: +/// `(array<'a>, array<'a>) => 'a`; a variable written `'\"1a"` has no +/// name and the alias gives its proxy the name unchecked); the others +/// follow compiler/ml/typetexp.ml:394-428 and today's checker. +const ALIASES: [(&str, &str); 10] = [ + // The alias's variable is linked to the aliased type (`unify_var t + // ty`, 412): both uses are one node. + ("(array<'a> as 'b, 'b) => 'a", "value v: &0((&1(array<'0:a>), @1) => '0:a)"), + ("(int as 'a, 'a) => 'a", "value v: &0((&1(int), @1) => @1)"), + // The name is used first: the first branch (396-407), `unify_var` + // of the used variable's node. + ("('a, int as 'a) => 'a", "value v: &0((&1(int), @1) => @1)"), + // An unnamed variable gets the alias as its name (417-426). + ("(_ as 'a, 'a) => int", "value v: &0(('0:a, '0:a) => &1(int))"), + // A named one keeps its own. + ("('a as 'b, 'b) => 'a", "value v: &0(('0:a, '0:a) => '0:a)"), + ("(('a as 'b) as 'c, 'c) => 'b", "value v: &0(('0:a, '0:a) => '0:a)"), + ("((int, 'a) as 'b, 'b) => 'a", "value v: &0((&1(tuple(&2(int), '0:a)), @1) => '0:a)"), + // No `validate_name` for the proxy's name (417-422). + ("(_ as '\\\"1a\", '\\\"1a\") => int", "value v: &0(('0:1a, '0:1a) => &1(int))"), + ( + "(int as 'a, string as 'b, ('a, 'b)) => int", + "value v: &0((&1(int), &2(string), &3(tuple(@1, @2))) => &4(int))", + ), + ("(k<_> as 'a, p<'a, 'a>) => int", "value v: &0((&1(k<'0>), &2(p<@1, @1>)) => &3(int))"), +]; + +/// Annotations both compilers refuse with `Alias_type_mismatch` +/// (typetexp.ml:403-406, 413-416): the alias's variable is bound to +/// another type already. OCaml: `('a, int as 'a, string as 'a) => int` +/// is refused at 1:29-40. +const ALIAS_CLASHES: [&str; 2] = ["('a, int as 'a, string as 'a) => int", "(int as 'a, string as 'a) => int"]; + +/// Self-aliases the OCAML compiler refuses ("This alias is bound to type +/// array<'a> but is used as an instance of type 'a", "The type variable +/// 'a occurs inside array<'a>"): the alias's variable is entered before +/// the aliased type is translated (409-411), so `'b` inside is the +/// variable itself, and `unify_var` (compiler/ml/ctype.ml:2748-2765) +/// takes `Tvar _, Tconstr _ when deep_occur t1 t2 -> unify` or `occur`. +/// TODAY'S CHECKER DIFFERS: it accepts each of them (a branch of its own +/// in its alias arm; reported, and being corrected by another change), +/// so no test pins today's checker on them. The first five were put to +/// OCaml by the coordinator; `k<'b> as 'b` (an abstract type) follows +/// from the same lines and is listed in the pull request as a program to +/// run. +const SELF_ALIASES_OCAML_REFUSES: [&str; 6] = [ + "(array<'b> as 'b) => int", + "((int, 'b) as 'b) => int", + "(('b => int) as 'b) => int", + "(option<'b> as 'b) => int", + "(array> as 'b) => int", + "(k<'b> as 'b) => int", +]; + +/// A record field's annotation and its `label m ..:` type in the +/// canonical signature of `type r = {m: }` after +/// [`PRELUDE`], as today's checker prints it (observed), or `None` when +/// today's checker refuses the declaration. OCaml agrees on the forms +/// the coordinator ran as object fields: a universal variable that does +/// not occur is dropped from the list (`'a 'b. 'a => int` prints `'a. +/// 'a => int`), `'a. (int as 'a) => int` is refused with "The universal +/// type variable 'a cannot be generalized: it is not a variable", and +/// `'a. ('a as 'b) => 'b` is accepted. +const FIELDS: [(&str, Option<&str>); 12] = [ + ("'a. 'a => 'a", Some("&0(poly[!0:a] &1((!0:a) => !0:a))")), + // typetexp.ml:556-567: only a variable that occurs is bound. + ("'a 'b. 'a => int", Some("&0(poly[!0:a] &1((!0:a) => &2(int)))")), + ("'a 'b. ('b, 'a)", Some("&0(poly[!0:a, !1:b] &1(tuple(!1:b, !0:a)))")), + // `List.assoc` finds the first of two variables of one name (308). + ("'a 'a. 'a => 'a", Some("&0(poly[!0:a] &1((!0:a) => !0:a))")), + // A field without a binder is no `Ptyp_poly`: the type itself. + ("int => int", Some("&0((&1(int)) => &2(int))")), + ("'a. array<'a> => k<'a>", Some("&0(poly[!0:a] &1((&2(array)) => &3(k)))")), + // The silent skip of `globalize_used_variables` (712-717): accepted + // by both compilers. + ("'a. ('a as 'b) => 'b", Some("&0(poly[!0:a] &1((!0:a) => !0:a))")), + // `Cannot_quantify` (565): bound to a type. + ("'a. (int as 'a) => int", None), + // `Cannot_quantify`: the second variable's proxy is the first's + // universal variable. + ("'a 'b. ('a as 'b) => int", None), + // `Unbound_type_variable` under the fixed policy (721-722). + ("'a. 'a => 'b", None), + // `Unbound_type_variable "_"` under the fixed policy (299-300). + ("'a. 'a => _", None), + ("'a. missing<'a>", None), +]; + +/// The coordinator's object programs, pinned on today's checker (it +/// agrees with OCaml on each): the alias of a universal variable, the +/// universal variable left outside its binder (field `n` holds the +/// universal variable of `m`), `Cannot_quantify`, the dropped variable, +/// and the outer `'a` beside the universal one. +const OBJECT_PROGRAMS: [(&str, Option<&str>); 5] = [ + ( + "{\"m\": 'a. ('a as 'b) => 'b} => int", + Some("value v: &0((&1(object{&2(m[Immutable]: &3(poly[!0:a] &4((!0:a) => !0:a)); &5(nil))})) => &6(int))"), + ), + ( + "{\"m\": 'a. ('a as 'c) => int, \"n\": 'c} => int", + Some( + "value v: &0((&1(object{&2(m[Immutable]: &3(poly[!0:a] &4((!0:a) => &5(int))); &6(n[Immutable]: &7(poly[] !0:a); &8(nil)))})) => &9(int))", + ), + ), + ("{\"m\": 'a. (int as 'a) => int} => int", None), + ( + "{\"m\": 'a 'b. 'a => int} => int", + Some("value v: &0((&1(object{&2(m[Immutable]: &3(poly[!0:a] &4((!0:a) => &5(int))); &6(nil))})) => &7(int))"), + ), + ( + "('a, {\"m\": 'a. 'a => 'a}) => 'a", + Some("value v: &0(('0:a, &1(object{&2(m[Immutable]: &3(poly[!1:a] &4((!1:a) => !1:a)); &5(nil))})) => '0:a)"), + ), +]; + +/// Annotations over the two types of [`PRELUDE`] without +/// `PLAIN_PARAMS`, with the line today's checker prints or `None` when +/// it refuses (observed). OCaml was put the refusals and `sh` +/// (decision 5's programs); the lines of the others are today's +/// checker's and are listed in the pull request as programs to run. +const PARAMETERS: [(&str, Option<&str>); 8] = [ + ("sh", None), + ("sh", Some("value v: &0(sh<&1(int), @1>)")), + // The second `unify_var` meets a parameter linked to the first + // argument (ctype.ml:2748-2765): the two arguments are one node. + ("sh<'x, array<'v>>", Some("value v: &0(sh<&1(array<'0:v>), @1>)")), + ("(sh<'x, 'y>, 'x) => 'y", Some("value v: &0((&1(sh<'0:y, '0:y>), '0:y) => '0:y)")), + ("cl", None), + ("cl>", Some("value v: &0(cl<&1(list<&2(int)>)>)")), + // The parameter's instance is not a variable: `unify` (2765), and + // the argument is bound to an instance of `list<'b>` without a name. + ("cl<'x> => 'x", Some("value v: &0((&1(cl<&2(list<'0>)>)) => @2)")), + ("cl<_>", Some("value v: &0(cl<&1(list<'0>)>)")), +]; + +fn external(annotation: &str) -> String { + format!("{PRELUDE}external v: {annotation} = \"v\"\n") +} + +fn field(annotation: &str) -> String { + format!("{PRELUDE}type r = {{m: {annotation}}}\n") +} + +/// The line of today's checker that starts with `prefix`, without the +/// prefix, or `None` when it rejects the program. +fn old_line(program: &str, prefix: &str) -> Option { + match old_judge(program) { + Verdict::Rejected => None, + Verdict::Accepted(signature) => Some( + signature + .lines() + .find_map(|line| line.trim_start().strip_prefix(prefix)) + .unwrap_or_else(|| panic!("no line {prefix:?} in\n{signature}")) + .to_string(), + ), + } +} + +const LABEL: &str = "label m runtime=None Immutable optional=false: "; + +/// Runs today. Every line of [`ALIASES`] is what today's checker prints, +/// and it refuses [`ALIAS_CLASHES`]. +#[test] +fn old_checker_aliases_are_pinned() { + for (annotation, line) in ALIASES { + let old = old_line(&external(annotation), "value v: ").map(|line| format!("value v: {line}")); + assert_eq!(old.as_deref(), Some(line), "{annotation}"); + } + for annotation in ALIAS_CLASHES { + assert_eq!(old_judge(&external(annotation)), Verdict::Rejected, "{annotation}"); + } +} + +/// Runs today. Every row of [`FIELDS`] and of [`OBJECT_PROGRAMS`] is +/// what today's checker answers. +#[test] +fn old_checker_polymorphic_types_are_pinned() { + for (annotation, line) in FIELDS { + assert_eq!(old_line(&field(annotation), LABEL).as_deref(), line, "{annotation}"); + } + for (annotation, line) in OBJECT_PROGRAMS { + let old = old_line(&external(annotation), "value v: ").map(|line| format!("value v: {line}")); + assert_eq!(old.as_deref(), line, "{annotation}"); + } +} + +/// Runs today. Every row of [`PARAMETERS`] is what today's checker +/// answers. +#[test] +fn old_checker_parameters_are_pinned() { + for (annotation, line) in PARAMETERS { + let old = old_line(&external(annotation), "value v: ").map(|line| format!("value v: {line}")); + assert_eq!(old.as_deref(), line, "{annotation}"); + } +} + +/// Runs today. The programs of `globalize_used_variables` and of +/// `transl_type_scheme`: under the fixed policy of a record field and of +/// a constructor argument an unbound variable is refused (OCaml: `type t +/// = {x: ('b, 'a)}` at 1:20, the variable `'a`, the FIRST in the order +/// of the names; `type t = A(('zz, 'b, 'a))` at 1:23); a declared +/// parameter is found; a parameter bound to a type by a field's alias +/// is accepted (the second unification, 727-733, binds the parameter: +/// the declaration's parameter prints as `int`), and bound to two types +/// by two fields it is refused (`Type_mismatch`, 733). The last three +/// were not put to OCaml: listed in the pull request. An external's +/// variables are generalized. +#[test] +fn old_checker_globalize_programs_are_pinned() { + assert_eq!(old_judge("type t = {x: ('b, 'a)}\n"), Verdict::Rejected); + assert_eq!(old_judge("type t = A(('zz, 'b, 'a))\n"), Verdict::Rejected); + assert!(matches!(old_judge("type t<'a, 'b> = {x: ('b, 'a)}\n"), Verdict::Accepted(_))); + assert_eq!(old_line("type t<'a> = {x: int as 'a}\n", "params ").as_deref(), Some("[&0(int)] arity=1 Public immediate=false Boxed")); + assert!(matches!(old_judge("type t<'a> = {x: int as 'a, y: int as 'a}\n"), Verdict::Accepted(_))); + assert_eq!(old_judge("type t<'a> = {x: int as 'a, y: string as 'a}\n"), Verdict::Rejected); + assert_eq!( + old_line("type t = {x: (int as 'c, 'c)}\n", "label x runtime=None Immutable optional=false: ").as_deref(), + Some("&0(tuple(&1(int), @1))") + ); + assert_eq!( + old_line("external v: ('a, 'a) => 'b = \"v\"\n", "value v: ").as_deref(), + Some("&0(('0:a, '0:a) => '1:b)") + ); + // `f(1, 2)` and `f("a", "b")` both type: the scheme is generalized. + let uses = "external f: ('a, 'a) => 'b = \"f\"\nlet a: int = f(1, 2)\nlet b: string = f(\"a\", \"b\")\n"; + assert!(matches!(old_judge(uses), Verdict::Accepted(_))); +} + +/// The new checker's side: a checker, scopes with the predefined types +/// in scope 0 and the types of [`PRELUDE`] in scope 1. +struct World { + c: Checker, + scopes: Scopes, + decls: Decls, + st: AnnotState, + /// The type indices of `sh` and `cl`. + sh: u32, + cl: u32, +} + +fn var_at(c: &mut Checker, level: u32) -> Ty { + let serial = c.g.nodes.len() as u32; + c.g.push(Node { head: VAR, level, a: NONE, b: serial }) +} + +fn constr_at(c: &mut Checker, level: u32, type_index: u32, args: &[Ty]) -> Ty { + let b = c.g.lists.len() as u32; + c.g.lists.push(Ty(NONE)); + c.g.lists.extend_from_slice(args); + c.g.push(Node { head: CONSTR | (args.len() as u32) << 8, level, a: type_index, b }) +} + +/// A row and a binder for `name`; the type index. +fn declare(w: &mut World, name: &str, arity: u16, reserved: u8) -> u32 { + let type_index = w.c.types.rows.len() as u32; + w.c.types.rows.push(TypeInfo { manifest: NONE, scope: 0, newtype: NONE, arity, flags: LOCAL, reserved }); + let name = w.scopes.names.intern(name); + let binder = w.scopes.binders.push(Key::new(name, Namespace::Type), type_index, NONE, BinderKind::Type); + w.scopes.bind(binder); + type_index +} + +/// Make `type_index` an abbreviation of `body` over `params`, all +/// generic (as `expand::tests::abbreviation`). +fn abbreviation(w: &mut World, type_index: u32, params: &[Ty], body: Ty) { + let c = &mut w.c; + let b = c.g.lists.len() as u32; + c.g.lists.extend_from_slice(params); + c.g.lists.push(body); + let root = c.g.push(Node { head: TUPLE | (params.len() as u32 + 1) << 8, level: GENERIC, a: 0, b }); + let template = c.g.capture(root); + let first = c.types.roots.len() as u32; + for ¶m in params { + let reference = Ty(c.g.forward[param.0 as usize].target); + c.types.roots.push(reference); + } + c.types.manifests.push(Manifest { template, params: first, body: Ty(c.g.forward[body.0 as usize].target) }); + let row = &mut c.types.rows[type_index as usize]; + row.manifest = c.types.manifests.len() as u32 - 1; + row.flags |= ABBREV; +} + +/// The declared parameters of a type without `PLAIN_PARAMS`. +fn parameters(w: &mut World, type_index: u32, params: &[Ty]) { + w.st.params_of.resize(type_index as usize + 1, NONE); + w.st.params_of[type_index as usize] = w.st.params.len() as u32; + w.st.params.extend_from_slice(params); +} + +fn world() -> World { + let mut w = World { + c: Checker::new(Graph::default(), TypeTable::default()), + scopes: Scopes::new(), + decls: Decls::default(), + st: AnnotState::default(), + sh: NONE, + cl: NONE, + }; + w.scopes.enter(); + w.decls.predefine(&mut w.c, &mut w.scopes, &mut w.st); + w.scopes.enter(); + declare(&mut w, "k", 1, PLAIN_PARAMS); + declare(&mut w, "p", 2, PLAIN_PARAMS); + // `type id<'a> = 'a`. + let id = declare(&mut w, "id", 1, PLAIN_PARAMS); + let a = var_at(&mut w.c, GENERIC); + abbreviation(&mut w, id, &[a], a); + // `type ph<'a> = int`. + let ph = declare(&mut w, "ph", 1, PLAIN_PARAMS); + let a = var_at(&mut w.c, GENERIC); + let int = constr_at(&mut w.c, GENERIC, 0, &[]); + abbreviation(&mut w, ph, &[a], int); + // `type sh<'a, 'b> = int constraint 'a = 'b`: both parameters are + // one generic variable. + w.sh = declare(&mut w, "sh", 2, 0); + let shared = var_at(&mut w.c, GENERIC); + let int = constr_at(&mut w.c, GENERIC, 0, &[]); + let sh = w.sh; + abbreviation(&mut w, sh, &[shared, shared], int); + parameters(&mut w, sh, &[shared, shared]); + // `type cl<'a> = 'b constraint 'a = list<'b>`: the parameter is the + // generic node `list<'b>`. + w.cl = declare(&mut w, "cl", 1, 0); + let b = var_at(&mut w.c, GENERIC); + let list = PREDEFINED_LIST; + let param = constr_at(&mut w.c, GENERIC, list, &[b]); + let cl = w.cl; + abbreviation(&mut w, cl, &[param], b); + parameters(&mut w, cl, &[param]); + w +} + +/// The type index of `list` (`decl::PREDEFINED`). +const PREDEFINED_LIST: u32 = 9; + +/// Parse `external v: = "v"` alone: the arena and the +/// annotation's node. +fn parse(annotation: &str) -> (ParseArena, CoreTypeIdx) { + let text = format!("external v: {annotation} = \"v\"\n"); + let mut parser = Parser::new("Case.res", &text); + let structure = module::parse_structure(&mut parser); + let root = match &structure[0].pstr_desc { + StructureItemDesc::Pstr_primitive(description) => description.pval_type, + other => panic!("not an external: {other:?}"), + }; + (parser.into_arena(), root) +} + +/// Parse `type r = {m: }` alone: the arena and the node of +/// the field's annotation (a `Ptyp_poly` when it binds variables). +fn parse_field(annotation: &str) -> (ParseArena, CoreTypeIdx) { + let text = format!("type r = {{m: {annotation}}}\n"); + let mut parser = Parser::new("Case.res", &text); + let structure = module::parse_structure(&mut parser); + let root = match &structure[0].pstr_desc { + StructureItemDesc::Pstr_type(group) => match &group.1[0].ptype_kind { + TypeKind::Ptype_record(labels) => labels[0].pld_type, + other => panic!("not a record: {other:?}"), + }, + other => panic!("not a type: {other:?}"), + }; + (parser.into_arena(), root) +} + +fn annot<'a>(w: &'a mut World, arena: &'a ParseArena) -> Annot<'a> { + Annot { c: &mut w.c, scopes: &mut w.scopes, arena, st: &mut w.st } +} + +fn translate(w: &mut World, arena: &ParseArena, root: CoreTypeIdx, policy: Policy) -> Result { + annot(w, arena).transl_type(root, policy) +} + +/// The canonical form of a node of the new graph, in the syntax of +/// today's canonical signature: `&n(..)` a node that is not a variable, +/// in the order first met, `@n` its later visits (so a type that names +/// itself prints and ends), `'n` a variable and `!n` a universal +/// variable in one numbering, `:name` after a named one. +fn canon(w: &mut World, root: Ty) -> String { + fn go(w: &mut World, ty: Ty, out: &mut String, vars: &mut Vec, nodes: &mut Vec) { + let ty = w.c.g.repr(ty); + let node = w.c.g.nodes[ty.0 as usize]; + let univar = node.head & EXTENDED != 0 + && matches!(w.c.extras.descriptors[node.a as usize], ExtraDescriptor::Univar(_)); + if node.tag() == VAR || univar { + let index = vars.iter().position(|&seen| seen == ty).unwrap_or_else(|| { + vars.push(ty); + vars.len() - 1 + }); + let name = if univar { + let ExtraDescriptor::Univar(name) = w.c.extras.descriptors[node.a as usize] else { + unreachable!() + }; + name + } else { + node.a + }; + let _ = write!(out, "{}{index}", if univar { '!' } else { '\'' }); + if name != NONE { + let _ = write!(out, ":{}", w.scopes.names.text(Name(name))); + } + return; + } + if let Some(index) = nodes.iter().position(|&seen| seen == ty) { + let _ = write!(out, "@{index}"); + return; + } + let _ = write!(out, "&{}(", nodes.len()); + nodes.push(ty); + let arity = node.arity(); + if node.head & EXTENDED != 0 { + assert_eq!(w.c.extras.descriptors[node.a as usize], ExtraDescriptor::Poly, "a node R5a-2 makes"); + out.push_str("poly["); + for at in 1..arity { + if at != 1 { + out.push_str(", "); + } + let bound = w.c.g.lists[(node.b + at) as usize]; + go(w, bound, out, vars, nodes); + } + out.push_str("] "); + let body = w.c.g.lists[node.b as usize]; + go(w, body, out, vars, nodes); + out.push(')'); + return; + } + match node.tag() { + CONSTR => { + let name = (0..w.scopes.binders.len()) + .find(|&binder| { + w.scopes.binders.kind[binder as usize] == BinderKind::Type + && w.scopes.binders.payload[binder as usize] == node.a + }) + .map(|binder| Key(w.scopes.binders.key[binder as usize]).name()) + .expect("a type with a binder"); + out.push_str(w.scopes.names.text(name)); + if arity != 0 { + out.push('<'); + for at in 0..arity { + if at != 0 { + out.push_str(", "); + } + let arg = w.c.g.lists[(node.b + 1 + at) as usize]; + go(w, arg, out, vars, nodes); + } + out.push('>'); + } + } + TUPLE => { + out.push_str("tuple("); + for at in 0..arity { + if at != 0 { + out.push_str(", "); + } + let element = w.c.g.lists[(node.b + at) as usize]; + go(w, element, out, vars, nodes); + } + out.push(')'); + } + ARROW => { + out.push('('); + for at in 0..arity { + if at != 0 { + out.push_str(", "); + } + let param = w.c.g.params[(node.b + at) as usize]; + go(w, param.ty, out, vars, nodes); + } + out.push_str(") => "); + go(w, Ty(node.a), out, vars, nodes); + } + other => panic!("a node R5a-2 does not make: tag {other}"), + } + out.push(')'); + } + let mut out = String::new(); + go(w, root, &mut out, &mut Vec::new(), &mut Vec::new()); + out +} + +fn value_line(w: &mut World, root: Ty) -> String { + format!("value v: {}", canon(w, root)) +} + +/// R5a-2. Reaches `Annot::transl_type`'s alias arm (R5a-2) and the +/// bodies of R5a-1; no later slice. +/// +/// Every annotation of [`ALIASES`] is translated to the type today's +/// checker gives it, read live beside the pinned line. Arms of +/// typetexp.ml:394-428: the name was used (first branch), the name is +/// 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(); + let (arena, root) = parse(annotation); + let ty = translate(&mut w, &arena, root, Policy::Extensible).expect(annotation); + assert_eq!(value_line(&mut w, ty), line, "{annotation}"); + assert!(w.st.frames.is_empty() && w.st.values.is_empty(), "{annotation}"); + assert_eq!(w.c.g.level, 1, "{annotation}"); + } +} + +/// R5a-2. Reaches the alias arm of `Annot::transl_type` (R5a-2) and the +/// bodies of R5a-1; no later slice. +/// +/// `Alias_type_mismatch` (typetexp.ml:403-406, 413-416) is `Stop::Error` +/// 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(); + let (arena, root) = parse(annotation); + assert_eq!(translate(&mut w, &arena, root, Policy::Extensible), Err(Stop::Error), "{annotation}"); + assert!(w.st.frames.is_empty() && w.st.values.is_empty(), "{annotation}"); + } +} + +/// R5a-2. Reaches the alias arm of `Annot::transl_type` (R5a-2), the +/// kernel's `Checker::unify_var`, and the bodies of R5a-1; no later +/// slice. +/// +/// The alias's variable is entered in the used variables BEFORE the +/// aliased type is translated (typetexp.ml:409-411), so `'b` inside +/// `array<'b> as 'b` is that variable and `unify_var` refuses the +/// binding: every program of [`SELF_ALIASES_OCAML_REFUSES`] is +/// `Stop::Error`, as OCaml answers and today's checker does not. A body +/// that enters the variable after the aliased type accepts them all. +/// +/// Through an abbreviation `unify_var` goes on (`Tvar _, Tconstr _ when +/// deep_occur t1 t2 -> unify`, ctype.ml:2753, and `unify` expands): +/// `id<'b> as 'b` is a variable named `b` (OCaml prints `'a => int`, +/// today's checker `id<'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(); + let (arena, root) = parse(annotation); + assert_eq!(translate(&mut w, &arena, root, Policy::Extensible), Err(Stop::Error), "{annotation}"); + } + let mut w = world(); + let (arena, root) = parse("(id<'b> as 'b) => int"); + let ty = translate(&mut w, &arena, root, Policy::Extensible).unwrap(); + assert_eq!(value_line(&mut w, ty), "value v: &0(('0:b) => &1(int))"); +} + +/// R5a-2. Reaches the alias arm of `Annot::transl_type` (R5a-2), the +/// kernel's `Checker::unify_var`, and the bodies of R5a-1; no later +/// slice. +/// +/// A phantom abbreviation makes a type that names itself: `ph<'b> as +/// 'b` with `type ph<'a> = int` is accepted by OCaml, which prints +/// `(ph<'a> as 'a) => int` (the occurrence walk retries after expanding +/// the constructor, ctype.ml:1384-1408, and the variable is linked to +/// the unexpanded node). The new checker holds the same graph: the +/// argument of the `ph` node is the node itself. The canonical text +/// 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(); + let (arena, root) = parse("(ph<'b> as 'b) => int"); + let ty = translate(&mut w, &arena, root, Policy::Extensible).unwrap(); + assert_eq!(value_line(&mut w, ty), "value v: &0((&1(ph<@1>)) => &2(int))"); + w.c.g.end_def(); + w.c.generalize(ty); + let copy = w.c.copy(ty); + assert_ne!(copy, ty); + assert_eq!(value_line(&mut w, copy), "value v: &0((&1(ph<@1>)) => &2(int))"); +} + +/// R5a-2. Reaches the alias arm of `Annot::transl_type` (R5a-2) and the +/// bodies of R5a-1; no later slice. +/// +/// What the arm leaves, for `(array<'a> as 'b, 'b, 'a)` one level up: +/// the used variables are `b` first (entered when the alias node is +/// entered, at the ALIAS node's location, 410-411), then `a`; the row +/// 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(); + let level = w.c.g.level; + let (arena, root) = parse("(array<'a> as 'b, 'b, 'a)"); + let first = w.c.g.nodes.len(); + let ty = translate(&mut w, &arena, root, Policy::Extensible).unwrap(); + let names: Vec<&str> = w.st.vars.used.iter().map(|used| w.scopes.names.text(used.name)).collect(); + assert_eq!(names, ["b", "a"]); + let crate::parser::ast::CoreTypeDesc::Ptyp_tuple(components) = &arena.get_core_type(root).ptyp_desc else { + panic!("a tuple"); + }; + let alias = arena.type_list(*components)[0]; + assert!(matches!(arena.get_core_type(alias).ptyp_desc, crate::parser::ast::CoreTypeDesc::Ptyp_alias(_))); + assert_eq!(w.st.vars.used[0].loc, arena.get_core_type(alias).ptyp_loc.0); + let tuple = w.c.g.nodes[ty.0 as usize]; + let component = w.c.g.lists[tuple.b as usize]; + let aliased = w.c.g.repr(w.st.rows[alias.0 as usize].ty); + assert_eq!(aliased, w.c.g.repr(component)); + assert_eq!(w.c.g.nodes[aliased.0 as usize].tag(), CONSTR); + for node in &w.c.g.nodes[first..] { + assert!(node.level == level || node.tag() == super::graph::LINK, "{node:?}"); + } + // The alias's variable, `'a`, `array<'a>` and the tuple: four nodes. + assert_eq!(w.c.g.nodes.len() - first, 4); +} + +/// The translation of a record field's annotation as `transl_label` +/// runs it (`transl_simple_type env closed`, typedecl.ml:195: the fixed +/// policy), with `declared` the names of the declaration's parameters. +fn field_type(w: &mut World, annotation: &str, declared: &[&str]) -> Result { + let (arena, root) = parse_field(annotation); + let level = w.c.g.level; + w.st.vars.reset(level); + w.c.g.begin_def(); + let mut a = annot(w, &arena); + for name in declared { + let name = a.scopes.names.intern(name); + let serial = a.c.g.nodes.len() as u32; + let level = a.st.vars.global_level; + let ty = a.c.g.push(Node { head: VAR, level, a: name.0, b: serial }); + a.add_declared(name, ty, NONE); + } + let result = a.transl_simple_type(root, true); + w.c.g.end_def(); + result +} + +/// R5a-2. Reaches the polymorphic arm of `Annot::transl_type`, +/// `Annot::univar`, `Annot::transl_simple_type`, `Annot::globalize`, +/// `Annot::add_declared`, `TypeVars::reset` (all R5a-2) and the bodies +/// of R5a-1; no later slice. +/// +/// Every row of [`FIELDS`]: the type today's checker gives the field, +/// read live, or `Stop::Error` where it refuses, except the alias of a +/// universal variable (`'a. ('a as 'b) => 'b`), which both compilers +/// accept and the new checker DECLINES (`Declined::PolyType`, decision +/// 16 of CHECKER_REWRITE 10.12: the used variable `b` is the universal +/// variable when `globalize` meets it and its unification is skipped, +/// typetexp.ml:712-717). +#[test] +#[ignore = "R5a-2 build"] +fn polymorphic_fields_agree_with_todays_checker() { + for (annotation, line) in FIELDS { + let mut w = world(); + let result = field_type(&mut w, annotation, &[]); + assert_eq!(old_line(&field(annotation), LABEL).as_deref(), line, "{annotation}"); + assert!(w.st.vars.univars.is_empty(), "{annotation}"); + assert_eq!(w.c.g.level, 1, "{annotation}"); + if annotation == "'a. ('a as 'b) => 'b" { + assert_eq!(result, Err(Stop::Declined(Declined::PolyType))); + assert_eq!(w.c.g.speculation_depth, 0, "the speculation is closed before the decline"); + continue; + } + match line { + Some(line) => assert_eq!(canon(&mut w, result.expect(annotation)), line, "{annotation}"), + None => assert_eq!(result, Err(Stop::Error), "{annotation}"), + } + } +} + +/// R5a-2. Reaches the polymorphic arm of `Annot::transl_type`, +/// `Annot::univar` (R5a-2) and the bodies of R5a-1; no later slice. +/// +/// What the arm leaves for `'a 'b. 'a => int` at level 1 +/// (typetexp.ml:545-571): the level is back; the list of universal +/// variables is empty and the name `a` finds none; the polymorphic node +/// and its body are at the current level, not generic (`unify_var env +/// (newvar ()) ty'`, 570, lowers the generic `Tpoly`); ONE universal +/// 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"); + let univars = w.c.extras.univars; + let ty = translate(&mut w, &arena, root, Policy::Fixed).unwrap(); + assert_eq!(w.c.g.level, 1); + assert!(w.st.vars.univars.is_empty()); + let a = w.scopes.names.intern("a"); + assert_eq!(annot(&mut w, &arena).univar(a), Ty(NONE)); + assert_eq!(w.c.extras.univars, univars + 1); + let poly = w.c.g.nodes[ty.0 as usize]; + assert_eq!(poly.head, TUPLE | EXTENDED | 2 << 8); + assert_eq!(w.c.extras.descriptors[poly.a as usize], ExtraDescriptor::Poly); + assert_eq!(poly.level, 1); + let body = w.c.g.lists[poly.b as usize]; + assert_eq!(w.c.g.nodes[body.0 as usize].level, 1); + let bound = w.c.g.lists[(poly.b + 1) as usize]; + let bound = w.c.g.nodes[bound.0 as usize]; + assert_eq!(bound.head, TUPLE | EXTENDED); + assert_eq!(bound.level, 1); + assert_eq!(w.c.extras.descriptors[bound.a as usize], ExtraDescriptor::Univar(a.0)); + // No used variable: the names of a binder are not used variables. + assert!(w.st.vars.used.is_empty()); +} + +/// R5a-2. Reaches the polymorphic arm of `Annot::transl_type`, +/// `Annot::univar` (R5a-2) and the bodies of R5a-1; no later slice. +/// +/// A universal variable hides a used variable of its name inside its +/// binder only (`univars () := new_univars @ !(univars ())`, 550; +/// `univars () := old_univars`, 553; the lookup of a variable tries +/// the universal ones first, 308). OCaml: `('a, {"m": 'a. 'a => 'a}) => +/// 'a` prints `('b, {"m": 'a. 'a => 'a}) => 'b`. Here: `'a` is used +/// (one annotation), then the field `'a. 'a => 'a` is translated, then +/// `'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"); + let outer = translate(&mut w, &arena, root, Policy::Extensible).unwrap(); + let (field_arena, field_root) = parse_field("'a. 'a => 'a"); + w.st.strs.reset(); + let poly = translate(&mut w, &field_arena, field_root, Policy::Extensible).unwrap(); + w.st.strs.reset(); + let again = translate(&mut w, &arena, root, Policy::Extensible).unwrap(); + assert_eq!(w.c.g.repr(outer), w.c.g.repr(again)); + assert_eq!(w.c.g.nodes[outer.0 as usize].tag(), VAR); + let node = w.c.g.nodes[poly.0 as usize]; + let bound = w.c.g.lists[(node.b + 1) as usize]; + assert_ne!(w.c.g.repr(bound), w.c.g.repr(outer)); + assert_eq!(canon(&mut w, poly), "&0(poly[!0:a] &1((!0:a) => !0:a))"); + assert_eq!(w.st.vars.used.len(), 1); +} + +/// R5a-2. Reaches the polymorphic arm of `Annot::transl_type` (R5a-2) +/// and the bodies of R5a-1; no later slice. +/// +/// An error inside a binder leaves nothing of the binder (10.11, item +/// 4): the graph's level is what it was (the arm's `begin_def` is taken +/// back), the list of universal variables is empty, the two stacks are +/// 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(); + let level = w.c.g.level; + let (arena, root) = parse_field("'a. missing<'a>"); + assert_eq!(translate(&mut w, &arena, root, Policy::Extensible), Err(Stop::Error)); + assert_eq!(w.c.g.level, level); + assert!(w.st.vars.univars.is_empty()); + assert!(w.st.frames.is_empty() && w.st.values.is_empty()); + w.st.strs.reset(); + let (arena, root) = parse("'a"); + let a = translate(&mut w, &arena, root, Policy::Extensible).unwrap(); + assert_eq!(w.st.vars.used.len(), 1); + assert_eq!(w.st.vars.used[0].ty, a); + assert_eq!(w.c.g.nodes[a.0 as usize].level, level); +} + +/// The names of `TypeVars::declared`, in the order entered. +fn declared_names(w: &World) -> Vec<&str> { + w.st.vars.declared.iter().map(|row| w.scopes.names.text(row.name)).collect() +} + +/// R5a-2. Reaches `Annot::globalize`, `Annot::transl_simple_type`, +/// `Annot::declared`, `Annot::add_declared`, `TypeVars::reset` (R5a-2) +/// and the bodies of R5a-1; no later slice. +/// +/// `globalize_used_variables` (typetexp.ml:705-734) without the fixed +/// policy, on `('zz, 'b, 'a)` one level up: the used variables are +/// visited in the increasing order of their names' bytes (`Tbl.iter`, +/// decision 8), so `type_variables` gains `a`, `b`, `zz` in that order, +/// not the order written; each has a variable at the global level +/// (`new_global_var`), one node with the annotation's variable (the +/// second unification, 727-733); the used variables are empty +/// 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; + w.st.vars.reset(level); + assert_eq!(w.st.vars.global_level, level + 1); + w.c.g.begin_def(); + let (arena, root) = parse("('zz, 'b, 'a)"); + let ty = annot(&mut w, &arena).transl_simple_type(root, false).unwrap(); + assert_eq!(declared_names(&w), ["a", "b", "zz"]); + assert!(w.st.vars.used.is_empty()); + assert!(w.st.vars.heads.iter().all(|&head| head == NONE)); + let tuple = w.c.g.nodes[ty.0 as usize]; + for (at, row) in [(2, 0), (1, 1), (0, 2)] { + let written = w.c.g.lists[(tuple.b + at) as usize]; + let global = w.st.vars.declared[row].ty; + assert_eq!(w.c.g.repr(written), w.c.g.repr(global)); + let node = w.c.g.repr(written); + assert_eq!(w.c.g.nodes[node.0 as usize].level, level + 1); + assert_eq!(w.c.g.nodes[node.0 as usize].tag(), VAR); + } + assert_eq!(canon(&mut w, ty), "&0(tuple('0:zz, '1:b, '2:a))"); + w.st.strs.reset(); + let (arena, root) = parse("array<'b>"); + let second = annot(&mut w, &arena).transl_simple_type(root, false).unwrap(); + assert_eq!(declared_names(&w), ["a", "b", "zz"]); + let array = w.c.g.nodes[second.0 as usize]; + let argument = w.c.g.lists[(array.b + 1) as usize]; + let b = w.st.vars.declared[1].ty; + assert_eq!(w.c.g.repr(argument), w.c.g.repr(b)); +} + +/// R5a-2. Reaches `Annot::globalize`, `Annot::transl_simple_type`, +/// `Annot::add_declared`, `TypeVars::reset` (R5a-2) and the bodies of +/// R5a-1; no later slice. +/// +/// The fixed policy (721-722): a used variable that is still a variable +/// and is not a declared one is `Unbound_type_variable`, `Stop::Error` +/// (`type t = {x: ('b, 'a)}`, refused by both compilers); with both +/// declared the annotation is the declared variables' own nodes (`type +/// t<'a, 'b> = {x: ('b, 'a)}`); a used variable that is bound to a type +/// 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)); + let mut w = world(); + assert_eq!(field_type(&mut w, "('b, 'a)", &["a"]), Err(Stop::Error)); + let mut w = world(); + let ty = field_type(&mut w, "('b, 'a)", &["a", "b"]).unwrap(); + assert_eq!(canon(&mut w, ty), "&0(tuple('0:b, '1:a))"); + let tuple = w.c.g.nodes[ty.0 as usize]; + let first = w.c.g.lists[tuple.b as usize]; + let b = w.st.vars.declared[1].ty; + assert_eq!(w.c.g.repr(first), w.c.g.repr(b)); + assert_eq!(declared_names(&w), ["a", "b"]); + let mut w = world(); + let ty = field_type(&mut w, "(int as 'c, 'c)", &[]).unwrap(); + assert_eq!(canon(&mut w, ty), "&0(tuple(&1(int), @1))"); + assert_eq!(declared_names(&w), ["c"]); +} + +/// R5a-2. Reaches `Annot::globalize`, `Annot::transl_simple_type`, +/// `Annot::add_declared`, `TypeVars::reset` (R5a-2) and the bodies of +/// R5a-1; no later slice. +/// +/// The second unification (727-733, `Type_mismatch`): the variables of +/// an item outlive one annotation, so a name bound to `int` by one +/// annotation and to `string` by the next is `Stop::Error` at the +/// second, and bound to `int` twice is accepted with one `int` node +/// class (`type t<'a> = {x: int as 'a, y: string as 'a}` is refused by +/// 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; + w.st.vars.reset(level); + w.c.g.begin_def(); + let (arena, root) = parse("int as 'a"); + let first = annot(&mut w, &arena).transl_simple_type(root, false).unwrap(); + w.st.strs.reset(); + let second = annot(&mut w, &arena).transl_simple_type(root, false).unwrap(); + let a = w.st.vars.declared[0].ty; + assert_eq!(w.c.g.repr(a), w.c.g.repr(first)); + assert_eq!(w.c.g.repr(a), w.c.g.repr(second)); + w.st.strs.reset(); + let (arena, root) = parse("string as 'a"); + assert_eq!(annot(&mut w, &arena).transl_simple_type(root, false), Err(Stop::Error)); +} + +/// R5a-2. Reaches `Annot::transl_type_scheme` and everything it calls +/// (`TypeVars::reset`, `Annot::transl_simple_type`, `Annot::globalize`, +/// all R5a-2) and the bodies of R5a-1; no later slice. +/// +/// `transl_type_scheme` (typetexp.ml:751-756) on `('a, 'a) => 'b`: the +/// line today's checker prints, read live; the level is what it was; +/// every node of the type is generic; two copies are two types whose +/// variables are their own (OCaml: `f(1, 2)` and `f("a", "b")` both +/// 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; + let (arena, root) = parse("('a, 'a) => 'b"); + let ty = annot(&mut w, &arena).transl_type_scheme(root).unwrap(); + assert_eq!(w.c.g.level, level); + assert_eq!(value_line(&mut w, ty), "value v: &0(('0:a, '0:a) => '1:b)"); + assert_eq!( + old_line("external v: ('a, 'a) => 'b = \"v\"\n", "value v: ").as_deref(), + Some("&0(('0:a, '0:a) => '1:b)") + ); + let arrow = w.c.g.nodes[ty.0 as usize]; + assert_eq!(arrow.level, GENERIC); + for at in 0..2 { + let param = w.c.g.params[(arrow.b + at) as usize].ty; + let param = w.c.g.repr(param); + assert_eq!(w.c.g.nodes[param.0 as usize].level, GENERIC); + } + let (one, two) = (w.c.copy(ty), w.c.copy(ty)); + let int = constr_at(&mut w.c, level, 0, &[]); + let string = constr_at(&mut w.c, level, 14, &[]); + let first = w.c.g.params[w.c.g.nodes[one.0 as usize].b as usize].ty; + let other = w.c.g.params[w.c.g.nodes[two.0 as usize].b as usize].ty; + assert!(w.c.unify(first, int).is_ok()); + assert!(w.c.unify(other, string).is_ok()); + // The next item: its `'a` is a new variable. + w.st.strs.reset(); + let (arena, root) = parse("'a"); + let next = annot(&mut w, &arena).transl_type_scheme(root).unwrap(); + let old = w.c.g.params[arrow.b as usize].ty; + assert_ne!(w.c.g.repr(next), w.c.g.repr(old)); + assert_eq!(declared_names(&w), ["a"]); + w.st.strs.reset(); + let (arena, root) = parse("missing"); + assert_eq!(annot(&mut w, &arena).transl_type_scheme(root), Err(Stop::Error)); + assert_eq!(w.c.g.level, level); +} + +/// R5a-2. Reaches `TypeVars::reset`, `Annot::add_declared`, +/// `Annot::declared` (R5a-2) and the bodies of R5a-1; no later slice. +/// +/// `reset_type_variables` (typetexp.ml:213-216): the declared variables +/// are forgotten head by head (the table by name is never filled +/// 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)"); + w.st.vars.reset(4); + assert_eq!(w.st.vars.global_level, 5); + annot(&mut w, &arena).transl_simple_type(root, false).unwrap(); + assert_eq!(declared_names(&w), ["x", "y"]); + let x = w.scopes.names.intern("x"); + assert_ne!(annot(&mut w, &arena).declared(x), Ty(NONE)); + w.st.vars.reset(1); + assert_eq!(w.st.vars.global_level, 2); + assert!(w.st.vars.declared.is_empty() && w.st.vars.used.is_empty()); + assert!(w.st.vars.declared_heads.iter().all(|&head| head == NONE)); + assert_eq!(annot(&mut w, &arena).declared(x), Ty(NONE)); +} + +/// R5a-2. Reaches `Annot::unify_params` (R5a-2) and the bodies of +/// R5a-1; no later slice. +/// +/// Every row of [`PARAMETERS`]: the type today's checker gives the +/// annotation, read live, or `Stop::Error` where it refuses. Arms of +/// typetexp.ml:372-389 and ctype.ml:2748-2765: a parameter's instance +/// that is a variable is linked to the argument; a second parameter +/// 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(); + let (arena, root) = parse(annotation); + let result = translate(&mut w, &arena, root, Policy::Extensible); + let old = old_line(&external(annotation), "value v: ").map(|line| format!("value v: {line}")); + assert_eq!(old.as_deref(), line, "{annotation}"); + match line { + Some(line) => assert_eq!(value_line(&mut w, result.expect(annotation)), line, "{annotation}"), + None => assert_eq!(result, Err(Stop::Error), "{annotation}"), + } + assert!(w.st.frames.is_empty() && w.st.values.is_empty(), "{annotation}"); + } +} + +/// R5a-2. Reaches `Annot::unify_params` (R5a-2) and the bodies of +/// R5a-1; no later slice. +/// +/// `instance_list` is ONE copy session (ctype.ml:891-894) of generic +/// nodes at the current level: after `sh<'x, 'y>` one level up, the +/// declared parameter of `sh` is still a generic variable bound to +/// nothing (a body that unifies the declared nodes themselves binds +/// them, and the next use of `sh` in the unit fails): `sh` +/// then `sh` both translate. The argument of a +/// parameter's instance is lowered to the annotation's level +/// (`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"); + translate(&mut w, &arena, root, Policy::Extensible).unwrap(); + w.st.strs.reset(); + let (arena, root) = parse("sh"); + translate(&mut w, &arena, root, Policy::Extensible).unwrap(); + let declared = w.st.params[w.st.params_of[w.sh as usize] as usize]; + let node = w.c.g.nodes[declared.0 as usize]; + assert_eq!((node.tag(), node.level), (VAR, GENERIC)); + let outer = w.c.g.level; + w.c.g.begin_def(); + w.st.strs.reset(); + let (arena, root) = parse("'x"); + let x = translate(&mut w, &arena, root, Policy::Extensible).unwrap(); + assert_eq!(w.c.g.nodes[x.0 as usize].level, outer + 1); + w.c.g.end_def(); + w.st.strs.reset(); + let (arena, root) = parse("sh<'x, 'y>"); + translate(&mut w, &arena, root, Policy::Extensible).unwrap(); + let x = w.c.g.repr(x); + assert_eq!(w.c.g.nodes[x.0 as usize].level, outer); +} + +/// The steps of `run` in a new world on the annotation `make(n)` gives, +/// at 1,000 and at 10,000: linear, and counted at all. +fn linear(shape: &str, make: impl Fn(usize) -> String, run: impl Fn(&mut World, &ParseArena, CoreTypeIdx), per_element: u64) { + let steps_at = |n: usize| { + let mut w = world(); + let (arena, root) = parse_field(&make(n)); + steps::scope(|| run(&mut w, &arena, root)) + }; + let (small, large) = (steps_at(1_000), steps_at(10_000)); + assert!(small >= 1_000, "{shape}: {small} steps at 1,000"); + assert!(large <= 11 * small, "{shape}: {small} at 1,000, {large} at 10,000"); + assert!( + large <= per_element * 10_000 + 100, + "{shape}: {large} steps at 10,000, more than {per_element} an element" + ); +} + +fn extensible(w: &mut World, arena: &ParseArena, root: CoreTypeIdx) { + translate(w, arena, root, Policy::Extensible).expect("the annotation translates"); +} + +/// R5a-2. Reaches the alias arm of `Annot::transl_type` (R5a-2) and the +/// bodies of R5a-1; no later slice. +/// +/// The loop over frames with alias nodes: n aliases of n names in one +/// tuple, `(int as 'v0, int as 'v1, ..)`. An alias is entered once (1 +/// step) around a constructor without arguments (4 steps); `unify_var` +/// of a new variable with a node without a child walks nothing, and +/// 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); +} + +/// R5a-2. Same bodies as `ten_thousand_aliases`. +/// +/// n uses of ONE alias after it: `(k as 'a, 'a, 'a, ..)` is one +/// load and one link followed a use (the alias's variable is a link to +/// the aliased type; measured on the prototype: 20,015 at 10,000) and +/// 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); + let mut w = world(); + let (arena, root) = parse_field(&make(10_000)); + let first = w.c.g.nodes.len(); + let ty = translate(&mut w, &arena, root, Policy::Extensible).unwrap(); + // The alias's variable, `int`, `k` and the tuple. + assert_eq!(w.c.g.nodes.len() - first, 4); + let tuple = w.c.g.nodes[ty.0 as usize]; + assert_eq!(tuple.arity(), 10_001); + let k = w.c.g.lists[tuple.b as usize]; + let k = w.c.g.repr(k); + for at in 0..tuple.arity() { + let slot = w.c.g.lists[(tuple.b + at) as usize]; + assert_eq!(w.c.g.repr(slot), k); + } +} + +/// R5a-2. Same bodies as `ten_thousand_aliases`. +/// +/// Aliases nested n deep around one type: `((int as 'v0) as 'v1) ..`. +/// Each alias's `unify_var` meets the node of the one inside (a +/// constructor without a child): no walk; 4 steps an alias (measured +/// on the prototype: 40,003 at 10,000: the node entered and the links +/// 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"); + for i in 0..n { + annotation = format!("({annotation} as 'v{i})"); + } + let (arena, root) = std::thread::Builder::new() + .stack_size(1 << 30) + .spawn(move || parse_field(&annotation)) + .unwrap() + .join() + .unwrap(); + std::thread::Builder::new() + .stack_size(2 << 20) + .spawn(move || { + let mut w = world(); + steps::scope(|| extensible(&mut w, &arena, root)) + }) + .unwrap() + .join() + .unwrap() + }; + 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 <= 4 * 10_000 + 100, "{large} steps at 10,000"); +} + +/// R5a-2. Reaches `Annot::globalize`, `Annot::transl_simple_type`, +/// `TypeVars::reset` (R5a-2) and the bodies of R5a-1; no later slice. +/// +/// The two loops of `globalize` over the used variables, and the loop +/// of `TypeVars::reset` over the declared ones: n distinct variables in +/// one tuple, written in DECREASING order of their names so that the +/// sort has work. Per variable: 1 step entered, 1 forgotten, 1 in each +/// loop of `globalize`, and the two unifications of two variables. The +/// comparisons of the sort are not steps; the structure is read: the +/// 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| { + w.st.vars.reset(1); + w.c.g.begin_def(); + annot(w, arena).transl_simple_type(root, false).expect("the annotation translates"); + w.c.g.end_def(); + }; + linear("globalized variables", make, run, 6); + let mut w = world(); + let (arena, root) = parse_field(&make(10_000)); + run(&mut w, &arena, root); + let names = declared_names(&w); + assert_eq!(names.len(), 10_000); + assert!(names.windows(2).all(|pair| pair[0].as_bytes() < pair[1].as_bytes())); + let steps = steps::scope(|| w.st.vars.reset(1)); + assert!((10_000..=10_100).contains(&steps), "{steps} steps to forget 10,000 declared variables"); +} + +/// R5a-2. Reaches the polymorphic arm of `Annot::transl_type`, +/// `Annot::univar` (R5a-2) and the bodies of R5a-1; no later slice. +/// +/// The loops of the polymorphic arm: over the variables of the binder +/// when it is entered, over the body for `deep_occur` (ONE walk for the +/// whole list), and over the list again to bind. `'v0 .. 'v. +/// ('v0, .., 'v)`: per variable 1 step in each loop, 1 for its use +/// and 1 for its node in `generalize` and in the last lowering. A body +/// that walks the type once per variable of the list (`deep_occur v +/// 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(); + format!("{}. ({})", names.join(" "), names.join(", ")) + }; + linear("universal variables", make, extensible, 7); + let mut w = world(); + let (arena, root) = parse_field(&make(10_000)); + let before = w.c.extras.univars; + let ty = translate(&mut w, &arena, root, Policy::Extensible).unwrap(); + assert_eq!(w.c.extras.univars - before, 10_000); + assert_eq!(w.c.g.nodes[ty.0 as usize].arity(), 10_001); + assert!(w.st.vars.univar_heads.iter().all(|&head| head == NONE)); +} + +/// R5a-2. Reaches `Annot::unify_params` (R5a-2) and the bodies of +/// R5a-1; no later slice. +/// +/// The loops of `unify_params` over the parameters: a type of n +/// parameters that are all ONE variable, applied to n times `int`. Per +/// parameter: the 4 steps of `int`, 1 in each of the two loops +/// (`unify_param`, then `enforce_constraints`), and the unification of +/// 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(); + let wide = declare(&mut w, "wide", n as u16, 0); + let shared = var_at(&mut w.c, GENERIC); + parameters(&mut w, wide, &vec![shared; n]); + let (arena, root) = parse(&format!("wide<{}>", vec!["int"; n].join(", "))); + steps::scope(|| extensible(&mut w, &arena, root)) + }; + 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 <= 14 * 10_000 + 100, "{large} steps at 10,000"); +} + +/// Every ignored test of this file names its slice as `R5a- build`, +/// and its doc comment names no slice after its own (the check of +/// `r5a_tests::ignored_tests_name_the_slices_they_reach`, on this +/// file). The number of ignored tests is not pinned. +#[test] +fn ignored_tests_name_the_slices_they_reach() { + let lines: Vec<&str> = include_str!("r5a2_tests.rs").lines().collect(); + let slice_of = |text: &str| -> Vec { + let mut found = Vec::new(); + let mut rest = text; + while let Some(at) = rest.find("R5a-") { + let digits: String = rest[at + 4..].chars().take_while(char::is_ascii_digit).collect(); + if let Ok(number) = digits.parse() { + found.push(number); + } + rest = &rest[at + 4..]; + } + found + }; + assert_eq!(slice_of("reaches R5a-2 and R5a-10"), [2, 10]); + for (at, line) in lines.iter().enumerate() { + let line = line.trim_start(); + if !line.starts_with("#[ignore") { + continue; + } + let own = line + .strip_prefix("#[ignore = \"R5a-") + .and_then(|rest| rest.strip_suffix(" build\"]")) + .and_then(|number| number.parse::().ok()) + .unwrap_or_else(|| panic!("line {}: an ignore that names no slice", at + 1)); + let mut doc = at; + while doc > 0 && { + let above = lines[doc - 1].trim_start(); + above.starts_with("///") || above.starts_with("#[") + } { + doc -= 1; + } + let named: Vec = lines[doc..at].iter().flat_map(|line| slice_of(line)).collect(); + assert!(named.contains(&own), "line {}: the doc does not name R5a-{own}", at + 1); + assert!( + named.iter().all(|&slice| slice <= own), + "line {}: a test of R5a-{own} names a later slice", + at + 1 + ); + } +} diff --git a/compiler-rust/src/tc/walk/typetexp.rs b/compiler-rust/src/tc/walk/typetexp.rs index 7d8561adbc..e4a7af4679 100644 --- a/compiler-rust/src/tc/walk/typetexp.rs +++ b/compiler-rust/src/tc/walk/typetexp.rs @@ -76,8 +76,20 @@ pub struct TypeVars { pub declared_heads: Vec, /// `type_variables`, in the order declared. (R5a-2) pub declared: Vec, - /// `univars`, innermost last. (R5a-2) + /// `univars`, innermost last. A row's `loc` is not a location: it + /// is the entry of `univar_heads` the row replaced, put back when + /// its binder is left. (R5a-2) pub univars: Vec, + /// By [`Name`]: the row of `univars` a variable of that name finds + /// (`List.assoc name !univars`, compiler/ml/typetexp.ml:308: the + /// innermost binder, and in one binder the first of two variables + /// of one name), or [`NONE`]; a name beyond the end has none. Every + /// entry is [`NONE`] while `univars` is empty. (R5a-2) + pub univar_heads: Vec, + /// `global_level` (compiler/ml/ctype.ml:120, 157): the level of the + /// variables [`Annot::globalize`] makes. Written by + /// [`TypeVars::reset`]. (R5a-2) + pub global_level: u32, } impl TypeVars { @@ -109,8 +121,15 @@ impl TypeVars { } /// `reset_type_variables` (compiler/ml/typetexp.ml:213-216) and the - /// used variables with it. O(variables of the item). (R5a-2) - pub fn reset(&mut self) { + /// used and universal variables with it: the head of every declared + /// variable is taken back row by row (1 step each; + /// `declared_heads` is never cleared or filled whole), then + /// [`TypeVars::forget_used`], then the heads of the universal + /// variables; `global_level` becomes `level + 1` + /// (`reset_global_level`, compiler/ml/ctype.ml:157), `level` being + /// the graph's current level. O(variables of the item). No + /// allocation. (R5a-2) + pub fn reset(&mut self, level: u32) { todo!("R5a-2") } } @@ -276,47 +295,124 @@ impl Annot<'_> { /// The parameters of a constructor against its arguments, for a type /// whose row has no `expand::PLAIN_PARAMS` (a parameter that is not /// a variable, or two parameters that are one variable): - /// `instance_list decl.type_params` (ONE copy of all the parameters, - /// compiler/ml/ctype.ml:891-894, so parameters that are one node are - /// one instance), then `unify_param` an argument, in order - /// (compiler/ml/typetexp.ml:373-385: `unify_var` when the type has - /// no manifest or a generic one, else `unify`), then - /// `enforce_constraints` on the node (387-389; ctype.ml:1333-1342). + /// `instance_list decl.type_params` (ONE copy session of all the + /// parameters, compiler/ml/ctype.ml:891-894, so parameters that are + /// one node are one instance), then `Checker::unify_var` of each + /// instance with its argument, in order + /// (compiler/ml/typetexp.ml:373-385; the `unify` of 377-379 is for a + /// manifest that is not generic, which only a stub of a recursive + /// 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. + /// /// The declared parameters are the `arity` nodes of /// [`AnnotState::params`] from `AnnotState::params_of[type_index]` - /// on, generic. `args` is where the translated arguments start in - /// [`AnnotState::values`], `node` the constructor node. A clash is + /// on, generic; a type index without an entry is + /// `Declined::NotBuilt`. `args` is where the translated arguments + /// start in [`AnnotState::values`], `node` the constructor node, + /// which the caller has made (nothing can tell that it is made + /// before the unifications: CHECKER_REWRITE 10.2, decision 12). The + /// instances are pushed on [`AnnotState::values`] above the + /// arguments and taken off again on both ways out. A clash is /// `Stop::Error` (`Type_mismatch`, at the ARGUMENT's location for - /// `unify_param`). O(parameters) plus the copy and the unifications. + /// `unify_param`). + /// + /// Cost: two copies of the declared parameters (1 step a generic + /// node copied), 1 step a parameter in each of the two loops, and + /// 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") } /// `globalize_used_variables env fixed` (compiler/ml/typetexp.ml: - /// 705-734), both halves: the used variables in the increasing - /// order of their names' bytes (`Tbl.iter`; CHECKER_REWRITE 10.2, - /// decision 8); a variable whose unification with its new global - /// variable fails is skipped without an error (712-717). - /// O(v log v) for the v variables the item used. (R5a-2) + /// 705-734), both halves, one after the other. + /// + /// First half, over the used variables in the increasing order of + /// their names' bytes (`Tbl.iter`; CHECKER_REWRITE 10.2, decision 8; + /// `TypeVars::used` is sorted in place, and not at all when it has + /// one row or none): a new variable at `TypeVars::global_level` is + /// unified with the used variable's node inside ONE speculation + /// (`Graph::speculate`); when that fails the speculation is + /// restored (`Checker::restore`) and the answer is + /// `Declined::PolyType`: OCaml skips the variable silently + /// (712-717), which leaves a universal variable outside its binder + /// (CHECKER_REWRITE 10.12, decision 16). Then: the name is a + /// declared variable ([`Annot::declared`]): nothing more here; else + /// under `fixed`, when the used variable's node is still a + /// variable, `Stop::Error` (`Unbound_type_variable`, 721-722); else + /// a second new variable at the global level is entered with + /// [`Annot::add_declared`]. + /// + /// Second half (727-733), over the same rows from the LAST to the + /// first (`r` is a list consed in the first half's order): + /// `Checker::unify` of the used variable's node (one node with the + /// first new variable by now) with the declared variable of its + /// name; a clash is `Stop::Error` (`Type_mismatch`). Then + /// [`TypeVars::forget_used`]. + /// + /// Cost: O(v log v) comparisons of names for the v variables the + /// item used, each O(the shorter name); 1 step a variable in each + /// half, two nodes a variable at most, and the unifications. No + /// allocation: the second half reads the rows the first sorted. + /// (R5a-2) pub fn globalize(&mut self, fixed: bool) -> Result<(), Stop> { todo!("R5a-2") } /// `transl_simple_type env fixed styp` (compiler/ml/typetexp.ml: - /// 736-742), `make_fixed_univars` (741) included. O(1) plus + /// 736-742): the universal variables and the used variables are + /// emptied, the annotation translated ([`Policy::Fixed`] or + /// [`Policy::Extensible`]), then [`Annot::globalize`]. + /// `make_fixed_univars` (741) writes only nodes of polymorphic + /// variants (677-702), and an annotation that has one declines: + /// 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") } /// `transl_type_scheme env styp` (compiler/ml/typetexp.ml:751-756): - /// the variables reset, the annotation translated one level up and - /// generalized. O(1) plus [`Annot::transl_simple_type`] and + /// [`TypeVars::reset`] at the current level, `begin_def`, + /// [`Annot::transl_simple_type`] without the fixed policy, + /// `end_def`, `Checker::generalize`. The level is given back on + /// `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") } + + /// `List.assoc name !(univars ())` (compiler/ml/typetexp.ml:308, + /// 398): the node of the universal variable `name` finds, or + /// `Ty(NONE)`. O(1): one test of `TypeVars::univars` for empty (all + /// an annotation outside a binder pays), then one bounds test and + /// two loads. (R5a-2) + #[inline] + pub fn univar(&self, name: Name) -> Ty { + todo!("R5a-2") + } + + /// `Tbl.find name !(type_variables ())` (compiler/ml/typetexp.ml: + /// 719): the node of a declared variable (a parameter of the + /// declaration, a variable an earlier annotation of the item + /// globalized), or `Ty(NONE)`. O(1): one bounds test and two loads. + /// (R5a-2) + #[inline] + pub fn declared(&self, name: Name) -> Ty { + todo!("R5a-2") + } + + /// `type_variables () := Tbl.add name v` (compiler/ml/typetexp.ml: + /// 254, 725). Amortized O(1): one row of `TypeVars::declared` and + /// one head; `declared_heads` grows to the name when it is beyond + /// the end. The name must have no row (`transl_type_param` raises + /// `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") + } } #[cfg(test)] From cc6758a8964cb99d0d984ffde2b5fb9384b79024 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 14:25:31 +0000 Subject: [PATCH 2/4] Checker rewrite R5a-2: the design of the variable half and its build prompt CHECKER_REWRITE.md 10.12: decisions 13 to 21 (the cut of R5a-2 in two, the alias arm beside typetexp.ml 394-428, who decides a self-alias, the decline in place of the silent skip of globalize, globalize as two loops, universal variables and the polymorphic arm beside 545-571, unify_params and enforce_constraints, what an error leaves), the skeleton changes with their reasons, measured costs, what R5a-1's tests pin that this slice removes, the second half on paper, and the table of programs with what OCaml and today's checker answer. 10.10 gains the prompt of R5a-2a; 10.7 its two rows; item 4 of 10.11 its State line. r5a2_tests.rs: one more ignored test, the global level of a globalized variable and the used variables emptied first. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-70623c69-2944-7bf2-a162-c8f0b9ef7aeb Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- .../checker-rewrite-r5a-design-2.internal.md | 1 + compiler-rust/docs/CHECKER_REWRITE.md | 702 +++++++++++++++++- compiler-rust/src/tc/r5a2_tests.rs | 27 + 3 files changed, 726 insertions(+), 4 deletions(-) create mode 100644 changes/checker-rewrite-r5a-design-2.internal.md diff --git a/changes/checker-rewrite-r5a-design-2.internal.md b/changes/checker-rewrite-r5a-design-2.internal.md new file mode 100644 index 0000000000..0f8fe31ba9 --- /dev/null +++ b/changes/checker-rewrite-r5a-design-2.internal.md @@ -0,0 +1 @@ +- Checker rewrite R5a, second design turn: slice R5a-2 is cut in two; the first half (aliases, universal variables, the variables of an item, shared and constrained parameters) is decided in section 10.12 of `compiler-rust/docs/CHECKER_REWRITE.md`, has its acceptance tests in `compiler-rust/src/tc/r5a2_tests.rs` and its build prompt, and was built once as a prototype that is not committed; the second half (paths and types of other units) is on paper. diff --git a/compiler-rust/docs/CHECKER_REWRITE.md b/compiler-rust/docs/CHECKER_REWRITE.md index 12799733f5..80183eb1f9 100644 --- a/compiler-rust/docs/CHECKER_REWRITE.md +++ b/compiler-rust/docs/CHECKER_REWRITE.md @@ -11861,7 +11861,8 @@ and layouts that R5a-3 to R5a-6 do not compute). | Slice | Builds | Files | Needs | Oracle | Step tests | Lines | |---|---|---|---|---|---|---:| | R5a-1 | The closed core of `transl_type`: `_`, a variable, a tuple, an arrow (labelled and optional parameters included), a constructor named by one component with variable parameters; `TypeVars` (used variables); `StrNames`; `CoreTypeRow`; the predefined rows | `walk/typetexp.rs`, `decl.rs` (`predefine`) | R3, R4 | `ANNOTATIONS` | a tuple of 10,000, an arrow of 10,000 parameters, a constructor nested 10,000 deep, 10,000 uses of one variable, 10,000 distinct variables | 450 (the prototype added 329 lines; the margin is for doc comments) | -| R5a-2 | The rest of annotations: `as`, `'a.` and universal variables, `globalize` (in the order of the names' bytes, with the silent skip of decision 8), `transl_simple_type`, `transl_type_scheme`, paths and types of other units, `unify_params` and `enforce_constraints` | `walk/typetexp.rs` | R5a-1 | `ANNOTATIONS`, decision 5's witness | 10,000 aliases, 10,000 variables globalized | 550 | +| R5a-2a | (R5a-2 was cut in two by its design turn, 10.12, decision 13.) `as`, `'a.` and universal variables, `globalize` (in the order of the names' bytes; a variable whose unification fails declines, decision 16), `transl_simple_type`, `transl_type_scheme`, `unify_params` and `enforce_constraints` | `walk/typetexp.rs` | R5a-1 | `r5a2_tests`: `ALIASES`, `FIELDS`, `PARAMETERS` against today's checker read live, the self-aliases against OCaml | 10,000 aliases, 10,000 uses of one alias, aliases nested 10,000 deep, 10,000 variables globalized, 10,000 universal variables, 10,000 shared parameters | 480 (the prototype changed 336 lines; the margin is for doc comments and the standard) | +| R5a-2b | A path of several components and a type of another unit (10.12.5; on paper, its design turn builds the row of another unit's type first) | `walk/typetexp.rs`, `decl.rs` | R5a-2a | to be written | to be written | not known | | R5a-3 | A group entered, abstract types and abbreviations, parameters (`Repeated_parameter`), stubs, `cyclic_abbrev` (`Recursive_abbrev` at step 5: without it every cyclic seed of the oracle differs), `generalize_decl`, `install`, `mark_group` | `decl.rs` | R5a-2 | generated groups at `Shapes` (10.6) | a group of 10,000; a head cycle of 10,000 | 600 | | R5a-4 | Records: label rows, schemes, `Duplicate_label` inside one record, warning 30 for labels (`Decls::duplicates`), the representation | `decl.rs` | R5a-3 | generated groups at `Shapes` | a record of 10,000 fields | 400 | | R5a-5 | Variants: constructor rows, schemes, `Duplicate_constructor` inside one variant, warning 30 for constructors, tags and the plain layout | `decl.rs` | R5a-3 | generated groups at `Shapes` | a variant of 10,000 constructors | 450 | @@ -11871,7 +11872,8 @@ and layouts that R5a-3 to R5a-6 do not compute). | R5a-9 | Intrinsic externals (decision 11: the type as written, the arity, `Null_arity_external`, the binder and its unused warning; every other external declines); a declaration-only unit published; the `both` check | `decl.rs`, `publish.rs` callers, `driver.rs` | R5a-8 | the corpora under `both` | 10,000 externals | 500 | | R5a-10 | The pre-scan, `check_unit` on a parse tree, `Declined::Expression`, the ratchet's real reasons | `decl.rs`, `mod.rs`, `driver.rs`, `scripts/tc_coverage.py` | R5a-9 | the ratchet | a unit of 10,000 items | 400 | -R5a-4 and R5a-5 can be built side by side after R5a-3 (different +R5a-3 needs R5a-2a only: a declaration's annotations name types of +its own unit until R5a-2b. R5a-4 and R5a-5 can be built side by side after R5a-3 (different functions of one file; each prompt will name the other's). Everything else is one line. R5a deletes nothing: nothing of today's checker is replaced before R5c. @@ -12105,6 +12107,270 @@ answers HTTP 401: commit locally, end the turn and say exactly what is local and where; a new turn with a new token begins with the push. ``` +#### R5a-2a + +R5a-2 was cut in two by its design turn (10.12, decision 13); this is +the prompt of the first half. R5a-2b has no prompt yet. + +**What ran against a prototype.** The prototype of R5a-2a is a comment +of the pull request "Checker rewrite R5a design turn 2: R5a-2 built +once" that starts `// R5A-PROTOTYPE R5a-2`: one diff against that +pull request's first commit WITH the second prototype of R5a-1 applied +before it (the two were fetched back and applied in that order with +`git apply --check`). With both applied, `cargo test --lib tc::r5a -- +--include-ignored` read 47 passed, 2 failed in the turn's first run and +48 passed, 2 failed after one test was added +(`globalized_variables_are_at_the_global_level`): all 28 tests of +`r5a2_tests` pass, and the 2 failures are the tests of R5a-1 that +10.12.4 names. Every ignored test of `r5a2_tests.rs` ran against it. + +Changed before they passed: the prototype's polymorphic arm lowered +the finished type to the binder's own level (the test +`a_polymorphic_type_binds_the_variables_that_occur` failed: left 2, +right 1) and was corrected; five expectations written on paper were +wrong and were replaced by what today's checker shows (a record field +without a binder is not wrapped in a polymorphic type; `sh` +has its two `int` nodes linked; `type t<'a> = {x: int as 'a}` is +accepted); the per-element bounds of the six step tests were set to +what the prototype counted. + +**What of the prototype the slice may not copy.** It may be read. (1) +The marker comments. (2) Its bodies lean on the second prototype of +R5a-1, which R5a-1's builder was free to write otherwise; each place +is listed in the prompt. Everything else of it is within the prompt. + +```text +Task R5a-2a: the variables of type annotations in the new checker. + +Precondition: trunk holds R5a-1's build (no todo!("R5a-1") in +src/tc/walk/typetexp.rs or src/tc/decl.rs) and the pull request +"Checker rewrite R5a design turn 2: R5a-2 built once" (the file +src/tc/r5a2_tests.rs exists). If either is missing, STOP and say so. + +Read first: AGENTS.md; CHECKER_REWRITE.md 6.0 and section 10 (10.1, +10.2 decisions 1, 4, 5, 8, 9, 12; 10.5; 10.8; 10.10; 10.11 item 4; +10.12 whole); compiler/ml/typetexp.ml lines 205-231 (the variable +tables, validate_name), 281-320 (transl_type through the variable +arm), 358-428 (the constructor arm and the alias arm), 545-571 (the +polymorphic arm), 677-756 (make_fixed_univars, +globalize_used_variables, transl_simple_type, +transl_simple_type_delayed, transl_type_scheme); compiler/ml/ctype.ml +120-162 (the levels), 509-520 (generalize), 879-894 (instance, +instance_list), 1333-1342 (enforce_constraints), 1723-1776 +(deep_occur), 2216-2247 (unify1_var, the first arms of unify), +2748-2767 (unify_var); src/tc/walk/typetexp.rs and +src/tc/r5a2_tests.rs whole; of the kernel: Checker::unify_var, +Checker::unify, Checker::restore, Checker::fresh_marks (unify.rs), +Graph::speculate, Graph::keep, Graph::write (graph.rs), +Graph::begin_def, end_def, children (level.rs), Checker::generalize, +Checker::copy, Checker::lower, Checker::link_memorized (expand.rs), +Graph::copy_begin, copy_ref, copy_drain (template.rs), Extras::univar +and ExtraDescriptor (rows.rs, segment.rs). You may read the prototype +(the pull request comment that starts "// R5A-PROTOTYPE R5a-2"); you +WRITE your bodies and do not apply it: it stands on the prototype of +R5a-1, not on R5a-1's build. + +Your functions, and only these, all in src/tc/walk/typetexp.rs: +TypeVars::reset, Annot::unify_params, Annot::globalize, +Annot::transl_simple_type, Annot::transl_type_scheme, Annot::univar, +Annot::declared, Annot::add_declared (the eight todo!("R5a-2")), and, +inside what R5a-1 built: the alias arm and the polymorphic arm of +Annot::transl_type (entering, the one child, leaving), the lookup of +the universal variables in its variable arm, its constructor arm's +road for a type without PLAIN_PARAMS, its way out on Err, its doc +comment, and private helpers of your own. You change no other +signature, no stated cost of a function you do not own, no kernel +body, nothing of src/tc/decl.rs, and no test except the three edits of +"Tests of R5a-1" below. If a signature, a cost or a test cannot be +met, STOP and report a reproduction. + +Where the prototype leans on the prototype of R5a-1; read R5a-1's +BUILT code at each and write yours to it: +- its helper names and its split into a driver loop, a function that + enters a node, one that gives a frame's next child and one that + leaves a frame; +- a frame's results are the slots of AnnotState::values from + Frame::base on, and the driver cuts the stack back to base and + pushes the answer when the frame is left. The alias arm pushes its + variable, and for a new alias the alias's Name, ABOVE base when the + node is entered, below the child's result, and tells "new" from + "found" by the number of slots (3 or 2). If R5a-1's build counts a + frame's children by its slots, keep that count right for the alias + and the polymorphic frame; do not grow Frame (12 bytes, pinned); +- the function that gives the next child answers None after the one + child of an alias and of a polymorphic type; +- the copy of a used variable's node when it is generic, which the + variable arm has inline, is also the alias arm's instance; +- the constructor arm stops with Declined::NotBuilt for a type + without PLAIN_PARAMS before an argument is translated: you take + that stop out; when the frame is left a type with the bit lowers + its arguments as before and a type without it makes its node and + calls unify_params (the prototype loads the TypeInfo row again + there: one load, allowed); +- the way out on Err empties the two stacks: you add the level and + the universal variables (10.12, decision 21); +- the name test of validate_name, which the variable arm has, is + also the test for a binder's variables. + +End state, as facts a search can check (run from compiler-rust/; +"before" was run on the head of the design turn, where R5a-1 is not +built: on your head search 3 and 4 may print lines of R5a-1's build +before you start, and the "after" is what counts): +1. rg -c 'todo!\("R5a-2"\)' src/tc/walk/typetexp.rs + before: 8. After: no output. +2. rg -c '#\[ignore = "R5a-2 build"\]' src/tc/r5a2_tests.rs src/tc/r5a_tests.rs + before: src/tc/r5a2_tests.rs:23 and src/tc/r5a_tests.rs:1. After: + no output. +3. rg -n 'R5A-PROTOTYPE|unreachable!|fn .*-> Vec<|\.clone\(\)|format!|Box::new|HashMap' src/tc/walk/typetexp.rs + before: no output. After: no output. +4. rg -n 'Declined::AliasType|PLAIN_PARAMS == 0' src/tc/walk/typetexp.rs + before: no output (R5a-1 is not built there). After: no output: + nothing of the walk answers AliasType, and no test of the bit + declines. +5. rg -n 'Declined::PolyType' src/tc/walk/typetexp.rs + after: the answer for Policy::Univars (10.12, decision 20), the + decline of globalize (decision 16), and doc comments; no arm of a + Ptyp_poly node. +6. rg -n 'fn a_type_without_plain_parameters_is_declined|"int as .a", Declined::AliasType' src/tc/r5a_tests.rs + before: two lines (579 and 97 on the head of the design turn). + After: no output. +7. cargo test --manifest-path compiler-rust/Cargo.toml --lib tc::r5a2_tests + before: 5 passed, 23 ignored. After: 28 passed, 0 ignored. +8. cargo test --manifest-path compiler-rust/Cargo.toml --lib tc:: + Run it on trunk before you start and write the three numbers down. + After: passed is trunk's plus 23, ignored is trunk's minus 24, 0 + failed (23 tests of r5a2_tests.rs and 1 of r5a_tests.rs stop being + ignored and pass; 1 passing test of r5a_tests.rs is deleted). + +Tests of R5a-1 (three edits of src/tc/r5a_tests.rs, the only ones; +10.12.4): delete the test a_type_without_plain_parameters_is_declined +with its doc comment (commit 5); delete the row ("int as 'a", +Declined::AliasType) of DECLINED and make the array's length 5 (commit +2); delete the line #[ignore = "R5a-2 build"] of +arguments_of_shared_parameters_are_unified (commit 5). Of +src/tc/r5a2_tests.rs you delete the 23 ignore lines and nothing else. + +Commits, in this order, each compiling and passing `cargo test --lib +tc::r5a` alone (the ignored tests it names un-ignored, the others +still ignored): +1. TypeVars::reset, Annot::univar, Annot::declared, + Annot::add_declared. No test is un-ignored (each is reached through + a later commit); add nothing. +2. The alias arm, with the lookup of the universal variables in it and + in the variable arm. Un-ignored: aliases_agree_with_todays_checker, + an_alias_bound_to_two_types_is_an_error, + a_self_alias_is_refused_as_in_ocaml, + a_phantom_self_alias_is_a_type_that_names_itself, + an_alias_enters_its_variable_first_at_the_alias_location, + ten_thousand_aliases, ten_thousand_uses_of_one_alias, + aliases_nested_ten_thousand_deep. The row of DECLINED goes. +3. The polymorphic arm and the way out on Err. Un-ignored: + a_polymorphic_type_binds_the_variables_that_occur, + a_universal_variable_hides_a_used_variable_inside_its_binder, + an_error_inside_a_binder_leaves_no_binder, + ten_thousand_universal_variables. +4. Annot::globalize, Annot::transl_simple_type, + Annot::transl_type_scheme. Un-ignored: + polymorphic_fields_agree_with_todays_checker, + used_variables_are_globalized_in_the_order_of_their_names, + globalized_variables_are_at_the_global_level, + the_fixed_policy_refuses_a_variable_that_is_not_declared, + a_name_bound_to_two_types_by_two_annotations_is_an_error, + a_scheme_is_generalized, reset_forgets_the_declared_variables, + ten_thousand_variables_globalized. +5. Annot::unify_params and the constructor arm's road to it. + Un-ignored: parameters_without_plain_params_agree_with_todays_checker, + the_declared_parameters_are_instantiated_not_bound, + ten_thousand_shared_parameters, and + r5a_tests::arguments_of_shared_parameters_are_unified; the test + a_type_without_plain_parameters_is_declined goes. In src/tc/mod.rs + the attribute on `walk` keeps dead_code (transl_type_scheme, + declared and add_declared have no caller before R5a-3 and R5a-9) + and loses unused_variables if R5a-1 left it; change nothing else + there. + +The engineering standard of 6.0 applies. For this slice in particular: +- Name each loop of your bodies in the pull request body with the step + test that runs it 10,000 times: the frames of aliases + (ten_thousand_aliases, aliases_nested_ten_thousand_deep), the + binder's variables when entered, the marking walk of the body and + the loop that binds (ten_thousand_universal_variables), the two + loops of globalize and the loop of TypeVars::reset + (ten_thousand_variables_globalized), the copy session and the two + loops of unify_params (ten_thousand_shared_parameters). A loop you + add that none of these runs gets a step test of your own of the + same form (1,000 against 10,000, large <= 11 * small, small >= + 1,000). +- No recursion. No Vec, String or Box a node; the only growth is of + the pools named in the doc comments. The sort of globalize is in + place (no key vector) and is not run for one row or none. +- The binder's variables that occur are found by ONE walk of the body + that marks (Checker::fresh_marks, Checker::marks, Graph::work, + Graph::children), not by Checker::deep_occur once a variable. +- A universal variable is found by TypeVars::univar_heads; the heads + of a binder are written from its last variable to its first and put + back from the first to the last; Annot::univar tests + univars.is_empty() first and that is all an annotation outside a + binder pays. +- An alias costs one NameTable::intern: the Name is kept in the slot + above the variable, not interned again when the frame is left. +- The proxy of a new alias gets the alias's name without the test of + validate_name; a binder's variable gets its name with it. +- The polymorphic node is made generic and then lowered to the level + AFTER end_def with Checker::lower; no variable is made for 570. +- globalize opens one speculation a variable, keeps it on success, and + on failure restores it with Checker::restore and answers + Err(Stop::Declined(Declined::PolyType)); the second loop runs from + the last row to the first. +- unify_params: one copy session for all the parameters (copy_begin, + a copy_ref each, copy_drain, then the pass Checker::copy runs after + its own session); unify_var in the first loop, a second session and + unify in the second; the instances leave the value stack on both + ways out. +- The doc comment of Annot::transl_type: the sentences that say an + alias, a polymorphic type and a type without PLAIN_PARAMS stop are + replaced by the arms as 10.12 has them (decisions 14, 18, 19, 21), + and its cost paragraph gains the lines of 10.12.3 for an alias and + a binder. +- Your helpers are total and never panic, as R5a-1's are. + +Not yours, of 10.11: items 1, 2, 3, 5 and 7 (the design turns of +R5a-3, R5a-8 and R5a-9); of item 4 the level a group raises and the +kernel's per-unit reset (R5a-3). A path of several components and a +type of another unit keep declining with Declined::TypePath: R5a-2b. +transl_simple_type_delayed, narrow and widen are R5b's. + +Shortcuts that count as failure: applying the prototype; a recursive +walk; Checker::deep_occur once per variable of a binder; a scan of +TypeVars::univars to find a name; interning an alias's text twice; +entering the alias's variable after the aliased type is translated; +taking the unification of the alias out, or naming the proxy before +it; skipping a used variable whose unification fails (OCaml's silent +skip) in place of the decline; leaving a speculation open on any way +out; unifying the declared parameter nodes themselves; one copy +session a parameter; leaving out the second loop of unify_params (no +test fails without it: 10.12, decision 19 says why it stays); a new +variable made only to lower the polymorphic node; a sort that +allocates; growing Frame, UsedVar or CoreTypeRow; a HashMap; changing +a bound, an expected line or a constant of r5a2_tests.rs; calling +into src/types from src/tc. + +Gates, with their real output in the pull request body: cargo build +and cargo test --lib tc:: for compiler-rust (the whole filter once, +its output to a file; it takes twenty minutes or more); cargo clippy +--manifest-path compiler-rust/Cargo.toml --all-targets -- -D warnings; +RUSTDOCFLAGS="-D warnings" cargo doc --no-deps from compiler-rust (a +public doc comment must not link a private item); CI green, with +`Instruction count` unchanged: nothing of a default build calls your +code, and say so plainly. + +One pull request against ocaml-to-rust-rewrite, titled "Checker +rewrite R5a-2a: aliases, universal variables and the variables of an +item". Push after every commit. If git push or gh answers HTTP 401: +commit locally, end the turn and say exactly what is local and where; +a new turn with a new token begins with the push. +``` + ### 10.11 Corrections after the review of the first design turn The review read both turns of pull request 430 (two first passes and @@ -12162,8 +12428,16 @@ decided or owed; each has a `State:` line. `end_def` leaves it raised, and `Graph::clear_instances` does not put it back. A decline while a speculation is open would meet the assertion of `clear_instances`. - `State:` owed to the design turn of R5a-3 (the level) and of R5a-2 - (a speculation of `globalize` closed before a decline can leave). + `State:` owed to the design turn of R5a-3 (the level a group + raises). R5a-2's part is decided in the pull request "Checker + rewrite R5a design turn 2: R5a-2 built once" (10.12, decisions 16, + 17 and 21): the one speculation of `globalize` is restored before + its decline leaves, and the test asserts a speculation depth of 0; + `transl_type` puts the level back on `Err` (its polymorphic arm + raises it) and `transl_type_scheme` gives its `begin_def` back; + `Checker::unexplained_failure`, which a clash outside a speculation + sets, is added to what the kernel's per-unit reset must clear + (still R5a-3's to name). 5. *The oracle.* A decline of the new side cannot be expressed (`Verdict` has two answers); the `shape` line of the canonical text is neither compared nor named as cut; the list of what the generator @@ -12198,3 +12472,423 @@ decided or owed; each has a `State:` line. ignored); the designer's runs of the two prototypes; the breaks the strengthened tests were seen to fail on (the second first pass read each against the second prototype). + +### 10.12 R5a-2 as designed + +The second design turn for R5a. It decides what 10.2 left open for +slice R5a-2, cuts the slice in two, and builds the first half once. + +**What it rests on.** Read in OCaml, every line: compiler/ml/typetexp.ml +63-136 (`narrow_unbound_lid_error`, `find_component`, `find_type` and +the lookups beside it), 205-320 (the variable tables, `validate_name`, +`transl_type_param`, `transl_type` through the variable arm), 321-428 +(arrow, tuple, constructor and alias arms), 545-588 (the polymorphic +arm, the package arm, the extension arm), 677-756 (`make_fixed_univars`, +`globalize_used_variables`, `transl_simple_type`, +`transl_simple_type_delayed`, `transl_type_scheme`); compiler/ml/ctype.ml +120-162 (the global level), 509-520 (`generalize`), 879-894 (`instance`, +`instance_list`), 1333-1342 (`enforce_constraints`), 1384-1408 +(`occur_rec`), 1723-1776 (`deep_occur`), 2216-2247 (`unify1_var` and the +first arms of `unify`), 2726-2733 (the outer `unify`), 2748-2767 +(`unify_var`). NOT read: `occur_univar`, `subst`, `update_level` and +`unify2`/`unify3` in OCaml (their answers were taken from the kernel's +functions, which ran); the object, variant and package arms of +typetexp.ml (431-544, 572-586: they decline); compiler/ml/env.ml; the +port of the alias and polymorphic arms in `src/types/typecore.rs` +(today's checker was RUN on every program below instead: 10.12.6). +Programs: the coordinator put the programs of 10.12.6 marked "OCaml" to +the released OCaml-built compiler; this turn had no OCaml compiler and +ran today's Rust checker on all of them +(`r5a2_tests::old_checker_*`, four tests that run today). + +#### 10.12.1 Decisions + +13. **R5a-2 is cut in two.** R5a-2a: the alias arm, universal variables + and the polymorphic arm, `globalize`, `transl_simple_type`, + `transl_type_scheme`, `unify_params` with `enforce_constraints`. + Built once in this turn: the prototype changes 336 lines (314 + added, 22 removed: `grep -c '^+'` and `grep -c '^-'` of the posted + diff, headers included), its tests are `src/tc/r5a2_tests.rs`, its + prompt is in 10.10. R5a-2b: a path of several components and a + type of another unit. On paper only (10.12.5): it needs a type of + another unit's segment as a row of the unit's own `TypeTable`, + which no function of the kernel makes today, and that was not + built or tried in this turn. Nothing of R5a-2a waits for it: until + R5a-2b a path of more than one component keeps declining + (`Declined::TypePath`), as R5a-1 has it. +14. **The alias arm (typetexp.ml:394-428) is one frame with the + variable below the aliased type's result.** Beside the lines: + + | OCaml | The new checker | + |---|---| + | 398: `List.assoc alias !(univars ())`, NO instance | `Annot::univar(name)`: the universal variable's node itself | + | 400: else `instance env (fst (Tbl.find alias !(used_variables ())))` | `TypeVars::used(name)`; a generic node is copied (`Checker::copy`), any other is itself. No node of the annotation being translated is generic there (below) | + | 409-411: else `let t = newvar ()`, entered in the used variables at `styp.ptyp_loc`, BEFORE `transl_type env policy st` | a variable without a name at the current level, `TypeVars::add_used(name, t, the ALIAS node's location)`, when the alias node is ENTERED | + | 402, 412: the aliased type | the frame's one child | + | 403, 413: `unify_var env t ty.ctyp_type`; `Unify` is `Alias_type_mismatch` at `styp.ptyp_loc` | `Checker::unify_var(t, ty)` when the frame is left; a clash is `Stop::Error` | + | 407: found branch answers `ty` | the aliased type's node | + | 417-426: new branch: `instance env t`, `px = Btype.proxy t`, a `Tvar None` or `Tunivar None` gets `Some alias`, logged; answers `t` | the instance (the node itself); its representative, when it is a variable without a name, is written with the alias's name by `Graph::write` (which logs inside a speculation; none is open); the answer is that node. `Btype.proxy` is the node itself for everything but an object and a variant, which decline. No `validate_name` | + + *Levels.* `newvar` is at the current level, and so is every node + the aliased type makes; `unify_var` lowers the aliased type to the + variable's level (`update_level env t1.level t2`, ctype.ml:2758), + which is the same level unless the name was first used at a lower + one. *What `instance` copies:* nothing. A used variable's node is + generic only after a `generalize` reached it, and the one + `generalize` inside an annotation is the polymorphic arm's, over + its body; the alias arm takes its instance when its own frame is + left, before any enclosing binder is. The copy-if-generic test is + kept (one load) because R5b's expression walk holds used variables + across a generalization. *The name.* The alias's text is a string + of the parse tree (`Ptyp_alias` holds no `StrIdx`), so the arm + pays one `NameTable::intern` (one hash) an alias node; the `Name` + is kept on the value stack between entering and leaving, in a + slot above the variable, for a new alias only: so "new or found" + is the number of slots the frame holds (3 or 2) and `Frame` keeps + its 12 bytes. *The row.* The alias node's `CoreTypeRow::ty` is the + arm's answer. *The canonical text* prints the name as `'n:name` + (`(_ as 'a, 'a)` is `('0:a, '0:a)`). + Programs: 10.12.6, rows A1 to A10 and the clashes. +15. **Who decides a self-alias: the kernel's `unify_var`, unchanged.** + Because the variable is entered first (409-411), `'b` inside + `array<'b> as 'b` IS the alias's variable, and `unify_var t + (array)` takes `Tvar _, Tconstr _ when deep_occur t1 t2 -> + unify` (ctype.ml:2753), whose occurrence test refuses. The + kernel's `Checker::unify_var` (unify.rs) answers every program as + OCaml does: `array<'b> as 'b`, `(int, 'b) as 'b`, `('b => int) as + 'b`, `option<'b> as 'b`, `array> as 'b` and `k<'b> as + 'b` (an abstract `k`) are `Stop::Error`; `id<'b> as 'b` with `type + id<'a> = 'a` is a variable named `b`; `ph<'b> as 'b` with `type + ph<'a> = int` is a `ph` node whose argument is the node itself. + Tests: `a_self_alias_is_refused_as_in_ocaml`, + `a_phantom_self_alias_is_a_type_that_names_itself`; both passed + against the prototype with no change to the kernel. + *The type that names itself is HELD, not declined.* Seen on the + prototype: the test's canonical text ends on it (`&1(ph<@1>)`), + `Checker::generalize` ends (it stops at a generic node), and + `Checker::copy` gives one new node that names itself (the + forwarding row is written before the children are copied). NOT + tried: `Graph::capture` of such a type into a template and the + canonical text of a published segment; R5a-9, which publishes, + declines a scheme that names itself unless its design turn shows + both. + TODAY'S CHECKER DIFFERS from OCaml on every refused self-alias (it + accepts them) and on `id<'b> as 'b` (it prints `id<'a> => int`): + a branch of its own in its alias arm, being corrected by another + change. The tests follow OCaml and no test pins today's checker on + a self-alias. +16. **A used variable whose globalization fails declines the unit** + (`Declined::PolyType`), where OCaml skips it silently + (typetexp.ml:711-717). The unification that fails is `unify env v + ty` of a new variable with the used variable's node: `Tvar _, _ -> + unify1_var` (ctype.ml:2244), which raises `Unify` from `occur` + (cannot: `v` is new), from `occur_univar env t2` (the node holds a + universal variable that is not bound inside it) or from + `update_level` (a type whose scope is above the global level: + none exists in R5a). The `with _` of 715 would also catch an + exception that is not `Unify`; by the lines read none is raised + there. So in R5a the skip is exactly "the used variable is, or + holds, a universal variable": `'a. ('a as 'b) => 'b`. OCaml + accepts that and can then leave the universal variable outside its + binder (`{"m": 'a. ('a as 'c) => int, "n": 'c}` prints `{"m": 'a. + 'a => int, "n": 'a}`: the coordinator's program; today's checker + agrees, `OBJECT_PROGRAMS`). The new checker does not build that + type: a universal variable outside its binder is a node no + function of the kernel was designed for (`occur_univar`, + `enter_poly` and the template capture all assume the binder), and + the form is not written in the corpora (not counted: said, not + measured). Declining costs nothing on any other annotation: the + test is the `Err` of a unification the arm runs anyway. The + decline is taken with the speculation closed (decision 17). + `r5a2_tests::polymorphic_fields_agree_with_todays_checker` asserts + the decline for the one row of `FIELDS` that reaches it and that + `Graph::speculation_depth` is 0. +17. **`globalize` is two loops over the used rows, no list between + them.** Decision 8 stands (the order of the names' bytes, by a + sort in place of `TypeVars::used`, skipped for one row or none). + - *The tables.* `type_variables` is `TypeVars::declared` with + `declared_heads` by `Name` (owner: the item; emptied by + `TypeVars::reset`, which is `reset_type_variables`, called by + `transl_type_scheme` here and by R5a-3 per declaration, + typedecl.ml:316, 420). `used_variables` is `TypeVars::used` + (emptied by `transl_simple_type` at entry, 738, and by + `globalize` at its end, 727). The global level is + `TypeVars::global_level`, `level + 1` at the reset + (`reset_global_level`, ctype.ml:157). `narrow` and `widen` + (typetexp.ml:218-222) are R5b's: they save and restore + `global_level` and `declared`, and nothing of R5a calls them. + - *First loop* (709-725), a row: a new variable `v` at the global + level; `Graph::speculate`; `Checker::unify(v, ty)`; on `Err` + `Checker::restore` and the decline of decision 16; on `Ok` + `Graph::keep`. The speculation is OCaml's snapshot; it is also + what keeps `Checker::unexplained_failure` clear (a failed + unification outside a speculation sets it, unify.rs) and what + 10.11 item 4 asks: no speculation is open when the decline + leaves. Then the name is looked up in `declared`: found, nothing + more; not found under `fixed` with the node still a variable, + `Stop::Error` (`Unbound_type_variable`, 721-722, tested AFTER + the unification as in OCaml: a name an alias bound to a type is + no error); else a second new variable at the global level is + entered in `declared`. + - *Second loop* (728-733), the rows from the last to the first + (`r` is consed in the first loop's order and iterated from its + head): `Checker::unify(ty, the declared variable of the name)`; + `Err` is `Stop::Error` (`Type_mismatch`). OCaml unifies `v`, not + `ty`; after the first loop they are one node, and `unify` starts + from the representatives, so the pair `(loc, v, v2)` need not be + kept: `ty` is in the row and `v2` is one load by the name. The + ORDER is kept as OCaml's because it can show: two used names + that are one node (`'a as 'b`) unified with two declared + parameters of different names leave one variable whose name + depends on which pair is unified first. + - *`transl_simple_type_delayed`* (744-749) runs the first loop and + returns the second as a closure; its callers are the expression + walk (typecore.ml:1423, 1863, 3571). R5a-2 builds NOTHING of + it. R5b's design turn splits `globalize` at the line between + the loops and decides where the rows wait: an annotation + translated between the two halves empties `used`, so the delayed + half needs its own rows there. + - *`make_fixed_univars`* (677-703) writes only variant nodes whose + row ends in a universal variable; an annotation with a variant + declines, so R5a calls nothing for it. R6b adds it. +18. **Universal variables live in `TypeVars::univars`, found through + `TypeVars::univar_heads`.** One `UsedVar` (12 bytes) per variable + of a binder that is open, innermost last; its `loc` field holds + the head it replaced (a universal variable has no location that + anything reads). `List.assoc name !univars` (308, 398) is the + innermost binder's first variable of that name: the heads of a + binder are written from its LAST variable to its first, and put + back from the first to the last when the binder is left. The list + is empty outside a binder, and `Annot::univar` tests that first: + an annotation without a binder pays that one branch at a variable + and at an alias, nothing else. A scan of the list would cost the + open variables at every use. + The polymorphic arm (545-571), beside the lines: + + | OCaml | The new checker | + |---|---| + | 547-548: `begin_def ()`; a `newvar ~name ()` a variable (named through `validate_name`) | `Graph::begin_def`; a variable a name at the new level, a row of `univars` each; then the heads | + | 550-553: the body with the list extended; the list put back | the frame's one child; the heads put back, the rows kept until the binder is closed | + | 554-555: `end_def ()`; `generalize ty` | `Graph::end_def`; `Checker::generalize(body)`: it stops at a node at or below the current level and at a generic node, which is OCaml's test (ctype.ml:511) | + | 556-567: per variable of the list, in order: `v = Btype.proxy ty1`; `if deep_occur v ty`: a generic `Tvar` becomes `Tunivar name` and joins the list, anything else is `Cannot_quantify` at `styp.ptyp_loc`; a variable that does not occur is dropped | ONE walk of the body that marks every node it reaches (`Checker::marks`, a new generation; `Graph::work` as the stack), then per variable one load of its representative's mark. A marked generic variable is rewritten in place to a universal variable (`TUPLE \| EXTENDED`, a row of `Extras::univar` with its name, level generic) and its handle pushed after the body's; marked and anything else is `Stop::Error`; not marked is skipped | + | 569: `Btype.newgenty (Tpoly (ty, List.rev ty_list))`: the list in the binder's order | one extended node, descriptor `Poly`, generic: slot 0 the body, then the bound variables in the binder's order | + | 570: `unify_var env (newvar ()) ty'` | `Checker::lower(poly, the current level)`: decision 5's argument (a new variable that nothing holds is an occurrence test that cannot find it, `update_level` and a link nobody reads) | + + *Why 570 is there.* `ty'` and its body are generic after 555 and + 569. The annotation around it is not: a node of it that held a + generic child would have that child COPIED by the next `instance` + that reaches it and skipped by the enclosing `generalize`. The + unification with a new variable is `update_level env + !current_level ty'`: the whole polymorphic type comes down to the + level of the annotation around it, the universal variables with + it. Seen: `a_polymorphic_type_binds_the_variables_that_occur` + (node, body and bound variable at level 1; the prototype first + lowered to the binder's own level and failed there). + *`deep_occur` and its cost.* OCaml's is a walk without marks of at + most 256 nodes, then, when that did not decide, a walk that MARKS + every node (`ty.level <- pivot_level - ty.level`, ctype.ml:1758- + 1772: a mark that stays for the walk, taken off by `unmark_type`; + not a path), once per variable of the list: variables × nodes of + the body at worst. The one walk here marks the same set (every + node reachable from the body, rows and objects included: `Graph:: + children` takes every slot of an extended node) and answers every + variable from it: nodes of the body + variables. Nothing is + bounded by number. Who else is on the two structures: `marks` and + `work` are scratch of kernel walks that have returned + (`generalize` before, `lower` after); the translation's own two + stacks are `AnnotState`'s; no copy session is open across a step + of the translation (`instance_list` opens and drains its own). + *`Cannot_quantify`*: the variable is bound to a type (`'a. (int + as 'a) => int`: OCaml, "it is not a variable"), is one node with + an earlier variable of the list that is already universal (`'a + 'b. ('a as 'b) => int`), or is not generic because it was unified + with a node of a lower level. + *What reaches the arm.* A polymorphic type stands in an object + field (declined in R5a) and a record field (R5a-4). `external v: + 'a. 'a => 'a = "v"` is refused by today's checker (observed) and + a binder inside a binder is refused too (`type r = {m: 'a. ('b. + 'b => 'a) => 'a}`, observed). So the tests reach the arm through + the parse tree of a record field: `type r = {m: }` is + parsed and the field's node is translated + (`r5a2_tests::parse_field`); the expected line is the label line + of today's checker for that declaration. A binder inside a binder + is reached by NO test: said in the pull request. +19. **`unify_params` always calls `unify_var`, and + `enforce_constraints` is kept as written.** `unify_param` + (typetexp.ml:374-379) is `unify` only for a manifest that is not + generic. Only a stub of a recursive group has one (decision 6), + and a stub's parameters are distinct `newgenvar ()`, so its row + has `PLAIN_PARAMS` (10.11 item 2) and never reaches + `unify_params`. Then 387-389: `enforce_constraints` is `subst` of + the declared parameters against the arguments with a new body + (ctype.ml:1333-1342), which is a SECOND instance of the + parameters unified with the arguments. After the first loop + succeeded the second cannot fail, by this argument: the arguments + are by then instances of the parameters' pattern, and a fresh + instance of a pattern unifies with any instance of it. That + argument was NOT put to OCaml as a program (a program would have + to show `Type_mismatch` at the whole constructor's location, 389, + and none was found), so the slice builds the second loop as OCaml + has it: two copy sessions a constructor of a type without + `PLAIN_PARAMS`, nothing for any other type. No test fails when the + second loop is dropped (the table of wrong bodies says so); open + question 2. + The copy is ONE session over all the parameters (`instance_list`, + ctype.ml:891-894): `Graph::copy_begin`, a `copy_ref` a parameter, + `copy_drain`, then the pass `Checker::copy` runs after its own + session (`link_memorized` when a memo is live or the graph has a + descriptor row). The kernel has no function for a session of + several roots outside `rows.rs`; the slice writes it as a private + helper from those parts and changes no kernel body. + Programs: decision 5's six, and 10.12.6 rows N1 to N8. +20. **`Policy::Univars` has no caller.** `rg -n 'Univars' compiler/ml` + prints the type (typetexp.ml:278) and four tests of the policy + (298, 313, 540, 658); nothing passes it. `transl_type` keeps + answering `Declined::PolyType` for it, as R5a-1 built it; a + later slice deletes the variant when it deletes the last test of + it. +21. **What an error leaves.** `transl_type` on `Err` empties its two + stacks (R5a-1) and, from R5a-2 on, puts the graph's level back to + what it was at entry (the polymorphic arm raised it) and empties + the universal variables with their heads. `transl_type_scheme` + gives its own `begin_def` back on `Err`. `globalize` leaves no + speculation open. What stays is what decision 1 lists (nodes, + rows, names) and, for a clash that is `Stop::Error` (an alias, a + parameter, the second loop of `globalize`), + `Checker::unexplained_failure`, set by a unification that failed + outside a speculation: it belongs to "the memos and scratch + tables of `Checker`" row of decision 1's table, emptied by the + kernel's per-unit reset that R5a-3's design turn names. + Tests: `an_error_inside_a_binder_leaves_no_binder`, + `a_scheme_is_generalized` (its last assertion). + +#### 10.12.2 Skeleton changes, each with its reason + +| Change | Reason | +|---|---| +| `TypeVars::reset(&mut self)` is `reset(&mut self, level: u32)` | `reset_type_variables` sets the global level from the current level (`reset_global_level`, ctype.ml:157), and `TypeVars` holds no graph | +| new field `TypeVars::global_level` | `new_global_var` (ctype.ml:213); the first skeleton had nowhere to keep it | +| new field `TypeVars::univar_heads`; the doc of `univars` says what a row's `loc` holds | decision 18: a lookup by index, not a scan | +| new functions `Annot::univar`, `Annot::declared`, `Annot::add_declared`, bodies `todo!("R5a-2")`, placed after `transl_type_scheme` | the lookups `globalize` and the two arms need; `declared` and `add_declared` are also what R5a-3's `make_params` calls (`transl_type_param`, typetexp.ml:250-254) | +| doc of `unify_params` | decision 19: always `unify_var`; the second copy session of `enforce_constraints`; who makes the node; the instances on the value stack; the stated cost | +| doc of `globalize` | decisions 16 and 17: the decline, the two loops, no pending list; the stated cost says what a comparison of the sort costs | +| doc of `transl_simple_type`, of `transl_type_scheme` | `make_fixed_univars` named as nothing before R6b; the level on `Err` | + +Not changed, though R5a-2a changes what they do: the doc comment of +`Annot::transl_type` and its body's helpers are R5a-1's lines while +R5a-1 is being built; the prompt of R5a-2a says which sentences of it +the builder rewrites. + +#### 10.12.3 Cost + +| Operation | Steps | An annotation without it pays | +|---|---|---| +| an alias node | 1 (the node entered), one `NameTable::intern`, one `Checker::unify_var` (a new variable against a node without a child: no walk); measured 7 an element for `int as 'v` in a tuple, 4 a level for aliases nested around one type | nothing: the arm is not entered | +| a use of an alias's name | 1 and one link followed (measured 2) | nothing | +| a variable or an alias inside or outside a binder | the test `univars.is_empty()` | that one branch | +| a binder of u variables over a body of n nodes | 1 a variable entered, n for `generalize`, n for the one marking walk, 1 a variable to bind, n for the last lowering; measured 7 a variable for `'v0 .. . ('v0, ..)` | nothing | +| `globalize` of v used variables | v log v comparisons of names for v > 1 (no step: a comparison is not a node), 1 a variable in each loop, two unifications of variables; measured 6 a variable with the translation | 2 loops of 0 or 1 row; no sort | +| `unify_params` of a parameters | 2 copy sessions of the parameters, 1 a parameter in each loop, the unifications; measured 14 a parameter with the 4 of its argument `int` | nothing: one bit of the `TypeInfo` row decides (decision 5) | +| `TypeVars::reset` | 1 a declared, used or universal variable of the item | 0 | + +"Measured" is the step count of the test of that name in +`r5a2_tests.rs` on the prototype at 10,000 elements, divided by 10,000. +No hash map; the one new hash is the alias's `intern`. No allocation a +node: the value stack holds the alias's variable and name and the +instances of `unify_params`. No new struct or enum: `UsedVar` and +`Frame` keep their sizes (`walk::typetexp::tests::sizes`). + +#### 10.12.4 What the tests of R5a-1 pin that R5a-2a removes + +`r5a_tests::a_type_without_plain_parameters_is_declined` asserts +`Declined::NotBuilt` for a type without `PLAIN_PARAMS`, and the row +`("int as 'a", Declined::AliasType)` of `r5a_tests::DECLINED` asserts +the alias decline. Both are R5a-1's end state and both end with +R5a-2a: its builder deletes the first test (its successor is +`r5a2_tests::parameters_without_plain_params_agree_with_todays_checker`) +and that one row. With both prototypes applied these are the only two +failures of `--lib tc::r5a -- --include-ignored` (47 passed, 2 failed). + +#### 10.12.5 R5a-2b on paper: paths and types of other units + +Read for it: typetexp.ml 63-107; `Scopes::lookup_path`, `PathError` +and `ModuleShape` in `src/tc/names.rs`; the signatures (not the body) +of `TypeTable::from_segment`, `Scopes::item`, `Scopes::import_table`. +What is decided, and what is not. + +- *How `find_type` reaches the type.* `Env.lookup_type` of a path of + several components is `Scopes::lookup_path(Namespace::Type, path, + modules, source)`: 1 step a component, by index all the way (the + first component a binder or a unit by `Name`, each later one a + `Scopes::search` in the module's member table). Its answer is a + `Resolved`: a binder (a type of this unit inside a module of this + unit: R5b's, no module exists in R5a), or an import (a row of + `Scopes::imported_members`, which names the segment and the export + item: `Scopes::item`). Then `Scopes::use_modules` for the modules on + the way, `Scopes::use_found` at `lid.loc` for the deprecation + warning (`check_deprecated`, 105-106) and the use mark of an import + (`Scopes::read_item`). +- *The unbound cases* (`narrow_unbound_lid_error`, 63-85, all at + `lid.loc`), from `PathError`: `UnboundModule` at a component is + `Unbound_module` of the path up to it; `Functor` is + `Access_functor_as_structure`; `Unbound` at the last is + `Unbound_type_constructor`; `Cannot_scrape_alias` (an alias to a + module that cannot be loaded) and + `Illegal_reference_to_recursive_module` have no `PathErrorKind`: + R5a-2b's design turn reads how `module_shape` answers them. All are + `Stop::Error`; `Unsupported` is `Declined::TypePath`. +- *When the `DeclRow` slot and the `TypeInfo` row are written.* When + an annotation first names the type (10.1): a dense table by import + row gives the type index or none; the first time, a row is pushed + on `TypeTable::rows` and a `NO_DECL` slot on `Decls::rows`; after + that one load. +- *NOT decided: what the row holds.* `TypeTable::from_segment` makes + a whole table from ONE segment, with that segment's own type + indices and template pools. A unit that names types of two other + units needs their rows in one table: the manifest's template of + another segment instantiated into this unit's graph with its type + indices translated, and the same for a type the manifest names in + turn. Which of these R4 or R3 already answer was not read. This is + the part R5a-2b's design turn builds first; until it does, R5a-2b + cannot be given a line count. +- *What declines in R5a-2b:* a module that is abstract or a functor + application on the way (`Unsupported`), a type of another unit with + a constraint (its parameter nodes would have to be instantiated + from the segment into `AnnotState::params`), and whatever the + design turn finds it cannot translate. + +#### 10.12.6 The programs + +"OCaml" is the released OCaml-built compiler, each file alone, run by +the coordinator; "today" is today's Rust checker, run by the tests +`r5a2_tests::old_checker_*` on the head of this turn. Where only +"today" is given the OCaml answer was not known to this turn and the +program is listed in the pull request for the reviewer. + +| # | Program | OCaml | Today | +|---|---|---|---| +| A1 | `external f: (array<'a> as 'b, 'b) => 'a = "f"` | `(array<'a>, array<'a>) => 'a` | the same type | +| A2 | `('a, int as 'a, string as 'a) => int` | refused at 1:29-40, "This alias is bound to type string but is used as an instance of type int" | refused | +| A3 | `(array<'b> as 'b) => int` | refused at 1:14-28, "This alias is bound to type array<'a> but is used as an instance of type 'a", "The type variable 'a occurs inside array<'a>" | ACCEPTED: differs | +| A4 | the same through a tuple, an arrow, an option, a record type | refused | ACCEPTED: differs | +| A5 | `type id<'a> = 'a`, `(id<'b> as 'b) => int` | accepted, `'a => int` | accepted, `id<'a> => int`: differs | +| A6 | `type p<'a> = int`, `(p<'b> as 'b) => int` | accepted, `(p<'a> as 'a) => int` | accepted, `p<'a> => int`: differs | +| A7 | `(_ as '\"1a", '\"1a") => int` | the proxy is named `1a` | the same | +| A8 | `(int as 'a, 'a) => 'a`, `('a, int as 'a) => 'a`, `('a as 'b, 'b) => 'a`, `(('a as 'b) as 'c, 'c) => 'b`, `((int, 'a) as 'b, 'b) => 'a`, `(int as 'a, string as 'b, ('a, 'b)) => int`, `(k<_> as 'a, p<'a, 'a>) => int`, `(_ as 'a, 'a) => int` | not known | the lines of `r5a2_tests::ALIASES` | +| A9 | `(int as 'a, string as 'a) => int` | not known | refused | +| A10 | `type k<'a>`, `(k<'b> as 'b) => int` | not known; by ctype.ml:2753 refused | ACCEPTED | +| P1 | `external f: {"m": 'a. ('a as 'b) => 'b} => int = "f"` | accepted, `{"m": 'a. 'a => 'a} => int` | the same | +| P2 | `{"m": 'a. ('a as 'c) => int, "n": 'c} => int` | accepted, `{"m": 'a. 'a => int, "n": 'a} => int` | the same | +| P3 | `{"m": 'a. (int as 'a) => int} => int` | refused at 1:19-40, "The universal type variable 'a cannot be generalized: it is not a variable." | refused | +| P4 | `{"m": 'a 'b. 'a => int} => int` | `'a. 'a => int` | the same | +| P5 | `('a, {"m": 'a. 'a => 'a}) => 'a` | `('b, {"m": 'a. 'a => 'a}) => 'b` | the same | +| P6 | `type t = {m: 'a. ('a as 'b) => 'b}` | accepted | accepted | +| P7 | `type r = {m: }` for the twelve `` of `r5a2_tests::FIELDS` (seven accepted, five refused) | not known beyond P3, P4, P6 as record fields | the lines of `FIELDS` | +| G1 | `type t = {x: ('b, 'a)}` | refused at 1:20, "Unbound type parameter 'a" | refused | +| G2 | `type t = A(('zz, 'b, 'a))` | refused at 1:23, `'a` | refused | +| G3 | `external f: ('a, 'a) => 'b = "f"`, `f(1, 2)`, `f("a", "b")` | both type | both type | +| G4 | `type t<'a> = {x: int as 'a}` | not known | accepted, the parameter prints `int` | +| G5 | `type t<'a> = {x: int as 'a, y: string as 'a}` | not known; by typetexp.ml:733 `Type_mismatch` | refused | +| G6 | `type t<'a> = {x: int as 'a, y: int as 'a}`; `type t = {x: (int as 'c, 'c)}` | not known | accepted | +| N1 | decision 5's six programs | 10.2 | agree | +| N2 | `sh<'x, array<'v>>`, `(sh<'x, 'y>, 'x) => 'y`, `cl>`, `cl<'x> => 'x`, `cl<_>` with `type sh<'a, 'b> = int constraint 'a = 'b` and `type cl<'a> = 'b constraint 'a = list<'b>` | not known | the lines of `r5a2_tests::PARAMETERS` (`(sh<'x, 'y>, 'x) => 'y` is one variable named `y`) | diff --git a/compiler-rust/src/tc/r5a2_tests.rs b/compiler-rust/src/tc/r5a2_tests.rs index 2a4b7fe36f..2ad02b5b78 100644 --- a/compiler-rust/src/tc/r5a2_tests.rs +++ b/compiler-rust/src/tc/r5a2_tests.rs @@ -857,6 +857,33 @@ fn used_variables_are_globalized_in_the_order_of_their_names() { assert_eq!(w.c.g.repr(argument), w.c.g.repr(b)); } +/// R5a-2. Reaches `Annot::globalize`, `Annot::transl_simple_type`, +/// `TypeVars::reset` (R5a-2) and the bodies of R5a-1; no later slice. +/// +/// The global level is not the current one (`new_global_var`, +/// compiler/ml/ctype.ml:213; `reset_global_level`, 157): with the +/// variables reset at level 1 and the annotation `'x` translated two +/// levels up, at level 3, its variable ends at level 2, lowered by the +/// unification with the new global variable (typetexp.ml:709-713). And +/// `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); + w.c.g.begin_def(); + w.c.g.begin_def(); + let (arena, root) = parse("'q"); + translate(&mut w, &arena, root, Policy::Extensible).unwrap(); + w.st.strs.reset(); + let (arena, root) = parse("'x"); + let x = annot(&mut w, &arena).transl_simple_type(root, false).unwrap(); + let x = w.c.g.repr(x); + assert_eq!(w.c.g.nodes[x.0 as usize].level, 2); + assert_eq!(declared_names(&w), ["x"]); +} + /// R5a-2. Reaches `Annot::globalize`, `Annot::transl_simple_type`, /// `Annot::add_declared`, `TypeVars::reset` (R5a-2) and the bodies of /// R5a-1; no later slice. From a618c9b56106e24e99def8612bb43b4fa90bc4bc 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 14:47:58 +0000 Subject: [PATCH 3/4] Checker rewrite R5a-2: the self-aliases observed on today's checker, the breaks seen to fail r5a2_tests.rs: after the merge of trunk today's checker refuses the six self-aliases and prints the two lines the new checker's tests expect for an alias through an identity and a phantom abbreviation; one test that runs today pins that. CHECKER_REWRITE.md: decision 15 and the programs table say so; 10.10 gains the table of 35 changes to the prototype each seen to fail a test, the four no test catches, and what was not run. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-70623c69-2944-7bf2-a162-c8f0b9ef7aeb Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/docs/CHECKER_REWRITE.md | 96 +++++++++++++++++++++------ compiler-rust/src/tc/r5a2_tests.rs | 49 ++++++++++---- 2 files changed, 113 insertions(+), 32 deletions(-) diff --git a/compiler-rust/docs/CHECKER_REWRITE.md b/compiler-rust/docs/CHECKER_REWRITE.md index 80183eb1f9..8b0caa5b2e 100644 --- a/compiler-rust/docs/CHECKER_REWRITE.md +++ b/compiler-rust/docs/CHECKER_REWRITE.md @@ -12117,11 +12117,13 @@ of the pull request "Checker rewrite R5a design turn 2: R5a-2 built once" that starts `// R5A-PROTOTYPE R5a-2`: one diff against that pull request's first commit WITH the second prototype of R5a-1 applied before it (the two were fetched back and applied in that order with -`git apply --check`). With both applied, `cargo test --lib tc::r5a -- ---include-ignored` read 47 passed, 2 failed in the turn's first run and -48 passed, 2 failed after one test was added -(`globalized_variables_are_at_the_global_level`): all 28 tests of -`r5a2_tests` pass, and the 2 failures are the tests of R5a-1 that +`git apply --check`; `walk/typetexp.rs` and `decl.rs` did not change +on the branch after that commit). With both applied, `cargo test --lib +tc::r5a -- --include-ignored` read 47 passed, 2 failed in the turn's +first run; `cargo test --lib tc::r5a2_tests -- --include-ignored` read +29 passed, 0 failed on the turn's head, after one ignored test +(`globalized_variables_are_at_the_global_level`) and one pin of +today's checker were added. The 2 failures are the tests of R5a-1 that 10.12.4 names. Every ignored test of `r5a2_tests.rs` ran against it. Changed before they passed: the prototype's polymorphic arm lowered @@ -12134,6 +12136,53 @@ has its two `int` nodes linked; `type t<'a> = {x: int as 'a}` is accepted); the per-element bounds of the six step tests were set to what the prototype counted. +Seen to fail, each on the prototype with one change (`cargo test --lib +tc::r5a2_tests -- --include-ignored`, the tests that failed): + +| Change to the body | Tests that failed | +|---|---| +| alias: the variable is not entered before the aliased type | `a_self_alias_is_refused_as_in_ocaml`, `a_phantom_self_alias_is_a_type_that_names_itself`, `aliases_agree_with_todays_checker`, `an_alias_enters_its_variable_first_at_the_alias_location` and five more | +| alias: no `unify_var` | `an_alias_bound_to_two_types_is_an_error`, `aliases_agree_with_todays_checker` and six more | +| alias: the proxy is never named | `aliases_agree_with_todays_checker` (`('0, '0)` for `('0:a, '0:a)`), `a_self_alias_is_refused_as_in_ocaml` | +| alias: the proxy's name goes through `validate_name` | `aliases_agree_with_todays_checker` | +| binder: the type is not lowered at the end | `a_polymorphic_type_binds_the_variables_that_occur` (left 100000000, right 1) | +| binder: every variable of the list is bound | the same, `polymorphic_fields_agree_with_todays_checker` | +| binder: `deep_occur` once a variable | `ten_thousand_universal_variables` (the relation of 1,000 to 10,000) | +| binder: the heads are not put back | `ten_thousand_universal_variables` (the heads are read) | +| binder: no `end_def`; no `generalize` | `a_polymorphic_type_binds_the_variables_that_occur`, `a_universal_variable_hides_a_used_variable_inside_its_binder`, `polymorphic_fields_agree_with_todays_checker`, `ten_thousand_universal_variables` | +| binder: a bound name that is no generic variable is dropped silently | `polymorphic_fields_agree_with_todays_checker` (left Ok, right Err(Error)) | +| `univar` never finds | the four binder tests | +| variable arm: the used variables before the universal ones | `a_universal_variable_hides_a_used_variable_inside_its_binder` | +| `globalize`: no sort | `used_variables_are_globalized_in_the_order_of_their_names` (left zz, b, a), `ten_thousand_variables_globalized` | +| `globalize`: the failed unification skipped silently; the speculation left open | `polymorphic_fields_agree_with_todays_checker` (the second: left 1, right 0) | +| `globalize`: no test of the fixed policy; the test also refuses a name bound to a type | `the_fixed_policy_refuses_a_variable_that_is_not_declared` | +| `globalize`: no second loop | `a_name_bound_to_two_types_by_two_annotations_is_an_error`, `used_variables_are_globalized_in_the_order_of_their_names`, `the_fixed_policy_refuses_a_variable_that_is_not_declared` | +| `globalize`: the used variables not forgotten | `used_variables_are_globalized_in_the_order_of_their_names`, `ten_thousand_variables_globalized` | +| `globalize`: the new variables at the current level | `globalized_variables_are_at_the_global_level` (left 3, right 2) | +| `transl_simple_type`: no `globalize`; the used variables not emptied first; always the extensible policy | eight tests; `globalized_variables_are_at_the_global_level` (left q, x); `polymorphic_fields_agree_with_todays_checker` | +| `transl_type_scheme`: no `generalize`; no reset; the level kept on an error | `a_scheme_is_generalized`, each at its own assertion | +| `unify_params`: one copy session a parameter | `parameters_without_plain_params_agree_with_todays_checker` (`sh` accepted) | +| `unify_params`: the declared parameters themselves unified | `the_declared_parameters_are_instantiated_not_bound` | +| constructor arm: a type without `PLAIN_PARAMS` only lowers | `parameters_without_plain_params_agree_with_todays_checker` | +| `reset`: the heads not taken back; the global level is the level given | `reset_forgets_the_declared_variables`, `a_scheme_is_generalized` and, for the level, two more | +| `declared` never finds | seven tests | +| `transl_type` on `Err`: the level not put back; the universal variables not dropped | `an_error_inside_a_binder_leaves_no_binder`, `polymorphic_fields_agree_with_todays_checker` | + +Not caught by any test, and said so: `enforce_constraints` (the second +loop of `unify_params`) left out, which decision 19 argues cannot +show; the instances of `unify_params` left on the value stack (the +driver cuts the stack back when the frame is left); the heads of a +binder written in source order, so that the LAST of two variables of +one name is found (the other does not occur and is dropped: the same +text); an instance of a new alias taken by `Checker::copy` without the +test for generic (the same node). Not run as a break because steps do +not count them: a `univar` that scans the list, an alias interned +twice, a sort that allocates. + +Not run: the five commits of the prompt were not each built and +tested alone; their order was checked by reading, for every test, the +functions it calls. + **What of the prototype the slice may not copy.** It may be read. (1) The marker comments. (2) Its bodies lean on the second prototype of R5a-1, which R5a-1's builder was free to write otherwise; each place @@ -12235,7 +12284,7 @@ before you start, and the "after" is what counts): before: two lines (579 and 97 on the head of the design turn). After: no output. 7. cargo test --manifest-path compiler-rust/Cargo.toml --lib tc::r5a2_tests - before: 5 passed, 23 ignored. After: 28 passed, 0 ignored. + before: 6 passed, 23 ignored. After: 29 passed, 0 ignored. 8. cargo test --manifest-path compiler-rust/Cargo.toml --lib tc:: Run it on trunk before you start and write the three numbers down. After: passed is trunk's plus 23, ignored is trunk's minus 24, 0 @@ -12252,7 +12301,9 @@ src/tc/r5a2_tests.rs you delete the 23 ignore lines and nothing else. Commits, in this order, each compiling and passing `cargo test --lib tc::r5a` alone (the ignored tests it names un-ignored, the others -still ignored): +still ignored). The order was checked by reading what each test calls, +not by building each commit: if a commit cannot pass alone, STOP and +report which test needs which later body. 1. TypeVars::reset, Annot::univar, Annot::declared, Annot::add_declared. No test is un-ignored (each is reached through a later commit); add nothing. @@ -12349,7 +12400,9 @@ it; skipping a used variable whose unification fails (OCaml's silent skip) in place of the decline; leaving a speculation open on any way out; unifying the declared parameter nodes themselves; one copy session a parameter; leaving out the second loop of unify_params (no -test fails without it: 10.12, decision 19 says why it stays); a new +test fails without it: 10.12, decision 19 says why it stays); writing +a binder's heads in source order (no test fails: the first of two +variables of one name must be the one found); a new variable made only to lower the polymorphic node; a sort that allocates; growing Frame, UsedVar or CoreTypeRow; a HashMap; changing a bound, an expected line or a constant of r5a2_tests.rs; calling @@ -12499,7 +12552,7 @@ port of the alias and polymorphic arms in `src/types/typecore.rs` Programs: the coordinator put the programs of 10.12.6 marked "OCaml" to the released OCaml-built compiler; this turn had no OCaml compiler and ran today's Rust checker on all of them -(`r5a2_tests::old_checker_*`, four tests that run today). +(`r5a2_tests::old_checker_*`, five tests that run today). #### 10.12.1 Decisions @@ -12572,16 +12625,19 @@ ran today's Rust checker on all of them canonical text of a published segment; R5a-9, which publishes, declines a scheme that names itself unless its design turn shows both. - TODAY'S CHECKER DIFFERS from OCaml on every refused self-alias (it - accepts them) and on `id<'b> as 'b` (it prints `id<'a> => int`): - a branch of its own in its alias arm, being corrected by another - change. The tests follow OCaml and no test pins today's checker on - a self-alias. + Today's checker differed from OCaml on every one of these when + the turn began (a branch of its own in its alias arm); the pull + request "An alias that names itself below a constructor is + refused, as in OCaml" corrected it, this branch merged it, and + `r5a2_tests::old_checker_self_aliases_are_pinned` now observes + today's checker on all eight: it refuses the six, and its + canonical lines for `id<'b> as 'b` and `ph<'b> as 'b` are the two + the new checker's tests expect, character for character. 16. **A used variable whose globalization fails declines the unit** (`Declined::PolyType`), where OCaml skips it silently (typetexp.ml:711-717). The unification that fails is `unify env v ty` of a new variable with the used variable's node: `Tvar _, _ -> - unify1_var` (ctype.ml:2244), which raises `Unify` from `occur` + unify1_var` (ctype.ml:2242), which raises `Unify` from `occur` (cannot: `v` is new), from `occur_univar env t2` (the node holds a universal variable that is not bound inside it) or from `update_level` (a type whose scope is above the global level: @@ -12869,14 +12925,14 @@ program is listed in the pull request for the reviewer. |---|---|---|---| | A1 | `external f: (array<'a> as 'b, 'b) => 'a = "f"` | `(array<'a>, array<'a>) => 'a` | the same type | | A2 | `('a, int as 'a, string as 'a) => int` | refused at 1:29-40, "This alias is bound to type string but is used as an instance of type int" | refused | -| A3 | `(array<'b> as 'b) => int` | refused at 1:14-28, "This alias is bound to type array<'a> but is used as an instance of type 'a", "The type variable 'a occurs inside array<'a>" | ACCEPTED: differs | -| A4 | the same through a tuple, an arrow, an option, a record type | refused | ACCEPTED: differs | -| A5 | `type id<'a> = 'a`, `(id<'b> as 'b) => int` | accepted, `'a => int` | accepted, `id<'a> => int`: differs | -| A6 | `type p<'a> = int`, `(p<'b> as 'b) => int` | accepted, `(p<'a> as 'a) => int` | accepted, `p<'a> => int`: differs | +| A3 | `(array<'b> as 'b) => int` | refused at 1:14-28, "This alias is bound to type array<'a> but is used as an instance of type 'a", "The type variable 'a occurs inside array<'a>" | refused (accepted before the correction named in decision 15) | +| A4 | the same through a tuple, an arrow, an option, a record type | refused | refused (tuple, arrow, option and a nested array observed) | +| A5 | `type id<'a> = 'a`, `(id<'b> as 'b) => int` | accepted, `'a => int` | accepted, a variable | +| A6 | `type p<'a> = int`, `(p<'b> as 'b) => int` | accepted, `(p<'a> as 'a) => int` | accepted, a `p` node whose argument is itself | | A7 | `(_ as '\"1a", '\"1a") => int` | the proxy is named `1a` | the same | | A8 | `(int as 'a, 'a) => 'a`, `('a, int as 'a) => 'a`, `('a as 'b, 'b) => 'a`, `(('a as 'b) as 'c, 'c) => 'b`, `((int, 'a) as 'b, 'b) => 'a`, `(int as 'a, string as 'b, ('a, 'b)) => int`, `(k<_> as 'a, p<'a, 'a>) => int`, `(_ as 'a, 'a) => int` | not known | the lines of `r5a2_tests::ALIASES` | | A9 | `(int as 'a, string as 'a) => int` | not known | refused | -| A10 | `type k<'a>`, `(k<'b> as 'b) => int` | not known; by ctype.ml:2753 refused | ACCEPTED | +| A10 | `type k<'a>`, `(k<'b> as 'b) => int` | not known; by ctype.ml:2753 refused | refused | | P1 | `external f: {"m": 'a. ('a as 'b) => 'b} => int = "f"` | accepted, `{"m": 'a. 'a => 'a} => int` | the same | | P2 | `{"m": 'a. ('a as 'c) => int, "n": 'c} => int` | accepted, `{"m": 'a. 'a => int, "n": 'a} => int` | the same | | P3 | `{"m": 'a. (int as 'a) => int} => int` | refused at 1:19-40, "The universal type variable 'a cannot be generalized: it is not a variable." | refused | diff --git a/compiler-rust/src/tc/r5a2_tests.rs b/compiler-rust/src/tc/r5a2_tests.rs index 2ad02b5b78..4ab529db64 100644 --- a/compiler-rust/src/tc/r5a2_tests.rs +++ b/compiler-rust/src/tc/r5a2_tests.rs @@ -82,12 +82,13 @@ const ALIAS_CLASHES: [&str; 2] = ["('a, int as 'a, string as 'a) => int", "(int /// the aliased type is translated (409-411), so `'b` inside is the /// variable itself, and `unify_var` (compiler/ml/ctype.ml:2748-2765) /// takes `Tvar _, Tconstr _ when deep_occur t1 t2 -> unify` or `occur`. -/// TODAY'S CHECKER DIFFERS: it accepts each of them (a branch of its own -/// in its alias arm; reported, and being corrected by another change), -/// so no test pins today's checker on them. The first five were put to -/// OCaml by the coordinator; `k<'b> as 'b` (an abstract type) follows -/// from the same lines and is listed in the pull request as a program to -/// run. +/// Today's checker accepted each of them until its alias arm was +/// corrected (the pull request "An alias that names itself below a +/// constructor is refused, as in OCaml"); since then it refuses them +/// too, and `old_checker_self_aliases_are_pinned` keeps that observed. +/// The first five were put to OCaml by the coordinator; `k<'b> as 'b` +/// (an abstract type) follows from the same lines and is listed in the +/// pull request as a program to run. const SELF_ALIASES_OCAML_REFUSES: [&str; 6] = [ "(array<'b> as 'b) => int", "((int, 'b) as 'b) => int", @@ -216,6 +217,31 @@ fn old_checker_aliases_are_pinned() { } } +/// Runs today. Today's checker refuses every program of +/// [`SELF_ALIASES_OCAML_REFUSES`], and through an abbreviation it +/// answers as OCAML does (the coordinator's run: `id<'b> as 'b` prints +/// `'a => int`, `p<'b> as 'b` with a phantom `p` prints `(p<'a> as 'a) +/// => int`). +#[test] +fn old_checker_self_aliases_are_pinned() { + for annotation in SELF_ALIASES_OCAML_REFUSES { + assert_eq!(old_judge(&external(annotation)), Verdict::Rejected, "{annotation}"); + } + assert_eq!( + old_line(&external("(id<'b> as 'b) => int"), "value v: ").as_deref(), + Some(SELF_ALIAS_IDENTITY) + ); + assert_eq!( + old_line(&external("(ph<'b> as 'b) => int"), "value v: ").as_deref(), + Some(SELF_ALIAS_PHANTOM) + ); +} + +/// `(id<'b> as 'b) => int` and `(ph<'b> as 'b) => int` in the canonical +/// text (observed on today's checker). +const SELF_ALIAS_IDENTITY: &str = "&0(('0:b) => &1(int))"; +const SELF_ALIAS_PHANTOM: &str = "&0((&1(ph<@1>)) => &2(int))"; + /// Runs today. Every row of [`FIELDS`] and of [`OBJECT_PROGRAMS`] is /// what today's checker answers. #[test] @@ -572,13 +598,12 @@ fn an_alias_bound_to_two_types_is_an_error() { /// aliased type is translated (typetexp.ml:409-411), so `'b` inside /// `array<'b> as 'b` is that variable and `unify_var` refuses the /// binding: every program of [`SELF_ALIASES_OCAML_REFUSES`] is -/// `Stop::Error`, as OCaml answers and today's checker does not. A body +/// `Stop::Error`, as OCaml and today's checker answer. A body /// that enters the variable after the aliased type accepts them all. /// /// Through an abbreviation `unify_var` goes on (`Tvar _, Tconstr _ when /// deep_occur t1 t2 -> unify`, ctype.ml:2753, and `unify` expands): -/// `id<'b> as 'b` is a variable named `b` (OCaml prints `'a => int`, -/// today's checker `id<'a> => int`). +/// `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() { @@ -590,7 +615,7 @@ fn a_self_alias_is_refused_as_in_ocaml() { let mut w = world(); let (arena, root) = parse("(id<'b> as 'b) => int"); let ty = translate(&mut w, &arena, root, Policy::Extensible).unwrap(); - assert_eq!(value_line(&mut w, ty), "value v: &0(('0:b) => &1(int))"); + assert_eq!(canon(&mut w, ty), SELF_ALIAS_IDENTITY); } /// R5a-2. Reaches the alias arm of `Annot::transl_type` (R5a-2), the @@ -612,12 +637,12 @@ fn a_phantom_self_alias_is_a_type_that_names_itself() { w.c.g.begin_def(); let (arena, root) = parse("(ph<'b> as 'b) => int"); let ty = translate(&mut w, &arena, root, Policy::Extensible).unwrap(); - assert_eq!(value_line(&mut w, ty), "value v: &0((&1(ph<@1>)) => &2(int))"); + assert_eq!(canon(&mut w, ty), SELF_ALIAS_PHANTOM); w.c.g.end_def(); w.c.generalize(ty); let copy = w.c.copy(ty); assert_ne!(copy, ty); - assert_eq!(value_line(&mut w, copy), "value v: &0((&1(ph<@1>)) => &2(int))"); + assert_eq!(canon(&mut w, copy), SELF_ALIAS_PHANTOM); } /// R5a-2. Reaches the alias arm of `Annot::transl_type` (R5a-2) and the From 39a933e958362bb3247f3acce33abdbecc82677d 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 14:51:48 +0000 Subject: [PATCH 4/4] Checker rewrite R5a-2: the prompt of R5a-2a stands on the build of R5a-1 The prototype was rebuilt on trunk's bodies of R5a-1 and posted again; the prompt names the functions of that build its code meets, and its searches give what they print on a head that holds it. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-70623c69-2944-7bf2-a162-c8f0b9ef7aeb Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/docs/CHECKER_REWRITE.md | 101 ++++++++++++++------------ 1 file changed, 56 insertions(+), 45 deletions(-) diff --git a/compiler-rust/docs/CHECKER_REWRITE.md b/compiler-rust/docs/CHECKER_REWRITE.md index 8b0caa5b2e..0c8e88e69d 100644 --- a/compiler-rust/docs/CHECKER_REWRITE.md +++ b/compiler-rust/docs/CHECKER_REWRITE.md @@ -12126,6 +12126,14 @@ first run; `cargo test --lib tc::r5a2_tests -- --include-ignored` read today's checker were added. The 2 failures are the tests of R5a-1 that 10.12.4 names. Every ignored test of `r5a2_tests.rs` ran against it. +A SECOND prototype (`// R5A-PROTOTYPE R5a-2, second`, a later comment +of the same pull request) is the same bodies rebuilt on the BUILT +bodies of R5a-1, after trunk gained them: one diff against the merge +commit of that pull request's branch, applied alone. With it `cargo +test --lib tc::r5a -- --include-ignored` read 49 passed, 2 failed (the +same two). It is the one to read. The breaks of the table below were +run against the first. + Changed before they passed: the prototype's polymorphic arm lowered the finished type to the binder's own level (the test `a_polymorphic_type_binds_the_variables_that_occur` failed: left 2, @@ -12183,10 +12191,11 @@ Not run: the five commits of the prompt were not each built and tested alone; their order was checked by reading, for every test, the functions it calls. -**What of the prototype the slice may not copy.** It may be read. (1) -The marker comments. (2) Its bodies lean on the second prototype of -R5a-1, which R5a-1's builder was free to write otherwise; each place -is listed in the prompt. Everything else of it is within the prompt. +**What of the prototypes the slice may not copy.** They may be read. +(1) The marker comments. (2) The second prototype's `new_var` calls a +new `var_at` and its test of a binder variable's name is written out +again beside the variable arm's: the slice shares one helper for each. +Everything else of the second prototype is within the prompt. ```text Task R5a-2a: the variables of type annotations in the new checker. @@ -12215,9 +12224,10 @@ Graph::begin_def, end_def, children (level.rs), Checker::generalize, Checker::copy, Checker::lower, Checker::link_memorized (expand.rs), Graph::copy_begin, copy_ref, copy_drain (template.rs), Extras::univar and ExtraDescriptor (rows.rs, segment.rs). You may read the prototype -(the pull request comment that starts "// R5A-PROTOTYPE R5a-2"); you -WRITE your bodies and do not apply it: it stands on the prototype of -R5a-1, not on R5a-1's build. +(the pull request comment that starts "// R5A-PROTOTYPE R5a-2, +second": it stands on R5a-1's build; the first one stands on R5a-1's +prototype and is superseded); you WRITE your bodies and do not apply +it. Your functions, and only these, all in src/tc/walk/typetexp.rs: TypeVars::reset, Annot::unify_params, Annot::globalize, @@ -12233,38 +12243,37 @@ body, nothing of src/tc/decl.rs, and no test except the three edits of "Tests of R5a-1" below. If a signature, a cost or a test cannot be met, STOP and report a reproduction. -Where the prototype leans on the prototype of R5a-1; read R5a-1's -BUILT code at each and write yours to it: -- its helper names and its split into a driver loop, a function that - enters a node, one that gives a frame's next child and one that - leaves a frame; +What your code meets in R5a-1's build (the second prototype shows +each place): +- the driver loop is Annot::walk, with enter, child and leave; the + variable maker is new_var; arrow_params is shared; - a frame's results are the slots of AnnotState::values from - Frame::base on, and the driver cuts the stack back to base and - pushes the answer when the frame is left. The alias arm pushes its - variable, and for a new alias the alias's Name, ABOVE base when the - node is entered, below the child's result, and tells "new" from - "found" by the number of slots (3 or 2). If R5a-1's build counts a - frame's children by its slots, keep that count right for the alias - and the polymorphic frame; do not grow Frame (12 bytes, pinned); -- the function that gives the next child answers None after the one - child of an alias and of a polymorphic type; + Frame::base on, and walk cuts the stack back to base and pushes the + answer when the frame is left. The alias arm pushes its variable, + and for a new alias the alias's Name, ABOVE base when the node is + entered, below the child's result, and tells "new" from "found" by + the number of slots (3 or 2). Do not grow Frame (12 bytes, pinned); +- child answers None after the one child of an alias and of a + polymorphic type; - the copy of a used variable's node when it is generic, which the - variable arm has inline, is also the alias arm's instance; -- the constructor arm stops with Declined::NotBuilt for a type - without PLAIN_PARAMS before an argument is translated: you take - that stop out; when the frame is left a type with the bit lowers - its arguments as before and a type without it makes its node and - calls unify_params (the prototype loads the TypeInfo row again - there: one load, allowed); -- the way out on Err empties the two stacks: you add the level and - the universal variables (10.12, decision 21); -- the name test of validate_name, which the variable arm has, is - also the test for a binder's variables. + variable arm has inline, is also the alias arm's instance: one + helper for both; +- enter stops with Declined::NotBuilt for a type without PLAIN_PARAMS + before an argument is translated: you take that stop out; in leave + a type with the bit lowers its arguments as before and a type + without it makes its node and calls unify_params (one more load of + the TypeInfo row there: allowed); +- transl_type's way out on Err empties the two stacks: you add the + level and the universal variables (10.12, decision 21); +- the rule of validate_name is inline in the variable arm, behind the + refusal of a leading underscore, as a test for an ASCII letter. A + binder's variable has no such refusal before it (typetexp.ml:548): + its test is `_` or an ASCII letter. One helper for both, with the + whole rule. End state, as facts a search can check (run from compiler-rust/; -"before" was run on the head of the design turn, where R5a-1 is not -built: on your head search 3 and 4 may print lines of R5a-1's build -before you start, and the "after" is what counts): +"before" was run on the head of the design turn, which holds R5a-1's +build): 1. rg -c 'todo!\("R5a-2"\)' src/tc/walk/typetexp.rs before: 8. After: no output. 2. rg -c '#\[ignore = "R5a-2 build"\]' src/tc/r5a2_tests.rs src/tc/r5a_tests.rs @@ -12273,20 +12282,21 @@ before you start, and the "after" is what counts): 3. rg -n 'R5A-PROTOTYPE|unreachable!|fn .*-> Vec<|\.clone\(\)|format!|Box::new|HashMap' src/tc/walk/typetexp.rs before: no output. After: no output. 4. rg -n 'Declined::AliasType|PLAIN_PARAMS == 0' src/tc/walk/typetexp.rs - before: no output (R5a-1 is not built there). After: no output: - nothing of the walk answers AliasType, and no test of the bit - declines. + before: lines 622 and 635. After: no output: nothing of the walk + answers AliasType, and no test of the bit declines. 5. rg -n 'Declined::PolyType' src/tc/walk/typetexp.rs - after: the answer for Policy::Univars (10.12, decision 20), the - decline of globalize (decision 16), and doc comments; no arm of a - Ptyp_poly node. + before: lines 388 (a doc comment), 493 (Policy::Univars) and 637 + (the Ptyp_poly arm). After: the answer for Policy::Univars (10.12, + decision 20), the decline of globalize (decision 16), and doc + comments; no arm of a Ptyp_poly node. 6. rg -n 'fn a_type_without_plain_parameters_is_declined|"int as .a", Declined::AliasType' src/tc/r5a_tests.rs - before: two lines (579 and 97 on the head of the design turn). + before: two lines (571 and 97 on the head of the design turn). After: no output. 7. cargo test --manifest-path compiler-rust/Cargo.toml --lib tc::r5a2_tests before: 6 passed, 23 ignored. After: 29 passed, 0 ignored. 8. cargo test --manifest-path compiler-rust/Cargo.toml --lib tc:: - Run it on trunk before you start and write the three numbers down. + Run it on trunk before you start and write the three numbers down + (the design turn's head: see the pull request for CI's count). After: passed is trunk's plus 23, ignored is trunk's minus 24, 0 failed (23 tests of r5a2_tests.rs and 1 of r5a_tests.rs stop being ignored and pass; 1 passing test of r5a_tests.rs is deleted). @@ -12337,8 +12347,8 @@ report which test needs which later body. a_type_without_plain_parameters_is_declined goes. In src/tc/mod.rs the attribute on `walk` keeps dead_code (transl_type_scheme, declared and add_declared have no caller before R5a-3 and R5a-9) - and loses unused_variables if R5a-1 left it; change nothing else - there. + and loses unused_variables if it is still there; change nothing + else there. The engineering standard of 6.0 applies. For this slice in particular: - Name each loop of your bodies in the pull request body with the step @@ -12856,6 +12866,7 @@ instances of `unify_params`. No new struct or enum: `UsedVar` and #### 10.12.4 What the tests of R5a-1 pin that R5a-2a removes +(Written before R5a-1 was merged; it holds on its build too.) `r5a_tests::a_type_without_plain_parameters_is_declined` asserts `Declined::NotBuilt` for a type without `PLAIN_PARAMS`, and the row `("int as 'a", Declined::AliasType)` of `r5a_tests::DECLINED` asserts