From 227f4291d991d530d6783a3931536716100ff12d Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Wed, 28 Oct 2026 11:39:31 -0700 Subject: [PATCH 1/5] chore(quest): infer instances in one pass before typing Co-Authored-By: Claude Opus 5.5 --- quest/m1/ffi-export/README.md | 1 + quest/m1/ffi-export/inference.md | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 quest/m1/ffi-export/inference.md diff --git a/quest/m1/ffi-export/README.md b/quest/m1/ffi-export/README.md index b56623757..48c3f6449 100644 --- a/quest/m1/ffi-export/README.md +++ b/quest/m1/ffi-export/README.md @@ -47,6 +47,7 @@ Every generator on the C ABI: ## Required +- [Infer instances in one pass before typing](/quest/m1/ffi-export/inference.md) - generic functions with closures, and concrete instances only a trait impl names, export - [Iterator and JSON arguments the exporter can't map yet](/quest/m1/ffi-export/instance-keys.md) - `IntoIterator` as a `Vec`, and `serde_json::Value` - [moq-clock's C names once it moves into kio](/quest/m1/ffi-export/crates.md) - `moq_now` and `moq_origin` become the clock's, after moq moves it into `kio::clock` - [Setters for an object's pub fields](/quest/m1/ffi-export/field-setters.md) - C fills in a session's config, as Rust assigns it diff --git a/quest/m1/ffi-export/inference.md b/quest/m1/ffi-export/inference.md new file mode 100644 index 000000000..d5ff77b2c --- /dev/null +++ b/quest/m1/ffi-export/inference.md @@ -0,0 +1,24 @@ +# [M] Infer instances in one pass before typing + +## Goal + +The exporter infers every instance a generic item exports at in one pass over the exported +crates' signatures, before it maps any type, so mapping a signature never discovers a new +instance. Two cases that inference misses today export: + +- a generic function inferred at an instance that also takes a closure or a foreign + callback, such as `fn apply u32>(p: Pair, f: F)`; +- a generic type's concrete instance that only an impl of an exported trait names, such + as `impl Seed for Wrap` taken by `fn seeded(seed: impl Seed)`. + +Instance names stay the shortest unique form, independent of crate order. + +## Plan + +Decided with the maintainer on 2026-10-28, after +[#152](https://github.com/kixelated/rust2/pull/152): restructure inference so these cases +fall out of the design rather than being patched one by one. Write the design note in the +PR body before coding, and check whether rustc's `rustc_monomorphize::collector` or another +analysis can be reused. + +Public API: none beyond the instances and functions these cases add. From 3c406bfc8829276a9506b0fc68cd6e8bba80a500 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Wed, 28 Oct 2026 11:53:19 -0700 Subject: [PATCH 2/5] refactor(ffi): infer instances in one pass before typing Inference walks every signature the export maps, at every choice its bounds allow, before any type is declared, so mapping a signature never discovers an instance. A function inferred at an instance keeps its lent closure and foreign callback parameters, and a concrete instance only a trait impl names, such as Wrap: Seed, is inferred. Drops the pending/named bookkeeping and the rerun of collection per inferred round. Co-Authored-By: Claude Opus 5.5 --- ffi/README.md | 10 +- ffi/fixtures/api/examples/transcript.rs | 4 + ffi/fixtures/api/src/lib.rs | 28 ++ ffi/fixtures/reject/expected.txt | 27 +- ffi/fixtures/reject/src/lib.rs | 23 + ffi/src/collect.rs | 550 ++++++++++++++---------- ffi/src/glue.rs | 4 +- ffi/src/ir.rs | 5 +- ffi/tests/api.c | 12 + ffi/tests/api.cpp | 6 + quest/m1/ffi-export/README.md | 1 - quest/m1/ffi-export/inference.md | 24 -- quest/m1/ffi-export/instance-keys.md | 6 +- 13 files changed, 429 insertions(+), 271 deletions(-) delete mode 100644 quest/m1/ffi-export/inference.md diff --git a/ffi/README.md b/ffi/README.md index a937eff45..d510e2b9e 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -83,10 +83,12 @@ A generic type infers the instances it exports at, with no config: the one at it defaults, if each type parameter has one; the one each inherent impl is of, such as `impl Pair`; each choice, for each parameter, among its default and the types the exports implement a trait bounding it for, one of the exports', which are `()`, a -primitive, `String`, or an exported type; and each instance a signature or field names, -once that is all its export refuses, which may name more. An instance that holds an -instance of a type inside it, such as `Cell>`, is refused, as it could name -ever deeper ones. +primitive, `String`, or an exported type or an instance of one, such as +`impl Seed for Wrap`; and each instance a signature, `pub` field, or constant +names at any choice its bounds allow, whether or not the rest of it maps, which may name +more. Inference finishes before any type is mapped, so mapping never adds an instance. +An instance that holds an instance of a type inside it, such as `Cell>`, is +refused, as it could name ever deeper ones. A record or enum holds only values and `Copy` handles: one with a field that does not map, or that holds itself, is an object instead, and the census lists it. A borrowed return is diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index 6d78e56d4..b3f30fe4d 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -280,6 +280,10 @@ fn main() { api_lib::kept(Point { x: 1, y: -2 }), api_lib::BOXED.value ); + let sides = Pair { left: 2u32, right: 5 }; + println!("apply {}", api_lib::apply(sides, |side| side * 3)); + println!("report {}", api_lib::report(sides, Print)); + println!("wrapped {}", api_lib::kept(api_lib::Wrap { value: 4u32 })); let token = api_lib::Token::new(7); println!("token {} dropped {}", token.id, api_lib::dropped()); diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index d5e2d706a..081e6b85d 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -769,6 +769,34 @@ impl Seed for Size { } } +/// Each side of `pair` through `f`, summed: a function inferred at each instance of +/// `Pair` whose sides are alike, taking a lent closure of the inferred type. +pub fn apply u32>(pair: Pair, f: F) -> u32 { + f(pair.left) + f(pair.right) +} + +/// Each side of `pair` to `log`, returning how many it kept: inferred as `apply` is, +/// taking a foreign implementation. +pub fn report(pair: Pair, log: L) -> u32 { + [pair.left, pair.right] + .iter() + .filter(|side| log.log(1, &format!("{side:?}"))) + .count() as u32 +} + +/// A wrapped value, which only its impl of `Seed` at `Wrap` names: each +/// function taking a seed infers that instance. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Wrap { + pub value: T, +} + +impl Seed for Wrap { + fn seed(&self) -> u64 { + u64::from(self.value) * 10 + } +} + /// A second `Point`, whose last segment clashes with the crate root's: an instance named /// by it takes its module too, and one named by the other keeps the shorter name. pub mod polar { diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index 2229dda24..c3c52530f 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -11,20 +11,21 @@ fixtures/reject/src/lib.rs:130:1: rust2-ffi: cannot export struct `Lease`: objec fixtures/reject/src/lib.rs:149:1: rust2-ffi: cannot export instance `Cell>`: Vec `std::string::String`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:14:1: rust2-ffi: cannot export fn `map`: foreign type `std::collections::HashMap`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:159:2: rust2-ffi: cannot export method `Cell::nest`: instance holding an instance of a type inside it `reject_fixture::Cell>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:165:1: rust2-ffi: cannot export fn `excluded_cell`: excluded type `reject_fixture::Cell`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:170:1: rust2-ffi: cannot export fn `listed`: refused type `reject_fixture::Cell>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:175:1: rust2-ffi: cannot export struct `Fixed`: generic type; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:178:1: rust2-ffi: cannot export fn `fixed`: const generic `reject_fixture::Fixed`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:183:9: rust2-ffi: cannot export use `HashSet`: re-export of another crate's item `std`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:186:1: rust2-ffi: cannot export fn `lend`: Waker outside a parameter taken by value; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:178:2: rust2-ffi: cannot export method `Pong>::ping`: instance holding an instance of a type inside it `reject_fixture::Ping>>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:188:1: rust2-ffi: cannot export fn `excluded_cell`: excluded type `reject_fixture::Cell`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:193:1: rust2-ffi: cannot export fn `listed`: refused type `reject_fixture::Cell>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:198:1: rust2-ffi: cannot export struct `Fixed`: generic type; exclude it in the config to leave it out fixtures/reject/src/lib.rs:19:1: rust2-ffi: cannot export fn `generic`: generic parameter `std::marker::Copy`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:201:2: rust2-ffi: fn `reject_fixture::Limit::max` and field `reject_fixture::Limit::max` are both `reject_limit_max` in C - fixtures/reject/src/lib.rs:193:2: note: field `reject_fixture::Limit::max` is here -fixtures/reject/src/lib.rs:207:1: rust2-ffi: cannot export fn `spawn`: closure kept past the call `impl FnOnce() + Send + 'static`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:212:1: rust2-ffi: cannot export fn `later`: closure kept past the call `impl FnOnce()`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:217:1: rust2-ffi: cannot export fn `twice`: closure bound `std::clone::Clone`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:223:1: rust2-ffi: cannot export fn `both`: closure type taken twice `F`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:229:1: rust2-ffi: cannot export fn `read`: lent object that borrows `&Text<'_>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:201:1: rust2-ffi: cannot export fn `fixed`: const generic `reject_fixture::Fixed`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:206:9: rust2-ffi: cannot export use `HashSet`: re-export of another crate's item `std`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:209:1: rust2-ffi: cannot export fn `lend`: Waker outside a parameter taken by value; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:224:2: rust2-ffi: fn `reject_fixture::Limit::max` and field `reject_fixture::Limit::max` are both `reject_limit_max` in C + fixtures/reject/src/lib.rs:216:2: note: field `reject_fixture::Limit::max` is here +fixtures/reject/src/lib.rs:230:1: rust2-ffi: cannot export fn `spawn`: closure kept past the call `impl FnOnce() + Send + 'static`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:235:1: rust2-ffi: cannot export fn `later`: closure kept past the call `impl FnOnce()`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:240:1: rust2-ffi: cannot export fn `twice`: closure bound `std::clone::Clone`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:246:1: rust2-ffi: cannot export fn `both`: closure type taken twice `F`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:252:1: rust2-ffi: cannot export fn `read`: lent object that borrows `&Text<'_>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:26:1: rust2-ffi: cannot export fn `borrowing`: borrowing future from a function that is not async; exclude it in the config to leave it out fixtures/reject/src/lib.rs:31:1: rust2-ffi: cannot export fn `nested`: nested Option `std::option::Option>>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:40:1: rust2-ffi: cannot export fn `peek`: reference to a handle inside a value `std::boxed::Box`; exclude it in the config to leave it out diff --git a/ffi/fixtures/reject/src/lib.rs b/ffi/fixtures/reject/src/lib.rs index dca98f6a2..2e04ef1fc 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -161,6 +161,29 @@ impl Cell { } } +/// Two generic types whose methods each wrap the other's instance in their own: inferring +/// from `Ping` names `Pong>`, whose `ping` names `Ping>>`, which +/// holds a `Ping` inside a `Ping` and ends inference there. +pub struct Ping(T); + +pub struct Pong(T); + +impl Ping { + pub fn pong(self) -> Pong> { + Pong(self) + } +} + +impl Pong { + pub fn ping(self) -> Ping> { + Ping(self) + } +} + +pub fn ping(value: u8) -> Ping { + Ping(value) +} + /// An instance the config excludes. pub fn excluded_cell(cell: Cell) -> u16 { cell.0 diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 72e5f65ca..ee997647b 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -5,9 +5,9 @@ //! type is refused. Nothing is opted in by attribute and nothing is skipped silently: the //! config's `exclude` is the only way to leave an item out, and `#[doc(hidden)]` items, //! which are no part of the documented API, are listed in the census. A generic type -//! exports at the instances it infers: its defaults, each instance an inherent impl is -//! of, its exports' implementations of the traits bounding it, and each instance an export -//! names; and only there. +//! exports at the instances it infers, before any type is mapped: its defaults, each +//! instance an inherent impl is of, its exports' implementations of the traits bounding it, +//! and each instance a signature names at any choice its bounds allow; and only there. use std::collections::VecDeque; @@ -15,7 +15,9 @@ use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{CrateNum, DefId}; use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::traits::{Obligation, ObligationCause}; -use rustc_middle::ty::{self, GenericArgKind, Ty, TyCtxt, TypeVisitableExt, TypingEnv}; +use rustc_middle::ty::{ + self, GenericArgKind, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingEnv, +}; use rustc_span::{Span, sym}; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _; @@ -34,9 +36,6 @@ pub struct Why { pub note: Option<(Span, String)>, } -/// The construct of an instance no export names, which one that does infers. -const UNNAMED: &str = "instance no export names"; - fn why(construct: &'static str, detail: impl Into) -> Why { Why { construct, @@ -129,9 +128,9 @@ struct Site<'tcx> { /// several types. struct Instantiation<'tcx> { args: ty::GenericArgsRef<'tcx>, - /// The type parameters that take a foreign implementation or a lent closure, with the - /// type each takes. - impls: Vec<(Ty<'tcx>, Type)>, + /// The type parameters that stay parameters, each taking a lent closure or a foreign + /// implementation, which typing maps. + kept: Vec>, /// The arguments of the type parameters that export at several types, which name it. named: Vec>, } @@ -145,10 +144,9 @@ struct Collector<'tcx> { instances: Vec>, /// Instances that do not export, and why. rejected: rustc_data_structures::fx::FxHashMap, Why>, - /// Instances the signature being mapped names that are not yet inferred. - pending: std::cell::RefCell>>, - /// Instances signatures that export but for them name, which the next pass infers. - named: std::cell::RefCell>>, + /// 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, /// The exported crates, the configured one first, and what collection found in each. crates: Vec, reports: Vec, @@ -190,7 +188,7 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, crates: &[Crate<'_>]) -> Collected { _ => None, } }); - let pass = |orphans: &rustc_data_structures::fx::FxHashSet>, named: &[Ty<'tcx>]| { + let pass = |orphans: &rustc_data_structures::fx::FxHashSet>| { let mut c = Collector { tcx, items: Vec::new(), @@ -212,8 +210,7 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, crates: &[Crate<'_>]) -> Collected { .collect(), instances: Vec::new(), rejected: Default::default(), - pending: Default::default(), - named: Default::default(), + inferring: true, left_out: Default::default(), impls: Default::default(), bytes, @@ -230,31 +227,16 @@ pub fn collect<'tcx>(tcx: TyCtxt<'tcx>, crates: &[Crate<'_>]) -> Collected { }, }; c.walk(); - c.infer(named); + c.infer(); c.declare(); c.define(); c }; // Refusing an object no export returns refuses what takes it, which may leave another - // object no export returns, so collection repeats until it refuses no more. Within each, - // an instance an export names may name more, so it repeats until it infers no more. + // object no export returns, so collection repeats until it refuses no more. let mut orphans = rustc_data_structures::fx::FxHashSet::default(); loop { - let mut named: Vec> = Vec::new(); - let c = loop { - let c = pass(&orphans, &named); - let more: Vec> = (c.named.borrow().iter().copied()) - .filter(|ty| !named.contains(ty)) - .collect(); - if more.is_empty() { - break c; - } - for ty in more { - if !named.contains(&ty) { - named.push(ty); - } - } - }; + let c = pass(&orphans); let more = c.orphans(); if more.is_empty() { return Collected { @@ -391,11 +373,13 @@ impl<'tcx> Collector<'tcx> { } } - /// Infer the instances each generic type exports at: its defaults, the instance each of - /// its inherent impls is of, each choice among its default and the implementations of - /// the traits bounding each parameter, and each instance the last pass's exports - /// `named`, with the instances inside it. - fn infer(&mut self, named: &[Ty<'tcx>]) { + /// Infer the instances each generic type exports at, with the instances inside each: its + /// defaults, the instance each of its inherent impls is of, each choice among its default + /// 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. + fn infer(&mut self) { let tcx = self.tcx; let mut candidates: Vec> = Vec::new(); for (def_id, _) in self.items.clone() { @@ -438,25 +422,129 @@ impl<'tcx> Collector<'tcx> { .map(|args| Ty::new_adt(tcx, adt, tcx.mk_args(&args))), ); } - candidates.extend(named); - // Each with the instances inside it, which its export needs. - let candidates: Vec> = (candidates.iter()) - .flat_map(|ty| ty.walk()) - .filter_map(|arg| arg.as_type()) - .collect(); - for ty in candidates { - let Some((key, site)) = self.admit(ty) else { - continue; - }; - match site { - Ok(site) if !self.instances.iter().any(|other| other.key == key) => self.instances.push(site), - Ok(_) => {} - Err(why) => { - self.rejected.insert(key, why); + let mut seen = 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. + let types: Vec> = (candidates.iter().chain(&named)) + .flat_map(|ty| ty.walk()) + .filter_map(|arg| arg.as_type()) + .filter(|&ty| seen.insert(ty)) + .collect(); + for ty in types { + match self.admit(ty) { + Some((key, Ok(site))) if !self.instances.iter().any(|other| other.key == key) => { + self.instances.push(site) + } + Some((_, Ok(_))) | None => {} + Some((key, Err(why))) => { + self.rejected.insert(key, why); + } } } + if self.instances.len() == inferred { + break; + } } self.instances.sort_by(|a, b| a.shown.cmp(&b.shown)); + self.inferring = false; + } + + /// Each type a signature the export maps names, bounds included, at every choice + /// [`Self::instantiate`] takes while inferring: each function's, constant's, and trait + /// method's, and each type's `pub` fields and the inherent methods and constants that + /// apply to it, an instance's at its arguments. + fn named(&mut self) -> Vec> { + let tcx = self.tcx; + let mut named = Vec::new(); + let mut sites = Vec::new(); + for (def_id, path) in self.items.clone() { + match tcx.def_kind(def_id) { + DefKind::Fn => named.extend(self.instantiated(def_id, &path, None)), + DefKind::Const => named.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 { name, .. } = item.kind { + let method = [&path[..], &[name.to_string()]].concat(); + named.extend(self.instantiated(item.def_id, &method, None)); + } + } + } + DefKind::Struct | DefKind::Enum if !self.typed(def_id) => sites.extend(self.sites(def_id, &path)), + _ => {} + } + } + sites.extend(self.instances.clone()); + for site in sites { + let adt = tcx.adt_def(site.key.def_id); + // An object's private fields are no part of its API. + let fields = adt.all_fields().filter(|field| field.vis.is_public()); + named.extend(fields.map(|field| field.ty(tcx, site.args).skip_norm_wip())); + for (item, parent, shown, hidden) in self.members(&site) { + match item.kind { + _ if hidden => {} + ty::AssocKind::Const { .. } => { + named.push(tcx.type_of(item.def_id).instantiate(tcx, parent).skip_norm_wip()) + } + _ => named.extend(self.instantiated(item.def_id, &shown, Some(parent))), + } + } + } + named + } + + /// The types a function's signature names, bounds included, at each instantiation it + /// is not excluded at. + fn instantiated(&mut self, def_id: DefId, shown: &Path, parent: Option>) -> Vec> { + let tcx = self.tcx; + let mut named = Vec::new(); + for instance in self.instantiate(def_id, parent).unwrap_or_default() { + if self.shown(shown, &instance).is_none() { + continue; + } + named.extend(self.spelled(def_id, instance.args)); + let clauses = tcx.clauses_of(def_id).instantiate(tcx, instance.args).clauses; + let mut types = Types(Vec::new()); + for clause in clauses { + clause.skip_norm_wip().visit_with(&mut types); + } + named.extend(types.0); + } + named + } + + /// The path reports show an instance of a function by, from its function's `shown`, + /// unless the config excludes it. + fn shown(&mut self, shown: &Path, instance: &Instantiation<'tcx>) -> Option { + let mut shown = shown.clone(); + if !instance.named.is_empty() { + let spelled: Vec = instance.named.iter().map(|&ty| self.spell(ty.peel_refs())).collect(); + *shown.last_mut().expect("a path has a segment") += &format!("<{}>", spelled.join(", ")); + if self.exclude(&shown) { + return None; + } + } + Some(shown) + } + + /// Each type a function's signature names at `args`, normalized, with what a returned + /// future resolves to. + fn spelled(&self, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Vec> { + let tcx = self.tcx; + let env = TypingEnv::post_analysis(tcx, def_id); + let normalize = |ty: Ty<'tcx>| { + tcx.try_normalize_erasing_regions(env, ty::Unnormalized::new_wip(ty)) + .unwrap_or(ty) + }; + let sig = tcx.fn_sig(def_id).instantiate(tcx, args).skip_norm_wip(); + let sig = tcx.instantiate_bound_regions_with_erased(sig); + let output = self.future_output(normalize(sig.output()), env); + (sig.inputs_and_output.iter().chain(output)) + .map(normalize) + .flat_map(|ty| ty.walk()) + .filter_map(|arg| arg.as_type()) + .collect() } /// The types the exports implement a trait bounding `param` of `def_id` for, one of @@ -965,25 +1053,6 @@ impl<'tcx> Collector<'tcx> { /// A struct's or enum's variants, with their fields mapped. fn fields(&self, site: &Site<'tcx>) -> Result, Vec> { - self.naming(|| self.variants(site)) - } - - /// What `map` makes of a signature or a type's fields, noting each instance it names - /// that is not yet inferred, where those are all it refuses: one an export names is - /// inferred. - fn naming(&self, map: impl FnOnce() -> Result>) -> Result> { - self.pending.borrow_mut().clear(); - let mapped = map(); - let pending = self.pending.take(); - if let Err(why) = &mapped - && why.iter().all(|why| why.construct == UNNAMED) - { - self.named.borrow_mut().extend(pending); - } - mapped - } - - fn variants(&self, site: &Site<'tcx>) -> Result, Vec> { let tcx = self.tcx; let adt = tcx.adt_def(site.key.def_id); let identity = site.args; @@ -1141,7 +1210,7 @@ impl<'tcx> Collector<'tcx> { } // Read through `&self`, so returned as a copy, as a borrowed return is. let read = Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, ty); - match self.naming(|| self.ty(read, Pos::Return).map_err(|why| vec![why])) { + match self.ty(read, Pos::Return) { Ok(ty) => getters.push(Function { path: [&site.path[..], &[name]].concat(), span, @@ -1155,7 +1224,7 @@ impl<'tcx> Collector<'tcx> { access: Access::Field { shared }, instance: None, }), - Err(why) => self.refuse(if shared { &key } else { &shown }, "field", span, why), + Err(why) => self.refuse(if shared { &key } else { &shown }, "field", span, vec![why]), } } getters @@ -1169,49 +1238,28 @@ impl<'tcx> Collector<'tcx> { let mut methods = Vec::new(); let mut refused = Vec::new(); let self_ty = self.site_ty(site); - for &imp in tcx.inherent_impls(def_id) { - let Some(parent) = self.impl_args(imp, self_ty) else { + for (item, parent, shown, hidden) in self.members(site) { + if hidden { + let (report, rest) = self.report(&shown); + report.hidden.push(rest); continue; - }; - for item in tcx.associated_items(imp).in_definition_order() { - let (ty::AssocKind::Fn { name, .. } | ty::AssocKind::Const { name, .. }) = item.kind else { - continue; - }; - if !tcx.visibility(item.def_id).is_public() { - continue; - } - let method = [&site.path[..], &[name.to_string()]].concat(); - let shown = [&site.shown[..], &[name.to_string()]].concat(); - if self.exclude(&shown) { - continue; - } - if tcx.is_doc_hidden(item.def_id) { - let (report, rest) = self.report(&shown); - report.hidden.push(rest); - continue; - } - // As an impl whose bounds fail, a method whose own bounds fail at the - // instance is none of its methods. - if !self.applies(item.def_id, parent) { - continue; - } - let span = tcx.def_span(item.def_id); - if let ty::AssocKind::Const { .. } = item.kind { - // An instance's constant is read in Rust, named through the instance. - let parent = site.key.args.map(|_| parent); - methods.extend(self.constant_item(item.def_id, shown, parent).map(|mut getter| { - getter.path = method; - getter - })); - continue; - } - for (function, shown, instance) in - self.functions(item.def_id, &method, &shown, Some(self_ty), Some(parent)) - { - match function { - Ok(function) => methods.push(function), - Err(why) => refused.push((shown, span, why, instance)), - } + } + let method = [&site.path[..], &[item.name().to_string()]].concat(); + let span = tcx.def_span(item.def_id); + if let ty::AssocKind::Const { .. } = item.kind { + // An instance's constant is read in Rust, named through the instance. + let parent = site.key.args.map(|_| parent); + methods.extend(self.constant_item(item.def_id, shown, parent).map(|mut getter| { + getter.path = method; + getter + })); + continue; + } + for (function, shown, instance) in self.functions(item.def_id, &method, &shown, Some(self_ty), Some(parent)) + { + match function { + Ok(function) => methods.push(function), + Err(why) => refused.push((shown, span, why, instance)), } } } @@ -1254,6 +1302,37 @@ impl<'tcx> Collector<'tcx> { (methods, traits) } + /// A type's inherent `pub` methods and constants the config does not exclude, each with + /// the arguments of its impl, the path reports show it by, and whether it is + /// `doc(hidden)`. One whose own bounds fail at the instance is none of its methods, as + /// is each of an impl whose bounds fail. + fn members(&mut self, site: &Site<'tcx>) -> Vec<(ty::AssocItem, ty::GenericArgsRef<'tcx>, Path, bool)> { + let tcx = self.tcx; + let self_ty = self.site_ty(site); + let mut members = Vec::new(); + for &imp in tcx.inherent_impls(site.key.def_id) { + let Some(parent) = self.impl_args(imp, self_ty) else { + continue; + }; + for &item in tcx.associated_items(imp).in_definition_order() { + if !matches!(item.kind, ty::AssocKind::Fn { .. } | ty::AssocKind::Const { .. }) + || !tcx.visibility(item.def_id).is_public() + { + continue; + } + let shown = [&site.shown[..], &[item.name().to_string()]].concat(); + if self.exclude(&shown) { + continue; + } + let hidden = tcx.is_doc_hidden(item.def_id); + if hidden || self.applies(item.def_id, parent) { + members.push((item, parent, shown, hidden)); + } + } + } + members + } + /// The arguments an inherent impl applies to `self_ty` at, if it does: its type /// parameters as `self_ty` fixes them, its lifetimes as they are, and its bounds met. fn impl_args(&self, imp: DefId, self_ty: Ty<'tcx>) -> Option> { @@ -1279,20 +1358,7 @@ impl<'tcx> Collector<'tcx> { let tcx = self.tcx; let mut args = ty::GenericArgs::identity_for_item(tcx, item).to_vec(); args[..parent.len()].copy_from_slice(parent); - let args = tcx.mk_args(&args); - let env = TypingEnv::post_analysis(tcx, item); - let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(env); - tcx.clauses_of(item) - .instantiate(tcx, args) - .clauses - .iter() - .all(|clause| { - let clause = clause.skip_norm_wip(); - clause.has_non_region_param() || { - let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, clause); - infcx.predicate_must_hold_modulo_regions(&obligation) - } - }) + self.holds(item, tcx.mk_args(&args)) } /// A trait's required methods, as a callback interface. @@ -1375,14 +1441,9 @@ impl<'tcx> Collector<'tcx> { }; let mut functions = Vec::new(); for instance in &instances { - let mut shown = shown.clone(); - if !instance.named.is_empty() { - let spelled: Vec = instance.named.iter().map(|&ty| self.spell(ty.peel_refs())).collect(); - *shown.last_mut().expect("a path has a segment") += &format!("<{}>", spelled.join(", ")); - if self.exclude(&shown) { - continue; - } - } + let Some(shown) = self.shown(shown, instance) else { + continue; + }; let function = self.function(def_id, path.clone(), self_ty, instance); functions.push((function, shown, !instance.named.is_empty())); } @@ -1397,21 +1458,27 @@ impl<'tcx> Collector<'tcx> { path: Path, self_ty: Option>, instance: &Instantiation<'tcx>, - ) -> Result> { - self.naming(|| self.signature(def_id, path, self_ty, instance)) - } - - fn signature( - &self, - def_id: DefId, - path: Path, - self_ty: Option>, - instance: &Instantiation<'tcx>, ) -> Result> { let tcx = self.tcx; let mut errs = Vec::new(); - *self.impls.borrow_mut() = instance.impls.clone(); let args = instance.args; + // Each kept parameter takes a lent closure, if an `Fn` trait bounds it, or else the + // foreign implementation `instantiate` kept it for. + let mut impls = Vec::new(); + for ¶m in &instance.kept { + let taken = self.closure(def_id, param, args).unwrap_or_else(|| { + let callback = self.foreign(def_id, param).expect("a kept parameter takes a callback"); + Ok(Type::Callback(callback, Dyn::Impl)) + }); + match taken { + Ok(taken) => impls.push((param, taken)), + Err(why) => errs.push(why), + } + } + if !errs.is_empty() { + return Err(errs); + } + *self.impls.borrow_mut() = impls; // What the glue names a declared type parameter as, which a call cannot always // infer; an `impl Trait` one cannot be named, and is inferred from its argument. let mut arg = |ty: Ty<'tcx>| { @@ -1428,7 +1495,14 @@ impl<'tcx> Collector<'tcx> { false => { let declared = (tcx.generics_of(def_id).own_params.iter()) .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Type { synthetic: false, .. })); - let args = declared.filter_map(|p| arg(args.type_at(p.index as usize))).collect(); + // A kept parameter is left for Rust to infer from its argument. + let args = declared + .map(|p| args.type_at(p.index as usize)) + .filter_map(|ty| match instance.kept.contains(&ty) { + true => Some(None), + false => arg(ty).map(Some), + }) + .collect(); let named = instance.named.iter().filter_map(|&ty| arg(ty.peel_refs())).collect(); Some(crate::ir::Instance { args, named }) } @@ -1539,9 +1613,12 @@ impl<'tcx> Collector<'tcx> { /// The generic arguments a function is exported with: its parent's (an impl's at the /// instance, or a trait's `Self`, which stays a parameter, as the trait is the - /// callback), lifetimes as they are, which [`Self::borrows`] decides, and each type - /// parameter by the rules in [`Self::choose`], or else at each type [`Self::each`] - /// finds, an instance for each choice where its bounds hold. + /// callback), lifetimes as they are, which [`Self::borrows`] decides, a type parameter + /// an `Fn` trait bounds kept for a lent closure, and each other by the rules in + /// [`Self::choose`], or else kept for a foreign implementation, or else at each type + /// [`Self::each`] finds, an instance for each choice where its bounds hold. While + /// inferring, a parameter takes every type `choose` ranks and every type `each` finds, + /// as typing may take any of them. fn instantiate( &self, def_id: DefId, @@ -1557,29 +1634,25 @@ impl<'tcx> Collector<'tcx> { args[..count].copy_from_slice(parent); } let base = args.clone(); - let mut impls = Vec::new(); + let mut kept = Vec::new(); let mut several = Vec::new(); for (i, arg) in identity.iter().enumerate() { match arg.kind() { _ if i < count => {} GenericArgKind::Lifetime(_) => {} GenericArgKind::Const(_) => errs.push(why("const generic", "")), - // The parameter stays, and `ty` maps it to the closure. - GenericArgKind::Type(param) if let Some(closure) = self.closure(def_id, param, &base) => { - match closure { - Ok(closure) => impls.push((param, closure)), - Err(why) => errs.push(why), - } - } + GenericArgKind::Type(param) if self.lent(def_id, param) => kept.push(param), GenericArgKind::Type(param) => match self.choose(def_id, param, &base) { - Ok(ty) => args[i] = ty.into(), - // The parameter stays, and `ty` maps it to the foreign implementation. + // Typing takes a later type only where an earlier one's export is refused. + Ok(ranked) if self.inferring => { + let last = ranked.iter().position(|&ty| !self.names_export(ty)); + several.push((i, ranked[..last.map_or(ranked.len(), |last| last + 1)].to_vec())); + } + Ok(ranked) => args[i] = ranked[0].into(), Err(Why { construct: "callback bound", .. - }) if let Some(callback) = self.foreign(def_id, param) => { - impls.push((param, Type::Callback(callback, Dyn::Impl))); - } + }) if self.foreign(def_id, param).is_some() => kept.push(param), Err(why) => match self.each(def_id, param, &base)[..] { [] => errs.push(why), ref each => several.push((i, each.to_vec())), @@ -1602,40 +1675,50 @@ impl<'tcx> Collector<'tcx> { }) .collect(); } - let env = TypingEnv::post_analysis(tcx, def_id); - let instances: Vec> = (choices.into_iter()) + let choices: Vec<_> = (choices.into_iter()) .map(|(args, named)| (tcx.mk_args(&args), named)) - .filter(|(args, named)| named.is_empty() || self.holds(def_id, args, env)) + .collect(); + let unmet = self.unmet(def_id, choices[0].0); + let instances: Vec> = (choices.into_iter()) + .filter(|(args, _)| self.holds(def_id, args)) .map(|(args, named)| Instantiation { args, - impls: impls.clone(), + kept: kept.clone(), named, }) .collect(); - match instances.is_empty() { - true => Err(vec![why("generic parameters no choice meets the bounds of", "")]), - false => Ok(instances), + match (instances.is_empty(), unmet) { + (true, Some(unmet)) => Err(vec![why("unmet bound", unmet.to_string())]), + _ => Ok(instances), } } /// Whether `def_id`'s bounds hold at `args`. - fn holds(&self, def_id: DefId, args: ty::GenericArgsRef<'tcx>, env: TypingEnv<'tcx>) -> bool { + fn holds(&self, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> bool { + self.unmet(def_id, args).is_none() + } + + /// The first of `def_id`'s bounds that fails at `args`, skipping each that names a type + /// parameter still one: a kept parameter's, which what the call passes meets, or one + /// not yet chosen's, which the item's own environment states only at its parameters. + fn unmet(&self, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Option> { let tcx = self.tcx; + let env = TypingEnv::post_analysis(tcx, def_id); let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(env); - tcx.clauses_of(def_id) - .instantiate(tcx, args) - .clauses - .iter() - .all(|clause| { - let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, clause.skip_norm_wip()); - infcx.predicate_must_hold_modulo_regions(&obligation) + (tcx.clauses_of(def_id).instantiate(tcx, args).clauses.iter()) + .map(|clause| clause.skip_norm_wip()) + .find(|&clause| { + !clause.has_non_region_param() && { + let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, clause); + !infcx.predicate_must_hold_modulo_regions(&obligation) + } }) } - /// The type a type parameter is exported as: `X` for `impl Into` or - /// `impl AsRef`, else the first of `String`, `Bytes`, and `Vec` meeting its - /// bounds. - fn choose(&self, def_id: DefId, param: Ty<'tcx>, base: &[ty::GenericArg<'tcx>]) -> Result, Why> { + /// The types a type parameter may be exported as, best first, which typing takes the + /// first of: `X` for `impl Into` or `impl AsRef`, then `String`, `Bytes`, and + /// `Vec`, each that meets its bounds and maps. + fn choose(&self, def_id: DefId, param: Ty<'tcx>, base: &[ty::GenericArg<'tcx>]) -> Result>, Why> { let tcx = self.tcx; let clauses = tcx.clauses_of(def_id); let identity = clauses.instantiate(tcx, tcx.mk_args(base)); @@ -1684,11 +1767,11 @@ impl<'tcx> Collector<'tcx> { candidates.push(Ty::new_adt(tcx, tcx.adt_def(vec), args)); } } - for &candidate in &candidates { - // `impl Into>` takes a `String` too, which maps where `Arc` does not. - if self.at(def_id, param, base, candidate).is_some() && self.ty(candidate, Pos::Param).is_ok() { - return Ok(candidate); - } + // `impl Into>` takes a `String` too, which maps where `Arc` does not. + candidates + .retain(|&candidate| self.at(def_id, param, base, candidate).is_some() && self.maps(candidate, Pos::Param)); + if !candidates.is_empty() { + return Ok(candidates); } // A bound on one of the crate's traits takes a foreign implementation. let local: Vec<_> = bounds @@ -1723,8 +1806,7 @@ impl<'tcx> Collector<'tcx> { let mut args = base.to_vec(); args[p.index as usize] = candidate.into(); let args = tcx.mk_args(&args); - self.holds(def_id, args, TypingEnv::post_analysis(tcx, def_id)) - .then_some(args) + self.holds(def_id, args).then_some(args) } /// The types a type parameter exports at each of, where no one type is the rules': @@ -1734,7 +1816,6 @@ impl<'tcx> Collector<'tcx> { /// bounds where 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 env = TypingEnv::post_analysis(tcx, def_id); let at = |candidate: Ty<'tcx>| self.at(def_id, param, base, candidate); // A lifetime bound, such as `'static`, which a reference to a value C passes for the // call cannot meet, though `at` holds modulo regions. @@ -1759,7 +1840,7 @@ impl<'tcx> Collector<'tcx> { }; // `X` and an implementation for `&X` both choose `&X`. let ty = tcx.erase_and_anonymize_regions(ty); - if !found.contains(&ty) && self.ty(ty, Pos::Param).is_ok() { + if !found.contains(&ty) && self.maps(ty, Pos::Param) { found.push(ty); } } @@ -1767,17 +1848,7 @@ impl<'tcx> Collector<'tcx> { ty::Adt(adt, args) if self.exported(adt.did().krate) && self.typed(adt.did()) => Some((adt.did(), args)), _ => None, }; - // Each type the signature names, with what a returned future resolves to. - let spelled = |args: ty::GenericArgsRef<'tcx>| { - let sig = tcx.fn_sig(def_id).instantiate(tcx, args).skip_norm_wip(); - let sig = tcx.instantiate_bound_regions_with_erased(sig); - let output = self.future_output(sig.output(), env); - let types: Vec> = (sig.inputs_and_output.iter().chain(output)) - .flat_map(|ty| ty.walk()) - .filter_map(|arg| arg.as_type()) - .collect(); - types - }; + let spelled = |args| self.spelled(def_id, args); let argument = spelled(tcx.mk_args(base)) .into_iter() .filter_map(exported) @@ -1795,10 +1866,14 @@ impl<'tcx> Collector<'tcx> { continue; }; let named = spelled(args).into_iter().filter_map(exported).all(|(adt, args)| { - matches!( - self.decl(adt, args), - Some(Decl::Record(_) | Decl::Enum(_) | Decl::Object(_)) - ) + 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::Enum(_) | Decl::Object(_)) + ), + } }); if named { found.push(candidate); @@ -1808,6 +1883,27 @@ impl<'tcx> Collector<'tcx> { found } + /// Whether an `Fn` trait bounds a type parameter, which then takes a lent closure. + fn lent(&self, def_id: DefId, param: Ty<'tcx>) -> bool { + let tcx = self.tcx; + (tcx.clauses_of(def_id).instantiate_identity(tcx).clauses.iter()) + .filter_map(|clause| clause.skip_norm_wip().as_trait_clause()) + .any(|pred| pred.self_ty().skip_binder() == param && tcx.fn_trait_kind_from_def_id(pred.def_id()).is_some()) + } + + /// Whether `ty` maps where `pos` puts it. While inferring, before any type is declared, + /// one naming an export's type does. + fn maps(&self, ty: Ty<'tcx>, pos: Pos) -> bool { + (self.inferring && self.names_export(ty)) || self.ty(ty, pos).is_ok() + } + + /// Whether `ty` names an export's type, which maps only once declared. + 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))) + } + /// The closure a type parameter takes, if an `Fn` trait bounds it: one the callee calls /// only during the call, which C lends as a function. A closure that may outlive the /// call, by a lifetime bound or by what the function returns, is refused. @@ -2172,8 +2268,7 @@ impl<'tcx> Collector<'tcx> { tcx.type_of(def_id).instantiate_identity().skip_norm_wip() } }; - // Through `naming`, so an instance only a constant names is inferred. - match self.naming(|| self.ty(ty, Pos::Return).map_err(|why| vec![why])) { + match self.ty(ty, Pos::Return) { Ok(ok) => Some(Function { path, span, @@ -2188,7 +2283,7 @@ impl<'tcx> Collector<'tcx> { instance: None, }), Err(why) => { - self.refuse(&path, "const", span, why); + self.refuse(&path, "const", span, vec![why]); None } } @@ -2338,18 +2433,17 @@ impl<'tcx> Collector<'tcx> { if let Some(construct) = self.left_out.get(&did) { return Err(why(construct, name)); } - if key.args.is_none() { - return Err(why("type not reachable from the crate root", name)); - } if let Some(why) = self.rejected.get(&key) { return Err(why.clone()); } - // Inferred if this is all its export refuses. - self.pending.borrow_mut().push(ty); - let mut why = why(UNNAMED, name); - let note = format!("`{}` exports only at the instances it infers", strip_args(tcx, did)); - why.note = Some((tcx.def_span(did), note)); - return Err(why); + if args.has_non_region_param() { + return Err(why("type parameter", name)); + } + // Inference admits or rejects each instance a signature names. + if key.args.is_some() && self.items.iter().any(|(item, _)| *item == did) { + unreachable!("inference missed the instance `{name}`"); + } + return Err(why("type not reachable from the crate root", name)); } } } @@ -2388,6 +2482,16 @@ 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); + } +} + /// Where a type appears, which decides the forms it may take. #[derive(Clone, Copy, PartialEq, Eq)] enum Pos { diff --git a/ffi/src/glue.rs b/ffi/src/glue.rs index 15bae186b..4925e36b6 100644 --- a/ffi/src/glue.rs +++ b/ffi/src/glue.rs @@ -955,7 +955,9 @@ impl Gen<'_> { None => self.path(&function.path), }; if let Some(instance) = function.instance.as_ref().filter(|i| !i.args.is_empty()) { - let args: Vec = instance.args.iter().map(|ty| self.rust(ty)).collect(); + let args: Vec = (instance.args.iter()) + .map(|ty| ty.as_ref().map_or_else(|| "_".to_string(), |ty| self.rust(ty))) + .collect(); callee = format!("{callee}::<{}>", args.join(", ")); } let call = match function.access { diff --git a/ffi/src/ir.rs b/ffi/src/ir.rs index 1917da348..837f07430 100644 --- a/ffi/src/ir.rs +++ b/ffi/src/ir.rs @@ -167,8 +167,9 @@ pub struct Function { /// exports at. pub struct Instance { /// The arguments of its declared type parameters, which the call names, as Rust - /// cannot infer one no argument names; its argument infers an `impl Trait` one. - pub args: Vec, + /// cannot infer one no argument names; its argument infers an `impl Trait` one, and + /// one left `None`, which takes a lent closure or a foreign implementation. + pub args: Vec>, /// The arguments that tell it from its other instances, which name it. pub named: Vec, } diff --git a/ffi/tests/api.c b/ffi/tests/api.c index ddaf4f863..deac9b1d2 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -55,6 +55,12 @@ static uint32_t seven(void *data) { return 7; } +/* A lent closure of an inferred instance's type. */ +static uint32_t triple(void *data, uint32_t side) { + (void)data; + return side * 3; +} + static uint64_t visit(void *data, const api_cursor *cursor) { (void)data; return api_cursor_at(cursor) * 2; @@ -420,6 +426,12 @@ static int script(void) { api_outer_inner_u8_free(outer); /* A bound that outlives the call takes a value, and an instance only a constant names. */ printf("kept %llu boxed %u\n", (unsigned long long)api_kept_point((api_point){.x = 1, .y = -2}), api_boxed().value); + /* Inferred instances taking a lent closure and a foreign implementation, and one only + * its impl of a trait names. */ + api_pair_u32 sides = {.left = 2, .right = 5}; + printf("apply %u\n", api_apply_u32(sides, triple, NULL)); + printf("report %u\n", api_report_u32(sides, (api_log){.vtable = &print_log})); + printf("wrapped %llu\n", (unsigned long long)api_kept_wrap_u32((api_wrap_u32){.value = 4})); /* Its Drop runs when C frees the handle, not before. */ api_token *token = api_token_new(7); diff --git a/ffi/tests/api.cpp b/ffi/tests/api.cpp index 60cd1072a..cc1c7d768 100644 --- a/ffi/tests/api.cpp +++ b/ffi/tests/api.cpp @@ -352,6 +352,12 @@ int script() { api::outer_inner_u8::new_(4).get()); // A bound that outlives the call takes a value, and an instance only a constant names. std::printf("kept %llu boxed %u\n", ull(api::kept_point({1, -2})), api::boxed().value); + // Inferred instances taking a lent closure and a foreign implementation, and one only + // its impl of a trait names. + api::pair_u32 sides{2, 5}; + std::printf("apply %u\n", api::apply_u32(sides, [](std::uint32_t side) { return side * 3; })); + std::printf("report %u\n", api::report_u32(sides, std::make_unique())); + std::printf("wrapped %llu\n", ull(api::kept_wrap_u32({4}))); // Its Drop runs when C++ destroys the handle, not before. { diff --git a/quest/m1/ffi-export/README.md b/quest/m1/ffi-export/README.md index 48c3f6449..b56623757 100644 --- a/quest/m1/ffi-export/README.md +++ b/quest/m1/ffi-export/README.md @@ -47,7 +47,6 @@ Every generator on the C ABI: ## Required -- [Infer instances in one pass before typing](/quest/m1/ffi-export/inference.md) - generic functions with closures, and concrete instances only a trait impl names, export - [Iterator and JSON arguments the exporter can't map yet](/quest/m1/ffi-export/instance-keys.md) - `IntoIterator` as a `Vec`, and `serde_json::Value` - [moq-clock's C names once it moves into kio](/quest/m1/ffi-export/crates.md) - `moq_now` and `moq_origin` become the clock's, after moq moves it into `kio::clock` - [Setters for an object's pub fields](/quest/m1/ffi-export/field-setters.md) - C fills in a session's config, as Rust assigns it diff --git a/quest/m1/ffi-export/inference.md b/quest/m1/ffi-export/inference.md deleted file mode 100644 index d5ff77b2c..000000000 --- a/quest/m1/ffi-export/inference.md +++ /dev/null @@ -1,24 +0,0 @@ -# [M] Infer instances in one pass before typing - -## Goal - -The exporter infers every instance a generic item exports at in one pass over the exported -crates' signatures, before it maps any type, so mapping a signature never discovers a new -instance. Two cases that inference misses today export: - -- a generic function inferred at an instance that also takes a closure or a foreign - callback, such as `fn apply u32>(p: Pair, f: F)`; -- a generic type's concrete instance that only an impl of an exported trait names, such - as `impl Seed for Wrap` taken by `fn seeded(seed: impl Seed)`. - -Instance names stay the shortest unique form, independent of crate order. - -## Plan - -Decided with the maintainer on 2026-10-28, after -[#152](https://github.com/kixelated/rust2/pull/152): restructure inference so these cases -fall out of the design rather than being patched one by one. Write the design note in the -PR body before coding, and check whether rustc's `rustc_monomorphize::collector` or another -analysis can be reused. - -Public API: none beyond the instances and functions these cases add. diff --git a/quest/m1/ffi-export/instance-keys.md b/quest/m1/ffi-export/instance-keys.md index 7fd539cb9..bb95d6623 100644 --- a/quest/m1/ffi-export/instance-keys.md +++ b/quest/m1/ffi-export/instance-keys.md @@ -19,9 +19,9 @@ hang's `Catalog<()>`. What remains is two type mappings. - `IntoIterator` as a `Vec` needs a `Vec` of records to map first. - `serde_json::Value` crosses the C ABI as something every generator can read; decide - its shape (JSON text is the obvious one) when the quest starts. Today the `T: Serialize` - parameter is refused as a generic parameter, though `String` meets its bound: find out - why first. + its shape (JSON text is the obvious one) when the quest starts. The `T: Serialize` + parameter now takes `String` by the choice rules, which serializes one JSON string + rather than a document; moq's config excludes both methods until then. - Report moq-ffi's coverage and the census before and after. Public API: the C names and types these methods export with. From e199039a6ec3ed42187bfe52e9bb87d12e413fba Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Wed, 28 Oct 2026 14:43:35 -0700 Subject: [PATCH 3/5] fix(ffi): bound inference by arguable instances, and keep callback choices while inferring Inference walks only the members of an instance whose arguments could map, so a method wrapping its argument in a tuple no longer grows instances forever. Before traits are declared, a parameter one exported trait bounds may stay for a foreign implementation, so a signature taking a callback no Rust type implements still names its instances. Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/api/examples/transcript.rs | 1 + ffi/fixtures/api/src/lib.rs | 8 ++++ ffi/fixtures/reject/expected.txt | 28 +++++++------ ffi/fixtures/reject/src/lib.rs | 14 +++++++ ffi/src/collect.rs | 56 +++++++++++++++++++------ ffi/tests/api.c | 1 + ffi/tests/api.cpp | 1 + 7 files changed, 84 insertions(+), 25 deletions(-) diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index b3f30fe4d..9bc2a48d3 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -284,6 +284,7 @@ fn main() { println!("apply {}", api_lib::apply(sides, |side| side * 3)); println!("report {}", api_lib::report(sides, Print)); println!("wrapped {}", api_lib::kept(api_lib::Wrap { value: 4u32 })); + println!("keeps {}", api_lib::keeps(Print).value); let token = api_lib::Token::new(7); println!("token {} dropped {}", token.id, api_lib::dropped()); diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index 081e6b85d..d51d62ae4 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -740,6 +740,14 @@ pub struct Boxed { pub const BOXED: Boxed = Boxed { value: 42 }; +/// Whether `log` kept a line, boxed: an instance only a function taking a foreign +/// implementation names. +pub fn keeps(log: impl Log) -> Boxed { + Boxed { + value: u8::from(log.log(2, "keeps")), + } +} + /// `from`'s weight. pub fn weigh(from: impl Seed) -> u32 { from.seed() diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index c3c52530f..404feb639 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -12,20 +12,22 @@ fixtures/reject/src/lib.rs:149:1: rust2-ffi: cannot export instance `Cell::nest`: instance holding an instance of a type inside it `reject_fixture::Cell>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:178:2: rust2-ffi: cannot export method `Pong>::ping`: instance holding an instance of a type inside it `reject_fixture::Ping>>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:188:1: rust2-ffi: cannot export fn `excluded_cell`: excluded type `reject_fixture::Cell`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:193:1: rust2-ffi: cannot export fn `listed`: refused type `reject_fixture::Cell>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:198:1: rust2-ffi: cannot export struct `Fixed`: generic type; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:189:1: rust2-ffi: cannot export instance `Grow<(u32,)>`: tuple; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:192:2: rust2-ffi: cannot export method `Grow::grow`: refused type `reject_fixture::Grow<(u32,)>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:19:1: rust2-ffi: cannot export fn `generic`: generic parameter `std::marker::Copy`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:201:1: rust2-ffi: cannot export fn `fixed`: const generic `reject_fixture::Fixed`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:206:9: rust2-ffi: cannot export use `HashSet`: re-export of another crate's item `std`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:209:1: rust2-ffi: cannot export fn `lend`: Waker outside a parameter taken by value; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:224:2: rust2-ffi: fn `reject_fixture::Limit::max` and field `reject_fixture::Limit::max` are both `reject_limit_max` in C - fixtures/reject/src/lib.rs:216:2: note: field `reject_fixture::Limit::max` is here -fixtures/reject/src/lib.rs:230:1: rust2-ffi: cannot export fn `spawn`: closure kept past the call `impl FnOnce() + Send + 'static`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:235:1: rust2-ffi: cannot export fn `later`: closure kept past the call `impl FnOnce()`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:240:1: rust2-ffi: cannot export fn `twice`: closure bound `std::clone::Clone`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:246:1: rust2-ffi: cannot export fn `both`: closure type taken twice `F`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:252:1: rust2-ffi: cannot export fn `read`: lent object that borrows `&Text<'_>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:202:1: rust2-ffi: cannot export fn `excluded_cell`: excluded type `reject_fixture::Cell`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:207:1: rust2-ffi: cannot export fn `listed`: refused type `reject_fixture::Cell>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:212:1: rust2-ffi: cannot export struct `Fixed`: generic type; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:215:1: rust2-ffi: cannot export fn `fixed`: const generic `reject_fixture::Fixed`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:220:9: rust2-ffi: cannot export use `HashSet`: re-export of another crate's item `std`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:223:1: rust2-ffi: cannot export fn `lend`: Waker outside a parameter taken by value; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:238:2: rust2-ffi: fn `reject_fixture::Limit::max` and field `reject_fixture::Limit::max` are both `reject_limit_max` in C + fixtures/reject/src/lib.rs:230:2: note: field `reject_fixture::Limit::max` is here +fixtures/reject/src/lib.rs:244:1: rust2-ffi: cannot export fn `spawn`: closure kept past the call `impl FnOnce() + Send + 'static`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:249:1: rust2-ffi: cannot export fn `later`: closure kept past the call `impl FnOnce()`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:254:1: rust2-ffi: cannot export fn `twice`: closure bound `std::clone::Clone`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:260:1: rust2-ffi: cannot export fn `both`: closure type taken twice `F`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:266:1: rust2-ffi: cannot export fn `read`: lent object that borrows `&Text<'_>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:26:1: rust2-ffi: cannot export fn `borrowing`: borrowing future from a function that is not async; exclude it in the config to leave it out fixtures/reject/src/lib.rs:31:1: rust2-ffi: cannot export fn `nested`: nested Option `std::option::Option>>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:40:1: rust2-ffi: cannot export fn `peek`: reference to a handle inside a value `std::boxed::Box`; exclude it in the config to leave it out diff --git a/ffi/fixtures/reject/src/lib.rs b/ffi/fixtures/reject/src/lib.rs index 2e04ef1fc..2ad5aa854 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -184,6 +184,20 @@ pub fn ping(value: u8) -> Ping { Ping(value) } +/// A generic type whose method wraps its argument in a tuple: `Grow<(u32,)>` is refused, +/// as a tuple is no type argument, so inference names nothing through its `grow`. +pub struct Grow(T); + +impl Grow { + pub fn grow(self) -> Grow<(T,)> { + Grow((self.0,)) + } +} + +pub fn grow(value: u32) -> Grow { + Grow(value) +} + /// An instance the config excludes. pub fn excluded_cell(cell: Cell) -> u16 { cell.0 diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index ee997647b..9c3d2c87e 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -475,7 +475,9 @@ impl<'tcx> Collector<'tcx> { _ => {} } } - sites.extend(self.instances.clone()); + // Typing refuses an instance whose arguments cannot name one, and maps none of its + // members, which could name ever larger instances, as `Grow<(T,)>` from `Grow`. + sites.extend((self.instances.iter()).filter(|site| self.arguable(site)).cloned()); for site in sites { let adt = tcx.adt_def(site.key.def_id); // An object's private fields are no part of its API. @@ -494,6 +496,19 @@ impl<'tcx> Collector<'tcx> { named } + /// Whether each type argument an instance is named by could map as [`Self::arg`] + /// requires: `()`, a primitive, `String`, or an export's type. + fn arguable(&self, site: &Site<'tcx>) -> bool { + let tcx = self.tcx; + site.args.types().take(site.explicit).all(|ty| match ty.kind() { + ty::Tuple(list) => list.is_empty(), + ty::Bool | ty::Char | ty::Float(_) => true, + ty::Int(_) | ty::Uint(_) => int(ty).is_some(), + ty::Adt(adt, _) => tcx.lang_items().string() == Some(adt.did()) || self.exported(adt.did().krate), + _ => false, + }) + } + /// The types a function's signature names, bounds included, at each instantiation it /// is not excluded at. fn instantiated(&mut self, def_id: DefId, shown: &Path, parent: Option>) -> Vec> { @@ -1467,7 +1482,7 @@ impl<'tcx> Collector<'tcx> { let mut impls = Vec::new(); for ¶m in &instance.kept { let taken = self.closure(def_id, param, args).unwrap_or_else(|| { - let callback = self.foreign(def_id, param).expect("a kept parameter takes a callback"); + let callback = self.taken(def_id, param).expect("a kept parameter takes a callback"); Ok(Type::Callback(callback, Dyn::Impl)) }); match taken { @@ -1652,11 +1667,18 @@ impl<'tcx> Collector<'tcx> { Err(Why { construct: "callback bound", .. - }) if self.foreign(def_id, param).is_some() => kept.push(param), - Err(why) => match self.each(def_id, param, &base)[..] { - [] => errs.push(why), - ref each => several.push((i, each.to_vec())), - }, + }) if self.taken(def_id, param).is_some() => kept.push(param), + Err(why) => { + let mut each = self.each(def_id, param, &base); + // Before any trait is declared, it may stay for a foreign implementation. + if self.inferring && self.foreign(def_id, param).is_some() { + each.push(param); + } + match each[..] { + [] => errs.push(why), + _ => several.push((i, each)), + } + } }, } } @@ -2004,9 +2026,10 @@ impl<'tcx> Collector<'tcx> { Some(Ok(Type::Closure(params, Box::new(ret)))) } - /// The callback a type parameter takes a foreign implementation of: one bounded by a - /// single exported trait, and otherwise only by what that implementation meets. - fn foreign(&self, def_id: DefId, param: Ty<'tcx>) -> Option { + /// The trait a type parameter may take a foreign implementation of: one bounded by a + /// single exported trait without type parameters, and otherwise only by what that + /// implementation meets. It does once the trait is declared a callback. + fn foreign(&self, def_id: DefId, param: Ty<'tcx>) -> Option { let tcx = self.tcx; let mut callback = None; for clause in tcx.clauses_of(def_id).instantiate_identity(tcx).clauses { @@ -2017,8 +2040,9 @@ impl<'tcx> Collector<'tcx> { continue; } let tr = bound.def_id(); - match self.trait_decl(tr) { - Some(Decl::Callback(i)) if callback.is_none() => callback = Some(*i), + let exported = self.items.iter().any(|(item, _)| *item == tr) && !self.typed(tr); + match callback { + None if tcx.def_kind(tr) == DefKind::Trait && exported => callback = Some(tr), _ if marker(tcx, tr) => {} _ => return None, } @@ -2026,6 +2050,14 @@ impl<'tcx> Collector<'tcx> { callback } + /// The callback a type parameter takes a foreign implementation of, as declared. + fn taken(&self, def_id: DefId, param: Ty<'tcx>) -> Option { + match self.trait_decl(self.foreign(def_id, param)?) { + Some(Decl::Callback(i)) => Some(*i), + _ => None, + } + } + /// What `ty` resolves to when awaited, if it is a future. fn future_output(&self, ty: Ty<'tcx>, env: TypingEnv<'tcx>) -> Option> { let tcx = self.tcx; diff --git a/ffi/tests/api.c b/ffi/tests/api.c index deac9b1d2..d72be32a3 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -432,6 +432,7 @@ static int script(void) { printf("apply %u\n", api_apply_u32(sides, triple, NULL)); printf("report %u\n", api_report_u32(sides, (api_log){.vtable = &print_log})); printf("wrapped %llu\n", (unsigned long long)api_kept_wrap_u32((api_wrap_u32){.value = 4})); + printf("keeps %u\n", api_keeps((api_log){.vtable = &print_log}).value); /* Its Drop runs when C frees the handle, not before. */ api_token *token = api_token_new(7); diff --git a/ffi/tests/api.cpp b/ffi/tests/api.cpp index cc1c7d768..1b5f805fd 100644 --- a/ffi/tests/api.cpp +++ b/ffi/tests/api.cpp @@ -358,6 +358,7 @@ int script() { std::printf("apply %u\n", api::apply_u32(sides, [](std::uint32_t side) { return side * 3; })); std::printf("report %u\n", api::report_u32(sides, std::make_unique())); std::printf("wrapped %llu\n", ull(api::kept_wrap_u32({4}))); + std::printf("keeps %u\n", api::keeps(std::make_unique()).value); // Its Drop runs when C++ destroys the handle, not before. { From 29d81a110e959c6bf0dbeb91ee510d2d0f37fd7f Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Wed, 28 Oct 2026 14:51:29 -0700 Subject: [PATCH 4/5] fix(ffi): refuse an instance whose arguments cannot name one before mapping its fields Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/reject/expected.txt | 33 +++++++++++++++++--------------- ffi/fixtures/reject/src/lib.rs | 18 +++++++++++++++++ ffi/src/collect.rs | 33 +++++++++++++++++++------------- 3 files changed, 56 insertions(+), 28 deletions(-) diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index 404feb639..5fb61a657 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -8,27 +8,30 @@ fixtures/reject/src/lib.rs:113:2: rust2-ffi: cannot export method `Text::replace fixtures/reject/src/lib.rs:118:2: rust2-ffi: cannot export method `Text::later`: returned object that borrows `impl std::future::Future>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:125:1: rust2-ffi: cannot export fn `either`: reference inside a parameter `std::option::Option<&str>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:130:1: rust2-ffi: cannot export struct `Lease`: object no export returns; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:149:1: rust2-ffi: cannot export instance `Cell>`: Vec `std::string::String`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:149:1: rust2-ffi: cannot export instance `Cell>`: type argument `std::vec::Vec`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:14:1: rust2-ffi: cannot export fn `map`: foreign type `std::collections::HashMap`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:159:2: rust2-ffi: cannot export method `Cell::nest`: instance holding an instance of a type inside it `reject_fixture::Cell>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:178:2: rust2-ffi: cannot export method `Pong>::ping`: instance holding an instance of a type inside it `reject_fixture::Ping>>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:189:1: rust2-ffi: cannot export instance `Grow<(u32,)>`: tuple; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:189:1: rust2-ffi: cannot export instance `Grow<(u32,)>`: type argument `(u32,)`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:192:2: rust2-ffi: cannot export method `Grow::grow`: refused type `reject_fixture::Grow<(u32,)>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:19:1: rust2-ffi: cannot export fn `generic`: generic parameter `std::marker::Copy`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:202:1: rust2-ffi: cannot export fn `excluded_cell`: excluded type `reject_fixture::Cell`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:207:1: rust2-ffi: cannot export fn `listed`: refused type `reject_fixture::Cell>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:212:1: rust2-ffi: cannot export struct `Fixed`: generic type; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:215:1: rust2-ffi: cannot export fn `fixed`: const generic `reject_fixture::Fixed`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:220:9: rust2-ffi: cannot export use `HashSet`: re-export of another crate's item `std`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:223:1: rust2-ffi: cannot export fn `lend`: Waker outside a parameter taken by value; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:238:2: rust2-ffi: fn `reject_fixture::Limit::max` and field `reject_fixture::Limit::max` are both `reject_limit_max` in C - fixtures/reject/src/lib.rs:230:2: note: field `reject_fixture::Limit::max` is here -fixtures/reject/src/lib.rs:244:1: rust2-ffi: cannot export fn `spawn`: closure kept past the call `impl FnOnce() + Send + 'static`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:249:1: rust2-ffi: cannot export fn `later`: closure kept past the call `impl FnOnce()`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:254:1: rust2-ffi: cannot export fn `twice`: closure bound `std::clone::Clone`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:260:1: rust2-ffi: cannot export fn `both`: closure type taken twice `F`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:266:1: rust2-ffi: cannot export fn `read`: lent object that borrows `&Text<'_>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:203:1: rust2-ffi: cannot export instance `Shell<(u32,)>`: type argument `(u32,)`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:208:1: rust2-ffi: cannot export struct `Core`: generic type; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:212:1: rust2-ffi: cannot export fn `shell`: refused type `reject_fixture::Shell<(u32,)>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:220:1: rust2-ffi: cannot export fn `excluded_cell`: excluded type `reject_fixture::Cell`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:225:1: rust2-ffi: cannot export fn `listed`: refused type `reject_fixture::Cell>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:230:1: rust2-ffi: cannot export struct `Fixed`: generic type; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:233:1: rust2-ffi: cannot export fn `fixed`: const generic `reject_fixture::Fixed`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:238:9: rust2-ffi: cannot export use `HashSet`: re-export of another crate's item `std`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:241:1: rust2-ffi: cannot export fn `lend`: Waker outside a parameter taken by value; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:256:2: rust2-ffi: fn `reject_fixture::Limit::max` and field `reject_fixture::Limit::max` are both `reject_limit_max` in C + fixtures/reject/src/lib.rs:248:2: note: field `reject_fixture::Limit::max` is here +fixtures/reject/src/lib.rs:262:1: rust2-ffi: cannot export fn `spawn`: closure kept past the call `impl FnOnce() + Send + 'static`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:267:1: rust2-ffi: cannot export fn `later`: closure kept past the call `impl FnOnce()`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:26:1: rust2-ffi: cannot export fn `borrowing`: borrowing future from a function that is not async; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:272:1: rust2-ffi: cannot export fn `twice`: closure bound `std::clone::Clone`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:278:1: rust2-ffi: cannot export fn `both`: closure type taken twice `F`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:284:1: rust2-ffi: cannot export fn `read`: lent object that borrows `&Text<'_>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:31:1: rust2-ffi: cannot export fn `nested`: nested Option `std::option::Option>>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:40:1: rust2-ffi: cannot export fn `peek`: reference to a handle inside a value `std::boxed::Box`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:45:1: rust2-ffi: cannot export static `COUNT`: static; exclude it in the config to leave it out diff --git a/ffi/fixtures/reject/src/lib.rs b/ffi/fixtures/reject/src/lib.rs index 2ad5aa854..2dc5564d7 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -198,6 +198,24 @@ pub fn grow(value: u32) -> Grow { Grow(value) } +/// A record whose instance at a tuple is refused before its fields map, so `Core`, +/// which only those fields name, is neither inferred nor needed. +pub struct Shell { + pub core: Core, + pub tag: T, +} + +pub struct Core { + pub value: T, +} + +pub fn shell() -> Shell<(u32,)> { + Shell { + core: Core { value: 1 }, + tag: (2,), + } +} + /// An instance the config excludes. pub fn excluded_cell(cell: Cell) -> u16 { cell.0 diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 9c3d2c87e..38a46b95a 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -475,9 +475,13 @@ impl<'tcx> Collector<'tcx> { _ => {} } } - // Typing refuses an instance whose arguments cannot name one, and maps none of its - // members, which could name ever larger instances, as `Grow<(T,)>` from `Grow`. - sites.extend((self.instances.iter()).filter(|site| self.arguable(site)).cloned()); + // `declare` refuses an instance whose arguments cannot name one, before mapping any + // of its members, which could name ever larger instances, as `Grow<(T,)>` does. + sites.extend( + (self.instances.iter()) + .filter(|site| self.unarguable(site).is_none()) + .cloned(), + ); for site in sites { let adt = tcx.adt_def(site.key.def_id); // An object's private fields are no part of its API. @@ -496,16 +500,16 @@ impl<'tcx> Collector<'tcx> { named } - /// Whether each type argument an instance is named by could map as [`Self::arg`] - /// requires: `()`, a primitive, `String`, or an export's type. - fn arguable(&self, site: &Site<'tcx>) -> bool { + /// The first type argument an instance is named by that cannot map as [`Self::arg`] + /// requires, which is `()`, a primitive, `String`, or an export's type. + fn unarguable(&self, site: &Site<'tcx>) -> Option> { let tcx = self.tcx; - site.args.types().take(site.explicit).all(|ty| match ty.kind() { - ty::Tuple(list) => list.is_empty(), - ty::Bool | ty::Char | ty::Float(_) => true, - ty::Int(_) | ty::Uint(_) => int(ty).is_some(), - ty::Adt(adt, _) => tcx.lang_items().string() == Some(adt.did()) || self.exported(adt.did().krate), - _ => false, + site.args.types().take(site.explicit).find(|&ty| match ty.kind() { + ty::Tuple(list) => !list.is_empty(), + ty::Bool | ty::Char | ty::Float(_) => false, + ty::Int(_) | ty::Uint(_) => int(ty).is_none(), + ty::Adt(adt, _) => tcx.lang_items().string() != Some(adt.did()) && !self.exported(adt.did().krate), + _ => true, }) } @@ -763,7 +767,10 @@ impl<'tcx> Collector<'tcx> { continue; } for site in self.sites(def_id, &path) { - let decl = self.declare_site(&site); + let decl = match self.unarguable(&site) { + Some(ty) => Decl::Refused(why("type argument", self.spell(ty))), + None => self.declare_site(&site), + }; self.decls.insert(site.key, decl); } } From 242bde4056d25c47b5469c09cefe5a581ab2d886 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Wed, 28 Oct 2026 15:03:04 -0700 Subject: [PATCH 5/5] fix(ffi): refuse an instance inference missed, and stop instantiating at the first refusal An instance typing meets that inference did not admit is now refused at the item's span as `instance not inferred`, with a note at the generic type, so a gap in inference shows in the census instead of crashing the exporter. A candidate typing tries and finds uninferred is rejected. `instantiate` returns at its first refusal, as inference does, so it maps no later parameter's candidates. Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/reject/expected.txt | 28 +++++++++++++++------------- ffi/fixtures/reject/src/lib.rs | 8 ++++++++ ffi/src/collect.rs | 22 ++++++++++++---------- 3 files changed, 35 insertions(+), 23 deletions(-) diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index 5fb61a657..99454bb6c 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -18,20 +18,22 @@ fixtures/reject/src/lib.rs:19:1: rust2-ffi: cannot export fn `generic`: generic fixtures/reject/src/lib.rs:203:1: rust2-ffi: cannot export instance `Shell<(u32,)>`: type argument `(u32,)`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:208:1: rust2-ffi: cannot export struct `Core`: generic type; exclude it in the config to leave it out fixtures/reject/src/lib.rs:212:1: rust2-ffi: cannot export fn `shell`: refused type `reject_fixture::Shell<(u32,)>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:220:1: rust2-ffi: cannot export fn `excluded_cell`: excluded type `reject_fixture::Cell`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:225:1: rust2-ffi: cannot export fn `listed`: refused type `reject_fixture::Cell>`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:230:1: rust2-ffi: cannot export struct `Fixed`: generic type; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:233:1: rust2-ffi: cannot export fn `fixed`: const generic `reject_fixture::Fixed`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:238:9: rust2-ffi: cannot export use `HashSet`: re-export of another crate's item `std`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:241:1: rust2-ffi: cannot export fn `lend`: Waker outside a parameter taken by value; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:256:2: rust2-ffi: fn `reject_fixture::Limit::max` and field `reject_fixture::Limit::max` are both `reject_limit_max` in C - fixtures/reject/src/lib.rs:248:2: note: field `reject_fixture::Limit::max` is here -fixtures/reject/src/lib.rs:262:1: rust2-ffi: cannot export fn `spawn`: closure kept past the call `impl FnOnce() + Send + 'static`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:267:1: rust2-ffi: cannot export fn `later`: closure kept past the call `impl FnOnce()`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:221:1: rust2-ffi: cannot export struct `Probe`: generic type; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:223:1: rust2-ffi: cannot export fn `probe`: const generic; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:228:1: rust2-ffi: cannot export fn `excluded_cell`: excluded type `reject_fixture::Cell`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:233:1: rust2-ffi: cannot export fn `listed`: refused type `reject_fixture::Cell>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:238:1: rust2-ffi: cannot export struct `Fixed`: generic type; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:241:1: rust2-ffi: cannot export fn `fixed`: const generic `reject_fixture::Fixed`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:246:9: rust2-ffi: cannot export use `HashSet`: re-export of another crate's item `std`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:249:1: rust2-ffi: cannot export fn `lend`: Waker outside a parameter taken by value; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:264:2: rust2-ffi: fn `reject_fixture::Limit::max` and field `reject_fixture::Limit::max` are both `reject_limit_max` in C + fixtures/reject/src/lib.rs:256:2: note: field `reject_fixture::Limit::max` is here fixtures/reject/src/lib.rs:26:1: rust2-ffi: cannot export fn `borrowing`: borrowing future from a function that is not async; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:272:1: rust2-ffi: cannot export fn `twice`: closure bound `std::clone::Clone`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:278:1: rust2-ffi: cannot export fn `both`: closure type taken twice `F`; exclude it in the config to leave it out -fixtures/reject/src/lib.rs:284:1: rust2-ffi: cannot export fn `read`: lent object that borrows `&Text<'_>`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:270:1: rust2-ffi: cannot export fn `spawn`: closure kept past the call `impl FnOnce() + Send + 'static`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:275:1: rust2-ffi: cannot export fn `later`: closure kept past the call `impl FnOnce()`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:280:1: rust2-ffi: cannot export fn `twice`: closure bound `std::clone::Clone`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:286:1: rust2-ffi: cannot export fn `both`: closure type taken twice `F`; exclude it in the config to leave it out +fixtures/reject/src/lib.rs:292:1: rust2-ffi: cannot export fn `read`: lent object that borrows `&Text<'_>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:31:1: rust2-ffi: cannot export fn `nested`: nested Option `std::option::Option>>`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:40:1: rust2-ffi: cannot export fn `peek`: reference to a handle inside a value `std::boxed::Box`; exclude it in the config to leave it out fixtures/reject/src/lib.rs:45:1: rust2-ffi: cannot export static `COUNT`: static; exclude it in the config to leave it out diff --git a/ffi/fixtures/reject/src/lib.rs b/ffi/fixtures/reject/src/lib.rs index 2dc5564d7..b8aac2ede 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -216,6 +216,14 @@ pub fn shell() -> Shell<(u32,)> { } } +/// A const generic function whose bound names an instance nothing else does: refused at +/// its const parameter, before any candidate for the other is mapped. +pub struct Probe(T); + +pub fn probe(x: impl Into>) { + let _ = x; +} + /// An instance the config excludes. pub fn excluded_cell(cell: Cell) -> u16 { cell.0 diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 38a46b95a..72be6a09e 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -1649,7 +1649,6 @@ impl<'tcx> Collector<'tcx> { let tcx = self.tcx; let generics = tcx.generics_of(def_id); let identity = ty::GenericArgs::identity_for_item(tcx, def_id); - let mut errs = Vec::new(); let mut args: Vec> = identity.to_vec(); let count = generics.parent_count; if let Some(parent) = parent { @@ -1662,7 +1661,8 @@ impl<'tcx> Collector<'tcx> { match arg.kind() { _ if i < count => {} GenericArgKind::Lifetime(_) => {} - GenericArgKind::Const(_) => errs.push(why("const generic", "")), + // The first refusal ends it, before any later parameter's candidates are mapped. + GenericArgKind::Const(_) => return Err(vec![why("const generic", "")]), GenericArgKind::Type(param) if self.lent(def_id, param) => kept.push(param), GenericArgKind::Type(param) => match self.choose(def_id, param, &base) { // Typing takes a later type only where an earlier one's export is refused. @@ -1681,17 +1681,14 @@ impl<'tcx> Collector<'tcx> { if self.inferring && self.foreign(def_id, param).is_some() { each.push(param); } - match each[..] { - [] => errs.push(why), - _ => several.push((i, each)), + if each.is_empty() { + return Err(vec![why]); } + several.push((i, each)); } }, } } - if !errs.is_empty() { - return Err(errs); - } let mut choices = vec![(args, Vec::new())]; for (i, each) in several { choices = (choices.into_iter()) @@ -2478,9 +2475,14 @@ impl<'tcx> Collector<'tcx> { if args.has_non_region_param() { return Err(why("type parameter", name)); } - // Inference admits or rejects each instance a signature names. + // Inference admits or rejects each instance a signature names, so one + // it did not is a gap in inference, which the census counts. if key.args.is_some() && self.items.iter().any(|(item, _)| *item == did) { - unreachable!("inference missed the instance `{name}`"); + let mut why = why("instance not inferred", name); + let note = + format!("`{}` exports only at the instances it infers", strip_args(tcx, did)); + why.note = Some((tcx.def_span(did), note)); + return Err(why); } return Err(why("type not reachable from the crate root", name)); }