Skip to content

Checker rewrite R5a design turn 2: R5a-2 built once - #436

Merged
jfrolich merged 6 commits into
ocaml-to-rust-rewritefrom
checker-rewrite-r5a-2-annotations
Nov 29, 2026
Merged

jfrolich merged 6 commits into
ocaml-to-rust-rewritefrom
checker-rewrite-r5a-2-annotations

Conversation

@jfrolich

@jfrolich jfrolich commented Nov 29, 2026 •

Copy link
Copy Markdown
Owner

Second design turn of slice R5a of the type checker rewrite (compiler-rust/docs/CHECKER_REWRITE.md, section 10). Slice R5a-2, the rest of type annotations, is decided, cut in two, and its first half is tested and built once as a prototype. No body of a slice is committed: the committed tree keeps its todo! bodies and its ignored tests, and nothing of a default build changes.

What is in it

  • Section 10.12 of the document: decisions 13 to 21, the skeleton changes with their reasons (10.12.2), measured costs (10.12.3), what R5a-1's tests pin that this slice removes (10.12.4), the second half on paper (10.12.5), and the table of programs with what OCaml and today's checker answer (10.12.6). 10.7 has the two rows of the cut; item 4 of 10.11 has its State: line; 10.10 has the prompt "Task R5a-2a".
  • src/tc/r5a2_tests.rs: 23 acceptance tests ignored until the slice is built, 5 pins of today's checker that run today, and the check that every ignored test names its slice.
  • src/tc/walk/typetexp.rs, skeleton only (listed below).
  • The prototype, twice. The one to read is comment 7257628931 (// R5A-PROTOTYPE R5a-2, second): one diff against commit def93a8, the merge of trunk after R5a-1 was built (pull request 435), applied alone; it stands on the BUILT bodies of R5a-1. Fetched back, git apply --check passes on def93a8 and on the head. The first, comment 7257203319, was built on commit 947fad3 with the second prototype of R5a-1 (comment 7255791970 of pull request 430) applied first; both applied in order there. The bodies of the eight R5a-2 functions are the same text in both.

Which deliverables are complete

  • M0 complete for the first half; for paths and types of other units (point d) it is a paper design that says what it does not decide.
  • M1 complete for the first half.
  • M2 complete for the first half: prototype posted, prompt written. The prompt is "Task R5a-2a", not "Task R5a-2", because of the cut.
  • M3 not started (decision 6, the stub of a recursive group).

The cut

The prototype of everything but paths changes 336 lines (314 added, 22 removed). Paths and types of other units were not built: a type of another unit needs a row in the unit's own type table, and TypeTable::from_segment makes a whole table from one segment. That needs a design turn that builds that row first (10.12.5). So: R5a-2a (aliases, universal variables, globalize, transl_simple_type, transl_type_scheme, unify_params) has tests, a prototype and a prompt; R5a-2b (paths, other units) has neither. R5a-3 needs only R5a-2a.

Decisions a review should confirm

  1. The cut above.
  2. The alias arm is one frame; the variable is entered when the node is entered; the proxy is named without validate_name; one intern an alias.
  3. A self-alias is decided by the kernel's unify_var, unchanged; a phantom self-alias (ph<'b> as 'b) is HELD as a node that names itself, not declined.
  4. A used variable whose globalization fails DECLINES the unit (Declined::PolyType), where OCaml skips it silently and can leave a universal variable outside its binder.
  5. globalize is two loops over the used rows with no list between them; the second runs from the last row to the first; one speculation a variable, closed before the decline.
  6. Universal variables are found through a head table by name; deep_occur for a binder's list is ONE marking walk of the body; the last line of the arm is Checker::lower.
  7. unify_params always calls unify_var; enforce_constraints is kept as a second copy session.
  8. Policy::Univars has no caller in OCaml and keeps declining.
  9. On Err, transl_type puts the level back and drops the universal variables.

Lines of OCaml read, and not read

Read, every line: compiler/ml/typetexp.ml 63-136, 205-428, 545-588, 677-756; compiler/ml/ctype.ml 120-162, 509-520, 879-894, 1333-1342, 1384-1408, 1723-1776, 2216-2247, 2726-2733, 2748-2767.
NOT read: occur_univar, subst, update_level, unify2/unify3 in OCaml (the kernel's functions were run instead); typetexp.ml 431-544 and 572-586 beyond the first lines (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 instead); the body of TypeTable::from_segment.

Tests run, with counts

Tree Command Result
trunk 8c6b498 with the R5a-1 prototype --lib tc::r5a_tests -- --include-ignored 21 passed, 1 failed (the R5a-2 test)
commit cc6758a (committed tree, before the merge of trunk) --lib tc:: 422 passed, 0 failed, 41 ignored (trunk: 417 and 18; this adds 5 passing and 23 ignored)
both prototypes on 947fad3 --lib tc::r5a -- --include-ignored 47 passed, 2 failed
both prototypes on a618c9b (trunk fb9a714 merged) --lib tc::r5a2_tests -- --include-ignored 29 passed, 0 failed
def93a8 (trunk with R5a-1 built merged), committed tree --lib tc::r5a 27 passed, 0 failed, 24 ignored
the second prototype on def93a8 --lib tc::r5a -- --include-ignored 49 passed, 2 failed

The 2 failures are tests of R5a-1 that pin a decline this slice removes (a_type_without_plain_parameters_is_declined, and the row int as 'a of unbuilt_annotations_decline); the prompt tells the builder to delete the first and that one row (10.12.4). The other 20 tests of R5a-1 pass with both prototypes.

NOT run: the whole tc:: filter on the head after the two merges of trunk (CI shows the number); the 39 breaks against the second prototype (they ran against the first); cargo clippy and cargo doc locally (CI's compiler-warnings passed on cc6758a); the five commits of the prompt each built alone (their order was checked by reading what each test calls, and the prompt says so).

Every acceptance test

All 23 ignored tests passed against the prototype. Three passed only after a change:

  • a_polymorphic_type_binds_the_variables_that_occur: the PROTOTYPE was wrong (it lowered the finished type to the binder's own level); corrected, then passed.
  • polymorphic_fields_agree_with_todays_checker, the_fixed_policy_refuses_a_variable_that_is_not_declared, parameters_without_plain_params_agree_with_todays_checker, ten_thousand_uses_of_one_alias: 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<int, int> has its two int nodes linked).
  • the six step tests: the per-element bound was set to what the prototype counted (7, 2, 4, 6, 7 and 14 an element). The relation large <= 11 * small, small >= 1,000 was not changed.

Arms no test reaches: a binder inside a binder (the parser or today's checker refuses every source form tried); the Tunivar None half of the proxy naming; Cannot_quantify for a variable lowered below its binder.

Wrong bodies

39 breaks of the prototype were run, one at a time, against --lib tc::r5a2_tests -- --include-ignored; 35 failed at least one test. The table is in 10.10 of the document; by function:

Function Wrong body Test that failed Seen
alias arm variable not entered before the aliased type a_self_alias_is_refused_as_in_ocaml and 8 more yes
alias arm no unify_var an_alias_bound_to_two_types_is_an_error and 7 more yes
alias arm proxy never named; name validated aliases_agree_with_todays_checker yes, both
polymorphic arm not lowered at the end a_polymorphic_type_binds_the_variables_that_occur yes
polymorphic arm deep_occur once a variable ten_thousand_universal_variables yes
polymorphic arm every variable bound; non-variable dropped silently; no end_def; no generalize; heads not put back polymorphic_fields_agree_with_todays_checker, ten_thousand_universal_variables yes, each
univar never finds four binder tests yes
variable arm used variables before universal ones a_universal_variable_hides_a_used_variable_inside_its_binder yes
globalize no sort used_variables_are_globalized_in_the_order_of_their_names yes
globalize silent skip; speculation left open polymorphic_fields_agree_with_todays_checker yes, both
globalize no fixed test; fixed test too wide; no second loop; used not forgotten; variables at the current level the_fixed_policy_refuses_a_variable_that_is_not_declared, a_name_bound_to_two_types_by_two_annotations_is_an_error, globalized_variables_are_at_the_global_level yes, each
transl_simple_type no globalize; used not emptied; always extensible 8 tests; globalized_variables_are_at_the_global_level; polymorphic_fields_agree_with_todays_checker yes, each
transl_type_scheme no generalize; no reset; level kept on an error a_scheme_is_generalized yes, each
unify_params one copy session a parameter parameters_without_plain_params_agree_with_todays_checker yes
unify_params declared parameters themselves unified the_declared_parameters_are_instantiated_not_bound yes
TypeVars::reset heads not taken back; global level not level + 1 reset_forgets_the_declared_variables yes, both
declared never finds 7 tests yes
transl_type on Err level not put back; universal variables not dropped an_error_inside_a_binder_leaves_no_binder yes, both

No test catches (each named in the prompt or argued in the document): enforce_constraints left out; a binder's heads written in source order; the instances of unify_params left on the value stack (the driver cuts them); Checker::copy without the generic test (the same node). Not run as breaks because steps do not count them: a univar that scans, an alias interned twice, a sort that allocates; all three are in the prompt's failure list.

Step tests seen to fail on a body that walks more: only ten_thousand_universal_variables (on deep_occur once a variable). The other five were NOT broken with a body that walks twice.

Today's checker against the OCaml texts

On the trunk this turn began from, today's checker accepted every refused self-alias and printed id<'a> => int for id<'b> as 'b. Pull request 433 corrected it; this branch merged trunk, and old_checker_self_aliases_are_pinned now observes agreement on all of them. No other program of the coordinator's list differs.

Programs whose OCaml answer this turn could not know

Each is a file to run alone; the test follows today's checker.

// 1: expected (int, int) => int
external v: (int as 'a, 'a) => 'a = "v"
// 2: expected refused, Alias_type_mismatch
external v: (int as 'a, string as 'a) => int = "v"
// 3: expected refused (the alias message), k abstract
type k<'a>
external v: (k<'b> as 'b) => int = "v"
// 4: expected ('a, 'a) => 'a
external v: (('a as 'b) as 'c, 'c) => 'b = "v"
// 5: expected accepted, the parameter prints as int
type t<'a> = {x: int as 'a}
// 6: expected refused, "This type string should be an instance of type int"
type t<'a> = {x: int as 'a, y: string as 'a}
// 7: expected accepted; the binder prints 'a 'b
type r = {m: 'a 'b. ('b, 'a)}
// 8: expected accepted, 'a. 'a => 'a
type r = {m: 'a 'a. 'a => 'a}
// 9: expected refused, Cannot_quantify
type r = {m: 'a 'b. ('a as 'b) => int}
// 10: expected refused (today's checker refuses both)
type r = {m: 'a. ('b. 'b => 'a) => 'a}
external v: 'a. 'a => 'a = "v"
// 11: expected sh<array<'v>, array<'v>>, the two arguments one type
type sh<'a, 'b> = int constraint 'a = 'b
external v: sh<'x, array<'v>> = "v"
// 12: expected one variable, printed 'y (which name survives)
type sh<'a, 'b> = int constraint 'a = 'b
external v: (sh<'x, 'y>, 'x) => 'y = "v"
// 13: expected cl<list<'a>> => list<'a>
type cl<'a> = 'b constraint 'a = list<'b>
external v: cl<'x> => 'x = "v"
// 14: is there ANY program refused with Type_mismatch at the whole constructor
// (typetexp.ml:389) and not at an argument (386)? None was found; decision 19.

Skeleton changes (signatures, costs, doc comments)

  • TypeVars::reset(&mut self) is reset(&mut self, level: u32).
  • New fields TypeVars::univar_heads and TypeVars::global_level; the doc of univars says what a row's loc holds. These two field lines are in the struct, not "after transl_type_scheme": a todo! body must be able to read them and the tests name them. They sit beside the fields marked R5a-2, away from every line R5a-1's builder writes; the R5a-1 prototype still applies.
  • New functions Annot::univar, Annot::declared, Annot::add_declared, bodies todo!("R5a-2"), after transl_type_scheme.
  • Doc comments and stated costs of unify_params, globalize, transl_simple_type, transl_type_scheme.
  • src/tc/mod.rs: one line, mod r5a2_tests; with the cfg of r5a_tests. r5a_tests.rs is not touched.

Attributes added: #[inline] on Annot::univar and Annot::declared (one bounds test and two loads, called once a variable node, as TypeVars::used has it).
Checks changed on trunk: none. Added: r5a2_tests::ignored_tests_name_the_slices_they_reach, the check of r5a_tests repeated for the new file; it pins no number. That every ignored test names only its own slice and earlier ones was checked by that test, which runs today.
No reader was added on the side of today's checker. No hash map, no new struct or enum.

Open questions, each with a recommended answer

  1. Decline or hold the type with a universal variable outside its binder (decision 16)? Recommended: decline; no corpus form was looked for, so count 'a. (.. as 'b) before R5c if in doubt.
  2. Keep enforce_constraints (decision 19)? Recommended: keep until program 14 is answered by OCaml's source or a run; then delete the second loop.
  3. Hold the phantom self-alias (decision 15)? Recommended: hold; R5a-9 declines a scheme that names itself unless its design turn shows Graph::capture and the published text on one.
  4. Who designs R5a-2b? Recommended: a design turn of its own, before R5a-9 and not before R5a-3, that first builds the row of another unit's type.
  5. The two R5a-1 tests R5a-2a must edit (10.12.4). Recommended: accept the three edits the prompt lists; nothing else of r5a_tests.rs moves.

Asked by the coordinator during the turn, and not done

  • Tests for the wrong bodies the review of pull request 435 found no R5a-1 test catches (a Param location taken from the type, resolved left empty for a constructor without arguments, the fixed policy skipped for a repeated _, a non-ASCII letter keeping its name, the wrong Declined variant, a decline by counting parameters, only the first argument lowered, a mark on a binder that is not a type): none was added. One of them touches this slice directly and is in the prompt: the rule of validate_name on trunk tests only for an ASCII letter behind a refusal of _, and a binder's variable has no such refusal, so the builder is told to share one helper with the whole rule.
  • No test of this turn pins char as distinct from int.

Gates

Nothing of a default build calls the new code: Instruction count cannot move, and no measurement was taken. CI is the gate for clippy, cargo doc and the parity checks.

Started by Jaap Frolich in this Assistant session

…ariable 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 <jfrolich@gmail.com>
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>
@jfrolich

Copy link
Copy Markdown
Owner Author

// R5A-PROTOTYPE R5a-2: the throw-away bodies of the first half of slice R5a-2 (R5a-2a: aliases, universal variables and polymorphic types, globalize, transl_simple_type, transl_type_scheme, unify_params with enforce_constraints). Paths of several components and types of other units (R5a-2b) are not in it.

It is ONE diff against commit 947fad3 of this branch WITH the prototype of R5a-1 applied first (comment 7255791970 of pull request 430, // R5A-PROTOTYPE R5a-1, second). In order, on 947fad3: git apply --check of the R5a-1 diff passes, and after applying it git apply --check of this one passes. With both applied, cargo test --manifest-path compiler-rust/Cargo.toml --lib tc::r5a -- --include-ignored read 47 passed, 2 failed: all 27 tests of r5a2_tests pass (22 of them are ignored on the committed tree), 20 of the 22 of r5a_tests pass, and the 2 failures are tests of R5a-1 that pin a decline this slice removes (a_type_without_plain_parameters_is_declined, and the row int as 'a of unbuilt_annotations_decline); the build prompt tells the builder what to do with each.

The prototype is not to be applied by the builder; it need not meet the engineering standard.

// R5A-PROTOTYPE R5a-2
diff --git a/compiler-rust/src/tc/walk/typetexp.rs b/compiler-rust/src/tc/walk/typetexp.rs
--- a/compiler-rust/src/tc/walk/typetexp.rs
+++ b/compiler-rust/src/tc/walk/typetexp.rs
@@ -10,6 +10,7 @@
 //! order, and its [`CoreTypeRow`] is written when it is left.
 
 use super::super::graph::{ARROW, CONSTR, GENERIC, NONE, Node, Param, TUPLE, Ty, VAR};
+use super::super::segment::{EXTENDED, ExtraDescriptor};
 use super::super::scope::{BinderKind, Key, Namespace, Resolved, ResolvedKind, USED};
 use super::super::expand::PLAIN_PARAMS;
 use super::super::{Declined, Stop};
@@ -148,7 +149,25 @@
     /// the graph's current level. O(variables of the item). No
     /// allocation. (R5a-2)
     pub fn reset(&mut self, level: u32) {
-        todo!("R5a-2")
+        // R5A-PROTOTYPE R5a-2
+        for row in 0..self.declared.len() {
+            #[cfg(test)]
+            super::super::steps::tick();
+            let name = self.declared[row].name;
+            self.declared_heads[name.0 as usize] = NONE;
+        }
+        self.declared.clear();
+        self.forget_used();
+        self.drop_univars();
+        self.global_level = level + 1;
+    }
+
+    fn drop_univars(&mut self) {
+        for row in 0..self.univars.len() {
+            let name = self.univars[row].name;
+            self.univar_heads[name.0 as usize] = NONE;
+        }
+        self.univars.clear();
     }
 }
 
@@ -303,10 +322,13 @@
     /// nested in another. No recursion: an annotation 10,000 deep uses the two
     /// stacks. No allocation beyond the growth of the pools. (R5a-1)
     pub fn transl_type(&mut self, root: CoreTypeIdx, policy: Policy) -> Result<Ty, Stop> {
+        let level = self.c.g.level;
         let result = self.run(root, policy);
         if result.is_err() {
             self.st.frames.clear();
             self.st.values.clear();
+            self.c.g.level = level;
+            self.st.vars.drop_univars();
         }
         result
     }
@@ -371,7 +393,42 @@
     /// the unifications. No allocation beyond the growth of the pools.
     /// (R5a-2)
     pub fn unify_params(&mut self, type_index: u32, args: u32, node: Ty) -> Result<(), Stop> {
-        todo!("R5a-2")
+        let arity = u32::from(self.c.types.info(type_index).arity);
+        let start = match self.st.params_of.get(type_index as usize) {
+            Some(&start) if start != NONE => start,
+            _ => return Err(Stop::Declined(Declined::NotBuilt)),
+        };
+        let mark = self.st.values.len();
+        // `instance_list decl.type_params`, then `unify_var` an argument.
+        self.instance_list(start, arity);
+        for at in 0..arity as usize {
+            #[cfg(test)]
+            super::super::steps::tick();
+            let param = self.st.values[mark + at];
+            let arg = self.st.values[args as usize + at];
+            if self.c.unify_var(param, arg).is_err() {
+                self.st.values.truncate(mark);
+                return Err(Stop::Error);
+            }
+        }
+        self.st.values.truncate(mark);
+        // `enforce_constraints` (ctype.ml:1333-1342): `subst` at the
+        // node's level with a new body.
+        let level = std::mem::replace(&mut self.c.g.level, self.c.g.nodes[node.0 as usize].level);
+        self.instance_list(start, arity);
+        self.c.g.level = level;
+        for at in 0..arity as usize {
+            #[cfg(test)]
+            super::super::steps::tick();
+            let param = self.st.values[mark + at];
+            let arg = self.st.values[args as usize + at];
+            if self.c.unify(param, arg).is_err() {
+                self.st.values.truncate(mark);
+                return Err(Stop::Error);
+            }
+        }
+        self.st.values.truncate(mark);
+        Ok(())
     }
 
     /// `globalize_used_variables env fixed` (compiler/ml/typetexp.ml:
@@ -406,7 +463,45 @@
     /// allocation: the second half reads the rows the first sorted.
     /// (R5a-2)
     pub fn globalize(&mut self, fixed: bool) -> Result<(), Stop> {
-        todo!("R5a-2")
+        if self.st.vars.used.len() > 1 {
+            let names = &self.scopes.names;
+            self.st
+                .vars
+                .used
+                .sort_unstable_by(|l, r| names.text(l.name).as_bytes().cmp(names.text(r.name).as_bytes()));
+        }
+        let global = self.st.vars.global_level;
+        for row in 0..self.st.vars.used.len() {
+            #[cfg(test)]
+            super::super::steps::tick();
+            let used = self.st.vars.used[row];
+            let v = self.var_at(NONE, global);
+            let token = self.c.g.speculate();
+            if self.c.unify(v, used.ty).is_err() {
+                self.c.restore(token);
+                return Err(Stop::Declined(Declined::PolyType));
+            }
+            self.c.g.keep(token);
+            if self.declared(used.name).0 == NONE {
+                let repr = self.c.g.repr(used.ty);
+                if fixed && self.c.g.nodes[repr.0 as usize].tag() == VAR {
+                    return Err(Stop::Error);
+                }
+                let v2 = self.var_at(NONE, global);
+                self.add_declared(used.name, v2, used.loc);
+            }
+        }
+        for row in (0..self.st.vars.used.len()).rev() {
+            #[cfg(test)]
+            super::super::steps::tick();
+            let used = self.st.vars.used[row];
+            let v2 = self.declared(used.name);
+            if self.c.unify(used.ty, v2).is_err() {
+                return Err(Stop::Error);
+            }
+        }
+        self.st.vars.forget_used();
+        Ok(())
     }
 
     /// `transl_simple_type env fixed styp` (compiler/ml/typetexp.ml:
@@ -418,7 +513,11 @@
     /// 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<Ty, Stop> {
-        todo!("R5a-2")
+        self.st.vars.drop_univars();
+        self.st.vars.forget_used();
+        let ty = self.transl_type(root, if fixed { Policy::Fixed } else { Policy::Extensible })?;
+        self.globalize(fixed)?;
+        Ok(ty)
     }
 
     /// `transl_type_scheme env styp` (compiler/ml/typetexp.ml:751-756):
@@ -428,7 +527,13 @@
     /// `Err` too. O(1) plus [`Annot::transl_simple_type`] and
     /// `Checker::generalize`. (R5a-2)
     pub fn transl_type_scheme(&mut self, root: CoreTypeIdx) -> Result<Ty, Stop> {
-        todo!("R5a-2")
+        self.st.vars.reset(self.c.g.level);
+        self.c.g.begin_def();
+        let result = self.transl_simple_type(root, false);
+        self.c.g.end_def();
+        let ty = result?;
+        self.c.generalize(ty);
+        Ok(ty)
     }
 
     /// `List.assoc name !(univars ())` (compiler/ml/typetexp.ml:308,
@@ -438,7 +543,14 @@
     /// two loads. (R5a-2)
     #[inline]
     pub fn univar(&self, name: Name) -> Ty {
-        todo!("R5a-2")
+        let vars = &self.st.vars;
+        if vars.univars.is_empty() {
+            return Ty(NONE);
+        }
+        match vars.univar_heads.get(name.0 as usize) {
+            Some(&row) if row != NONE => vars.univars[row as usize].ty,
+            _ => Ty(NONE),
+        }
     }
 
     /// `Tbl.find name !(type_variables ())` (compiler/ml/typetexp.ml:
@@ -448,7 +560,11 @@
     /// (R5a-2)
     #[inline]
     pub fn declared(&self, name: Name) -> Ty {
-        todo!("R5a-2")
+        let vars = &self.st.vars;
+        match vars.declared_heads.get(name.0 as usize) {
+            Some(&row) if row != NONE => vars.declared[row as usize].ty,
+            _ => Ty(NONE),
+        }
     }
 
     /// `type_variables () := Tbl.add name v` (compiler/ml/typetexp.ml:
@@ -458,7 +574,13 @@
     /// `Already_bound` first, 250-251; R5a-3 tests it with
     /// [`Annot::declared`]). (R5a-2)
     pub fn add_declared(&mut self, name: Name, ty: Ty, loc: u32) {
-        todo!("R5a-2")
+        let vars = &mut self.st.vars;
+        let at = name.0 as usize;
+        if at >= vars.declared_heads.len() {
+            vars.declared_heads.resize(at + 1, NONE);
+        }
+        vars.declared_heads[at] = vars.declared.len() as u32;
+        vars.declared.push(UsedVar { name, ty, loc });
     }
 }
 
@@ -502,8 +624,41 @@
     }
 
     fn var(&mut self, name: u32) -> Ty {
-        let serial = self.c.g.nodes.len() as u32;
         let level = self.c.g.level;
+        self.var_at(name, level)
+    }
+
+    /// `instance env t` of a used variable's node.
+    fn instance(&mut self, ty: Ty) -> Ty {
+        let repr = self.c.g.repr(ty);
+        if self.c.g.nodes[repr.0 as usize].level == GENERIC {
+            self.c.copy(ty)
+        } else {
+            ty
+        }
+    }
+
+    /// `instance_list` of `arity` parameters from `start`: pushed on
+    /// `values`.
+    fn instance_list(&mut self, start: u32, arity: u32) {
+        let first = self.c.g.nodes.len();
+        self.c.g.copy_begin();
+        for at in 0..arity {
+            let param = self.st.params[(start + at) as usize];
+            let copy = self.c.g.copy_ref(param);
+            self.st.values.push(copy);
+        }
+        self.c.g.copy_drain();
+        let cells = !self.c.extras.descriptors.is_empty();
+        if self.c.memo.live != 0 || cells {
+            self.c.extras.copying = true;
+            self.c.link_memorized(first, NONE, cells);
+            self.c.extras.copying = false;
+        }
+    }
+
+    fn var_at(&mut self, name: u32, level: u32) -> Ty {
+        let serial = self.c.g.nodes.len() as u32;
         self.c.g.push(Node {
             head: VAR,
             level,
@@ -532,7 +687,8 @@
                     return Err(Stop::Error);
                 }
                 let name = self.st.strs.name(arena, &mut self.scopes.names, *text);
-                let used = self.st.vars.used(name);
+                let universal = self.univar(name);
+                let used = if universal.0 != NONE { universal } else { self.st.vars.used(name) };
                 if used.0 == NONE {
                     // `validate_name` (typetexp.ml:224-231).
                     let first = arena.get_string(*text).as_bytes().first().copied();
@@ -564,9 +720,6 @@
                 if !repeated && args.len() as u32 != arity {
                     return Err(Stop::Error);
                 }
-                if info.reserved & PLAIN_PARAMS == 0 {
-                    return Err(Stop::Declined(Declined::NotBuilt));
-                }
                 self.set_row(node, CoreTypeRow { ty: Ty(NONE), resolved });
                 self.push_frame(node);
                 return Ok(());
@@ -577,9 +730,58 @@
                 return Ok(());
             }
             CoreTypeDesc::Ptyp_object(_) => return Err(Stop::Declined(Declined::ObjectType)),
-            CoreTypeDesc::Ptyp_alias(_) => return Err(Stop::Declined(Declined::AliasType)),
+            CoreTypeDesc::Ptyp_alias(inner) => {
+                // typetexp.ml:394-428, before the aliased type.
+                let name = self.scopes.names.intern(&inner.1);
+                let mut t = self.univar(name);
+                let mut new = false;
+                if t.0 == NONE {
+                    let used = self.st.vars.used(name);
+                    if used.0 == NONE {
+                        t = self.var(NONE);
+                        self.st.vars.add_used(name, t, core.ptyp_loc.0);
+                        new = true;
+                    } else {
+                        t = self.instance(used);
+                    }
+                }
+                self.set_row(node, NO_ROW);
+                self.push_frame(node);
+                // Below the aliased type's result: the variable, and for
+                // a new one the alias's name (a `Name` in a slot).
+                self.st.values.push(t);
+                if new {
+                    self.st.values.push(Ty(name.0));
+                }
+                return Ok(());
+            }
             CoreTypeDesc::Ptyp_variant(_) => return Err(Stop::Declined(Declined::PolyVariantType)),
-            CoreTypeDesc::Ptyp_poly(_) => return Err(Stop::Declined(Declined::PolyType)),
+            CoreTypeDesc::Ptyp_poly(inner) => {
+                // typetexp.ml:545-549.
+                self.c.g.begin_def();
+                let first = self.st.vars.univars.len();
+                for var in &inner.0 {
+                    #[cfg(test)]
+                    super::super::steps::tick();
+                    let name = self.st.strs.name(arena, &mut self.scopes.names, var.txt);
+                    let first_byte = arena.get_string(var.txt).as_bytes().first().copied();
+                    let named = first_byte.is_some_and(|c| c == b'_' || c.is_ascii_alphabetic());
+                    let ty = self.var(if named { name.0 } else { NONE });
+                    self.st.vars.univars.push(UsedVar { name, ty, loc: NONE });
+                }
+                let vars = &mut self.st.vars;
+                for row in (first..vars.univars.len()).rev() {
+                    let at = vars.univars[row].name.0 as usize;
+                    if at >= vars.univar_heads.len() {
+                        vars.univar_heads.resize(at + 1, NONE);
+                    }
+                    vars.univars[row].loc = vars.univar_heads[at];
+                    vars.univar_heads[at] = row as u32;
+                }
+                self.set_row(node, NO_ROW);
+                self.push_frame(node);
+                return Ok(());
+            }
             CoreTypeDesc::Ptyp_package(_) => return Err(Stop::Declined(Declined::PackageType)),
             CoreTypeDesc::Ptyp_extension(_) => return Err(Stop::Declined(Declined::ExtensionType)),
         };
@@ -607,6 +809,8 @@
         let arena = self.arena;
         let next = frame.next as usize;
         Ok(match &arena.get_core_type(CoreTypeIdx(frame.node)).ptyp_desc {
+            CoreTypeDesc::Ptyp_alias(inner) => (next == 0).then_some(inner.0),
+            CoreTypeDesc::Ptyp_poly(inner) => (next == 0).then_some(inner.1),
             CoreTypeDesc::Ptyp_tuple(list) => arena.type_list(*list).get(next).copied(),
             CoreTypeDesc::Ptyp_constr((_, list)) => {
                 let args = arena.type_list(*list);
@@ -658,21 +862,28 @@
             }
             CoreTypeDesc::Ptyp_constr(_) => {
                 let type_index = self.type_index(frame.node)?;
-                for at in base..base + count {
-                    let arg = self.st.values[at];
-                    if self.c.lower(arg, level).is_err() {
-                        return Err(Stop::Error);
+                let plain = self.c.types.info(type_index).reserved & PLAIN_PARAMS != 0;
+                if plain {
+                    for at in base..base + count {
+                        let arg = self.st.values[at];
+                        if self.c.lower(arg, level).is_err() {
+                            return Err(Stop::Error);
+                        }
                     }
                 }
                 let b = self.c.g.lists.len() as u32;
                 self.c.g.lists.push(Ty(NONE));
                 self.c.g.lists.extend_from_slice(&self.st.values[base..]);
-                self.c.g.push(Node {
+                let constr = self.c.g.push(Node {
                     head: CONSTR | (count as u32) << 8,
                     level,
                     a: type_index,
                     b,
-                })
+                });
+                if !plain {
+                    self.unify_params(type_index, base as u32, constr)?;
+                }
+                constr
             }
             CoreTypeDesc::Ptyp_arrow(inner) => {
                 let (arg, _, _) = &**inner;
@@ -712,6 +923,87 @@
                     b,
                 })
             }
+            CoreTypeDesc::Ptyp_alias(_) => {
+                // typetexp.ml:402-427, after the aliased type.
+                let t = self.st.values[base];
+                let ty = self.st.values[base + count - 1];
+                if self.c.unify_var(t, ty).is_err() {
+                    return Err(Stop::Error);
+                }
+                if count == 2 {
+                    ty
+                } else {
+                    let name = self.st.values[base + 1].0;
+                    let t = self.instance(t);
+                    let proxy = self.c.g.repr(t);
+                    let found = self.c.g.nodes[proxy.0 as usize];
+                    if found.tag() == VAR && found.a == NONE {
+                        self.c.g.write(proxy, Node { a: name, ..found });
+                    }
+                    t
+                }
+            }
+            CoreTypeDesc::Ptyp_poly(inner) => {
+                // typetexp.ml:550-571.
+                let body = self.st.values[base];
+                let first = self.st.vars.univars.len() - inner.0.len();
+                let vars = &mut self.st.vars;
+                for row in first..vars.univars.len() {
+                    let at = vars.univars[row].name.0 as usize;
+                    vars.univar_heads[at] = vars.univars[row].loc;
+                }
+                self.c.g.end_def();
+                self.c.generalize(body);
+                // `deep_occur v ty` for every variable of the list: one walk.
+                let generation = self.c.fresh_marks();
+                self.c.g.work.clear();
+                self.c.g.work.push(body);
+                while let Some(ty) = self.c.g.work.pop() {
+                    let ty = self.c.g.repr(ty);
+                    if self.c.marks[ty.0 as usize] == generation {
+                        continue;
+                    }
+                    #[cfg(test)]
+                    super::super::steps::tick();
+                    self.c.marks[ty.0 as usize] = generation;
+                    let reached = self.c.g.nodes[ty.0 as usize];
+                    self.c.g.children(reached, false);
+                }
+                let b = self.c.g.lists.len() as u32;
+                self.c.g.lists.push(body);
+                let mut bound = 0;
+                for row in first..self.st.vars.univars.len() {
+                    #[cfg(test)]
+                    super::super::steps::tick();
+                    let v = self.c.g.repr(self.st.vars.univars[row].ty);
+                    if self.c.marks[v.0 as usize] != generation {
+                        continue;
+                    }
+                    let found = self.c.g.nodes[v.0 as usize];
+                    if found.tag() != VAR || found.level != GENERIC {
+                        return Err(Stop::Error);
+                    }
+                    let a = self.c.extras.univar(found.a);
+                    self.c.g.write(v, Node { head: TUPLE | EXTENDED, level: GENERIC, a, b: 0 });
+                    self.c.g.lists.push(v);
+                    bound += 1;
+                }
+                self.st.vars.univars.truncate(first);
+                let a = self.c.extras.descriptors.len() as u32;
+                self.c.extras.descriptors.push(ExtraDescriptor::Poly);
+                let poly = self.c.g.push(Node {
+                    head: TUPLE | EXTENDED | (bound + 1) << 8,
+                    level: GENERIC,
+                    a,
+                    b,
+                });
+                // `unify_var env (newvar ()) ty'` (571).
+                let level = self.c.g.level;
+                if self.c.lower(poly, level).is_err() {
+                    return Err(Stop::Error);
+                }
+                poly
+            }
             _ => return Err(NOT_A_FRAME),
         })
     }

open-session-submodule Bot and others added 4 commits November 29, 2026 14:25
…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 <jfrolich@gmail.com>
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>
Trunk gained the corrected alias arm of today's checker (pull request 433).

Co-authored-by: Jaap Frolich <jfrolich@gmail.com>
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>
…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 <jfrolich@gmail.com>
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>
Trunk gained the build of R5a-1 (pull request 435).

Co-authored-by: Jaap Frolich <jfrolich@gmail.com>
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>
@jfrolich

Copy link
Copy Markdown
Owner Author

// R5A-PROTOTYPE R5a-2, second: the same throw-away bodies of R5a-2a as the first comment, rebuilt on the BUILT bodies of R5a-1 after trunk gained them (pull request 435). It is ONE diff against commit def93a8 of this branch (the merge of trunk) and needs no other diff applied first: git apply --check passes on def93a8. It supersedes the first comment, which stands on the prototype of R5a-1; the bodies of the eight R5a-2 functions are the same text, and the arms inside enter, child and leave are placed in trunk's functions (walk, new_var).

With it applied on def93a8, cargo test --manifest-path compiler-rust/Cargo.toml --lib tc::r5a -- --include-ignored read 49 passed, 2 failed: all 29 tests of r5a2_tests pass, 20 of the 22 of r5a_tests pass, and the 2 failures are the tests of R5a-1 that pin a decline this slice removes (a_type_without_plain_parameters_is_declined, the row int as 'a of unbuilt_annotations_decline). The 39 breaks of the wrong-body table were run against the first prototype, not this one.

The builder does not apply it.

// R5A-PROTOTYPE R5a-2, second
diff --git a/compiler-rust/src/tc/walk/typetexp.rs b/compiler-rust/src/tc/walk/typetexp.rs
index 5dde1aed3..018cea321 100644
--- a/compiler-rust/src/tc/walk/typetexp.rs
+++ b/compiler-rust/src/tc/walk/typetexp.rs
@@ -13,6 +13,7 @@ use super::super::expand::PLAIN_PARAMS;
 use super::super::graph::{ARROW, CONSTR, GENERIC, NONE, Node, Param, TUPLE, Ty, VAR};
 use super::super::name_table::{Name, NameTable};
 use super::super::scope::{BinderKind, Key, Namespace, Resolved, ResolvedKind, Scopes, USED};
+use super::super::segment::{EXTENDED, ExtraDescriptor};
 use super::super::unify::Checker;
 use super::super::{Declined, Stop};
 use crate::intern::StrIdx;
@@ -147,7 +148,25 @@ impl TypeVars {
     /// the graph's current level. O(variables of the item). No
     /// allocation. (R5a-2)
     pub fn reset(&mut self, level: u32) {
-        todo!("R5a-2")
+        // R5A-PROTOTYPE R5a-2
+        for row in 0..self.declared.len() {
+            #[cfg(test)]
+            super::super::steps::tick();
+            let name = self.declared[row].name;
+            self.declared_heads[name.0 as usize] = NONE;
+        }
+        self.declared.clear();
+        self.forget_used();
+        self.drop_univars();
+        self.global_level = level + 1;
+    }
+
+    fn drop_univars(&mut self) {
+        for row in 0..self.univars.len() {
+            let name = self.univars[row].name;
+            self.univar_heads[name.0 as usize] = NONE;
+        }
+        self.univars.clear();
     }
 }
 
@@ -302,10 +321,14 @@ impl Annot<'_> {
     /// nested in another. No recursion: an annotation 10,000 deep uses the two
     /// stacks. No allocation beyond the growth of the pools. (R5a-1)
     pub fn transl_type(&mut self, root: CoreTypeIdx, policy: Policy) -> Result<Ty, Stop> {
+        // R5A-PROTOTYPE R5a-2
+        let level = self.c.g.level;
         let result = self.walk(root, policy);
         if result.is_err() {
             self.st.frames.clear();
             self.st.values.clear();
+            self.c.g.level = level;
+            self.st.vars.drop_univars();
         }
         result
     }
@@ -372,7 +395,42 @@ impl Annot<'_> {
     /// the unifications. No allocation beyond the growth of the pools.
     /// (R5a-2)
     pub fn unify_params(&mut self, type_index: u32, args: u32, node: Ty) -> Result<(), Stop> {
-        todo!("R5a-2")
+        let arity = u32::from(self.c.types.info(type_index).arity);
+        let start = match self.st.params_of.get(type_index as usize) {
+            Some(&start) if start != NONE => start,
+            _ => return Err(Stop::Declined(Declined::NotBuilt)),
+        };
+        let mark = self.st.values.len();
+        // `instance_list decl.type_params`, then `unify_var` an argument.
+        self.instance_list(start, arity);
+        for at in 0..arity as usize {
+            #[cfg(test)]
+            super::super::steps::tick();
+            let param = self.st.values[mark + at];
+            let arg = self.st.values[args as usize + at];
+            if self.c.unify_var(param, arg).is_err() {
+                self.st.values.truncate(mark);
+                return Err(Stop::Error);
+            }
+        }
+        self.st.values.truncate(mark);
+        // `enforce_constraints` (ctype.ml:1333-1342): `subst` at the
+        // node's level with a new body.
+        let level = std::mem::replace(&mut self.c.g.level, self.c.g.nodes[node.0 as usize].level);
+        self.instance_list(start, arity);
+        self.c.g.level = level;
+        for at in 0..arity as usize {
+            #[cfg(test)]
+            super::super::steps::tick();
+            let param = self.st.values[mark + at];
+            let arg = self.st.values[args as usize + at];
+            if self.c.unify(param, arg).is_err() {
+                self.st.values.truncate(mark);
+                return Err(Stop::Error);
+            }
+        }
+        self.st.values.truncate(mark);
+        Ok(())
     }
 
     /// `globalize_used_variables env fixed` (compiler/ml/typetexp.ml:
@@ -407,7 +465,45 @@ impl Annot<'_> {
     /// allocation: the second half reads the rows the first sorted.
     /// (R5a-2)
     pub fn globalize(&mut self, fixed: bool) -> Result<(), Stop> {
-        todo!("R5a-2")
+        if self.st.vars.used.len() > 1 {
+            let names = &self.scopes.names;
+            self.st
+                .vars
+                .used
+                .sort_unstable_by(|l, r| names.text(l.name).as_bytes().cmp(names.text(r.name).as_bytes()));
+        }
+        let global = self.st.vars.global_level;
+        for row in 0..self.st.vars.used.len() {
+            #[cfg(test)]
+            super::super::steps::tick();
+            let used = self.st.vars.used[row];
+            let v = self.var_at(NONE, global);
+            let token = self.c.g.speculate();
+            if self.c.unify(v, used.ty).is_err() {
+                self.c.restore(token);
+                return Err(Stop::Declined(Declined::PolyType));
+            }
+            self.c.g.keep(token);
+            if self.declared(used.name).0 == NONE {
+                let repr = self.c.g.repr(used.ty);
+                if fixed && self.c.g.nodes[repr.0 as usize].tag() == VAR {
+                    return Err(Stop::Error);
+                }
+                let v2 = self.var_at(NONE, global);
+                self.add_declared(used.name, v2, used.loc);
+            }
+        }
+        for row in (0..self.st.vars.used.len()).rev() {
+            #[cfg(test)]
+            super::super::steps::tick();
+            let used = self.st.vars.used[row];
+            let v2 = self.declared(used.name);
+            if self.c.unify(used.ty, v2).is_err() {
+                return Err(Stop::Error);
+            }
+        }
+        self.st.vars.forget_used();
+        Ok(())
     }
 
     /// `transl_simple_type env fixed styp` (compiler/ml/typetexp.ml:
@@ -419,7 +515,11 @@ impl Annot<'_> {
     /// nothing is done for it before R6b. O(1) plus
     /// [`Annot::transl_type`] and [`Annot::globalize`]. (R5a-2)
     pub fn transl_simple_type(&mut self, root: CoreTypeIdx, fixed: bool) -> Result<Ty, Stop> {
-        todo!("R5a-2")
+        self.st.vars.drop_univars();
+        self.st.vars.forget_used();
+        let ty = self.transl_type(root, if fixed { Policy::Fixed } else { Policy::Extensible })?;
+        self.globalize(fixed)?;
+        Ok(ty)
     }
 
     /// `transl_type_scheme env styp` (compiler/ml/typetexp.ml:751-756):
@@ -429,7 +529,13 @@ impl Annot<'_> {
     /// `Err` too. O(1) plus [`Annot::transl_simple_type`] and
     /// `Checker::generalize`. (R5a-2)
     pub fn transl_type_scheme(&mut self, root: CoreTypeIdx) -> Result<Ty, Stop> {
-        todo!("R5a-2")
+        self.st.vars.reset(self.c.g.level);
+        self.c.g.begin_def();
+        let result = self.transl_simple_type(root, false);
+        self.c.g.end_def();
+        let ty = result?;
+        self.c.generalize(ty);
+        Ok(ty)
     }
 
     /// `List.assoc name !(univars ())` (compiler/ml/typetexp.ml:308,
@@ -439,7 +545,14 @@ impl Annot<'_> {
     /// two loads. (R5a-2)
     #[inline]
     pub fn univar(&self, name: Name) -> Ty {
-        todo!("R5a-2")
+        let vars = &self.st.vars;
+        if vars.univars.is_empty() {
+            return Ty(NONE);
+        }
+        match vars.univar_heads.get(name.0 as usize) {
+            Some(&row) if row != NONE => vars.univars[row as usize].ty,
+            _ => Ty(NONE),
+        }
     }
 
     /// `Tbl.find name !(type_variables ())` (compiler/ml/typetexp.ml:
@@ -449,7 +562,11 @@ impl Annot<'_> {
     /// (R5a-2)
     #[inline]
     pub fn declared(&self, name: Name) -> Ty {
-        todo!("R5a-2")
+        let vars = &self.st.vars;
+        match vars.declared_heads.get(name.0 as usize) {
+            Some(&row) if row != NONE => vars.declared[row as usize].ty,
+            _ => Ty(NONE),
+        }
     }
 
     /// `type_variables () := Tbl.add name v` (compiler/ml/typetexp.ml:
@@ -459,7 +576,13 @@ impl Annot<'_> {
     /// `Already_bound` first, 250-251; R5a-3 tests it with
     /// [`Annot::declared`]). (R5a-2)
     pub fn add_declared(&mut self, name: Name, ty: Ty, loc: u32) {
-        todo!("R5a-2")
+        let vars = &mut self.st.vars;
+        let at = name.0 as usize;
+        if at >= vars.declared_heads.len() {
+            vars.declared_heads.resize(at + 1, NONE);
+        }
+        vars.declared_heads[at] = vars.declared.len() as u32;
+        vars.declared.push(UsedVar { name, ty, loc });
     }
 }
 
@@ -525,8 +648,41 @@ impl Annot<'_> {
     /// the current level whose serial is its index, named by the [`Name`]
     /// in `name` or by none ([`NONE`]). O(1): one node.
     fn new_var(&mut self, name: u32) -> Ty {
-        let serial = self.c.g.nodes.len() as u32;
         let level = self.c.g.level;
+        self.var_at(name, level)
+    }
+
+    /// `instance env t` of a used variable's node.
+    fn instance(&mut self, ty: Ty) -> Ty {
+        let repr = self.c.g.repr(ty);
+        if self.c.g.nodes[repr.0 as usize].level == GENERIC {
+            self.c.copy(ty)
+        } else {
+            ty
+        }
+    }
+
+    /// `instance_list` of `arity` parameters from `start`: pushed on
+    /// `values`.
+    fn instance_list(&mut self, start: u32, arity: u32) {
+        let first = self.c.g.nodes.len();
+        self.c.g.copy_begin();
+        for at in 0..arity {
+            let param = self.st.params[(start + at) as usize];
+            let copy = self.c.g.copy_ref(param);
+            self.st.values.push(copy);
+        }
+        self.c.g.copy_drain();
+        let cells = !self.c.extras.descriptors.is_empty();
+        if self.c.memo.live != 0 || cells {
+            self.c.extras.copying = true;
+            self.c.link_memorized(first, NONE, cells);
+            self.c.extras.copying = false;
+        }
+    }
+
+    fn var_at(&mut self, name: u32, level: u32) -> Ty {
+        let serial = self.c.g.nodes.len() as u32;
         self.c.g.push(Node {
             head: VAR,
             level,
@@ -580,7 +736,8 @@ impl Annot<'_> {
                     return Err(Stop::Error);
                 }
                 let name = self.st.strs.name(arena, &mut self.scopes.names, *text);
-                let used = self.st.vars.used(name);
+                let universal = self.univar(name);
+                let used = if universal.0 != NONE { universal } else { self.st.vars.used(name) };
                 if used.0 != NONE {
                     // `instance env`: a node that is not generic is
                     // itself (`copy`, compiler/ml/ctype.ml:744-797).
@@ -619,9 +776,6 @@ impl Annot<'_> {
                 }
                 // CHECKER_REWRITE 10.2, decision 5: without the bit the
                 // road is `Annot::unify_params` (R5a-2).
-                if info.reserved & PLAIN_PARAMS == 0 {
-                    return Err(Stop::Declined(Declined::NotBuilt));
-                }
                 self.set_row(node, CoreTypeRow { ty: Ty(NONE), resolved });
                 self.push_frame(node);
                 return Ok(());
@@ -632,9 +786,58 @@ impl Annot<'_> {
                 return Ok(());
             }
             CoreTypeDesc::Ptyp_object(_) => return Err(Stop::Declined(Declined::ObjectType)),
-            CoreTypeDesc::Ptyp_alias(_) => return Err(Stop::Declined(Declined::AliasType)),
+            CoreTypeDesc::Ptyp_alias(inner) => {
+                // typetexp.ml:394-428, before the aliased type.
+                let name = self.scopes.names.intern(&inner.1);
+                let mut t = self.univar(name);
+                let mut new = false;
+                if t.0 == NONE {
+                    let used = self.st.vars.used(name);
+                    if used.0 == NONE {
+                        t = self.new_var(NONE);
+                        self.st.vars.add_used(name, t, core.ptyp_loc.0);
+                        new = true;
+                    } else {
+                        t = self.instance(used);
+                    }
+                }
+                self.set_row(node, NO_ROW);
+                self.push_frame(node);
+                // Below the aliased type's result: the variable, and for
+                // a new one the alias's name (a `Name` in a slot).
+                self.st.values.push(t);
+                if new {
+                    self.st.values.push(Ty(name.0));
+                }
+                return Ok(());
+            }
             CoreTypeDesc::Ptyp_variant(_) => return Err(Stop::Declined(Declined::PolyVariantType)),
-            CoreTypeDesc::Ptyp_poly(_) => return Err(Stop::Declined(Declined::PolyType)),
+            CoreTypeDesc::Ptyp_poly(inner) => {
+                // typetexp.ml:545-549.
+                self.c.g.begin_def();
+                let first = self.st.vars.univars.len();
+                for var in &inner.0 {
+                    #[cfg(test)]
+                    super::super::steps::tick();
+                    let name = self.st.strs.name(arena, &mut self.scopes.names, var.txt);
+                    let first_byte = arena.get_string(var.txt).as_bytes().first().copied();
+                    let named = first_byte.is_some_and(|c| c == b'_' || c.is_ascii_alphabetic());
+                    let ty = self.new_var(if named { name.0 } else { NONE });
+                    self.st.vars.univars.push(UsedVar { name, ty, loc: NONE });
+                }
+                let vars = &mut self.st.vars;
+                for row in (first..vars.univars.len()).rev() {
+                    let at = vars.univars[row].name.0 as usize;
+                    if at >= vars.univar_heads.len() {
+                        vars.univar_heads.resize(at + 1, NONE);
+                    }
+                    vars.univars[row].loc = vars.univar_heads[at];
+                    vars.univar_heads[at] = row as u32;
+                }
+                self.set_row(node, NO_ROW);
+                self.push_frame(node);
+                return Ok(());
+            }
             CoreTypeDesc::Ptyp_package(_) => return Err(Stop::Declined(Declined::PackageType)),
             CoreTypeDesc::Ptyp_extension(_) => return Err(Stop::Declined(Declined::ExtensionType)),
         };
@@ -665,6 +868,8 @@ impl Annot<'_> {
         let arena = self.arena;
         let next = frame.next as usize;
         Ok(match &arena.get_core_type(CoreTypeIdx(frame.node)).ptyp_desc {
+            CoreTypeDesc::Ptyp_alias(inner) => (next == 0).then_some(inner.0),
+            CoreTypeDesc::Ptyp_poly(inner) => (next == 0).then_some(inner.1),
             CoreTypeDesc::Ptyp_tuple(list) => arena.type_list(*list).get(next).copied(),
             CoreTypeDesc::Ptyp_constr((_, list)) => match arena.type_list(*list) {
                 // One `_`: as many times as the type has parameters (the
@@ -736,19 +941,26 @@ impl Annot<'_> {
             // for the instance (CHECKER_REWRITE 10.2, decision 5).
             CoreTypeDesc::Ptyp_constr(_) => {
                 let type_index = self.type_index(frame.node)?;
-                for at in base..self.st.values.len() {
-                    let arg = self.st.values[at];
-                    self.c.lower(arg, level).map_err(|_clash| Stop::Error)?;
+                let plain = self.c.types.info(type_index).reserved & PLAIN_PARAMS != 0;
+                if plain {
+                    for at in base..self.st.values.len() {
+                        let arg = self.st.values[at];
+                        self.c.lower(arg, level).map_err(|_clash| Stop::Error)?;
+                    }
                 }
                 let b = self.c.g.lists.len() as u32;
                 self.c.g.lists.push(Ty(NONE));
                 self.c.g.lists.extend_from_slice(&self.st.values[base..]);
-                self.c.g.push(Node {
+                let constr = self.c.g.push(Node {
                     head: CONSTR | count << 8,
                     level,
                     a: type_index,
                     b,
-                })
+                });
+                if !plain {
+                    self.unify_params(type_index, base as u32, constr)?;
+                }
+                constr
             }
             CoreTypeDesc::Ptyp_arrow(arrow) => {
                 let (first, _, _) = &**arrow;
@@ -786,6 +998,87 @@ impl Annot<'_> {
                     b,
                 })
             }
+            CoreTypeDesc::Ptyp_alias(_) => {
+                // typetexp.ml:402-427, after the aliased type.
+                let t = self.st.values[base];
+                let ty = self.st.values[base + count as usize - 1];
+                if self.c.unify_var(t, ty).is_err() {
+                    return Err(Stop::Error);
+                }
+                if count == 2 {
+                    ty
+                } else {
+                    let name = self.st.values[base + 1].0;
+                    let t = self.instance(t);
+                    let proxy = self.c.g.repr(t);
+                    let found = self.c.g.nodes[proxy.0 as usize];
+                    if found.tag() == VAR && found.a == NONE {
+                        self.c.g.write(proxy, Node { a: name, ..found });
+                    }
+                    t
+                }
+            }
+            CoreTypeDesc::Ptyp_poly(inner) => {
+                // typetexp.ml:550-571.
+                let body = self.st.values[base];
+                let first = self.st.vars.univars.len() - inner.0.len();
+                let vars = &mut self.st.vars;
+                for row in first..vars.univars.len() {
+                    let at = vars.univars[row].name.0 as usize;
+                    vars.univar_heads[at] = vars.univars[row].loc;
+                }
+                self.c.g.end_def();
+                self.c.generalize(body);
+                // `deep_occur v ty` for every variable of the list: one walk.
+                let generation = self.c.fresh_marks();
+                self.c.g.work.clear();
+                self.c.g.work.push(body);
+                while let Some(ty) = self.c.g.work.pop() {
+                    let ty = self.c.g.repr(ty);
+                    if self.c.marks[ty.0 as usize] == generation {
+                        continue;
+                    }
+                    #[cfg(test)]
+                    super::super::steps::tick();
+                    self.c.marks[ty.0 as usize] = generation;
+                    let reached = self.c.g.nodes[ty.0 as usize];
+                    self.c.g.children(reached, false);
+                }
+                let b = self.c.g.lists.len() as u32;
+                self.c.g.lists.push(body);
+                let mut bound = 0;
+                for row in first..self.st.vars.univars.len() {
+                    #[cfg(test)]
+                    super::super::steps::tick();
+                    let v = self.c.g.repr(self.st.vars.univars[row].ty);
+                    if self.c.marks[v.0 as usize] != generation {
+                        continue;
+                    }
+                    let found = self.c.g.nodes[v.0 as usize];
+                    if found.tag() != VAR || found.level != GENERIC {
+                        return Err(Stop::Error);
+                    }
+                    let a = self.c.extras.univar(found.a);
+                    self.c.g.write(v, Node { head: TUPLE | EXTENDED, level: GENERIC, a, b: 0 });
+                    self.c.g.lists.push(v);
+                    bound += 1;
+                }
+                self.st.vars.univars.truncate(first);
+                let a = self.c.extras.descriptors.len() as u32;
+                self.c.extras.descriptors.push(ExtraDescriptor::Poly);
+                let poly = self.c.g.push(Node {
+                    head: TUPLE | EXTENDED | (bound + 1) << 8,
+                    level: GENERIC,
+                    a,
+                    b,
+                });
+                // `unify_var env (newvar ()) ty'` (571).
+                let level = self.c.g.level;
+                if self.c.lower(poly, level).is_err() {
+                    return Err(Stop::Error);
+                }
+                poly
+            }
             _ => return Err(NOT_A_FRAME),
         })
     }

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 <jfrolich@gmail.com>
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>
@jfrolich

Copy link
Copy Markdown
Owner Author

First-pass checklist review at 39a933e (a checklist for the final reviewer, not an approval).

First-pass review (checklist, not an approval):

Setup: git fetch origin; D=origin/ocaml-to-rust-rewrite...origin/checker-rewrite-r5a-2-annotations; git diff $D > $TMPDIR/pr.diff; the head tree and compiler/ml came from git archive origin/checker-rewrite-r5a-2-annotations. The prototype was cut from comment 7257628931 (from the line // R5A-PROTOTYPE R5a-2, second to the first closing fence after the first diff --git) into proto.diff and applied to git archive def93a8aa2 compiler-rust/src/tc with patch -p1 --dry-run and then patch -p1. It applies cleanly: patching file 'compiler-rust/src/tc/walk/typetexp.rs', with no offset or fuzz messages. All OCaml line numbers below are the branch's compiler/ml. This host has no cargo and no rg; everything here is reading, grep -E, sed, git and gh.

1. Scope — PASS

git diff --stat $D gives 5 files: changes/checker-rewrite-r5a-design-2.internal.md +1, compiler-rust/docs/CHECKER_REWRITE.md +769, src/tc/mod.rs +2, src/tc/r5a2_tests.rs +1347 (new), src/tc/walk/typetexp.rs 136 lines changed.

  • 10.12 "R5a-2 as designed" is CHECKER_REWRITE.md:12539-13010 on the head. Decisions 13-21 are at 12567-12830; 10.12.2-10.12.6 follow.
  • "Task R5a-2a" is in 10.10, CHECKER_REWRITE.md:12201-12435.
  • r5a2_tests.rs: grep -c '#\[ignore = "R5a-2 build"\]' gives 23, and grep -c '^#\[test\]' gives 29. That is 23 ignored tests, 5 old_checker_* pins and ignored_tests_name_the_slices_they_reach.
  • typetexp.rs: two new fields, reset(level), three new todo! functions, and doc comments (section 11).
  • mod.rs: #[cfg(all(test, debug_assertions))] mod r5a2_tests;.
  • Not done, as the body says: M3, R5a-2b (paths and other units, on paper only), the R5a-1 wrong-body tests the coordinator asked for, and a char-vs-int test.
  • Done beyond the list: the two rows of 10.7, the State: line of 10.11 item 4, and the changes fragment.

2. Default path — PASS

tc/mod.rs:57-58: pub(crate) fn check_unit() -> Result<Infallible, Declined> { Err(Declined::NotBuilt) }. Outside src/tc and src/types, grep -rn "transl_type\b\|Annot {" finds no caller. Decls::reset (decl.rs:274) is todo!("R5a-3"), so nothing calls TypeVars::reset either. No changed function runs in an ordinary build, so the body needed no measurement and gives none.

3. Engineering standard — PASS for the diff; notes on the prototype

Greps were run over the + lines of each source file (git diff $D -- <file> | grep '^+').

  • (a) Costs: univar, declared and add_declared state O(1); reset, globalize, unify_params, transl_simple_type and transl_type_scheme state their costs (quoted in section 11). OK.
  • (b) Step tests: each loop the prompt names has a 10,000 test (section 17). Loops in the prototype that never tick are invisible to every step test:
    • the head-writing and head-restoring loops of the polymorphic arm (proto.diff lines 327-334 and +400:13-16);
    • drop_univars;
    • the loop of instance_list, where only copy_ref ticks;
    • the sort.
  • (c) HashMap, HashSet, BTreeMap: none.
  • (d) Allocation outside tests: none in typetexp.rs. The prototype grows only pools: univar_heads and declared_heads .resize, g.lists.push, extras.descriptors.push, st.values.push.
  • (e) Locks, atomics, thread_local, RefCell: none.
  • (f) Repeated walks: the polymorphic arm walks the body three times — generalize, then the marking walk, then lower. The marking walk cannot be folded into generalize: generalize stops at nodes at or below the current level, and deep_occur must see a lowered binder variable below such a node (that is a Cannot_quantify). Defensible.
  • (g) No new struct or enum. walk::typetexp::tests::sizes is unchanged (CoreTypeRow 8, UsedVar 12, Frame 12, Policy 1). TypeVars is not size-pinned; it is one per worker.
  • (h) Added: #[inline] ×2 and todo!("R5a-2") ×3 (the new skeleton functions) in typetexp.rs; #[ignore = "R5a-2 build"] ×23 in the tests. No allow(, unsafe or unimplemented!.

4. Tests and oracles — PASS

No existing test, expectation, fixture, ratchet or script is touched. The diff has 5 files (section 1), and r5a_tests.rs is not among them. Weakenings come later, by the prompt: it lets the builder delete a_type_without_plain_parameters_is_declined and the DECLINED row ("int as 'a", Declined::AliasType) (section 19c).

5. New scripts and fixtures — PASS

None. The new test file is in --lib, and the compiler-tests log runs it: test tc::r5a2_tests::old_checker_aliases_are_pinned ... ok, among others.

6. Privacy — PASS

grep -n -i -E "tella|submodule\.nl|rescript-bench-corpus|/Users/|opensession|jake" pr.diff returns 0 hits.

7. Changelog — PASS

changes/checker-rewrite-r5a-design-2.internal.md starts with "- C". CHANGELOG.md does not appear in the diff.

8. Numbers — UNCLEAR

  • "336 lines (314 added, 22 removed)": on the posted second prototype grep -c '^+' proto.diff gives 314 and grep -c '^-' gives 21 (headers included). The figure is off by one, probably taken from the first prototype.
  • The test-count table (21/1, 422/41, 47/2, 29/0, 27/24, 49/2): commands are given, but every result is a summary; no raw output is pasted.
  • "39 breaks, 35 caught": a table only, no output.
  • Step counts (70,001, 20,015, 40,003, 60,001, 70,006, 139,995): written in test doc comments, no output.
  • CI is not quoted. For the head, see section 23.

9. Focused tests — not run (host review)

10. Where I would look hardest

  1. enforce_constraints is unify_var in OCaml, not unify. Ctype.enforce_constraints calls subst (ctype.ml:1339). subst unifies through !unify' (ctype.ml:1129-1130), and unify' is set to unify_var (ctype.ml:2767: let _ = unify' := unify_var). Decision 19, the doc of unify_params, the prompt ("a second session and unify in the second") and the prototype (self.c.unify(param, arg), proto.diff line 89) all say unify. By my reading the two cannot differ in R5a: the instance is fresh, and at this point no universal variable is a Tunivar. Still, the text is wrong, and no test tells them apart.
  2. The globalize sort. sort_unstable_by permutes TypeVars::used in place, while TypeVars::heads[name] still holds the row indices from before the sort. Until forget_used runs, TypeVars::used(name) answers wrong rows. On the Err and decline exits of the prototype's globalize, forget_used is not called (proto.diff lines 116-139). Nothing reads used afterwards in R5a, because transl_simple_type forgets first. But no doc comment says the heads go stale, and R5b's split of globalize (decision 17) would meet it. Also, no test catches a second loop run in source order (section 17).
  3. The exact-fit step bounds, and the record-field wrapper. Every per-element bound equals the prototype's count plus a slack of 100 steps at 10,000 elements (for example 70,001 against 70,100). A correct body that ticks once more per element fails, and the prompt forbids changing a bound, so the builder must STOP. Separately, transl_label calls Ast_helper.Typ.force_poly before transl_simple_type (typedecl.ml:194-195). So in OCaml every record field without a binder goes through the polymorphic arm with [] and becomes Tpoly(t, []) (typetexp.ml:569). The FIELDS comment "A field without a binder is no Ptyp_poly: the type itself" is true only of the parse tree, and field_type's doc says "as transl_label runs it (typedecl.ml:195)" while leaving out line 194. This is R5a-4's to decide.

11. Files — PASS

(a) The diff touches no body that R5a-1 built: walk, enter, child, leave, find_type, new_var, forget_used, used, add_used, StrNames::name and Decls::predefine are all unchanged, and r5a_tests.rs is not in the diff. From git diff $D -- compiler-rust/src/tc/walk/typetexp.rs, the only changed lines outside doc comments are:

+    pub univar_heads: Vec<u32>,
+    pub global_level: u32,
-    pub fn reset(&mut self) {
+    pub fn reset(&mut self, level: u32) {
+    #[inline]
+    pub fn univar(&self, name: Name) -> Ty {        todo!("R5a-2")
+    #[inline]
+    pub fn declared(&self, name: Name) -> Ty {      todo!("R5a-2")
+    pub fn add_declared(&mut self, name: Name, ty: Ty, loc: u32) {   todo!("R5a-2")

(b) The two new fields of TypeVars (typetexp.rs:86-95), with their doc comments:

    /// 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<u32>,
    /// `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,
  • #[derive(Default)] (typetexp.rs:69) initialises them: an empty univar_heads and global_level = 0. OCaml starts with global = ref 1 (ctype.ml:116). Every caller resets first (transl_type_scheme; R5a-3 per declaration, typedecl.ml:316 and 420), so this is harmless unless something globalizes before a reset. Nothing states that invariant.
  • In the prototype, global_level is written only by reset. univar_heads is put back by the binder's leave and set to NONE by drop_univars (called from reset, from transl_simple_type at entry, and from transl_type on Err).
  • No size_of test moved.

(c) Signatures and doc comments, against the body's "Skeleton changes":

  • The only changed signature is reset(&mut self) → reset(&mut self, level: u32).
  • The doc of univars adds: "A row's loc is not a location: it is the entry of univar_heads the row replaced".
  • unify_params: old "unify_param an argument … (unify_var when the type has no manifest or a generic one, else unify)"; new "Checker::unify_var of each instance … the unify of 377-379 is for a manifest that is not generic, which only a stub … has", plus "a second copy session … and Checker::unify" (see finding 10.1), the NotBuilt decline, the instances on values, and the cost.
  • globalize: old "a variable whose unification … fails is skipped without an error (712-717). O(v log v)"; new: the decline Declined::PolyType, the two halves, the reverse order of the second half, and the cost.
  • transl_simple_type: now says what it empties and that make_fixed_univars does nothing before R6b.
  • transl_type_scheme: now lists its steps and "The level is given back on Err too".
  • This matches the body's list item for item.

(d) mod.rs gains one item, written as two lines (the cfg attribute and mod r5a2_tests;). Nothing else changes.

12. The alias arm (decisions 14, 15) — PASS, kernel side partly UNCLEAR

typetexp.ml:394-428:

394  | Ptyp_alias (st, alias) ->
395    let cty =
396      try
397        let t =
398          try List.assoc alias !(univars ())
399          with Not_found ->
400            instance env (fst (Tbl.find alias !(used_variables ())))
401        in
402        let ty = transl_type env policy st in
403        (try unify_var env t ty.ctyp_type
404         with Unify trace ->
405           let trace = swap_list trace in
406           raise (Error (styp.ptyp_loc, env, Alias_type_mismatch trace)));
407        ty
408      with Not_found ->
409        let t = newvar () in
410        used_variables () :=
411          Tbl.add alias (t, styp.ptyp_loc) !(used_variables ());
412        let ty = transl_type env policy st in
413        (try unify_var env t ty.ctyp_type
414         with Unify trace ->
415           let trace = swap_list trace in
416           raise (Error (styp.ptyp_loc, env, Alias_type_mismatch trace)));
417        let t = instance env t in
418        let px = Btype.proxy t in
419        (match px.desc with
420        | Tvar None ->
421          Btype.log_type px;
422          px.desc <- Tvar (Some alias)
423        | Tunivar None ->
424          Btype.log_type px;
425          px.desc <- Tunivar (Some alias)
426        | _ -> ());
427        {ty with ctyp_type = t}
Step 10.12 Prototype
398 univars, no instance Annot::univar let mut t = self.univar(name) (proto 289) SAME
400 used var, instance used, copied if generic t = self.instance(used) (298); helper instance copies only a generic representative (+227-235) SAME
409-411 fresh UNNAMED var at the current level, entered BEFORE the child, at the alias node's location same new_var(NONE) (the current level); add_used(name, t, core.ptyp_loc.0) in enter (294-295) SAME
402/412 child frame's one child child: Ptyp_alias(inner) => (next == 0).then_some(inner.0) (346) SAME
403/413 unify_var t ty; error at the alias node Checker::unify_var; Stop::Error if self.c.unify_var(t, ty).is_err() { return Err(Stop::Error) } (+387-393). Stop has no location SAME
407 found: answers ty the aliased node if count == 2 { ty } SAME
417 instance env t itself self.instance(t) SAME
418-426 proxy Tvar None named, no validate_name same, Graph::write if found.tag() == VAR && found.a == NONE { write a: name } SAME
423-425 Tunivar None not mentioned beyond "no test" MISSING unreachable in R5a: t's representative can be a universal variable only after its binder is closed, and a binder sits only in a field

The name is interned once in enter (self.scopes.names.intern(&inner.1), 288) and carried in a value slot (values.push(Ty(name.0)), 307). New versus found is told by count 3 or 2. Matches the design.

Decision 15, OCaml side, by reading 2748-2765, 2240-2242 and occur_rec 1384-1408 (unify2/unify3 were not pasted):

  • array<'b> as 'b: Tvar, Tconstr when deep_occur (2753) → unify → 2240 → unify2. array does not expand, so occur → occur_rec: Tconstr → child == ty0 → raise Occur → try_expand_head raises Cannot_expand → Occur. Refused.
  • k<'b> as 'b with k abstract: the same path. Refused, which agrees with the fact.
  • id<'b> as 'b: 2753 → unify → unify2 expands id<t> to t, so both heads are t and nothing is linked. t stays an unnamed variable, and 420-422 names it b. That prints 'a => int, as the fact says.
  • p<'b> as 'b with p<'a> = int: unify2 expands to int. Then, in unify3's Tvar arm, occur t p<t> hits t inside p → Occur → the expansion int → no occurrence. t is linked to the UNEXPANDED p<t>, so the type names itself, as the fact says.

Kernel side: Checker::unify_var (unify.rs:2201) sends a non-variable target with children to binding_occurrence(var, ty, occur_first, routed = target is CONSTR). When the scan finds the variable it answers Ok(true), and the kernel calls self.unify(var, ty), which is OCaml's 2753 routing. I did not follow the kernel's unify2/unify3 arms; the body says they were run on the prototype. The node the kernel holds for ph<'b> as 'b is ph<@self>: SELF_ALIAS_PHANTOM is &0((&1(ph<@1>)) => &2(int)), and old_checker_self_aliases_are_pinned observes it on today's checker.

Walks without marks on a node that names itself:

  • Graph::generalize (level.rs:73) writes GENERIC before pushing the children and skips GENERIC nodes: ends.
  • Graph::lower (level.rs:53) writes the level before the children and skips level <= target: ends.
  • Graph::copy_ref / copy_drain (template.rs:17-110) write forward before the children: ends.
  • Graph::capture (template.rs:429) writes forward in capture_ref before pushing: ends, by reading; never run.
  • The test canonicaliser keeps a nodes list: ends.
  • The kernel's published canonical printer (canonical/printed.rs) and the variance walks of R5a-7: not read, UNCLEAR. R5a-9 is told to decline (decision 15).

Objects: Ptyp_object(_) => return Err(Stop::Declined(Declined::ObjectType)) is in enter (typetexp.rs:634 on trunk). An alias over an object declines when the child is entered, before any field is translated. Confirmed.

13. The polymorphic arm (decision 18) — PASS

545  | Ptyp_poly (vars, st) ->
546    let vars = List.map (fun v -> v.txt) vars in
547    begin_def ();
548    let new_univars = List.map (fun name -> (name, newvar ~name ())) vars in
549    let old_univars = !(univars ()) in
550    univars () := new_univars @ !(univars ());
551    let cty = transl_type env policy st in
552    let ty = cty.ctyp_type in
553    univars () := old_univars;
554    end_def ();
555    generalize ty;
556    let ty_list =
557      List.fold_left
558        (fun tyl (name, ty1) ->
559          let v = Btype.proxy ty1 in
560          if deep_occur v ty then
561            match v.desc with
562            | Tvar name when v.level = Btype.generic_level ->
563              v.desc <- Tunivar name;
564              v :: tyl
565            | _ -> raise (Error (styp.ptyp_loc, env, Cannot_quantify (name, v)))
566          else tyl)
567        [] new_univars
568    in
569    let ty' = Btype.newgenty (Tpoly (ty, List.rev ty_list)) in
570    unify_var env (newvar ()) ty';

In order:

  • begin_def → self.c.g.begin_def() (proto 315). SAME.
  • newvar ~name → named = first_byte.is_some_and(|c| c == b'_' || c.is_ascii_alphabetic()), new_var(if named { name.0 } else { NONE }) (321-323). That is validate_name, typetexp.ml:224-228 (strict_ident). SAME.
    • The prompt (12424-12428 of the doc) tells the builder: "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."
    • For a binder written '_a, OCaml names the variable _a: 306-307 is in the Ptyp_var arm only, so it is reached by a USE, before the lookup at 308. The prototype keeps trunk's starts_with('_') → Err in front of its new univar lookup (typetexp.rs:579 on trunk). SAME.
  • 550/553: rows pushed in source order, then heads written from last to first (for row in (first..len).rev(), 327-334); restored first to last in leave (+400:13-16). SAME.
  • 554-555: end_def then generalize(body) (+400:17-18). SAME.
  • 556-567: one marking walk (+400:20-33), then the rows in SOURCE order (for row in first..len). An unmarked row is skipped; a marked row is rewritten if it is VAR and GENERIC, else Err(Stop::Error). Same verdict and the same first failing variable as the fold.
  • 569: the list is pushed in source order, which equals List.rev of the consed list. SAME.
  • 570: unify_var env (newvar ()) ty'. ty' is a Tpoly, not a Tconstr, so this takes 2754: occur (cannot find the new variable), then update_level env !current_level ty', then a link nobody reads. That is Checker::lower(poly, level) (+400:62-66). When types.scoped == 0 that is Graph::lower, which cannot fail. With scoped types it can fail, and OCaml would let Unify escape (570 has no handler); in R5a this is unreachable.

Duplicate binder names, 'a 'a. 'a => 'a: List.assoc over new_univars @ old finds the FIRST. The prototype writes heads from the last row to the first, so the first row's head is the one left. The Tpoly list is [v1], v2 is dropped, and the prototype gives the same. No test tells it from source order: the canonical text is the same.

Aliased binders, 'a 'b. ('a as 'b) => int: the alias finds 'b in univars, and unify_var(b, a) links b to a, both in OCaml and in the kernel (g.link(var, ty)). The fold makes a a universal variable; then proxy b is a, which is now a Tunivar, so Cannot_quantify('b, …) with "already bound to another variable", at the whole type (565). The prototype gives Err on row b. SAME; the new checker keeps no message.

Marks: fresh_marks() gives a new generation of Checker::marks (unify.rs:3069), and the walk uses Graph::work. generalize has just emptied work. No copy session is open (instance_list drains its own), no relation is in progress, and the translation's two stacks are in AnnotState, not in marks. Cost: n (generalize) + n (marks) + u + n (lower), as 10.12.3 says.

Nested binder, by reading only: the inner begin_def is at L+2 and its generalize stops at nodes ≤ L+1, so the outer variable stays a Tvar at L+1. The inner poly is lowered to L+1 and generalized again by the outer arm. first = univars.len() - inner.0.len() holds because the inner leave truncated to its own first. Right by reading.

14. globalize (decisions 16, 17) — PASS with notes

705 let globalize_used_variables env fixed =
706   let r = ref [] in
707   Tbl.iter
708     (fun name (ty, loc) ->
709       let v = new_global_var () in
710       let snap = Btype.snapshot () in
711       if
712         try
713           unify env v ty;
714           true
715         with _ ->
716           Btype.backtrack snap;
717           false
718       then (
719         try r := (loc, v, Tbl.find name !(type_variables ())) :: !r
720         with Not_found ->
721           if fixed && Btype.is_Tvar (repr ty) then
722             raise (Error (loc, env, Unbound_type_variable ("'" ^ name)));
723           let v2 = new_global_var () in
724           r := (loc, v, v2) :: !r;
725           type_variables () := Tbl.add name v2 !(type_variables ())))
726     !(used_variables ());
727   used_variables () := Tbl.empty;
728   fun () ->
729     List.iter
730       (function
731         | loc, t1, t2 -> (
732           try unify env t1 t2
733           with Unify trace -> raise (Error (loc, env, Type_mismatch trace))))
734       !r
  • Byte order: sort_unstable_by(|l, r| names.text(l.name).as_bytes().cmp(names.text(r.name).as_bytes())), guarded by if used.len() > 1 (proto 104-110). The names are distinct, so unstable equals stable. sort_unstable does not allocate, and 0 or 1 rows pay nothing. OK; but see finding 10.2 on the stale heads.
  • Per row:
    • var_at(NONE, global), then speculate, then self.c.unify(v, used.ty). On Err: self.c.restore(token); return Err(Stop::Declined(Declined::PolyType)). On Ok: keep (116-122).
    • Then declared(name): if absent, the fixed-and-VAR test gives Err(Stop::Error), else add_declared(name, var_at(NONE, global), used.loc).
    • Then the second loop for row in (0..len).rev() with unify(used.ty, declared(name)), then forget_used.
  • The unify called at 713 is the 2773 wrapper (2769-2771: current_univar_pairs () := pairs with []).
  • Order: r is consed in name order and iterated from its head, so reverse name order. The prototype's .rev() over the sorted rows is the same order.
  • (a) The decline happens with the speculation restored. The nodes made (v) and earlier rows' kept unifications and declared rows remain; 10.2 decision 1 lists nodes and links as emptied by Decls::reset. The test asserts speculation_depth == 0. OK.
  • (b) When can unify env v ty fail? v is new at the global level, so Tvar _, _ -> unify1_var (2242), unless ty is a Tconstr that holds v (it cannot: v is new).
    • unify1_var (2216-2225) can raise from occur (impossible), from occur_univar env t2 (ty is or holds a universal variable that is not bound inside it), or from update_level (only with scoped types: none in R5a; a node lower than the global level is simply left alone).
    • No other exception, by reading unify (2227-2274) and occur (1488, 1467-1484). occur_full maps Occur to Unify [] and re-raises anything else, and nothing else is raised here.
    • Smallest annotations: 'a. ('a as 'b) => int, where 'b IS the universal variable, and 'a. (array<'a> as 'b) => int, where 'b holds it, both as a record field. CONFIRMED.
  • Decision 17's second loop: the same order as OCaml, as shown above. OK.
  • Note: 10.2 decision 8 (CHECKER_REWRITE.md:11485-11499) still says "skips one that does not unify … goes on WITHOUT an error". It was not amended or given a pointer to decision 16, and the prompt tells the builder to read it.

15. transl_simple_type, transl_type_scheme, make_fixed_univars — PASS

677 let rec make_fixed_univars ty =
678   let ty = repr ty in
679   if ty.level >= Btype.lowest_level then (
680     Btype.mark_type_node ty;
681     match ty.desc with
682     | Tvariant row -> … (row_fixed = true when row_more is a Tunivar) …
698       Btype.iter_row make_fixed_univars row
699     | _ -> Btype.iter_type_expr make_fixed_univars ty)
701 let make_fixed_univars ty =
702   make_fixed_univars ty;
703   Btype.unmark_type ty
736 let transl_simple_type env fixed styp =
737   univars () := [];
738   used_variables () := Tbl.empty;
739   let typ = transl_type env (if fixed then Fixed else Extensible) styp in
740   globalize_used_variables env fixed ();
741   make_fixed_univars typ.ctyp_type;
742   typ
744 let transl_simple_type_delayed env styp =
745   univars () := [];
746   used_variables () := Tbl.empty;
747   let typ = transl_type env Extensible styp in
748   make_fixed_univars typ.ctyp_type;
749   (typ, globalize_used_variables env false)
751 let transl_type_scheme env styp =
752   reset_type_variables ();
753   begin_def ();
754   let typ = transl_simple_type env false styp in
755   end_def ();
756   generalize typ.ctyp_type;
757   typ
  • make_fixed_univars writes only Tvariant rows; variants decline. Leaving it out is right, and the doc of transl_simple_type and decision 17 say so.
  • The prototype's transl_simple_type is drop_univars; forget_used; transl_type; globalize. declared is not touched, as in OCaml.
  • The prototype's transl_type_scheme is reset(level); begin_def; transl_simple_type(false); end_def; result?; generalize. SAME.
  • Exits, with entry level L:
    • transl_type on Err sets g.level = L (proto 45, 50) and drops univars.
    • globalize's exits do not move the level.
    • transl_type_scheme calls end_def before ?.
    • Every exit returns at its entry level. OK.
  • Difference: OCaml's reset_type_variables (typetexp.ml:213-216) also calls Ctype.reset_reified_var_counter () and does NOT empty univars or used_variables. The design's reset empties both and has no counter. Unobservable through transl_type_scheme. Whether the reified-variable counter matters is for R5a-3, and is NOT CHECKED.
  • transl_simple_type_delayed is left to R5b: decision 17 says R5b splits globalize at the line between the loops, with rows of its own.

16. unify_params and enforce_constraints (decision 19) — DOUBT on the text, PASS on behaviour

372    let args = List.map (transl_type env policy) stl in
373    let params = instance_list decl.type_params in
374    let unify_param =
375      match decl.type_manifest with
376      | None -> unify_var
377      | Some ty ->
378        if (repr ty).level = Btype.generic_level then unify_var else unify
379    in
380    List.iter2
381      (fun (sty, cty) ty' ->
382        try unify_param env ty' cty.ctyp_type
383        with Unify trace ->
384          raise (Error (sty.ptyp_loc, env, Type_mismatch (swap_list trace))))
385      (List.combine stl args) params;
386    let constr = newconstr path (List.map (fun ctyp -> ctyp.ctyp_type) args) in
387    (try Ctype.enforce_constraints env constr
388     with Unify trace ->
389       raise (Error (styp.ptyp_loc, env, Type_mismatch trace)));
ctype.ml
 891 let instance_list env schl =
 892   with_copy_session (fun () ->
 893       let env = gadt_env env in
 894       List.map (fun t -> copy ?env t) schl)
1333 let enforce_constraints env ty =
1334   match ty with
1335   | {desc = Tconstr (path, args, _abbrev); level} -> (
1336     try
1337       let decl = Env.find_type path env in
1338       ignore
1339         (subst env level Public (ref Mnil) None decl.type_params args
1340            (newvar2 level))
1341     with Not_found -> ())
1342   | _ -> assert false
1113 let subst env level priv abbrev ty params args body =
1116   current_level () := level;
1118     let body0 = newvar () in
1127     let params', body' = instance_parameterized_type params body in
1129     !unify' env body0 body';
1130     List.iter2 (!unify' env) params' args;
2767 let _ = unify' := unify_var
  • When is the manifest not generic? Only for a stub of a recursive group: enter_type gives type_manifest = Some (Ctype.newvar ()) (typedecl.ml:89-92) and type_params = List.map (fun _ -> Btype.newgenvar ()) (85), so a stub has PLAIN_PARAMS and never reaches unify_params. 10.11 item 2 has R5a-3 record why unify and unify_var agree there. No test holds it. OK.
  • The error location (383-386, the argument's) is not represented (Stop::Error). Fine.
  • enforce_constraints is a SECOND instance (at the node's level, 1116) unified with the arguments, through unify_var (1130 and 2767). Finding 10.1 is the unify versus unify_var mismatch.
  • Can it fail after the first loop? By reading, no. For constraint 'a = list<'b>, the first loop leaves the argument list<b1> and the second unifies list<b2> with it, binding b2 to b1. For a parameter constrained through another constrained type (cl2<'a> = int constraint 'a = cl<'b>), the declared parameter is cl<list<c>>; the second instance unifies path by path with the first's result. CONFIRMED by reading; no program.
  • The three programs, through the prototype:
    • sh<'x, array<'v>>: the instance is [q, q]. unify_var(q, X) links q to X; unify_var(q≡X, array<V>) links X to array. The node is sh<array<V>, array<V>>, one node twice. The second loop ([r, r]) changes nothing. This matches the fact and PARAMETERS &0(sh<&1(array<'0:v>), @1>).
    • (sh<'x, 'y>, 'x) => 'y: q links to X, then X (a VAR) links to Y (g.link(var, ty)), so there is one variable. This matches the fact (sh<'a,'a>,'a) => 'a.
    • cl<'x> => 'x: the instance is list<b1>, which is not a VAR, so unify_var goes to unify and X is linked to list<b1>. The result is cl<list<'a>> => list<'a>, as the fact says.

17. The tests — PASS, with uncaught wrong bodies

The canonicaliser (canon, r5a2_tests.rs:449-549) prints node identity (&n, @n), variables 'n and universal variables !n in one numbering with :name, and the universal list poly[..] in slot order. It prints no levels.

  • old_checker_aliases_are_pinned: ALIASES lines and ALIAS_CLASHES refused on today's checker. Observed.
  • old_checker_self_aliases_are_pinned: 6 refused; the id and ph lines. Observed.
  • old_checker_polymorphic_types_are_pinned: FIELDS and OBJECT_PROGRAMS. Observed.
  • old_checker_parameters_are_pinned: PARAMETERS. Observed.
  • old_checker_globalize_programs_are_pinned: G1-G6 and the scheme. Observed.
  • ignored_tests_name_the_slices_they_reach: a structural check.
  • aliases_agree_with_todays_checker: the ALIASES canonical lines (expected values observed live), empty stacks, level 1.
  • an_alias_bound_to_two_types_is_an_error: Err(Error), empty stacks. By hand, agrees with OCaml.
  • a_self_alias_is_refused_as_in_ocaml: 6 × Err; id prints ('0:b) => int. The constant is observed.
  • a_phantom_self_alias_is_a_type_that_names_itself: the ph line, then generalize and copy end, and the copy prints the same.
  • an_alias_enters_its_variable_first_at_the_alias_location: used = [b, a]; loc is the alias node's; the row is the aliased node; levels; 4 nodes. By hand.
  • polymorphic_fields_agree_with_todays_checker: FIELDS (observed); the decline of 'a. ('a as 'b) => 'b with depth 0.
  • a_polymorphic_type_binds_the_variables_that_occur: head bits, level 1, one univar named a. By hand.
  • a_universal_variable_hides_a_used_variable_inside_its_binder: node identity across three translations. By hand.
  • an_error_inside_a_binder_leaves_no_binder: level, univars, stacks, then the next 'a. By hand.
  • used_variables_are_globalized_in_the_order_of_their_names: declared = [a, b, zz]; global level; heads all NONE. By hand.
  • globalized_variables_are_at_the_global_level: the level is 2, and 'q is not globalized. By hand.
  • the_fixed_policy_refuses_a_variable_that_is_not_declared: four cases. By hand, agrees with G1.
  • a_name_bound_to_two_types_by_two_annotations_is_an_error: int twice is one class; string is Err. By hand.
  • a_scheme_is_generalized: the line (observed); generic; two copies; the next item's 'a; level on Err.
  • reset_forgets_the_declared_variables: global_level 5 and 2; heads NONE. By hand.
  • parameters_without_plain_params_agree_with_todays_checker: PARAMETERS. Observed.
  • the_declared_parameters_are_instantiated_not_bound: the declared parameter stays VAR/GENERIC; 'x is lowered. By hand.
  • The six step tests: by hand, with bounds fitted to the prototype.

Re-derived wrong bodies, two per function:

  • Alias arm: no unify_var → an_alias_bound_to_two_types_is_an_error. Variable entered at leave instead of at enter → an_alias_enters_its_variable_first_at_the_alias_location (the order [b, a]). Note: if the body still finds 'b in used at leave, array<'b> as 'b stays refused, so the self-alias test alone would not catch that variant.
  • Polymorphic arm: deep_occur once per variable → ten_thousand_universal_variables. No final lower → a_polymorphic_type_binds… (level).
  • globalize: no sort → used_variables_are_globalized…. The silent skip → polymorphic_fields….
  • transl_simple_type: used variables not emptied first → globalized_variables_are_at_the_global_level ('q).
  • transl_type_scheme: no generalize → a_scheme_is_generalized.
  • unify_params: declared nodes unified → the_declared_parameters_are_instantiated_not_bound. One session per parameter → parameters… (sh<int, string>).
  • reset: global_level = level → reset_forgets….

Wrong bodies that NO test catches, beyond the four the body names:

  1. globalize's second loop in forward order. Every test's used names are distinct variables, and either order gives the same classes. Decision 17 says the order "can show"; no test shows it.
  2. The binder's name WITHOUT validate_name (no binder in FIELDS has an invalid name).
  3. unify instead of unify_var in the first loop of unify_params.
  4. The second loop at the current level instead of the node's: the same level in every test.
  5. TypeVars::reset not dropping univars: always empty there.
  6. Annot::univar without the is_empty() test: it does not tick.
  7. Tunivar None proxy naming: unreachable.

Step tests: every one asserts small >= 1_000, large <= 11 * small, and large <= per_element * 10_000 + 100 (r5a2_tests.rs:1115-1128; the nested, globalized and shared tests inline the same). The bounds against the prototype's counts are: aliases 70,100 vs 70,001; uses 20,100 vs 20,015; nested 40,100 vs 40,003; globalized 60,100 vs 60,001; universal 70,100 vs 70,006; shared 140,100 vs 139,995. So any doubled walk that ticks fails all five that were not broken, by reading. A doubled loop that does not tick (the heads loops, drop_univars, the sort, instance_list's own loop) fails none. Only steps::tick() counts.

Pins against the facts: no pin differs.

  • ALIASES row 2 is (int, int) => int, and (('a as 'b) as 'c, 'c) => 'b is ('a, 'a) => 'a.
  • FIELDS: 'a 'b. ('a as 'b) => int is None and 'a. (int as 'a) => int is None.
  • OBJECT_PROGRAMS: P1 and P2 are accepted, with poly[] !0:a outside its binder.
  • PARAMETERS matches all three sh/cl facts.
  • G1 and G5 are refused; G4 is [&0(int)].
  • The canonical text keeps variable names ('0:a) where OCaml's printer prints 'a for 'zz. That is a printer difference, not a pin of the type.
  • No test pins char distinct from int. No old_checker_* test pins a variable with an invalid name; only the alias proxy '\"1a", which is OCaml-right by 417-426.

18. The prototype arm by arm — PASS

  • Code that the design text does not mention:
    • a new private var_at(name, level) that new_var calls; 10.10 forbids copying it as is and asks for one shared helper;
    • the name rule written out a second time in the binder arm (321-322);
    • instance used by the alias arm only, while the variable arm keeps its inline copy (the prompt asks for one helper);
    • drop_univars (not named in the doc).
  • The reverse (design text the prototype does not do): Tunivar None naming (section 12).
  • No unwrap, expect, unreachable! or panic! in the prototype (grep '^+' proto.diff | grep -E "unwrap|expect\(|unreachable!|panic!" is empty). Panics possible only on broken invariants:
    • indexing univars.len() - inner.0.len(), values[base + count - 1], params[(start + at)] and univar_heads[at] in leave (sized by enter's resize);
    • kernel Graph::children's panic!("expected representative descriptor") for a tag outside VAR/ARROW/CONSTR/TUPLE (EXTENDED nodes have tag TUPLE, since tag() = head & 15 and EXTENDED = 1 << 4);
    • Graph::end_def's assert!(self.level > 1);
    • copy_begin's expect("copy generation exhausted").
  • Recursion: none.
  • Vectors, empty at entry and on every exit:
    • st.values: the alias slots are cut by walk, the instance_list copies are truncated to mark on all three exits, and transl_type clears on Err.
    • vars.univars: truncated at the binder's leave; dropped on Err and at transl_simple_type's entry.
    • g.work: cleared before the marking walk and drained by it.
    • vars.used: forgotten on globalize's Ok exit only (see 10.2).

19. The prompt "Task R5a-2a" — PASS with notes

(a) End-state searches, run on the head with grep instead of rg:

  1. todo!("R5a-2") count: 8. Prompt: 8.
  2. src/tc/r5a2_tests.rs:23 and src/tc/r5a_tests.rs:1. Matches.
  3. Prototype markers and forbidden calls: no output. Matches.
  4. Lines 622 (PLAIN_PARAMS == 0) and 635 (AliasType). Matches.
  5. Declined::PolyType at 388, 493 and 637. Matches.
  6. r5a_tests.rs:97 and 571. Matches.

(b) Can each commit build alone? By reading, no commit's body calls a function of a later commit:

  • 1 calls forget_used (R5a-1) only;
  • 2 calls univar (commit 1) and instance (its own);
  • 3 calls univar and drop_univars (commit 1);
  • 4 calls reset, declared and add_declared (commit 1);
  • 5 calls instance_list (its own).

Every test un-ignored in commits 2-4 reaches no type without PLAIN_PARAMS: FIELDS and ALIASES use only k, p, id, ph and predefined types.

(c) Counts: r5a2 goes from 6 passed / 23 ignored to 29 / 0. The whole tc:: filter: passed is trunk + 24 − 1 = +23, ignored is −24. Consistent. The prompt allows exactly three edits of r5a_tests.rs: "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)". The deleted test pins Declined::NotBuilt and "no node is made" for t<int, string> with shared parameters (r5a_tests.rs:563-581), a decline R5a-2a removes. Its replacements are r5a2_tests::parameters_without_plain_params_agree_with_todays_checker (refusal of sh<int, string>) and r5a_tests::arguments_of_shared_parameters_are_unified. Justified.

(d) Every name exists on the head or in the prototype:

  • kernel functions: Checker::unify_var (unify.rs:2201), unify (517), restore (1877), fresh_marks (3069); Graph::speculate / keep / write (graph.rs:199/208/139); begin_def / end_def / children (level.rs); Checker::generalize / copy / lower / link_memorized (expand.rs:952/1509/1715/1541); copy_begin / copy_ref / copy_drain (template.rs); Extras::univar (rows.rs:651); ExtraDescriptor::Poly (segment.rs:585);
  • fields and helpers: speculation_depth (graph.rs:76), Graph::work (graph.rs:77), Checker::marks (unify.rs:319), arrow_params;
  • all 23 test names and r5a_tests::arguments_of_shared_parameters_are_unified.

None is missing. Declined::AliasType becomes unconstructed; #[allow(dead_code)] on Declined (mod.rs:13) hides that.

(e) What the prompt says the prototype leans on, against trunk: walk (trunk typetexp.rs:614-635: pops the frame, leave, writes the row, truncates to base, pushes), new_var (527), arrow_params, and the inline rule (579-581 starts_with('_') → Err; 598 is_ascii_alphabetic). All as described. The helper rule "is _ or an ASCII letter" equals strict_ident (typetexp.ml:224). Its two callers are the variable arm, where _ is already refused so the result is the same, and the binder arm. An empty name gives none through first(), which the prompt does not say in words.

(f) The failure list is present. The prompt mentions none of the wrong bodies 17.1-17.4.

(g) On 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."

20. The cut and 10.12.5 — PASS

  • Trunk's find_type (typetexp.rs:324-341) answers only a ResolvedKind::Binder of BinderKind::Type; any import gives Declined::TypePath, and Ptyp_constr gives TypePath for any non-Lident (605-608). So in R5a-3 a manifest or field that names M.t, or a type of another unit reached through open, declines. That is safe. The 10.7 row of R5a-3 still says "Needs: R5a-2" (CHECKER_REWRITE.md:11878), while the text says R5a-2a.
  • TypeTable::from_segment (expand.rs:189-237) makes one row per segment paths row. Own declarations get declaration_row (arity, flags, a manifest whose template stays in the segment's graph, newtype); every other path is ABSTRACT. Then come variances and mark_manifests.
  • A row for ONE type of another unit would need:
    1. that segment's type_declarations[i] and type_details;
    2. its manifest template brought into this unit's graph or template pools, since templates index the other segment's pools;
    3. the type indices inside that template (that segment's paths) mapped to rows of this table, created lazily and transitively;
    4. the variance, injective and constrained bits, and scope = 0;
    5. for a type without PLAIN_PARAMS, its parameter nodes instantiated into AnnotState::params and params_of.

21. Decisions 13 to 21

  • 13, the cut: from_segment builds a whole-segment table (expand.rs:189). CONFIRMED BY MY READING.
  • 14, the alias arm as one frame: the table in section 12. CONFIRMED.
  • 15, the self-alias decided by the kernel's unify_var: OCaml 2753, 2240 and 1384-1408. CONFIRMED on the OCaml side; kernel unify2/unify3 NOT CHECKED (the prototype run).
  • 16, decline where OCaml skips: the only failure is occur_univar (2219) when scoped == 0. CONFIRMED.
  • 17, two loops, reverse order: OCaml's r consing (719, 724) and List.iter (729). CONFIRMED; the order is untested (17.1).
  • 18, head table, one marking walk, lower: 545-571 and 1758-1772; the duplicate and aliased cases. CONFIRMED.
  • 19, unify_var always; enforce_constraints kept: DOUBT. The first loop is CONFIRMED (stubs are plain, typedecl.ml:85). The second loop is unify_var in OCaml (ctype.ml:1129-1130, 2767), not unify as written.
  • 20, Univars has no caller: grep -n Univars typetexp.ml gives 278, 298, 313, 540, 658. CONFIRMED.
  • 21, Err restores the level and univars: proto 45-51 and 164-168. CONFIRMED.
  • 10.11 item 4: the State: line is present (CHECKER_REWRITE.md:12491-12502: "the one speculation of globalize is restored before its decline leaves … transl_type puts the level back on Err … transl_type_scheme gives its begin_def back"). It is true of the prototype: self.c.restore(token); return Err(Stop::Declined(Declined::PolyType)) (proto 118-120).

22. Citations

All in 10.12, the prompt, the typetexp.rs doc comments and r5a2_tests.rs are RIGHT on the branch except:

  • r5a2_tests.rs:51, "(unify_var t ty, 412)": typetexp.ml:412 → 413 (412 is let ty = transl_type env policy st).
  • typetexp.rs doc of transl_type_scheme, r5a2_tests.rs:978 and 10.12 ("677-756"): typetexp.ml:751-756 → 751-757.
  • typetexp.rs doc of transl_simple_type, "make_fixed_univars … (677-702)": typetexp.ml:677-702 → 677-703.
  • 10.12 "2726-2733 (the outer unify)": ctype.ml:2726 → 2728 (2726 ends the previous function).
  • r5a2_tests.rs:686, "as transl_label runs it (transl_simple_type env closed, typedecl.ml:195)": the line is right, but typedecl.ml:194 Ast_helper.Typ.force_poly arg comes first (finding 10.3).

Checked RIGHT: 213-216, 224-231, 250-254, 278, 298, 299-300, 306-308, 313, 358-389, 394-428 (398, 400, 403-406, 407, 409-411, 413-416, 417-426), 540, 545-571 (547, 548, 550, 553, 554-555, 556-567, 560, 565, 569, 570), 658, 705-734 (709-713, 711-717, 719, 721-722, 725, 727, 728-733, 733), 736-742, 738, 741, 744-749; ctype.ml 120, 157, 213, 509-520, 511, 879-894, 891-894, 1333-1342, 1384-1408, 1723-1776, 1758-1772, 2216-2247, 2242, 2748-2765, 2753, 2758, 2765, 2767; typedecl.ml 316, 420; typecore.ml 1423, 1863, 3571.

23. CI on the head

gh pr checks 436 -R jfrolich/rescript-rust: all 23 checks pass. Run 46275170956 has headSha 39a933e.

  • compiler-tests (job 141384781970):
    • lines matching ^test tc::.*\.\.\. ok$: 440;
    • lines matching ^test tc::.*\.\.\. ignored: 24, which are the 23 r5a2_tests acceptance tests above plus tc::r5a_tests::arguments_of_shared_parameters_are_unified;
    • FAILED: 0;
    • library: test result: ok. 3306 passed; 0 failed; 48 ignored; 0 measured; 0 filtered out; finished in 1112.16s.
  • compiler-warnings (job 141384781616): cargo clippy --locked … --all-targets --no-default-features -- -D warnings finished both runs; RUSTDOCFLAGS: -D warnings, Documenting rescript-compiler … Finished.
  • Instruction count (run 46275170991, job 141386778455): "Within the threshold of +0.1%."; base 4,355,569,218, head 4,356,216,890, change +647,672 (+0.015%).

@jfrolich

Copy link
Copy Markdown
Owner Author

Coordinator review, final, at 39a933e (the author did not write this review). It follows the first-pass checklist review above (7258428653), which read the OCaml source line by line beside the design and the prototype; I did not repeat that reading and say below what I checked myself.

What this pull request puts on trunk. The design of R5a-2 (CHECKER_REWRITE 10.12, decisions 13 to 21), cut in two; for the first half, R5a-2a (aliases, universal variables and the polymorphic arm, globalize, transl_simple_type, transl_type_scheme, unify_params), the acceptance tests (r5a2_tests.rs: 23 ignored for the build, 5 that pin today's checker), skeleton changes with todo! bodies, and the prompt "Task R5a-2a". The slice is not here: its prototype is comment 7257628931. No build reaches any of it.

Checked by me.

  • The designer's sandbox had no OCaml compiler and listed fourteen programs whose answer it could not know. I ran them (and four more) through the OCaml compiler: every one that parses answers as the tests expect. (int as 'a, 'a) => 'a prints (int, int) => int; (int as 'a, string as 'a) is refused at the second alias; k<'b> as 'b with k abstract is refused with the alias text and "occurs inside"; (('a as 'b) as 'c, 'c) => 'b prints ('a, 'a) => 'a; type t<'a> = {x: int as 'a} is accepted and t<string> is then refused; with y: string as 'a added it is refused at 1:32-43 with "This type string should be an instance of type int"; 'a 'b. ('b, 'a) keeps both binders; 'a 'a. 'a => 'a prints 'a. 'a => 'a; 'a 'b. 'a => int prints 'a. 'a => int; 'a 'b. ('a as 'b) => int is refused at the whole polymorphic type ("'b cannot be generalized: it is already bound to another variable"); the three programs of a shared and of a constrained parameter print sh<array<'a>, array<'a>>, (sh<'a, 'a>, 'a) => 'a and cl<list<'a>> => list<'a>. Program 10 does not parse as written; a binder inside a binder parses through an object field and is accepted.
  • The first pass's finding on enforce_constraints, in the source: subst unifies through !unify' (ctype.ml 1129-1130) and unify' is unify_var (2767). Decision 19, the doc comment of unify_params and the prompt say unify for the second loop. The builder is told to call unify_var there and to reword that one sentence.
  • The step tests: each asserts small >= 1_000, large <= 11 * small and a bound of the prototype's count an element plus 100 steps. That is an exact pin: a body that walks twice fails, and so does a correct body that counts one step more an element. Accepted as a pin; the builder reports both numbers and stops if it meets it.
  • The merge with trunk is clean; the privacy search over the added lines prints 0.

Decisions. 13 (the cut: R5a-3 needs R5a-2a only), 14, 17, 18, 20 and 21: confirmed by the first pass's reading. 16 (a used variable whose globalization fails declines the unit where OCaml skips it silently): accepted; a decline sends the unit to today's checker and is never wrong, and it is taken with the speculation closed. 15 (a phantom self-alias is held as a type that names itself): accepted for annotations; R5a-9 declines such a scheme unless its design shows capture and publication on one. 19: accepted with the correction above.

Owed, and to whom.

  1. The builder of R5a-2a: unify_var in the second loop of unify_params, with the one doc sentence.
  2. R5a-3's design turn: tests for the wrong bodies no test catches (the second loop of globalize in forward order; a binder named without the name rule; unify in the first loop of unify_params; the second loop at the current level instead of the node's; TypeVars::reset not dropping the universal variables); TypeVars::heads is stale after the sort of globalize on its error and decline exits (say so or put them back; Decls::reset); TypeVars::default() has global_level 0 where OCaml starts at 1; decision 8 of 10.2 still says "skips" and needs a pointer to decision 16; the row of R5a-3 in 10.7 says it needs R5a-2 where it needs R5a-2a; whether reset_reified_var_counter matters.
  3. R5a-4's design turn: transl_label calls force_poly before transl_simple_type (typedecl.ml 194-195), so every record field passes the polymorphic arm and is Tpoly(t, []); the comment of FIELDS and the doc of field_type speak of the parse tree only.
  4. R5a-2b (a path of several components, a type of another unit): a design turn of its own, before R5a-9.
  5. One renumbering commit: the five citations the first pass lists in its section 22; "314 added, 22 removed" is 21 removed.
  6. Still open from the review of pull request 435: tests for the wrong bodies of R5a-1.

CI on 39a933e: 23 of 23 (read by the first pass: tc:: 440 passed and 24 ignored, library 3306 passed and 48 ignored, Instruction count +0.015% on code no build reaches).

Not rerun or not read by me: any cargo command; the prototype (applied by the first pass, not by me); the skeleton diff of walk/typetexp.rs and the 28 tests line by line (the first pass's sections 11 and 17); the 39 breaks the designer saw; the kernel's arms for a type that names itself beyond what the first pass followed.

Merging. R5a-2a is built next, by a builder that writes the bodies reading the prototype.

@jfrolich
jfrolich marked this pull request as ready for review November 29, 2026 16:02
@jfrolich
jfrolich merged commit e6d92fe into ocaml-to-rust-rewrite Nov 29, 2026
23 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant