From dbd99aef1835f62e1cfdbd4172830713eef83536 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 20 Nov 2026 03:07:39 -0800 Subject: [PATCH 1/8] chore(quest): claim quest/m1/ffi-inference.md Quest-Claim: 5ce147bf699b5228 From 0a58763e36f88fe11f61e64d00d166be4367eb0c Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 20 Nov 2026 05:17:53 -0800 Subject: [PATCH 2/8] fix(ffi): bound instance inference by what the API spells js-sys's census ran for hours: inference offered a type parameter every argument of every instance, at any position, and counted wasm-bindgen's JsValue as an export's type, so each round fed the next. - A parameter held in a generic type takes what it is in that type's instances, at its own position, as const parameters already did. - An instance nests generic types no deeper than the deepest type the API spells, besides holding none of its own type. - Types a round names are normalized before admission, so a field's or bound's associated type names its instance once. - names_export counts only items and types reachable by path. - held_forms runs once per named type. js-sys's census now finishes in about 30 s and leaves KNOWN; moq's instances and census are unchanged. Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/reject/expected.txt | 2 + ffi/fixtures/reject/src/lib.rs | 26 ++++ ffi/src/collect.rs | 235 +++++++++++++++++++++++++------ ffi/src/help.rs | 3 + ffi/tests/fixtures/corpus.rs | 1 - quest/m1/ffi-inference.md | 28 ---- 6 files changed, 224 insertions(+), 71 deletions(-) delete mode 100644 quest/m1/ffi-inference.md diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index 9f799e67d..a74489c77 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -152,6 +152,8 @@ fixtures/reject/src/lib.rs:1597:1: rust2-ffi: cannot export fn `cow_error_later` help: make the future's error `Cow`, which crosses as its message, or an owned value fixtures/reject/src/lib.rs:1602:1: rust2-ffi: cannot export fn `cow_param`: Cow other than a returned string or bytes `std::borrow::Cow<'_, str>` help: take `&str`, `&[u8]`, or an owned value instead, and return `Cow` only as a whole `Cow` or `Cow<[u8]>` +fixtures/reject/src/lib.rs:1623:2: rust2-ffi: cannot export method `Knot>::tie`: instance deeper than any type the API spells `reject::Tie>>` + help: spell the instance in a signature of its own, such as a function returning it, or stop nesting generic types in a method's signature fixtures/reject/src/lib.rs:162:1: rust2-ffi: cannot export fn `measure`: foreign type `tls::held::Local` help: use a type that maps, such as `BTreeMap` for a `HashMap` and `Vec` for an iterator, or wrap it in a type of your own whose methods take and return mapped types fixtures/reject/src/lib.rs:167:1: rust2-ffi: cannot export instance `Cell>`: type argument `std::vec::Vec` diff --git a/ffi/fixtures/reject/src/lib.rs b/ffi/fixtures/reject/src/lib.rs index 3617827d5..d5f795000 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -1602,3 +1602,29 @@ pub async fn cow_error_later(bytes: &[u8]) -> Result) -> usize { text.len() } + +/// Three generic types whose methods each wrap their own in the next: inferring from +/// `Rope` names `Knot>`, as deep as `Rope::knot` spells, whose `tie` names +/// `Tie>>`, deeper than any type the crate spells, which ends inference +/// there though no type holds its own. +pub struct Rope(T); + +pub struct Knot(T); + +pub struct Tie(T); + +impl Rope { + pub fn knot(self) -> Knot> { + Knot(self) + } +} + +impl Knot { + pub fn tie(self) -> Tie> { + Tie(self) + } +} + +pub fn rope(value: u8) -> Rope { + Rope(value) +} diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 435cf05f1..9f69abfa0 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -57,6 +57,9 @@ const FOREIGN: [(&str, &str, &str); 3] = [ /// holds the `Arc`. pub(crate) const BOTH: &str = "another crate's type both by value and in an Arc"; +/// The construct of an instance nesting generic types deeper than any type the API spells. +pub(crate) const DEEPER: &str = "instance deeper than any type the API spells"; + /// The construct of an instance inference missed: a bug in the exporter, not the crate. pub(crate) const NOT_INFERRED: &str = "instance not inferred"; @@ -238,6 +241,13 @@ struct Collector<'tcx> { instances: Vec>, /// Instances that do not export, and why. rejected: rustc_data_structures::fx::FxHashMap, Why>, + /// The items the walk reached, as `items` lists them. + listed: rustc_data_structures::fx::FxHashSet, + /// The generic types instances are inferred of. + generic: rustc_data_structures::fx::FxHashSet, + /// How deeply the deepest type the API spells nests `generic`'s types, which bounds an + /// inferred instance's own nesting. + deepest: usize, /// Whether instances are still being inferred, before any type is declared: each type /// then counts as mapping, so inference takes every choice typing could. inferring: bool, @@ -428,6 +438,9 @@ pub(crate) fn collect<'tcx>(tcx: TyCtxt<'tcx>, facade: &Facade<'_>) -> Collected }, instances: Vec::new(), rejected: Default::default(), + listed: Default::default(), + generic: Default::default(), + deepest: 0, inferring: true, left_out: Default::default(), impls: Default::default(), @@ -829,9 +842,17 @@ impl<'tcx> Collector<'tcx> { /// and the implementations of the traits bounding each parameter, and each instance a /// signature the export maps names, at every choice its bounds allow. An instance adds /// its own fields and methods, so this repeats until it infers no more, which it does: - /// no instance holds one of its own type, so each is no deeper than the generic types. + /// no instance holds one of its own type, nor nests generic types deeper than a type the + /// API spells. fn infer(&mut self) { let tcx = self.tcx; + self.listed = self.items.iter().map(|&(def_id, _)| def_id).collect(); + self.generic = (self.items.iter()) + .map(|&(def_id, _)| def_id) + .filter(|&def_id| { + matches!(tcx.def_kind(def_id), DefKind::Struct | DefKind::Enum | DefKind::Union) && self.typed(def_id) + }) + .collect(); let mut candidates: Vec> = Vec::new(); for (def_id, _) in self.items.clone() { if !matches!(tcx.def_kind(def_id), DefKind::Struct | DefKind::Enum) || !self.typed(def_id) { @@ -876,19 +897,33 @@ impl<'tcx> Collector<'tcx> { .map(|args| Ty::new_adt(tcx, adt, tcx.mk_args(&args))), ); } + let mut spelled = Depth::new(&self.generic); + candidates.visit_with(&mut spelled); + self.spells(&mut spelled); + self.deepest = spelled.max; let mut seen = rustc_data_structures::fx::FxHashSet::default(); + let mut held = rustc_data_structures::fx::FxHashSet::default(); loop { let inferred = self.instances.len(); let named = self.named(); - // Each with the instances inside it, which its export needs. + for &ty in candidates.iter().chain(&named) { + if held.insert(ty) { + self.held_forms(ty); + } + } + // Each with the instances inside it, which its export needs, normalized, as a + // field or a bound may name its instance's argument by an associated type. let types: Vec> = (candidates.iter().chain(&named)) + .map(|&ty| match ty.has_aliases() { + true => tcx + .try_normalize_erasing_regions(TypingEnv::fully_monomorphized(), ty::Unnormalized::new_wip(ty)) + .unwrap_or(ty), + false => ty, + }) .flat_map(|ty| ty.walk()) .filter_map(|arg| arg.as_type()) .filter(|&ty| seen.insert(ty)) .collect(); - for ty in candidates.iter().chain(&named) { - self.held_forms(*ty); - } for ty in types { match self.admit(ty) { Some((key, Ok(site))) if !self.instances.iter().any(|other| other.key == key) => { @@ -1269,9 +1304,75 @@ impl<'tcx> Collector<'tcx> { found } + /// How deeply `ty` nests the generic types instances are inferred of. + fn depth(&self, ty: Ty<'tcx>) -> usize { + let mut depth = Depth::new(&self.generic); + ty.visit_with(&mut depth); + depth.max + } + + /// Visit every type the API spells at its own parameters: each function's, constant's, + /// and trait method's signature with its bounds, and each type's defaults, `pub` fields, + /// and inherent impls with their `pub` methods and constants. + fn spells(&self, visitor: &mut Depth<'_>) { + let tcx = self.tcx; + let mut functions = Vec::new(); + let mut types = Vec::new(); + for &(def_id, _) in &self.items { + match tcx.def_kind(def_id) { + DefKind::Fn => functions.push(def_id), + DefKind::Const => types.push(tcx.type_of(def_id).instantiate_identity().skip_norm_wip()), + DefKind::Trait => { + for item in tcx.associated_items(def_id).in_definition_order() { + if let ty::AssocKind::Fn { .. } = item.kind { + functions.push(item.def_id); + } + } + } + DefKind::Struct | DefKind::Enum | DefKind::Union => { + for param in &tcx.generics_of(def_id).own_params { + if let Some(default) = param.default_value(tcx) { + default.instantiate_identity().skip_norm_wip().visit_with(visitor); + } + } + for field in tcx.adt_def(def_id).all_fields().filter(|field| in_api(tcx, field)) { + types.push(tcx.type_of(field.did).instantiate_identity().skip_norm_wip()); + } + for &imp in tcx.inherent_impls(def_id) { + types.push(tcx.type_of(imp).instantiate_identity().skip_norm_wip()); + for item in tcx.associated_items(imp).in_definition_order() { + if !tcx.visibility(item.def_id).is_public() || tcx.is_doc_hidden(item.def_id) { + continue; + } + match item.kind { + ty::AssocKind::Fn { .. } => functions.push(item.def_id), + ty::AssocKind::Const { .. } => { + types.push(tcx.type_of(item.def_id).instantiate_identity().skip_norm_wip()) + } + _ => {} + } + } + } + } + _ => {} + } + } + types.visit_with(visitor); + for def_id in functions { + tcx.fn_sig(def_id) + .instantiate_identity() + .skip_norm_wip() + .visit_with(visitor); + for clause in tcx.clauses_of(def_id).instantiate_identity(tcx).clauses { + clause.skip_norm_wip().visit_with(visitor); + } + } + } + /// The instance `ty` is, if it is an exported generic type at arguments without type - /// parameters, or why it does not export: an argument holds an instance of a type - /// inside it, which could otherwise name ever deeper instances, or a bound is unmet. + /// parameters, or why it does not export: an argument holds an instance of a type inside + /// it, or it nests generic types deeper than any type the API spells, either of which + /// could otherwise name ever deeper instances, or a bound is unmet. fn admit(&mut self, ty: Ty<'tcx>) -> Option<(Key<'tcx>, Result, Why>)> { let tcx = self.tcx; let ty::Adt(adt, args) = *ty.kind() else { @@ -1304,6 +1405,9 @@ impl<'tcx> Collector<'tcx> { Err(why("instance holding an instance of a type inside it", spelled)), )); } + if self.depth(ty) > self.deepest { + return Some((key, Err(why(DEEPER, spelled)))); + } let (infcx, env) = tcx.infer_ctxt().build_with_typing_env(TypingEnv::fully_monomorphized()); for clause in tcx.clauses_of(def_id).instantiate(tcx, args).clauses { let clause = clause.skip_norm_wip(); @@ -4554,8 +4658,8 @@ impl<'tcx> Collector<'tcx> { /// The types a type parameter exports at each of, where no one type is the rules': /// each type the exports implement a trait bounding it for, or a reference to it where /// that meets the bounds too, which leaves C its handle; and, as an argument of a - /// generic type the signature names, each argument of an instance that meets its - /// bounds where each generic type the signature names is an instance. + /// generic type the signature names, what it is in each instance of that type, where + /// that meets its bounds and each generic type the signature names is an instance. fn each(&self, def_id: DefId, param: Ty<'tcx>, base: &[ty::GenericArg<'tcx>]) -> Vec> { let tcx = self.tcx; let at = |candidate: Ty<'tcx>| self.at(def_id, param, base, candidate); @@ -4588,40 +4692,57 @@ impl<'tcx> Collector<'tcx> { _ => None, }; let spelled = |args| self.spelled(def_id, args); - let argument = spelled(tcx.mk_args(base)) - .into_iter() - .filter_map(exported) - .any(|(_, args)| args.iter().any(|arg| arg.walk().any(|a| a == param.into()))); - for site in self.instances.iter().filter(|_| argument) { - for candidate in site.args.types().filter(|ty| !(iterated && ty.is_ref())) { - let erased = tcx.erase_and_anonymize_regions(candidate); - if found - .iter() - .any(|&f| tcx.erase_and_anonymize_regions(f.peel_refs()) == erased) - { + let ty::Param(p) = param.kind() else { + unreachable!("a generic type argument is a parameter"); + }; + // What `param` is in each instance of a generic type the signature holds it in, as + // `Foo` offers `X` for `Foo`; an instance of another type, or an argument at + // another position, offers nothing, so no choice feeds an unrelated signature. + let mut offered: Vec> = Vec::new(); + for holder in spelled(tcx.mk_args(base)) { + let Some((adt, args)) = exported(holder) else { continue }; + if !args.iter().any(|arg| arg.walk().any(|a| a == param.into())) { + continue; + } + for site in self.instances.iter().filter(|site| site.key.def_id == adt) { + let mut args = base.to_vec(); + if !matches(tcx, holder, self.site_ty(site), &mut args) { continue; } - let Some(args) = at(candidate) else { - continue; - }; - // A type naming a parameter not yet chosen is checked once it is. - let named = (spelled(args).into_iter().filter_map(exported)) - .filter(|(_, args)| !args.has_non_region_param()) - .all(|(adt, args)| { - let key = self.key(adt, *args); - match self.inferring { - true => self.instances.iter().any(|site| site.key == key), - false => matches!( - self.decls.get(&key), - Some(Decl::Record(_) | Decl::Value(_) | Decl::Enum(_) | Decl::Object(_)) - ), - } - }); - if named { - found.push(candidate); + let candidate = args[p.index as usize].expect_ty(); + if candidate != param && !offered.contains(&candidate) { + offered.push(candidate); } } } + for candidate in offered.into_iter().filter(|ty| !(iterated && ty.is_ref())) { + let erased = tcx.erase_and_anonymize_regions(candidate); + if found + .iter() + .any(|&f| tcx.erase_and_anonymize_regions(f.peel_refs()) == erased) + { + continue; + } + let Some(args) = at(candidate) else { + continue; + }; + // A type naming a parameter not yet chosen is checked once it is. + let named = (spelled(args).into_iter().filter_map(exported)) + .filter(|(_, args)| !args.has_non_region_param()) + .all(|(adt, args)| { + let key = self.key(adt, *args); + match self.inferring { + true => self.instances.iter().any(|site| site.key == key), + false => matches!( + self.decls.get(&key), + Some(Decl::Record(_) | Decl::Value(_) | Decl::Enum(_) | Decl::Object(_)) + ), + } + }); + if named { + found.push(candidate); + } + } found } @@ -4697,11 +4818,17 @@ impl<'tcx> Collector<'tcx> { mapped } - /// Whether `ty` names an export's type, which maps only once declared. + /// Whether `ty` names an export's type, which maps only once declared: an item the walk + /// reached, or one a later pass reaches by its own crate's path. Another type of an + /// exported crate, as wasm-bindgen's `JsValue` is to js-sys, never maps. fn names_export(&self, ty: Ty<'tcx>) -> bool { - ty.walk() - .filter_map(|arg| arg.as_type()) - .any(|ty| matches!(ty.kind(), ty::Adt(adt, _) if self.exported(adt.did().krate))) + ty.walk().filter_map(|arg| arg.as_type()).any(|ty| match ty.kind() { + ty::Adt(adt, _) => { + let did = adt.did(); + self.exported(did.krate) && (self.listed.contains(&did) || self.reachable(did)) + } + _ => false, + }) } /// The closure a type parameter takes, if an `Fn` trait bounds it, which C implements as @@ -6403,6 +6530,30 @@ impl<'tcx> Collector<'tcx> { /// Each type a visited value names, at any depth. struct Types<'tcx>(Vec>); +/// How deeply the types visited nest generic types, each inside another's arguments one +/// level deeper. +struct Depth<'a> { + generic: &'a rustc_data_structures::fx::FxHashSet, + at: usize, + max: usize, +} + +impl<'a> Depth<'a> { + fn new(generic: &'a rustc_data_structures::fx::FxHashSet) -> Self { + Self { generic, at: 0, max: 0 } + } +} + +impl<'tcx> TypeVisitor> for Depth<'_> { + fn visit_ty(&mut self, ty: Ty<'tcx>) { + let own = matches!(ty.kind(), ty::Adt(adt, _) if self.generic.contains(&adt.did())) as usize; + self.at += own; + self.max = self.max.max(self.at); + ty.super_visit_with(self); + self.at -= own; + } +} + impl<'tcx> TypeVisitor> for Types<'tcx> { fn visit_ty(&mut self, ty: Ty<'tcx>) { self.0.push(ty); diff --git a/ffi/src/help.rs b/ffi/src/help.rs index 5080b90cd..9eaafa9a1 100644 --- a/ffi/src/help.rs +++ b/ffi/src/help.rs @@ -36,6 +36,9 @@ pub(crate) fn of(construct: &str) -> Option<&'static str> { "instance holding an instance of a type inside it" => { "do not nest the generic type in itself at a deeper instance, as `Cell>` does" } + crate::collect::DEEPER => { + "spell the instance in a signature of its own, such as a function returning it, or stop nesting generic types in a method's signature" + } "unmet bound of the instance" | "unmet bound" => { "implement the bound for the type, or loosen it; an instance exports only where every bound holds" } diff --git a/ffi/tests/fixtures/corpus.rs b/ffi/tests/fixtures/corpus.rs index d11b20359..eef830616 100644 --- a/ffi/tests/fixtures/corpus.rs +++ b/ffi/tests/fixtures/corpus.rs @@ -36,7 +36,6 @@ const KNOWN: &[(&str, &str)] = &[ ("hyper", "/quest/m1/ffi-corpus-bugs.md"), ("icu_locale_core", "/quest/m1/ffi-apart.md"), ("itertools", "/quest/m1/ffi-apart.md"), - ("js-sys", "/quest/m1/ffi-inference.md"), ("libc", "/quest/m1/ffi-apart.md"), ("log", "/quest/m1/ffi-apart.md"), ("nu-ansi-term", "/quest/m1/ffi-apart.md"), diff --git a/quest/m1/ffi-inference.md b/quest/m1/ffi-inference.md deleted file mode 100644 index 9e3ab69ab..000000000 --- a/quest/m1/ffi-inference.md +++ /dev/null @@ -1,28 +0,0 @@ -# [L] Bound instance inference by design - -## Goal - -`rust2-ffi --census` and `--out` on js-sys 0.3.107's facade finish, as they do on every -other crate of the corpus, and js-sys leaves `KNOWN` in `ffi/tests/fixtures/corpus.rs`. - -## Plan - -Kept by the maintainer on 2026-11-19, in the pick of [#878](https://github.com/kixel-ai/rust2/pull/878). - -Found by [the corpus](/ffi/tests/fixtures/corpus.rs) on 2026-11-19: js-sys's census ran -two hours without finishing. `Collector::infer` repeats until no round adds an instance, -and each round names every instance's members anew. js-sys's generic types (`Array`, -`Promise`, and the like) are bounded by a trait every JS type implements, so each round -nests one more generic type inside another: 0, 909, 1579, then 2478 instances, naming 0.4M, -5M, 30M, then 94M types, the last round taking four minutes. Nothing bounds the depth but -the count of distinct generic types, since only an instance holding its own type is -refused. - -Recommended: bound what a round may add by what the API names rather than by a constant, -such as inferring an instance only where an export's own signature, a type's default, or -a bound's implementor names it, and not where only another inferred instance's member -does; measure moq's census before and after, since its instances must not change. Also -worth measuring: `held_forms` walks every named type on every round, which a set of the -types it has seen would cut. - -Public API: none, unless the bound leaves out instances some export names today. From 14785be89f59a7de16884c972eb527ce62c3e888 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 20 Nov 2026 05:48:23 -0800 Subject: [PATCH 3/8] fix(ffi): offer a parameter what it is in its holder's instances, by structure matches walked a type's arguments with TypeWalker, which skips repeats, so RangedI16<0, 0> never matched RangedI16; it now pairs each constructor's arguments directly, tuples, references, slices, arrays, and raw pointers included. A generic export with no instance yet still offers any instance's arguments, so nom's fail names Fail's first instance. Co-Authored-By: Claude Opus 5.5 --- ffi/src/collect.rs | 116 +++++++++++++++++++++++++++------------------ 1 file changed, 69 insertions(+), 47 deletions(-) diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 9f69abfa0..37655b836 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -4696,22 +4696,32 @@ impl<'tcx> Collector<'tcx> { unreachable!("a generic type argument is a parameter"); }; // What `param` is in each instance of a generic type the signature holds it in, as - // `Foo` offers `X` for `Foo`; an instance of another type, or an argument at - // another position, offers nothing, so no choice feeds an unrelated signature. + // `Foo` offers `X` for `Foo`, so no choice feeds a signature its type's instances + // never name. One with no instance yet takes any instance's argument, so a function can + // name its type's first, as nom's `fail` names `Fail`'s; another crate's type, which + // has none, offers nothing. let mut offered: Vec> = Vec::new(); + let mut offer = |candidate: Ty<'tcx>| { + if candidate != param && !offered.contains(&candidate) { + offered.push(candidate); + } + }; for holder in spelled(tcx.mk_args(base)) { let Some((adt, args)) = exported(holder) else { continue }; - if !args.iter().any(|arg| arg.walk().any(|a| a == param.into())) { + if !self.generic.contains(&adt) || !args.iter().any(|arg| arg.walk().any(|a| a == param.into())) { continue; } - for site in self.instances.iter().filter(|site| site.key.def_id == adt) { + let mut sites = self.instances.iter().filter(|site| site.key.def_id == adt).peekable(); + if sites.peek().is_none() { + self.instances + .iter() + .flat_map(|site| site.args.types()) + .for_each(&mut offer); + } + for site in sites { let mut args = base.to_vec(); - if !matches(tcx, holder, self.site_ty(site), &mut args) { - continue; - } - let candidate = args[p.index as usize].expect_ty(); - if candidate != param && !offered.contains(&candidate) { - offered.push(candidate); + if matches(tcx, holder, self.site_ty(site), &mut args) { + offer(args[p.index as usize].expect_ty()); } } } @@ -7316,46 +7326,58 @@ fn implements<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, def_id: DefId, item: rustc_ infcx.type_implements_trait(tr, [ty], env).must_apply_modulo_regions() } -/// Whether `ty` is an instance of an impl's self type `pattern`, binding each of the -/// impl's type parameters in `args`, which starts as its identity. An instance's -/// arguments are never references or tuples but `()`, so structure decides it; lifetimes -/// stay as the impl names them. +/// Whether `ty` is an instance of `pattern`, an impl's self type or a type a signature +/// names, binding each of its type and const parameters in `args`, which starts as their +/// identity: each constructor, such as a type's, a tuple's, or a reference's, must be the +/// same, and lifetimes stay as `pattern` names them. fn matches<'tcx>(tcx: TyCtxt<'tcx>, pattern: Ty<'tcx>, ty: Ty<'tcx>, args: &mut [ty::GenericArg<'tcx>]) -> bool { - match (pattern.kind(), ty.kind()) { - (ty::Param(param), _) => { - let slot = &mut args[param.index as usize]; - match slot.as_type() == Some(pattern) { - true => { - *slot = ty.into(); - true - } - false => { - slot.as_type().map(|bound| tcx.erase_and_anonymize_regions(bound)) - == Some(tcx.erase_and_anonymize_regions(ty)) - } + if let ty::Param(param) = pattern.kind() { + let slot = &mut args[param.index as usize]; + return match slot.as_type() == Some(pattern) { + true => { + *slot = ty.into(); + true } - } - (ty::Adt(a, pattern_args), ty::Adt(b, ty_args)) if a.did() == b.did() => { - (pattern_args.iter().zip(ty_args.iter())).all(|(p, t)| match (p.kind(), t.kind()) { - (GenericArgKind::Type(p), GenericArgKind::Type(t)) => matches(tcx, p, t, args), - (GenericArgKind::Const(p), GenericArgKind::Const(t)) => match p.kind() { - ty::ConstKind::Param(param) => { - let slot = &mut args[param.index as usize]; - match slot.as_const() == Some(p) { - true => { - *slot = t.into(); - true - } - false => slot.as_const() == Some(t), - } - } - _ => p == t, - }, - _ => true, - }) - } - _ => tcx.erase_and_anonymize_regions(pattern) == tcx.erase_and_anonymize_regions(ty), + false => { + slot.as_type().map(|bound| tcx.erase_and_anonymize_regions(bound)) + == Some(tcx.erase_and_anonymize_regions(ty)) + } + }; } + if !pattern.has_non_region_param() { + return tcx.erase_and_anonymize_regions(pattern) == tcx.erase_and_anonymize_regions(ty); + } + // The same constructor, each argument matching in turn; any other, such as an associated + // type's, binds nothing. + let pairs: Vec<(ty::GenericArg<'tcx>, ty::GenericArg<'tcx>)> = match (pattern.kind(), ty.kind()) { + (ty::Adt(a, p), ty::Adt(b, t)) if a.did() == b.did() => p.iter().zip(t.iter()).collect(), + (ty::Tuple(p), ty::Tuple(t)) if p.len() == t.len() => { + (p.iter().zip(t.iter())).map(|(p, t)| (p.into(), t.into())).collect() + } + (ty::Ref(_, p, a), ty::Ref(_, t, b)) if a == b => vec![((*p).into(), (*t).into())], + (ty::RawPtr(p, a), ty::RawPtr(t, b)) if a == b => vec![((*p).into(), (*t).into())], + (ty::Slice(p), ty::Slice(t)) => vec![((*p).into(), (*t).into())], + (ty::Array(p, n), ty::Array(t, m)) => vec![((*p).into(), (*t).into()), ((*n).into(), (*m).into())], + _ => return false, + }; + pairs.into_iter().all(|(p, t)| match (p.kind(), t.kind()) { + (GenericArgKind::Type(p), GenericArgKind::Type(t)) => matches(tcx, p, t, args), + (GenericArgKind::Const(p), GenericArgKind::Const(t)) => match p.kind() { + ty::ConstKind::Param(param) => { + let slot = &mut args[param.index as usize]; + match slot.as_const() == Some(p) { + true => { + *slot = t.into(); + true + } + false => slot.as_const() == Some(t), + } + } + _ => p == t, + }, + (GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => true, + _ => false, + }) } /// A type's own generic arguments as it is exported: its lifetimes `'static`. From e4a8cf0d9aa422a2fb538065957e6da9ca2438cc Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 20 Nov 2026 05:51:53 -0800 Subject: [PATCH 4/8] refactor(ffi): keep Types' impl beside it Co-Authored-By: Claude Opus 5.5 --- ffi/src/collect.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 37655b836..10265cd12 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -6540,6 +6540,13 @@ impl<'tcx> Collector<'tcx> { /// Each type a visited value names, at any depth. struct Types<'tcx>(Vec>); +impl<'tcx> TypeVisitor> for Types<'tcx> { + fn visit_ty(&mut self, ty: Ty<'tcx>) { + self.0.push(ty); + ty.super_visit_with(self); + } +} + /// How deeply the types visited nest generic types, each inside another's arguments one /// level deeper. struct Depth<'a> { @@ -6564,13 +6571,6 @@ impl<'tcx> TypeVisitor> for Depth<'_> { } } -impl<'tcx> TypeVisitor> for Types<'tcx> { - fn visit_ty(&mut self, ty: Ty<'tcx>) { - self.0.push(ty); - ty.super_visit_with(self); - } -} - /// Where a type appears, which decides the forms it may take. #[derive(Clone, Copy, PartialEq, Eq)] enum Pos { From 617cdb66b462387f454579d3cad6ee5a7a6b6b90 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 20 Nov 2026 06:01:19 -0800 Subject: [PATCH 5/8] fix(ffi): measure the depth ceiling as inference names types An async function's output and a parameter's implementor are what inference names, so the ceiling counts functions' signatures as spelled resolves them and every type the first round names, before any instance does. Co-Authored-By: Claude Opus 5.5 --- ffi/src/collect.rs | 23 ++++++++++++++++------- ffi/tests/fixtures.rs | 22 ++++++++++++++++++++++ 2 files changed, 38 insertions(+), 7 deletions(-) diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 10265cd12..646bbb7ee 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -903,6 +903,7 @@ impl<'tcx> Collector<'tcx> { self.deepest = spelled.max; let mut seen = rustc_data_structures::fx::FxHashSet::default(); let mut held = rustc_data_structures::fx::FxHashSet::default(); + let mut first = true; loop { let inferred = self.instances.len(); let named = self.named(); @@ -911,15 +912,24 @@ impl<'tcx> Collector<'tcx> { self.held_forms(ty); } } - // Each with the instances inside it, which its export needs, normalized, as a - // field or a bound may name its instance's argument by an associated type. - let types: Vec> = (candidates.iter().chain(&named)) + // Normalized, as a field or a bound may name its instance's argument by an + // associated type. + let named: Vec> = (candidates.iter().chain(&named)) .map(|&ty| match ty.has_aliases() { true => tcx .try_normalize_erasing_regions(TypingEnv::fully_monomorphized(), ty::Unnormalized::new_wip(ty)) .unwrap_or(ty), false => ty, }) + .collect(); + // What the first round names, before any instance does, is the API's too: each + // function at its implementors, and each future at what it resolves to. + if std::mem::take(&mut first) { + let deepest = named.iter().map(|&ty| self.depth(ty)).max(); + self.deepest = self.deepest.max(deepest.unwrap_or(0)); + } + // Each with the instances inside it, which its export needs. + let types: Vec> = (named.iter()) .flat_map(|ty| ty.walk()) .filter_map(|arg| arg.as_type()) .filter(|&ty| seen.insert(ty)) @@ -1312,7 +1322,7 @@ impl<'tcx> Collector<'tcx> { } /// Visit every type the API spells at its own parameters: each function's, constant's, - /// and trait method's signature with its bounds, and each type's defaults, `pub` fields, + /// and trait method's signature as inference names it, with its bounds, and each type's defaults, `pub` fields, /// and inherent impls with their `pub` methods and constants. fn spells(&self, visitor: &mut Depth<'_>) { let tcx = self.tcx; @@ -1359,9 +1369,8 @@ impl<'tcx> Collector<'tcx> { } types.visit_with(visitor); for def_id in functions { - tcx.fn_sig(def_id) - .instantiate_identity() - .skip_norm_wip() + // As inference names it: normalized, and a future as what it resolves to. + self.spelled(def_id, ty::GenericArgs::identity_for_item(tcx, def_id)) .visit_with(visitor); for clause in tcx.clauses_of(def_id).instantiate_identity(tcx).clauses { clause.skip_norm_wip().visit_with(visitor); diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 3749dc3e0..8ad007f64 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -4296,6 +4296,28 @@ fn census_counts_traits() { assert!(report.contains("| Traits | 0 | 1 | 0% |"), "{report}"); } +/// The depth an instance may nest to counts what inference names, not only what the +/// signatures spell: an async function's output, and a parameter's implementor. +#[test] +fn census_depth() { + let lib = "pub struct Wrap(pub T);\n\n\ + pub async fn make() -> Wrap {\n\tWrap(0)\n}\n\n\ + pub trait Seed: Copy {\n\tfn seed(&self) -> u8;\n}\n\n\ + #[derive(Clone, Copy)]\npub struct Held(pub T);\n\n\ + impl Seed for Held {\n\tfn seed(&self) -> u8 {\n\t\t1\n\t}\n}\n\n\ + pub fn plant(seed: impl Seed) -> u8 {\n\tseed.seed()\n}\n"; + let package = package("census_depth", &[("src/lib.rs", lib)]); + let output = census(&package.join("Cargo.toml"), &[]).output().unwrap(); + assert!( + output.status.success(), + "the census failed:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + let report = std::fs::read_to_string(package.join("census/census_depth.md")).unwrap(); + assert!(!report.contains("instance deeper"), "{report}"); + assert!(report.contains("| Functions | 2 | 0 |"), "{report}"); +} + /// A method Swift refuses leaves out only itself, not the accessors of a field of its name. #[test] fn census_swift_field() { From cebc42e04056eb681291ea308f4f557c034867da Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 20 Nov 2026 06:11:04 -0800 Subject: [PATCH 6/8] fix(ffi): count the impls a bound names in the depth ceiling A method's implementor, which only an instance of its type names, is an impl header the API spells, so the ceiling counts every impl of each trait the API's bounds name, blanket impls' bounds followed. Co-Authored-By: Claude Opus 5.5 --- ffi/src/collect.rs | 35 ++++++++++++++++++++++++++++++++--- ffi/tests/fixtures.rs | 13 +++++++++++-- 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 646bbb7ee..46361f0da 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -1322,8 +1322,9 @@ impl<'tcx> Collector<'tcx> { } /// Visit every type the API spells at its own parameters: each function's, constant's, - /// and trait method's signature as inference names it, with its bounds, and each type's defaults, `pub` fields, - /// and inherent impls with their `pub` methods and constants. + /// and trait method's signature as inference names it, with its bounds and the impls of + /// the traits they name, and each type's defaults, `pub` fields, and inherent impls with + /// their `pub` methods and constants. fn spells(&self, visitor: &mut Depth<'_>) { let tcx = self.tcx; let mut functions = Vec::new(); @@ -1368,12 +1369,40 @@ impl<'tcx> Collector<'tcx> { } } types.visit_with(visitor); + let mut traits = Vec::new(); + let mut bounded = |clause: ty::Clause<'tcx>, traits: &mut Vec| { + if let Some(bound) = clause.as_trait_clause() + && self.exported(bound.def_id().krate) + && !traits.contains(&bound.def_id()) + { + traits.push(bound.def_id()); + } + }; for def_id in functions { // As inference names it: normalized, and a future as what it resolves to. self.spelled(def_id, ty::GenericArgs::identity_for_item(tcx, def_id)) .visit_with(visitor); for clause in tcx.clauses_of(def_id).instantiate_identity(tcx).clauses { - clause.skip_norm_wip().visit_with(visitor); + let clause = clause.skip_norm_wip(); + clause.visit_with(visitor); + bounded(clause, &mut traits); + } + } + // Each impl of a trait a bound names, which a parameter may take as its implementor, + // a blanket impl's own bounds included, as `implementors` follows them. + let mut i = 0; + while let Some(&tr) = traits.get(i) { + i += 1; + for imp in tcx.all_impls(tr).filter(|imp| self.exported(imp.krate)) { + let ty = tcx.type_of(imp).instantiate_identity().skip_norm_wip(); + match ty.kind() { + ty::Param(_) => { + for clause in tcx.clauses_of(imp).instantiate_identity(tcx).clauses { + bounded(clause.skip_norm_wip(), &mut traits); + } + } + _ => ty.visit_with(visitor), + } } } } diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 8ad007f64..aaf9df233 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -4297,7 +4297,8 @@ fn census_counts_traits() { } /// The depth an instance may nest to counts what inference names, not only what the -/// signatures spell: an async function's output, and a parameter's implementor. +/// signatures spell: an async function's output, and a parameter's implementor, a +/// method's too, which only an instance of its type names. #[test] fn census_depth() { let lib = "pub struct Wrap(pub T);\n\n\ @@ -4305,7 +4306,11 @@ fn census_depth() { pub trait Seed: Copy {\n\tfn seed(&self) -> u8;\n}\n\n\ #[derive(Clone, Copy)]\npub struct Held(pub T);\n\n\ impl Seed for Held {\n\tfn seed(&self) -> u8 {\n\t\t1\n\t}\n}\n\n\ - pub fn plant(seed: impl Seed) -> u8 {\n\tseed.seed()\n}\n"; + pub fn plant(seed: impl Seed) -> u8 {\n\tseed.seed()\n}\n\n\ + #[derive(Clone, Copy)]\npub struct Host(pub T);\n\n\ + pub trait Grow: Copy {\n\tfn grow(&self) -> u8;\n}\n\n\ + impl Grow for Held> {\n\tfn grow(&self) -> u8 {\n\t\t2\n\t}\n}\n\n\ + impl Host {\n\tpub fn plant(&self, seed: impl Grow) -> u8 {\n\t\tseed.grow()\n\t}\n}\n"; let package = package("census_depth", &[("src/lib.rs", lib)]); let output = census(&package.join("Cargo.toml"), &[]).output().unwrap(); assert!( @@ -4316,6 +4321,10 @@ fn census_depth() { let report = std::fs::read_to_string(package.join("census/census_depth.md")).unwrap(); assert!(!report.contains("instance deeper"), "{report}"); assert!(report.contains("| Functions | 2 | 0 |"), "{report}"); + assert!( + report.contains("| Methods and fields of exported types | 2 | 0 |"), + "{report}" + ); } /// A method Swift refuses leaves out only itself, not the accessors of a field of its name. From 8662612ea65adc95972adbd0f29cc0eff6b2afaf Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 20 Nov 2026 06:15:23 -0800 Subject: [PATCH 7/8] fix(ffi): drop an unneeded mut Co-Authored-By: Claude Opus 5.5 --- ffi/src/collect.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 46361f0da..7d8cb6c02 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -1370,7 +1370,7 @@ impl<'tcx> Collector<'tcx> { } types.visit_with(visitor); let mut traits = Vec::new(); - let mut bounded = |clause: ty::Clause<'tcx>, traits: &mut Vec| { + let bounded = |clause: ty::Clause<'tcx>, traits: &mut Vec| { if let Some(bound) = clause.as_trait_clause() && self.exported(bound.def_id().krate) && !traits.contains(&bound.def_id()) From 23d3735becadfd5850db73a1451b719447ce5576 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 20 Nov 2026 06:27:13 -0800 Subject: [PATCH 8/8] fix(ffi): count an inherent impl's type only through a public member Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/reject/src/lib.rs | 7 +++++++ ffi/src/collect.rs | 13 ++++++++----- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/ffi/fixtures/reject/src/lib.rs b/ffi/fixtures/reject/src/lib.rs index d5f795000..a40e5fcbe 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -1628,3 +1628,10 @@ impl Knot { pub fn rope(value: u8) -> Rope { Rope(value) } + +/// An impl with no public member spells nothing, so it raises no instance's depth past +/// what the API spells: `Tie>>` stays refused. +impl Rope>> { + #[allow(dead_code, reason = "private, so no part of the API")] + fn private(&self) {} +} diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 7d8cb6c02..01d50c994 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -1350,11 +1350,14 @@ impl<'tcx> Collector<'tcx> { types.push(tcx.type_of(field.did).instantiate_identity().skip_norm_wip()); } for &imp in tcx.inherent_impls(def_id) { - types.push(tcx.type_of(imp).instantiate_identity().skip_norm_wip()); - for item in tcx.associated_items(imp).in_definition_order() { - if !tcx.visibility(item.def_id).is_public() || tcx.is_doc_hidden(item.def_id) { - continue; - } + // An impl spells its type only through a member in the API. + let members: Vec<_> = (tcx.associated_items(imp).in_definition_order()) + .filter(|item| tcx.visibility(item.def_id).is_public() && !tcx.is_doc_hidden(item.def_id)) + .collect(); + if !members.is_empty() { + types.push(tcx.type_of(imp).instantiate_identity().skip_norm_wip()); + } + for item in members { match item.kind { ty::AssocKind::Fn { .. } => functions.push(item.def_id), ty::AssocKind::Const { .. } => {