From 92862d20764a5937d87f28c1770fd2efc80596f2 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:04:06 +0000 Subject: [PATCH 01/30] Refuse a GADT instance that would escape its equation, as OCaml does Why: OCaml records, per `switch` whose patterns may add equations, the types known only through an equation (`Env.gadt_instances`, compiler/ml/env.ml:1305-1345), and refuses to expand or lower one below that level (ctype.ml:587-589, 1215-1227). Rust did not track them (`Env::add_gadt_instance_level` took no level), so it accepted and compiled programs OCaml refuses. Typing modified (expanding an equation's type below its switch): Example: type rec t<_> = Int: t let f = (type a, x: t, y: a) => switch x { | Int => if true { y } else { 0 } } Before (diagnostic): accepted; `function f(x, y) { return y; }` After (diagnostic): We've found a bug for you! Main.res:4:33 This has type: int But this if statement is expected to return: a (defined as int) This instance of int is ambiguous: it would escape the scope of its equation if expressions must return the same type in all branches (if, else if, else). The instance sets live in the type context, one per scope, each holding its enclosing scope's handle; the environment holds the innermost handle (`EnvData::gadt_instances`), so cloning an environment copies a `u32` and no set. Additions are journaled and undone on backtrack, as OCaml trails `set_typeset`. Ported: the expansion level of an equation (env.ml:1805-1810), `cleanup_abbrev` when tracing starts (ctype.ml:182), the test and the additions of `expand_abbrev_gen` (ctype.ml:1215-1227), the chain of `try_expand_head` (ctype.ml:1270-1276), `unify2`'s expansions failing with the pair (ctype.ml:2289-2292), the test of `update_level` (ctype.ml:587-589), and the arm of `unify` for two locally abstract types (ctype.ml:2255-2268), without which an accepted `eq` program became refused. Review: What does a program without GADTs pay? The test in the level update is one load of `has_gadt_instance_scopes` and a branch; every other read and write runs only while tracing is on (under local constraints) or in an environment with an instance scope. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- changes/gadt-instance-ambiguity.fix.md | 1 + compiler-rust/src/types/context.rs | 201 +++++++++++- compiler-rust/src/types/ctype.rs | 290 +++++++++++++++--- compiler-rust/src/types/env.rs | 25 +- compiler-rust/src/types/typecore.rs | 4 +- ...adt_instance_ambiguous_abbrev.res.expected | 16 + ...ce_ambiguous_abbrev_annotated.res.expected | 16 + ...stance_ambiguous_abbrev_chain.res.expected | 20 ++ ...gadt_instance_ambiguous_array.res.expected | 20 ++ ...instance_ambiguous_eq_witness.res.expected | 16 + ...e_ambiguous_function_returned.res.expected | 16 + .../gadt_instance_ambiguous_if.res.expected | 16 + ...stance_ambiguous_inner_switch.res.expected | 16 + ...ce_ambiguous_let_after_switch.res.expected | 16 + ...ance_ambiguous_nested_pattern.res.expected | 16 + ...adt_instance_ambiguous_object.res.expected | 19 ++ ...nstance_ambiguous_object_open.res.expected | 19 ++ ...ance_ambiguous_outer_abstract.res.expected | 16 + ...nstance_ambiguous_polyvariant.res.expected | 14 + ...stance_ambiguous_record_field.res.expected | 18 ++ ...stance_ambiguous_ref_assigned.res.expected | 16 + ...tance_ambiguous_two_equations.res.expected | 16 + .../gadt_instance_ambiguous_abbrev.res | 6 + ...dt_instance_ambiguous_abbrev_annotated.res | 6 + .../gadt_instance_ambiguous_abbrev_chain.res | 7 + .../gadt_instance_ambiguous_array.res | 6 + .../gadt_instance_ambiguous_eq_witness.res | 5 + ...t_instance_ambiguous_function_returned.res | 5 + .../fixtures/gadt_instance_ambiguous_if.res | 5 + .../gadt_instance_ambiguous_inner_switch.res | 9 + ...dt_instance_ambiguous_let_after_switch.res | 10 + ...gadt_instance_ambiguous_nested_pattern.res | 6 + .../gadt_instance_ambiguous_object.res | 5 + .../gadt_instance_ambiguous_object_open.res | 8 + ...gadt_instance_ambiguous_outer_abstract.res | 8 + .../gadt_instance_ambiguous_polyvariant.res | 5 + .../gadt_instance_ambiguous_record_field.res | 6 + .../gadt_instance_ambiguous_ref_assigned.res | 8 + .../gadt_instance_ambiguous_two_equations.res | 6 + .../src/gadt_instance_ambiguous_accepted.mjs | 234 ++++++++++++++ .../src/gadt_instance_ambiguous_accepted.res | 186 +++++++++++ 41 files changed, 1281 insertions(+), 57 deletions(-) create mode 100644 changes/gadt-instance-ambiguity.fix.md create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_abbrev.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_abbrev_annotated.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_abbrev_chain.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_array.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_eq_witness.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_function_returned.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_if.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_inner_switch.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_let_after_switch.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_nested_pattern.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_object.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_object_open.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_outer_abstract.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_polyvariant.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_record_field.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_ref_assigned.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_two_equations.res.expected create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_abbrev.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_abbrev_annotated.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_abbrev_chain.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_array.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_eq_witness.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_function_returned.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_if.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_inner_switch.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_let_after_switch.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_nested_pattern.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_object.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_object_open.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_outer_abstract.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_polyvariant.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_record_field.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_ref_assigned.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_two_equations.res create mode 100644 tests/tests/src/gadt_instance_ambiguous_accepted.mjs create mode 100644 tests/tests/src/gadt_instance_ambiguous_accepted.res diff --git a/changes/gadt-instance-ambiguity.fix.md b/changes/gadt-instance-ambiguity.fix.md new file mode 100644 index 0000000000..38d88a8938 --- /dev/null +++ b/changes/gadt-instance-ambiguity.fix.md @@ -0,0 +1 @@ +- Refuse, as the OCaml compiler does, a value whose type is known only through a GADT equation when it leaves the case of that equation, for example `if true { y } else { 0 }` with `y: a` under `| Int =>` without a result annotation ("This instance of int is ambiguous"). diff --git a/compiler-rust/src/types/context.rs b/compiler-rust/src/types/context.rs index b80fdc33e8..318f9bbf51 100644 --- a/compiler-rust/src/types/context.rs +++ b/compiler-rust/src/types/context.rs @@ -562,8 +562,40 @@ enum TypeMutation { NongenLevel(i32), GlobalLevel(i32), SavedLevels(Vec<(i32, i32)>), + /// btype.ml `Ctypeset`: a type added to a GADT instance set + /// (`Env.add_gadt_instances`, env.ml:1325-1329); undone by removing the + /// scope's last member. + GadtInstance(GadtScopeRef), } +/// Handle of a GADT instance scope of [`TypeContext`]; `NONE` for an +/// environment outside every such scope. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct GadtScopeRef(u32); + +impl GadtScopeRef { + /// No scope: OCaml's empty `gadt_instances` list. + pub const NONE: GadtScopeRef = GadtScopeRef(u32::MAX); + + /// Whether this is [`Self::NONE`]. + #[inline] + pub fn is_none(self) -> bool { + self == Self::NONE + } + + fn index(self) -> usize { + self.0 as usize + } +} + +/// One entry of OCaml `Env.gadt_instances` (compiler/ml/env.ml:368): the +/// level of a `switch` or function whose patterns may add equations, and the +/// types known there only through one of them. +struct GadtInstanceScope { + level: i32, + parent: GadtScopeRef, + members: Vec, +} #[derive(Default)] struct TypeMutationJournal { @@ -829,6 +861,17 @@ pub struct TypeContext { /// GADT instance tracking flag trace_gadt_instances: Cell, + /// The sets of OCaml `Env.gadt_instances` (compiler/ml/env.ml:1305-1345), + /// one per `switch` or function whose patterns may add equations, + /// indexed by [`GadtScopeRef`]. An environment holds the handle of its + /// innermost scope; each scope holds its enclosing one's, so a clone of + /// an environment copies a `u32` and never a set. + gadt_instance_scopes: RefCell>, + + /// Whether this unit has created a GADT instance scope: the one load + /// [`Self::has_gadt_instance_scopes`] tests on every level update. + has_gadt_instance_scopes: Cell, + /// Whether this unit created or copied a polymorphic type with at least /// one bound variable (see [`Self::note_bound_universal`]). Only then /// can the inclusion of the unit in its own inferred signature fail. @@ -1390,6 +1433,8 @@ impl TypeContext { global_level: Cell::new(1), saved_levels: RefCell::new(Vec::new()), trace_gadt_instances: Cell::new(false), + gadt_instance_scopes: RefCell::new(Vec::new()), + has_gadt_instance_scopes: Cell::new(false), bound_universals: Cell::new(false), passive_variants: Cell::new(false), rigid_variants: Cell::new(false), @@ -3697,6 +3742,12 @@ impl TypeContext { *self.saved_levels.borrow_mut() = value; restored += 1; } + TypeMutation::GadtInstance(scope) => { + self.gadt_instance_scopes.borrow_mut()[scope.index()] + .members + .pop(); + restored += 1; + } } } snapshot.restored = true; @@ -5613,10 +5664,15 @@ impl TypeContext { // GADT Tracking // ======================================================================== - /// Check and set GADT instance tracing. + /// OCaml `check_trace_gadt_instances` (compiler/ml/ctype.ml:178-184): + /// turn GADT instance tracing on under local constraints, forgetting the + /// memorized expansions (`cleanup_abbrev`) so that each is made again + /// through the instance test of `expand_abbrev_gen`. Returns whether + /// this call turned it on. pub fn check_trace_gadt_instances(&self, has_constraints: bool) -> bool { if !self.trace_gadt_instances.get() && has_constraints { self.trace_gadt_instances.set(true); + self.clear_abbrev_memos(); true } else { false @@ -5656,6 +5712,124 @@ impl TypeContext { self.trace_gadt_instances.get() } + /// Whether this unit has a GADT instance scope at all. One load: the + /// test every level update makes before it looks at an environment's + /// scopes (OCaml `Env.gadt_instance_level`, ctype.ml:587). + #[inline] + pub fn has_gadt_instance_scopes(&self) -> bool { + self.has_gadt_instance_scopes.get() + } + + /// OCaml `Env.add_gadt_instance_level lv` (compiler/ml/env.ml:1307-1308): + /// a new, empty instance set at `level` inside `parent`. O(1) amortized. + pub(crate) fn new_gadt_instance_scope(&self, level: i32, parent: GadtScopeRef) -> GadtScopeRef { + let mut scopes = self.gadt_instance_scopes.borrow_mut(); + let scope = + GadtScopeRef(u32::try_from(scopes.len()).expect("GADT instance scope overflow")); + scopes.push(GadtInstanceScope { + level, + parent, + members: Vec::new(), + }); + self.has_gadt_instance_scopes.set(true); + scope + } + + /// OCaml `Env.gadt_instance_level env t` (compiler/ml/env.ml:1314-1323): + /// the level of the innermost scope from `scope` outwards whose set holds + /// `ty`, a representative. A member is compared by its representative, + /// as OCaml replaces the members of a set by theirs before testing. + /// Cost: one step per scope and per member of the scopes visited. + pub(crate) fn gadt_instance_level(&self, scope: GadtScopeRef, ty: TypeExprRef) -> Option { + let scopes = self.gadt_instance_scopes.borrow(); + let mut current = scope; + while !current.is_none() { + let entry = &scopes[current.index()]; + for &member in &entry.members { + #[cfg(test)] + crate::tc::steps::tick(); + if self.repr(member) == ty { + return Some(entry.level); + } + } + current = entry.parent; + } + None + } + + /// The scope at `level` from `scope` outwards: OCaml's + /// `List.assoc lv env.gadt_instances` (env.ml:1326-1328, 1333-1335). + /// One step per scope visited. + fn gadt_instance_scope_at(&self, scope: GadtScopeRef, level: i32) -> GadtScopeRef { + let scopes = self.gadt_instance_scopes.borrow(); + let mut current = scope; + while !current.is_none() { + let entry = &scopes[current.index()]; + if entry.level == level { + return current; + } + current = entry.parent; + } + panic!("Env.add_gadt_instances: no instance scope at level {level}") + } + + /// Append `ty` to the set of `scope`, journaled. O(1) amortized. A + /// member added twice answers [`Self::gadt_instance_level`] as once. + fn push_gadt_instance(&self, scope: GadtScopeRef, ty: TypeExprRef) { + self.gadt_instance_scopes.borrow_mut()[scope.index()] + .members + .push(ty); + self.record_mutation( + || TypeMutation::GadtInstance(scope), + crate::perf_counters::TypeMutationKind::State, + ); + } + + /// OCaml `Env.add_gadt_instances env lv tl` (compiler/ml/env.ml:1325-1329): + /// add `types` to the set at `level` of the scopes from `scope` outwards. + /// Cost: the scopes visited plus O(1) per type. + pub(crate) fn add_gadt_instances( + &self, + scope: GadtScopeRef, + level: i32, + types: &[TypeExprRef], + ) { + let scope = self.gadt_instance_scope_at(scope, level); + for &ty in types { + self.push_gadt_instance(scope, ty); + } + } + + /// OCaml `Env.add_gadt_instance_chain env lv t` (compiler/ml/env.ml:1332-1345): + /// add `ty` and, while it is a constructor with a memorized expansion, + /// that expansion, stopping at the first type the set already holds. + /// Only for a type `expand_head` has expanded. Cost: the scopes visited + /// plus, per type of the chain, one step per member and one walk of the + /// constructor's memo chain. + pub(crate) fn add_gadt_instance_chain(&self, scope: GadtScopeRef, level: i32, ty: TypeExprRef) { + let scope = self.gadt_instance_scope_at(scope, level); + let mut current = Some(ty); + while let Some(ty) = current { + let ty = self.repr(ty); + // `Type_set.mem t !r` (env.ml:1339): the node itself, which ends + // the chain. + let member = self.gadt_instance_scopes.borrow()[scope.index()] + .members + .contains(&ty); + if member { + return; + } + self.push_gadt_instance(scope, ty); + let constr = match &*self.borrow_desc(ty) { + TypeDesc::Tconstr { path, abbrev, .. } => Some((*path, *abbrev)), + _ => None, + }; + current = constr.and_then(|(path, abbrev)| { + self.find_abbrev_expansion(abbrev, PrivateFlag::Private, &path) + }); + } + } + // ======================================================================== // Type Representative (Union-Find) // ======================================================================== @@ -5936,7 +6110,7 @@ mod tests { let ctx = TypeContext::new(Arc::new(IdGenerator::new())); let env = Env::empty(); let mut other = env.clone(); - other.add_gadt_instance_level(); + other.add_gadt_instance_level(&ctx, 1); let path = Path::pident(Ident::create_persistent("M")); let signature = Arc::new(Vec::new()); ctx.register_resolved_module_sig("M", Some(env.scope_id()), path, signature.clone()); @@ -6161,12 +6335,33 @@ mod tests { } } + #[test] + fn gadt_instance_level_is_one_step_per_member_at_ten_thousand() { + let ctx = TypeContext::new(Arc::new(IdGenerator::new())); + let outer = ctx.new_gadt_instance_scope(5, GadtScopeRef::NONE); + let inner = ctx.new_gadt_instance_scope(9, outer); + let members: Vec<_> = (0..10_000).map(|_| ctx.new_var(None)).collect(); + ctx.add_gadt_instances(inner, 5, &members); + let other = ctx.new_var(None); + // The inner set is empty: one step per member of the outer one. + let mut level = Some(0); + let steps = crate::tc::steps::scope(|| level = ctx.gadt_instance_level(inner, other)); + assert_eq!((level, steps), (None, 10_000)); + let steps = + crate::tc::steps::scope(|| level = ctx.gadt_instance_level(inner, members[9_999])); + assert_eq!((level, steps), (Some(5), 10_000)); + // A member linked to another type answers for its representative. + ctx.set_desc(members[0], TypeDesc::Tlink(other)); + assert_eq!(ctx.gadt_instance_level(inner, other), Some(5)); + assert_eq!(ctx.gadt_instance_level(GadtScopeRef::NONE, other), None); + } + #[test] fn borrowed_path_keys_find_owned_cache_entries() { let ctx = TypeContext::new(std::sync::Arc::new(IdGenerator::new())); let scope = Env::empty().scope_id(); let mut other = Env::empty(); - other.add_gadt_instance_level(); + other.add_gadt_instance_level(&ctx, 1); let module = Path::pdot(super::super::predef::path_int(), "M"); let ty = Path::pdot_pos(module, "t", 3); ctx.register_type_newtype_level(scope, &ty, Some(2)); diff --git a/compiler-rust/src/types/ctype.rs b/compiler-rust/src/types/ctype.rs index a902ba31e7..93280ae92b 100644 --- a/compiler-rust/src/types/ctype.rs +++ b/compiler-rust/src/types/ctype.rs @@ -590,6 +590,65 @@ fn is_instantiable(ctx: &TypeContext, env: &Env, path: &Path) -> bool { }) } +/// OCaml `is_newtype env p` (compiler/ml/ctype.ml:1862-1868): `p` is a +/// public abstract type with a newtype level. One declaration lookup. +fn is_newtype(ctx: &TypeContext, env: &Env, path: &Path) -> bool { + lookup_type_decl_for_path(ctx, env, path).is_some_and(|decl| { + decl.type_newtype_level.is_some() + && matches!(decl.type_kind, super::TypeKind::TypeAbstract) + && decl.type_private == super::PrivateFlag::Public + }) +} + +/// OCaml `unify`'s arm for two nullary locally abstract types under local +/// constraints (compiler/ml/ctype.ml:2255-2268): "do not use local +/// constraints more than necessary". Only the type with the later newtype +/// level is expanded, once, and unified with the other; no level is lowered +/// before. `None` when the arm does not apply or the type cannot be +/// expanded, and unification goes on as `unify2`. One call is four +/// declaration lookups and one expansion. +fn unify_newtypes( + ctx: &TypeContext, + state: &mut UnifyState, + t1: TypeExprRef, + t2: TypeExprRef, +) -> Option> { + let env = state.env().filter(|env| env.has_local_constraints())?; + let nullary_path = |ty: TypeExprRef| match &*ctx.borrow_desc(ty) { + TypeDesc::Tconstr { path, args, abbrev } if args.is_empty() => Some((*path, *abbrev)), + _ => None, + }; + let ((p1, a1), (p2, a2)) = (nullary_path(t1)?, nullary_path(t2)?); + // The arm before it (ctype.ml:2247-2254) links the same constructor + // without a memorized expansion; `unify_types` starts with it. + if p1.same(&p2) && !(has_cached_expansion(ctx, &p1, a1) || has_cached_expansion(ctx, &p2, a2)) { + return None; + } + if !(is_newtype(ctx, env, &p1) && is_newtype(ctx, env, &p2)) { + return None; + } + let expand_first = find_newtype_level(ctx, env, &p1) >= find_newtype_level(ctx, env, &p2); + let expanded = if expand_first { t1 } else { t2 }; + match try_expand_head_traced(ctx, env, expanded, ExpandHeadMode::Unify) { + Ok(Some(expansion)) => { + let expansion = ctx.repr(expansion); + Some(if expand_first { + unify(ctx, state, expansion, t2) + } else { + unify(ctx, state, t1, expansion) + }) + } + Ok(None) => None, + Err(ambiguous) => { + let level = ctx.get_level(ambiguous); + Some(Err(TypeError::Unify(vec![( + ambiguous, + new_var_at_level(ctx, level), + )]))) + } + } +} + /// OCaml `find_newtype_level` (compiler/ml/ctype.ml:2084-2091): the newtype /// level of the declaration, else the path's binding time twice. One call is /// one declaration lookup. @@ -1746,8 +1805,11 @@ fn unify_gadt_equation( } (None, None) => return None, }; + let Some(newtype_level) = state.newtype_level else { + panic!("Ctype.add_gadt_equation: get_newtype_level called outside pattern unification"); + }; let env = state.env_mut()?; - add_gadt_equation(ctx, env, &source, destination); + add_gadt_equation(ctx, env, &source, destination, newtype_level); Some(Ok(())) } @@ -1758,6 +1820,7 @@ fn add_gadt_equation( env: &mut Env, source_path: &Path, destination: TypeExprRef, + newtype_level: i32, ) { if !local_non_recursive_abbrev(ctx, env, source_path, destination) { return; @@ -1775,7 +1838,11 @@ fn add_gadt_equation( type_private: super::PrivateFlag::Public, type_manifest: Some(destination_copy), type_variance: vec![], - type_newtype_level: Some(source_lev), + // OCaml `Env.add_local_constraint` (compiler/ml/env.ml:1805-1810) + // keeps the definition level and records the pattern's newtype + // level as the expansion level, the level of the GADT instance set + // an expansion of this equation joins (ctype.ml:1215-1227). + type_newtype_level: Some((source_lev.0, newtype_level)), type_loc: crate::types::DeclLoc::none(), type_attributes: vec![], type_immediate: false, @@ -2693,7 +2760,12 @@ fn update_level_checked_above( if ctx.compiler_counters_enabled() { crate::perf_counters::census_update_level(ctx, level, ty); } - if lower_plain_levels(ctx, env, level, ty) { + // A node in a GADT instance set may refuse to be lowered + // (`update_level_pass`), which the plain update does not test: it is + // skipped in an environment with an instance scope. One load and one + // branch when the unit has none. + let instances = ctx.has_gadt_instance_scopes() && !env.gadt_instance_scope().is_none(); + if !instances && lower_plain_levels(ctx, env, level, ty) { return Ok(()); } let snapshot = ctx.snapshot_type_state(); @@ -2893,6 +2965,22 @@ fn level_update_is_plain( .all(|child| level_update_is_plain(ctx, env, level, child, visited)) } +/// OCaml `Env.gadt_instance_level env ty` (compiler/ml/env.ml:1314-1323) +/// of the representative of `ty`: the level of the innermost GADT instance +/// set of `env` holding it. One load and one branch when the unit has no +/// instance scope; otherwise [`TypeContext::gadt_instance_level`]. +#[inline] +pub(crate) fn gadt_instance_level(ctx: &TypeContext, env: &Env, ty: TypeExprRef) -> Option { + if !ctx.has_gadt_instance_scopes() { + return None; + } + let scope = env.gadt_instance_scope(); + if scope.is_none() { + return None; + } + ctx.gadt_instance_level(scope, ctx.repr(ty)) +} + /// OCaml `newvar2 level`. #[track_caller] fn new_var_at_level(ctx: &TypeContext, level: i32) -> TypeExprRef { @@ -2914,6 +3002,14 @@ fn update_level_pass( let current = ctx.get_level(ty); if level < current { + // OCaml ctype.ml:587-589: a GADT instance cannot be lowered below + // the level of its set; the error is the same pair as an escaping + // constructor's. + if let Some(instance_level) = gadt_instance_level(ctx, env, ty) + && level < instance_level + { + return Err(ty); + } let desc = ctx.borrow_desc(ty); match &*desc { TypeDesc::Tconstr { path, args, .. } => { @@ -4655,6 +4751,22 @@ fn try_expand_head_with_mode( ty: TypeExprRef, mode: ExpandHeadMode, ) -> Option { + // OCaml `try_expand_safe` (ctype.ml:1260-1265): an ambiguous GADT + // instance is a type that cannot be expanded. It is found before the + // expansion changes anything, so there is nothing to backtrack. + try_expand_head_traced(ctx, env, ty, mode).unwrap_or(None) +} + +/// OCaml `expand_abbrev_gen` (compiler/ml/ctype.ml:1190-1229) of one head. +/// `Err(ty)` is its `Unify [(ty, newvar2 level)]` (ctype.ml:1225): while +/// GADT instances are traced, the expansion of `ty` is known only at an +/// instance level above `ty`'s own level. +fn try_expand_head_traced( + ctx: &TypeContext, + env: &Env, + ty: TypeExprRef, + mode: ExpandHeadMode, +) -> Result, TypeExprRef> { let ty = ctx.repr(ty); let desc = ctx.borrow_desc(ty); match &*desc { @@ -4693,24 +4805,51 @@ fn try_expand_head_with_mode( } // The cached expansion is returned even when it is `ty` // itself (ctype.ml:1360-1362, PR#7324). - return Some(ctx.repr(cached)); - } - - let expand_with_subst = - |params: &[TypeExprRef], manifest: TypeExprRef| -> TypeExprRef { - subst_with_memo( - ctx, - env, - ty, - lookup_abbrev, - private_flag, - AbbrevDefinition { - params: params.into(), - body: manifest, - }, - ctx.type_list(args), - ) + return Ok(Some(ctx.repr(cached))); + } + + // `expansion_level` is the expansion level of the declaration + // (`Env.find_type_expansion`'s `lv`, env.ml:902): set for a + // GADT equation. + let expand_with_subst = |params: &[TypeExprRef], + manifest: TypeExprRef, + expansion_level: Option| + -> Result { + // ctype.ml:1218-1227: the highest level of the equation and + // of an instance set holding `ty`. The test is made before + // `subst` here: it reads only `ty`, which `subst` leaves as + // it is. + let instance_level = if ctx.trace_gadt_instances() { + expansion_level.max(gadt_instance_level(ctx, env, ty)) + } else { + None }; + if let Some(instance_level) = instance_level + && ctx.get_level(ty) < instance_level + { + return Err(ty); + } + let expanded = subst_with_memo( + ctx, + env, + ty, + lookup_abbrev, + private_flag, + AbbrevDefinition { + params: params.into(), + body: manifest, + }, + ctx.type_list(args), + ); + if let Some(instance_level) = instance_level { + ctx.add_gadt_instances( + env.gadt_instance_scope(), + instance_level, + &[ty, expanded], + ); + } + Ok(expanded) + }; let can_expand_decl_manifest = |decl: &super::decl::TypeDeclaration, manifest: TypeExprRef| { @@ -4730,8 +4869,9 @@ fn try_expand_head_with_mode( if let Some(manifest) = constraint_decl.type_manifest { let params = &constraint_decl.type_params; if params.len() == args.len() { - let expanded = expand_with_subst(params, manifest); - return Some(expanded); + let expansion_level = + constraint_decl.type_newtype_level.map(|(_, level)| level); + return expand_with_subst(params, manifest, expansion_level).map(Some); } } } @@ -4745,7 +4885,7 @@ fn try_expand_head_with_mode( .find_type_by_ident(id) .is_ok_and(|decl| decl.type_manifest.is_none()) { - return None; + return Ok(None); } // Qualified heads: the outcome depends only on the module scope, @@ -4776,9 +4916,11 @@ fn try_expand_head_with_mode( expansion } }; - return match expansion { + return Ok(match expansion { + // A declaration reached through a module has no + // newtype level, hence no expansion level. PdotExpansion::Expand { params, manifest } => { - Some(expand_with_subst(¶ms, manifest)) + expand_with_subst(¶ms, manifest, None).map(Some)? } PdotExpansion::Rewrite(target) => { let level = ctx.get_level(ty); @@ -4791,7 +4933,7 @@ fn try_expand_head_with_mode( Some(rewritten) } PdotExpansion::None => None, - }; + }); } // 1. Prefer environment lookup when the declaration matches the @@ -4869,8 +5011,10 @@ fn try_expand_head_with_mode( if can_expand_decl_manifest(env_decl, manifest) { let params = &env_decl.type_params; if params.len() == args.len() { - let expanded = expand_with_subst(params, manifest); - return Some(expanded); + let expansion_level = + env_decl.type_newtype_level.map(|(_, level)| level); + return expand_with_subst(params, manifest, expansion_level) + .map(Some); } else { forbid_fallback_manifest_expansion = true; } @@ -4956,14 +5100,14 @@ fn try_expand_head_with_mode( abbrev: orig_abbrev, }); ctx.set_level(rewritten, level); - return Some(rewritten); + return Ok(Some(rewritten)); } } if can_expand_decl_manifest(&decl, manifest) { let params = &decl.type_params; if params.len() == args.len() { - let expanded = expand_with_subst(params, manifest); - return Some(expanded); + let expansion_level = decl.type_newtype_level.map(|(_, level)| level); + return expand_with_subst(params, manifest, expansion_level).map(Some); } else { forbid_fallback_manifest_expansion = true; } @@ -4978,7 +5122,7 @@ fn try_expand_head_with_mode( // `expand_head_unif`, so keep unification on the same path instead // of recovering later with Rust-only alias fallback work. if local_env_type_is_authoritative && forbid_fallback_manifest_expansion { - return None; + return Ok(None); } { let path_norm = match mode { @@ -4995,13 +5139,13 @@ fn try_expand_head_with_mode( abbrev: orig_abbrev, }); ctx.set_level(normalized, level); - Some(normalized) + Ok(Some(normalized)) } else { - None + Ok(None) } } } - _ => None, + _ => Ok(None), } } @@ -7194,7 +7338,43 @@ fn expand_head_with_mode( ty: TypeExprRef, mode: ExpandHeadMode, ) -> TypeExprRef { - let mut current = ctx.repr(ty); + match expand_head_traced(ctx, env, ty, mode, false) { + Ok(expanded) => expanded, + Err(_) => unreachable!("a safe expansion reports no ambiguous GADT instance"), + } +} + +/// OCaml `expand_head_unif` (compiler/ml/ctype.ml:1279) for unification: +/// an expansion that would let a GADT instance out of its equation's scope +/// is OCaml's `Unify [(ty, newvar2 level)]` (ctype.ml:1225). +fn expand_head_unif_traced( + ctx: &TypeContext, + env: &Env, + ty: TypeExprRef, + mode: ExpandHeadMode, +) -> TypeResult { + expand_head_traced(ctx, env, ty, mode, true).map_err(|ambiguous| { + let level = ctx.get_level(ambiguous); + TypeError::Unify(vec![(ambiguous, new_var_at_level(ctx, level))]) + }) +} + +/// OCaml `try_expand_head` (compiler/ml/ctype.ml:1266-1276): expand the head +/// of `ty` until it cannot be expanded, with `try_expand_once` when +/// `unsafe_once` (an ambiguous instance is `Err`) and `try_expand_safe` +/// otherwise. When the result is a GADT instance, `ty` and the expansions +/// memorized from it join its set. At most 20 expansions; the instance test +/// is one load and one branch when the unit has no instance scope. +fn expand_head_traced( + ctx: &TypeContext, + env: &Env, + ty: TypeExprRef, + mode: ExpandHeadMode, + unsafe_once: bool, +) -> Result { + let start = ctx.repr(ty); + let mut current = start; + let mut expanded_once = false; // Stack-allocated cycle detection for up to 20 iterations. // Linear scan is faster than HashSet for this small size. let mut seen = [TypeExprRef(0); 20]; @@ -7204,8 +7384,14 @@ fn expand_head_with_mode( } seen[seen_len] = current; let seen_len = seen_len + 1; - match try_expand_head_with_mode(ctx, env, current, mode) { + let next = if unsafe_once { + try_expand_head_traced(ctx, env, current, mode)? + } else { + try_expand_head_with_mode(ctx, env, current, mode) + }; + match next { Some(expanded) => { + expanded_once = true; let expanded = ctx.repr(expanded); if expanded == current { break; @@ -7218,7 +7404,12 @@ fn expand_head_with_mode( None => break, } } - current + // ctype.ml:1273-1275: `ty` and its expansions are instances where the + // full expansion is one. + if expanded_once && let Some(level) = gadt_instance_level(ctx, env, current) { + ctx.add_gadt_instance_chain(env.gadt_instance_scope(), level, start); + } + Ok(current) } // ============================================================================ @@ -8032,7 +8223,10 @@ pub fn unify( state.mark_unified(t1, t2); // Get descriptors - let result = unify_types(ctx, state, t1, t2, t2); + let result = match unify_newtypes(ctx, state, t1, t2) { + Some(result) => result, + None => unify_types(ctx, state, t1, t2, t2), + }; let result = if let Err(TypeError::Unify(trace)) = &result { // Add this pair to the trace @@ -8665,8 +8859,8 @@ fn unify_types( if !facts.is_some_and(|facts| facts.var_free) { if ty_is_constr && state.env().is_some() && deep_occur(ctx, var, ty) { let env = state.env().expect("checked above"); - let exp1 = expand_head_unif(ctx, env, t1); - let exp2 = expand_head_unif(ctx, env, t2); + let exp1 = expand_head_unif_traced(ctx, env, t1, ExpandHeadMode::Unify)?; + let exp2 = expand_head_unif_traced(ctx, env, t2, ExpandHeadMode::Unify)?; return unify_after_expansion(ctx, state, t1, exp1, t2, exp2); } if occur_check(ctx, state.env(), state.mode, var, ty).is_err() { @@ -8799,8 +8993,8 @@ fn unify_types( // OCaml compiler/ml/ctype.ml:2338-2344 (`unify2`) expands // both constructor heads before the constructor-path cases // at ctype.ml:2412-2414 are considered. - let exp1 = expand_head_unif(ctx, env, t1); - let exp2 = expand_head_unif(ctx, env, t2); + let exp1 = expand_head_unif_traced(ctx, env, t1, ExpandHeadMode::Unify)?; + let exp2 = expand_head_unif_traced(ctx, env, t2, ExpandHeadMode::Unify)?; if exp1 != t1 || exp2 != t2 { return unify_after_expansion(ctx, state, t1, exp1, t2, exp2); } @@ -8914,8 +9108,8 @@ fn unify_types( // persistent aliases such as `Stdlib.Lazy.t` do not repeatedly // allocate normalized-but-still-abstract heads before argument // unification. - let exp1 = expand_head_unif(ctx, env, t1); - let exp2 = expand_head_unif(ctx, env, t2); + let exp1 = expand_head_unif_traced(ctx, env, t1, ExpandHeadMode::Unify)?; + let exp2 = expand_head_unif_traced(ctx, env, t2, ExpandHeadMode::Unify)?; if exp1 != t1 || exp2 != t2 { return unify_after_expansion(ctx, state, t1, exp1, t2, exp2); } @@ -9179,13 +9373,15 @@ fn unify_types( if is_constr1 || is_constr2 { if let Some(env) = state.env() { // Fully expand both sides through all aliases + // An ambiguous GADT instance fails as in OCaml's + // `expand_head_unif` (ctype.ml:2291-2292). let exp1 = if is_constr1 { - expand_head(ctx, env, t1) + expand_head_unif_traced(ctx, env, t1, ExpandHeadMode::General)? } else { t1 }; let exp2 = if is_constr2 { - expand_head(ctx, env, t2) + expand_head_unif_traced(ctx, env, t2, ExpandHeadMode::General)? } else { t2 }; diff --git a/compiler-rust/src/types/env.rs b/compiler-rust/src/types/env.rs index 8fcfe79887..b0c23bf0bf 100644 --- a/compiler-rust/src/types/env.rs +++ b/compiler-rust/src/types/env.rs @@ -1561,6 +1561,10 @@ struct EnvData { /// Local constraints (for GADTs). local_constraints: PersistentHashMap>, + /// The innermost GADT instance scope (OCaml `gadt_instances`, + /// compiler/ml/env.ml:368); its sets live in the [`TypeContext`]. + gadt_instances: super::context::GadtScopeRef, + /// The label array `store_type` described with each local record type /// (compiler/ml/env.ml:1561-1569 stores `(decl, (constructors, labels))` /// in `env.types`): what `find_type_descrs (Pident id)` returns. @@ -1657,6 +1661,7 @@ impl Env { scope_caches: std::rc::Rc::default(), implicit_open_roots: PersistentHashSet::default(), local_constraints: PersistentHashMap::default(), + gadt_instances: super::context::GadtScopeRef::NONE, type_label_families: PersistentHashMap::default(), flags: EnvFlags::default(), }), @@ -2797,11 +2802,21 @@ impl Env { .map(|(p, d)| (p, d.as_ref())) } - /// `Env.add_gadt_instance_level` (env.ml) returns a fresh Env record. - /// Rust does not track GADT instances, so only the fresh scope identity - /// that the scope-keyed caches observe is kept. - pub fn add_gadt_instance_level(&mut self) { + /// OCaml `Env.add_gadt_instance_level lv` (compiler/ml/env.ml:1307-1308): + /// enter a new, empty GADT instance set at `level`. The set lives in + /// `ctx`; the environment keeps its handle, so clones share it as OCaml's + /// share the `ref`. O(1) amortized, plus the copy of the shared bindings + /// record if another environment holds it. + pub fn add_gadt_instance_level(&mut self, ctx: &TypeContext, level: i32) { self.bump_scope(); + let parent = self.data.gadt_instances; + self.data_mut().gadt_instances = ctx.new_gadt_instance_scope(level, parent); + } + + /// The innermost GADT instance scope, `NONE` outside every one. O(1). + #[inline] + pub fn gadt_instance_scope(&self) -> super::context::GadtScopeRef { + self.data.gadt_instances } // ======================================================================== @@ -3481,7 +3496,7 @@ mod tests { env, env.add_local_constraint(Path::pident(id), declaration.clone()) ); - extends!(env, env.add_gadt_instance_level()); + extends!(env, env.add_gadt_instance_level(&ctx, 1)); extends!(env, env.mark_implicit_open_root("Stdlib")); let coerced = retained.implicit_coercion(); assert_ne!(coerced.id(), original_id); diff --git a/compiler-rust/src/types/typecore.rs b/compiler-rust/src/types/typecore.rs index ff11f187a0..3058102b93 100644 --- a/compiler-rust/src/types/typecore.rs +++ b/compiler-rust/src/types/typecore.rs @@ -11973,7 +11973,7 @@ fn type_match( gadt_lev = ctx.current_stamp(); ctx.init_def(gadt_lev + 1000); let mut scoped_env = val_case_env.clone(); - scoped_env.add_gadt_instance_level(); + scoped_env.add_gadt_instance_level(ctx, gadt_lev); gadt_match_env = scoped_env; &gadt_match_env } else { @@ -13622,7 +13622,7 @@ fn type_function_nary( let lev = ctx.current_stamp(); ctx.init_def(lev + 1000); let mut env = env.clone(); - env.add_gadt_instance_level(); + env.add_gadt_instance_level(ctx, lev); (lev, env) } let gadt_env; diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_abbrev.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_abbrev.res.expected new file mode 100644 index 0000000000..d272f9c84b --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_abbrev.res.expected @@ -0,0 +1,16 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_abbrev.res:5:31 + + 3 │ let f = (type a, x: t, y: a) => + 4 │ switch x { + 5 │ | U => if true { y } else { 0 } + 6 │ } + 7 │ + + This has type: int + But this if statement is expected to return: a (defined as int) + This instance of int is ambiguous: + it would escape the scope of its equation + + if expressions must return the same type in all branches (if, else if, else). \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_abbrev_annotated.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_abbrev_annotated.res.expected new file mode 100644 index 0000000000..d5cff8bd1d --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_abbrev_annotated.res.expected @@ -0,0 +1,16 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_abbrev_annotated.res:5:36 + + 3 │ let f = (type a, x: t, y: a) => + 4 │ switch x { + 5 │ | U => if true { (1: u) } else { y } + 6 │ } + 7 │ + + This has type: a (defined as int) + But this if statement is expected to return: u (defined as int) + This instance of int is ambiguous: + it would escape the scope of its equation + + if expressions must return the same type in all branches (if, else if, else). \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_abbrev_chain.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_abbrev_chain.res.expected new file mode 100644 index 0000000000..6657fc4afd --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_abbrev_chain.res.expected @@ -0,0 +1,20 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_abbrev_chain.res:6:14 + + 4 │ let f = (type a, x: t, y: a) => + 5 │ switch x { + 6 │ | V => [y, 0] + 7 │ } + 8 │ + + This array item has type: int + But this array is expected to have items of type: a (defined as int) + This instance of int is ambiguous: + it would escape the scope of its equation + + Arrays can only contain items of the same type. + + Possible solutions: + - Convert all values in the array to the same type. + - Use a tuple, if your array is of fixed length. Tuples can mix types freely, and compiles to a JavaScript array. Example of a tuple: `let myTuple = (10, "hello", 15.5, true) \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_array.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_array.res.expected new file mode 100644 index 0000000000..7b91ebb2ae --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_array.res.expected @@ -0,0 +1,20 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_array.res:4:16 + + 2 │ let f = (type a, x: t, y: a) => + 3 │ switch x { + 4 │ | Int => [y, 0] + 5 │ | Str => [] + 6 │ } + + This array item has type: int + But this array is expected to have items of type: a (defined as int) + This instance of int is ambiguous: + it would escape the scope of its equation + + Arrays can only contain items of the same type. + + Possible solutions: + - Convert all values in the array to the same type. + - Use a tuple, if your array is of fixed length. Tuples can mix types freely, and compiles to a JavaScript array. Example of a tuple: `let myTuple = (10, "hello", 15.5, true) \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_eq_witness.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_eq_witness.res.expected new file mode 100644 index 0000000000..d7149de083 --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_eq_witness.res.expected @@ -0,0 +1,16 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_eq_witness.res:4:34 + + 2 │ let f = (type a, e: eq, y: a) => + 3 │ switch e { + 4 │ | Refl => if true { y } else { 0 } + 5 │ } + 6 │ + + This has type: int + But this if statement is expected to return: a (defined as int) + This instance of int is ambiguous: + it would escape the scope of its equation + + if expressions must return the same type in all branches (if, else if, else). \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_function_returned.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_function_returned.res.expected new file mode 100644 index 0000000000..edb7c7816f --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_function_returned.res.expected @@ -0,0 +1,16 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_function_returned.res:4:35 + + 2 │ let f = (type a, x: t, y: a) => + 3 │ switch x { + 4 │ | Int => b => if b { y } else { 0 } + 5 │ } + 6 │ + + This has type: int + But this if statement is expected to return: a (defined as int) + This instance of int is ambiguous: + it would escape the scope of its equation + + if expressions must return the same type in all branches (if, else if, else). \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_if.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_if.res.expected new file mode 100644 index 0000000000..b9aa5bb8a9 --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_if.res.expected @@ -0,0 +1,16 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_if.res:4:33 + + 2 │ let f = (type a, x: t, y: a) => + 3 │ switch x { + 4 │ | Int => if true { y } else { 0 } + 5 │ } + 6 │ + + This has type: int + But this if statement is expected to return: a (defined as int) + This instance of int is ambiguous: + it would escape the scope of its equation + + if expressions must return the same type in all branches (if, else if, else). \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_inner_switch.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_inner_switch.res.expected new file mode 100644 index 0000000000..e429ccf336 --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_inner_switch.res.expected @@ -0,0 +1,16 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_inner_switch.res:7:16 + + 5 ┆ switch b { + 6 ┆ | true => y + 7 ┆ | false => 0 + 8 ┆ } + 9 ┆ } + + This has type: int + But this if statement is expected to return: a (defined as int) + This instance of int is ambiguous: + it would escape the scope of its equation + + if expressions must return the same type in all branches (if, else if, else). \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_let_after_switch.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_let_after_switch.res.expected new file mode 100644 index 0000000000..c8689be0bc --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_let_after_switch.res.expected @@ -0,0 +1,16 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_let_after_switch.res:6:28 + + 4 ┆ | Int => { + 5 ┆ let w = 0 + 6 ┆ if true { w } else { y } + 7 ┆ } + 8 ┆ } + + This has type: a (defined as int) + But this if statement is expected to return: int + This instance of int is ambiguous: + it would escape the scope of its equation + + if expressions must return the same type in all branches (if, else if, else). \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_nested_pattern.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_nested_pattern.res.expected new file mode 100644 index 0000000000..33b38a12e7 --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_nested_pattern.res.expected @@ -0,0 +1,16 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_nested_pattern.res:4:39 + + 2 │ let f = (type a, x: option>, y: a) => + 3 │ switch x { + 4 │ | Some(Int) => if true { y } else { 0 } + 5 │ | None => y + 6 │ } + + This has type: int + But this if statement is expected to return: a (defined as int) + This instance of int is ambiguous: + it would escape the scope of its equation + + if expressions must return the same type in all branches (if, else if, else). \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_object.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_object.res.expected new file mode 100644 index 0000000000..7a9262099d --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_object.res.expected @@ -0,0 +1,19 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_object.res:4:40-47 + + 2 │ let f = (type a, x: t, y: a) => + 3 │ switch x { + 4 │ | Int => if true { {"f": y} } else { {"f": 0} } + 5 │ } + 6 │ + + This has type: {"f": int} + But this if statement is expected to return: {"f": a} + + The incompatible parts: + int vs a (defined as int) + This instance of int is ambiguous: + it would escape the scope of its equation + + if expressions must return the same type in all branches (if, else if, else). \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_object_open.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_object_open.res.expected new file mode 100644 index 0000000000..02799d0536 --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_object_open.res.expected @@ -0,0 +1,19 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_object_open.res:6:28-35 + + 4 ┆ | Int => { + 5 ┆ ignore(o["f"] + 1) + 6 ┆ if true { o } else { {"f": y} } + 7 ┆ } + 8 ┆ } + + This has type: {"f": a} + But this if statement is expected to return: {.."f": int} + + The incompatible parts: + a (defined as int) vs int + This instance of int is ambiguous: + it would escape the scope of its equation + + if expressions must return the same type in all branches (if, else if, else). \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_outer_abstract.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_outer_abstract.res.expected new file mode 100644 index 0000000000..85a88315e7 --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_outer_abstract.res.expected @@ -0,0 +1,16 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_outer_abstract.res:5:35 + + 3 ┆ let g = (y: a) => + 4 ┆ switch x { + 5 ┆ | Int => if true { y } else { 0 } + 6 ┆ } + 7 ┆ g + + This has type: int + But this if statement is expected to return: a (defined as int) + This instance of int is ambiguous: + it would escape the scope of its equation + + if expressions must return the same type in all branches (if, else if, else). \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_polyvariant.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_polyvariant.res.expected new file mode 100644 index 0000000000..33d98bab3f --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_polyvariant.res.expected @@ -0,0 +1,14 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_polyvariant.res:4:40 + + 2 │ let f = (type a, x: t, y: a) => + 3 │ switch x { + 4 │ | Int => if true { #A(y) } else { #A(0) } + 5 │ } + 6 │ + + This has type: int + But it's expected to have type: a (defined as int) + This instance of int is ambiguous: + it would escape the scope of its equation \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_record_field.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_record_field.res.expected new file mode 100644 index 0000000000..52820b3ce1 --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_record_field.res.expected @@ -0,0 +1,18 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_record_field.res:5:12-23 + + 3 │ let f = (type a, x: t, y: a) => + 4 │ switch x { + 5 │ | Int => {a: y, b: 0} + 6 │ } + 7 │ + + This has type: r + But it's expected to have type: 'a + This instance of int is ambiguous: + it would escape the scope of its equation + + Possible solutions: + - These types are compatible at runtime. You can use the coercion operator to convert to the expected type: ({a: y, b: 0} :> r) + \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_ref_assigned.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_ref_assigned.res.expected new file mode 100644 index 0000000000..e429b162cd --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_ref_assigned.res.expected @@ -0,0 +1,16 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_ref_assigned.res:5:43 + + 3 ┆ let r = ref(None) + 4 ┆ switch x { + 5 ┆ | Int => r := Some(if true { y } else { 0 }) + 6 ┆ } + 7 ┆ r.contents + + This has type: int + But this if statement is expected to return: a (defined as int) + This instance of int is ambiguous: + it would escape the scope of its equation + + if expressions must return the same type in all branches (if, else if, else). \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_two_equations.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_two_equations.res.expected new file mode 100644 index 0000000000..a390312114 --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_two_equations.res.expected @@ -0,0 +1,16 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_two_equations.res:4:33 + + 2 │ let f = (type a, x: t, y: a) => + 3 │ switch x { + 4 │ | Int => if true { y } else { 0 } + 5 │ | Str => if true { y } else { "" } + 6 │ } + + This has type: int + But this if statement is expected to return: a (defined as int) + This instance of int is ambiguous: + it would escape the scope of its equation + + if expressions must return the same type in all branches (if, else if, else). \ No newline at end of file diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_abbrev.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_abbrev.res new file mode 100644 index 0000000000..8d0d294f06 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_abbrev.res @@ -0,0 +1,6 @@ +type u = int +type rec t<_> = U: t +let f = (type a, x: t, y: a) => + switch x { + | U => if true { y } else { 0 } + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_abbrev_annotated.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_abbrev_annotated.res new file mode 100644 index 0000000000..1325f8b7bc --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_abbrev_annotated.res @@ -0,0 +1,6 @@ +type u = int +type rec t<_> = U: t +let f = (type a, x: t, y: a) => + switch x { + | U => if true { (1: u) } else { y } + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_abbrev_chain.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_abbrev_chain.res new file mode 100644 index 0000000000..483e6919cc --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_abbrev_chain.res @@ -0,0 +1,7 @@ +type u = int +type v = u +type rec t<_> = V: t +let f = (type a, x: t, y: a) => + switch x { + | V => [y, 0] + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_array.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_array.res new file mode 100644 index 0000000000..d7045a4a1b --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_array.res @@ -0,0 +1,6 @@ +type rec t<_> = Int: t | Str: t +let f = (type a, x: t, y: a) => + switch x { + | Int => [y, 0] + | Str => [] + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_eq_witness.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_eq_witness.res new file mode 100644 index 0000000000..9d31ef50f3 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_eq_witness.res @@ -0,0 +1,5 @@ +type rec eq<'a, 'b> = Refl: eq<'a, 'a> +let f = (type a, e: eq, y: a) => + switch e { + | Refl => if true { y } else { 0 } + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_function_returned.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_function_returned.res new file mode 100644 index 0000000000..468434ffbf --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_function_returned.res @@ -0,0 +1,5 @@ +type rec t<_> = Int: t +let f = (type a, x: t, y: a) => + switch x { + | Int => b => if b { y } else { 0 } + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_if.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_if.res new file mode 100644 index 0000000000..4cb5226a48 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_if.res @@ -0,0 +1,5 @@ +type rec t<_> = Int: t +let f = (type a, x: t, y: a) => + switch x { + | Int => if true { y } else { 0 } + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_inner_switch.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_inner_switch.res new file mode 100644 index 0000000000..3eef35b074 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_inner_switch.res @@ -0,0 +1,9 @@ +type rec t<_> = Int: t +let f = (type a, x: t, y: a, b) => + switch x { + | Int => + switch b { + | true => y + | false => 0 + } + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_let_after_switch.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_let_after_switch.res new file mode 100644 index 0000000000..38e4ec068c --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_let_after_switch.res @@ -0,0 +1,10 @@ +type rec t<_> = Int: t +let f = (type a, x: t, y: a) => { + let z = switch x { + | Int => { + let w = 0 + if true { w } else { y } + } + } + z +} diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_nested_pattern.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_nested_pattern.res new file mode 100644 index 0000000000..8aa08ae986 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_nested_pattern.res @@ -0,0 +1,6 @@ +type rec t<_> = Int: t +let f = (type a, x: option>, y: a) => + switch x { + | Some(Int) => if true { y } else { 0 } + | None => y + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_object.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_object.res new file mode 100644 index 0000000000..ec6ef54708 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_object.res @@ -0,0 +1,5 @@ +type rec t<_> = Int: t +let f = (type a, x: t, y: a) => + switch x { + | Int => if true { {"f": y} } else { {"f": 0} } + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_object_open.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_object_open.res new file mode 100644 index 0000000000..95460e8fb3 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_object_open.res @@ -0,0 +1,8 @@ +type rec t<_> = Int: t +let f = (type a, x: t, y: a, o) => + switch x { + | Int => { + ignore(o["f"] + 1) + if true { o } else { {"f": y} } + } + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_outer_abstract.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_outer_abstract.res new file mode 100644 index 0000000000..a0d4f193f6 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_outer_abstract.res @@ -0,0 +1,8 @@ +type rec t<_> = Int: t +let f = (type a, x: t) => { + let g = (y: a) => + switch x { + | Int => if true { y } else { 0 } + } + g +} diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_polyvariant.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_polyvariant.res new file mode 100644 index 0000000000..7d3b739c31 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_polyvariant.res @@ -0,0 +1,5 @@ +type rec t<_> = Int: t +let f = (type a, x: t, y: a) => + switch x { + | Int => if true { #A(y) } else { #A(0) } + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_record_field.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_record_field.res new file mode 100644 index 0000000000..6bcb6982eb --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_record_field.res @@ -0,0 +1,6 @@ +type rec t<_> = Int: t +type r<'a> = {a: 'a, b: 'a} +let f = (type a, x: t, y: a) => + switch x { + | Int => {a: y, b: 0} + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_ref_assigned.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_ref_assigned.res new file mode 100644 index 0000000000..5be11259b0 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_ref_assigned.res @@ -0,0 +1,8 @@ +type rec t<_> = Int: t +let f = (type a, x: t, y: a) => { + let r = ref(None) + switch x { + | Int => r := Some(if true { y } else { 0 }) + } + r.contents +} diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_two_equations.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_two_equations.res new file mode 100644 index 0000000000..1344df69cf --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_two_equations.res @@ -0,0 +1,6 @@ +type rec t<_> = Int: t | Str: t +let f = (type a, x: t, y: a) => + switch x { + | Int => if true { y } else { 0 } + | Str => if true { y } else { "" } + } diff --git a/tests/tests/src/gadt_instance_ambiguous_accepted.mjs b/tests/tests/src/gadt_instance_ambiguous_accepted.mjs new file mode 100644 index 0000000000..b7d60680cf --- /dev/null +++ b/tests/tests/src/gadt_instance_ambiguous_accepted.mjs @@ -0,0 +1,234 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Stdlib_List from "@rescript/runtime/lib/es6/Stdlib_List.mjs"; + +function f(x, y) { + return y; +} + +let ResultAnnotation = { + f: f +}; + +function f$1(x, y) { + return y + 1 | 0; +} + +let PlusOne = { + f: f$1 +}; + +function f$2(x, y) { + if (x === "Int") { + return [ + 0, + 1 + ]; + } else { + return [ + y, + 2 + ]; + } +} + +let TupleTwoCases = { + f: f$2 +}; + +function f$3(e, x, y) { + return x; +} + +let EqTwoVars = { + f: f$3 +}; + +function f$4(x, y) { + return y; +} + +let BranchAnnotation = { + f: f$4 +}; + +function h(n) { + return (n << 1); +} + +function f$5(x, y) { + return (y << 1); +} + +let PassToIntFn = { + h: h, + f: f$5 +}; + +function g(e) { + return e._1 + 1 | 0; +} + +let ExistentialNoEscape = { + g: g +}; + +function f$6(x, y) { + if (x === "Int") { + return [ + y, + 0 + ]; + } else { + return []; + } +} + +let ArrayResultAnnotation = { + f: f$6 +}; + +function g$1(e) { + +} + +let ExistentialIgnored = { + g: g$1 +}; + +function f$7(x, y) { + return { + NAME: "A", + VAL: y + }; +} + +let PolyvariantOpen = { + f: f$7 +}; + +function f$8(x, y) { + return y; +} + +let ResultIsA = { + f: f$8 +}; + +function f$9(x, y, o) { + return { + f: 0, + g: y + }; +} + +let ObjectFieldLevel = { + f: f$9 +}; + +function f$10(x, y, v) { + if (typeof v === "object") { + return { + NAME: "A", + VAL: v.VAL + }; + } else { + return "B"; + } +} + +let PolyvariantClosed = { + f: f$10 +}; + +function f$11(x, y) { + let r = { + contents: [] + }; + r.contents = [y]; + return r; +} + +let Unify2ChainEscape = { + f: f$11 +}; + +function g$2(n, m) { + return n + m | 0; +} + +function f$12(x, y) { + return extra => y + extra | 0; +} + +let LowerArgs = { + g: g$2, + f: f$12 +}; + +function f$13(x, y) { + if (x === "Int") { + return 0; + } else { + return Stdlib_List.length(y); + } +} + +let LocalAbbrevRec = { + f: f$13 +}; + +function f$14(x, z, y, w) { + return [ + y + 1 | 0, + w + ]; +} + +let NestedSwitchLevels = { + f: f$14 +}; + +function f$15(x, y) { + let o = { + m: y + }; + return o.m + 0 | 0; +} + +let FieldObjectMethod = { + f: f$15 +}; + +function f$16(x, y) { + let r = y; + r = r + 1 | 0; + return r; +} + +let WhileRef = { + f: f$16 +}; + +export { + ResultAnnotation, + PlusOne, + TupleTwoCases, + EqTwoVars, + BranchAnnotation, + PassToIntFn, + ExistentialNoEscape, + ArrayResultAnnotation, + ExistentialIgnored, + PolyvariantOpen, + ResultIsA, + ObjectFieldLevel, + PolyvariantClosed, + Unify2ChainEscape, + LowerArgs, + LocalAbbrevRec, + NestedSwitchLevels, + FieldObjectMethod, + WhileRef, +} +/* No side effect */ diff --git a/tests/tests/src/gadt_instance_ambiguous_accepted.res b/tests/tests/src/gadt_instance_ambiguous_accepted.res new file mode 100644 index 0000000000..e01ecccb98 --- /dev/null +++ b/tests/tests/src/gadt_instance_ambiguous_accepted.res @@ -0,0 +1,186 @@ +// Programs where a GADT equation's type does not leave its case: both +// compilers accept them (the refused ones are the super_errors fixtures +// gadt_instance_ambiguous_*). + +module ResultAnnotation = { + type rec t<_> = Int: t + let f = (type a, x: t, y: a): int => + switch x { + | Int => if true { y } else { 0 } + } +} + +module PlusOne = { + type rec t<_> = Int: t + let f = (type a, x: t, y: a) => + switch x { + | Int => y + 1 + } +} + +module TupleTwoCases = { + type rec t<_> = Int: t | Int2: t + let f = (type a, x: t, y: a) => + switch x { + | Int => (0, 1) + | Int2 => (y, 2) + } +} + +module EqTwoVars = { + type rec eq<'a, 'b> = Refl: eq<'a, 'a> + let f = (type a b, e: eq, x: a, y: b) => + switch e { + | Refl => if true { x } else { y } + } +} + +module BranchAnnotation = { + type rec t<_> = Int: t + let f = (type a, x: t, y: a) => + switch x { + | Int => if true { (y: int) } else { 0 } + } +} + +module PassToIntFn = { + type rec t<_> = Int: t + let h = (n: int) => n * 2 + let f = (type a, x: t, y: a) => + switch x { + | Int => h(y) + } +} + +module ExistentialNoEscape = { + type rec t<_> = Int: t + type rec ex = Ex(t<'a>, 'a): ex + let g = e => + switch e { + | Ex(Int, v) => v + 1 + } +} + +module ArrayResultAnnotation = { + type rec t<_> = Int: t | Str: t + let f = (type a, x: t, y: a): array => + switch x { + | Int => [y, 0] + | Str => [] + } +} + +module ExistentialIgnored = { + type rec t<_> = Int: t + type rec ex = Ex(t<'a>, 'a): ex + let g = e => + switch e { + | Ex(Int, v) => ignore(v) + } +} + +module PolyvariantOpen = { + type rec t<_> = Int: t + let f = (type a, x: t, y: a) => + switch x { + | Int => if true { #A(y) } else { #B(0) } + } +} + +module ResultIsA = { + type rec t<_> = Int: t + let f = (type a, x: t, y: a): a => + switch x { + | Int => if true { y } else { 0 } + } +} + +module ObjectFieldLevel = { + type rec t<_> = Int: t + let f = (type a, x: t, y: a, o: {..}) => + switch x { + | Int => { + let p = {"f": 0, "g": y} + if true { p } else { o } + } + } +} + +module PolyvariantClosed = { + type rec t<_> = Int: t + let f = (type a, x: t, y: a, v: [< #A(int) | #B]) => + switch x { + | Int => + switch v { + | #A(n) => if true { #A(n) } else { #A(y) } + | #B => #B + } + } +} + +module Unify2ChainEscape = { + type rec t<_> = Int: t + type u = int + let f = (type a, x: t, y: a) => { + let r = ref([]) + switch x { + | Int => { + let z: u = y + r := [z] + } + } + r + } +} + +module LowerArgs = { + type rec t<_> = Int: t + let g = (n: int, m) => n + m + let f = (type a, x: t, y: a) => + switch x { + | Int => g(y, ...) + } +} + +module LocalAbbrevRec = { + type rec t<_> = Int: t | L: t> + let f = (type a, x: t, y: a) => + switch x { + | Int => 0 + | L => List.length(y) + } +} + +module NestedSwitchLevels = { + type rec t<_> = Int: t + type rec s<_> = Str: s + let f = (type a b, x: t, z: s, y: a, w: b) => + switch x { + | Int => + switch z { + | Str => (y + 1, w ++ "") + } + } +} + +module FieldObjectMethod = { + type rec t<_> = Int: t + let f = (type a, x: t, y: a) => + switch x { + | Int => { + let o = {"m": y} + o["m"] + 0 + } + } +} + +module WhileRef = { + type rec t<_> = Int: t + let f = (type a, x: t, y: a) => { + let r = ref(y) + switch x { + | Int => r.contents = r.contents + 1 + } + r.contents + } +} From 22a53a612fc325ed5d05ed6c79bd7bbd43894c64 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:13:05 +0000 Subject: [PATCH 02/30] A copy of a GADT instance joins its set, as in OCaml's copy Why: OCaml's `copy ?env` (compiler/ml/ctype.ml:770-774), reached through `instance env` and `instance_list env` (ctype.ml:879-894), adds the copy of a node in an instance set to that set when the environment has local constraints. Rust's `instance` takes no environment, so a function generalized inside a case gave copies that were no instances, and its result left the case. Typing modified (instantiating a generalized instance below its switch): Example: type rec t<_> = Int: t let f = (type a, x: t, y: a) => switch x { | Int => { let k = () => if true { y } else { 0 } k() } } Before (diagnostic): accepted; `function f(x, y) { return y; }` After (diagnostic): Main.res:6:7-9 This has type: a (defined as int) But it's expected to have type: 'a This instance of int is ambiguous: it would escape the scope of its equation `instance_in` and `instance_list_in` take the environment; the type checker's `instance env` sites use them (constants and predefined types keep `instance`, OCaml's `instance_def`). The copy is made as before; then, only in an environment with local constraints and an instance scope, the copy table is walked once and the copy of each instance is added. Without a scope in the unit an `instance` call pays one load and one branch. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/types/ctype.rs | 92 ++++++++++++ compiler-rust/src/types/type_expr.rs | 24 +++ compiler-rust/src/types/typecore.rs | 127 ++++++++-------- ...ce_ambiguous_generalized_copy.res.expected | 18 +++ ...dt_instance_ambiguous_generalized_copy.res | 8 + .../src/gadt_instance_ambiguous_accepted.mjs | 127 ++++++++++++++++ .../src/gadt_instance_ambiguous_accepted.res | 139 ++++++++++++++++++ 7 files changed, 472 insertions(+), 63 deletions(-) create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_generalized_copy.res.expected create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_generalized_copy.res diff --git a/compiler-rust/src/types/ctype.rs b/compiler-rust/src/types/ctype.rs index 93280ae92b..633af1dc7a 100644 --- a/compiler-rust/src/types/ctype.rs +++ b/compiler-rust/src/types/ctype.rs @@ -12430,6 +12430,70 @@ pub fn instance(ctx: &TypeContext, ty: TypeExprRef) -> TypeExprRef { copy_type_cached(ctx, ty, &mut cache) } +/// OCaml `instance env sch` (compiler/ml/ctype.ml:879-887): [`instance`], +/// and when `env` has local constraints, a copy of a GADT instance joins +/// the instance's set (`copy ?env`, ctype.ml:770-774). Without an instance +/// scope in the unit this costs one load and one branch more than +/// [`instance`]. +pub fn instance_in(ctx: &TypeContext, env: &Env, ty: TypeExprRef) -> TypeExprRef { + let Some(scope) = copy_instance_scope(ctx, env) else { + return instance(ctx, ty); + }; + let ty = ctx.repr(ty); + if ctx.get_level(ty) != GENERIC_LEVEL { + return ty; + } + let mut cache = CopyCache::new(ctx); + let copy = copy_type_cached(ctx, ty, &mut cache); + add_copied_gadt_instances(ctx, scope, &cache); + copy +} + +/// OCaml `instance_list env schl` (compiler/ml/ctype.ml:891-894): as +/// [`instance_in`], sharing one copy session. +pub fn instance_list_in(ctx: &TypeContext, env: &Env, types: &[TypeExprRef]) -> Vec { + let Some(scope) = copy_instance_scope(ctx, env) else { + return instance_list(ctx, types); + }; + let mut cache = CopyCache::new(ctx); + let copies = types + .iter() + .map(|&ty| copy_type_cached(ctx, ty, &mut cache)) + .collect(); + add_copied_gadt_instances(ctx, scope, &cache); + copies +} + +/// The GADT instance scope a copy in `env` adds to: OCaml's `gadt_env` +/// (ctype.ml:877), an environment with local constraints, and in it an +/// instance scope. One load and one branch when the unit has none. +#[inline] +fn copy_instance_scope(ctx: &TypeContext, env: &Env) -> Option { + if !ctx.has_gadt_instance_scopes() || !env.has_local_constraints() { + return None; + } + let scope = env.gadt_instance_scope(); + (!scope.is_none()).then_some(scope) +} + +/// `copy ?env` (compiler/ml/ctype.ml:770-774) for a finished copy session: +/// the copy of each node in an instance set joins that set. The originals +/// are not changed by the copy, so testing them afterwards is testing them +/// when they were copied. Cost: per copied node, one +/// [`TypeContext::gadt_instance_level`]; run only under local constraints +/// with an instance scope. +fn add_copied_gadt_instances( + ctx: &TypeContext, + scope: super::context::GadtScopeRef, + cache: &CopyCache<'_>, +) { + cache.nodes.for_each(|original, ©| { + if let Some(level) = ctx.gadt_instance_level(scope, ctx.repr(original)) { + ctx.add_gadt_instances(scope, level, &[copy]); + } + }); +} + /// For the compiler counters (see `TypeContext::counts_this_call`): count /// the instantiation of `roots` that `again`, the caller called again, /// runs. @@ -16074,6 +16138,34 @@ mod tests { assert_eq!(steps, 10_000); } + #[test] + fn instance_in_tests_each_copied_node_once_at_ten_thousand() { + let ctx = TypeContext::new(std::sync::Arc::new(IdGenerator::new())); + let mut env = Env::empty(); + let local = Path::pident(crate::ident::Ident::create_persistent("a")); + env.add_local_constraint(local, reified_type_decl(7)); + env.add_gadt_instance_level(&ctx, 7); + let member = ctx.new_generic_type(TypeDesc::Tvar(None)); + let mut items = vec![member]; + items.extend((1..9_999).map(|_| ctx.new_generic_type(TypeDesc::Tvar(None)))); + let tuple = ctx.new_generic_type(TypeDesc::Ttuple(ctx.new_type_list(&items))); + ctx.add_gadt_instances(env.gadt_instance_scope(), 7, &[member]); + let mut copy = tuple; + // One lookup per copied node, one step per member: the member's + // own lookup comes first and adds its copy, so each later lookup + // scans two members. + let steps = crate::tc::steps::scope(|| copy = instance_in(&ctx, &env, tuple)); + assert_eq!(steps, 1 + 2 * 9_999); + let copied_member = match &*ctx.borrow_desc(copy) { + TypeDesc::Ttuple(items) => ctx.type_list(items).get(0).expect("first item"), + _ => unreachable!("a tuple copies to a tuple"), + }; + assert_eq!(gadt_instance_level(&ctx, &env, copied_member), Some(7)); + // Outside local constraints the copy adds nothing and tests nothing. + let steps = crate::tc::steps::scope(|| copy = instance_in(&ctx, &Env::empty(), tuple)); + assert_eq!(steps, 0); + } + #[test] fn univar_scope_pairs_ten_thousand_binders_in_one_step_each() { let ctx = TypeContext::new(std::sync::Arc::new(IdGenerator::new())); diff --git a/compiler-rust/src/types/type_expr.rs b/compiler-rust/src/types/type_expr.rs index 8e5119e9b7..4ceeb6a06e 100644 --- a/compiler-rust/src/types/type_expr.rs +++ b/compiler-rust/src/types/type_expr.rs @@ -1144,6 +1144,30 @@ impl TypeExprRefMap { self.entry_count += 1; } + /// Call `f` on every entry, in no particular order. Cost: one step per + /// entry, or per handle of the span in dense storage. + pub(crate) fn for_each(&self, mut f: impl FnMut(TypeExprRef, &T)) { + match &self.storage { + TypeExprRefMapStorage::Inline { entries, len } => { + for (key, value) in entries[..*len].iter().flatten() { + f(*key, value); + } + } + TypeExprRefMapStorage::Dense { offset, values } => { + for (index, value) in values.iter().enumerate() { + if let Some(value) = value { + f(TypeExprRef(offset + index as u32), value); + } + } + } + TypeExprRefMapStorage::Sparse(values) => { + for (key, value) in values { + f(*key, value); + } + } + } + } + #[inline] pub(crate) fn get(&self, key: TypeExprRef) -> Option<&T> { match &self.storage { diff --git a/compiler-rust/src/types/typecore.rs b/compiler-rust/src/types/typecore.rs index 3058102b93..3cd474a04c 100644 --- a/compiler-rust/src/types/typecore.rs +++ b/compiler-rust/src/types/typecore.rs @@ -3188,9 +3188,9 @@ fn transl_type_inner( let ty = if let Some((_, existing)) = tctx.univars.iter().find(|(name, _)| name == &name_str) { - crate::types::instance(ctx, *existing) + crate::types::ctype::instance_in(ctx, env, *existing) } else if let Some(&existing) = tctx.used_variables.get(&name_str) { - crate::types::instance(ctx, existing) + crate::types::ctype::instance_in(ctx, env, existing) } else { let v = ctx.new_var(Some(crate::name::Name::new(&name_str))); tctx.used_variables.insert(name_str.clone(), v); @@ -3324,7 +3324,7 @@ fn transl_type_inner( ctx.get_level(manifest) == crate::types::type_expr::GENERIC_LEVEL } }; - let params = crate::types::ctype::instance_list(ctx, &decl.type_params); + let params = crate::types::ctype::instance_list_in(ctx, env, &decl.type_params); for ((param_ty, arg_ty), arg) in params.iter().zip(arg_refs.iter()).zip(parsed_args.iter()) { @@ -3402,7 +3402,7 @@ fn transl_type_inner( })?; (inner_ctyp, inner_ty) } else if let Some(existing_alias) = existing_alias { - let alias_ty = crate::types::instance(ctx, existing_alias); + let alias_ty = crate::types::ctype::instance_in(ctx, env, existing_alias); let (inner_ctyp, inner_ty) = transl_type_inner(tctx, env, inner)?; crate::types::ctype::unify_var(ctx, &mut tctx.unify_state, alias_ty, inner_ty) .map_err(|err| TypeCoreError::AliasTypeMismatch { @@ -3440,7 +3440,7 @@ fn transl_type_inner( trace: alias_type_mismatch_trace(err, inner_ty, alias_ty), })?; - let instantiated = crate::types::instance(ctx, alias_ty); + let instantiated = crate::types::ctype::instance_in(ctx, env, alias_ty); let proxy = crate::types::btype::proxy(ctx, instantiated); let rename_desc = { let proxy_desc = ctx.get_desc(proxy); @@ -7535,8 +7535,8 @@ fn type_pattern_constraint( let var_level = ctx.current_level(); crate::types::generalize_structure(ctx, var_level, ctype_ty); - let constraint_ty = crate::types::instance(ctx, ctype_ty); - let inner_expected_ty = crate::types::instance(ctx, ctype_ty); + let constraint_ty = crate::types::ctype::instance_in(ctx, env, ctype_ty); + let inner_expected_ty = crate::types::ctype::instance_in(ctx, env, ctype_ty); unify_pattern_types(tctx, loc, constraint_ty, expected_ty)?; @@ -8768,7 +8768,7 @@ fn type_expect_with_recarg_unscoped<'a>( // `Predef.type_array ty` with `ty_expected`, types elements with // `ty`, then stores `exp_type = instance env ty_expected` rather // than the temporary array node. - let exp_type = crate::types::instance(ctx, expected_ty); + let exp_type = crate::types::ctype::instance_in(ctx, env, expected_ty); Ok({ let typed_node = Expression::new( ExpressionDesc::Texp_array(tctx.typed.push_exprs(typed_exprs)), @@ -8811,7 +8811,7 @@ fn type_expect_with_recarg_unscoped<'a>( } }); } - let exp_type = crate::types::instance(ctx, expected_ty); + let exp_type = crate::types::ctype::instance_in(ctx, env, expected_ty); let node = Expression::new( ExpressionDesc::Texp_dict(tctx.typed.push_dict_entries(typed_entries)), loc, @@ -8856,7 +8856,7 @@ fn type_expect_with_recarg_unscoped<'a>( None, )?); } - let exp_type = crate::types::instance(ctx, expected_ty); + let exp_type = crate::types::ctype::instance_in(ctx, env, expected_ty); let node = Expression::new( ExpressionDesc::Texp_spread(kind, tctx.typed.push_exprs(parts)), loc, @@ -8927,7 +8927,7 @@ fn type_expect_with_recarg_unscoped<'a>( if crate::types::ctype::unify( ctx, &mut tctx.unify_state, - crate::types::instance(ctx, tag.exp_type), + crate::types::ctype::instance_in(ctx, env, tag.exp_type), tag_ty, ) .is_err() @@ -9351,7 +9351,7 @@ fn type_identifier( note_value_ident_use(tctx, env, longident, lid.loc, &path, &desc, deprecated_function_call)?; check_inlined_record_escape(ctx, loc, desc.val_type, recarg)?; - let ty = crate::types::instance(ctx, desc.val_type); + let ty = crate::types::ctype::instance_in(ctx, env, desc.val_type); finish_expected_at(tctx, expr, loc, ty, expected_ty, context)?; Ok({ @@ -10288,7 +10288,7 @@ fn type_application_parts( filter_arrow_for_lowered_apply(tctx, env, typed_funct.exp_type, args.len()) { let expected = materialize_expected(tctx, sexp, expected_ty); - let expected_inst = crate::types::instance(ctx, expected); + let expected_inst = crate::types::ctype::instance_in(ctx, env, expected); unify_expression_types(tctx, loc, ty_res, expected_inst, None)?; } } @@ -10298,7 +10298,7 @@ fn type_application_parts( function_argument_type_clash_context(typed_funct_value_path.as_ref()) }; - let lowered_ty = crate::types::instance(ctx, typed_funct.exp_type); + let lowered_ty = crate::types::ctype::instance_in(ctx, env, typed_funct.exp_type); ctx.end_def(); // OCaml compiler/ml/typecore.ml:2579-2582 instances the function type and // immediately runs `lower_args` (typecore.ml:2335-2342). @@ -10373,7 +10373,7 @@ fn type_application_parts( let expanded_inst_ty = crate::types::ctype::expand_head( ctx, env, - crate::types::instance(ctx, typed_funct.exp_type), + crate::types::ctype::instance_in(ctx, env, typed_funct.exp_type), ); let (inst_params, inst_ret) = match &*ctx.borrow_desc(expanded_inst_ty) { TypeDesc::Tarrow { args, ret } if args.len() == declared_params.len() => { @@ -10486,7 +10486,7 @@ fn type_application_parts( ignored.push(OmittedArrow { param }); argument_thunks.push(ApplyArgThunk::SynthOptionalNone { label: param.label().to_arg_label(), - option_ty: crate::types::instance(ctx, param.typ), + option_ty: crate::types::ctype::instance_in(ctx, env, param.typ), }); } else { omitted.push(OmittedArrow { param }); @@ -10787,7 +10787,7 @@ fn finish_non_gadt_type_cases( unify_expression_types( tctx, loc, - crate::types::instance(ctx, ty_res), + crate::types::ctype::instance_in(ctx, env, ty_res), ctx.new_var(None), None, )?; @@ -11027,7 +11027,7 @@ fn run_unused_check( ) { tctx.drain_open_slot_uses(); let saved = std::mem::replace(&mut tctx.warning_config, warning_config); - let expected_ty = crate::types::instance(tctx.type_ctx, ty_arg_check); + let expected_ty = crate::types::ctype::instance_in(tctx.type_ctx, env, ty_arg_check); // The checker retypes counter-examples through `tctx` while it reads the // case patterns; see [`PatCase`]. let mut ta = std::mem::take(&mut tctx.typed); @@ -11556,9 +11556,9 @@ fn type_match_cases_batch_non_gadt<'a>( let case_scrutinee_ty = if erase_either { instance_for_erase_either_patterns(ctx, ty_arg) } else if propagate { - crate::types::instance(ctx, generic_scrutinee_ty) + crate::types::ctype::instance_in(ctx, env, generic_scrutinee_ty) } else { - crate::types::instance(ctx, ty_arg) + crate::types::ctype::instance_in(ctx, env, ty_arg) }; let mut state = PatternState::new(); state.reset(true); @@ -11646,9 +11646,9 @@ fn type_match_cases_batch_non_gadt<'a>( if propagate || erase_either { let propagated_ty = if erase_either { - crate::types::instance(ctx, ty_arg) + crate::types::ctype::instance_in(ctx, env, ty_arg) } else { - crate::types::instance(ctx, generic_scrutinee_ty) + crate::types::ctype::instance_in(ctx, env, generic_scrutinee_ty) }; let propagate_result = (|| -> TypeCoreResult<()> { for pending in &pending_cases { @@ -11737,7 +11737,7 @@ fn type_match_cases_batch_non_gadt<'a>( )?; // Match OCaml type_cases: `exp_type = instance env ty_res'` where // `ty_res'` is corrected per-case when the pattern contains GADTs. - let case_exp_ty = crate::types::instance(ctx, case_body_ty); + let case_exp_ty = crate::types::ctype::instance_in(ctx, env, case_body_ty); let typed_body = Expression { exp_type: case_exp_ty, ..typed_body @@ -12034,7 +12034,7 @@ fn type_match( // List.iter (fun c -> unify_exp ~context:None env c.c_rhs ty_res') cases // This links per-case body result copies back through one shared node. if has_generalized_value_patterns { - let shared_case_body_ty = crate::types::instance(ctx, expected_ty); + let shared_case_body_ty = crate::types::ctype::instance_in(ctx, env, expected_ty); for case in &typed_val_cases { let rhs = tctx.expr(case.c_rhs); let (rhs_loc, rhs_type) = (rhs.exp_loc, rhs.exp_type); @@ -12070,7 +12070,7 @@ fn type_match( unify_expression_types( tctx, loc, - crate::types::instance(ctx, ty_res), + crate::types::ctype::instance_in(ctx, env, ty_res), ctx.new_var(None), None, )?; @@ -12102,7 +12102,7 @@ fn type_match( unify_expression_types( tctx, loc, - crate::types::instance(ctx, ty_res), + crate::types::ctype::instance_in(ctx, env, ty_res), ctx.new_var(None), None, )?; @@ -12168,7 +12168,7 @@ fn type_match( }; // Keep sharing: match OCaml's `exp_type = instance env ty_expected` - let result_ty = crate::types::instance(ctx, expected_ty); + let result_ty = crate::types::ctype::instance_in(ctx, env, expected_ty); Ok({ let typed_node = Expression::new( ExpressionDesc::Texp_match( @@ -12940,7 +12940,7 @@ fn type_case_pattern_impl<'a>( let case_scrutinee_ty = if erase_either { instance_for_erase_either_patterns(tctx.type_ctx, scrutinee_ty) } else { - crate::types::instance(tctx.type_ctx, generic_scrutinee_ty) + crate::types::ctype::instance_in(tctx.type_ctx, env, generic_scrutinee_ty) }; // OCaml compiler/ml/typecore.ml:4420-4434: `type_pattern ~lev`, where // `lev` is the `init_env` level (typecore.ml:4387-4395), not the raised @@ -13059,7 +13059,7 @@ fn type_pending_case_body( &pending.unpacks, body_context, )?; - let case_exp_ty = crate::types::instance(tctx.type_ctx, case_body_ty); + let case_exp_ty = crate::types::ctype::instance_in(tctx.type_ctx, env, case_body_ty); let typed_body = Expression { exp_type: case_exp_ty, ..typed_body @@ -13554,7 +13554,7 @@ fn type_function_nary( if separate { ctx.begin_def(); } - let inst = crate::types::instance(ctx, fun_ty); + let inst = crate::types::ctype::instance_in(ctx, env, fun_ty); let expanded = crate::types::ctype::expand_head_unif(ctx, env, inst); let (mut parameter_types, result_type) = { let desc = ctx.get_desc(expanded); @@ -13668,7 +13668,7 @@ fn type_function_nary( let ty_arg_i = if erase_either { instance_for_erase_either_patterns(ctx, ty_arg_c) } else { - crate::types::instance(ctx, ty_arg_c) + crate::types::ctype::instance_in(ctx, env, ty_arg_c) }; // `type_pattern ~lev env spat ty_arg_i` returns the pattern's // environment with the GADT equations it introduced; Rust's GADT @@ -13752,7 +13752,7 @@ fn type_function_nary( run_globalize_forces(tctx, state.take_globalize_forces())?; if propagate || erase_either { tctx.set_unify_env(&body_env); - let parameter_instance = crate::types::instance(ctx, ty_arg_c); + let parameter_instance = crate::types::ctype::instance_in(ctx, env, ty_arg_c); unify_pattern_types(tctx, typed.pat_loc, typed.pat_type, parameter_instance)?; } Ok(()) @@ -13862,12 +13862,12 @@ fn type_function_nary( body_result_type, &unpacks, None, async_body, )?; let mut typed_body = Expression { - exp_type: crate::types::instance(ctx, body_result_type), + exp_type: crate::types::ctype::instance_in(ctx, env, body_result_type), ..typed_body }; if has_gadts { // typecore.ml:4136-4138. - let shared_result = crate::types::instance(ctx, result_type); + let shared_result = crate::types::ctype::instance_in(ctx, env, result_type); tctx.set_unify_env(env); unify_expression_types( tctx, @@ -13969,13 +13969,14 @@ fn type_function_nary( if do_init { // Ensure that existential types do not escape (typecore.ml:4195-4198). ctx.end_def(); - let result_instance = crate::types::instance(ctx, result_type); + let result_instance = crate::types::ctype::instance_in(ctx, env, result_type); tctx.set_unify_env(env); unify_expression_types(tctx, loc, result_instance, ctx.new_var(None), None)?; } - let exp_type = crate::types::instance( + let exp_type = crate::types::ctype::instance_in( ctx, + env, ctx.new_generic_type(TypeDesc::Tarrow { args: ctx.new_type_args_from( labels @@ -14584,8 +14585,8 @@ fn type_construct( ctx.end_def(); let var_level = ctx.current_level(); crate::types::generalize_structure(ctx, var_level, result_ty); - let result_ty_inst = crate::types::ctype::instance(ctx, result_ty); - let expected_inst = crate::types::ctype::instance(ctx, expected_ty); + let result_ty_inst = crate::types::ctype::instance_in(ctx, env, result_ty); + let expected_inst = crate::types::ctype::instance_in(ctx, env, expected_ty); unify_expression_types(tctx, loc, result_ty_inst, expected_inst, None)?; ctx.end_def(); @@ -14599,12 +14600,12 @@ fn type_construct( let mut inst_list = Vec::with_capacity(1 + arg_types_for_expect.len()); inst_list.push(result_ty); inst_list.extend(arg_types_for_expect.iter().copied()); - let mut instanced = crate::types::ctype::instance_list(ctx, &inst_list); + let mut instanced = crate::types::ctype::instance_list_in(ctx, env, &inst_list); result_ty = instanced.remove(0); let arg_types_for_unify = instanced; if !separate { - let expected_inst = crate::types::ctype::instance(ctx, expected_ty); + let expected_inst = crate::types::ctype::instance_in(ctx, env, expected_ty); unify_expression_types(tctx, loc, result_ty, expected_inst, None)?; } @@ -14684,7 +14685,7 @@ fn type_variant( // OCaml fast path: when expected type is already a variant row with // this label carrying payload, type the payload against that row slot // and keep `exp_type = instance expected_ty`. - let expected_inst = crate::types::ctype::instance(ctx, expected_ty); + let expected_inst = crate::types::ctype::instance_in(ctx, env, expected_ty); let expanded_expected = crate::types::ctype::expand_head(ctx, env, expected_ty); let expanded_expected_inst = crate::types::ctype::expand_head(ctx, env, expected_inst); @@ -15400,7 +15401,7 @@ fn type_record( ctx.begin_def(); let ty = ctx.new_constr( path, - crate::types::ctype::instance_list(ctx, &decl.type_params), + crate::types::ctype::instance_list_in(ctx, env, &decl.type_params), ); ctx.end_def(); crate::types::generalize_structure(ctx, ctx.current_level(), ty); @@ -15828,8 +15829,8 @@ fn type_record( // Match OCaml typecore.ml:3695-3698: // unify env (instance_def ty_res) (instance env ty_expected) // let ty_arg = instance_def ty_arg - let ty_res = crate::types::ctype::instance(ctx, ty_res0); - let expected_record_ty = crate::types::ctype::instance(ctx, record_ty); + let ty_res = crate::types::ctype::instance_in(ctx, env, ty_res0); + let expected_record_ty = crate::types::ctype::instance_in(ctx, env, record_ty); if let Err(err) = crate::types::unify( ctx, &mut tctx.unify_state, @@ -15847,7 +15848,7 @@ fn type_record( env: Some(tctx.type_ctx.store_typed_env(env)), }); } - (poly_vars, crate::types::ctype::instance(ctx, ty_arg0)) + (poly_vars, crate::types::ctype::instance_in(ctx, env, ty_arg0)) }; if separate { @@ -15941,7 +15942,7 @@ fn type_record( )?; // OCaml `type_argument`: after typing against `ty_expected'`, unify with // a fresh `instance` of that type to preserve sharing behavior. - let field_input_ty_inst = crate::types::ctype::instance(ctx, field_input_ty); + let field_input_ty_inst = crate::types::ctype::instance_in(ctx, env, field_input_ty); unify_expression_types( tctx, loc, @@ -15994,7 +15995,7 @@ fn type_record( // (compiler/ml/typecore.ml:1185-1198). That is a shallow record update; // mutate the owned Rust expression instead of deep-cloning its desc. let mut final_expr = final_expr; - final_expr.exp_type = crate::types::ctype::instance(ctx, final_expr.exp_type); + final_expr.exp_type = crate::types::ctype::instance_in(ctx, env, final_expr.exp_type); explicit_entries.push((std::sync::Arc::new(label_desc), field.lid, tctx.push_expr(final_expr))); } @@ -16012,7 +16013,7 @@ fn type_record( }); // OCaml: unify_exp_types ty_record (instance env ty_expected) - let expected_inst_for_record = crate::types::instance(ctx, expected_ty); + let expected_inst_for_record = crate::types::ctype::instance_in(ctx, env, expected_ty); unify_expression_types(tctx, loc, record_ty, expected_inst_for_record, None)?; // OCaml `check_duplicates` (compiler/ml/typecore.ml:2232-2245) runs after // every field is typed and the record type is unified with the expected @@ -16084,7 +16085,7 @@ fn type_record( if let Some(ref mut typed_base_expr) = typed_base { // OCaml: let ty_exp = instance env exp.exp_type - let mut ty_exp = crate::types::instance(ctx, typed_base_expr.exp_type); + let mut ty_exp = crate::types::ctype::instance_in(ctx, env, typed_base_expr.exp_type); // Keep OCaml's identity split for persistent constructor heads only. // Local constructor families (e.g. mario_game viewport) should keep // sharing to avoid over-allocation and id drift. @@ -16125,7 +16126,7 @@ fn type_record( let (_poly2, ty_arg2, ty_res2) = crate::types::ctype::instance_label(ctx, false, env_label); unify_expression_types(tctx, loc, ty_arg1, ty_arg2, None)?; - let expected_inst = crate::types::instance(ctx, expected_ty); + let expected_inst = crate::types::ctype::instance_in(ctx, env, expected_ty); unify_expression_types(tctx, loc, expected_inst, ty_res2, None)?; } } @@ -16146,7 +16147,7 @@ fn type_record( // type and the `with` base expression type for persistent constructor // families only. if let Some(base_expr) = typed_base.as_mut() { - let mut output_ty = crate::types::instance(ctx, base_expr.exp_type); + let mut output_ty = crate::types::ctype::instance_in(ctx, env, base_expr.exp_type); if ctx.repr(output_ty) == ctx.repr(record_ty) { let repr = ctx.repr(output_ty); let desc = ctx.get_desc(repr); @@ -16170,7 +16171,7 @@ fn type_record( // typecore.ml:2983-2990. Keep this as a fresh post-unify instance rather // than the original expected node so later application unification observes // the same typedtree sharing and force order. - let record_exp_ty = crate::types::instance(ctx, expected_ty); + let record_exp_ty = crate::types::ctype::instance_in(ctx, env, expected_ty); // `record_fields lbl_exp_list` (typecore.ml:393-402): only the written // fields, already in `lbl_pos` order. @@ -16839,8 +16840,8 @@ fn type_setfield( // label result with the expected record type (raising // `Label_mismatch` at the label), then instances the field // argument before typing the assigned value. - let ty_res = crate::types::ctype::instance(ctx, ty_res0); - let expected_record_ty = crate::types::ctype::instance(ctx, ty_record); + let ty_res = crate::types::ctype::instance_in(ctx, env, ty_res0); + let expected_record_ty = crate::types::ctype::instance_in(ctx, env, ty_record); let label_result_unify = crate::types::unify(ctx, &mut tctx.unify_state, ty_res, expected_record_ty) .map_err(|err| TypeCoreError::LabelMismatch { @@ -16852,7 +16853,7 @@ fn type_setfield( }, env: Some(tctx.type_ctx.store_typed_env(env)), }); - let field_ty = crate::types::ctype::instance(ctx, ty_arg0); + let field_ty = crate::types::ctype::instance_in(ctx, env, ty_arg0); if separate { // OCaml compiler/ml/typecore.ml:3722-3725 closes the second local @@ -16906,7 +16907,7 @@ fn type_setfield( let typed_value = type_expect(tctx, env, new_value, field_ty, field_context)?; // OCaml compiler/ml/typecore.ml:3740-3743 uses `type_argument`, which // types against `ty_arg` and then unifies with `instance env ty_arg`. - let field_ty_inst = crate::types::ctype::instance(ctx, field_ty); + let field_ty_inst = crate::types::ctype::instance_in(ctx, env, field_ty); unify_expression_types(tctx, loc, typed_value.exp_type, field_ty_inst, None)?; Ok((label_desc, field_ty, poly_field, typed_value)) @@ -16930,7 +16931,7 @@ fn type_setfield( }; // OCaml compiler/ml/typecore.ml:3779 returns `{arg with exp_type = // instance env arg.exp_type}` from `type_label_exp`. - typed_value.exp_type = crate::types::ctype::instance(ctx, typed_value.exp_type); + typed_value.exp_type = crate::types::ctype::instance_in(ctx, env, typed_value.exp_type); // OCaml typecore.ml:2953: `unify_exp env record ty_record`. unify_expression_types( tctx, @@ -17018,8 +17019,8 @@ fn type_constraint( // // Both instances are created BEFORE type_expect runs, so they see the // GENERIC ctype_ty before any handler can consume it via unification. - let result_ty = crate::types::instance(ctx, ctype_ty); - let arg_unify_ty = crate::types::instance(ctx, ctype_ty); + let result_ty = crate::types::ctype::instance_in(ctx, env, ctype_ty); + let arg_unify_ty = crate::types::ctype::instance_in(ctx, env, ctype_ty); // Pass the GENERIC constraint type to type_expect (matches OCaml). // Rue handlers create per-expression instances via rue_unify. @@ -17664,7 +17665,7 @@ fn type_object_field_value( ctx.end_def(); let mut value = value?; check_univars_or_less_general(tctx, env, true, "field value", &value, typ, &vars)?; - value.exp_type = crate::types::ctype::instance(ctx, value.exp_type); + value.exp_type = crate::types::ctype::instance_in(ctx, env, value.exp_type); Ok(value) } None => { @@ -18675,7 +18676,7 @@ fn type_pack( // instance the expected type, expand it to a package, then call // Typemod.type_package for the module expression and package arguments. let ctx = tctx.type_ctx; - let expected_inst = crate::types::ctype::instance(ctx, expected_ty); + let expected_inst = crate::types::ctype::instance_in(ctx, env, expected_ty); let expanded = crate::types::ctype::expand_head(ctx, env, expected_inst); let (pack_path, pack_lids, expected_pack_args) = { let desc = ctx.get_desc(ctx.repr(expanded)); @@ -19130,7 +19131,7 @@ fn type_body_with_module_unpacks( // OCaml's wrap_unpacks types the unpack as Pexp_ident through type_expect, // which calls instance() on the looked-up type. Match that by instancing here. - let unpack_inst_ty = crate::types::instance(tctx.type_ctx, unpack.ty); + let unpack_inst_ty = crate::types::ctype::instance_in(tctx.type_ctx, env, unpack.ty); let unpack_expr = Expression::new( ExpressionDesc::Texp_ident(Path::pident(unpack.id), located_lid, Arc::new(value_desc)), unpack.loc_idx, @@ -21226,7 +21227,7 @@ fn type_let_bindings( &inst_vars, )?; // OCaml: {exp with exp_type = instance env exp.exp_type} - let new_exp_type = crate::types::ctype::instance(ctx, exp.exp_type); + let new_exp_type = crate::types::ctype::instance_in(ctx, env, exp.exp_type); Ok(Expression { exp_type: new_exp_type, ..exp diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_generalized_copy.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_generalized_copy.res.expected new file mode 100644 index 0000000000..51cd19aa4b --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_generalized_copy.res.expected @@ -0,0 +1,18 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_generalized_copy.res:6:7-9 + + 4 ┆ | Int => { + 5 ┆ let k = () => if true { y } else { 0 } + 6 ┆ k() + 7 ┆ } + 8 ┆ } + + This has type: a (defined as int) + But it's expected to have type: 'a + This instance of int is ambiguous: + it would escape the scope of its equation + + Possible solutions: + - These types are compatible at runtime. You can use the coercion operator to convert to the expected type: (k() :> int) + \ No newline at end of file diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_generalized_copy.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_generalized_copy.res new file mode 100644 index 0000000000..6d88bb4998 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_generalized_copy.res @@ -0,0 +1,8 @@ +type rec t<_> = Int: t +let f = (type a, x: t, y: a) => + switch x { + | Int => { + let k = () => if true { y } else { 0 } + k() + } + } diff --git a/tests/tests/src/gadt_instance_ambiguous_accepted.mjs b/tests/tests/src/gadt_instance_ambiguous_accepted.mjs index b7d60680cf..6bb1d2fc46 100644 --- a/tests/tests/src/gadt_instance_ambiguous_accepted.mjs +++ b/tests/tests/src/gadt_instance_ambiguous_accepted.mjs @@ -1,6 +1,7 @@ // Generated by ReScript, PLEASE EDIT WITH CARE import * as Stdlib_List from "@rescript/runtime/lib/es6/Stdlib_List.mjs"; +import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.mjs"; function f(x, y) { return y; @@ -210,6 +211,120 @@ let WhileRef = { f: f$16 }; +function f$17(x, y) { + return 1; +} + +let ChainEquality = { + f: f$17 +}; + +function f$18(x, y) { + return 1; +} + +let ChainAnnot = { + f: f$18 +}; + +function f$19(x, y) { + return [1]; +} + +let ChainAbbrev = { + f: f$19 +}; + +function f$20(x, y, w) { + return w; +} + +let ChainOuterParam = { + f: f$20 +}; + +function f$21(x, y, o) { + return o; +} + +let ObjectFields = { + f: f$21 +}; + +function f$22(x, y) { + let r = { + contents: undefined + }; + r.contents = { + NAME: "A", + VAL: y + }; + return r; +} + +let PolyvariantOpenMore = { + f: f$22 +}; + +function f$23(x, y) { + if (x === "Int") { + return y + 1 | 0; + } else { + return Stdlib_List.length(y); + } +} + +let LocalRecAbbrev = { + f: f$23 +}; + +function f$24(e, y) { + return 2; +} + +let EqChain = { + f: f$24 +}; + +function f$25(x, y) { + let w = 1; + return w; +} + +let ChainRef = { + f: f$25 +}; + +function f$26(x, y) { + let w = [1]; + y === Stdlib_Option.getOr(w[0], 0); + return w; +} + +let ChainRefArray = { + f: f$26 +}; + +function f$27(x, y) { + let g = n => n; + return g; +} + +let ChainParamFn = { + f: f$27 +}; + +function f$28(x, y) { + let w = { + contents: 1 + }; + return w; +} + +let ChainRefReverse = { + f: f$28 +}; + export { ResultAnnotation, PlusOne, @@ -230,5 +345,17 @@ export { NestedSwitchLevels, FieldObjectMethod, WhileRef, + ChainEquality, + ChainAnnot, + ChainAbbrev, + ChainOuterParam, + ObjectFields, + PolyvariantOpenMore, + LocalRecAbbrev, + EqChain, + ChainRef, + ChainRefArray, + ChainParamFn, + ChainRefReverse, } /* No side effect */ diff --git a/tests/tests/src/gadt_instance_ambiguous_accepted.res b/tests/tests/src/gadt_instance_ambiguous_accepted.res index e01ecccb98..d1a194563e 100644 --- a/tests/tests/src/gadt_instance_ambiguous_accepted.res +++ b/tests/tests/src/gadt_instance_ambiguous_accepted.res @@ -184,3 +184,142 @@ module WhileRef = { r.contents } } + +module ChainEquality = { + type rec t<_> = Int: t + let f = (type a, x: t, y: a) => + switch x { + | Int => { + let w = 1 + ignore(y == w) + if true { w } else { w } + } + } +} + +module ChainAnnot = { + type rec t<_> = Int: t + let f = (type a, x: t, y: a) => + switch x { + | Int => { + let w = 1 + let _ = [y, w] + w + } + } +} + +module ChainAbbrev = { + type rec t<_> = Int: t + type u = int + let f = (type a, x: t, y: a) => + switch x { + | Int => { + let w: u = 1 + ignore(y == w) + [w] + } + } +} + +module ChainOuterParam = { + type rec t<_> = Int: t + let f = (type a, x: t, y: a, w: int) => + switch x { + | Int => { + ignore(y == w) + w + } + } +} + +module ObjectFields = { + type rec t<_> = Int: t + let f = (type a, x: t, y: a, o) => + switch x { + | Int => { + ignore(o["g"] == 1) + if true { o } else { {"f": y, "g": 0} } + } + } +} + +module PolyvariantOpenMore = { + type rec t<_> = Int: t + let f = (type a, x: t, y: a) => { + let r = ref(None) + switch x { + | Int => r := Some(#A(y)) + } + r + } +} + +module LocalRecAbbrev = { + type rec t<_> = Int: t | Lst: t> + let f = (type a, x: t, y: a) => + switch x { + | Int => y + 1 + | Lst => List.length(y) + } +} + +module EqChain = { + type rec eq<'a, 'b> = Refl: eq<'a, 'a> + let f = (type a, e: eq, y: a) => + switch e { + | Refl => { + let w = 2 + ignore(y == w) + w + } + } +} + +module ChainRef = { + type rec t<_> = Int: t + let f = (type a, x: t, y: a) => + switch x { + | Int => { + let w = ref(1) + ignore(y == w.contents) + w.contents + } + } +} + +module ChainRefArray = { + type rec t<_> = Int: t + let f = (type a, x: t, y: a) => + switch x { + | Int => { + let w = [1] + ignore(y == w[0]->Option.getOr(0)) + w + } + } +} + +module ChainParamFn = { + type rec t<_> = Int: t + let f = (type a, x: t, y: a) => + switch x { + | Int => { + let g = n => n + ignore(g(y) == 1) + g + } + } +} + +module ChainRefReverse = { + type rec t<_> = Int: t + let f = (type a, x: t, y: a) => + switch x { + | Int => { + let w = ref(1) + ignore(w.contents == y) + w + } + } +} From 7d08707fd519515af8c4dfff0261a264b6ef57e9 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:18:28 +0000 Subject: [PATCH 03/30] Record A1, the GADT instance port, with its 64 programs The third round of CHECKER_DEPARTURES.md gets the place A1: the 64 programs run through both compilers before and after the two commits of the port, the causes on both sides, and the OCaml sites left open because no program shows them. The twelve probes that differed on trunk and had no fixture become super_errors fixtures. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/docs/CHECKER_DEPARTURES.md | 189 ++++++++++++++++++ ...guous_abbrev_annotation_array.res.expected | 20 ++ ...mbiguous_application_argument.res.expected | 17 ++ ...guous_application_if_argument.res.expected | 16 ++ ..._ambiguous_application_result.res.expected | 14 ++ ...ambiguous_constructor_payload.res.expected | 14 ++ ...ce_ambiguous_generalized_poly.res.expected | 20 ++ ...tance_ambiguous_nested_switch.res.expected | 14 ++ ...ce_ambiguous_object_in_option.res.expected | 26 +++ ...ance_ambiguous_option_payload.res.expected | 16 ++ ...ambiguous_partial_application.res.expected | 17 ++ ...biguous_polyvariant_nested_if.res.expected | 18 ++ ...iguous_polyvariant_open_param.res.expected | 18 ++ ...ance_ambiguous_abbrev_annotation_array.res | 9 + ...nstance_ambiguous_application_argument.res | 6 + ...ance_ambiguous_application_if_argument.res | 5 + ..._instance_ambiguous_application_result.res | 8 + ...instance_ambiguous_constructor_payload.res | 6 + ...dt_instance_ambiguous_generalized_poly.res | 8 + .../gadt_instance_ambiguous_nested_switch.res | 9 + ...dt_instance_ambiguous_object_in_option.res | 8 + ...gadt_instance_ambiguous_option_payload.res | 5 + ...instance_ambiguous_partial_application.res | 6 + ...stance_ambiguous_polyvariant_nested_if.res | 8 + ...tance_ambiguous_polyvariant_open_param.res | 8 + 25 files changed, 485 insertions(+) create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_abbrev_annotation_array.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_application_argument.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_application_if_argument.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_application_result.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_constructor_payload.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_generalized_poly.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_nested_switch.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_object_in_option.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_option_payload.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_partial_application.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_polyvariant_nested_if.res.expected create mode 100644 tests/build_tests/super_errors/expected/gadt_instance_ambiguous_polyvariant_open_param.res.expected create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_abbrev_annotation_array.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_application_argument.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_application_if_argument.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_application_result.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_constructor_payload.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_generalized_poly.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_nested_switch.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_object_in_option.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_option_payload.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_partial_application.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_polyvariant_nested_if.res create mode 100644 tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_polyvariant_open_param.res diff --git a/compiler-rust/docs/CHECKER_DEPARTURES.md b/compiler-rust/docs/CHECKER_DEPARTURES.md index 46147cab41..693580d5da 100644 --- a/compiler-rust/docs/CHECKER_DEPARTURES.md +++ b/compiler-rust/docs/CHECKER_DEPARTURES.md @@ -8579,6 +8579,195 @@ programs all agree after this commit, program 10 included. Nothing of this place. +### A1 - an instance of a type that is ambiguous outside its equation is refused + +Found while fixing: the Rust compiler accepted, and compiled, programs whose +value has a type known only through a GADT equation and leaves the case of +that equation. OCaml refuses them. Witnesses, both verified on trunk +`109b2bd4c`: + +```rescript +type rec t<_> = Int: t +let f = (type a, x: t, y: a) => + switch x { + | Int => if true { y } else { 0 } + } +``` + +OCaml refuses at 4:33: "This has type: int / But this if statement is +expected to return: a (defined as int) / This instance of int is ambiguous: +/ it would escape the scope of its equation / if expressions must return +the same type in all branches (if, else if, else)." Rust emitted +`function f(x, y) { return y; }`. The second witness, `[y, 0]` under +`Int =>` next to `Str => []`, is refused at 4:16 ("This array item has +type: int / But this array is expected to have items of type: a (defined +as int)" and the same two lines, then the array advice and its "Possible +solutions:"); Rust accepted it. + +Commands are the ones in "Scope, calibration and reproducibility": each +program is `Main.res` alone, run with `bsc -w +A -bs-jsx 4 -color never +Main.res` through both compilers; "agree" is the same exit status and the +same output byte for byte (the whole diagnostic, its location, the +JavaScript and every warning). Rust before is trunk `109b2bd4c`, after is +the second commit below. The witnesses are p01 and p02; p03 to p30 are the +shapes asked for (each expression form whose branches are unified, the +`eq<'a, 'b>` witness, a nested constructor pattern, two equations for one +type, an outer function's locally abstract type, the programs that must +stay accepted, an object and a variant row, abbreviations as the +equation's right side); q01 to q18 and r01 to r16 probe the remaining +OCaml sites. `T` is `type rec t<_> = Int: t` and the function is +`(type a, x: t, y: a) => switch x { ... }` unless the row says +otherwise. + +| # | program | OCaml | Rust before | Rust after | +| --- | --- | --- | --- | --- | +| p01 | `if true { y } else { 0 }` under `Int =>` (witness 1) | refused at 4:33 | DIFFER (accepted) | agree | +| p02 | `[y, 0]` under `Int =>`, `Str => []` (witness 2) | refused at 4:16 | DIFFER (accepted) | agree | +| p03 | witness 1 with `: int` on `f` | accepted | agree | agree | +| p04 | `Int => y + 1` | accepted | agree | agree | +| p05 | a `switch b` inside the branch returning `y` and `0` | refused at 7:16 | DIFFER (accepted) | agree | +| p06 | `(0, 1)` and `(y, 2)` from two cases of `t` | accepted | agree | agree | +| p07 | `{a: y, b: 0}` of `r<'a>` | refused at 5:12-23 | DIFFER (accepted) | agree | +| p08 | `let z = switch ...` unannotated, used after it | refused at 6:28 | DIFFER (accepted) | agree | +| p09 | `b => if b { y } else { 0 }` returned | refused at 4:35 | DIFFER (accepted) | agree | +| p10 | `r := Some(if true { y } else { 0 })` | refused at 5:43 | DIFFER (accepted) | agree | +| p11 | `eq`, `Refl => if true { x } else { y }` | accepted | agree | agree | +| p12 | `eq`, `Refl => if true { y } else { 0 }` | refused at 4:34 | DIFFER (accepted) | agree | +| p13 | `Some(Int) =>` (nested constructor) | refused at 4:39 | DIFFER (accepted) | agree | +| p14 | `Int` and `Str` cases, each mixing `y` and a literal | refused at 4:33 | DIFFER (accepted) | agree | +| p15 | `a` of the outer function, `switch` in an inner one | refused at 5:35 | DIFFER (accepted) | agree | +| p16 | `(y: int)` in the branch | accepted | agree | agree | +| p17 | `h(y)` with `h: int => int` | accepted | agree | agree | +| p18 | `Ex(Int, v) => v + 1` | accepted | agree | agree | +| p19 | `{"f": y}` and `{"f": 0}` (object row) | refused at 4:40-47 | DIFFER (accepted) | agree | +| p20 | `#A(y)` and `#A(0)` (variant row) | refused at 4:40 | DIFFER (accepted) | agree | +| p21 | `type u = int`, `U: t`, `y` and `0` | refused at 5:31 | DIFFER (accepted) | agree | +| p22 | the same with `(1: u)` first | refused at 5:36 | DIFFER (accepted) | agree | +| p23 | witness 2 with `: array` | accepted | agree | agree | +| p24 | `Ex(Int, v) => ignore(v)` | accepted | agree | agree | +| p25 | `#A(y)` and `#B(0)` | accepted | agree | agree | +| p26 | witness 1 with `: a` on `f` | accepted | agree | agree | +| p27 | an open object parameter and `{"f": y}` | refused at 6:28-35 | DIFFER (accepted) | agree | +| p28 | `type v = u`, `type u = int`, `V: t`, `[y, 0]` | refused at 6:14 | DIFFER (accepted) | agree | +| p29 | `{v: 0}` and `{v: y}` from `Int` and `Str` | refused at 6:16 | agree | agree | +| p30 | `let k = switch x { \| Int => y }; k + 1` | refused at 6:3 | agree | agree | +| q01 | `let k = () => if true { y } else { 0 }; k()` | refused at 6:7-9 | DIFFER (accepted) | agree | +| q02 | `let k = z => if true { z } else { 0 }; [k(y)]` | refused at 6:8-11 | DIFFER (accepted) | agree | +| q03 | `{"f": 0, "g": y}` against an open object | accepted | agree | agree | +| q04 | `r := Some({"f": if true { y } else { 1 }})` | refused at 5:22-52 | DIFFER (accepted) | agree | +| q05 | `#A(0)`, `#A(y)` and a variant parameter | refused at 6:52 | DIFFER (accepted) | agree | +| q06 | `[< #A(int) \| #B]` parameter, `#A(n)` or `#A(y)` | accepted | agree | agree | +| q07 | `let z: u = y; [z, y]` | refused at 7:11 | DIFFER (accepted) | agree | +| q08 | `let z: u = y; r := [z]` | accepted | agree | agree | +| q09 | `g(y, ...)`, `g: (int, 'm) => int` | accepted | agree | agree | +| q10 | `g(y, ...)`, `g = (n, m: int) => if ... n else m` | refused at 5:12-20 | DIFFER (accepted) | agree | +| q11 | `L: t>`, `List.length(y)` | accepted | agree | agree | +| q12 | `id(if true { y } else { 0 })` | refused at 5:12-39 | DIFFER (accepted) | agree | +| q13 | `Some(if true { 1 } else { y })` | refused at 4:38 | DIFFER (accepted) | agree | +| q14 | two switches, two equations, `(y + 1, w ++ "")` | accepted | agree | agree | +| q15 | the same returning `(y, w)` or `(0, "")` | refused at 7:41 | DIFFER (accepted) | agree | +| q16 | `Box(y)` or `Box(0)` | refused at 5:42 | DIFFER (accepted) | agree | +| q17 | `o["m"] + 0` with `o = {"m": y}` | accepted | agree | agree | +| q18 | `r = ref(y)` outside, `r.contents + 1` inside | accepted | agree | agree | +| r01 | `let w = 1; y == w; w` | accepted | agree | agree | +| r02 | `let _ = [y, w]; w` | accepted | agree | agree | +| r03 | `let w: u = 1; y == w; [w]` | accepted | agree | agree | +| r04 | `y == w` with a parameter `w: int` | accepted | agree | agree | +| r05 | `o["g"] == 1`, `{"f": y, "g": 0}` | accepted | agree | agree | +| r06 | `o := Some({"f": y})`, read after the switch | refused at 9:13 | agree | agree | +| r07 | `v == #A(1)`, then `v` or `#A(y)` | refused at 6:31 | DIFFER (accepted) | agree | +| r08 | `r := Some(#A(y))` | accepted | agree | agree | +| r09 | `g(y) + 1` then `g(0)`, `g` a parameter | refused at 6:9 | DIFFER (accepted) | agree | +| r10 | `g(if true { y } else { 0 })` | refused at 4:35 | DIFFER (accepted) | agree | +| r11 | `Lst: t>`, `List.length(y)` | accepted | agree | agree | +| r12 | `eq`, `y == w; w` | accepted | agree | agree | +| r13 | `let w = ref(1); y == w.contents; w.contents` | accepted | agree | agree | +| r14 | `let w = [1]`, `y == w[0]...`, `w` | accepted | agree | agree | +| r15 | `let g = n => n; g(y) == 1; g` | accepted | agree | agree | +| r16 | `w.contents == y; w` | accepted | agree | agree | + +There is no principal mode in this compiler, and none of the sites below +reads one. + +#### Fixed + +- `92862d207`. OCaml keeps, per `switch` (or function) whose patterns may + add equations, a set of the types known only through an equation + (`gadt_instances`, `compiler/ml/env.ml:368`, `1305-1345`; a level is + added by `type_cases` and the function form, + `compiler/ml/typecore.ml:4034-4042`, `4822-4828`). While tracing is on + (under local constraints, `compiler/ml/ctype.ml:176-191`, which also + forgets the memorized expansions), `expand_abbrev_gen` + (`ctype.ml:1215-1227`) refuses to expand a type whose level is below the + equation's expansion level or its set's, and adds the type and its + expansion to the set; `try_expand_head` (`ctype.ml:1270-1276`) adds the + chain of an expansion that ends in an instance; `update_level` + (`ctype.ml:587-589`) refuses to lower an instance below its set's level. + The refusal is `Unify [(ty, newvar2 level)]`, which `printtyp.ml:1340-1362` + prints as "This instance of ... is ambiguous". Rust's + `Env::add_gadt_instance_level` took no level and tracked nothing. Now + the sets are in the type context (`TypeContext::new_gadt_instance_scope`, + `gadt_instance_level`, `add_gadt_instances`, `add_gadt_instance_chain`, + `compiler-rust/src/types/context.rs:5725-5830`), each scope holding its + enclosing one's handle, and the environment holds the innermost handle + (`compiler-rust/src/types/env.rs:2810`). Both callers of + `add_gadt_instance_level` (`typecore.rs:11976`, `13625`) build the case + environment as a clone of the outer one; with the handle in the shared + bindings record, a clone copies a `u32` and never a set, and every + environment of a case sees the set as OCaml's share its `ref`. Additions + are journaled (`TypeMutation::GadtInstance`) and undone on backtrack, as + OCaml trails `set_typeset`. The equation records the pattern's newtype + level as its expansion level (`env.ml:1805-1810`; + `add_gadt_equation`, `ctype.rs:1845`); `check_trace_gadt_instances` + forgets the memorized expansions (`ctype.ml:182`); the expansion test is + `try_expand_head_traced` (`ctype.rs:4764`), made before the + substitution, which it does not affect; `expand_head_traced` + (`ctype.rs:7368`) adds the chain; the unifier's expansions + (`unify2`, `ctype.ml:2289-2292`) propagate the refusal + (`expand_head_unif_traced`, `ctype.rs:7350`); `update_level_pass` + (`ctype.rs:3005`) makes the level test. Without OCaml's arm of `unify` + for two nullary locally abstract types (`ctype.ml:2255-2268`: expand + only the later one, lower nothing first), p11 became refused. A trace + with the arm disabled shows `unify_types` lowering the copy of `b` + (level 2008) and `a` to the outer level 1005 before expanding, and the + expansion of the copy of `b` then refused (1005 below the instance + level 1008); OCaml's arm expands that copy at its own level. + `unify_newtypes` (`ctype.rs:610`) is that arm. The level test costs one load (`has_gadt_instance_scopes`) and one + branch per level update in a unit without an instance scope; the plain + level update is skipped only in an environment with one. +- `22a53a612`. OCaml's `copy ?env` (`ctype.ml:770-774`), reached through + `instance env` and `instance_list env` (`ctype.ml:877-894`), adds the + copy of an instance to its set under local constraints. A function + generalized inside a case (q01) gave Rust copies that were no instances. + `instance_in` and `instance_list_in` (`ctype.rs:12438`) take the + environment and, only under local constraints with an instance scope, + walk the finished copy's table once (`add_copied_gadt_instances`, + `ctype.rs:12485`); the typecore sites of OCaml's `instance env` use them. +- Fixtures: super_errors `gadt_instance_ambiguous_*` (the 30 programs + refused by OCaml that Rust accepted: p01, p02, p05, p07-p10, p12-p15, + p19-p22, p27, p28, q01, q02, q04, q05, q07, q10, q12, q13, q15, q16, r07, + r09, r10), and `tests/tests/src/gadt_instance_ambiguous_accepted.res` + (31 accepted programs, the JavaScript of each compared by the + JavaScript parity suite). + +#### Open + +No program of the 64 shows a difference at these OCaml sites, which are +not ported: the chain of `unify2` after expansion (`ctype.ml:2293-2298`: +r01-r04, r12-r16 were written for it and agree), the level test of +`unify_fields` (`ctype.ml:2490`: q03, r05, r06), of `unify_row`'s row +variable (`ctype.ml:2609-2611`: q05, q06, r07, r08), the tracing wrappers +of `unify_var` (`ctype.ml:2759-2766`), `expand_head_trace` +(`ctype.ml:2782-2784`), the application's `lower_args` +(`typecore.ml:2828`: q09, q10, r09, r10) and `local_non_recursive_abbrev` +(`ctype.ml:1533-1534`: q11, r11), and `copy ?env ~partial` through +`instance ~partial env` (Rust's `instance_partial`). The level updates +that Rust makes without an environment (`update_level`, for the same +nullary constructor, universal variables, object and row variables) make +no level test; no program here reaches one with an instance. The port +was stopped at the sites a program shows, as the size limit of the task +asks. + ## Fourth round: modules, aliases and usage marks ### Scope, commands and calibration diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_abbrev_annotation_array.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_abbrev_annotation_array.res.expected new file mode 100644 index 0000000000..74048891ae --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_abbrev_annotation_array.res.expected @@ -0,0 +1,20 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_abbrev_annotation_array.res:7:11 + + 5 ┆ | Int => { + 6 ┆ let z: u = y + 7 ┆ [z, y] + 8 ┆ } + 9 ┆ } + + This array item has type: a (defined as int) + But this array is expected to have items of type: u (defined as int) + This instance of int is ambiguous: + it would escape the scope of its equation + + Arrays can only contain items of the same type. + + Possible solutions: + - Convert all values in the array to the same type. + - Use a tuple, if your array is of fixed length. Tuples can mix types freely, and compiles to a JavaScript array. Example of a tuple: `let myTuple = (10, "hello", 15.5, true) \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_application_argument.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_application_argument.res.expected new file mode 100644 index 0000000000..2ee6d90a1e --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_application_argument.res.expected @@ -0,0 +1,17 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_application_argument.res:5:12-39 + + 3 │ let f = (type a, x: t, y: a) => + 4 │ switch x { + 5 │ | Int => id(if true { y } else { 0 }) + 6 │ } + 7 │ + + This has type: a (defined as int) + But this switch is expected to return: 'a + This instance of int is ambiguous: + it would escape the scope of its equation + + All branches in a switch must return the same type. + To fix this, change your branch to return the expected type. \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_application_if_argument.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_application_if_argument.res.expected new file mode 100644 index 0000000000..eab6586bbd --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_application_if_argument.res.expected @@ -0,0 +1,16 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_application_if_argument.res:4:35 + + 2 │ let f = (type a, x: t, y: a, g) => + 3 │ switch x { + 4 │ | Int => g(if true { y } else { 0 }) + 5 │ } + 6 │ + + This has type: int + But this if statement is expected to return: a (defined as int) + This instance of int is ambiguous: + it would escape the scope of its equation + + if expressions must return the same type in all branches (if, else if, else). \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_application_result.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_application_result.res.expected new file mode 100644 index 0000000000..3276a43acd --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_application_result.res.expected @@ -0,0 +1,14 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_application_result.res:6:9 + + 4 ┆ | Int => { + 5 ┆ ignore(g(y) + 1) + 6 ┆ g(0) + 7 ┆ } + 8 ┆ } + + This has type: int + But this function argument is expecting: a (defined as int) + This instance of int is ambiguous: + it would escape the scope of its equation \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_constructor_payload.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_constructor_payload.res.expected new file mode 100644 index 0000000000..1311182938 --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_constructor_payload.res.expected @@ -0,0 +1,14 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_constructor_payload.res:5:42 + + 3 │ let f = (type a, x: t, y: a) => + 4 │ switch x { + 5 │ | Int => if true { Box(y) } else { Box(0) } + 6 │ } + 7 │ + + This has type: int + But it's expected to have type: a (defined as int) + This instance of int is ambiguous: + it would escape the scope of its equation \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_generalized_poly.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_generalized_poly.res.expected new file mode 100644 index 0000000000..f39627155d --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_generalized_poly.res.expected @@ -0,0 +1,20 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_generalized_poly.res:6:8-11 + + 4 ┆ | Int => { + 5 ┆ let k = z => if true { z } else { 0 } + 6 ┆ [k(y)] + 7 ┆ } + 8 ┆ } + + This array item has type: a (defined as int) + But this array is expected to have items of type: 'a + This instance of int is ambiguous: + it would escape the scope of its equation + + Arrays can only contain items of the same type. + + Possible solutions: + - Convert all values in the array to the same type. + - Use a tuple, if your array is of fixed length. Tuples can mix types freely, and compiles to a JavaScript array. Example of a tuple: `let myTuple = (10, "hello", 15.5, true) \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_nested_switch.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_nested_switch.res.expected new file mode 100644 index 0000000000..789d4c25f3 --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_nested_switch.res.expected @@ -0,0 +1,14 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_nested_switch.res:7:41 + + 5 ┆ | Int => + 6 ┆ switch z { + 7 ┆ | Str => if true { (y, w) } else { (0, "") } + 8 ┆ } + 9 ┆ } + + This has type: int + But it's expected to have type: a (defined as int) + This instance of int is ambiguous: + it would escape the scope of its equation \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_object_in_option.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_object_in_option.res.expected new file mode 100644 index 0000000000..5dc496b860 --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_object_in_option.res.expected @@ -0,0 +1,26 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_object_in_option.res:5:22-52 + + 3 ┆ let r = ref(None) + 4 ┆ switch x { + 5 ┆ | Int => r := Some({"f": if true { y } else { 1 }}) + 6 ┆ } + 7 ┆ r + + This has type: {"f": a} + But it's expected to have type: 'a + This instance of int is ambiguous: + it would escape the scope of its equation + + Possible solutions: + - These types are compatible at runtime. You can use the coercion operator to convert to the expected type: ( + { + "f": if true { + y + } else { + 1 + }, + } :> {"f": a} +) + \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_option_payload.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_option_payload.res.expected new file mode 100644 index 0000000000..4082cbc56f --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_option_payload.res.expected @@ -0,0 +1,16 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_option_payload.res:4:38 + + 2 │ let f = (type a, x: t, y: a) => + 3 │ switch x { + 4 │ | Int => Some(if true { 1 } else { y }) + 5 │ } + 6 │ + + This has type: a (defined as int) + But this if statement is expected to return: int + This instance of int is ambiguous: + it would escape the scope of its equation + + if expressions must return the same type in all branches (if, else if, else). \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_partial_application.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_partial_application.res.expected new file mode 100644 index 0000000000..51beb7734b --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_partial_application.res.expected @@ -0,0 +1,17 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_partial_application.res:5:12-20 + + 3 │ let f = (type a, x: t, y: a) => + 4 │ switch x { + 5 │ | Int => g(y, ...) + 6 │ } + 7 │ + + This has type: int => a + But this switch is expected to return: 'a + This instance of int is ambiguous: + it would escape the scope of its equation + + All branches in a switch must return the same type. + To fix this, change your branch to return the expected type. \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_polyvariant_nested_if.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_polyvariant_nested_if.res.expected new file mode 100644 index 0000000000..12d296ce9f --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_polyvariant_nested_if.res.expected @@ -0,0 +1,18 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_polyvariant_nested_if.res:6:52 + + 4 ┆ | Int => { + 5 ┆ let w = #A(0) + 6 ┆ if true { v } else { if true { w } else { #A(y) } } + 7 ┆ } + 8 ┆ } + + This has type: a (defined as int) + But it's expected to have type: int + This instance of int is ambiguous: + it would escape the scope of its equation + + Possible solutions: + - These types are compatible at runtime. You can use the coercion operator to convert to the expected type: (y :> int) + \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_polyvariant_open_param.res.expected b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_polyvariant_open_param.res.expected new file mode 100644 index 0000000000..e99fd8f2f1 --- /dev/null +++ b/tests/build_tests/super_errors/expected/gadt_instance_ambiguous_polyvariant_open_param.res.expected @@ -0,0 +1,18 @@ + + We've found a bug for you! + /.../fixtures/gadt_instance_ambiguous_polyvariant_open_param.res:6:31 + + 4 ┆ | Int => { + 5 ┆ ignore(v == #A(1)) + 6 ┆ if true { v } else { #A(y) } + 7 ┆ } + 8 ┆ } + + This has type: a (defined as int) + But it's expected to have type: int + This instance of int is ambiguous: + it would escape the scope of its equation + + Possible solutions: + - These types are compatible at runtime. You can use the coercion operator to convert to the expected type: (y :> int) + \ No newline at end of file diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_abbrev_annotation_array.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_abbrev_annotation_array.res new file mode 100644 index 0000000000..f8c9951ce6 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_abbrev_annotation_array.res @@ -0,0 +1,9 @@ +type rec t<_> = Int: t +type u = int +let f = (type a, x: t, y: a) => + switch x { + | Int => { + let z: u = y + [z, y] + } + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_application_argument.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_application_argument.res new file mode 100644 index 0000000000..68eed9740d --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_application_argument.res @@ -0,0 +1,6 @@ +type rec t<_> = Int: t +let id = v => v +let f = (type a, x: t, y: a) => + switch x { + | Int => id(if true { y } else { 0 }) + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_application_if_argument.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_application_if_argument.res new file mode 100644 index 0000000000..9edd51eb3d --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_application_if_argument.res @@ -0,0 +1,5 @@ +type rec t<_> = Int: t +let f = (type a, x: t, y: a, g) => + switch x { + | Int => g(if true { y } else { 0 }) + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_application_result.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_application_result.res new file mode 100644 index 0000000000..6ed6cfa693 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_application_result.res @@ -0,0 +1,8 @@ +type rec t<_> = Int: t +let f = (type a, x: t, y: a, g) => + switch x { + | Int => { + ignore(g(y) + 1) + g(0) + } + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_constructor_payload.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_constructor_payload.res new file mode 100644 index 0000000000..0526259ee3 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_constructor_payload.res @@ -0,0 +1,6 @@ +type rec t<_> = Int: t +type box<'a> = Box('a) +let f = (type a, x: t, y: a) => + switch x { + | Int => if true { Box(y) } else { Box(0) } + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_generalized_poly.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_generalized_poly.res new file mode 100644 index 0000000000..5c861a2347 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_generalized_poly.res @@ -0,0 +1,8 @@ +type rec t<_> = Int: t +let f = (type a, x: t, y: a) => + switch x { + | Int => { + let k = z => if true { z } else { 0 } + [k(y)] + } + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_nested_switch.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_nested_switch.res new file mode 100644 index 0000000000..6b19575bdc --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_nested_switch.res @@ -0,0 +1,9 @@ +type rec t<_> = Int: t +type rec s<_> = Str: s +let f = (type a b, x: t, z: s, y: a, w: b) => + switch x { + | Int => + switch z { + | Str => if true { (y, w) } else { (0, "") } + } + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_object_in_option.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_object_in_option.res new file mode 100644 index 0000000000..8319a59d52 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_object_in_option.res @@ -0,0 +1,8 @@ +type rec t<_> = Int: t +let f = (type a, x: t, y: a) => { + let r = ref(None) + switch x { + | Int => r := Some({"f": if true { y } else { 1 }}) + } + r +} diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_option_payload.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_option_payload.res new file mode 100644 index 0000000000..ec1114b1b3 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_option_payload.res @@ -0,0 +1,5 @@ +type rec t<_> = Int: t +let f = (type a, x: t, y: a) => + switch x { + | Int => Some(if true { 1 } else { y }) + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_partial_application.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_partial_application.res new file mode 100644 index 0000000000..cc0fb143ed --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_partial_application.res @@ -0,0 +1,6 @@ +type rec t<_> = Int: t +let g = (n, m: int) => if true { n } else { m } +let f = (type a, x: t, y: a) => + switch x { + | Int => g(y, ...) + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_polyvariant_nested_if.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_polyvariant_nested_if.res new file mode 100644 index 0000000000..0a59e8d07a --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_polyvariant_nested_if.res @@ -0,0 +1,8 @@ +type rec t<_> = Int: t +let f = (type a, x: t, y: a, v) => + switch x { + | Int => { + let w = #A(0) + if true { v } else { if true { w } else { #A(y) } } + } + } diff --git a/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_polyvariant_open_param.res b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_polyvariant_open_param.res new file mode 100644 index 0000000000..255d3873cd --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/gadt_instance_ambiguous_polyvariant_open_param.res @@ -0,0 +1,8 @@ +type rec t<_> = Int: t +let f = (type a, x: t, y: a, v) => + switch x { + | Int => { + ignore(v == #A(1)) + if true { v } else { #A(y) } + } + } From 752db1e00c3dcc6d344a759df35c921b9c893efd Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:37:49 +0000 Subject: [PATCH 04/30] Keep the GADT instance tests off the default path of expansion and copy Why: The instruction count of a clean tests/tests build rose by 0.313% with the port: the expansion of a head returned a `Result` through two more call layers, which changed what was inlined (`try_expand_head_with_mode` -29.4M, `try_expand_head_traced` +23.6M, `expand_head_traced` +15.1M, `find_abbrev_expansion` +8.2M instructions), and every `instance_in` call tested for an instance scope before copying (+2.3M). The expansion of one head is again trunk's function returning an `Option`; an ambiguous instance is written to an out-slot that only the unifier reads, and the traced end of `expand_abbrev_gen` is a cold function reached only while tracing. The head-expansion loop is one function, generic over whether it propagates the refusal, so the safe instantiation is trunk's loop. The test of `try_expand_head`'s chain is made only while tracing: one load and one branch outside it. `instance` and `instance_in` share one body; the instance-scope test follows a copy of a generic root only. `unify` reuses its local-constraints test for the newtype arm. All 64 programs of A1 agree as before. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/types/ctype.rs | 342 ++++++++++++++++--------------- 1 file changed, 180 insertions(+), 162 deletions(-) diff --git a/compiler-rust/src/types/ctype.rs b/compiler-rust/src/types/ctype.rs index 633af1dc7a..ca179e4fa2 100644 --- a/compiler-rust/src/types/ctype.rs +++ b/compiler-rust/src/types/ctype.rs @@ -606,14 +606,14 @@ fn is_newtype(ctx: &TypeContext, env: &Env, path: &Path) -> bool { /// level is expanded, once, and unified with the other; no level is lowered /// before. `None` when the arm does not apply or the type cannot be /// expanded, and unification goes on as `unify2`. One call is four -/// declaration lookups and one expansion. +/// declaration lookups and one expansion; only under local constraints. fn unify_newtypes( ctx: &TypeContext, state: &mut UnifyState, t1: TypeExprRef, t2: TypeExprRef, ) -> Option> { - let env = state.env().filter(|env| env.has_local_constraints())?; + let env = state.env()?; let nullary_path = |ty: TypeExprRef| match &*ctx.borrow_desc(ty) { TypeDesc::Tconstr { path, args, abbrev } if args.is_empty() => Some((*path, *abbrev)), _ => None, @@ -629,8 +629,9 @@ fn unify_newtypes( } let expand_first = find_newtype_level(ctx, env, &p1) >= find_newtype_level(ctx, env, &p2); let expanded = if expand_first { t1 } else { t2 }; - match try_expand_head_traced(ctx, env, expanded, ExpandHeadMode::Unify) { - Ok(Some(expansion)) => { + let mut ambiguous = None; + match try_expand_head_with_mode(ctx, env, expanded, ExpandHeadMode::Unify, &mut ambiguous) { + Some(expansion) => { let expansion = ctx.repr(expansion); Some(if expand_first { unify(ctx, state, expansion, t2) @@ -638,14 +639,7 @@ fn unify_newtypes( unify(ctx, state, t1, expansion) }) } - Ok(None) => None, - Err(ambiguous) => { - let level = ctx.get_level(ambiguous); - Some(Err(TypeError::Unify(vec![( - ambiguous, - new_var_at_level(ctx, level), - )]))) - } + None => ambiguous.map(|ambiguous| Err(ambiguous_instance(ctx, ambiguous))), } } @@ -875,7 +869,7 @@ fn expands_to_datatype(ctx: &TypeContext, env: &Env, ty: TypeExprRef) -> bool { return true; } drop(decl); - match try_expand_head_with_mode(ctx, env, ty, ExpandHeadMode::General) { + match try_expand_head_with_mode(ctx, env, ty, ExpandHeadMode::General, &mut None) { Some(expanded) => expands_to_datatype(ctx, env, expanded), None => false, } @@ -4745,28 +4739,20 @@ enum ExpandHeadMode { Optimize, } +/// OCaml `expand_abbrev_gen` (compiler/ml/ctype.ml:1190-1229) of one head. +/// While GADT instances are traced, an expansion of `ty` known only at an +/// instance level above `ty`'s level is OCaml's `Unify [(ty, newvar2 +/// level)]` (ctype.ml:1225): it returns `None` with `ty` in `ambiguous`, +/// having changed nothing. A caller that expands safely +/// (`try_expand_safe`, ctype.ml:1260-1265) takes that as a type that cannot +/// be expanded. fn try_expand_head_with_mode( ctx: &TypeContext, env: &Env, ty: TypeExprRef, mode: ExpandHeadMode, + ambiguous: &mut Option, ) -> Option { - // OCaml `try_expand_safe` (ctype.ml:1260-1265): an ambiguous GADT - // instance is a type that cannot be expanded. It is found before the - // expansion changes anything, so there is nothing to backtrack. - try_expand_head_traced(ctx, env, ty, mode).unwrap_or(None) -} - -/// OCaml `expand_abbrev_gen` (compiler/ml/ctype.ml:1190-1229) of one head. -/// `Err(ty)` is its `Unify [(ty, newvar2 level)]` (ctype.ml:1225): while -/// GADT instances are traced, the expansion of `ty` is known only at an -/// instance level above `ty`'s own level. -fn try_expand_head_traced( - ctx: &TypeContext, - env: &Env, - ty: TypeExprRef, - mode: ExpandHeadMode, -) -> Result, TypeExprRef> { let ty = ctx.repr(ty); let desc = ctx.borrow_desc(ty); match &*desc { @@ -4805,50 +4791,34 @@ fn try_expand_head_traced( } // The cached expansion is returned even when it is `ty` // itself (ctype.ml:1360-1362, PR#7324). - return Ok(Some(ctx.repr(cached))); - } - - // `expansion_level` is the expansion level of the declaration - // (`Env.find_type_expansion`'s `lv`, env.ml:902): set for a - // GADT equation. - let expand_with_subst = |params: &[TypeExprRef], - manifest: TypeExprRef, - expansion_level: Option| - -> Result { - // ctype.ml:1218-1227: the highest level of the equation and - // of an instance set holding `ty`. The test is made before - // `subst` here: it reads only `ty`, which `subst` leaves as - // it is. - let instance_level = if ctx.trace_gadt_instances() { - expansion_level.max(gadt_instance_level(ctx, env, ty)) - } else { - None + return Some(ctx.repr(cached)); + } + + // `expansion_level` is the declaration's expansion level + // (`Env.find_type_expansion`'s `lv`, env.ml:902), set for a GADT + // equation. + let mut expand_with_subst = |params: &[TypeExprRef], + manifest: TypeExprRef, + expansion_level: Option| + -> Option { + let subst = || { + subst_with_memo( + ctx, + env, + ty, + lookup_abbrev, + private_flag, + AbbrevDefinition { + params: params.into(), + body: manifest, + }, + ctx.type_list(args), + ) }; - if let Some(instance_level) = instance_level - && ctx.get_level(ty) < instance_level - { - return Err(ty); + if ctx.trace_gadt_instances() { + return subst_gadt_instance(ctx, env, ty, expansion_level, ambiguous, subst); } - let expanded = subst_with_memo( - ctx, - env, - ty, - lookup_abbrev, - private_flag, - AbbrevDefinition { - params: params.into(), - body: manifest, - }, - ctx.type_list(args), - ); - if let Some(instance_level) = instance_level { - ctx.add_gadt_instances( - env.gadt_instance_scope(), - instance_level, - &[ty, expanded], - ); - } - Ok(expanded) + Some(subst()) }; let can_expand_decl_manifest = @@ -4871,7 +4841,7 @@ fn try_expand_head_traced( if params.len() == args.len() { let expansion_level = constraint_decl.type_newtype_level.map(|(_, level)| level); - return expand_with_subst(params, manifest, expansion_level).map(Some); + return expand_with_subst(params, manifest, expansion_level); } } } @@ -4885,7 +4855,7 @@ fn try_expand_head_traced( .find_type_by_ident(id) .is_ok_and(|decl| decl.type_manifest.is_none()) { - return Ok(None); + return None; } // Qualified heads: the outcome depends only on the module scope, @@ -4916,11 +4886,11 @@ fn try_expand_head_traced( expansion } }; - return Ok(match expansion { - // A declaration reached through a module has no - // newtype level, hence no expansion level. + return match expansion { + // A declaration reached through a module has no newtype + // level, hence no expansion level. PdotExpansion::Expand { params, manifest } => { - expand_with_subst(¶ms, manifest, None).map(Some)? + expand_with_subst(¶ms, manifest, None) } PdotExpansion::Rewrite(target) => { let level = ctx.get_level(ty); @@ -4933,7 +4903,7 @@ fn try_expand_head_traced( Some(rewritten) } PdotExpansion::None => None, - }); + }; } // 1. Prefer environment lookup when the declaration matches the @@ -5013,8 +4983,7 @@ fn try_expand_head_traced( if params.len() == args.len() { let expansion_level = env_decl.type_newtype_level.map(|(_, level)| level); - return expand_with_subst(params, manifest, expansion_level) - .map(Some); + return expand_with_subst(params, manifest, expansion_level); } else { forbid_fallback_manifest_expansion = true; } @@ -5100,14 +5069,14 @@ fn try_expand_head_traced( abbrev: orig_abbrev, }); ctx.set_level(rewritten, level); - return Ok(Some(rewritten)); + return Some(rewritten); } } if can_expand_decl_manifest(&decl, manifest) { let params = &decl.type_params; if params.len() == args.len() { let expansion_level = decl.type_newtype_level.map(|(_, level)| level); - return expand_with_subst(params, manifest, expansion_level).map(Some); + return expand_with_subst(params, manifest, expansion_level); } else { forbid_fallback_manifest_expansion = true; } @@ -5122,7 +5091,7 @@ fn try_expand_head_traced( // `expand_head_unif`, so keep unification on the same path instead // of recovering later with Rust-only alias fallback work. if local_env_type_is_authoritative && forbid_fallback_manifest_expansion { - return Ok(None); + return None; } { let path_norm = match mode { @@ -5139,18 +5108,48 @@ fn try_expand_head_traced( abbrev: orig_abbrev, }); ctx.set_level(normalized, level); - Ok(Some(normalized)) + Some(normalized) } else { - Ok(None) + None } } } - _ => Ok(None), + _ => None, + } +} + +/// The traced end of `expand_abbrev_gen` (compiler/ml/ctype.ml:1215-1227): +/// the highest of the declaration's expansion level and the level of an +/// instance set holding `ty`; below it, `ty` is ambiguous and is not +/// expanded; otherwise `ty` and its expansion join that set. The test is +/// made before `subst`, which leaves `ty` as it is. Cost: one +/// [`gadt_instance_level`] and the substitution. +#[cold] +#[inline(never)] +fn subst_gadt_instance( + ctx: &TypeContext, + env: &Env, + ty: TypeExprRef, + expansion_level: Option, + ambiguous: &mut Option, + subst: impl FnOnce() -> TypeExprRef, +) -> Option { + let instance_level = expansion_level.max(gadt_instance_level(ctx, env, ty)); + if let Some(instance_level) = instance_level + && ctx.get_level(ty) < instance_level + { + *ambiguous = Some(ty); + return None; } + let expanded = subst(); + if let Some(instance_level) = instance_level { + ctx.add_gadt_instances(env.gadt_instance_scope(), instance_level, &[ty, expanded]); + } + Some(expanded) } fn try_expand_head(ctx: &TypeContext, env: &Env, ty: TypeExprRef) -> Option { - try_expand_head_with_mode(ctx, env, ty, ExpandHeadMode::General) + try_expand_head_with_mode(ctx, env, ty, ExpandHeadMode::General, &mut None) } /// Fully expand a type through all aliases until it can't be expanded further. @@ -5169,7 +5168,7 @@ pub(crate) fn expand_abbrev_opt_once( // OCaml compiler/ml/ctype.ml:4165 calls `expand_abbrev_opt` from // `cyclic_abbrev`; ctype.ml:1464-1478 defines that as the Private // expansion path through `Env.find_type_expansion_opt`. - try_expand_head_with_mode(ctx, env, ty, ExpandHeadMode::Optimize) + try_expand_head_with_mode(ctx, env, ty, ExpandHeadMode::Optimize, &mut None) .map(|expanded| ctx.repr(expanded)) } @@ -6393,7 +6392,7 @@ fn subtype_rec( Ok(()) } (TypeDesc::Tconstr { path: p1, .. }, _) if generic_private_abbrev(ctx, env, p1) => { - match try_expand_head_with_mode(ctx, env, t1, ExpandHeadMode::Optimize) { + match try_expand_head_with_mode(ctx, env, t1, ExpandHeadMode::Optimize, &mut None) { Some(expanded) => subtype_rec(ctx, env, subtypes, trace, expanded, t2, cstrs), None => { push_subtype_cstr(cstrs, trace, t1, t2, None); @@ -7338,7 +7337,7 @@ fn expand_head_with_mode( ty: TypeExprRef, mode: ExpandHeadMode, ) -> TypeExprRef { - match expand_head_traced(ctx, env, ty, mode, false) { + match expand_head_loop::(ctx, env, ty, mode) { Ok(expanded) => expanded, Err(_) => unreachable!("a safe expansion reports no ambiguous GADT instance"), } @@ -7346,35 +7345,42 @@ fn expand_head_with_mode( /// OCaml `expand_head_unif` (compiler/ml/ctype.ml:1279) for unification: /// an expansion that would let a GADT instance out of its equation's scope -/// is OCaml's `Unify [(ty, newvar2 level)]` (ctype.ml:1225). +/// fails with OCaml's `Unify [(ty, newvar2 level)]` (ctype.ml:1225). fn expand_head_unif_traced( ctx: &TypeContext, env: &Env, ty: TypeExprRef, mode: ExpandHeadMode, ) -> TypeResult { - expand_head_traced(ctx, env, ty, mode, true).map_err(|ambiguous| { - let level = ctx.get_level(ambiguous); - TypeError::Unify(vec![(ambiguous, new_var_at_level(ctx, level))]) - }) + expand_head_loop::(ctx, env, ty, mode) + .map_err(|ambiguous| ambiguous_instance(ctx, ambiguous)) +} + +/// OCaml's `Unify [(ty, newvar2 level)]` for an ambiguous GADT instance +/// `ty` (compiler/ml/ctype.ml:589, 1225). +#[cold] +fn ambiguous_instance(ctx: &TypeContext, ty: TypeExprRef) -> TypeError { + let level = ctx.get_level(ty); + TypeError::Unify(vec![(ty, new_var_at_level(ctx, level))]) } /// OCaml `try_expand_head` (compiler/ml/ctype.ml:1266-1276): expand the head -/// of `ty` until it cannot be expanded, with `try_expand_once` when -/// `unsafe_once` (an ambiguous instance is `Err`) and `try_expand_safe` -/// otherwise. When the result is a GADT instance, `ty` and the expansions -/// memorized from it join its set. At most 20 expansions; the instance test -/// is one load and one branch when the unit has no instance scope. -fn expand_head_traced( +/// of `ty` until it cannot be expanded. With `PROPAGATE` an ambiguous GADT +/// instance is `Err` (`try_expand_once`); without, it ends the expansion +/// (`try_expand_safe`). While instances are traced, a result that is one +/// makes `ty` and the expansions memorized from it members of its set. At +/// most 20 expansions; the instance test is one load and one branch while +/// instances are not traced. +#[inline(always)] +fn expand_head_loop( ctx: &TypeContext, env: &Env, ty: TypeExprRef, mode: ExpandHeadMode, - unsafe_once: bool, ) -> Result { let start = ctx.repr(ty); let mut current = start; - let mut expanded_once = false; + let mut ambiguous = None; // Stack-allocated cycle detection for up to 20 iterations. // Linear scan is faster than HashSet for this small size. let mut seen = [TypeExprRef(0); 20]; @@ -7384,14 +7390,8 @@ fn expand_head_traced( } seen[seen_len] = current; let seen_len = seen_len + 1; - let next = if unsafe_once { - try_expand_head_traced(ctx, env, current, mode)? - } else { - try_expand_head_with_mode(ctx, env, current, mode) - }; - match next { + match try_expand_head_with_mode(ctx, env, current, mode, &mut ambiguous) { Some(expanded) => { - expanded_once = true; let expanded = ctx.repr(expanded); if expanded == current { break; @@ -7401,17 +7401,35 @@ fn expand_head_traced( } current = expanded; } - None => break, + None => { + if PROPAGATE && let Some(ambiguous) = ambiguous { + return Err(ambiguous); + } + break; + } } } - // ctype.ml:1273-1275: `ty` and its expansions are instances where the - // full expansion is one. - if expanded_once && let Some(level) = gadt_instance_level(ctx, env, current) { - ctx.add_gadt_instance_chain(env.gadt_instance_scope(), level, start); + // ctype.ml:1273-1275. OCaml makes this test after every expansion; it + // is made here only while instances are traced, so that an expansion + // outside a unification pays one load and one branch. No program found + // shows the difference (CHECKER_DEPARTURES.md, A1). + if current != start && ctx.trace_gadt_instances() { + add_expansion_chain(ctx, env, start, current); } Ok(current) } +/// ctype.ml:1273-1275: when the full expansion `expanded` of `ty` is a GADT +/// instance, `ty` and its memorized expansions join its set. One +/// [`gadt_instance_level`] plus [`TypeContext::add_gadt_instance_chain`]. +#[cold] +#[inline(never)] +fn add_expansion_chain(ctx: &TypeContext, env: &Env, ty: TypeExprRef, expanded: TypeExprRef) { + if let Some(level) = gadt_instance_level(ctx, env, expanded) { + ctx.add_gadt_instance_chain(env.gadt_instance_scope(), level, ty); + } +} + // ============================================================================ // Method Filtering (Objects) // ============================================================================ @@ -8216,14 +8234,19 @@ pub fn unify( return Ok(()); } - let reset_tracing = - ctx.check_trace_gadt_instances(state.env().is_some_and(|env| env.has_local_constraints())); + let has_local_constraints = state.env().is_some_and(|env| env.has_local_constraints()); + let reset_tracing = ctx.check_trace_gadt_instances(has_local_constraints); // Mark as being unified state.mark_unified(t1, t2); // Get descriptors - let result = match unify_newtypes(ctx, state, t1, t2) { + let newtypes = if has_local_constraints { + unify_newtypes(ctx, state, t1, t2) + } else { + None + }; + let result = match newtypes { Some(result) => result, None => unify_types(ctx, state, t1, t2, t2), }; @@ -12417,76 +12440,71 @@ pub fn lower_args(ctx: &TypeContext, env: &Env, ty: TypeExprRef) { /// This replaces all generic type variables with fresh ones, /// creating a new instance of a polymorphic type. pub fn instance(ctx: &TypeContext, ty: TypeExprRef) -> TypeExprRef { - if ctx.counts_this_call() { - return counted_instance(ctx, [ty], || instance(ctx, ty)); - } - let ty = ctx.repr(ty); - // OCaml compiler/ml/ctype.ml:762: a non-generic root needs no copy session. - // Partial copies must still use instance_partial's forgetting rules. - if ctx.get_level(ty) != GENERIC_LEVEL { - return ty; - } - let mut cache = CopyCache::new(ctx); - copy_type_cached(ctx, ty, &mut cache) + instance_copy(ctx, None, ty) } /// OCaml `instance env sch` (compiler/ml/ctype.ml:879-887): [`instance`], /// and when `env` has local constraints, a copy of a GADT instance joins -/// the instance's set (`copy ?env`, ctype.ml:770-774). Without an instance -/// scope in the unit this costs one load and one branch more than -/// [`instance`]. +/// the instance's set (`copy ?env`, ctype.ml:770-774). Beyond +/// [`instance`], a copy made in a unit without an instance scope costs one +/// load and one branch. pub fn instance_in(ctx: &TypeContext, env: &Env, ty: TypeExprRef) -> TypeExprRef { - let Some(scope) = copy_instance_scope(ctx, env) else { - return instance(ctx, ty); - }; + instance_copy(ctx, Some(env), ty) +} + +#[inline(always)] +fn instance_copy(ctx: &TypeContext, env: Option<&Env>, ty: TypeExprRef) -> TypeExprRef { + if ctx.counts_this_call() { + return counted_instance(ctx, [ty], || instance_copy(ctx, env, ty)); + } let ty = ctx.repr(ty); + // OCaml compiler/ml/ctype.ml:762: a non-generic root needs no copy session. + // Partial copies must still use instance_partial's forgetting rules. if ctx.get_level(ty) != GENERIC_LEVEL { return ty; } let mut cache = CopyCache::new(ctx); let copy = copy_type_cached(ctx, ty, &mut cache); - add_copied_gadt_instances(ctx, scope, &cache); + if let Some(env) = env + && ctx.has_gadt_instance_scopes() + { + add_copied_gadt_instances(ctx, env, &cache); + } copy } /// OCaml `instance_list env schl` (compiler/ml/ctype.ml:891-894): as /// [`instance_in`], sharing one copy session. pub fn instance_list_in(ctx: &TypeContext, env: &Env, types: &[TypeExprRef]) -> Vec { - let Some(scope) = copy_instance_scope(ctx, env) else { - return instance_list(ctx, types); - }; + if ctx.counts_this_call() { + return counted_instance(ctx, types.iter().copied(), || { + instance_list_in(ctx, env, types) + }); + } let mut cache = CopyCache::new(ctx); let copies = types .iter() .map(|&ty| copy_type_cached(ctx, ty, &mut cache)) .collect(); - add_copied_gadt_instances(ctx, scope, &cache); + if ctx.has_gadt_instance_scopes() { + add_copied_gadt_instances(ctx, env, &cache); + } copies } -/// The GADT instance scope a copy in `env` adds to: OCaml's `gadt_env` -/// (ctype.ml:877), an environment with local constraints, and in it an -/// instance scope. One load and one branch when the unit has none. -#[inline] -fn copy_instance_scope(ctx: &TypeContext, env: &Env) -> Option { - if !ctx.has_gadt_instance_scopes() || !env.has_local_constraints() { - return None; - } +/// `copy ?env` (compiler/ml/ctype.ml:770-774) for a finished copy session in +/// `env`: under local constraints (OCaml's `gadt_env`, ctype.ml:877), the +/// copy of each node in an instance set joins that set. The originals are +/// not changed by the copy, so testing them afterwards is testing them when +/// they were copied. Cost: per copied node, one +/// [`TypeContext::gadt_instance_level`]. +#[cold] +#[inline(never)] +fn add_copied_gadt_instances(ctx: &TypeContext, env: &Env, cache: &CopyCache<'_>) { let scope = env.gadt_instance_scope(); - (!scope.is_none()).then_some(scope) -} - -/// `copy ?env` (compiler/ml/ctype.ml:770-774) for a finished copy session: -/// the copy of each node in an instance set joins that set. The originals -/// are not changed by the copy, so testing them afterwards is testing them -/// when they were copied. Cost: per copied node, one -/// [`TypeContext::gadt_instance_level`]; run only under local constraints -/// with an instance scope. -fn add_copied_gadt_instances( - ctx: &TypeContext, - scope: super::context::GadtScopeRef, - cache: &CopyCache<'_>, -) { + if !env.has_local_constraints() || scope.is_none() { + return; + } cache.nodes.for_each(|original, ©| { if let Some(level) = ctx.gadt_instance_level(scope, ctx.repr(original)) { ctx.add_gadt_instances(scope, level, &[copy]); From b46a3af774864b47196b76313d00e62e38969d38 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:45:00 +0000 Subject: [PATCH 05/30] Add no GADT instance where no instance scope is at the equation's level Why: The checker tests on trunk drive the old checker's pattern unification on an environment that has an equation (expansion level 999) but no instance scope, which the type checker never builds: both callers of `Env::add_gadt_instance_level` add the scope before the patterns that add equations. `add_gadt_instances` panicked there, where OCaml's `List.assoc` asserts (compiler/ml/env.ml:1326-1328). It now adds nothing; `tc::differential::tests::old_checker_gives_the_equation_to_the_newer_locally_abstract_type`, `generated_cases_find_a_pattern_unification_in_expression_mode` and `old_side_of_the_pattern_plan_is_not_vacuous` pass unchanged. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/types/context.rs | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/compiler-rust/src/types/context.rs b/compiler-rust/src/types/context.rs index 318f9bbf51..82e88d99d3 100644 --- a/compiler-rust/src/types/context.rs +++ b/compiler-rust/src/types/context.rs @@ -5759,18 +5759,22 @@ impl TypeContext { /// The scope at `level` from `scope` outwards: OCaml's /// `List.assoc lv env.gadt_instances` (env.ml:1326-1328, 1333-1335). - /// One step per scope visited. - fn gadt_instance_scope_at(&self, scope: GadtScopeRef, level: i32) -> GadtScopeRef { + /// One step per scope visited. `None` where OCaml asserts: an + /// environment with an equation but no instance scope at its level, + /// which the type checker does not make (both of its callers of + /// [`Env::add_gadt_instance_level`] add the scope before the patterns + /// that add equations) and the checker tests build directly. + fn gadt_instance_scope_at(&self, scope: GadtScopeRef, level: i32) -> Option { let scopes = self.gadt_instance_scopes.borrow(); let mut current = scope; while !current.is_none() { let entry = &scopes[current.index()]; if entry.level == level { - return current; + return Some(current); } current = entry.parent; } - panic!("Env.add_gadt_instances: no instance scope at level {level}") + None } /// Append `ty` to the set of `scope`, journaled. O(1) amortized. A @@ -5794,7 +5798,9 @@ impl TypeContext { level: i32, types: &[TypeExprRef], ) { - let scope = self.gadt_instance_scope_at(scope, level); + let Some(scope) = self.gadt_instance_scope_at(scope, level) else { + return; + }; for &ty in types { self.push_gadt_instance(scope, ty); } @@ -5807,7 +5813,9 @@ impl TypeContext { /// plus, per type of the chain, one step per member and one walk of the /// constructor's memo chain. pub(crate) fn add_gadt_instance_chain(&self, scope: GadtScopeRef, level: i32, ty: TypeExprRef) { - let scope = self.gadt_instance_scope_at(scope, level); + let Some(scope) = self.gadt_instance_scope_at(scope, level) else { + return; + }; let mut current = Some(ty); while let Some(ty) = current { let ty = self.repr(ty); From c0daf094f2135ae7e9066d9d37581f03aadbae84 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:45:00 +0000 Subject: [PATCH 06/30] Re-record the checker coverage ratchet for the new tests/tests unit tests/tests gained gadt_instance_ambiguous_accepted, one more unit the new checker declines (NotBuilt 832 -> 833); recorded with `scripts/tc_coverage.py --rescript rewatch/target/release/rescript --write`. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/tc_coverage.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler-rust/tc_coverage.txt b/compiler-rust/tc_coverage.txt index 7af8ed20a3..b356573391 100644 --- a/compiler-rust/tc_coverage.txt +++ b/compiler-rust/tc_coverage.txt @@ -1,3 +1,3 @@ application NotBuilt 3841 runtime NotBuilt 158 -tests/tests NotBuilt 832 +tests/tests NotBuilt 833 From c8346e661f3b054e7b19c8d0e47138955bcb6170 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:03:48 +0000 Subject: [PATCH 07/30] Record the cost of the GADT instance port and its later commits in A1 The instruction counts the CI check measured, by function, and the line numbers after the expansion was moved off the default path. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/docs/CHECKER_DEPARTURES.md | 46 ++++++++++++++++++------ 1 file changed, 35 insertions(+), 11 deletions(-) diff --git a/compiler-rust/docs/CHECKER_DEPARTURES.md b/compiler-rust/docs/CHECKER_DEPARTURES.md index 693580d5da..97843dec9d 100644 --- a/compiler-rust/docs/CHECKER_DEPARTURES.md +++ b/compiler-rust/docs/CHECKER_DEPARTURES.md @@ -8708,7 +8708,7 @@ reads one. `Env::add_gadt_instance_level` took no level and tracked nothing. Now the sets are in the type context (`TypeContext::new_gadt_instance_scope`, `gadt_instance_level`, `add_gadt_instances`, `add_gadt_instance_chain`, - `compiler-rust/src/types/context.rs:5725-5830`), each scope holding its + `compiler-rust/src/types/context.rs:5725-5845`), each scope holding its enclosing one's handle, and the environment holds the innermost handle (`compiler-rust/src/types/env.rs:2810`). Both callers of `add_gadt_instance_level` (`typecore.rs:11976`, `13625`) build the case @@ -8718,14 +8718,15 @@ reads one. are journaled (`TypeMutation::GadtInstance`) and undone on backtrack, as OCaml trails `set_typeset`. The equation records the pattern's newtype level as its expansion level (`env.ml:1805-1810`; - `add_gadt_equation`, `ctype.rs:1845`); `check_trace_gadt_instances` + `add_gadt_equation`, `ctype.rs:1839`); `check_trace_gadt_instances` forgets the memorized expansions (`ctype.ml:182`); the expansion test is - `try_expand_head_traced` (`ctype.rs:4764`), made before the - substitution, which it does not affect; `expand_head_traced` - (`ctype.rs:7368`) adds the chain; the unifier's expansions - (`unify2`, `ctype.ml:2289-2292`) propagate the refusal - (`expand_head_unif_traced`, `ctype.rs:7350`); `update_level_pass` - (`ctype.rs:3005`) makes the level test. Without OCaml's arm of `unify` + `subst_gadt_instance` (`ctype.rs:5129`), reached from + `try_expand_head_with_mode` (`ctype.rs:4749`) only while tracing and + made before the substitution, which it does not affect; the head + expansion loop (`expand_head_loop`, `ctype.rs:7375`) adds the chain; + the unifier's expansions (`unify2`, `ctype.ml:2289-2292`) propagate the + refusal (`expand_head_unif_traced`, `ctype.rs:7349`); + `update_level_pass` (`ctype.rs:2999`) makes the level test. Without OCaml's arm of `unify` for two nullary locally abstract types (`ctype.ml:2255-2268`: expand only the later one, lower nothing first), p11 became refused. A trace with the arm disabled shows `unify_types` lowering the copy of `b` @@ -8739,10 +8740,15 @@ reads one. `instance env` and `instance_list env` (`ctype.ml:877-894`), adds the copy of an instance to its set under local constraints. A function generalized inside a case (q01) gave Rust copies that were no instances. - `instance_in` and `instance_list_in` (`ctype.rs:12438`) take the + `instance_in` and `instance_list_in` (`ctype.rs:12451`) take the environment and, only under local constraints with an instance scope, walk the finished copy's table once (`add_copied_gadt_instances`, - `ctype.rs:12485`); the typecore sites of OCaml's `instance env` use them. + `ctype.rs:12503`); the typecore sites of OCaml's `instance env` use them. +- `752db1e00` keeps these tests off the default path (see "Cost" below); + `b46a3af77` adds nothing where an environment has an equation but no + instance scope at its level, a state OCaml asserts against + (`env.ml:1326-1328`), which the type checker does not build and the + checker tests on trunk do. - Fixtures: super_errors `gadt_instance_ambiguous_*` (the 30 programs refused by OCaml that Rust accepted: p01, p02, p05, p07-p10, p12-p15, p19-p22, p27, p28, q01, q02, q04, q05, q07, q10, q12, q13, q15, q16, r07, @@ -8766,7 +8772,25 @@ that Rust makes without an environment (`update_level`, for the same nullary constructor, universal variables, object and row variables) make no level test; no program here reaches one with an instance. The port was stopped at the sites a program shows, as the size limit of the task -asks. +asks. The chain of `try_expand_head` (`ctype.ml:1273-1275`) is added only +while tracing (`expand_head_loop`), where OCaml adds it after every +expansion; no program of the 64 shows the difference. + +Cost: open. The `Instruction count` check on a clean `tests/tests` build +measured +12,960,104 instructions (+0.313%) for `92862d207`..`7d08707fd` +and +11,397,960 (+0.276%) for `c0daf094f` (base 4,134,894,291, head +4,146,292,251), against the limit of +0.03%. Of the second: +`find_abbrev_expansion` +8.2M against `try_expand_head_with_mode` +-4.7M (the second caller, the chain, keeps it from being inlined), +`instance_in` +7.1M against `instance` -6.0M and `instance_list_in` ++1.4M against `instance_list` -1.3M (the flag test after a copy and the +environment argument), `expand_head_unif_traced` +2.4M and +`expand_head_with_mode` +1.0M (the out-slot and the chain test of the +loop), and about 2.5M of work that OCaml does too in units with an +instance scope (`add_copied_gadt_instances` 0.5M, `gadt_instance_level` +0.5M, the general level update instead of the plain one 0.5M, +`repr_chain` 0.4M, `unify` 0.3M, allocation). That last part alone is +above the limit. ## Fourth round: modules, aliases and usage marks From ae16a975d6ce4637d2198ff68156276747ec231a Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:15:34 +0000 Subject: [PATCH 08/30] Copy for GADT instances only where the environment has an instance scope `instance` and `instance_list` are trunk's again. The `instance env` sites test the unit's flag and then the environment at hand; only when it has an instance scope do they call the copy that walks the finished copy table (`instance_with_gadt_instances`, not inlined). Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/types/ctype.rs | 83 +++++++++++++++++++++----------- 1 file changed, 56 insertions(+), 27 deletions(-) diff --git a/compiler-rust/src/types/ctype.rs b/compiler-rust/src/types/ctype.rs index ca179e4fa2..bfef9266c3 100644 --- a/compiler-rust/src/types/ctype.rs +++ b/compiler-rust/src/types/ctype.rs @@ -12440,45 +12440,78 @@ pub fn lower_args(ctx: &TypeContext, env: &Env, ty: TypeExprRef) { /// This replaces all generic type variables with fresh ones, /// creating a new instance of a polymorphic type. pub fn instance(ctx: &TypeContext, ty: TypeExprRef) -> TypeExprRef { - instance_copy(ctx, None, ty) + if ctx.counts_this_call() { + return counted_instance(ctx, [ty], || instance(ctx, ty)); + } + let ty = ctx.repr(ty); + // OCaml compiler/ml/ctype.ml:762: a non-generic root needs no copy session. + // Partial copies must still use instance_partial's forgetting rules. + if ctx.get_level(ty) != GENERIC_LEVEL { + return ty; + } + let mut cache = CopyCache::new(ctx); + copy_type_cached(ctx, ty, &mut cache) } /// OCaml `instance env sch` (compiler/ml/ctype.ml:879-887): [`instance`], -/// and when `env` has local constraints, a copy of a GADT instance joins -/// the instance's set (`copy ?env`, ctype.ml:770-774). Beyond -/// [`instance`], a copy made in a unit without an instance scope costs one -/// load and one branch. +/// and in an environment with an instance scope, [`instance_with_gadt_instances`]. +/// The test is one load and one branch in a unit without an instance scope. pub fn instance_in(ctx: &TypeContext, env: &Env, ty: TypeExprRef) -> TypeExprRef { - instance_copy(ctx, Some(env), ty) + if has_gadt_instance_scope(ctx, env) { + instance_with_gadt_instances(ctx, env, ty) + } else { + instance(ctx, ty) + } } -#[inline(always)] -fn instance_copy(ctx: &TypeContext, env: Option<&Env>, ty: TypeExprRef) -> TypeExprRef { +/// OCaml `instance_list env schl` (compiler/ml/ctype.ml:891-894): as +/// [`instance_in`], sharing one copy session. +pub fn instance_list_in(ctx: &TypeContext, env: &Env, types: &[TypeExprRef]) -> Vec { + if has_gadt_instance_scope(ctx, env) { + instance_list_with_gadt_instances(ctx, env, types) + } else { + instance_list(ctx, types) + } +} + +/// The guard of every GADT instance test outside unification: `env`, the +/// environment at hand, has an instance scope (it is inside a `switch` or +/// function whose patterns may add equations). The unit's flag is tested +/// first: one load and one branch in a unit without an instance scope. +fn has_gadt_instance_scope(ctx: &TypeContext, env: &Env) -> bool { + ctx.has_gadt_instance_scopes() && !env.gadt_instance_scope().is_none() +} + +/// [`instance`] in an environment with an instance scope: `copy ?env` +/// (compiler/ml/ctype.ml:770-774) adds the copy of each instance to its +/// set when `env` has local constraints. Cost: the copy, then per copied +/// node one [`TypeContext::gadt_instance_level`]. +#[inline(never)] +fn instance_with_gadt_instances(ctx: &TypeContext, env: &Env, ty: TypeExprRef) -> TypeExprRef { if ctx.counts_this_call() { - return counted_instance(ctx, [ty], || instance_copy(ctx, env, ty)); + return counted_instance(ctx, [ty], || instance_with_gadt_instances(ctx, env, ty)); } let ty = ctx.repr(ty); - // OCaml compiler/ml/ctype.ml:762: a non-generic root needs no copy session. - // Partial copies must still use instance_partial's forgetting rules. if ctx.get_level(ty) != GENERIC_LEVEL { return ty; } let mut cache = CopyCache::new(ctx); let copy = copy_type_cached(ctx, ty, &mut cache); - if let Some(env) = env - && ctx.has_gadt_instance_scopes() - { - add_copied_gadt_instances(ctx, env, &cache); - } + add_copied_gadt_instances(ctx, env, &cache); copy } -/// OCaml `instance_list env schl` (compiler/ml/ctype.ml:891-894): as -/// [`instance_in`], sharing one copy session. -pub fn instance_list_in(ctx: &TypeContext, env: &Env, types: &[TypeExprRef]) -> Vec { +/// [`instance_list`] in an environment with an instance scope, as +/// [`instance_with_gadt_instances`]. +#[inline(never)] +fn instance_list_with_gadt_instances( + ctx: &TypeContext, + env: &Env, + types: &[TypeExprRef], +) -> Vec { if ctx.counts_this_call() { return counted_instance(ctx, types.iter().copied(), || { - instance_list_in(ctx, env, types) + instance_list_with_gadt_instances(ctx, env, types) }); } let mut cache = CopyCache::new(ctx); @@ -12486,9 +12519,7 @@ pub fn instance_list_in(ctx: &TypeContext, env: &Env, types: &[TypeExprRef]) -> .iter() .map(|&ty| copy_type_cached(ctx, ty, &mut cache)) .collect(); - if ctx.has_gadt_instance_scopes() { - add_copied_gadt_instances(ctx, env, &cache); - } + add_copied_gadt_instances(ctx, env, &cache); copies } @@ -12498,13 +12529,11 @@ pub fn instance_list_in(ctx: &TypeContext, env: &Env, types: &[TypeExprRef]) -> /// not changed by the copy, so testing them afterwards is testing them when /// they were copied. Cost: per copied node, one /// [`TypeContext::gadt_instance_level`]. -#[cold] -#[inline(never)] fn add_copied_gadt_instances(ctx: &TypeContext, env: &Env, cache: &CopyCache<'_>) { - let scope = env.gadt_instance_scope(); - if !env.has_local_constraints() || scope.is_none() { + if !env.has_local_constraints() { return; } + let scope = env.gadt_instance_scope(); cache.nodes.for_each(|original, ©| { if let Some(level) = ctx.gadt_instance_level(scope, ctx.repr(original)) { ctx.add_gadt_instances(scope, level, &[copy]); From c3cd63b5dd9d486f1f2238e4253e138d96806143 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:29:48 +0000 Subject: [PATCH 09/30] Expand heads with the GADT instance test only where the environment has an instance scope Trunk's head expansion runs unchanged outside an instance scope. In an environment with one, a traced loop calls the traced instantiation of the expansion, which makes the test of expand_abbrev_gen, and adds try_expand_head's chain whenever the result is an instance, as OCaml does whatever the tracing flag. The unifier's expansions take the same choice. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/types/ctype.rs | 155 +++++++++++++++++++------------ 1 file changed, 97 insertions(+), 58 deletions(-) diff --git a/compiler-rust/src/types/ctype.rs b/compiler-rust/src/types/ctype.rs index bfef9266c3..68cab09bd7 100644 --- a/compiler-rust/src/types/ctype.rs +++ b/compiler-rust/src/types/ctype.rs @@ -630,7 +630,7 @@ fn unify_newtypes( let expand_first = find_newtype_level(ctx, env, &p1) >= find_newtype_level(ctx, env, &p2); let expanded = if expand_first { t1 } else { t2 }; let mut ambiguous = None; - match try_expand_head_with_mode(ctx, env, expanded, ExpandHeadMode::Unify, &mut ambiguous) { + match try_expand_head_with_mode::(ctx, env, expanded, ExpandHeadMode::Unify, &mut ambiguous) { Some(expansion) => { let expansion = ctx.repr(expansion); Some(if expand_first { @@ -869,7 +869,7 @@ fn expands_to_datatype(ctx: &TypeContext, env: &Env, ty: TypeExprRef) -> bool { return true; } drop(decl); - match try_expand_head_with_mode(ctx, env, ty, ExpandHeadMode::General, &mut None) { + match try_expand_head(ctx, env, ty) { Some(expanded) => expands_to_datatype(ctx, env, expanded), None => false, } @@ -4745,8 +4745,10 @@ enum ExpandHeadMode { /// level)]` (ctype.ml:1225): it returns `None` with `ty` in `ambiguous`, /// having changed nothing. A caller that expands safely /// (`try_expand_safe`, ctype.ml:1260-1265) takes that as a type that cannot -/// be expanded. -fn try_expand_head_with_mode( +/// be expanded. Only the `TRACED` instantiation, called in an environment +/// with an instance scope, makes the test; without one the test cannot +/// fail, and the other instantiation is trunk's expansion. +fn try_expand_head_with_mode( ctx: &TypeContext, env: &Env, ty: TypeExprRef, @@ -4815,7 +4817,7 @@ fn try_expand_head_with_mode( ctx.type_list(args), ) }; - if ctx.trace_gadt_instances() { + if TRACED && ctx.trace_gadt_instances() { return subst_gadt_instance(ctx, env, ty, expansion_level, ambiguous, subst); } Some(subst()) @@ -5124,8 +5126,6 @@ fn try_expand_head_with_mode( /// expanded; otherwise `ty` and its expansion join that set. The test is /// made before `subst`, which leaves `ty` as it is. Cost: one /// [`gadt_instance_level`] and the substitution. -#[cold] -#[inline(never)] fn subst_gadt_instance( ctx: &TypeContext, env: &Env, @@ -5149,7 +5149,11 @@ fn subst_gadt_instance( } fn try_expand_head(ctx: &TypeContext, env: &Env, ty: TypeExprRef) -> Option { - try_expand_head_with_mode(ctx, env, ty, ExpandHeadMode::General, &mut None) + if has_gadt_instance_scope(ctx, env) { + try_expand_head_with_mode::(ctx, env, ty, ExpandHeadMode::General, &mut None) + } else { + try_expand_head_with_mode::(ctx, env, ty, ExpandHeadMode::General, &mut None) + } } /// Fully expand a type through all aliases until it can't be expanded further. @@ -5168,7 +5172,7 @@ pub(crate) fn expand_abbrev_opt_once( // OCaml compiler/ml/ctype.ml:4165 calls `expand_abbrev_opt` from // `cyclic_abbrev`; ctype.ml:1464-1478 defines that as the Private // expansion path through `Env.find_type_expansion_opt`. - try_expand_head_with_mode(ctx, env, ty, ExpandHeadMode::Optimize, &mut None) + try_expand_head_with_mode::(ctx, env, ty, ExpandHeadMode::Optimize, &mut None) .map(|expanded| ctx.repr(expanded)) } @@ -6392,7 +6396,7 @@ fn subtype_rec( Ok(()) } (TypeDesc::Tconstr { path: p1, .. }, _) if generic_private_abbrev(ctx, env, p1) => { - match try_expand_head_with_mode(ctx, env, t1, ExpandHeadMode::Optimize, &mut None) { + match try_expand_head_with_mode::(ctx, env, t1, ExpandHeadMode::Optimize, &mut None) { Some(expanded) => subtype_rec(ctx, env, subtypes, trace, expanded, t2, cstrs), None => { push_subtype_cstr(cstrs, trace, t1, t2, None); @@ -7337,42 +7341,83 @@ fn expand_head_with_mode( ty: TypeExprRef, mode: ExpandHeadMode, ) -> TypeExprRef { - match expand_head_loop::(ctx, env, ty, mode) { - Ok(expanded) => expanded, - Err(_) => unreachable!("a safe expansion reports no ambiguous GADT instance"), + if has_gadt_instance_scope(ctx, env) { + match expand_head_traced::(ctx, env, ty, mode) { + Ok(expanded) => expanded, + Err(_) => unreachable!("a safe expansion reports no ambiguous GADT instance"), + } + } else { + expand_head_plain(ctx, env, ty, mode) } } -/// OCaml `expand_head_unif` (compiler/ml/ctype.ml:1279) for unification: -/// an expansion that would let a GADT instance out of its equation's scope -/// fails with OCaml's `Unify [(ty, newvar2 level)]` (ctype.ml:1225). -fn expand_head_unif_traced( +/// Trunk's head expansion: [`expand_head_with_mode`] outside an instance +/// scope. +fn expand_head_plain( ctx: &TypeContext, env: &Env, ty: TypeExprRef, mode: ExpandHeadMode, -) -> TypeResult { - expand_head_loop::(ctx, env, ty, mode) - .map_err(|ambiguous| ambiguous_instance(ctx, ambiguous)) +) -> TypeExprRef { + let mut current = ctx.repr(ty); + // Stack-allocated cycle detection for up to 20 iterations. + // Linear scan is faster than HashSet for this small size. + let mut seen = [TypeExprRef(0); 20]; + for seen_len in 0..seen.len() { + if seen[..seen_len].contains(¤t) { + break; + } + seen[seen_len] = current; + let seen_len = seen_len + 1; + match try_expand_head_with_mode::(ctx, env, current, mode, &mut None) { + Some(expanded) => { + let expanded = ctx.repr(expanded); + if expanded == current { + break; + } + if seen[..seen_len].contains(&expanded) { + break; + } + current = expanded; + } + None => break, + } + } + current +} + +/// OCaml `expand_head_unif` (compiler/ml/ctype.ml:1279) at the expansions +/// of unification (`unify2`, ctype.ml:2289-2292): in an environment with an +/// instance scope, an expansion that would let a GADT instance out of its +/// equation's scope is `Err` with the instance; elsewhere trunk's +/// expansion. +fn expand_head_for_unify( + ctx: &TypeContext, + env: &Env, + ty: TypeExprRef, + mode: ExpandHeadMode, +) -> Result { + if has_gadt_instance_scope(ctx, env) { + expand_head_traced::(ctx, env, ty, mode) + } else { + Ok(expand_head_plain(ctx, env, ty, mode)) + } } /// OCaml's `Unify [(ty, newvar2 level)]` for an ambiguous GADT instance /// `ty` (compiler/ml/ctype.ml:589, 1225). -#[cold] fn ambiguous_instance(ctx: &TypeContext, ty: TypeExprRef) -> TypeError { let level = ctx.get_level(ty); TypeError::Unify(vec![(ty, new_var_at_level(ctx, level))]) } -/// OCaml `try_expand_head` (compiler/ml/ctype.ml:1266-1276): expand the head -/// of `ty` until it cannot be expanded. With `PROPAGATE` an ambiguous GADT -/// instance is `Err` (`try_expand_once`); without, it ends the expansion -/// (`try_expand_safe`). While instances are traced, a result that is one -/// makes `ty` and the expansions memorized from it members of its set. At -/// most 20 expansions; the instance test is one load and one branch while -/// instances are not traced. -#[inline(always)] -fn expand_head_loop( +/// OCaml `try_expand_head` (compiler/ml/ctype.ml:1266-1276) in an +/// environment with an instance scope: expand the head of `ty` until it +/// cannot be expanded. With `PROPAGATE` an ambiguous GADT instance is `Err` +/// (`try_expand_once`); without, it ends the expansion (`try_expand_safe`). +/// When the result is an instance, `ty` and the expansions memorized from +/// it join its set. At most 20 expansions. +fn expand_head_traced( ctx: &TypeContext, env: &Env, ty: TypeExprRef, @@ -7381,8 +7426,6 @@ fn expand_head_loop( let start = ctx.repr(ty); let mut current = start; let mut ambiguous = None; - // Stack-allocated cycle detection for up to 20 iterations. - // Linear scan is faster than HashSet for this small size. let mut seen = [TypeExprRef(0); 20]; for seen_len in 0..seen.len() { if seen[..seen_len].contains(¤t) { @@ -7390,7 +7433,7 @@ fn expand_head_loop( } seen[seen_len] = current; let seen_len = seen_len + 1; - match try_expand_head_with_mode(ctx, env, current, mode, &mut ambiguous) { + match try_expand_head_with_mode::(ctx, env, current, mode, &mut ambiguous) { Some(expanded) => { let expanded = ctx.repr(expanded); if expanded == current { @@ -7409,27 +7452,15 @@ fn expand_head_loop( } } } - // ctype.ml:1273-1275. OCaml makes this test after every expansion; it - // is made here only while instances are traced, so that an expansion - // outside a unification pays one load and one branch. No program found - // shows the difference (CHECKER_DEPARTURES.md, A1). - if current != start && ctx.trace_gadt_instances() { - add_expansion_chain(ctx, env, start, current); + // ctype.ml:1273-1275. + if current != start + && let Some(level) = gadt_instance_level(ctx, env, current) + { + ctx.add_gadt_instance_chain(env.gadt_instance_scope(), level, start); } Ok(current) } -/// ctype.ml:1273-1275: when the full expansion `expanded` of `ty` is a GADT -/// instance, `ty` and its memorized expansions join its set. One -/// [`gadt_instance_level`] plus [`TypeContext::add_gadt_instance_chain`]. -#[cold] -#[inline(never)] -fn add_expansion_chain(ctx: &TypeContext, env: &Env, ty: TypeExprRef, expanded: TypeExprRef) { - if let Some(level) = gadt_instance_level(ctx, env, expanded) { - ctx.add_gadt_instance_chain(env.gadt_instance_scope(), level, ty); - } -} - // ============================================================================ // Method Filtering (Objects) // ============================================================================ @@ -8882,8 +8913,10 @@ fn unify_types( if !facts.is_some_and(|facts| facts.var_free) { if ty_is_constr && state.env().is_some() && deep_occur(ctx, var, ty) { let env = state.env().expect("checked above"); - let exp1 = expand_head_unif_traced(ctx, env, t1, ExpandHeadMode::Unify)?; - let exp2 = expand_head_unif_traced(ctx, env, t2, ExpandHeadMode::Unify)?; + let exp1 = expand_head_for_unify(ctx, env, t1, ExpandHeadMode::Unify) + .map_err(|ty| ambiguous_instance(ctx, ty))?; + let exp2 = expand_head_for_unify(ctx, env, t2, ExpandHeadMode::Unify) + .map_err(|ty| ambiguous_instance(ctx, ty))?; return unify_after_expansion(ctx, state, t1, exp1, t2, exp2); } if occur_check(ctx, state.env(), state.mode, var, ty).is_err() { @@ -9016,8 +9049,10 @@ fn unify_types( // OCaml compiler/ml/ctype.ml:2338-2344 (`unify2`) expands // both constructor heads before the constructor-path cases // at ctype.ml:2412-2414 are considered. - let exp1 = expand_head_unif_traced(ctx, env, t1, ExpandHeadMode::Unify)?; - let exp2 = expand_head_unif_traced(ctx, env, t2, ExpandHeadMode::Unify)?; + let exp1 = expand_head_for_unify(ctx, env, t1, ExpandHeadMode::Unify) + .map_err(|ty| ambiguous_instance(ctx, ty))?; + let exp2 = expand_head_for_unify(ctx, env, t2, ExpandHeadMode::Unify) + .map_err(|ty| ambiguous_instance(ctx, ty))?; if exp1 != t1 || exp2 != t2 { return unify_after_expansion(ctx, state, t1, exp1, t2, exp2); } @@ -9131,8 +9166,10 @@ fn unify_types( // persistent aliases such as `Stdlib.Lazy.t` do not repeatedly // allocate normalized-but-still-abstract heads before argument // unification. - let exp1 = expand_head_unif_traced(ctx, env, t1, ExpandHeadMode::Unify)?; - let exp2 = expand_head_unif_traced(ctx, env, t2, ExpandHeadMode::Unify)?; + let exp1 = expand_head_for_unify(ctx, env, t1, ExpandHeadMode::Unify) + .map_err(|ty| ambiguous_instance(ctx, ty))?; + let exp2 = expand_head_for_unify(ctx, env, t2, ExpandHeadMode::Unify) + .map_err(|ty| ambiguous_instance(ctx, ty))?; if exp1 != t1 || exp2 != t2 { return unify_after_expansion(ctx, state, t1, exp1, t2, exp2); } @@ -9399,12 +9436,14 @@ fn unify_types( // An ambiguous GADT instance fails as in OCaml's // `expand_head_unif` (ctype.ml:2291-2292). let exp1 = if is_constr1 { - expand_head_unif_traced(ctx, env, t1, ExpandHeadMode::General)? + expand_head_for_unify(ctx, env, t1, ExpandHeadMode::General) + .map_err(|ty| ambiguous_instance(ctx, ty))? } else { t1 }; let exp2 = if is_constr2 { - expand_head_unif_traced(ctx, env, t2, ExpandHeadMode::General)? + expand_head_for_unify(ctx, env, t2, ExpandHeadMode::General) + .map_err(|ty| ambiguous_instance(ctx, ty))? } else { t2 }; From bcc2a4ef447e2e6232ebf6205d0c4b3358b137a3 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:39:14 +0000 Subject: [PATCH 10/30] Scan the memo for the GADT instance chain on its own The chain of try_expand_head (compiler/ml/env.ml:1342) has its own scan of the memorized expansions, so find_abbrev_expansion keeps trunk's one caller, the head expansion, and is inlined there as on trunk. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/types/context.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/compiler-rust/src/types/context.rs b/compiler-rust/src/types/context.rs index 82e88d99d3..5cb14c9232 100644 --- a/compiler-rust/src/types/context.rs +++ b/compiler-rust/src/types/context.rs @@ -5832,8 +5832,13 @@ impl TypeContext { TypeDesc::Tconstr { path, abbrev, .. } => Some((*path, *abbrev)), _ => None, }; + // `find_expans Private p !memo` (env.ml:1342): a memorized + // expansion of `path` of any privacy. Its own scan, so that + // `find_abbrev_expansion` keeps its one caller. current = constr.and_then(|(path, abbrev)| { - self.find_abbrev_expansion(abbrev, PrivateFlag::Private, &path) + self.scan_abbrev_chain(abbrev, |_, cached_path, _, expansion| { + path.same(cached_path).then_some(expansion) + }) }); } } From 4679c1d94de052e2a851382b9dfff167ad62c420 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:52:28 +0000 Subject: [PATCH 11/30] Format the lines of the GADT instance expansion rustfmt's layout for the lines the three attempts changed; no code change. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/types/ctype.rs | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/compiler-rust/src/types/ctype.rs b/compiler-rust/src/types/ctype.rs index 68cab09bd7..24f03caae2 100644 --- a/compiler-rust/src/types/ctype.rs +++ b/compiler-rust/src/types/ctype.rs @@ -630,7 +630,13 @@ fn unify_newtypes( let expand_first = find_newtype_level(ctx, env, &p1) >= find_newtype_level(ctx, env, &p2); let expanded = if expand_first { t1 } else { t2 }; let mut ambiguous = None; - match try_expand_head_with_mode::(ctx, env, expanded, ExpandHeadMode::Unify, &mut ambiguous) { + match try_expand_head_with_mode::( + ctx, + env, + expanded, + ExpandHeadMode::Unify, + &mut ambiguous, + ) { Some(expansion) => { let expansion = ctx.repr(expansion); Some(if expand_first { @@ -6396,7 +6402,13 @@ fn subtype_rec( Ok(()) } (TypeDesc::Tconstr { path: p1, .. }, _) if generic_private_abbrev(ctx, env, p1) => { - match try_expand_head_with_mode::(ctx, env, t1, ExpandHeadMode::Optimize, &mut None) { + match try_expand_head_with_mode::( + ctx, + env, + t1, + ExpandHeadMode::Optimize, + &mut None, + ) { Some(expanded) => subtype_rec(ctx, env, subtypes, trace, expanded, t2, cstrs), None => { push_subtype_cstr(cstrs, trace, t1, t2, None); @@ -9050,9 +9062,9 @@ fn unify_types( // both constructor heads before the constructor-path cases // at ctype.ml:2412-2414 are considered. let exp1 = expand_head_for_unify(ctx, env, t1, ExpandHeadMode::Unify) - .map_err(|ty| ambiguous_instance(ctx, ty))?; + .map_err(|ty| ambiguous_instance(ctx, ty))?; let exp2 = expand_head_for_unify(ctx, env, t2, ExpandHeadMode::Unify) - .map_err(|ty| ambiguous_instance(ctx, ty))?; + .map_err(|ty| ambiguous_instance(ctx, ty))?; if exp1 != t1 || exp2 != t2 { return unify_after_expansion(ctx, state, t1, exp1, t2, exp2); } @@ -9437,13 +9449,13 @@ fn unify_types( // `expand_head_unif` (ctype.ml:2291-2292). let exp1 = if is_constr1 { expand_head_for_unify(ctx, env, t1, ExpandHeadMode::General) - .map_err(|ty| ambiguous_instance(ctx, ty))? + .map_err(|ty| ambiguous_instance(ctx, ty))? } else { t1 }; let exp2 = if is_constr2 { expand_head_for_unify(ctx, env, t2, ExpandHeadMode::General) - .map_err(|ty| ambiguous_instance(ctx, ty))? + .map_err(|ty| ambiguous_instance(ctx, ty))? } else { t2 }; From 8d0abc3bb51aeb28f0ac61bce9eaadf84c2da79b Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:04:53 +0000 Subject: [PATCH 12/30] Record the measured cost of A1 split by function, and the chain's guard Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/docs/CHECKER_DEPARTURES.md | 70 ++++++++++++++++-------- 1 file changed, 47 insertions(+), 23 deletions(-) diff --git a/compiler-rust/docs/CHECKER_DEPARTURES.md b/compiler-rust/docs/CHECKER_DEPARTURES.md index 97843dec9d..7401e6219f 100644 --- a/compiler-rust/docs/CHECKER_DEPARTURES.md +++ b/compiler-rust/docs/CHECKER_DEPARTURES.md @@ -8722,10 +8722,10 @@ reads one. forgets the memorized expansions (`ctype.ml:182`); the expansion test is `subst_gadt_instance` (`ctype.rs:5129`), reached from `try_expand_head_with_mode` (`ctype.rs:4749`) only while tracing and - made before the substitution, which it does not affect; the head - expansion loop (`expand_head_loop`, `ctype.rs:7375`) adds the chain; - the unifier's expansions (`unify2`, `ctype.ml:2289-2292`) propagate the - refusal (`expand_head_unif_traced`, `ctype.rs:7349`); + made before the substitution, which it does not affect; the traced + head expansion (`expand_head_traced`) adds the chain; the unifier's + expansions (`unify2`, `ctype.ml:2289-2292`) propagate the refusal + (`expand_head_for_unify`); `update_level_pass` (`ctype.rs:2999`) makes the level test. Without OCaml's arm of `unify` for two nullary locally abstract types (`ctype.ml:2255-2268`: expand only the later one, lower nothing first), p11 became refused. A trace @@ -8772,25 +8772,49 @@ that Rust makes without an environment (`update_level`, for the same nullary constructor, universal variables, object and row variables) make no level test; no program here reaches one with an instance. The port was stopped at the sites a program shows, as the size limit of the task -asks. The chain of `try_expand_head` (`ctype.ml:1273-1275`) is added only -while tracing (`expand_head_loop`), where OCaml adds it after every -expansion; no program of the 64 shows the difference. - -Cost: open. The `Instruction count` check on a clean `tests/tests` build -measured +12,960,104 instructions (+0.313%) for `92862d207`..`7d08707fd` -and +11,397,960 (+0.276%) for `c0daf094f` (base 4,134,894,291, head -4,146,292,251), against the limit of +0.03%. Of the second: -`find_abbrev_expansion` +8.2M against `try_expand_head_with_mode` --4.7M (the second caller, the chain, keeps it from being inlined), -`instance_in` +7.1M against `instance` -6.0M and `instance_list_in` -+1.4M against `instance_list` -1.3M (the flag test after a copy and the -environment argument), `expand_head_unif_traced` +2.4M and -`expand_head_with_mode` +1.0M (the out-slot and the chain test of the -loop), and about 2.5M of work that OCaml does too in units with an -instance scope (`add_copied_gadt_instances` 0.5M, `gadt_instance_level` -0.5M, the general level update instead of the plain one 0.5M, -`repr_chain` 0.4M, `unify` 0.3M, allocation). That last part alone is -above the limit. +asks. The chain of `try_expand_head` (`ctype.ml:1273-1275`) is added +whenever the environment at hand has an instance scope +(`expand_head_traced`, since `c3cd63b5d`), as OCaml adds it whatever the +tracing flag, for example while the result of a `switch` is lowered in +the outer environment after its cases. Five programs aimed at that moment +(an abbreviation whose expansion is the instance: a local module's +`type u = a`, `type box<'a> = 'a` returned from the case, compared, and +bound in a `let` used after the `switch`, with and without a result +annotation) are accepted by OCaml and by Rust. + +Cost: open. The guard of every test outside unification is that the +environment at hand has an instance scope: the type context's flag (one +load, false in a unit with no instance scope) and then the environment's +handle (`has_gadt_instance_scope`). 434 of the 788 units of `tests/tests` +add an instance scope, 2,169 in all: OCaml's `contains_gadt` +(`typecore.ml:2372`) looks a pattern's constructors up by name with +`lookup_all_constructors`, and Rust ports that rule. + +The CI `Instruction count` check on a clean `tests/tests` build: ++12,960,104 (+0.313%) for `7d08707fd`, +11,397,960 (+0.276%) for +`c0daf094f`, +7,466,613 (+0.181%) for `4679c1d94` (base 4,134,982,569, +head 4,142,449,182). The last, split: + +| | function | change | +| --- | --- | ---: | +| a | `try_expand_head_with_mode::` (+20,876,059) and its closure (+268,694) against trunk's `try_expand_head_with_mode` (-29,369,475) and closure (-109,870), with `find_abbrev_expansion` +8,176,501, `find_pdot_expansion` +1,412,464, `register_pdot_expansion` +382,131, `pdot_expansion` +222,207 no longer inlined | +1,858,711 | +| a | `expand_head_plain` against `expand_head_with_mode` | -571,304 | +| a | `expand_head_for_unify` (the guard at the unifier's expansions) | +852,103 | +| a | the guard of `instance_in` at its sites: `type_application_parts` +601,508, `type_identifier` +168,826, `type_function_nary` +135,577, `instance_in` +91,230 | +997,141 | +| a | `moregen` | +219,454 | +| b | `gadt_instance_level` +471,915, `repr_chain` +391,308 (the lookups) | +863,223 | +| b | `try_expand_head_with_mode::` | +423,762 | +| b | `instance_with_gadt_instances` +342,857 against `instance` -313,577 | +29,280 | +| b | the general level update in place of the plain one: `update_level_checked_above` +283,546, `update_level_pass` +238,663, `update_level_children` +104,313, `TypeMutationSnapshot::drop` +104,168, `restore_type_state` +97,172, `lower_plain_levels::lower` -160,692 | +667,170 | +| b | `Env::data_mut` +190,067, `Env::add_gadt_instance_level` +91,766 (a scope per `switch` with a generalized constructor) | +281,833 | +| b | `unify` (the newtype arm and `cleanup_abbrev` under local constraints) | +257,776 | + +(a) is about +3.36M (+0.081%), above the +0.03% limit; (b) about +2.52M. +`IdTbl::find_by_ident` (+525,453), the path iterator and the allocator +make up the rest and move by as much between runs. The largest part of +(a) is the second instantiation of the head expansion: each calls +`find_abbrev_expansion` and `find_pdot_expansion`, which are no longer +inlined into trunk's instantiation. ## Fourth round: modules, aliases and usage marks From 82e309f01a31cd0d80eb7809cdc01b1eeaced62a Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:12:26 +0000 Subject: [PATCH 13/30] Guard the GADT instance tests by a type having joined an instance set Why: An instance scope exists inside almost every `switch` of more than one case: OCaml's `type_cases` adds the level whenever the exhaustiveness check will run (compiler/ml/typecore.ml:4814-4818, 4913-4914), so 434 of the 788 units of tests/tests add one. Every read of a set is a no-op while every set is empty, and a set gets its first member only from `expand_abbrev_gen` (ctype.ml:1217-1227) under the tracing flag. The type context's flag is now "a type has been added to an instance set in this unit", set where a member is pushed, not where a scope is created, and kept in one byte with the tracing flag. Copies and level updates test it; the expansion sites test the byte (tracing or a member), so the test that adds the first member still runs. Without either, every site runs trunk's code after one load and one branch. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/types/context.rs | 50 +++++++++++++++++++----------- compiler-rust/src/types/ctype.rs | 28 +++++++++++------ 2 files changed, 50 insertions(+), 28 deletions(-) diff --git a/compiler-rust/src/types/context.rs b/compiler-rust/src/types/context.rs index 5cb14c9232..1eee01bbaa 100644 --- a/compiler-rust/src/types/context.rs +++ b/compiler-rust/src/types/context.rs @@ -568,6 +568,11 @@ enum TypeMutation { GadtInstance(GadtScopeRef), } +/// [`TypeContext`]'s GADT state bit for OCaml's `trace_gadt_instances`. +const GADT_TRACING: u8 = 1; +/// [`TypeContext`]'s GADT state bit: a type has joined an instance set. +const GADT_MEMBERS: u8 = 2; + /// Handle of a GADT instance scope of [`TypeContext`]; `NONE` for an /// environment outside every such scope. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -858,8 +863,13 @@ pub struct TypeContext { /// Saved levels stack saved_levels: RefCell>, - /// GADT instance tracking flag - trace_gadt_instances: Cell, + /// OCaml's GADT instance state in one byte, so that a site that needs + /// to know whether either is set tests it with one load: + /// [`GADT_TRACING`], OCaml `Ctype.trace_gadt_instances`, and + /// [`GADT_MEMBERS`], set when a type is first added to an instance set + /// in this unit (it stays set if a backtrack removes the member: that is + /// only slower). + gadt_state: Cell, /// The sets of OCaml `Env.gadt_instances` (compiler/ml/env.ml:1305-1345), /// one per `switch` or function whose patterns may add equations, @@ -868,10 +878,6 @@ pub struct TypeContext { /// an environment copies a `u32` and never a set. gadt_instance_scopes: RefCell>, - /// Whether this unit has created a GADT instance scope: the one load - /// [`Self::has_gadt_instance_scopes`] tests on every level update. - has_gadt_instance_scopes: Cell, - /// Whether this unit created or copied a polymorphic type with at least /// one bound variable (see [`Self::note_bound_universal`]). Only then /// can the inclusion of the unit in its own inferred signature fail. @@ -1432,9 +1438,8 @@ impl TypeContext { nongen_level: Cell::new(0), global_level: Cell::new(1), saved_levels: RefCell::new(Vec::new()), - trace_gadt_instances: Cell::new(false), + gadt_state: Cell::new(0), gadt_instance_scopes: RefCell::new(Vec::new()), - has_gadt_instance_scopes: Cell::new(false), bound_universals: Cell::new(false), passive_variants: Cell::new(false), rigid_variants: Cell::new(false), @@ -5670,8 +5675,8 @@ impl TypeContext { /// through the instance test of `expand_abbrev_gen`. Returns whether /// this call turned it on. pub fn check_trace_gadt_instances(&self, has_constraints: bool) -> bool { - if !self.trace_gadt_instances.get() && has_constraints { - self.trace_gadt_instances.set(true); + if !self.trace_gadt_instances() && has_constraints { + self.gadt_state.set(self.gadt_state.get() | GADT_TRACING); self.clear_abbrev_memos(); true } else { @@ -5682,7 +5687,7 @@ impl TypeContext { /// Reset GADT instance tracing. pub fn reset_trace_gadt_instances(&self, was_set: bool) { if was_set { - self.trace_gadt_instances.set(false); + self.gadt_state.set(self.gadt_state.get() & !GADT_TRACING); } } @@ -5709,15 +5714,24 @@ impl TypeContext { /// Whether GADT instances are being tracked (OCaml `Ctype.trace_gadt_instances`). pub fn trace_gadt_instances(&self) -> bool { - self.trace_gadt_instances.get() + self.gadt_state.get() & GADT_TRACING != 0 + } + + /// Whether a type has been added to a GADT instance set in this unit. + /// While it has not, every set is empty and every test of OCaml's + /// `Env.gadt_instance_level` answers `None`. One load. + #[inline] + pub fn has_gadt_instances(&self) -> bool { + self.gadt_state.get() & GADT_MEMBERS != 0 } - /// Whether this unit has a GADT instance scope at all. One load: the - /// test every level update makes before it looks at an environment's - /// scopes (OCaml `Env.gadt_instance_level`, ctype.ml:587). + /// Whether GADT instances are traced or a type has been added to an + /// instance set: where an expansion may make the test of OCaml's + /// `expand_abbrev_gen` (ctype.ml:1215-1227), which adds the first + /// member of a set. One load. #[inline] - pub fn has_gadt_instance_scopes(&self) -> bool { - self.has_gadt_instance_scopes.get() + pub fn expands_gadt_instances(&self) -> bool { + self.gadt_state.get() != 0 } /// OCaml `Env.add_gadt_instance_level lv` (compiler/ml/env.ml:1307-1308): @@ -5731,7 +5745,6 @@ impl TypeContext { parent, members: Vec::new(), }); - self.has_gadt_instance_scopes.set(true); scope } @@ -5783,6 +5796,7 @@ impl TypeContext { self.gadt_instance_scopes.borrow_mut()[scope.index()] .members .push(ty); + self.gadt_state.set(self.gadt_state.get() | GADT_MEMBERS); self.record_mutation( || TypeMutation::GadtInstance(scope), crate::perf_counters::TypeMutationKind::State, diff --git a/compiler-rust/src/types/ctype.rs b/compiler-rust/src/types/ctype.rs index 24f03caae2..37557aa75d 100644 --- a/compiler-rust/src/types/ctype.rs +++ b/compiler-rust/src/types/ctype.rs @@ -2764,7 +2764,7 @@ fn update_level_checked_above( // (`update_level_pass`), which the plain update does not test: it is // skipped in an environment with an instance scope. One load and one // branch when the unit has none. - let instances = ctx.has_gadt_instance_scopes() && !env.gadt_instance_scope().is_none(); + let instances = ctx.has_gadt_instances() && !env.gadt_instance_scope().is_none(); if !instances && lower_plain_levels(ctx, env, level, ty) { return Ok(()); } @@ -2971,7 +2971,7 @@ fn level_update_is_plain( /// instance scope; otherwise [`TypeContext::gadt_instance_level`]. #[inline] pub(crate) fn gadt_instance_level(ctx: &TypeContext, env: &Env, ty: TypeExprRef) -> Option { - if !ctx.has_gadt_instance_scopes() { + if !ctx.has_gadt_instances() { return None; } let scope = env.gadt_instance_scope(); @@ -5155,7 +5155,7 @@ fn subst_gadt_instance( } fn try_expand_head(ctx: &TypeContext, env: &Env, ty: TypeExprRef) -> Option { - if has_gadt_instance_scope(ctx, env) { + if expands_gadt_instances(ctx, env) { try_expand_head_with_mode::(ctx, env, ty, ExpandHeadMode::General, &mut None) } else { try_expand_head_with_mode::(ctx, env, ty, ExpandHeadMode::General, &mut None) @@ -7353,7 +7353,7 @@ fn expand_head_with_mode( ty: TypeExprRef, mode: ExpandHeadMode, ) -> TypeExprRef { - if has_gadt_instance_scope(ctx, env) { + if expands_gadt_instances(ctx, env) { match expand_head_traced::(ctx, env, ty, mode) { Ok(expanded) => expanded, Err(_) => unreachable!("a safe expansion reports no ambiguous GADT instance"), @@ -7409,7 +7409,7 @@ fn expand_head_for_unify( ty: TypeExprRef, mode: ExpandHeadMode, ) -> Result { - if has_gadt_instance_scope(ctx, env) { + if expands_gadt_instances(ctx, env) { expand_head_traced::(ctx, env, ty, mode) } else { Ok(expand_head_plain(ctx, env, ty, mode)) @@ -12525,12 +12525,20 @@ pub fn instance_list_in(ctx: &TypeContext, env: &Env, types: &[TypeExprRef]) -> } } -/// The guard of every GADT instance test outside unification: `env`, the -/// environment at hand, has an instance scope (it is inside a `switch` or -/// function whose patterns may add equations). The unit's flag is tested -/// first: one load and one branch in a unit without an instance scope. +/// The guard of the GADT instance tests of copies and level updates: a type +/// has joined an instance set in this unit (until one has, every set is +/// empty and each test answers nothing) and `env`, the environment at hand, +/// has an instance scope. One load and one branch while no type has. fn has_gadt_instance_scope(ctx: &TypeContext, env: &Env) -> bool { - ctx.has_gadt_instance_scopes() && !env.gadt_instance_scope().is_none() + ctx.has_gadt_instances() && !env.gadt_instance_scope().is_none() +} + +/// The guard of the traced expansion: instances are traced (the test of +/// `expand_abbrev_gen`, ctype.ml:1215-1227, may add the first member of a +/// set) or a type has joined a set, and `env` has an instance scope. One +/// load and one branch while neither holds. +fn expands_gadt_instances(ctx: &TypeContext, env: &Env) -> bool { + ctx.expands_gadt_instances() && !env.gadt_instance_scope().is_none() } /// [`instance`] in an environment with an instance scope: `copy ?env` From cbaf8d70d3751cfb200795fa69b8fa278826d1c2 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:23:35 +0000 Subject: [PATCH 14/30] Test a GADT instance before trunk's single expansion, not in a second copy The traced expansion was a second instantiation of `try_expand_head_with_mode`, so `find_abbrev_expansion` and `find_pdot_expansion` had two callers and were no longer inlined into trunk's. `try_expand_head_traced` now wraps trunk's function: while tracing and with no memorized expansion, it looks up the equation and its expansion level, refuses an ambiguous instance before expanding (nothing to undo), and otherwise records the type and its expansion in their instance set after it. A type that is an instance through another route is tested after the expansion, whose memo is then forgotten as OCaml's `try_expand_safe` backtracks it. The memo test is a scan of its own (`has_memorized_expansion`). Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/types/context.rs | 17 +++ compiler-rust/src/types/ctype.rs | 164 +++++++++++++++-------------- 2 files changed, 100 insertions(+), 81 deletions(-) diff --git a/compiler-rust/src/types/context.rs b/compiler-rust/src/types/context.rs index 1eee01bbaa..210969f87f 100644 --- a/compiler-rust/src/types/context.rs +++ b/compiler-rust/src/types/context.rs @@ -4038,6 +4038,23 @@ impl TypeContext { }) } + /// Whether the chain `memo` memorizes an expansion of `path` that + /// `find_expans private_flag` finds (compiler/ml/btype.ml:612-618): the + /// test of the traced expansion, a scan of its own so that + /// [`Self::find_abbrev_expansion`] keeps its one caller. One step per + /// chain cell. + pub(crate) fn has_memorized_expansion( + &self, + memo: AbbrevMemoRef, + private_flag: PrivateFlag, + path: &Path, + ) -> bool { + self.scan_abbrev_chain(memo, |cached_private, cached_path, _, expansion| { + (private_flag <= cached_private && path.same(cached_path)).then_some(expansion) + }) + .is_some() + } + /// Find the original type (abbrev field) for a path in a memo chain. /// This is OCaml's `find_repr` — returns the ORIGINAL type node that was /// memoized, creating Tlink sharing in copy_type_cached. diff --git a/compiler-rust/src/types/ctype.rs b/compiler-rust/src/types/ctype.rs index 37557aa75d..54dbd24429 100644 --- a/compiler-rust/src/types/ctype.rs +++ b/compiler-rust/src/types/ctype.rs @@ -629,15 +629,8 @@ fn unify_newtypes( } let expand_first = find_newtype_level(ctx, env, &p1) >= find_newtype_level(ctx, env, &p2); let expanded = if expand_first { t1 } else { t2 }; - let mut ambiguous = None; - match try_expand_head_with_mode::( - ctx, - env, - expanded, - ExpandHeadMode::Unify, - &mut ambiguous, - ) { - Some(expansion) => { + match try_expand_head_traced(ctx, env, expanded, ExpandHeadMode::Unify) { + Ok(Some(expansion)) => { let expansion = ctx.repr(expansion); Some(if expand_first { unify(ctx, state, expansion, t2) @@ -645,7 +638,8 @@ fn unify_newtypes( unify(ctx, state, t1, expansion) }) } - None => ambiguous.map(|ambiguous| Err(ambiguous_instance(ctx, ambiguous))), + Ok(None) => None, + Err(ambiguous) => Some(Err(ambiguous_instance(ctx, ambiguous))), } } @@ -4745,21 +4739,11 @@ enum ExpandHeadMode { Optimize, } -/// OCaml `expand_abbrev_gen` (compiler/ml/ctype.ml:1190-1229) of one head. -/// While GADT instances are traced, an expansion of `ty` known only at an -/// instance level above `ty`'s level is OCaml's `Unify [(ty, newvar2 -/// level)]` (ctype.ml:1225): it returns `None` with `ty` in `ambiguous`, -/// having changed nothing. A caller that expands safely -/// (`try_expand_safe`, ctype.ml:1260-1265) takes that as a type that cannot -/// be expanded. Only the `TRACED` instantiation, called in an environment -/// with an instance scope, makes the test; without one the test cannot -/// fail, and the other instantiation is trunk's expansion. -fn try_expand_head_with_mode( +fn try_expand_head_with_mode( ctx: &TypeContext, env: &Env, ty: TypeExprRef, mode: ExpandHeadMode, - ambiguous: &mut Option, ) -> Option { let ty = ctx.repr(ty); let desc = ctx.borrow_desc(ty); @@ -4802,14 +4786,8 @@ fn try_expand_head_with_mode( return Some(ctx.repr(cached)); } - // `expansion_level` is the declaration's expansion level - // (`Env.find_type_expansion`'s `lv`, env.ml:902), set for a GADT - // equation. - let mut expand_with_subst = |params: &[TypeExprRef], - manifest: TypeExprRef, - expansion_level: Option| - -> Option { - let subst = || { + let expand_with_subst = + |params: &[TypeExprRef], manifest: TypeExprRef| -> TypeExprRef { subst_with_memo( ctx, env, @@ -4823,11 +4801,6 @@ fn try_expand_head_with_mode( ctx.type_list(args), ) }; - if TRACED && ctx.trace_gadt_instances() { - return subst_gadt_instance(ctx, env, ty, expansion_level, ambiguous, subst); - } - Some(subst()) - }; let can_expand_decl_manifest = |decl: &super::decl::TypeDeclaration, manifest: TypeExprRef| { @@ -4847,9 +4820,8 @@ fn try_expand_head_with_mode( if let Some(manifest) = constraint_decl.type_manifest { let params = &constraint_decl.type_params; if params.len() == args.len() { - let expansion_level = - constraint_decl.type_newtype_level.map(|(_, level)| level); - return expand_with_subst(params, manifest, expansion_level); + let expanded = expand_with_subst(params, manifest); + return Some(expanded); } } } @@ -4895,10 +4867,8 @@ fn try_expand_head_with_mode( } }; return match expansion { - // A declaration reached through a module has no newtype - // level, hence no expansion level. PdotExpansion::Expand { params, manifest } => { - expand_with_subst(¶ms, manifest, None) + Some(expand_with_subst(¶ms, manifest)) } PdotExpansion::Rewrite(target) => { let level = ctx.get_level(ty); @@ -4989,9 +4959,8 @@ fn try_expand_head_with_mode( if can_expand_decl_manifest(env_decl, manifest) { let params = &env_decl.type_params; if params.len() == args.len() { - let expansion_level = - env_decl.type_newtype_level.map(|(_, level)| level); - return expand_with_subst(params, manifest, expansion_level); + let expanded = expand_with_subst(params, manifest); + return Some(expanded); } else { forbid_fallback_manifest_expansion = true; } @@ -5083,8 +5052,8 @@ fn try_expand_head_with_mode( if can_expand_decl_manifest(&decl, manifest) { let params = &decl.type_params; if params.len() == args.len() { - let expansion_level = decl.type_newtype_level.map(|(_, level)| level); - return expand_with_subst(params, manifest, expansion_level); + let expanded = expand_with_subst(params, manifest); + return Some(expanded); } else { forbid_fallback_manifest_expansion = true; } @@ -5126,39 +5095,78 @@ fn try_expand_head_with_mode( } } -/// The traced end of `expand_abbrev_gen` (compiler/ml/ctype.ml:1215-1227): -/// the highest of the declaration's expansion level and the level of an -/// instance set holding `ty`; below it, `ty` is ambiguous and is not -/// expanded; otherwise `ty` and its expansion join that set. The test is -/// made before `subst`, which leaves `ty` as it is. Cost: one -/// [`gadt_instance_level`] and the substitution. -fn subst_gadt_instance( +/// OCaml `expand_abbrev_gen` (compiler/ml/ctype.ml:1190-1229) of one head +/// with its GADT instance test (ctype.ml:1215-1227), around trunk's +/// expansion. While instances are traced and the expansion is not a +/// memorized one (OCaml tests only when it substitutes), the level of the +/// equation (`Env.find_type_expansion`'s `lv`) or of an instance set +/// holding `ty`, whichever is higher, is compared with `ty`'s: below it, +/// `ty` is ambiguous (`Err(ty)`, OCaml's `Unify [(ty, newvar2 level)]`); +/// otherwise `ty` and its expansion join that set. For an equation the +/// test is made before the expansion, which leaves `ty` as it is. For a +/// type that is an instance through another route it is made after, and a +/// refused expansion is forgotten from `ty`'s memo, as OCaml's +/// `try_expand_safe` backtracks it. Cost: one scan of `ty`'s memo, one +/// local-constraint lookup and one [`gadt_instance_level`] beside trunk's +/// expansion. +fn try_expand_head_traced( ctx: &TypeContext, env: &Env, ty: TypeExprRef, - expansion_level: Option, - ambiguous: &mut Option, - subst: impl FnOnce() -> TypeExprRef, -) -> Option { - let instance_level = expansion_level.max(gadt_instance_level(ctx, env, ty)); - if let Some(instance_level) = instance_level - && ctx.get_level(ty) < instance_level - { - *ambiguous = Some(ty); - return None; + mode: ExpandHeadMode, +) -> Result, TypeExprRef> { + if !ctx.trace_gadt_instances() { + return Ok(try_expand_head_with_mode(ctx, env, ty, mode)); } - let expanded = subst(); - if let Some(instance_level) = instance_level { + let ty = ctx.repr(ty); + let (path, arity, abbrev) = match &*ctx.borrow_desc(ty) { + TypeDesc::Tconstr { path, args, abbrev } => (*path, args.len(), *abbrev), + _ => return Ok(try_expand_head_with_mode(ctx, env, ty, mode)), + }; + // While tracing, `proper_abbrevs` gives the constructor's own memo. + let private_flag = match mode { + ExpandHeadMode::Optimize => PrivateFlag::Private, + ExpandHeadMode::General | ExpandHeadMode::Unify => PrivateFlag::Public, + }; + if ctx.has_memorized_expansion(abbrev, private_flag, &path) { + return Ok(try_expand_head_with_mode(ctx, env, ty, mode)); + } + let level = ctx.get_level(ty); + let set_level = gadt_instance_level(ctx, env, ty); + // The expansion's first route after the memo: an equation of the same + // arity, whose expansion level is its newtype level's second part. + let equation = env + .find_local_constraint(&path) + .filter(|decl| decl.type_manifest.is_some() && decl.type_params.len() == arity) + .map(|decl| decl.type_newtype_level.map(|(_, level)| level)); + let instance_level = match equation { + Some(expansion_level) => { + let instance_level = expansion_level.max(set_level); + if instance_level.is_some_and(|instance_level| level < instance_level) { + return Err(ty); + } + instance_level + } + None => set_level, + }; + let expanded = try_expand_head_with_mode(ctx, env, ty, mode); + if let (Some(instance_level), Some(expanded)) = (instance_level, expanded) { + if equation.is_none() && level < instance_level { + if abbrev != AbbrevMemoRef::nil() { + ctx.forget_abbrev(abbrev, &path); + } + return Err(ty); + } ctx.add_gadt_instances(env.gadt_instance_scope(), instance_level, &[ty, expanded]); } - Some(expanded) + Ok(expanded) } fn try_expand_head(ctx: &TypeContext, env: &Env, ty: TypeExprRef) -> Option { if expands_gadt_instances(ctx, env) { - try_expand_head_with_mode::(ctx, env, ty, ExpandHeadMode::General, &mut None) + try_expand_head_traced(ctx, env, ty, ExpandHeadMode::General).unwrap_or(None) } else { - try_expand_head_with_mode::(ctx, env, ty, ExpandHeadMode::General, &mut None) + try_expand_head_with_mode(ctx, env, ty, ExpandHeadMode::General) } } @@ -5178,7 +5186,7 @@ pub(crate) fn expand_abbrev_opt_once( // OCaml compiler/ml/ctype.ml:4165 calls `expand_abbrev_opt` from // `cyclic_abbrev`; ctype.ml:1464-1478 defines that as the Private // expansion path through `Env.find_type_expansion_opt`. - try_expand_head_with_mode::(ctx, env, ty, ExpandHeadMode::Optimize, &mut None) + try_expand_head_with_mode(ctx, env, ty, ExpandHeadMode::Optimize) .map(|expanded| ctx.repr(expanded)) } @@ -6402,13 +6410,7 @@ fn subtype_rec( Ok(()) } (TypeDesc::Tconstr { path: p1, .. }, _) if generic_private_abbrev(ctx, env, p1) => { - match try_expand_head_with_mode::( - ctx, - env, - t1, - ExpandHeadMode::Optimize, - &mut None, - ) { + match try_expand_head_with_mode(ctx, env, t1, ExpandHeadMode::Optimize) { Some(expanded) => subtype_rec(ctx, env, subtypes, trace, expanded, t2, cstrs), None => { push_subtype_cstr(cstrs, trace, t1, t2, None); @@ -7381,7 +7383,7 @@ fn expand_head_plain( } seen[seen_len] = current; let seen_len = seen_len + 1; - match try_expand_head_with_mode::(ctx, env, current, mode, &mut None) { + match try_expand_head_with_mode(ctx, env, current, mode) { Some(expanded) => { let expanded = ctx.repr(expanded); if expanded == current { @@ -7437,7 +7439,6 @@ fn expand_head_traced( ) -> Result { let start = ctx.repr(ty); let mut current = start; - let mut ambiguous = None; let mut seen = [TypeExprRef(0); 20]; for seen_len in 0..seen.len() { if seen[..seen_len].contains(¤t) { @@ -7445,8 +7446,8 @@ fn expand_head_traced( } seen[seen_len] = current; let seen_len = seen_len + 1; - match try_expand_head_with_mode::(ctx, env, current, mode, &mut ambiguous) { - Some(expanded) => { + match try_expand_head_traced(ctx, env, current, mode) { + Ok(Some(expanded)) => { let expanded = ctx.repr(expanded); if expanded == current { break; @@ -7456,8 +7457,9 @@ fn expand_head_traced( } current = expanded; } - None => { - if PROPAGATE && let Some(ambiguous) = ambiguous { + Ok(None) => break, + Err(ambiguous) => { + if PROPAGATE { return Err(ambiguous); } break; From fe245f217e5ae48ec07f4ca677a299a6f101c4be Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:33:46 +0000 Subject: [PATCH 15/30] Make trunk's expansion calls at the unifier's sites while no instance can be expanded `expand_head_for_unify` returned a `Result` from both arms and tested the guard once per side. The pair sites now test it once (`expand_heads_unif`) and, while it is false, make trunk's two expansions directly; the traced pair, which refuses an ambiguous instance, is a separate function. The fully expanded comparison's site (`expand_head_in_unify`) does the same for one side. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/types/ctype.rs | 73 ++++++++++++++++++++------------ 1 file changed, 47 insertions(+), 26 deletions(-) diff --git a/compiler-rust/src/types/ctype.rs b/compiler-rust/src/types/ctype.rs index 54dbd24429..636e5b190d 100644 --- a/compiler-rust/src/types/ctype.rs +++ b/compiler-rust/src/types/ctype.rs @@ -7400,21 +7400,53 @@ fn expand_head_plain( current } -/// OCaml `expand_head_unif` (compiler/ml/ctype.ml:1279) at the expansions -/// of unification (`unify2`, ctype.ml:2289-2292): in an environment with an -/// instance scope, an expansion that would let a GADT instance out of its -/// equation's scope is `Err` with the instance; elsewhere trunk's -/// expansion. -fn expand_head_for_unify( +/// OCaml `expand_head_unif` (compiler/ml/ctype.ml:2289-2292) of both sides +/// of a unification: trunk's expansions while no instance can be expanded +/// (one load and one branch for the pair), otherwise the traced ones, which +/// refuse an ambiguous GADT instance. +fn expand_heads_unif( + ctx: &TypeContext, + env: &Env, + t1: TypeExprRef, + t2: TypeExprRef, +) -> Result<(TypeExprRef, TypeExprRef), TypeError> { + if expands_gadt_instances(ctx, env) { + expand_heads_traced(ctx, env, t1, t2) + } else { + Ok(( + expand_head_plain(ctx, env, t1, ExpandHeadMode::Unify), + expand_head_plain(ctx, env, t2, ExpandHeadMode::Unify), + )) + } +} + +/// The traced expansions of [`expand_heads_unif`]. +fn expand_heads_traced( + ctx: &TypeContext, + env: &Env, + t1: TypeExprRef, + t2: TypeExprRef, +) -> Result<(TypeExprRef, TypeExprRef), TypeError> { + let traced = |ty| { + expand_head_traced::(ctx, env, ty, ExpandHeadMode::Unify) + .map_err(|ty| ambiguous_instance(ctx, ty)) + }; + Ok((traced(t1)?, traced(t2)?)) +} + +/// OCaml `expand_head` in `unify`'s fully expanded comparison: trunk's +/// expansion while no instance can be expanded (one load and one branch), +/// otherwise the traced one, which refuses an ambiguous GADT instance. +fn expand_head_in_unify( ctx: &TypeContext, env: &Env, ty: TypeExprRef, - mode: ExpandHeadMode, -) -> Result { +) -> Result { if expands_gadt_instances(ctx, env) { - expand_head_traced::(ctx, env, ty, mode) + expand_head_traced::(ctx, env, ty, ExpandHeadMode::General) + .map_err(|ty| ambiguous_instance(ctx, ty)) } else { - Ok(expand_head_plain(ctx, env, ty, mode)) + Ok(expand_head_plain(ctx, env, ty, ExpandHeadMode::General)) } } @@ -8927,10 +8959,7 @@ fn unify_types( if !facts.is_some_and(|facts| facts.var_free) { if ty_is_constr && state.env().is_some() && deep_occur(ctx, var, ty) { let env = state.env().expect("checked above"); - let exp1 = expand_head_for_unify(ctx, env, t1, ExpandHeadMode::Unify) - .map_err(|ty| ambiguous_instance(ctx, ty))?; - let exp2 = expand_head_for_unify(ctx, env, t2, ExpandHeadMode::Unify) - .map_err(|ty| ambiguous_instance(ctx, ty))?; + let (exp1, exp2) = expand_heads_unif(ctx, env, t1, t2)?; return unify_after_expansion(ctx, state, t1, exp1, t2, exp2); } if occur_check(ctx, state.env(), state.mode, var, ty).is_err() { @@ -9063,10 +9092,7 @@ fn unify_types( // OCaml compiler/ml/ctype.ml:2338-2344 (`unify2`) expands // both constructor heads before the constructor-path cases // at ctype.ml:2412-2414 are considered. - let exp1 = expand_head_for_unify(ctx, env, t1, ExpandHeadMode::Unify) - .map_err(|ty| ambiguous_instance(ctx, ty))?; - let exp2 = expand_head_for_unify(ctx, env, t2, ExpandHeadMode::Unify) - .map_err(|ty| ambiguous_instance(ctx, ty))?; + let (exp1, exp2) = expand_heads_unif(ctx, env, t1, t2)?; if exp1 != t1 || exp2 != t2 { return unify_after_expansion(ctx, state, t1, exp1, t2, exp2); } @@ -9180,10 +9206,7 @@ fn unify_types( // persistent aliases such as `Stdlib.Lazy.t` do not repeatedly // allocate normalized-but-still-abstract heads before argument // unification. - let exp1 = expand_head_for_unify(ctx, env, t1, ExpandHeadMode::Unify) - .map_err(|ty| ambiguous_instance(ctx, ty))?; - let exp2 = expand_head_for_unify(ctx, env, t2, ExpandHeadMode::Unify) - .map_err(|ty| ambiguous_instance(ctx, ty))?; + let (exp1, exp2) = expand_heads_unif(ctx, env, t1, t2)?; if exp1 != t1 || exp2 != t2 { return unify_after_expansion(ctx, state, t1, exp1, t2, exp2); } @@ -9450,14 +9473,12 @@ fn unify_types( // An ambiguous GADT instance fails as in OCaml's // `expand_head_unif` (ctype.ml:2291-2292). let exp1 = if is_constr1 { - expand_head_for_unify(ctx, env, t1, ExpandHeadMode::General) - .map_err(|ty| ambiguous_instance(ctx, ty))? + expand_head_in_unify(ctx, env, t1)? } else { t1 }; let exp2 = if is_constr2 { - expand_head_for_unify(ctx, env, t2, ExpandHeadMode::General) - .map_err(|ty| ambiguous_instance(ctx, ty))? + expand_head_in_unify(ctx, env, t2)? } else { t2 }; From d1faed4e5c27f707bf42e49cc4ce8356f46e7355 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:55:20 +0000 Subject: [PATCH 16/30] Record A1's guard, its two programs and the cost split of fe245f217 Corrects why 434 units add an instance scope: type_cases adds one for every switch whose exhaustiveness is checked. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/docs/CHECKER_DEPARTURES.md | 97 +++++++++++++++--------- 1 file changed, 61 insertions(+), 36 deletions(-) diff --git a/compiler-rust/docs/CHECKER_DEPARTURES.md b/compiler-rust/docs/CHECKER_DEPARTURES.md index 7401e6219f..69d236437f 100644 --- a/compiler-rust/docs/CHECKER_DEPARTURES.md +++ b/compiler-rust/docs/CHECKER_DEPARTURES.md @@ -8720,12 +8720,12 @@ reads one. level as its expansion level (`env.ml:1805-1810`; `add_gadt_equation`, `ctype.rs:1839`); `check_trace_gadt_instances` forgets the memorized expansions (`ctype.ml:182`); the expansion test is - `subst_gadt_instance` (`ctype.rs:5129`), reached from - `try_expand_head_with_mode` (`ctype.rs:4749`) only while tracing and - made before the substitution, which it does not affect; the traced - head expansion (`expand_head_traced`) adds the chain; the unifier's - expansions (`unify2`, `ctype.ml:2289-2292`) propagate the refusal - (`expand_head_for_unify`); + `try_expand_head_traced`, which wraps trunk's `try_expand_head_with_mode` + (since `cbaf8d70d`) and, while tracing, tests an equation before the + expansion, which it does not affect; the traced head expansion + (`expand_head_traced`) adds the chain; the unifier's expansions + (`unify2`, `ctype.ml:2289-2292`) propagate the refusal + (`expand_heads_unif`, `expand_head_in_unify`); `update_level_pass` (`ctype.rs:2999`) makes the level test. Without OCaml's arm of `unify` for two nullary locally abstract types (`ctype.ml:2255-2268`: expand only the later one, lower nothing first), p11 became refused. A trace @@ -8733,9 +8733,8 @@ reads one. (level 2008) and `a` to the outer level 1005 before expanding, and the expansion of the copy of `b` then refused (1005 below the instance level 1008); OCaml's arm expands that copy at its own level. - `unify_newtypes` (`ctype.rs:610`) is that arm. The level test costs one load (`has_gadt_instance_scopes`) and one - branch per level update in a unit without an instance scope; the plain - level update is skipped only in an environment with one. + `unify_newtypes` (`ctype.rs:610`) is that arm. The level test costs one load (`has_gadt_instances`) and one + branch per level update in a unit where no type has joined a set. - `22a53a612`. OCaml's `copy ?env` (`ctype.ml:770-774`), reached through `instance env` and `instance_list env` (`ctype.ml:877-894`), adds the copy of an instance to its set under local constraints. A function @@ -8782,39 +8781,65 @@ the outer environment after its cases. Five programs aimed at that moment bound in a `let` used after the `switch`, with and without a result annotation) are accepted by OCaml and by Rust. -Cost: open. The guard of every test outside unification is that the -environment at hand has an instance scope: the type context's flag (one -load, false in a unit with no instance scope) and then the environment's -handle (`has_gadt_instance_scope`). 434 of the 788 units of `tests/tests` -add an instance scope, 2,169 in all: OCaml's `contains_gadt` -(`typecore.ml:2372`) looks a pattern's constructors up by name with -`lookup_all_constructors`, and Rust ports that rule. +Two programs aimed at the guard (see "Cost" below) agree. In the first, +the unit's first `switch` (on an `option`) has no generalized +constructor and its second, `switch x { | Int => if true { y } else { 0 } }` +with `x: t` and `y: a`, refuses the instance: OCaml and Rust both +print "This instance of int is ambiguous" at `9:33`. In the second, a +first function adds the instance (`[y, 0]` under `Int`) and two later +functions with no generalized constructor lower types through a `switch` +(`Some(n) => [n, f(Int, n)]`, and a `ref([])` assigned in a case): both +compilers accept it with the same JavaScript. + +Cost: open. Every read of an instance set answers nothing while every set +is empty, and a set gets its first member only from the test of +`expand_abbrev_gen` (`ctype.ml:1217-1227`) while tracing. So the type +context's flag is "a type has been added to an instance set in this +unit" (`has_gadt_instances`, set in `push_gadt_instance`, since +`82e309f01`), kept in one byte with the tracing flag. Copies and level +updates test it, then the environment's scope handle; the expansion sites +test the byte (`expands_gadt_instances`: tracing or a member), so the +test that adds the first member still runs. Scopes are created as before: +434 of the 788 units of `tests/tests` add one, 2,169 in all, because +OCaml's `type_cases` adds an instance level for a `switch` without a +generalized constructor whenever the exhaustiveness check will run +(`typecore.ml:4814-4818`, `4913-4914`; Rust `typecore.rs` at the +`needs_exhaust_check` test). 7 of the 788 units add an instance. The CI `Instruction count` check on a clean `tests/tests` build: +12,960,104 (+0.313%) for `7d08707fd`, +11,397,960 (+0.276%) for -`c0daf094f`, +7,466,613 (+0.181%) for `4679c1d94` (base 4,134,982,569, -head 4,142,449,182). The last, split: +`c0daf094f`, +7,466,613 (+0.181%) for `4679c1d94`, +5,138,728 +(+0.124%) for `fe245f217` (base 4,134,734,897, head 4,139,873,625). The +last, split into the guard sites (one load and one branch each), (a) the +rest of what a unit pays that adds no instance, and (b) the work while +tracing or after a member: | | function | change | | --- | --- | ---: | -| a | `try_expand_head_with_mode::` (+20,876,059) and its closure (+268,694) against trunk's `try_expand_head_with_mode` (-29,369,475) and closure (-109,870), with `find_abbrev_expansion` +8,176,501, `find_pdot_expansion` +1,412,464, `register_pdot_expansion` +382,131, `pdot_expansion` +222,207 no longer inlined | +1,858,711 | -| a | `expand_head_plain` against `expand_head_with_mode` | -571,304 | -| a | `expand_head_for_unify` (the guard at the unifier's expansions) | +852,103 | -| a | the guard of `instance_in` at its sites: `type_application_parts` +601,508, `type_identifier` +168,826, `type_function_nary` +135,577, `instance_in` +91,230 | +997,141 | -| a | `moregen` | +219,454 | -| b | `gadt_instance_level` +471,915, `repr_chain` +391,308 (the lookups) | +863,223 | -| b | `try_expand_head_with_mode::` | +423,762 | -| b | `instance_with_gadt_instances` +342,857 against `instance` -313,577 | +29,280 | -| b | the general level update in place of the plain one: `update_level_checked_above` +283,546, `update_level_pass` +238,663, `update_level_children` +104,313, `TypeMutationSnapshot::drop` +104,168, `restore_type_state` +97,172, `lower_plain_levels::lower` -160,692 | +667,170 | -| b | `Env::data_mut` +190,067, `Env::add_gadt_instance_level` +91,766 (a scope per `switch` with a generalized constructor) | +281,833 | -| b | `unify` (the newtype arm and `cleanup_abbrev` under local constraints) | +257,776 | - -(a) is about +3.36M (+0.081%), above the +0.03% limit; (b) about +2.52M. -`IdTbl::find_by_ident` (+525,453), the path iterator and the allocator -make up the rest and move by as much between runs. The largest part of -(a) is the second instantiation of the head expansion: each calls -`find_abbrev_expansion` and `find_pdot_expansion`, which are no longer -inlined into trunk's instantiation. +| site | the unifier's pairs (`expand_heads_unif`) | +497,792 | +| site | `instance_in` / `instance_list_in` at typecore's sites: `type_application_parts` +398,277, `type_identifier` +130,678, `type_function_nary` +96,633, `instance_in` +65,613, `instance_list_in` +44,386 | +735,587 | +| site | `update_level_checked_above` | +140,409 | +| site | `expand_head_with_mode`'s guard, inlined into `moregen` at its two `expand_head` calls | +129,160 | +| site | `try_expand_head` | +56,221 | +| a | `unify`: the newtype arm (`unify_newtypes`, `is_newtype`, `find_newtype_level`) is inlined into it since `82e309f01`, its frame grows from 0x1e8 to 0x238 bytes and every call spills more | +1,130,695 | +| a | `expand_head_plain` +12,100,981 against `expand_head_with_mode` -12,250,409 | -149,428 | +| a | scope creation: `Env::data_mut` +190,067, `Env::add_gadt_instance_level` +89,597, `make_mut` +76,159 and +46,401 | +402,224 | +| a | `restore_type_state` (the journal's new entry) | +97,242 | +| a | `unify_types` -166,879, `lower_plain_levels::lower` -54,768 | -221,647 | +| b | `gadt_instance_level` +679,023, `repr_chain` +642,364 | +1,321,387 | +| b | `try_expand_head_traced` +242,590, `expand_head_traced::` +108,040, `::` +64,273, `Env::find_local_constraint` +46,958 | +461,861 | +| b | `update_level_pass` +89,441, `instance_with_gadt_instances` +45,419 | +134,860 | + +The sites come to +1,559,169, (a) to +1,259,086 (+0.0305%, 18,666 above ++0.03%) and (b) to +1,918,108. The remaining +402,365 is +`IdTbl::find_by_ident` (-501,294) and the allocator, which move by as +much between runs. + +Measured locally (fat LTO, one codegen unit, five runs a side; trunk +459b87ca5 as base): `bcc2a4ef4` +4,401,645, the flag `82e309f01` ++6,529,629 (not lower, kept because the flag defines (a)), one +instantiation of the expansion `cbaf8d70d` +5,694,179, trunk's calls at +the unifier's sites `fe245f217` +5,213,073. ## Fourth round: modules, aliases and usage marks From 89b7ae1e8aec5f63c676095834fc68d3ac97beaa Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:58:02 +0000 Subject: [PATCH 17/30] Keep the newtype arm out of unify's body Inlined, it grew unify's frame from 0x1e8 to 0x238 bytes, so every call spilled more registers. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/types/ctype.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/compiler-rust/src/types/ctype.rs b/compiler-rust/src/types/ctype.rs index 636e5b190d..0590a4dd8a 100644 --- a/compiler-rust/src/types/ctype.rs +++ b/compiler-rust/src/types/ctype.rs @@ -607,6 +607,7 @@ fn is_newtype(ctx: &TypeContext, env: &Env, path: &Path) -> bool { /// before. `None` when the arm does not apply or the type cannot be /// expanded, and unification goes on as `unify2`. One call is four /// declaration lookups and one expansion; only under local constraints. +#[inline(never)] fn unify_newtypes( ctx: &TypeContext, state: &mut UnifyState, From 43e204bef1dd95ab341412f79e37da094518d70a Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:58:31 +0000 Subject: [PATCH 18/30] State the cost of the GADT instance lookup against OCaml's Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/types/context.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/compiler-rust/src/types/context.rs b/compiler-rust/src/types/context.rs index 210969f87f..bb21942c1a 100644 --- a/compiler-rust/src/types/context.rs +++ b/compiler-rust/src/types/context.rs @@ -5769,7 +5769,12 @@ impl TypeContext { /// the level of the innermost scope from `scope` outwards whose set holds /// `ty`, a representative. A member is compared by its representative, /// as OCaml replaces the members of a set by theirs before testing. - /// Cost: one step per scope and per member of the scopes visited. + /// Cost: one step per scope visited and one [`Self::repr`] per member of + /// those scopes, as added (a type added twice is two members): linear + /// in the members read, since a `repr` compresses the links it follows, + /// so a member's links are walked once. OCaml's costs, per scope, a + /// scan of the set for links (and a rebuild of the set when one is + /// found), then a set lookup logarithmic in its distinct members. pub(crate) fn gadt_instance_level(&self, scope: GadtScopeRef, ty: TypeExprRef) -> Option { let scopes = self.gadt_instance_scopes.borrow(); let mut current = scope; @@ -5897,7 +5902,10 @@ impl TypeContext { } /// Follow a link chain starting at `t` (whose next node is `first_next`) - /// and compress it. + /// and compress it. Cost: one step per link, after which each node it + /// compresses links to the representative directly; + /// [`Self::gadt_instance_level`] reaches it through the `repr` of each + /// member it reads. #[inline(never)] fn repr_chain(&self, t: TypeExprRef, first_next: TypeExprRef) -> TypeExprRef { // Follow chain to the end, collecting nodes for path compression. From 8cd9bdec622f1867cdd39eecce0785cc5bdbc72f Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:06:30 +0000 Subject: [PATCH 19/30] Revert "Keep the newtype arm out of unify's body" (+4,521,654; unify +1,914,955) This reverts commit 89b7ae1e8. Measured locally against trunk 459b87ca5 (fat LTO, one codegen unit, five runs a side), the total fell from +5,213,073 to +4,521,654, but only through functions the commit does not touch (`IdTbl::find_by_ident` -802,026, the path iterator), which move by as much between runs. `unify` itself rose from +1,130,695 to +1,914,955: with `#[inline(never)]` on `unify_newtypes` its frame grows from 0x238 to 0x258 bytes (trunk: 0x1e8), so the attribute adds to what a unit without an instance pays. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/types/ctype.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/compiler-rust/src/types/ctype.rs b/compiler-rust/src/types/ctype.rs index 0590a4dd8a..636e5b190d 100644 --- a/compiler-rust/src/types/ctype.rs +++ b/compiler-rust/src/types/ctype.rs @@ -607,7 +607,6 @@ fn is_newtype(ctx: &TypeContext, env: &Env, path: &Path) -> bool { /// before. `None` when the arm does not apply or the type cannot be /// expanded, and unification goes on as `unify2`. One call is four /// declaration lookups and one expansion; only under local constraints. -#[inline(never)] fn unify_newtypes( ctx: &TypeContext, state: &mut UnifyState, From f3af82e028d1b6677529f0aa75369fe9dcffe06b Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:22:13 +0000 Subject: [PATCH 20/30] Record A1's accepted cost and the reverted inline(never) attempt Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/docs/CHECKER_DEPARTURES.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/compiler-rust/docs/CHECKER_DEPARTURES.md b/compiler-rust/docs/CHECKER_DEPARTURES.md index 69d236437f..089dabe69a 100644 --- a/compiler-rust/docs/CHECKER_DEPARTURES.md +++ b/compiler-rust/docs/CHECKER_DEPARTURES.md @@ -8791,7 +8791,7 @@ functions with no generalized constructor lower types through a `switch` (`Some(n) => [n, f(Int, n)]`, and a `ref([])` assigned in a case): both compilers accept it with the same JavaScript. -Cost: open. Every read of an instance set answers nothing while every set +Cost: accepted at the figures below. Every read of an instance set answers nothing while every set is empty, and a set gets its first member only from the test of `expand_abbrev_gen` (`ctype.ml:1217-1227`) while tracing. So the type context's flag is "a type has been added to an instance set in this @@ -8839,7 +8839,14 @@ Measured locally (fat LTO, one codegen unit, five runs a side; trunk 459b87ca5 as base): `bcc2a4ef4` +4,401,645, the flag `82e309f01` +6,529,629 (not lower, kept because the flag defines (a)), one instantiation of the expansion `cbaf8d70d` +5,694,179, trunk's calls at -the unifier's sites `fe245f217` +5,213,073. +the unifier's sites `fe245f217` +5,213,073. `#[inline(never)]` on +`unify_newtypes` (`89b7ae1e8`) measured +4,521,654 but raised `unify` +from +1,130,695 to +1,914,955 (its frame grows to 0x258 bytes; the drop +was `IdTbl::find_by_ident` and the path iterator), and was reverted +(`8cd9bdec6`). CI on `8cd9bdec6`, whose checker code is `fe245f217`'s: +base 4,135,460,618, head 4,141,213,244, +5,752,626 (+0.139%), every +function of the table above unchanged and `IdTbl::find_by_ident` at ++706,988. ## Fourth round: modules, aliases and usage marks From d5f63f64b832543ec30b798172fe6017ab7eb6a4 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:25:03 +0100 Subject: [PATCH 21/30] Name the copy with GADT instances in the doc of instance_in without a link to a private item The documentation build refused the link from a public function to a private one. The sentence about the guard now says what the guard is: a type has joined an instance set in this unit. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/os-01a1c9fa-0c5d-7912-a93b-3e7f38e53547 Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/types/ctype.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/compiler-rust/src/types/ctype.rs b/compiler-rust/src/types/ctype.rs index 636e5b190d..bc46ad5884 100644 --- a/compiler-rust/src/types/ctype.rs +++ b/compiler-rust/src/types/ctype.rs @@ -12528,8 +12528,9 @@ pub fn instance(ctx: &TypeContext, ty: TypeExprRef) -> TypeExprRef { } /// OCaml `instance env sch` (compiler/ml/ctype.ml:879-887): [`instance`], -/// and in an environment with an instance scope, [`instance_with_gadt_instances`]. -/// The test is one load and one branch in a unit without an instance scope. +/// and, once a type has joined an instance set in this unit and `env` has an +/// instance scope, `instance_with_gadt_instances`. +/// The test is one load and one branch while no type has joined a set. pub fn instance_in(ctx: &TypeContext, env: &Env, ty: TypeExprRef) -> TypeExprRef { if has_gadt_instance_scope(ctx, env) { instance_with_gadt_instances(ctx, env, ty) From ed5a1a84ac1d0d2dd3be06bbf17de5c34b57ed37 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:27:35 +0100 Subject: [PATCH 22/30] Accept the instruction count of the GADT instance port No change to the tree. The port measures about +0.12 to +0.14% on the tests/tests build: one load and one branch at each copy, expansion and level-update site while no type has joined an instance set, a larger frame in unify, and the instance lookups OCaml also makes in the units that add an instance. The split by function is in the pull request and under A1 of CHECKER_DEPARTURES.md. Instruction-count-increase: GADT instance tracking as OCaml has it; guard tests at the ported sites and the instance work in units that add an instance, split by function in the pull request Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/os-01a1c9fa-0c5d-7912-a93b-3e7f38e53547 Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> From de5bef189ad29b3594c365bb3f5343ab21c555f4 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:44:00 +0000 Subject: [PATCH 23/30] Make typecore's copies add to an instance set exactly where OCaml's do OCaml's copy adds to an instance set only when given the environment (`instance env`, `instance_list env`; ctype.ml:877-894); `instance_def` and typetexp's `instance_list` (`Ctype.instance_list Env.empty`, typetexp.ml:61) add nothing. Back to `instance` / `instance_list`, where OCaml passes no environment: the declaration parameters of a type constructor (typetexp.ml:373), the constructor result under local constraints (typecore.ml:4739 `instance_def ty_res`), and the label result and argument of a record field and of a field assignment (typecore.ml:4315, 4319). To `instance_in`, where OCaml passes it: `rue` (typecore.ml:2607 `instance env ty_expected`; `rue_unify`, `finish_expected` and `finish_expected_at` take the environment), `object_field_use_type` (typecore.ml:2553 `instance env ty`), and the expected type of a record (typecore.ml:3044, 3148) and of a coercion's `rue`, through `instance_if_generic_in`. The tuple's copy has no OCaml counterpart (typecore.ml:2940 unifies `ty_expected` itself) and keeps trunk's. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/types/typecore.rs | 138 ++++++++++++++++++---------- 1 file changed, 91 insertions(+), 47 deletions(-) diff --git a/compiler-rust/src/types/typecore.rs b/compiler-rust/src/types/typecore.rs index 3cd474a04c..9726251d68 100644 --- a/compiler-rust/src/types/typecore.rs +++ b/compiler-rust/src/types/typecore.rs @@ -3324,7 +3324,9 @@ fn transl_type_inner( ctx.get_level(manifest) == crate::types::type_expr::GENERIC_LEVEL } }; - let params = crate::types::ctype::instance_list_in(ctx, env, &decl.type_params); + // typetexp.ml:373 `instance_list decl.type_params`, typetexp's + // `Ctype.instance_list Env.empty` (typetexp.ml:61): no instance set. + let params = crate::types::ctype::instance_list(ctx, &decl.type_params); for ((param_ty, arg_ty), arg) in params.iter().zip(arg_refs.iter()).zip(parsed_args.iter()) { @@ -8362,7 +8364,7 @@ fn type_expect_with_recarg_unscoped<'a>( let constant = convert_constant(cst, loc, tctx.arena)?; let ty = type_constant(ctx, env, &constant); match expected_ty { - Expected::Known(expected) => rue_unify(tctx, loc, ty, expected, context)?, + Expected::Known(expected) => rue_unify(tctx, env, loc, ty, expected, context)?, Expected::Infer { level, .. } => { // type_constant instances a nullary predefined constructor at // current_level. No scope or universal variable can escape, and @@ -8394,7 +8396,14 @@ fn type_expect_with_recarg_unscoped<'a>( &expr.pexp_attributes, )?; // OCaml: rue { ... exp_type = ty_arg; ... } - finish_expected(tctx, expr, typed_field.exp_type, &mut expected_ty, context)?; + finish_expected( + tctx, + env, + expr, + typed_field.exp_type, + &mut expected_ty, + context, + )?; return Ok(typed_field); } if let ED::Pexp_apply(inner) = &expr.pexp_desc { @@ -8402,7 +8411,14 @@ fn type_expect_with_recarg_unscoped<'a>( type_application(tctx, env, expr, inner, &mut expected_ty, context)?; // The two rue checks share one expected type, including when an Infer // request must be materialised by the first check or a lowered apply. - finish_expected(tctx, expr, typed_apply.exp_type, &mut expected_ty, context)?; + finish_expected( + tctx, + env, + expr, + typed_apply.exp_type, + &mut expected_ty, + context, + )?; return Ok(typed_apply); } if let ED::Pexp_await(operand) = &expr.pexp_desc { @@ -8441,7 +8457,7 @@ fn type_expect_with_recarg_unscoped<'a>( } let unit_ty = env.type_unit(ctx); // `rue`: `unify env unit (instance ty_expected)` (typecore.ml:3051-3074). - rue_unify(tctx, loc, unit_ty, expected_ty, context)?; + rue_unify(tctx, env, loc, unit_ty, expected_ty, context)?; Ok({ let typed_node = Expression::new(ExpressionDesc::Texp_break, loc, unit_ty, exp_env_ref); @@ -8460,7 +8476,7 @@ fn type_expect_with_recarg_unscoped<'a>( } let unit_ty = env.type_unit(ctx); // `rue`: `unify env unit (instance ty_expected)` (typecore.ml:3051-3074). - rue_unify(tctx, loc, unit_ty, expected_ty, context)?; + rue_unify(tctx, env, loc, unit_ty, expected_ty, context)?; Ok({ let typed_node = Expression::new(ExpressionDesc::Texp_continue, loc, unit_ty, exp_env_ref); @@ -8483,6 +8499,8 @@ fn type_expect_with_recarg_unscoped<'a>( // Create tuple type and unify (instance generic expected_ty to avoid corruption) let tuple_ty = ctx.new_tuple(elem_types.clone()); + // No OCaml counterpart: typecore.ml:2940 unifies `ty_expected` + // itself, so this copy adds to no instance set. let eff_expected = instance_if_generic(ctx, expected_ty); // OCaml typecore.ml:2670: `unify_exp_types ~context:None`. unify_expression_types(tctx, loc, tuple_ty, eff_expected, None)?; @@ -8688,7 +8706,7 @@ fn type_expect_with_recarg_unscoped<'a>( // OCaml typecore.ml:3082-3090: `rue { ... exp_type = instance_def // Predef.type_unit }`, i.e. `unify env unit (instance ty_expected)`. let result_unit_ty = env.type_unit(ctx); - rue_unify(tctx, loc, result_unit_ty, expected_ty, context)?; + rue_unify(tctx, env, loc, result_unit_ty, expected_ty, context)?; Ok({ let typed_node = Expression::new( @@ -8725,7 +8743,7 @@ fn type_expect_with_recarg_unscoped<'a>( // OCaml typecore.ml:3401-3414: `rue` unifies // `instance_def Predef.type_unit` with `instance env ty_expected`. let unit_ty = env.type_unit(ctx); - rue_unify(tctx, loc, unit_ty, expected_ty, context)?; + rue_unify(tctx, env, loc, unit_ty, expected_ty, context)?; unit_ty } }; @@ -8893,7 +8911,7 @@ fn type_expect_with_recarg_unscoped<'a>( } ctx.end_def(); let exp_type = crate::types::instance(ctx, env.type_string(ctx)); - rue_unify(tctx, loc, exp_type, expected_ty, context)?; + rue_unify(tctx, env, loc, exp_type, expected_ty, context)?; Ok({ let typed_node = Expression::new( ExpressionDesc::Texp_template { @@ -8949,7 +8967,7 @@ fn type_expect_with_recarg_unscoped<'a>( } unify_expression_types(tctx, loc, ctx.new_var(None), tag.exp_type, None)?; ctx.end_def(); - rue_unify(tctx, loc, output_ty, expected_ty, context)?; + rue_unify(tctx, env, loc, output_ty, expected_ty, context)?; let raw_sources = template .raw_sources .iter() @@ -9352,7 +9370,7 @@ fn type_identifier( check_inlined_record_escape(ctx, loc, desc.val_type, recarg)?; let ty = crate::types::ctype::instance_in(ctx, env, desc.val_type); - finish_expected_at(tctx, expr, loc, ty, expected_ty, context)?; + finish_expected_at(tctx, env, expr, loc, ty, expected_ty, context)?; Ok({ let typed_node = Expression::new( @@ -9371,19 +9389,20 @@ fn type_identifier( /// representative choice, level updates and error traces in those cases. fn finish_expected( tctx: &mut TypeCheckContext<'_>, + env: &Env, expr: &ParsedExpression, ty: TypeExprRef, expected: &mut Expected, context: Option, ) -> TypeCoreResult<()> { - finish_expected_at(tctx, expr, expr.pexp_loc, ty, expected, context) + finish_expected_at(tctx, env, expr, expr.pexp_loc, ty, expected, context) } /// Finish an expected type at the construct's semantic location. /// Cost: the existing expected-variable check and, when needed, unification; /// no location allocation, traversal or additional type lookup. fn finish_expected_at( - tctx: &mut TypeCheckContext<'_>, expr: &ParsedExpression, loc: LocIdx, + tctx: &mut TypeCheckContext<'_>, env: &Env, expr: &ParsedExpression, loc: LocIdx, ty: TypeExprRef, expected: &mut Expected, context: Option, ) -> TypeCoreResult<()> { if let Expected::Infer { level, .. } = *expected @@ -9392,7 +9411,7 @@ fn finish_expected_at( return Ok(()); } let expected = materialize_expected(tctx, expr, expected); - rue_unify(tctx, loc, ty, expected, context) + rue_unify(tctx, env, loc, ty, expected, context) } fn materialize_expected( @@ -9468,6 +9487,19 @@ fn instance_if_generic(ctx: &TypeContext, ty: TypeExprRef) -> TypeExprRef { } } +/// [`instance_if_generic`] for a site that stands for OCaml's +/// `instance env ty_expected`: OCaml's copy returns a node that is not +/// generic as it is and adds nothing for it (ctype.ml:750), so the copy is +/// made only for a generic type, through [`crate::types::ctype::instance_in`]. +/// Cost: one load and one branch, then `instance_in`'s. +fn instance_if_generic_in(ctx: &TypeContext, env: &Env, ty: TypeExprRef) -> TypeExprRef { + if ctx.get_level(ctx.repr(ty)) == crate::types::type_expr::GENERIC_LEVEL { + crate::types::ctype::instance_in(ctx, env, ty) + } else { + ty + } +} + /// OCaml's `rue` mechanism: always instance the expected type before unifying. /// This matters even for monomorphic expected types, because OCaml still copies /// the top-level node and preserves distinct physical identities in the typed tree. @@ -9484,14 +9516,18 @@ fn proper_exp_loc(ta: &TypedArena, exp: &Expression) -> LocIdx { .unwrap_or(exp.exp_loc) } +/// OCaml `rue` (typecore.ml:2606-2608): `unify_exp` of the expression's +/// type with `instance env ty_expected`, whose copy adds to an instance set +/// under local constraints. fn rue_unify( tctx: &mut TypeCheckContext<'_>, + env: &Env, loc: LocIdx, exp_ty: TypeExprRef, expected_ty: TypeExprRef, context: Option, ) -> TypeCoreResult<()> { - let inst = crate::types::instance(tctx.type_ctx, expected_ty); + let inst = crate::types::ctype::instance_in(tctx.type_ctx, env, expected_ty); unify_expression_types(tctx, loc, exp_ty, inst, context) } @@ -9716,7 +9752,7 @@ fn translate_unified_ops( }; // OCaml: rue { ... exp_type = ty_res; ... } (unified ops are Pexp_apply) - if let Err(e) = finish_expected(tctx, sexp, result_ty, expected_ty, context) { + if let Err(e) = finish_expected(tctx, env, sexp, result_ty, expected_ty, context) { return Some(Err(e)); } @@ -9772,7 +9808,7 @@ fn translate_unified_ops( }; // OCaml: rue { ... exp_type = ty_res; ... } (unified ops are Pexp_apply) - if let Err(e) = finish_expected(tctx, sexp, result_ty, expected_ty, context) { + if let Err(e) = finish_expected(tctx, env, sexp, result_ty, expected_ty, context) { return Some(Err(e)); } @@ -10690,7 +10726,7 @@ fn type_application_parts( unify_expression_types(tctx, loc, ctx.new_var(None), typed_funct.exp_type, None)?; // OCaml: rue { ... exp_type = ty_res; ... } - finish_expected_at(tctx, sexp, loc, result_ty, expected_ty, context)?; + finish_expected_at(tctx, env, sexp, loc, result_ty, expected_ty, context)?; Ok({ let typed_node = Expression::new( @@ -11832,7 +11868,7 @@ fn type_conditional( let typed_then = type_expect(tctx, env, then_branch, ctx.predef_unit(), return_context)?; let then_exp_type = typed_then.exp_type; - rue_unify(tctx, loc, then_exp_type, expected_ty, context)?; + rue_unify(tctx, env, loc, then_exp_type, expected_ty, context)?; Ok({ let typed_node = Expression::new( @@ -13469,7 +13505,7 @@ fn type_function_nary_with_newtypes( is_async, attributes, )?; - rue_unify(tctx, loc, typed.exp_type, expected_ty, None)?; + rue_unify(tctx, env, loc, typed.exp_type, expected_ty, None)?; Ok(typed) } @@ -14118,7 +14154,7 @@ fn type_for( // OCaml typecore.ml:3117-3126: `rue { ... exp_type = instance_def // Predef.type_unit }`, i.e. `unify env unit (instance ty_expected)`. let result_unit_ty = env.type_unit(ctx); - rue_unify(tctx, loc, result_unit_ty, expected_ty, context)?; + rue_unify(tctx, env, loc, result_unit_ty, expected_ty, context)?; Ok({ let typed_node = Expression::new( @@ -14335,7 +14371,7 @@ fn type_for_of( // OCaml `rue { ... exp_type = instance_def Predef.type_unit }`, i.e. // `unify env unit (instance ty_expected)`. let result_unit_ty = env.type_unit(ctx); - rue_unify(tctx, loc, result_unit_ty, expected_ty, context)?; + rue_unify(tctx, env, loc, result_unit_ty, expected_ty, context)?; let pat_box = Box::new(pat.clone()); let desc = if await_kw { @@ -14585,7 +14621,8 @@ fn type_construct( ctx.end_def(); let var_level = ctx.current_level(); crate::types::generalize_structure(ctx, var_level, result_ty); - let result_ty_inst = crate::types::ctype::instance_in(ctx, env, result_ty); + // typecore.ml:4739 `instance_def ty_res`. + let result_ty_inst = crate::types::ctype::instance(ctx, result_ty); let expected_inst = crate::types::ctype::instance_in(ctx, env, expected_ty); unify_expression_types(tctx, loc, result_ty_inst, expected_inst, None)?; ctx.end_def(); @@ -14752,7 +14789,7 @@ fn type_variant( row_name: None, }); // OCaml: rue { ... exp_type = variant_row; ... } - rue_unify(tctx, loc, variant_ty, expected_ty, context)?; + rue_unify(tctx, env, loc, variant_ty, expected_ty, context)?; return Ok({ let typed_node = Expression::new( ExpressionDesc::Texp_variant(label.to_string(), Some(tctx.push_expr(typed_arg))), @@ -14778,7 +14815,7 @@ fn type_variant( row_name: None, }); // OCaml: rue { ... exp_type = variant_row; ... } - rue_unify(tctx, loc, variant_ty, expected_ty, context)?; + rue_unify(tctx, env, loc, variant_ty, expected_ty, context)?; Ok({ let typed_node = Expression::new( @@ -15343,8 +15380,10 @@ fn type_record( // checked against the expected type and, with a spread, its type. let first_lid = fields.first().map(|field| field.lid.txt); check_no_record_syntax_on_dict(tctx, env, loc, expected_ty, first_lid)?; - // Protect a generic expected type from record typing side effects. - let expected_ty = instance_if_generic(ctx, expected_ty); + // Protect a generic expected type from record typing side effects. This + // is the copy of OCaml's `instance env ty_expected` (typecore.ml:3044, + // 3148): the later `instance_in` of the copy, not generic, is the node. + let expected_ty = instance_if_generic_in(ctx, env, expected_ty); // Type check base expression if present. // Match OCaml: type the base with type_exp (no expected type constraint), @@ -15829,7 +15868,7 @@ fn type_record( // Match OCaml typecore.ml:3695-3698: // unify env (instance_def ty_res) (instance env ty_expected) // let ty_arg = instance_def ty_arg - let ty_res = crate::types::ctype::instance_in(ctx, env, ty_res0); + let ty_res = crate::types::ctype::instance(ctx, ty_res0); let expected_record_ty = crate::types::ctype::instance_in(ctx, env, record_ty); if let Err(err) = crate::types::unify( ctx, @@ -15848,7 +15887,7 @@ fn type_record( env: Some(tctx.type_ctx.store_typed_env(env)), }); } - (poly_vars, crate::types::ctype::instance_in(ctx, env, ty_arg0)) + (poly_vars, crate::types::ctype::instance(ctx, ty_arg0)) }; if separate { @@ -16840,7 +16879,8 @@ fn type_setfield( // label result with the expected record type (raising // `Label_mismatch` at the label), then instances the field // argument before typing the assigned value. - let ty_res = crate::types::ctype::instance_in(ctx, env, ty_res0); + // typecore.ml:4315 `instance_def ty_res`, `instance env ty_expected`. + let ty_res = crate::types::ctype::instance(ctx, ty_res0); let expected_record_ty = crate::types::ctype::instance_in(ctx, env, ty_record); let label_result_unify = crate::types::unify(ctx, &mut tctx.unify_state, ty_res, expected_record_ty) @@ -16853,7 +16893,8 @@ fn type_setfield( }, env: Some(tctx.type_ctx.store_typed_env(env)), }); - let field_ty = crate::types::ctype::instance_in(ctx, env, ty_arg0); + // typecore.ml:4319 `instance_def ty_arg`. + let field_ty = crate::types::ctype::instance(ctx, ty_arg0); if separate { // OCaml compiler/ml/typecore.ml:3722-3725 closes the second local @@ -16966,7 +17007,7 @@ fn type_setfield( // OCaml typecore.ml:2961-2969: `rue { ... exp_type = instance_def // Predef.type_unit }`, i.e. `unify_exp env exp (instance env ty_expected)`. - rue_unify(tctx, loc, unit_ty, expected_ty, context)?; + rue_unify(tctx, env, loc, unit_ty, expected_ty, context)?; Ok({ let typed_node = Expression::new( @@ -17029,7 +17070,7 @@ fn type_constraint( let typed_inner = type_expect(tctx, env, inner_expr, ctype_ty, None)?; unify_expression_types(tctx, loc, typed_inner.exp_type, arg_unify_ty, None)?; - rue_unify(tctx, loc, result_ty, expected_ty, context)?; + rue_unify(tctx, env, loc, result_ty, expected_ty, context)?; let mut result = typed_inner; result.exp_type = result_ty; @@ -17136,7 +17177,7 @@ fn type_coerce( // OCaml `rue { exp_type = ty'; ... }` (typecore.ml:3295-3305, 2369-2371) // after the coercion check: `unify_exp` at the coercion's location // (`proper_exp_loc`) of `ty'` with `instance env ty_expected`. - let inst_expected = instance_if_generic(ctx, expected_ty); + let inst_expected = instance_if_generic_in(ctx, env, expected_ty); unify_expression_types(tctx, loc, to_ty, inst_expected, None)?; // Return the inner expression with the coercion as exp_extra @@ -17416,7 +17457,7 @@ fn type_newtype( ); // OCaml: rue { ... exp_type = ety; ... } - rue_unify(tctx, loc, rewritten_ty, expected_ty, None)?; + rue_unify(tctx, env, loc, rewritten_ty, expected_ty, None)?; Ok(Expression { exp_loc: loc, @@ -17442,7 +17483,7 @@ fn type_promise_application( let result = type_application_parts(tctx, env, source, primitive.loc, &[], ApplicationCallee::Promise(primitive), &[(ArgLabel::Nolabel, operand)], false, false, expected, context)?; - finish_expected_at(tctx, source, primitive.loc, result.exp_type, expected, context)?; + finish_expected_at(tctx, env, source, primitive.loc, result.exp_type, expected, context)?; Ok(result) } @@ -17483,14 +17524,16 @@ fn method_name_is_plain_ident(name: &str) -> bool { /// be a variable; constrain it to the ordinary, empty-binder form. fn object_field_use_type( tctx: &mut TypeCheckContext<'_>, + env: &Env, typ: TypeExprRef, ) -> Result { let ctx = tctx.type_ctx; let typ = ctx.repr(typ); let desc = *ctx.get_desc(typ); match desc { + // typecore.ml:2553 `instance env ty`. TypeDesc::Tpoly { body, vars } if vars.is_empty() => { - Ok(crate::types::ctype::instance(ctx, body)) + Ok(crate::types::ctype::instance_in(ctx, env, body)) } TypeDesc::Tpoly { body, vars } => { Ok(crate::types::ctype::instance_poly(ctx, false, false, ctx.type_list(vars), body).1) @@ -17539,7 +17582,7 @@ fn type_object_get( // Lookup constrains an open object row to contain the field, without // requiring or adding write capability. let field_ty = crate::types::ctype::filter_method(ctx, env, &field.txt, typed_obj.exp_type) - .and_then(|typ| object_field_use_type(tctx, typ)); + .and_then(|typ| object_field_use_type(tctx, env, typ)); let field_ty = match field_ty { Ok(ty) => ty, Err(_) => { @@ -17552,7 +17595,7 @@ fn type_object_get( } }; - rue_unify(tctx, loc, field_ty, expected_ty, context)?; + rue_unify(tctx, env, loc, field_ty, expected_ty, context)?; Ok({ let typed_node = Expression::new( @@ -17620,7 +17663,7 @@ fn type_object_set( }; let value = type_object_field_value(tctx, env, svalue, typ)?; let unit_ty = env.type_unit(ctx); - rue_unify(tctx, loc, unit_ty, expected_ty, context)?; + rue_unify(tctx, env, loc, unit_ty, expected_ty, context)?; Ok({ let typed_node = Expression::new( ExpressionDesc::Texp_object_set( @@ -17669,8 +17712,8 @@ fn type_object_field_value( Ok(value) } None => { - let typ = - object_field_use_type(tctx, typ).map_err(|err| TypeCoreError::ExprTypeClash { + let typ = object_field_use_type(tctx, env, typ).map_err(|err| { + TypeCoreError::ExprTypeClash { loc: svalue.pexp_loc, trace: match err { TypeError::Unify(trace) => trace, @@ -17678,7 +17721,8 @@ fn type_object_field_value( }, context: None, env: Some(tctx.type_ctx.store_typed_env(env)), - })?; + } + })?; type_expect(tctx, env, svalue, typ, None) } } @@ -17737,7 +17781,7 @@ fn type_object_literal( }); } let exp_type = ctx.new_type(TypeDesc::Tobject { fields: row }); - rue_unify(tctx, loc, exp_type, expected_ty, context)?; + rue_unify(tctx, env, loc, exp_type, expected_ty, context)?; Ok({ let typed_node = Expression::new( ExpressionDesc::Texp_object_literal(fields), @@ -18962,7 +19006,7 @@ fn type_pack( .env() .cloned(); tctx.unify_state.set_env(&package_env); - let rue_result = rue_unify(tctx, loc, packed_type, expected_ty, context); + let rue_result = rue_unify(tctx, env, loc, packed_type, expected_ty, context); if let Some(saved_env) = saved_unify_env { tctx.unify_state.set_env(&saved_env); } @@ -30749,13 +30793,13 @@ mod tests { ctx.set_current_level(11); let result = ctx.new_var(None); let mut expected = Expected::Infer { level: 10, site: InferenceSite::Expression }; - finish_expected(&mut tctx, &expr, result, &mut expected, None).unwrap(); + finish_expected(&mut tctx, &env, &expr, result, &mut expected, None).unwrap(); let Expected::Known(materialized) = expected else { panic!("variable roots retain ordinary unification"); }; assert_eq!(ctx.repr(result), materialized); assert_eq!(ctx.get_level(materialized), 10); - finish_expected(&mut tctx, &expr, result, &mut expected, None).unwrap(); + finish_expected(&mut tctx, &env, &expr, result, &mut expected, None).unwrap(); assert!(matches!(expected, Expected::Known(ty) if ty == materialized)); assert_eq!(ctx.repr(result), materialized); } From 0684ebd56704e4d31d30b62a8d0c26dfe49d1fa8 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:47:19 +0000 Subject: [PATCH 24/30] Record the copy sites corrected in de5bef189 and the programs aimed at them Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/docs/CHECKER_DEPARTURES.md | 36 ++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/compiler-rust/docs/CHECKER_DEPARTURES.md b/compiler-rust/docs/CHECKER_DEPARTURES.md index 089dabe69a..7239cd8ab4 100644 --- a/compiler-rust/docs/CHECKER_DEPARTURES.md +++ b/compiler-rust/docs/CHECKER_DEPARTURES.md @@ -8743,6 +8743,21 @@ reads one. environment and, only under local constraints with an instance scope, walk the finished copy's table once (`add_copied_gadt_instances`, `ctype.rs:12503`); the typecore sites of OCaml's `instance env` use them. +- `de5bef189` makes the copy sites of `typecore.rs` OCaml's in both + directions. Six had been converted where OCaml copies without an + environment and adds nothing: the declaration parameters of a type + constructor (typetexp's `instance_list`, `Ctype.instance_list Env.empty`, + `typetexp.ml:61`, `373`), the constructor result under local constraints + (`typecore.ml:4739` `instance_def ty_res`), and the label result and + argument of a record field and of a field assignment (`typecore.ml:4315`, + `4319` `instance_def`). They are `instance` / `instance_list` again. + Where OCaml passes the environment and Rust did not: `rue` + (`typecore.ml:2607` `instance env ty_expected`; `rue_unify` and + `finish_expected` now take the environment), `object_field_use_type` + (`typecore.ml:2553` `instance env ty`), and the copies of the expected + type of a record (`typecore.ml:3044`, `3148`) and of a coercion's `rue` + (`instance_if_generic_in`). The tuple's copy (`instance_if_generic`) has + no OCaml counterpart: `typecore.ml:2940` unifies `ty_expected` itself. - `752db1e00` keeps these tests off the default path (see "Cost" below); `b46a3af77` adds nothing where an environment has an equation but no instance scope at its level, a state OCaml asserts against @@ -8791,6 +8806,27 @@ functions with no generalized constructor lower types through a `switch` (`Some(n) => [n, f(Int, n)]`, and a `ref([])` assigned in a case): both compilers accept it with the same JavaScript. +Nineteen programs aimed at these sites agree with OCaml on the head +before `de5bef189` and after it; none is a witness, so none is a fixture. +The sites were corrected because the copy must do what OCaml's does. +(a) For `rue` and the other `instance env` sites, inside a case with +`Int: t`: a function `(z: a) => z + 1` generalized in the case and +passed through a constructor `Box(g)`, a record field `{fn: g}`, a +coercion `(g :> a => int)`, an object field read and written +(`o["fn"]`, `o["v"]`), a tuple `(g, 1)`, `Some(g)` against +`Some((z: int) => z)`, a polymorphic field `{fn: g, n: y}`, a pattern +`let Box(h) = b`, a constructor with two arguments `Box(y, 0)`, nested +constructors `Box(Box(g))`, and the labels `{p: y, q: 0}`, returned and +behind an `if`. (b) For the label sites: a record declared in a local +module inside the case, `module M = { type r = {v: a} }`, built with `0` +or `y`, its mutable field assigned `m.v = 0`, read after the case, behind +an `if` against `1` or `2`, with a second field `w: int` built from `y`, +and with a type parameter beside `v: a`. OCaml and Rust refuse the same +eight with "This instance of int is ambiguous" at the same place (`Some` +behind `if`, the object field read, `Box(y, 0)`, both label programs, and +three of the local records), and accept the other eleven with the same +JavaScript. + Cost: accepted at the figures below. Every read of an instance set answers nothing while every set is empty, and a set gets its first member only from the test of `expand_abbrev_gen` (`ctype.ml:1217-1227`) while tracing. So the type From 702f4bd661b80db4772f8673dec1ab7ac0144e3f Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:48:31 +0000 Subject: [PATCH 25/30] Document A1's costs and scope creation, and test the chain's steps No behaviour change. Cost notes for `expand_head_plain`, `expand_heads_traced`, `ambiguous_instance`, `instance_list_in` and `instance_list_with_gadt_instances`; a step test of `add_gadt_instance_chain` at 1,000 and 10,000 members (its membership scan now ticks the test-only step counter). Under A1: where Rust creates instance scopes, which corrects the reason given for the 434 units; the scope OCaml adds for a `switch` without a generalized constructor and Rust does not, as a difference without a program; duplicates in the member sets; the newtype arm; the journal; and the figures of the two remaining `#[inline(never)]`. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/docs/CHECKER_DEPARTURES.md | 45 +++++++++++++++++++++--- compiler-rust/src/types/context.rs | 27 +++++++++++++- compiler-rust/src/types/ctype.rs | 25 +++++++++---- 3 files changed, 85 insertions(+), 12 deletions(-) diff --git a/compiler-rust/docs/CHECKER_DEPARTURES.md b/compiler-rust/docs/CHECKER_DEPARTURES.md index 7239cd8ab4..3a43ad4549 100644 --- a/compiler-rust/docs/CHECKER_DEPARTURES.md +++ b/compiler-rust/docs/CHECKER_DEPARTURES.md @@ -8770,8 +8770,37 @@ reads one. (31 accepted programs, the JavaScript of each compared by the JavaScript parity suite). +The member sets keep duplicates: a type expanded again after the memo is +cleared is pushed again, where OCaml's set holds it once, so a lookup is +linear in additions, not in distinct members. + +The arm for two locally abstract types (`unify_newtypes`) runs under +local constraints whatever the member flag, as OCaml's does. + +Set additions are journaled (`TypeMutation::GadtInstance`) and undone on +backtrack, as OCaml's `set_typeset` logs them (`btype.ml:80`, `706`, +`749`). + #### Open +A difference without a program: Rust adds no scope where OCaml's +`type_cases` adds one for a `switch` without a generalized constructor +that gets an exhaustiveness check (`typecore.ml:4913-4914`, `if do_init && +not has_gadts then init_env ()`); Rust's `type_match` and +`finish_non_gadt_type_cases` raise the level there but call no +`add_gadt_instance_level`. It cannot be seen: a member is only ever added +at the expansion level of an equation, or at the level of a set that +already holds the type. The patterns of that `switch` have no +generalized constructor and add no equation, so OCaml's inner set stays +empty and its lookups go on to the outer sets, as Rust's do. The +exhaustiveness check types counterexample patterns in that environment, +which can add an equation at that level; there the refusal test still +compares with the equation's expansion level in Rust, only the member is +not recorded, and the check's typing is undone afterwards in both. Three +programs with a generalized type under `_` (a tuple with an `int`, an +`option>` with a guard, `t`) give the same warnings in both +compilers. + No program of the 64 shows a difference at these OCaml sites, which are not ported: the chain of `unify2` after expansion (`ctype.ml:2293-2298`: r01-r04, r12-r16 were written for it and agree), the level test of @@ -8836,11 +8865,14 @@ unit" (`has_gadt_instances`, set in `push_gadt_instance`, since updates test it, then the environment's scope handle; the expansion sites test the byte (`expands_gadt_instances`: tracing or a member), so the test that adds the first member still runs. Scopes are created as before: -434 of the 788 units of `tests/tests` add one, 2,169 in all, because -OCaml's `type_cases` adds an instance level for a `switch` without a -generalized constructor whenever the exhaustiveness check will run -(`typecore.ml:4814-4818`, `4913-4914`; Rust `typecore.rs` at the -`needs_exhaust_check` test). 7 of the 788 units add an instance. +434 of the 788 units of `tests/tests` add one, 2,169 in all. Rust adds a +scope in two places: `type_function_nary`'s `init_env`, for a function +whose parameters contain a generalized constructor (`has_gadts`) and for +one with a parameter that is not a plain variable, such as `()`, whose +patterns get an exhaustiveness check (`do_init && !has_gadts`, +`typecore.ml:4196-4197`); and `type_match`, for a `switch` with a +generalized constructor only (`typecore.ml:4819-4828`). Most of the 434 +are the second kind of function. 7 of the 788 units add an instance. The CI `Instruction count` check on a clean `tests/tests` build: +12,960,104 (+0.313%) for `7d08707fd`, +11,397,960 (+0.276%) for @@ -8871,6 +8903,9 @@ The sites come to +1,559,169, (a) to +1,259,086 (+0.0305%, 18,666 above `IdTbl::find_by_ident` (-501,294) and the allocator, which move by as much between runs. +Two `#[inline(never)]` remain, on `instance_with_gadt_instances` and +`instance_list_with_gadt_instances`, from the copy-path attempt +`ae16a975d`, which measured +9,118,887 against +11,678,261 before it. Measured locally (fat LTO, one codegen unit, five runs a side; trunk 459b87ca5 as base): `bcc2a4ef4` +4,401,645, the flag `82e309f01` +6,529,629 (not lower, kept because the flag defines (a)), one diff --git a/compiler-rust/src/types/context.rs b/compiler-rust/src/types/context.rs index bb21942c1a..ec4382e719 100644 --- a/compiler-rust/src/types/context.rs +++ b/compiler-rust/src/types/context.rs @@ -5859,7 +5859,12 @@ impl TypeContext { // the chain. let member = self.gadt_instance_scopes.borrow()[scope.index()] .members - .contains(&ty); + .iter() + .any(|&member| { + #[cfg(test)] + crate::tc::steps::tick(); + member == ty + }); if member { return; } @@ -6408,6 +6413,26 @@ mod tests { assert_eq!(ctx.gadt_instance_level(GadtScopeRef::NONE, other), None); } + /// A chain of one type against a set of `n` members: one membership + /// step per member, so ten times the members is ten times the steps. + #[test] + fn gadt_instance_chain_is_linear_in_the_members_of_its_set() { + let chain_steps = |n: usize| { + let ctx = TypeContext::new(Arc::new(IdGenerator::new())); + let scope = ctx.new_gadt_instance_scope(5, GadtScopeRef::NONE); + let members: Vec<_> = (0..n).map(|_| ctx.new_var(None)).collect(); + ctx.add_gadt_instances(scope, 5, &members); + let ty = ctx.new_var(None); + let steps = crate::tc::steps::scope(|| ctx.add_gadt_instance_chain(scope, 5, ty)); + assert_eq!(ctx.gadt_instance_level(scope, ty), Some(5)); + steps + }; + let small = chain_steps(1_000); + let large = chain_steps(10_000); + assert!(small > 0); + assert_eq!(large, 10 * small); + } + #[test] fn borrowed_path_keys_find_owned_cache_entries() { let ctx = TypeContext::new(std::sync::Arc::new(IdGenerator::new())); diff --git a/compiler-rust/src/types/ctype.rs b/compiler-rust/src/types/ctype.rs index bc46ad5884..c541e9a333 100644 --- a/compiler-rust/src/types/ctype.rs +++ b/compiler-rust/src/types/ctype.rs @@ -7366,7 +7366,9 @@ fn expand_head_with_mode( } /// Trunk's head expansion: [`expand_head_with_mode`] outside an instance -/// scope. +/// scope. Cost: at most 20 expansions of the head, each one memo scan or +/// one declaration lookup and a substitution, plus a scan of the up to 20 +/// heads already seen. fn expand_head_plain( ctx: &TypeContext, env: &Env, @@ -7420,7 +7422,10 @@ fn expand_heads_unif( } } -/// The traced expansions of [`expand_heads_unif`]. +/// The traced expansions of [`expand_heads_unif`]. Cost: two +/// [`expand_head_traced`], each at most 20 expansions, every one with the +/// instance test of [`try_expand_head_traced`] (one memo scan, one +/// local-constraint lookup and one [`gadt_instance_level`]). fn expand_heads_traced( ctx: &TypeContext, env: &Env, @@ -7451,7 +7456,8 @@ fn expand_head_in_unify( } /// OCaml's `Unify [(ty, newvar2 level)]` for an ambiguous GADT instance -/// `ty` (compiler/ml/ctype.ml:589, 1225). +/// `ty` (compiler/ml/ctype.ml:589, 1225). Cost: one fresh variable and a +/// one-pair trace vector; only on the error path. fn ambiguous_instance(ctx: &TypeContext, ty: TypeExprRef) -> TypeError { let level = ctx.get_level(ty); TypeError::Unify(vec![(ty, new_var_at_level(ctx, level))]) @@ -12540,7 +12546,9 @@ pub fn instance_in(ctx: &TypeContext, env: &Env, ty: TypeExprRef) -> TypeExprRef } /// OCaml `instance_list env schl` (compiler/ml/ctype.ml:891-894): as -/// [`instance_in`], sharing one copy session. +/// [`instance_in`], sharing one copy session. Cost: [`instance_list`]'s +/// after one load and one branch while no type has joined an instance set; +/// otherwise that of `instance_list_with_gadt_instances`. pub fn instance_list_in(ctx: &TypeContext, env: &Env, types: &[TypeExprRef]) -> Vec { if has_gadt_instance_scope(ctx, env) { instance_list_with_gadt_instances(ctx, env, types) @@ -12568,7 +12576,8 @@ fn expands_gadt_instances(ctx: &TypeContext, env: &Env) -> bool { /// [`instance`] in an environment with an instance scope: `copy ?env` /// (compiler/ml/ctype.ml:770-774) adds the copy of each instance to its /// set when `env` has local constraints. Cost: the copy, then per copied -/// node one [`TypeContext::gadt_instance_level`]. +/// node one [`TypeContext::gadt_instance_level`]. Not inlined, so that +/// `instance_in` keeps trunk's inlined `instance`. #[inline(never)] fn instance_with_gadt_instances(ctx: &TypeContext, env: &Env, ty: TypeExprRef) -> TypeExprRef { if ctx.counts_this_call() { @@ -12585,7 +12594,11 @@ fn instance_with_gadt_instances(ctx: &TypeContext, env: &Env, ty: TypeExprRef) - } /// [`instance_list`] in an environment with an instance scope, as -/// [`instance_with_gadt_instances`]. +/// [`instance_with_gadt_instances`]. Cost: the copy of every type in one +/// session, then per copied node one [`TypeContext::gadt_instance_level`] +/// under local constraints. Not inlined, so that `instance_list_in` keeps +/// trunk's inlined `instance_list` (measured with the first attempt of the +/// second turn on the pull request). #[inline(never)] fn instance_list_with_gadt_instances( ctx: &TypeContext, From 66dfd833085c82be051b27cc91dc2954559c6bce Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:51:25 +0000 Subject: [PATCH 26/30] Give the second copy of a record's base type trunk's call OCaml has no copy there: typecore.ml:3165 stores the copy of 3153 (`ty_exp = instance env exp.exp_type`) as the base's type, so this Rust-only copy adds to no instance set. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/types/typecore.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/compiler-rust/src/types/typecore.rs b/compiler-rust/src/types/typecore.rs index 9726251d68..5860fa0aed 100644 --- a/compiler-rust/src/types/typecore.rs +++ b/compiler-rust/src/types/typecore.rs @@ -16186,7 +16186,9 @@ fn type_record( // type and the `with` base expression type for persistent constructor // families only. if let Some(base_expr) = typed_base.as_mut() { - let mut output_ty = crate::types::ctype::instance_in(ctx, env, base_expr.exp_type); + // No OCaml counterpart: typecore.ml:3165 stores the copy of 3153 + // (`ty_exp`), so this copy adds to no instance set. + let mut output_ty = crate::types::ctype::instance(ctx, base_expr.exp_type); if ctx.repr(output_ty) == ctx.repr(record_ty) { let repr = ctx.repr(output_ty); let desc = ctx.get_desc(repr); From 5f8d821f90f603b4a2c5e4ff67e6522dbc1cb16d Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:52:58 +0000 Subject: [PATCH 27/30] Copy the expected type of assert(false) as OCaml does typecore.ml:3780 gives `assert(false)` the type `instance env ty_expected`; Rust used the expected type uncopied, which adds nothing to an instance set. A type that is not generic is returned unchanged by the copy, as before. Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/src/types/typecore.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/compiler-rust/src/types/typecore.rs b/compiler-rust/src/types/typecore.rs index 5860fa0aed..13c8ed97e5 100644 --- a/compiler-rust/src/types/typecore.rs +++ b/compiler-rust/src/types/typecore.rs @@ -8738,7 +8738,10 @@ fn type_expect_with_recarg_unscoped<'a>( // assert(false) has the expected type (polymorphic), others have type unit let exp_type = match &typed_e.exp_desc { - ExpressionDesc::Texp_construct(_, cd, _) if cd.cstr_name == "false" => expected_ty, + // typecore.ml:3780 `instance env ty_expected`. + ExpressionDesc::Texp_construct(_, cd, _) if cd.cstr_name == "false" => { + crate::types::ctype::instance_in(ctx, env, expected_ty) + } _ => { // OCaml typecore.ml:3401-3414: `rue` unifies // `instance_def Predef.type_unit` with `instance env ty_expected`. From 848fc888a080909194ce4d4937639aa672438d03 Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:53:31 +0000 Subject: [PATCH 28/30] Record the copy sites of typecore.rs by form under A1 Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/docs/CHECKER_DEPARTURES.md | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/compiler-rust/docs/CHECKER_DEPARTURES.md b/compiler-rust/docs/CHECKER_DEPARTURES.md index 3a43ad4549..420609deb0 100644 --- a/compiler-rust/docs/CHECKER_DEPARTURES.md +++ b/compiler-rust/docs/CHECKER_DEPARTURES.md @@ -8758,6 +8758,19 @@ reads one. type of a record (`typecore.ml:3044`, `3148`) and of a coercion's `rue` (`instance_if_generic_in`). The tuple's copy (`instance_if_generic`) has no OCaml counterpart: `typecore.ml:2940` unifies `ty_expected` itself. + `66dfd8330` gives the second copy of a record's `with` base trunk's + `instance`: OCaml has no copy there (`typecore.ml:3165` stores the copy + of `3153`). `5f8d821f9` copies the expected type of `assert(false)` with + the environment (`typecore.ml:3780`), where Rust used it uncopied. Of the + 83 copy sites of `typecore.rs`, 60 copy with the environment as OCaml's + `instance env` / `instance_list env` (and typetexp's `instance env`), 19 + without it as OCaml's `instance_def` and typetexp's `instance_list`, and + 4 have no OCaml counterpart and keep trunk's call. Three OCaml sites have + no Rust copy: `is_ignore` and the `ignore` case of `type_application` + (`typecore.ml:2498`, `4496`: Rust tests the primitive by name and copies + nothing), and the `let` with locally abstract types + (`typecore.ml:5092`), where Rust types the rewritten expression, whose + `rue` copies the expected type in the same environment. - `752db1e00` keeps these tests off the default path (see "Cost" below); `b46a3af77` adds nothing where an environment has an equation but no instance scope at its level, a state OCaml asserts against @@ -8835,7 +8848,8 @@ functions with no generalized constructor lower types through a `switch` (`Some(n) => [n, f(Int, n)]`, and a `ref([])` assigned in a case): both compilers accept it with the same JavaScript. -Nineteen programs aimed at these sites agree with OCaml on the head +Twenty-one programs aimed at these sites (two of them `assert(false)`, +in a branch and as a field of a generalized record) agree with OCaml on the head before `de5bef189` and after it; none is a witness, so none is a fixture. The sites were corrected because the copy must do what OCaml's does. (a) For `rue` and the other `instance env` sites, inside a case with From 5cfe8a23ff7bd2905da182731787e530d69b292f Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:54:19 +0000 Subject: [PATCH 29/30] Count the assert(false) copy among A1's copy sites Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/docs/CHECKER_DEPARTURES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler-rust/docs/CHECKER_DEPARTURES.md b/compiler-rust/docs/CHECKER_DEPARTURES.md index 420609deb0..a60f99aa43 100644 --- a/compiler-rust/docs/CHECKER_DEPARTURES.md +++ b/compiler-rust/docs/CHECKER_DEPARTURES.md @@ -8762,7 +8762,7 @@ reads one. `instance`: OCaml has no copy there (`typecore.ml:3165` stores the copy of `3153`). `5f8d821f9` copies the expected type of `assert(false)` with the environment (`typecore.ml:3780`), where Rust used it uncopied. Of the - 83 copy sites of `typecore.rs`, 60 copy with the environment as OCaml's + 84 copy sites of `typecore.rs`, 61 copy with the environment as OCaml's `instance env` / `instance_list env` (and typetexp's `instance env`), 19 without it as OCaml's `instance_def` and typetexp's `instance_list`, and 4 have no OCaml counterpart and keep trunk's call. Three OCaml sites have From 4150bc81318476acf355c8a888143fabb4457d2a Mon Sep 17 00:00:00 2001 From: "open-session-submodule[bot]" <341020755+open-session-submodule[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:06:47 +0000 Subject: [PATCH 30/30] Count the accepted programs of A1's copy sites Co-authored-by: Jaap Frolich Session: https://os.submodule.nl/session/bks-bd5a5126-dea8-7249-82a4-e8fae2447c0b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com> --- compiler-rust/docs/CHECKER_DEPARTURES.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler-rust/docs/CHECKER_DEPARTURES.md b/compiler-rust/docs/CHECKER_DEPARTURES.md index a60f99aa43..0317439738 100644 --- a/compiler-rust/docs/CHECKER_DEPARTURES.md +++ b/compiler-rust/docs/CHECKER_DEPARTURES.md @@ -8867,8 +8867,8 @@ an `if` against `1` or `2`, with a second field `w: int` built from `y`, and with a type parameter beside `v: a`. OCaml and Rust refuse the same eight with "This instance of int is ambiguous" at the same place (`Some` behind `if`, the object field read, `Box(y, 0)`, both label programs, and -three of the local records), and accept the other eleven with the same -JavaScript. +three of the local records), and accept the other thirteen with the +same JavaScript. Cost: accepted at the figures below. Every read of an instance set answers nothing while every set is empty, and a set gets its first member only from the test of