diff --git a/ffi/README.md b/ffi/README.md index 2b851923f..e82f999ac 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -94,7 +94,7 @@ public path names, or an error taken by value, is held by value as an opaque han | any other type | an object: an opaque handle to an `Arc`, freed with `_free`; one that is `Copy`, such as std's `Instant`, whose padding a `rustc` may place anywhere, is copied out of its handle where Rust takes it by value, and a closure neither takes nor returns one by value; one that is not `Send`, such as kio's `clock::Entered`, stays on the thread that made it, as [the C ABI](#the-c-abi)'s threads say | | a type whose only generic parameters are lifetimes, such as `Path<'a>` | an object holding its `'static` form | | a generic type, at each instance it infers | that instance as any other type, with each method whose impl and own bounds it meets; any other instance is refused | -| a `pub` field of an object or opaque value | a getter returning a copy, and a setter assigning in place, as `x.field = value` does | +| a `pub` field of an object or opaque value | a getter returning a copy, and a setter assigning in place, as `x.field = value` does; a `repr(packed)` struct's field that may lie unaligned, which rustc lets no reference point at, is copied out if `Copy`, else read unaligned into a `ManuallyDrop`, which the struct still owns and drops, so one that must be lent instead, a field that is not `Clone`, is refused unless aligned within the packing, as is one holding an atomic or `Cell` inline, whose unaligned copy would race a write through `&self` | | a `pub` trait | a callback interface: a table of C functions and their data; a trait C cannot implement, such as one with a blanket impl, an associated type, or a supertrait but a marker, is left out, since C never passes one, and a signature taking one from C is refused | | a type parameter or `impl` bounded by `Fn`, `FnMut`, or `FnOnce` alone, taking what a callback takes, objects by reference, or opaque values, and returning a scalar, a `String`, an opaque value, an `Option` of one, or a `Result` of one and a `String` | a C function and its `void *` data; one a lifetime bound or the return lets outlive the call, as kio's `clock::drive` and a spawned task's are, adds a `free` Rust calls once it drops it; a closure of any other signature is refused | | a type parameter or `impl` taken by value and bounded by `Future` or `IntoFuture`, whose every bound `Pin + Send>>` meets, as kio's `clock::timeout` takes, or taken as `Pin<&mut F>` by a poll, as kio's `Waiter::poll_future` takes | `_foreign_future`: a future of `()` C implements, which Rust takes as that type, or which the future the poll makes owns and pins; a future of another output is refused | diff --git a/ffi/fixtures/api/examples/transcript.rs b/ffi/fixtures/api/examples/transcript.rs index 5d2146ab2..4e1fee073 100644 --- a/ffi/fixtures/api/examples/transcript.rs +++ b/ffi/fixtures/api/examples/transcript.rs @@ -405,6 +405,27 @@ fn main() { let mut counted = kept; let same = api::Hits::eq(&mut counted, kept); println!("counted {same} {}", counted.hits); + // A packed value's fields are read into locals, as a reference to one is refused. + let mut regs = api::Regs::new(1, u64::MAX, Point { x: 3, y: -4 }); + let saved = regs; + regs.fcw = 9; + regs.at = Point { x: 5, y: 6 }; + let fcw = regs.fcw; + let wide = regs.wide; + let at = regs.at; + let tag = regs.tag; + let old_fcw = saved.fcw; + let old_wide = saved.wide; + let old_at = saved.at; + println!( + "regs {fcw} {wide} {} {} {tag} {} {old_fcw} {old_wide} {} {} {}", + at.x, + at.y, + regs.seed(), + old_at.x, + old_at.y, + regs == saved + ); let mut extent = api::Extent::new(5, 3); let start = extent; let old = extent.slide(10); diff --git a/ffi/fixtures/api/src/lib.rs b/ffi/fixtures/api/src/lib.rs index 5487cdff3..a06ab4dfe 100644 --- a/ffi/fixtures/api/src/lib.rs +++ b/ffi/fixtures/api/src/lib.rs @@ -2165,6 +2165,79 @@ impl Hits { } } +/// A packed value, as redox_syscall's `FloatRegisters` is: its fields lie unaligned, which +/// rustc lets no reference point at, so a getter copies out its `u16`, `u64`, and record, +/// and borrows the `u8`, which no packing misaligns. +#[derive(Clone, Copy, Debug, PartialEq)] +#[repr(C, packed)] +pub struct Regs { + pub fcw: u16, + pub wide: u64, + pub at: Point, + pub tag: u8, + seed: u8, +} + +impl Regs { + pub fn new(fcw: u16, wide: u64, at: Point) -> Self { + Self { + fcw, + wide, + at, + tag: 7, + seed: 1, + } + } + + pub fn seed(&self) -> u8 { + self.seed + } +} + +/// A packed object: its `String` and `Option` lie unaligned, so a getter clones what it +/// reads out of the field without dropping the original, its hasp, aligned to 1, is +/// lent from the folio in place, and its dock is lent through the reference it holds, which +/// is copied out. +#[repr(C, packed)] +pub struct Folio { + pub page: u16, + pub title: String, + pub note: Option, + pub hasp: Hasp, + pub dock: &'static Hasp, + seed: u8, +} + +static DOCK: Hasp = Hasp(std::sync::atomic::AtomicBool::new(false)); + +impl Folio { + pub fn new(page: u16, title: &str) -> Self { + Self { + page, + title: title.to_string(), + note: None, + hasp: Hasp::default(), + dock: &DOCK, + seed: 3, + } + } + + pub fn seed(&self) -> u8 { + self.seed + } +} + +/// A flag that is not `Clone` and one byte wide, so aligned wherever it lies. +#[derive(Default)] +pub struct Hasp(std::sync::atomic::AtomicBool); + +impl Hasp { + /// Sets the flag, returning whether it was set already. + pub fn set(&self) -> bool { + self.0.swap(true, std::sync::atomic::Ordering::Relaxed) + } +} + /// A span whose `pub` start sits beside a private length, which no record could hold. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Extent { diff --git a/ffi/fixtures/reject/expected.txt b/ffi/fixtures/reject/expected.txt index a74489c77..0b00c3f59 100644 --- a/ffi/fixtures/reject/expected.txt +++ b/ffi/fixtures/reject/expected.txt @@ -156,10 +156,14 @@ fixtures/reject/src/lib.rs:1623:2: rust2-ffi: cannot export method `Knot>`: type argument `std::vec::Vec` help: instantiate it at types that map, such as integers, `String`, or an exported type; `&str`, `Cow`, and other borrows do not fixtures/reject/src/lib.rs:167:1: rust2-ffi: cannot export instance `Cell`: type argument `tls::held::Cert` help: instantiate it at types that map, such as integers, `String`, or an exported type; `&str`, `Cow`, and other borrows do not +fixtures/reject/src/lib.rs:1681:2: rust2-ffi: cannot export field `Ledger::dial`: unaligned interior-mutable field `Dial` + help: hold the field behind an `Arc` or a `Box`, or take `repr(packed)` off the struct, since copying out an atomic or `Cell` unaligned would race a write through `&self` fixtures/reject/src/lib.rs:16:1: rust2-ffi: cannot export fn `generic`: generic parameter `std::marker::Copy` help: bound it by a trait the exporter maps, such as `Into`, `AsRef`, `Fn(..)`, or `IntoIterator`, or one of the crate's own traits, or take a concrete type fixtures/reject/src/lib.rs:170:1: rust2-ffi: cannot export fn `sealed`: refused type `reject::Cell` diff --git a/ffi/fixtures/reject/src/lib.rs b/ffi/fixtures/reject/src/lib.rs index a40e5fcbe..5ed772433 100644 --- a/ffi/fixtures/reject/src/lib.rs +++ b/ffi/fixtures/reject/src/lib.rs @@ -1635,3 +1635,62 @@ impl Rope>> { #[allow(dead_code, reason = "private, so no part of the API")] fn private(&self) {} } + +/// A packed object whose field is not `Clone` and lies unaligned, so a getter has no copy to +/// return and no aligned field to lend: the getter is refused, the setter kept. +#[repr(C, packed)] +pub struct Packed { + pub lone: Lone, + seed: u8, +} + +pub fn packed() -> Packed { + Packed { lone: Lone(2), seed: 0 } +} + +impl Packed { + pub fn seed(&self) -> u8 { + self.seed + } +} + +/// A `Clone` object holding an atomic, which another `&self` method may write while a getter +/// copies its bytes out unaligned: that read is non-atomic, so the getter is refused. +pub struct Dial(std::sync::atomic::AtomicU32); + +impl Clone for Dial { + fn clone(&self) -> Self { + Self(std::sync::atomic::AtomicU32::new( + self.0.load(std::sync::atomic::Ordering::Relaxed), + )) + } +} + +pub fn dial() -> Dial { + Dial(std::sync::atomic::AtomicU32::new(0)) +} + +impl Dial { + pub fn hit(&self) { + self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } +} + +#[repr(C, packed)] +pub struct Ledger { + pub dial: Dial, + seed: u8, +} + +pub fn ledger() -> Ledger { + Ledger { + dial: Dial(std::sync::atomic::AtomicU32::new(0)), + seed: 0, + } +} + +impl Ledger { + pub fn seed(&self) -> u8 { + self.seed + } +} diff --git a/ffi/src/collect.rs b/ffi/src/collect.rs index 09c9f8469..243ee7e86 100644 --- a/ffi/src/collect.rs +++ b/ffi/src/collect.rs @@ -30,7 +30,7 @@ use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _ use crate::ir::{ Access, Api, Callback, Closure, Collection, Constant, Dyn, Enum, Family, Field, Function, Held, Home, Int, Jni, - Literal, Mutability, Object, On, Order, Param, Path, Receiver, Record, Task, TaskKind, Traits, Type, Variant, + Literal, Mutability, Object, On, Order, Param, Path, Read, Receiver, Record, Task, TaskKind, Traits, Type, Variant, }; /// Why something is refused: a construct, ranked by the census, and what it names. @@ -77,6 +77,10 @@ pub(crate) const UNHELD: [&str; 5] = [ /// implements and C cannot: no value C holds could be passed for it. const UNMET: &str = "bound no type C holds meets"; +/// The construct of a field lent from a `repr(packed)` struct, where it may lie unaligned. +const UNALIGNED: &str = "lent unaligned field"; +const RACY: &str = "unaligned interior-mutable field"; + fn why(construct: &'static str, detail: impl Into) -> Why { Why { construct, @@ -2994,9 +2998,16 @@ impl<'tcx> Collector<'tcx> { let lends = handle && !self.is_clone(held) && matches!(object.kind(), ty::Adt(adt, args) if matches!(self.decl(adt.did(), *args), Some(Decl::Object(_)))); + let how = self.field_read(site, ty); let mapped = { self.lending.set(lends); - let get = self.ty(read, Pos::Return); + // A lent field is the field itself, which an unaligned one cannot be; one lent + // through a reference it holds is its pointee, which the copied reference reaches. + let get = match (lends && assigned && how != Read::Borrow, self.racy(how, ty)) { + (true, _) => Err(why(UNALIGNED, ty.to_string())), + (_, true) => Err(why(RACY, ty.to_string())), + _ => self.ty(read, Pos::Return), + }; self.lending.set(false); // A handle outlives every call, so a reference it holds is `'static`, which // C's borrow for the call is not. @@ -3011,7 +3022,11 @@ impl<'tcx> Collector<'tcx> { // crate's is not, is still written: its getter alone is refused, and the // setter keeps the type in the API, so one no export returns leaves out // both. - (Err(get), Ok(Some(set))) if get.construct == "borrowed return that is not Clone" => { + (Err(get), Ok(Some(set))) + if get.construct == "borrowed return that is not Clone" + || get.construct == UNALIGNED + || get.construct == RACY => + { self.refuse(&shown, "field", span, vec![get]); Ok((None, Some(set))) } @@ -3072,6 +3087,9 @@ impl<'tcx> Collector<'tcx> { access: Access::Field { set, through: !assigned, + read: how, + unfrozen: self.unfrozen(ty), + copy: self.copies(site, ty), }, instance: None, home: Home::default(), @@ -3097,6 +3115,50 @@ impl<'tcx> Collector<'tcx> { accessors } + /// How the glue reads a field of type `ty` of the struct `site`: rustc refuses a reference + /// to a `repr(packed)` struct's field whose alignment exceeds the packing (E0793), so + /// that one is copied out by value if it is `Copy`, else read unaligned into a + /// `ManuallyDrop`, which the getter takes its clone from, leaving the struct its owner. + fn field_read(&self, site: &Site<'tcx>, ty: Ty<'tcx>) -> Read { + let tcx = self.tcx; + let Some(pack) = tcx.adt_def(site.key.def_id).repr().pack else { + return Read::Borrow; + }; + let ty = tcx.erase_and_anonymize_regions(ty); + let input = TypingEnv::fully_monomorphized().as_query_input(ty); + if tcx.layout_of(input).is_ok_and(|layout| layout.align <= pack) { + return Read::Borrow; + } + match self.copies(site, ty) { + true => Read::Copy, + false => Read::Take, + } + } + + /// Whether a field of type `ty` of the struct `site` is `Copy` on this target: another + /// target of the same field, which reads it by `Copy`, may not have it so. + fn copies(&self, site: &Site<'tcx>, ty: Ty<'tcx>) -> bool { + let ty = self.tcx.erase_and_anonymize_regions(ty); + implements(self.tcx, ty, site.key.def_id, sym::Copy) + } + + /// Whether reading a field of type `ty` out unaligned, as `how` says, would race: a type + /// holding an `UnsafeCell` inline, such as an atomic, may be written through `&self` + /// while the read copies its bytes, and a non-atomic read of that is undefined behavior. + fn racy(&self, how: Read, ty: Ty<'tcx>) -> bool { + let tcx = self.tcx; + let ty = tcx.erase_and_anonymize_regions(ty); + how == Read::Take && !ty.is_freeze(tcx, TypingEnv::fully_monomorphized()) + } + + /// Whether a field of type `ty` holds an `UnsafeCell` inline: another target of the same + /// field, whose packing may differ, may read it unaligned, which would race there. + fn unfrozen(&self, ty: Ty<'tcx>) -> bool { + let tcx = self.tcx; + let ty = tcx.erase_and_anonymize_regions(ty); + !ty.is_freeze(tcx, TypingEnv::fully_monomorphized()) + } + /// A value's methods, refusing each through `&mut self`: C passes the value as a copy, /// so what the method changes would be lost. fn unmutated(&mut self, methods: Vec) -> Vec { diff --git a/ffi/src/glue.rs b/ffi/src/glue.rs index 34d7dfe3c..8901d5e9e 100644 --- a/ffi/src/glue.rs +++ b/ffi/src/glue.rs @@ -16,7 +16,7 @@ use rustc_data_structures::stable_hash::StableHasher; use crate::abi::{self, Abi, CFG, Ty}; use crate::config::Package; use crate::ir::{ - Access, Closure, Collection, Family, Function, Held, Jni, Literal, Mutability, On, Opaque, Receiver, Task, + Access, Closure, Collection, Family, Function, Held, Jni, Literal, Mutability, On, Opaque, Read, Receiver, Task, TaskKind, Traits, Type, }; @@ -3102,12 +3102,24 @@ impl Gen<'_> { ) } Access::Call => format!("{callee}({})", args.join(", ")), - Access::Field { set: false, through } => format!( - "&{}({}).{}", - if through { "*" } else { "" }, - args[0], - ident(function.name()) - ), + Access::Field { + set: false, + through, + read, + .. + } => { + let deref = if through { "*" } else { "" }; + let field = format!("({}).{}", args[0], ident(function.name())); + // An unaligned field of a packed struct is no reference's target: it is + // copied out, or read into a `ManuallyDrop` that the struct still owns. + match read { + Read::Borrow => format!("&{deref}{field}"), + Read::Copy => format!("&{deref}{{ {field} }}"), + Read::Take => format!( + "&{deref}*::std::mem::ManuallyDrop::new(unsafe {{ ::std::ptr::addr_of!({field}).read_unaligned() }})" + ), + } + } Access::Field { set: true, .. } => format!("({}).{} = {}", args[0], ident(function.name()), args[1]), Access::Const => callee, Access::Parse => format!( diff --git a/ffi/src/help.rs b/ffi/src/help.rs index 9eaafa9a1..ab99af3f4 100644 --- a/ffi/src/help.rs +++ b/ffi/src/help.rs @@ -133,6 +133,12 @@ pub(crate) fn of(construct: &str) -> Option<&'static str> { "borrowed return that is not Clone" => { "return an owned value or a `Clone` type, since a borrowed return crosses as a clone" } + "lent unaligned field" => { + "make the field `Clone` or a type aligned within the packing, or take `repr(packed)` off the struct, since rustc refuses a reference to an unaligned field and a handle cannot be lent from a copy" + } + "unaligned interior-mutable field" => { + "hold the field behind an `Arc` or a `Box`, or take `repr(packed)` off the struct, since copying out an atomic or `Cell` unaligned would race a write through `&self`" + } "&mut of a slice" => { "take `&[u8]` and return the changed `Vec`, or hold the buffer in an object; C lends no buffer mutably" } diff --git a/ffi/src/ir.rs b/ffi/src/ir.rs index 4f327a1ea..ebdb5e396 100644 --- a/ffi/src/ir.rs +++ b/ffi/src/ir.rs @@ -609,6 +609,17 @@ pub(crate) enum Access { set: bool, #[serde(default, skip_serializing_if = "std::ops::Not::not")] through: bool, + #[serde(default, skip_serializing_if = "Read::is_borrow")] + read: Read, + /// Whether the field holds an `UnsafeCell` inline, so that reading it unaligned, as + /// `Take` does, would race: no target where it does may merge with one reading it that + /// way, as its struct's packing may differ between targets. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + unfrozen: bool, + /// Whether the field's type is `Copy` on its target, which `Copy` reads it by: a merge + /// reads it that way for a target that borrows it only where that target has it so. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + copy: bool, }, /// It reads a constant that is not a `bool` or integer. Const, @@ -619,6 +630,33 @@ pub(crate) enum Access { Text, } +/// How a getter reads a field in Rust, which the field's struct decides: a `repr(packed)` +/// one's field may lie unaligned, which rustc refuses a reference to. +/// +/// A getter's value is the same through any mode that compiles, and the order is how far one +/// reaches: `Take` reads any field on any layout, `Copy` any `Copy` one. The merge of two +/// targets' getters of a field reads it the greater of theirs, but by `Take` rather than `Copy` +/// where a target that borrows the field does not have it `Copy` (`Access::Field`'s `copy`), +/// and not at all where that reads out unaligned what the other target holds an `UnsafeCell` +/// in (`unfrozen`), which is a difference between the targets. +#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] +pub(crate) enum Read { + /// It borrows the field. + #[default] + Borrow, + /// It copies the field out, as `Copy` allows of an unaligned one. + Copy, + /// It reads the field out unaligned into a `ManuallyDrop`, which never drops it: the + /// struct still owns and drops the original. + Take, +} + +impl Read { + fn is_borrow(&self) -> bool { + *self == Self::Borrow + } +} + impl Function { pub(crate) fn name(&self) -> &str { self.path.last().expect("a function has a name") diff --git a/ffi/src/merge.rs b/ffi/src/merge.rs index 3b7fb3076..e48344d3b 100644 --- a/ffi/src/merge.rs +++ b/ffi/src/merge.rs @@ -13,7 +13,8 @@ use rustc_span::source_map::SourceMap; use rustc_span::{DUMMY_SP, Span}; use crate::ir::{ - Api, Callback, Constant, Enum, Field, Function, Home, Object, On, Record, TaskKind, Traits, Type, Variant, + Access, Api, Callback, Constant, Enum, Field, Function, Home, Object, On, Read, Record, TaskKind, Traits, Type, + Variant, }; /// A target's API, as a check writes it for the export of several targets. @@ -202,6 +203,22 @@ fn bare(item: &T, clear: impl Fn(&mut T)) -> T { item } +/// Whether two functions read alike, which a field's two targets do whichever way its +/// layout makes each getter read it. +fn same_access(a: &Access, b: &Access) -> bool { + match (a, b) { + ( + Access::Field { set, through, .. }, + Access::Field { + set: other, + through: through_other, + .. + }, + ) => set == other && through == through_other, + _ => a == b, + } +} + pub(crate) fn bare_function(f: &Function) -> Function { bare(f, |f| { f.span = DUMMY_SP; @@ -210,6 +227,15 @@ pub(crate) fn bare_function(f: &Function) -> Function { f.on = On::ALL; // Merged apart, as a trait's leaves are. f.leaf = false; + // Merged to the greatest, as a target's layout may decide it. + if let Access::Field { + read, unfrozen, copy, .. + } = &mut f.access + { + *read = Read::Borrow; + *unfrozen = false; + *copy = false; + } }) } @@ -575,7 +601,7 @@ impl Merged { // A field's getter and setter share its path. let Some(at) = ours .iter() - .position(|f| f.shown == function.shown && f.access == function.access) + .position(|f| f.shown == function.shown && same_access(&f.access, &function.access)) else { ours.push(function); continue; @@ -584,6 +610,54 @@ impl Merged { let what = format!("fn `{}`", function.shown.join("::")); self.differ(what, (ours[at].on, ours[at].span), (function.on, function.span)); } + // One getter serves a field on every target, though `repr(packed)` may make one + // target's layout need another read than the next's: it reads by the mode that + // accepts both, whose value is the same, unless that is an unaligned read of what + // a target holds an `UnsafeCell` in, which would race there. A target that + // borrows a field that is not `Copy` there is not served by a `Copy` read, so + // that merges to `Take`. + let races = match (&mut ours[at].access, &function.access) { + ( + Access::Field { + set, + read: ours, + unfrozen: ours_unfrozen, + copy: ours_copy, + .. + }, + Access::Field { + read: theirs, + unfrozen: theirs_unfrozen, + copy: theirs_copy, + .. + }, + ) => { + let mut read = (*ours).max(*theirs); + if read == Read::Copy + && ((*ours == Read::Borrow && !*ours_copy) || (*theirs == Read::Borrow && !*theirs_copy)) + { + read = Read::Take; + } + // A setter assigns and never reads the field, so it cannot race. + let races = !*set + && read == Read::Take + && ((*ours != read && *ours_unfrozen) || (*theirs != read && *theirs_unfrozen)); + if !races { + *ours = read; + *ours_unfrozen |= *theirs_unfrozen; + *ours_copy &= *theirs_copy; + } + races + } + _ => false, + }; + if races { + let what = format!( + "fn `{}`, which one target reads out unaligned and another holds an atomic or `Cell` in", + function.shown.join("::") + ); + 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); @@ -845,7 +919,7 @@ mod tests { use rustc_span::DUMMY_SP; use super::{On, cycle, linked, order_crates}; - use crate::ir::{Api, Enum, Field, Home, Traits, Type, Variant}; + use crate::ir::{Access, Api, Enum, Field, Function, Home, Read, Traits, Type, Variant}; /// Docs keep the target's whose links resolve more, as one lacking an item does not. #[test] @@ -959,4 +1033,143 @@ mod tests { let (_, differs) = super::merge(vec![api("x", true), api("y", true)]); assert!(differs.is_empty()); } + + /// A packed struct's field may read another way on each target, by its layout there: the + /// merge keeps one getter for it, reading the way both accept, and no difference. + #[test] + fn merges_a_fields_getter_across_read_modes() { + let getter = |read: Read, unfrozen: bool| Function { + path: ["f", "Regs", "n"].map(String::from).to_vec(), + shown: ["f", "Regs", "n"].map(String::from).to_vec(), + span: DUMMY_SP, + on: On::ALL, + docs: String::new(), + deprecated: None, + receiver: Some(crate::ir::Receiver::Ref), + params: Vec::new(), + units: Vec::new(), + ok: Type::Int(crate::ir::Int::Usize), + err: None, + future: false, + eager: false, + holds: false, + task: None, + send: true, + collect: false, + lends: false, + lends_mut: false, + derefs: 0, + leaf: true, + ties: false, + access: Access::Field { + set: false, + through: false, + read, + unfrozen, + copy: read != Read::Take, + }, + instance: None, + home: Home::default(), + }; + let api = |target: &str, read: Read, unfrozen: bool| { + let path = ["f", "Regs"].map(String::from).to_vec(); + let record = crate::ir::Record { + path: path.clone(), + home: Home::default(), + shown: path, + args: Vec::new(), + span: DUMMY_SP, + on: On::ALL, + docs: String::new(), + deprecated: None, + fields: Vec::new(), + tuple: false, + methods: vec![getter(read, unfrozen)], + traits: Traits::default(), + opaque: None, + sizes: BTreeMap::new(), + }; + Api { + records: vec![record], + enums: Vec::new(), + objects: Vec::new(), + callbacks: Vec::new(), + functions: Vec::new(), + constants: Vec::new(), + crates: vec!["f".into()], + reached: Vec::new(), + profiles: Default::default(), + targets: vec![target.into()], + links: Default::default(), + } + }; + for (first, second) in [(Read::Borrow, Read::Copy), (Read::Copy, Read::Borrow)] { + let (merged, differs) = super::merge(vec![api("x", first, false), api("y", second, false)]); + assert!(differs.is_empty()); + let methods = &merged.records[0].methods; + assert_eq!(methods.len(), 1, "one getter for the field"); + assert_eq!(methods[0].on.0, 3); + assert!(matches!(methods[0].access, Access::Field { read: Read::Copy, .. })); + } + // An unaligned read of what one target holds an atomic in would race there. + let (merged, differs) = super::merge(vec![api("x", Read::Borrow, false), api("y", Read::Take, false)]); + assert!(differs.is_empty()); + assert!(matches!( + merged.records[0].methods[0].access, + Access::Field { read: Read::Take, .. } + )); + for (first, second) in [ + (api("x", Read::Borrow, true), api("y", Read::Take, false)), + (api("x", Read::Take, false), api("y", Read::Borrow, true)), + ] { + let (merged, differs) = super::merge(vec![first, second]); + assert_eq!(differs.len(), 1); + assert_eq!((differs[0].first.0.as_str(), differs[0].second.0.as_str()), ("x", "y")); + assert_eq!(merged.records[0].methods.len(), 1); + } + // A target that borrows what is not `Copy` there is not served by a `Copy` read: the + // merge reads by `Take`, and it still reports a field the other target holds an atomic in. + let uncopied = |mut api: Api| { + if let Access::Field { copy, .. } = &mut api.records[0].methods[0].access { + *copy = false; + } + api + }; + for (first, second) in [ + (uncopied(api("x", Read::Borrow, false)), api("y", Read::Copy, false)), + (api("x", Read::Copy, false), uncopied(api("y", Read::Borrow, false))), + ] { + let (merged, differs) = super::merge(vec![first, second]); + assert!(differs.is_empty()); + assert!(matches!( + merged.records[0].methods[0].access, + Access::Field { + read: Read::Take, + copy: false, + .. + } + )); + } + let (merged, differs) = super::merge(vec![ + uncopied(api("x", Read::Borrow, true)), + api("y", Read::Copy, false), + ]); + assert_eq!(differs.len(), 1); + assert_eq!(merged.records[0].methods.len(), 1); + // A setter never reads the field, so the same pair merges without a difference. + let setter = |mut api: Api| { + if let Access::Field { set, .. } = &mut api.records[0].methods[0].access { + *set = true; + } + api + }; + for (first, second) in [ + (api("x", Read::Borrow, true), api("y", Read::Take, true)), + (api("x", Read::Take, true), api("y", Read::Borrow, true)), + ] { + let (merged, differs) = super::merge(vec![setter(first), setter(second)]); + assert!(differs.is_empty()); + assert_eq!(merged.records[0].methods.len(), 1); + } + } } diff --git a/ffi/surface/api/c.h b/ffi/surface/api/c.h index 913db4800..7f7aa9aa9 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)0xa4b13378f22571caULL) +#define API_CONTRACT ((uint64_t)0xad26ecc1f5ae34e2ULL) uint64_t api_contract(void); uint32_t api_target(void); typedef int32_t api_status; @@ -114,6 +114,7 @@ typedef struct api_Waiter api_Waiter; typedef struct api_Feed api_Feed; typedef struct api_Countdown api_Countdown; typedef struct api_Retired api_Retired; +typedef struct api_Folio api_Folio; typedef struct api_Logger api_Logger; typedef struct api_Journal api_Journal; typedef struct api_Local api_Local; @@ -149,6 +150,7 @@ typedef struct api_Channel api_Channel; typedef struct api_Gap api_Gap; typedef struct api_Berth api_Berth; typedef struct api_Mark api_Mark; +typedef struct api_Hasp api_Hasp; typedef struct api_Message api_Message; typedef struct api_Node api_Node; typedef struct api_Tally api_Tally; @@ -733,6 +735,9 @@ typedef struct api_Rated { typedef struct api_Hits { uint64_t opaque[2]; } api_Hits; +typedef struct api_Regs { + uint8_t opaque[20]; +} api_Regs; typedef struct api_Extent { uint64_t opaque[2]; } api_Extent; @@ -1372,6 +1377,18 @@ void api_Hits_misses_set(api_Hits *self, uint64_t value); api_Hits api_Hits_of(uint64_t hits, uint64_t misses); void api_Hits_add(api_Hits *self, api_Hits other); bool api_Hits_eq_(api_Hits *self, api_Hits other); +bool api_Regs_eq(const api_Regs *a, const api_Regs *b); +API_MUST_USE api_buf api_Regs_debug(const api_Regs *self); +uint16_t api_Regs_fcw_get(const api_Regs *self); +void api_Regs_fcw_set(api_Regs *self, uint16_t value); +uint64_t api_Regs_wide_get(const api_Regs *self); +void api_Regs_wide_set(api_Regs *self, uint64_t value); +api_Point api_Regs_at_get(const api_Regs *self); +void api_Regs_at_set(api_Regs *self, api_Point value); +uint8_t api_Regs_tag_get(const api_Regs *self); +void api_Regs_tag_set(api_Regs *self, uint8_t value); +api_Regs api_Regs_new(uint16_t fcw, uint64_t wide, api_Point at); +uint8_t api_Regs_seed(const api_Regs *self); bool api_Extent_eq(const api_Extent *a, const api_Extent *b); API_MUST_USE api_buf api_Extent_debug(const api_Extent *self); uint64_t api_Extent_start_get(const api_Extent *self); @@ -1740,6 +1757,19 @@ API_MUST_USE api_Retired_next_future *api_Retired_next(api_Retired *self, api_st API_MUST_USE api_poll api_Retired_next_start(api_Retired *self, api_option_u32 *out, api_Retired_next_future **future, api_status *status); API_MUST_USE api_poll api_Retired_next_poll(api_Retired_next_future *future, api_waker waker, api_option_u32 *out); void api_Retired_next_future_free(api_Retired_next_future *future); +void api_Folio_free(api_Folio *self); +void api_Folio_drop(api_Folio *self, api_status *status); +uint16_t api_Folio_page_get(const api_Folio *self, api_status *status); +void api_Folio_page_set(api_Folio *self, uint16_t value, api_status *status); +API_MUST_USE api_buf api_Folio_title_get(const api_Folio *self, api_status *status); +void api_Folio_title_set(api_Folio *self, api_buf value, api_status *status); +API_MUST_USE api_buf api_Folio_note_get(const api_Folio *self, api_status *status); +void api_Folio_note_set(api_Folio *self, api_buf value, api_status *status); +API_MUST_USE api_Hasp *api_Folio_hasp_get(const api_Folio *self, api_status *status); +void api_Folio_hasp_set(api_Folio *self, api_Hasp *value, api_status *status); +API_MUST_USE api_Hasp *api_Folio_dock_get(const api_Folio *self, api_status *status); +API_MUST_USE api_Folio *api_Folio_new(uint16_t page, api_buf title); +uint8_t api_Folio_seed(const api_Folio *self, api_status *status); void api_Logger_free(api_Logger *self); API_MUST_USE api_Logger *api_Logger_new(api_Log sink); bool api_Logger_write(const api_Logger *self, api_buf line); @@ -2068,6 +2098,10 @@ API_MUST_USE api_buf api_Mark_debug(const api_Mark *self, api_status *status); API_MUST_USE api_Mark *api_Mark_of(uint64_t count); uint64_t api_Mark_count(const api_Mark *self, api_status *status); void api_Mark_add(api_Mark *self, uint64_t by, api_status *status); +void api_Hasp_free(api_Hasp *self); +void api_Hasp_drop(api_Hasp *self, api_status *status); +API_MUST_USE api_Hasp *api_Hasp_default(void); +bool api_Hasp_set(const api_Hasp *self, api_status *status); void api_Message_free(api_Message *self); void api_Message_drop(api_Message *self, api_status *status); API_MUST_USE api_Message *api_Message_clone(const api_Message *self, api_status *status); diff --git a/ffi/surface/api/cpp.hpp b/ffi/surface/api/cpp.hpp index ef4d81578..f3cc12dfb 100644 --- a/ffi/surface/api/cpp.hpp +++ b/ffi/surface/api/cpp.hpp @@ -166,6 +166,21 @@ namespace api { static ::api::Retired new_(::std::uint32_t from); [[deprecated("count with `Countdown`")]] RUST2_FFI_CALLABLE ::api::Retired_next_future next(); }; + class RUST2_FFI_CONSUMABLE Folio { + RUST2_FFI_UNCONSUMED Folio(Folio &&other RUST2_FFI_MOVED_FROM) noexcept = default; + Folio &operator=(Folio &&other) noexcept = default; + RUST2_FFI_CALLABLE ::std::uint16_t page_get() const; + RUST2_FFI_CALLABLE void page_set(::std::uint16_t value); + RUST2_FFI_CALLABLE ::api::buf title_get() const; + RUST2_FFI_CALLABLE void title_set(::api::input value); + RUST2_FFI_CALLABLE ::std::optional<::api::buf> note_get() const; + RUST2_FFI_CALLABLE void note_set(::std::optional<::api::input> value); + RUST2_FFI_CALLABLE ::api::Hasp hasp_get() const; + RUST2_FFI_CALLABLE void hasp_set(::api::Hasp value); + RUST2_FFI_CALLABLE ::api::Hasp dock_get() const; + static ::api::Folio new_(::std::uint16_t page, ::api::input title); + RUST2_FFI_CALLABLE ::std::uint8_t seed() const; + }; class RUST2_FFI_CONSUMABLE Logger { RUST2_FFI_UNCONSUMED Logger(Logger &&other RUST2_FFI_MOVED_FROM) noexcept = default; Logger &operator=(Logger &&other) noexcept = default; @@ -507,6 +522,12 @@ namespace api { RUST2_FFI_CALLABLE ::std::uint64_t count() const; RUST2_FFI_CALLABLE void add(::std::uint64_t by); }; + class RUST2_FFI_CONSUMABLE Hasp { + RUST2_FFI_UNCONSUMED Hasp(Hasp &&other RUST2_FFI_MOVED_FROM) noexcept = default; + Hasp &operator=(Hasp &&other) noexcept = default; + static Hasp default_(); + RUST2_FFI_CALLABLE bool set() const; + }; class RUST2_FFI_CONSUMABLE Message { RUST2_FFI_UNCONSUMED Message(Message &&other RUST2_FFI_MOVED_FROM) noexcept = default; Message &operator=(Message &&other) noexcept = default; @@ -1007,6 +1028,21 @@ namespace api { void add(const ::api::Hits &other); bool eq_(const ::api::Hits &other); }; + class Regs { + friend bool operator==(const Regs &a__, const Regs &b_); + friend bool operator!=(const Regs &a__, const Regs &b_); + ::api::buf debug() const; + ::std::uint16_t fcw_get() const; + void fcw_set(::std::uint16_t value); + ::std::uint64_t wide_get() const; + void wide_set(::std::uint64_t value); + ::api::Point at_get() const; + void at_set(const ::api::Point &value); + ::std::uint8_t tag_get() const; + void tag_set(::std::uint8_t value); + static ::api::Regs new_(::std::uint16_t fcw, ::std::uint64_t wide, const ::api::Point &at); + ::std::uint8_t seed() const; + }; class Extent { friend bool operator==(const Extent &a__, const Extent &b_); friend bool operator!=(const Extent &a__, const Extent &b_); @@ -1531,6 +1567,7 @@ namespace api { inline bool operator==(const Clocked &a__, const Clocked &b_); inline bool operator==(const Rated &a__, const Rated &b_); inline bool operator==(const Hits &a__, const Hits &b_); + inline bool operator==(const Regs &a__, const Regs &b_); inline bool operator==(const Extent &a__, const Extent &b_); inline bool operator==(const Pair_Size_u8 &a__, const Pair_Size_u8 &b_); inline bool operator==(const Pair_non_zero_u16 &a__, const Pair_non_zero_u16 &b_); @@ -2318,6 +2355,7 @@ namespace api { class Rated; class Score; class Hits; + class Regs; class Extent; struct Pair_Size_u8; struct Pair_non_zero_u16; @@ -2382,6 +2420,7 @@ namespace api { class Feed; class Countdown; class Retired; + class Folio; class Logger; class Journal; class Local; @@ -2417,6 +2456,7 @@ namespace api { class Gap; class Berth; class Mark; + class Hasp; class Message; class Node; class Tally; diff --git a/ffi/surface/api/dart.dart b/ffi/surface/api/dart.dart index c98e1dcc0..8d2128bdd 100644 --- a/ffi/surface/api/dart.dart +++ b/ffi/surface/api/dart.dart @@ -370,6 +370,21 @@ final class Hits { Hits add(Hits other); (Hits, bool) eq(Hits other); } +final class Regs { + String debug(); + @override bool operator ==(Object other); + @override int get hashCode; + int get fcwGet; + Regs fcwSet(int value); + U64 get wideGet; + Regs wideSet(U64 value); + Point get atGet; + Regs atSet(Point value); + int get tagGet; + Regs tagSet(int value); + factory Regs(int fcw, U64 wide, Point at); + int seed(); +} final class Extent { String debug(); @override bool operator ==(Object other); @@ -1229,6 +1244,19 @@ final class Retired extends _Object { @Deprecated('count with `Countdown`') Cancelable next(); @Deprecated('count with `Countdown`') dasync.Stream asStream(); } +final class Folio extends _Object { + int get pageGet; + void pageSet(int value); + String get titleGet; + void titleSet(String value); + String? get noteGet; + void noteSet(String? value); + Hasp get haspGet; + void haspSet(Hasp value); + Hasp get dockGet; + factory Folio(int page, String title); + int seed(); +} final class Logger extends _Object { factory Logger(Log sink); bool write(String line); @@ -1507,6 +1535,10 @@ final class Mark extends _Object { U64 count(); void add(U64 by); } +final class Hasp extends _Object { + factory Hasp.default_(); + bool set(); +} final class Message extends _Object { String debug(); Message clone(); diff --git a/ffi/surface/api/go.txt b/ffi/surface/api/go.txt index 3b439bef6..11cdee5f5 100644 --- a/ffi/surface/api/go.txt +++ b/ffi/surface/api/go.txt @@ -1035,6 +1035,21 @@ type FiledReceipt struct { func (self *FiledReceipt) Clone() (*FiledReceipt, error) func (self *FiledReceipt) Close() error func (self *FiledReceipt) Count() (uint32, error) +type Folio struct { + Handle_ *p_rt.Handle_ +} +func NewFolio(page uint16, title string) (*Folio, error) +func (self *Folio) Close() error +func (self *Folio) DockGet() (*Hasp, error) +func (self *Folio) HaspGet() (*Hasp, error) +func (self *Folio) HaspSet(value *Hasp) error +func (self *Folio) NoteGet() (*string, error) +func (self *Folio) NoteSet(value *string) error +func (self *Folio) PageGet() (uint16, error) +func (self *Folio) PageSet(value uint16) error +func (self *Folio) Seed() (uint8, error) +func (self *Folio) TitleGet() (string, error) +func (self *Folio) TitleSet(value string) error type Forged struct { Handle_ *p_rt.Handle_ } @@ -1084,6 +1099,12 @@ func (self *Handle) Count() (uint32, error) type Hasher struct { Seed uint8 } +type Hasp struct { + Handle_ *p_rt.Handle_ +} +func HaspDefault() *Hasp +func (self *Hasp) Close() error +func (self *Hasp) Set() (bool, error) type Hits struct { Bytes_ [2]uint64 Made_ bool @@ -1693,6 +1714,22 @@ func (self *Registry) FirstGet() (*Counter, error) func (self *Registry) FirstSet(value *Counter) error func (self *Registry) Last() (*Counter, error) func (self *Registry) Push(counter *Counter) error +type Regs struct { + Bytes_ [20]uint8 + Made_ bool +} +func NewRegs(fcw uint16, wide uint64, at Point) Regs +func (self Regs) AtGet() Point +func (self *Regs) AtSet(value Point) +func (self Regs) Equal(other Regs) bool +func (self Regs) FcwGet() uint16 +func (self *Regs) FcwSet(value uint16) +func (self Regs) GoString() string +func (self Regs) Seed() uint8 +func (self Regs) TagGet() uint8 +func (self *Regs) TagSet(value uint8) +func (self Regs) WideGet() uint64 +func (self *Regs) WideSet(value uint64) type Resolving struct { Handle_ *p_rt.Handle_ } diff --git a/ffi/surface/api/kotlin.kt b/ffi/surface/api/kotlin.kt index 033757cc5..08b385608 100644 --- a/ffi/surface/api/kotlin.kt +++ b/ffi/surface/api/kotlin.kt @@ -249,6 +249,23 @@ class Hits internal constructor() { @kotlin.jvm.JvmStatic fun of(hits: kotlin.ULong, misses: kotlin.ULong): api.Hits } } +class Regs internal constructor() { + fun debug(): kotlin.String + override fun equals(other: kotlin.Any?): kotlin.Boolean + override fun hashCode(): kotlin.Int + val fcwGet: kotlin.UShort + fun fcwSet(value: kotlin.UShort): api.Regs + val wideGet: kotlin.ULong + fun wideSet(value: kotlin.ULong): api.Regs + val atGet: api.Point + fun atSet(value: api.Point): api.Regs + val tagGet: kotlin.UByte + fun tagSet(value: kotlin.UByte): api.Regs + fun seed(): kotlin.UByte + companion object { + @kotlin.jvm.JvmStatic fun new(fcw: kotlin.UShort, wide: kotlin.ULong, at: api.Point): api.Regs + } +} class Extent internal constructor() { fun debug(): kotlin.String override fun equals(other: kotlin.Any?): kotlin.Boolean @@ -773,6 +790,22 @@ class Retired internal constructor(raw: Long, lent: Boolean = false) : AutoClose @kotlin.jvm.JvmStatic fun new(from: kotlin.UInt): api.Retired } } +class Folio internal constructor(raw: Long, lent: Boolean = false) : AutoCloseable { + override fun close() + val pageGet: kotlin.UShort + fun pageSet(value: kotlin.UShort) + val titleGet: kotlin.String + fun titleSet(value: kotlin.String) + val noteGet: kotlin.String? + fun noteSet(value: kotlin.String?) + val haspGet: api.Hasp + fun haspSet(value: api.Hasp) + val dockGet: api.Hasp + fun seed(): kotlin.UByte + companion object { + @kotlin.jvm.JvmStatic fun new(page: kotlin.UShort, title: kotlin.String): api.Folio + } +} class Logger internal constructor(raw: Long, lent: Boolean = false) : AutoCloseable { override fun close() fun write(line: kotlin.String): kotlin.Boolean @@ -1153,6 +1186,13 @@ class Mark internal constructor(raw: Long, lent: Boolean = false) : AutoCloseabl @kotlin.jvm.JvmStatic fun of(count: kotlin.ULong): api.Mark } } +class Hasp internal constructor(raw: Long, lent: Boolean = false) : AutoCloseable { + override fun close() + fun set(): kotlin.Boolean + companion object { + @kotlin.jvm.JvmStatic fun default(): api.Hasp + } +} class Message internal constructor(raw: Long, lent: Boolean = false) : AutoCloseable { override fun close() fun debug(): kotlin.String diff --git a/ffi/surface/api/python.pyi b/ffi/surface/api/python.pyi index 264f1ca9e..6dbd6eee7 100644 --- a/ffi/surface/api/python.pyi +++ b/ffi/surface/api/python.pyi @@ -1,5 +1,5 @@ # api.py -__all__ = ['A', 'Area', 'Array', 'ArrayU8x4', 'Atlas', 'B', 'BOXED', 'Batch', 'Batch2', 'Beat', 'Berth', 'Board', 'Booth', 'Bound', 'BoundU64', 'BoundsU64', 'BoundsU64Exception', 'BoxedU16', 'BoxedU8', 'Buffer', 'Builtin', 'C', 'CancellationError', 'Cancelled', 'Channel', 'Choice', 'Clash', 'ClashAny', 'ClashBreak', 'ClashCandidate', 'ClashChange', 'ClashDescribed', 'ClashEmptyString', 'ClashEraser', 'ClashErrno', 'ClashEscaped', 'ClashLevel', 'ClashMalformed', 'ClashMalformedException', 'ClashOp', 'ClashReader', 'ClashSeed', 'ClashSource', 'ClashSpan', 'ClashStore', 'ClashTag', 'ClashTone', 'ClashTone_', 'ClashUnderscored', 'Clocked', 'Codecs', 'Core', 'Countdown', 'Counter', 'Cursor', 'Deprecated', 'Der', 'Dial', 'Digest', 'DoubleArray', 'Draft', 'Duration', 'EOF', 'Error', 'ErrorException', 'Event', 'Extent', 'FAR', 'Family', 'Fault', 'FaultException', 'Feed', 'FiledReceipt', 'ForeignReader', 'Forged', 'GREETINGS', 'Gap', 'Gauge', 'Guarded', 'Handle', 'Hasher', 'Hits', 'Holder', 'Hooked', 'InnerU8', 'Instant', 'Journal', 'Json', 'JvmField', 'JvmStatic', 'Key', 'Knob', 'LIMIT', 'Label', 'Labeled', 'Labelled', 'Latch', 'Layered', 'Ledger', 'LeftRightU8', 'LeftU8', 'Level', 'LimitsBytes', 'LimitsDuration', 'ListClashToneException', 'Local', 'LocalWaiter', 'Log', 'LogCount', 'LogThread', 'Logger', 'LongArray', 'MacrosStreams', 'Mark', 'Marker', 'Measure', 'Message', 'Meter', 'Meters', 'Moment', 'Mut', 'Name', 'Node', 'NonZeros', 'Note', 'Numbers', 'OptIn', 'OuterInnerU8', 'PRIMES', 'Packaged', 'Packet', 'PadU16', 'PadU8', 'Page', 'PairNonZeroU16', 'PairSizeU8', 'PairU32', 'PairU8Size', 'Parcel', 'Part', 'Pass', 'Peer', 'Pinned', 'Placement', 'Plain', 'Platform', 'Point', 'PolarPoint', 'PolarTurn', 'Polar_Turn', 'Qualifiers', 'Quantity', 'Rank', 'Rated', 'Reading', 'Receipt', 'Refusal', 'RefusalException', 'Registry', 'Resolving', 'Retired', 'Retry', 'RightLeftU8', 'RightU8', 'STEP', 'Scan', 'Score', 'Seat', 'Shadowed', 'Shape', 'Sheet', 'Site', 'Size', 'Slip', 'SlotU32', 'SlotU8', 'Span', 'Spawned', 'Spot', 'Stack', 'Stage', 'Stamp', 'Stamped', 'StartSeekable', 'Status', 'StdIoError', 'Stretch', 'StringException', 'Tab', 'Tag', 'Tallies', 'Tally', 'Ticket', 'Tier', 'TlsCert', 'TlsCodec', 'TlsConfig', 'TlsPolicyLifetime', 'TlsResolver', 'TlsSession', 'Token', 'Trail', 'Turner', 'URL', 'Undo', 'Url', 'VecClashTone', 'Verbosity', 'Version', 'Waiter', 'Waker', 'Weighted', 'Wide', 'Window', 'Worker', 'WrapU32', 'Wrapped', '__all___', '__all____', '_deprecated_', 'admit', 'advance', 'after', 'alpn', 'alpn_lent', 'apply_non_zero_u16', 'apply_u32', 'area', 'assert_', 'attempt', 'beats', 'below', 'booth_count', 'boxed_counter', 'boxed_floats', 'boxed_name', 'boxed_tuple', 'breadth', 'bump_both', 'bump_either', 'bumped', 'byte_len', 'byte_limits', 'capacities_2_2', 'capacities_2_4', 'capacities_4_2', 'capacities_4_4', 'cert_der', 'cert_len', 'certify', 'chain_len', 'choose', 'chunks', 'clash_any', 'clash_audible', 'clash_audio_encoder_finish', 'clash_audio_encoder_finish_', 'clash_candidate', 'clash_described', 'clash_empty', 'clash_erase', 'clash_erase_', 'clash_erased', 'clash_ignore', 'clash_lend', 'clash_lend_', 'clash_nested', 'clash_run', 'clash_underscored', 'clash_underscored_next', 'clash_waited', 'clocked_after', 'coordinates', 'corner', 'corner_later', 'count', 'counted', 'counters', 'crammed', 'cross', 'crowded', 'deprecated', 'describe', 'describe_non_zeros', 'digit', 'divide', 'doubled', 'doubled_i64', 'doubled_ttl', 'drain_2', 'drain_4', 'drive', 'dropped', 'each', 'either', 'either_later', 'emit', 'emit_from_thread', 'emit_later', 'encode', 'end', 'ends', 'entries', 'erased', 'errno', 'excuse', 'extended', 'failure', 'failure_kind', 'failure_message', 'farther_hop', 'file', 'fill_2', 'fill_4', 'filter', 'find', 'fingerprint', 'first_of', 'flip', 'greet', 'grow', 'halved', 'halves', 'has_instant', 'has_text', 'heft', 'held_count', 'hex', 'hook', 'host', 'is_family', 'is_kept', 'jam', 'jni_one', 'join_words', 'joined', 'jvm_sum', 'keep_point', 'keeper_point', 'keeps', 'kept_counter', 'kept_or_point', 'kept_point', 'kept_polar_point', 'kept_size', 'kept_wrap_u32', 'knob', 'lasting', 'later', 'layer_name', 'least', 'len', 'lent_back', 'less', 'lettered', 'level_later', 'local_after', 'local_later', 'local_or_new', 'local_or_new_later', 'locals_dropped', 'log_counts', 'log_later', 'log_on_drop', 'log_waker', 'longer', 'longest', 'louder', 'macros_streamed', 'made', 'marked', 'measured', 'moment_at', 'named', 'negated', 'next_char', 'next_hop', 'next_ips', 'next_packet', 'nexts', 'non_zeros', 'now', 'nudge', 'nudge_by', 'numbered', 'offered_len', 'offset', 'offsetof', 'on_first_thread', 'only', 'page', 'pair', 'paired', 'parents', 'parse_cert', 'parse_later', 'peek', 'placement', 'platform', 'pointer_bits', 'polar_point', 'poll_tripled', 'port', 'ports', 'prefixed', 'push_counted', 'put_number', 'queued_hex', 'reach', 'read_len', 'reading', 'reading_bump', 'reading_debug', 'reading_echo', 'reasons', 'refuse', 'reissue', 'reissue_lent', 'relay', 'report_non_zero_u16', 'report_u32', 'resolve', 'resolved', 'resolver', 'resume', 'return_moved', 'return_values', 'rooted_name', 'rows', 'same', 'same_char', 'same_duration', 'same_ip_addr', 'same_isize', 'same_labelled', 'same_path', 'same_socket_addr', 'same_socket_addr_v4', 'same_socket_addr_v6', 'same_string', 'same_u128', 'same_u64', 'same_usize', 'sample_hex', 'scaled', 'scanned', 'seat', 'second_later', 'sections', 'secure', 'seeds_counter_counter', 'seeds_counter_point', 'seeds_counter_polar_point', 'seeds_counter_size', 'seeds_counter_wrap_u32', 'seeds_point_counter', 'seeds_point_point', 'seeds_point_polar_point', 'seeds_point_size', 'seeds_point_wrap_u32', 'seek_to', 'sentence', 'shift', 'shifted', 'since', 'span', 'spell', 'spend', 'split_last', 'spread', 'stamp_at', 'stored', 'stored_text', 'stray', 'stretched', 'sum_all', 'sum_lists', 'sum_u32', 'summed', 'summed_up_receipt', 'sums', 'swapped', 'tag', 'tagged', 'tail', 'tallied', 'tally_log_count', 'tick_name', 'tickets', 'timed_hex', 'title', 'token_bytes', 'token_slice', 'total', 'turned', 'undone', 'unescaped', 'unescaped_later', 'unescaped_maybe', 'unhook', 'unnamed', 'unwound', 'unzeroed', 'verify', 'visit_chunks', 'visit_stray', 'walk', 'wasm_log', 'wasm_only', 'wasm_take', 'watch', 'weigh_all_counter', 'weigh_point', 'wexitstatus', 'wide', 'widen', 'widths', 'wind', 'within', 'words', 'worth', 'yielded'] +__all__ = ['A', 'Area', 'Array', 'ArrayU8x4', 'Atlas', 'B', 'BOXED', 'Batch', 'Batch2', 'Beat', 'Berth', 'Board', 'Booth', 'Bound', 'BoundU64', 'BoundsU64', 'BoundsU64Exception', 'BoxedU16', 'BoxedU8', 'Buffer', 'Builtin', 'C', 'CancellationError', 'Cancelled', 'Channel', 'Choice', 'Clash', 'ClashAny', 'ClashBreak', 'ClashCandidate', 'ClashChange', 'ClashDescribed', 'ClashEmptyString', 'ClashEraser', 'ClashErrno', 'ClashEscaped', 'ClashLevel', 'ClashMalformed', 'ClashMalformedException', 'ClashOp', 'ClashReader', 'ClashSeed', 'ClashSource', 'ClashSpan', 'ClashStore', 'ClashTag', 'ClashTone', 'ClashTone_', 'ClashUnderscored', 'Clocked', 'Codecs', 'Core', 'Countdown', 'Counter', 'Cursor', 'Deprecated', 'Der', 'Dial', 'Digest', 'DoubleArray', 'Draft', 'Duration', 'EOF', 'Error', 'ErrorException', 'Event', 'Extent', 'FAR', 'Family', 'Fault', 'FaultException', 'Feed', 'FiledReceipt', 'Folio', 'ForeignReader', 'Forged', 'GREETINGS', 'Gap', 'Gauge', 'Guarded', 'Handle', 'Hasher', 'Hasp', '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', 'Regs', 'Resolving', 'Retired', 'Retry', 'RightLeftU8', 'RightU8', 'STEP', 'Scan', 'Score', 'Seat', 'Shadowed', 'Shape', 'Sheet', 'Site', 'Size', 'Slip', 'SlotU32', 'SlotU8', 'Span', 'Spawned', 'Spot', 'Stack', 'Stage', 'Stamp', 'Stamped', 'StartSeekable', 'Status', 'StdIoError', 'Stretch', 'StringException', 'Tab', 'Tag', 'Tallies', 'Tally', 'Ticket', 'Tier', 'TlsCert', 'TlsCodec', 'TlsConfig', 'TlsPolicyLifetime', 'TlsResolver', 'TlsSession', 'Token', 'Trail', 'Turner', 'URL', 'Undo', 'Url', 'VecClashTone', 'Verbosity', 'Version', 'Waiter', 'Waker', 'Weighted', 'Wide', 'Window', 'Worker', 'WrapU32', 'Wrapped', '__all___', '__all____', '_deprecated_', 'admit', 'advance', 'after', 'alpn', 'alpn_lent', 'apply_non_zero_u16', 'apply_u32', 'area', 'assert_', 'attempt', 'beats', 'below', 'booth_count', 'boxed_counter', 'boxed_floats', 'boxed_name', 'boxed_tuple', 'breadth', 'bump_both', 'bump_either', 'bumped', 'byte_len', 'byte_limits', 'capacities_2_2', 'capacities_2_4', 'capacities_4_2', 'capacities_4_4', 'cert_der', 'cert_len', 'certify', 'chain_len', 'choose', 'chunks', 'clash_any', 'clash_audible', 'clash_audio_encoder_finish', 'clash_audio_encoder_finish_', 'clash_candidate', 'clash_described', 'clash_empty', 'clash_erase', 'clash_erase_', 'clash_erased', 'clash_ignore', 'clash_lend', 'clash_lend_', 'clash_nested', 'clash_run', 'clash_underscored', 'clash_underscored_next', 'clash_waited', 'clocked_after', 'coordinates', 'corner', 'corner_later', 'count', 'counted', 'counters', 'crammed', 'cross', 'crowded', 'deprecated', 'describe', 'describe_non_zeros', 'digit', 'divide', 'doubled', 'doubled_i64', 'doubled_ttl', 'drain_2', 'drain_4', 'drive', 'dropped', 'each', 'either', 'either_later', 'emit', 'emit_from_thread', 'emit_later', 'encode', 'end', 'ends', 'entries', 'erased', 'errno', 'excuse', 'extended', 'failure', 'failure_kind', 'failure_message', 'farther_hop', 'file', 'fill_2', 'fill_4', 'filter', 'find', 'fingerprint', 'first_of', 'flip', 'greet', 'grow', 'halved', 'halves', 'has_instant', 'has_text', 'heft', 'held_count', 'hex', 'hook', 'host', 'is_family', 'is_kept', 'jam', 'jni_one', 'join_words', 'joined', 'jvm_sum', 'keep_point', 'keeper_point', 'keeps', 'kept_counter', 'kept_or_point', 'kept_point', 'kept_polar_point', 'kept_size', 'kept_wrap_u32', 'knob', 'lasting', 'later', 'layer_name', 'least', 'len', 'lent_back', 'less', 'lettered', 'level_later', 'local_after', 'local_later', 'local_or_new', 'local_or_new_later', 'locals_dropped', 'log_counts', 'log_later', 'log_on_drop', 'log_waker', 'longer', 'longest', 'louder', 'macros_streamed', 'made', 'marked', 'measured', 'moment_at', 'named', 'negated', 'next_char', 'next_hop', 'next_ips', 'next_packet', 'nexts', 'non_zeros', 'now', 'nudge', 'nudge_by', 'numbered', 'offered_len', 'offset', 'offsetof', 'on_first_thread', 'only', 'page', 'pair', 'paired', 'parents', 'parse_cert', 'parse_later', 'peek', 'placement', 'platform', 'pointer_bits', 'polar_point', 'poll_tripled', 'port', 'ports', 'prefixed', 'push_counted', 'put_number', 'queued_hex', 'reach', 'read_len', 'reading', 'reading_bump', 'reading_debug', 'reading_echo', 'reasons', 'refuse', 'reissue', 'reissue_lent', 'relay', 'report_non_zero_u16', 'report_u32', 'resolve', 'resolved', 'resolver', 'resume', 'return_moved', 'return_values', 'rooted_name', 'rows', 'same', 'same_char', 'same_duration', 'same_ip_addr', 'same_isize', 'same_labelled', 'same_path', 'same_socket_addr', 'same_socket_addr_v4', 'same_socket_addr_v6', 'same_string', 'same_u128', 'same_u64', 'same_usize', 'sample_hex', 'scaled', 'scanned', 'seat', 'second_later', 'sections', 'secure', 'seeds_counter_counter', 'seeds_counter_point', 'seeds_counter_polar_point', 'seeds_counter_size', 'seeds_counter_wrap_u32', 'seeds_point_counter', 'seeds_point_point', 'seeds_point_polar_point', 'seeds_point_size', 'seeds_point_wrap_u32', 'seek_to', 'sentence', 'shift', 'shifted', 'since', 'span', 'spell', 'spend', 'split_last', 'spread', 'stamp_at', 'stored', 'stored_text', 'stray', 'stretched', 'sum_all', 'sum_lists', 'sum_u32', 'summed', 'summed_up_receipt', 'sums', 'swapped', 'tag', 'tagged', 'tail', 'tallied', 'tally_log_count', 'tick_name', 'tickets', 'timed_hex', 'title', 'token_bytes', 'token_slice', 'total', 'turned', 'undone', 'unescaped', 'unescaped_later', 'unescaped_maybe', 'unhook', 'unnamed', 'unwound', 'unzeroed', 'verify', 'visit_chunks', 'visit_stray', 'walk', 'wasm_log', 'wasm_only', 'wasm_take', 'watch', 'weigh_all_counter', 'weigh_point', 'wexitstatus', 'wide', 'widen', 'widths', 'wind', 'within', 'words', 'worth', 'yielded'] class Waker: def __init__(self, wake: _typing.Callable[[], _object], loop: _asyncio.AbstractEventLoop | None=None) -> None: ... def wake(self) -> None: ... @@ -229,6 +229,24 @@ class Hits(_n.Value): def of(hits: _int, misses: _int) -> Hits: ... def add(self, other: Hits) -> Hits: ... def eq(self, other: Hits) -> _tuple[Hits, _bool]: ... +class Regs(_n.Value): + def __eq__(self, other: _object) -> _bool: ... + def __repr__(self) -> _str: ... + @_property + def fcw_get(self) -> _int: ... + def fcw_set(self, value: _int) -> Regs: ... + @_property + def wide_get(self) -> _int: ... + def wide_set(self, value: _int) -> Regs: ... + @_property + def at_get(self) -> Point: ... + def at_set(self, value: Point) -> Regs: ... + @_property + def tag_get(self) -> _int: ... + def tag_set(self, value: _int) -> Regs: ... + @_staticmethod + def new(fcw: _int, wide: _int, at: Point) -> Regs: ... + def seed(self) -> _int: ... class Extent(_n.Value): def __eq__(self, other: _object) -> _bool: ... def __repr__(self) -> _str: ... @@ -982,6 +1000,24 @@ class Retired(_n.Object): async def __anext__(self) -> _int: ... @_staticmethod def new(from_: _int) -> Retired: ... +class Folio(_n.Object): + @_property + def page_get(self) -> _int: ... + def page_set(self, value: _int) -> None: ... + @_property + def title_get(self) -> _str: ... + def title_set(self, value: _str) -> None: ... + @_property + def note_get(self) -> _str | None: ... + def note_set(self, value: _str | None) -> None: ... + @_property + def hasp_get(self) -> Hasp: ... + def hasp_set(self, value: Hasp) -> None: ... + @_property + def dock_get(self) -> Hasp: ... + @_staticmethod + def new(page: _int, title: _str) -> Folio: ... + def seed(self) -> _int: ... class Logger(_n.Object): @_staticmethod def new(sink: Log) -> Logger: ... @@ -1289,6 +1325,10 @@ class Mark(_n.Object): def of(count: _int) -> Mark: ... def count(self) -> _int: ... def add(self, by: _int) -> None: ... +class Hasp(_n.Object): + @_staticmethod + def default() -> Hasp: ... + def set(self) -> _bool: ... class Message(_n.Object): def __repr__(self) -> _str: ... def clone(self) -> Message: ... diff --git a/ffi/surface/api/swift.swift b/ffi/surface/api/swift.swift index 48b6ea52f..28d162ee2 100644 --- a/ffi/surface/api/swift.swift +++ b/ffi/surface/api/swift.swift @@ -361,6 +361,20 @@ public struct Hits: Sendable, CustomDebugStringConvertible, Equatable { @inlinable public mutating func add(_ other: Hits) @inlinable public mutating func eq(_ other: Hits) -> Swift.Bool } +public struct Regs: Sendable, CustomDebugStringConvertible, Equatable { + @inlinable public var debugDescription: Swift.String { get } + @inlinable public static func == (a: Regs, b: Regs) -> Swift.Bool + @inlinable public var fcwGet: Swift.UInt16 { get } + @inlinable public mutating func fcwSet(_ value: Swift.UInt16) + @inlinable public var wideGet: Swift.UInt64 { get } + @inlinable public mutating func wideSet(_ value: Swift.UInt64) + @inlinable public var atGet: Point { get } + @inlinable public mutating func atSet(_ value: Point) + @inlinable public var tagGet: Swift.UInt8 { get } + @inlinable public mutating func tagSet(_ value: Swift.UInt8) + @inlinable public static func new(_ fcw: Swift.UInt16, _ wide: Swift.UInt64, _ at: Point) -> Regs + @inlinable public func seed() -> Swift.UInt8 +} public struct Extent: Sendable, CustomDebugStringConvertible, Equatable { @inlinable public var debugDescription: Swift.String { get } @inlinable public static func == (a: Extent, b: Extent) -> Swift.Bool @@ -1035,6 +1049,19 @@ public struct Retired: ~Copyable, @unchecked Sendable { @available(*, deprecated, message: "count with `Countdown`") @inlinable nonisolated(nonsending) public mutating func next() async throws -> Swift.UInt32? @available(*, deprecated, message: "count with `Countdown`") @inlinable public consuming func stream() -> RetiredStream } +public struct Folio: ~Copyable, @unchecked Sendable { + @inlinable public var pageGet: Swift.UInt16 { get } + @inlinable public mutating func pageSet(_ value: Swift.UInt16) throws + @inlinable public var titleGet: Swift.String { get } + @inlinable public mutating func titleSet(_ value: Swift.String) throws + @inlinable public var noteGet: Swift.String? { get } + @inlinable public mutating func noteSet(_ value: Swift.String?) throws + @inlinable public func haspGet() throws -> Hasp + @inlinable public mutating func haspSet(_ value: consuming Hasp) throws + @inlinable public func dockGet() throws -> Hasp + @inlinable public static func new(_ page: Swift.UInt16, _ title: Swift.String) -> Folio + @inlinable public func seed() throws -> Swift.UInt8 +} public struct Logger: ~Copyable, @unchecked Sendable { @inlinable public static func new(_ sink: any Log) -> Logger @inlinable public func write(_ line: Swift.String) -> Swift.Bool @@ -1315,6 +1342,10 @@ public final class Mark: @unchecked Sendable { @inlinable public func count() throws -> Swift.UInt64 @inlinable public func add(_ by: Swift.UInt64) throws } +public struct Hasp: ~Copyable, @unchecked Sendable { + @inlinable public static func `default`() -> Hasp + @inlinable public func set() throws -> Swift.Bool +} public struct Message: ~Copyable, @unchecked Sendable { @inlinable public var debugDescription: Swift.String { get } @inlinable public func clone() throws -> Message diff --git a/ffi/surface/api/web.d.ts b/ffi/surface/api/web.d.ts index ae8a8a0e7..e067a239a 100644 --- a/ffi/surface/api/web.d.ts +++ b/ffi/surface/api/web.d.ts @@ -631,6 +631,23 @@ export type FiledReceipt = rt.Handle<"FiledReceipt">; export declare function clone(self: FiledReceipt): FiledReceipt; export declare function count(self: FiledReceipt): number; +// Folio.ts +import * as rt from "./rt.ts"; +import type { Hasp } from "./Hasp.ts"; +export type Folio = rt.Handle<"Folio">; +export declare function pageGet(self: Folio): number; +export declare function pageSet(self: Folio, value: number): void; +export declare function titleGet(self: Folio): string; +export declare function titleSet(self: Folio, value: string): void; +export declare function noteGet(self: Folio): string | undefined; +export declare function noteSet(self: Folio, value: string | undefined): void; +export declare function haspGet(self: Folio): Hasp; +export declare function haspSet(self: Folio, value: Hasp): void; +export declare function dockGet(self: Folio): Hasp; +export declare function new$(page: number, title: string): Folio; +export declare function seed(self: Folio): number; +export { new$ as new }; + // Gap.ts import * as rt from "./rt.ts"; export type Gap = rt.Handle<"Gap">; @@ -666,6 +683,13 @@ export type Hasher = { seed: number; }; +// Hasp.ts +import * as rt from "./rt.ts"; +export type Hasp = rt.Handle<"Hasp">; +export declare function default$(): Hasp; +export declare function set(self: Hasp): boolean; +export { default$ as default }; + // Hits.ts import * as rt from "./rt.ts"; export type Hits = rt.Opaque<"Hits">; @@ -1367,6 +1391,24 @@ export declare function push(self: Registry, counter: Counter): void; export declare function edit(self: Registry, edit: (a0: Counter) => boolean): boolean; export { default$ as default, new$ as new }; +// Regs.ts +import * as rt from "./rt.ts"; +import type { Point } from "./Point.ts"; +export type Regs = rt.Opaque<"Regs">; +export declare function debug(self: Regs): string; +export declare function eq(a: Regs, b: Regs): boolean; +export declare function fcwGet(self: Regs): number; +export declare function fcwSet(self: Regs, value: number): Regs; +export declare function wideGet(self: Regs): rt.u64; +export declare function wideSet(self: Regs, value: rt.u64): Regs; +export declare function atGet(self: Regs): Point; +export declare function atSet(self: Regs, value: Point): Regs; +export declare function tagGet(self: Regs): number; +export declare function tagSet(self: Regs, value: number): Regs; +export declare function new$(fcw: number, wide: rt.u64, at: Point): Regs; +export declare function seed(self: Regs): number; +export { new$ as new }; + // Resolving.ts import * as rt from "./rt.ts"; import type { TlsResolver } from "./TlsResolver.ts"; @@ -1929,6 +1971,7 @@ import type { Rank } from "./Rank.ts"; import type { Rated } from "./Rated.ts"; import type { Reading } from "./Reading.ts"; import type { Refusal } from "./Refusal.ts"; +import type { Regs } from "./Regs.ts"; import type { RightLeftU8 } from "./RightLeftU8.ts"; import type { RightU8 } from "./RightU8.ts"; import type { Score } from "./Score.ts"; @@ -2006,9 +2049,11 @@ export declare const k_Draft: rt.Kind; export declare const k_Fault: rt.Kind; export declare const k_Feed: rt.Kind; export declare const k_Filed_Receipt: rt.Kind; +export declare const k_Folio: rt.Kind; export declare const k_Gap: rt.Kind; export declare const k_Gauge: rt.Kind; export declare const k_Handle: rt.Kind; +export declare const k_Hasp: rt.Kind; export declare const k_Holder: rt.Kind; export declare const k_Instant: rt.Kind; export declare const k_Journal: rt.Kind; @@ -2143,6 +2188,7 @@ export declare function r_Platform(p: number, o: boolean): Platform; export declare function r_Point(p: number, o: boolean): Point; export declare function r_Rated(p: number, o: boolean): Rated; export declare function r_Reading(p: number, o: boolean): Reading; +export declare function r_Regs(p: number, o: boolean): Regs; export declare function r_Score(p: number, o: boolean): Score; export declare function r_Seat(p: number, o: boolean): Seat; export declare function r_Size(p: number, o: boolean): Size; @@ -2347,6 +2393,7 @@ export declare function w_Qualifiers(p: number, v: Qualifiers): void; export declare function w_Rank(p: number, v: Rank): void; export declare function w_Rated(p: number, v: Rated): void; export declare function w_Reading(p: number, v: Reading): void; +export declare function w_Regs(p: number, v: Regs): void; export declare function w_Right_Left_u8(p: number, v: RightLeftU8): void; export declare function w_Right_u8(p: number, v: RightU8): void; export declare function w_Score(p: number, v: Score): void; diff --git a/ffi/tests/api.c b/ffi/tests/api.c index 30983d14c..49388de79 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -1567,6 +1567,51 @@ static int statuses(void) { api_Meter_free(first); api_Meters_free(meters); + /* A packed object's fields are read and written where they lie unaligned: a `String` is + * cloned from its field and the folio still drops the original, and its latch, which + * no packing misaligns, is lent in place. */ + status = 0; + api_Folio *folio = api_Folio_new(5, str("title")); + api_buf title = api_Folio_title_get(folio, &status); + if (status != 0 || title.len != 5 || memcmp(title.ptr, "title", 5) != 0) { + fprintf(stderr, "a packed folio's title is %.*s\n", (int)title.len, (const char *)title.ptr); + failed = 1; + } + api_buf_free(title); + api_Folio_title_set(folio, str("renamed"), &status); + api_Folio_note_set(folio, str("a note"), &status); + api_Folio_page_set(folio, 9, &status); + title = api_Folio_title_get(folio, &status); + api_buf note = api_Folio_note_get(folio, &status); + if (status != 0 || api_Folio_page_get(folio, &status) != 9 || api_Folio_seed(folio, &status) != 3 || + title.len != 7 || memcmp(title.ptr, "renamed", 7) != 0 || note.len != 6 || + memcmp(note.ptr, "a note", 6) != 0) { + fprintf(stderr, "a packed folio's fields read %.*s %.*s, status %d\n", (int)title.len, + (const char *)title.ptr, (int)note.len, (const char *)note.ptr, status); + failed = 1; + } + api_buf_free(title); + api_buf_free(note); + api_Hasp *hasp = api_Folio_hasp_get(folio, &status); + api_Hasp *again = api_Folio_hasp_get(folio, &status); + bool first_set = api_Hasp_set(hasp, &status); + if (first_set || !api_Hasp_set(again, &status) || status != 0) { + fprintf(stderr, "a packed folio's hasp is not the one it holds, status %d\n", status); + failed = 1; + } + api_Hasp_free(hasp); + api_Hasp_free(again); + api_Hasp *dock = api_Folio_dock_get(folio, &status); + api_Hasp *docked = api_Folio_dock_get(folio, &status); + bool dock_first = api_Hasp_set(dock, &status); + if (dock_first || !api_Hasp_set(docked, &status) || status != 0) { + fprintf(stderr, "a packed folio's dock is not the one it points to, status %d\n", status); + failed = 1; + } + api_Hasp_free(dock); + api_Hasp_free(docked); + api_Folio_free(folio); + /* A counter moved in beside a dropped mark, alone or held in a record or an enum, is * refused before the move, so the counter is still there; once every mark is live, * the call moves it. */ diff --git a/quest/m1/ffi-packed-fields.md b/quest/m1/ffi-packed-fields.md deleted file mode 100644 index 82d182b12..000000000 --- a/quest/m1/ffi-packed-fields.md +++ /dev/null @@ -1,25 +0,0 @@ -# [S] Read a packed record's fields without a reference - -## Goal - -A `#[repr(packed)]` record's field binds: the glue that reads one, as Python's field -getters do, builds, so redox_syscall's `FloatRegisters` binds in every language. - -## Plan - -Decided with the maintainer on 2026-11-19, in the pick of [#919](https://github.com/kixel-ai/rust2/pull/919): ✅ kept as planned (rejected: dropping it). - -Found by the corpus on 2026-11-20, binding redox_syscall without the items its census -refuses: the Python glue's getter of `FloatRegisters::fcw` is `&(&a_self).fcw`, which rustc -refuses as a reference to a packed struct's field (E0793). - -Recommended: reduce it to a packed record in the api fixture, with a `Copy` field and one -that is not, such as a `String`, since `repr(packed)` makes no field `Copy`. Wherever the -glue now borrows a packed field, copy a `Copy` one out by value, `{ a_self.fcw }`, and read -any other unaligned into a `ManuallyDrop` to take what the getter takes from it, as its -clone, so the record still owns and drops the original. A getter that lends the field, as -`Collector::accessors` lends a non-`Clone` object field from the receiver's handle, has no -copy to lend from: it lends the field itself only where rustc allows the reference, a field -aligned to 1, and refuses any other with the field's span. - -Public API: none.