diff --git a/ffi/README.md b/ffi/README.md index 9f6ad1f97..14fd66b53 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -683,7 +683,13 @@ the rest cross encoded. name, as does a type named as the runtime or a generated class. Any other top-level name, such as a function's or an exception's, takes a trailing `_` where a type, the runtime, or an earlier name has it. A keyword is quoted in backticks, and a member named as one Kotlin - gives its type takes a trailing `_`. A constructor such as `new` stays a companion function: `Counter.new(1)`. + gives its type takes a trailing `_`. Names of one scope that Kotlin spells alike, such as + the fields `new` and `new_` in camel case, are kept apart in any order, as C++'s are: one + spelled as its Rust name keeps it, and the rest take a trailing `_` until free, in Rust's + name order (`new_` and `new`). A companion's functions are a scope apart from the + instance's. A call's parameters are kept apart the same way, but by a number, since the + call's own locals end in `_`: Rust's `(new_, new)` are `(new2, new)`, so a named argument + reads as Rust's. A constructor such as `new` stays a companion function: `Counter.new(1)`. - **Objects** are classes owning their handle, `AutoCloseable`, which each call holds until it returns, so the handle is freed only once no call holds it; a call after `close()` throws. Of a checked type, `close()` drops the value through Rust's own @@ -869,7 +875,8 @@ caller imports it with no ignores. snake_case without their type's name (`moq.TrackProducer.append_group`), and two types whose names would match kept apart as Kotlin's are (`TokioConnect_Error`), as are top-level names that clash. A keyword, a member Python gives every such class, or a - method named as a field takes a trailing `_`. A member or top-level name may be a + method named as a field takes a trailing `_`, as does a field named as a member a trait + gives its type (`default_` beside `Default`'s `default()`). A member or top-level name may be a builtin's (`bytes`, `int`): the module reads each builtin through an alias (`_bytes`). Constructors such as `new` stay static methods: `Counter.new(1)`. The module's `__all__` lists every export, so `from moq import *` reaches one whose Rust name starts with `_` @@ -990,8 +997,10 @@ value of a Rust type crosses as one Swift type that holds it exactly, and back u - **Names** are as Kotlin's, at the module's top level: types in PascalCase without the prefix, members in camelCase without their type's name (`TrackProducer.appendGroup`). A keyword is quoted in backticks, and a member named as one Swift gives its type, such as - `init`, or as a field or member before it, takes a trailing `_`. Names that clash are - kept apart as Kotlin's are. Parameters have no labels but an optional borrowed object's, + `init`, or as a field, takes a trailing `_`, as does a record's field named as a member + `Display` or `Debug` gives it (`description_`). Names that clash are kept apart as Kotlin's + are, in any order, a method by its name with its labels: Rust's `delete()` and + `delete_(a, b)` are `delete()` and `delete(_:_:)`. Parameters have no labels but an optional borrowed object's, so a call reads as Rust's, and a constructor such as `new` stays a static function: `Counter.new(1)`. - **Objects** are noncopyable structs (`~Copyable`) owning their handle, freed in `deinit`, @@ -1182,10 +1191,12 @@ other than one in its own form, `module ` and `go 1.24`. returns that type, or an `Option` of it (moq's `clock::interval` is `kio.NewClockInterval`), and otherwise takes a trailing `_` (`mux::codec::opus::config` is `mux.CodecOpusConfig_`). - A method named `Close` or `Error`, or as a field or a method before it, and a parameter + A method named `Close` or `Error`, or as a field, and a parameter named as a Go keyword, a predeclared name, or a package the code uses, take a trailing `_` too, as does a variant's or error's name or any other in a package that another - there, or the runtime's, takes. + there, or the runtime's, takes. Names of one scope that Pascal case spells alike, such + as the fields `new` and `new_`, are kept apart as Kotlin's are, in any order: `New` and + `New_`. - **Objects** are pointers to structs owning their handle, each an `io.Closer`, which each call holds until it returns, so the handle is freed only once no call holds it. Of a checked type, `Close()` drops the value through Rust's own `_drop`, as Rust's `drop` @@ -1338,7 +1349,8 @@ the library's own URI, mapped to the library by a build hook or by `--native-ass (`Position.group`). A type's other functions are static members. Two types whose names would match are kept apart by a number (`Cancelled2`), as a type's name holds no `_`, which Dart's lints refuse. A reserved word takes a trailing `_` (`Point.default_()`), - and any other member that clashes takes a trailing `_` (`foo_`) when that is free, else a number then a `_` (`default2_`); names that clash, + and any other member that clashes takes a trailing `_` (`foo_`) when that is free, else a number then a `_` (`default2_`), + in any order, as Kotlin's do: one spelled as its Rust name keeps it; names that clash, such as one the runtime declares or a data enum's variant class, are kept apart the same way. The glue's C names are `_dart_`, with a `_` more for each C name of the export already there. The generated file passes `dart analyze --fatal-infos` with @@ -1570,7 +1582,9 @@ packs the api fixture's with npm, installs it into a project of its own, type-ch and `load`. Names are the C names without the prefix: a type in Pascal case, and a function in camel case, a constant's in upper case; a reserved word is exported as is from a local with a trailing `$`, so `Counter.new("c", 1)` and `Point.default()` work - through the module's namespace. + through the module's namespace. Names of one scope that camel case spells alike are kept + apart as Kotlin's are, in any order: functions `erase_` and `erase` are `erase_` and + `erase`, and fields `new_` and `new`, as no field takes a trailing `_`, are `new2` and `new`. - **Values**: a record is a plain object of its fields in camel case, positional ones `_0`, `_1`, and so on; an opaque value an `rt.Opaque`, its bytes, which only Rust makes. A plain enum is a union of its variants' names, and an enum with data a union of objects tagged diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index 63693ac84..5487cdff3 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -5095,6 +5095,27 @@ pub mod clash { /// Nothing, named and typed as the method a JVM finalizer overrides. pub fn finalize(&self) {} + + /// Seven, by a static function that camel case names as the method `count`. + pub fn count_() -> u32 { + 7 + } + + /// The count, by a method that camel case names as the static `count_`. + pub fn count(&self) -> u32 { + self.count + } + + /// A store of five, by a constructor that camel case names as the method `open`. + pub fn open_() -> Store { + Store { count: 5 } + } + + /// The count plus two, wrapping past `u32::MAX`, by a method that camel case names as + /// the constructor `open_`. + pub fn open(&self) -> u32 { + self.count.wrapping_add(2) + } } /// A level, whose values are named as the members `Debug` and `Default` give a type, as @@ -5152,6 +5173,25 @@ pub mod clash { } } + /// Digits whose fields are named as the members Swift's protocols for `Display` and `Debug` + /// give a type. + #[derive(Clone, Copy, Debug, PartialEq)] + pub struct Described { + pub description: u8, + pub debug_description: u8, + } + + impl std::fmt::Display for Described { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}{}", self.description, self.debug_description) + } + } + + /// `described`'s fields as decimal digits, from `description` up. + pub fn described(described: Described) -> u32 { + u32::from(described.description) * 10 + u32::from(described.debug_description) + } + /// Bytes read one at a time, whose methods go vet reads as `io.ByteScanner`'s, as /// untrusted's `Reader::read_byte` is. pub struct Reader { @@ -5216,22 +5256,132 @@ pub mod clash { } } - /// A byte, whose methods `delete` and `delete_` C++ escapes alike, as `delete_`. + /// A byte, whose methods `delete_` and `delete` C++ escapes alike, as `delete_`, and the + /// rest name alike where their case drops the `_`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Escaped { pub new: u8, } impl Escaped { + /// `new` plus the arguments, by parameters C++ escapes alike. + pub fn delete_(&self, new: u8, new_: u8) -> u8 { + self.new + new * 10 + new_ * 100 + } + /// `new`, by a method C++ escapes as `delete_`. pub fn delete(&self) -> u8 { self.new } + } - /// `new` plus the arguments, by parameters C++ escapes alike. - pub fn delete_(&self, new: u8, new_: u8) -> u8 { - self.new + new * 10 + new_ * 100 - } + /// Digits whose fields differ only by trailing underscores, which camel case drops, and + /// are named as the members `Debug` and `Default` give a type. + #[derive(Clone, Copy, Debug, Default, PartialEq)] + pub struct Underscored { + pub new_: u8, + pub new: u8, + pub debug: u8, + pub default: u8, + } + + /// An edit, whose values differ only by a trailing underscore, which Swift's case drops. + #[allow(non_camel_case_types, reason = "the clash under test")] + #[derive(Clone, Copy, Debug, PartialEq)] + pub enum Op { + Delete_, + Delete, + } + + /// A change, whose payload's fields differ only by a trailing underscore. + #[derive(Clone, Copy, Debug, PartialEq)] + pub enum Change { + Set { new_: u8, new: u8 }, + Clear, + } + + /// `underscored`'s fields as decimal digits, from `new_` up, after `op`'s and `change`'s, + /// to show each crossed to its own place. + pub fn underscored(underscored: Underscored, op: Op, change: Change) -> u32 { + let Underscored { + new_, + new, + debug, + default, + } = underscored; + let change = match change { + Change::Set { new_, new } => u32::from(new_) * 10 + u32::from(new), + Change::Clear => 0, + }; + let digits = [new_, new, debug, default] + .iter() + .fold(0, |n, &d| n * 10 + u32::from(d)); + (op as u32 + 1) * 1_000_000 + change * 10_000 + digits + } + + /// The underscored record with each field one more, wrapping past 255, and the change with + /// each swapped. + pub fn underscored_next(underscored: Underscored, change: Change) -> (Underscored, Change) { + let Underscored { + new_, + new, + debug, + default, + } = underscored; + let next = Underscored { + new_: new_.wrapping_add(1), + new: new.wrapping_add(1), + debug: debug.wrapping_add(1), + default: default.wrapping_add(1), + }; + let change = match change { + Change::Set { new_, new } => Change::Set { new_: new, new: new_ }, + Change::Clear => Change::Clear, + }; + (next, change) + } + + /// An eraser, implemented in each binding, whose methods and parameters differ only by + /// trailing underscores. + pub trait Eraser { + /// The arguments as decimal digits. + fn delete_(&self, new_: u8, new: u8) -> u8; + + /// One. + fn delete(&self) -> u8; + } + + /// `eraser`'s `delete_(1, 2)`, then its `delete()`, as decimal digits. + pub fn erased(eraser: impl Eraser) -> u32 { + u32::from(eraser.delete_(1, 2)) * 10 + u32::from(eraser.delete()) + } + + /// Two, by a name that differs only by a trailing underscore from `erase`'s. + pub fn erase_() -> u8 { + 2 + } + + /// One. + pub fn erase() -> u8 { + 1 + } + + /// One more than the store's count, or none without one, by a name that differs only by + /// a trailing underscore from `lend`'s: Swift's overload leaving out `store` would be + /// `lend()` too. The sum saturates at `u32::MAX`. + pub fn lend_(store: Option<&Store>) -> u32 { + store.map_or(0, |store| store.count.saturating_add(1)) + } + + /// Nine. + pub fn lend() -> u32 { + 9 + } + + /// Ten times what `work_` returns, plus `work`, by parameters that differ only by a + /// trailing underscore, the closure's first. + pub fn run(work_: impl Fn() -> u8, work: u8) -> u32 { + u32::from(work_()) * 10 + u32::from(work) } /// The tone, or no tones where it is silent: an error Go names as `VecClashTone`'s variant. @@ -5615,6 +5765,12 @@ pub fn __all__(note: u8) -> u8 { note + 2 } +/// Three more than `note`, wrapping past 255, by the name Python would give `__all__`, which +/// this one keeps. +pub fn __all___(note: u8) -> u8 { + note.wrapping_add(3) +} + /// A dial, whose docs carry each rustdoc form a binding renders as its own: links to a /// method [`Self::turn`], a field [`Dial::level`], a variant [`Error::Overflow`], a /// function [`advance`], a constant [`LIMIT`], an object [`Counter`], a callback's method diff --git a/ffi/fixtures/lock/src/lib.rs b/ffi/fixtures/lock/src/lib.rs index 7d1225202..ffd77b282 100644 --- a/ffi/fixtures/lock/src/lib.rs +++ b/ffi/fixtures/lock/src/lib.rs @@ -265,7 +265,7 @@ pub fn smoothStep() -> u32 { 2 } -/// Kept function whose camel name is claimed by the added function first. +/// Kept function, which moves past the added `smoothStep` in camel case, in Rust's name order. pub fn smooth_step() -> u32 { 1 } diff --git a/ffi/src/abi.rs b/ffi/src/abi.rs index 4ec83f8b1..c18b85100 100644 --- a/ffi/src/abi.rs +++ b/ffi/src/abi.rs @@ -17,7 +17,7 @@ use std::collections::{BTreeMap, HashMap}; use rustc_span::Span; use crate::ir::{ - Access, Api, Closure, Dyn, Family, Function, Home, Int, Jni, Literal, Mutability, On, Order, Receiver, Type, + Access, Api, Closure, Dyn, Family, Function, Home, Int, Jni, Literal, Mutability, On, Order, Param, Receiver, Type, }; /// A C name one item claims twice, which no rename can tell apart: the name, then what @@ -2087,23 +2087,89 @@ pub(crate) fn unique(names: Vec, taken: impl Fn(&str) -> bool) -> Vec) -> Vec { - let names: Vec = names.into_iter().collect(); - let mut taken = std::collections::BTreeSet::new(); - (names.iter()) - .map(|name| { - let mut unique = name.clone(); - let mut n = 2; - while taken.contains(&unique) || (unique != *name && names.contains(&unique)) { - unique = format!("{name}{n}"); - n += 1; - } - taken.insert(unique.clone()); - unique - }) - .collect() +/// A language's names of `rust`, the names of one scope, kept apart from each other and from +/// what `taken` names for each, by its index, whatever their order. `spelled` is each one's +/// spelling in the language, and `own` whether a spelling reads back as its Rust name. One +/// that does keeps it while neither `taken` nor another that does and is not taken holds it, +/// and every other, in Rust's order of names, takes the first of its `step`s that is free, as +/// [`underscored`] counts them. So beside `new`, which keeps `new`, a `new_` that camel case +/// spells `new` takes `new_`, and no order of the source moves either. +pub(crate) fn named( + rust: &[&str], + spelled: Vec, + own: impl Fn(&str, &str) -> bool, + taken: impl Fn(usize, &str) -> bool, + step: impl Fn(&str, usize) -> String, +) -> Vec { + named_apart(rust, spelled, own, taken, step, |_, a, _, b| a == b) +} + +/// [`named`]'s names, where two items clash only as `clash` reads them, each by its index and +/// name, for a language whose items of one scope may share a name, such as Dart's named +/// constructor and instance method, or Swift's overloads of different labels. +pub(crate) fn named_apart( + rust: &[&str], + spelled: Vec, + own: impl Fn(&str, &str) -> bool, + taken: impl Fn(usize, &str) -> bool, + step: impl Fn(&str, usize) -> String, + clash: impl Fn(usize, &str, usize, &str) -> bool, +) -> Vec { + let mut names = spelled.clone(); + // Those that could keep their spelling: one taken moves anyway, so it holds back no other. + let owns: Vec = (0..rust.len()) + .map(|k| own(rust[k], &spelled[k]) && !taken(k, &spelled[k])) + .collect(); + let kept: Vec = (0..rust.len()) + .map(|k| owns[k] && (0..rust.len()).all(|j| j == k || !owns[j] || !clash(k, &spelled[k], j, &spelled[j]))) + .collect(); + let mut held: Vec = (0..rust.len()).filter(|&k| kept[k]).collect(); + let mut moved: Vec = (0..rust.len()).filter(|&k| !kept[k]).collect(); + moved.sort_by_key(|&k| rust[k]); + for k in moved { + let mut n = 0; + while taken(k, &names[k]) || held.iter().any(|&j| clash(k, &names[k], j, &names[j])) { + n += 1; + names[k] = step(&spelled[k], n); + } + held.push(k); + } + names +} + +/// Asserts that no two of the `members` of the type `rust` in `language` are one, as `same` +/// reads them. Each generator names a scope's members apart through [`named`], and from +/// every other scope of the type that they share, so two alike are its bug, not the crate's. +pub(crate) fn assert_apart(rust: &str, language: &str, members: &[String], same: impl Fn(&str, &str) -> bool) { + for (k, member) in members.iter().enumerate() { + if members[..k].iter().any(|other| same(other, member)) { + panic!("rust2-ffi named two members of `{rust}` `{member}` in {language}"); + } + } +} + +/// The `n`th name to try in place of `name` where it is taken: `n` more trailing `_`s, after +/// its name and before any `(` of argument labels. +pub(crate) fn underscored(name: &str, n: usize) -> String { + let at = name.find('(').unwrap_or(name.len()); + format!("{}{}{}", &name[..at], "_".repeat(n), &name[at..]) +} + +/// A language's names of `params`, each as `spell` spells its Rust name, kept apart from each +/// other and from what `taken` names as [`named`] keeps a scope's, by [`numbered`] steps, since +/// a generated call's own locals end in `_`. So of `new_` and `new`, both `new` in camel case, +/// Rust's `new` keeps `new` and `new_` takes `new2`, in either order. +pub(crate) fn distinct(params: &[Param], spell: impl Fn(&str) -> String, taken: impl Fn(&str) -> bool) -> Vec { + let rust: Vec<&str> = params.iter().map(|param| param.name.as_str()).collect(); + let spelled = rust.iter().map(|name| spell(name)).collect(); + let own = |rust: &str, name: &str| name == rust || snake(name) == rust; + named(&rust, spelled, own, |_, name| taken(name), numbered) +} + +/// The `n`th name to try in place of `name` where it is taken: it with the number `n + 1`, +/// `foo2`, for a name that never ends in `_`. +pub(crate) fn numbered(name: &str, n: usize) -> String { + format!("{name}{}", n + 1) } /// A name that C or C++, which includes the header, would read as a keyword or macro or @@ -2298,7 +2364,7 @@ pub(crate) fn dyn_wrap(form: Dyn, expr: &str) -> String { #[cfg(test)] mod tests { - use super::{apart, defined, escape, past_cycles, shortest, unique}; + use super::{apart, defined, distinct, escape, named, named_apart, past_cycles, shortest, underscored, unique}; #[test] fn escapes_keep_apart_from_every_macro() { @@ -2375,6 +2441,96 @@ mod tests { assert_eq!(names(&["String", "B"], &["String"]), ["String_", "B"]); } + #[test] + fn named_keeps_names_apart_in_either_order() { + // Camel case, which drops a trailing `_`: a name reads back as its Rust if it is that + // Rust's own snake case. + let names = |rust: &[&str], taken: &[&str]| { + let spelled = rust.iter().map(|name| name.trim_end_matches('_').to_string()).collect(); + let own = |rust: &str, name: &str| name == rust; + named(rust, spelled, own, |_, name| taken.contains(&name), underscored) + }; + // The name spelled as Rust's keeps it, and the other recovers Rust's `_`, in either order. + assert_eq!(names(&["new_", "new"], &[]), ["new_", "new"]); + assert_eq!(names(&["new", "new_"], &[]), ["new", "new_"]); + // Those that move go in Rust's name order, whatever the scope's. + assert_eq!(names(&["a__", "a", "a_"], &[]), ["a__", "a", "a_"]); + // Where none is spelled as Rust's, the first in Rust's order takes the spelling. + assert_eq!(names(&["a__", "a_"], &[]), ["a_", "a"]); + // A name taken moves even where it is Rust's own. + assert_eq!(names(&["a_", "a"], &["a"]), ["a__", "a_"]); + // Two that read back alike as Rust's own both move, in the scope's order where Rust's + // names are alike too. + let spelled = vec!["x".to_string(), "x".to_string()]; + assert_eq!( + named(&["x", "x"], spelled, |_, _| true, |_, _| false, underscored), + ["x", "x_"] + ); + } + + #[test] + fn named_apart_keeps_a_name_where_nothing_clashes() { + // Each item's space, as Dart's constructor and instance method are: 0 and 1 apart, 2 in both. + let names = |rust: &[&str], spaces: &[u8]| { + let spelled = rust.iter().map(|name| name.trim_end_matches('_').to_string()).collect(); + let clash = |k: usize, a: &str, j: usize, b: &str| { + a == b && (spaces[k] == spaces[j] || spaces[k] == 2 || spaces[j] == 2) + }; + named_apart( + rust, + spelled, + |rust, name| name == rust, + |_, _| false, + underscored, + clash, + ) + }; + // Apart, both keep `open`, in either order. + assert_eq!(names(&["open_", "open"], &[1, 0]), ["open", "open"]); + assert_eq!(names(&["open", "open_"], &[0, 1]), ["open", "open"]); + // One in both spaces clashes with each, and Rust's own keeps the name. + assert_eq!(names(&["open_", "open"], &[2, 0]), ["open_", "open"]); + assert_eq!(names(&["open", "open_"], &[1, 2]), ["open", "open_"]); + // One whose spelling only it finds taken, as a Swift function's is where an enum case + // holds one of its overloads, moves, and leaves the spelling to the other that reads + // back as its Rust, not to `FOO_BAR`, which comes first in Rust's order. + let spelled = vec!["fooBar".to_string(); 3]; + let clash = |_: usize, a: &str, _: usize, b: &str| a == b; + let taken = |k: usize, name: &str| k == 0 && name == "fooBar"; + let own = |rust: &str, _: &str| rust != "FOO_BAR"; + let rust = ["foo_bar", "fooBar", "FOO_BAR"]; + let names = named_apart(&rust, spelled, own, taken, underscored, clash); + assert_eq!(names, ["fooBar__", "fooBar", "fooBar_"]); + } + + #[test] + fn distinct_params_number_the_one_not_spelled_as_rust() { + let params = |names: &[&str]| -> Vec { + (names.iter()) + .map(|name| crate::ir::Param { + name: name.to_string(), + ty: crate::ir::Type::Bool, + interned: false, + }) + .collect() + }; + let camel = |name: &str| name.trim_end_matches('_').to_string(); + let names = |names: &[&str]| distinct(¶ms(names), camel, |_| false); + // Rust's `new` keeps `new` in either order, and a number never ends a name in `_`. + assert_eq!(names(&["new_", "new"]), ["new2", "new"]); + assert_eq!(names(&["new", "new_"]), ["new", "new2"]); + // A step skips a name another keeps, and one taken. + assert_eq!(names(&["a_", "a", "a2"]), ["a3", "a", "a2"]); + let receiving = distinct(¶ms(&["self_"]), camel, |name| name == "self"); + assert_eq!(receiving, ["self2"]); + } + + #[test] + fn underscored_steps_before_labels() { + assert_eq!(underscored("delete", 1), "delete_"); + assert_eq!(underscored("delete(_:_:)", 2), "delete__(_:_:)"); + } + /// Each instance's arguments, each by its path's segments, whose forms are their /// suffixes, shortest first. fn group(instances: &[&[&[&str]]]) -> Vec>> { diff --git a/ffi/src/dart.rs b/ffi/src/dart.rs index 30167800f..35f58025a 100644 --- a/ffi/src/dart.rs +++ b/ffi/src/dart.rs @@ -597,20 +597,10 @@ impl<'a> Gen<'a> { keys.into_iter().zip(names).collect() } - /// Check that no two members of the type `rust` share a Dart name, as [`collides`] reads - /// them. - fn distinct(&mut self, rust: &str, members: &[String]) { - let mut clashes = BTreeSet::new(); - for (k, member) in members.iter().enumerate() { - if let Some(other) = members[..k].iter().find(|other| collides(other, member)) { - clashes.insert(other.rsplit(' ').next().unwrap_or(other).to_string()); - } - } - for name in clashes { - self.errors.push(format!( - "two members of `{rust}` are both `{name}` in Dart, which rust2-ffi should keep apart" - )); - } + /// Asserts that no two members of the type `rust` share a Dart name, as [`collides`] + /// reads them and [`abi::assert_apart`] checks. + fn distinct(&self, rust: &str, members: &[String]) { + abi::assert_apart(rust, "Dart", members, collides); } /// Drops the constructors of the object classes that nothing calls: a type only ever lent @@ -1351,8 +1341,8 @@ impl<'a> Gen<'a> { Type::Record(i) => { let record = &abi.api.records[*i]; let mut lines = Vec::new(); - for field in &record.fields { - let e = format!("v.{}", field_name(&field.name)); + for (field, name) in record.fields.iter().zip(field_names(&record.fields)) { + let e = format!("v.{name}"); let dst = format!("c.{}", slot(&abi::escape(&field.name))); lines.push(self.write(&field.ty, &e, &dst, "t")); } @@ -1371,8 +1361,8 @@ impl<'a> Gen<'a> { body.insert(0, format!("_on(0x{on:x}, '{c}.{}');", variant.name)); } let member = abi::escape(&abi::snake(&variant.name)); - for field in &variant.fields { - let e = format!("v.{}", field_name(&field.name)); + for (field, name) in variant.fields.iter().zip(field_names(&variant.fields)) { + let e = format!("v.{name}"); let dst = format!("c.$u.{}.{}", slot(&member), slot(&abi::escape(&field.name))); body.push(self.write(&field.ty, &e, &dst, "t")); } @@ -1481,20 +1471,21 @@ impl<'a> Gen<'a> { let class = self.struct_class(&Ty::Struct(c.to_string())); let record = &abi.api.records[*i]; let mut args = Vec::new(); - for field in &record.fields { + for (field, name) in record.fields.iter().zip(field_names(&record.fields)) { let value = self.lift(&field.ty, &format!("c.{}", slot(&abi::escape(&field.name)))); args.push(match record.tuple { true => value, - false => format!("{}: {value}", field_name(&field.name)), + false => format!("{name}: {value}"), }); } (class, format!("{dt}({})", args.join(", "))) } Type::Enum(i) if abi.api.enums[*i].plain() => { let e = &abi.api.enums[*i]; - let cases: Vec = (e.variants.iter()) - .map(|v| format!("\t\t{} => {dt}.{},", v.discriminant, enum_value(e.traits, &v.name))) + let cases: Vec = (e.variants.iter().zip(enum_values(e))) + .map(|(v, value)| format!("\t\t{} => {dt}.{value},", v.discriminant)) .collect(); + ( "int".to_string(), format!( @@ -1511,14 +1502,14 @@ impl<'a> Gen<'a> { let case = self.variant_class(&dt, &variant.name); let member = abi::escape(&abi::snake(&variant.name)); let mut args = Vec::new(); - for field in &variant.fields { + for (field, name) in variant.fields.iter().zip(field_names(&variant.fields)) { let value = self.lift( &field.ty, &format!("c.$u.{}.{}", slot(&member), slot(&abi::escape(&field.name))), ); args.push(match variant.tuple { true => value, - false => format!("{}: {value}", field_name(&field.name)), + false => format!("{name}: {value}"), }); } cases.push(format!("\t\t{n} => {case}({}),", args.join(", "))); @@ -1738,8 +1729,12 @@ impl<'a> Gen<'a> { for i in 0..api.callbacks.len() { self.callback(i); } - for function in &api.functions { - if let Some((code, _)) = self.function(function, None, None, &[]) { + let functions: Vec<&Function> = api.functions.iter().collect(); + let named = self.names(&functions, (None, None), |_, name| { + TAKEN.contains(&name) || self.names.contains_key(name) + }); + for (function, name) in api.functions.iter().zip(&named) { + if let Some((code, _)) = self.function(function, (None, None), name, &[]) { self.top.push_str(&code); self.top.push('\n'); } @@ -2076,8 +2071,16 @@ impl<'a> Gen<'a> { body: &mut Vec, members: &mut Vec, ) { - for method in methods { - if let Some((code, member)) = self.function(method, Some(owner), Some(ty), members) { + let functions: Vec<&Function> = methods.iter().collect(); + let owned = (Some(owner), Some(ty)); + let declared: Vec> = (methods.iter()).map(|method| self.declared(method, owned).2).collect(); + // Each name a member its type declares already takes, as [`collides`] reads it. + let named = self.names(&functions, owned, |k, name| match declared[k] { + Some(kind) => members.iter().any(|other| collides(other, &format!("{kind}{name}"))), + None => false, + }); + for (method, name) in methods.iter().zip(&named) { + if let Some((code, member)) = self.function(method, owned, name, members) { members.push(member); body.push(indent(&code)); } @@ -2132,9 +2135,8 @@ impl<'a> Gen<'a> { ); return; } - let fields: Vec<(String, String)> = (record.fields.iter()) - .map(|f| { - let name = field_name(&f.name); + let fields: Vec<(String, String)> = (record.fields.iter().zip(field_names(&record.fields))) + .map(|(f, name)| { crate::lock::field(&mut self.locked, &record.shown, &f.name, &name); (name, self.dt(&f.ty)) }) @@ -2186,9 +2188,8 @@ impl<'a> Gen<'a> { // A value of a variant the library's target lacks is refused as it crosses, when // its C value is read. let limited = e.variants.iter().any(|v| !abi.api.everywhere(v.on)); - let values: Vec = (e.variants.iter()) - .map(|v| { - let value = enum_value(e.traits, &v.name); + let values: Vec = (e.variants.iter().zip(enum_values(e))) + .map(|(v, value)| { crate::lock::variant(&mut self.locked, &e.shown, &v.name, &value); members.push(format!("static {value}")); match limited { @@ -2230,9 +2231,7 @@ impl<'a> Gen<'a> { self.traits(&ty, &c, e.traits, &mut body, &mut members); // Each variant's fields, which its class declares beside the methods it inherits, so a // method takes a trailing `_` beside one, as a record's does beside its own. - let fields: BTreeSet = (e.variants.iter().flat_map(|v| &v.fields)) - .map(|f| field_name(&f.name)) - .collect(); + let fields: BTreeSet = (e.variants.iter()).flat_map(|v| field_names(&v.fields)).collect(); members.extend(fields); let owner = abi.ty(&ty); self.methods(&e.methods, &owner, &ty, &mut body, &mut members); @@ -2245,9 +2244,8 @@ impl<'a> Gen<'a> { ); for (k, variant) in e.variants.iter().enumerate() { let case = self.variant_class(&name, &variant.name); - let fields: Vec<(String, String)> = (variant.fields.iter()) - .map(|f| { - let name = field_name(&f.name); + let fields: Vec<(String, String)> = (variant.fields.iter().zip(field_names(&variant.fields))) + .map(|(f, name)| { crate::lock::variant_field(&mut self.locked, &e.shown, &variant.name, &f.name, &name); (name, self.dt(&f.ty)) }) @@ -2338,14 +2336,12 @@ impl<'a> Gen<'a> { let rust = callback.path.join("::"); let mut body = Vec::new(); let mut members = Vec::new(); - // `close` is the hook Rust calls once it drops an implementation. - let reserved: Vec<&str> = OBJECT.iter().copied().chain(["close"]).collect(); - for method in &callback.methods { - let member = member(&abi::snake(method.name()), &reserved); + for (method, member) in callback.methods.iter().zip(callback_members(&callback.methods)) { crate::lock::function(&mut self.locked, method, &member); members.push(member.clone()); - let params: Vec = (method.params.iter()) - .map(|p| format!("{} {}", self.dt(&p.ty), param_name(&p.name))) + let names = abi::distinct(&method.params, param_name, |_| false); + let params: Vec = (method.params.iter().zip(names)) + .map(|(p, name)| format!("{} {name}", self.dt(&p.ty))) .collect(); body.push(format!( "{}\t{} {member}({});", @@ -2389,9 +2385,7 @@ impl<'a> Gen<'a> { let rust = callback.path.join("::"); let mut relays = Vec::new(); let mut trampolines = Vec::new(); - let reserved: Vec<&str> = OBJECT.iter().copied().chain(["close"]).collect(); - for method in &callback.methods { - let member = member(&abi::snake(method.name()), &reserved); + for (method, member) in callback.methods.iter().zip(callback_members(&callback.methods)) { // The trampoline Rust's relay calls on the isolate's thread. let c_params: Vec = method.params.iter().map(|p| abi.ty(&p.ty)).collect(); let ret = abi.ty(&method.ok); @@ -2636,17 +2630,99 @@ impl<'a> Gen<'a> { } } - /// `function`'s Dart form and its member name, a member of `owner` (whose IR type is - /// `owner_ty`) if it has one. + /// The name each of `functions` takes as a member of `owner` (whose IR type is + /// `owner_ty`) if it has one, or at the top level, apart from each other and from what + /// `taken` holds for each, by its index, as [`abi::named`] keeps a scope's. Two clash + /// only as [`collides`] reads them, so a named constructor keeps the name of an instance + /// method, as Dart allows. + fn names( + &self, + functions: &[&Function], + owner: (Option<&Ty>, Option<&Type>), + taken: impl Fn(usize, &str) -> bool, + ) -> Vec { + let mut rust = Vec::new(); + let mut spelled = Vec::new(); + let mut kinds = Vec::new(); + for function in functions { + let (name, member, kind) = self.declared(function, owner); + rust.push(name); + spelled.push(member); + kinds.push(kind); + } + let rust: Vec<&str> = rust.iter().map(String::as_str).collect(); + // An unnamed constructor clashes with none. + let clash = |k: usize, a: &str, j: usize, b: &str| match (kinds[k], kinds[j]) { + (Some(kk), Some(kj)) => collides(&format!("{kk}{a}"), &format!("{kj}{b}")), + _ => false, + }; + abi::named_apart(&rust, spelled, own, taken, alternative, clash) + } + + /// The declaration `function` makes as a member of `owner` (whose IR type is `owner_ty`) + /// if it has one, before it keeps apart from another: the Rust name it spells, its Dart + /// name, and what [`collides`] reads before that name, `static ` or `new ` or none, or + /// `None` for an unnamed constructor, which no name clashes with. + fn declared( + &self, + function: &Function, + (owner, owner_ty): (Option<&Ty>, Option<&Type>), + ) -> (String, String, Option<&'static str>) { + let abi = self.abi; + let (back, export) = match (owner.zip(owner_ty)).and_then(|(owner, ty)| abi.handed_back(function, owner, ty)) { + Some((back, export, _)) => (Some(back), export), + None => (None, abi.export(function, owner)), + }; + let function = back.as_ref().unwrap_or(function); + let own = match owner { + Some(Ty::Struct(o) | Ty::Enum(o) | Ty::Handle { name: o, .. }) => { + export.named.strip_prefix(o.as_str()).and_then(|r| r.strip_prefix('_')) + } + _ => None, + }; + let mut reserved: Vec<&str> = OBJECT.to_vec(); + if matches!(owner_ty, Some(Type::Object(_))) { + reserved.push("close"); + } + // Named as Rust's path is, whatever C's clashes rename. + let rust = own.unwrap_or_else(|| self.bare(&export.named)).to_string(); + let member = member(&rust, &reserved); + let receiver = function.receiver.filter(|_| owner.is_some()); + let is_static = receiver.is_none() && owner.is_some(); + let stat = if is_static { "static " } else { "" }; + let plain = function.params.is_empty() && !function.future && function.err.is_none(); + let kind = match (function.access, receiver) { + (Access::Field { set: false, .. }, Some(_)) if plain => Some(""), + (Access::Const, None) if plain => Some(stat), + // A function of a type returning it is a constructor: an object's or opaque + // value's `new` is its unnamed one. + _ if is_static && !function.future && Some(&strip_refs(&function.ok)) == owner_ty => { + let unnamed = match owner_ty { + Some(Type::Object(_)) => true, + Some(Type::Record(i)) => abi.api.records[*i].opaque.is_some(), + _ => false, + }; + match rust == "new" && unnamed { + true => None, + false => Some("new "), + } + } + _ => Some(stat), + }; + (rust, member, kind) + } + + /// `function`'s Dart form `member`, of `owner` (whose IR type is `owner_ty`) if it has + /// one, apart from the members `taken` names, and its entry as [`collides`] reads it. fn function( &mut self, function: &Function, - owner: Option<&Ty>, - owner_ty: Option<&Type>, + owner: (Option<&Ty>, Option<&Type>), + member: &str, taken: &[String], ) -> Option<(String, String)> { let on = std::mem::replace(&mut self.on, function.on); - let code = self.function_on(function, owner, owner_ty, taken); + let code = self.function_on(function, owner, member, taken); self.on = on; code } @@ -2654,8 +2730,8 @@ impl<'a> Gen<'a> { fn function_on( &mut self, function: &Function, - owner: Option<&Ty>, - owner_ty: Option<&Type>, + (owner, owner_ty): (Option<&Ty>, Option<&Type>), + member: &str, taken: &[String], ) -> Option<(String, String)> { let abi = self.abi; @@ -2682,14 +2758,9 @@ impl<'a> Gen<'a> { Some(o) => export.named.strip_prefix(o.as_str()).and_then(|r| r.strip_prefix('_')), None => None, }; - let mut reserved: Vec<&str> = OBJECT.to_vec(); - if matches!(owner_ty, Some(Type::Object(_))) { - reserved.push("close"); - } // Named as Rust's path is, whatever C's clashes rename. let named = self.bare(&export.named).to_string(); let snake = own.unwrap_or(&named); - let member = member(snake, &reserved); let receiver = function.receiver.filter(|_| owner.is_some()); // A leaf call runs on the isolate's thread, with no thread hop, as nothing in it @@ -2724,9 +2795,9 @@ impl<'a> Gen<'a> { // Whether the call is given a value Rust takes, whose buffers the arena frees // unless the call returns. let mut gives = false; - let names = abi::distinct(function.params.iter().map(|param| param_name(¶m.name))); + let names = abi::distinct(&function.params, param_name, |_| false); let mut writes = Vec::new(); - for (k, (param, name)) in function.params.iter().zip(names).enumerate() { + for (k, (param, name)) in function.params.iter().zip(names.iter().cloned()).enumerate() { let (_, c) = c_params.next().expect("each parameter has its C one"); // A value passed for `&mut`, in a holder that takes what Rust writes back. if param.ty.written() { @@ -3062,8 +3133,7 @@ impl<'a> Gen<'a> { "\n\nRust changes a copy of this value, which it returns first, as the call left it: this one never changes.", ); } - for param in &function.params { - let name = param_name(¶m.name); + for (param, name) in function.params.iter().zip(&names) { match ¶m.ty { Type::Closure(closure_) => { text.push_str(&match closure_.kept { @@ -3100,8 +3170,8 @@ impl<'a> Gen<'a> { let stat = if is_static { "static " } else { "" }; let code_body = indent(&body.join("\n")); let mut member = match owner { - None => self.claim(&member, format!("fn `{}`", function.path.join("::"))), - Some(_) => member, + None => self.claim(member, format!("fn `{}`", function.path.join("::"))), + Some(_) => member.to_string(), }; // A member its type declares already, as a field of its name, takes the next of its // alternatives. @@ -3260,14 +3330,14 @@ impl<'a> Gen<'a> { let e = &abi.api.enums[i]; let name = owner(doc::Owner::Enum(i)); match e.plain() { - true => format!("{name}.{}", enum_value(e.traits, &e.variants[v].name)), + true => format!("{name}.{}", enum_values(e).swap_remove(v)), false => self.variant_class(&name, &e.variants[v].name), } } doc::Target::Field(i, n) => format!( "{}.{}", owner(doc::Owner::Record(i)), - field_name(&abi.api.records[i].fields[n].name) + field_names(&abi.api.records[i].fields).swap_remove(n) ), doc::Target::Constant(c) => self.locked.get(&format!("const {}", c.path.join("::")))?.clone(), doc::Target::Function(of, f) => { @@ -3572,10 +3642,38 @@ fn param_name(name: &str) -> String { member(name, &[]) } -/// A plain enum's value: its variant in camel case, with `_` appended while a member every -/// Dart enum has, or one its traits `t` give it, takes it, since a static member clashes -/// with either kind. -fn enum_value(t: crate::ir::Traits, variant: &str) -> String { +/// Whether the Dart name `name` reads back as the Rust one `rust`, as it spells it or in +/// camel case, for [`abi::named`]. +fn own(rust: &str, name: &str) -> bool { + name == rust || abi::snake(name) == rust +} + +/// The `n`th of the [`alternatives`] to `name`, for [`abi::named`]. +fn alternative(name: &str, n: usize) -> String { + alternatives(name).nth(n).expect("alternatives never end") +} + +/// The names of a callback's `methods`, one scope's, apart as [`abi::named`] keeps them, and +/// from what every object has and the `close` hook Rust calls once it drops an implementation. +fn callback_members(methods: &[Function]) -> Vec { + let reserved: Vec<&str> = OBJECT.iter().copied().chain(["close"]).collect(); + let rust: Vec<&str> = methods.iter().map(|method| method.name()).collect(); + let spelled = rust.iter().map(|name| member(&abi::snake(name), &reserved)).collect(); + abi::named(&rust, spelled, own, |_, _| false, alternative) +} + +/// The Dart names of `fields`, one scope's, each [`field_name`], kept apart as [`abi::named`] +/// keeps them. +fn field_names(fields: &[crate::ir::Field]) -> Vec { + let rust: Vec<&str> = fields.iter().map(|f| f.name.as_str()).collect(); + let spelled = rust.iter().map(|name| field_name(name)).collect(); + abi::named(&rust, spelled, own, |_, _| false, alternative) +} + +/// A plain enum's values: each variant in camel case, kept apart from the others, and from a +/// member every Dart enum has or one its traits give it, since a static member clashes with +/// either kind, as [`abi::named`] keeps them. +fn enum_values(e: &crate::ir::Enum) -> Vec { const ENUM: &[&str] = &[ "values", "index", @@ -3587,13 +3685,18 @@ fn enum_value(t: crate::ir::Traits, variant: &str) -> String { "compareTo", "partialCompareTo", ]; + let t = e.traits; let made = [(t.debug, "debug"), (t.default, "default_")]; - let taken = |name: &str| ENUM.contains(&name) || made.iter().any(|(has, made)| *has && *made == name); - let mut name = member(&abi::snake(variant), &[]); - while taken(&name) { - name.push('_'); - } - name + let taken = |_, name: &str| ENUM.contains(&name) || made.iter().any(|(has, made)| *has && *made == name); + let rust: Vec<&str> = e.variants.iter().map(|v| v.name.as_str()).collect(); + let spelled = rust.iter().map(|name| member(&abi::snake(name), &[])).collect(); + abi::named( + &rust, + spelled, + |rust, name| pascal(name) == rust, + taken, + abi::underscored, + ) } /// Whether the members `a` and `b` of one type clash, each `static x`, `new x` for a diff --git a/ffi/src/go.rs b/ffi/src/go.rs index 3082ea435..a70fe51b7 100644 --- a/ffi/src/go.rs +++ b/ffi/src/go.rs @@ -934,9 +934,9 @@ impl<'a> Gen<'a> { pascal(self.bare(c)) } - /// The Go names of parameters, each [`local`], [`abi::distinct`]. + /// The Go names of parameters, each [`local`], kept apart as [`abi::distinct`] keeps them. fn locals(&self, params: &[Param]) -> Vec { - abi::distinct(params.iter().map(|p| local(&p.name))) + abi::distinct(params, local, |_| false) } /// The package-level Go name `what` takes, `name` unless that is taken. @@ -945,16 +945,10 @@ impl<'a> Gen<'a> { abi::claim(&mut self.names, |name| rt && taken(name), name, what) } - /// Check that no two members of the type `rust` share a Go name. - fn distinct(&mut self, rust: &str, members: &[String]) { - let mut seen = BTreeSet::new(); - for member in members { - if !seen.insert(member) { - self.errors.push(format!( - "two members of `{rust}` are both `{member}` in Go, which rust2-ffi should keep apart" - )); - } - } + /// Asserts that no two members of the type `rust` share a Go name, as + /// [`abi::assert_apart`] does. + fn distinct(&self, rust: &str, members: &[String]) { + abi::assert_apart(rust, "Go", members, |a, b| a == b); } /// The Go type of `ty`, as a value, a parameter, or a result. @@ -1466,12 +1460,24 @@ impl<'a> Gen<'a> { for i in (0..api.callbacks.len()).filter(|&i| mine(&api.callbacks[i].home)) { self.callback(i); } - for function in api.functions.iter().filter(|f| mine(&f.home)) { - let mut method = self.function(function, None, None); - method.name = self.claim(&method.name, format!("fn `{}`", function.path.join("::"))); + // Named apart from each other as [`abi::named`] keeps a scope's, then from the rest. + let functions: Vec<&Function> = api.functions.iter().filter(|f| mine(&f.home)).collect(); + let mut methods: Vec = functions.iter().map(|f| self.function(f, None, None)).collect(); + let rust: Vec = (functions.iter()) + .map(|f| rest(&abi.prefix, &abi.export(f, None).on_home().named, &f.shown, &f.home).to_string()) + .collect(); + let rust: Vec<&str> = rust.iter().map(String::as_str).collect(); + let spelled = methods.iter().map(|method| method.name.clone()).collect(); + let rt = self.pkg == Packages::RT; + let own = |rust: &str, name: &str| abi::snake(name) == rust || name == rust.to_uppercase(); + let free = |_: usize, name: &str| rt && taken(name) || self.names.contains_key(name); + let names = abi::named(&rust, spelled, own, free, abi::underscored); + for ((function, method), name) in functions.into_iter().zip(&mut methods).zip(names) { + method.name = self.claim(&name, format!("fn `{}`", function.path.join("::"))); crate::lock::function(&mut self.locked, function, &method.name); self.top.push_str(&method.write()); } + self.moved(); self.errors_of(); } @@ -2100,32 +2106,27 @@ impl<'a> Gen<'a> { self.distinct(&rust, &members); } - /// The Go names of a record's fields: each [`field_name`], with a trailing `_` while - /// a method its traits give it, which an interface requires by name, or an earlier - /// field takes it. + /// The Go names of a record's fields, kept apart from a method its traits give it, which + /// an interface requires by name, as [`field_names`] keeps them. fn record_fields(&mut self, i: usize) -> Vec { let record = &self.abi.api.records[i]; - let mut taken = self.trait_methods(&Type::Record(i), record.traits); - (record.fields.iter()) - .map(|f| { - let name = unique(&mut taken, field_name(&f.name)); - crate::lock::field(&mut self.locked, &record.shown, &f.name, &name); - name - }) - .collect() + let taken = self.trait_methods(&Type::Record(i), record.traits); + let names = field_names(&record.fields, &taken); + for (f, name) in record.fields.iter().zip(&names) { + crate::lock::field(&mut self.locked, &record.shown, &f.name, name); + } + names } /// The Go names of a data enum's variant's fields, clear of the methods its traits add. fn variant_fields(&mut self, i: usize, variant: &Variant) -> Vec { let e = &self.abi.api.enums[i]; - let mut taken = self.trait_methods(&Type::Enum(i), e.traits); - (variant.fields.iter()) - .map(|f| { - let name = unique(&mut taken, field_name(&f.name)); - crate::lock::variant_field(&mut self.locked, &e.shown, &variant.name, &f.name, &name); - name - }) - .collect() + let taken = self.trait_methods(&Type::Enum(i), e.traits); + let names = field_names(&variant.fields, &taken); + for (f, name) in variant.fields.iter().zip(&names) { + crate::lock::variant_field(&mut self.locked, &e.shown, &variant.name, &f.name, name); + } + names } /// The methods the traits `t` of the type `ty` add, which a field's name must clear. @@ -2199,16 +2200,47 @@ impl<'a> Gen<'a> { owner: &Ty, fields: &[String], ) -> Vec { - let (methods, statics) = self.members(ty, c, rust, traits, functions, owner); + let (mut methods, statics) = self.members(ty, c, rust, traits, functions, owner); let mut members = Vec::new(); let mut taken: BTreeSet = fields.iter().cloned().collect(); - // Each method's final name and receiver, by its lock key, which a stream's adapter calls. - let mut named = BTreeMap::new(); let error = self.errored(ty); - for mut method in methods { + // What its traits make, and `Error`, keep their names, which an interface requires, + // before Rust's, which keep apart as one scope. + for method in methods.iter_mut().filter(|m| m.key.is_none()) { while method.vetted(error) || !taken.insert(method.name.clone()) { method.name.push('_'); } + } + let own: Vec = (0..methods.len()).filter(|&k| methods[k].key.is_some()).collect(); + let rust: Vec<&str> = (own.iter()) + .map(|&k| { + let key = methods[k].key.as_deref(); + (functions.iter()) + .find(|f| Some(crate::lock::function_key(f).as_str()) == key) + .expect("a method is of its type's functions") + .name() + }) + .collect(); + for &k in &own { + while methods[k].vetted(error) { + methods[k].name.push('_'); + } + } + let spelled = own.iter().map(|&k| methods[k].name.clone()).collect(); + let names = abi::named( + &rust, + spelled, + |rust, name| abi::snake(name) == rust, + |_, name| taken.contains(name), + abi::underscored, + ); + for (k, name) in own.into_iter().zip(names) { + taken.insert(name.clone()); + methods[k].name = name; + } + // Each method's final name and receiver, by its lock key, which a stream's adapter calls. + let mut named = BTreeMap::new(); + for method in methods { if let Some(key) = &method.key { self.locked.insert(key.clone(), method.name.clone()); named.insert(key.clone(), (method.name.clone(), method.receiver.clone())); @@ -2569,21 +2601,37 @@ impl<'a> Gen<'a> { let mut body = Vec::new(); let mut members = Vec::new(); let mut table = vec!["\tv.free = goRelease\n".to_string()]; - for method in &callback.methods { - let types: Vec = method.params.iter().map(|p| self.go_param(&p.ty)).collect(); - let ret = match method.ok { - Type::Unit => None, - _ => Some(self.go(&method.ok)), - }; - // An interface's method is vetted too, though never as an `error`'s. - let (ps, rs): (Vec<&str>, Vec<&str>) = ( - types.iter().map(String::as_str).collect(), - ret.iter().map(String::as_str).collect(), - ); - let mut member = pascal(method.name()); - while vetted(&member, &ps, &rs, false) { - member.push('_'); - } + let signatures: Vec<(Vec, Option)> = (callback.methods.iter()) + .map(|method| { + let types: Vec = method.params.iter().map(|p| self.go_param(&p.ty)).collect(); + let ret = match method.ok { + Type::Unit => None, + _ => Some(self.go(&method.ok)), + }; + (types, ret) + }) + .collect(); + // An interface's method is vetted too, though never as an `error`'s. + let spelled = (callback.methods.iter().zip(&signatures)) + .map(|(method, (types, ret))| { + let ps: Vec<&str> = types.iter().map(String::as_str).collect(); + let rs: Vec<&str> = ret.iter().map(String::as_str).collect(); + let mut member = pascal(method.name()); + while vetted(&member, &ps, &rs, false) { + member.push('_'); + } + member + }) + .collect(); + let methods: Vec<&str> = callback.methods.iter().map(|method| method.name()).collect(); + let named = abi::named( + &methods, + spelled, + |rust, name| abi::snake(name) == rust, + |_, _| false, + abi::underscored, + ); + for ((method, (types, ret)), member) in callback.methods.iter().zip(signatures).zip(named) { crate::lock::function(&mut self.locked, method, &member); members.push(member.clone()); let names = self.locals(&method.params); @@ -3663,14 +3711,21 @@ fn vetted(name: &str, params: &[&str], results: &[&str], error: bool) -> bool { && !(alike(want, params, false) && alike(got, results, false)) } -/// `name`, with `_` appended until it is clear of `taken`, which then holds it. -fn unique(taken: &mut BTreeSet, mut name: String) -> String { - while !taken.insert(name.clone()) { - name.push('_'); - } - name +/// The Go names of `fields`, one scope's, each [`field_name`], kept apart from each other and +/// from `taken` as [`abi::named`] keeps them. +fn field_names(fields: &[crate::ir::Field], taken: &BTreeSet) -> Vec { + let rust: Vec<&str> = fields.iter().map(|f| f.name.as_str()).collect(); + let spelled = rust.iter().map(|name| field_name(name)).collect(); + abi::named( + &rust, + spelled, + |rust, name| abi::snake(name) == rust, + |_, name| taken.contains(name), + abi::underscored, + ) } +/// A field's Go name, in Pascal case: a positional one's is `V0`, `V1`, ... fn field_name(name: &str) -> String { match name.starts_with(|c: char| c.is_ascii_digit()) { true => format!("V{name}"), diff --git a/ffi/src/kotlin.rs b/ffi/src/kotlin.rs index ad4c18617..bac6a2f23 100644 --- a/ffi/src/kotlin.rs +++ b/ffi/src/kotlin.rs @@ -30,7 +30,9 @@ use rustc_data_structures::stable_hash::StableHasher; use crate::abi::{self, Abi, Ty, pascal}; use crate::doc; -use crate::ir::{Access, Family, Function, Int, Jni, Literal, Mutability, On, Opaque, Order, Param, Receiver, Type}; +use crate::ir::{ + Access, Family, Field, Function, Int, Jni, Literal, Mutability, On, Opaque, Order, Param, Receiver, Type, +}; const RUNTIME: &str = include_str!("../runtime/rt.kt"); /// The runtime's public types, at the generated file's top level. @@ -1466,8 +1468,14 @@ impl<'a> Gen<'a> { self.callback(i); } let mut top = Vec::new(); - for function in &api.functions { - if let Some(code) = self.function(function, None, None, Place::Static, &[]) { + let functions: Vec<&Function> = api.functions.iter().collect(); + let named = self.names(&functions, (None, None), Place::Static, |declared| { + let name = declared.split_once(' ').map_or(declared, |(_, name)| name); + taken(name) || self.names.contains_key(name) + }); + let jvm = self.jvm_named(&api.functions, (None, None), &named, &[]); + for ((function, name), jvm) in api.functions.iter().zip(&named).zip(&jvm) { + if let Some(code) = self.function(function, (None, None), Place::Static, (name, jvm), &[]) { top.push(code); } } @@ -1819,13 +1827,11 @@ impl<'a> Gen<'a> { let name = self.class(&c); let rust = abi.api.rust(&record.path, &record.args); let ty = Type::Record(i); - let fields: Vec<(String, String)> = record - .fields - .iter() - .map(|f| { - let field = field_name(&f.name); - crate::lock::field(&mut self.locked, &record.shown, &f.name, &field); - (field, self.kt(&f.ty)) + let named = field_names(&record.fields); + let fields: Vec<(String, String)> = (record.fields.iter().zip(&named)) + .map(|(f, field)| { + crate::lock::field(&mut self.locked, &record.shown, &f.name, field); + (field.clone(), self.kt(&f.ty)) }) .collect(); let mut body = Vec::new(); @@ -1836,7 +1842,24 @@ impl<'a> Gen<'a> { members.extend(holders(&opaque).iter().map(|h| format!("val {h}"))); } let owner = Ty::Struct(c.clone()); - for method in &record.methods { + let (own_members, own_statics) = (names(&body), names(&statics)); + let methods = self.methods_named( + &record.methods, + (Some(&owner), Some(&ty)), + |place, declared| match place { + Place::Member => members.iter().chain(&own_members).any(|m| m == declared), + Place::Static => own_statics.iter().any(|m| m == declared), + }, + ); + // A data class's `componentN`, which Kotlin declares for each field. + let components = (1..=fields.len()).map(|n| format!("component{n}")); + let jvm_taken: Vec = (members.iter().map(|m| jvm_name(m))) + .chain(components) + .chain(jvm_names(&body)) + .chain(jvm_names(&statics)) + .collect(); + let jvm = self.jvm_named(&record.methods, (Some(&owner), Some(&ty)), &methods, &jvm_taken); + for ((method, member), jvm) in record.methods.iter().zip(&methods).zip(&jvm) { let place = match method.receiver { Some(_) => Place::Member, None => Place::Static, @@ -1846,14 +1869,7 @@ impl<'a> Gen<'a> { Place::Member => (members.iter().cloned()).chain(names(&body)).collect(), Place::Static => names(&statics), }; - // A data class's `componentN`, which Kotlin declares for each field. - let components = (1..=fields.len()).map(|n| format!("component{n}")); - let jvm = (members.iter().map(|m| jvm_name(m))) - .chain(components) - .chain(jvm_names(&body)) - .chain(jvm_names(&statics)); - let taken = kept_apart(own, jvm); - if let Some(code) = self.function(method, Some(&owner), Some(&ty), place, &taken) { + if let Some(code) = self.function(method, (Some(&owner), Some(&ty)), place, (member, jvm), &own) { match place { Place::Member => body.push(code), Place::Static => statics.push(indent(&code)), @@ -1867,6 +1883,7 @@ impl<'a> Gen<'a> { } members.extend(body.iter().filter_map(|b| member_name(b))); self.distinct(&rust, &members); + self.distinct(&rust, &names(&statics)); if !statics.is_empty() { body.push(format!("\tcompanion object {{\n{}\t}}\n", statics.join("\n"))); } @@ -1918,13 +1935,8 @@ impl<'a> Gen<'a> { } } // The codec. - let writes: Vec = record - .fields - .iter() - .map(|f| { - let e = format!("v.{}", field_name(&f.name)); - self.write_value(&f.ty, "w", &e) - }) + let writes: Vec = (record.fields.iter().zip(&named)) + .map(|(f, field)| self.write_value(&f.ty, "w", &format!("v.{field}"))) .collect(); let reads: Vec = record.fields.iter().map(|f| self.read_value(&f.ty, "r")).collect(); let _ = write!( @@ -2015,7 +2027,30 @@ impl<'a> Gen<'a> { let mut statics = Vec::new(); self.traits(&ty, &c, e.traits, &mut body, &mut statics); let owner = abi.ty(&ty); - for method in &e.methods { + let (own_members, own_statics) = (names(&body), names(&statics)); + let methods = self.methods_named(&e.methods, (Some(&owner), Some(&ty)), |place, declared| match place { + Place::Member => own_members.iter().any(|m| m == declared), + Place::Static => own_statics.iter().any(|m| m == declared), + }); + // What a Kotlin enum declares on the JVM: its own statics, and `Enum`'s final methods. + let synthesized = match e.plain() { + true => &[ + "values", + "valueOf", + "getEntries", + "name", + "ordinal", + "compareTo", + "getDeclaringClass", + ][..], + false => &[], + }; + let jvm_taken: Vec = (synthesized.iter().map(|s| s.to_string())) + .chain(jvm_names(&body)) + .chain(jvm_names(&statics)) + .collect(); + let jvm = self.jvm_named(&e.methods, (Some(&owner), Some(&ty)), &methods, &jvm_taken); + for ((method, member), jvm) in e.methods.iter().zip(&methods).zip(&jvm) { let place = match method.receiver { Some(_) => Place::Member, None => Place::Static, @@ -2025,24 +2060,7 @@ impl<'a> Gen<'a> { Place::Member => names(&body), Place::Static => names(&statics), }; - // What a Kotlin enum declares on the JVM: its own statics, and `Enum`'s final methods. - let synthesized = match e.plain() { - true => &[ - "values", - "valueOf", - "getEntries", - "name", - "ordinal", - "compareTo", - "getDeclaringClass", - ][..], - false => &[], - }; - let jvm = (synthesized.iter().map(|s| s.to_string())) - .chain(jvm_names(&body)) - .chain(jvm_names(&statics)); - let taken = kept_apart(own, jvm); - if let Some(code) = self.function(method, Some(&owner), Some(&ty), place, &taken) { + if let Some(code) = self.function(method, (Some(&owner), Some(&ty)), place, (member, jvm), &own) { match place { Place::Member => body.push(code), Place::Static => statics.push(indent(&code)), @@ -2055,9 +2073,9 @@ impl<'a> Gen<'a> { members.push("val value".to_string()); self.distinct(&rust, &members); // An entry the library's target lacks is refused as it crosses, when its value is read. - let entries: Vec = (e.variants.iter()) - .map(|v| { - let entry = abi::snake(&v.name).to_uppercase(); + let names = variant_names(e); + let entries: Vec = (e.variants.iter().zip(&names)) + .map(|(v, entry)| { crate::lock::variant(&mut self.locked, &e.shown, &v.name, &format!("{name}.{entry}")); match abi.api.everywhere(v.on) { true => format!("\t{entry}({}),", v.discriminant), @@ -2074,10 +2092,8 @@ impl<'a> Gen<'a> { true => "", false => "open ", }; - let cases: Vec = e - .variants - .iter() - .map(|v| format!("\t\t\t{} -> {}", v.discriminant, abi::snake(&v.name).to_uppercase())) + let cases: Vec = (e.variants.iter().zip(&names)) + .map(|(v, entry)| format!("\t\t\t{} -> {entry}", v.discriminant)) .collect(); statics.push(format!( "\t\tinternal fun of(value: Int): {name} = when (value) {{\n{}\n\t\t\telse -> error(\"{c}: an invalid value\")\n\t\t}}\n", @@ -2099,16 +2115,13 @@ impl<'a> Gen<'a> { let mut reads = Vec::new(); let mut glue_reads = Vec::new(); let mut glue_writes = Vec::new(); - for (n, variant) in e.variants.iter().enumerate() { - let vname = pascal(&variant.name); + for (n, (variant, vname)) in e.variants.iter().zip(variant_names(e)).enumerate() { crate::lock::variant(&mut self.locked, &e.shown, &variant.name, &format!("{name}.{vname}")); members.push(format!("class {vname}")); - let fields: Vec = variant - .fields - .iter() - .map(|f| { - let field = field_name(&f.name); - crate::lock::variant_field(&mut self.locked, &e.shown, &variant.name, &f.name, &field); + let names = field_names(&variant.fields); + let fields: Vec = (variant.fields.iter().zip(&names)) + .map(|(f, field)| { + crate::lock::variant_field(&mut self.locked, &e.shown, &variant.name, &f.name, field); format!("val {field}: {}", self.kt(&f.ty)) }) .collect(); @@ -2118,9 +2131,8 @@ impl<'a> Gen<'a> { let on = variant.on.0 & abi.api.all().0; write.insert(0, format!("_Native.check({on}uL, \"{c}.{}\")", variant.name)); } - for f in &variant.fields { - let e = format!("v.{}", field_name(&f.name)); - write.push(self.write_value(&f.ty, "w", &e)); + for (f, field) in variant.fields.iter().zip(&names) { + write.push(self.write_value(&f.ty, "w", &format!("v.{field}"))); } let read: Vec = variant.fields.iter().map(|f| self.read_value(&f.ty, "r")).collect(); match variant.fields.is_empty() { @@ -2135,7 +2147,6 @@ impl<'a> Gen<'a> { false => { let body = match variant.fields.iter().any(|f| self.by_contents(&f.ty)) { true => { - let names: Vec = variant.fields.iter().map(|f| field_name(&f.name)).collect(); format!(" {{\n{}\t}}", indent(&Self::contents(&vname, &names))) } false => String::new(), @@ -2169,6 +2180,7 @@ impl<'a> Gen<'a> { } } self.distinct(&rust, &members); + self.distinct(&rust, &names(&statics)); if !statics.is_empty() { body.push(format!("\tcompanion object {{\n{}\t}}\n", statics.join("\n"))); } @@ -2235,7 +2247,18 @@ impl<'a> Gen<'a> { name: c.clone(), constant: false, }; - for method in &object.methods { + let (own_members, own_statics) = (names(&body), names(&statics)); + let methods = self.methods_named( + &object.methods, + (Some(&owner), Some(&ty)), + |place, declared| match place { + Place::Member => own_members.iter().any(|m| m == declared), + Place::Static => own_statics.iter().any(|m| m == declared), + }, + ); + let jvm_taken: Vec = jvm_names(&body).chain(jvm_names(&statics)).collect(); + let jvm = self.jvm_named(&object.methods, (Some(&owner), Some(&ty)), &methods, &jvm_taken); + for ((method, member), jvm) in object.methods.iter().zip(&methods).zip(&jvm) { let place = match method.receiver { Some(_) => Place::Member, None => Place::Static, @@ -2245,8 +2268,7 @@ impl<'a> Gen<'a> { Place::Member => names(&body), Place::Static => names(&statics), }; - let taken = kept_apart(own, jvm_names(&body).chain(jvm_names(&statics))); - if let Some(code) = self.function(method, Some(&owner), Some(&ty), place, &taken) { + if let Some(code) = self.function(method, (Some(&owner), Some(&ty)), place, (member, jvm), &own) { match place { Place::Member => body.push(code), Place::Static => statics.push(indent(&code)), @@ -2268,9 +2290,8 @@ impl<'a> Gen<'a> { &mut self.locked, )); } - let mut members: Vec = body.iter().filter_map(|b| member_name(b)).collect(); - members.extend(statics.iter().filter_map(|s| member_name(s))); - self.distinct(&rust, &members); + self.distinct(&rust, &names(&body)); + self.distinct(&rust, &names(&statics)); if !statics.is_empty() { body.push(format!("\tcompanion object {{\n{}\t}}\n", statics.join("\n"))); } @@ -2295,17 +2316,31 @@ impl<'a> Gen<'a> { let mut body = Vec::new(); let mut table = vec!["free: Some(rt::free_callback)".to_string()]; let mut members = Vec::new(); - for (n, method) in callback.methods.iter().enumerate() { - // Apart from what `Any` or `java.lang.Object` declares of its signature, since no - // `@JvmName` renames an interface's method, which is open. - let types: Vec = method.params.iter().map(|p| self.kt_param(&p.ty)).collect(); - let types: Vec<&str> = types.iter().map(String::as_str).collect(); - let mut member = member(&abi::snake(method.name()), &[]); - while object_method(&member, &types) - || (types.is_empty() && ["toString", "hashCode"].contains(&member.as_str())) - { - member.push('_'); - } + // Apart from what `Any` or `java.lang.Object` declares of its signature, since no + // `@JvmName` renames an interface's method, which is open. + let spelled = (callback.methods.iter()) + .map(|method| { + let types: Vec = method.params.iter().map(|p| self.kt_param(&p.ty)).collect(); + let types: Vec<&str> = types.iter().map(String::as_str).collect(); + let mut member = member(&abi::snake(method.name()), &[]).trim_matches('`').to_string(); + while object_method(&member, &types) + || (types.is_empty() && ["toString", "hashCode"].contains(&member.as_str())) + { + member.push('_'); + } + member + }) + .collect(); + let methods: Vec<&str> = callback.methods.iter().map(|method| method.name()).collect(); + let named = abi::named( + &methods, + spelled, + |rust, name| abi::snake(name) == rust, + |_, _| false, + abi::underscored, + ); + for (n, (method, member)) in callback.methods.iter().zip(&named).enumerate() { + let member = kw(member); crate::lock::function(&mut self.locked, method, &member); members.push(format!("fun {member}")); let params: Vec = (method.params.iter().zip(locals(&method.params))) @@ -2663,16 +2698,12 @@ impl<'a> Gen<'a> { doc::Target::Callback(i) => owner(doc::Owner::Callback(i)), doc::Target::Variant(i, v) => { let e = &abi.api.enums[i]; - let name = &e.variants[v].name; - match e.plain() { - true => format!("{}.{}", owner(doc::Owner::Enum(i)), abi::snake(name).to_uppercase()), - false => format!("{}.{}", owner(doc::Owner::Enum(i)), pascal(name)), - } + format!("{}.{}", owner(doc::Owner::Enum(i)), variant_names(e).swap_remove(v)) } doc::Target::Field(i, n) => format!( "{}.{}", owner(doc::Owner::Record(i)), - field_name(&abi.api.records[i].fields[n].name) + field_names(&abi.api.records[i].fields).swap_remove(n) ), doc::Target::Constant(c) => self.locked.get(&format!("const {}", c.path.join("::")))?.clone(), doc::Target::Function(of, f) => { @@ -2702,31 +2733,187 @@ impl<'a> Gen<'a> { name } - /// Check that no two members of the type `rust` share a Kotlin name. - fn distinct(&mut self, rust: &str, members: &[String]) { - let mut seen = BTreeSet::new(); - for member in members { - if !seen.insert(member) { - let name = member.split(' ').next_back().unwrap_or(member); - self.errors.push(format!( - "two members of `{rust}` are both `{name}` in Kotlin, which rust2-ffi should keep apart" - )); + /// Asserts that no two members of the type `rust`, each by its kind and Kotlin name, are + /// one, as [`abi::assert_apart`] does. + fn distinct(&self, rust: &str, members: &[String]) { + abi::assert_apart(rust, "Kotlin", members, |a, b| a == b); + } + + /// The name each of a type's `methods` takes, of `owner` (whose IR type is `owner_ty`), + /// apart from the others of its place and from what `taken` holds of that place, as + /// [`Gen::names`] keeps them. + fn methods_named( + &self, + methods: &[Function], + owner: (Option<&Ty>, Option<&Type>), + taken: impl Fn(Place, &str) -> bool, + ) -> Vec { + let mut named = vec![String::new(); methods.len()]; + for place in [Place::Member, Place::Static] { + let of: Vec = (0..methods.len()) + .filter(|&k| (methods[k].receiver.is_some()) == (place == Place::Member)) + .collect(); + let functions: Vec<&Function> = of.iter().map(|&k| &methods[k]).collect(); + for (k, name) in of + .into_iter() + .zip(self.names(&functions, owner, place, |d| taken(place, d))) + { + named[k] = name; } } + named + } + + /// The JVM method each of a type's `methods`, Kotlin's `named`, compiles to, of `owner` + /// (whose IR type is `owner_ty`): apart across both places, since a companion's + /// `@JvmStatic` member shares the class's names, from the JVM methods `taken` names and + /// `java.lang.Object`'s, as [`abi::named`] keeps a scope's. So of Rust's `count(&self)` + /// and `count_()`, both Kotlin's `count`, the method keeps `count` on the JVM in either + /// order. + fn jvm_named( + &mut self, + methods: &[Function], + (owner, owner_ty): (Option<&Ty>, Option<&Type>), + named: &[String], + taken: &[String], + ) -> Vec { + let abi = self.abi; + let (mut rust, mut spelled, mut getters, mut types) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + for (method, member) in methods.iter().zip(named) { + let place = match method.receiver { + Some(_) => Place::Member, + None => Place::Static, + }; + let (name, declared) = self.spelled(method, (owner, owner_ty), place); + let kind = declared.split_once(' ').map_or("fun", |(kind, _)| kind); + // The parameter types `function_on` declares, which `object_method` reads. + let (back, export) = match (owner.zip(owner_ty)).and_then(|(o, ty)| abi.handed_back(method, o, ty)) { + Some((back, export, _)) => (Some(back), export), + None => (None, abi.export(method, owner)), + }; + let function = back.as_ref().unwrap_or(method); + let params: Vec = match export.future { + Some(_) => vec!["kotlin.coroutines.Continuation".to_string()], + None => (function.params.iter()) + .filter(|p| p.ty != Type::Jni(Jni::Env)) + .map(|p| self.kt_param(&p.ty)) + .collect(), + }; + rust.push(name); + spelled.push(jvm_name(&format!("{kind} {member}"))); + getters.push(kind == "val"); + types.push(params); + } + let rust: Vec<&str> = rust.iter().map(String::as_str).collect(); + let own = |rust: &str, jvm: &str| jvm == rust || abi::snake(jvm) == rust; + let taken = |k: usize, jvm: &str| { + let params: Vec<&str> = types[k].iter().map(String::as_str).collect(); + taken.iter().any(|t| t == jvm) || (!getters[k] && object_method(jvm, ¶ms)) + }; + abi::named(&rust, spelled, own, taken, abi::underscored) + } + + /// The name each of `functions` takes in `place` of `owner` (whose IR type is + /// `owner_ty`) if it has one, or at the top level, apart from each other and from what + /// `taken` holds of a declaration's kind and name, such as `fun of`, as [`abi::named`] + /// keeps a scope's. + fn names( + &self, + functions: &[&Function], + (owner, owner_ty): (Option<&Ty>, Option<&Type>), + place: Place, + taken: impl Fn(&str) -> bool, + ) -> Vec { + let (rust, spelled): (Vec, Vec) = (functions.iter()) + .map(|function| self.spelled(function, (owner, owner_ty), place)) + .unzip(); + let rust: Vec<&str> = rust.iter().map(String::as_str).collect(); + let unkind = |declared: &str| { + declared + .split_once(' ') + .map_or(declared.to_string(), |(_, name)| name.to_string()) + }; + // A constant's upper case reads back as it is, and each other's camel case in snake case. + let own = |rust: &str, declared: &str| { + let name = unkind(declared); + name == rust || abi::snake(&name) == rust + }; + let quoted = |declared: &str| match declared.split_once(' ') { + Some((kind, name)) => taken(&format!("{kind} {}", kw(name))), + None => taken(declared), + }; + (abi::named(&rust, spelled, own, |_, name| quoted(name), abi::underscored).iter()) + .map(|declared| kw(&unkind(declared))) + .collect() + } + + /// The declaration `function` makes in `place` of `owner` (whose IR type is `owner_ty`) + /// if it has one, before it keeps apart from any other: the Rust name it spells, and its + /// kind and Kotlin name, unquoted, such as `fun intoLabel`. + fn spelled( + &self, + function: &Function, + (owner, owner_ty): (Option<&Ty>, Option<&Type>), + place: Place, + ) -> (String, String) { + let abi = self.abi; + let (back, export) = match (owner.zip(owner_ty)).and_then(|(owner, ty)| abi.handed_back(function, owner, ty)) { + Some((back, export, _)) => (Some(back), export), + None => (None, abi.export(function, owner)), + }; + let function = back.as_ref().unwrap_or(function); + let owner_c = match owner { + Some(Ty::Struct(n) | Ty::Enum(n) | Ty::Handle { name: n, .. }) => Some(n.as_str()), + _ => None, + }; + let own = owner_c.and_then(|o| export.named.strip_prefix(o)?.strip_prefix('_')); + let reserved: &[&str] = match owner_ty { + Some(Type::Object(_)) => &["close", "equals", "hashCode", "toString", "handle"], + Some(Type::Record(_)) => &["copy", "equals", "hashCode", "toString"], + // A plain enum is a Kotlin enum, which has its own. + Some(Type::Enum(i)) if abi.api.enums[*i].plain() => &[ + "equals", + "hashCode", + "toString", + "of", + "value", + "name", + "ordinal", + "compareTo", + ], + Some(_) => &["equals", "hashCode", "toString"], + None => &[], + }; + // Named as Rust's path is, whatever C's clashes rename. + let rust = own.unwrap_or_else(|| self.bare(&export.named)).to_string(); + let member = member(&rust, reserved); + let member = member.trim_matches('`'); + let receiver = function.receiver.filter(|_| owner.is_some()); + let property = matches!( + (function.access, place, receiver), + (Access::Field { .. }, Place::Member, _) | (Access::Const, _, None) + ) && function.params.is_empty(); + let declared = match (property, function.access) { + (true, Access::Const) => format!("val {}", member.to_uppercase()), + (true, _) => format!("val {member}"), + (false, _) => format!("fun {member}"), + }; + (rust, declared) } - /// `function`'s Kotlin form, a member of `owner` (whose IR type is `owner_ty`) if it - /// has one, apart from the members `taken` names, with its native methods and glue. + /// `function`'s Kotlin form `member`, compiled to the JVM method `jvm`, of `owner` (whose + /// IR type is `owner_ty`) if it has one, apart from the members `taken` names, with its + /// native methods and glue. fn function( &mut self, function: &Function, - owner: Option<&Ty>, - owner_ty: Option<&Type>, + owner: (Option<&Ty>, Option<&Type>), place: Place, + (member, jvm): (&str, &str), taken: &[String], ) -> Option { let on = std::mem::replace(&mut self.on, function.on); - let code = self.function_on(function, owner, owner_ty, place, taken); + let code = self.function_on(function, owner, place, (member, jvm), taken); self.on = on; code } @@ -2734,9 +2921,9 @@ impl<'a> Gen<'a> { fn function_on( &mut self, function: &Function, - owner: Option<&Ty>, - owner_ty: Option<&Type>, + (owner, owner_ty): (Option<&Ty>, Option<&Type>), place: Place, + (member, jvm): (&str, &str), taken: &[String], ) -> Option { let abi = self.abi; @@ -2760,35 +2947,6 @@ impl<'a> Gen<'a> { ); let c_name = export.call.name.clone(); let bare = self.bare(&c_name).to_string(); - let owner_c = match owner { - Some(Ty::Struct(n) | Ty::Enum(n) | Ty::Handle { name: n, .. }) => Some(n.clone()), - _ => None, - }; - let own = match &owner_c { - Some(o) => export.named.strip_prefix(o.as_str()).and_then(|r| r.strip_prefix('_')), - None => None, - }; - let reserved: &[&str] = match owner_ty { - Some(Type::Object(_)) => &["close", "equals", "hashCode", "toString", "handle"], - Some(Type::Record(_)) => &["copy", "equals", "hashCode", "toString"], - // A plain enum is a Kotlin enum, which has its own. - Some(Type::Enum(i)) if abi.api.enums[*i].plain() => &[ - "equals", - "hashCode", - "toString", - "of", - "value", - "name", - "ordinal", - "compareTo", - ], - Some(_) => &["equals", "hashCode", "toString"], - None => &[], - }; - // Named as Rust's path is, whatever C's clashes rename. - let named = self.bare(&export.named).to_string(); - let snake = own.unwrap_or(&named); - let member = member(snake, reserved); let mut n = 0; let mut args: Vec = Vec::new(); @@ -3506,19 +3664,16 @@ impl<'a> Gen<'a> { (function.access, place, receiver), (Access::Field { .. }, Place::Member, _) | (Access::Const, _, None) ) && function.params.is_empty(); - let member = match function.access { - Access::Const if property => member.to_uppercase(), - _ => member, - }; let top = owner.is_none(); let kind = match property { true => "val", false => "fun", }; let mut member = match top { - true => self.claim(&member, format!("fn `{}`", function.path.join("::"))), - false => member, + true => self.claim(member, format!("fn `{}`", function.path.join("::"))), + false => member.to_string(), }; + // A member its type declares already takes a trailing `_`. while taken.contains(&format!("{kind} {member}")) { member = format!("{}_", member.trim_matches('`')); @@ -3545,27 +3700,16 @@ impl<'a> Gen<'a> { if place == Place::Static && !top { annotations.push_str("@kotlin.jvm.JvmStatic\n"); } - // A JVM method its class declares already, in either place, since a companion's - // `@JvmStatic` member shares the class's names, as a field's getter `getX` does, - // leaves the Kotlin name alone and takes a trailing `_` on the JVM. + // A JVM name [`Gen::jvm_named`] moved leaves the Kotlin name alone. let target = if getter { "get:" } else { "" }; let declared = jvm_name(&format!("{kind} {member}")); - let mut jvm = declared.clone(); - // A suspending function takes its continuation too, so clashes with none of `Object`'s. - let types: Vec<&str> = match export.future { - Some(_) => vec!["kotlin.coroutines.Continuation"], - None => (kt_params.iter()).filter_map(|p| Some(p.split_once(": ")?.1)).collect(), - }; - while taken.contains(&format!("jvm {jvm}")) || (!getter && object_method(&jvm, &types)) { - jvm.push('_'); - } if jvm != declared { let _ = writeln!(annotations, "@{target}kotlin.jvm.JvmName(\"{jvm}\")"); } // Java calls it by its JVM name, which the lock keeps beside the Kotlin one, so a // member added beside it that moves it is a break even where it had none. let key = format!("{} / jvm", crate::lock::function_key(function)); - self.locked.insert(key, jvm.clone()); + self.locked.insert(key, jvm.to_string()); if let Some(exception) = &exception { let _ = writeln!(annotations, "@{target}kotlin.jvm.Throws({exception}::class)"); } @@ -3661,8 +3805,9 @@ impl<'a> Gen<'a> { return from_kotlin(&opaque, &words); } let mut fields = Vec::new(); - for (k, field) in abi.api.records[i].fields.iter().enumerate() { - let e = format!("{e}.{}", field_name(&field.name)); + let names = field_names(&abi.api.records[i].fields); + for (k, (field, name)) in abi.api.records[i].fields.iter().zip(&names).enumerate() { + let e = format!("{e}.{name}"); let value = match &field.ty { Type::Record(j) => self.flat_in(*j, &e, (&mut *arg, &mut *n), (w, &mut *writes), r), ty if scalar(abi, ty) => { @@ -4301,17 +4446,55 @@ fn camel(name: &str) -> String { } } -/// The Kotlin names of parameters, in camel case, [`abi::distinct`], and quoted if a -/// keyword. +/// The Kotlin names of parameters, in camel case, kept apart as [`abi::distinct`] keeps +/// them, and quoted if a keyword. fn locals(params: &[Param]) -> Vec { - (abi::distinct(params.iter().map(|p| camel(&p.name))).iter()) + (abi::distinct(params, camel, |_| false).iter()) .map(|name| kw(name)) .collect() } -/// A field's Kotlin name. -fn field_name(name: &str) -> String { - kw(&camel(name)) +/// The Kotlin names of the variants of `e`, one scope's as [`abi::named`] keeps them apart: a +/// plain enum's entries in upper snake case, and a data enum's classes in Pascal case. +fn variant_names(e: &crate::ir::Enum) -> Vec { + let rust: Vec<&str> = e.variants.iter().map(|v| v.name.as_str()).collect(); + match e.plain() { + true => { + let spelled = rust.iter().map(|name| abi::snake(name).to_uppercase()).collect(); + abi::named( + &rust, + spelled, + |rust, name| pascal(&name.to_lowercase()) == rust, + |_, _| false, + abi::underscored, + ) + } + false => { + let spelled = rust.iter().map(|name| pascal(name)).collect(); + abi::named( + &rust, + spelled, + |rust, name| name == rust, + |_, _| false, + abi::underscored, + ) + } + } +} + +/// The Kotlin names of `fields`, one scope's, in camel case as [`abi::named`] keeps them +/// apart, and quoted where a keyword. +fn field_names(fields: &[Field]) -> Vec { + let rust: Vec<&str> = fields.iter().map(|f| f.name.as_str()).collect(); + let spelled = rust.iter().map(|name| camel(name)).collect(); + let names = abi::named( + &rust, + spelled, + |rust, name| abi::snake(name) == rust, + |_, _| false, + abi::underscored, + ); + names.iter().map(|name| kw(name)).collect() } /// A member's Kotlin name: in camel case, quoted if a keyword, or with `_` appended if diff --git a/ffi/src/lock.rs b/ffi/src/lock.rs index 35a28a5fd..301ee4184 100644 --- a/ffi/src/lock.rs +++ b/ffi/src/lock.rs @@ -63,7 +63,12 @@ pub(crate) fn variants( /// Record the name a binding gives the field `field` of the record at `owner`. pub(crate) fn field(names: &mut BTreeMap, owner: &[String], field: &str, name: &str) { - names.insert(format!("{} / field {field}", type_key(owner)), name.to_string()); + names.insert(field_key(owner, field), name.to_string()); +} + +/// The key [`field`] records the name of the field `field` of the record at `owner` under. +pub(crate) fn field_key(owner: &[String], field: &str) -> String { + format!("{} / field {field}", type_key(owner)) } /// Record the name a binding gives the variant `variant` of the enum at `owner`. @@ -1008,13 +1013,15 @@ mod tests { }; let mut base = api(); base.objects.push(object("Fault")); - base.objects[0].variants = vec![variant("FooBar")]; + base.objects[0].variants = vec![variant("Foo_Bar")]; base.functions[0].err = Some(Type::Object(0)); let old = crate::python::generate(&Abi::new(&base, "lock"), "lock", 0).unwrap(); - assert_eq!(old.names["error Fault / variant FooBar"], "FaultException.FooBar"); - // `Foo_Bar` added first takes `FooBar`, which the kept variant had. + assert_eq!(old.names["error Fault / variant Foo_Bar"], "FaultException.FooBar"); + // `FooBar` added, which Python spells as its Rust, takes `FooBar` from the kept + // variant, whichever comes first. let mut now = base.clone(); - now.objects[0].variants.insert(0, variant("Foo_Bar")); + now.objects[0].variants.push(variant("FooBar")); + assert!( breaks(&base, &now, "lock").is_empty(), "an added variant passes structurally" diff --git a/ffi/src/python.rs b/ffi/src/python.rs index 9af60c914..3e06849ef 100644 --- a/ffi/src/python.rs +++ b/ffi/src/python.rs @@ -525,8 +525,6 @@ impl<'a> Gen<'a> { /// defines `__x__` names, such as the module's own `__all__` and `__getattr__`, which /// one takes a trailing `_` past. fn claim(&mut self, name: &str, what: String) -> String { - let dunder = - |name: &str| name.len() > 4 && name.starts_with("__") && name.ends_with("__") && !name.ends_with("___"); abi::claim(&mut self.names, dunder, name, what) } @@ -881,10 +879,22 @@ impl<'a> Gen<'a> { for i in 0..api.callbacks.len() { self.callback(i); } - // The glue's functions, declared for type checkers and bound to its own. + // The glue's functions, declared for type checkers and bound to its own, kept apart + // as one scope. let (mut declared, mut bound) = (Vec::new(), Vec::new()); - for function in &api.functions { - match self.function(function, None, None, Place::Top) { + let (rust, spelled): (Vec, Vec) = (api.functions.iter()) + .map(|function| self.spelled(function, None, Place::Top, &[])) + .unzip(); + let rust: Vec<&str> = rust.iter().map(String::as_str).collect(); + let named = abi::named( + &rust, + spelled, + |rust, name| name == rust, + |_, name| dunder(name) || self.names.contains_key(name), + abi::underscored, + ); + for (function, member) in api.functions.iter().zip(&named) { + match self.function(function, None, Place::Top, member) { Some(Form::Native(code, binding)) => { bound.push(indent_by(&binding.expect("a module's function is bound"), 1)); declared.push(indent_by(&code, 1)); @@ -947,9 +957,9 @@ impl<'a> Gen<'a> { return; } }; - let vnames = variant_classes(variants.iter().copied()); - // Kept apart by order, a subclass's name is locked, so a variant added before one - // whose name it takes breaks the baseline. + let vnames = variant_classes(&variants); + // A subclass's name is locked, so a variant added whose name it takes breaks the + // baseline. for (variant, vname) in variants.iter().zip(&vnames) { self.locked .insert(format!("{key} / variant {variant}"), format!("{name}.{vname}")); @@ -984,8 +994,9 @@ impl<'a> Gen<'a> { _ => unreachable!("an enum"), }; let entries: Vec = (e.variants.iter().zip(&vnames)) - .map(|(v, vname)| match e.plain() { - true => format!("\t{py}.{}: _{name}_{vname},\n", abi::snake(&v.name).to_uppercase()), + .zip(values(e)) + .map(|((_, vname), value)| match e.plain() { + true => format!("\t{py}.{value}: _{name}_{vname},\n"), false => format!("\t_{py}_{vname}: _{name}_{vname},\n"), }) .collect(); @@ -1343,19 +1354,33 @@ impl<'a> Gen<'a> { true => &["__aiter__", "__anext__"], false => &[], }; - for method in methods { - let place = match method.receiver { - Some(_) => Place::Member, - None => Place::Static, - }; - // A name its data or an earlier member takes, its own takes a trailing `_` against. - let earlier: Vec = body.codes().filter_map(|code| member_name(code)).collect(); - let reserved: Vec<&str> = (reserved.iter().copied()) - .chain(protocol.iter().copied()) - .chain(data.iter().map(String::as_str)) - .chain(earlier.iter().map(String::as_str)) - .collect(); - let code = match self.function(method, Some(owner), Some((ty, &reserved)), place) { + // A name its data or a member its traits made takes, its own takes a trailing `_` + // against, and the methods, of either place, keep apart as one scope. + let made: Vec = body.codes().filter_map(|code| member_name(code)).collect(); + let reserved: Vec<&str> = (reserved.iter().copied()) + .chain(protocol.iter().copied()) + .chain(data.iter().map(String::as_str)) + .chain(made.iter().map(String::as_str)) + .collect(); + let place = |method: &Function| match method.receiver { + Some(_) => Place::Member, + None => Place::Static, + }; + let (names, spelled): (Vec, Vec) = (methods.iter()) + .map(|method| self.spelled(method, Some((owner, ty)), place(method), &reserved)) + .unzip(); + let own: Vec<&str> = names.iter().map(String::as_str).collect(); + let taken = |name: &str| reserved.contains(&name) || TAKEN.contains(&name); + let named = abi::named( + &own, + spelled, + |rust, name| name == rust, + |_, name| taken(name), + abi::underscored, + ); + for (method, member) in methods.iter().zip(&named) { + let place = place(method); + let code = match self.function(method, Some((owner, ty)), place, member) { Some(Form::Native(code, binding)) => { body.native.push(indent_by(&code, 1)); body.runtime.extend(binding.map(|b| indent_by(&b, 1))); @@ -1391,16 +1416,15 @@ impl<'a> Gen<'a> { [aiter.to_string(), format!("{}{anext}", deprecator(deprecated))] } - /// Check that the members `codes` of the type `rust` and its data's names `data` differ. - fn distinct<'c>(&mut self, rust: &str, data: &[String], codes: impl Iterator) { - let mut seen = BTreeSet::new(); - for name in data.iter().cloned().chain(codes.filter_map(|code| member_name(code))) { - if !seen.insert(name.clone()) { - self.errors.push(format!( - "two members of `{rust}` are both `{name}` in Python, which rust2-ffi should keep apart" - )); - } - } + /// Asserts that the members `codes` of the type `rust` and its data's names `data` + /// differ, as [`abi::assert_apart`] does. + fn distinct<'c>(&self, rust: &str, data: &[String], codes: impl Iterator) { + let members: Vec = data + .iter() + .cloned() + .chain(codes.filter_map(|code| member_name(code))) + .collect(); + abi::assert_apart(rust, "Python", &members, |a, b| a == b); } fn record(&mut self, i: usize) { @@ -1418,7 +1442,9 @@ impl<'a> Gen<'a> { } self.traits(&ty, &c, record.traits, &mut body); let owner = Ty::Struct(c.clone()); - let data: Vec = record.fields.iter().map(|f| field_name(&f.name)).collect(); + // A field yields to a member its traits made, as a method does. + let made: Vec = body.codes().filter_map(|code| member_name(code)).collect(); + let data = field_names(&record.fields, |name| made.iter().any(|m| m == name)); self.methods(&record.methods, (&ty, &owner, &rust), &data, &[], &mut body); if record.opaque.is_some() { let text = format!( @@ -1438,12 +1464,11 @@ impl<'a> Gen<'a> { ); return; } - let fields: Vec = (record.fields.iter()) - .map(|f| Slot { + let fields: Vec = (record.fields.iter().zip(&data)) + .map(|(f, name)| Slot { name: { - let name = field_name(&f.name); - crate::lock::field(&mut self.locked, &record.shown, &f.name, &name); - name + crate::lock::field(&mut self.locked, &record.shown, &f.name, name); + name.clone() }, ty: self.py_field(&f.ty), docs: deprecation(&f.docs, f.deprecated.as_deref()), @@ -1461,8 +1486,8 @@ impl<'a> Gen<'a> { let mut reads = Vec::new(); let mut fields = Vec::new(); let mut writes = Vec::new(); - for (n, field) in record.fields.iter().enumerate() { - let key = self.key(&field_name(&field.name)); + for (n, (field, name)) in record.fields.iter().zip(&data).enumerate() { + let key = self.key(name); let read = match n { 0 => format!("rt::field(o, {t}, {key}, s)?"), _ => format!("rt::attr(o, {key}, s)?"), @@ -1512,7 +1537,7 @@ impl<'a> Gen<'a> { "fn on_{c}(v: i32) -> R {{\n\tmatch v {{\n{missing}\t\t_ => Ok(v),\n\t}}\n}}\n\n" ); } - let data: Vec = e.variants.iter().map(|v| abi::snake(&v.name).to_uppercase()).collect(); + let data = values(e); // An `Enum`'s members have these. self.methods(&e.methods, (&ty, &owner, &rust), &data, &["name", "value"], &mut body); for (v, member) in e.variants.iter().zip(&data) { @@ -1534,18 +1559,18 @@ impl<'a> Gen<'a> { return; } // Each variant's class, and its fields, which on an instance hide the enum's members. - let vnames = variant_classes(e.variants.iter().map(|v| v.name.as_str())); + let vnames = variant_classes(&e.variants.iter().map(|v| v.name.as_str()).collect::>()); for (variant, vname) in e.variants.iter().zip(&vnames) { crate::lock::variant(&mut self.locked, &e.shown, &variant.name, &format!("{name}.{vname}")); } - let mut data = vnames.clone(); - let fields: BTreeSet = e - .variants - .iter() - .flat_map(|v| &v.fields) - .map(|f| field_name(&f.name)) + // A field yields to a member its traits made, as a method does, and to a variant's class, + // which a name of no case, such as `名`, spells alike. + let made: Vec = body.codes().filter_map(|code| member_name(code)).collect(); + let named: Vec> = (e.variants.iter()) + .map(|v| field_names(&v.fields, |name| made.iter().chain(&vnames).any(|m| m == name))) .collect(); - data.extend(fields); + let mut data = vnames.clone(); + data.extend(named.iter().flatten().cloned().collect::>()); self.methods(&e.methods, (&ty, &owner, &rust), &data, &[], &mut body); // Each variant's class is bound on the enum's once made, after the enum's own. for vname in &vnames { @@ -1564,16 +1589,15 @@ impl<'a> Gen<'a> { ); let mut reads = Vec::new(); let mut writes = Vec::new(); - for (n, (variant, vname)) in e.variants.iter().zip(&vnames).enumerate() { + for (n, ((variant, vname), names)) in e.variants.iter().zip(&vnames).zip(&named).enumerate() { let class = format!("_{name}_{vname}"); let key = abi::payload(&c, &variant.name); let tv = self.register(&key, class.clone()); - let fields: Vec = (variant.fields.iter()) - .map(|f| Slot { + let fields: Vec = (variant.fields.iter().zip(names)) + .map(|(f, name)| Slot { name: { - let name = field_name(&f.name); - crate::lock::variant_field(&mut self.locked, &e.shown, &variant.name, &f.name, &name); - name + crate::lock::variant_field(&mut self.locked, &e.shown, &variant.name, &f.name, name); + name.clone() }, ty: self.py_field(&f.ty), docs: f.docs.clone(), @@ -1605,8 +1629,8 @@ impl<'a> Gen<'a> { let mut binds = Vec::new(); let mut fields = Vec::new(); let mut lowers = Vec::new(); - for (k, f) in variant.fields.iter().enumerate() { - let key = self.key(&field_name(&f.name)); + for (k, (f, name)) in variant.fields.iter().zip(names).enumerate() { + let key = self.key(name); binds.push(format!("let x{k} = rt::attr(o, {key}, s)?;")); fields.push(format!("f{k}: {}?", self.lift(&f.ty, &format!("x{k}"), "take"))); lowers.push(format!("({key}, {})", self.lower(&f.ty, &format!("p.f{k}")))); @@ -1673,12 +1697,18 @@ impl<'a> Gen<'a> { self.register(&c, name.clone()); let mut body = Vec::new(); let mut table = vec!["free: Some(rt::free_callback)".to_string()]; - let mut names: Vec = Vec::new(); - for (n, method) in callback.methods.iter().enumerate() { - // A name an earlier method took, its own takes a trailing `_` against. - let reserved: Vec<&str> = names.iter().map(String::as_str).collect(); - let member = member(&abi::snake(method.name()), &reserved); - names.push(member.clone()); + // One scope, kept apart as [`abi::named`] keeps it: beside Rust's `from_`, `from`, a + // keyword in Python, takes `from__`, in either order. + let rust_names: Vec<&str> = callback.methods.iter().map(|method| method.name()).collect(); + let spelled = rust_names.iter().map(|name| member(&abi::snake(name), &[])).collect(); + let named = abi::named( + &rust_names, + spelled, + |rust, name| name == rust, + |_, name| TAKEN.contains(&name), + abi::underscored, + ); + for (n, (method, member)) in callback.methods.iter().zip(named).enumerate() { crate::lock::function(&mut self.locked, method, &member); let params: Vec = std::iter::once("self".to_string()) .chain( @@ -1866,11 +1896,10 @@ impl<'a> Gen<'a> { doc::Target::Callback(i) => ("class", owner(doc::Owner::Callback(i))), doc::Target::Variant(i, v) => { let e = &abi.api.enums[i]; - let name = &e.variants[v].name; match e.plain() { true => ( "attr", - format!("{}.{}", owner(doc::Owner::Enum(i)), abi::snake(name).to_uppercase()), + format!("{}.{}", owner(doc::Owner::Enum(i)), values(e).swap_remove(v)), ), // As its class is named, apart from its siblings'. false => ( @@ -1878,19 +1907,21 @@ impl<'a> Gen<'a> { format!( "{}.{}", owner(doc::Owner::Enum(i)), - variant_classes(e.variants.iter().map(|v| v.name.as_str())).swap_remove(v) + variant_classes(&e.variants.iter().map(|v| v.name.as_str()).collect::>()) + .swap_remove(v) ), ), } } - doc::Target::Field(i, n) => ( - "attr", - format!( - "{}.{}", - owner(doc::Owner::Record(i)), - field_name(&abi.api.records[i].fields[n].name) - ), - ), + // As the record named it, apart from its traits' members. + doc::Target::Field(i, n) => { + let record = &abi.api.records[i]; + let key = crate::lock::field_key(&record.shown, &record.fields[n].name); + ( + "attr", + format!("{}.{}", owner(doc::Owner::Record(i)), self.locked.get(&key)?), + ) + } doc::Target::Constant(c) => ( "data", self.locked.get(&format!("const {}", c.path.join("::")))?.clone(), @@ -2022,17 +2053,52 @@ impl<'a> Gen<'a> { } } - /// `function`'s Python form, a member of `owner` if it has one (whose IR type and - /// reserved member names are `owner_ty`), with its native function and glue. + /// The Python name `function` spells in `place` of `owner` (with its IR type) if it has + /// one, before it keeps apart from another's: the Rust name it spells, and its own, with + /// `_` appended until none of `reserved`. A constant's is in upper case, which can join + /// two Rust names, as icu_properties' `SentenceBreak::Sp` and its alias `SP`. + fn spelled( + &self, + function: &Function, + owner: Option<(&Ty, &Type)>, + place: Place, + reserved: &[&str], + ) -> (String, String) { + let abi = self.abi; + let (back, export) = match owner.and_then(|(owner, ty)| abi.handed_back(function, owner, ty)) { + Some((back, export, _)) => (Some(back), export), + None => (None, abi.export(function, owner.map(|(owner, _)| owner))), + }; + let function = back.as_ref().unwrap_or(function); + let own = match owner { + Some((Ty::Struct(o) | Ty::Enum(o) | Ty::Handle { name: o, .. }, _)) => { + export.named.strip_prefix(o.as_str()).and_then(|r| r.strip_prefix('_')) + } + _ => None, + }; + // Named as Rust's path is, whatever C's clashes rename. + let rust = own.unwrap_or_else(|| self.bare(&export.named)).to_string(); + let member = member(&abi::snake(&rust), reserved); + let constant = function.access == Access::Const && function.params.is_empty() && place != Place::Member; + let member = match (place, constant) { + (Place::Top, true) => member.to_uppercase(), + (Place::Static, true) => self::member(&member.to_uppercase(), reserved), + _ => member, + }; + (rust, member) + } + + /// `function`'s Python form `member`, of `owner` (with its IR type) if it has one, with + /// its native function and glue. fn function( &mut self, function: &Function, - owner: Option<&Ty>, - owner_ty: Option<(&Type, &[&str])>, + owner: Option<(&Ty, &Type)>, place: Place, + member: &str, ) -> Option
{ let on = std::mem::replace(&mut self.on, function.on); - let form = self.function_on(function, owner, owner_ty, place); + let form = self.function_on(function, owner, place, member); self.on = on; form } @@ -2040,14 +2106,15 @@ impl<'a> Gen<'a> { fn function_on( &mut self, function: &Function, - owner: Option<&Ty>, - owner_ty: Option<(&Type, &[&str])>, + owned: Option<(&Ty, &Type)>, place: Place, + member: &str, ) -> Option { let abi = self.abi; + let (owner, owner_ty) = (owned.map(|(owner, _)| owner), owned.map(|(_, ty)| ty)); // A value is immutable in Python, so its `&mut self` method returns it as the call // left it, calling the C function in place on a copy it hands back. - let handed = (owner.zip(owner_ty)).and_then(|(owner, (ty, _))| abi.handed_back(function, owner, ty)); + let handed = owned.and_then(|(owner, ty)| abi.handed_back(function, owner, ty)); let (back, export, handed) = match handed { Some((back, export, handed)) => (Some(back), export, Some(handed)), None => (None, abi.export(function, owner), None), @@ -2059,23 +2126,11 @@ impl<'a> Gen<'a> { Some(Ty::Struct(n) | Ty::Enum(n) | Ty::Handle { name: n, .. }) => Some(n.clone()), _ => None, }; - let own = match &owner_c { - Some(o) => export.named.strip_prefix(o.as_str()).and_then(|r| r.strip_prefix('_')), - None => None, - }; - let reserved = owner_ty.map_or(&[][..], |(_, r)| r); - // Named as Rust's path is, whatever C's clashes rename. - let named = self.bare(&export.named).to_string(); - let snake = own.unwrap_or(&named); - let member = member(&abi::snake(snake), reserved); let constant = function.access == Access::Const && function.params.is_empty() && place != Place::Member; let member = match (place, constant) { - (Place::Top, true) => self.claim(&member.to_uppercase(), format!("const `{}`", function.path.join("::"))), - (Place::Top, false) => self.claim(&member, format!("fn `{}`", function.path.join("::"))), - // Upper case can join two Rust names, as icu_properties' `SentenceBreak::Sp` - // and its alias `SP`, so the later is kept apart again. - (Place::Static, true) => self::member(&member.to_uppercase(), reserved), - _ => member, + (Place::Top, true) => self.claim(member, format!("const `{}`", function.path.join("::"))), + (Place::Top, false) => self.claim(member, format!("fn `{}`", function.path.join("::"))), + _ => member.to_string(), }; crate::lock::function(&mut self.locked, function, &member); @@ -2093,7 +2148,7 @@ impl<'a> Gen<'a> { let receiver = function.receiver.filter(|_| owner.is_some()); if let Some(receiver) = receiver { let (_, c) = c_params.next().expect("a method has its receiver"); - let ty = owner_ty.expect("a method has its type").0.clone(); + let ty = owner_ty.expect("a method has its type").clone(); py_params.push("self".to_string()); py_args.push("self".to_string()); native_params.push(format!("p0: {}", self.py_ty(&ty))); @@ -2237,7 +2292,7 @@ impl<'a> Gen<'a> { None => format!("crate::{c_name}({})", args.join(", ")), }; // A leaf keeps the GIL, which no part of it can wait on: see `Abi::leaf`. - let call = match abi.leaf(function, owner_ty.map(|(ty, _)| ty)) { + let call = match abi.leaf(function, owner_ty) { true => format!("rt::leaf(|| {call})"), false => format!("rt::call(|| {call})"), }; @@ -2358,7 +2413,7 @@ impl<'a> Gen<'a> { .push(format!("@_staticmethod\ndef {bare}() -> {ret}: ...\n")); // An `Enum` makes a member of any other value, to a type checker as at run time. let value = match owner_ty { - Some((Type::Enum(i), _)) if abi.api.enums[*i].plain() => format!("_enum.nonmember(_n.{bare}())"), + Some(Type::Enum(i)) if abi.api.enums[*i].plain() => format!("_enum.nonmember(_n.{bare}())"), _ => format!("_n.{bare}()"), }; return Some(Form::Native( @@ -2507,18 +2562,65 @@ fn member(snake: &str, reserved: &[&str]) -> String { name } -/// The class names of variants `names`, as Python spells them: `FooBar` for Rust's -/// `FooBar` and `Foo_Bar` alike, so a later one an earlier one took takes a trailing `_`. -fn variant_classes<'n>(names: impl Iterator) -> Vec { - let mut classes: Vec = Vec::new(); - for name in names { - let mut class = kw(&pascal(name)); - while classes.contains(&class) { - class.push('_'); - } - classes.push(class); - } - classes +/// Whether a module-level `name` is a `__x__` name Python defines, such as `__all__`, which +/// one ending in `___` is not. +fn dunder(name: &str) -> bool { + name.len() > 4 && name.starts_with("__") && name.ends_with("__") && !name.ends_with("___") +} + +/// The class names of variants `names`, as Python spells them, `FooBar` for Rust's `FooBar` +/// and `Foo_Bar` alike, kept apart as [`abi::named`] keeps a scope's. +fn variant_classes(names: &[&str]) -> Vec { + let spelled = names.iter().map(|name| kw(&pascal(name))).collect(); + abi::named( + names, + spelled, + |rust, name| name == rust, + |_, _| false, + abi::underscored, + ) +} + +/// The Python names of the plain enum `e`'s values, in upper snake case, kept apart as +/// [`abi::named`] keeps a scope's. +fn values(e: &crate::ir::Enum) -> Vec { + let rust: Vec<&str> = e.variants.iter().map(|v| v.name.as_str()).collect(); + value_names(&rust) +} + +/// [`values`] of the variants `rust`, clear of the names an `_enum.Enum`'s body makes no +/// member of: it refuses a `_X_` name, skips a `__X__` one, and the class body mangles a `__X` +/// one private. +fn value_names(rust: &[&str]) -> Vec { + let spelled = rust.iter().map(|name| abi::snake(name).to_uppercase()).collect(); + // `enum`'s own `_is_sunder` and `_is_dunder`, and the compiler's mangling. + let between = |name: &str, ends: &str| { + let inner = name.strip_prefix(ends).and_then(|name| name.strip_suffix(ends)); + inner.is_some_and(|inner| !inner.is_empty() && !inner.starts_with('_') && !inner.ends_with('_')) + }; + let private = |name: &str| name.starts_with("__") && !name.ends_with("__"); + let unmember = |name: &str| between(name, "_") || between(name, "__") || private(name); + abi::named( + rust, + spelled, + |rust, name| pascal(&name.to_lowercase()) == rust, + |_, name| unmember(name), + abi::underscored, + ) +} + +/// The Python names of `fields`, one scope's, kept apart from each other and from what +/// `taken` holds as [`abi::named`] keeps them. +fn field_names(fields: &[crate::ir::Field], taken: impl Fn(&str) -> bool) -> Vec { + let rust: Vec<&str> = fields.iter().map(|f| f.name.as_str()).collect(); + let spelled = rust.iter().map(|name| field_name(name)).collect(); + abi::named( + &rust, + spelled, + |rust, name| name == rust, + |_, name| taken(name), + abi::underscored, + ) } /// A field's Python name: a positional one's is `_0`, `_1`, ... @@ -2539,18 +2641,19 @@ fn param_name(name: &str) -> String { } } -/// The Python names of `params`, each apart from the others: one that an earlier parameter's -/// rename took, such as `_all_` after `_all`, gets another `_`. -fn param_names<'a>(params: impl IntoIterator) -> Vec { - let mut out: Vec = Vec::new(); - for param in params { - let mut name = param_name(¶m.name); - while out.contains(&name) { - name.push('_'); - } - out.push(name); - } - out +/// The Python names of `params`, kept apart as [`abi::named`] keeps a scope's: beside Rust's +/// `_all_`, which keeps its name, `_all`, which the runtime's `_all` renames to `_all_`, takes +/// `_all__`, in either order. +fn param_names(params: &[Param]) -> Vec { + let rust: Vec<&str> = params.iter().map(|p| p.name.as_str()).collect(); + let spelled = rust.iter().map(|name| param_name(name)).collect(); + abi::named( + &rust, + spelled, + |rust, name| name == rust, + |_, _| false, + abi::underscored, + ) } /// The name a member's code declares, for [`Gen::distinct`]. @@ -2728,7 +2831,7 @@ fn record_class(name: &str, bases: &str, docs: &str, fields: &[Slot], members: & #[cfg(test)] mod tests { - use super::{DEPRECATOR, IMPORTS, RUNTIME, TAKEN, member, param_name, param_names, variant_classes}; + use super::{DEPRECATOR, IMPORTS, RUNTIME, TAKEN, member, param_name, param_names, value_names, variant_classes}; use crate::ir::{Param, Type}; /// Every alias the module imports, and every `_` name the runtime binds at module level, @@ -2782,18 +2885,28 @@ mod tests { // `_any` is read only by `_load`, which has no parameter, so it keeps its name. assert_eq!(param_name("_any"), "_any"); assert_eq!(param_name("_all"), "_all_"); - assert_eq!(params(&["_all", "_all_"]), ["_all_", "_all__"]); + // Rust's `_all_` keeps its name in either order. + assert_eq!(params(&["_all", "_all_"]), ["_all__", "_all_"]); assert_eq!(params(&["_all_", "_all"]), ["_all_", "_all__"]); assert_eq!(params(&["a", "b"]), ["a", "b"]); } #[test] fn variant_classes_keep_apart() { - let names = ["FooBar", "Foo_Bar", "None", "Late"]; assert_eq!( - variant_classes(names.into_iter()), + variant_classes(&["FooBar", "Foo_Bar", "None", "Late"]), ["FooBar", "FooBar_", "None_", "Late"] ); + // Pascal case spells `FooBar` as its Rust whichever comes first. + assert_eq!(variant_classes(&["Foo_Bar", "FooBar"]), ["FooBar_", "FooBar"]); + } + + #[test] + fn values_are_members_of_an_enum() { + assert_eq!( + value_names(&["_Hidden_", "__Hidden__", "__Hidden", "___Shown__", "Plain"]), + ["_HIDDEN__", "__HIDDEN____", "__HIDDEN___", "___SHOWN__", "PLAIN"] + ); } #[test] diff --git a/ffi/src/swift.rs b/ffi/src/swift.rs index f0fbcd47b..2ff567794 100644 --- a/ffi/src/swift.rs +++ b/ffi/src/swift.rs @@ -334,17 +334,10 @@ impl<'a> Gen<'a> { name } - /// Check that no two members of the type `rust` share a full Swift name, as [`full`] - /// spells it. - fn distinct(&mut self, rust: &str, members: &[String]) { - let mut seen = BTreeSet::new(); - for member in members { - if !seen.insert(member) { - self.errors.push(format!( - "two members of `{rust}` are both `{member}` in Swift, which rust2-ffi should keep apart" - )); - } - } + /// Asserts that no two members of the type `rust` share a full Swift name, as [`full`] + /// spells it and [`abi::assert_apart`] checks. + fn distinct(&self, rust: &str, members: &[String]) { + abi::assert_apart(rust, "Swift", members, |a, b| a == b); } /// Whether Swift's value of `ty` is noncopyable: it holds an object's struct. @@ -823,8 +816,13 @@ impl<'a> Gen<'a> { for i in 0..api.callbacks.len() { self.callback(i); } - for function in &api.functions { - for (code, _) in self.function(function, None, None, &[]) { + let functions: Vec<&Function> = api.functions.iter().collect(); + let named = self.names(&functions, None, None, |full| { + let name = full.split('(').next().unwrap_or(full); + TAKEN.contains(&name) || self.names.contains_key(full) + }); + for (function, name) in api.functions.iter().zip(&named) { + for (code, _) in self.function(function, (None, None), name, &[]) { self.top.push_str(&code); self.top.push('\n'); } @@ -1136,8 +1134,12 @@ impl<'a> Gen<'a> { body: &mut Vec, members: &mut Vec, ) { - for method in methods { - for (code, member) in self.function(method, Some(owner), Some(ty), members) { + let methods_: Vec<&Function> = methods.iter().collect(); + let named = self.names(&methods_, Some(owner), Some(ty), |full| { + members.iter().any(|m| m == full) + }); + for (method, name) in methods.iter().zip(&named) { + for (code, member) in self.function(method, (Some(owner), Some(ty)), name, members) { members.push(member); body.push(indent(&code)); } @@ -1155,8 +1157,8 @@ impl<'a> Gen<'a> { if record.opaque.is_some() { return self.opaque(i); } - let fields: Vec<(String, String)> = (record.fields.iter()) - .map(|f| (field_name(&f.name), self.sw(&f.ty))) + let fields: Vec<(String, String)> = (record.fields.iter().zip(field_names(&record.fields, RECORD))) + .map(|(f, name)| (name, self.sw(&f.ty))) .collect(); for (f, (name, _)) in record.fields.iter().zip(&fields) { crate::lock::field(&mut self.locked, &record.shown, &f.name, &unquote(name)); @@ -1292,27 +1294,27 @@ impl<'a> Gen<'a> { let mut cases = Vec::new(); let mut lifts = Vec::new(); let mut lowers = Vec::new(); - for variant in &e.variants { + for (variant, case) in e.variants.iter().zip(case_names(e)) { let snake = abi::snake(&variant.name); - let case = case_of(e.traits, &variant.name); + let names = field_names(&variant.fields, &["init"]); crate::lock::variant(&mut self.locked, &e.shown, &variant.name, &unquote(&case)); if !variant.tuple { - for f in &variant.fields { - let label = unquote(&field_name(&f.name)); + for (f, name) in variant.fields.iter().zip(&names) { + let label = unquote(name); crate::lock::variant_field(&mut self.locked, &e.shown, &variant.name, &f.name, &label); } } - let labels = variant.fields.iter().map(|f| match variant.tuple { + let labels = names.iter().map(|name| match variant.tuple { true => "_".to_string(), - false => unquote(&field_name(&f.name)), + false => unquote(name), }); members.push(full(true, &case, labels)); let tag = format!("{upper}_{}", snake.to_uppercase()); let member = kw(&abi::escape(&snake)); - let fields: Vec = (variant.fields.iter()) - .map(|f| match variant.tuple { + let fields: Vec = (variant.fields.iter().zip(&names)) + .map(|(f, name)| match variant.tuple { true => self.sw(&f.ty), - false => format!("{}: {}", field_name(&f.name), self.sw(&f.ty)), + false => format!("{name}: {}", self.sw(&f.ty)), }) .collect(); match fields.is_empty() { @@ -1326,12 +1328,12 @@ impl<'a> Gen<'a> { lowers.push(format!("\t\tcase .{case}:\n\t\t\t{refused}return {tag}")); continue; } - let lifted: Vec = (variant.fields.iter()) - .map(|f| { + let lifted: Vec = (variant.fields.iter().zip(&names)) + .map(|(f, name)| { let value = self.lift(&f.ty, &format!("c.{member}.{}", kw(&abi::escape(&f.name)))); match variant.tuple { true => value, - false => format!("{}: {value}", unquote(&field_name(&f.name))), + false => format!("{}: {value}", unquote(name)), } }) .collect(); @@ -1448,8 +1450,12 @@ impl<'a> Gen<'a> { constant: false, }; let mut streams = Vec::new(); - for method in &object.methods { - for (code, member) in self.function(method, Some(&owner), Some(&ty), &members) { + let methods: Vec<&Function> = object.methods.iter().collect(); + let named = self.names(&methods, Some(&owner), Some(&ty), |full| { + members.iter().any(|m| m == full) + }); + for (method, name) in object.methods.iter().zip(&named) { + for (code, member) in self.function(method, (Some(&owner), Some(&ty)), name, &members) { if method.stream().is_some() { streams.push((method, member.clone())); } @@ -1582,8 +1588,16 @@ impl<'a> Gen<'a> { let mut body = Vec::new(); let mut members = Vec::new(); let mut table = vec![format!("free: {{ data in Box.release(data) }}")]; - for method in &callback.methods { - let member = member(&abi::snake(method.name()), &[]); + let methods: Vec<&str> = callback.methods.iter().map(|method| method.name()).collect(); + let spelled = (callback.methods.iter()) + .map(|method| { + let member = member(&abi::snake(method.name()), &[]); + full(false, &member, method.params.iter().map(|_| "_".to_string())) + }) + .collect(); + let named = abi::named(&methods, spelled, own, |_, _| false, abi::underscored); + for (method, full_name) in callback.methods.iter().zip(&named) { + let member = kw(&unfull(full_name)); crate::lock::function(&mut self.locked, method, &member); self.docc.insert( crate::lock::function_key(method), @@ -1875,15 +1889,131 @@ impl<'a> Gen<'a> { } } + /// The name each of `functions` takes as a member of `owner` (whose IR type is + /// `owner_ty`) if it has one, or at the top level, apart from each other and from what + /// `taken` holds of a member's full name, as [`abi::named`] keeps a scope's. Each is + /// apart in every overload [`Gen::function`] gives it, each of its own labels, so Rust's + /// `foo()` keeps `foo()` beside a `foo_(value: Option<&T>)` whose overload without + /// `value` would be `foo()` too. + fn names( + &self, + functions: &[&Function], + owner: Option<&Ty>, + owner_ty: Option<&Type>, + taken: impl Fn(&str) -> bool, + ) -> Vec { + let (mut rust, mut spelled, mut forms) = (Vec::new(), Vec::new(), Vec::new()); + for function in functions { + let export = self.abi.export(function, owner); + let (name, member, is_static, var) = self.declared(function, owner, owner_ty, &export); + let labels: Vec<(String, bool)> = match var { + true => Vec::new(), + false => (function.params.iter().zip(locals(&function.params))) + .map(|(p, name)| match self.lent_option(&p.ty) { + true => (unquote(&name), true), + false => ("_".to_string(), false), + }) + .collect(), + }; + let optional = labels.iter().filter(|(_, optional)| *optional).count(); + // Each overload's labels, leaving out the optional ones its mask clears. + let overloads: Vec> = (0..1usize << optional) + .map(|mask| { + let mut bit = 0; + (labels.iter()) + .filter(|(_, optional)| { + bit += usize::from(*optional); + !*optional || mask & (1 << (bit - 1)) != 0 + }) + .map(|(label, _)| label.clone()) + .collect() + }) + .collect(); + rust.push(name); + spelled.push(full(is_static, &member, labels.into_iter().map(|(label, _)| label))); + forms.push((is_static, overloads)); + } + let rust: Vec<&str> = rust.iter().map(String::as_str).collect(); + let fulls = |k: usize, name: &str| -> Vec { + let (is_static, overloads) = &forms[k]; + let name = unfull(name); + (overloads.iter()) + .map(|labels| full(*is_static, &name, labels.iter().cloned())) + .collect() + }; + let clash = |k: usize, a: &str, j: usize, b: &str| { + let theirs = fulls(j, b); + fulls(k, a).iter().any(|full| theirs.contains(full)) + }; + let taken = |k: usize, name: &str| fulls(k, name).iter().any(|full| taken(full)); + (abi::named_apart(&rust, spelled, own, taken, abi::underscored, clash).iter()) + .map(|full| kw(&unfull(full))) + .collect() + } + + /// The declaration `function` makes as a member of `owner` (whose IR type is `owner_ty`) + /// if it has one, exported as `export`, before it keeps apart from another: the Rust name + /// it spells, its Swift name, whether it is static, and whether it is a property, whose + /// name is a constant's in upper case. + fn declared( + &self, + function: &Function, + owner: Option<&Ty>, + owner_ty: Option<&Type>, + export: &abi::Export, + ) -> (String, String, bool, bool) { + let abi = self.abi; + let own = match owner { + Some(Ty::Struct(o) | Ty::Enum(o) | Ty::Handle { name: o, .. }) => { + export.named.strip_prefix(o.as_str()).and_then(|r| r.strip_prefix('_')) + } + _ => None, + }; + let reserved: &[&str] = match owner_ty { + Some(Type::Object(_)) => &["handle", "init", "deinit"], + Some(_) => &["init"], + None => &[], + }; + // Named as Rust's path is, whatever C's clashes rename. + let rust = own.unwrap_or_else(|| self.bare(&export.named)).to_string(); + let member = member(&rust, reserved); + let receiver = function.receiver.filter(|_| owner.is_some()); + // A struct's method that consumes or writes back its value is `consuming` or `mutating`. + let unique = owner_ty.is_some_and(|ty| self.unique(ty)); + let value = matches!(export.call.params.first(), Some((_, Ty::InOut(_)))); + let mutates = match receiver { + Some(Receiver::Owned) => unique, + Some(Receiver::Mut) => unique || value, + _ => false, + }; + let everywhere = abi.api.everywhere(function.on); + let throws = function.future || function.err.is_some() || export.call.status().is_some() || !everywhere; + // A field read stays a property though a check of its handle may fail, which throws + // from its getter, unless Swift cannot copy its value, whose getter cannot throw. + let getter = throws && !function.future && function.err.is_none() && everywhere && !self.unique(&function.ok); + let var = match (function.access, receiver) { + (Access::Field { set: false, .. }, Some(_)) => { + function.params.is_empty() && (!throws || getter) && !mutates + } + (Access::Const, None) => function.params.is_empty() && !throws, + _ => false, + }; + let member = match (var, function.access) { + (true, Access::Const) => member.trim_matches('`').to_uppercase(), + _ => member, + }; + (rust, member, receiver.is_none() && owner.is_some(), var) + } + /// `function`'s Swift forms and their member names, members of `owner` (whose IR type - /// is `owner_ty`) if it has one, apart from the members `taken` names: an overload for - /// each choice of passing or leaving out each `Option<&T>` of a struct, since an optional - /// holds a struct only by consuming it. + /// is `owner_ty`) if it has one, named `name` apart from the members `taken` names: an + /// overload for each choice of passing or leaving out each `Option<&T>` of a struct, since + /// an optional holds a struct only by consuming it. fn function( &mut self, function: &Function, - owner: Option<&Ty>, - owner_ty: Option<&Type>, + (owner, owner_ty): (Option<&Ty>, Option<&Type>), + name: &str, taken: &[String], ) -> Vec<(String, String)> { let optional: Vec = (function.params.iter().enumerate()) @@ -1900,7 +2030,7 @@ impl<'a> Gen<'a> { .filter(|(bit, _)| mask & (1 << bit) == 0) .map(|(_, k)| *k) .collect(); - self.overload(function, owner, owner_ty, taken, &left) + self.overload(function, (owner, owner_ty), (name, taken), &left) }) .collect() } @@ -1910,36 +2040,20 @@ impl<'a> Gen<'a> { lent_option(&self.structs, ty) } - /// One of `function`'s Swift forms, apart from the members `taken` names, leaving out - /// the optional borrowed parameters in `left`, which pass `None`. + /// One of `function`'s Swift forms, named `member` apart from the members `taken` names, + /// leaving out the optional borrowed parameters in `left`, which pass `None`. fn overload( &mut self, function: &Function, - owner: Option<&Ty>, - owner_ty: Option<&Type>, - taken: &[String], + (owner, owner_ty): (Option<&Ty>, Option<&Type>), + (member, taken): (&str, &[String]), left: &BTreeSet, ) -> (String, String) { let abi = self.abi; let export = abi.export(function, owner); let c_name = export.call.name.clone(); - let owner_c = match owner { - Some(Ty::Struct(n) | Ty::Enum(n) | Ty::Handle { name: n, .. }) => Some(n.clone()), - _ => None, - }; - let own = match &owner_c { - Some(o) => export.named.strip_prefix(o.as_str()).and_then(|r| r.strip_prefix('_')), - None => None, - }; - let reserved: &[&str] = match owner_ty { - Some(Type::Object(_)) => &["handle", "init", "deinit"], - Some(_) => &["init"], - None => &[], - }; - // Named as Rust's path is, whatever C's clashes rename. - let named = self.bare(&export.named).to_string(); - let snake = own.unwrap_or(&named); - let mut member = member(snake, reserved); + let (_, _, is_static, var) = self.declared(function, owner, owner_ty, &export); + let mut member = member.to_string(); let receiver = function.receiver.filter(|_| owner.is_some()); let object = matches!(owner, Some(Ty::Handle { .. })) && receiver.is_some(); @@ -2373,28 +2487,11 @@ impl<'a> Gen<'a> { Type::Unit => String::new(), _ => format!(" -> {}", self.sw(&ok)), }; - let is_static = receiver.is_none() && owner.is_some(); let stat = match is_static { true => "static ", false => "", }; let body = body.join("\n"); - let var = function.params.is_empty() && !throws; - // A field read stays a property though a check of its handle may fail, which throws - // from its getter, unless Swift cannot copy its value, whose getter cannot throw. - let getter = throws && !function.future && function.err.is_none() && everywhere && !self.unique(&function.ok); - let var = match (function.access, receiver) { - (Access::Field { set: false, .. }, Some(_)) => { - function.params.is_empty() && (!throws || getter) && mutation.is_empty() - } - (Access::Const, None) => { - if var { - member = member.trim_matches('`').to_uppercase(); - } - var - } - _ => false, - }; let labels: Vec = match var { true => Vec::new(), false => (params.iter()) @@ -2515,12 +2612,12 @@ impl<'a> Gen<'a> { doc::Target::Variant(i, v) => format!( "{}/{}", owner(doc::Owner::Enum(i)), - unquote(&case_of(abi.api.enums[i].traits, &abi.api.enums[i].variants[v].name)) + unquote(&case_names(&abi.api.enums[i]).swap_remove(v)) ), doc::Target::Field(i, n) => format!( "{}/{}", owner(doc::Owner::Record(i)), - unquote(&field_name(&abi.api.records[i].fields[n].name)) + unquote(&field_names(&abi.api.records[i].fields, RECORD).swap_remove(n)) ), doc::Target::Constant(c) => self.locked.get(&format!("const {}", c.path.join("::")))?.clone(), doc::Target::Function(of, f) => { @@ -2723,10 +2820,10 @@ fn lift_int(int: Int, e: &str) -> String { } } -/// The Swift names of parameters, in camel case, [`abi::distinct`], and quoted if a -/// keyword. +/// The Swift names of parameters, in camel case, kept apart as [`abi::distinct`] keeps +/// them, and quoted if a keyword. fn locals(params: &[Param]) -> Vec { - (abi::distinct(params.iter().map(|p| camel(&p.name))).iter()) + (abi::distinct(params, camel, |_| false).iter()) .map(|name| kw(name)) .collect() } @@ -2744,18 +2841,40 @@ fn camel(name: &str) -> String { } } -/// A variant's case: `init` would name the initializer, and `default`, with its traits `t`, -/// `Default`'s static `default()`. -fn case_of(t: crate::ir::Traits, variant: &str) -> String { - match t.default { - true => member(&abi::snake(variant), &["init", "default"]), - false => member(&abi::snake(variant), &["init"]), - } +/// The cases of the enum `e`, one scope's, in camel case as [`abi::named`] keeps them apart, +/// and quoted where a keyword: `init` would name the initializer, and `default`, where `e` +/// has `Default`, its static `default()`. +fn case_names(e: &crate::ir::Enum) -> Vec { + let rust: Vec<&str> = e.variants.iter().map(|v| v.name.as_str()).collect(); + let spelled = rust.iter().map(|name| camel(&abi::snake(name))).collect(); + let taken = |name: &str| name == "init" || (e.traits.default && name == "default"); + let names = abi::named( + &rust, + spelled, + |rust, name| pascal(name) == rust, + |_, name| taken(name), + abi::underscored, + ); + names.iter().map(|name| kw(name)).collect() } -/// A field's Swift name: `init` would name the initializer. -fn field_name(name: &str) -> String { - member(name, &["init"]) +/// A record's members its fields keep apart from: the initializer, and the properties +/// `Display` and `Debug` give it, so a record that gains either renames no field. +const RECORD: &[&str] = &["init", "description", "debugDescription"]; + +/// The Swift names of `fields`, one scope's, in camel case as [`abi::named`] keeps them +/// apart from each other and from `taken`, and quoted where a keyword. +fn field_names(fields: &[crate::ir::Field], taken: &[&str]) -> Vec { + let rust: Vec<&str> = fields.iter().map(|f| f.name.as_str()).collect(); + let spelled = rust.iter().map(|name| camel(name)).collect(); + let names = abi::named( + &rust, + spelled, + |rust, name| abi::snake(name) == rust, + |_, name| taken.contains(&name), + abi::underscored, + ); + names.iter().map(|name| kw(name)).collect() } /// A member's Swift name: in camel case, quoted if a keyword, or with `_` appended if @@ -2783,6 +2902,19 @@ fn full(is_static: bool, name: &str, labels: impl IntoIterator) - } } +/// The name of a member's [`full`] name. +fn unfull(full: &str) -> String { + let full = full.strip_prefix("static ").unwrap_or(full); + full.split('(').next().unwrap_or(full).to_string() +} + +/// Whether the member's [`full`] name `full` reads back as the Rust name `rust`, as it +/// spells it or in camel case, for [`abi::named`]. +fn own(rust: &str, full: &str) -> bool { + let name = unfull(full); + name == rust || abi::snake(&name) == rust +} + /// A function's name as DocC links it: with its argument labels. fn docc_call<'l>(name: &str, labels: impl IntoIterator) -> String { let labels: String = labels.into_iter().map(|l| format!("{l}:")).collect(); diff --git a/ffi/src/web.rs b/ffi/src/web.rs index 51cc66b1b..799647bfe 100644 --- a/ffi/src/web.rs +++ b/ffi/src/web.rs @@ -1600,19 +1600,38 @@ fn field_name(name: &str) -> String { camel(name) } -/// The names of a record's fields, each a field's, and distinct: `foo` and `foo_`, both -/// `foo` in camel case, are `foo` and `foo2`. +/// The names of a record's fields, each a field's, kept apart as [`abi::named`] keeps them, +/// by an [`abi::numbered`] step: `foo` and `foo_`, both `foo` in camel case, are `foo` and +/// `foo2` in either order. fn field_names(fields: &[crate::ir::Field]) -> Vec { - abi::distinct(fields.iter().map(|f| field_name(&f.name))) + let rust: Vec<&str> = fields.iter().map(|f| f.name.as_str()).collect(); + let spelled = rust.iter().map(|name| field_name(name)).collect(); + abi::named( + &rust, + spelled, + |rust, name| abi::snake(name) == rust, + |_, _| false, + abi::numbered, + ) } /// The names of a data enum variant's fields: a record's, but `tag$` for one named `tag`, /// which names the variant. fn variant_fields(fields: &[crate::ir::Field]) -> Vec { - abi::distinct(fields.iter().map(|f| match field_name(&f.name) { - name if name == "tag" => "tag$".to_string(), - name => name, - })) + let rust: Vec<&str> = fields.iter().map(|f| f.name.as_str()).collect(); + let spelled = (rust.iter()) + .map(|name| match field_name(name) { + name if name == "tag" => "tag$".to_string(), + name => name, + }) + .collect(); + abi::named( + &rust, + spelled, + |rust, name| abi::snake(name) == rust, + |_, _| false, + abi::numbered, + ) } /// A parameter's name: in camel case, with `_` appended if a reserved word. @@ -1981,7 +2000,8 @@ impl Gen<'_> { let rust = callback.path.join("::"); let class = self.class(&c); let mut fields = vec!["free: Some(runtime::FREE)".to_string()]; - for method in &callback.methods { + let members = method_names(&callback.methods); + for (method, member) in callback.methods.iter().zip(&members) { let m = method.name(); let name = format!("{space}_cb_{bare}_{m}"); let params: Vec = method.params.iter().map(|p| abi.ty(&p.ty)).collect(); @@ -1998,7 +2018,6 @@ impl Gen<'_> { for (n, (param, c)) in method.params.iter().zip(¶ms).enumerate() { args.push(self.arg_in(¶m.ty, c, &format!("p{n}"), &mut lines, &mut lent)); } - let member = method_name(m); let call = format!("rt.find<{t}>(data).{member}({})", args.join(", ")); let mut body = Vec::new(); self.outgoing(&method.ok, &ret, &call, &mut body); @@ -2183,14 +2202,19 @@ fn constant_local(name: &str) -> String { } } -/// A trait method's name in camel case, with `$` appended if a reserved word or `close`. -fn method_name(name: &str) -> String { - let name = camel(name); +/// The names of a trait's methods, one scope's, in camel case as [`abi::named`] keeps them +/// apart, each with `$` appended if a reserved word or `close`. +fn method_names(methods: &[Function]) -> Vec { // `close` is the hook Rust calls once it drops an implementation. - match RESERVED.contains(&name.as_str()) || name == "close" { + let escape = |name: &str| match RESERVED.contains(&name) || name == "close" { true => format!("{name}$"), - false => name, - } + false => name.to_string(), + }; + let rust: Vec<&str> = methods.iter().map(|method| method.name()).collect(); + let spelled = rust.iter().map(|name| escape(&camel(name))).collect(); + let own = |rust: &str, name: &str| abi::snake(name.trim_end_matches('$')) == rust; + let step = |name: &str, n: usize| escape(&abi::underscored(name.trim_end_matches('$'), n)); + abi::named(&rust, spelled, own, |_, _| false, step) } impl Gen<'_> { @@ -2255,8 +2279,9 @@ impl Gen<'_> { } self.module = "index".to_string(); let mut taken = BTreeSet::new(); - for function in &api.functions { - if let Some(code) = self.function(function, None, None, &mut taken) { + let names = self.names(&api.functions, (None, None), |name| self.names.contains_key(name)); + for (function, name) in api.functions.iter().zip(&names) { + if let Some(code) = self.function(function, (None, None), name, &mut taken) { self.module = "index".to_string(); self.out().body.push_str(&code); self.out().body.push('\n'); @@ -2275,8 +2300,9 @@ impl Gen<'_> { /// Each method of a type, into its module. fn methods(&mut self, methods: &[Function], owner: &Ty, ty: &Type, taken: &mut BTreeSet) { let module = self.module.clone(); - for method in methods { - if let Some(code) = self.function(method, Some(owner), Some(ty), taken) { + let names = self.names(methods, (Some(owner), Some(ty)), |name| taken.contains(name)); + for (method, name) in methods.iter().zip(&names) { + if let Some(code) = self.function(method, (Some(owner), Some(ty)), name, taken) { self.module = module.clone(); self.out().body.push_str(&code); self.out().body.push('\n'); @@ -2513,11 +2539,11 @@ impl Gen<'_> { let rust = callback.path.join("::"); self.module = name.clone(); let mut members = Vec::new(); - for method in &callback.methods { - let member = method_name(method.name()); + for (method, member) in callback.methods.iter().zip(method_names(&callback.methods)) { crate::lock::function(&mut self.locked, method, &member); - let params: Vec = (method.params.iter()) - .map(|p| format!("{}: {}", param_name(&p.name), self.tt(&p.ty))) + let names = abi::distinct(&method.params, param_name, |_| false); + let params: Vec = (method.params.iter().zip(names)) + .map(|(p, name)| format!("{name}: {}", self.tt(&p.ty))) .collect(); let ok = self.tt(&method.ok); members.push(format!( @@ -2745,13 +2771,59 @@ fn wrap(lines: &[String]) -> String { } impl Gen<'_> { - /// `function`'s TypeScript, a function of the module of its type `owner_ty` if it has - /// one, whose C type is `owner`, named apart from `taken`; none if not on the target. + /// The name each of `functions` takes as a member of `owner` (whose IR type is + /// `owner_ty`) if it has one, or at the top level, apart from each other and from what + /// `taken` holds, as [`abi::named`] keeps a scope's: a constant's in upper case, and each + /// other's in camel case. One not on this target takes none. + fn names( + &self, + functions: &[Function], + (owner, owner_ty): (Option<&Ty>, Option<&Type>), + taken: impl Fn(&str) -> bool, + ) -> Vec { + let abi = self.abi; + let (rust, spelled): (Vec, Vec) = (functions.iter()) + .map(|function| { + let export = match (owner.zip(owner_ty)).and_then(|(owner, ty)| abi.handed_back(function, owner, ty)) { + Some((_, export, _)) => export, + None => abi.export(function, owner), + }; + let own = match owner { + Some(Ty::Struct(o) | Ty::Enum(o) | Ty::Handle { name: o, .. }) => { + export.named.strip_prefix(o.as_str()).and_then(|r| r.strip_prefix('_')) + } + _ => None, + }; + // Named as Rust's path is, whatever C's clashes rename. + let rust = own.unwrap_or_else(|| self.bare(&export.named)).to_string(); + let base = match function.access { + Access::Const => abi::snake(&rust).to_uppercase(), + _ => camel(&rust), + }; + match self.here(function.on) { + true => (rust, base), + false => (String::new(), String::new()), + } + }) + .unzip(); + let rust: Vec<&str> = rust.iter().map(String::as_str).collect(); + let own = |rust: &str, name: &str| name == rust || abi::snake(name) == rust; + abi::named( + &rust, + spelled, + own, + |_, name| !name.is_empty() && taken(name), + abi::underscored, + ) + } + + /// `function`'s TypeScript form `member`, of `owner` (whose IR type is `owner_ty`) if it + /// has one, which `taken` then holds. fn function( &mut self, function: &Function, - owner: Option<&Ty>, - owner_ty: Option<&Type>, + (owner, owner_ty): (Option<&Ty>, Option<&Type>), + member: &str, taken: &mut BTreeSet, ) -> Option { let abi = self.abi; @@ -2786,36 +2858,22 @@ impl Gen<'_> { }; let function = handed.as_ref().unwrap_or(function); let c_name = export.call.name.clone(); - let owner_c = match owner { - Some(Ty::Struct(n) | Ty::Enum(n) | Ty::Handle { name: n, .. }) => Some(n.clone()), - _ => None, - }; - let own = match &owner_c { - Some(o) => export.named.strip_prefix(o.as_str()).and_then(|r| r.strip_prefix('_')), - None => None, - }; - // Named as Rust's path is, whatever C's clashes rename. - let named = self.bare(&export.named).to_string(); - let snake = own.unwrap_or(&named); - let base = match function.access { - Access::Const => abi::snake(snake).to_uppercase(), - _ => camel(snake), - }; let member = match owner { None => abi::claim( &mut self.names, |_| false, - &base, + member, format!("fn `{}`", function.path.join("::")), ), Some(_) => { - let mut member = base; + let mut member = member.to_string(); while taken.contains(&member) { member.push('_'); } member } }; + taken.insert(member.clone()); crate::lock::function(&mut self.locked, function, &member); let local = match RESERVED.contains(&member.as_str()) { @@ -2850,12 +2908,10 @@ impl Gen<'_> { args.push("self$".to_string()); } // Distinct from each other, and from the receiver's `self`. - let receiving = receiver.is_some() as usize; - let names = (function.params.iter()).map(|param| param_name(¶m.name)); - let names = abi::distinct(["self".to_string()].into_iter().take(receiving).chain(names)); - let names = names.into_iter().skip(receiving); + let receiving = receiver.is_some(); + let names = abi::distinct(&function.params, param_name, |name| receiving && name == "self"); let mut writes = Vec::new(); - for (k, (param, name)) in function.params.iter().zip(names).enumerate() { + for (k, (param, name)) in function.params.iter().zip(&names).enumerate() { let (_, c) = c_params.next().expect("each parameter has its C one"); let a = format!("a{k}$"); // A value passed for `&mut`, in a place that takes what Rust writes back. @@ -2897,7 +2953,7 @@ impl Gen<'_> { if matches!(param.ty.base(), Type::Callback(..)) => { let l = self.layout(c); - let put = self.put(param.ty.base(), &name, &a, false); + let put = self.put(param.ty.base(), name, &a, false); gives.push(format!("const {a} = rt.alloc({}, {});\n{put}", l.size, l.align)); args.push(a); } @@ -2910,7 +2966,7 @@ impl Gen<'_> { args.push(a); } (ty, c) => { - lines.push(self.pass(ty, c, &name, &a)); + lines.push(self.pass(ty, c, name, &a)); // Rust takes `Bytes` by value: lent bytes become a second owner of its // buffer once nothing left to lower can throw, so none is given in vain. if matches!(ty, Type::Bytes) || matches!(ty, Type::Option(inner) if **inner == Type::Bytes) { @@ -3055,8 +3111,7 @@ impl Gen<'_> { "\n\nRust changes a copy of this value, which it returns first, as the call left it: this one never changes.", ); } - for param in &function.params { - let name = param_name(¶m.name); + for (param, name) in function.params.iter().zip(&names) { if let Type::Closure(closure) = ¶m.ty { text.push_str(&match closure.kept { true => format!("\n\nRust keeps `{name}` until it drops it."), diff --git a/ffi/surface/api/c.h b/ffi/surface/api/c.h index 7c7c51495..913db4800 100644 --- a/ffi/surface/api/c.h +++ b/ffi/surface/api/c.h @@ -17,7 +17,7 @@ #ifdef __cplusplus extern "C" { #endif -#define API_CONTRACT ((uint64_t)0x7dc26467f8de48a0ULL) +#define API_CONTRACT ((uint64_t)0xa4b13378f22571caULL) uint64_t api_contract(void); uint32_t api_target(void); typedef int32_t api_status; @@ -210,6 +210,10 @@ typedef enum api_clash_Level { API_CLASH_LEVEL_DEFAULT = 0, API_CLASH_LEVEL_DEBUG = 1, } api_clash_Level; +typedef enum api_clash_Op { + API_CLASH_OP_DELETE_ = 0, + API_CLASH_OP_DELETE = 1, +} api_clash_Op; typedef enum api_Level { API_LEVEL_ERROR = 0, API_LEVEL_WARN = 1, @@ -889,12 +893,22 @@ typedef struct api_clash_Break { typedef struct api_clash_Malformed { uint8_t at; } api_clash_Malformed; +typedef struct api_clash_Described { + uint8_t description; + uint8_t debug_description; +} api_clash_Described; typedef struct api_clash_Errno { int32_t errno_; } api_clash_Errno; typedef struct api_clash_Escaped { uint8_t new_; } api_clash_Escaped; +typedef struct api_clash_Underscored { + uint8_t new__; + uint8_t new_; + uint8_t debug; + uint8_t default_; +} api_clash_Underscored; typedef struct api_tls_policy_Lifetime { uint32_t seconds; } api_tls_policy_Lifetime; @@ -1163,6 +1177,20 @@ typedef struct api_clash_Tag { api_clash_Tag_Private private_; }; } api_clash_Tag; +typedef enum api_clash_Change_tag { + API_CLASH_CHANGE_SET = 0, + API_CLASH_CHANGE_CLEAR = 1, +} api_clash_Change_tag; +typedef struct api_clash_Change_Set { + uint8_t new__; + uint8_t new_; +} api_clash_Change_Set; +typedef struct api_clash_Change { + api_clash_Change_tag tag; + union { + api_clash_Change_Set set; + }; +} api_clash_Change; typedef struct api_Log_vtable { void (*free)(void *data); bool (*log)(void *data, uint8_t level, api_buf line); @@ -1223,6 +1251,15 @@ typedef struct api_clash_Source { const api_clash_Source_vtable *vtable; void *data; } api_clash_Source; +typedef struct api_clash_Eraser_vtable { + void (*free)(void *data); + uint8_t (*delete__)(void *data, uint8_t new__, uint8_t new_); + uint8_t (*delete_)(void *data); +} api_clash_Eraser_vtable; +typedef struct api_clash_Eraser { + const api_clash_Eraser_vtable *vtable; + void *data; +} api_clash_Eraser; #define API_LIMIT ((uint64_t)1000ULL) #define API_FAR ((int64_t)9223372036854775807LL) #define API_EOF ((int32_t)-1) @@ -1498,6 +1535,10 @@ bool api_clash_Malformed_eq(const api_clash_Malformed *a, const api_clash_Malfor API_MUST_USE api_buf api_clash_Malformed_to_string(const api_clash_Malformed *self); API_MUST_USE api_buf api_clash_Malformed_debug(const api_clash_Malformed *self); bool api_clash_Malformed_is(const api_clash_Malformed *self, uint8_t at); +void api_clash_Described_free(api_clash_Described *self); +bool api_clash_Described_eq(const api_clash_Described *a, const api_clash_Described *b); +API_MUST_USE api_buf api_clash_Described_to_string(const api_clash_Described *self); +API_MUST_USE api_buf api_clash_Described_debug(const api_clash_Described *self); void api_clash_Errno_free(api_clash_Errno *self); bool api_clash_Errno_eq(const api_clash_Errno *a, const api_clash_Errno *b); API_MUST_USE api_buf api_clash_Errno_debug(const api_clash_Errno *self); @@ -1505,8 +1546,12 @@ api_clash_Errno api_clash_Errno_NULL(void); void api_clash_Escaped_free(api_clash_Escaped *self); bool api_clash_Escaped_eq(const api_clash_Escaped *a, const api_clash_Escaped *b); API_MUST_USE api_buf api_clash_Escaped_debug(const api_clash_Escaped *self); -uint8_t api_clash_Escaped_delete(const api_clash_Escaped *self); uint8_t api_clash_Escaped_delete_(const api_clash_Escaped *self, uint8_t new_, uint8_t new__); +uint8_t api_clash_Escaped_delete(const api_clash_Escaped *self); +void api_clash_Underscored_free(api_clash_Underscored *self); +bool api_clash_Underscored_eq(const api_clash_Underscored *a, const api_clash_Underscored *b); +API_MUST_USE api_buf api_clash_Underscored_debug(const api_clash_Underscored *self); +api_clash_Underscored api_clash_Underscored_default(void); void api_tls_policy_Lifetime_free(api_tls_policy_Lifetime *self); bool api_tls_policy_Lifetime_eq(const api_tls_policy_Lifetime *a, const api_tls_policy_Lifetime *b); API_MUST_USE api_buf api_tls_policy_Lifetime_debug(const api_tls_policy_Lifetime *self); @@ -1587,6 +1632,11 @@ void api_clash_Tag_free(api_clash_Tag *self); bool api_clash_Tag_eq(const api_clash_Tag *a, const api_clash_Tag *b); API_MUST_USE api_buf api_clash_Tag_debug(const api_clash_Tag *self); uint32_t api_clash_Tag_number(const api_clash_Tag *self); +bool api_clash_Op_eq(const api_clash_Op *a, const api_clash_Op *b); +API_MUST_USE api_buf api_clash_Op_debug(const api_clash_Op *self); +void api_clash_Change_free(api_clash_Change *self); +bool api_clash_Change_eq(const api_clash_Change *a, const api_clash_Change *b); +API_MUST_USE api_buf api_clash_Change_debug(const api_clash_Change *self); bool api_Level_eq(const api_Level *a, const api_Level *b); uint64_t api_Level_hash(const api_Level *self); int8_t api_Level_partial_cmp(const api_Level *a, const api_Level *b); @@ -2164,6 +2214,10 @@ uint32_t api_clash_Store_free_(const api_clash_Store *self); uint32_t api_clash_Store_close(const api_clash_Store *self); void api_clash_Store_wait(const api_clash_Store *self); void api_clash_Store_finalize(const api_clash_Store *self); +uint32_t api_clash_Store_count_(void); +uint32_t api_clash_Store_count(const api_clash_Store *self); +API_MUST_USE api_clash_Store *api_clash_Store_open_(void); +uint32_t api_clash_Store_open(const api_clash_Store *self); void api_clash_Reader_free(api_clash_Reader *self); void api_clash_Reader_drop(api_clash_Reader *self, api_status *status); API_MUST_USE api_clash_Reader *api_clash_Reader_new(api_buf bytes); @@ -2606,6 +2660,7 @@ API_MUST_USE api_buf api_unzeroed(api_buf bytes); uint8_t api_deprecated(uint8_t note); uint8_t api__deprecated(uint8_t note); uint8_t api___all__(uint8_t note); +uint8_t api___all___(uint8_t note); api_Knob api_knob(api_Dial dial); typedef struct api_level_later_future api_level_later_future; API_MUST_USE api_level_later_future *api_level_later(api_Dial dial); @@ -2629,7 +2684,16 @@ API_MUST_USE api_clash_Any api_clash_any(api_buf type_url); api_clash_Candidate api_clash_candidate(uint8_t at); uint8_t api_clash_ignore(uint8_t arg0, uint8_t arg1, uint8_t arg2); API_MUST_USE api_clash_Empty_string *api_clash_empty(void); +uint32_t api_clash_described(api_clash_Described described); uint8_t api_clash_waited(api_clash_Source source); +uint32_t api_clash_underscored(api_clash_Underscored underscored, api_clash_Op op, api_clash_Change change); +void api_clash_underscored_next(api_clash_Underscored underscored, api_clash_Change change, api_clash_Underscored *out0, api_clash_Change *out1); +uint32_t api_clash_erased(api_clash_Eraser eraser); +uint8_t api_clash_erase_(void); +uint8_t api_clash_erase(void); +uint32_t api_clash_lend_(const api_clash_Store *store); +uint32_t api_clash_lend(void); +uint32_t api_clash_run(uint8_t (*work__)(void *data), void *work___data, uint8_t work); API_MUST_USE bool api_clash_audible(api_clash_Tone tone, api_clash_Tone *out, api_vec_clash_Tone *err); uint32_t api_clash_nested(api_option_tuple_tuple_u8_u16_u32 a, api_option_tuple_tuple_u8_u16_u32_ b); uint8_t api_clash_audio_encoder_finish(void); diff --git a/ffi/surface/api/cpp.hpp b/ffi/surface/api/cpp.hpp index ff5988b73..ef4d81578 100644 --- a/ffi/surface/api/cpp.hpp +++ b/ffi/surface/api/cpp.hpp @@ -42,6 +42,10 @@ namespace api { default_ = 0, debug = 1, }; + enum class clash_Op { + delete_ = 0, + delete__ = 1, + }; inline constexpr ::std::uint64_t LIMIT = API_LIMIT; inline constexpr ::std::int64_t FAR = API_FAR; inline constexpr ::std::int32_t EOF_ = API_EOF; @@ -693,6 +697,10 @@ namespace api { RUST2_FFI_CALLABLE ::std::uint32_t close() const; RUST2_FFI_CALLABLE void wait() const; RUST2_FFI_CALLABLE void finalize() const; + static ::std::uint32_t count_(); + RUST2_FFI_CALLABLE ::std::uint32_t count() const; + static ::api::clash_Store open_(); + RUST2_FFI_CALLABLE ::std::uint32_t open() const; }; class RUST2_FFI_CONSUMABLE clash_Reader { RUST2_FFI_UNCONSUMED clash_Reader(clash_Reader &&other RUST2_FFI_MOVED_FROM) noexcept = default; @@ -794,6 +802,11 @@ namespace api { virtual void wait() const = 0; virtual ::std::uint8_t read_byte() const = 0; }; + class clash_Eraser { + virtual ~clash_Eraser() = default; + virtual ::std::uint8_t delete_(::std::uint8_t new_, ::std::uint8_t new__) const = 0; + virtual ::std::uint8_t delete__() const = 0; + }; struct Parcel { ::api::Mark mark; ::api::buf payload; @@ -1324,6 +1337,14 @@ namespace api { ::api::buf debug() const; bool is(::std::uint8_t at_) const; }; + struct clash_Described { + ::std::uint8_t description; + ::std::uint8_t debug_description; + friend bool operator==(const clash_Described &a__, const clash_Described &b_); + friend bool operator!=(const clash_Described &a__, const clash_Described &b_); + ::api::buf to_string() const; + ::api::buf debug() const; + }; struct clash_Errno { ::std::int32_t errno_; friend bool operator==(const clash_Errno &a__, const clash_Errno &b_); @@ -1336,8 +1357,18 @@ namespace api { friend bool operator==(const clash_Escaped &a__, const clash_Escaped &b_); friend bool operator!=(const clash_Escaped &a__, const clash_Escaped &b_); ::api::buf debug() const; - ::std::uint8_t delete__() const; ::std::uint8_t delete_(::std::uint8_t new__, ::std::uint8_t new___) const; + ::std::uint8_t delete__() const; + }; + struct clash_Underscored { + ::std::uint8_t new_; + ::std::uint8_t new__; + ::std::uint8_t debug_; + ::std::uint8_t default__; + friend bool operator==(const clash_Underscored &a__, const clash_Underscored &b_); + friend bool operator!=(const clash_Underscored &a__, const clash_Underscored &b_); + ::api::buf debug() const; + static clash_Underscored default_(); }; struct Core { ::std::uint32_t id; @@ -1468,6 +1499,12 @@ namespace api { struct clash_Tag_Private { ::std::uint32_t number; }; + struct clash_Change_Set { + ::std::uint8_t new_; + ::std::uint8_t new__; + }; + struct clash_Change_Clear { + }; #if defined(__cpp_lib_three_way_comparison) inline ::std::partial_ordering operator<=>(const Quantity &a__, const Quantity &b_); #endif @@ -1543,8 +1580,10 @@ namespace api { inline bool operator==(const clash_Any &a__, const clash_Any &b_); inline bool operator==(const clash_Break &a__, const clash_Break &b_); inline bool operator==(const clash_Malformed &a__, const clash_Malformed &b_); + inline bool operator==(const clash_Described &a__, const clash_Described &b_); inline bool operator==(const clash_Errno &a__, const clash_Errno &b_); inline bool operator==(const clash_Escaped &a__, const clash_Escaped &b_); + inline bool operator==(const clash_Underscored &a__, const clash_Underscored &b_); inline bool operator==(::api::Shape a__, ::api::Shape b_); inline bool operator!=(::api::Shape a__, ::api::Shape b_); inline ::api::buf Shape_debug(::api::Shape self); @@ -1625,6 +1664,12 @@ namespace api { inline bool operator!=(const ::api::clash_Tag &a__, const ::api::clash_Tag &b_); inline ::api::buf clash_Tag_debug(const ::api::clash_Tag &self); inline ::std::uint32_t clash_Tag_number(const ::api::clash_Tag &self); + inline bool operator==(::api::clash_Op a__, ::api::clash_Op b_); + inline bool operator!=(::api::clash_Op a__, ::api::clash_Op b_); + inline ::api::buf clash_Op_debug(::api::clash_Op self); + inline bool operator==(const ::api::clash_Change &a__, const ::api::clash_Change &b_); + inline bool operator!=(const ::api::clash_Change &a__, const ::api::clash_Change &b_); + inline ::api::buf clash_Change_debug(const ::api::clash_Change &self); inline bool has_text(const ::api::Note ¬e); inline ::std::uint64_t marked(const ::api::Mark &api_marked); inline ::std::optional<::api::Reading> reading(::std::uint32_t n); @@ -1893,6 +1938,7 @@ namespace api { inline ::std::uint8_t deprecated(::std::uint8_t note); inline ::std::uint8_t _deprecated(::std::uint8_t note); inline ::std::uint8_t __all___(::std::uint8_t note); + inline ::std::uint8_t __all____(::std::uint8_t note); [[deprecated]] inline ::api::Knob knob(const ::api::Dial &dial); [[deprecated("read its `level`")]] inline ::api::level_later_future level_later(const ::api::Dial &dial); inline ::api::result<::api::Dial, ::api::Error> turned(const ::api::Dial &dial, ::std::unique_ptr<::api::Turner> turner); @@ -1912,7 +1958,16 @@ namespace api { inline ::api::clash_Candidate clash_candidate(::std::uint8_t at); inline ::std::uint8_t clash_ignore(::std::uint8_t arg0, ::std::uint8_t arg1, ::std::uint8_t arg2); inline ::api::clash_Empty_string clash_empty(); + inline ::std::uint32_t clash_described(const ::api::clash_Described &described); inline ::std::uint8_t clash_waited(::std::unique_ptr<::api::clash_Source> source); + inline ::std::uint32_t clash_underscored(const ::api::clash_Underscored &underscored, ::api::clash_Op op, const ::api::clash_Change &change); + inline ::std::tuple<::api::clash_Underscored, ::api::clash_Change> clash_underscored_next(const ::api::clash_Underscored &underscored, const ::api::clash_Change &change); + inline ::std::uint32_t clash_erased(::std::unique_ptr<::api::clash_Eraser> eraser); + inline ::std::uint8_t clash_erase_(); + inline ::std::uint8_t clash_erase(); + inline ::std::uint32_t clash_lend_(const ::api::clash_Store *store); + inline ::std::uint32_t clash_lend(); + template inline ::std::uint32_t clash_run(F0 &&work_, ::std::uint8_t work); inline ::api::result<::api::clash_Tone, ::std::vector<::api::clash_Tone>> clash_audible(const ::api::clash_Tone &tone); inline ::std::uint32_t clash_nested(const ::std::optional<::std::tuple<::std::tuple<::std::uint8_t, ::std::uint16_t>, ::std::uint32_t>> &a__, const ::std::optional<::std::tuple<::std::tuple<::std::uint8_t, ::std::uint16_t, ::std::uint32_t>>> &b_); inline ::std::uint8_t clash_audio_encoder_finish(); @@ -2233,6 +2288,7 @@ namespace api { enum class VecClashTone; enum class Tier; enum class clash_Level; + enum class clash_Op; enum class Level; struct Parcel; struct Weighted; @@ -2305,8 +2361,10 @@ namespace api { struct clash_Any; struct clash_Break; struct clash_Malformed; + struct clash_Described; struct clash_Errno; struct clash_Escaped; + struct clash_Underscored; struct tls_policy_Lifetime; struct Core; class Board; @@ -2402,6 +2460,7 @@ namespace api { class Undo; class Stretch; class clash_Source; + class clash_Eraser; struct Choice_Empty; struct Choice_Picked; using Choice = ::std::variant; @@ -2461,6 +2520,9 @@ namespace api { struct clash_Tag_Application; struct clash_Tag_Private; using clash_Tag = ::std::variant; + struct clash_Change_Set; + struct clash_Change_Clear; + using clash_Change = ::std::variant; using Clash_after_future = ::api::future; using Clash_tagged_future = ::api::future; using Waiter_poll_future_future = ::api::future; diff --git a/ffi/surface/api/dart.dart b/ffi/surface/api/dart.dart index 001e8c45a..c98e1dcc0 100644 --- a/ffi/surface/api/dart.dart +++ b/ffi/surface/api/dart.dart @@ -732,8 +732,8 @@ final class ClashBreak { String debug(); @override bool operator ==(Object other); @override int get hashCode; - static ClashBreak get sp; static ClashBreak get sp_; + static ClashBreak get sp; } final class ClashMalformed implements Exception { final int at; @@ -744,6 +744,15 @@ final class ClashMalformed implements Exception { @override int get hashCode; bool is_(int at); } +final class ClashDescribed { + final int description; + final int debugDescription; + const ClashDescribed({required this.description, required this.debugDescription}); + @override String toString(); + String debug(); + @override bool operator ==(Object other); + @override int get hashCode; +} final class ClashErrno { final int errno; const ClashErrno({required this.errno}); @@ -758,8 +767,19 @@ final class ClashEscaped { String debug(); @override bool operator ==(Object other); @override int get hashCode; + int delete_(int new_2, int new_); int delete(); - int delete_(int new_, int new_2); +} +final class ClashUnderscored { + final int new_; + final int new2_; + final int debug_; + final int default_; + const ClashUnderscored({required this.new_, required this.new2_, required this.debug_, required this.default_}); + String debug(); + @override bool operator ==(Object other); + @override int get hashCode; + factory ClashUnderscored.default_(); } final class TlsPolicyLifetime { final int seconds; @@ -1086,6 +1106,26 @@ final class ClashTagPrivate extends ClashTag { final int number; const ClashTagPrivate({required this.number}); } +enum ClashOp { + delete_(0), + delete(1), + const ClashOp(this._c); + String debug(); +} +sealed class ClashChange { + const ClashChange(); + String debug(); + @override bool operator ==(Object other); + @override int get hashCode; +} +final class ClashChangeSet extends ClashChange { + final int new_; + final int new2_; + const ClashChangeSet({required this.new_, required this.new2_}); +} +final class ClashChangeClear extends ClashChange { + const ClashChangeClear(); +} enum Level implements Comparable { error(0), warn(1), @@ -1617,6 +1657,10 @@ final class ClashStore extends _Object { int close_(); void wait(); void finalize(); + static int count_(); + int count(); + factory ClashStore.open(); + int open(); } final class ClashReader extends _Object { factory ClashReader(typed.Uint8List bytes); @@ -1747,6 +1791,11 @@ abstract class ClashSource { int readByte(); void close(); } +abstract class ClashEraser { + int delete_(int new_, int new_2); + int delete(); + void close(); +} final class BoundsU64Exception implements Exception { final BoundsU64 error; const BoundsU64Exception(this.error); @@ -2035,6 +2084,7 @@ typed.Uint8List unzeroed(typed.Uint8List bytes); int deprecated(int note); int deprecated_(int note); int all(int note); +int all_(int note); @Deprecated('') Knob knob(Dial dial); @Deprecated('read its `level`') Cancelable levelLater(Dial dial); Dial turned(Dial dial, Turner turner); @@ -2054,7 +2104,16 @@ ClashAny clashAny(String typeUrl); ClashCandidate clashCandidate(int at); int clashIgnore(int arg0, int arg1, int arg2); ClashEmptyString clashEmpty(); +int clashDescribed(ClashDescribed described); int clashWaited(ClashSource source); +int clashUnderscored(ClashUnderscored underscored, ClashOp op, ClashChange change); +(ClashUnderscored, ClashChange) clashUnderscoredNext(ClashUnderscored underscored, ClashChange change); +int clashErased(ClashEraser eraser); +int clashErase_(); +int clashErase(); +int clashLend_(ClashStore? store); +int clashLend(); +int clashRun(int Function() work2, int work); ClashTone clashAudible(ClashTone tone); int clashNested(((int, int), int)? a, ((int, int, int),)? b); int clashAudioEncoderFinish(); diff --git a/ffi/surface/api/go.txt b/ffi/surface/api/go.txt index fc5e92e49..3b439bef6 100644 --- a/ffi/surface/api/go.txt +++ b/ffi/surface/api/go.txt @@ -11,6 +11,7 @@ FUNCTIONS func Admit(entry p_rt.Tuple4[*Counter, *Mark, Seat, Choice]) (uint64, error) func After(ctx context.Context, first func(context.Context), value uint32) (uint32, error) func All(note uint8) uint8 +func All_(note uint8) uint8 func Alpn(config *p_tls.Config) (string, error) func AlpnLent(config *p_tls.Config) (string, error) func ApplyNonZeroU16(pair PairNonZeroU16, f func(uint16) uint32) (uint32, error) @@ -43,10 +44,21 @@ func Choose(choice Choice) (uint64, error) func Chunks(bytes p_rt.Bytes, size uint) []p_rt.Bytes func ClashAudioEncoderFinish() uint8 func ClashAudioEncoderFinish_() uint8 +func ClashDescribed_(described ClashDescribed) uint32 +func ClashErase() uint8 +func ClashErase_() uint8 +func ClashErased(eraser ClashEraser) uint32 +func ClashEraserVtable_() unsafe.Pointer func ClashIgnore(arg0 uint8, arg1 uint8, arg2 uint8) uint8 +func ClashLend() uint32 +func ClashLend_(store *ClashStore) (uint32, error) func ClashListed(java []uint32, kotlin *uint32) [][]uint32 func ClashNested(a *p_rt.Tuple2[p_rt.Tuple2[uint8, uint16], uint32], b *p_rt.Tuple3[uint8, uint16, uint32]) uint32 +func ClashRun(work2 func() uint8, work uint8) uint32 func ClashSourceVtable_() unsafe.Pointer +func ClashStoreCount() uint32 +func ClashUnderscoredNext(underscored ClashUnderscored, change ClashChange) (ClashUnderscored, ClashChange) +func ClashUnderscored_(underscored ClashUnderscored, op ClashOp, change ClashChange) uint32 func ClashWaited(source ClashSource) uint8 func Coordinates(point *Point) int32 func Corner(unit bool) (p_rt.Tuple2[uint32, uint32], error) @@ -512,6 +524,27 @@ type ClashCandidateNone struct { } func (self ClashCandidateNone) Equal(other ClashCandidate) bool func (self ClashCandidateNone) GoString() string +type ClashChange interface { + GoString() string + Equal(other ClashChange) bool +} +type ClashChangeClear struct { +} +func (self ClashChangeClear) Equal(other ClashChange) bool +func (self ClashChangeClear) GoString() string +type ClashChangeSet struct { + New_ uint8 + New uint8 +} +func (self ClashChangeSet) Equal(other ClashChange) bool +func (self ClashChangeSet) GoString() string +type ClashDescribed struct { + Description uint8 + DebugDescription uint8 +} +func (self ClashDescribed) Equal(other ClashDescribed) bool +func (self ClashDescribed) GoString() string +func (self ClashDescribed) String() string type ClashDouble struct { V0 float64 } @@ -531,6 +564,10 @@ type ClashEmptyString struct { func ClashEmpty() *ClashEmptyString func (self *ClashEmptyString) Close() error func (self *ClashEmptyString) IsEmpty() (bool, error) +type ClashEraser interface { + Delete_(new_ uint8, new_2 uint8) uint8 + Delete() uint8 +} type ClashErrno struct { Errno int32 } @@ -541,7 +578,7 @@ type ClashEscaped struct { New uint8 } func (self ClashEscaped) Delete() uint8 -func (self ClashEscaped) Delete_(new_ uint8, new_2 uint8) uint8 +func (self ClashEscaped) Delete_(new_2 uint8, new_ uint8) uint8 func (self ClashEscaped) Equal(other ClashEscaped) bool func (self ClashEscaped) GoString() string type ClashEvent struct { @@ -638,6 +675,13 @@ func (self ClashNative) Point() (*Point, error) func (self ClashNative) Reading(kotlin uint32) (Reading, error) func (self ClashNative) Stamp(kotlin uint64) (Stamp, error) func (self ClashNative) Tagged(ctx context.Context, tag string) (string, error) +type ClashOp int32 +const ( + ClashOpDelete_ ClashOp = 0 + ClashOpDelete ClashOp = 1 +) +func (self ClashOp) Equal(other ClashOp) bool +func (self ClashOp) GoString() string type ClashPair struct { V0 uint8 V1 uint8 @@ -721,11 +765,14 @@ func (self ClashStamp) Tagged(ctx context.Context, tag string) (string, error) type ClashStore struct { Handle_ *p_rt.Handle_ } +func ClashStoreOpen() *ClashStore func NewClashStore(count uint32) *ClashStore func (self *ClashStore) Close() error func (self *ClashStore) Close_() (uint32, error) +func (self *ClashStore) Count() (uint32, error) func (self *ClashStore) Finalize() error func (self *ClashStore) Free() (uint32, error) +func (self *ClashStore) Open() (uint32, error) func (self *ClashStore) Wait() error type ClashString struct { V0 string @@ -768,6 +815,15 @@ type ClashTone_ struct { } func (self ClashTone_) Equal(other ClashTone_) bool func (self ClashTone_) GoString() string +type ClashUnderscored struct { + New_ uint8 + New uint8 + Debug uint8 + Default uint8 +} +func ClashUnderscoredDefault() ClashUnderscored +func (self ClashUnderscored) Equal(other ClashUnderscored) bool +func (self ClashUnderscored) GoString() string type ClashUnit struct { } func (self ClashUnit) Bytes() (p_rt.Bytes, error) diff --git a/ffi/surface/api/kotlin.kt b/ffi/surface/api/kotlin.kt index 6715d89f4..033757cc5 100644 --- a/ffi/surface/api/kotlin.kt +++ b/ffi/surface/api/kotlin.kt @@ -432,8 +432,8 @@ data class ClashAny(val typeUrl: kotlin.String) { data class ClashBreak(val _0: kotlin.UByte) { fun debug(): kotlin.String companion object { - @kotlin.jvm.JvmStatic val SP: api.ClashBreak @kotlin.jvm.JvmStatic val SP_: api.ClashBreak + @kotlin.jvm.JvmStatic val SP: api.ClashBreak } } data class ClashMalformed(val at: kotlin.UByte) { @@ -441,16 +441,26 @@ data class ClashMalformed(val at: kotlin.UByte) { fun debug(): kotlin.String fun `is`(at: kotlin.UByte): kotlin.Boolean } +data class ClashDescribed(val description: kotlin.UByte, val debugDescription: kotlin.UByte) { + final override fun toString(): kotlin.String + fun debug(): kotlin.String +} data class ClashErrno(val errno: kotlin.Int) { fun debug(): kotlin.String companion object { - @kotlin.jvm.JvmStatic val `NULL`: api.ClashErrno + @kotlin.jvm.JvmStatic val NULL: api.ClashErrno } } data class ClashEscaped(val new: kotlin.UByte) { fun debug(): kotlin.String - fun delete(): kotlin.UByte fun delete_(new: kotlin.UByte, new2: kotlin.UByte): kotlin.UByte + fun delete(): kotlin.UByte +} +data class ClashUnderscored(val new_: kotlin.UByte, val new: kotlin.UByte, val debug: kotlin.UByte, val default: kotlin.UByte) { + fun debug(): kotlin.String + companion object { + @kotlin.jvm.JvmStatic fun default(): api.ClashUnderscored + } } data class TlsPolicyLifetime(val seconds: kotlin.UInt) { fun debug(): kotlin.String @@ -619,6 +629,17 @@ sealed class ClashTag { fun debug(): kotlin.String fun number(): kotlin.UInt } +enum class ClashOp(internal val value: Int) { + DELETE_(0), + DELETE(1); + fun debug(): kotlin.String + companion object {} +} +sealed class ClashChange { + data class Set(val new_: kotlin.UByte, val new: kotlin.UByte) : ClashChange() + data object Clear : ClashChange() + fun debug(): kotlin.String +} enum class Level(internal val value: Int) { ERROR(0), WARN(1), @@ -1322,8 +1343,12 @@ class ClashStore internal constructor(raw: Long, lent: Boolean = false) : AutoCl fun close_(): kotlin.UInt @kotlin.jvm.JvmName("wait_") fun wait() @kotlin.jvm.JvmName("finalize_") fun finalize() + fun count(): kotlin.UInt + fun open(): kotlin.UInt companion object { @kotlin.jvm.JvmStatic fun new(count: kotlin.UInt): api.ClashStore + @kotlin.jvm.JvmStatic @kotlin.jvm.JvmName("count_") fun count(): kotlin.UInt + @kotlin.jvm.JvmStatic @kotlin.jvm.JvmName("open_") fun open(): api.ClashStore } } class ClashReader internal constructor(raw: Long, lent: Boolean = false) : AutoCloseable { @@ -1475,6 +1500,10 @@ interface ClashSource { fun wait_() fun readByte(): kotlin.UByte } +interface ClashEraser { + fun delete_(new2: kotlin.UByte, new: kotlin.UByte): kotlin.UByte + fun delete(): kotlin.UByte +} data class Tuple1(val first: T1) { override fun equals(other: kotlin.Any?): kotlin.Boolean override fun hashCode(): kotlin.Int @@ -1784,6 +1813,7 @@ fun unzeroed(bytes: api.Bytes): api.Bytes fun deprecated(note: kotlin.UByte): kotlin.UByte fun deprecated_(note: kotlin.UByte): kotlin.UByte fun all(note: kotlin.UByte): kotlin.UByte +fun all_(note: kotlin.UByte): kotlin.UByte @kotlin.Deprecated("") fun knob(dial: api.Dial): api.Knob @kotlin.Deprecated("read its `level`") suspend fun levelLater(dial: api.Dial): kotlin.ULong @kotlin.jvm.Throws(ErrorException::class) fun turned(dial: api.Dial, turner: api.Turner): api.Dial @@ -1803,7 +1833,16 @@ fun clashAny(typeUrl: kotlin.String): api.ClashAny fun clashCandidate(at: kotlin.UByte): api.ClashCandidate fun clashIgnore(arg0: kotlin.UByte, arg1: kotlin.UByte, arg2: kotlin.UByte): kotlin.UByte fun clashEmpty(): api.ClashEmptyString +fun clashDescribed(described: api.ClashDescribed): kotlin.UInt fun clashWaited(source: api.ClashSource): kotlin.UByte +fun clashUnderscored(underscored: api.ClashUnderscored, op: api.ClashOp, change: api.ClashChange): kotlin.UInt +fun clashUnderscoredNext(underscored: api.ClashUnderscored, change: api.ClashChange): kotlin.Pair +fun clashErased(eraser: api.ClashEraser): kotlin.UInt +fun clashErase_(): kotlin.UByte +fun clashErase(): kotlin.UByte +fun clashLend_(store: api.ClashStore?): kotlin.UInt +fun clashLend(): kotlin.UInt +fun clashRun(work2: () -> kotlin.UByte, work: kotlin.UByte): kotlin.UInt @kotlin.jvm.Throws(kotlincollectionsListClashToneException::class) fun clashAudible(tone: api.ClashTone): api.ClashTone fun clashNested(a: kotlin.Pair, kotlin.UInt>?, b: api.Tuple1>?): kotlin.UInt fun clashAudioEncoderFinish(): kotlin.UByte diff --git a/ffi/surface/api/python.pyi b/ffi/surface/api/python.pyi index a1e0dffb9..264f1ca9e 100644 --- a/ffi/surface/api/python.pyi +++ b/ffi/surface/api/python.pyi @@ -1,5 +1,5 @@ # api.py -__all__ = ['A', 'Area', 'Array', 'ArrayU8x4', 'Atlas', 'B', 'BOXED', 'Batch', 'Batch2', 'Beat', 'Berth', 'Board', 'Booth', 'Bound', 'BoundU64', 'BoundsU64', 'BoundsU64Exception', 'BoxedU16', 'BoxedU8', 'Buffer', 'Builtin', 'C', 'CancellationError', 'Cancelled', 'Channel', 'Choice', 'Clash', 'ClashAny', 'ClashBreak', 'ClashCandidate', 'ClashEmptyString', 'ClashErrno', 'ClashEscaped', 'ClashLevel', 'ClashMalformed', 'ClashMalformedException', 'ClashReader', 'ClashSeed', 'ClashSource', 'ClashSpan', 'ClashStore', 'ClashTag', 'ClashTone', 'ClashTone_', 'Clocked', 'Codecs', 'Core', 'Countdown', 'Counter', 'Cursor', 'Deprecated', 'Der', 'Dial', 'Digest', 'DoubleArray', 'Draft', 'Duration', 'EOF', 'Error', 'ErrorException', 'Event', 'Extent', 'FAR', 'Family', 'Fault', 'FaultException', 'Feed', 'FiledReceipt', 'ForeignReader', 'Forged', 'GREETINGS', 'Gap', 'Gauge', 'Guarded', 'Handle', 'Hasher', 'Hits', 'Holder', 'Hooked', 'InnerU8', 'Instant', 'Journal', 'Json', 'JvmField', 'JvmStatic', 'Key', 'Knob', 'LIMIT', 'Label', 'Labeled', 'Labelled', 'Latch', 'Layered', 'Ledger', 'LeftRightU8', 'LeftU8', 'Level', 'LimitsBytes', 'LimitsDuration', 'ListClashToneException', 'Local', 'LocalWaiter', 'Log', 'LogCount', 'LogThread', 'Logger', 'LongArray', 'MacrosStreams', 'Mark', 'Marker', 'Measure', 'Message', 'Meter', 'Meters', 'Moment', 'Mut', 'Name', 'Node', 'NonZeros', 'Note', 'Numbers', 'OptIn', 'OuterInnerU8', 'PRIMES', 'Packaged', 'Packet', 'PadU16', 'PadU8', 'Page', 'PairNonZeroU16', 'PairSizeU8', 'PairU32', 'PairU8Size', 'Parcel', 'Part', 'Pass', 'Peer', 'Pinned', 'Placement', 'Plain', 'Platform', 'Point', 'PolarPoint', 'PolarTurn', 'Polar_Turn', 'Qualifiers', 'Quantity', 'Rank', 'Rated', 'Reading', 'Receipt', 'Refusal', 'RefusalException', 'Registry', 'Resolving', 'Retired', 'Retry', 'RightLeftU8', 'RightU8', 'STEP', 'Scan', 'Score', 'Seat', 'Shadowed', 'Shape', 'Sheet', 'Site', 'Size', 'Slip', 'SlotU32', 'SlotU8', 'Span', 'Spawned', 'Spot', 'Stack', 'Stage', 'Stamp', 'Stamped', 'StartSeekable', 'Status', 'StdIoError', 'Stretch', 'StringException', 'Tab', 'Tag', 'Tallies', 'Tally', 'Ticket', 'Tier', 'TlsCert', 'TlsCodec', 'TlsConfig', 'TlsPolicyLifetime', 'TlsResolver', 'TlsSession', 'Token', 'Trail', 'Turner', 'URL', 'Undo', 'Url', 'VecClashTone', 'Verbosity', 'Version', 'Waiter', 'Waker', 'Weighted', 'Wide', 'Window', 'Worker', 'WrapU32', 'Wrapped', '__all___', '_deprecated_', 'admit', 'advance', 'after', 'alpn', 'alpn_lent', 'apply_non_zero_u16', 'apply_u32', 'area', 'assert_', 'attempt', 'beats', 'below', 'booth_count', 'boxed_counter', 'boxed_floats', 'boxed_name', 'boxed_tuple', 'breadth', 'bump_both', 'bump_either', 'bumped', 'byte_len', 'byte_limits', 'capacities_2_2', 'capacities_2_4', 'capacities_4_2', 'capacities_4_4', 'cert_der', 'cert_len', 'certify', 'chain_len', 'choose', 'chunks', 'clash_any', 'clash_audible', 'clash_audio_encoder_finish', 'clash_audio_encoder_finish_', 'clash_candidate', 'clash_empty', 'clash_ignore', 'clash_nested', 'clash_waited', 'clocked_after', 'coordinates', 'corner', 'corner_later', 'count', 'counted', 'counters', 'crammed', 'cross', 'crowded', 'deprecated', 'describe', 'describe_non_zeros', 'digit', 'divide', 'doubled', 'doubled_i64', 'doubled_ttl', 'drain_2', 'drain_4', 'drive', 'dropped', 'each', 'either', 'either_later', 'emit', 'emit_from_thread', 'emit_later', 'encode', 'end', 'ends', 'entries', 'erased', 'errno', 'excuse', 'extended', 'failure', 'failure_kind', 'failure_message', 'farther_hop', 'file', 'fill_2', 'fill_4', 'filter', 'find', 'fingerprint', 'first_of', 'flip', 'greet', 'grow', 'halved', 'halves', 'has_instant', 'has_text', 'heft', 'held_count', 'hex', 'hook', 'host', 'is_family', 'is_kept', 'jam', 'jni_one', 'join_words', 'joined', 'jvm_sum', 'keep_point', 'keeper_point', 'keeps', 'kept_counter', 'kept_or_point', 'kept_point', 'kept_polar_point', 'kept_size', 'kept_wrap_u32', 'knob', 'lasting', 'later', 'layer_name', 'least', 'len', 'lent_back', 'less', 'lettered', 'level_later', 'local_after', 'local_later', 'local_or_new', 'local_or_new_later', 'locals_dropped', 'log_counts', 'log_later', 'log_on_drop', 'log_waker', 'longer', 'longest', 'louder', 'macros_streamed', 'made', 'marked', 'measured', 'moment_at', 'named', 'negated', 'next_char', 'next_hop', 'next_ips', 'next_packet', 'nexts', 'non_zeros', 'now', 'nudge', 'nudge_by', 'numbered', 'offered_len', 'offset', 'offsetof', 'on_first_thread', 'only', 'page', 'pair', 'paired', 'parents', 'parse_cert', 'parse_later', 'peek', 'placement', 'platform', 'pointer_bits', 'polar_point', 'poll_tripled', 'port', 'ports', 'prefixed', 'push_counted', 'put_number', 'queued_hex', 'reach', 'read_len', 'reading', 'reading_bump', 'reading_debug', 'reading_echo', 'reasons', 'refuse', 'reissue', 'reissue_lent', 'relay', 'report_non_zero_u16', 'report_u32', 'resolve', 'resolved', 'resolver', 'resume', 'return_moved', 'return_values', 'rooted_name', 'rows', 'same', 'same_char', 'same_duration', 'same_ip_addr', 'same_isize', 'same_labelled', 'same_path', 'same_socket_addr', 'same_socket_addr_v4', 'same_socket_addr_v6', 'same_string', 'same_u128', 'same_u64', 'same_usize', 'sample_hex', 'scaled', 'scanned', 'seat', 'second_later', 'sections', 'secure', 'seeds_counter_counter', 'seeds_counter_point', 'seeds_counter_polar_point', 'seeds_counter_size', 'seeds_counter_wrap_u32', 'seeds_point_counter', 'seeds_point_point', 'seeds_point_polar_point', 'seeds_point_size', 'seeds_point_wrap_u32', 'seek_to', 'sentence', 'shift', 'shifted', 'since', 'span', 'spell', 'spend', 'split_last', 'spread', 'stamp_at', 'stored', 'stored_text', 'stray', 'stretched', 'sum_all', 'sum_lists', 'sum_u32', 'summed', 'summed_up_receipt', 'sums', 'swapped', 'tag', 'tagged', 'tail', 'tallied', 'tally_log_count', 'tick_name', 'tickets', 'timed_hex', 'title', 'token_bytes', 'token_slice', 'total', 'turned', 'undone', 'unescaped', 'unescaped_later', 'unescaped_maybe', 'unhook', 'unnamed', 'unwound', 'unzeroed', 'verify', 'visit_chunks', 'visit_stray', 'walk', 'wasm_log', 'wasm_only', 'wasm_take', 'watch', 'weigh_all_counter', 'weigh_point', 'wexitstatus', 'wide', 'widen', 'widths', 'wind', 'within', 'words', 'worth', 'yielded'] +__all__ = ['A', 'Area', 'Array', 'ArrayU8x4', 'Atlas', 'B', 'BOXED', 'Batch', 'Batch2', 'Beat', 'Berth', 'Board', 'Booth', 'Bound', 'BoundU64', 'BoundsU64', 'BoundsU64Exception', 'BoxedU16', 'BoxedU8', 'Buffer', 'Builtin', 'C', 'CancellationError', 'Cancelled', 'Channel', 'Choice', 'Clash', 'ClashAny', 'ClashBreak', 'ClashCandidate', 'ClashChange', 'ClashDescribed', 'ClashEmptyString', 'ClashEraser', 'ClashErrno', 'ClashEscaped', 'ClashLevel', 'ClashMalformed', 'ClashMalformedException', 'ClashOp', 'ClashReader', 'ClashSeed', 'ClashSource', 'ClashSpan', 'ClashStore', 'ClashTag', 'ClashTone', 'ClashTone_', 'ClashUnderscored', 'Clocked', 'Codecs', 'Core', 'Countdown', 'Counter', 'Cursor', 'Deprecated', 'Der', 'Dial', 'Digest', 'DoubleArray', 'Draft', 'Duration', 'EOF', 'Error', 'ErrorException', 'Event', 'Extent', 'FAR', 'Family', 'Fault', 'FaultException', 'Feed', 'FiledReceipt', 'ForeignReader', 'Forged', 'GREETINGS', 'Gap', 'Gauge', 'Guarded', 'Handle', 'Hasher', 'Hits', 'Holder', 'Hooked', 'InnerU8', 'Instant', 'Journal', 'Json', 'JvmField', 'JvmStatic', 'Key', 'Knob', 'LIMIT', 'Label', 'Labeled', 'Labelled', 'Latch', 'Layered', 'Ledger', 'LeftRightU8', 'LeftU8', 'Level', 'LimitsBytes', 'LimitsDuration', 'ListClashToneException', 'Local', 'LocalWaiter', 'Log', 'LogCount', 'LogThread', 'Logger', 'LongArray', 'MacrosStreams', 'Mark', 'Marker', 'Measure', 'Message', 'Meter', 'Meters', 'Moment', 'Mut', 'Name', 'Node', 'NonZeros', 'Note', 'Numbers', 'OptIn', 'OuterInnerU8', 'PRIMES', 'Packaged', 'Packet', 'PadU16', 'PadU8', 'Page', 'PairNonZeroU16', 'PairSizeU8', 'PairU32', 'PairU8Size', 'Parcel', 'Part', 'Pass', 'Peer', 'Pinned', 'Placement', 'Plain', 'Platform', 'Point', 'PolarPoint', 'PolarTurn', 'Polar_Turn', 'Qualifiers', 'Quantity', 'Rank', 'Rated', 'Reading', 'Receipt', 'Refusal', 'RefusalException', 'Registry', 'Resolving', 'Retired', 'Retry', 'RightLeftU8', 'RightU8', 'STEP', 'Scan', 'Score', 'Seat', 'Shadowed', 'Shape', 'Sheet', 'Site', 'Size', 'Slip', 'SlotU32', 'SlotU8', 'Span', 'Spawned', 'Spot', 'Stack', 'Stage', 'Stamp', 'Stamped', 'StartSeekable', 'Status', 'StdIoError', 'Stretch', 'StringException', 'Tab', 'Tag', 'Tallies', 'Tally', 'Ticket', 'Tier', 'TlsCert', 'TlsCodec', 'TlsConfig', 'TlsPolicyLifetime', 'TlsResolver', 'TlsSession', 'Token', 'Trail', 'Turner', 'URL', 'Undo', 'Url', 'VecClashTone', 'Verbosity', 'Version', 'Waiter', 'Waker', 'Weighted', 'Wide', 'Window', 'Worker', 'WrapU32', 'Wrapped', '__all___', '__all____', '_deprecated_', 'admit', 'advance', 'after', 'alpn', 'alpn_lent', 'apply_non_zero_u16', 'apply_u32', 'area', 'assert_', 'attempt', 'beats', 'below', 'booth_count', 'boxed_counter', 'boxed_floats', 'boxed_name', 'boxed_tuple', 'breadth', 'bump_both', 'bump_either', 'bumped', 'byte_len', 'byte_limits', 'capacities_2_2', 'capacities_2_4', 'capacities_4_2', 'capacities_4_4', 'cert_der', 'cert_len', 'certify', 'chain_len', 'choose', 'chunks', 'clash_any', 'clash_audible', 'clash_audio_encoder_finish', 'clash_audio_encoder_finish_', 'clash_candidate', 'clash_described', 'clash_empty', 'clash_erase', 'clash_erase_', 'clash_erased', 'clash_ignore', 'clash_lend', 'clash_lend_', 'clash_nested', 'clash_run', 'clash_underscored', 'clash_underscored_next', 'clash_waited', 'clocked_after', 'coordinates', 'corner', 'corner_later', 'count', 'counted', 'counters', 'crammed', 'cross', 'crowded', 'deprecated', 'describe', 'describe_non_zeros', 'digit', 'divide', 'doubled', 'doubled_i64', 'doubled_ttl', 'drain_2', 'drain_4', 'drive', 'dropped', 'each', 'either', 'either_later', 'emit', 'emit_from_thread', 'emit_later', 'encode', 'end', 'ends', 'entries', 'erased', 'errno', 'excuse', 'extended', 'failure', 'failure_kind', 'failure_message', 'farther_hop', 'file', 'fill_2', 'fill_4', 'filter', 'find', 'fingerprint', 'first_of', 'flip', 'greet', 'grow', 'halved', 'halves', 'has_instant', 'has_text', 'heft', 'held_count', 'hex', 'hook', 'host', 'is_family', 'is_kept', 'jam', 'jni_one', 'join_words', 'joined', 'jvm_sum', 'keep_point', 'keeper_point', 'keeps', 'kept_counter', 'kept_or_point', 'kept_point', 'kept_polar_point', 'kept_size', 'kept_wrap_u32', 'knob', 'lasting', 'later', 'layer_name', 'least', 'len', 'lent_back', 'less', 'lettered', 'level_later', 'local_after', 'local_later', 'local_or_new', 'local_or_new_later', 'locals_dropped', 'log_counts', 'log_later', 'log_on_drop', 'log_waker', 'longer', 'longest', 'louder', 'macros_streamed', 'made', 'marked', 'measured', 'moment_at', 'named', 'negated', 'next_char', 'next_hop', 'next_ips', 'next_packet', 'nexts', 'non_zeros', 'now', 'nudge', 'nudge_by', 'numbered', 'offered_len', 'offset', 'offsetof', 'on_first_thread', 'only', 'page', 'pair', 'paired', 'parents', 'parse_cert', 'parse_later', 'peek', 'placement', 'platform', 'pointer_bits', 'polar_point', 'poll_tripled', 'port', 'ports', 'prefixed', 'push_counted', 'put_number', 'queued_hex', 'reach', 'read_len', 'reading', 'reading_bump', 'reading_debug', 'reading_echo', 'reasons', 'refuse', 'reissue', 'reissue_lent', 'relay', 'report_non_zero_u16', 'report_u32', 'resolve', 'resolved', 'resolver', 'resume', 'return_moved', 'return_values', 'rooted_name', 'rows', 'same', 'same_char', 'same_duration', 'same_ip_addr', 'same_isize', 'same_labelled', 'same_path', 'same_socket_addr', 'same_socket_addr_v4', 'same_socket_addr_v6', 'same_string', 'same_u128', 'same_u64', 'same_usize', 'sample_hex', 'scaled', 'scanned', 'seat', 'second_later', 'sections', 'secure', 'seeds_counter_counter', 'seeds_counter_point', 'seeds_counter_polar_point', 'seeds_counter_size', 'seeds_counter_wrap_u32', 'seeds_point_counter', 'seeds_point_point', 'seeds_point_polar_point', 'seeds_point_size', 'seeds_point_wrap_u32', 'seek_to', 'sentence', 'shift', 'shifted', 'since', 'span', 'spell', 'spend', 'split_last', 'spread', 'stamp_at', 'stored', 'stored_text', 'stray', 'stretched', 'sum_all', 'sum_lists', 'sum_u32', 'summed', 'summed_up_receipt', 'sums', 'swapped', 'tag', 'tagged', 'tail', 'tallied', 'tally_log_count', 'tick_name', 'tickets', 'timed_hex', 'title', 'token_bytes', 'token_slice', 'total', 'turned', 'undone', 'unescaped', 'unescaped_later', 'unescaped_maybe', 'unhook', 'unnamed', 'unwound', 'unzeroed', 'verify', 'visit_chunks', 'visit_stray', 'walk', 'wasm_log', 'wasm_only', 'wasm_take', 'watch', 'weigh_all_counter', 'weigh_point', 'wexitstatus', 'wide', 'widen', 'widths', 'wind', 'within', 'words', 'worth', 'yielded'] class Waker: def __init__(self, wake: _typing.Callable[[], _object], loop: _asyncio.AbstractEventLoop | None=None) -> None: ... def wake(self) -> None: ... @@ -520,10 +520,10 @@ class ClashBreak(_Record): def __init__(self, _0: _int) -> None: ... def __eq__(self, other: _object) -> _bool: ... def __repr__(self) -> _str: ... - SP = _n.clash_Break_Sp() - SP_ = _n.clash_Break_SP() - SP = _Const(_n.clash_Break_Sp) - SP_ = _Const(_n.clash_Break_SP) + SP_ = _n.clash_Break_Sp() + SP = _n.clash_Break_SP() + SP_ = _Const(_n.clash_Break_Sp) + SP = _Const(_n.clash_Break_SP) class ClashMalformed(_Record): at: _int def __init__(self, at: _int) -> None: ... @@ -531,6 +531,13 @@ class ClashMalformed(_Record): def __str__(self) -> _str: ... def __repr__(self) -> _str: ... def is_(self, at: _int) -> _bool: ... +class ClashDescribed(_Record): + description: _int + debug_description: _int + def __init__(self, description: _int, debug_description: _int) -> None: ... + def __eq__(self, other: _object) -> _bool: ... + def __str__(self) -> _str: ... + def __repr__(self) -> _str: ... class ClashErrno(_Record): errno: _int def __init__(self, errno: _int) -> None: ... @@ -543,8 +550,18 @@ class ClashEscaped(_Record): def __init__(self, new: _int) -> None: ... def __eq__(self, other: _object) -> _bool: ... def __repr__(self) -> _str: ... - def delete(self) -> _int: ... def delete_(self, new: _int, new_: _int) -> _int: ... + def delete(self) -> _int: ... +class ClashUnderscored(_Record): + new_: _int + new: _int + debug: _int + default_: _int + def __init__(self, new_: _int, new: _int, debug: _int, default_: _int) -> None: ... + def __eq__(self, other: _object) -> _bool: ... + def __repr__(self) -> _str: ... + @_staticmethod + def default() -> ClashUnderscored: ... class TlsPolicyLifetime(_Record): seconds: _int def __init__(self, seconds: _int) -> None: ... @@ -840,6 +857,21 @@ class _ClashTag_Private(ClashTag, _Record): number: _int def __init__(self, number: _int) -> None: ... def __eq__(self, other: _object) -> _bool: ... +class ClashOp(_enum.Enum): + DELETE_ = 0 + DELETE = 1 + def __repr__(self) -> _str: ... +class ClashChange: + def __repr__(self) -> _str: ... + Set: _typing.TypeAlias = '_ClashChange_Set' + Clear: _typing.TypeAlias = '_ClashChange_Clear' +class _ClashChange_Set(ClashChange, _Record): + new_: _int + new: _int + def __init__(self, new_: _int, new: _int) -> None: ... + def __eq__(self, other: _object) -> _bool: ... +class _ClashChange_Clear(ClashChange, _Record): + def __eq__(self, other: _object) -> _bool: ... class Level(_enum.Enum): ERROR = 0 WARN = 1 @@ -1409,6 +1441,12 @@ class ClashStore(_n.Object): def close(self) -> _int: ... def wait(self) -> None: ... def finalize(self) -> None: ... + @_staticmethod + def count_() -> _int: ... + def count(self) -> _int: ... + @_staticmethod + def open_() -> ClashStore: ... + def open(self) -> _int: ... class ClashReader(_n.Object): @_staticmethod def new(bytes: _bytes | _bytearray | _memoryview) -> ClashReader: ... @@ -1531,6 +1569,11 @@ class ClashSource(_abc.ABC): def wait(self) -> None: ... @_abc.abstractmethod def read_byte(self) -> _int: ... +class ClashEraser(_abc.ABC): + @_abc.abstractmethod + def delete_(self, new_: _int, new: _int) -> _int: ... + @_abc.abstractmethod + def delete(self) -> _int: ... class BoundsU64Exception(_Exception): def __init__(self, error: BoundsU64) -> None: ... def __str__(self) -> _str: ... @@ -1839,6 +1882,7 @@ def same_ip_addr(v: _ipaddress.IPv4Address | _ipaddress.IPv6Address) -> _ipaddre def unescaped(text: _str) -> _str: ... def unzeroed(bytes: _bytes | _bytearray | _memoryview) -> _memoryview: ... def deprecated(note: _int) -> _int: ... +def __all____(note: _int) -> _int: ... def __all___(note: _int) -> _int: ... @_deprecated('') def knob(dial: Dial) -> Knob: ... @@ -1859,7 +1903,16 @@ def clash_any(type_url: _str) -> ClashAny: ... def clash_candidate(at: _int) -> ClashCandidate: ... def clash_ignore(arg0: _int, arg1: _int, arg2: _int) -> _int: ... def clash_empty() -> ClashEmptyString: ... +def clash_described(described: ClashDescribed) -> _int: ... def clash_waited(source: ClashSource) -> _int: ... +def clash_underscored(underscored: ClashUnderscored, op: ClashOp, change: ClashChange) -> _int: ... +def clash_underscored_next(underscored: ClashUnderscored, change: ClashChange) -> _tuple[ClashUnderscored, ClashChange]: ... +def clash_erased(eraser: ClashEraser) -> _int: ... +def clash_erase_() -> _int: ... +def clash_erase() -> _int: ... +def clash_lend_(store: ClashStore | None) -> _int: ... +def clash_lend() -> _int: ... +def clash_run(work_: _typing.Callable[[], _int], work: _int) -> _int: ... def clash_audible(tone: ClashTone) -> ClashTone: ... def clash_nested(a: _tuple[_tuple[_int, _int], _int] | None, b: _tuple[_tuple[_int, _int, _int]] | None) -> _int: ... def clash_audio_encoder_finish() -> _int: ... @@ -2136,7 +2189,16 @@ clash_any = _n.clash_any clash_candidate = _n.clash_candidate clash_ignore = _n.clash_ignore clash_empty = _n.clash_empty +clash_described = _n.clash_described clash_waited = _n.clash_waited +clash_underscored = _n.clash_underscored +clash_underscored_next = _n.clash_underscored_next +clash_erased = _n.clash_erased +clash_erase_ = _n.clash_erase_ +clash_erase = _n.clash_erase +clash_lend_ = _n.clash_lend_ +clash_lend = _n.clash_lend +clash_run = _n.clash_run clash_audible = _n.clash_audible clash_nested = _n.clash_nested clash_audio_encoder_finish = _n.clash_audio_encoder_finish diff --git a/ffi/surface/api/swift.swift b/ffi/surface/api/swift.swift index fb9a22e7d..48b6ea52f 100644 --- a/ffi/surface/api/swift.swift +++ b/ffi/surface/api/swift.swift @@ -681,8 +681,8 @@ public struct ClashBreak: Sendable, CustomDebugStringConvertible, Equatable { @inlinable public init(_ _0: Swift.UInt8) @inlinable public var debugDescription: Swift.String { get } @inlinable public static func == (a: ClashBreak, b: ClashBreak) -> Swift.Bool - @inlinable public static var SP: ClashBreak { get } @inlinable public static var SP_: ClashBreak { get } + @inlinable public static var SP: ClashBreak { get } } public struct ClashMalformed: Sendable, CustomStringConvertible, CustomDebugStringConvertible, Equatable { public var at: Swift.UInt8 @@ -692,6 +692,14 @@ public struct ClashMalformed: Sendable, CustomStringConvertible, CustomDebugStri @inlinable public static func == (a: ClashMalformed, b: ClashMalformed) -> Swift.Bool @inlinable public func `is`(_ at: Swift.UInt8) -> Swift.Bool } +public struct ClashDescribed: Sendable, CustomStringConvertible, CustomDebugStringConvertible, Equatable { + public var description_: Swift.UInt8 + public var debugDescription_: Swift.UInt8 + @inlinable public init(description_: Swift.UInt8, debugDescription_: Swift.UInt8) + @inlinable public var description: Swift.String { get } + @inlinable public var debugDescription: Swift.String { get } + @inlinable public static func == (a: ClashDescribed, b: ClashDescribed) -> Swift.Bool +} public struct ClashErrno: Sendable, CustomDebugStringConvertible, Equatable { public var errno: Swift.Int32 @inlinable public init(errno: Swift.Int32) @@ -704,8 +712,18 @@ public struct ClashEscaped: Sendable, CustomDebugStringConvertible, Equatable { @inlinable public init(new: Swift.UInt8) @inlinable public var debugDescription: Swift.String { get } @inlinable public static func == (a: ClashEscaped, b: ClashEscaped) -> Swift.Bool - @inlinable public func delete() -> Swift.UInt8 @inlinable public func delete(_ new: Swift.UInt8, _ new2: Swift.UInt8) -> Swift.UInt8 + @inlinable public func delete() -> Swift.UInt8 +} +public struct ClashUnderscored: Sendable, CustomDebugStringConvertible, Equatable { + public var new_: Swift.UInt8 + public var new: Swift.UInt8 + public var debug: Swift.UInt8 + public var `default`: Swift.UInt8 + @inlinable public init(new_: Swift.UInt8, new: Swift.UInt8, debug: Swift.UInt8, `default`: Swift.UInt8) + @inlinable public var debugDescription: Swift.String { get } + @inlinable public static func == (a: ClashUnderscored, b: ClashUnderscored) -> Swift.Bool + @inlinable public static func `default`() -> ClashUnderscored } public struct TlsPolicyLifetime: Sendable, CustomDebugStringConvertible, Equatable { public var seconds: Swift.UInt32 @@ -873,6 +891,18 @@ public enum ClashTag: Sendable, CustomDebugStringConvertible, Equatable { @inlinable public static func == (a: ClashTag, b: ClashTag) -> Swift.Bool @inlinable public func number() -> Swift.UInt32 } +public enum ClashOp: Sendable, CustomDebugStringConvertible, Equatable { + case delete_ + case delete + @inlinable public var debugDescription: Swift.String { get } + @inlinable public static func == (a: ClashOp, b: ClashOp) -> Swift.Bool +} +public enum ClashChange: Sendable, CustomDebugStringConvertible, Equatable { + case set(new_: Swift.UInt8, new: Swift.UInt8) + case clear + @inlinable public var debugDescription: Swift.String { get } + @inlinable public static func == (a: ClashChange, b: ClashChange) -> Swift.Bool +} public enum Level: Sendable, CustomStringConvertible, Hashable, Comparable { case error case warn @@ -1440,6 +1470,10 @@ public struct ClashStore: ~Copyable, @unchecked Sendable { @inlinable public func close() -> Swift.UInt32 @inlinable public func wait() @inlinable public func finalize() + @inlinable public static func count() -> Swift.UInt32 + @inlinable public func count() -> Swift.UInt32 + @inlinable public static func `open`() -> ClashStore + @inlinable public func `open`() -> Swift.UInt32 } public struct ClashReader: ~Copyable, @unchecked Sendable { @inlinable public static func new(_ bytes: Bytes) -> ClashReader @@ -1554,6 +1588,10 @@ public protocol ClashSource: Sendable { func wait() func readByte() -> Swift.UInt8 } +public protocol ClashEraser: Sendable { + func delete(_ new2: Swift.UInt8, _ new: Swift.UInt8) -> Swift.UInt8 + func delete() -> Swift.UInt8 +} public struct BoundsU64Error: Swift.Error, CustomStringConvertible { public let error: BoundsU64 @inlinable public init(error: BoundsU64) @@ -1849,6 +1887,7 @@ public let URL: Swift.UInt64 @inlinable public func deprecated(_ note: Swift.UInt8) -> Swift.UInt8 @inlinable public func deprecated_(_ note: Swift.UInt8) -> Swift.UInt8 @inlinable public func all(_ note: Swift.UInt8) -> Swift.UInt8 +@inlinable public func all_(_ note: Swift.UInt8) -> Swift.UInt8 @available(*, deprecated) @inlinable public func knob(_ dial: Dial) -> Knob @available(*, deprecated, message: "read its `level`") @inlinable nonisolated(nonsending) public func levelLater(_ dial: Dial) async throws -> Swift.UInt64 @inlinable public func turned(_ dial: Dial, _ turner: any Turner) throws -> Dial @@ -1868,7 +1907,17 @@ public let URL: Swift.UInt64 @inlinable public func clashCandidate(_ at: Swift.UInt8) -> ClashCandidate @inlinable public func clashIgnore(_ arg0: Swift.UInt8, _ arg1: Swift.UInt8, _ arg2: Swift.UInt8) -> Swift.UInt8 @inlinable public func clashEmpty() -> ClashEmptyString +@inlinable public func clashDescribed(_ described: ClashDescribed) -> Swift.UInt32 @inlinable public func clashWaited(_ source: any ClashSource) -> Swift.UInt8 +@inlinable public func clashUnderscored(_ underscored: ClashUnderscored, _ op: ClashOp, _ change: ClashChange) -> Swift.UInt32 +@inlinable public func clashUnderscoredNext(_ underscored: ClashUnderscored, _ change: ClashChange) -> (ClashUnderscored, ClashChange) +@inlinable public func clashErased(_ eraser: any ClashEraser) -> Swift.UInt32 +@inlinable public func clashErase_() -> Swift.UInt8 +@inlinable public func clashErase() -> Swift.UInt8 +@inlinable public func clashLend_() -> Swift.UInt32 +@inlinable public func clashLend_(store: borrowing ClashStore) -> Swift.UInt32 +@inlinable public func clashLend() -> Swift.UInt32 +@inlinable public func clashRun(_ work2: @Sendable () -> Swift.UInt8, _ work: Swift.UInt8) -> Swift.UInt32 @inlinable public func clashAudible(_ tone: ClashTone) throws -> ClashTone @inlinable public func clashNested(_ a: ((Swift.UInt8, Swift.UInt16), Swift.UInt32)?, _ b: (Swift.UInt8, Swift.UInt16, Swift.UInt32)?) -> Swift.UInt32 @inlinable public func clashAudioEncoderFinish() -> Swift.UInt8 diff --git a/ffi/surface/api/web.d.ts b/ffi/surface/api/web.d.ts index a8416e493..ae8a8a0e7 100644 --- a/ffi/surface/api/web.d.ts +++ b/ffi/surface/api/web.d.ts @@ -272,8 +272,8 @@ export type ClashBreak = { }; export declare function debug(self: ClashBreak): string; export declare function eq(a: ClashBreak, b: ClashBreak): boolean; -export declare function SP(): ClashBreak; export declare function SP_(): ClashBreak; +export declare function SP(): ClashBreak; // ClashCandidate.ts export type ClashCandidate = { @@ -285,11 +285,38 @@ export type ClashCandidate = { export declare function debug(self: ClashCandidate): string; export declare function eq(a: ClashCandidate, b: ClashCandidate): boolean; +// ClashChange.ts +export type ClashChange = { + tag: "Set"; + new2: number; + new: number; +} | { + tag: "Clear"; +}; +export declare function debug(self: ClashChange): string; +export declare function eq(a: ClashChange, b: ClashChange): boolean; + +// ClashDescribed.ts +export type ClashDescribed = { + description: number; + debugDescription: number; +}; +export declare function toString(self: ClashDescribed): string; +export declare function debug(self: ClashDescribed): string; +export declare function eq(a: ClashDescribed, b: ClashDescribed): boolean; + // ClashEmptyString.ts import * as rt from "./rt.ts"; export type ClashEmptyString = rt.Handle<"ClashEmptyString">; export declare function isEmpty(self: ClashEmptyString): boolean; +// ClashEraser.ts +export interface ClashEraser { + delete_(new_: number, new_2: number): number; + delete$(): number; + close?(): void; +} + // ClashErrno.ts export type ClashErrno = { errno: number; @@ -304,8 +331,8 @@ export type ClashEscaped = { }; export declare function debug(self: ClashEscaped): string; export declare function eq(a: ClashEscaped, b: ClashEscaped): boolean; +export declare function delete_(self: ClashEscaped, new_2: number, new_: number): number; export declare function delete$(self: ClashEscaped): number; -export declare function delete_(self: ClashEscaped, new_: number, new_2: number): number; export { delete$ as delete }; // ClashLevel.ts @@ -324,6 +351,10 @@ export declare function debug(self: ClashMalformed): string; export declare function eq(a: ClashMalformed, b: ClashMalformed): boolean; export declare function is(self: ClashMalformed, at: number): boolean; +// ClashOp.ts +export type ClashOp = "Delete_" | "Delete"; +export declare function debug(self: ClashOp): string; + // ClashReader.ts import * as rt from "./rt.ts"; import type { ClashMalformed } from "./ClashMalformed.ts"; @@ -367,6 +398,10 @@ export declare function free(self: ClashStore): number; export declare function close(self: ClashStore): number; export declare function wait(self: ClashStore): void; export declare function finalize(self: ClashStore): void; +export declare function count_(): number; +export declare function count(self: ClashStore): number; +export declare function open_(): ClashStore; +export declare function open(self: ClashStore): number; export { new$ as new }; // ClashTag.ts @@ -395,6 +430,18 @@ export type ClashTone_ = { export declare function debug(self: ClashTone_): string; export declare function eq(a: ClashTone_, b: ClashTone_): boolean; +// ClashUnderscored.ts +export type ClashUnderscored = { + new2: number; + new: number; + debug: number; + default: number; +}; +export declare function debug(self: ClashUnderscored): string; +export declare function eq(a: ClashUnderscored, b: ClashUnderscored): boolean; +export declare function default$(): ClashUnderscored; +export { default$ as default }; + // Clocked.ts import type { Moment } from "./Moment.ts"; export type Clocked = { @@ -1814,14 +1861,18 @@ import type { Clash } from "./Clash.ts"; import type { ClashAny } from "./ClashAny.ts"; import type { ClashBreak } from "./ClashBreak.ts"; import type { ClashCandidate } from "./ClashCandidate.ts"; +import type { ClashChange } from "./ClashChange.ts"; +import type { ClashDescribed } from "./ClashDescribed.ts"; import type { ClashErrno } from "./ClashErrno.ts"; import type { ClashEscaped } from "./ClashEscaped.ts"; import type { ClashLevel } from "./ClashLevel.ts"; import type { ClashMalformed } from "./ClashMalformed.ts"; +import type { ClashOp } from "./ClashOp.ts"; import type { ClashSpan } from "./ClashSpan.ts"; import type { ClashTag } from "./ClashTag.ts"; import type { ClashTone } from "./ClashTone.ts"; import type { ClashTone_ } from "./ClashTone_.ts"; +import type { ClashUnderscored } from "./ClashUnderscored.ts"; import type { Clocked } from "./Clocked.ts"; import type { Counter } from "./Counter.ts"; import type { Cursor } from "./Cursor.ts"; @@ -1913,6 +1964,7 @@ export declare function e_Status_(v: Status): number; export declare function e_Tier(v: Tier): number; export declare function e_VecClashTone(v: VecClashTone): number; export declare function e_clash_Level(v: ClashLevel): number; +export declare function e_clash_Op(v: ClashOp): number; export declare function f0(): number; export declare function f1(): number; export declare function f10(): number; @@ -2131,9 +2183,11 @@ export declare function r_bounds_u64(p: number, o: boolean): { export declare function r_clash_Any(p: number, o: boolean): ClashAny; export declare function r_clash_Break(p: number, o: boolean): ClashBreak; export declare function r_clash_Candidate(p: number, o: boolean): ClashCandidate; +export declare function r_clash_Change(p: number, o: boolean): ClashChange; export declare function r_clash_Errno(p: number, o: boolean): ClashErrno; export declare function r_clash_Malformed(p: number, o: boolean): ClashMalformed; export declare function r_clash_Tone(p: number, o: boolean): ClashTone; +export declare function r_clash_Underscored(p: number, o: boolean): ClashUnderscored; export declare function r_option_Level(p: number, o: boolean): Level | undefined; export declare function r_option_Moment(p: number, o: boolean): Moment | undefined; export declare function r_option_Point(p: number, o: boolean): Point | undefined; @@ -2241,6 +2295,7 @@ export declare function vt_Scan(): number; export declare function vt_Stretch(): number; export declare function vt_Turner(): number; export declare function vt_Undo(): number; +export declare function vt_clash_Eraser(): number; export declare function vt_clash_Source(): number; export declare function w_Atlas(p: number, v: Atlas): void; export declare function w_Booth(p: number, v: Booth): void; @@ -2344,6 +2399,8 @@ export declare function w_bounds_u64(p: number, v: { export declare function w_clash_Any(p: number, v: ClashAny): void; export declare function w_clash_Break(p: number, v: ClashBreak): void; export declare function w_clash_Candidate(p: number, v: ClashCandidate): void; +export declare function w_clash_Change(p: number, v: ClashChange): void; +export declare function w_clash_Described(p: number, v: ClashDescribed): void; export declare function w_clash_Errno(p: number, v: ClashErrno): void; export declare function w_clash_Escaped(p: number, v: ClashEscaped): void; export declare function w_clash_Malformed(p: number, v: ClashMalformed): void; @@ -2351,6 +2408,7 @@ export declare function w_clash_Span(p: number, v: ClashSpan): void; export declare function w_clash_TONE(p: number, v: ClashTone_): void; export declare function w_clash_Tag(p: number, v: ClashTag): void; export declare function w_clash_Tone(p: number, v: ClashTone): void; +export declare function w_clash_Underscored(p: number, v: ClashUnderscored): void; export declare function w_macros_Streams(p: number, v: MacrosStreams): void; export declare function w_option_Level(p: number, v: Level | undefined): void; export declare function w_option_Point(p: number, v: Point | undefined): void; @@ -2439,6 +2497,8 @@ export declare const imports: { api_web_cb_Undo_delete: (data: number, p0: number) => number; api_web_cb_Undo_free: (data: number) => number; api_web_cb_Undo_type: (data: number) => number; + api_web_cb_clash_Eraser_delete: (data: number) => number; + api_web_cb_clash_Eraser_delete_: (data: number, p0: number, p1: number) => number; api_web_cb_clash_Source_read_byte: (data: number) => number; api_web_cb_clash_Source_wait: (data: number) => void; api_web_i_fn_0: (data: number, p0: bigint) => void; @@ -2476,9 +2536,15 @@ import type { BoxedU8 } from "./BoxedU8.ts"; import type { Choice } from "./Choice.ts"; import type { ClashAny } from "./ClashAny.ts"; import type { ClashCandidate } from "./ClashCandidate.ts"; +import type { ClashChange } from "./ClashChange.ts"; +import type { ClashDescribed } from "./ClashDescribed.ts"; import type { ClashEmptyString } from "./ClashEmptyString.ts"; +import type { ClashEraser } from "./ClashEraser.ts"; +import type { ClashOp } from "./ClashOp.ts"; import type { ClashSource } from "./ClashSource.ts"; +import type { ClashStore } from "./ClashStore.ts"; import type { ClashTone } from "./ClashTone.ts"; +import type { ClashUnderscored } from "./ClashUnderscored.ts"; import type { Clocked } from "./Clocked.ts"; import type { Counter } from "./Counter.ts"; import type { Cursor } from "./Cursor.ts"; @@ -2892,6 +2958,7 @@ export declare function unzeroed(bytes: Uint8Array | rt.Bytes): rt.Bytes; export declare function deprecated(note: number): number; export declare function deprecated_(note: number): number; export declare function all(note: number): number; +export declare function all_(note: number): number; export declare function knob(dial: Dial): Knob; export declare function levelLater(dial: Dial): rt.Call; export declare function turned(dial: Dial, turner: Turner): rt.Result; @@ -2911,7 +2978,16 @@ export declare function clashAny(typeUrl: string): ClashAny; export declare function clashCandidate(at: number): ClashCandidate; export declare function clashIgnore(arg0: number, arg1: number, arg2: number): number; export declare function clashEmpty(): ClashEmptyString; +export declare function clashDescribed(described: ClashDescribed): number; export declare function clashWaited(source: ClashSource): number; +export declare function clashUnderscored(underscored: ClashUnderscored, op: ClashOp, change: ClashChange): number; +export declare function clashUnderscoredNext(underscored: ClashUnderscored, change: ClashChange): [ClashUnderscored, ClashChange]; +export declare function clashErased(eraser: ClashEraser): number; +export declare function clashErase_(): number; +export declare function clashErase(): number; +export declare function clashLend_(store: ClashStore | undefined): number; +export declare function clashLend(): number; +export declare function clashRun(work2: () => number, work: number): number; export declare function clashAudible(tone: ClashTone): rt.Result; export declare function clashNested(a: [[number, number], number] | undefined, b: [[number, number, number]] | undefined): number; export declare function clashAudioEncoderFinish(): number; diff --git a/ffi/surface/moq/dart.dart b/ffi/surface/moq/dart.dart index 9987bb7fa..49b51e9b4 100644 --- a/ffi/surface/moq/dart.dart +++ b/ffi/surface/moq/dart.dart @@ -2528,12 +2528,12 @@ final class MuxClock extends _Object { @override bool operator ==(Object other); @override int get hashCode; factory MuxClock.default_(); - static Timescale get timescale; + static Timescale get timescale_; factory MuxClock(); factory MuxClock.at(ClockInstant epoch, ClockWall wall); Timestamp now(); Timestamp capture(ClockInstant at); - Timescale timescale_(); + Timescale timescale(); HangCatalogClock? wall(); ClockWall wallClock(Timestamp pts); } diff --git a/ffi/tests/api.c b/ffi/tests/api.c index e0d72fc26..30983d14c 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -870,6 +870,14 @@ static api_buf unspelled(void) { /* What the transcript's output does not show: each check of the ABI's contract beyond it. */ static void checks(void) { + /* Names that differ only by trailing underscores, which C keeps apart, each reaching its own + * Rust. */ + api_clash_Underscored underscored = {1, 2, 3, 4}; + api_clash_Change set = {.tag = API_CLASH_CHANGE_SET, .set = {5, 6}}; + if (api_clash_underscored(underscored, API_CLASH_OP_DELETE, set) != 2561234 || api_clash_erase_() != 2 || api_clash_erase() != 1) { + tr_fail("names apart by trailing underscores"); + } + /* A field named as errno.h's macro, escaped. */ api_clash_Errno none = api_clash_Errno_NULL(); if (none.errno_ != 0 || API_EOF != -1 || api_WEXITSTATUS(0x300) != 3) { diff --git a/ffi/tests/api.cpp b/ffi/tests/api.cpp index 06907b286..d8adae29b 100644 --- a/ffi/tests/api.cpp +++ b/ffi/tests/api.cpp @@ -72,6 +72,17 @@ unsigned long long ull(std::uint64_t v) { return static_cast(v); } +// An eraser whose methods differ only by a trailing underscore, which C++ escapes alike. +class Eraser final : public api::clash_Eraser { +public: + std::uint8_t delete_(std::uint8_t new_, std::uint8_t new__) const override { + return static_cast(new_ * 10 + new__); + } + std::uint8_t delete__() const override { + return 3; + } +}; + // The Log callback: keeps even levels. class Print final : public api::Log { public: @@ -579,6 +590,19 @@ int checks() { api::clash_Escaped escaped{3}; check(escaped.delete__() == 3 && escaped.delete_(1, 2) == 213, "methods C++ escapes alike stay apart"); } + // Names that differ only by trailing underscores, each reaching its own Rust: Rust's + // `new_` keeps its name and `new`, which C++ escapes alike, moves past it. + { + api::clash_Underscored underscored{1, 2, 3, 4}; + api::clash_Change set{api::clash_Change_Set{5, 6}}; + check(api::clash_underscored(underscored, api::clash_Op::delete__, set) == 2561234, "names apart by trailing underscores cross"); + auto [next, change] = api::clash_underscored_next(underscored, set); + const auto *swapped = std::get_if(&change); + check(next == api::clash_Underscored{2, 3, 4, 5} && swapped && swapped->new_ == 6 && swapped->new__ == 5, + "names apart by trailing underscores cross back"); + check(api::clash_erased(std::make_unique()) == 123, "a callback's methods apart by a trailing underscore"); + check(api::clash_erase_() == 2 && api::clash_erase() == 1, "functions apart by a trailing underscore"); + } // A name takes a copy of the caller's buffer, which is its own again after. { api::Name name = api::Name::owned("a"); diff --git a/ffi/tests/api.dart b/ffi/tests/api.dart index 853d162de..aba6b6d88 100644 --- a/ffi/tests/api.dart +++ b/ffi/tests/api.dart @@ -87,6 +87,15 @@ final class Print extends api.Log { void close() => print('freed'); } +/// An eraser whose methods differ only by a trailing underscore. +final class Eraser extends api.ClashEraser { + @override + int delete_(int new_, int new_2) => new_ * 10 + new_2; + + @override + int delete() => 3; +} + /// The Undo callback: each method returns its own digit. final class Edits extends api.Undo { @override @@ -456,6 +465,28 @@ void checks() { check(api.ClashLevel.debug_.index_() == 2 && api.ClashLevel.debug_.index == 1, 'a method named as an enum\'s index'); final tag = api.ClashTagPrivate(number: 3); check(tag.number == 3 && tag.number_() == 13, 'a method named as its variants\' field'); + // Names that differ only by trailing underscores, each reaching its own Rust: a name Dart + // spells as Rust does keeps it, whichever comes first. + final underscored = api.ClashUnderscored(new_: 1, new2_: 2, debug_: 3, default_: 4); + check( + api.clashUnderscored(underscored, api.ClashOp.delete, api.ClashChangeSet(new_: 5, new2_: 6)) == 2561234, + 'names apart by trailing underscores cross', + ); + check( + api.clashUnderscoredNext(underscored, api.ClashChangeSet(new_: 5, new2_: 6)) == + (api.ClashUnderscored(new_: 2, new2_: 3, debug_: 4, default_: 5), api.ClashChangeSet(new_: 6, new2_: 5)), + 'names apart by trailing underscores cross back', + ); + check(api.clashErased(Eraser()) == 123, 'a callback\'s methods apart by a trailing underscore'); + check( + api.ClashEscaped(new_: 3).delete() == 3 && api.ClashEscaped(new_: 3).delete_(1, 2) == 213, + 'methods apart by a trailing underscore', + ); + check(api.clashErase_() == 2 && api.clashErase() == 1, 'functions apart by a trailing underscore'); + // A named constructor keeps the name of an instance method, as Dart allows. + final opened = api.ClashStore.open(); + check(opened.open() == 7, 'a named constructor and a method named alike'); + opened.close(); print('checks ok'); } diff --git a/ffi/tests/api.go b/ffi/tests/api.go index 5c9770237..5cabd6349 100644 --- a/ffi/tests/api.go +++ b/ffi/tests/api.go @@ -444,6 +444,17 @@ func checks() { ok(reader.Close()) check(api.ClashWaited(source{}) == 4, "an interface's method named as io.ByteReader's") } + // Names that differ only by trailing underscores, each reaching its own Rust: a name Go + // spells as Rust does keeps it, whichever comes first. + { + underscored := api.ClashUnderscored{New_: 1, New: 2, Debug: 3, Default: 4} + check(api.ClashUnderscored_(underscored, api.ClashOpDelete, api.ClashChangeSet{New_: 5, New: 6}) == 2_561_234, "names apart by trailing underscores cross") + next, change := api.ClashUnderscoredNext(underscored, api.ClashChangeSet{New_: 5, New: 6}) + check(next == api.ClashUnderscored{New_: 2, New: 3, Debug: 4, Default: 5} && change == api.ClashChangeSet{New_: 6, New: 5}, "names apart by trailing underscores cross back") + check(api.ClashErased(eraser{}) == 123, "an interface's methods apart by a trailing underscore") + check(api.ClashEscaped{New: 3}.Delete() == 3 && api.ClashEscaped{New: 3}.Delete_(1, 2) == 213, "methods apart by a trailing underscore") + check(api.ClashErase_() == 2 && api.ClashErase() == 1, "functions apart by a trailing underscore") + } // A path that is no UTF-8 is a Go string all the same. check(api.Stray() == "\xff", "a path that is not UTF-8 crosses as its bytes") var lent string @@ -1488,7 +1499,17 @@ func broken(which string) { } } -// cancelLog cancels its context at each line, and counts them. +// eraser is a clash.Eraser, whose methods differ only by a trailing underscore. +type eraser struct{} + +func (eraser) Delete_(new_ uint8, new_2 uint8) uint8 { + return new_*10 + new_2 +} + +func (eraser) Delete() uint8 { + return 3 +} + // source is a clash.Source, reading 4 at once. type source struct{} @@ -1498,6 +1519,7 @@ func (source) ReadByte_() uint8 { return 4 } +// cancelLog cancels its context at each line, and counts them. type cancelLog struct { cancel context.CancelFunc lines atomic.Int32 diff --git a/ffi/tests/api.kt b/ffi/tests/api.kt index f679427d7..04163d465 100644 --- a/ffi/tests/api.kt +++ b/ffi/tests/api.kt @@ -356,6 +356,33 @@ fun checks() { override fun readByte(): UByte = 4u } check(clashWaited(source) == 4.toUByte() && waits == 1, "an interface's method named as java.lang.Object's") + // Names that differ only by trailing underscores, each reaching its own Rust: a name Kotlin + // spells as Rust does keeps it, whichever comes first. + val underscored = ClashUnderscored(new_ = 1u, new = 2u, debug = 3u, default = 4u) + check(clashUnderscored(underscored, ClashOp.DELETE, ClashChange.Set(new_ = 5u, new = 6u)) == 2_561_234u, "names apart by trailing underscores cross") + check( + clashUnderscoredNext(underscored, ClashChange.Set(new_ = 5u, new = 6u)) == + Pair(ClashUnderscored(new_ = 2u, new = 3u, debug = 4u, default = 5u), ClashChange.Set(new_ = 6u, new = 5u)), + "names apart by trailing underscores cross back", + ) + val eraser = object : ClashEraser { + override fun delete_(new2: UByte, new: UByte): UByte = (new2.toInt() * 10 + new.toInt()).toUByte() + + override fun delete(): UByte = 3u + } + check(clashErased(eraser) == 123u, "an interface's methods apart by a trailing underscore") + check(ClashEscaped(3u).delete() == 3.toUByte() && ClashEscaped(3u).delete_(1u, 2u) == 213.toUByte(), "methods apart by a trailing underscore") + check(clashErase_() == 2.toUByte() && clashErase() == 1.toUByte(), "functions apart by a trailing underscore") + // Rust's parameter `new` keeps `new`, wherever it is, so a named argument reaches it. + check(ClashEscaped(3u).delete_(new = 1u, new2 = 2u) == 213.toUByte(), "named arguments apart by a trailing underscore") + // A companion's function and an instance's method named alike, each in its own scope. + ClashStore.new(5u).use { store -> + check(store.count() == 5u && ClashStore.count() == 7u, "a static function and a method named alike") + } + // On the JVM, the method `open` keeps its name, and the static `open_` takes `open_`. + ClashStore.open().use { store -> + check(store.open() == 7u, "a static constructor and a method named alike") + } // A record holding a value past a word crosses as its words, in and out, and a call // with no slots left for one passes it encoded. diff --git a/ffi/tests/api.py b/ffi/tests/api.py index 89ed12a29..b50d2c99c 100644 --- a/ffi/tests/api.py +++ b/ffi/tests/api.py @@ -42,6 +42,16 @@ def close(self): print("freed") +class Eraser(api.ClashEraser): + """An eraser whose methods differ only by a trailing underscore.""" + + def delete_(self, new_, new): + return new_ * 10 + new + + def delete(self): + return 3 + + class Edits(api.Undo): """The Undo callback: each method returns its own digit.""" @@ -1139,6 +1149,19 @@ def raises(error, f, what): check(os.fsencode(path) == b"\xff", "a path that is not UTF-8 keeps its bytes") check(api.parents([path, os.fsdecode(b"\xfe/\xff")])[1] == os.fsdecode(b"\xfe"), "and crosses back") check(bytes(api.Clash.String("hi").bytes()) == b"hi", "a method named as a builtin runs") + # Names that differ only by trailing underscores, each reaching its own Rust: a name Python + # spells as Rust does keeps it, whichever comes first. + underscored = api.ClashUnderscored(new_=1, new=2, debug=3, default_=4) + check(api.clash_underscored(underscored, api.ClashOp.DELETE, api.ClashChange.Set(new_=5, new=6)) == 2_561_234, "names apart by trailing underscores cross") + check( + api.clash_underscored_next(underscored, api.ClashChange.Set(new_=5, new=6)) + == (api.ClashUnderscored(new_=2, new=3, debug=4, default_=5), api.ClashChange.Set(new_=6, new=5)), + "names apart by trailing underscores cross back", + ) + check(api.clash_erased(Eraser()) == 123, "a callback's methods apart by a trailing underscore") + check(api.ClashEscaped(new=3).delete() == 3 and api.ClashEscaped(new=3).delete_(1, 2) == 213, "methods apart by a trailing underscore") + check(api.clash_erase_() == 2 and api.clash_erase() == 1, "functions apart by a trailing underscore") + check(api.ClashStore.open_().open() == 7, "a static function and a method apart by a trailing underscore") print("values ok") @@ -1344,15 +1367,17 @@ class Tagged(api.Weighted): # `import *` reaches every export: a `pub fn _deprecated` too, which takes a trailing `_` # beside the module's own `_deprecated`, as `pub fn __all__` does beside the name Python - # reserves, and each constant `__getattr__` makes; and no import: what the module binds - # without a leading `_` but its `__future__` import. + # reserves, past `pub fn __all___`, which keeps its own, and each constant `__getattr__` + # makes; and no import: what the module binds without a leading `_` but its `__future__` + # import. star = {} exec("from api import *", star) del star["__builtins__"] check(star["_deprecated_"](1) == 2, "a pub fn named with a leading underscore") - check(star["__all___"](1) == 3, "a pub fn named as a name Python reserves") + check(star["__all____"](1) == 3, "a pub fn named as a name Python reserves") + check(star["__all___"](1) == 4, "a pub fn named as the one Python reserves would take") public = {name for name in vars(api) if not name.startswith("_")} - {"annotations"} - expected = public | {"_deprecated_", "__all___"} | set(api._consts) + expected = public | {"_deprecated_", "__all___", "__all____"} | set(api._consts) check(set(star) == expected, f"import * reaches the exports: {sorted(set(star) ^ expected)}") print("idioms ok") diff --git a/ffi/tests/api.swift b/ffi/tests/api.swift index f426e644d..0b31c8bec 100644 --- a/ffi/tests/api.swift +++ b/ffi/tests/api.swift @@ -436,6 +436,13 @@ func f64Bits(_ floats: [Double]) -> [UInt64] { floats.map(\.bitPattern) } +/// An eraser whose methods differ only by a trailing underscore, which Swift keeps apart by +/// their labels. +struct Eraser: ClashEraser { + func delete(_ new2: UInt8, _ new: UInt8) -> UInt8 { new2 * 10 + new } + func delete() -> UInt8 { 3 } +} + /// What the transcript's script says only in Rust, or Swift alone has: its own types' /// conversions, the errors and checks it throws, and its protocols. func checks() { @@ -443,6 +450,29 @@ func checks() { check(ArrayU8x4([1, 2, 3]) == nil, "3 bytes are no [u8; 4]") check(advance(.init_(1)) == .init_(0) && advance(.init_(0)) == .done, "a variant named init crosses") check(ClashLevel.default() == .default_ && ClashLevel.debug.index() == 2, "a variant named as Default's member crosses") + // Names that differ only by trailing underscores, each reaching its own Rust: a name Swift + // spells as Rust does keeps it, whichever comes first. + let underscored = ClashUnderscored(new_: 1, new: 2, debug: 3, default: 4) + check(clashUnderscored(underscored, .delete, .set(new_: 5, new: 6)) == 2_561_234, "names apart by trailing underscores cross") + let next = clashUnderscoredNext(underscored, .set(new_: 5, new: 6)) + check( + next.0 == ClashUnderscored(new_: 2, new: 3, debug: 4, default: 5) && next.1 == ClashChange.set(new_: 6, new: 5), + "names apart by trailing underscores cross back" + ) + check(ClashOp.delete_ != ClashOp.delete, "values apart by a trailing underscore") + check(clashErased(Eraser()) == 123, "a protocol's methods apart by a trailing underscore") + check(ClashEscaped(new: 3).delete() == 3 && ClashEscaped(new: 3).delete(1, 2) == 213, "methods apart by a trailing underscore") + check(clashErase_() == 2 && clashErase() == 1, "functions apart by a trailing underscore") + // Fields named as `Display`'s and `Debug`'s members, which take a trailing `_`. + let described = ClashDescribed(description_: 1, debugDescription_: 2) + check(clashDescribed(described) == 12 && described.description == "12", "fields named as a trait's members") + // A static function and a method named alike. + check(ClashStore.count() == 7 && ClashStore.new(5).count() == 5, "a static function and a method named alike") + check(ClashStore.open().open() == 7, "a static constructor and a method named alike") + // Rust's `lend()` keeps its name beside the overload of `lend_` that leaves out `store`. + let lent = ClashStore.new(3) + check(clashLend() == 9 && clashLend_() == 0 && clashLend_(store: lent) == 4, "an overload apart from a function by a trailing underscore") + // Rust's seconds are a u64, past Int64's. let rustMax = try! RustDuration(secs: .max, nanos: 999_999_999) let past = RustDuration.seconds(UInt64(Int64.max) + 1) diff --git a/ffi/tests/api.ts b/ffi/tests/api.ts index 15df13e9f..00b3a96ec 100644 --- a/ffi/tests/api.ts +++ b/ffi/tests/api.ts @@ -19,6 +19,8 @@ import * as g from "./web/glue.ts"; import * as Batch from "./web/Batch.ts"; import * as Board from "./web/Board.ts"; import * as Channel from "./web/Channel.ts"; +import type { ClashEraser } from "./web/ClashEraser.ts"; +import * as ClashEscaped from "./web/ClashEscaped.ts"; import * as Counter from "./web/Counter.ts"; import * as Countdown from "./web/Countdown.ts"; import * as Digest from "./web/Digest.ts"; @@ -104,6 +106,16 @@ export class Print implements Log { } } +/** An eraser whose methods differ only by a trailing underscore. */ +class Eraser implements ClashEraser { + delete_(new_: number, new_2: number): number { + return new_ * 10 + new_2; + } + delete$(): number { + return 3; + } +} + /** The Undo callback: each method returns its own digit, as transcript.rs's does. */ export class Edits implements Undo { delete$(n: number): number { @@ -511,6 +523,18 @@ function checks(): void { const counters = api.counters(["x", "y"]); api.worth([counters[0]!], [counters[1]!]); for (const counter of counters) closed(() => Counter.get(counter), "Counter", "a counter moved in is closed"); + // Names that differ only by trailing underscores, each reaching its own Rust: a name + // TypeScript spells as Rust does keeps it, whichever comes first. + const underscored = { new2: 1, new: 2, debug: 3, default: 4 }; + check(api.clashUnderscored(underscored, "Delete", { tag: "Set", new2: 5, new: 6 }) === 2_561_234, "names apart by trailing underscores cross"); + const [next, change] = api.clashUnderscoredNext(underscored, { tag: "Set", new2: 5, new: 6 }); + check( + next.new2 === 2 && next.new === 3 && next.debug === 4 && next.default === 5 && change.tag === "Set" && change.new2 === 6 && change.new === 5, + "names apart by trailing underscores cross back", + ); + check(api.clashErased(new Eraser()) === 123, "a callback's methods apart by a trailing underscore"); + check(ClashEscaped.delete({ new: 3 }) === 3 && ClashEscaped.delete_({ new: 3 }, 1, 2) === 213, "methods apart by a trailing underscore"); + check(api.clashErase_() === 2 && api.clashErase() === 1, "functions apart by a trailing underscore"); print("checks ok"); } diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index fc95cb827..2f5007b05 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -4276,14 +4276,19 @@ fn lock() { ("Kotlin", "smoothStep", "smoothStep_"), ("Swift", "smoothStep", "smoothStep_"), ("Dart", "smoothStep", "smoothStep_"), - ("Python", "smooth_step", "smooth_step_"), - ("Go", "SmoothStep", "SmoothStep_"), ] { assert!( stderr.contains(&format!("its {language} name `{old}` is now `{new}`")), "missing member rename for {language}:\n{stderr}" ); } + // Python's and Go's cases spell `smooth_step` alone as its Rust, so it keeps its name. + for (language, old) in [("Python", "smooth_step"), ("Go", "SmoothStep")] { + assert!( + !stderr.contains(&format!("its {language} name `{old}` is now")), + "a {language} name spelled as its Rust moved:\n{stderr}" + ); + } assert!(!stderr.contains("its C name"), "a C name changed:\n{stderr}"); assert!(!dir.join("names/api.json").exists()); diff --git a/quest/m1/ffi-export/kotlin-jvm-mangled-names.md b/quest/m1/ffi-export/kotlin-jvm-mangled-names.md new file mode 100644 index 000000000..5119407a1 --- /dev/null +++ b/quest/m1/ffi-export/kotlin-jvm-mangled-names.md @@ -0,0 +1,30 @@ +# [M] Kotlin: Java calls a member Kotlin mangles by the JVM name the lock records + +## Goal + +Every generated Kotlin function and property that plain Java can call has the JVM name the +lock's `/ jvm` entry records, including those Kotlin mangles for an inline class, and one +Java cannot call records no JVM name, so the lock never holds a name the class lacks. + +## Plan + +Found by CodeRabbit on [kixel-ai/rust2#934](https://github.com/kixel-ai/rust2/pull/934#discussion_r4652081539). +Since [#919](https://github.com/kixel-ai/rust2/pull/919), `Gen::function` in +`ffi/src/kotlin.rs` writes the name it computes to the `/ jvm` lock entry and emits +`@JvmName` only where that name differs from the declared one. Kotlin mangles the JVM name of +a function taking an inline class (`UInt`, `ULong`, `UShort`, `UByte`, an opaque `value +class`) and of a class member returning one, so `ClashStore.count(): UInt` is +`count-pVg5ArA` on the JVM while the lock records `count`. A hyphenated name is not a Java +identifier, so Java cannot call any such member, and the lock's break check watches a name +that does not exist. + +Checked with kotlinc and javap on 2026-11-21: a top-level function returning `UInt` is not +mangled; a member is. `@JvmName` on a final member or a property getter pins the name +exactly, mangled or not, and Java calls it. `@JvmName` on a member of a `value class` is a +compile error, and such a member compiles to a static `name-hash(bits)`. + +Recommendation: emit `@JvmName` on every function and getter Kotlin would mangle, with the +name `Gen::jvm_named` gives it, so the lock's entry is the method's name and `Caller.java` +calls one, such as `ClashStore.count()`. A member of an opaque value class records no +`/ jvm` entry, as Java cannot call it. Rejected: recording no JVM name for every mangled +member, which keeps unsigned APIs out of Java's reach. diff --git a/quest/m1/ffi-export/trailing-underscore-names.md b/quest/m1/ffi-export/trailing-underscore-names.md deleted file mode 100644 index a122326c2..000000000 --- a/quest/m1/ffi-export/trailing-underscore-names.md +++ /dev/null @@ -1,29 +0,0 @@ -# [M] Names that differ by trailing underscores export in every binding - -## Goal - -A crate whose names in one scope differ only by trailing underscores, such as fields `new` -and `new_`, methods `delete` and `delete_`, or variants `Delete` and `Delete_`, exports in -every language: each binding names them apart, as C and C++ do, rather than refusing the -whole export. - -## Plan - -Decided with the maintainer on 2026-11-19, in the pick of [#914](https://github.com/kixel-ai/rust2/pull/914): ✅ kept, giving every language C++'s order-independent rule (rejected: dropping it). - -Found by [cpp-name-collisions](https://github.com/kixel-ai/rust2/pull/914), whose fixture -could not carry its pairs: each of these refused the api fixture's export with "two -members of ... are both ... which rust2-ffi should keep apart", with no span. - -- Kotlin: record fields `new`/`new_` and a callback's methods `delete`/`delete_` - (camel case drops the `_`). -- Swift: plain enum variants `Delete`/`Delete_`. -- Go: a data enum payload's fields `new`/`new_`. -- Python: a field `default` beside `Default`'s `default`. -- Dart: a field `debug` beside `Debug`'s `debug`. - -Recommended: give each its own language's rule the way C++'s `named` does in -`ffi/src/cpp.rs` (a name its language spells as Rust does keeps it, and the rest take a -suffix until free, so order never renames one), then add the pairs to the api fixture's -`clash` module with a call per language. The refusal that stays as a backstop names the -second item's span.