mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b321c094d2 | ||
|
|
d4768d606f | ||
|
|
148008c695 | ||
|
|
2b5845464c | ||
|
|
5e388cb38f | ||
|
|
49daf2895e | ||
|
|
682d3dafbd | ||
|
|
ad03b5b0bf | ||
|
|
324925aedb | ||
|
|
e78a987e3e | ||
|
|
2c8fa44eb4 | ||
|
|
6b22316077 | ||
|
|
98cabee4c6 | ||
|
|
e0848abc59 | ||
|
|
f237a5ee50 |
No files matched your search
@@ -1433,6 +1433,18 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
|
||||
}
|
||||
|
||||
// Rebuild stale Rasterize subgraphs from before the async-source conversion gave the inner proto node a unit primary input (5 inputs, now 6).
|
||||
if let DocumentNodeImplementation::Network(inner) = &node.implementation
|
||||
&& inner
|
||||
.nodes
|
||||
.values()
|
||||
.any(|n| n.inputs.len() == 5 && matches!(&n.implementation, DocumentNodeImplementation::ProtoNode(id) if id.as_str().contains("rasterize")))
|
||||
&& document.network_interface.reference(node_id, network_path) == Some(DefinitionIdentifier::Network("Rasterize".into()))
|
||||
&& let Some(node_definition) = resolve_document_node_type(&DefinitionIdentifier::Network("Rasterize".into()))
|
||||
{
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
|
||||
}
|
||||
|
||||
// Upgrade old nodes to use `Context` instead of `()` or `Footprint` as their call argument
|
||||
if node.call_argument == graph_craft::concrete!(()) || node.call_argument == graph_craft::concrete!(graphene_std::transform::Footprint) {
|
||||
document.network_interface.set_call_argument(node_id, network_path, graph_craft::concrete!(graphene_std::Context));
|
||||
|
||||
@@ -33,6 +33,20 @@ fn over_budget(used: usize, budget: usize) -> bool {
|
||||
used >= budget / 8 * 7
|
||||
}
|
||||
|
||||
/// The deep element glue is filled by runtime registration: ctors at load
|
||||
/// natively, host-invoked exports on wasm. A lifetime-carrying element whose
|
||||
/// glue never registered takes the shallow clone-out path, which brands its
|
||||
/// arena borrows `'static` for a memo to hold across a reset, so a missed
|
||||
/// registration is caught here rather than at the first capture.
|
||||
fn assert_deep_element_glue() {
|
||||
for (name, registered) in [
|
||||
("graphic", core_types::record::has_deep_element_glue(std::any::TypeId::of::<graphic_types::Graphic<'static>>())),
|
||||
("artboard", core_types::record::has_deep_element_glue(std::any::TypeId::of::<graphic_types::Artboard<'static>>())),
|
||||
] {
|
||||
assert!(registered, "deep element glue for `{name}` is missing; run `__node_registry_deep_element_{name}` first");
|
||||
}
|
||||
}
|
||||
|
||||
fn new_arena(capacity: usize) -> Arena {
|
||||
Arena::new(capacity).unwrap_or_else(|| {
|
||||
log::error!("arena generations exhausted; continuing without frame caching");
|
||||
@@ -66,6 +80,7 @@ fn noop_runtime() -> Arc<DynGraphRuntime> {
|
||||
|
||||
impl Default for DynamicExecutor {
|
||||
fn default() -> Self {
|
||||
assert_deep_element_glue();
|
||||
Self {
|
||||
output: Default::default(),
|
||||
tree: Default::default(),
|
||||
@@ -96,6 +111,7 @@ pub struct ResolvedDocumentNodeTypesDelta {
|
||||
|
||||
impl DynamicExecutor {
|
||||
pub fn new(mut proto_network: ProtoNetwork) -> Result<Self, GraphErrors> {
|
||||
assert_deep_element_glue();
|
||||
let mut typing_context = TypingContext::new(&node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&mut proto_network)?;
|
||||
let output = proto_network.output;
|
||||
|
||||
@@ -27,11 +27,12 @@ pub struct Arena {
|
||||
/// a park costs one pointer in the arena and owns its content outside it.
|
||||
retained_heap: AtomicUsize,
|
||||
/// Where [`Arena::move_park`] sent each moved park, as its offset here to
|
||||
/// the header's address in the receiving arena and the moved type's key, so
|
||||
/// a payload two records share is moved once and a mistyped sharer is
|
||||
/// refused. Cleared by [`Arena::reset`], so a forwarding holds for one
|
||||
/// generation.
|
||||
forwarded: Mutex<HashMap<usize, (usize, TypeId)>>,
|
||||
/// the header's address in the receiving arena, the moved type's key and
|
||||
/// that arena's generation, so a payload two records share is moved once
|
||||
/// while a mistyped sharer, a sharer naming another destination, and a
|
||||
/// sharer whose destination has since flushed are all refused. Cleared by
|
||||
/// [`Arena::reset`], so a forwarding holds for one generation.
|
||||
forwarded: Mutex<HashMap<usize, (usize, TypeId, u64)>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Arena {
|
||||
@@ -53,6 +54,9 @@ struct DropEntry {
|
||||
|
||||
/// The glue a tombstoned entry carries: its payload was moved to another arena,
|
||||
/// which now owns the obligation.
|
||||
///
|
||||
/// # Safety
|
||||
/// None: the payload is neither read nor dropped, so any pointer is accepted.
|
||||
unsafe fn inert(_: *mut u8) {}
|
||||
|
||||
/// The entry parking `offset`, `None` where the arena holds no obligation for
|
||||
@@ -236,11 +240,15 @@ impl Arena {
|
||||
// Built before the write so an unencodable offset drops `value` here
|
||||
// rather than stranding it in the arena without drop glue.
|
||||
let weak = ArenaWeak::new(self.generation(), offset)?;
|
||||
// SAFETY: `reserve` returned `offset`, so it is within the backbone.
|
||||
let ptr = unsafe { self.base().add(offset) }.cast::<T>();
|
||||
// SAFETY: freshly reserved, aligned, in-bounds, unaliased.
|
||||
unsafe { ptr.write(value) };
|
||||
if std::mem::needs_drop::<T>() {
|
||||
/// # Safety
|
||||
/// `p` must address the live `T` this entry was registered for.
|
||||
unsafe fn glue<T>(p: *mut u8) {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { p.cast::<T>().drop_in_place() }
|
||||
}
|
||||
self.drops.lock().unwrap().push(DropEntry { offset, type_of, drop_fn: glue::<T>, retained });
|
||||
@@ -264,6 +272,12 @@ impl Arena {
|
||||
/// fan-out sharer's second move reaches the one header and the obligation
|
||||
/// is never duplicated.
|
||||
///
|
||||
/// A forwarding is to one destination generation, since the returned
|
||||
/// pointer is only the caller's to publish where it lands in the `dst` it
|
||||
/// named: a second move to another arena, or to one that has flushed since,
|
||||
/// is refused rather than answered with a foreign or freed header. The
|
||||
/// refusal reads as a decline, so the caller takes its clone path.
|
||||
///
|
||||
/// `dst` is credited `retained`, which is what a clone of the payload would
|
||||
/// have credited it, and this arena is debited what its own park recorded,
|
||||
/// so neither counter reads worse than it did before the move.
|
||||
@@ -290,8 +304,11 @@ impl Arena {
|
||||
(offset < self.buf.len()).then_some(())?;
|
||||
let type_of = TypeId::of::<T::Static>();
|
||||
let mut forwarded = self.forwarded.lock().unwrap();
|
||||
if let Some(&(moved, moved_type)) = forwarded.get(&offset) {
|
||||
if let Some(&(moved, moved_type, moved_generation)) = forwarded.get(&offset) {
|
||||
(moved_type == type_of).then_some(())?;
|
||||
// Generations are globally unique, so the match is `dst` itself and
|
||||
// its current epoch; anything else declines.
|
||||
(moved_generation == dst.generation()).then_some(())?;
|
||||
return Some(moved as *const T::Static);
|
||||
}
|
||||
let mut entries = self.drops.lock().unwrap();
|
||||
@@ -305,7 +322,10 @@ impl Arena {
|
||||
let parked = std::mem::replace(&mut entries[entry].retained, 0);
|
||||
entries[entry].drop_fn = inert;
|
||||
drop(entries);
|
||||
/// # Safety
|
||||
/// `p` must address the live `T` this entry was registered for.
|
||||
unsafe fn glue<T>(p: *mut u8) {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { p.cast::<T>().drop_in_place() }
|
||||
}
|
||||
dst.drops.lock().unwrap().push(DropEntry {
|
||||
@@ -316,7 +336,7 @@ impl Arena {
|
||||
});
|
||||
dst.retained_heap.fetch_add(retained, Ordering::Relaxed);
|
||||
let _ = self.retained_heap.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| Some(current.saturating_sub(parked)));
|
||||
forwarded.insert(offset, (target as usize, type_of));
|
||||
forwarded.insert(offset, (target as usize, type_of, dst.generation()));
|
||||
Some(target.cast_const())
|
||||
}
|
||||
|
||||
@@ -335,6 +355,7 @@ impl Arena {
|
||||
pub fn alloc_scratch<T: Send + Sync>(&self, len: usize) -> Option<&mut [MaybeUninit<T>]> {
|
||||
let size = size_of::<T>().checked_mul(len)?;
|
||||
let offset = self.reserve(size, align_of::<T>())?;
|
||||
// SAFETY: `reserve` returned `offset`, so it is within the backbone.
|
||||
let ptr = unsafe { self.base().add(offset) }.cast::<MaybeUninit<T>>();
|
||||
// SAFETY: exclusive region; lifetime tied to `&self`, and `reset` takes
|
||||
// `&mut self`, so the slice cannot outlive the generation.
|
||||
@@ -344,9 +365,13 @@ impl Arena {
|
||||
/// The generation-checked handle for a region this arena holds, `None` for
|
||||
/// a pointer from anywhere else. The handle keeps the region's provenance,
|
||||
/// so a cache stores one where it would otherwise launder an address.
|
||||
///
|
||||
/// The offset must sit below the bump watermark, not merely inside the
|
||||
/// backbone: [`ArenaWeak::upgrade`] hands out a `&T` at it, so only bytes a
|
||||
/// reservation already handed out may be minted into a handle.
|
||||
pub fn handle_at(&self, ptr: *const u8) -> Option<ArenaWeak<u8>> {
|
||||
let offset = (ptr as usize).checked_sub(self.base() as usize)?;
|
||||
(offset < self.buf.len()).then_some(())?;
|
||||
(offset < self.offset.load(Ordering::Acquire)).then_some(())?;
|
||||
ArenaWeak::new(self.generation(), offset)
|
||||
}
|
||||
|
||||
@@ -362,13 +387,14 @@ impl Arena {
|
||||
self.forwarded.get_mut().unwrap().clear();
|
||||
self.generation.store(PARKED_GENERATION, Ordering::Release);
|
||||
for entry in entries.into_iter().rev() {
|
||||
// Debited before the glue runs: a panicking destructor drops the
|
||||
// remaining entries unglued, so a hint subtracted afterwards would
|
||||
// strand on the counter for the arena's whole life.
|
||||
let retained = self.retained_heap.get_mut();
|
||||
*retained = retained.saturating_sub(entry.retained);
|
||||
// SAFETY: registered at alloc time; insert-only means the region was
|
||||
// never overwritten within this generation.
|
||||
unsafe { (entry.drop_fn)(base.add(entry.offset)) }
|
||||
// Decremented as each payload's heap is freed, so an unwinding reset
|
||||
// leaves the counter matching what is still parked.
|
||||
let retained = self.retained_heap.get_mut();
|
||||
*retained = retained.saturating_sub(entry.retained);
|
||||
}
|
||||
*self.offset.get_mut() = 0;
|
||||
*self.exhausted.get_mut() = false;
|
||||
@@ -550,6 +576,57 @@ mod tests {
|
||||
assert!(cell.load(&arena).is_none(), "a half-dropped generation must resolve no handle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_mint_only_over_reserved_bytes() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let (value, _) = arena.alloc(41u32).unwrap();
|
||||
let ptr = std::ptr::from_ref(value).cast::<u8>();
|
||||
assert!(arena.handle_at(ptr).is_some(), "a byte the bump handed out mints a handle");
|
||||
|
||||
let unreserved = ptr.wrapping_add(64);
|
||||
assert!(arena.contains(unreserved), "the fixture stays inside the backbone");
|
||||
assert!(arena.handle_at(unreserved).is_none(), "a byte past the watermark mints nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_forwarding_answers_only_the_destination_it_recorded() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
struct Probe(#[allow(dead_code)] String);
|
||||
unsafe impl dyn_any::StaticType for Probe {
|
||||
type Static = Probe;
|
||||
}
|
||||
let transient = Arena::new(1024).unwrap();
|
||||
let mut first = Arena::new(1024).unwrap();
|
||||
let second = Arena::new(1024).unwrap();
|
||||
|
||||
let (parked, _) = transient.alloc_sized_keyed(Probe(String::from("shared by two records")), 21).unwrap();
|
||||
let src = std::ptr::from_ref(parked).cast::<u8>();
|
||||
unsafe { transient.move_park::<Probe>(src, &first, 21) }.unwrap();
|
||||
|
||||
assert!(unsafe { transient.move_park::<Probe>(src, &second, 21) }.is_none(), "a sharer naming another destination is refused");
|
||||
first.reset();
|
||||
assert!(unsafe { transient.move_park::<Probe>(src, &first, 21) }.is_none(), "a flushed destination is refused too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_panicking_destructor_does_not_strand_the_retained_hint() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
struct Bomb;
|
||||
impl Drop for Bomb {
|
||||
fn drop(&mut self) {
|
||||
panic!("payload destructor");
|
||||
}
|
||||
}
|
||||
let mut arena = Arena::new(1024).unwrap();
|
||||
arena.alloc_sized(Bomb, 64).unwrap();
|
||||
assert_eq!(arena.retained_heap(), 64);
|
||||
|
||||
let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| arena.reset()));
|
||||
assert!(unwound.is_err(), "the panic must propagate out of reset");
|
||||
assert_eq!(arena.retained_heap(), 0, "the hint is debited before the glue that panics");
|
||||
}
|
||||
|
||||
/// Held by every test that perturbs [`NEXT_GENERATION`], so a swapped-out counter
|
||||
/// is never observed by a concurrently constructing test.
|
||||
static COUNTER_GUARD: Mutex<()> = Mutex::new(());
|
||||
|
||||
@@ -20,15 +20,35 @@ use std::sync::{LazyLock, Mutex};
|
||||
|
||||
/// Declares an attribute name: one marker per name, fixing the value type and
|
||||
/// the name-specific default. Declare markers through the [`attribute!`]
|
||||
/// macro, which also registers them into the [`ATTRIBUTE_REGISTRY`].
|
||||
pub trait Attribute: 'static {
|
||||
/// macro, which also registers them into the [`ATTRIBUTE_REGISTRY`] and emits
|
||||
/// an impl meeting the obligations below.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// [`REPARK`](Self::REPARK) must be `Some` for every marker whose
|
||||
/// [`Value<'e>`](Self::Value) can carry a borrow shorter than `'static`. The
|
||||
/// plain-value arm of the census writer retypes the value [`from_stored`] hands
|
||||
/// it from the stored form's lifetime to the field's, which is only a relabel
|
||||
/// where the value borrows nothing; a re-parking marker instead writes a
|
||||
/// reference into the arena it is given.
|
||||
///
|
||||
/// [`from_stored`](Self::from_stored) must accept exactly the erased form
|
||||
/// [`read_erased`](Self::read_erased) produces, and [`read_erased`] must read
|
||||
/// its `ptr` as this marker's own `Value`. The two are each other's inverse
|
||||
/// across every persistence seam, so a marker that reads one type and stores
|
||||
/// another writes a value of the wrong type into the field.
|
||||
pub unsafe trait Attribute: 'static {
|
||||
/// The name as it appears in documents and diagnostics.
|
||||
const NAME: &'static str;
|
||||
/// The value type every read and write of this name shares. The lifetime
|
||||
/// is the evaluation the value flows in; non-reference values ignore it.
|
||||
/// The value outlives that evaluation, so its `'static` instantiation is
|
||||
/// the one the census registers and layouts stamp their type id from.
|
||||
type Value<'e>: Copy + Default + std::fmt::Debug + 'e;
|
||||
///
|
||||
/// `Send + Sync` because a record's bytes are these values: `RecordValue`
|
||||
/// is `Send + Sync` over whatever the field writes put there, and the write
|
||||
/// path never consults the census, so the bound has to sit here.
|
||||
type Value<'e>: Copy + Default + std::fmt::Debug + Send + Sync + 'e;
|
||||
/// The name-specific default, filled where an item lacks the attribute.
|
||||
/// Producing a value for any `'e` from no inputs, reference defaults can
|
||||
/// only point at `'static` data, which is what lets the census fill them
|
||||
@@ -151,6 +171,13 @@ pub struct AttributeInfo {
|
||||
/// Writes a legacy stored value into a field of this marker, parking
|
||||
/// droppable payloads. A wrong-typed stored value leaves the field
|
||||
/// untouched; `None` reports arena exhaustion.
|
||||
///
|
||||
/// `dst` must address a live field of *this row's* value type: the glue
|
||||
/// writes its own `Value`'s worth of bytes there, so a caller resolving the
|
||||
/// field by [`name`](Self::name) checks [`size`](Self::size) and
|
||||
/// [`value_type`](Self::value_type) against the field first. The fields
|
||||
/// here are public and the struct is `Copy`, so a row is a claim about a
|
||||
/// marker rather than a proof about a field.
|
||||
pub write_stored: unsafe fn(&dyn AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>,
|
||||
}
|
||||
|
||||
@@ -172,12 +199,15 @@ where
|
||||
crate::record::FieldWrite::of::<A>(level)
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `dst` must address a live field of `A`'s value type.
|
||||
unsafe fn write_stored<A: Attribute>(stored: &dyn AnyAttributeValue, dst: *mut u8, arena: &crate::arena::Arena) -> Option<()> {
|
||||
if A::from_stored(stored.as_any()).is_none() {
|
||||
// A wrong-typed stored value reads as absent, so the field keeps its default.
|
||||
return Some(());
|
||||
}
|
||||
match A::REPARK {
|
||||
// SAFETY: the caller's contract; the glue is this marker's own.
|
||||
Some(repark) => unsafe { repark(stored, dst, arena) },
|
||||
None => {
|
||||
let value = A::from_stored(stored.as_any()).expect("checked above");
|
||||
@@ -256,7 +286,10 @@ macro_rules! attribute {
|
||||
$(#[$meta])*
|
||||
$vis struct $marker;
|
||||
|
||||
impl $crate::attribute::Attribute for $marker {
|
||||
// SAFETY: the reference-valued arms emit `REPARK`, the plain arm's value
|
||||
// type cannot name `'e`, and `read_erased` and `from_stored` are emitted
|
||||
// as each other's inverse.
|
||||
unsafe impl $crate::attribute::Attribute for $marker {
|
||||
const NAME: &'static str = $name;
|
||||
type Value<'e> = ::core::option::Option<&'e $value>;
|
||||
|
||||
@@ -295,7 +328,10 @@ macro_rules! attribute {
|
||||
$(#[$meta])*
|
||||
$vis struct $marker;
|
||||
|
||||
impl $crate::attribute::Attribute for $marker {
|
||||
// SAFETY: the reference-valued arms emit `REPARK`, the plain arm's value
|
||||
// type cannot name `'e`, and `read_erased` and `from_stored` are emitted
|
||||
// as each other's inverse.
|
||||
unsafe impl $crate::attribute::Attribute for $marker {
|
||||
const NAME: &'static str = $name;
|
||||
type Value<'e> = &'e $value;
|
||||
$(
|
||||
@@ -330,7 +366,10 @@ macro_rules! attribute {
|
||||
$(#[$meta])*
|
||||
$vis struct $marker;
|
||||
|
||||
impl $crate::attribute::Attribute for $marker {
|
||||
// SAFETY: the reference-valued arms emit `REPARK`, the plain arm's value
|
||||
// type cannot name `'e`, and `read_erased` and `from_stored` are emitted
|
||||
// as each other's inverse.
|
||||
unsafe impl $crate::attribute::Attribute for $marker {
|
||||
const NAME: &'static str = $name;
|
||||
type Value<'e> = $value;
|
||||
$(
|
||||
@@ -486,7 +525,8 @@ mod tests {
|
||||
#[should_panic(expected = "two value types")]
|
||||
fn a_second_marker_at_a_different_type_panics() {
|
||||
struct Conflict;
|
||||
impl Attribute for Conflict {
|
||||
// SAFETY: `bool` borrows nothing, so the plain-value arm is the right one.
|
||||
unsafe impl Attribute for Conflict {
|
||||
const NAME: &'static str = "opacity";
|
||||
type Value<'e> = bool;
|
||||
|
||||
|
||||
@@ -375,6 +375,7 @@ impl CacheHash for AttributeDyn {
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: the type carries no lifetime, so it is its own static form.
|
||||
unsafe impl StaticType for AttributeDyn {
|
||||
type Static = Self;
|
||||
}
|
||||
@@ -418,6 +419,7 @@ impl CacheHash for AttributeValueDyn {
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: as for AttributeDyn.
|
||||
unsafe impl StaticType for AttributeValueDyn {
|
||||
type Static = Self;
|
||||
}
|
||||
@@ -501,6 +503,7 @@ impl CacheHash for ListDyn {
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: as for AttributeDyn.
|
||||
unsafe impl StaticType for ListDyn {
|
||||
type Static = Self;
|
||||
}
|
||||
@@ -1190,6 +1193,8 @@ impl<T> ApplyTransform for List<T> {
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: the list carries its lifetime only through T, so substituting T's
|
||||
// static form substitutes the list's and keeps the layout identical.
|
||||
unsafe impl<T: StaticTypeSized> StaticType for List<T> {
|
||||
type Static = List<T::Static>;
|
||||
}
|
||||
|
||||
@@ -50,9 +50,10 @@ impl std::fmt::Debug for RecordValue<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: `element_write` requires the element `Send + Sync` and attribute payloads
|
||||
// are `Copy` or arena-backed, so the record bytes behind the pointer are thread-safe;
|
||||
// `'e` ties the pointer's validity to the shared arena and record-stack discipline.
|
||||
// SAFETY: `element_write` requires the element `Send + Sync` and every field holds an
|
||||
// `Attribute::Value`, which the trait bounds `Send + Sync`, so the record bytes behind
|
||||
// the pointer are thread-safe; `'e` ties the pointer's validity to the shared arena and
|
||||
// record-stack discipline.
|
||||
unsafe impl Send for RecordValue<'_> {}
|
||||
// SAFETY: as `Send`.
|
||||
unsafe impl Sync for RecordValue<'_> {}
|
||||
|
||||
@@ -214,6 +214,7 @@ impl<'a, 'e, N> RecordInput<'a, 'e, N> {
|
||||
/// `rec` must be a record of the layout the offsets were resolved against
|
||||
/// and `El` its element type; both are proven at wiring.
|
||||
unsafe fn element_only<El: Clone>(rec: Rec<'_>, _reads: &[Option<usize>]) -> El {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { read_element::<El>(rec) }
|
||||
}
|
||||
|
||||
@@ -516,6 +517,8 @@ impl<El: Clone + 'static, N> RecordExtract<El, N> {
|
||||
// The element copies out by value, so the input's claim dies with
|
||||
// the scope.
|
||||
let scope = frames.scope();
|
||||
// SAFETY: the served value is a record of `self.layout`, whose element is
|
||||
// `El` by the wiring that built this extract.
|
||||
serve_input(&self.edge, input, &scope).map(|value| unsafe { read_element::<El>(self.layout.rec(&value)) })
|
||||
}
|
||||
}
|
||||
@@ -28,11 +28,17 @@ impl FieldWrite {
|
||||
where
|
||||
A::Value<'static>: graphene_hash::CacheHash + PartialEq + 'static,
|
||||
{
|
||||
/// # Safety
|
||||
/// `ptr` must address a live `V`.
|
||||
unsafe fn content_hash<V: graphene_hash::CacheHash>(ptr: *const u8, state: &mut dyn core::hash::Hasher) {
|
||||
let mut state = state;
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { &*ptr.cast::<V>() }.cache_hash(&mut state);
|
||||
}
|
||||
/// # Safety
|
||||
/// `a` and `b` must both address a live `V`.
|
||||
unsafe fn content_eq<V: PartialEq>(a: *const u8, b: *const u8) -> bool {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { *a.cast::<V>() == *b.cast::<V>() }
|
||||
}
|
||||
Self {
|
||||
@@ -132,12 +138,18 @@ impl Eq for ElementWrite {}
|
||||
|
||||
impl Default for ElementWrite {
|
||||
fn default() -> Self {
|
||||
/// # Safety
|
||||
/// None: the empty element has no bytes, so nothing is read.
|
||||
unsafe fn clone_out(_ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync> {
|
||||
Box::new(())
|
||||
}
|
||||
/// # Safety
|
||||
/// None: nothing is written, the empty element having no slot.
|
||||
unsafe fn repark(_value: &(dyn std::any::Any + Send + Sync), _dst: *mut u8, _arena: &crate::arena::Arena) -> Option<()> {
|
||||
Some(())
|
||||
}
|
||||
/// # Safety
|
||||
/// None: the move always declines, so `parked` is never read.
|
||||
unsafe fn park_move(_parked: *const u8, _promotion: &Promotion<'_>) -> Option<*const u8> {
|
||||
None
|
||||
}
|
||||
@@ -508,22 +520,32 @@ pub fn element_write<T: Clone + Send + Sync + dyn_any::StaticTypeSized>() -> Ele
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
/// # Safety
|
||||
/// `ptr` must address a live element of `T` in the form [`element_parked`] picks.
|
||||
unsafe fn clone_out<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync>
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
if let Some(deep) = deep_element_glue(std::any::TypeId::of::<T::Static>()) {
|
||||
// SAFETY: the caller's contract; the glue is registered for this element type.
|
||||
return unsafe { (deep.clone_out)(ptr) };
|
||||
}
|
||||
// SAFETY: a lifetime-carrying element type registers deep glue, so
|
||||
// this shallow path only erases borrow-free values.
|
||||
// SAFETY: a lifetime-carrying element type registers deep glue, so this
|
||||
// shallow path only erases borrow-free values. The registration is a
|
||||
// whole-program convention rather than something this call can check:
|
||||
// the executor asserts the in-tree types registered before it evaluates,
|
||||
// which is where a missed wasm registration export is caught.
|
||||
Box::new(unsafe { erase_static(read_element::<T>(Rec::new(ptr))) })
|
||||
}
|
||||
/// # Safety
|
||||
/// `dst` must be fresh element storage of a record whose element is `T`, and
|
||||
/// `value` must be the clone-out this glue produced for that element type.
|
||||
unsafe fn repark<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(value: &(dyn std::any::Any + Send + Sync), dst: *mut u8, arena: &crate::arena::Arena) -> Option<()>
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
if let Some(deep) = deep_element_glue(std::any::TypeId::of::<T::Static>()) {
|
||||
// SAFETY: the caller's contract; the glue is registered for this element type.
|
||||
return unsafe { (deep.repark)(value, dst, arena) };
|
||||
}
|
||||
let retained = retained_measure(std::any::TypeId::of::<T::Static>()).map_or(0, |measure| measure(value));
|
||||
@@ -568,11 +590,17 @@ pub fn element_write_hashed<T: Clone + Send + Sync + graphene_hash::CacheHash +
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
/// # Safety
|
||||
/// `ptr` must address a live element of `T` in the form [`element_parked`] picks.
|
||||
unsafe fn content_hash<T: graphene_hash::CacheHash>(ptr: *const u8, state: &mut dyn core::hash::Hasher) {
|
||||
let mut state = state;
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { borrow_element::<T>(Rec::new(ptr)) }.cache_hash(&mut state);
|
||||
}
|
||||
/// # Safety
|
||||
/// `a` and `b` must each address a live element of `T` in that same form.
|
||||
unsafe fn content_eq<T: PartialEq>(a: *const u8, b: *const u8) -> bool {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { borrow_element::<T>(Rec::new(a)) == borrow_element::<T>(Rec::new(b)) }
|
||||
}
|
||||
ElementWrite {
|
||||
|
||||
@@ -28,7 +28,7 @@ pub use layout::{
|
||||
ElToken, ElementSpec, ElementWrite, ElementWritePick, ElementWritePickHashed, ElementWritePickPlain, FieldDesc, FieldOffset, FieldWrite, InputReads, Layout, LayoutMeta, RecordLayout, copy_plan,
|
||||
element_dims, element_parked, element_write, element_write_hashed, empty_layout,
|
||||
};
|
||||
pub use owned::{OwnedRecord, deepen_field_value, register_deep_element_clone, register_deep_field_value, replay_field_value};
|
||||
pub use owned::{OwnedRecord, deepen_field_value, has_deep_element_glue, register_deep_element_clone, register_deep_field_value, replay_field_value};
|
||||
pub use promote::{Promotion, assert_promoted, register_element_promote, register_field_promote, register_retained_heap};
|
||||
pub use route::{RecordSource, SourcePlan};
|
||||
pub use run::{Group, GroupItem, RunBuilder, RunColumn, RunView};
|
||||
|
||||
@@ -32,6 +32,13 @@ pub(in crate::record) fn deep_element_glue(type_id: std::any::TypeId) -> Option<
|
||||
DEEP_ELEMENT_CLONES.lock().unwrap().get(&type_id).copied()
|
||||
}
|
||||
|
||||
/// Whether elements of a type registered deep glue. The shallow clone path is
|
||||
/// only sound for types that did not need to, so a host that drives the
|
||||
/// registration itself checks the types it owes before it evaluates anything.
|
||||
pub fn has_deep_element_glue(type_id: std::any::TypeId) -> bool {
|
||||
DEEP_ELEMENT_CLONES.lock().unwrap().contains_key(&type_id)
|
||||
}
|
||||
|
||||
/// Deep-copy overrides for field values whose content borrows the
|
||||
/// evaluation's arena (a graphic list holding native groups), keyed by the
|
||||
/// field's owned value form. Consulted at the persistence seams only:
|
||||
@@ -106,17 +113,21 @@ impl OwnedRecord {
|
||||
// The element-to-field seam is never written, so the copy stays untyped:
|
||||
// a `&[u8]` over the frame would read those bytes.
|
||||
let mut staged = Vec::<u8>::with_capacity(layout.size);
|
||||
// SAFETY: the caller's contract sizes the record at `layout.size`, which
|
||||
// is the capacity just reserved, so the copy fills exactly the staging.
|
||||
let bytes = unsafe {
|
||||
std::ptr::copy_nonoverlapping(rec.ptr(), staged.as_mut_ptr(), layout.size);
|
||||
staged.set_len(layout.size);
|
||||
staged.into_boxed_slice()
|
||||
};
|
||||
// SAFETY: the caller's contract; a parked element sits at offset 0.
|
||||
let element = layout.element.parked.then(|| unsafe { (layout.element.clone_out)(rec.ptr()) });
|
||||
let fields = layout
|
||||
.fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, field)| field.repark.is_some())
|
||||
// SAFETY: the caller's contract; each field reads its own descriptor's offset.
|
||||
.map(|(index, field)| (index, field.type_id, deepen_field_value(unsafe { (field.read_erased)(rec.ptr().add(field.offset)) })))
|
||||
.collect();
|
||||
OwnedRecord { bytes, element, fields }
|
||||
@@ -139,15 +150,21 @@ impl OwnedRecord {
|
||||
self.write_into(layout, slot.dst(), arena)
|
||||
}
|
||||
|
||||
/// `dst` is a claimed frame of `layout`, and `replay_into`'s asserts have
|
||||
/// established that `layout` is the one the copy was taken at.
|
||||
fn write_into(&self, layout: &Layout, dst: *mut u8, arena: &crate::arena::Arena) -> Option<()> {
|
||||
// SAFETY: the copy is `layout.size` bytes and the claim is a frame of it.
|
||||
unsafe { std::ptr::copy_nonoverlapping(self.bytes.as_ptr(), dst, self.bytes.len()) };
|
||||
if let Some(element) = &self.element {
|
||||
// SAFETY: the element was cloned out of this layout's own slot at offset 0.
|
||||
unsafe { (layout.element.repark)(&**element, dst, arena) }?;
|
||||
}
|
||||
for (index, _, value) in &self.fields {
|
||||
let field = &layout.fields[*index];
|
||||
let repark = field.repark.expect("copied fields carry re-park glue");
|
||||
let resident = replay_field_value(&**value, arena)?;
|
||||
// SAFETY: the asserts matched this index's field type, so the glue and
|
||||
// the value agree; the write lands in that field's own region.
|
||||
unsafe { repark(resident.as_deref().unwrap_or(&**value), dst.add(field.offset), arena) }?;
|
||||
}
|
||||
Some(())
|
||||
|
||||
@@ -99,6 +99,7 @@ pub(in crate::record) unsafe fn promote_record(layout: &Layout, dst: *mut u8, pr
|
||||
None => {
|
||||
// SAFETY: as above, and the clone owns its content.
|
||||
let owned = unsafe { (layout.element.clone_out)(dst.cast_const()) };
|
||||
// SAFETY: the clone is this element's own type, back into its slot.
|
||||
unsafe { (layout.element.repark)(&*owned, dst, promotion.persistent) }?;
|
||||
}
|
||||
},
|
||||
@@ -243,6 +244,7 @@ impl MaterializedSpan {
|
||||
// SAFETY: the caller's contract on the lane, into the lane's own
|
||||
// region of the freshly reserved slab.
|
||||
let dst = unsafe { base.add(lane * stride) };
|
||||
// SAFETY: as above; `layout.size` bytes of a lane fit its own stride.
|
||||
unsafe { std::ptr::copy_nonoverlapping(batch.get(lane).rec().ptr(), dst, layout.size) };
|
||||
// SAFETY: the copy images a record of this layout.
|
||||
unsafe { promote_record(layout, dst, promotion) }?;
|
||||
|
||||
@@ -51,6 +51,8 @@ impl SourcePlan {
|
||||
/// buffer of the plan's union layout that does not overlap `src`. The
|
||||
/// returned view borrows `dst`, so `'d` must not outlive it.
|
||||
pub unsafe fn translate<'d>(&self, src: Rec<'_>, dst: *mut u8) -> Rec<'d> {
|
||||
// SAFETY: the caller's contract; the plan's moves and fills name only
|
||||
// offsets of the layouts it was built from.
|
||||
unsafe {
|
||||
apply_plan(src, dst, &self.moves);
|
||||
for (offset, bytes) in &self.fills {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use super::access::write_element;
|
||||
use super::layout::{ElementWrite, FieldOffset, FieldWrite, Layout, element_write_hashed};
|
||||
use super::owned::deep_field_glue;
|
||||
use super::owned::{deep_field_glue, deepen_field_value, replay_field_value};
|
||||
use super::promote::{Promotion, promote_record};
|
||||
|
||||
/// A group's element is compared and hashed by content, so it needs glue: the
|
||||
@@ -14,6 +14,41 @@ fn assert_element_glue(layout: &Layout) {
|
||||
);
|
||||
}
|
||||
|
||||
/// Whether a lane of `layout` names payloads a byte copy would leave parked in
|
||||
/// the source arena.
|
||||
fn holds_parked(layout: &Layout) -> bool {
|
||||
layout.element.parked || layout.fields.iter().any(|field| field.repark.is_some())
|
||||
}
|
||||
|
||||
/// Re-parks one copied lane's payloads into `arena`, so a lane copied across
|
||||
/// arenas owns what it names instead of pointing back at the source's parks.
|
||||
/// The counterpart of [`promote_record`] for a copy whose target is a serving
|
||||
/// arena rather than the persistent region, so every reference clones.
|
||||
/// `None` reports arena exhaustion.
|
||||
///
|
||||
/// # Safety
|
||||
/// `dst` must image a live record of `layout` whose parked references still
|
||||
/// resolve, which is the source lane's own image before this rewrites it.
|
||||
unsafe fn readopt_record(layout: &Layout, dst: *mut u8, arena: &crate::arena::Arena) -> Option<()> {
|
||||
if layout.element.parked {
|
||||
// SAFETY: the caller's contract; the clone owns all of its content.
|
||||
let owned = unsafe { (layout.element.clone_out)(dst.cast_const()) };
|
||||
// SAFETY: the clone is the element's own type, into its own slot.
|
||||
unsafe { (layout.element.repark)(&*owned, dst, arena) }?;
|
||||
}
|
||||
for field in &layout.fields {
|
||||
let Some(repark) = field.repark else { continue };
|
||||
// SAFETY: a parked field slot holds one reference at its offset.
|
||||
let slot = unsafe { dst.add(field.offset) };
|
||||
// SAFETY: the slot images a parked field of this descriptor.
|
||||
let value = deepen_field_value(unsafe { (field.read_erased)(slot.cast_const()) });
|
||||
let resident = replay_field_value(&*value, arena)?;
|
||||
// SAFETY: the replay produced this field's own value type.
|
||||
unsafe { repark(resident.as_deref().unwrap_or(&*value), slot, arena) }?;
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Builds a resident run lane by lane: fresh frames in the arena at a layout
|
||||
/// derived from the element glue and field writes, elements pushed in order
|
||||
/// and attributes written onto pushed lanes. The finished item's frames are
|
||||
@@ -61,6 +96,8 @@ impl<'e> RunBuilder<'e> {
|
||||
// `lane` is below `len`; the element slot and each field's region are
|
||||
// disjoint parts of this lane.
|
||||
let base = unsafe { self.frames.add(lane * stride) };
|
||||
// SAFETY: the element slot is fresh, and the assert above matched `T` to
|
||||
// the layout's element type.
|
||||
unsafe { write_element(base, element, self.arena) }?;
|
||||
for field in &self.layout.fields {
|
||||
// SAFETY: as above; the field region is within the lane.
|
||||
@@ -98,13 +135,23 @@ impl<'e> RunBuilder<'e> {
|
||||
|
||||
/// Writes a legacy stored value on an already pushed lane through the
|
||||
/// census glue, parking droppable payloads. A marker outside the layout's
|
||||
/// fields is dropped; a wrong-typed stored value leaves the field's
|
||||
/// fields is dropped, as is one whose row and field agree on the name but
|
||||
/// not on the value type; a wrong-typed stored value leaves the field's
|
||||
/// default. `None` reports arena exhaustion.
|
||||
pub fn attr_stored(&mut self, lane: usize, info: &crate::attribute::AttributeInfo, value: &dyn crate::list::AnyAttributeValue) -> Option<()> {
|
||||
assert!(lane < self.pushed, "attributes write onto pushed lanes");
|
||||
let Some(offset) = self.layout.offset_of(info.name, 0) else { return Some(()) };
|
||||
// SAFETY: the offset comes from the builder's own layout, and the
|
||||
// census writer verifies the stored type before touching the field.
|
||||
let Some(field) = self.layout.fields.iter().find(|field| field.name == info.name && field.level == 0) else {
|
||||
return Some(());
|
||||
};
|
||||
let (offset, size, type_id) = (field.offset, field.size, field.type_id);
|
||||
// The row reaches the field by name alone, so the writer's own value type
|
||||
// is checked against the field before its glue writes there, as `push`
|
||||
// checks the default writer's.
|
||||
if info.size != size || info.value_type != type_id {
|
||||
return Some(());
|
||||
}
|
||||
// SAFETY: the offset comes from the builder's own layout, and the field
|
||||
// was just checked to hold the writer's own value type at its size.
|
||||
unsafe { (info.write_stored)(value, self.frames.add(lane * self.layout.lane_stride() + offset), self.arena) }
|
||||
}
|
||||
|
||||
@@ -169,7 +216,8 @@ impl<'e> GroupItem<'e> {
|
||||
/// Copies the batch's lanes into the arena and clones its layout.
|
||||
/// Returns `None` when the arena is exhausted. Parked regions must carry
|
||||
/// the content glue, so equality and hashing never fall back to pointer
|
||||
/// bytes.
|
||||
/// bytes. A copied lane's parked payloads re-park into `arena`, so the
|
||||
/// adopted run names nothing the source arena's reset frees.
|
||||
pub fn adopt(batch: crate::node::RecordBatch<'_>, arena: &'e crate::arena::Arena) -> Option<Self> {
|
||||
let layout = batch.layout().clone();
|
||||
assert_element_glue(&layout);
|
||||
@@ -190,9 +238,16 @@ impl<'e> GroupItem<'e> {
|
||||
}
|
||||
let scratch = arena.alloc_scratch::<u64>((batch.len() * stride).div_ceil(8))?;
|
||||
let frames = scratch.as_mut_ptr().cast::<u8>();
|
||||
let parked = holds_parked(&layout);
|
||||
for lane in 0..batch.len() {
|
||||
// SAFETY: both sides hold `len` lanes at the shared layout's stride.
|
||||
unsafe { std::ptr::copy_nonoverlapping(batch.get(lane).rec().ptr(), frames.add(lane * stride), stride) };
|
||||
let dst = unsafe { frames.add(lane * stride) };
|
||||
// SAFETY: as above; the scratch was reserved for exactly these lanes.
|
||||
unsafe { std::ptr::copy_nonoverlapping(batch.get(lane).rec().ptr(), dst, stride) };
|
||||
if parked {
|
||||
// SAFETY: the copy images a live record of this layout.
|
||||
unsafe { readopt_record(&layout, dst, arena) }?;
|
||||
}
|
||||
}
|
||||
Some(Self {
|
||||
layout,
|
||||
@@ -303,6 +358,7 @@ impl<'e> GroupItem<'e> {
|
||||
.layout
|
||||
.element
|
||||
.parked
|
||||
// SAFETY: as above; a parked element sits at each lane's offset 0.
|
||||
.then(|| (0..self.len).map(|lane| unsafe { (self.layout.element.clone_out)(frames.add(lane * stride)) }).collect());
|
||||
let fields = self
|
||||
.layout
|
||||
@@ -311,6 +367,7 @@ impl<'e> GroupItem<'e> {
|
||||
.enumerate()
|
||||
.filter(|(_, field)| field.repark.is_some())
|
||||
.map(|(index, field)| {
|
||||
// SAFETY: as above; each lane reads this descriptor's own offset.
|
||||
let mut values: Vec<_> = (0..self.len).map(|lane| unsafe { (field.read_erased)(frames.add(lane * stride + field.offset)) }).collect();
|
||||
if let Some(glue) = values.first().and_then(|value| deep_field_glue(value.as_any().type_id())) {
|
||||
for value in &mut values {
|
||||
@@ -335,8 +392,9 @@ impl<'e> GroupItem<'e> {
|
||||
/// `arena`, sharing only where its lanes already live there.
|
||||
pub fn replay<'a>(&self, arena: &'a crate::arena::Arena) -> Option<GroupItem<'a>> {
|
||||
let ItemStorage::Owned(owned) = &self.storage else {
|
||||
// A resident item re-serves at the target arena's own lifetime,
|
||||
// so its lanes copy rather than relabeling the borrow.
|
||||
// A resident item re-serves at the target arena's own lifetime, so
|
||||
// its lanes copy and their parked payloads re-park there rather
|
||||
// than relabeling the borrow.
|
||||
return GroupItem::adopt(self.lanes(), arena);
|
||||
};
|
||||
let stride = self.layout.lane_stride();
|
||||
@@ -347,6 +405,7 @@ impl<'e> GroupItem<'e> {
|
||||
unsafe { std::ptr::copy_nonoverlapping(owned.bytes.as_ptr(), frames, owned.bytes.len()) };
|
||||
if let Some(elements) = &owned.elements {
|
||||
for (lane, element) in elements.iter().enumerate() {
|
||||
// SAFETY: as above; the clone is this element's own type, into its lane's slot.
|
||||
unsafe { (self.layout.element.repark)(&**element, frames.add(lane * stride), arena) }?;
|
||||
}
|
||||
}
|
||||
@@ -355,6 +414,8 @@ impl<'e> GroupItem<'e> {
|
||||
let repark = field.repark.expect("copied fields carry re-park glue");
|
||||
let glue = values.first().and_then(|value| deep_field_glue(value.as_any().type_id()));
|
||||
for (lane, value) in values.iter().enumerate() {
|
||||
// SAFETY: the copy took these values through this field's own glue,
|
||||
// so each writes its own type into its lane's region of the field.
|
||||
match glue {
|
||||
Some(glue) => match (glue.replay)(&**value, arena)? {
|
||||
Some(resident) => unsafe { repark(&*resident, frames.add(lane * stride + field.offset), arena) }?,
|
||||
@@ -547,14 +608,20 @@ impl<'e> Group<'e> {
|
||||
/// touches. The element always carries glue (`assert_element_glue`) and
|
||||
/// `FieldWrite::of` always installs field glue, so a padded value's own
|
||||
/// padding never reaches the byte fallback either.
|
||||
///
|
||||
/// # Safety
|
||||
/// `a` and `b` must both be live records of `layout`.
|
||||
unsafe fn record_content_eq(layout: &Layout, a: *const u8, b: *const u8) -> bool {
|
||||
// SAFETY: the caller's contract; each call reads a written span of the layout.
|
||||
let bytes_eq = |offset: usize, size: usize| unsafe { std::slice::from_raw_parts(a.add(offset), size) == std::slice::from_raw_parts(b.add(offset), size) };
|
||||
let element = match layout.element.content_eq {
|
||||
// SAFETY: the caller's contract; the glue is the element's own.
|
||||
Some(eq) => unsafe { eq(a, b) },
|
||||
None => bytes_eq(0, layout.element.size),
|
||||
};
|
||||
element
|
||||
&& layout.fields.iter().all(|field| match field.content_eq {
|
||||
// SAFETY: as above, at this descriptor's own offset.
|
||||
Some(eq) => unsafe { eq(a.add(field.offset), b.add(field.offset)) },
|
||||
None => bytes_eq(field.offset, field.size),
|
||||
})
|
||||
@@ -562,14 +629,21 @@ unsafe fn record_content_eq(layout: &Layout, a: *const u8, b: *const u8) -> bool
|
||||
|
||||
/// Hashes one record region of `layout` by content, with the byte fallback
|
||||
/// of [`record_content_eq`].
|
||||
///
|
||||
/// # Safety
|
||||
/// `ptr` must be a live record of `layout`.
|
||||
unsafe fn record_content_hash(layout: &Layout, ptr: *const u8, state: &mut dyn core::hash::Hasher) {
|
||||
match layout.element.content_hash {
|
||||
// SAFETY: the caller's contract; the glue is the element's own.
|
||||
Some(hash) => unsafe { hash(ptr, state) },
|
||||
// SAFETY: as above; the element's own bytes are written.
|
||||
None => state.write(unsafe { std::slice::from_raw_parts(ptr, layout.element.size) }),
|
||||
}
|
||||
for field in &layout.fields {
|
||||
match field.content_hash {
|
||||
// SAFETY: as above, at this descriptor's own offset.
|
||||
Some(hash) => unsafe { hash(ptr.add(field.offset), state) },
|
||||
// SAFETY: as above; the field's own bytes are written.
|
||||
None => state.write(unsafe { std::slice::from_raw_parts(ptr.add(field.offset), field.size) }),
|
||||
}
|
||||
}
|
||||
@@ -753,6 +827,34 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cross_arena_adopt_re_parks_what_the_lanes_name() {
|
||||
use crate::lane::LaneSource;
|
||||
|
||||
let mut source = crate::arena::Arena::new(1 << 16).unwrap();
|
||||
let target = crate::arena::Arena::new(1 << 16).unwrap();
|
||||
|
||||
let adopted = {
|
||||
let mut builder = RunBuilder::new(&source, element_write_hashed::<String>(), &[FieldWrite::of::<crate::attribute::Name>(0)], 2).unwrap();
|
||||
for lane in 0..2 {
|
||||
let lane = builder.push(format!("element {lane}")).unwrap();
|
||||
let (name, _) = source.alloc(format!("field {lane}")).unwrap();
|
||||
builder.attr::<crate::attribute::Name>(lane, name.as_str());
|
||||
}
|
||||
let item = builder.finish();
|
||||
GroupItem::adopt(item.lanes(), &target).unwrap()
|
||||
};
|
||||
// The adopted run must own what it names: the source's flush frees every
|
||||
// payload the lanes were built over.
|
||||
source.reset();
|
||||
|
||||
let run = RunView::<String>::new(&adopted).expect("the run holds string elements");
|
||||
for lane in 0..2 {
|
||||
assert_eq!(run.element(lane).map(String::as_str), Some(format!("element {lane}").as_str()), "lane {lane}");
|
||||
assert_eq!(run.attr::<crate::attribute::Name>(lane), format!("field {lane}"), "lane {lane}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_content_equality_and_hashing_read_through_the_park() {
|
||||
use graphene_hash::CacheHash;
|
||||
@@ -867,6 +969,26 @@ mod tests {
|
||||
assert_eq!(run.attr::<crate::attribute::EditorLayerPath>(0), &[crate::uuid::NodeId(3)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_census_row_pointed_at_another_field_writes_nothing() {
|
||||
use crate::attribute::{Attribute, Opacity, Transform};
|
||||
use crate::lane::LaneSource;
|
||||
|
||||
let arena = crate::arena::Arena::new(1 << 16).unwrap();
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<f64>(), &[FieldWrite::of::<Opacity>(0)], 1).unwrap();
|
||||
let lane = builder.push(0f64).unwrap();
|
||||
|
||||
// The transform writer renamed onto the 8-byte opacity field: a
|
||||
// 48-byte write past the lane if the name were the only check.
|
||||
let mut forged = crate::attribute::info(Transform::NAME).unwrap();
|
||||
forged.name = Opacity::NAME;
|
||||
builder.attr_stored(lane, &forged, &glam::DAffine2::from_translation((5., 6.).into())).unwrap();
|
||||
|
||||
let item = builder.finish();
|
||||
let run = RunView::<f64>::new(&item).expect("the run holds f64 elements");
|
||||
assert_eq!(run.attr::<Opacity>(0), 1., "the mistyped row leaves the census default");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_typed_or_undeclared_column_leaves_the_default() {
|
||||
use crate::lane::LaneSource;
|
||||
|
||||
@@ -127,12 +127,22 @@ impl<N: ?Sized> SharedSource<N> {
|
||||
|
||||
/// Re-derives the cached pointer from the owned payload. An exclusive
|
||||
/// re-borrow of the payload invalidates the pointer taken before it, so
|
||||
/// every mutation through `own` ends here.
|
||||
/// every mutation through `own` ends here, an unwinding one included.
|
||||
pub fn rederive(&mut self) {
|
||||
self.ptr = std::ptr::NonNull::from(&*self.own);
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-derives on the way out of an exclusive re-borrow, so a mutation that
|
||||
/// panics cannot leave the cached pointer retired for a caller that catches.
|
||||
struct Rederive<'a, N: ?Sized>(&'a mut SharedSource<N>);
|
||||
|
||||
impl<N: ?Sized> Drop for Rederive<'_, N> {
|
||||
fn drop(&mut self) {
|
||||
self.0.rederive();
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: `ptr` is derived from the owned Arc and never mutated through, so the source is exactly as
|
||||
// thread safe as the payload it shares.
|
||||
unsafe impl<N: ?Sized + Send + Sync> Send for SharedSource<N> {}
|
||||
@@ -207,6 +217,9 @@ unsafe impl Send for SourceHandle {}
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl Sync for SourceHandle {}
|
||||
|
||||
#[cfg(all(target_family = "wasm", target_feature = "atomics"))]
|
||||
compile_error!("SourceHandle's wasm Send/Sync rest on a single-threaded build; a +atomics target needs the stored node bounded instead");
|
||||
|
||||
impl SourceHandle {
|
||||
pub fn new_record<T: 'static>(node: std::sync::Arc<ErasedRecordNode>) -> Self {
|
||||
Self::new_erased(node, record_source_type::<T>())
|
||||
@@ -224,9 +237,11 @@ impl SourceHandle {
|
||||
layout: |edge| Node::<ContextImpl>::layout(edge.downcast_ref::<SharedSource<N>>().expect("layout hook matches the stored edge type")),
|
||||
set_layout: |edge, layout| {
|
||||
let shared = edge.downcast_mut::<SharedSource<N>>().expect("set_layout hook matches the stored edge type");
|
||||
let node = std::sync::Arc::get_mut(&mut shared.own).expect("layout is installed before the node is shared");
|
||||
// The re-borrow below retires the cached pointer, so the rederive
|
||||
// is a guard: a panicking `set_layout` must not leave it stale.
|
||||
let guard = Rederive(shared);
|
||||
let node = std::sync::Arc::get_mut(&mut guard.0.own).expect("layout is installed before the node is shared");
|
||||
Node::<ContextImpl>::set_layout(node, layout);
|
||||
shared.rederive();
|
||||
},
|
||||
ty,
|
||||
}
|
||||
|
||||
@@ -30,6 +30,9 @@ unsafe impl Send for RuntimeHandle {}
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl Sync for RuntimeHandle {}
|
||||
|
||||
#[cfg(all(target_family = "wasm", target_feature = "atomics"))]
|
||||
compile_error!("RuntimeHandle's wasm Send/Sync rest on a single-threaded build; a +atomics target needs the payload bounded instead");
|
||||
|
||||
impl std::fmt::Debug for RuntimeHandle {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("RuntimeHandle").finish_non_exhaustive()
|
||||
@@ -102,6 +105,9 @@ unsafe impl<S> Send for GraphRuntime<S> {}
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl<S> Sync for GraphRuntime<S> {}
|
||||
|
||||
#[cfg(all(target_family = "wasm", target_feature = "atomics"))]
|
||||
compile_error!("GraphRuntime's wasm Send/Sync are unbounded in S and rest on a single-threaded build; a +atomics target needs S bounded instead");
|
||||
|
||||
impl<S> GraphRuntime<S> {
|
||||
pub fn new(spawner: S) -> Self {
|
||||
Self {
|
||||
|
||||
@@ -50,11 +50,13 @@ impl<'e> Artboard<'e> {
|
||||
/// # Safety
|
||||
/// `ptr` must point at a live parked `Artboard` element field.
|
||||
unsafe fn deep_clone_artboard(ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync> {
|
||||
// SAFETY: the caller's contract.
|
||||
let artboard = unsafe { core_types::record::borrow_element::<Artboard>(core_types::record::Rec::new(ptr)) };
|
||||
let mut content = artboard.0.clone();
|
||||
for element in content.iter_element_values_mut() {
|
||||
*element = crate::graphic::map_groups_to_owned(element);
|
||||
}
|
||||
crate::graphic::map_attribute_groups_to_owned(&mut content);
|
||||
Box::new(Artboard(content))
|
||||
}
|
||||
|
||||
@@ -70,22 +72,27 @@ unsafe fn deep_repark_artboard(value: &(dyn std::any::Any + Send + Sync), dst: *
|
||||
for element in content.iter_element_values_mut() {
|
||||
*element = crate::graphic::map_groups_to_resident(element, arena)?;
|
||||
}
|
||||
crate::graphic::map_attribute_groups_to_resident(&mut content, arena)?;
|
||||
// SAFETY: the caller's contract on `dst`; the replayed content is an `Artboard`.
|
||||
unsafe { core_types::record::write_element(dst, Artboard(content), arena) }
|
||||
}
|
||||
|
||||
/// The promote for `Artboard` elements: as for `Graphic`, content groups the
|
||||
/// persistent region already holds are shared rather than copied, and
|
||||
/// group-free content moves its header instead of copying its heap.
|
||||
/// persistent region already holds are shared rather than copied, and content
|
||||
/// no group is reachable from moves its header instead of copying its heap.
|
||||
///
|
||||
/// # Safety
|
||||
/// `src` must point at a live parked `Artboard` element field, and `dst` at
|
||||
/// the element field the promoted reference is written to.
|
||||
unsafe fn promote_artboard(src: *const u8, dst: *mut u8, promotion: &core_types::record::Promotion<'_>) -> Option<()> {
|
||||
// SAFETY: the caller's contract on `src`.
|
||||
let artboard = unsafe { core_types::record::borrow_element::<Artboard>(core_types::record::Rec::new(src)) };
|
||||
if !crate::graphic::list_contains_groups(&artboard.0) {
|
||||
// SAFETY: a parked element slot holds one reference at offset 0, and
|
||||
// group-free content owns all of itself.
|
||||
// content no group is reachable from, elements and item attribute values
|
||||
// alike, owns all of itself.
|
||||
let header = unsafe { src.cast::<*const u8>().read() };
|
||||
// SAFETY: as above; the group-free check establishes the own-all-content half.
|
||||
if let Some(moved) = unsafe { promotion.move_park::<Artboard>(header, 0) } {
|
||||
// SAFETY: as above, into the promoted image's own element slot.
|
||||
unsafe { dst.cast::<*const Artboard>().write(moved) };
|
||||
@@ -97,6 +104,8 @@ unsafe fn promote_artboard(src: *const u8, dst: *mut u8, promotion: &core_types:
|
||||
let (element, attributes) = item.into_parts();
|
||||
content.push(core_types::list::Item::from_parts(crate::graphic::map_groups_to_persistent(&element, promotion)?, attributes));
|
||||
}
|
||||
crate::graphic::map_attribute_groups_to_persistent(&mut content, promotion)?;
|
||||
// SAFETY: the caller's contract on `dst`; the promoted content is an `Artboard`.
|
||||
unsafe { core_types::record::write_element(dst, Artboard(content), promotion.persistent()) }
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ pub fn map_groups_to_owned<'out>(graphic: &Graphic<'_>) -> Graphic<'out> {
|
||||
let (element, attributes) = item.into_parts();
|
||||
out.push(Item::from_parts(map_groups_to_owned(&element), attributes));
|
||||
}
|
||||
map_attribute_groups_to_owned(&mut out);
|
||||
Graphic::Graphic(out)
|
||||
}
|
||||
Graphic::Vector(vector) => Graphic::Vector(vector.clone()),
|
||||
@@ -39,6 +40,7 @@ pub fn map_groups_to_resident<'a>(graphic: &Graphic<'a>, arena: &'a core_types::
|
||||
for child in children.iter_element_values_mut() {
|
||||
*child = map_groups_to_resident(child, arena)?;
|
||||
}
|
||||
map_attribute_groups_to_resident(&mut children, arena)?;
|
||||
Some(Graphic::Graphic(children))
|
||||
}
|
||||
other => Some(other.clone()),
|
||||
@@ -52,6 +54,7 @@ pub fn map_groups_to_resident<'a>(graphic: &Graphic<'a>, arena: &'a core_types::
|
||||
/// # Safety
|
||||
/// `ptr` must point at a live parked `Graphic` element field.
|
||||
unsafe fn deep_clone_graphic(ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync> {
|
||||
// SAFETY: the caller's contract.
|
||||
let graphic = unsafe { core_types::record::borrow_element::<Graphic>(core_types::record::Rec::new(ptr)) };
|
||||
Box::new(map_groups_to_owned(graphic))
|
||||
}
|
||||
@@ -66,6 +69,7 @@ unsafe fn deep_repark_graphic(value: &(dyn std::any::Any + Send + Sync), dst: *m
|
||||
let graphic = value.downcast_ref::<Graphic>().expect("an element replays at its own type");
|
||||
let resident = map_groups_to_resident(graphic, arena)?;
|
||||
let retained = graphic_retained_heap(&resident);
|
||||
// SAFETY: the caller's contract; the resident form is a `Graphic` for `dst`.
|
||||
unsafe { core_types::record::write_element_sized(dst, resident, arena, retained) }
|
||||
}
|
||||
|
||||
@@ -81,6 +85,7 @@ pub fn map_groups_to_persistent<'p>(graphic: &Graphic<'_>, promotion: &core_type
|
||||
let (element, attributes) = item.into_parts();
|
||||
out.push(Item::from_parts(map_groups_to_persistent(&element, promotion)?, attributes));
|
||||
}
|
||||
map_attribute_groups_to_persistent(&mut out, promotion)?;
|
||||
Some(Graphic::Graphic(out))
|
||||
}
|
||||
Graphic::Vector(vector) => Some(Graphic::Vector(vector.clone())),
|
||||
@@ -92,20 +97,84 @@ pub fn map_groups_to_persistent<'p>(graphic: &Graphic<'_>, promotion: &core_type
|
||||
}
|
||||
}
|
||||
|
||||
/// The list's attribute keys, owned so the columns can be walked mutably.
|
||||
fn attribute_keys(list: &List<Graphic>) -> Vec<String> {
|
||||
list.attribute_keys().map(str::to_string).collect()
|
||||
}
|
||||
|
||||
/// Every group held in the list's item attribute values, deep-copied to its
|
||||
/// owned form. Element values are the caller's own pass; a value list's own
|
||||
/// item attributes recurse here.
|
||||
pub(crate) fn map_attribute_groups_to_owned(list: &mut List<Graphic<'_>>) {
|
||||
for key in attribute_keys(list) {
|
||||
// A column of a type that cannot hold groups is skipped whole.
|
||||
let Some(values) = list.iter_attribute_values_mut::<Option<List<Graphic>>>(&key) else { continue };
|
||||
for value in values.flatten() {
|
||||
for element in value.iter_element_values_mut() {
|
||||
*element = map_groups_to_owned(element);
|
||||
}
|
||||
map_attribute_groups_to_owned(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every owned group held in the list's item attribute values, re-parked into
|
||||
/// `arena`. `None` reports arena exhaustion.
|
||||
pub(crate) fn map_attribute_groups_to_resident(list: &mut List<Graphic<'_>>, arena: &core_types::arena::Arena) -> Option<()> {
|
||||
for key in attribute_keys(list) {
|
||||
// A column of a type that cannot hold groups is skipped whole.
|
||||
let Some(values) = list.iter_attribute_values_mut::<Option<List<Graphic>>>(&key) else { continue };
|
||||
for value in values.flatten() {
|
||||
for element in value.iter_element_values_mut() {
|
||||
let resident = map_groups_to_resident(element, arena)?;
|
||||
// SAFETY: the attribute store is erased, and the replay serves as
|
||||
// long as `arena`, which the store's reader outlives.
|
||||
*element = unsafe { core_types::record::erase_static(resident) };
|
||||
}
|
||||
map_attribute_groups_to_resident(value, arena)?;
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Every group held in the list's item attribute values, promoted into the
|
||||
/// persistent region on the same Cow dispatch the elements take. `None` reports
|
||||
/// arena exhaustion.
|
||||
pub(crate) fn map_attribute_groups_to_persistent(list: &mut List<Graphic<'_>>, promotion: &core_types::record::Promotion<'_>) -> Option<()> {
|
||||
for key in attribute_keys(list) {
|
||||
// A column of a type that cannot hold groups is skipped whole.
|
||||
let Some(values) = list.iter_attribute_values_mut::<Option<List<Graphic>>>(&key) else { continue };
|
||||
for value in values.flatten() {
|
||||
for element in value.iter_element_values_mut() {
|
||||
let promoted = map_groups_to_persistent(element, promotion)?;
|
||||
// SAFETY: the attribute store is erased, and persistent content
|
||||
// outlives the evaluation.
|
||||
*element = unsafe { core_types::record::erase_static(promoted) };
|
||||
}
|
||||
map_attribute_groups_to_persistent(value, promotion)?;
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// The promote for `Graphic` elements: the generic path would deep-copy every
|
||||
/// interior through an owned intermediate, while this shares the interiors the
|
||||
/// persistent region already holds. A group-free graphic references nothing the
|
||||
/// evaluation owns, so its header moves and its heap is never copied.
|
||||
/// persistent region already holds. A graphic no group is reachable from
|
||||
/// references nothing the evaluation owns, so its header moves and its heap is
|
||||
/// never copied.
|
||||
///
|
||||
/// # Safety
|
||||
/// `src` must point at a live parked `Graphic` element field, and `dst` at the
|
||||
/// element field the promoted reference is written to.
|
||||
unsafe fn promote_graphic(src: *const u8, dst: *mut u8, promotion: &core_types::record::Promotion<'_>) -> Option<()> {
|
||||
// SAFETY: the caller's contract on `src`.
|
||||
let graphic = unsafe { core_types::record::borrow_element::<Graphic>(core_types::record::Rec::new(src)) };
|
||||
if !graphic_contains_groups(graphic) {
|
||||
// SAFETY: a parked element slot holds one reference at offset 0, and a
|
||||
// group-free graphic owns all of its content.
|
||||
// graphic no group is reachable from, elements and item attribute values
|
||||
// alike, owns all of its content.
|
||||
let header = unsafe { src.cast::<*const u8>().read() };
|
||||
// SAFETY: as above; the group-free check establishes the own-all-content half.
|
||||
if let Some(moved) = unsafe { promotion.move_park::<Graphic<'static>>(header, graphic_retained_heap(graphic)) } {
|
||||
// SAFETY: as above, into the promoted image's own element slot.
|
||||
unsafe { dst.cast::<*const Graphic<'static>>().write(moved) };
|
||||
@@ -114,6 +183,7 @@ unsafe fn promote_graphic(src: *const u8, dst: *mut u8, promotion: &core_types::
|
||||
}
|
||||
let promoted = map_groups_to_persistent(graphic, promotion)?;
|
||||
let retained = graphic_retained_heap(&promoted);
|
||||
// SAFETY: the caller's contract on `dst`; the promoted form is a `Graphic`.
|
||||
unsafe { core_types::record::write_element_sized(dst, promoted, promotion.persistent(), retained) }
|
||||
}
|
||||
|
||||
@@ -140,6 +210,8 @@ fn vector_retained_heap(vector: &Vector) -> usize {
|
||||
+ size_of_val(vector.colinear_manipulators.as_slice())
|
||||
}
|
||||
|
||||
/// Whether any group is reachable from the graphic, so it does not own all of
|
||||
/// its content.
|
||||
fn graphic_contains_groups(graphic: &Graphic) -> bool {
|
||||
match graphic {
|
||||
Graphic::Group(_) => true,
|
||||
@@ -148,8 +220,24 @@ fn graphic_contains_groups(graphic: &Graphic) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether any group is reachable from the list, so it does not own all of its
|
||||
/// content. An item attribute value holds its groups exactly as an element
|
||||
/// does: a cloned group there keeps a resident interior borrowing the
|
||||
/// evaluation's arena, so the elements alone cannot decide ownership.
|
||||
pub(crate) fn list_contains_groups(list: &List<Graphic>) -> bool {
|
||||
(0..list.len()).any(|index| list.element(index).is_some_and(graphic_contains_groups))
|
||||
(0..list.len()).any(|index| list.element(index).is_some_and(graphic_contains_groups)) || attribute_values_contain_groups(list)
|
||||
}
|
||||
|
||||
/// Whether any group hides in the list's item attribute values. Only the
|
||||
/// group-capable columns are scanned: those are the value types the deep field
|
||||
/// glue is registered for, today `Option<List<Graphic>>` alone. A list with no
|
||||
/// attribute columns costs nothing, and a column of any other type is decided
|
||||
/// by its one downcast rather than per value.
|
||||
fn attribute_values_contain_groups(list: &List<Graphic>) -> bool {
|
||||
list.attribute_keys().any(|key| {
|
||||
list.iter_attribute_values::<Option<List<Graphic>>>(key)
|
||||
.is_some_and(|mut values| values.any(|value| value.as_ref().is_some_and(list_contains_groups)))
|
||||
})
|
||||
}
|
||||
|
||||
/// The heap a graphic list's elements own, group interiors excluded as
|
||||
@@ -159,8 +247,9 @@ fn list_retained_heap(list: &List<Graphic>) -> usize {
|
||||
}
|
||||
|
||||
/// The deep copy-out for graphic-list field values (the paint markers' owned
|
||||
/// form): content groups leave in their owned form. Declines (`None`) for
|
||||
/// group-free content, which already owns everything.
|
||||
/// form): content groups leave in their owned form, whether an element or an
|
||||
/// item attribute value holds them. Declines (`None`) for group-free content,
|
||||
/// which already owns everything.
|
||||
fn deep_clone_graphic_list(value: &dyn core_types::list::AnyAttributeValue) -> Option<Box<dyn core_types::list::AnyAttributeValue>> {
|
||||
let list = value.as_any().downcast_ref::<Option<List<Graphic>>>().expect("a graphic list field deep-copies at its own type");
|
||||
let list = list.as_ref().filter(|list| list_contains_groups(list))?;
|
||||
@@ -168,12 +257,14 @@ fn deep_clone_graphic_list(value: &dyn core_types::list::AnyAttributeValue) -> O
|
||||
for element in list.iter_element_values_mut() {
|
||||
*element = map_groups_to_owned(element);
|
||||
}
|
||||
map_attribute_groups_to_owned(&mut list);
|
||||
Some(Box::new(Some(list)))
|
||||
}
|
||||
|
||||
/// The deep replay for graphic-list field values: owned content groups replay
|
||||
/// into the serving arena before the field re-parks. `Some(None)` declines
|
||||
/// for group-free content; `None` reports arena exhaustion.
|
||||
/// into the serving arena before the field re-parks, whether an element or an
|
||||
/// item attribute value holds them. `Some(None)` declines for group-free
|
||||
/// content; `None` reports arena exhaustion.
|
||||
fn deep_repark_graphic_list(value: &dyn core_types::list::AnyAttributeValue, arena: &core_types::arena::Arena) -> Option<Option<Box<dyn core_types::list::AnyAttributeValue>>> {
|
||||
let list = value.as_any().downcast_ref::<Option<List<Graphic>>>().expect("a graphic list field replays at its own type");
|
||||
let Some(list) = list.as_ref().filter(|list| list_contains_groups(list)) else {
|
||||
@@ -183,6 +274,9 @@ fn deep_repark_graphic_list(value: &dyn core_types::list::AnyAttributeValue, are
|
||||
for element in list.iter_element_values_mut() {
|
||||
*element = map_groups_to_resident(element, arena)?;
|
||||
}
|
||||
map_attribute_groups_to_resident(&mut list, arena)?;
|
||||
// SAFETY: every group the clone carried, in an element or an item attribute
|
||||
// value, now names `arena`, whose borrow the replayed field is read at.
|
||||
let list = unsafe { core_types::record::erase_static(list) };
|
||||
Some(Some(Box::new(Some(list))))
|
||||
}
|
||||
@@ -192,12 +286,13 @@ fn deep_repark_graphic_list(value: &dyn core_types::list::AnyAttributeValue, are
|
||||
/// while this maps the content transient-to-persistent in one pass.
|
||||
///
|
||||
/// THE TWO-LEVEL SHARING LAW: the field's own header is not provenance-shared.
|
||||
/// It moves where the content is group-free, since the payload then owns all of
|
||||
/// its content and the transient arena confirms the reference is its own park,
|
||||
/// and otherwise it clones into a fresh persistent park. One level inside, a
|
||||
/// content group's interior is arena-resident and its provenance is decidable,
|
||||
/// so it takes [`map_groups_to_persistent`]'s Cow dispatch: an interior the
|
||||
/// persistent region already holds is shared pointer for pointer.
|
||||
/// It moves where no group is reachable from the list, elements and item
|
||||
/// attribute values alike, since the payload then owns all of its content and
|
||||
/// the transient arena confirms the reference is its own park, and otherwise it
|
||||
/// clones into a fresh persistent park. One level inside, a content group's
|
||||
/// interior is arena-resident and its provenance is decidable, so it takes
|
||||
/// [`map_groups_to_persistent`]'s Cow dispatch: an interior the persistent
|
||||
/// region already holds is shared pointer for pointer.
|
||||
///
|
||||
/// # Safety
|
||||
/// `src` must point at a live parked graphic-list field, and `dst` at the field
|
||||
@@ -211,9 +306,9 @@ unsafe fn promote_graphic_list(src: *const u8, dst: *mut u8, promotion: &core_ty
|
||||
};
|
||||
let retained = list_retained_heap(list);
|
||||
if !list_contains_groups(list) {
|
||||
// SAFETY: a group-free list owns all of its content, and the arena
|
||||
// declines a reference that is not a park at the list's own address
|
||||
// and size.
|
||||
// SAFETY: a list no group is reachable from, elements and item attribute
|
||||
// values alike, owns all of its content, and the arena declines a
|
||||
// reference that is not a park at the list's own address and size.
|
||||
if let Some(moved) = unsafe { promotion.move_park::<List<Graphic<'static>>>(std::ptr::from_ref(list).cast(), retained) } {
|
||||
// SAFETY: the move published a live list in the persistent region.
|
||||
unsafe { dst.cast::<Option<&List<Graphic<'static>>>>().write(Some(&*moved)) };
|
||||
@@ -224,8 +319,10 @@ unsafe fn promote_graphic_list(src: *const u8, dst: *mut u8, promotion: &core_ty
|
||||
for element in promoted.iter_element_values_mut() {
|
||||
*element = map_groups_to_persistent(element, promotion)?;
|
||||
}
|
||||
// SAFETY: every borrow the clone carried was replaced by persistent content
|
||||
// above, so the erased form outlives the evaluation.
|
||||
map_attribute_groups_to_persistent(&mut promoted, promotion)?;
|
||||
// SAFETY: every borrow the clone carried, in an element or an item attribute
|
||||
// value, was replaced by persistent content above, so the erased form
|
||||
// outlives the evaluation.
|
||||
let promoted = unsafe { core_types::record::erase_static(promoted) };
|
||||
let (parked, _) = promotion.persistent().alloc_sized(promoted, retained)?;
|
||||
// SAFETY: the slot holds one optional reference.
|
||||
@@ -263,7 +360,7 @@ mod run_tests {
|
||||
use super::*;
|
||||
use crate::graphic::test_support::{native_group_paint, unit_square_at};
|
||||
use crate::graphic::{group_to_legacy_list, map_groups_to_legacy};
|
||||
use crate::markers::Fill;
|
||||
use crate::markers::{Fill, Stroke};
|
||||
use core_types::attribute::Attribute;
|
||||
use core_types::lane::LaneSource;
|
||||
use core_types::record::{FieldWrite, RunBuilder, RunView, element_write_hashed};
|
||||
@@ -466,4 +563,98 @@ mod run_tests {
|
||||
let served = promoted_paint(&span, &layout, 0, &persistent);
|
||||
assert!(matches!(served.element(0), Some(Graphic::Vector(_))), "the moved paint survives the transient reset");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paint_field_whose_attributes_hold_groups_never_moves() {
|
||||
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||
let mut transient = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let persistent = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
|
||||
// Group-free elements, with the resident group hidden in an item attribute.
|
||||
let native = native_group_paint(&inner_vector, &transient);
|
||||
let expected = map_groups_to_legacy(native.element(0).unwrap());
|
||||
let mut paint = List::new_from_element(Graphic::Vector(unit_square_at(DVec2::new(4., 4.))));
|
||||
// SAFETY: the erased native list serves only while `transient` is live; the
|
||||
// promote under test replaces its borrows.
|
||||
paint.set_attribute::<Option<List<Graphic>>>(Stroke::NAME, 0, Some(unsafe { core_types::record::erase_static(native) }));
|
||||
let (paint, _) = transient.alloc_sized_keyed(paint, 0).unwrap();
|
||||
|
||||
let (layout, span, _frames) = promote_paint_field(Some(paint), 1, &transient, &persistent);
|
||||
let served = promoted_paint(&span, &layout, 0, &persistent);
|
||||
let moved = std::ptr::eq(std::ptr::from_ref(served).cast::<u8>(), std::ptr::from_ref(paint).cast::<u8>());
|
||||
assert!(!moved, "an attribute-held group denies the move, so the promote parks a header of its own");
|
||||
|
||||
transient.reset();
|
||||
let served = promoted_paint(&span, &layout, 0, &persistent);
|
||||
let held = served.attribute::<Option<List<Graphic>>>(Stroke::NAME, 0).expect("the stroke attribute rides the promoted list");
|
||||
let held = held.as_ref().expect("the stroke is present");
|
||||
assert_eq!(map_groups_to_legacy(held.element(0).unwrap()), expected, "the attribute-held group serves from persistent storage after the reset");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_free_paint_field_moves_past_its_attribute_columns() {
|
||||
let mut transient = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let persistent = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
|
||||
let mut paint = List::new_from_element(Graphic::Vector(unit_square_at(DVec2::ZERO)));
|
||||
// Columns of a type that cannot hold groups, and a group-capable column
|
||||
// whose value holds none: neither denies the move.
|
||||
paint.set_attribute::<f64>("opacity", 0, 0.5);
|
||||
paint.set_attribute::<Color>("probe:color", 0, Color::BLACK);
|
||||
paint.set_attribute::<Option<List<Graphic>>>(Stroke::NAME, 0, Some(List::new_from_element(Graphic::Color(Color::WHITE))));
|
||||
let heap = {
|
||||
let Some(Graphic::Vector(vector)) = paint.element(0) else { panic!("the paint carries a vector") };
|
||||
vector.point_domain.positions().as_ptr()
|
||||
};
|
||||
let (paint, _) = transient.alloc_sized_keyed(paint, 0).unwrap();
|
||||
|
||||
let (layout, span, _frames) = promote_paint_field(Some(paint), 1, &transient, &persistent);
|
||||
let served = promoted_paint(&span, &layout, 0, &persistent);
|
||||
let Some(Graphic::Vector(vector)) = served.element(0) else { panic!("the promote keeps the vector") };
|
||||
assert_eq!(vector.point_domain.positions().as_ptr(), heap, "the promote moved the header, so the served paint names the pre-promote heap");
|
||||
|
||||
transient.reset();
|
||||
let served = promoted_paint(&span, &layout, 0, &persistent);
|
||||
assert!(matches!(served.element(0), Some(Graphic::Vector(_))), "the moved paint survives the transient reset");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_owned_record_deep_copies_attribute_held_groups() {
|
||||
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||
let source = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let native = native_group_paint(&inner_vector, &source);
|
||||
let expected = map_groups_to_legacy(native.element(0).unwrap());
|
||||
|
||||
// The field's elements are group-free; the group rides an item attribute,
|
||||
// which the shallow read alone would leave borrowing `source`.
|
||||
let mut paint = List::new_from_element(Graphic::Vector(unit_square_at(DVec2::new(2., 2.))));
|
||||
// SAFETY: the erased native list serves only while `source` is live; the
|
||||
// deep glue under test replaces its borrows at the copy-out seam.
|
||||
paint.set_attribute::<Option<List<Graphic>>>(Stroke::NAME, 0, Some(unsafe { core_types::record::erase_static(native) }));
|
||||
|
||||
let vector = unit_square_at(DVec2::new(4., 4.));
|
||||
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
|
||||
let lane = builder.push(vector.clone()).unwrap();
|
||||
builder.attr::<Fill>(lane, Some(&paint));
|
||||
let item = builder.finish();
|
||||
let layout = item.layout().clone();
|
||||
let offset = layout.offset_of(Fill::NAME, 0).unwrap();
|
||||
// SAFETY: the item's lane is a live record of `layout`.
|
||||
let owned = unsafe { core_types::record::OwnedRecord::copy_out(&layout, item.lanes().get(0).rec()) };
|
||||
drop(item);
|
||||
drop(paint);
|
||||
drop(source);
|
||||
|
||||
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let frames = core_types::record::test_frames(layout.frame_bytes());
|
||||
let mut slot = frames.claim(&layout);
|
||||
owned.replay_into(&mut slot, &arena).expect("the arena holds the replay");
|
||||
// SAFETY: the replay completes the record in the claimed frame.
|
||||
let value = unsafe { slot.finish() };
|
||||
// SAFETY: the replay wrote a record of `layout`.
|
||||
let served = unsafe { layout.rec(&value).read::<Option<&List<Graphic>>>(offset) }.expect("the fill replays present");
|
||||
let held = served.attribute::<Option<List<Graphic>>>(Stroke::NAME, 0).expect("the stroke attribute rides the replayed list");
|
||||
let held = held.as_ref().expect("the stroke is present");
|
||||
assert_eq!(map_groups_to_legacy(held.element(0).unwrap()), expected, "the attribute-held group replayed into the serving arena");
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ mod legacy;
|
||||
mod paint;
|
||||
mod walk;
|
||||
|
||||
pub(crate) use glue::list_contains_groups;
|
||||
pub(crate) use glue::{list_contains_groups, map_attribute_groups_to_owned, map_attribute_groups_to_persistent, map_attribute_groups_to_resident};
|
||||
pub use glue::{map_groups_to_owned, map_groups_to_persistent, map_groups_to_resident};
|
||||
pub(crate) use legacy::run_to_legacy_list;
|
||||
pub use legacy::{group_to_legacy_graphic, group_to_legacy_list, map_groups_to_legacy, map_paint_attrs_to_legacy, run_to_list};
|
||||
|
||||
@@ -1265,6 +1265,9 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
};
|
||||
// A lazy input claims beyond every input frame this node holds, and its
|
||||
// cursor is shared, so the inputs a kernel drives claim past each other.
|
||||
// The snapshot copies the cursor where it stands, so every frame the node
|
||||
// still reads after the kernel runs (the carrier's included) must have been
|
||||
// claimed before it.
|
||||
let lazy_frames_entry = quote! {
|
||||
let __lazy_frames = __frame.frames().reborrow();
|
||||
};
|
||||
@@ -1807,6 +1810,17 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
.filter(|field| matches!(field.ty, ParsedFieldType::Regular(_)))
|
||||
.map(|field| &field.pat_ident.ident)
|
||||
.collect();
|
||||
let tail_form = if async_fn {
|
||||
Tail::SpawnAsyncFn
|
||||
} else if future_kernel {
|
||||
Tail::SpawnFuture
|
||||
} else {
|
||||
match ir::node_kind(&node) {
|
||||
ir::NodeKind::RecordIo => Tail::Record,
|
||||
ir::NodeKind::Flip => Tail::Flip,
|
||||
ir::NodeKind::Routing | ir::NodeKind::Opaque => Tail::Forward,
|
||||
}
|
||||
};
|
||||
// A carried tail claims the node's frame first, evaluates the carrier
|
||||
// beyond it, and carries its fields; every exit closes the frame through
|
||||
// `lift_poll_into`.
|
||||
@@ -1850,6 +1864,37 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
}
|
||||
})
|
||||
});
|
||||
// A record tail's carrier claim, the one the plan and the kernel read
|
||||
// `__src_rec` out of.
|
||||
let carrier_eval = (record_io && !skips_carrier && !lazy_carrier).then(|| {
|
||||
let name = ®ular_fields[0].pat_ident.ident;
|
||||
quote! {
|
||||
let __src = match __cell.eval_input(0, &self.#name, __input, __frame.frames()) {
|
||||
Ok(value) => value,
|
||||
Err(interrupt) => return interrupt.into()
|
||||
};
|
||||
let __src_rec = self.__carrier.rec(&__src);
|
||||
}
|
||||
});
|
||||
// The carrier's record stays claimed and readable through the kernel call, so
|
||||
// its claim runs before the lazy snapshot and the lazy handles claim past it
|
||||
// rather than over it. With no lazy input there is no snapshot and the claim
|
||||
// stays in the tail.
|
||||
let has_lazy = regular_fields.iter().any(|field| matches!(field.ty, ParsedFieldType::Node(_)));
|
||||
let hoisted_carrier = match (has_lazy, tail_form) {
|
||||
(false, _) => TokenStream2::new(),
|
||||
(true, Tail::Record) => carrier_eval.clone().unwrap_or_default(),
|
||||
(true, _) => carried_prelude.clone().unwrap_or_default(),
|
||||
};
|
||||
let carried_prelude = match has_lazy {
|
||||
true => None,
|
||||
false => carried_prelude,
|
||||
};
|
||||
let carrier_eval = match has_lazy {
|
||||
true => None,
|
||||
false => carrier_eval,
|
||||
};
|
||||
let lazy_entry = quote!(#hoisted_carrier #lazy_frames_entry);
|
||||
// Async slots persist plain values across evaluations; the source lifts
|
||||
// the slot value onto its record input at every merge point, into the
|
||||
// carried frame when the node has a carrier.
|
||||
@@ -1966,16 +2011,6 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
}
|
||||
});
|
||||
let record_kernel_call = quote!(self::#fn_name(__input #(, &self.#data_names)* #(, #carrier_arg)* #(, #value_args)*));
|
||||
let carrier_eval = (!skips_carrier && !lazy_carrier).then(|| {
|
||||
let name = ®ular_fields[0].pat_ident.ident;
|
||||
quote! {
|
||||
let __src = match __cell.eval_input(0, &self.#name, __input, __frame.frames()) {
|
||||
Ok(value) => value,
|
||||
Err(interrupt) => return interrupt.into()
|
||||
};
|
||||
let __src_rec = self.__carrier.rec(&__src);
|
||||
}
|
||||
});
|
||||
let carry = (!skips_carrier && !lazy_carrier).then(|| quote!(unsafe { __frame.carry(__src_rec, &self.__plan) };));
|
||||
// A lazy carrier's source record is the token the kernel returned; its
|
||||
// content frames sit above the claim and stay readable until its drop.
|
||||
@@ -2097,17 +2132,6 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
__cell.merge(__frame.lift_served(#core_types::gpoll::GPoll::Final(__kernel_value), #core_types::context::ExtractArena::arena(__input)))
|
||||
}
|
||||
});
|
||||
let tail_form = if async_fn {
|
||||
Tail::SpawnAsyncFn
|
||||
} else if future_kernel {
|
||||
Tail::SpawnFuture
|
||||
} else {
|
||||
match ir::node_kind(&node) {
|
||||
ir::NodeKind::RecordIo => Tail::Record,
|
||||
ir::NodeKind::Flip => Tail::Flip,
|
||||
ir::NodeKind::Routing | ir::NodeKind::Opaque => Tail::Forward,
|
||||
}
|
||||
};
|
||||
let lower_tail = |form: Tail| match form {
|
||||
Tail::Forward => lift.clone(),
|
||||
Tail::Record => record_tail.clone().expect("a record-io node has a record tail"),
|
||||
@@ -2225,7 +2249,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let clamp = clamp_tokens(field);
|
||||
(field, quote!(#body #clamp))
|
||||
}),
|
||||
&lazy_frames_entry,
|
||||
&lazy_entry,
|
||||
);
|
||||
// The rebind path with nothing hoisted: every non-carrier input binds
|
||||
// fresh per lane, so an index-dependent input reaches its own lane.
|
||||
@@ -2242,7 +2266,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let clamp = clamp_tokens(field);
|
||||
(field, quote!(#body #clamp))
|
||||
}),
|
||||
&lazy_frames_entry,
|
||||
&lazy_entry,
|
||||
);
|
||||
// A hoisted value is moved into every lane's kernel call, so each
|
||||
// lane consumes a clone; view and borrow binds copy freely.
|
||||
@@ -2694,7 +2718,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
EvalStep::Bind(index, field) => {
|
||||
let body = bind_body(*index, field, false, "e!(__frame.frames()));
|
||||
match matches!(field.ty, ParsedFieldType::Node(_)) && !std::mem::replace(&mut lazy_declared, true) {
|
||||
true => quote!(#lazy_frames_entry #body),
|
||||
true => quote!(#lazy_entry #body),
|
||||
false => body,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -360,6 +360,15 @@ fn offset(_: impl Ctx, element: f64, by: &f64) -> f64 {
|
||||
element + *by
|
||||
}
|
||||
|
||||
/// Test-only flip node holding a borrow of its lent carrier across a lazy
|
||||
/// input's evaluation: the borrow points into the carrier's frame, so the lazy
|
||||
/// input's claim has to start beyond it.
|
||||
#[node_macro::node(category("Test"))]
|
||||
fn lend_across_lazy(ctx: impl Ctx, element: &f64, addend: impl Node<Context<'_>, Output = f64>) -> Result<f64, Interrupt> {
|
||||
let added = addend.eval(ctx)?;
|
||||
Ok(*element + added)
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Test"))]
|
||||
async fn double_async(_: impl Ctx, element: f64) -> f64 {
|
||||
element * 2.
|
||||
@@ -2342,6 +2351,35 @@ mod tests {
|
||||
assert_eq!(served.attr::<Opacity>(), 0.25);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lent_carrier_borrow_survives_a_lazy_inputs_claim() {
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let carrier_layout = f64_layout(&["opacity"]);
|
||||
let addend_layout = f64_layout(&["opacity"]);
|
||||
assert!(carrier_layout.frame_bytes() != 0, "the lend must borrow into a spilled frame for the claims to overlap");
|
||||
let frames = frames_for(&[&carrier_layout, &addend_layout]);
|
||||
|
||||
let node = install(
|
||||
LendAcrossLazyNode::new(
|
||||
f64_record_source(&carrier_layout, 2., vec![("opacity", 0.25)]),
|
||||
f64_record_source(&addend_layout, 40., vec![("opacity", 0.5)]),
|
||||
&carrier_layout,
|
||||
&addend_layout,
|
||||
),
|
||||
lend_across_lazy_layout_meta(),
|
||||
&[Some(&carrier_layout), None],
|
||||
);
|
||||
let GPoll::Final(served) = core_types::record::capture(&node, &ctx, &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
assert_eq!(served.element::<f64>(), 42., "the lazy input claims beyond the carrier's frame, so the borrow keeps its element");
|
||||
assert_eq!(served.attr::<Opacity>(), 0.25);
|
||||
}
|
||||
|
||||
struct InlineRuntime;
|
||||
|
||||
impl core_types::runtime::Runtime for InlineRuntime {
|
||||
|
||||
Reference in new issue
Block a user