diff --git a/ffi/Cargo.lock b/ffi/Cargo.lock index 775590a36..9a9793b70 100644 --- a/ffi/Cargo.lock +++ b/ffi/Cargo.lock @@ -161,6 +161,10 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "edge-fixture" +version = "0.0.0" + [[package]] name = "either" version = "1.19.0" diff --git a/ffi/README.md b/ffi/README.md index ee77272e2..c263b56c5 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -1244,15 +1244,19 @@ the library's own URI, mapped to the library by a build hook or by `--native-ass - **Names** are the C names without the prefix: a type in Pascal case and a member in camel case, so `moq_track_Producer` is `TrackProducer`, and its method - `moq_track_Producer_append_group` is `TrackProducer.appendGroup`, and a constant in - upper case (`LIMIT`). A function of a type + `moq_track_Producer_append_group` is `TrackProducer.appendGroup`, and a constant too + (`limit`), as Dart's lints name one. A function of a type that returns it is a constructor, which may share its name with a field: an object's `new` is its unnamed one (`Counter('c', 1)`), and any other a named one (`Position.group`). A type's other functions are static members. Two types whose - names would match are kept apart as Kotlin's are (`TokioConnect_Error`). A reserved word takes - a trailing `_` (`Point.default_()`), and names that clash, such as one the runtime - declares or a data enum's variant class, are kept apart as Kotlin's are. The glue's C - names are `_dart_`, with a `_` more for each C name of the export already there. + 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, + 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 + `package:lints/core.yaml`, the lints pub.dev scores a package with ([`tests/dart_lints.yaml`](tests/dart_lints.yaml)), + and no `ignore_for_file`. - **Objects** are final classes owning their handle. Of a checked type, `close()` drops the value through Rust's own `_drop`, as Rust's `drop` would, and frees the handle in the same crossing, and a `close()` while a call borrows the value, from a closure that diff --git a/ffi/fixtures/edge/Cargo.toml b/ffi/fixtures/edge/Cargo.toml new file mode 100644 index 000000000..e1c40dc36 --- /dev/null +++ b/ffi/fixtures/edge/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "edge-fixture" +description = "A small API, whose generated Dart has no use for most of its runtime" +version = "0.0.0" +edition = "2024" +license = "MIT OR Apache-2.0" +publish = false + +[lib] +name = "edge" + +[lints] +workspace = true diff --git a/ffi/fixtures/edge/src/lib.rs b/ffi/fixtures/edge/src/lib.rs new file mode 100644 index 000000000..56b3db939 --- /dev/null +++ b/ffi/fixtures/edge/src/lib.rs @@ -0,0 +1,20 @@ +//! A small API of shapes whose Dart leaves part of the generator's output unused, each of which +//! Dart's analyzer would report once nothing refers to it. + +/// An array taken and never returned, so Dart never reads one. +pub fn sum(bytes: [u8; 32]) -> u32 { + bytes.iter().map(|b| u32::from(*b)).sum() +} + +/// An array returned and never taken, so Dart never writes one. +pub fn zeros() -> [u8; 4] { + [0; 4] +} + +/// A record only on one target, whose only items are the checks of its derived `Debug`: the +/// target check is no function's. +#[cfg(target_arch = "wasm32")] +#[derive(Debug)] +pub struct Wasm { + pub n: u32, +} diff --git a/ffi/justfile b/ffi/justfile index 847e0ba52..59c13263c 100644 --- a/ffi/justfile +++ b/ffi/justfile @@ -429,6 +429,12 @@ dart-program dir main: printf '{"configVersion": 2, "packages": [{"name": "moq", "rootUri": "file://%s/dart/", "packageUri": "./"}]}\n' "$out" > "$dir/.dart_tool/package_config.json" printf 'format-version: [1, 0, 0]\nnative-assets:\n %s_%s:\n "package:moq/moq.dart": [absolute, "%s"]\n' "{{ os() }}" "$arch" "$out/target/release/$lib" > "$dir/native_assets.yaml" dart analyze --fatal-infos "$dir" + # pub.dev scores the library with the lints in tests/dart_lints.yaml, which the analyzer reads from the directory it analyzes. + rm -rf "$dir-lint" + mkdir "$dir-lint" + cp "$out"/dart/*.dart "$dir-lint" + cp tests/dart_lints.yaml "$dir-lint/analysis_options.yaml" + dart analyze --fatal-infos "$dir-lint" sdk=$(dirname "$(dirname "$(realpath "$(command -v dart)")")") "$sdk/bin/dartaotruntime" "$sdk/bin/snapshots/gen_kernel_aot.dart.snapshot" --platform "$sdk/lib/_internal/vm_platform_strong.dill" \ --packages "$dir/.dart_tool/package_config.json" --native-assets "$dir/native_assets.yaml" -o "$dir/main.dill" "$dir/main.dart" diff --git a/ffi/moq/bench/export.dart b/ffi/moq/bench/export.dart index d6f7dab94..4c8a584d7 100644 --- a/ffi/moq/bench/export.dart +++ b/ffi/moq/bench/export.dart @@ -125,7 +125,7 @@ Future throughput(moq.TrackProducer track, moq.TrackSubscriber subscriber, Future> round() async { final out = {}; final broadcast = moq.BroadcastInfo().produce(); - final track = broadcast.createTrack('bench', moq.TrackInfo.default_().withTimescale(moq.Timescale.MICRO)); + final track = broadcast.createTrack('bench', moq.TrackInfo.default_().withTimescale(moq.Timescale.micro)); final frame = Uint8List(100); micros = 0; diff --git a/ffi/moq/moq.dart b/ffi/moq/moq.dart index a2b1c7023..602051b6f 100644 --- a/ffi/moq/moq.dart +++ b/ffi/moq/moq.dart @@ -241,7 +241,7 @@ Future catalog() async { // a JSON document, and a section Dart parses from text, set in the lent catalog and read // back as text. final status = producer.jsonSnapshotConfig( - publisher.createTrack('status', moq.TrackInfo.default_().withTimescale(moq.Timescale.MILLI)), + publisher.createTrack('status', moq.TrackInfo.default_().withTimescale(moq.Timescale.milli)), moq.MuxJsonConfig.default_(), moq.MuxJsonOptions.default_(), ); @@ -310,7 +310,7 @@ void config() { client.close(); url.close(); // A `Vec`, as a list. - expect(moq.ALPNS.isNotEmpty, 'a constant slice crosses as a list'); + expect(moq.alpns.isNotEmpty, 'a constant slice crosses as a list'); final alpns = versions.alpns(); expect(alpns.isNotEmpty && alpns.every((a) => a.isNotEmpty), 'each version has an ALPN'); versions.close(); diff --git a/ffi/runtime/rt.dart b/ffi/runtime/rt.dart index bc3465589..e0810726e 100644 --- a/ffi/runtime/rt.dart +++ b/ffi/runtime/rt.dart @@ -102,11 +102,13 @@ final class RustDuration implements Comparable { @override String toString() => '${secs.toRadixString(10)}.${nanos.toString().padLeft(9, '0')}s'; + // ignore: unused_element void _put(_Duration c) { c.secs = secs.bits; c.nanos = nanos; } + // ignore: unused_element static RustDuration _of(_Duration c) => RustDuration._(U64.fromBits(c.secs), c.nanos); } @@ -122,6 +124,7 @@ final class PathBuf { /// byte or, on Windows, they are not WTF-8. PathBuf.fromBytes(List bytes) : _bytes = _osPath(bytes); + // ignore: unused_element PathBuf._(this._bytes); /// Its bytes, which never change. @@ -167,6 +170,7 @@ sealed class IpAddr { @override String toString() => toInternetAddress().address; + // ignore: unused_element static void _put(_IpAddr c, IpAddr v) { switch (v) { case Ipv4Addr(): @@ -178,6 +182,7 @@ sealed class IpAddr { } } + // ignore: unused_element static IpAddr _of(_IpAddr c) => c.v6 ? Ipv6Addr._of(c.ip.v6) : Ipv4Addr._of(c.ip.v4); } @@ -303,6 +308,7 @@ sealed class SocketAddr { IpAddr get ip; int get port; + // ignore: unused_element static void _put(_SocketAddr c, SocketAddr v) { switch (v) { case SocketAddrV4(): @@ -314,6 +320,7 @@ sealed class SocketAddr { } } + // ignore: unused_element static SocketAddr _of(_SocketAddr c) => c.v6 ? SocketAddrV6._of(c.addr.v6) : SocketAddrV4._of(c.addr.v4); } @@ -387,10 +394,10 @@ final class SocketAddrV6 extends SocketAddr { ip._put(c.ip); c.port = port; c.flowinfo = flowinfo; - c.scope_id = scopeId; + c.scopeId = scopeId; } - static SocketAddrV6 _of(_SocketAddrV6 c) => SocketAddrV6._(Ipv6Addr._of(c.ip), c.port, c.flowinfo, c.scope_id); + static SocketAddrV6 _of(_SocketAddrV6 c) => SocketAddrV6._(Ipv6Addr._of(c.ip), c.port, c.flowinfo, c.scopeId); } /// A copy of `bytes`, throwing an [ArgumentError] where one is not a byte or, on Windows, @@ -484,6 +491,7 @@ extension type Cancelable._(Future _future) implements Future { /// The future of `call`, whose start left the future in Rust that pended: polled again /// here with a waker, which its first poll had no use for. +// ignore: unused_element Cancelable _call(_Call call) { final future = call._done.future; _n.calls[future] = call; @@ -534,6 +542,7 @@ final class _Call { } /// Complete it with what Rust returned, from its poll. + // ignore: unused_element void _ready(T value) => _done.complete(value); /// Complete it with the error Rust returned, from its poll. @@ -618,7 +627,7 @@ final class _SocketAddrV6 extends ffi.Struct { @ffi.Uint32() external int flowinfo; @ffi.Uint32() - external int scope_id; + external int scopeId; } final class _Socket extends ffi.Union { @@ -802,6 +811,7 @@ abstract base class _Object implements ffi.Finalizable { /// The garbage collector's hold of an owned one's handle, from when the nursery pushed it /// out until freed. + // ignore: unused_field ffi.Pointer _own = ffi.nullptr; /// Its slot in the nursery while there, else -1. @@ -829,6 +839,7 @@ abstract base class _Object implements ffi.Finalizable { } /// The handle for a leaf call, which needs no hold: no Dart runs to close it meanwhile. + // ignore: unused_element ffi.Pointer get _live { if (_closed) throw StateError('$_type is closed'); return _raw; diff --git a/ffi/src/dart.rs b/ffi/src/dart.rs index 81674956e..825a412fd 100644 --- a/ffi/src/dart.rs +++ b/ffi/src/dart.rs @@ -70,7 +70,7 @@ pub(crate) fn generate(abi: &Abi<'_>, packages: &str, contract: u64) -> Result, packages: &str, contract: u64) -> Result, packages: &str, contract: u64) -> Result 0 + }; + let on_fn = match checks { + true => format!( + "/// The index of the library's target among those this file serves.\n\ + final int _target = {target_fn}();\n\n\ + /// Throws unless the library's target is among those of [on], as the item [what] is.\n\ + void _on(int on, String what) {{\n\tif ((on >>> _target) & 1 == 0) {{\n\t\tthrow UnsupportedError(\"$what: it is not on this library's target\");\n\t}}\n}}\n\n" + ), + false => String::new(), + }; let mut dart = format!( "// Generated by rust2-ffi: Dart over the C ABI of the pub API of {packages}. Do not edit.\n\ - // ignore_for_file: type=lint, unused_element, unused_field, deprecated_member_use_from_same_package\n\n\ + \n\ import 'dart:async' as dasync;\n\ import 'dart:convert' as convert;\n\ import 'dart:ffi' as ffi;\n\ @@ -125,13 +151,11 @@ pub(crate) fn generate(abi: &Abi<'_>, packages: &str, contract: u64) -> Result _{p}_contract() == 0x{contract:016x};\n\n\ - /// The index of the library's target among those this file serves.\n\ - final int _target = _{p}_target();\n\n\ - /// Throws unless the library's target is among those of [on], as the item [what] is.\n\ - void _on(int on, String what) {{\n\tif ((on >>> _target) & 1 == 0) {{\n\t\tthrow UnsupportedError(\"$what: it is not on this library's target\");\n\t}}\n}}\n\n\ + bool _contract() => {contract_fn}() == 0x{contract:016x};\n\n\ + {on_fn}\ /// Throws unless [status], which the call [what] wrote, is zero: a run-time check failed.\n\ - void _status(int status, String what) {{\n\tif (status == 0) return;\n\t_n.status.value = 0;\n\tfinal m = _statusMessage(status);\n\tvar n = 0;\n\twhile (m[n] != 0) n++;\n\tthrow StateError('$what: ${{const convert.Utf8Decoder().convert(m.asTypedList(n))}}');\n}}\n\n" + // ignore: unused_element\n\ + void _status(int status, String what) {{\n\tif (status == 0) return;\n\t_n.status.value = 0;\n\tfinal m = _statusMessage(status);\n\tvar n = 0;\n\twhile (m[n] != 0) {{\n\t\tn++;\n\t}}\n\tthrow StateError('$what: ${{const convert.Utf8Decoder().convert(m.asTypedList(n))}}');\n}}\n\n" ); for (name, params, ret, dart_params, dart_ret) in [ ("contract", "", "ffi.Uint64", "", "int"), @@ -261,8 +285,11 @@ pub(crate) fn generate(abi: &Abi<'_>, packages: &str, contract: u64) -> Result format!("_{p}_{name}"), + "contract" | "target" => private(&format!("{p}_{name}")), "buf_free" => "_bufFree".to_string(), "buf_copy" => "_bufCopy".to_string(), "status_message" => "_statusMessage".to_string(), @@ -465,6 +492,15 @@ struct Gen<'a> { relays: Vec, /// Each closure type, whose trampoline is `_t`. trampolines: Vec, + /// Each object class's `_` constructor, with the native that frees what it builds, and its + /// `_lent` one, which go if nothing calls them. + constructors: BTreeMap, + /// The callbacks whose tables are written, which only one given to Rust has. + tabled: BTreeSet, + /// Each array class's `_of` and `_write`, which go if nothing reads or writes the class. + arrays: BTreeMap, + /// The array classes written into Rust. + written: BTreeSet, fresh: usize, /// The targets of the item being written, whose calls check theirs. on: On, @@ -493,7 +529,11 @@ impl<'a> Gen<'a> { /// The top-level Dart name `what` takes, `name` unless that is taken. fn claim(&mut self, name: &str, what: String) -> String { - abi::claim(&mut self.names, |name| TAKEN.contains(&name), name, what) + let free = alternatives(name) + .find(|alt| !(TAKEN.contains(&alt.as_str()) || self.names.contains_key(alt))) + .expect("alternatives never end"); + self.names.insert(free.clone(), what); + free } /// The class of the variant `variant` of the data enum Dart names `name`. @@ -502,7 +542,7 @@ impl<'a> Gen<'a> { } /// The class of each variant of a data enum, by the enum's Dart name and the variant's: - /// `{enum}{variant}`, [`abi::unique`] among them and apart from every other top-level + /// `{enum}{variant}`, [`unique`] among them and apart from every other top-level /// name the runtime or a type takes. fn variants(&self, taken: &dyn Fn(&str) -> bool) -> HashMap<(String, String), String> { let api = self.abi.api; @@ -516,8 +556,11 @@ impl<'a> Gen<'a> { } keys.sort(); let types: BTreeSet = (self.classes.keys()).map(|c| self.class(c)).collect(); - let names = keys.iter().map(|(name, variant)| format!("{name}{variant}")).collect(); - let names = abi::unique(names, |name| taken(name) || types.contains(name)); + let names = keys + .iter() + .map(|(name, variant)| format!("{name}{}", variant.replace('_', ""))) + .collect(); + let names = unique(names, |name| taken(name) || types.contains(name)); keys.into_iter().zip(names).collect() } @@ -537,6 +580,47 @@ impl<'a> Gen<'a> { } } + /// Drops the constructors of the object classes that nothing calls: a type only ever lent + /// to a callback has no `_`, and one only ever returned has no `_lent`, which Dart's + /// analyzer would report as unused. + fn unconstructed(&mut self) { + let code: String = [&self.types, &self.top] + .into_iter() + .chain(self.helpers.values()) + .chain(self.structs.values()) + .map(String::as_str) + .collect(); + let calls = |name: &str, ctor: &str| calls(&code, &format!("{name}.{ctor}(")); + for (name, (of, write)) in std::mem::take(&mut self.arrays) { + if calls(&name, "_of") == 0 { + self.types = self.types.replace(&of, ""); + } + if !self.written.contains(&name) { + self.types = self.types.replace(&write, ""); + } + } + for (name, (owned, lent, freeing)) in std::mem::take(&mut self.constructors) { + // Each declares itself once. + let owned_unused = calls(&name, "_") == 1; + let lent_unused = calls(&name, "_lent") == 1; + if owned_unused { + self.types = self.types.replace(&owned, ""); + self.natives.retain(|_, decl| !decl.contains(&format!(" {freeing}("))); + } + // A class nothing makes, an object only ever passed to Rust, keeps one constructor, as + // Dart's implicit one would call `_Object()`, which takes arguments. + if lent_unused { + let kept = match owned_unused { + true => format!( + "\t// The class's only constructor, which no Dart code calls.\n\t// ignore: unused_element\n{lent}" + ), + false => String::new(), + }; + self.types = self.types.replace(&lent, &kept); + } + } + } + /// The Dart type of `ty`, as a value, a parameter, or a result. fn dt(&mut self, ty: &Type) -> String { let abi = self.abi; @@ -664,7 +748,7 @@ impl<'a> Gen<'a> { if (0..abi.api.callbacks.len()).any(|i| abi.callback(i) == name) { return "_Callback".to_string(); } - let class = format!("_{name}"); + let class = private_type(&name); if self.structs.contains_key(&name) { return class; } @@ -704,7 +788,7 @@ impl<'a> Gen<'a> { fields.push(("value".into(), abi.ty(inner))); } else if let Some(elements) = abi.tuples.get(&name) { for (n, element) in elements.iter().enumerate() { - fields.push((format!("_{n}"), abi.ty(element))); + fields.push((format!("${n}"), abi.ty(element))); } } else if let Some(i) = (0..abi.api.records.len()).find(|&i| abi.record(i) == name) { if let Some(opaque) = &abi.api.records[i].opaque { @@ -722,10 +806,10 @@ impl<'a> Gen<'a> { } else if let Some(i) = (0..abi.api.enums.len()).find(|&i| abi.enumeration(i) == name) { let e = &abi.api.enums[i]; let mut extra = String::new(); - let union = format!("_{name}_u"); + let union = private_type(&format!("{name}_u")); let mut members = Vec::new(); for variant in e.variants.iter().filter(|v| !v.fields.is_empty()) { - let payload = abi::payload(&name, &variant.name); + let payload_class = private_type(&abi::payload(&name, &variant.name)); let mut decls = Vec::new(); for field in &variant.fields { let ty = abi.ty(&field.ty); @@ -733,12 +817,12 @@ impl<'a> Gen<'a> { } let _ = write!( extra, - "final class _{payload} extends ffi.Struct {{\n{}}}\n\n", + "final class {payload_class} extends ffi.Struct {{\n{}}}\n\n", decls.concat() ); members.push(format!( - "\texternal _{payload} ${};\n", - abi::escape(&abi::snake(&variant.name)) + "\texternal {payload_class} {};\n", + slot(&abi::escape(&abi::snake(&variant.name))) )); } let _ = write!( @@ -778,8 +862,8 @@ impl<'a> Gen<'a> { _ => None, }; match annotation { - Some(a) => format!("\t@{a}()\n\texternal {} ${name};\n", self.ct(ty)), - None => format!("\texternal {} ${name};\n", self.nt(ty)), + Some(a) => format!("\t@{a}()\n\texternal {} {};\n", self.ct(ty), slot(name)), + None => format!("\texternal {} {};\n", self.nt(ty), slot(name)), } } @@ -791,7 +875,7 @@ impl<'a> Gen<'a> { /// The `@Native` binding of `sig`'s C function as the Dart function `_`, declared /// once, as a leaf call if `leaf`. fn declare(&mut self, name: &str, sig: &Sig, leaf: bool) -> String { - let local = format!("_{name}"); + let local = private(name); if !self.natives.contains_key(name) { let natives: Vec = sig.params.iter().map(|(_, ty)| self.nt(ty)).collect(); let darts: Vec = (sig.params.iter().enumerate()) @@ -817,7 +901,7 @@ impl<'a> Gen<'a> { fn served(&mut self, call: &Sig) -> String { let name = format!("{}_serve_{}", self.space, self.bare(&call.name)); if self.natives.contains_key(&name) { - return format!("_{name}"); + return private(&name); } let mut params = vec![Ty::Data]; params.extend(call.params.iter().map(|(_, ty)| ty.clone())); @@ -873,7 +957,7 @@ impl<'a> Gen<'a> { return native; } // On a target its item is not on, the call throws before it calls in. - let checked = format!("{native}_on"); + let checked = format!("{native}$on"); if !self.natives.contains_key(&checked) { let decl = self.natives[name].replacen(&format!("{native}("), &format!("{checked}("), 1); let params: Vec = (0..params).map(|n| format!("p{n}")).collect(); @@ -902,6 +986,7 @@ impl<'a> Gen<'a> { let bare = self.bare(c); let space = &self.space; let own = format!("{space}_own_{bare}"); + let own_ = private(&own); let raw = rs(handle); let _ = write!( self.glue, @@ -910,17 +995,19 @@ impl<'a> Gen<'a> { self.natives.insert( own.clone(), format!( - "@ffi.Native Function(ffi.Handle, ffi.Pointer)>(symbol: '{own}')\nexternal ffi.Pointer _{own}(Object p0, ffi.Pointer p1);\n\n" + "@ffi.Native Function(ffi.Handle, ffi.Pointer)>(symbol: '{own}')\nexternal ffi.Pointer {own_}(Object p0, ffi.Pointer p1);\n\n" ), ); let freeing = format!("{space}_freeing_{bare}"); + let freeing_ = private(&freeing); self.natives.insert( freeing.clone(), format!( - "@ffi.Native)>(symbol: '{c}_free')\nexternal void _{freeing}(ffi.Pointer p0);\n\n" + "@ffi.Native)>(symbol: '{c}_free')\nexternal void {freeing_}(ffi.Pointer p0);\n\n" ), ); let free = format!("{space}_free_{bare}"); + let free_ = private(&free); let _ = write!( self.glue, "#[unsafe(no_mangle)]\npub unsafe extern \"C\" fn {free}(home: *const c_void, own: *mut c_void, object: *mut c_void, raw: {raw}) {{\n\tif !own.is_null() {{\n\t\tunsafe {{ runtime::disown(own, object) }};\n\t}}\n\tlet home = unsafe {{ &*home.cast::() }};\n\tunsafe {{ home.serve(move || crate::{c}_free(raw)) }}\n}}\n\n" @@ -928,11 +1015,12 @@ impl<'a> Gen<'a> { self.natives.insert( free.clone(), format!( - "@ffi.Native, ffi.Pointer, ffi.Handle, ffi.Pointer)>(symbol: '{free}')\nexternal void _{free}(ffi.Pointer p0, ffi.Pointer p1, Object p2, ffi.Pointer p3);\n\n" + "@ffi.Native, ffi.Pointer, ffi.Handle, ffi.Pointer)>(symbol: '{free}')\nexternal void {free_}(ffi.Pointer p0, ffi.Pointer p1, Object p2, ffi.Pointer p3);\n\n" ), ); let close = checked.then(|| { let close = format!("{space}_close_{bare}"); + let close_ = private(&close); // The status stays the call's own while the isolate serves others meanwhile, as a // served call's does. let _ = write!( @@ -942,15 +1030,15 @@ impl<'a> Gen<'a> { self.natives.insert( close.clone(), format!( - "@ffi.Native, ffi.Pointer, ffi.Handle, ffi.Pointer, ffi.Bool, ffi.Pointer)>(symbol: '{close}')\nexternal void _{close}(ffi.Pointer p0, ffi.Pointer p1, Object p2, ffi.Pointer p3, bool p4, ffi.Pointer p5);\n\n" + "@ffi.Native, ffi.Pointer, ffi.Handle, ffi.Pointer, ffi.Bool, ffi.Pointer)>(symbol: '{close}')\nexternal void {close_}(ffi.Pointer p0, ffi.Pointer p1, Object p2, ffi.Pointer p3, bool p4, ffi.Pointer p5);\n\n" ), ); - format!("_{close}") + close_ }); Owned { - own: format!("_{own}"), - freeing: format!("_{freeing}"), - free: format!("_{free}"), + own: own_, + freeing: freeing_, + free: free_, close, } } @@ -1017,7 +1105,10 @@ impl<'a> Gen<'a> { Type::Slice | Type::Vec | Type::Bytes => format!("a_.bytes({dst}, {e}, {take});"), Type::U128 => format!("_n.u128({dst}, {e});"), Type::Duration => format!("{e}._put({dst});"), - Type::Array(_) => format!("{e}._write({dst});"), + Type::Array(n) => { + self.written.insert(Abi::array_class(*n)); + format!("{e}._write({dst});") + } // The sealed class of either family writes which it is, and each family itself. Type::SocketAddr(Family::Any) => format!("SocketAddr._put({dst}, {e});"), Type::IpAddr(Family::Any) => format!("IpAddr._put({dst}, {e});"), @@ -1065,12 +1156,12 @@ impl<'a> Gen<'a> { if let Some(name) = self.writers.get(ty) { return name.clone(); } - let mut name = format!("_w_{c}"); + let mut name = format!("_w${}", mangle(c)); for k in 2.. { if !self.helpers.contains_key(&name) { break; } - name = format!("_w_{c}_{k}"); + name = format!("_w${}${k}", mangle(c)); } self.writers.insert(ty.clone(), name.clone()); self.helpers.insert(name.clone(), String::new()); @@ -1080,7 +1171,7 @@ impl<'a> Gen<'a> { let body = match ty { Type::Record(i) if abi.api.records[*i].opaque.is_some() => { let units = abi.api.records[*i].opaque.as_ref().map_or(0, |o| o.units()); - let lines: Vec = (0..units).map(|k| format!("c.$opaque[{k}] = v._{k};")).collect(); + let lines: Vec = (0..units).map(|k| format!("c.$opaque[{k}] = v._u{k};")).collect(); lines.join("\n\t") } Type::Record(i) => { @@ -1088,7 +1179,7 @@ impl<'a> Gen<'a> { let mut lines = Vec::new(); for field in &record.fields { let e = format!("v.{}", field_name(&field.name)); - let dst = format!("c.${}", abi::escape(&field.name)); + let dst = format!("c.{}", slot(&abi::escape(&field.name))); lines.push(self.write(&field.ty, &e, &dst, "t")); } lines.join("\n\t") @@ -1108,7 +1199,7 @@ impl<'a> Gen<'a> { let member = abi::escape(&abi::snake(&variant.name)); for field in &variant.fields { let e = format!("v.{}", field_name(&field.name)); - let dst = format!("c.$u.${member}.${}", abi::escape(&field.name)); + let dst = format!("c.$u.{}.{}", slot(&member), slot(&abi::escape(&field.name))); body.push(self.write(&field.ty, &e, &dst, "t")); } lines.push(format!( @@ -1148,7 +1239,7 @@ impl<'a> Gen<'a> { Type::Tuple(elements) => { let mut lines = Vec::new(); for (n, element) in elements.iter().enumerate() { - lines.push(self.write(element, &format!("v.${}", n + 1), &format!("c.$_{n}"), "t")); + lines.push(self.write(element, &format!("v.${}", n + 1), &format!("c.$${n}"), "t")); } lines.join("\n\t") } @@ -1192,12 +1283,12 @@ impl<'a> Gen<'a> { if let Some(name) = self.readers.get(ty) { return name.clone(); } - let mut name = format!("_r_{c}"); + let mut name = format!("_r${}", mangle(c)); for k in 2.. { if !self.helpers.contains_key(&name) { break; } - name = format!("_r_{c}_{k}"); + name = format!("_r${}${k}", mangle(c)); } self.readers.insert(ty.clone(), name.clone()); self.helpers.insert(name.clone(), String::new()); @@ -1215,7 +1306,7 @@ impl<'a> Gen<'a> { let record = &abi.api.records[*i]; let mut args = Vec::new(); for field in &record.fields { - let value = self.lift(&field.ty, &format!("c.${}", abi::escape(&field.name))); + 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)), @@ -1245,7 +1336,10 @@ impl<'a> Gen<'a> { let member = abi::escape(&abi::snake(&variant.name)); let mut args = Vec::new(); for field in &variant.fields { - let value = self.lift(&field.ty, &format!("c.$u.${member}.${}", abi::escape(&field.name))); + 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)), @@ -1297,7 +1391,7 @@ impl<'a> Gen<'a> { Type::Tuple(elements) => { let class = self.struct_class(&Ty::Struct(c.to_string())); let lifted: Vec = (elements.iter().enumerate()) - .map(|(n, e)| self.lift(e, &format!("c.$_{n}"))) + .map(|(n, e)| self.lift(e, &format!("c.$${n}"))) .collect(); let body = match lifted.len() { 1 => format!("({},)", lifted[0]), @@ -1422,13 +1516,20 @@ impl<'a> Gen<'a> { for (c, n) in &abi.arrays { let name = Abi::array_class(*n); let s = self.struct_class(&Ty::Struct(c.clone())); + let of = format!( + "{name}._(this._bytes);\n\n\tstatic {name} _of({s} c) => {name}._(typed.Uint8List.fromList([for (var i = 0; i < {n}; i++) c.items[i]]));\n\n\t" + ); + let write = format!( + "void _write({s} c) {{\n\t\tfor (var i = 0; i < {n}; i++) {{\n\t\t\tc.items[i] = _bytes[i];\n\t\t}}\n\t}}\n\n\t" + ); + self.arrays.insert(name.clone(), (of.clone(), write.clone())); let _ = write!( self.types, - "/// A Rust `[u8; {n}]`: exactly {n} bytes, copied in and out, so it never changes.\nfinal class {name} {{\n\tfinal typed.Uint8List _bytes;\n\n\t/// A copy of [bytes], which must hold exactly {n}, each from 0 through 255.\n\t{name}(List bytes) : _bytes = typed.Uint8List.fromList(bytes) {{\n\t\tif (bytes.length != {n} || bytes.any((b) => b < 0 || b > 255)) {{\n\t\t\tthrow ArgumentError.value(bytes, 'bytes', 'is no [u8; {n}]');\n\t\t}}\n\t}}\n\n\t{name}._(this._bytes);\n\n\tint operator [](int index) => _bytes[index];\n\n\ttyped.Uint8List toBytes() => typed.Uint8List.fromList(_bytes);\n\n\tstatic {name} _of({s} c) => {name}._(typed.Uint8List.fromList([for (var i = 0; i < {n}; i++) c.items[i]]));\n\n\tvoid _write({s} c) {{\n\t\tfor (var i = 0; i < {n}; i++) {{\n\t\t\tc.items[i] = _bytes[i];\n\t\t}}\n\t}}\n\n\t@override\n\tbool operator ==(Object other) => other is {name} && _equal(other._bytes);\n\n\tbool _equal(typed.Uint8List other) {{\n\t\tfor (var i = 0; i < {n}; i++) {{\n\t\t\tif (other[i] != _bytes[i]) return false;\n\t\t}}\n\t\treturn true;\n\t}}\n\n\t@override\n\tint get hashCode => Object.hashAll(_bytes);\n\n\t@override\n\tString toString() => _bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();\n}}\n\n" + "/// A Rust `[u8; {n}]`: exactly {n} bytes, copied in and out, so it never changes.\nfinal class {name} {{\n\tfinal typed.Uint8List _bytes;\n\n\t/// A copy of [bytes], which must hold exactly {n}, each from 0 through 255.\n\t{name}(List bytes) : _bytes = typed.Uint8List.fromList(bytes) {{\n\t\tif (bytes.length != {n} || bytes.any((b) => b < 0 || b > 255)) {{\n\t\t\tthrow ArgumentError.value(bytes, 'bytes', 'is no [u8; {n}]');\n\t\t}}\n\t}}\n\n\tint operator [](int index) => _bytes[index];\n\n\ttyped.Uint8List toBytes() => typed.Uint8List.fromList(_bytes);\n\n\t{of}{write}@override\n\tbool operator ==(Object other) => other is {name} && _equal(other._bytes);\n\n\tbool _equal(typed.Uint8List other) {{\n\t\tfor (var i = 0; i < {n}; i++) {{\n\t\t\tif (other[i] != _bytes[i]) return false;\n\t\t}}\n\t\treturn true;\n\t}}\n\n\t@override\n\tint get hashCode => Object.hashAll(_bytes);\n\n\t@override\n\tString toString() => _bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();\n}}\n\n" ); } for constant in &api.constants { - let name = abi::snake(self.bare(&abi.name(&constant.path))).to_uppercase(); + let name = member(&abi::snake(self.bare(&abi.name(&constant.path))), &[]); let name = self.claim(&name, format!("const `{}`", constant.path.join("::"))); self.locked .insert(format!("const {}", constant.path.join("::")), name.clone()); @@ -1745,7 +1846,7 @@ impl<'a> Gen<'a> { let ty = Type::Record(i); if let Some(opaque) = &record.opaque { // Its bytes, in the units of its C struct, each an `int` of the same bits. - let units: Vec = (0..opaque.units()).map(|k| format!("_{k}")).collect(); + let units: Vec = (0..opaque.units()).map(|k| format!("_u{k}")).collect(); let mut members = Vec::new(); let mut body = vec![format!( "\tconst {name}._({});\n\n{}", @@ -1787,7 +1888,7 @@ impl<'a> Gen<'a> { self.traits(&ty, &c, record.traits, &mut body, &mut members); self.methods(&record.methods, &Ty::Struct(c.clone()), &ty, &mut body, &mut members); self.check_members(&rust, &mut members); - let text = format!("{rust}\n\n{}", record.docs); + let text = format!("`{rust}`\n\n{}", record.docs); let _ = write!( self.types, "{}final class {name} {{\n{}}}\n\n", @@ -1812,7 +1913,7 @@ impl<'a> Gen<'a> { let ty = Type::Enum(i); let mut members = Vec::new(); let mut body = Vec::new(); - let text = format!("{rust}\n\n{}", e.docs); + let text = format!("`{rust}`\n\n{}", e.docs); if e.plain() { // A value of a variant the library's target lacks is refused as it crosses, when // its C value is read. @@ -1924,13 +2025,20 @@ impl<'a> Gen<'a> { None => String::new(), }; let close = format!("\t@override\n\tvoid _free() => {free}(_n.home, _own, this, _raw);\n{close}"); - let mut body = vec![format!( - "\t{name}._(ffi.Pointer raw) : super(raw, true, {checked}) {{\n\t\t_n.nursery.push(this, ffi.Native.addressOf)>>({freeing}).cast());\n\t}}\n\n\t{name}._lent(ffi.Pointer raw) : super(raw, false, {checked});\n\n\t@override\n\tString get _type => '{name}';\n\n\t@override\n\tvoid _register() => _own = {own}(this, _raw);\n\n{close}" - )]; + let owned_ctor = format!( + "\t{name}._(ffi.Pointer raw) : super(raw, true, {checked}) {{\n\t\t_n.nursery.push(this, ffi.Native.addressOf)>>({freeing}).cast());\n\t}}\n\n" + ); + let lent_ctor = format!("\t{name}._lent(ffi.Pointer raw) : super(raw, false, {checked});\n\n"); + let body = format!( + "{owned_ctor}{lent_ctor}\t@override\n\tString get _type => '{name}';\n\n\t@override\n\tvoid _register() => _own = {own}(this, _raw);\n\n{close}" + ); + self.constructors + .insert(name.clone(), (owned_ctor, lent_ctor, freeing.clone())); + let mut body = vec![body]; self.traits(&ty, &c, object.traits, &mut body, &mut members); self.methods(&object.methods, &owner, &ty, &mut body, &mut members); self.distinct(&rust, &members); - let text = format!("{rust}\n\n{}", object.docs); + let text = format!("`{rust}`\n\n{}", object.docs); let _ = write!( self.types, "{}final class {name} extends _Object {{\n{}}}\n\n", @@ -1948,8 +2056,6 @@ impl<'a> Gen<'a> { let rust = callback.path.join("::"); let mut body = Vec::new(); let mut members = Vec::new(); - let mut relays = Vec::new(); - let mut trampolines = 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 { @@ -1969,6 +2075,41 @@ impl<'a> Gen<'a> { self.dt(&method.ok), params.join(", ") )); + } + self.distinct(&rust, &members); + body.push( + "\t/// Called once Rust drops this implementation, to free what it holds: at once on the\n\t/// isolate's thread, or else from its event loop.\n\tvoid close() {}".to_string(), + ); + let text = format!( + "{rust}: implemented in Dart. Rust calls its methods on the isolate's thread: from\n\ + another, the call waits for the isolate's event loop to run it.\n\n{}", + callback.docs + ); + let _ = write!( + self.types, + "{}abstract class {name} {{\n{}\n}}\n\n", + docs(text.trim(), callback.deprecated.as_deref(), ""), + body.join("\n\n") + ); + } + + /// What Rust's calls into a callback `c` run: a trampoline per method on the isolate's + /// thread, the relay in the glue that reaches it, and the tables that hold both, which only + /// a callback given to Rust needs. + fn callback_tables(&mut self, c: &str) { + let abi = self.abi; + let i = (0..abi.api.callbacks.len()) + .find(|&i| abi.callback(i) == c) + .expect("a callback of that name"); + let callback = &abi.api.callbacks[i]; + let on = std::mem::replace(&mut self.on, callback.on); + let name = self.class(c); + 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); // 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); @@ -1977,7 +2118,7 @@ impl<'a> Gen<'a> { .collect(); let call = format!("(_n.lent[data.address] as {name}).{member}({})", lifted.join(", ")); let what = format!("{rust}::{}", method.name()); - let t = format!("_cb_{}_{}", self.bare(&c), method.name()); + let t = format!("_cb${}${}", mangle(self.bare(c)), mangle(method.name())); let body = match &method.ok { Type::Unit => format!("{call};"), ok => format!("return {};", self.lower(ok, &call)), @@ -1985,7 +2126,7 @@ impl<'a> Gen<'a> { let tramp = self.trampoline_fn(&t, &c_params, &ret, &body, &what, &[]); trampolines.push(tramp); // Its relay in the glue. - let relay = format!("{}_cb_{}_{}", self.space, self.bare(&c), method.name()); + let relay = format!("{}_cb_{}_{}", self.space, self.bare(c), method.name()); let mut fn_params = vec![Ty::Data]; fn_params.extend(c_params.iter().cloned()); let native = self.native_fn(&relay, fn_params.clone(), ret.clone()); @@ -2007,8 +2148,7 @@ impl<'a> Gen<'a> { m = method.name(), ); } - self.distinct(&rust, &members); - let tables = format!("_tables_{}", self.bare(&c)); + let tables = format!("_tables${}", mangle(self.bare(c))); self.helpers.insert( tables.clone(), format!( @@ -2017,20 +2157,7 @@ impl<'a> Gen<'a> { trampolines.join(",\n\t") ), ); - body.push( - "\t/// Called once Rust drops this implementation, to free what it holds: at once on the\n\t/// isolate's thread, or else from its event loop.\n\tvoid close() {}".to_string(), - ); - let text = format!( - "{rust}: implemented in Dart. Rust calls its methods on the isolate's thread: from\n\ - another, the call waits for the isolate's event loop to run it.\n\n{}", - callback.docs - ); - let _ = write!( - self.types, - "{}abstract class {name} {{\n{}\n}}\n\n", - docs(text.trim(), callback.deprecated.as_deref(), ""), - body.join("\n\n") - ); + self.on = on; } /// A static function `name` C calls with `data` and `c_params`, running `body`, which @@ -2190,7 +2317,7 @@ impl<'a> Gen<'a> { Type::String => format!("_n.copied({e})"), Type::Record(_) | Type::Option(_) => { let c = self.c_name(ty); - let name = format!("_ret_{c}"); + let name = format!("_ret${}", mangle(&c)); if !self.helpers.contains_key(&name) { let class = self.struct_class(&Ty::Struct(c.clone())); let w = self.writer(&c, ty); @@ -2261,11 +2388,7 @@ impl<'a> Gen<'a> { // 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); - // A constant in upper case, as Rust names it, apart from a method of its name. - let member = match function.access { - Access::Const => abi::snake(snake).to_uppercase(), - _ => member(snake, &reserved), - }; + 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 @@ -2343,7 +2466,13 @@ impl<'a> Gen<'a> { (_, Ty::ForeignReader) => args.push(format!("_n.reader(a_, {name})")), (Type::Callback(i, _), _) => { let cb = abi.callback(*i); - args.push(format!("_n.give(_tables_{}, {name}, {name}.close)", self.bare(&cb))); + if self.tabled.insert(cb.clone()) { + self.callback_tables(&cb); + } + args.push(format!( + "_n.give(_tables${}, {name}, {name}.close)", + mangle(self.bare(&cb)) + )); gave = true; } (Type::Waker, _) => { @@ -2403,13 +2532,9 @@ impl<'a> Gen<'a> { }; // Each call, and each poll and free of its future, serves the isolate while it waits. - let call_fn = match leaf { - true => self.leaf(&export.call), - false => { - args.insert(0, "_n.home".to_string()); - self.served(&export.call) - } - }; + if !leaf { + args.insert(0, "_n.home".to_string()); + } let mut body = Vec::new(); let ret_type; @@ -2427,7 +2552,7 @@ impl<'a> Gen<'a> { let mut stmts: Vec = Vec::new(); for (n, ty) in &poll_outs { stmts.push(self.out_decl(n, ty)); - poll_args.push(format!("o_{n}")); + poll_args.push(out_var(n)); } // A future that is not `Send` lives on a home, which polls it, so its check fails // only for one a callback made elsewhere. @@ -2463,8 +2588,8 @@ impl<'a> Gen<'a> { "case 2:\n\treturn Cancelable._(Future<{ok_dt}>.error({error}));" )); } - started.push("default:\n\tf_ = o_f_.value;".to_string()); - let poll_name = format!("_p_{c_name}"); + started.push("default:\n\tf_ = o$f_.value;".to_string()); + let poll_name = format!("_p${}", mangle(&c_name)); self.helpers.insert( poll_name.clone(), format!( @@ -2480,10 +2605,10 @@ impl<'a> Gen<'a> { let mut inner = pre.clone(); for (n, ty) in &poll_outs { inner.push(self.out_decl(n, ty)); - start_args.push(format!("o_{n}")); + start_args.push(out_var(n)); } - inner.push("final o_f_ = a_>();".to_string()); - start_args.push("o_f_".to_string()); + inner.push("final o$f_ = a_>();".to_string()); + start_args.push("o$f_".to_string()); let started = indent(&started.join("\n")); if status { start_args.push("s_".to_string()); @@ -2510,10 +2635,14 @@ impl<'a> Gen<'a> { inner.push(self.out_decl(n, ty)); } let mut call_args = args.clone(); - call_args.extend(outs.iter().map(|(n, _)| format!("o_{n}"))); + call_args.extend(outs.iter().map(|(n, _)| out_var(n))); if status { call_args.push("s_".to_string()); } + let call_fn = match leaf { + true => self.leaf(&export.call), + false => self.served(&export.call), + }; let call = format!("{call_fn}({})", call_args.join(", ")); // Rust took what it was given, even for a call its check refuses. let took = match gives { @@ -2622,7 +2751,10 @@ impl<'a> Gen<'a> { None => self.claim(&member, format!("fn `{}`", function.path.join("::"))), Some(_) => member, }; - // A member its type declares already, as a field of its name, takes a trailing `_`. + // A member its type declares already, as a field of its name, takes the next of its + // alternatives. + let mut alternatives = alternatives(&member); + alternatives.next(); let (head, member) = loop { let (head, entry) = match (function.access, receiver) { (Access::Field { set: false, .. }, Some(_)) @@ -2660,7 +2792,7 @@ impl<'a> Gen<'a> { if entry == "new " || !taken.iter().any(|other| collides(other, &entry)) { break (head, entry); } - member.push('_'); + member = alternatives.next().expect("alternatives never end"); }; crate::lock::function(&mut self.locked, function, &member); @@ -2678,15 +2810,15 @@ impl<'a> Gen<'a> { unreachable!("an out parameter is a pointer") }; let nt = self.nt(inner); - format!("final o_{name} = a_<{nt}>();") + format!("final {} = a_<{nt}>();", out_var(name)) } /// The C value an out pointer `o_` holds once written: a scalar's value, or a /// struct's view. fn out_value(&self, name: &str, ty: Option<&Ty>) -> String { match ty { - Some(Ty::Out(inner)) if !Self::scalar(inner) => format!("o_{name}.ref"), - _ => format!("o_{name}.value"), + Some(Ty::Out(inner)) if !Self::scalar(inner) => format!("{}.ref", out_var(name)), + _ => format!("{}.value", out_var(name)), } } @@ -2700,8 +2832,8 @@ impl<'a> Gen<'a> { let e = strip_refs(e); let c = abi.ty(&e); let v = match Self::scalar(&c) { - true => format!("o_out{n}.value"), - false => format!("o_out{n}.ref"), + true => format!("o$out{n}.value"), + false => format!("o$out{n}.ref"), }; self.lift(&e, &v) }) @@ -2714,8 +2846,8 @@ impl<'a> Gen<'a> { _ => { let c = abi.ty(ok); let v = match Self::scalar(&c) { - true => "o_out.value", - false => "o_out.ref", + true => "o$out.value", + false => "o$out.ref", }; self.lift(ok, v) } @@ -2917,10 +3049,45 @@ fn int_literal(v: i128) -> String { } } -/// A snake-case name in camel case: `into_label` is `intoLabel`, and `0` is `$0`. +/// A C name as a private Dart name, its `_`s as `$`s: Dart's lints read an underscore inside +/// an identifier as a break in its words, and no Rust or C name has a `$` to clash with. +fn private(c: &str) -> String { + format!("_{}", mangle(c)) +} + +/// [`private`], for a type, which starts in upper case. +fn private_type(c: &str) -> String { + let mut chars = mangle(c).chars().collect::>(); + chars[0] = chars[0].to_ascii_uppercase(); + format!("_{}", chars.into_iter().collect::()) +} + +/// How many times `code` has `call`, which is no end of a longer name. +fn calls(code: &str, call: &str) -> usize { + (code.match_indices(call)) + .filter(|(at, _)| !code[..*at].ends_with(|c: char| c.is_alphanumeric() || c == '_' || c == '$')) + .count() +} + +/// The local a call's out pointer `name` lands in. +fn out_var(name: &str) -> String { + format!("o${}", mangle(name)) +} + +/// `name` with its `_`s as `$`s. +fn mangle(name: &str) -> String { + name.replace('_', "$") +} + +/// The name of a field of a C struct: `$` and its name, as Dart's own members never are. +fn slot(name: &str) -> String { + format!("${}", mangle(name)) +} + +/// A snake-case name in camel case: `into_label` is `intoLabel`, and `0_set` is `$0Set`. fn camel(name: &str) -> String { if name.starts_with(|c: char| c.is_ascii_digit()) { - return format!("${name}"); + return format!("${}", pascal(name)); } let pascal = pascal(name); let mut chars = pascal.chars(); @@ -2930,14 +3097,74 @@ fn camel(name: &str) -> String { } } -/// A type's Dart name: a built-in identifier takes a trailing `_`. +/// A type's Dart name: a built-in identifier takes a `2`, since Dart's lints allow no `_` in +/// a type's name. fn type_name(name: &str) -> String { match BUILT_IN.contains(&name) { - true => format!("{name}_"), + true => format!("{name}2"), false => name.to_string(), } } +/// `name`, then the names to try in its place where it is taken: a type takes the next number +/// (`Cancelled2`), as Dart's lints allow no `_` in one, and any other name a trailing `_`, +/// then a number before it (`default_`, `default2_`), which no name Rust gives it ends in. +fn alternatives(name: &str) -> impl Iterator + use<> { + let base = name.trim_end_matches('_').to_string(); + let type_ = name.starts_with(|c: char| c.is_ascii_uppercase()); + let name = name.to_string(); + let first = name.clone(); + std::iter::once(first).chain( + (1..) + .filter_map(move |n| match (type_, n) { + (true, 1) => None, + (true, n) => Some(format!("{base}{n}")), + (false, 1) => Some(format!("{base}_")), + (false, n) => Some(format!("{base}{n}_")), + }) + .filter(move |alt| *alt != name), + ) +} + +/// `names`, each kept apart from what `taken` names and from the others, as [`abi::unique`] +/// does, but by [`alternatives`]: one taken, or an earlier one's, takes the first free +/// alternative, never another's own. +fn unique(names: Vec, taken: impl Fn(&str) -> bool) -> Vec { + let mut used = BTreeSet::new(); + (names.iter()) + .map(|name| { + let free = alternatives(name) + .find(|alt| !(taken(alt) || used.contains(alt) || (alt != name && names.contains(alt)))) + .expect("alternatives never end"); + used.insert(free.clone()); + free + }) + .collect() +} + +/// The classes `abi` names, as [`Abi::classes`] does, but with no `_` in a name, which +/// Dart's lints allow in no type's: one it joined from a module and a type, `Polar_Turn`, +/// drops it, and one it made distinct with a trailing `_` takes a number instead, each +/// after every name that has none. +fn classes(abi: &Abi<'_>, taken: &dyn Fn(&str) -> bool) -> HashMap { + let mut classes = abi.classes(|_| (String::new(), 0), taken); + let mut apart: Vec<(String, String)> = (classes.iter()) + .filter(|(_, name)| name.contains('_')) + .map(|(c, name)| (name.clone(), c.clone())) + .collect(); + apart.sort(); + let mut used: BTreeSet = (classes.values()).filter(|name| !name.contains('_')).cloned().collect(); + for (name, c) in apart { + let base = name.trim_end_matches('_').replace('_', ""); + let free = alternatives(&base) + .find(|alt| !(taken(alt) || used.contains(alt))) + .expect("alternatives never end"); + used.insert(free.clone()); + classes.insert(c, free); + } + classes +} + /// A member's Dart name: in camel case, with `_` appended if a reserved word or one of /// `reserved`. fn member(snake: &str, reserved: &[&str]) -> String { diff --git a/ffi/surface/api/dart.dart b/ffi/surface/api/dart.dart index 2fa438543..574ff19cd 100644 --- a/ffi/surface/api/dart.dart +++ b/ffi/surface/api/dart.dart @@ -1,6 +1,8 @@ // api.dart extension type const U64.fromBits(int bits) { U64(int value); + factory U64.fromBigInt(BigInt value); + static const max = U64.fromBits(-1); int toInt(); BigInt toBigInt(); String toRadixString(int radix); @@ -566,9 +568,9 @@ final class Booth { @override bool operator ==(Object other); @override int get hashCode; } -final class Cancelled_ { +final class Cancelled2 { final int step; - const Cancelled_({required this.step}); + const Cancelled2({required this.step}); String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -624,15 +626,15 @@ final class Spot { @override int get hashCode; factory Spot.deserialize(Json deserializer); } -final class Deprecated_ { +final class Deprecated2 { final bool on; @Deprecated('') final int lower; final bool deprecated; - const Deprecated_({required this.on, required this.lower, required this.deprecated}); + const Deprecated2({required this.on, required this.lower, required this.deprecated}); String debug(); @override bool operator ==(Object other); @override int get hashCode; - factory Deprecated_.default_(); + factory Deprecated2.default_(); } final class Dial { final U64 level; @@ -662,9 +664,9 @@ final class PolarPoint { @override bool operator ==(Object other); @override int get hashCode; } -final class Polar_Turn { +final class PolarTurn2 { final int part; - const Polar_Turn({required this.part}); + const PolarTurn2({required this.part}); String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -676,9 +678,9 @@ final class ClashTone { @override bool operator ==(Object other); @override int get hashCode; } -final class ClashTone_ { +final class ClashTone2 { final int db; - const ClashTone_({required this.db}); + const ClashTone2({required this.db}); String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -706,8 +708,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; + static ClashBreak get sp_; } final class TlsPolicyLifetime { final int seconds; @@ -735,9 +737,9 @@ final class ChoicePicked extends Choice { sealed class Array { const Array(); } -final class ArrayU8x4_ extends Array { +final class ArrayU8x42 extends Array { final int $0; - const ArrayU8x4_(this.$0); + const ArrayU8x42(this.$0); } sealed class Platform { const Platform(); @@ -768,8 +770,8 @@ enum Shape { const Shape(this._c); String debug(); static Shape? valueOf(String name); - static List get ALL; - static List get BOTH; + static List get all; + static List get both; } sealed class Event { const Event(); @@ -846,8 +848,8 @@ final class ClashBytes extends Clash { final typed.Uint8List $0; const ClashBytes(this.$0); } -final class ClashAny_ extends Clash { - const ClashAny_(); +final class ClashAny2 extends Clash { + const ClashAny2(); } final class ClashUnit extends Clash { const ClashUnit(); @@ -1119,8 +1121,8 @@ final class SlotU8 extends _Object { int value(); } final class Resolving extends _Object { - TlsResolver get $0_get; - void $0_set(TlsResolver value); + TlsResolver get $0Get; + void $0Set(TlsResolver value); factory Resolving(String name); } final class Codecs extends _Object { @@ -1422,7 +1424,7 @@ final class Key extends _Object { } final class ClashSeed extends _Object { factory ClashSeed.default_(); - factory ClashSeed.default__(); + factory ClashSeed.default2_(); int value(); bool bool_(); } @@ -1537,10 +1539,10 @@ final class VecClashToneException implements Exception { const VecClashToneException(this.error); @override String toString(); } -const LIMIT = U64.fromBits(1000); -const FAR = 9223372036854775807; -const URL = U64.fromBits(1000); -@Deprecated('pass a step to `Dial::turn`, whose `}` or `{` alone stays in the note') const STEP = U64.fromBits(1); +const limit = U64.fromBits(1000); +const far = 9223372036854775807; +const url = U64.fromBits(1000); +@Deprecated('pass a step to `Dial::turn`, whose `}` or `{` alone stays in the note') const step = U64.fromBits(1); bool hasText(Note note); U64 marked(Mark apiMarked); Reading? reading(int n); @@ -1658,7 +1660,7 @@ U64 keptPolarPoint(PolarPoint from); int keepPoint(Point kept); int keptOrPoint(Point? kept); int keeperPoint(Point keeper); -BoxedU16 get BOXED; +BoxedU16 get boxed; BoxedU8 keeps(Log log); int weighPoint(Point from); int applyNonZeroU16(PairNonZeroU16 pair, int Function(int) f); @@ -1666,7 +1668,7 @@ int applyU32(PairU32 pair, int Function(int) f); int reportNonZeroU16(PairNonZeroU16 pair, Log log); int reportU32(PairU32 pair, Log log); int tallyLogCount(Log log); -int wind(PolarTurn whole, Polar_Turn part); +int wind(PolarTurn whole, PolarTurn2 part); U64 area(Size size); U64 seedsPointPoint(Point from); U64 seedsPointCounter(Counter from); @@ -1756,8 +1758,8 @@ RustDuration since(Instant later, Instant earlier); bool hasInstant(Instant? at); Level? louder(Level? filter); String spell(Level? filter); -List get GREETINGS; -typed.Uint32List get PRIMES; +List get greetings; +typed.Uint32List get primes; List numbered(List names); (SocketAddrV4, SocketAddrV6) nexts(SocketAddrV4 v4, SocketAddrV6 v6); (Ipv4Addr, Ipv6Addr) nextIps(Ipv4Addr v4, Ipv6Addr v6); diff --git a/ffi/surface/moq/dart.dart b/ffi/surface/moq/dart.dart index 362764bb0..27ef4c116 100644 --- a/ffi/surface/moq/dart.dart +++ b/ffi/surface/moq/dart.dart @@ -1,6 +1,8 @@ // moq.dart extension type const U64.fromBits(int bits) { U64(int value); + factory U64.fromBigInt(BigInt value); + static const max = U64.fromBits(-1); int toInt(); BigInt toBigInt(); String toRadixString(int radix); @@ -184,10 +186,10 @@ final class Timescale { String debug(); @override bool operator ==(Object other); @override int get hashCode; - static Timescale get SECOND; - static Timescale get MILLI; - static Timescale get MICRO; - static Timescale get NANO; + static Timescale get second; + static Timescale get milli; + static Timescale get micro; + static Timescale get nano; factory Timescale(U64 unitsPerSecond); U64 asU64(); } @@ -195,7 +197,7 @@ final class Timestamp { String debug(); @override bool operator ==(Object other); @override int get hashCode; - static Timestamp get ZERO; + static Timestamp get zero; factory Timestamp(U64 value, Timescale scale); factory Timestamp.unscaled(U64 key); factory Timestamp.fromScale(U64 value, U64 unitsPerSecond); @@ -219,7 +221,7 @@ final class ClockInstant { String debug(); @override bool operator ==(Object other); @override int get hashCode; - static ClockInstant get ZERO; + static ClockInstant get zero; factory ClockInstant.now(); RustDuration elapsed(); RustDuration durationSince(ClockInstant earlier); @@ -242,8 +244,8 @@ final class ClockWall { String debug(); @override bool operator ==(Object other); @override int get hashCode; - static ClockWall get UNIX_EPOCH; - static ClockWall get MOQ_EPOCH; + static ClockWall get unixEpoch; + static ClockWall get moqEpoch; factory ClockWall.now(); RustDuration? checkedDurationSince(ClockWall earlier); RustDuration saturatingDurationSince(ClockWall earlier); @@ -510,7 +512,7 @@ final class BandwidthRate { @override bool operator ==(Object other); @override int get hashCode; factory BandwidthRate.default_(); - static BandwidthRate get ZERO; + static BandwidthRate get zero; factory BandwidthRate.fromBps(U64 bps); factory BandwidthRate.fromKbps(U64 kbps); factory BandwidthRate.fromMbps(U64 mbps); @@ -638,7 +640,7 @@ final class HangCatalogAv1 { @override bool operator ==(Object other); @override int get hashCode; factory HangCatalogAv1.default_(); - static String get PREFIX; + static String get prefix; } final class HangCatalogMastering { final HangCatalogChromaticity red; @@ -1142,7 +1144,7 @@ enum StatsFailure { expired(3), const StatsFailure(this._c); String debug(); - static List get ALL; + static List get all; String asStr(); } enum StatsRefusalKind { @@ -1154,7 +1156,7 @@ enum StatsRefusalKind { expired(5), const StatsRefusalKind(this._c); String debug(); - static List get ALL; + static List get all; String asStr(); } enum StatsRouteClose { @@ -1167,7 +1169,7 @@ enum StatsRouteClose { other(6), const StatsRouteClose(this._c); String debug(); - static List get ALL; + static List get all; String asStr(); } enum StatsRouteRefusal { @@ -1176,7 +1178,7 @@ enum StatsRouteRefusal { looped(2), const StatsRouteRefusal(this._c); String debug(); - static List get ALL; + static List get all; String asStr(); } enum StatsWithdrawal { @@ -1184,7 +1186,7 @@ enum StatsWithdrawal { drain(1), const StatsWithdrawal(this._c); String debug(); - static List get ALL; + static List get all; String asStr(); } enum TransportAddress { @@ -1462,7 +1464,7 @@ enum MuxCatalogCatalogFormat { const MuxCatalogCatalogFormat(this._c); String debug(); factory MuxCatalogCatalogFormat.default_(); - static MuxCatalogCatalogFormat get DEFAULT; + static MuxCatalogCatalogFormat get default2_; String extension(); static MuxCatalogCatalogFormat? detect(String name); } @@ -1914,7 +1916,7 @@ enum MoqTokioAcceptFailure { const MoqTokioAcceptFailure(this._c); @override String toString(); String debug(); - static List get ALL; + static List get all; String asStr(); } enum MoqTokioRedirect { @@ -1969,26 +1971,26 @@ final class RustlsProtocolVersionSSLv2 extends RustlsProtocolVersion { final class RustlsProtocolVersionSSLv3 extends RustlsProtocolVersion { const RustlsProtocolVersionSSLv3(); } -final class RustlsProtocolVersionTLSv1_0 extends RustlsProtocolVersion { - const RustlsProtocolVersionTLSv1_0(); +final class RustlsProtocolVersionTLSv10 extends RustlsProtocolVersion { + const RustlsProtocolVersionTLSv10(); } -final class RustlsProtocolVersionTLSv1_1 extends RustlsProtocolVersion { - const RustlsProtocolVersionTLSv1_1(); +final class RustlsProtocolVersionTLSv11 extends RustlsProtocolVersion { + const RustlsProtocolVersionTLSv11(); } -final class RustlsProtocolVersionTLSv1_2 extends RustlsProtocolVersion { - const RustlsProtocolVersionTLSv1_2(); +final class RustlsProtocolVersionTLSv12 extends RustlsProtocolVersion { + const RustlsProtocolVersionTLSv12(); } -final class RustlsProtocolVersionTLSv1_3 extends RustlsProtocolVersion { - const RustlsProtocolVersionTLSv1_3(); +final class RustlsProtocolVersionTLSv13 extends RustlsProtocolVersion { + const RustlsProtocolVersionTLSv13(); } -final class RustlsProtocolVersionDTLSv1_0 extends RustlsProtocolVersion { - const RustlsProtocolVersionDTLSv1_0(); +final class RustlsProtocolVersionDTLSv10 extends RustlsProtocolVersion { + const RustlsProtocolVersionDTLSv10(); } -final class RustlsProtocolVersionDTLSv1_2 extends RustlsProtocolVersion { - const RustlsProtocolVersionDTLSv1_2(); +final class RustlsProtocolVersionDTLSv12 extends RustlsProtocolVersion { + const RustlsProtocolVersionDTLSv12(); } -final class RustlsProtocolVersionDTLSv1_3 extends RustlsProtocolVersion { - const RustlsProtocolVersionDTLSv1_3(); +final class RustlsProtocolVersionDTLSv13 extends RustlsProtocolVersion { + const RustlsProtocolVersionDTLSv13(); } final class RustlsProtocolVersionUnknown extends RustlsProtocolVersion { final int $0; @@ -2007,7 +2009,7 @@ enum MoqQuicConnectionMuxVersion { qMux02(2), const MoqQuicConnectionMuxVersion(this._c); String debug(); - static List get ALL; + static List get all; bool usesRecords(); String alpn(); String prefix(); @@ -2019,7 +2021,7 @@ enum MoqSockDemuxDiscard { overflow(3), const MoqSockDemuxDiscard(this._c); String debug(); - static List get ALL; + static List get all; String asStr(); } enum MoqSockUdpEcnCodepoint { @@ -2227,7 +2229,7 @@ final class Version extends _Object { Version clone(); @override bool operator ==(Object other); @override int get hashCode; - static List get ALL; + static List get all; bool hasRequestPath(); String asStr(); String alpn(); @@ -2283,7 +2285,7 @@ final class ClockManual extends _Object { String debug(); ClockManual clone(); factory ClockManual.default_(); - static ClockWall get WALL_START; + static ClockWall get wallStart; factory ClockManual(); ClockInstant now(); ClockWall wall(); @@ -2301,7 +2303,7 @@ final class ClockWallMap extends _Object { String debug(); ClockWallMap clone(); factory ClockWallMap.default_(); - static RustDuration get TOLERANCE; + static RustDuration get tolerance; void sample(ClockInstant now, ClockWall wall); ClockInstant? map(ClockWall at); } @@ -2337,7 +2339,7 @@ final class HangCatalog extends _Object { void includeSet(List<(String, HangCatalogInclude)> value); HangCatalogSkipped get skippedGet; void skippedSet(HangCatalogSkipped value); - static String get DEFAULT_NAME; + static String get defaultName; static TrackInfo defaultTrackInfo(); static TrackSubscription defaultSubscription(); void checkRenditions(); @@ -2431,12 +2433,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); } @@ -2455,7 +2457,7 @@ final class MuxIngest extends _Object { MuxCatalogConfig catalog(); } final class MuxLingerUnit extends _Object { - static RustDuration get DEFAULT; + static RustDuration get default_; factory MuxLingerUnit(List broadcasts, RustDuration duration); Cancelable wait(); } @@ -2946,7 +2948,7 @@ final class BandwidthCap extends _Object { void rateSet(BandwidthRate value); RustDuration get burstGet; void burstSet(RustDuration value); - static RustDuration get DEFAULT_BURST; + static RustDuration get defaultBurst; factory BandwidthCap(BandwidthRate rate); BandwidthCap withBurst(RustDuration burst); } @@ -2976,7 +2978,7 @@ final class BandwidthViewers extends _Object { String debug(); BandwidthViewers clone(); factory BandwidthViewers.default_(); - static BandwidthRate get MAX_TARGET; + static BandwidthRate get maxTarget; factory BandwidthViewers(BandwidthWeak estimate); BandwidthViewer watch(BandwidthRate max); void setTarget(BandwidthRate? target); @@ -7217,7 +7219,7 @@ final class MuxContainerTsStatsRelease extends _Object { } final class MuxContainerTsStatsLog extends _Object { factory MuxContainerTsStatsLog.default_(); - static RustDuration get INTERVAL; + static RustDuration get interval; void sample(MuxContainerTsStatsSnapshot latest); void finish(MuxContainerTsStatsSnapshot latest); } @@ -7249,7 +7251,7 @@ final class MoqTokioCliBound extends _Object { MoqTokioCliBound clone(); @override bool operator ==(Object other); @override int get hashCode; - static MoqTokioCliBound get NONE; + static MoqTokioCliBound get none; } final class MoqTokioTcpTlsAcceptor extends _Object { MoqTokioTcpTlsAcceptor clone(); @@ -7697,16 +7699,16 @@ final class StringException implements Exception { const StringException(this.error); @override String toString(); } -const PATH_MAX_PARTS = U64.fromBits(32); -const PATH_MAX_BYTES = U64.fromBits(4096); -const PATTERN_MAX_SEGMENTS = U64.fromBits(32); -const PATTERN_MAX_INTERSECTIONS = U64.fromBits(1024); -const SETUP_TOKEN_OUT_OF_BAND = U64.fromBits(0); -const TRANSPORT_MIN_RECEIVE_WINDOW = U64.fromBits(1048576); -const TRANSPORT_SETUP_RECEIVE_WINDOW = U64.fromBits(131102); -const HANG_CATALOG_MAX_SAFE_INTEGER = U64.fromBits(9007199254740991); -String get IMPLEMENTATION; -List get ALPNS; +const pathMaxParts = U64.fromBits(32); +const pathMaxBytes = U64.fromBits(4096); +const patternMaxSegments = U64.fromBits(32); +const patternMaxIntersections = U64.fromBits(1024); +const setupTokenOutOfBand = U64.fromBits(0); +const transportMinReceiveWindow = U64.fromBits(1048576); +const transportSetupReceiveWindow = U64.fromBits(131102); +const hangCatalogMaxSafeInteger = U64.fromBits(9007199254740991); +String get implementation; +List get alpns; String escape(String content); String unescape(String segment); ClockInstant clockNow(); @@ -7722,26 +7724,26 @@ Cancelable clockSleep(RustDuration duration); Cancelable clockSleepUntil(ClockInstant at); Cancelable clockTimeout(RustDuration duration, Future future); Cancelable clockTimeoutAt(ClockInstant deadline, Future future); -RustDuration get SERVER_DEFAULT_TIMEOUT; +RustDuration get serverDefaultTimeout; Cancelable timeRunDriver(Driver driver); Cancelable timeRunOriginDriver(OriginDriver driver); U64 varintDecodeQuic(Mut r); void varintEncodeQuic(U64 value, Mut w); -RustDuration get CACHE_DEFAULT_EXPIRY; -String get HANG_ECHO_SUFFIX; -String get HANG_ECHO_TRACK; +RustDuration get cacheDefaultExpiry; +String get hangEchoSuffix; +String get hangEchoTrack; bool hangEchoIsEcho(Path path); -HangCatalogPriorities get HANG_CATALOG_PRIORITY; -RustDuration get HANG_CONTAINER_MAX_AGE; -Timescale get HANG_CONTAINER_TIMESCALE; +HangCatalogPriorities get hangCatalogPriority; +RustDuration get hangContainerMaxAge; +Timescale get hangContainerTimescale; TrackInfo hangContainerTrackInfo(int priority); -RustDuration get MUX_CONTAINER_DELAY_MAX; -RustDuration get MUX_RATE_RETRY; +RustDuration get muxContainerDelayMax; +RustDuration get muxRateRetry; ArrayU8x32 tokioTlsParseFingerprint(String value); OriginProducer tokioOriginSpawn(); (TransportMemorySession, TransportMemorySession) transportMemoryPair(TransportMemoryConfig config); HangCatalogAudioConfig muxCodecAacConfig(typed.Uint8List init); -typed.Uint8List get MUX_CODEC_ANNEXB_START_CODE; +typed.Uint8List get muxCodecAnnexbStartCode; typed.Uint8List muxCodecAnnexbFromLengthPrefixed(typed.Uint8List payload, U64 lengthSize, typed.Uint8List? prefix); typed.Uint8List muxCodecAnnexbBuildPrefix(List nals); void muxCodecAnnexbLengthPrefixedToAnnexb(typed.Uint8List data, U64 lengthSize, Mut out); @@ -7751,7 +7753,7 @@ HangCatalogAudioConfig muxCodecFlacConfig(typed.Uint8List init); HangCatalogVideoConfig muxCodecH264Config(typed.Uint8List buf); HangCatalogVideoConfig muxCodecH265Config(typed.Uint8List buf); HangCatalogAudioConfig muxCodecMp3Config(typed.Uint8List init); -RustDuration get MUX_CODEC_OPUS_WARMUP; +RustDuration get muxCodecOpusWarmup; int? muxCodecOpusPacketSamples(typed.Uint8List packet); HangCatalogAudioConfig muxCodecOpusConfig(typed.Uint8List init); MuxContainerMp4Finish? muxContainerMp4Repair(SeekableReader file); diff --git a/ffi/surface/surface.py b/ffi/surface/surface.py index 7979a54dd..9ff28e270 100644 --- a/ffi/surface/surface.py +++ b/ffi/surface/surface.py @@ -284,7 +284,7 @@ def scope(self, start, end, level, kind, public): elif depth == 0 and c == "{": j = self.close(i) header, hmask = code[hs:i], masked[hs:i] - if assignment(hmask) is not None: + if assignment(hmask) is not None and not self.initializers(hmask): # A value, such as a lambda or a set literal, that the `;` ends. i = j + 1 continue @@ -309,6 +309,11 @@ def scope(self, start, end, level, kind, public): if masked[hs:end].strip(): raise Malformed(f"a declaration without its end: {squash(code[hs:end])[:80]}") + def initializers(self, hmask): + """Whether a Dart header is a constructor with an initializer list (`A(x) : _x = x`), + whose `{` opens a body rather than a value.""" + return self.lang == "dart" and re.search(r"\)\s*:[^;]*$", hmask) is not None + def friend(self, hmask): """Whether a C++ declaration declares a function as a friend, which a caller finds by its arguments whatever access section declares it, unlike a friend type or a function diff --git a/ffi/surface/test_surface.py b/ffi/surface/test_surface.py index 9b982ff77..e4ab65ae9 100644 --- a/ffi/surface/test_surface.py +++ b/ffi/surface/test_surface.py @@ -236,6 +236,22 @@ class Dart(unittest.TestCase): def outline(self, text): return lines(surface.braced(text, "dart")) + def test_constructor_initializer_list_ends_at_its_body(self): + self.assertEqual(self.outline(""" +final class A { +\tA(List b) : _b = b { +\t\tx(); +\t} + +\tint operator [](int index) => _b[index]; +} +"""), [ + "final class A {", + "\tA(List b);", + "\tint operator [](int index);", + "}", + ]) + def test_private_names_and_bodies(self): source = """ import 'dart:ffi' as ffi; diff --git a/ffi/tests/dart_lints.yaml b/ffi/tests/dart_lints.yaml new file mode 100644 index 000000000..1cdc20de0 --- /dev/null +++ b/ffi/tests/dart_lints.yaml @@ -0,0 +1,40 @@ +# The lints pub.dev scores a package with: package:lints/core.yaml, which pana loads when a +# package has no analysis_options.yaml of its own. Copied from lints 6.1.0 so the check needs +# no pub get; `dart analyze --options` reads this where the generated Dart has none. +linter: + rules: + - avoid_empty_else + - avoid_relative_lib_imports + - avoid_shadowing_type_parameters + - avoid_types_as_parameter_names + - await_only_futures + - camel_case_extensions + - camel_case_types + - collection_methods_unrelated_type + - curly_braces_in_flow_control_structures + - dangling_library_doc_comments + - depend_on_referenced_packages + - empty_catches + - file_names + - hash_and_equals + - implicit_call_tearoffs + - library_annotations + - no_duplicate_case_values + - no_wildcard_variable_uses + - non_constant_identifier_names + - null_check_on_nullable_type_parameter + - prefer_generic_function_type_aliases + - prefer_is_empty + - prefer_is_not_empty + - prefer_iterable_whereType + - prefer_typing_uninitialized_variables + - provide_deprecation_message + - secure_pubspec_urls + - strict_top_level_inference + - type_literal_in_constant_pattern + - unintended_html_in_doc_comment + - unnecessary_overrides + - unrelated_type_equality_checks + - use_string_in_part_of_directives + - valid_regexps + - void_checks diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index d156f3c37..3749dc3e0 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -2622,6 +2622,31 @@ const TSCONFIG_PACKAGE: &str = r#"{ } "#; +/// The generated Dart of a small API, which uses little of the runtime and of what the +/// generator writes per type, analyzes with no issue as well: nothing it leaves unused stays. +#[test] +fn dart_small_api_lints() { + let dir = scratch().join("edge").join("dart"); + let out = scratch().join("edge").join("out"); + let output = export("edge", &out, &[WASM, host()], &[]); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + let lint = dir.join("lint"); + step::write( + &lint.join("analysis_options.yaml"), + std::fs::read_to_string(manifest_dir().join("tests/dart_lints.yaml")).unwrap(), + ); + step::write( + &lint.join("edge.dart"), + std::fs::read_to_string(out.join("dart").join("edge.dart")).unwrap(), + ); + let step = Step { + stamp: &dir.join("analyze.stamp"), + reads: &[&lint], + writes: &[], + }; + step.run(Command::new("dart").args(["analyze", "--fatal-infos"]).arg(&lint)); +} + /// The generated Dart, analyzed with no issue, runs `tests/api.dart`'s script, which prints /// the native transcript, then its futures, what closing and the garbage collector free, /// and each contract it fails loud on, and a Dart file of another contract fails to load. @@ -2631,12 +2656,22 @@ fn api_dart() { let scripts = generated("dart", "transcript.dart", &transcript::dart::emit(transcript())); let dir = scratch().join("api").join("dart"); let generated = api.out.join("dart"); + // The analyzer reads its options from the analyzed directory, so analyze a copy with them. + let lint = dir.join("lint"); + step::write( + &lint.join("analysis_options.yaml"), + std::fs::read_to_string(manifest_dir().join("tests/dart_lints.yaml")).unwrap(), + ); + step::write( + &lint.join("api.dart"), + std::fs::read_to_string(generated.join("api.dart")).unwrap(), + ); let step = Step { stamp: &dir.join("analyze.stamp"), - reads: &[&generated], + reads: &[&lint], writes: &[], }; - step.run(Command::new("dart").args(["analyze", "--fatal-infos"]).arg(&generated)); + step.run(Command::new("dart").args(["analyze", "--fatal-infos"]).arg(&lint)); // What looks like a leaf but reaches user code is no leaf call. The script catches a // hand-written `PartialEq`; a getter's drain it cannot, as a home drains each drop // queued for it at once, apart from any call. Nor is one walking a length the caller @@ -2734,7 +2769,7 @@ fn api_dart() { // The same Dart, with another contract than the library's in place of its own, refuses // it at the first call. let source = std::fs::read_to_string(generated.join("api.dart")).unwrap(); - let at = source.find("_contract() == 0x").expect("the Dart checks its contract") + "_contract() == 0x".len(); + let at = source.find("contract() == 0x").expect("the Dart checks its contract") + "contract() == 0x".len(); let mut mismatched = source.clone(); let digit = if &source[at..at + 1] == "0" { "1" } else { "0" }; mismatched.replace_range(at..at + 1, digit); @@ -4026,11 +4061,16 @@ fn lock() { let names = locked("names"); assert!(!names.status.success(), "binding renames passed the lock"); let stderr = String::from_utf8_lossy(&names.stderr); - for language in ["Kotlin", "Swift", "Go", "Dart", "Python"] { + // Dart's lints allow no `_` in a type's name, so it takes a number instead. + for (language, new) in [ + ("Kotlin", "GraphicsEncoder_Finish"), + ("Swift", "GraphicsEncoder_Finish"), + ("Go", "GraphicsEncoder_Finish"), + ("Dart", "GraphicsEncoderFinish2"), + ("Python", "GraphicsEncoder_Finish"), + ] { assert!( - stderr.contains(&format!( - "its {language} name `GraphicsEncoderFinish` is now `GraphicsEncoder_Finish`" - )), + stderr.contains(&format!("its {language} name `GraphicsEncoderFinish` is now `{new}`")), "missing class rename for {language}:\n{stderr}" ); } @@ -4064,8 +4104,8 @@ fn lock() { "its Kotlin name `StringException` is now `StringException_`", "its Python name `StringException` is now `StringException_`", "its Swift name `StringError` is now `StringError_`", - "its Dart name `StringException` is now `StringException_`", - "its Dart name `ShapeCircle` is now `ShapeCircle_`", + "its Dart name `StringException` is now `StringException2`", + "its Dart name `ShapeCircle` is now `ShapeCircle2`", "its Go name `ModeFast` is now `ModeFast_`", "its Go name `GoString` is now `GoString_`", "/ overload omitting Rust parameter indices 0 (zero-based): its Swift name `debugDescription` is now `debugDescription_`", @@ -4096,10 +4136,14 @@ fn lock() { .unwrap(); assert!(!output.status.success()); let stderr = String::from_utf8_lossy(&output.stderr); - for language in ["Kotlin", "Python", "Dart"] { + for (language, new) in [ + ("Kotlin", "StringException_"), + ("Python", "StringException_"), + ("Dart", "StringException2"), + ] { assert!( stderr.contains(&format!( - "exception class for `string`: its {language} name `StringException` is now `StringException_`" + "exception class for `string`: its {language} name `StringException` is now `{new}`" )), "{stderr}" ); diff --git a/quest/m1/ffi-export/README.md b/quest/m1/ffi-export/README.md index a76929d9d..5899c9524 100644 --- a/quest/m1/ffi-export/README.md +++ b/quest/m1/ffi-export/README.md @@ -98,8 +98,7 @@ Decided with the maintainer on 2026-11-18, in the per-language audit: as soon as possible: "You're allowed to break the API absolutely. Do it sooner." They are the API surface lock (`ffi/surface/`), which landed first, C and C++, Swift (landed), - Kotlin (landed), Python (landed), - [Dart](/quest/m1/ffi-export/dart-analyze.md), and docs. + Kotlin (landed), Python (landed), Dart (landed), and docs. Rejected: only the surface lock holding the pin; all of them after the pin. - ✅ Work that changes no generated API, or only adds to it, stays out of this epic, as decided on 2026-11-12: [proofs](/quest/m1/ffi-proofs/README.md), diff --git a/quest/m1/ffi-export/dart-analyze.md b/quest/m1/ffi-export/dart-analyze.md deleted file mode 100644 index fc1e30ab1..000000000 --- a/quest/m1/ffi-export/dart-analyze.md +++ /dev/null @@ -1,18 +0,0 @@ -# [XS] Analyze the generated Dart package - -## Goal - -`dart analyze --fatal-infos` runs on the generated Dart library itself, for the `api` -fixture and moq, with no file-wide `ignore_for_file: type=lint`, and passes, as pub.dev -scores `lib/` with the analyzer. - -## Plan - -Found by the 2026-11-18 language audit: `just dart-program` (`ffi/justfile:394`) -analyzes only the test program's directory, and the generated file opens with -`ignore_for_file: type=lint` (`ffi/src/dart.rs:117`), so its lints never surface. - -Decided with the maintainer on 2026-11-18: ✅ in this epic, since fixing lints can rename -or retype generated API (rejected: after the pin). - -Public API: whatever renames the analyzer's fixes need, if any. diff --git a/quest/m1/ffi-export/ship.md b/quest/m1/ffi-export/ship.md index 728d5efb8..30839a707 100644 --- a/quest/m1/ffi-export/ship.md +++ b/quest/m1/ffi-export/ship.md @@ -16,7 +16,3 @@ the refusals epic, since finished, which held back every other child. Every sibling lands first, since each breaks a generated API moq would otherwise adopt and then see change. A sibling planned later adds itself to `Required` here. - -## Required - -- [Dart analysis](/quest/m1/ffi-export/dart-analyze.md) - lint fixes may rename generated Dart