From 5a9ff6a7fb6ad6b11bbd97bd66be4ba098b43aa5 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 20 Nov 2026 00:37:34 -0800 Subject: [PATCH 1/9] chore(quest): claim quest/m1/ffi-speed/leaf-bodies.md Quest-Claim: 91dcc2723c9d774e From 3ca61abb22ba2bfdde29796c4895d145519e6a40 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 20 Nov 2026 01:44:49 -0800 Subject: [PATCH 2/9] perf(ffi): prove method and Deref bodies leaves from their MIR A `&self` or `&mut self` method of a `Send` object taking and returning scalars, and a field or method reached through `Deref`, is now a leaf when its MIR, and each `Deref`'s, calls only bodies proven the same way and core's computing intrinsics, drops nothing that runs code, and has no loop, recursion, assertion, or static. Python keeps the GIL across one and Dart makes it a leaf call. Every crate of the export's target now encodes its MIR (`-Zalways-encode-mir`). Co-Authored-By: Claude Opus 5.5 --- bench/ffi/README.md | 60 ++++++- ffi/README.md | 25 +-- ffi/fixtures/api/src/lib.rs | 77 ++++++++ ffi/src/abi.rs | 37 ++-- ffi/src/collect.rs | 38 +++- ffi/src/driver.rs | 1 + ffi/src/ir.rs | 14 ++ ffi/src/leaf.rs | 283 ++++++++++++++++++++++++++++++ ffi/src/lock.rs | 1 + ffi/src/main.rs | 1 + ffi/src/merge.rs | 3 + ffi/src/wasm.rs | 8 +- ffi/surface/api/c.h | 27 ++- ffi/surface/api/cpp.hpp | 30 ++++ ffi/surface/api/dart.dart | 24 +++ ffi/surface/api/go.txt | 28 +++ ffi/surface/api/kotlin.kt | 30 ++++ ffi/surface/api/python.pyi | 28 +++ ffi/surface/api/swift.swift | 24 +++ ffi/surface/api/web.d.ts | 19 ++ ffi/tests/api.dart | 13 ++ ffi/tests/api.py | 12 ++ ffi/tests/fixtures.rs | 22 ++- quest/m1/ffi-speed/leaf-bodies.md | 31 ---- 24 files changed, 756 insertions(+), 80 deletions(-) create mode 100644 ffi/src/leaf.rs delete mode 100644 quest/m1/ffi-speed/leaf-bodies.md diff --git a/bench/ffi/README.md b/bench/ffi/README.md index afe337262..648a1076f 100644 --- a/bench/ffi/README.md +++ b/bench/ffi/README.md @@ -217,13 +217,13 @@ GIL, which dwarfs the handle's own contention. ## Leaf calls A leaf is a call the export proves runs no code but std's and the glue's, waits on no -lock, and calls no binding: a primitive `pub` field of a `Send` object reached without a -`Deref`, or a `PartialEq` or `Hash` derived down to primitives ([`Abi::leaf`](../../ffi/src/abi.rs)). +lock, and calls no binding: a method or `pub` field of a `Send` object, taking and returning +scalars, whose body and each `Deref`'s on the way its MIR proves so, or a `PartialEq` or +`Hash` derived down to primitives ([`Abi::leaf`](../../ffi/src/abi.rs)). Python keeps the GIL across one, and Dart makes it a leaf call (`isLeaf`) to the C function itself on the isolate's thread, with no serving thunk, no thread hop, and no `_Arena`. -The benchmark's u64 getter, `demand.sequence()`, is a method, which the proof cannot see -into, so the `field` case reads `track::Info::priority` instead; `group.sequence` is a -field too, but reached through `group::Producer`'s `Deref`, which is user code. +The `field` case reads `track::Info::priority`, a field; the u64 getter, `demand.start()`, +a method returning one, is a leaf since the export reads its body ([below](#leaf-bodies)). Measured 2026-11-19 on **fedora**, an AMD Ryzen 9 9950X (16 cores, 32 threads), through `quest gate`, against moq `ffcb7cd9`. Before is rust2 `52070b3d` with this change's @@ -261,7 +261,32 @@ within the spread of its rounds. Python's 37 ns is more than the 10 to 15 the per-language audit estimated for the GIL's round trip, as `rt::call` does more around it: it may look for the event loop running, and after the call drains what other threads freed and resumes what the call woke, all of which -a leaf skips. A getter that is no leaf, such as `demand.sequence()`, still pays it. +a leaf skips. A call that is no leaf, such as `track.is_closed()`, which takes moq's lock, +still pays it. + +### Leaf bodies + +A method's body, and a `Deref`'s on the way to a member, is a leaf when its MIR +([`leaf.rs`](../../ffi/src/leaf.rs)) calls only bodies proven the same way and core's +intrinsics that only compute, drops nothing whose drop runs other code, has no loop, no +recursion, no assertion, and no static. So `demand.start()` and `group::Producer`'s +`start`, through its `Deref`, are leaves, as are 91 more of the stand-in's methods and +accessors: Dart makes 348 of its calls leaf calls, against 255. + +Measured 2026-11-20 on **fedora**, through `quest gate`, against moq `1aa86d5e`: before is +rust2 `8798a5d7`, after is this change, each program alternating before and after for 5 +rounds at a load average of 7 to 15; each cell is the median wall time in ns per call. + +| case | before | after | +|---|---|---| +| Python `getter` | 64.5 | 26.7 | +| Python `shared:getter` | 1,790 | 119 | +| Python `own:getter` | 1,779 | 113 | +| Dart `getter` | 26.5 | 15.8 | + +The four threads no longer hand the GIL to each other on every call, which was most of +their 1.8 us. Every other case of both languages moved within 4% either way, Python's +`field` included, whose code is the same. ## Swift's inlined calls @@ -787,8 +812,27 @@ the refusal), 3 rounds each, alternating, at a load average of 24 to 31; medians The refusal adds about 11 CPU seconds, and its walk of the stand-in's 299,455 reachable instances takes 6.5 s of them. Wall time ranged 24 to 60 s and 39 to 69 s between rounds at this load, so its gap is rough; the walk's check runs after moq's crates, with nothing -beside it. Peak memory doubles, steady across rounds. A native export reads no MIR and -pays none of it. +beside it. Peak memory doubles, steady across rounds. + +A native export reads MIR only for its [leaf bodies](#leaf-bodies), which every crate +encodes for it with `-Zalways-encode-mir`, as `cargo check` encodes none. Measured +2026-11-20 on **fedora** the same way, the stand-in's native export from an emptied target +before (rust2 `8798a5d7`) and after this change, 10 rounds each, alternating, at a load +average of 9 to 19; medians: + +| export | wall s | CPU s | peak RSS | +|---|---|---|---| +| before | 23.0 | 101.8 | 896 MiB | +| after | 25.1 | 110.7 | 937 MiB | + +So leaves cost the export about 9 CPU seconds, 9%, and 5% of its peak memory, and the +crates' metadata grows from 135 to 228 MB. The flag alone, measured apart at rust2 +`8798a5d7` in 7 rounds at a load of 12 to 25, added 8 CPU seconds and 44 MiB, so nearly +all of it is the flag's: the proof walks only the bodies of methods whose signature a leaf +could have. CPU time ranged 95 to 117 s and 104 to 134 s between rounds, so its gap is +rough. Recording each crate's leaves in the driver as it compiles the crate would cost +less, but needs a store of facts keyed by each crate's build beside cargo's own, which +9 seconds does not repay. ### Lending returned bytes diff --git a/ffi/README.md b/ffi/README.md index 3cfaaee62..829322255 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -771,12 +771,15 @@ free-threaded build (3.13t, 3.14t), which the module refuses at import with an ` loads the library from beside itself: `lib.so`, `lib.dylib`, or `.dll`. Its glue converts each Python value to the C value and calls the C ABI function in-process, so a call is one crossing, which releases the GIL while Rust runs, -so Rust may call Python back from any thread meanwhile. A leaf keeps it: a read or write of -a primitive `pub` field of a `Send` object reached without a `Deref`, or a `PartialEq` or -`Hash` derived, or std's, down to primitives, which the export proves runs no code but -std's and the glue's, waits on no lock, and calls no Python, so it cannot deadlock on the -GIL (`Abi::leaf` in `src/abi.rs` gives the argument). A field read costs 26 ns that way, -against 63 releasing it ([the benchmark](../bench/ffi/README.md#leaf-calls)). +so Rust may call Python back from any thread meanwhile. A leaf keeps it: a `&self` or +`&mut self` method, or a read or write of a `pub` field, of a `Send` object, taking and +returning only scalars, whose body and each `Deref`'s on the way the export proves, from +their MIR, run no code but std's and the glue's in a bounded number of steps, or a +`PartialEq` or `Hash` derived, or std's, down to primitives. A leaf waits on no lock and +calls no Python, so it cannot deadlock on the GIL (`Abi::leaf` in `src/abi.rs` gives the +argument, and `src/leaf.rs` the proof). So `demand.start()`, which returns a field, costs +27 ns, against 65 releasing the GIL, and 0.1 us on four threads at once, against 1.8 +([the benchmark](../bench/ffi/README.md#leaf-calls)). Each function, method, and property but an `async def` is the extension's own, bound in the module or set on its class as it loads, so a call enters it with no Python frame between; the Python declares them under `typing.TYPE_CHECKING`, for type checkers. They @@ -1350,7 +1353,8 @@ the library's own URI, mapped to the library by a build hook or by `--native-ass into Dart meanwhile. Any other call runs on the isolate's thread, since nothing it waits on can call into Dart. A leaf, as Python keeps the GIL across, is a leaf call (`isLeaf`) to the C function on the isolate's thread, with no hop and no arena: a field read costs - 13 ns, against 31, and against 2 us while Rust holds a closure. A call that holds only + 13 ns, against 31, and against 2 us while Rust holds a closure, and `demand.start()` 16, + against 27. A call that holds only its receiver holds it with no arena either. An isolate may move between threads, so a value that is not `Send` is made on a home, a thread Rust owns, which runs each call on it. @@ -1427,9 +1431,10 @@ packs the api fixture's with npm, installs it into a project of its own, type-ch function, and each one a crate's `.init_array` static runs when the module loads, through every call, `dyn` implementation, function pointer, static, and drop it can reach, std's included, and into C and whatever Rust the C calls back, so a new std needs - no change here: every crate builds with `-Zalways-encode-mir`, std's from the dev - shell's MIR sysroot or else `-Zbuild-std`, which doubles the export's peak memory, as - [measured](../bench/ffi/README.md#the-exports-build-cost); a native export reads no MIR. + no change here: every crate builds with `-Zalways-encode-mir`, as every export's does + for its [leaves](#python), std's from the dev shell's MIR sysroot or else + `-Zbuild-std`, which doubles the export's peak memory, as + [measured](../bench/ffi/README.md#the-exports-build-cost). A C function or static no linked library defines, which would fail the module's link, is refused the same way, as is a call into wasm-bindgen, whose imports on `wasm32-wasip1` compile to stubs that panic. `thread::Builder::spawn` and a socket's `connect` and `bind` diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index 083e2c25c..c7c66816d 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -2587,6 +2587,13 @@ impl Hooked { pub fn new(n: u64) -> Self { Self { n, gated: Gated(n) } } + + /// Its count, by a method that runs the hook first: no leaf call, though it returns + /// what a leaf would. + pub fn count(&self) -> u64 { + run_hook(); + self.n + } } /// A value whose `PartialEq`, written by hand, claims to be derived, as a procedural @@ -2672,6 +2679,76 @@ impl Plain { pinned: (-1, 'p'), } } + + /// Its count, by a method whose body only reads it: a leaf call. + pub fn count(&self) -> u64 { + self.n + } + + /// Set its count, by a method whose body only writes it: a leaf call. + pub fn recount(&mut self, n: u64) { + self.n = n; + } + + /// Count up to its count: a loop as long as the caller makes it, so no leaf call. + pub fn steps(&self) -> u64 { + let mut i = 0u64; + while i < self.n { + i = i.wrapping_add(1); + } + i + } + + /// How many locals have dropped, a static's count: no leaf call. + pub fn locals(&self) -> u32 { + LOCALS.load(std::sync::atomic::Ordering::Relaxed) + } +} + +/// A [`Plain`] behind a `Deref` and `DerefMut` that only borrow it, so its fields and +/// methods are leaf calls through it too. +pub struct Wrapped(Plain); + +impl Wrapped { + pub fn new(n: u64) -> Self { + Self(Plain::new(n, false)) + } +} + +impl std::ops::Deref for Wrapped { + type Target = Plain; + + fn deref(&self) -> &Plain { + &self.0 + } +} + +impl std::ops::DerefMut for Wrapped { + fn deref_mut(&mut self) -> &mut Plain { + &mut self.0 + } +} + +/// A [`Plain`] behind a `Deref` that runs the hook, so nothing reached through it is a +/// leaf call. +#[cfg(not(target_arch = "wasm32"))] +pub struct Guarded(Plain); + +#[cfg(not(target_arch = "wasm32"))] +impl Guarded { + pub fn new(n: u64) -> Self { + Self(Plain::new(n, false)) + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl std::ops::Deref for Guarded { + type Target = Plain; + + fn deref(&self) -> &Plain { + run_hook(); + &self.0 + } } /// A value whose derived `PartialEq` and `Hash` reach no user code but walk a string as diff --git a/ffi/src/abi.rs b/ffi/src/abi.rs index aabb51708..dedb8ef44 100644 --- a/ffi/src/abi.rs +++ b/ffi/src/abi.rs @@ -1290,9 +1290,14 @@ impl<'a> Abi<'a> { /// Whether a call of `function`, a method of `owner` if it has one, is a leaf: proven to /// run no code but the glue's, its runtime's, and std's, to wait on no lock, and to call /// into no binding. Python then keeps the GIL across it, and Dart makes it a leaf call, - /// which runs on the isolate's own thread with no thread hop. It is the read or write of a - /// primitive `pub` field of a `Send` object reached without a `Deref`, which no object - /// that is not `Send` may lend. + /// which runs on the isolate's own thread with no thread hop. It is a `&self` or + /// `&mut self` method, or the read or write of a `pub` field, of a `Send` object, which no + /// object that is not `Send` may lend, taking only scalars and returning one or nothing, whose Rust + /// [`Function::leaf`] proves: each body it runs, the method's and each `Deref`'s on the + /// way, calls only bodies proven the same way and core's intrinsics that only compute, + /// drops nothing whose drop runs other code, loops nowhere, recurses nowhere, asserts + /// nothing, which would run the panic hook on failure, and uses no static. Its MIR proves + /// it, which is the code that runs, not how its source looks or what an attribute claims. /// /// Why holding the GIL across one cannot deadlock: a deadlock needs the call to wait on /// another thread that waits on the GIL. A leaf's only shared state is the handle's @@ -1301,28 +1306,26 @@ impl<'a> Abi<'a> { /// Its value is `Send`, so its borrow runs no `Thread::own`, whose drain would drop what /// other threads queued of the thread's values that are not `Send`, by any `Drop`; a /// handle lent from another borrows that one too, so no owner up its chain of lenders - /// may be other than `Send` either. A field - /// reached through `Deref`, of an enum, or of anything but a primitive would run user - /// code to read, clone, or drop. So it ends in a bounded number of steps whoever holds - /// the GIL, and since it runs no Python, nothing in it needs the GIL either. + /// may be other than `Send` either. A body with no loop, no recursion, and no call but + /// to such bodies ends in a bounded number of steps whoever holds the GIL, and since it + /// runs no Python, nothing in it needs the GIL either. pub(crate) fn leaf(&self, function: &Function, owner: Option<&Type>) -> bool { let Some(Type::Object(i)) = owner else { return false; }; - let primitive = |ty: &Type| { - matches!( - ty, - Type::Bool | Type::Int(_) | Type::NonZero(_) | Type::F32 | Type::F64 | Type::Char - ) - }; - let field = match function.access { + let shape = match function.access { Access::Field { set: false, .. } => { - matches!(&function.ok, Type::Ref(_, ty) if primitive(ty)) && function.params.is_empty() + matches!(&function.ok, Type::Ref(_, ty) if ty.scalar()) && function.params.is_empty() + } + Access::Field { set: true, .. } => matches!(&function.params[..], [param] if param.ty.scalar()), + Access::Call => { + matches!(function.receiver, Some(Receiver::Ref | Receiver::Mut)) + && (function.ok.scalar() || matches!(function.ok, Type::Unit)) + && function.params.iter().all(|p| p.ty.scalar()) } - Access::Field { set: true, .. } => matches!(&function.params[..], [param] if primitive(¶m.ty)), _ => false, }; - field && !self.affine[*i] && function.derefs == 0 && function.err.is_none() && !function.future + shape && function.leaf && !self.affine[*i] && function.err.is_none() && !function.future } /// Whether `ty`'s `_eq`, or with `hash` its `_hash`, is a leaf, as [`Self::leaf`] diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 9e1fec7cc..4821ce2d7 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -295,6 +295,8 @@ struct Collector<'tcx> { /// Whether the type being mapped is only tried, as a candidate or before another rule, /// whose failure reaches no type. probing: std::cell::Cell, + /// The proofs of which calls are leaves. + leaves: crate::leaf::Leaves<'tcx>, api: Api, } @@ -450,6 +452,7 @@ pub(crate) fn collect<'tcx>(tcx: TyCtxt<'tcx>, facade: &Facade<'_>) -> Collected barred: barred.to_vec(), erring: Default::default(), probing: Default::default(), + leaves: crate::leaf::Leaves::new(tcx), api: Api { records: Vec::new(), enums: Vec::new(), @@ -2001,6 +2004,7 @@ impl<'tcx> Collector<'tcx> { lends: false, lends_mut: false, derefs: 0, + leaf: false, ties: false, access: Access::Parse, instance: None, @@ -2058,6 +2062,7 @@ impl<'tcx> Collector<'tcx> { lends: false, lends_mut: false, derefs: 0, + leaf: false, ties: false, access: Access::Text, instance: None, @@ -2504,7 +2509,7 @@ impl<'tcx> Collector<'tcx> { let self_ty = self.site_ty(&site); let chain = self.derefs(self_ty); if !chain.is_empty() { - chains.push((index, self.member_names(self_ty), chain)); + chains.push((index, self_ty, self.member_names(self_ty), chain)); } let shared = traits.clone && self.clone_shares(self.site_ty(&site), def_id); let object = &mut self.api.objects[index]; @@ -2528,8 +2533,8 @@ impl<'tcx> Collector<'tcx> { } } } - for (object, names, chain) in chains { - self.forward(object, names, chain, &records); + for (object, self_ty, names, chain) in chains { + self.forward(object, self_ty, names, chain, &records); } } @@ -2605,10 +2610,12 @@ impl<'tcx> Collector<'tcx> { /// Give object `object` the methods and field accessors of each type it derefs to, as /// Rust's auto-deref reaches them: each one through `&self`, and through `&mut self` while /// every `Deref` on the way is a `DerefMut`, unless a nearer type's member takes its name. - /// A target forwards what it exports itself, so its refusals hold here too. + /// A target forwards what it exports itself, so its refusals hold here too. A member is a + /// leaf where it is one on its type and each `Deref` on the way, from `self_ty`, is too. fn forward( &mut self, object: usize, + self_ty: Ty<'tcx>, mut names: (Vec, Vec), chain: Vec<(Option>, Ty<'tcx>, usize, bool)>, records: &rustc_data_structures::fx::FxHashMap>, @@ -2618,7 +2625,10 @@ impl<'tcx> Collector<'tcx> { (o.path.clone(), o.shown.clone()) }; let mut all = Vec::new(); + // The type each `Deref` on the way to this one derefs from. + let (mut from, mut froms) = (self_ty, Vec::new()); for (key, ty, derefs, mutable) in chain { + froms.push(from); let decl = key.and_then(|key| self.decls.get(&key).cloned()); // A member of a deprecated type leaves its type's deprecation to the type, which // the object reaching it does not carry: the member takes it on. @@ -2658,6 +2668,9 @@ impl<'tcx> Collector<'tcx> { _ => false, }) .map(|mut m| { + // The glue reaches a `&mut self` member, a setter's too, through `DerefMut`. + let exclusive = m.receiver == Some(Receiver::Mut); + m.leaf &= froms.iter().all(|&ty| self.leaves.deref(ty, exclusive)); let name = |p: &Path| p.last().expect("a method has a name").clone(); m.path = [&path[..], &[name(&m.path)]].concat(); m.shown = [&shown[..], &[name(&m.shown)]].concat(); @@ -2667,6 +2680,7 @@ impl<'tcx> Collector<'tcx> { }) .collect(); all.extend(forwarded); + from = ty; let (methods, fields) = self.member_names(ty); names.0.extend(methods); names.1.extend(fields); @@ -2869,6 +2883,12 @@ impl<'tcx> Collector<'tcx> { GenericArgKind::Const(_) => true, }); let ties = !independent && !self.lifetimes(ty).0.is_empty(); + // A `Copy` value's read and write run no code. + let copied = !held.has_param() + && tcx.type_is_copy_modulo_regions( + TypingEnv::fully_monomorphized(), + tcx.erase_and_anonymize_regions(held), + ); match mapped { Ok((get, set)) => { let accessor = |receiver, params, ok, set| Function { @@ -2892,6 +2912,7 @@ impl<'tcx> Collector<'tcx> { lends: false, lends_mut: false, derefs: 0, + leaf: copied, ties, access: Access::Field { set, @@ -3923,6 +3944,13 @@ impl<'tcx> Collector<'tcx> { ), ); } + // Proven only where the rest of a leaf holds, which costs nothing to check. + let leaf = matches!(receiver, Some(Receiver::Ref | Receiver::Mut)) + && !future + && err.is_none() + && ok.as_ref().is_some_and(|ok| ok.scalar() || matches!(ok, Type::Unit)) + && params.iter().all(|p| p.ty.scalar()) + && self.leaves.call(def_id, args); match (errs.is_empty(), ok) { (true, Some(ok)) => Ok(Function { path, @@ -3945,6 +3973,7 @@ impl<'tcx> Collector<'tcx> { lends, lends_mut, derefs: 0, + leaf, ties, access: Access::Call, instance, @@ -5825,6 +5854,7 @@ impl<'tcx> Collector<'tcx> { lends: false, lends_mut: false, derefs: 0, + leaf: false, ties: false, access: Access::Const, instance: None, diff --git a/ffi/src/driver.rs b/ffi/src/driver.rs index 245bedc69..4f1a815f0 100644 --- a/ffi/src/driver.rs +++ b/ffi/src/driver.rs @@ -34,6 +34,7 @@ pub(crate) fn run(args: Vec) -> ExitCode { }; } rust2_driver::rustc::run("rust2-ffi", args, |args, added| { + crate::leaf::flags(args, added); crate::wasm::flags(args, added)?; if let Some(walk) = crate::wasm::Walk::for_args(args)? { return Ok(Some(Box::new(walk))); diff --git a/ffi/src/ir.rs b/ffi/src/ir.rs index fed139c78..d61e96276 100644 --- a/ffi/src/ir.rs +++ b/ffi/src/ir.rs @@ -513,6 +513,12 @@ pub(crate) struct Function { /// the receiver's handle, each a `DerefMut` for `&mut self`, as Rust's auto-deref does. #[serde(default)] pub(crate) derefs: usize, + /// Whether the Rust a call runs is proven to run no code but std's and the glue's, in a + /// bounded number of steps: a field's read or write, or a method's body, and each + /// `Deref` on the way to it. [`crate::abi::Abi::leaf`] says what else a leaf needs. A + /// baseline written before it has none. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub(crate) leaf: bool, /// Whether a lifetime of an object it takes is `'static`, or names something else in the /// signature, so the value may outlive the call or carry its borrow out of it: a handle an /// exclusive lend returned fails it, since its borrow is the lend's. @@ -850,6 +856,14 @@ pub(crate) fn each(ty: &Type, f: &mut dyn FnMut(&Type)) { } impl Type { + /// Whether it crosses as one C scalar, which no code but the glue's lifts or lowers. + pub(crate) fn scalar(&self) -> bool { + matches!( + self, + Type::Bool | Type::Int(_) | Type::NonZero(_) | Type::F32 | Type::F64 | Type::Char + ) + } + /// Whether a parameter of this type is a value C passes in that Rust writes back /// through an out pointer: `&mut` of anything but an object, whose handle it borrows, /// or a reader, which C implements. diff --git a/ffi/src/leaf.rs b/ffi/src/leaf.rs new file mode 100644 index 000000000..de4cd6fb9 --- /dev/null +++ b/ffi/src/leaf.rs @@ -0,0 +1,283 @@ +//! Which calls are leaves, by their MIR: a body that runs no code but bodies proven the same +//! way and core's intrinsics that compute alone, in a bounded number of steps, as +//! [`crate::abi::Abi::leaf`] needs. + +use std::cell::RefCell; + +use rustc_attr_ir::LangItem; +use rustc_data_structures::fx::FxHashMap; +use rustc_hir::def::DefKind; +use rustc_hir::def_id::DefId; +use rustc_middle::mir::visit::Visitor; +use rustc_middle::mir::{self, BasicBlock, Location, Rvalue, TerminatorKind}; +use rustc_middle::ty::{self, Instance, InstanceKind, ShimKind, Ty, TyCtxt, TypeVisitableExt, TypingEnv}; +use rustc_span::DUMMY_SP; + +/// The flag each crate compiled for an export's target adds to rustc's: all of its MIR, which +/// `cargo check` encodes none of. Measured on moq's stand-in, it costs the export about 9% +/// of its CPU time and 5% of its peak memory (`bench/ffi/README.md`'s "The export's build +/// cost"). +const FLAG: &str = "-Zalways-encode-mir"; + +/// Add [`FLAG`] to rustc's `args` for a crate of the export's target, not a build script or +/// proc macro, which cargo compiles without `--target`. Cargo's query of the compiler, whose +/// answer it hashes into every unit's fingerprint, names it, so a target directory keeps +/// nothing compiled without it. +pub(crate) fn flags(args: &[String], added: &mut Vec) { + if args[1..] == ["-vV"] { + println!("rust2-ffi-leaf: {FLAG}"); + } + if args.iter().any(|arg| arg == "--target") { + added.push(FLAG.to_string()); + } +} + +/// The proofs of a crate's leaves. +pub(crate) struct Leaves<'tcx> { + tcx: TyCtxt<'tcx>, + /// Whether each instance met is a leaf: `None` while its walk is open. + seen: RefCell, Option>>, + /// How many walks are open, which the crate's recursion limit bounds. + depth: std::cell::Cell, +} + +impl<'tcx> Leaves<'tcx> { + pub(crate) fn new(tcx: TyCtxt<'tcx>) -> Self { + Self { + tcx, + seen: Default::default(), + depth: Default::default(), + } + } + + /// Whether a call of `def_id` at `args`, which name no parameter, is a leaf. + pub(crate) fn call(&self, def_id: DefId, args: ty::GenericArgs<'tcx>) -> bool { + let tcx = self.tcx; + if args.has_param() { + return false; + } + let args = tcx.erase_and_anonymize_regions(args); + match Instance::try_resolve(tcx, TypingEnv::fully_monomorphized(), def_id, args) { + Ok(Some(instance)) => self.instance(instance), + _ => false, + } + } + + /// Whether `::deref`, or with `mutable` `::deref_mut`, is a + /// leaf, as the glue calls it to reach a member of the type `ty` derefs to. + pub(crate) fn deref(&self, ty: Ty<'tcx>, mutable: bool) -> bool { + let tcx = self.tcx; + let lang = tcx.lang_items(); + let tr = match mutable { + true => lang.deref_mut_trait(), + false => lang.deref_trait(), + }; + // Each trait's one method. + let method = tr.and_then(|tr| tcx.associated_items(tr).in_definition_order().find(|i| i.is_fn())); + method.is_some_and(|m| self.call(m.def_id, tcx.mk_args(&[ty.into()]))) + } + + fn instance(&self, instance: Instance<'tcx>) -> bool { + if let Some(&found) = self.seen.borrow().get(&instance) { + // An open walk met again is recursion, which no bound on its steps holds. + return found.unwrap_or(false); + } + let depth = self.depth.get(); + if !self.tcx.recursion_limit().value_within_limit(depth) { + return false; + } + self.seen.borrow_mut().insert(instance, None); + self.depth.set(depth + 1); + let found = self.body(instance); + self.depth.set(depth); + self.seen.borrow_mut().insert(instance, Some(found)); + found + } + + fn body(&self, instance: Instance<'tcx>) -> bool { + let tcx = self.tcx; + match instance.def { + InstanceKind::Intrinsic(def_id) => return computes(tcx.item_name(def_id).as_str()), + InstanceKind::Item(def_id) => { + // A constructor only builds its value. + if matches!(tcx.def_kind(def_id), DefKind::Ctor(..)) { + return true; + } + // A foreign function, or one whose crate kept no MIR, as std's that is + // neither generic nor inline: what it runs is unknown. + if !tcx.is_mir_available(def_id) { + return false; + } + } + // Drop glue of a type with nothing to drop. + InstanceKind::Shim(ShimKind::DropGlue(_, None)) => return true, + // A trait object's method, an LLVM intrinsic, and a thread local's initializer: + // what each runs is unknown, or may be anything. + InstanceKind::Virtual(..) + | InstanceKind::LlvmIntrinsic(_) + | InstanceKind::Shim(ShimKind::ThreadLocal(_)) => return false, + // Every other shim's MIR rustc builds here, which the walk follows. + InstanceKind::Shim(_) => {} + } + let body = tcx.instance_mir(instance.def); + let blocks = &body.basic_blocks; + // A loop, of a lock's spin or a length the caller picks, bounds no number of steps. + let mut order = vec![usize::MAX; blocks.len()]; + for (at, &block) in blocks.reverse_postorder().iter().enumerate() { + order[block.index()] = at; + } + let reached = |block: BasicBlock| order[block.index()] != usize::MAX; + let env = TypingEnv::fully_monomorphized(); + let mono = |ty: Ty<'tcx>| { + instance.try_instantiate_mir_and_normalize_erasing_regions(tcx, env, ty::EarlyBinder::bind(tcx, ty)) + }; + for (block, data) in blocks.iter_enumerated() { + // Cleanup runs only as a call or a drop unwinds, which none a leaf makes does. + if data.is_cleanup || !reached(block) { + continue; + } + let terminator = data.terminator(); + let forward = terminator + .successors() + .all(|to| blocks[to].is_cleanup || order[to.index()] > order[block.index()]); + if !forward { + return false; + } + let ok = match &terminator.kind { + TerminatorKind::Goto { .. } + | TerminatorKind::SwitchInt { .. } + | TerminatorKind::Return + | TerminatorKind::Unreachable + | TerminatorKind::FalseEdge { .. } + | TerminatorKind::FalseUnwind { .. } => true, + TerminatorKind::Call { func, .. } | TerminatorKind::TailCall { func, .. } => { + match mono(func.ty(body, tcx)).map(|ty| *ty.kind()) { + Ok(ty::FnDef(def_id, args)) => args.no_bound_vars().is_some_and(|args| self.call(def_id, args)), + // A function pointer's callee is unknown. + _ => false, + } + } + TerminatorKind::Drop { place, .. } => match mono(place.ty(body, tcx).ty) { + Ok(ty) => self.drop(ty), + Err(_) => false, + }, + // An assertion that fails panics, which runs the panic hook. + TerminatorKind::Assert { .. } + | TerminatorKind::InlineAsm { .. } + | TerminatorKind::Yield { .. } + | TerminatorKind::CoroutineDrop + | TerminatorKind::UnwindResume + | TerminatorKind::UnwindTerminate(_) => false, + }; + if !ok { + return false; + } + } + // A static is shared state beyond the handle's borrow, which is a leaf's only one. + let mut statics = Statics { tcx, found: false }; + for (block, data) in blocks.iter_enumerated() { + if !data.is_cleanup && reached(block) { + statics.visit_basic_block_data(block, data); + } + } + !statics.found + } + + /// Whether dropping a value of `ty` is a leaf: nothing to drop, or drop glue proven so. + fn drop(&self, ty: Ty<'tcx>) -> bool { + let tcx = self.tcx; + if !ty.needs_drop(tcx, TypingEnv::fully_monomorphized()) { + return true; + } + let glue = tcx.require_lang_item(LangItem::DropGlue, DUMMY_SP); + self.call(glue, tcx.mk_args(&[ty.into()])) + } +} + +/// Whether core's intrinsic `name` only computes: it runs no other code, waits on nothing, +/// and cannot panic. Any other, such as `catch_unwind`, is no leaf. +fn computes(name: &str) -> bool { + name.starts_with("atomic_") + || matches!( + name, + "add_with_overflow" + | "aggregate_raw_ptr" + | "align_of" + | "align_of_val" + | "arith_offset" + | "assume" + | "bitreverse" + | "black_box" + | "bswap" + | "carrying_mul_add" + | "cold_path" + | "copy" + | "copy_nonoverlapping" + | "ctlz" + | "ctlz_nonzero" + | "ctpop" + | "cttz" + | "cttz_nonzero" + | "discriminant_value" + | "disjoint_bitor" + | "exact_div" + | "forget" + | "likely" + | "mul_with_overflow" + | "needs_drop" + | "offset" + | "overflow_checks" + | "ptr_guaranteed_cmp" + | "ptr_mask" + | "ptr_metadata" + | "ptr_offset_from" + | "ptr_offset_from_unsigned" + | "read_via_copy" + | "rotate_left" + | "rotate_right" + | "saturating_add" + | "saturating_sub" + | "select_unpredictable" + | "size_of" + | "size_of_val" + | "slice_get_unchecked" + | "sub_with_overflow" + | "three_way_compare" + | "transmute" + | "transmute_unchecked" + | "typed_swap_nonoverlapping" + | "ub_checks" + | "unchecked_add" + | "unchecked_div" + | "unchecked_mul" + | "unchecked_rem" + | "unchecked_shl" + | "unchecked_shr" + | "unchecked_sub" + | "unlikely" + | "unreachable" + | "variant_count" + | "wrapping_add" + | "wrapping_mul" + | "wrapping_sub" + | "write_bytes" + | "write_via_move" + ) +} + +/// Finds a use of a static, or of a thread local. +struct Statics<'tcx> { + tcx: TyCtxt<'tcx>, + found: bool, +} + +impl<'tcx> Visitor<'tcx> for Statics<'tcx> { + fn visit_const_operand(&mut self, constant: &mir::ConstOperand<'tcx>, _: Location) { + self.found |= constant.check_static_ptr(self.tcx).is_some(); + } + + fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) { + self.found |= matches!(rvalue, Rvalue::ThreadLocalRef(_)); + self.super_rvalue(rvalue, location); + } +} diff --git a/ffi/src/lock.rs b/ffi/src/lock.rs index f734bfec4..fdebccb97 100644 --- a/ffi/src/lock.rs +++ b/ffi/src/lock.rs @@ -896,6 +896,7 @@ mod tests { lends: false, lends_mut: false, derefs: 0, + leaf: false, ties: false, access: Access::Call, instance: None, diff --git a/ffi/src/main.rs b/ffi/src/main.rs index 72e581fd6..eb06dc6d7 100644 --- a/ffi/src/main.rs +++ b/ffi/src/main.rs @@ -45,6 +45,7 @@ mod help; mod ir; mod js; mod kotlin; +mod leaf; mod lock; mod merge; mod python; diff --git a/ffi/src/merge.rs b/ffi/src/merge.rs index e28e59615..933fe88a9 100644 --- a/ffi/src/merge.rs +++ b/ffi/src/merge.rs @@ -208,6 +208,8 @@ pub(crate) fn bare_function(f: &Function) -> Function { f.docs.clear(); f.deprecated = None; f.on = On::ALL; + // Merged apart, as a trait's leaves are. + f.leaf = false; }) } @@ -582,6 +584,7 @@ impl Merged { self.differ(what, (ours[at].on, ours[at].span), (function.on, function.span)); } ours[at].on.0 |= function.on.0; + ours[at].leaf &= function.leaf; linked(&mut ours[at].docs, function.docs); } ours diff --git a/ffi/src/wasm.rs b/ffi/src/wasm.rs index 24f89c67d..311581686 100644 --- a/ffi/src/wasm.rs +++ b/ffi/src/wasm.rs @@ -60,10 +60,10 @@ pub fn host(target: &str) -> Option<&'static Host> { HOSTS.iter().find(|host| host.target == target) } -/// The rustc flags of every crate compiled for a target with a host: all of its MIR, which -/// `cargo check` encodes for generic and inline functions alone, with each call where the -/// source makes it, as inlining would not keep it. -const MIR: [&str; 2] = ["-Zalways-encode-mir", "-Zinline-mir=no"]; +/// The rustc flags of every crate compiled for a target with a host, beside the MIR +/// [`crate::leaf::flags`] has every crate encode: each call where the source makes it, as +/// inlining would not keep it. +const MIR: [&str; 1] = ["-Zinline-mir=no"]; /// The std crates `-Zbuild-std` checks for a target with a host when no sysroot is set, /// which flake.nix's sysroot holds too. diff --git a/ffi/surface/api/c.h b/ffi/surface/api/c.h index f9f324f56..3506c58fb 100644 --- a/ffi/surface/api/c.h +++ b/ffi/surface/api/c.h @@ -7,7 +7,7 @@ #ifdef __cplusplus extern "C" { #endif -#define API_CONTRACT ((uint64_t)0x4ef55d1d8a723c39ULL) +#define API_CONTRACT ((uint64_t)0x16bb8402bd12e81eULL) uint64_t api_contract(void); uint32_t api_target(void); typedef int32_t api_status; @@ -104,6 +104,7 @@ typedef struct api_Waiter api_Waiter; typedef struct api_Logger api_Logger; typedef struct api_Journal api_Journal; typedef struct api_Local api_Local; +typedef struct api_Wrapped api_Wrapped; typedef struct api_LocalWaiter api_LocalWaiter; typedef struct api_Retry api_Retry; typedef struct api_Digest api_Digest; @@ -162,6 +163,7 @@ typedef struct api_tls_Codec api_tls_Codec; typedef struct api_Spawned api_Spawned; typedef struct api_LogThread api_LogThread; typedef struct api_Pinned api_Pinned; +typedef struct api_Guarded api_Guarded; typedef struct api_Hooked api_Hooked; typedef struct api_Forged api_Forged; typedef struct api_Part api_Part; @@ -1547,6 +1549,17 @@ api_poll api_Local_poll_count_poll(api_Local_poll_count_future *future, api_wake void api_Local_poll_count_future_free(api_Local_poll_count_future *future); uint64_t api_Local_thread_number(const api_Local *self, api_status *status); bool api_Local_on_own_thread(const api_Local *self, api_status *status); +void api_Wrapped_free(api_Wrapped *self); +void api_Wrapped_drop(api_Wrapped *self, api_status *status); +api_Wrapped *api_Wrapped_new(uint64_t n); +uint64_t api_Wrapped_n_get(const api_Wrapped *self, api_status *status); +void api_Wrapped_n_set(api_Wrapped *self, uint64_t value, api_status *status); +bool api_Wrapped_on_get(const api_Wrapped *self, api_status *status); +void api_Wrapped_on_set(api_Wrapped *self, bool value, api_status *status); +uint64_t api_Wrapped_count(const api_Wrapped *self, api_status *status); +void api_Wrapped_recount(api_Wrapped *self, uint64_t n, api_status *status); +uint64_t api_Wrapped_steps(const api_Wrapped *self, api_status *status); +uint32_t api_Wrapped_locals(const api_Wrapped *self, api_status *status); void api_LocalWaiter_free(api_LocalWaiter *self); void api_LocalWaiter_drop(api_LocalWaiter *self, api_status *status); api_LocalWaiter *api_LocalWaiter_new(api_waker waker_); @@ -1870,6 +1883,10 @@ void api_Plain_n_set(api_Plain *self, uint64_t value, api_status *status); bool api_Plain_on_get(const api_Plain *self, api_status *status); void api_Plain_on_set(api_Plain *self, bool value, api_status *status); api_Plain *api_Plain_new(uint64_t n, bool on); +uint64_t api_Plain_count(const api_Plain *self, api_status *status); +void api_Plain_recount(api_Plain *self, uint64_t n, api_status *status); +uint64_t api_Plain_steps(const api_Plain *self, api_status *status); +uint32_t api_Plain_locals(const api_Plain *self, api_status *status); void api_Labeled_free(api_Labeled *self); bool api_Labeled_eq(const api_Labeled *a, const api_Labeled *b); uint64_t api_Labeled_hash(const api_Labeled *self); @@ -1999,6 +2016,13 @@ void api_Pinned_value_set(api_Pinned *self, uint64_t value, api_status *status); api_Pinned *api_Pinned_new(uint64_t value); api_Pinned *api_Pinned_new_homed(uint64_t value); api_Part *api_Pinned_part(const api_Pinned *self, api_status *status); +void api_Guarded_free(api_Guarded *self); +api_Guarded *api_Guarded_new(uint64_t n); +uint64_t api_Guarded_n_get(const api_Guarded *self); +bool api_Guarded_on_get(const api_Guarded *self); +uint64_t api_Guarded_count(const api_Guarded *self); +uint64_t api_Guarded_steps(const api_Guarded *self); +uint32_t api_Guarded_locals(const api_Guarded *self); void api_Hooked_free(api_Hooked *self); void api_Hooked_drop(api_Hooked *self, api_status *status); bool api_Hooked_eq(const api_Hooked *a, const api_Hooked *b, api_status *status); @@ -2006,6 +2030,7 @@ api_buf api_Hooked_debug(const api_Hooked *self, api_status *status); uint64_t api_Hooked_n_get(const api_Hooked *self, api_status *status); void api_Hooked_n_set(api_Hooked *self, uint64_t value, api_status *status); api_Hooked *api_Hooked_new(uint64_t n); +uint64_t api_Hooked_count(const api_Hooked *self, api_status *status); void api_Forged_free(api_Forged *self); void api_Forged_drop(api_Forged *self, api_status *status); bool api_Forged_eq(const api_Forged *a, const api_Forged *b, api_status *status); diff --git a/ffi/surface/api/cpp.hpp b/ffi/surface/api/cpp.hpp index 9d7c0140b..4d4cbffcf 100644 --- a/ffi/surface/api/cpp.hpp +++ b/ffi/surface/api/cpp.hpp @@ -163,6 +163,19 @@ namespace api { RUST2_FFI_CALLABLE ::std::uint64_t thread_number() const; RUST2_FFI_CALLABLE bool on_own_thread() const; }; + class RUST2_FFI_CONSUMABLE Wrapped { + RUST2_FFI_UNCONSUMED Wrapped(Wrapped &&other RUST2_FFI_MOVED_FROM) noexcept = default; + Wrapped &operator=(Wrapped &&other) noexcept = default; + static ::api::Wrapped new_(::std::uint64_t n); + RUST2_FFI_CALLABLE ::std::uint64_t n_get() const; + RUST2_FFI_CALLABLE void n_set(::std::uint64_t value); + RUST2_FFI_CALLABLE bool on_get() const; + RUST2_FFI_CALLABLE void on_set(bool value); + RUST2_FFI_CALLABLE ::std::uint64_t count() const; + RUST2_FFI_CALLABLE void recount(::std::uint64_t n); + RUST2_FFI_CALLABLE ::std::uint64_t steps() const; + RUST2_FFI_CALLABLE ::std::uint32_t locals() const; + }; class RUST2_FFI_CONSUMABLE LocalWaiter { RUST2_FFI_UNCONSUMED LocalWaiter(LocalWaiter &&other RUST2_FFI_MOVED_FROM) noexcept = default; LocalWaiter &operator=(LocalWaiter &&other) noexcept = default; @@ -500,6 +513,10 @@ namespace api { RUST2_FFI_CALLABLE bool on_get() const; RUST2_FFI_CALLABLE void on_set(bool value); static ::api::Plain new_(::std::uint64_t n, bool on); + RUST2_FFI_CALLABLE ::std::uint64_t count() const; + RUST2_FFI_CALLABLE void recount(::std::uint64_t n); + RUST2_FFI_CALLABLE ::std::uint64_t steps() const; + RUST2_FFI_CALLABLE ::std::uint32_t locals() const; }; class RUST2_FFI_CONSUMABLE Labeled { RUST2_FFI_UNCONSUMED Labeled(Labeled &&other RUST2_FFI_MOVED_FROM) noexcept = default; @@ -626,6 +643,16 @@ namespace api { static ::api::Pinned new_(::std::uint64_t value); RUST2_FFI_CALLABLE ::api::Part part() const; }; + class RUST2_FFI_CONSUMABLE Guarded { + RUST2_FFI_UNCONSUMED Guarded(Guarded &&other RUST2_FFI_MOVED_FROM) noexcept = default; + Guarded &operator=(Guarded &&other) noexcept = default; + static ::api::Guarded new_(::std::uint64_t n); + RUST2_FFI_CALLABLE ::std::uint64_t n_get() const; + RUST2_FFI_CALLABLE bool on_get() const; + RUST2_FFI_CALLABLE ::std::uint64_t count() const; + RUST2_FFI_CALLABLE ::std::uint64_t steps() const; + RUST2_FFI_CALLABLE ::std::uint32_t locals() const; + }; class RUST2_FFI_CONSUMABLE Hooked { RUST2_FFI_UNCONSUMED Hooked(Hooked &&other RUST2_FFI_MOVED_FROM) noexcept = default; Hooked &operator=(Hooked &&other) noexcept = default; @@ -635,6 +662,7 @@ namespace api { RUST2_FFI_CALLABLE ::std::uint64_t n_get() const; RUST2_FFI_CALLABLE void n_set(::std::uint64_t value); static ::api::Hooked new_(::std::uint64_t n); + RUST2_FFI_CALLABLE ::std::uint64_t count() const; }; class RUST2_FFI_CONSUMABLE Forged { RUST2_FFI_UNCONSUMED Forged(Forged &&other RUST2_FFI_MOVED_FROM) noexcept = default; @@ -2050,6 +2078,7 @@ namespace api { class Logger; class Journal; class Local; + class Wrapped; class LocalWaiter; class Retry; class Digest; @@ -2108,6 +2137,7 @@ namespace api { class Spawned; class LogThread; class Pinned; + class Guarded; class Hooked; class Forged; class Part; diff --git a/ffi/surface/api/dart.dart b/ffi/surface/api/dart.dart index 2fa438543..639cbfb14 100644 --- a/ffi/surface/api/dart.dart +++ b/ffi/surface/api/dart.dart @@ -1080,6 +1080,17 @@ final class Local extends _Object { U64 threadNumber(); bool onOwnThread(); } +final class Wrapped extends _Object { + factory Wrapped(U64 n); + U64 get nGet; + void nSet(U64 value); + bool get onGet; + void onSet(bool value); + U64 count(); + void recount(U64 n); + U64 steps(); + int locals(); +} final class LocalWaiter extends _Object { factory LocalWaiter(void Function() waker); static Cancelable pollReady(int n); @@ -1356,6 +1367,10 @@ final class Plain extends _Object { bool get onGet; void onSet(bool value); factory Plain(U64 n, bool on); + U64 count(); + void recount(U64 n); + U64 steps(); + int locals(); } final class Labeled extends _Object { String debug(); @@ -1482,6 +1497,14 @@ final class Pinned extends _Object { factory Pinned(U64 value); Part part(); } +final class Guarded extends _Object { + factory Guarded(U64 n); + U64 get nGet; + bool get onGet; + U64 count(); + U64 steps(); + int locals(); +} final class Hooked extends _Object { String debug(); @override bool operator ==(Object other); @@ -1489,6 +1512,7 @@ final class Hooked extends _Object { U64 get nGet; void nSet(U64 value); factory Hooked(U64 n); + U64 count(); } final class Forged extends _Object { String debug(); diff --git a/ffi/surface/api/go.txt b/ffi/surface/api/go.txt index 52d82c018..d5a54727d 100644 --- a/ffi/surface/api/go.txt +++ b/ffi/surface/api/go.txt @@ -906,6 +906,16 @@ func (self *Gauge) Later(ctx context.Context) (uint64, error) func (self *Gauge) Level() (uint64, error) func (self *Gauge) Reaches(ctx context.Context, this uint64) (bool, error) func (self *Gauge) Set(level uint64) error +type Guarded struct { + Handle_ *p_rt.Handle_ +} +func NewGuarded(n uint64) (*Guarded, error) +func (self *Guarded) Close() error +func (self *Guarded) Count() (uint64, error) +func (self *Guarded) Locals() (uint32, error) +func (self *Guarded) NGet() (uint64, error) +func (self *Guarded) OnGet() (bool, error) +func (self *Guarded) Steps() (uint64, error) type Handle struct { Handle_ *p_rt.Handle_ } @@ -942,6 +952,7 @@ type Hooked struct { } func NewHooked(n uint64) (*Hooked, error) func (self *Hooked) Close() error +func (self *Hooked) Count() (uint64, error) func (self *Hooked) Equal(other *Hooked) (bool, error) func (self *Hooked) GoString() string func (self *Hooked) NGet() (uint64, error) @@ -1376,12 +1387,16 @@ type Plain struct { } func NewPlain(n uint64, on bool) *Plain func (self *Plain) Close() error +func (self *Plain) Count() (uint64, error) func (self *Plain) Equal(other *Plain) (bool, error) func (self *Plain) GoString() string +func (self *Plain) Locals() (uint32, error) func (self *Plain) NGet() (uint64, error) func (self *Plain) NSet(value uint64) error func (self *Plain) OnGet() (bool, error) func (self *Plain) OnSet(value bool) error +func (self *Plain) Recount(n uint64) error +func (self *Plain) Steps() (uint64, error) type Platform interface { } func NewPlatform() Platform @@ -1777,6 +1792,19 @@ type WrapU32 struct { } func (self WrapU32) Equal(other WrapU32) bool func (self WrapU32) GoString() string +type Wrapped struct { + Handle_ *p_rt.Handle_ +} +func NewWrapped(n uint64) *Wrapped +func (self *Wrapped) Close() error +func (self *Wrapped) Count() (uint64, error) +func (self *Wrapped) Locals() (uint32, error) +func (self *Wrapped) NGet() (uint64, error) +func (self *Wrapped) NSet(value uint64) error +func (self *Wrapped) OnGet() (bool, error) +func (self *Wrapped) OnSet(value bool) error +func (self *Wrapped) Recount(n uint64) error +func (self *Wrapped) Steps() (uint64, error) package core // import "api/core" diff --git a/ffi/surface/api/kotlin.kt b/ffi/surface/api/kotlin.kt index 0e7b7336c..f2797498d 100644 --- a/ffi/surface/api/kotlin.kt +++ b/ffi/surface/api/kotlin.kt @@ -702,6 +702,20 @@ class Local internal constructor(raw: Long, lent: Boolean = false) : AutoCloseab @kotlin.jvm.JvmStatic fun new(): api.Local } } +class Wrapped internal constructor(raw: Long, lent: Boolean = false) : AutoCloseable { + override fun close() + val nGet: kotlin.ULong + fun nSet(value: kotlin.ULong) + val onGet: kotlin.Boolean + fun onSet(value: kotlin.Boolean) + fun count(): kotlin.ULong + fun recount(n: kotlin.ULong) + fun steps(): kotlin.ULong + fun locals(): kotlin.UInt + companion object { + @kotlin.jvm.JvmStatic fun new(n: kotlin.ULong): api.Wrapped + } +} class LocalWaiter internal constructor(raw: Long, lent: Boolean = false) : AutoCloseable { override fun close() companion object { @@ -1074,6 +1088,10 @@ class Plain internal constructor(raw: Long, lent: Boolean = false) : AutoCloseab fun nSet(value: kotlin.ULong) val onGet: kotlin.Boolean fun onSet(value: kotlin.Boolean) + fun count(): kotlin.ULong + fun recount(n: kotlin.ULong) + fun steps(): kotlin.ULong + fun locals(): kotlin.UInt companion object { @kotlin.jvm.JvmStatic fun new(n: kotlin.ULong, on: kotlin.Boolean): api.Plain } @@ -1255,6 +1273,17 @@ class Pinned internal constructor(raw: Long, lent: Boolean = false) : AutoClosea @kotlin.jvm.JvmStatic fun new(value: kotlin.ULong): api.Pinned } } +class Guarded internal constructor(raw: Long, lent: Boolean = false) : AutoCloseable { + override fun close() + val nGet: kotlin.ULong + val onGet: kotlin.Boolean + fun count(): kotlin.ULong + fun steps(): kotlin.ULong + fun locals(): kotlin.UInt + companion object { + @kotlin.jvm.JvmStatic fun new(n: kotlin.ULong): api.Guarded + } +} class Hooked internal constructor(raw: Long, lent: Boolean = false) : AutoCloseable { override fun close() fun debug(): kotlin.String @@ -1262,6 +1291,7 @@ class Hooked internal constructor(raw: Long, lent: Boolean = false) : AutoClosea override fun hashCode(): kotlin.Int val nGet: kotlin.ULong fun nSet(value: kotlin.ULong) + fun count(): kotlin.ULong companion object { @kotlin.jvm.JvmStatic fun new(n: kotlin.ULong): api.Hooked } diff --git a/ffi/surface/api/python.pyi b/ffi/surface/api/python.pyi index baf9647c9..a2c1caf41 100644 --- a/ffi/surface/api/python.pyi +++ b/ffi/surface/api/python.pyi @@ -863,6 +863,19 @@ class Local(_n.Object): def visit(self, f: _typing.Callable[[], _int]) -> _int: ... def thread_number(self) -> _int: ... def on_own_thread(self) -> _bool: ... +class Wrapped(_n.Object): + @_staticmethod + def new(n: _int) -> Wrapped: ... + @_property + def n_get(self) -> _int: ... + def n_set(self, value: _int) -> None: ... + @_property + def on_get(self) -> _bool: ... + def on_set(self, value: _bool) -> None: ... + def count(self) -> _int: ... + def recount(self, n: _int) -> None: ... + def steps(self) -> _int: ... + def locals(self) -> _int: ... class LocalWaiter(_n.Object): @_staticmethod async def poll_ready(n: _int) -> _int: ... @@ -1172,6 +1185,10 @@ class Plain(_n.Object): def on_set(self, value: _bool) -> None: ... @_staticmethod def new(n: _int, on: _bool) -> Plain: ... + def count(self) -> _int: ... + def recount(self, n: _int) -> None: ... + def steps(self) -> _int: ... + def locals(self) -> _int: ... class Labeled(_n.Object): def __eq__(self, other: _object) -> _bool: ... def __repr__(self) -> _str: ... @@ -1293,6 +1310,16 @@ class Pinned(_n.Object): @_staticmethod def new(value: _int) -> Pinned: ... def part(self) -> Part: ... +class Guarded(_n.Object): + @_staticmethod + def new(n: _int) -> Guarded: ... + @_property + def n_get(self) -> _int: ... + @_property + def on_get(self) -> _bool: ... + def count(self) -> _int: ... + def steps(self) -> _int: ... + def locals(self) -> _int: ... class Hooked(_n.Object): def __eq__(self, other: _object) -> _bool: ... def __repr__(self) -> _str: ... @@ -1301,6 +1328,7 @@ class Hooked(_n.Object): def n_set(self, value: _int) -> None: ... @_staticmethod def new(n: _int) -> Hooked: ... + def count(self) -> _int: ... class Forged(_n.Object): def __eq__(self, other: _object) -> _bool: ... def __repr__(self) -> _str: ... diff --git a/ffi/surface/api/swift.swift b/ffi/surface/api/swift.swift index add1dac10..c6ff2a3c5 100644 --- a/ffi/surface/api/swift.swift +++ b/ffi/surface/api/swift.swift @@ -899,6 +899,17 @@ public struct Local: ~Copyable { @inlinable public func threadNumber() throws -> Swift.UInt64 @inlinable public func onOwnThread() throws -> Swift.Bool } +public struct Wrapped: ~Copyable, @unchecked Sendable { + @inlinable public static func new(_ n: Swift.UInt64) -> Wrapped + @inlinable public var nGet: Swift.UInt64 { get } + @inlinable public mutating func nSet(_ value: Swift.UInt64) throws + @inlinable public var onGet: Swift.Bool { get } + @inlinable public mutating func onSet(_ value: Swift.Bool) throws + @inlinable public func count() throws -> Swift.UInt64 + @inlinable public mutating func recount(_ n: Swift.UInt64) throws + @inlinable public func steps() throws -> Swift.UInt64 + @inlinable public func locals() throws -> Swift.UInt32 +} public struct LocalWaiter: ~Copyable { @inlinable public static func new(_ waker: @escaping @Sendable () -> Void) -> LocalWaiter @inlinable nonisolated(nonsending) public static func pollReady(_ n: Swift.UInt32) async throws -> Swift.UInt32 @@ -1176,6 +1187,10 @@ public struct Plain: ~Copyable, @unchecked Sendable { @inlinable public var onGet: Swift.Bool { get } @inlinable public mutating func onSet(_ value: Swift.Bool) throws @inlinable public static func new(_ n: Swift.UInt64, _ on: Swift.Bool) -> Plain + @inlinable public func count() throws -> Swift.UInt64 + @inlinable public mutating func recount(_ n: Swift.UInt64) throws + @inlinable public func steps() throws -> Swift.UInt64 + @inlinable public func locals() throws -> Swift.UInt32 } public struct Labeled: ~Copyable, @unchecked Sendable { @inlinable public var debugDescription: Swift.String { get } @@ -1307,12 +1322,21 @@ public struct Pinned: ~Copyable { @inlinable public static func new(_ value: Swift.UInt64) throws -> Pinned @inlinable public func part() throws -> Part } +public struct Guarded: ~Copyable, @unchecked Sendable { + @inlinable public static func new(_ n: Swift.UInt64) throws -> Guarded + @inlinable public func nGet() throws -> Swift.UInt64 + @inlinable public func onGet() throws -> Swift.Bool + @inlinable public func count() throws -> Swift.UInt64 + @inlinable public func steps() throws -> Swift.UInt64 + @inlinable public func locals() throws -> Swift.UInt32 +} public struct Hooked: ~Copyable, @unchecked Sendable { @inlinable public var debugDescription: Swift.String { get } @inlinable public static func == (a: borrowing Hooked, b: borrowing Hooked) throws -> Swift.Bool @inlinable public func nGet() throws -> Swift.UInt64 @inlinable public mutating func nSet(_ value: Swift.UInt64) throws @inlinable public static func new(_ n: Swift.UInt64) throws -> Hooked + @inlinable public func count() throws -> Swift.UInt64 } public struct Forged: ~Copyable, @unchecked Sendable { @inlinable public var debugDescription: Swift.String { get } diff --git a/ffi/surface/api/web.d.ts b/ffi/surface/api/web.d.ts index 1e4f4ce9f..ce5c49e08 100644 --- a/ffi/surface/api/web.d.ts +++ b/ffi/surface/api/web.d.ts @@ -1066,6 +1066,10 @@ export declare function nSet(self: Plain, value: rt.u64): void; export declare function onGet(self: Plain): boolean; export declare function onSet(self: Plain, value: boolean): void; export declare function new$(n: rt.u64, on: boolean): Plain; +export declare function count(self: Plain): rt.u64; +export declare function recount(self: Plain, n: rt.u64): void; +export declare function steps(self: Plain): rt.u64; +export declare function locals(self: Plain): number; export { new$ as new }; // Platform.ts @@ -1590,6 +1594,20 @@ export type WrapU32 = { export declare function debug(self: WrapU32): string; export declare function eq(a: WrapU32, b: WrapU32): boolean; +// Wrapped.ts +import * as rt from "./rt.ts"; +export type Wrapped = rt.Handle<"Wrapped">; +export declare function new$(n: rt.u64): Wrapped; +export declare function nGet(self: Wrapped): rt.u64; +export declare function nSet(self: Wrapped, value: rt.u64): void; +export declare function onGet(self: Wrapped): boolean; +export declare function onSet(self: Wrapped, value: boolean): void; +export declare function count(self: Wrapped): rt.u64; +export declare function recount(self: Wrapped, n: rt.u64): void; +export declare function steps(self: Wrapped): rt.u64; +export declare function locals(self: Wrapped): number; +export { new$ as new }; + // glue.ts import * as rt from "./rt.ts"; import type { A } from "./A.ts"; @@ -1772,6 +1790,7 @@ export declare const k_Url: rt.Kind; export declare const k_Verbosity: rt.Kind; export declare const k_Waiter: rt.Kind; export declare const k_Worker: rt.Kind; +export declare const k_Wrapped: rt.Kind; export declare const k_c: rt.Kind; export declare const k_clash_Empty_string: rt.Kind; export declare const k_clash_Seed: rt.Kind; diff --git a/ffi/tests/api.dart b/ffi/tests/api.dart index ca4ef35d4..b7134e1f3 100644 --- a/ffi/tests/api.dart +++ b/ffi/tests/api.dart @@ -1077,6 +1077,13 @@ Future leaf() async { check(plain.nGet == api.U64(4) && plain.onGet, 'a leaf getter reads what a leaf setter wrote'); check(plain == api.Plain(api.U64(4), true) && plain != api.Plain(api.U64(4), false), 'a leaf equality'); check(plain.hashCode == api.Plain(api.U64(4), true).hashCode, 'a leaf hash'); + plain.recount(api.U64(5)); + check(plain.count() == api.U64(5), 'a leaf method reads what a leaf method wrote'); + check(plain.steps() == api.U64(5), 'a method that loops'); + final wrapped = api.Wrapped(api.U64(3)); + wrapped.nSet(api.U64(4)); + check(wrapped.nGet == api.U64(4) && wrapped.count() == api.U64(4), 'a leaf through a Deref'); + wrapped.close(); // A walk of a string the caller sized, which a leaf call would make the collector wait on. final labeled = api.Labeled('a' * 100); check(labeled == api.Labeled('a' * 100) && labeled != api.Labeled('b'), 'a served equality over a string'); @@ -1098,6 +1105,12 @@ Future leaf() async { check(pinned.valueGet == api.U64(5), 'a getter of a value kept on its thread'); pinned.close(); check(hooked == 3, 'a drop on a home serves the isolate'); + check(api.Hooked(api.U64(1)).count() == api.U64(1), 'a hooked method'); + check(hooked == 4, 'a hooked method serves the isolate'); + final guarded = api.Guarded(api.U64(2)); + check(guarded.nGet == api.U64(2) && guarded.count() == api.U64(2), 'a hooked Deref'); + check(hooked == 6, 'a hooked Deref serves the isolate'); + guarded.close(); api.unhook(); print('leaf ok'); } diff --git a/ffi/tests/api.py b/ffi/tests/api.py index 026c74951..cf0c3565b 100644 --- a/ffi/tests/api.py +++ b/ffi/tests/api.py @@ -1282,6 +1282,12 @@ def leaf(): check(plain.n_get == 4 and plain.on_get, "a leaf getter reads what a leaf setter wrote") check(plain == api.Plain.new(4, True) and plain != api.Plain.new(4, False), "a leaf equality") check(hash(plain) == hash(api.Plain.new(4, True)), "a leaf hash") + plain.recount(5) + check(plain.count() == 5, "a leaf method reads what a leaf method wrote") + check(plain.steps() == 5, "a method that loops") + wrapped = api.Wrapped.new(3) + wrapped.n_set(4) + check(wrapped.n_get == 4 and wrapped.count() == 4, "a leaf through a Deref") labeled = api.Labeled.new("a" * 100) check(labeled == api.Labeled.new("a" * 100) and labeled != api.Labeled.new("b"), "a leaf equality over a string") check(hash(labeled) == hash(api.Labeled.new("a" * 100)), "a leaf hash over a string") @@ -1312,6 +1318,12 @@ def leaf(): thread.join() count = len(hooked) check(use() and len(hooked) == count + 1, "a use of a part that drains releases the GIL") + count = len(hooked) + check(api.Hooked.new(1).count() == 1 and len(hooked) == count + 1, "a hooked method") + check(hooked[-1] != threading.get_ident(), "a hooked method releases the GIL") + guarded = api.Guarded.new(2) + check(guarded.n_get == 2 and guarded.count() == 2, "a hooked Deref") + check(len(hooked) == count + 3, "a hooked Deref releases the GIL") api.unhook() del part del pinned diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 35d53fe40..213d37b09 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -2613,10 +2613,11 @@ fn api_dart() { writes: &[], }; step.run(Command::new("dart").args(["analyze", "--fatal-infos"]).arg(&generated)); - // 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 - // picks, which would stall the isolate group's collector until it returns. + // What looks like a leaf but reaches user code, loops, or reads a static is no leaf + // call. The script catches a hand-written `PartialEq`, method, or `Deref`; 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 picks, which would stall the isolate + // group's collector until it returns. let code = std::fs::read_to_string(generated.join("api.dart")).unwrap(); let leaf = |symbol: &str| code.contains(&format!("(symbol: '{symbol}', isLeaf: true)")); assert!( @@ -2625,6 +2626,12 @@ fn api_dart() { "api_Plain_hash", "api_Plain_n_get", "api_Plain_n_set", + "api_Plain_count", + "api_Plain_recount", + "api_Wrapped_n_get", + "api_Wrapped_n_set", + "api_Wrapped_count", + "api_Wrapped_recount", "api_contract" ] .into_iter() @@ -2640,7 +2647,12 @@ fn api_dart() { "api_Part_eq", "api_Part_hash", "api_Labeled_eq", - "api_Labeled_hash" + "api_Labeled_hash", + "api_Plain_steps", + "api_Plain_locals", + "api_Hooked_count", + "api_Guarded_n_get", + "api_Guarded_count" ] .into_iter() .all(|symbol| !leaf(symbol)), diff --git a/quest/m1/ffi-speed/leaf-bodies.md b/quest/m1/ffi-speed/leaf-bodies.md deleted file mode 100644 index 05b63967a..000000000 --- a/quest/m1/ffi-speed/leaf-bodies.md +++ /dev/null @@ -1,31 +0,0 @@ -# [M] Leaf calls through trivial method bodies - -## Goal - -A method whose body the export proves reaches no user code, such as moq's -`group::Demand::sequence` (`self.sequence`), and a `pub` field reached through a `Deref` -whose `deref` is such a body, as `group::Producer`'s `sequence` is, are leaves as -`Abi::leaf` in `ffi/src/abi.rs` defines them: Python keeps the GIL across them and Dart -makes them leaf calls. A body is proven by its MIR, not by its shape or an attribute. It -lands only where [the binding benchmark](/bench/ffi/README.md#leaf-calls) shows it faster, -with the export's added time and memory measured beside it. - -## Plan - -Decided with the maintainer on 2026-11-19, in the pick of [#887](https://github.com/kixel-ai/rust2/pull/887): ✅ keep it, and measure what `-Zalways-encode-mir` on dependencies costs the export's build first, choosing between it and per-crate facts recorded in the driver by that measurement (rejected: either route chosen outright; dropping the quest). - -Found by the [crossings](https://github.com/kixel-ai/rust2/pull/887) work. A leaf is now -only a primitive `pub` field read or written directly, or a `PartialEq` or `Hash` derived -down to primitives, since a native export reads no MIR. Most accessors are methods: the -benchmark's `demand.sequence()` costs Python 65 ns against 26 for a leaf field, and Dart -23 against 13. - -Recommended: prove a body a leaf when its optimized MIR has no call but to bodies proven -the same way and to std's own functions known to run no other code, no drop of a value -whose drop runs code, no inline assembly, and no access to a `static`; a body that fails -is simply no leaf, as today. Upstream crates' MIR exists in a check only under -`-Zalways-encode-mir`, which the web export already passes (about 11 CPU s and twice the -peak memory on the stand-in, per the benchmark's "The export's build cost"). Measure that -cost on the native export first. If it is too high, the driver already wraps every crate's -rustc, so it could record each crate's leaf bodies while compiling it instead, keyed by -the crate's metadata hash; compare the two before choosing. From af1b59f003aac581f42b5361adfcb1c4321f9ad1 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 20 Nov 2026 01:50:00 -0800 Subject: [PATCH 3/9] docs(ffi): say which profile's MIR proves a leaf Co-Authored-By: Claude Opus 5.5 --- ffi/src/abi.rs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/ffi/src/abi.rs b/ffi/src/abi.rs index dedb8ef44..7b2b1a0f5 100644 --- a/ffi/src/abi.rs +++ b/ffi/src/abi.rs @@ -1292,12 +1292,15 @@ impl<'a> Abi<'a> { /// into no binding. Python then keeps the GIL across it, and Dart makes it a leaf call, /// which runs on the isolate's own thread with no thread hop. It is a `&self` or /// `&mut self` method, or the read or write of a `pub` field, of a `Send` object, which no - /// object that is not `Send` may lend, taking only scalars and returning one or nothing, whose Rust - /// [`Function::leaf`] proves: each body it runs, the method's and each `Deref`'s on the - /// way, calls only bodies proven the same way and core's intrinsics that only compute, - /// drops nothing whose drop runs other code, loops nowhere, recurses nowhere, asserts - /// nothing, which would run the panic hook on failure, and uses no static. Its MIR proves - /// it, which is the code that runs, not how its source looks or what an attribute claims. + /// object that is not `Send` may lend, taking only scalars and returning one or nothing, + /// whose Rust [`Function::leaf`] proves: each body it runs, the method's and each + /// `Deref`'s on the way, calls only bodies proven the same way and core's intrinsics that + /// only compute, drops nothing whose drop runs other code, loops nowhere, recurses + /// nowhere, asserts nothing, which would run the panic hook on failure, and uses no + /// static. Its MIR proves it, which is the code that runs, not how its source looks or + /// what an attribute claims: the MIR the export's check compiles, with `debug_assertions` + /// on, so code only a build without them compiles, under `cfg(not(debug_assertions))`, is + /// code the proof never sees. /// /// Why holding the GIL across one cannot deadlock: a deadlock needs the call to wait on /// another thread that waits on the GIL. A leaf's only shared state is the handle's From 3a38f24cbd62fe5abe7c01246ded4c151eb4e1b3 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 20 Nov 2026 02:04:03 -0800 Subject: [PATCH 4/9] fix(ffi): no leaf copies or fills a count the caller picks A copy or fill intrinsic, or a lowered copy statement, whose count is no constant does as much work as the caller makes it without a loop in its MIR, so it is no leaf. Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/api/src/lib.rs | 10 +++++++++- ffi/src/leaf.rs | 30 +++++++++++++++++++++++++----- ffi/surface/api/c.h | 10 ++++++---- ffi/surface/api/cpp.hpp | 1 + ffi/surface/api/dart.dart | 1 + ffi/surface/api/go.txt | 1 + ffi/surface/api/kotlin.kt | 1 + ffi/surface/api/python.pyi | 1 + ffi/surface/api/swift.swift | 8 +++----- ffi/surface/api/web.d.ts | 1 + ffi/tests/api.dart | 2 ++ ffi/tests/api.py | 2 ++ ffi/tests/fixtures.rs | 1 + 13 files changed, 54 insertions(+), 15 deletions(-) diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index c7c66816d..4e4825272 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -2757,11 +2757,19 @@ impl std::ops::Deref for Guarded { #[derive(Debug, PartialEq, Hash)] pub struct Labeled { label: String, + bytes: Vec, } impl Labeled { pub fn new(label: String) -> Self { - Self { label } + let bytes = label.clone().into_bytes(); + Self { label, bytes } + } + + /// Zero its bytes: a fill as long as the caller makes it, with no loop in its MIR, so no + /// leaf call. + pub fn blank(&mut self) { + self.bytes.fill(0); } } diff --git a/ffi/src/leaf.rs b/ffi/src/leaf.rs index de4cd6fb9..a54d046aa 100644 --- a/ffi/src/leaf.rs +++ b/ffi/src/leaf.rs @@ -9,7 +9,7 @@ use rustc_data_structures::fx::FxHashMap; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; use rustc_middle::mir::visit::Visitor; -use rustc_middle::mir::{self, BasicBlock, Location, Rvalue, TerminatorKind}; +use rustc_middle::mir::{self, BasicBlock, Location, NonDivergingIntrinsic, Rvalue, StatementKind, TerminatorKind}; use rustc_middle::ty::{self, Instance, InstanceKind, ShimKind, Ty, TyCtxt, TypeVisitableExt, TypingEnv}; use rustc_span::DUMMY_SP; @@ -150,9 +150,20 @@ impl<'tcx> Leaves<'tcx> { | TerminatorKind::Unreachable | TerminatorKind::FalseEdge { .. } | TerminatorKind::FalseUnwind { .. } => true, - TerminatorKind::Call { func, .. } | TerminatorKind::TailCall { func, .. } => { + TerminatorKind::Call { func, args, .. } | TerminatorKind::TailCall { func, args, .. } => { match mono(func.ty(body, tcx)).map(|ty| *ty.kind()) { - Ok(ty::FnDef(def_id, args)) => args.no_bound_vars().is_some_and(|args| self.call(def_id, args)), + Ok(ty::FnDef(def_id, generics)) => { + // A copy or fill of as many values as the caller picks is a loop of + // its own. + let sized = tcx.intrinsic(def_id).is_some_and(|i| { + matches!(i.name.as_str(), "copy" | "copy_nonoverlapping" | "write_bytes") + }); + let counted = !sized || args.get(2).is_some_and(|count| count.node.constant().is_some()); + counted + && generics + .no_bound_vars() + .is_some_and(|generics| self.call(def_id, generics)) + } // A function pointer's callee is unknown. _ => false, } @@ -169,7 +180,15 @@ impl<'tcx> Leaves<'tcx> { | TerminatorKind::UnwindResume | TerminatorKind::UnwindTerminate(_) => false, }; - if !ok { + // The same copy, lowered to a statement. + let copies = data.statements.iter().any(|statement| { + matches!( + &statement.kind, + StatementKind::Intrinsic(intrinsic) + if matches!(&**intrinsic, NonDivergingIntrinsic::CopyNonOverlapping(copy) if copy.count.constant().is_none()) + ) + }); + if !ok || copies { return false; } } @@ -195,7 +214,8 @@ impl<'tcx> Leaves<'tcx> { } /// Whether core's intrinsic `name` only computes: it runs no other code, waits on nothing, -/// and cannot panic. Any other, such as `catch_unwind`, is no leaf. +/// and cannot panic. Any other, such as `catch_unwind`, is no leaf. A copy or fill is one +/// only of a count fixed at its call. fn computes(name: &str) -> bool { name.starts_with("atomic_") || matches!( diff --git a/ffi/surface/api/c.h b/ffi/surface/api/c.h index 3506c58fb..74a64acf1 100644 --- a/ffi/surface/api/c.h +++ b/ffi/surface/api/c.h @@ -7,7 +7,7 @@ #ifdef __cplusplus extern "C" { #endif -#define API_CONTRACT ((uint64_t)0x16bb8402bd12e81eULL) +#define API_CONTRACT ((uint64_t)0xd077a7000af2ace2ULL) uint64_t api_contract(void); uint32_t api_target(void); typedef int32_t api_status; @@ -1888,10 +1888,12 @@ void api_Plain_recount(api_Plain *self, uint64_t n, api_status *status); uint64_t api_Plain_steps(const api_Plain *self, api_status *status); uint32_t api_Plain_locals(const api_Plain *self, api_status *status); void api_Labeled_free(api_Labeled *self); -bool api_Labeled_eq(const api_Labeled *a, const api_Labeled *b); -uint64_t api_Labeled_hash(const api_Labeled *self); -api_buf api_Labeled_debug(const api_Labeled *self); +void api_Labeled_drop(api_Labeled *self, api_status *status); +bool api_Labeled_eq(const api_Labeled *a, const api_Labeled *b, api_status *status); +uint64_t api_Labeled_hash(const api_Labeled *self, api_status *status); +api_buf api_Labeled_debug(const api_Labeled *self, api_status *status); api_Labeled *api_Labeled_new(api_buf label); +void api_Labeled_blank(api_Labeled *self, api_status *status); void api_Gauge_free(api_Gauge *self); void api_Gauge_drop(api_Gauge *self, api_status *status); bool api_Gauge_borrowed(const api_Gauge *self); diff --git a/ffi/surface/api/cpp.hpp b/ffi/surface/api/cpp.hpp index 4d4cbffcf..92ab6deb6 100644 --- a/ffi/surface/api/cpp.hpp +++ b/ffi/surface/api/cpp.hpp @@ -526,6 +526,7 @@ namespace api { RUST2_FFI_CALLABLE ::std::uint64_t hash() const; RUST2_FFI_CALLABLE ::api::buf debug() const; static ::api::Labeled new_(::api::input label); + RUST2_FFI_CALLABLE void blank(); }; class RUST2_FFI_CONSUMABLE Gauge { RUST2_FFI_UNCONSUMED Gauge(Gauge &&other RUST2_FFI_MOVED_FROM) noexcept = default; diff --git a/ffi/surface/api/dart.dart b/ffi/surface/api/dart.dart index 639cbfb14..4cd3ac3a0 100644 --- a/ffi/surface/api/dart.dart +++ b/ffi/surface/api/dart.dart @@ -1377,6 +1377,7 @@ final class Labeled extends _Object { @override bool operator ==(Object other); @override int get hashCode; factory Labeled(String label); + void blank(); } final class Gauge extends _Object { Gauge clone(); diff --git a/ffi/surface/api/go.txt b/ffi/surface/api/go.txt index d5a54727d..38ff93877 100644 --- a/ffi/surface/api/go.txt +++ b/ffi/surface/api/go.txt @@ -1007,6 +1007,7 @@ type Labeled struct { Handle_ *p_rt.Handle_ } func NewLabeled(label string) (*Labeled, error) +func (self *Labeled) Blank() error func (self *Labeled) Close() error func (self *Labeled) Equal(other *Labeled) (bool, error) func (self *Labeled) GoString() string diff --git a/ffi/surface/api/kotlin.kt b/ffi/surface/api/kotlin.kt index f2797498d..fd5d26a8f 100644 --- a/ffi/surface/api/kotlin.kt +++ b/ffi/surface/api/kotlin.kt @@ -1101,6 +1101,7 @@ class Labeled internal constructor(raw: Long, lent: Boolean = false) : AutoClose fun debug(): kotlin.String override fun equals(other: kotlin.Any?): kotlin.Boolean override fun hashCode(): kotlin.Int + fun blank() companion object { @kotlin.jvm.JvmStatic fun new(label: kotlin.String): api.Labeled } diff --git a/ffi/surface/api/python.pyi b/ffi/surface/api/python.pyi index a2c1caf41..117531d82 100644 --- a/ffi/surface/api/python.pyi +++ b/ffi/surface/api/python.pyi @@ -1195,6 +1195,7 @@ class Labeled(_n.Object): def __hash__(self) -> _int: ... @_staticmethod def new(label: _str) -> Labeled: ... + def blank(self) -> None: ... class Gauge(_n.Object): async def later(self) -> _int: ... async def reaches(self, this: _int) -> _bool: ... diff --git a/ffi/surface/api/swift.swift b/ffi/surface/api/swift.swift index c6ff2a3c5..6e55b8023 100644 --- a/ffi/surface/api/swift.swift +++ b/ffi/surface/api/swift.swift @@ -1194,13 +1194,11 @@ public struct Plain: ~Copyable, @unchecked Sendable { } public struct Labeled: ~Copyable, @unchecked Sendable { @inlinable public var debugDescription: Swift.String { get } - @inlinable public static func == (a: borrowing Labeled, b: borrowing Labeled) -> Swift.Bool - @inlinable public func hash(into hasher: inout Swift.Hasher) + @inlinable public static func == (a: borrowing Labeled, b: borrowing Labeled) throws -> Swift.Bool + @inlinable public func hash(into hasher: inout Swift.Hasher) throws @inlinable public static func new(_ label: Swift.String) -> Labeled + @inlinable public mutating func blank() throws } -#if compiler(>=6.4) -extension Labeled: Hashable {} -#endif public struct Gauge: ~Copyable, @unchecked Sendable { @inlinable public func clone() throws -> Gauge @inlinable public static func new(_ level: Swift.UInt64) -> Gauge diff --git a/ffi/surface/api/web.d.ts b/ffi/surface/api/web.d.ts index ce5c49e08..46385c6eb 100644 --- a/ffi/surface/api/web.d.ts +++ b/ffi/surface/api/web.d.ts @@ -634,6 +634,7 @@ export declare function debug(self: Labeled): string; export declare function eq(a: Labeled, b: Labeled): boolean; export declare function hash(self: Labeled): rt.u64; export declare function new$(label: string): Labeled; +export declare function blank(self: Labeled): void; export { new$ as new }; // Labelled.ts diff --git a/ffi/tests/api.dart b/ffi/tests/api.dart index b7134e1f3..a89ed6bc8 100644 --- a/ffi/tests/api.dart +++ b/ffi/tests/api.dart @@ -1088,6 +1088,8 @@ Future leaf() async { final labeled = api.Labeled('a' * 100); check(labeled == api.Labeled('a' * 100) && labeled != api.Labeled('b'), 'a served equality over a string'); check(labeled.hashCode == api.Labeled('a' * 100).hashCode, 'a served hash over a string'); + labeled.blank(); + check(labeled != api.Labeled('a' * 100), 'a fill the caller sized'); labeled.close(); plain.close(); throws(() => plain.nGet, 'a leaf getter of a closed object throws'); diff --git a/ffi/tests/api.py b/ffi/tests/api.py index cf0c3565b..cae602d10 100644 --- a/ffi/tests/api.py +++ b/ffi/tests/api.py @@ -1291,6 +1291,8 @@ def leaf(): labeled = api.Labeled.new("a" * 100) check(labeled == api.Labeled.new("a" * 100) and labeled != api.Labeled.new("b"), "a leaf equality over a string") check(hash(labeled) == hash(api.Labeled.new("a" * 100)), "a leaf hash over a string") + labeled.blank() + check(labeled != api.Labeled.new("a" * 100), "a fill the caller sized") hooked = [] api.hook(lambda: hooked.append(threading.get_ident())) diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 213d37b09..8589df2e5 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -2649,6 +2649,7 @@ fn api_dart() { "api_Labeled_eq", "api_Labeled_hash", "api_Plain_steps", + "api_Labeled_blank", "api_Plain_locals", "api_Hooked_count", "api_Guarded_n_get", From 95ace74771f934e0458c7e0a206274eb4de1cdd0 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 20 Nov 2026 02:07:02 -0800 Subject: [PATCH 5/9] docs(quest): prove leaves against the profile the library builds with Co-Authored-By: Claude Opus 5.5 --- quest/m1/ffi-speed/leaf-profile.md | 38 ++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 quest/m1/ffi-speed/leaf-profile.md diff --git a/quest/m1/ffi-speed/leaf-profile.md b/quest/m1/ffi-speed/leaf-profile.md new file mode 100644 index 000000000..7d736ef40 --- /dev/null +++ b/quest/m1/ffi-speed/leaf-profile.md @@ -0,0 +1,38 @@ +# [L] Prove leaves against the profile the library builds with + +## Goal + +A leaf ([`Abi::leaf`](/ffi/src/abi.rs)) is proven against the bodies the library actually +runs, in every build profile. A build whose profile differs from what the proof saw takes the +slow path in every binding instead of trusting the proof. A release build, which moq ships, +still makes its leaves leaf calls. + +## Plan + +Found by the review of [#911](https://github.com/kixel-ai/rust2/pull/911). The proof reads the +MIR of the export's one `cargo check`, a dev-profile check with `debug_assertions` on. The +library is built separately, usually with `--release`, as `ffi/release/package.py` and the +benchmark do. Code compiled only without debug assertions (`cfg(not(debug_assertions))`, or a +cfg a build script derives from `PROFILE` or `OPT_LEVEL`) is never seen. A scalar accessor +whose release body waits on something that waits on the GIL would then deadlock Python, or run +outside Dart's serving path. No text scan closes this gap: build scripts, proc macros, and +other crates' macros can each hide a profile-dependent cfg. + +Recommended: + +- Check with release settings, so the proof covers the release body. This also moves the + API's own `cfg(debug_assertions)` items to release's side, so it is a change to what the + whole export exports, and needs measuring. +- Have the generated crate's build script compare the profile it builds under (`PROFILE`, + `OPT_LEVEL`, `CARGO_CFG_DEBUG_ASSERTIONS`) with the check's, which the export records. On a + mismatch, it sets a cfg that turns every leaf back into a normal call. Python's leaf choice + is Rust glue, so a cfg suffices. Dart's `isLeaf` is fixed in the Dart source, so it declares + both bindings and picks one through a flag the library reports at load. + +## Waiting + +- Maintainer: whether the export checks with release settings rather than dev's. Options: + release settings plus the build-time guard above (recommended: sound in every profile, and + release builds keep their leaves); the guard alone on today's dev check (sound, but release + builds lose every leaf); or keep the documented boundary (no work). An agent cannot take + this: it changes which `cfg`-gated items every export exports. From 5b88edc1484d0d8cbbf2749e5b141f5c02b9f399 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 20 Nov 2026 16:32:06 -0800 Subject: [PATCH 6/9] test(ffi): a caller-sized fill gets a type of its own Labeled keeps its one case, a derived eq or hash walking a string, and its immutable ABI; Buffer carries the fill that has no loop in its MIR. Co-Authored-By: Claude Opus 5.5 --- ffi/fixtures/api/src/lib.rs | 23 ++++++++++++++++++++--- ffi/surface/api/c.h | 33 ++++++++++++++++++++++++++++++++- ffi/surface/api/cpp.hpp | 9 ++++++++- ffi/surface/api/dart.dart | 6 +++++- ffi/surface/api/go.txt | 8 +++++++- ffi/surface/api/kotlin.kt | 9 ++++++++- ffi/surface/api/python.pyi | 8 ++++++-- ffi/surface/api/swift.swift | 13 ++++++++++--- ffi/surface/api/web.d.ts | 10 +++++++++- ffi/tests/api.dart | 6 ++++-- ffi/tests/api.py | 5 +++-- ffi/tests/fixtures.rs | 2 +- 12 files changed, 113 insertions(+), 19 deletions(-) diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index 6c4b5e2e8..b7eadf9fa 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -2837,13 +2837,25 @@ impl std::ops::Deref for Guarded { #[derive(Debug, PartialEq, Hash)] pub struct Labeled { label: String, - bytes: Vec, } impl Labeled { pub fn new(label: String) -> Self { - let bytes = label.clone().into_bytes(); - Self { label, bytes } + Self { label } + } +} + +/// Bytes as many as the caller asks for. +pub struct Buffer { + bytes: Vec, +} + +impl Buffer { + /// A buffer of `len` ones. + pub fn new(len: u32) -> Self { + Self { + bytes: vec![1; len as usize], + } } /// Zero its bytes: a fill as long as the caller makes it, with no loop in its MIR, so no @@ -2851,6 +2863,11 @@ impl Labeled { pub fn blank(&mut self) { self.bytes.fill(0); } + + /// Whether every byte is zero. + pub fn zeroed(&self) -> bool { + self.bytes.iter().all(|&b| b == 0) + } } /// A handle to `local`'s count if there is one, else a new local: made where `local` diff --git a/ffi/surface/api/c.h b/ffi/surface/api/c.h index 6714df3f7..f3d9190b6 100644 --- a/ffi/surface/api/c.h +++ b/ffi/surface/api/c.h @@ -17,7 +17,7 @@ #ifdef __cplusplus extern "C" { #endif -#define API_CONTRACT ((uint64_t)0xd3f64c00ea2877f9ULL) +#define API_CONTRACT ((uint64_t)0x727fe4d5bd50a58bULL) uint64_t api_contract(void); uint32_t api_target(void); typedef int32_t api_status; @@ -117,6 +117,8 @@ typedef struct api_Retired api_Retired; typedef struct api_Logger api_Logger; typedef struct api_Journal api_Journal; typedef struct api_Local api_Local; +typedef struct api_Wrapped api_Wrapped; +typedef struct api_Buffer api_Buffer; typedef struct api_LocalWaiter api_LocalWaiter; typedef struct api_Retry api_Retry; typedef struct api_Digest api_Digest; @@ -178,6 +180,7 @@ typedef struct api_tls_Codec api_tls_Codec; typedef struct api_Spawned api_Spawned; typedef struct api_LogThread api_LogThread; typedef struct api_Pinned api_Pinned; +typedef struct api_Guarded api_Guarded; typedef struct api_Hooked api_Hooked; typedef struct api_Forged api_Forged; typedef struct api_Part api_Part; @@ -1710,6 +1713,22 @@ API_MUST_USE api_poll api_Local_poll_count_poll(api_Local_poll_count_future *fut void api_Local_poll_count_future_free(api_Local_poll_count_future *future); uint64_t api_Local_thread_number(const api_Local *self, api_status *status); bool api_Local_on_own_thread(const api_Local *self, api_status *status); +void api_Wrapped_free(api_Wrapped *self); +void api_Wrapped_drop(api_Wrapped *self, api_status *status); +API_MUST_USE api_Wrapped *api_Wrapped_new(uint64_t n); +uint64_t api_Wrapped_n_get(const api_Wrapped *self, api_status *status); +void api_Wrapped_n_set(api_Wrapped *self, uint64_t value, api_status *status); +bool api_Wrapped_on_get(const api_Wrapped *self, api_status *status); +void api_Wrapped_on_set(api_Wrapped *self, bool value, api_status *status); +uint64_t api_Wrapped_count(const api_Wrapped *self, api_status *status); +void api_Wrapped_recount(api_Wrapped *self, uint64_t n, api_status *status); +uint64_t api_Wrapped_steps(const api_Wrapped *self, api_status *status); +uint32_t api_Wrapped_locals(const api_Wrapped *self, api_status *status); +void api_Buffer_free(api_Buffer *self); +void api_Buffer_drop(api_Buffer *self, api_status *status); +API_MUST_USE api_Buffer *api_Buffer_new(uint32_t len); +void api_Buffer_blank(api_Buffer *self, api_status *status); +bool api_Buffer_zeroed(const api_Buffer *self, api_status *status); void api_LocalWaiter_free(api_LocalWaiter *self); void api_LocalWaiter_drop(api_LocalWaiter *self, api_status *status); API_MUST_USE api_LocalWaiter *api_LocalWaiter_new(api_waker waker_); @@ -2034,6 +2053,10 @@ void api_Plain_n_set(api_Plain *self, uint64_t value, api_status *status); bool api_Plain_on_get(const api_Plain *self, api_status *status); void api_Plain_on_set(api_Plain *self, bool value, api_status *status); API_MUST_USE api_Plain *api_Plain_new(uint64_t n, bool on); +uint64_t api_Plain_count(const api_Plain *self, api_status *status); +void api_Plain_recount(api_Plain *self, uint64_t n, api_status *status); +uint64_t api_Plain_steps(const api_Plain *self, api_status *status); +uint32_t api_Plain_locals(const api_Plain *self, api_status *status); void api_Labeled_free(api_Labeled *self); bool api_Labeled_eq(const api_Labeled *a, const api_Labeled *b); uint64_t api_Labeled_hash(const api_Labeled *self); @@ -2187,6 +2210,13 @@ void api_Pinned_value_set(api_Pinned *self, uint64_t value, api_status *status); API_MUST_USE api_Pinned *api_Pinned_new(uint64_t value); API_MUST_USE api_Pinned *api_Pinned_new_homed(uint64_t value); API_MUST_USE api_Part *api_Pinned_part(const api_Pinned *self, api_status *status); +void api_Guarded_free(api_Guarded *self); +API_MUST_USE api_Guarded *api_Guarded_new(uint64_t n); +uint64_t api_Guarded_n_get(const api_Guarded *self); +bool api_Guarded_on_get(const api_Guarded *self); +uint64_t api_Guarded_count(const api_Guarded *self); +uint64_t api_Guarded_steps(const api_Guarded *self); +uint32_t api_Guarded_locals(const api_Guarded *self); void api_Hooked_free(api_Hooked *self); void api_Hooked_drop(api_Hooked *self, api_status *status); bool api_Hooked_eq(const api_Hooked *a, const api_Hooked *b, api_status *status); @@ -2194,6 +2224,7 @@ API_MUST_USE api_buf api_Hooked_debug(const api_Hooked *self, api_status *status uint64_t api_Hooked_n_get(const api_Hooked *self, api_status *status); void api_Hooked_n_set(api_Hooked *self, uint64_t value, api_status *status); API_MUST_USE api_Hooked *api_Hooked_new(uint64_t n); +uint64_t api_Hooked_count(const api_Hooked *self, api_status *status); void api_Forged_free(api_Forged *self); void api_Forged_drop(api_Forged *self, api_status *status); bool api_Forged_eq(const api_Forged *a, const api_Forged *b, api_status *status); diff --git a/ffi/surface/api/cpp.hpp b/ffi/surface/api/cpp.hpp index d1c2edffd..bc6c03bcb 100644 --- a/ffi/surface/api/cpp.hpp +++ b/ffi/surface/api/cpp.hpp @@ -205,6 +205,13 @@ namespace api { RUST2_FFI_CALLABLE ::std::uint64_t steps() const; RUST2_FFI_CALLABLE ::std::uint32_t locals() const; }; + class RUST2_FFI_CONSUMABLE Buffer { + RUST2_FFI_UNCONSUMED Buffer(Buffer &&other RUST2_FFI_MOVED_FROM) noexcept = default; + Buffer &operator=(Buffer &&other) noexcept = default; + static ::api::Buffer new_(::std::uint32_t len); + RUST2_FFI_CALLABLE void blank(); + RUST2_FFI_CALLABLE bool zeroed() const; + }; class RUST2_FFI_CONSUMABLE LocalWaiter { RUST2_FFI_UNCONSUMED LocalWaiter(LocalWaiter &&other RUST2_FFI_MOVED_FROM) noexcept = default; LocalWaiter &operator=(LocalWaiter &&other) noexcept = default; @@ -556,7 +563,6 @@ namespace api { RUST2_FFI_CALLABLE ::std::uint64_t hash() const; RUST2_FFI_CALLABLE ::api::buf debug() const; static ::api::Labeled new_(::api::input label); - RUST2_FFI_CALLABLE void blank(); }; class RUST2_FFI_CONSUMABLE Gauge { RUST2_FFI_UNCONSUMED Gauge(Gauge &&other RUST2_FFI_MOVED_FROM) noexcept = default; @@ -2304,6 +2310,7 @@ namespace api { class Journal; class Local; class Wrapped; + class Buffer; class LocalWaiter; class Retry; class Digest; diff --git a/ffi/surface/api/dart.dart b/ffi/surface/api/dart.dart index 0110753fa..437c38688 100644 --- a/ffi/surface/api/dart.dart +++ b/ffi/surface/api/dart.dart @@ -1223,6 +1223,11 @@ final class Wrapped extends _Object { U64 steps(); int locals(); } +final class Buffer extends _Object { + factory Buffer(int len); + void blank(); + bool zeroed(); +} final class LocalWaiter extends _Object { factory LocalWaiter(void Function() waker); static Cancelable pollReady(int n); @@ -1510,7 +1515,6 @@ final class Labeled extends _Object { @override bool operator ==(Object other); @override int get hashCode; factory Labeled(String label); - void blank(); } final class Gauge extends _Object { Gauge clone(); diff --git a/ffi/surface/api/go.txt b/ffi/surface/api/go.txt index d671fbd93..dfcabff99 100644 --- a/ffi/surface/api/go.txt +++ b/ffi/surface/api/go.txt @@ -355,6 +355,13 @@ type BoxedU8 struct { func Keeps(log Log) BoxedU8 func (self BoxedU8) Equal(other BoxedU8) bool func (self BoxedU8) GoString() string +type Buffer struct { + Handle_ *p_rt.Handle_ +} +func NewBuffer(len_ uint32) *Buffer +func (self *Buffer) Blank() error +func (self *Buffer) Close() error +func (self *Buffer) Zeroed() (bool, error) type Builtin interface { Equal(other Builtin) bool } @@ -1094,7 +1101,6 @@ type Labeled struct { Handle_ *p_rt.Handle_ } func NewLabeled(label string) (*Labeled, error) -func (self *Labeled) Blank() error func (self *Labeled) Close() error func (self *Labeled) Equal(other *Labeled) (bool, error) func (self *Labeled) GoString() string diff --git a/ffi/surface/api/kotlin.kt b/ffi/surface/api/kotlin.kt index 75c18e47e..372923801 100644 --- a/ffi/surface/api/kotlin.kt +++ b/ffi/surface/api/kotlin.kt @@ -794,6 +794,14 @@ class Wrapped internal constructor(raw: Long, lent: Boolean = false) : AutoClose @kotlin.jvm.JvmStatic fun new(n: kotlin.ULong): api.Wrapped } } +class Buffer internal constructor(raw: Long, lent: Boolean = false) : AutoCloseable { + override fun close() + fun blank() + fun zeroed(): kotlin.Boolean + companion object { + @kotlin.jvm.JvmStatic fun new(len: kotlin.UInt): api.Buffer + } +} class LocalWaiter internal constructor(raw: Long, lent: Boolean = false) : AutoCloseable { override fun close() companion object { @@ -1180,7 +1188,6 @@ class Labeled internal constructor(raw: Long, lent: Boolean = false) : AutoClose fun debug(): kotlin.String override fun equals(other: kotlin.Any?): kotlin.Boolean override fun hashCode(): kotlin.Int - fun blank() companion object { @kotlin.jvm.JvmStatic fun new(label: kotlin.String): api.Labeled } diff --git a/ffi/surface/api/python.pyi b/ffi/surface/api/python.pyi index 09c8b5fc9..571481b46 100644 --- a/ffi/surface/api/python.pyi +++ b/ffi/surface/api/python.pyi @@ -1,5 +1,5 @@ # api.py -__all__ = ['A', 'Area', 'Array', 'ArrayU8x4', 'Atlas', 'B', 'BOXED', 'Batch', 'Batch2', 'Beat', 'Berth', 'Board', 'Booth', 'Bound', 'BoundU64', 'BoundsU64', 'BoundsU64Exception', 'BoxedU16', 'BoxedU8', 'Builtin', 'C', 'CancellationError', 'Cancelled', 'Channel', 'Choice', 'Clash', 'ClashAny', 'ClashBreak', 'ClashCandidate', 'ClashEmptyString', 'ClashErrno', 'ClashEscaped', 'ClashLevel', 'ClashMalformed', 'ClashMalformedException', 'ClashReader', 'ClashSeed', 'ClashSource', 'ClashSpan', 'ClashStore', 'ClashTag', 'ClashTone', 'ClashTone_', 'Clocked', 'Codecs', 'Core', 'Countdown', 'Counter', 'Cursor', 'Deprecated', 'Der', 'Dial', 'Digest', 'DoubleArray', 'Draft', 'Duration', 'EOF', 'Error', 'ErrorException', 'Event', 'Extent', 'FAR', 'Family', 'Fault', 'FaultException', 'Feed', 'FiledReceipt', 'ForeignReader', 'Forged', 'GREETINGS', 'Gap', 'Gauge', 'Handle', 'Hasher', 'Hits', 'Holder', 'Hooked', 'InnerU8', 'Instant', 'Journal', 'Json', 'JvmField', 'JvmStatic', 'Key', 'Knob', 'LIMIT', 'Label', 'Labeled', 'Labelled', 'Latch', 'Layered', 'Ledger', 'LeftRightU8', 'LeftU8', 'Level', 'LimitsBytes', 'LimitsDuration', 'ListClashToneException', 'Local', 'LocalWaiter', 'Log', 'LogCount', 'LogThread', 'Logger', 'LongArray', 'MacrosStreams', 'Mark', 'Marker', 'Measure', 'Message', 'Meter', 'Meters', 'Moment', 'Mut', 'Name', 'Node', 'NonZeros', 'Note', 'Numbers', 'OptIn', 'OuterInnerU8', 'PRIMES', 'Packaged', 'Packet', 'PadU16', 'PadU8', 'Page', 'PairNonZeroU16', 'PairSizeU8', 'PairU32', 'PairU8Size', 'Parcel', 'Part', 'Pass', 'Peer', 'Pinned', 'Placement', 'Plain', 'Platform', 'Point', 'PolarPoint', 'PolarTurn', 'Polar_Turn', 'Qualifiers', 'Quantity', 'Rank', 'Rated', 'Reading', 'Receipt', 'Refusal', 'RefusalException', 'Registry', 'Resolving', 'Retired', 'Retry', 'RightLeftU8', 'RightU8', 'STEP', 'Scan', 'Score', 'Seat', 'Shadowed', 'Shape', 'Sheet', 'Site', 'Size', 'Slip', 'SlotU32', 'SlotU8', 'Span', 'Spawned', 'Spot', 'Stack', 'Stage', 'Stamp', 'Stamped', 'StartSeekable', 'Status', 'StdIoError', 'StringException', 'Tab', 'Tallies', 'Tally', 'Ticket', 'Tier', 'TlsCert', 'TlsCodec', 'TlsConfig', 'TlsPolicyLifetime', 'TlsResolver', 'TlsSession', 'Token', 'Trail', 'Turner', 'URL', 'Undo', 'Url', 'VecClashTone', 'Verbosity', 'Version', 'Waiter', 'Waker', 'Weighted', 'Wide', 'Window', 'Worker', 'WrapU32', '__all___', '_deprecated_', 'admit', 'advance', 'after', 'alpn', 'alpn_lent', 'apply_non_zero_u16', 'apply_u32', 'area', 'assert_', 'attempt', 'beats', 'below', 'booth_count', 'boxed_counter', 'boxed_floats', 'boxed_name', 'boxed_tuple', 'breadth', 'bump_both', 'bump_either', 'byte_len', 'byte_limits', 'capacities_2_2', 'capacities_2_4', 'capacities_4_2', 'capacities_4_4', 'cert_der', 'cert_len', 'certify', 'chain_len', 'choose', 'chunks', 'clash_any', 'clash_audible', 'clash_audio_encoder_finish', 'clash_audio_encoder_finish_', 'clash_candidate', 'clash_empty', 'clash_ignore', 'clash_nested', 'clash_waited', 'clocked_after', 'coordinates', 'corner', 'corner_later', 'count', 'counted', 'counters', 'crammed', 'cross', 'crowded', 'deprecated', 'describe', 'describe_non_zeros', 'digit', 'divide', 'doubled', 'doubled_i64', 'doubled_ttl', 'drain_2', 'drain_4', 'drive', 'dropped', 'each', 'either', 'either_later', 'emit', 'emit_from_thread', 'emit_later', 'encode', 'end', 'ends', 'entries', 'erased', 'errno', 'excuse', 'extended', 'failure', 'failure_kind', 'failure_message', 'farther_hop', 'file', 'fill_2', 'fill_4', 'filter', 'find', 'fingerprint', 'first_of', 'flip', 'greet', 'grow', 'halved', 'halves', 'has_instant', 'has_text', 'heft', 'held_count', 'hex', 'hook', 'host', 'is_family', 'is_kept', 'jam', 'jni_one', 'join_words', 'joined', 'jvm_sum', 'keep_point', 'keeper_point', 'keeps', 'kept_counter', 'kept_or_point', 'kept_point', 'kept_polar_point', 'kept_size', 'kept_wrap_u32', 'knob', 'lasting', 'later', 'layer_name', 'least', 'len', 'lent_back', 'less', 'level_later', 'local_after', 'local_later', 'local_or_new', 'local_or_new_later', 'locals_dropped', 'log_counts', 'log_later', 'log_on_drop', 'log_waker', 'longer', 'longest', 'louder', 'macros_streamed', 'made', 'marked', 'moment_at', 'named', 'next_char', 'next_hop', 'next_ips', 'next_packet', 'nexts', 'non_zeros', 'now', 'nudge', 'nudge_by', 'numbered', 'offered_len', 'offset', 'offsetof', 'on_first_thread', 'only', 'page', 'pair', 'parents', 'parse_cert', 'parse_later', 'peek', 'placement', 'platform', 'pointer_bits', 'polar_point', 'poll_tripled', 'port', 'ports', 'prefixed', 'push_counted', 'put_number', 'queued_hex', 'reach', 'read_len', 'reading', 'reading_bump', 'reading_debug', 'reading_echo', 'reasons', 'refuse', 'reissue', 'reissue_lent', 'relay', 'report_non_zero_u16', 'report_u32', 'resolve', 'resolved', 'resolver', 'resume', 'return_moved', 'return_values', 'rooted_name', 'rows', 'same', 'same_char', 'same_duration', 'same_ip_addr', 'same_isize', 'same_labelled', 'same_path', 'same_socket_addr', 'same_socket_addr_v4', 'same_socket_addr_v6', 'same_string', 'same_u128', 'same_u64', 'same_usize', 'sample_hex', 'scaled', 'scanned', 'seat', 'second_later', 'sections', 'secure', 'seeds_counter_counter', 'seeds_counter_point', 'seeds_counter_polar_point', 'seeds_counter_size', 'seeds_counter_wrap_u32', 'seeds_point_counter', 'seeds_point_point', 'seeds_point_polar_point', 'seeds_point_size', 'seeds_point_wrap_u32', 'seek_to', 'sentence', 'shift', 'shifted', 'since', 'span', 'spell', 'spend', 'split_last', 'spread', 'stamp_at', 'stored', 'stored_text', 'stray', 'sum_all', 'sum_lists', 'sum_u32', 'summed', 'summed_up_receipt', 'sums', 'swapped', 'tag', 'tagged', 'tail', 'tallied', 'tally_log_count', 'tick_name', 'tickets', 'timed_hex', 'title', 'token_bytes', 'token_slice', 'total', 'turned', 'undone', 'unescaped', 'unescaped_later', 'unescaped_maybe', 'unhook', 'unnamed', 'unzeroed', 'verify', 'visit_chunks', 'visit_stray', 'walk', 'wasm_log', 'wasm_only', 'wasm_take', 'watch', 'weigh_all_counter', 'weigh_point', 'wexitstatus', 'wide', 'widen', 'widths', 'wind', 'within', 'words', 'worth', 'yielded'] +__all__ = ['A', 'Area', 'Array', 'ArrayU8x4', 'Atlas', 'B', 'BOXED', 'Batch', 'Batch2', 'Beat', 'Berth', 'Board', 'Booth', 'Bound', 'BoundU64', 'BoundsU64', 'BoundsU64Exception', 'BoxedU16', 'BoxedU8', 'Buffer', 'Builtin', 'C', 'CancellationError', 'Cancelled', 'Channel', 'Choice', 'Clash', 'ClashAny', 'ClashBreak', 'ClashCandidate', 'ClashEmptyString', 'ClashErrno', 'ClashEscaped', 'ClashLevel', 'ClashMalformed', 'ClashMalformedException', 'ClashReader', 'ClashSeed', 'ClashSource', 'ClashSpan', 'ClashStore', 'ClashTag', 'ClashTone', 'ClashTone_', 'Clocked', 'Codecs', 'Core', 'Countdown', 'Counter', 'Cursor', 'Deprecated', 'Der', 'Dial', 'Digest', 'DoubleArray', 'Draft', 'Duration', 'EOF', 'Error', 'ErrorException', 'Event', 'Extent', 'FAR', 'Family', 'Fault', 'FaultException', 'Feed', 'FiledReceipt', 'ForeignReader', 'Forged', 'GREETINGS', 'Gap', 'Gauge', 'Guarded', 'Handle', 'Hasher', 'Hits', 'Holder', 'Hooked', 'InnerU8', 'Instant', 'Journal', 'Json', 'JvmField', 'JvmStatic', 'Key', 'Knob', 'LIMIT', 'Label', 'Labeled', 'Labelled', 'Latch', 'Layered', 'Ledger', 'LeftRightU8', 'LeftU8', 'Level', 'LimitsBytes', 'LimitsDuration', 'ListClashToneException', 'Local', 'LocalWaiter', 'Log', 'LogCount', 'LogThread', 'Logger', 'LongArray', 'MacrosStreams', 'Mark', 'Marker', 'Measure', 'Message', 'Meter', 'Meters', 'Moment', 'Mut', 'Name', 'Node', 'NonZeros', 'Note', 'Numbers', 'OptIn', 'OuterInnerU8', 'PRIMES', 'Packaged', 'Packet', 'PadU16', 'PadU8', 'Page', 'PairNonZeroU16', 'PairSizeU8', 'PairU32', 'PairU8Size', 'Parcel', 'Part', 'Pass', 'Peer', 'Pinned', 'Placement', 'Plain', 'Platform', 'Point', 'PolarPoint', 'PolarTurn', 'Polar_Turn', 'Qualifiers', 'Quantity', 'Rank', 'Rated', 'Reading', 'Receipt', 'Refusal', 'RefusalException', 'Registry', 'Resolving', 'Retired', 'Retry', 'RightLeftU8', 'RightU8', 'STEP', 'Scan', 'Score', 'Seat', 'Shadowed', 'Shape', 'Sheet', 'Site', 'Size', 'Slip', 'SlotU32', 'SlotU8', 'Span', 'Spawned', 'Spot', 'Stack', 'Stage', 'Stamp', 'Stamped', 'StartSeekable', 'Status', 'StdIoError', 'StringException', 'Tab', 'Tallies', 'Tally', 'Ticket', 'Tier', 'TlsCert', 'TlsCodec', 'TlsConfig', 'TlsPolicyLifetime', 'TlsResolver', 'TlsSession', 'Token', 'Trail', 'Turner', 'URL', 'Undo', 'Url', 'VecClashTone', 'Verbosity', 'Version', 'Waiter', 'Waker', 'Weighted', 'Wide', 'Window', 'Worker', 'WrapU32', 'Wrapped', '__all___', '_deprecated_', 'admit', 'advance', 'after', 'alpn', 'alpn_lent', 'apply_non_zero_u16', 'apply_u32', 'area', 'assert_', 'attempt', 'beats', 'below', 'booth_count', 'boxed_counter', 'boxed_floats', 'boxed_name', 'boxed_tuple', 'breadth', 'bump_both', 'bump_either', 'byte_len', 'byte_limits', 'capacities_2_2', 'capacities_2_4', 'capacities_4_2', 'capacities_4_4', 'cert_der', 'cert_len', 'certify', 'chain_len', 'choose', 'chunks', 'clash_any', 'clash_audible', 'clash_audio_encoder_finish', 'clash_audio_encoder_finish_', 'clash_candidate', 'clash_empty', 'clash_ignore', 'clash_nested', 'clash_waited', 'clocked_after', 'coordinates', 'corner', 'corner_later', 'count', 'counted', 'counters', 'crammed', 'cross', 'crowded', 'deprecated', 'describe', 'describe_non_zeros', 'digit', 'divide', 'doubled', 'doubled_i64', 'doubled_ttl', 'drain_2', 'drain_4', 'drive', 'dropped', 'each', 'either', 'either_later', 'emit', 'emit_from_thread', 'emit_later', 'encode', 'end', 'ends', 'entries', 'erased', 'errno', 'excuse', 'extended', 'failure', 'failure_kind', 'failure_message', 'farther_hop', 'file', 'fill_2', 'fill_4', 'filter', 'find', 'fingerprint', 'first_of', 'flip', 'greet', 'grow', 'halved', 'halves', 'has_instant', 'has_text', 'heft', 'held_count', 'hex', 'hook', 'host', 'is_family', 'is_kept', 'jam', 'jni_one', 'join_words', 'joined', 'jvm_sum', 'keep_point', 'keeper_point', 'keeps', 'kept_counter', 'kept_or_point', 'kept_point', 'kept_polar_point', 'kept_size', 'kept_wrap_u32', 'knob', 'lasting', 'later', 'layer_name', 'least', 'len', 'lent_back', 'less', 'level_later', 'local_after', 'local_later', 'local_or_new', 'local_or_new_later', 'locals_dropped', 'log_counts', 'log_later', 'log_on_drop', 'log_waker', 'longer', 'longest', 'louder', 'macros_streamed', 'made', 'marked', 'moment_at', 'named', 'next_char', 'next_hop', 'next_ips', 'next_packet', 'nexts', 'non_zeros', 'now', 'nudge', 'nudge_by', 'numbered', 'offered_len', 'offset', 'offsetof', 'on_first_thread', 'only', 'page', 'pair', 'parents', 'parse_cert', 'parse_later', 'peek', 'placement', 'platform', 'pointer_bits', 'polar_point', 'poll_tripled', 'port', 'ports', 'prefixed', 'push_counted', 'put_number', 'queued_hex', 'reach', 'read_len', 'reading', 'reading_bump', 'reading_debug', 'reading_echo', 'reasons', 'refuse', 'reissue', 'reissue_lent', 'relay', 'report_non_zero_u16', 'report_u32', 'resolve', 'resolved', 'resolver', 'resume', 'return_moved', 'return_values', 'rooted_name', 'rows', 'same', 'same_char', 'same_duration', 'same_ip_addr', 'same_isize', 'same_labelled', 'same_path', 'same_socket_addr', 'same_socket_addr_v4', 'same_socket_addr_v6', 'same_string', 'same_u128', 'same_u64', 'same_usize', 'sample_hex', 'scaled', 'scanned', 'seat', 'second_later', 'sections', 'secure', 'seeds_counter_counter', 'seeds_counter_point', 'seeds_counter_polar_point', 'seeds_counter_size', 'seeds_counter_wrap_u32', 'seeds_point_counter', 'seeds_point_point', 'seeds_point_polar_point', 'seeds_point_size', 'seeds_point_wrap_u32', 'seek_to', 'sentence', 'shift', 'shifted', 'since', 'span', 'spell', 'spend', 'split_last', 'spread', 'stamp_at', 'stored', 'stored_text', 'stray', 'sum_all', 'sum_lists', 'sum_u32', 'summed', 'summed_up_receipt', 'sums', 'swapped', 'tag', 'tagged', 'tail', 'tallied', 'tally_log_count', 'tick_name', 'tickets', 'timed_hex', 'title', 'token_bytes', 'token_slice', 'total', 'turned', 'undone', 'unescaped', 'unescaped_later', 'unescaped_maybe', 'unhook', 'unnamed', 'unzeroed', 'verify', 'visit_chunks', 'visit_stray', 'walk', 'wasm_log', 'wasm_only', 'wasm_take', 'watch', 'weigh_all_counter', 'weigh_point', 'wexitstatus', 'wide', 'widen', 'widths', 'wind', 'within', 'words', 'worth', 'yielded'] class Waker: def __init__(self, wake: _typing.Callable[[], _object], loop: _asyncio.AbstractEventLoop | None=None) -> None: ... def wake(self) -> None: ... @@ -987,6 +987,11 @@ class Wrapped(_n.Object): def recount(self, n: _int) -> None: ... def steps(self) -> _int: ... def locals(self) -> _int: ... +class Buffer(_n.Object): + @_staticmethod + def new(len: _int) -> Buffer: ... + def blank(self) -> None: ... + def zeroed(self) -> _bool: ... class LocalWaiter(_n.Object): @_staticmethod async def poll_ready(n: _int) -> _int: ... @@ -1307,7 +1312,6 @@ class Labeled(_n.Object): def __hash__(self) -> _int: ... @_staticmethod def new(label: _str) -> Labeled: ... - def blank(self) -> None: ... class Gauge(_n.Object): async def later(self) -> _int: ... async def reaches(self, this: _int) -> _bool: ... diff --git a/ffi/surface/api/swift.swift b/ffi/surface/api/swift.swift index ae25c608d..3026f1a41 100644 --- a/ffi/surface/api/swift.swift +++ b/ffi/surface/api/swift.swift @@ -1039,6 +1039,11 @@ public struct Wrapped: ~Copyable, @unchecked Sendable { @inlinable public func steps() throws -> Swift.UInt64 @inlinable public func locals() throws -> Swift.UInt32 } +public struct Buffer: ~Copyable, @unchecked Sendable { + @inlinable public static func new(_ len: Swift.UInt32) -> Buffer + @inlinable public mutating func blank() throws + @inlinable public func zeroed() throws -> Swift.Bool +} public struct LocalWaiter: ~Copyable { @inlinable public static func new(_ waker: @escaping @Sendable () -> Void) -> LocalWaiter @inlinable nonisolated(nonsending) public static func pollReady(_ n: Swift.UInt32) async throws -> Swift.UInt32 @@ -1324,11 +1329,13 @@ public struct Plain: ~Copyable, @unchecked Sendable { } public struct Labeled: ~Copyable, @unchecked Sendable { @inlinable public var debugDescription: Swift.String { get } - @inlinable public static func == (a: borrowing Labeled, b: borrowing Labeled) throws -> Swift.Bool - @inlinable public func hash(into hasher: inout Swift.Hasher) throws + @inlinable public static func == (a: borrowing Labeled, b: borrowing Labeled) -> Swift.Bool + @inlinable public func hash(into hasher: inout Swift.Hasher) @inlinable public static func new(_ label: Swift.String) -> Labeled - @inlinable public mutating func blank() throws } +#if compiler(>=6.4) +extension Labeled: Hashable {} +#endif public struct Gauge: ~Copyable, @unchecked Sendable { @inlinable public func clone() throws -> Gauge @inlinable public static func new(_ level: Swift.UInt64) -> Gauge diff --git a/ffi/surface/api/web.d.ts b/ffi/surface/api/web.d.ts index 9e5f2ed60..fab11049a 100644 --- a/ffi/surface/api/web.d.ts +++ b/ffi/surface/api/web.d.ts @@ -108,6 +108,14 @@ export type BoxedU8 = { export declare function debug(self: BoxedU8): string; export declare function eq(a: BoxedU8, b: BoxedU8): boolean; +// Buffer.ts +import * as rt from "./rt.ts"; +export type Buffer = rt.Handle<"Buffer">; +export declare function new$(len: number): Buffer; +export declare function blank(self: Buffer): void; +export declare function zeroed(self: Buffer): boolean; +export { new$ as new }; + // Builtin.ts import * as rt from "./rt.ts"; export type Builtin = { @@ -720,7 +728,6 @@ export declare function debug(self: Labeled): string; export declare function eq(a: Labeled, b: Labeled): boolean; export declare function hash(self: Labeled): rt.u64; export declare function new$(label: string): Labeled; -export declare function blank(self: Labeled): void; export { new$ as new }; // Labelled.ts @@ -1917,6 +1924,7 @@ export declare const k_Batch: rt.Kind; export declare const k_Batch_2: rt.Kind; export declare const k_Berth: rt.Kind; export declare const k_Board: rt.Kind; +export declare const k_Buffer: rt.Kind; export declare const k_Channel: rt.Kind; export declare const k_Codecs: rt.Kind; export declare const k_Countdown: rt.Kind; diff --git a/ffi/tests/api.dart b/ffi/tests/api.dart index d86b8ab01..853d162de 100644 --- a/ffi/tests/api.dart +++ b/ffi/tests/api.dart @@ -1241,9 +1241,11 @@ Future leaf() async { final labeled = api.Labeled('a' * 100); check(labeled == api.Labeled('a' * 100) && labeled != api.Labeled('b'), 'a served equality over a string'); check(labeled.hashCode == api.Labeled('a' * 100).hashCode, 'a served hash over a string'); - labeled.blank(); - check(labeled != api.Labeled('a' * 100), 'a fill the caller sized'); labeled.close(); + final buffer = api.Buffer(100); + buffer.blank(); + check(buffer.zeroed(), 'a fill the caller sized'); + buffer.close(); plain.close(); throws(() => plain.nGet, 'a leaf getter of a closed object throws'); diff --git a/ffi/tests/api.py b/ffi/tests/api.py index d260e60bb..89ed12a29 100644 --- a/ffi/tests/api.py +++ b/ffi/tests/api.py @@ -1375,8 +1375,9 @@ def leaf(): labeled = api.Labeled.new("a" * 100) check(labeled == api.Labeled.new("a" * 100) and labeled != api.Labeled.new("b"), "a leaf equality over a string") check(hash(labeled) == hash(api.Labeled.new("a" * 100)), "a leaf hash over a string") - labeled.blank() - check(labeled != api.Labeled.new("a" * 100), "a fill the caller sized") + buffer = api.Buffer.new(100) + buffer.blank() + check(buffer.zeroed(), "a fill the caller sized") hooked = [] api.hook(lambda: hooked.append(threading.get_ident())) diff --git a/ffi/tests/fixtures.rs b/ffi/tests/fixtures.rs index 714b8a0cb..76f688bff 100644 --- a/ffi/tests/fixtures.rs +++ b/ffi/tests/fixtures.rs @@ -2717,7 +2717,7 @@ fn api_dart() { "api_Labeled_eq", "api_Labeled_hash", "api_Plain_steps", - "api_Labeled_blank", + "api_Buffer_blank", "api_Plain_locals", "api_Hooked_count", "api_Guarded_n_get", From cd599cca19f9fe4f901c59b6f268d80628ecc519 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 20 Nov 2026 16:40:09 -0800 Subject: [PATCH 7/9] docs(quest): record the leaf-profile decision Co-Authored-By: Claude Opus 5.5 --- quest/m1/ffi-speed/leaf-profile.md | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/quest/m1/ffi-speed/leaf-profile.md b/quest/m1/ffi-speed/leaf-profile.md index 7d736ef40..4e2baf483 100644 --- a/quest/m1/ffi-speed/leaf-profile.md +++ b/quest/m1/ffi-speed/leaf-profile.md @@ -18,7 +18,9 @@ whose release body waits on something that waits on the GIL would then deadlock outside Dart's serving path. No text scan closes this gap: build scripts, proc macros, and other crates' macros can each hide a profile-dependent cfg. -Recommended: +Decided by the maintainer on [#911](https://github.com/kixel-ai/rust2/pull/911#issuecomment-7054086583): +check with release settings plus a build-time guard in each binding (rejected: the guard alone +on today's dev check, which loses every leaf in release builds; keeping the documented boundary). - Check with release settings, so the proof covers the release body. This also moves the API's own `cfg(debug_assertions)` items to release's side, so it is a change to what the @@ -28,11 +30,3 @@ Recommended: mismatch, it sets a cfg that turns every leaf back into a normal call. Python's leaf choice is Rust glue, so a cfg suffices. Dart's `isLeaf` is fixed in the Dart source, so it declares both bindings and picks one through a flag the library reports at load. - -## Waiting - -- Maintainer: whether the export checks with release settings rather than dev's. Options: - release settings plus the build-time guard above (recommended: sound in every profile, and - release builds keep their leaves); the guard alone on today's dev check (sound, but release - builds lose every leaf); or keep the documented boundary (no work). An agent cannot take - this: it changes which `cfg`-gated items every export exports. From f28d9b5354aac1477df465f3a6a4d935b8ff2b6c Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Fri, 20 Nov 2026 16:44:51 -0800 Subject: [PATCH 8/9] docs(quest): say leaf-profile closes the boundary #911 lands with Co-Authored-By: Claude Opus 5.5 --- quest/m1/ffi-speed/leaf-profile.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/quest/m1/ffi-speed/leaf-profile.md b/quest/m1/ffi-speed/leaf-profile.md index 4e2baf483..b57bb2d8a 100644 --- a/quest/m1/ffi-speed/leaf-profile.md +++ b/quest/m1/ffi-speed/leaf-profile.md @@ -18,9 +18,11 @@ whose release body waits on something that waits on the GIL would then deadlock outside Dart's serving path. No text scan closes this gap: build scripts, proc macros, and other crates' macros can each hide a profile-dependent cfg. -Decided by the maintainer on [#911](https://github.com/kixel-ai/rust2/pull/911#issuecomment-7054086583): -check with release settings plus a build-time guard in each binding (rejected: the guard alone -on today's dev check, which loses every leaf in release builds; keeping the documented boundary). +Decided by the maintainer on [#911](https://github.com/kixel-ai/rust2/pull/911#issuecomment-7054086583), +which lands with the boundary documented in `Abi::leaf` (rejected there: growing #911 into this +quest's work). This quest closes it: check with release settings plus a build-time guard in each +binding (rejected: the guard alone on today's dev check, which loses every leaf in release +builds; keeping the documented boundary for good). - Check with release settings, so the proof covers the release body. This also moves the API's own `cfg(debug_assertions)` items to release's side, so it is a change to what the From c1c7545e1a30bf5dbf1904c09f0b0f8bd92d58c5 Mon Sep 17 00:00:00 2001 From: quest fixer Date: Fri, 20 Nov 2026 17:06:59 -0800 Subject: [PATCH 9/9] style(ffi): format merged leaf predicate --- ffi/src/abi.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/ffi/src/abi.rs b/ffi/src/abi.rs index b396983b5..e265b66ed 100644 --- a/ffi/src/abi.rs +++ b/ffi/src/abi.rs @@ -1407,12 +1407,7 @@ impl<'a> Abi<'a> { } _ => false, }; - shape - && function.leaf - && !self.affine[*i] - && !self.chained[*i] - && function.err.is_none() - && !function.future + shape && function.leaf && !self.affine[*i] && !self.chained[*i] && function.err.is_none() && !function.future } /// Whether `ty`'s `_eq`, or with `hash` its `_hash`, is a leaf, as [`Self::leaf`]