Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions ffi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,11 @@ refused, and the census counts why.
name. A type instance's methods are named through it, and a function instance appends
its arguments' names, a reference's by what it borrows. An `exclude` of a type or method
by the generic type's path leaves it out of every instance, and by the instance's path
(`"catalog::Producer<moq_mux::catalog::hang::Extra>::stats"`) out of that one; a
`rename` by the generic item's path renames each of its instances.
(`"catalog::Producer<moq_mux::catalog::hang::Extra>::stats"`) out of that one. A
`rename` matches paths as `exclude` does: by the generic item's path it renames each of
its instances, and by an instance's path (`"catalog::Producer<moq_mux::catalog::hang::Extra>"`)
that one alone, whose arguments then add nothing to its name, while the others keep
theirs. The longer path wins, and at one length, the instance's.

## C++

Expand Down
5 changes: 4 additions & 1 deletion ffi/fixtures/api/ffi.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,12 @@ exclude = [
"Timed",
]

# The field `Retry::limit`, whose name its method takes.
# The field `Retry::limit`, whose name its method takes, and one instance each of `Pair`
# and `Counter::seeded`, whose other instances keep their names.
[rename]
"Counter::seeded<dep_fixture::Size>" = "counter_from_size"
"field@Retry::limit" = "retry_limit_setting"
"Pair<dep_fixture::Size, u8>" = "size_tag"

# Exported into the same library: `grow` names its types.
[crates.dep-fixture]
Expand Down
1 change: 1 addition & 0 deletions ffi/fixtures/reject/expected.txt
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,5 @@ fixtures/reject/src/lib.rs:92:1: rust2-ffi: cannot export fn `retext`: 'static b
fixtures/reject/src/lib.rs:92:15: note: `'a` is `'static`, as a handle outlives every call
fixtures/reject/src/lib.rs:97:1: rust2-ffi: cannot export fn `first`: borrowed return that is not Clone `Opaque`; exclude it in the config to leave it out
fixtures/reject/src/lib.rs:9:1: rust2-ffi: cannot export fn `pair`: tuple of references `(&str, u8)`; exclude it in the config to leave it out
no span: rust2-ffi: rename `Cell<u16>` in the config names nothing exported
no span: rust2-ffi: rename `field@Limit::min` in the config names nothing exported
3 changes: 2 additions & 1 deletion ffi/fixtures/reject/ffi.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ prefix = "reject"
# An exclusion leaves an item or an instance out, so nothing refuses it.
exclude = ["Cell<u16>", "Excluded", "Held"]

# A field that is none: `min` names nothing of `Limit`.
# A field that is none: `min` names nothing of `Limit`. An instance the config leaves out.
[rename]
"Cell<u16>" = "short_cell"
"field@Limit::min" = "limit_min"

# Another export, whose `Size` claims the same C name as this one's.
Expand Down
105 changes: 68 additions & 37 deletions ffi/src/abi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use std::collections::{BTreeMap, HashMap};

use rustc_span::Span;

use crate::config;
use crate::ir::{Access, Api, Dyn, Function, Int, Receiver, Type};

/// A C name claimed twice: the name, then what claimed it first and second.
Expand Down Expand Up @@ -92,7 +93,7 @@ pub struct Abi<'a> {
pub api: &'a Api,
pub prefix: String,
/// C names for Rust paths, each starting with its crate's name, in place of the
/// rule's: an item's, and its methods' through it.
/// rule's: an item's, and its methods' through it, or an instance's alone.
rename: &'a BTreeMap<String, String>,
/// The renamed paths some name went through.
renamed: std::cell::RefCell<std::collections::BTreeSet<String>>,
Expand Down Expand Up @@ -134,34 +135,52 @@ impl<'a> Abi<'a> {

/// The C name for a Rust path, which starts with its crate's name.
pub fn name(&self, path: &[String]) -> String {
std::iter::once(self.prefix.clone())
.chain(self.segments(path))
.collect::<Vec<_>>()
.join("_")
self.named(path).0
}

/// The segments of a Rust path's C name after the prefix: a renamed part as one, then
/// each segment past it in snake case.
fn segments(&self, path: &[String]) -> Vec<String> {
/// The C name for the item at `shown`, its path with its instances' arguments, and
/// whether a rename named the instance it is alone, which no suffix then names.
fn named(&self, shown: &[String]) -> (String, bool) {
let (segments, alone) = self.segments(shown);
let name = std::iter::once(self.prefix.clone()).chain(segments).collect::<Vec<_>>();
(name.join("_"), alone)
}

/// The segments of the C name of the item at `shown` after the prefix: the longest
/// renamed part, as `exclude` matches it, as one, then each segment past it in snake
/// case; and whether the rename named the instance it is alone.
fn segments(&self, shown: &[String]) -> (Vec<String>, bool) {
let mut segments = Vec::new();
let mut rest = &path[1..];
for len in (2..=path.len()).rev() {
let key = path[..len].join("::");
let mut rest = &shown[1..];
let mut alone = false;
for (len, key) in config::keys(shown).take_while(|&(len, _)| len >= 2) {
if let Some(renamed) = self.rename.get(&key) {
alone = len == shown.len() && key.ends_with('>');
self.renamed.borrow_mut().insert(key);
segments.push(renamed.clone());
rest = &path[len..];
rest = &shown[len..];
break;
}
// No config names a foreign type, which is named by its role instead.
if key == "serde_json::Value" {
segments.push("json".to_string());
rest = &path[len..];
rest = &shown[len..];
break;
}
}
segments.extend(rest.iter().map(|segment| snake(segment)));
segments
segments.extend(
rest.iter()
.map(|segment| snake(segment.split('<').next().unwrap_or(segment))),
);
(segments, alone)
}

/// The key, with `prefix` before it, of the rename naming the item at `shown` itself
/// rather than a module or type it is in.
fn renames(&self, shown: &[String], prefix: &str) -> Option<String> {
(config::keys(shown).take_while(|&(len, _)| len == shown.len()))
.map(|(_, key)| format!("{prefix}{key}"))
.find(|key| self.rename.contains_key(key))
}

/// The config's renames that name nothing exported.
Expand All @@ -180,22 +199,29 @@ impl<'a> Abi<'a> {
}

pub fn record(&self, i: usize) -> String {
self.type_instance(&self.api.records[i].path, &self.api.records[i].args)
let item = &self.api.records[i];
self.type_instance(&item.path, &item.shown, &item.args)
}

pub fn enumeration(&self, i: usize) -> String {
self.type_instance(&self.api.enums[i].path, &self.api.enums[i].args)
let item = &self.api.enums[i];
self.type_instance(&item.path, &item.shown, &item.args)
}

pub fn object(&self, i: usize) -> String {
self.type_instance(&self.api.objects[i].path, &self.api.objects[i].args)
let item = &self.api.objects[i];
self.type_instance(&item.path, &item.shown, &item.args)
}

/// The C name of the instance of the type at `path` at `args`, among the type's every
/// instance, whichever kind each is.
fn type_instance(&self, path: &[String], args: &[Type]) -> String {
/// The C name of the instance of the type at `path` at `args`, shown as `shown`, among
/// the type's every instance, whichever kind each is.
fn type_instance(&self, path: &[String], shown: &[String], args: &[Type]) -> String {
let api = self.api;
self.instance(false, self.name(path), args, || {
let (name, alone) = self.named(shown);
if alone {
return name;
}
self.instance(false, name, args, || {
let records = api.records.iter().map(|r| (&r.path, &r.args));
let enums = api.enums.iter().map(|e| (&e.path, &e.args));
let objects = api.objects.iter().map(|o| (&o.path, &o.args));
Expand Down Expand Up @@ -232,14 +258,17 @@ impl<'a> Abi<'a> {
/// instance's name, so two items whose instances name each other, as `A<B<u8>>` and
/// `B<A<u8>>`, name each without the other.
fn arg_forms(&self, ty: &Type) -> Vec<String> {
let (path, args) = match ty {
Type::Record(i) => (&self.api.records[*i].path, &self.api.records[*i].args),
Type::Enum(i) => (&self.api.enums[*i].path, &self.api.enums[*i].args),
Type::Object(i) => (&self.api.objects[*i].path, &self.api.objects[*i].args),
let (shown, args) = match ty {
Type::Record(i) => (&self.api.records[*i].shown, &self.api.records[*i].args),
Type::Enum(i) => (&self.api.enums[*i].shown, &self.api.enums[*i].args),
Type::Object(i) => (&self.api.objects[*i].shown, &self.api.objects[*i].args),
Type::Ref(_, inner) | Type::Box(inner) => return self.arg_forms(inner),
ty => return vec![self.key(ty)],
};
let segments = self.segments(path);
let (segments, alone) = self.segments(shown);
if alone {
return segments;
}
let nested: Vec<Vec<String>> = args.iter().map(|arg| self.arg_forms(arg)).collect();
let steps = nested.iter().map(Vec::len).max().unwrap_or(1);
let form = |len: usize, step: usize| {
Expand All @@ -266,11 +295,11 @@ impl<'a> Abi<'a> {
let Access::Field { shared, set } = function.access else {
return self.method_name(function, owner_name, false);
};
let key = format!("field@{}", function.path.join("::"));
let name = match self.rename.get(&key) {
Some(renamed) => {
let name = match self.renames(&function.shown, "field@") {
Some(key) => {
let renamed = format!("{}_{}", self.prefix, self.rename[&key]);
self.renamed.borrow_mut().insert(key);
format!("{}_{renamed}", self.prefix)
renamed
}
None => self.method_name(function, owner_name, shared),
};
Expand All @@ -285,14 +314,16 @@ impl<'a> Abi<'a> {
}

/// A function's C name through its type's, unless renamed by its path and no method
/// or constant `shared` its name, then each argument of the instance it is.
/// or constant `shared` its name, then each argument of the instance it is, unless
/// renamed alone.
fn method_name(&self, function: &Function, owner: Option<&str>, shared: bool) -> String {
let path = function.path.join("::");
let name = match owner {
Some(owner) if shared || !self.rename.contains_key(&path) => format!("{owner}_{}", snake(function.name())),
_ => self.name(&function.path),
let (name, alone) = match owner {
Some(owner) if shared || self.renames(&function.shown, "").is_none() => {
(format!("{owner}_{}", snake(function.name())), false)
}
_ => self.named(&function.shown),
};
let Some(instance) = &function.instance else {
let Some(instance) = function.instance.as_ref().filter(|_| !alone) else {
return name;
};
self.instance(true, name, &instance.named, || {
Expand Down
34 changes: 22 additions & 12 deletions ffi/src/collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use rustc_trait_selection::infer::InferCtxtExt;
use rustc_trait_selection::traits::ObligationCtxt;
use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;

use crate::config;
use crate::ir::{
Access, Api, Callback, Constant, Dyn, Enum, Family, Field, Function, Int, Literal, Mutability, Object, Param, Path,
Receiver, Record, Traits, Type, Variant,
Expand Down Expand Up @@ -283,12 +284,9 @@ impl<'tcx> Collector<'tcx> {
/// Whether the config excludes `path`, counting the exclusion. A member of an instance
/// is left out by its instance's path or its type's, which leaves it out of each.
fn exclude(&mut self, path: &[String]) -> bool {
let generic: Vec<&str> = path[1..].iter().map(|s| s.split('<').next().unwrap_or(s)).collect();
let generic = generic.join("::");
let (report, joined) = self.report(path);
for (excluded, count) in &mut report.excluded {
let covers = |path: &str| path == excluded || path.starts_with(&format!("{excluded}::"));
if covers(&joined) || covers(&generic) {
let (report, _) = self.report(path);
for (_, key) in config::keys(&path[1..]) {
if let Some((_, count)) = report.excluded.iter_mut().find(|(excluded, _)| *excluded == key) {
*count += 1;
return true;
}
Expand Down Expand Up @@ -830,12 +828,13 @@ impl<'tcx> Collector<'tcx> {
continue;
};
let api = &mut self.api;
let (path, docs) = (site.path, docs.clone());
let (path, shown, docs) = (site.path, site.shown, docs.clone());
match decl {
Decl::Record(i) => {
*i = api.records.len();
api.records.push(Record {
path,
shown,
args: Vec::new(),
span,
docs,
Expand All @@ -849,6 +848,7 @@ impl<'tcx> Collector<'tcx> {
*i = api.enums.len();
api.enums.push(Enum {
path,
shown,
args: Vec::new(),
span,
docs,
Expand All @@ -866,6 +866,7 @@ impl<'tcx> Collector<'tcx> {
let lifetimes = tcx.generics_of(def_id).own_counts().lifetimes;
api.objects.push(Object {
path,
shown,
args: Vec::new(),
span,
docs,
Expand Down Expand Up @@ -914,6 +915,7 @@ impl<'tcx> Collector<'tcx> {
};
let parse = |docs: &str| Function {
path: path("parse"),
shown: path("parse"),
span,
docs: docs.to_string(),
receiver: None,
Expand Down Expand Up @@ -948,6 +950,7 @@ impl<'tcx> Collector<'tcx> {
parse("Parse a JSON document, failing with why it is not one."),
Function {
path: path("to_text"),
shown: path("to_text"),
span,
docs: "The document as JSON text.".to_string(),
receiver: Some(Receiver::Ref),
Expand All @@ -966,6 +969,7 @@ impl<'tcx> Collector<'tcx> {
};
Object {
path: path(""),
shown: path(""),
args: Vec::new(),
span,
docs: docs.to_string(),
Expand Down Expand Up @@ -1437,6 +1441,7 @@ impl<'tcx> Collector<'tcx> {
Ok((get, set)) => {
let accessor = |receiver, params, ok, set| Function {
path: [&site.path[..], std::slice::from_ref(&name)].concat(),
shown: shown.clone(),
span,
docs: docs(tcx, field.did),
receiver: Some(receiver),
Expand Down Expand Up @@ -1624,7 +1629,9 @@ impl<'tcx> Collector<'tcx> {
let function = self
.instantiate(item.def_id, None)
.and_then(|instances| match &instances[..] {
[one] if one.named.is_empty() => self.function(item.def_id, method, Some(self_ty), one),
[one] if one.named.is_empty() => {
self.function(item.def_id, method.clone(), method, Some(self_ty), one)
}
_ => Err(vec![why("generic parameter", name.to_string())]),
});
match function {
Expand Down Expand Up @@ -1676,18 +1683,19 @@ impl<'tcx> Collector<'tcx> {
let Some(shown) = self.shown(shown, instance) else {
continue;
};
let function = self.function(def_id, path.clone(), self_ty, instance);
let function = self.function(def_id, path.clone(), shown.clone(), self_ty, instance);
functions.push((function, shown, !instance.named.is_empty()));
}
functions
}

/// A function or method's signature at one of its instances: a method's receiver is
/// `self_ty`.
/// A function or method's signature at one of its instances, which the config names by
/// `shown`: a method's receiver is `self_ty`.
fn function(
&self,
def_id: DefId,
path: Path,
shown: Path,
self_ty: Option<Ty<'tcx>>,
instance: &Instantiation<'tcx>,
) -> Result<Function, Vec<Why>> {
Expand Down Expand Up @@ -1841,6 +1849,7 @@ impl<'tcx> Collector<'tcx> {
match (errs.is_empty(), ok) {
(true, Some(ok)) => Ok(Function {
path,
shown,
span: tcx.def_span(def_id),
docs: docs(tcx, def_id),
receiver,
Expand Down Expand Up @@ -2828,7 +2837,8 @@ impl<'tcx> Collector<'tcx> {
};
match self.ty(ty, Pos::Return) {
Ok(ok) => Some(Function {
path,
path: path.clone(),
shown: path,
span,
docs: docs(tcx, def_id),
receiver: None,
Expand Down
15 changes: 14 additions & 1 deletion ffi/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ pub struct Config {
pub exclude: Vec<String>,
/// C names, without the prefix, for paths from the crate root whose names the rule
/// makes clash: `"session::Stats" = "session_stats_snapshot"`. A type's methods are
/// named through its new name. A field is named by its path as `exclude` names it.
/// named through its new name. Paths match as `exclude`'s do, so an instance's renames
/// it alone, and a field is named by its path as `exclude` names it.
Comment on lines +25 to +26

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Defer instance renaming until a consumer needs it

The commit explicitly states that moq has no consumer for this feature, and the only added uses are synthetic fixture renames. This violates AGENTS.md's requirement that every change have a consumer using it now, with moq as the first consumer. The deleted quest also explicitly deferred this work until a consumer encounters a clash that existing renames cannot resolve. Keep the feature deferred until that concrete use exists, or include the consumer that justifies expanding the configuration and naming machinery.

AGENTS.md reference: AGENTS.md:L33-L33

Useful? React with 👍 / 👎.

#[serde(default)]
pub rename: BTreeMap<String, String>,
/// Other packages exported into the same library, each a dependency of `package`, by
Expand All @@ -42,6 +43,18 @@ pub struct Items {
pub rename: BTreeMap<String, String>,
}

/// The keys `exclude` and `rename` name the item at `shown` by, its path with its
/// instances' arguments, longest first: each prefix of it as is, then without the
/// arguments, which names the generic item's every instance. Each comes with its length.
pub fn keys(shown: &[String]) -> impl Iterator<Item = (usize, String)> + '_ {
(1..=shown.len()).rev().flat_map(move |len| {
let exact = shown[..len].join("::");
let generic: Vec<&str> = shown[..len].iter().map(|s| s.split('<').next().unwrap_or(s)).collect();
let generic = Some(generic.join("::")).filter(|generic| *generic != exact);
std::iter::once(exact).chain(generic).map(move |key| (len, key))
Comment on lines +51 to +54

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve owner arguments when matching generic method renames

For a generic method on a generic type instance, the matcher emits only the fully instantiated path and the fully generic path, omitting the key that selects all method instances on one owner instance. For example, the existing fixture's Pair<u32>::beside<dep_fixture::Size> produces neither Pair<u32>::beside nor a match for a rename keyed that way. method_name consequently ignores that rename, and unused_renames rejects the export as naming nothing. Generate the intermediate key with the owner's arguments retained and the method's arguments removed so renaming a member of one type instance also works for generic members.

Useful? React with 👍 / 👎.

})
}

impl Config {
pub fn load(path: &Path) -> Result<Self, String> {
let text = std::fs::read_to_string(path).map_err(|err| format!("reading {}: {err}", path.display()))?;
Expand Down
Loading