From fe5e673119629c66070eea9a26cff237fbd4a6c3 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 17:00:55 -0800 Subject: [PATCH 1/6] chore(quest): claim quest/m1/ffi-export/dart-analyze.md Quest-Claim: 2b9cfea987fd57f5 From 15a53173ac97df948db6b2173e60c12ec955d777 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 17:36:51 -0800 Subject: [PATCH 2/6] ffi!: analyze the generated Dart with pub.dev's lints The generated Dart no longer opens with ignore_for_file and passes dart analyze --fatal-infos under package:lints/core.yaml, as pub.dev scores lib/. Co-Authored-By: Claude Sonnet 5.5 --- ffi/README.md | 16 +- ffi/justfile | 6 + ffi/moq/moq.dart | 4 +- ffi/runtime/rt.dart | 6 +- ffi/src/dart.rs | 423 +++++++++++++++++------ ffi/surface/api/dart.dart | 185 ++++++++-- ffi/surface/moq/dart.dart | 503 ++++++++++++++++++++++++---- ffi/tests/api.dart | 14 +- ffi/tests/dart_lints.yaml | 40 +++ ffi/tests/fixtures.rs | 13 +- quest/m1/ffi-export/README.md | 2 +- quest/m1/ffi-export/dart-analyze.md | 18 - quest/m1/ffi-export/ship.md | 1 - 13 files changed, 995 insertions(+), 236 deletions(-) create mode 100644 ffi/tests/dart_lints.yaml delete mode 100644 quest/m1/ffi-export/dart-analyze.md diff --git a/ffi/README.md b/ffi/README.md index bed53024a..6ddd0c4c5 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -1187,15 +1187,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 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/justfile b/ffi/justfile index 9ffd4710a..47cf69d01 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/moq.dart b/ffi/moq/moq.dart index 4823207d9..696e0f52d 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..0a6ab2fe5 100644 --- a/ffi/runtime/rt.dart +++ b/ffi/runtime/rt.dart @@ -387,10 +387,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, @@ -618,7 +618,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 { diff --git a/ffi/src/dart.rs b/ffi/src/dart.rs index 23b1522ed..34c78310f 100644 --- a/ffi/src/dart.rs +++ b/ffi/src/dart.rs @@ -69,7 +69,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\n\n\ + \n\ import 'dart:async' as dasync;\n\ import 'dart:convert' as convert;\n\ import 'dart:ffi' as ffi;\n\ @@ -124,13 +149,10 @@ 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" + 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"), @@ -260,8 +282,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(), @@ -458,6 +483,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, @@ -486,7 +520,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`. @@ -495,7 +533,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; @@ -509,8 +547,8 @@ 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() } @@ -530,6 +568,37 @@ 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. + if calls(&name, "_") == 1 { + self.types = self.types.replace(&owned, ""); + self.natives.retain(|_, decl| !decl.contains(&format!(" {freeing}("))); + } + if calls(&name, "_lent") == 1 { + self.types = self.types.replace(&lent, ""); + } + } + } + /// The Dart type of `ty`, as a value, a parameter, or a result. fn dt(&mut self, ty: &Type) -> String { let abi = self.abi; @@ -657,7 +726,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; } @@ -697,7 +766,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 { @@ -715,10 +784,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); @@ -726,12 +795,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!( @@ -771,8 +840,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)), } } @@ -784,7 +853,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()) @@ -810,7 +879,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())); @@ -866,7 +935,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(); @@ -895,6 +964,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, @@ -903,17 +973,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" @@ -921,11 +993,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!( @@ -935,15 +1008,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, } } @@ -1010,7 +1083,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});"), @@ -1058,12 +1134,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()); @@ -1073,7 +1149,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) => { @@ -1081,7 +1157,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") @@ -1101,7 +1177,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!( @@ -1141,7 +1217,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") } @@ -1185,12 +1261,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()); @@ -1208,7 +1284,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)), @@ -1238,7 +1314,7 @@ 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)), @@ -1290,7 +1366,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]), @@ -1415,13 +1491,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!( + "static {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\t{name}._(this._bytes);\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()); @@ -1734,7 +1817,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{}", @@ -1776,7 +1859,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", @@ -1801,7 +1884,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. @@ -1913,13 +1996,19 @@ 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", @@ -1937,8 +2026,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 { @@ -1954,6 +2041,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(), ""), + 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); @@ -1962,7 +2084,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)), @@ -1992,8 +2114,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!( @@ -2002,22 +2123,10 @@ 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(), ""), - body.join("\n\n") - ); + self.on = on; } + /// A static function `name` C calls with `data` and `c_params`, running `body`, which /// returns the C result, with each object in `lent` closed after, and aborting on what /// it throws. Returns the pointer to it as an expression. @@ -2175,7 +2284,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); @@ -2246,11 +2355,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 @@ -2328,7 +2433,10 @@ 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, _) => { @@ -2388,13 +2496,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; @@ -2412,7 +2516,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. @@ -2448,8 +2552,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!( @@ -2465,10 +2569,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()); @@ -2495,10 +2599,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 { @@ -2607,7 +2715,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(_)) @@ -2645,7 +2756,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); @@ -2659,15 +2770,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)), } } @@ -2681,8 +2792,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) }) @@ -2695,8 +2806,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) } @@ -2821,10 +2932,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(); @@ -2834,14 +2980,77 @@ 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 3cde662a5..a2dd046df 100644 --- a/ffi/surface/api/dart.dart +++ b/ffi/surface/api/dart.dart @@ -260,6 +260,7 @@ final class Window { bool contains(U64 n); } final class Ticket { + final int $u0; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -277,6 +278,7 @@ final class Seat { U64 count(); } final class Stamp { + final int $u0; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -286,6 +288,8 @@ final class Stamp { bool later(Stamp other); } final class Moment { + final int $u0; + final int $u1; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -294,6 +298,8 @@ final class Moment { Moment after(U64 ticks); } final class LongArray { + final int $u0; + final int $u1; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -323,6 +329,134 @@ final class OptIn { @override int get hashCode; } final class Wide { + final int $u0; + final int $u1; + final int $u2; + final int $u3; + final int $u4; + final int $u5; + final int $u6; + final int $u7; + final int $u8; + final int $u9; + final int $u10; + final int $u11; + final int $u12; + final int $u13; + final int $u14; + final int $u15; + final int $u16; + final int $u17; + final int $u18; + final int $u19; + final int $u20; + final int $u21; + final int $u22; + final int $u23; + final int $u24; + final int $u25; + final int $u26; + final int $u27; + final int $u28; + final int $u29; + final int $u30; + final int $u31; + final int $u32; + final int $u33; + final int $u34; + final int $u35; + final int $u36; + final int $u37; + final int $u38; + final int $u39; + final int $u40; + final int $u41; + final int $u42; + final int $u43; + final int $u44; + final int $u45; + final int $u46; + final int $u47; + final int $u48; + final int $u49; + final int $u50; + final int $u51; + final int $u52; + final int $u53; + final int $u54; + final int $u55; + final int $u56; + final int $u57; + final int $u58; + final int $u59; + final int $u60; + final int $u61; + final int $u62; + final int $u63; + final int $u64; + final int $u65; + final int $u66; + final int $u67; + final int $u68; + final int $u69; + final int $u70; + final int $u71; + final int $u72; + final int $u73; + final int $u74; + final int $u75; + final int $u76; + final int $u77; + final int $u78; + final int $u79; + final int $u80; + final int $u81; + final int $u82; + final int $u83; + final int $u84; + final int $u85; + final int $u86; + final int $u87; + final int $u88; + final int $u89; + final int $u90; + final int $u91; + final int $u92; + final int $u93; + final int $u94; + final int $u95; + final int $u96; + final int $u97; + final int $u98; + final int $u99; + final int $u100; + final int $u101; + final int $u102; + final int $u103; + final int $u104; + final int $u105; + final int $u106; + final int $u107; + final int $u108; + final int $u109; + final int $u110; + final int $u111; + final int $u112; + final int $u113; + final int $u114; + final int $u115; + final int $u116; + final int $u117; + final int $u118; + final int $u119; + final int $u120; + final int $u121; + final int $u122; + final int $u123; + final int $u124; + final int $u125; + final int $u126; + final int $u127; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -338,6 +472,7 @@ final class Clocked { @override int get hashCode; } final class Score { + final int $u0; String debug(); factory Score.of(U64 count); U64 count(); @@ -348,6 +483,8 @@ final class Score { (Score, U64, U64) absorb(Mut other); } final class Hits { + final int $u0; + final int $u1; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -361,6 +498,8 @@ final class Hits { (Hits, bool) eq(Hits other); } final class Extent { + final int $u0; + final int $u1; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -557,9 +696,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; @@ -614,9 +753,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; @@ -628,9 +767,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; @@ -658,8 +797,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; @@ -687,9 +826,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(); @@ -719,8 +858,8 @@ enum Shape { square(4), const Shape(this._c); String debug(); - static List get ALL; - static List get BOTH; + static List get all; + static List get both; } sealed class Event { const Event(); @@ -797,8 +936,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(); @@ -1056,8 +1195,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 { @@ -1346,7 +1485,7 @@ final class Key extends _Object { } final class ClashSeed extends _Object { factory ClashSeed.default_(); - factory ClashSeed.default__(); + factory ClashSeed.default2_(); int value(); bool bool_(); } @@ -1452,8 +1591,8 @@ final class VecClashToneException implements Exception { const VecClashToneException(this.error); @override String toString(); } -const LIMIT = U64.fromBits(1000); -const FAR = 9223372036854775807; +const limit = U64.fromBits(1000); +const far = 9223372036854775807; bool hasText(Note note); U64 marked(Mark apiMarked); Reading? reading(int n); @@ -1572,7 +1711,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); @@ -1580,7 +1719,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); @@ -1668,8 +1807,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 911580ecd..37b8bcc60 100644 --- a/ffi/surface/moq/dart.dart +++ b/ffi/surface/moq/dart.dart @@ -174,28 +174,31 @@ final class ArrayU8x6 { @override String toString(); } final class TimeOverflow implements Exception { + final int $u0; @override String toString(); String debug(); @override bool operator ==(Object other); @override int get hashCode; } final class Timescale { + final int $u0; @override String toString(); 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(); } final class ClockInstant { + final int $u0; 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); @@ -209,17 +212,19 @@ final class ClockInstant { factory ClockInstant.fromStd(Instant at); } final class ClockElapsed implements Exception { + final int $u0; @override String toString(); String debug(); @override bool operator ==(Object other); @override int get hashCode; } final class ClockWall { + final int $u0; 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); @@ -236,6 +241,7 @@ final class SetupToken { @override int get hashCode; } final class SessionLimits { + final int $u0; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -244,6 +250,9 @@ final class SessionLimits { SessionLimits announcesSet(U64 value); } final class StatsContent { + final int $u0; + final int $u1; + final int $u2; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -256,6 +265,22 @@ final class StatsContent { StatsContent groupsSet(U64 value); } final class StatsTraffic { + final int $u0; + final int $u1; + final int $u2; + final int $u3; + final int $u4; + final int $u5; + final int $u6; + final int $u7; + final int $u8; + final int $u9; + final int $u10; + final int $u11; + final int $u12; + final int $u13; + final int $u14; + final int $u15; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -294,6 +319,42 @@ final class StatsTraffic { bool isIdle(); } final class StatsPresence { + final int $u0; + final int $u1; + final int $u2; + final int $u3; + final int $u4; + final int $u5; + final int $u6; + final int $u7; + final int $u8; + final int $u9; + final int $u10; + final int $u11; + final int $u12; + final int $u13; + final int $u14; + final int $u15; + final int $u16; + final int $u17; + final int $u18; + final int $u19; + final int $u20; + final int $u21; + final int $u22; + final int $u23; + final int $u24; + final int $u25; + final int $u26; + final int $u27; + final int $u28; + final int $u29; + final int $u30; + final int $u31; + final int $u32; + final int $u33; + final int $u34; + final int $u35; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -328,6 +389,8 @@ final class StatsPresence { U64 active(); } final class StatsActivity { + final int $u0; + final int $u1; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -338,6 +401,10 @@ final class StatsActivity { StatsActivity activeSet(U64 value); } final class StatsTotals { + final int $u0; + final int $u1; + final int $u2; + final int $u3; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -352,6 +419,10 @@ final class StatsTotals { StatsTotals rxMessagesSet(U64 value); } final class StatsFailures { + final int $u0; + final int $u1; + final int $u2; + final int $u3; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -369,6 +440,12 @@ final class StatsFailures { bool regressed(StatsFailures previous); } final class StatsRefusals { + final int $u0; + final int $u1; + final int $u2; + final int $u3; + final int $u4; + final int $u5; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -390,6 +467,13 @@ final class StatsRefusals { bool regressed(StatsRefusals previous); } final class StatsRouteCloses { + final int $u0; + final int $u1; + final int $u2; + final int $u3; + final int $u4; + final int $u5; + final int $u6; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -414,6 +498,9 @@ final class StatsRouteCloses { bool regressed(StatsRouteCloses previous); } final class StatsRouteRefusals { + final int $u0; + final int $u1; + final int $u2; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -430,6 +517,22 @@ final class StatsRouteRefusals { bool regressed(StatsRouteRefusals previous); } final class StatsRoutes { + final int $u0; + final int $u1; + final int $u2; + final int $u3; + final int $u4; + final int $u5; + final int $u6; + final int $u7; + final int $u8; + final int $u9; + final int $u10; + final int $u11; + final int $u12; + final int $u13; + final int $u14; + final int $u15; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -450,6 +553,8 @@ final class StatsRoutes { bool regressed(StatsRoutes previous); } final class StatsWithdrawals { + final int $u0; + final int $u1; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -464,11 +569,12 @@ final class StatsWithdrawals { bool regressed(StatsWithdrawals previous); } final class BandwidthRate { + final int $u0; String debug(); @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); @@ -510,6 +616,8 @@ final class TrackDelay { TrackDelay withMax(RustDuration? max); } final class TrackPosition { + final int $u0; + final int $u1; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -532,6 +640,7 @@ final class TrackRange { factory TrackRange.oldest(); } final class OriginCost { + final int $u0; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -540,6 +649,7 @@ final class OriginCost { U64 value(); } final class OriginPriority { + final int $u0; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -556,6 +666,10 @@ final class HangCatalogAac { @override int get hashCode; } final class HangCatalogPriorities { + final int $u0; + final int $u1; + final int $u2; + final int $u3; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -587,7 +701,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; @@ -753,6 +867,265 @@ final class MuxCodecMp3Config { factory MuxCodecMp3Config.parse(typed.Uint8List data); } final class MuxCodecOpusMapping { + final int $u0; + final int $u1; + final int $u2; + final int $u3; + final int $u4; + final int $u5; + final int $u6; + final int $u7; + final int $u8; + final int $u9; + final int $u10; + final int $u11; + final int $u12; + final int $u13; + final int $u14; + final int $u15; + final int $u16; + final int $u17; + final int $u18; + final int $u19; + final int $u20; + final int $u21; + final int $u22; + final int $u23; + final int $u24; + final int $u25; + final int $u26; + final int $u27; + final int $u28; + final int $u29; + final int $u30; + final int $u31; + final int $u32; + final int $u33; + final int $u34; + final int $u35; + final int $u36; + final int $u37; + final int $u38; + final int $u39; + final int $u40; + final int $u41; + final int $u42; + final int $u43; + final int $u44; + final int $u45; + final int $u46; + final int $u47; + final int $u48; + final int $u49; + final int $u50; + final int $u51; + final int $u52; + final int $u53; + final int $u54; + final int $u55; + final int $u56; + final int $u57; + final int $u58; + final int $u59; + final int $u60; + final int $u61; + final int $u62; + final int $u63; + final int $u64; + final int $u65; + final int $u66; + final int $u67; + final int $u68; + final int $u69; + final int $u70; + final int $u71; + final int $u72; + final int $u73; + final int $u74; + final int $u75; + final int $u76; + final int $u77; + final int $u78; + final int $u79; + final int $u80; + final int $u81; + final int $u82; + final int $u83; + final int $u84; + final int $u85; + final int $u86; + final int $u87; + final int $u88; + final int $u89; + final int $u90; + final int $u91; + final int $u92; + final int $u93; + final int $u94; + final int $u95; + final int $u96; + final int $u97; + final int $u98; + final int $u99; + final int $u100; + final int $u101; + final int $u102; + final int $u103; + final int $u104; + final int $u105; + final int $u106; + final int $u107; + final int $u108; + final int $u109; + final int $u110; + final int $u111; + final int $u112; + final int $u113; + final int $u114; + final int $u115; + final int $u116; + final int $u117; + final int $u118; + final int $u119; + final int $u120; + final int $u121; + final int $u122; + final int $u123; + final int $u124; + final int $u125; + final int $u126; + final int $u127; + final int $u128; + final int $u129; + final int $u130; + final int $u131; + final int $u132; + final int $u133; + final int $u134; + final int $u135; + final int $u136; + final int $u137; + final int $u138; + final int $u139; + final int $u140; + final int $u141; + final int $u142; + final int $u143; + final int $u144; + final int $u145; + final int $u146; + final int $u147; + final int $u148; + final int $u149; + final int $u150; + final int $u151; + final int $u152; + final int $u153; + final int $u154; + final int $u155; + final int $u156; + final int $u157; + final int $u158; + final int $u159; + final int $u160; + final int $u161; + final int $u162; + final int $u163; + final int $u164; + final int $u165; + final int $u166; + final int $u167; + final int $u168; + final int $u169; + final int $u170; + final int $u171; + final int $u172; + final int $u173; + final int $u174; + final int $u175; + final int $u176; + final int $u177; + final int $u178; + final int $u179; + final int $u180; + final int $u181; + final int $u182; + final int $u183; + final int $u184; + final int $u185; + final int $u186; + final int $u187; + final int $u188; + final int $u189; + final int $u190; + final int $u191; + final int $u192; + final int $u193; + final int $u194; + final int $u195; + final int $u196; + final int $u197; + final int $u198; + final int $u199; + final int $u200; + final int $u201; + final int $u202; + final int $u203; + final int $u204; + final int $u205; + final int $u206; + final int $u207; + final int $u208; + final int $u209; + final int $u210; + final int $u211; + final int $u212; + final int $u213; + final int $u214; + final int $u215; + final int $u216; + final int $u217; + final int $u218; + final int $u219; + final int $u220; + final int $u221; + final int $u222; + final int $u223; + final int $u224; + final int $u225; + final int $u226; + final int $u227; + final int $u228; + final int $u229; + final int $u230; + final int $u231; + final int $u232; + final int $u233; + final int $u234; + final int $u235; + final int $u236; + final int $u237; + final int $u238; + final int $u239; + final int $u240; + final int $u241; + final int $u242; + final int $u243; + final int $u244; + final int $u245; + final int $u246; + final int $u247; + final int $u248; + final int $u249; + final int $u250; + final int $u251; + final int $u252; + final int $u253; + final int $u254; + final int $u255; + final int $u256; + final int $u257; + final int $u258; String debug(); @override bool operator ==(Object other); @override int get hashCode; @@ -1091,7 +1464,7 @@ enum StatsFailure { expired(3), const StatsFailure(this._c); String debug(); - static List get ALL; + static List get all; String asStr(); } enum StatsRefusalKind { @@ -1103,7 +1476,7 @@ enum StatsRefusalKind { expired(5), const StatsRefusalKind(this._c); String debug(); - static List get ALL; + static List get all; String asStr(); } enum StatsRouteClose { @@ -1116,7 +1489,7 @@ enum StatsRouteClose { other(6), const StatsRouteClose(this._c); String debug(); - static List get ALL; + static List get all; String asStr(); } enum StatsRouteRefusal { @@ -1125,7 +1498,7 @@ enum StatsRouteRefusal { looped(2), const StatsRouteRefusal(this._c); String debug(); - static List get ALL; + static List get all; String asStr(); } enum StatsWithdrawal { @@ -1133,7 +1506,7 @@ enum StatsWithdrawal { drain(1), const StatsWithdrawal(this._c); String debug(); - static List get ALL; + static List get all; String asStr(); } enum TransportAddress { @@ -1411,7 +1784,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); } @@ -1863,7 +2236,7 @@ enum MoqTokioAcceptFailure { const MoqTokioAcceptFailure(this._c); @override String toString(); String debug(); - static List get ALL; + static List get all; String asStr(); } enum MoqTokioRedirect { @@ -1918,26 +2291,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; @@ -1956,7 +2329,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(); @@ -1968,7 +2341,7 @@ enum MoqSockDemuxDiscard { overflow(3), const MoqSockDemuxDiscard(this._c); String debug(); - static List get ALL; + static List get all; String asStr(); } enum MoqSockUdpEcnCodepoint { @@ -2175,7 +2548,7 @@ final class Timestamp extends _Object { Timestamp clone(); @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); @@ -2201,7 +2574,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(); @@ -2257,7 +2630,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(); @@ -2275,7 +2648,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); } @@ -2311,7 +2684,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(); @@ -2405,12 +2778,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); } @@ -2429,7 +2802,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(); } @@ -2940,7 +3313,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); } @@ -2970,7 +3343,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); @@ -7220,7 +7593,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); } @@ -7252,7 +7625,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(); @@ -7699,16 +8072,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; ClockInstant clockNow(); ClockWall clockWall(); (ClockInstant, ClockWall) clockOrigin(); @@ -7722,26 +8095,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 +8124,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/tests/api.dart b/ffi/tests/api.dart index fbe1758d9..1d116ba05 100644 --- a/ffi/tests/api.dart +++ b/ffi/tests/api.dart @@ -153,7 +153,7 @@ Future until(bool Function() done, String what) async { } Future script() async { - print('limit ${api.LIMIT}'); + print('limit ${api.limit}'); final p = const api.Point(x: 1, y: 2).offset(2, 3); print('offset ${p.x} ${p.y}'); @@ -553,12 +553,12 @@ Future script() async { print('polar ${api.polarPoint(2)!.distance} ${api.polarPoint(0) == null} ' 'area ${api.area(const api.Size(width: 2, height: 3))}'); // Two types whose paths join alike, the second kept apart where its path splits. - print('wind ${api.wind(const api.PolarTurn(whole: 2), const api.Polar_Turn(part: 3))}'); + print('wind ${api.wind(const api.PolarTurn(whole: 2), const api.PolarTurn2(part: 3))}'); // Names that clash in some language, each kept apart there. const clashSpan = api.ClashSpan(width: 4); final clashStore = api.ClashStore(7); - print('clash ${const api.ClashTone(hz: 440).debug()} ${const api.ClashTone_(db: 3).debug()} ' - '${const api.Cancelled_(step: 2).debug()} span ${clashSpan.width_()} ${clashSpan.toString_()} $clashSpan ' + print('clash ${const api.ClashTone(hz: 440).debug()} ${const api.ClashTone2(db: 3).debug()} ' + '${const api.Cancelled2(step: 2).debug()} span ${clashSpan.width_()} ${clashSpan.toString_()} $clashSpan ' 'store ${clashStore.free()} ${clashStore.close_()} ' 'audio ${api.clashAudioEncoderFinish()} ${api.clashAudioEncoderFinish_()} ' 'nested ${api.clashNested(((1, 2), 3), ((1, 2, 3),))}'); @@ -570,7 +570,7 @@ Future script() async { ); print('cross $cross outer ${api.OuterInnerU8(4).get()}'); // A bound that outlives the call takes a value, and an instance only a constant names. - print('kept ${api.keptPoint(const api.Point(x: 1, y: -2))} boxed ${api.BOXED.value}'); + print('kept ${api.keptPoint(const api.Point(x: 1, y: -2))} boxed ${api.boxed.value}'); print('keep ${api.keepPoint(const api.Point(x: 1, y: -2))}'); const five = api.Point(x: 5, y: 2); print('kept or ${api.keptOrPoint(five)} ${api.keptOrPoint(null)} keeper ${api.keeperPoint(five)}'); @@ -823,8 +823,8 @@ Future script() async { api.Label l => l.debug(), _ => throw ArgumentError(v), }).join(', ')}]'; - print('shapes ${debugs(api.Shape.ALL)} greetings ${quoted(api.GREETINGS)}'); - print('both ${debugs(api.Shape.BOTH)} primes ${api.PRIMES}'); + print('shapes ${debugs(api.Shape.all)} greetings ${quoted(api.greetings)}'); + print('both ${debugs(api.Shape.both)} primes ${api.primes}'); final trail = api.Trail([const api.Point(x: 1, y: 2), const api.Point(x: 3, y: 4)], ['a', 'b']); print('trail ${debugs(trail.points())} ${debugs(trail.labels())}'); // Returned iterators, each collected at the call: drained labels are gone after. 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 3eafe6d5b..e5d6d9d60 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -2045,12 +2045,19 @@ fn api_dart() { let api = api(); 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 @@ -2139,7 +2146,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); diff --git a/quest/m1/ffi-export/README.md b/quest/m1/ffi-export/README.md index 3c29f909f..8299f40ce 100644 --- a/quest/m1/ffi-export/README.md +++ b/quest/m1/ffi-export/README.md @@ -99,7 +99,7 @@ Decided with the maintainer on 2026-11-18, in the per-language audit: are the API surface lock (`ffi/surface/`), which landed first, [C and C++](/quest/m1/ffi-export/cpp-idioms.md), [Swift](/quest/m1/ffi-export/swift-span.md), [Kotlin](/quest/m1/ffi-export/kotlin-idioms.md), [Python](/quest/m1/ffi-export/python-idioms.md), - [Dart](/quest/m1/ffi-export/dart-analyze.md), and [docs](/quest/m1/ffi-export/docs.md). + and [docs](/quest/m1/ffi-export/docs.md). 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 48e5d7073..d196d1b2c 100644 --- a/quest/m1/ffi-export/ship.md +++ b/quest/m1/ffi-export/ship.md @@ -24,6 +24,5 @@ then see change. A sibling planned later adds itself to `Required` here. - [Swift spans](/quest/m1/ffi-export/swift-span.md) - lent bytes and slices change the Swift API - [Kotlin idioms](/quest/m1/ffi-export/kotlin-idioms.md) - direct buffers and Java annotations change the Kotlin API - [Python idioms](/quest/m1/ffi-export/python-idioms.md) - the exception hierarchy changes the Python API -- [Dart analysis](/quest/m1/ffi-export/dart-analyze.md) - lint fixes may rename generated Dart - [Docs](/quest/m1/ffi-export/docs.md) - doc links and deprecations in every binding - [Niche values](/quest/m1/ffi-export/niche-values.md) - moq's `Timestamp` changes from a handle back to a value in every binding From 6ab7df8f0193bb441164989782105c4ee87e7afc Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 18:12:42 -0800 Subject: [PATCH 3/6] ffi!: fix the Dart lints, test, and bench programs the renames touch Co-Authored-By: Claude Sonnet 5.5 --- ffi/moq/bench/export.dart | 2 +- ffi/src/dart.rs | 30 ++++++++++++++++++------------ ffi/tests/fixtures.rs | 30 +++++++++++++++++++++--------- 3 files changed, 40 insertions(+), 22 deletions(-) diff --git a/ffi/moq/bench/export.dart b/ffi/moq/bench/export.dart index ac0d6356c..778b88472 100644 --- a/ffi/moq/bench/export.dart +++ b/ffi/moq/bench/export.dart @@ -126,7 +126,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/src/dart.rs b/ffi/src/dart.rs index 34c78310f..8c58e22eb 100644 --- a/ffi/src/dart.rs +++ b/ffi/src/dart.rs @@ -547,7 +547,10 @@ 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.replace('_', ""))).collect(); + 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() } @@ -1314,7 +1317,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.{}.{}", slot(&member), slot(&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)), @@ -2003,7 +2009,8 @@ impl<'a> Gen<'a> { 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())); + 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); @@ -2084,7 +2091,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${}${}", mangle(self.bare(&c)), mangle(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)), @@ -2092,7 +2099,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()); @@ -2114,7 +2121,7 @@ impl<'a> Gen<'a> { m = method.name(), ); } - let tables = format!("_tables${}", mangle(self.bare(&c))); + let tables = format!("_tables${}", mangle(self.bare(c))); self.helpers.insert( tables.clone(), format!( @@ -2126,7 +2133,6 @@ impl<'a> Gen<'a> { self.on = on; } - /// A static function `name` C calls with `data` and `c_params`, running `body`, which /// returns the C result, with each object in `lent` closed after, and aborting on what /// it throws. Returns the pointer to it as an expression. @@ -2436,7 +2442,10 @@ impl<'a> Gen<'a> { if self.tabled.insert(cb.clone()) { self.callback_tables(&cb); } - args.push(format!("_n.give(_tables${}, {name}, {name}.close)", mangle(self.bare(&cb)))); + args.push(format!( + "_n.give(_tables${}, {name}, {name}.close)", + mangle(self.bare(&cb)) + )); gave = true; } (Type::Waker, _) => { @@ -3036,10 +3045,7 @@ fn classes(abi: &Abi<'_>, taken: &dyn Fn(&str) -> bool) -> HashMap = (classes.values()) - .filter(|name| !name.contains('_')) - .cloned() - .collect(); + 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) diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 446159ed7..f5809d874 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -2051,7 +2051,10 @@ fn api_dart() { &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()); + 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: &[&lint], @@ -3397,11 +3400,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}" ); } @@ -3435,8 +3443,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_`", @@ -3467,10 +3475,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}" ); From bc74cc7ea578b0927b93a2348a8b443abdd98e22 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 18:35:46 -0800 Subject: [PATCH 4/6] ffi: keep what the Dart analyzer would call unused out of small APIs Co-Authored-By: Claude Sonnet 5.5 --- ffi/Cargo.lock | 4 ++++ ffi/fixtures/edge/Cargo.toml | 13 +++++++++++++ ffi/fixtures/edge/ffi.toml | 2 ++ ffi/fixtures/edge/src/lib.rs | 20 ++++++++++++++++++++ ffi/runtime/rt.dart | 11 +++++++++++ ffi/src/dart.rs | 22 +++++++++++++++++----- ffi/surface/api/dart.dart | 1 - ffi/surface/moq/dart.dart | 5 ----- ffi/tests/fixtures.rs | 25 +++++++++++++++++++++++++ 9 files changed, 92 insertions(+), 11 deletions(-) create mode 100644 ffi/fixtures/edge/Cargo.toml create mode 100644 ffi/fixtures/edge/ffi.toml create mode 100644 ffi/fixtures/edge/src/lib.rs diff --git a/ffi/Cargo.lock b/ffi/Cargo.lock index e74618aaf..5459a2c55 100644 --- a/ffi/Cargo.lock +++ b/ffi/Cargo.lock @@ -161,6 +161,10 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "edge-fixture" +version = "0.0.0" + [[package]] name = "either" version = "1.19.0" 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/ffi.toml b/ffi/fixtures/edge/ffi.toml new file mode 100644 index 000000000..fd1aea94b --- /dev/null +++ b/ffi/fixtures/edge/ffi.toml @@ -0,0 +1,2 @@ +# Nothing left out. +exclude = [] 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/runtime/rt.dart b/ffi/runtime/rt.dart index 0a6ab2fe5..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); } @@ -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. @@ -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 8c58e22eb..173774ff6 100644 --- a/ffi/src/dart.rs +++ b/ffi/src/dart.rs @@ -124,6 +124,7 @@ pub(crate) fn generate(abi: &Abi<'_>, packages: &str, contract: u64) -> Result 0 @@ -152,6 +153,7 @@ pub(crate) fn generate(abi: &Abi<'_>, packages: &str, contract: u64) -> Result {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\ + // 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 [ @@ -592,12 +594,22 @@ impl<'a> Gen<'a> { } for (name, (owned, lent, freeing)) in std::mem::take(&mut self.constructors) { // Each declares itself once. - if calls(&name, "_") == 1 { + 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}("))); } - if calls(&name, "_lent") == 1 { - self.types = self.types.replace(&lent, ""); + // 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); } } } @@ -1498,7 +1510,7 @@ impl<'a> Gen<'a> { let name = Abi::array_class(*n); let s = self.struct_class(&Ty::Struct(c.clone())); let of = format!( - "static {name} _of({s} c) => {name}._(typed.Uint8List.fromList([for (var i = 0; i < {n}; i++) c.items[i]]));\n\n\t" + "{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" @@ -1506,7 +1518,7 @@ impl<'a> Gen<'a> { 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\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" + "/// 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 { diff --git a/ffi/surface/api/dart.dart b/ffi/surface/api/dart.dart index a2dd046df..e47185429 100644 --- a/ffi/surface/api/dart.dart +++ b/ffi/surface/api/dart.dart @@ -135,7 +135,6 @@ final class RangeU64 { } final class ArrayU8x4 { ArrayU8x4(List bytes); - int operator [](int index); typed.Uint8List toBytes(); @override bool operator ==(Object other); @override int get hashCode; diff --git a/ffi/surface/moq/dart.dart b/ffi/surface/moq/dart.dart index 37b8bcc60..8bd04d801 100644 --- a/ffi/surface/moq/dart.dart +++ b/ffi/surface/moq/dart.dart @@ -135,7 +135,6 @@ final class RangeU64 { } final class ArrayU8x16 { ArrayU8x16(List bytes); - int operator [](int index); typed.Uint8List toBytes(); @override bool operator ==(Object other); @override int get hashCode; @@ -143,7 +142,6 @@ final class ArrayU8x16 { } final class ArrayU8x2 { ArrayU8x2(List bytes); - int operator [](int index); typed.Uint8List toBytes(); @override bool operator ==(Object other); @override int get hashCode; @@ -151,7 +149,6 @@ final class ArrayU8x2 { } final class ArrayU8x32 { ArrayU8x32(List bytes); - int operator [](int index); typed.Uint8List toBytes(); @override bool operator ==(Object other); @override int get hashCode; @@ -159,7 +156,6 @@ final class ArrayU8x32 { } final class ArrayU8x4 { ArrayU8x4(List bytes); - int operator [](int index); typed.Uint8List toBytes(); @override bool operator ==(Object other); @override int get hashCode; @@ -167,7 +163,6 @@ final class ArrayU8x4 { } final class ArrayU8x6 { ArrayU8x6(List bytes); - int operator [](int index); typed.Uint8List toBytes(); @override bool operator ==(Object other); @override int get hashCode; diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index f5809d874..e05f6b8f2 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -2037,6 +2037,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. From 24b92415fc281c063e3ac2d9fb4a96d2a34f3902 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Thu, 19 Nov 2026 22:18:41 -0800 Subject: [PATCH 5/6] docs(ffi): name the bare trailing underscore in Dart's member collision rule Co-Authored-By: Claude Sonnet 5.5 --- ffi/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ffi/README.md b/ffi/README.md index acfed6d54..57fd5fd3e 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -1225,7 +1225,7 @@ 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 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_`); 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 From 4c6a92903a13c34971f5c5a767975a47c4f4d230 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 20 Nov 2026 01:09:33 -0800 Subject: [PATCH 6/6] ffi: delete the unread edge fixture ffi.toml #903 removed the config loader; nothing reads this file. Co-Authored-By: Claude Sonnet 5.5 --- ffi/fixtures/edge/ffi.toml | 2 -- 1 file changed, 2 deletions(-) delete mode 100644 ffi/fixtures/edge/ffi.toml diff --git a/ffi/fixtures/edge/ffi.toml b/ffi/fixtures/edge/ffi.toml deleted file mode 100644 index fd1aea94b..000000000 --- a/ffi/fixtures/edge/ffi.toml +++ /dev/null @@ -1,2 +0,0 @@ -# Nothing left out. -exclude = []