Compare commits

..
14 changed files with 260 additions and 161 deletions

No files matched your search

@@ -1038,6 +1038,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
},
DocumentNode {
inputs: vec![
NodeInput::value(TaggedValue::None, false),
NodeInput::import(generic!(T), 0),
NodeInput::import(concrete!(Footprint), 1),
NodeInput::node(NodeId(1), 0),
+35 -76
View File
@@ -1,4 +1,3 @@
use std::any::TypeId;
use std::cell::UnsafeCell;
use std::collections::HashMap;
use std::marker::PhantomData;
@@ -27,11 +26,11 @@ 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
/// the header's address in the receiving arena and the moved size, 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)>>,
forwarded: Mutex<HashMap<usize, (usize, usize)>>,
}
impl std::fmt::Debug for Arena {
@@ -42,9 +41,9 @@ impl std::fmt::Debug for Arena {
struct DropEntry {
offset: usize,
/// The parked payload's static-type key, `None` where the park was
/// allocated without one and so never moves.
type_of: Option<TypeId>,
/// The parked payload's own size, so [`Arena::move_park`] refuses a
/// reference into a park of another type that shares the offset.
size: usize,
drop_fn: unsafe fn(*mut u8),
/// The park glue's estimate of the heap this payload owns, 0 where the
/// glue cannot measure it, so the counter is a lower bound.
@@ -215,23 +214,6 @@ impl Arena {
/// [`Arena::alloc`] with the park glue's estimate of the heap `value` owns,
/// which the region's own occupancy cannot see.
pub fn alloc_sized<T: Send + Sync>(&self, value: T, retained: usize) -> Option<(&T, ArenaWeak<T>)> {
self.alloc_stamped(value, retained, None)
}
/// [`Arena::alloc_sized`] stamping the park's static-type key, which is what
/// [`Arena::move_park`] matches on, so only a park allocated here can move.
pub fn alloc_sized_keyed<T: Send + Sync + dyn_any::StaticTypeSized>(&self, value: T, retained: usize) -> Option<(&T, ArenaWeak<T>)> {
self.alloc_stamped(value, retained, Some(TypeId::of::<T::Static>()))
}
/// [`Arena::alloc_sized_keyed`] for park glue already holding the element's
/// static form, which projects the key from the element type instead of
/// from the value's own. Crate-private: a wrong key mistypes a move.
pub(crate) fn alloc_sized_as<T: Send + Sync>(&self, value: T, retained: usize, type_of: TypeId) -> Option<(&T, ArenaWeak<T>)> {
self.alloc_stamped(value, retained, Some(type_of))
}
fn alloc_stamped<T: Send + Sync>(&self, value: T, retained: usize, type_of: Option<TypeId>) -> Option<(&T, ArenaWeak<T>)> {
let offset = self.reserve(size_of::<T>(), align_of::<T>())?;
// Built before the write so an unencodable offset drops `value` here
// rather than stranding it in the arena without drop glue.
@@ -243,7 +225,7 @@ impl Arena {
unsafe fn glue<T>(p: *mut u8) {
unsafe { p.cast::<T>().drop_in_place() }
}
self.drops.lock().unwrap().push(DropEntry { offset, type_of, drop_fn: glue::<T>, retained });
self.drops.lock().unwrap().push(DropEntry { offset, size: size_of::<T>(), drop_fn: glue::<T>, retained });
self.retained_heap.fetch_add(retained, Ordering::Relaxed);
}
// SAFETY: initialized above; insert-only, so no `&mut` to it can exist.
@@ -268,40 +250,32 @@ impl Arena {
/// have credited it, and this arena is debited what its own park recorded,
/// so neither counter reads worse than it did before the move.
///
/// The move republishes the payload at `T::Static`, which is the key both
/// [`Arena::alloc_sized_keyed`] and this stamp, so a park and its move
/// project the type exactly once each and agree by construction.
///
/// `None` where `src` is not this arena's park keyed to `T::Static`, where
/// the type is zero-sized (whose parks share an offset and so cannot be
/// told apart), or where `dst` refused the header.
/// `None` where `src` is not this arena's park of `T`'s own size, where
/// `T` is zero-sized (whose parks share an offset and so cannot be told
/// apart), or where `dst` refused the header.
///
/// # Safety
/// `src` must address a live `T`, and `T` must own all of its content: the
/// moved header may reference no storage of this arena, which is also what
/// lets the payload be republished at `T::Static`. The key settles the
/// type, so the caller owes no size or identity argument beyond those two.
pub unsafe fn move_park<T: dyn_any::StaticTypeSized>(&self, src: *const u8, dst: &Arena, retained: usize) -> Option<*const T::Static>
where
T::Static: Send + Sync,
{
(size_of::<T::Static>() != 0).then_some(())?;
/// `src` must address a live `T`, and a park of this arena at that address
/// and size must be the `T` itself, not another type's park the address
/// coincides with. `T` must own all of its content: the moved header may
/// reference no storage of this arena.
pub unsafe fn move_park<T: Send + Sync>(&self, src: *const u8, dst: &Arena, retained: usize) -> Option<*const T> {
(size_of::<T>() != 0).then_some(())?;
let offset = (src as usize).checked_sub(self.base() as usize)?;
(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) {
(moved_type == type_of).then_some(())?;
return Some(moved as *const T::Static);
if let Some(&(moved, size)) = forwarded.get(&offset) {
(size == size_of::<T>()).then_some(())?;
return Some(moved as *const T);
}
let mut entries = self.drops.lock().unwrap();
let entry = entry_at(&entries, offset)?;
(entries[entry].type_of == Some(type_of)).then_some(())?;
let slot = dst.alloc_scratch::<T::Static>(1)?;
let target = slot.as_mut_ptr().cast::<T::Static>();
(entries[entry].size == size_of::<T>()).then_some(())?;
let slot = dst.alloc_scratch::<T>(1)?;
let target = slot.as_mut_ptr().cast::<T>();
// SAFETY: the caller's contract on `src`, into a freshly reserved,
// aligned, unaliased slot of the same type.
unsafe { std::ptr::copy_nonoverlapping(src.cast::<T::Static>(), target, 1) };
unsafe { std::ptr::copy_nonoverlapping(src.cast::<T>(), target, 1) };
let parked = std::mem::replace(&mut entries[entry].retained, 0);
entries[entry].drop_fn = inert;
drop(entries);
@@ -310,13 +284,13 @@ impl Arena {
}
dst.drops.lock().unwrap().push(DropEntry {
offset: target as usize - dst.base() as usize,
type_of: Some(type_of),
drop_fn: glue::<T::Static>,
size: size_of::<T>(),
drop_fn: glue::<T>,
retained,
});
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, size_of::<T>()));
Some(target.cast_const())
}
@@ -633,7 +607,7 @@ mod tests {
let owned = String::from("moved, never cloned");
let length = owned.len();
let heap = owned.as_ptr();
let (parked, _) = transient.alloc_sized_keyed(owned, length).unwrap();
let (parked, _) = transient.alloc_sized(owned, length).unwrap();
let src = std::ptr::from_ref(parked).cast::<u8>();
let moved = unsafe { transient.move_park::<String>(src, &persistent, length) }.unwrap();
@@ -653,9 +627,6 @@ mod tests {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
static DROPS: AtomicU32 = AtomicU32::new(0);
struct Probe(#[allow(dead_code)] String);
unsafe impl dyn_any::StaticType for Probe {
type Static = Probe;
}
impl Drop for Probe {
fn drop(&mut self) {
DROPS.fetch_add(1, Ordering::Relaxed);
@@ -665,7 +636,7 @@ mod tests {
let mut transient = Arena::new(1024).unwrap();
let mut persistent = Arena::new(1024).unwrap();
let (parked, _) = transient.alloc_sized_keyed(Probe(String::from("shared by two records")), 21).unwrap();
let (parked, _) = transient.alloc_sized(Probe(String::from("shared by two records")), 21).unwrap();
let src = std::ptr::from_ref(parked).cast::<u8>();
let first = unsafe { transient.move_park::<Probe>(src, &persistent, 21) }.unwrap();
let second = unsafe { transient.move_park::<Probe>(src, &persistent, 21) }.unwrap();
@@ -681,27 +652,18 @@ mod tests {
#[test]
fn a_move_refuses_a_mistyped_park_and_its_forwarding() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
struct Owner(#[allow(dead_code)] String);
unsafe impl dyn_any::StaticType for Owner {
type Static = Owner;
}
/// Owner's layout exactly, so only the type key tells the two apart.
struct Twin(#[allow(dead_code)] String);
unsafe impl dyn_any::StaticType for Twin {
type Static = Twin;
struct Owner {
_first: String,
_tail: u64,
}
let mut transient = Arena::new(1024).unwrap();
let mut persistent = Arena::new(1024).unwrap();
let (parked, _) = transient.alloc_sized_keyed(Owner(String::from("a keyed park")), 0).unwrap();
let (parked, _) = transient.alloc(Owner { _first: String::from("a first member"), _tail: 0 }).unwrap();
let src = std::ptr::from_ref(parked).cast::<u8>();
assert!(unsafe { transient.move_park::<Twin>(src, &persistent, 0) }.is_none(), "a park of another type of the same size is refused");
assert!(unsafe { transient.move_park::<String>(src, &persistent, 0) }.is_none(), "a park of another size is refused");
unsafe { transient.move_park::<Owner>(src, &persistent, 0) }.unwrap();
assert!(unsafe { transient.move_park::<Twin>(src, &persistent, 0) }.is_none(), "the forwarding refuses the same mistype");
let (unkeyed, _) = transient.alloc(Owner(String::from("an unkeyed park"))).unwrap();
let src = std::ptr::from_ref(unkeyed).cast::<u8>();
assert!(unsafe { transient.move_park::<Owner>(src, &persistent, 0) }.is_none(), "a park allocated without a key never moves");
assert!(unsafe { transient.move_park::<String>(src, &persistent, 0) }.is_none(), "the forwarding refuses the same mistype");
transient.reset();
persistent.reset();
@@ -712,9 +674,6 @@ mod tests {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
static DROPS: AtomicU32 = AtomicU32::new(0);
struct Probe(#[allow(dead_code)] String);
unsafe impl dyn_any::StaticType for Probe {
type Static = Probe;
}
impl Drop for Probe {
fn drop(&mut self) {
DROPS.fetch_add(1, Ordering::Relaxed);
@@ -724,7 +683,7 @@ mod tests {
let mut transient = Arena::new(1024).unwrap();
let mut persistent = Arena::new(1024).unwrap();
let (parked, _) = transient.alloc_sized_keyed(Probe(String::from("first generation")), 16).unwrap();
let (parked, _) = transient.alloc_sized(Probe(String::from("first generation")), 16).unwrap();
let src = std::ptr::from_ref(parked).cast::<u8>();
unsafe { transient.move_park::<Probe>(src, &persistent, 16) }.unwrap();
assert_eq!(transient.forwarded.lock().unwrap().len(), 1, "the move tombstoned the entry it left");
@@ -79,6 +79,45 @@ impl<'e, A: Attribute> std::fmt::Debug for Attr<'e, A> {
}
}
/// An attribute write that outlives the evaluation producing it: an async
/// source's slot persists across generations, so a reference value cannot
/// cross as itself. The value crosses deep-copied through the field glue and
/// parks into the serving arena at every lift, which is why the copy is paid
/// once per invocation rather than once per evaluation.
pub struct OwnedAttr<A: Attribute>(Box<dyn AnyAttributeValue>, PhantomData<fn() -> A>);
impl<A: Attribute> OwnedAttr<A> {
/// Deep-copies `value` out of the evaluation that produced it.
pub fn new(value: A::Value<'_>) -> Self {
// SAFETY: the read addresses a live local of the marker's value type.
let erased = unsafe { A::read_erased((&raw const value).cast()) };
OwnedAttr(crate::record::deepen_field_value(erased), PhantomData)
}
/// Parks the copy into `arena` for one evaluation; `None` reports arena
/// exhaustion.
pub fn park<'e>(&self, arena: &'e crate::arena::Arena) -> Option<A::Value<'e>> {
let resident = crate::record::replay_field_value(&*self.0, arena)?;
let mut value = A::default();
// SAFETY: the slot is a live field of the marker's value type, and the
// stored value is the copy `new` took at that same type.
unsafe { write_stored::<A>(resident.as_deref().unwrap_or(&*self.0), (&raw mut value).cast(), arena) }?;
Some(value)
}
}
impl<A: Attribute> Clone for OwnedAttr<A> {
fn clone(&self) -> Self {
OwnedAttr(self.0.clone(), PhantomData)
}
}
impl<A: Attribute> std::fmt::Debug for OwnedAttr<A> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple(A::NAME).field(&self.0.display_string()).finish()
}
}
/// A deletion of `A` in a node's return tuple: the name leaves the output
/// layout, so downstream reads yield the declared default again. Functionally
/// a write of the default; the value carries nothing.
@@ -410,6 +449,27 @@ mod tests {
assert_eq!(row.size, size_of::<&str>());
}
#[test]
fn an_owned_reference_crossing_parks_into_the_serving_arena() {
let owned = OwnedAttr::<Name>::new("crossing");
let arena = crate::arena::Arena::new(1024).unwrap();
assert_eq!(owned.park(&arena).unwrap(), "crossing");
assert_eq!(owned.clone().park(&arena).unwrap(), "crossing", "the crossing parks again on every evaluation");
}
#[test]
fn an_owned_plain_crossing_rides_its_bytes() {
let arena = crate::arena::Arena::new(64).unwrap();
assert_eq!(OwnedAttr::<Opacity>::new(0.25).park(&arena).unwrap(), 0.25);
}
#[test]
fn an_exhausted_arena_refuses_an_owned_reference_crossing() {
let owned = OwnedAttr::<Name>::new("too long for this arena");
let arena = crate::arena::Arena::new(8).unwrap();
assert!(owned.park(&arena).is_none());
}
#[test]
fn reregistration_at_the_same_type_is_idempotent() {
register::<Opacity>();
+30 -45
View File
@@ -1313,7 +1313,7 @@ pub unsafe fn write_field<T>(dst: *mut u8, offset: usize, value: T) {
/// `dst` must be the claimed frame (or inline scratch when `frame_bytes` is
/// 0) of a record whose element is `T` and whose frame size is `frame_bytes`,
/// with every carried field already written.
pub(crate) unsafe fn lift_poll_into<'e, T: Send + Sync + dyn_any::StaticTypeSized>(poll: GPoll<T>, dst: *mut u8, frame_bytes: usize, arena: &'e crate::arena::Arena) -> GPoll<RecordValue<'e>> {
pub(crate) unsafe fn lift_poll_into<'e, T: Send + Sync>(poll: GPoll<T>, dst: *mut u8, frame_bytes: usize, arena: &'e crate::arena::Arena) -> GPoll<RecordValue<'e>> {
let build = |element: T| {
let written = unsafe { write_element(dst, element, arena) };
written.map(|()| match frame_bytes {
@@ -1426,13 +1426,25 @@ fn deep_field_glue(type_id: std::any::TypeId) -> Option<DeepFieldGlue> {
DEEP_FIELD_VALUES.lock().unwrap().get(&type_id).copied()
}
fn deepen_field_value(value: Box<dyn crate::list::AnyAttributeValue>) -> Box<dyn crate::list::AnyAttributeValue> {
/// The copy-out half over an erased field value: the owned form a value takes
/// when it crosses out of the evaluation whose arena its content borrows. A
/// value with no registered glue already owns everything and passes through.
pub fn deepen_field_value(value: Box<dyn crate::list::AnyAttributeValue>) -> Box<dyn crate::list::AnyAttributeValue> {
match deep_field_glue(value.as_any().type_id()) {
Some(glue) => (glue.copy_out)(&*value).unwrap_or(value),
None => value,
}
}
/// The replay half over an erased field value: `Some(None)` where the value
/// already owns its content, `None` on arena exhaustion.
pub fn replay_field_value(value: &dyn crate::list::AnyAttributeValue, arena: &crate::arena::Arena) -> Option<Option<Box<dyn crate::list::AnyAttributeValue>>> {
match deep_field_glue(value.as_any().type_id()) {
Some(glue) => (glue.replay)(value, arena),
None => Some(None),
}
}
/// The element slot a record wire of `T` carries, its erased glue bound at
/// the statically-known type.
pub fn element_write<T: Clone + Send + Sync + dyn_any::StaticTypeSized>() -> ElementWrite
@@ -1459,8 +1471,7 @@ where
}
let retained = retained_measure(std::any::TypeId::of::<T::Static>()).map_or(0, |measure| measure(value));
let value = value.downcast_ref::<T::Static>().expect("an element replays at its own type");
// SAFETY: the caller's contract, keyed as this element's own parks are.
unsafe { write_element_keyed(dst, value.clone(), arena, retained, std::any::TypeId::of::<T::Static>()) }
unsafe { write_element_sized(dst, value.clone(), arena, retained) }
}
/// Declines for a type carrying deep glue, whose value may hold interiors
/// the evaluation's arena owns and which a moved header may not reference.
@@ -1477,7 +1488,7 @@ where
let retained = retained_measure(std::any::TypeId::of::<T::Static>()).map_or(0, |measure| measure(value));
// SAFETY: as above, and the decline above establishes that the payload
// owns all of its content.
unsafe { promotion.move_park::<T>(parked, retained) }.map(<*const T::Static>::cast)
unsafe { promotion.move_park::<T::Static>(parked, retained) }.map(<*const T::Static>::cast)
}
let (size, align) = element_dims::<T>();
ElementWrite {
@@ -1564,7 +1575,7 @@ pub unsafe fn read_element<T: Clone>(rec: Rec<'_>) -> T {
/// # Safety
/// `dst` must be fresh element storage of a record whose element is `T`.
/// `None` reports arena exhaustion for a parked element.
pub unsafe fn write_element<T: Send + Sync + dyn_any::StaticTypeSized>(dst: *mut u8, value: T, arena: &crate::arena::Arena) -> Option<()> {
pub unsafe fn write_element<T: Send + Sync>(dst: *mut u8, value: T, arena: &crate::arena::Arena) -> Option<()> {
unsafe { write_element_sized(dst, value, arena, 0) }
}
@@ -1572,21 +1583,10 @@ pub unsafe fn write_element<T: Send + Sync + dyn_any::StaticTypeSized>(dst: *mut
///
/// # Safety
/// As [`write_element`].
pub unsafe fn write_element_sized<T: Send + Sync + dyn_any::StaticTypeSized>(dst: *mut u8, value: T, arena: &crate::arena::Arena, retained: usize) -> Option<()> {
// SAFETY: the caller's contract; `T::Static` is the element type's own key.
unsafe { write_element_keyed(dst, value, arena, retained, std::any::TypeId::of::<T::Static>()) }
}
/// [`write_element_sized`] for replay glue already holding the element's
/// static form, whose key the element type it replays into supplies.
///
/// # Safety
/// As [`write_element`], and `type_of` must be that element type's key, since
/// a park carrying it is what [`Promotion::move_park`] moves at.
pub(crate) unsafe fn write_element_keyed<T: Send + Sync>(dst: *mut u8, value: T, arena: &crate::arena::Arena, retained: usize, type_of: std::any::TypeId) -> Option<()> {
pub unsafe fn write_element_sized<T: Send + Sync>(dst: *mut u8, value: T, arena: &crate::arena::Arena, retained: usize) -> Option<()> {
match element_parked::<T>() {
true => {
let (parked, _) = arena.alloc_sized_as(value, retained, type_of)?;
let (parked, _) = arena.alloc_sized(value, retained)?;
unsafe { dst.cast::<&T>().write(parked) };
Some(())
}
@@ -1867,9 +1867,8 @@ impl<'a> Promotion<'a> {
/// Moves a transient payload's header into the persistent region instead of
/// cloning the heap it owns: the heap travels with the drop obligation and
/// is freed at the persistent flush, never at the transient reset. `None`
/// where the header is not the transient arena's own park keyed to `T`'s
/// static type or the region refused it, which leaves the caller its clone
/// path.
/// where the header is not the transient arena's own park of `T`'s size or
/// the region refused it, which leaves the caller its clone path.
///
/// The forwarding is the evaluation's, so a payload two records share moves
/// once and both reach the one persistent header. The source header stays
@@ -1877,14 +1876,10 @@ impl<'a> Promotion<'a> {
/// the move keeps sound: no read of it may outlive the persistent flush.
///
/// # Safety
/// `parked` must address a live `T`, and `T` must own all of its content, a
/// persistent header being allowed to reference no transient storage, which
/// is also what lets it be republished at `T::Static`. The park's key
/// settles the type, so the caller owes no identity argument.
pub unsafe fn move_park<T: dyn_any::StaticTypeSized>(&self, parked: *const u8, retained: usize) -> Option<*const T::Static>
where
T::Static: Send + Sync,
{
/// `parked` must address a live `T`, and a transient park at that address
/// and size must be the `T` itself. `T` must own all of its content, a
/// persistent header being allowed to reference no transient storage.
pub unsafe fn move_park<T: Send + Sync>(&self, parked: *const u8, retained: usize) -> Option<*const T> {
// SAFETY: the caller's contract, forwarded to the parking arena.
unsafe { self.transient.move_park::<T>(parked, self.persistent, retained) }
}
@@ -1935,14 +1930,9 @@ unsafe fn promote_record(layout: &Layout, dst: *mut u8, promotion: &Promotion<'_
}
// SAFETY: the slot images a parked field of this descriptor.
let value = deepen_field_value(unsafe { (field.read_erased)(slot.cast_const()) });
match deep_field_glue(value.as_any().type_id()) {
Some(glue) => match (glue.replay)(&*value, promotion.persistent)? {
// SAFETY: the replay produced this field's own value type.
Some(resident) => unsafe { repark(&*resident, slot, promotion.persistent) }?,
None => unsafe { repark(&*value, slot, promotion.persistent) }?,
},
None => unsafe { repark(&*value, slot, promotion.persistent) }?,
}
let resident = replay_field_value(&*value, promotion.persistent)?;
// SAFETY: the replay produced this field's own value type.
unsafe { repark(resident.as_deref().unwrap_or(&*value), slot, promotion.persistent) }?;
}
Some(())
}
@@ -2220,13 +2210,8 @@ impl OwnedRecord {
for (index, value) in &self.fields {
let field = &layout.fields[*index];
let repark = field.repark.expect("copied fields carry re-park glue");
match deep_field_glue(value.as_any().type_id()) {
Some(glue) => match (glue.replay)(&**value, arena)? {
Some(resident) => unsafe { repark(&*resident, dst.add(field.offset), arena) }?,
None => unsafe { repark(&**value, dst.add(field.offset), arena) }?,
},
None => unsafe { repark(&**value, dst.add(field.offset), arena) }?,
}
let resident = replay_field_value(&**value, arena)?;
unsafe { repark(resident.as_deref().unwrap_or(&**value), dst.add(field.offset), arena) }?;
}
Some(())
}
@@ -1842,7 +1842,7 @@ mod run_tests {
};
// SAFETY: the list serves only while `persistent` is live, and the
// promote under test replaces every borrow it carries.
let (paint, _) = transient.alloc_sized_keyed(unsafe { core_types::record::erase_static(published) }, 0).unwrap();
let (paint, _) = transient.alloc(unsafe { core_types::record::erase_static(published) }).unwrap();
let occupied = persistent.occupancy();
let (layout, span, _frames) = promote_paint_field(Some(paint), 1, &transient, &persistent);
@@ -1866,7 +1866,7 @@ mod run_tests {
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 (paint, _) = transient.alloc(paint).unwrap();
let (layout, span, _frames) = promote_paint_field(Some(paint), 2, &transient, &persistent);
let served = promoted_paint(&span, &layout, 0, &persistent);
+26 -10
View File
@@ -132,18 +132,20 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
// Flipped nodes carry their kernel generics as struct parameters: record
// edges no longer bind them through `Output`, so the struct must. A
// ranked input's element generic is carried on any node kind for the
// same reason: the materialized view monomorphizes the kernel per row.
// same reason: the materialized view monomorphizes the kernel per row. A
// record-io node's secondary inputs read erased off their wire, so a
// generic one of them names is carried too.
let ctx_ident_for_flip = context_param(parsed).map(|ctx| ctx.ident.clone());
let ranked_carries = |ident: &Ident| {
regular_fields.iter().any(|field| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, list_levels, .. }) => *list_levels > 0 && type_contains_ident(ty, ident),
let carries_generic = |ident: &Ident| {
regular_fields.iter().enumerate().any(|(index, field)| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, list_levels, .. }) => (*list_levels > 0 || (record_io && index > 0)) && type_contains_ident(ty, ident),
_ => false,
})
};
let carried_generics: Vec<&syn::GenericParam> = fn_generics
.iter()
.filter(|param| match param {
syn::GenericParam::Type(tp) => Some(&tp.ident) != ctx_ident_for_flip.as_ref() && !data_field_generic_idents.contains(&tp.ident) && (flip || ranked_carries(&tp.ident)),
syn::GenericParam::Type(tp) => Some(&tp.ident) != ctx_ident_for_flip.as_ref() && !data_field_generic_idents.contains(&tp.ident) && (flip || carries_generic(&tp.ident)),
_ => false,
})
.collect();
@@ -1859,14 +1861,28 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
// carried frame when the node has a carrier.
// A writing source stores the kernel's whole tuple as that plain value:
// the lift writes the attributes through the claim, then lifts the
// element, the shape the sync record tail closes with.
// element, the shape the sync record tail closes with. An owned crossing
// parks into the serving arena first, so its exhaustion is a poll.
let source_writes = (record_io && async_source && !write_markers.is_empty()).then(|| {
let binders: Vec<Ident> = (0..write_markers.len()).map(|index| format_ident!("__attr_{index}")).collect();
let slots: Vec<Ident> = (0..write_markers.len()).map(|index| format_ident!("__write_{index}")).collect();
let stores = node.output.shape.attrs.iter().enumerate().map(|(index, attr)| {
let binder = &binders[index];
let slot = format_ident!("__write_{index}");
match attr.owned {
false => quote!(unsafe { __frame.attr_at(self.#slot, #binder.0) };),
true => quote! {
let #binder = match #binder.park(#core_types::context::ExtractArena::arena(__input)) {
::core::option::Option::Some(value) => value,
::core::option::Option::None => return #core_types::gpoll::GPoll::arena_exhausted(),
};
unsafe { __frame.attr_at(self.#slot, #binder) };
},
}
});
quote! {
.map(|(__element #(, #core_types::attribute::Attr(#binders))*)| {
#(unsafe { __frame.attr_at(self.#slots, #binders) };)*
__element
.and_then(|(__element #(, #binders)*)| {
#(#stores)*
#core_types::gpoll::GPoll::Final(__element)
})
}
});
+26 -3
View File
@@ -96,9 +96,16 @@ fn output(parsed: &ParsedNodeFn, generics: &[Ident]) -> Output {
shape: ItemShape {
element: element_of(&element, generics),
depth,
attrs: writes.into_iter().map(|marker| LevelAttr { marker, level: 0 }).collect(),
attrs: writes
.into_iter()
.map(|write| LevelAttr {
marker: write.marker,
level: 0,
owned: write.owned,
})
.collect(),
},
removes: removes.into_iter().map(|marker| LevelAttr { marker, level: 0 }).collect(),
removes: removes.into_iter().map(|marker| LevelAttr { marker, level: 0, owned: false }).collect(),
gathers,
}
}
@@ -158,6 +165,7 @@ fn item_shape(element: &Type, depth: u8, reads: &[AttributeRead], generics: &[Id
.map(|read| LevelAttr {
marker: read.marker.clone(),
level: 0,
owned: false,
})
.collect(),
}
@@ -557,6 +565,8 @@ pub(crate) enum Element {
pub(crate) struct LevelAttr {
pub(crate) marker: Type,
pub(crate) level: u8,
/// Writes only: the value crosses as an owned copy that parks at the lift.
pub(crate) owned: bool,
}
pub(crate) enum Effect {
@@ -680,7 +690,7 @@ mod tests {
Facts {
sources: if skips_carrier(parsed) { vec![] } else { vec![0] },
carried: token_carrier(parsed),
writes: markers(write_markers.iter()),
writes: markers(write_markers.iter().map(|write| &write.marker)),
removes: markers(removes.iter()),
delta: 0,
}
@@ -780,6 +790,19 @@ mod tests {
);
}
#[test]
fn bridge_record_owned_write_async_source() {
let node = assert_bridge(
quote!(category("")),
quote!(
async fn tag_async(_: impl Ctx, _: (), val: f64) -> (f64, OwnedAttr<Label>) {
(val, OwnedAttr::new(""))
}
),
);
assert!(node.output.shape.attrs.iter().all(|attr| attr.owned), "an `OwnedAttr` slot crosses the boundary owned");
}
/// An async source's element is the value its slot stores, so a byte-carried
/// generic token has no form here.
#[test]
+18 -4
View File
@@ -51,13 +51,20 @@ pub(crate) struct AttributeRead {
pub(crate) marker: Type,
}
/// One attribute write slot: the marker, and whether it crosses as an owned
/// copy (`OwnedAttr<M>`) instead of an evaluation-lifetime value (`Attr<M>`).
pub(crate) struct AttrWrite {
pub(crate) marker: Type,
pub(crate) owned: bool,
}
/// The write half of a record kernel's return: the element type in the first
/// tuple slot, then the attribute markers written and the ones removed. `None`
/// unless the value is a well-formed write tuple (a non-marker element first,
/// then only `Attr` and `RemoveAttr` slots, at least one).
/// then only `Attr`, `OwnedAttr` and `RemoveAttr` slots, at least one).
pub(crate) struct RecordWrites {
pub(crate) element: Type,
pub(crate) markers: Vec<Type>,
pub(crate) markers: Vec<AttrWrite>,
pub(crate) removes: Vec<Type>,
}
@@ -65,14 +72,16 @@ pub(crate) fn record_writes(value: &Type) -> Option<RecordWrites> {
let Type::Tuple(tuple) = value else { return None };
let mut slots = tuple.elems.iter();
let element = slots.next()?;
if attr_marker(element).is_some() || remove_attr_marker(element).is_some() {
if attr_marker(element).is_some() || owned_attr_marker(element).is_some() || remove_attr_marker(element).is_some() {
return None;
}
let mut markers = Vec::new();
let mut removes = Vec::new();
for slot in slots {
if let Some(marker) = attr_marker(slot) {
markers.push(marker);
markers.push(AttrWrite { marker, owned: false });
} else if let Some(marker) = owned_attr_marker(slot) {
markers.push(AttrWrite { marker, owned: true });
} else if let Some(marker) = remove_attr_marker(slot) {
removes.push(marker);
} else {
@@ -91,6 +100,11 @@ pub(crate) fn attr_marker(ty: &Type) -> Option<Type> {
marker_of(ty, "Attr")
}
/// Returns the marker type of an `OwnedAttr<Marker>` type, if `ty` is one.
pub(crate) fn owned_attr_marker(ty: &Type) -> Option<Type> {
marker_of(ty, "OwnedAttr")
}
/// Returns the marker type of a `RemoveAttr<Marker>` type, if `ty` is one.
pub(crate) fn remove_attr_marker(ty: &Type) -> Option<Type> {
marker_of(ty, "RemoveAttr")
+5 -2
View File
@@ -162,8 +162,11 @@ fn validate_record_io(parsed: &ParsedNodeFn) {
}
if let Some(writes) = &writes {
let mut seen_writes: Vec<String> = Vec::new();
for marker in &writes.markers {
let written = marker.to_token_stream().to_string();
for write in &writes.markers {
if write.owned && !async_source {
emit_error!(parsed.output_type.span(), "an owned attribute crossing belongs to an async source; a synchronous write parks its value in the kernel");
}
let written = write.marker.to_token_stream().to_string();
if seen_writes.contains(&written) {
emit_error!(parsed.output_type.span(), "attribute `{}` is written twice", written);
}
+39 -1
View File
@@ -6,7 +6,7 @@
//! wiring is by hand until the compiler pass constructs layouts.
use core_types::Ctx;
use core_types::attribute::{Attr, EditorLayerPath, Opacity, RemoveAttr, Transform};
use core_types::attribute::{Attr, EditorLayerPath, Opacity, OwnedAttr, RemoveAttr, Transform};
use core_types::context::{DeriveCtx, ExtractIndex, IndexLink, InjectIndex, ModifyIndex};
use core_types::extent::{ExtentIn, LevelIn, ListIn, ValueIn};
use core_types::gpoll::{ErrorKind, Extent, GPoll, GraphError, Interrupt, Level};
@@ -379,6 +379,13 @@ async fn measure_async(_: impl Ctx, _: (), element: f64) -> (f64, Attr<Length>)
(element, Attr(element.abs()))
}
/// Test-only async source whose reference value crosses the future boundary
/// owned: the slot holds the deep copy and every lift parks it afresh.
#[node_macro::node(category("Test"))]
async fn tag_async(_: impl Ctx, _: (), element: f64, label: String) -> (f64, OwnedAttr<Label>) {
(element, OwnedAttr::new(label.as_str()))
}
#[node_macro::node(category("Test"))]
fn fallback(ctx: impl Ctx, _: (), #[expose] content: impl Node<Context<'_>, Output = (f64, Attr<Opacity>)>, #[expose] alternate: impl Node<Context<'_>, Output = f64>) -> Result<f64, Interrupt> {
let (element, opacity) = content.eval(ctx)?;
@@ -2452,6 +2459,37 @@ mod tests {
assert_eq!(served.attr::<Length>(), 4.);
}
#[test]
fn an_owned_crossing_parks_its_reference_on_every_lift() {
let arena = Arena::new(1024).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let (runtime, _) = lifted_value(core_types::runtime::RuntimeHandle(std::sync::Arc::new(InlineRuntime)));
let (source_id, _) = lifted_value(7 as SourceId);
let layout = tag_async_layout();
let frames = frames_for(&[&layout]);
let node = install(
TagAsyncNode::new(ValueSource::new(()), ValueSource::new(3.), ValueSource::new("tagged".to_string()), runtime, source_id),
tag_async_layout_meta(),
&[],
);
assert_eq!(Node::<ContextImpl>::layout(&node), &layout);
let offset = layout.offset_of("label", 0).expect("the source writes the label");
for pass in ["the spawning eval", "the slot hit"] {
let scoped = frames.scope();
let GPoll::Final(value) = core_types::record::serve_edge(&node, &ctx, &scoped) else {
panic!("an inline completion is final on {pass}");
};
let rec = layout.rec(&value);
assert_eq!(unsafe { rec.element::<f64>() }, 3., "{pass}");
assert_eq!(unsafe { rec.read::<&str>(offset) }, "tagged", "{pass}");
}
}
#[test]
fn lazy_reads_bind_to_their_edge_and_leave_the_untaken_branch_unevaluated() {
let arena = Arena::new(1024).unwrap();
+1 -1
View File
@@ -214,7 +214,7 @@ where
};
let park_paint = |paint: Option<List<Graphic<'static>>>| -> Result<Option<&'e List<Graphic<'static>>>, Interrupt> {
match paint {
Some(paint) => Ok(Some(arena.alloc_sized_keyed(paint, 0).ok_or_else(exhausted)?.0)),
Some(paint) => Ok(Some(arena.alloc(paint).ok_or_else(exhausted)?.0)),
None => Ok(None),
}
};
@@ -2,10 +2,12 @@
use base64::Engine;
#[cfg(target_family = "wasm")]
use canvas_utils::{Canvas, CanvasHandle};
#[cfg(target_family = "wasm")]
use core_types::attribute::{Attr, OwnedAttr, Transform};
use core_types::color::SRGBA8;
use core_types::gpoll::GPoll;
#[cfg(target_family = "wasm")]
use core_types::list::{Item, List};
use core_types::list::List;
#[cfg(target_family = "wasm")]
use core_types::math::bbox::Bbox;
@@ -21,13 +23,13 @@ pub use graph_craft::document::value::RenderOutputType;
#[cfg(target_family = "wasm")]
pub use graphene_canvas_utils as canvas_utils;
#[cfg(target_family = "wasm")]
use graphic_types::ATTR_EDITOR_MERGED_LAYERS;
#[cfg(target_family = "wasm")]
use graphic_types::Graphic;
#[cfg(target_family = "wasm")]
use graphic_types::IntoGraphicList;
#[cfg(target_family = "wasm")]
use graphic_types::Vector;
#[cfg(target_family = "wasm")]
use graphic_types::markers::EditorMergedLayers;
use graphic_types::raster_types::Image;
use graphic_types::raster_types::{CPU, Raster};
#[cfg(target_family = "wasm")]
@@ -204,6 +206,7 @@ fn create_canvas(_: impl Ctx) -> CanvasHandle {
#[node_macro::node(category(""))]
async fn rasterize<T: WasmNotSend + Clone>(
_: impl Ctx,
_: (),
#[implementations(
List<Vector>,
List<Raster<CPU>>,
@@ -214,7 +217,7 @@ async fn rasterize<T: WasmNotSend + Clone>(
mut data: List<T>,
footprint: Footprint,
mut canvas: CanvasHandle,
) -> List<Raster<CPU>>
) -> (Raster<CPU>, Attr<Transform>, OwnedAttr<EditorMergedLayers>)
where
List<T>: Render + Clone + graphic_types::IntoGraphicList,
{
@@ -222,12 +225,15 @@ where
if footprint.transform.matrix2.determinant() == 0. {
log::trace!("Invalid footprint received for rasterization");
return List::new();
// A zero-size raster renders as nothing, matching the legacy empty list
return (Raster::new_cpu(Image::default()), Attr(DAffine2::IDENTITY), OwnedAttr::new(None));
}
// Snapshot the input as a List<Graphic> so the renderer can recurse into the original child layers
// when collecting metadata, exposing their click targets to editor tools (same mechanism as Boolean Operation).
// The copy is owned before the first await: the input's arena content dies with the spawning evaluation.
let upstream_graphic_list = data.clone().into_graphic_list();
let merged_layers = OwnedAttr::new(Some(&upstream_graphic_list));
let mut render = SvgRender::new();
let aabb = Bbox::from_transform(footprint.transform).to_axis_aligned_bbox();
@@ -264,11 +270,7 @@ where
let rasterized = context.get_image_data(0, 0, resolution.x as i32, resolution.y as i32).unwrap();
let image = Image::from_image_data(&rasterized.data().0, resolution.x as u32, resolution.y as u32);
List::new_from_item(
Item::new_from_element(Raster::new_cpu(image))
.with_attribute(ATTR_TRANSFORM, footprint.transform)
.with_attribute(ATTR_EDITOR_MERGED_LAYERS, Some(upstream_graphic_list)),
)
(Raster::new_cpu(image), Attr(footprint.transform), merged_layers)
}
#[node_macro::node(category(""), inject_scope)]
+2 -2
View File
@@ -69,7 +69,7 @@ fn boolean_core<'e>(
};
let park_paint = |paint: Option<List<Graphic<'static>>>| -> Result<Option<&'e List<Graphic>>, core_types::gpoll::Interrupt> {
match paint {
Some(list) => Ok(Some(arena.alloc_sized_keyed(list, 0).ok_or_else(exhausted)?.0)),
Some(list) => Ok(Some(arena.alloc(list).ok_or_else(exhausted)?.0)),
None => Ok(None),
}
};
@@ -82,7 +82,7 @@ fn boolean_core<'e>(
let layer_path = arena.alloc(layer_path).ok_or_else(exhausted)?.0;
// Snapshot the input layers so the renderer can recurse into them for
// editor click-target preservation.
let merged_layers = arena.alloc_sized_keyed(snapshot, 0).ok_or_else(exhausted)?.0;
let merged_layers = arena.alloc(snapshot).ok_or_else(exhausted)?.0;
Ok((
element,
+3 -5
View File
@@ -276,10 +276,8 @@ fn assign_colors_graphic_extent(
pub use _assign_colors_graphic_mod::assign_colors_graphic_entries;
/// Keyed, so a group-free paint's promote moves this header rather than
/// cloning the content it owns.
fn park_paint<'e>(arena: &'e core_types::arena::Arena, paint: List<Graphic<'static>>) -> Result<&'e List<Graphic<'static>>, Interrupt> {
let (parked, _) = arena.alloc_sized_keyed(paint, 0).ok_or(GraphError {
let (parked, _) = arena.alloc(paint).ok_or(GraphError {
kind: core_types::gpoll::ErrorKind::ArenaExhausted,
trace: Vec::new(),
})?;
@@ -1557,7 +1555,7 @@ fn emit_legacy_lane<'e>(
let merged_layers = output
.attribute::<Option<List<Graphic>>>(ATTR_EDITOR_MERGED_LAYERS, lane)
.and_then(|layers| layers.as_ref())
.map(|layers| arena.alloc_sized_keyed(layers.clone(), 0).ok_or_else(exhausted).map(|(parked, _)| parked))
.map(|layers| arena.alloc(layers.clone()).ok_or_else(exhausted).map(|(parked, _)| parked))
.transpose()?;
Ok((
@@ -1886,7 +1884,7 @@ fn flatten_path_core<'e>(
let layer_path = arena.alloc(layer_path).ok_or_else(exhausted)?.0;
// Snapshot the input layers so the renderer can recurse into them for
// editor click-target preservation, as the boolean operation does.
let merged_layers = arena.alloc_sized_keyed(snapshot, 0).ok_or_else(exhausted)?.0;
let merged_layers = arena.alloc(snapshot).ok_or_else(exhausted)?.0;
Ok((output, Attr(DAffine2::IDENTITY), Attr(fill), Attr(stroke), Attr(layer_path.as_slice()), Attr(Some(merged_layers))))
}