Update node macro to new syntax

This commit is contained in:
Dennis Kobert
2026-07-26 20:58:11 +00:00
parent 99f94503c3
commit 44277c9636
11 changed files with 1492 additions and 347 deletions

View File

@@ -36,6 +36,9 @@ pub trait ExtractPosition {
}
pub trait ExtractIndex {
fn try_index(&self) -> Option<impl Iterator<Item = usize>>;
fn innermost_index(&self) -> u64 {
self.try_index().and_then(|mut indices| indices.next()).unwrap_or(0) as u64
}
}
pub trait ExtractVarArgs {
// TODO: Consider returning a slice or something like that
@@ -466,7 +469,8 @@ impl CloneVarArgs for Arc<OwnedContextImpl> {
// TYPES `Context` AND `OwnedContextImpl`
// ======================================
pub type Context<'a> = Option<Arc<OwnedContextImpl>>;
pub type OwnedContext = Option<Arc<OwnedContextImpl>>;
pub type Context<'a> = ContextImpl<'a>;
type DynRef<'a> = &'a (dyn Any + Send + Sync);
type DynBox = Box<dyn AnyHash + Send + Sync>;
@@ -655,9 +659,39 @@ pub struct PositionLink<'a> {
pub type DynSlot<'a> = &'a (dyn AnyHash + Send + Sync);
#[derive(Clone, Copy)]
pub enum VarArgSlots<'a> {
Single(DynSlot<'a>),
Slice(&'a [DynSlot<'a>]),
}
impl<'a> VarArgSlots<'a> {
pub fn get(&self, index: usize) -> Option<DynSlot<'a>> {
match self {
VarArgSlots::Single(slot) => (index == 0).then_some(*slot),
VarArgSlots::Slice(slots) => slots.get(index).copied(),
}
}
pub fn len(&self) -> usize {
match self {
VarArgSlots::Single(_) => 1,
VarArgSlots::Slice(slots) => slots.len(),
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn iter(&self) -> impl Iterator<Item = DynSlot<'a>> + '_ {
(0..self.len()).filter_map(move |index| self.get(index))
}
}
#[derive(Clone, Copy)]
pub struct VarArgLink<'a> {
pub args: &'a [DynSlot<'a>],
pub args: VarArgSlots<'a>,
pub outer: Option<&'a VarArgLink<'a>>,
}
@@ -704,6 +738,17 @@ impl<'a> EvalScope<'a> {
scope
}
pub fn nullified(&self, keep: ContextFeatures) -> EvalScope<'a> {
let mut scope = EvalScope {
real_time: self.real_time.filter(|_| keep.contains(ContextFeatures::REAL_TIME)),
animation_time: self.animation_time.filter(|_| keep.contains(ContextFeatures::ANIMATION_TIME)),
pointer_position: self.pointer_position.filter(|_| keep.contains(ContextFeatures::POINTER_POSITION)),
..*self
};
scope.hash = scope.compute_hash(None);
scope
}
fn compute_hash(&self, retain: Option<&[SourceId]>) -> u64 {
let mut hasher = std::hash::DefaultHasher::new();
self.real_time.map(f64::to_bits).hash(&mut hasher);
@@ -735,6 +780,106 @@ pub trait ExtractArena {
fn arena(&self) -> Self::ArenaRef;
}
pub trait CtxFamily {
type Ctx<'s>: Ctx + DeriveCtx<Family = Self>;
}
pub type Derived<'s, C> = <<C as DeriveCtx>::Family as CtxFamily>::Ctx<'s>;
pub trait DeriveCtx {
type Family: CtxFamily;
fn derived(&self) -> Derived<'_, Self>;
fn index_head(&self) -> IndexLink<'_>;
fn scope(&self) -> &EvalScope<'_>;
fn position_head(&self) -> Option<&PositionLink<'_>>;
fn varargs_head(&self) -> Option<&VarArgLink<'_>>;
fn promoted<'s>(&'s self, spilled_head: &'s IndexLink<'s>, inner_index: u64) -> Derived<'s, Self>;
fn with_footprint<'s>(&'s self, footprint: &'s Footprint) -> Derived<'s, Self>;
fn with_varargs<'s>(&'s self, varargs: &'s VarArgLink<'s>) -> Derived<'s, Self>;
fn with_position<'s>(&'s self, position: &'s PositionLink<'s>) -> Derived<'s, Self>;
fn with_scope<'s>(&'s self, scope: &'s EvalScope<'s>) -> Derived<'s, Self>;
fn nullified<'s>(&'s self, keep: ContextFeatures, scope: &'s EvalScope<'s>) -> Derived<'s, Self>;
fn modify_footprint(&self, modify: impl FnOnce(&mut Footprint)) -> ModifiedFootprint<'_, Self>
where
Self: ExtractFootprint + Sized,
{
let mut footprint = self.try_footprint().copied();
if let Some(footprint) = &mut footprint {
modify(footprint);
}
ModifiedFootprint { ctx: self, footprint }
}
fn push_vararg<'s>(&'s self, arg: DynSlot<'s>) -> VarArgScope<'s, Self>
where
Self: Sized,
{
VarArgScope {
ctx: self,
link: VarArgLink {
args: VarArgSlots::Single(arg),
outer: self.varargs_head(),
},
}
}
fn push_position(&self, position: DVec2) -> PositionScope<'_, Self>
where
Self: Sized,
{
PositionScope {
ctx: self,
link: PositionLink {
position,
outer: self.position_head(),
},
}
}
}
pub struct PositionScope<'c, C> {
ctx: &'c C,
link: PositionLink<'c>,
}
impl<C: DeriveCtx> PositionScope<'_, C> {
pub fn ctx(&self) -> Derived<'_, C> {
self.ctx.with_position(&self.link)
}
}
pub struct VarArgScope<'c, C> {
ctx: &'c C,
link: VarArgLink<'c>,
}
impl<C: DeriveCtx> VarArgScope<'_, C> {
pub fn ctx(&self) -> Derived<'_, C> {
self.ctx.with_varargs(&self.link)
}
}
pub struct ModifiedFootprint<'c, C> {
ctx: &'c C,
footprint: Option<Footprint>,
}
impl<C: DeriveCtx> ModifiedFootprint<'_, C> {
pub fn ctx(&self) -> Derived<'_, C> {
match &self.footprint {
Some(footprint) => self.ctx.with_footprint(footprint),
None => self.ctx.derived(),
}
}
}
pub struct ContextImplFamily;
impl CtxFamily for ContextImplFamily {
type Ctx<'s> = ContextImpl<'s>;
}
#[derive(Clone, Copy)]
pub struct ContextImpl<'a> {
index: IndexLink<'a>,
@@ -791,6 +936,22 @@ impl<'a> ContextImpl<'a> {
ContextImpl { position: Some(position), ..*self }
}
pub fn nullified<'s>(&self, keep: ContextFeatures, scope: &'s EvalScope<'s>) -> ContextImpl<'s>
where
'a: 's,
{
ContextImpl {
index: match keep.contains(ContextFeatures::INDEX) {
true => self.index,
false => IndexLink { index: 0, outer: None },
},
position: self.position.filter(|_| keep.contains(ContextFeatures::POSITION)),
varargs: self.varargs.filter(|_| keep.contains(ContextFeatures::VARARGS)),
footprint: self.footprint.filter(|_| keep.contains(ContextFeatures::FOOTPRINT)),
scope,
}
}
pub fn promoted<'s>(&self, spilled_head: &'s IndexLink<'s>, inner_index: u64) -> ContextImpl<'s>
where
'a: 's,
@@ -849,7 +1010,7 @@ impl ExtractVarArgs for ContextImpl<'_> {
let mut remaining = index;
loop {
match link.args.get(remaining) {
Some(arg) => return Ok(*arg as DynRef<'_>),
Some(arg) => return Ok(arg as DynRef<'_>),
None => {
remaining -= link.args.len();
link = link.outer.ok_or(VarArgsResult::IndexOutOfBounds)?;
@@ -867,7 +1028,7 @@ impl ExtractVarArgs for ContextImpl<'_> {
let mut count = 0u64;
let mut link = self.varargs;
while let Some(current) = link {
for arg in current.args {
for arg in current.args.iter() {
arg.dyn_hash(&mut *hasher);
count += 1;
}
@@ -883,6 +1044,54 @@ impl<'a> ExtractArena for ContextImpl<'a> {
}
}
impl<'a> DeriveCtx for ContextImpl<'a> {
type Family = ContextImplFamily;
fn derived(&self) -> ContextImpl<'_> {
*self
}
fn index_head(&self) -> IndexLink<'_> {
self.index
}
fn scope(&self) -> &EvalScope<'_> {
self.scope
}
fn position_head(&self) -> Option<&PositionLink<'_>> {
self.position
}
fn varargs_head(&self) -> Option<&VarArgLink<'_>> {
self.varargs
}
fn promoted<'s>(&'s self, spilled_head: &'s IndexLink<'s>, inner_index: u64) -> ContextImpl<'s> {
ContextImpl::promoted(self, spilled_head, inner_index)
}
fn with_footprint<'s>(&'s self, footprint: &'s Footprint) -> ContextImpl<'s> {
ContextImpl::with_footprint(self, footprint)
}
fn with_varargs<'s>(&'s self, varargs: &'s VarArgLink<'s>) -> ContextImpl<'s> {
ContextImpl::with_varargs(self, varargs)
}
fn with_position<'s>(&'s self, position: &'s PositionLink<'s>) -> ContextImpl<'s> {
ContextImpl::with_position(self, position)
}
fn with_scope<'s>(&'s self, scope: &'s EvalScope<'s>) -> ContextImpl<'s> {
ContextImpl::with_scope(self, scope)
}
fn nullified<'s>(&'s self, keep: ContextFeatures, scope: &'s EvalScope<'s>) -> ContextImpl<'s> {
ContextImpl::nullified(self, keep, scope)
}
}
impl graphene_hash::CacheHash for ContextImpl<'_> {
fn cache_hash<H: Hasher>(&self, state: &mut H) {
match self.footprint {
@@ -1053,13 +1262,15 @@ mod context_impl_tests {
let outer_value = 7u32;
let outer_args: [DynSlot; 1] = [&outer_value];
let outer_link = VarArgLink { args: &outer_args, outer: None };
let outer_link = VarArgLink {
args: VarArgSlots::Slice(&outer_args),
outer: None,
};
let outer_ctx = root.with_varargs(&outer_link);
let inner_value = String::from("inner");
let inner_args: [DynSlot; 1] = [&inner_value];
let inner_link = VarArgLink {
args: &inner_args,
args: VarArgSlots::Single(&inner_value),
outer: Some(&outer_link),
};
let inner_ctx = root.with_varargs(&inner_link);

View File

@@ -1,5 +1,6 @@
use crate::context::InjectIndex;
use crate::gpoll::{Extent, Finality, GPoll, GraphError};
use crate::gpoll::{Extent, Finality, GPoll, GraphError, Interrupt};
use std::cell::Cell;
use std::mem::MaybeUninit;
use std::ops::Range;
@@ -118,6 +119,123 @@ where
}
}
pub struct StatusCell {
finality: Cell<Finality>,
error: Cell<Option<GraphError>>,
no_partial: bool,
}
impl Default for StatusCell {
fn default() -> Self {
Self::new()
}
}
impl StatusCell {
pub fn new() -> Self {
Self {
finality: Cell::new(Finality::AllFinal),
error: Cell::new(None),
no_partial: false,
}
}
pub fn no_partial() -> Self {
Self {
no_partial: true,
..Self::new()
}
}
pub fn eval_input<Input, N: GNode<Input>>(&self, input_index: usize, node: &N, input: &Input) -> Result<N::Output, Interrupt> {
match node.eval(input) {
GPoll::Final(value) => Ok(value),
GPoll::Partial(_) if self.no_partial => Err(Interrupt::Pending),
GPoll::Partial(value) => {
self.finality.set(Finality::Partial);
Ok(value)
}
GPoll::Fallback(boxed) => {
let (value, error) = *boxed;
let first = self.error.take();
self.error.set(first.or(Some(error.traced(input_index))));
Ok(value)
}
GPoll::Pending => Err(Interrupt::Pending),
GPoll::Error(mut error) => {
error.trace.push(input_index);
Err(Interrupt::Error(error))
}
}
}
pub fn finish<T>(self, value: T) -> GPoll<T> {
match (self.error.take(), self.finality.get()) {
(Some(error), _) => GPoll::Fallback(Box::new((value, error))),
(None, Finality::AllFinal) => GPoll::Final(value),
(None, Finality::Partial) => GPoll::Partial(value),
}
}
pub fn merge<T>(self, poll: GPoll<T>) -> GPoll<T> {
match poll {
GPoll::Final(value) => self.finish(value),
GPoll::Partial(value) => match self.finish(value) {
GPoll::Final(value) => GPoll::Partial(value),
other => other,
},
GPoll::Fallback(boxed) => {
let (value, error) = *boxed;
let first = self.error.take().unwrap_or(error);
GPoll::Fallback(Box::new((value, first)))
}
interrupted => interrupted,
}
}
}
#[derive(Clone, Copy)]
pub struct LazyInput<'a, N> {
node: &'a N,
cell: &'a StatusCell,
input_index: usize,
}
impl<'a, N> LazyInput<'a, N> {
pub fn new(node: &'a N, cell: &'a StatusCell, input_index: usize) -> Self {
Self { node, cell, input_index }
}
pub fn eval<Input>(&self, ctx: &Input) -> Result<N::Output, Interrupt>
where
N: GNode<Input>,
{
self.cell.eval_input(self.input_index, self.node, ctx)
}
}
impl<'a, Input, N> GNode<Input> for LazyInput<'a, N>
where
N: GNode<Input>,
{
type Output = N::Output;
fn eval(&self, input: &Input) -> GPoll<Self::Output> {
self.node.eval(input)
}
fn extent(&self, input: &Input) -> GPoll<Extent> {
self.node.extent(input)
}
fn eval_batch<'b>(&self, input: &'b Input, range: Range<u64>, scratch: Option<&'b mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'b, Self::Output>
where
Input: InjectIndex + Copy,
{
self.node.eval_batch(input, range, scratch)
}
}
#[cfg(test)]
mod tests {
use super::*;

View File

@@ -23,6 +23,11 @@ impl GraphError {
trace: Vec::new(),
}
}
pub fn traced(mut self, input_index: usize) -> Self {
self.trace.push(input_index);
self
}
}
#[derive(Clone, Debug, PartialEq)]

View File

@@ -18,6 +18,7 @@ pub mod render_complexity;
pub mod transform;
pub mod uuid;
pub mod value;
pub mod wire;
pub use crate as core_types;
pub use blending::*;

View File

@@ -44,13 +44,13 @@ impl<'i, N: for<'a> Node<'a, I> + Copy, I: 'i> Copy for TypeNode<N, I, <N as Nod
pub trait Convert<T, C>: Sized {
/// Converts this type into the (usually inferred) output type.
#[must_use]
fn convert(self, footprint: Footprint, converter: C) -> impl Future<Output = T> + Send;
fn convert(self, footprint: Footprint, converter: C) -> T;
}
impl<T: ToString + Send> Convert<String, ()> for T {
/// Converts this type into a `String` using its `ToString` implementation.
#[inline]
async fn convert(self, _: Footprint, _converter: ()) -> String {
fn convert(self, _: Footprint, _converter: ()) -> String {
self.to_string()
}
}
@@ -60,7 +60,7 @@ pub trait ListConvert<U> {
}
impl<U, T: ListConvert<U> + Send> Convert<List<U>, ()> for List<T> {
async fn convert(self, _: Footprint, _: ()) -> List<U> {
fn convert(self, _: Footprint, _: ()) -> List<U> {
let list: List<U> = self
.into_iter()
.map(|row| {
@@ -76,7 +76,7 @@ impl<U, T: ListConvert<U> + Send> Convert<List<U>, ()> for List<T> {
/// from any `List<U>` express their signature as `AttributeDyn` and avoid monomorphizing
/// over `U`; the compiler inserts this convert to bridge concrete-typed graph wires to the dyn input.
impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static> Convert<AttributeDyn, ()> for List<T> {
async fn convert(self, _: Footprint, _: ()) -> AttributeDyn {
fn convert(self, _: Footprint, _: ()) -> AttributeDyn {
let values: Vec<T> = self.into_iter().map(|row| row.into_element()).collect();
AttributeDyn(Box::new(Attribute(values)))
}
@@ -86,7 +86,7 @@ impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash
/// (such as `write_attribute`'s value-producing input) be generic over the destination list type
/// alone, with the compiler-inserted convert handling each concrete value type at the wire level.
impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static> Convert<AttributeValueDyn, ()> for T {
async fn convert(self, _: Footprint, _: ()) -> AttributeValueDyn {
fn convert(self, _: Footprint, _: ()) -> AttributeValueDyn {
AttributeValueDyn(Box::new(self))
}
}
@@ -95,13 +95,13 @@ impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash
/// only need attribute access (such as the `read_attribute_*` family) take a single `ListDyn` input
/// instead of monomorphizing over every possible carrier list type.
impl<T: Send> Convert<ListDyn, ()> for List<T> {
async fn convert(self, _: Footprint, _: ()) -> ListDyn {
fn convert(self, _: Footprint, _: ()) -> ListDyn {
self.into()
}
}
impl Convert<DVec2, ()> for DVec2 {
async fn convert(self, _: Footprint, _: ()) -> DVec2 {
fn convert(self, _: Footprint, _: ()) -> DVec2 {
self
}
}
@@ -115,7 +115,7 @@ pub trait FromAnchorPosition {
// Converts a position into a vector path composed of a single anchor point
impl<T: FromAnchorPosition + Send> Convert<List<T>, ()> for DVec2 {
async fn convert(self, _: Footprint, _: ()) -> List<T> {
fn convert(self, _: Footprint, _: ()) -> List<T> {
List::new_from_item(Item::new_from_element(T::from_anchor_position(self)))
}
}
@@ -124,7 +124,7 @@ impl<T: FromAnchorPosition + Send> Convert<List<T>, ()> for DVec2 {
macro_rules! impl_convert {
($from:ty, $to:ty) => {
impl Convert<$to, ()> for $from {
async fn convert(self, _: Footprint, _: ()) -> $to {
fn convert(self, _: Footprint, _: ()) -> $to {
self as $to
}
}
@@ -146,7 +146,7 @@ macro_rules! impl_convert {
impl_convert!(usize, $to);
impl Convert<DVec2, ()> for $to {
async fn convert(self, _: Footprint, _: ()) -> DVec2 {
fn convert(self, _: Footprint, _: ()) -> DVec2 {
DVec2::splat(self as f64)
}
}

View File

@@ -0,0 +1,560 @@
use crate::Type;
use crate::arena::{Arena, ArenaCell};
use crate::concrete;
use crate::context::{ContextImpl, Ctx, ExtractArena};
use crate::frame_table::{FrameTable, Lookup};
use crate::gnode::GNode;
use crate::gpoll::{Extent, Finality, GPoll};
use graphene_hash::CacheHash;
use std::any::Any;
use std::hash::Hasher;
use std::sync::Mutex;
pub type ErasedGNode<T> = dyn for<'c> GNode<ContextImpl<'c>, Output = T>;
pub type ErasedLendGNode<T> = dyn for<'c> GNode<ContextImpl<'c>, Output = &'c T>;
pub fn cache_key<C: CacheHash + ?Sized>(ctx: &C) -> u64 {
let mut hasher = std::hash::DefaultHasher::new();
ctx.cache_hash(&mut hasher);
hasher.finish()
}
#[derive(Debug, PartialEq)]
pub enum WireError {
Arity { expected: usize, got: usize },
Type { expected: Type, found: Type },
MissingCapability { ty: Type },
}
#[derive(Clone, Copy, Default)]
pub struct WireCapabilities {
pub memoize: Option<fn(EdgeHandle) -> Result<EdgeHandle, WireError>>,
pub lend: Option<fn(EdgeHandle) -> Result<EdgeHandle, WireError>>,
}
fn memoize_edge<T: Clone + 'static>(edge: EdgeHandle) -> Result<EdgeHandle, WireError> {
let content = edge.downcast::<T>()?;
Ok(EdgeHandle::new(Box::new(MemoizeNode::new(content)) as Box<ErasedGNode<T>>))
}
fn lend_edge<T: Clone + 'static>(edge: EdgeHandle) -> Result<EdgeHandle, WireError> {
let content = edge.downcast::<T>()?;
Ok(EdgeHandle::new_ref(Box::new(FrameMemoNode::new(content)) as Box<ErasedLendGNode<T>>))
}
pub struct EdgeHandle {
node: Box<dyn Any>,
ty: Type,
capabilities: WireCapabilities,
}
impl std::fmt::Debug for EdgeHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EdgeHandle").field("ty", &self.ty).finish_non_exhaustive()
}
}
impl EdgeHandle {
pub fn new<T: Clone + 'static>(node: Box<ErasedGNode<T>>) -> Self {
Self::new_erased(
node,
concrete!(T),
WireCapabilities {
memoize: Some(memoize_edge::<T>),
lend: Some(lend_edge::<T>),
},
)
}
pub fn new_ref<T: 'static>(node: Box<ErasedLendGNode<T>>) -> Self {
Self::new_erased(node, Type::Ref(Box::new(concrete!(T))), WireCapabilities::default())
}
pub fn new_erased<N: ?Sized>(node: Box<N>, ty: Type, capabilities: WireCapabilities) -> Self
where
Box<N>: Any,
{
Self {
node: Box::new(node),
ty,
capabilities,
}
}
pub fn wire_type(&self) -> &Type {
&self.ty
}
pub fn memoized(self) -> Result<EdgeHandle, WireError> {
match self.capabilities.memoize {
Some(wrap) => wrap(self),
None => Err(WireError::MissingCapability { ty: self.ty }),
}
}
pub fn lent(self) -> Result<EdgeHandle, WireError> {
match self.capabilities.lend {
Some(wrap) => wrap(self),
None => Err(WireError::MissingCapability { ty: self.ty }),
}
}
pub fn downcast<T: 'static>(self) -> Result<Box<ErasedGNode<T>>, WireError> {
self.downcast_erased(concrete!(T))
}
pub fn downcast_lend<T: 'static>(self) -> Result<Box<ErasedLendGNode<T>>, WireError> {
self.downcast_erased(Type::Ref(Box::new(concrete!(T))))
}
pub fn downcast_erased<N: ?Sized>(self, expected: Type) -> Result<Box<N>, WireError>
where
Box<N>: Any,
{
let found = self.ty;
self.node.downcast::<Box<N>>().map(|node| *node).map_err(|_| WireError::Type { expected, found })
}
}
pub struct NodeIoRecord {
pub inputs: Vec<Type>,
pub output: Type,
}
pub struct RegistryEntry {
pub io: NodeIoRecord,
pub wire: fn(Vec<EdgeHandle>) -> Result<EdgeHandle, WireError>,
}
pub fn resolve_and_wire(entry: &RegistryEntry, inputs: Vec<EdgeHandle>) -> Result<EdgeHandle, WireError> {
if inputs.len() != entry.io.inputs.len() {
return Err(WireError::Arity {
expected: entry.io.inputs.len(),
got: inputs.len(),
});
}
for (handle, expected) in inputs.iter().zip(&entry.io.inputs) {
if handle.wire_type() != expected {
return Err(WireError::Type {
expected: expected.clone(),
found: handle.wire_type().clone(),
});
}
}
(entry.wire)(inputs)
}
pub struct MemoizeNode<T, NodeContent> {
cache: Mutex<Option<(u64, T, Finality)>>,
content: NodeContent,
}
impl<T, NodeContent> MemoizeNode<T, NodeContent> {
pub fn new(content: NodeContent) -> Self {
Self {
cache: Mutex::new(None),
content,
}
}
}
impl<T, Input, NodeContent> GNode<Input> for MemoizeNode<T, NodeContent>
where
T: Clone,
Input: Ctx + CacheHash,
NodeContent: GNode<Input, Output = T>,
{
type Output = T;
fn eval(&self, input: &Input) -> GPoll<T> {
let key = cache_key(input);
if let Some((hash, value, finality)) = self.cache.lock().unwrap().as_ref() {
if *hash == key {
return match finality {
Finality::AllFinal => GPoll::Final(value.clone()),
Finality::Partial => GPoll::Partial(value.clone()),
};
}
}
let result = self.content.eval(input);
match &result {
GPoll::Final(value) => *self.cache.lock().unwrap() = Some((key, value.clone(), Finality::AllFinal)),
GPoll::Partial(value) => *self.cache.lock().unwrap() = Some((key, value.clone(), Finality::Partial)),
GPoll::Pending | GPoll::Fallback(_) | GPoll::Error(_) => {}
}
result
}
fn extent(&self, input: &Input) -> GPoll<Extent> {
self.content.extent(input)
}
}
pub struct FrameMemoNode<T, NodeContent> {
cell: ArenaCell<FrameTable<T, 32>>,
content: NodeContent,
}
impl<T, NodeContent> FrameMemoNode<T, NodeContent> {
pub fn new(content: NodeContent) -> Self {
Self {
cell: ArenaCell::new(),
content,
}
}
}
impl<'e, T, Input, NodeContent> GNode<Input> for FrameMemoNode<T, NodeContent>
where
T: Clone + 'static,
Input: Ctx + CacheHash + ExtractArena<ArenaRef = &'e Arena>,
NodeContent: GNode<Input, Output = T>,
{
type Output = &'e T;
fn eval(&self, input: &Input) -> GPoll<&'e T> {
let arena = input.arena();
let table = match self.cell.load(arena) {
Some(table) => table,
None => match arena.alloc(FrameTable::new()) {
Some((table, weak)) => {
self.cell.store(weak);
table
}
None => return park(arena, self.content.eval(input)),
},
};
match table.lookup(cache_key(input)) {
Lookup::Hit(Finality::AllFinal, value) => GPoll::Final(value),
Lookup::Hit(Finality::Partial, value) => GPoll::Partial(value),
Lookup::Vacant(slot) => match self.content.eval(input) {
GPoll::Final(value) => GPoll::Final(slot.publish(value, Finality::AllFinal)),
GPoll::Partial(value) => GPoll::Partial(slot.publish(value, Finality::Partial)),
unpublishable => {
slot.release();
park(arena, unpublishable)
}
},
Lookup::Full => park(arena, self.content.eval(input)),
}
}
fn extent(&self, input: &Input) -> GPoll<Extent> {
self.content.extent(input)
}
}
pub fn park<'e, T>(arena: &'e Arena, result: GPoll<T>) -> GPoll<&'e T> {
match result {
GPoll::Final(value) => match arena.alloc(value) {
Some((parked, _)) => GPoll::Final(parked),
None => GPoll::arena_exhausted(),
},
GPoll::Partial(value) => match arena.alloc(value) {
Some((parked, _)) => GPoll::Partial(parked),
None => GPoll::arena_exhausted(),
},
GPoll::Fallback(boxed) => {
let (value, error) = *boxed;
match arena.alloc(value) {
Some((parked, _)) => GPoll::Fallback(Box::new((parked, error))),
None => GPoll::arena_exhausted(),
}
}
GPoll::Pending => GPoll::Pending,
GPoll::Error(error) => GPoll::Error(error),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::context::EvalScope;
use crate::SourceId;
use std::sync::atomic::{AtomicU32, Ordering};
struct CountingNode(AtomicU32);
impl<Input> GNode<Input> for CountingNode {
type Output = u32;
fn eval(&self, _input: &Input) -> GPoll<u32> {
GPoll::Final(self.0.fetch_add(1, Ordering::Relaxed) + 1)
}
}
struct ValueNode<T>(T);
impl<T: Clone, Input> GNode<Input> for ValueNode<T> {
type Output = T;
fn eval(&self, _input: &Input) -> GPoll<T> {
GPoll::Final(self.0.clone())
}
}
fn scope_fixture<'a>(generations: &'a [(SourceId, u64)], arena: &'a Arena) -> EvalScope<'a> {
EvalScope::new(Some(0.5), None, None, generations, arena)
}
#[test]
fn memo_capability_wraps_edges_type_blind() {
let arena = Arena::new(1024);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let edge = EdgeHandle::new(Box::new(CountingNode(AtomicU32::new(0))) as Box<ErasedGNode<u32>>);
let memoized = edge.memoized().unwrap().downcast::<u32>().unwrap();
assert_eq!(memoized.eval(&ctx), GPoll::Final(1));
assert_eq!(memoized.eval(&ctx), GPoll::Final(1));
}
#[test]
fn memo_invalidates_on_generation_bump() {
let arena = Arena::new(1024);
let source: SourceId = 7;
let before = [(source, 1)];
let after = [(source, 2)];
let scope_before = scope_fixture(&before, &arena);
let scope_after = scope_fixture(&after, &arena);
let edge = EdgeHandle::new(Box::new(CountingNode(AtomicU32::new(0))) as Box<ErasedGNode<u32>>);
let memoized = edge.memoized().unwrap().downcast::<u32>().unwrap();
assert_eq!(memoized.eval(&ContextImpl::root(&scope_before)), GPoll::Final(1));
assert_eq!(memoized.eval(&ContextImpl::root(&scope_before)), GPoll::Final(1));
assert_eq!(memoized.eval(&ContextImpl::root(&scope_after)), GPoll::Final(2));
}
#[test]
fn memoized_edges_stack_and_rewire() {
let arena = Arena::new(1024);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let edge = EdgeHandle::new(Box::new(CountingNode(AtomicU32::new(0))) as Box<ErasedGNode<u32>>);
let stacked = edge.memoized().unwrap().memoized().unwrap().downcast::<u32>().unwrap();
assert_eq!(stacked.eval(&ctx), GPoll::Final(1));
assert_eq!(stacked.eval(&ctx), GPoll::Final(1));
}
#[test]
fn lend_capability_turns_an_owned_edge_into_a_lending_edge() {
let arena = Arena::new(4096);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let edge = EdgeHandle::new(Box::new(ValueNode("lent out".to_string())) as Box<ErasedGNode<String>>);
let lending = edge.lent().unwrap();
assert_eq!(*lending.wire_type(), Type::Ref(Box::new(concrete!(String))));
let node = lending.downcast_lend::<String>().unwrap();
let GPoll::Final(first) = node.eval(&ctx) else {
panic!("lend must fill the frame table and lend");
};
let GPoll::Final(second) = node.eval(&ctx) else {
panic!("second eval must lend the published value");
};
assert_eq!(first, "lent out");
assert!(std::ptr::eq(first, second));
}
#[test]
fn ref_edges_report_missing_capabilities() {
let edge = EdgeHandle::new(Box::new(ValueNode(5u32)) as Box<ErasedGNode<u32>>);
let lending = edge.lent().unwrap();
match lending.memoized() {
Err(WireError::MissingCapability { ty }) => assert_eq!(ty, Type::Ref(Box::new(concrete!(u32)))),
other => panic!("expected missing capability, got {:?}", other.map(|handle| handle.ty)),
}
}
#[test]
fn borrow_carrying_value_types_wire_through_the_general_constructor() {
struct SplitBorrow<'c>(&'c str, usize);
struct SplitNode<Node0> {
content: Node0,
}
impl<'e, Input, Node0> GNode<Input> for SplitNode<Node0>
where
Input: Ctx,
Node0: GNode<Input, Output = &'e String>,
{
type Output = SplitBorrow<'e>;
fn eval(&self, input: &Input) -> GPoll<SplitBorrow<'e>> {
self.content.eval(input).map(|value| SplitBorrow(value, value.len()))
}
}
type ErasedSplitEdge = dyn for<'c> GNode<ContextImpl<'c>, Output = SplitBorrow<'c>>;
let arena = Arena::new(4096);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let lending = EdgeHandle::new(Box::new(ValueNode("held".to_string())) as Box<ErasedGNode<String>>).lent().unwrap();
let upstream = lending.downcast_lend::<String>().unwrap();
let node: Box<ErasedSplitEdge> = Box::new(SplitNode { content: upstream });
let handle = EdgeHandle::new_erased(node, concrete!(SplitBorrow<'static>), WireCapabilities::default());
assert_eq!(*handle.wire_type(), concrete!(SplitBorrow<'static>));
let wired = handle.downcast_erased::<ErasedSplitEdge>(concrete!(SplitBorrow<'static>)).unwrap();
let GPoll::Final(split) = wired.eval(&ctx) else {
panic!("borrow-carrying output must eval through the erased edge");
};
assert_eq!(split.0, "held");
assert_eq!(split.1, 4);
}
#[test]
fn derive_ctx_repeat_pushes_index_levels_through_the_erased_edge() {
use crate::context::{Derived, DeriveCtx, ExtractIndex};
struct RepeatNode<Node0> {
content: Node0,
}
impl<C, T, Node0> GNode<C> for RepeatNode<Node0>
where
C: Ctx + DeriveCtx,
Node0: for<'x> GNode<Derived<'x, C>, Output = T>,
{
type Output = Vec<T>;
fn eval(&self, input: &C) -> GPoll<Vec<T>> {
let spilled = input.index_head();
let mut result = Vec::new();
for index in 0..3 {
let derived = input.promoted(&spilled, index);
match self.content.eval(&derived) {
GPoll::Final(value) => result.push(value),
other => return other.map(|_| Vec::new()),
}
}
GPoll::Final(result)
}
}
struct LevelsNode;
impl<Input: ExtractIndex> GNode<Input> for LevelsNode {
type Output = Vec<usize>;
fn eval(&self, input: &Input) -> GPoll<Vec<usize>> {
GPoll::Final(input.try_index().map(|levels| levels.collect()).unwrap_or_default())
}
}
let arena = Arena::new(1024);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let nested = RepeatNode {
content: RepeatNode { content: LevelsNode },
};
let erased: Box<ErasedGNode<Vec<Vec<Vec<usize>>>>> = Box::new(nested);
let GPoll::Final(outer) = erased.eval(&ctx) else {
panic!("nested repeat must evaluate");
};
assert_eq!(outer.len(), 3);
assert_eq!(outer[2][1], vec![1, 2, 0]);
assert_eq!(outer[0][0], vec![0, 0, 0]);
}
#[test]
fn derive_ctx_footprint_replace_reaches_the_content() {
use crate::context::{Derived, DeriveCtx, ExtractFootprint};
use crate::transform::Footprint;
struct ShiftFootprintNode<Node0> {
content: Node0,
}
impl<C, T, Node0> GNode<C> for ShiftFootprintNode<Node0>
where
C: Ctx + DeriveCtx + ExtractFootprint,
Node0: for<'x> GNode<Derived<'x, C>, Output = T>,
{
type Output = T;
fn eval(&self, input: &C) -> GPoll<T> {
let mut footprint = input.try_footprint().copied().unwrap_or(Footprint::DEFAULT);
footprint.resolution.x += 7;
let derived = input.with_footprint(&footprint);
self.content.eval(&derived)
}
}
struct ResolutionNode;
impl<Input: ExtractFootprint> GNode<Input> for ResolutionNode {
type Output = u32;
fn eval(&self, input: &Input) -> GPoll<u32> {
GPoll::Final(input.try_footprint().map(|footprint| footprint.resolution.x).unwrap_or(0))
}
}
let arena = Arena::new(1024);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let graph: Box<ErasedGNode<u32>> = Box::new(ShiftFootprintNode {
content: ShiftFootprintNode { content: ResolutionNode },
});
assert_eq!(graph.eval(&ctx), GPoll::Final(Footprint::DEFAULT.resolution.x + 14));
}
#[test]
fn resolve_and_wire_checks_arity_and_types() {
fn wire_strlen(args: Vec<EdgeHandle>) -> Result<EdgeHandle, WireError> {
let mut args = args.into_iter();
let value = args.next().ok_or(WireError::Arity { expected: 1, got: 0 })?.downcast::<String>()?;
drop(value);
Ok(EdgeHandle::new(Box::new(ValueNode(0u32)) as Box<ErasedGNode<u32>>))
}
let entry = RegistryEntry {
io: NodeIoRecord {
inputs: vec![concrete!(String)],
output: concrete!(u32),
},
wire: wire_strlen,
};
let owned = EdgeHandle::new(Box::new(ValueNode("typed".to_string())) as Box<ErasedGNode<String>>);
assert!(resolve_and_wire(&entry, vec![owned]).is_ok());
assert_eq!(resolve_and_wire(&entry, vec![]).unwrap_err(), WireError::Arity { expected: 1, got: 0 });
let mistyped = EdgeHandle::new(Box::new(ValueNode(1.0f64)) as Box<ErasedGNode<f64>>);
assert_eq!(
resolve_and_wire(&entry, vec![mistyped]).unwrap_err(),
WireError::Type {
expected: concrete!(String),
found: concrete!(f64),
}
);
let lent = EdgeHandle::new(Box::new(ValueNode("typed".to_string())) as Box<ErasedGNode<String>>).lent().unwrap();
assert_eq!(
resolve_and_wire(&entry, vec![lent]).unwrap_err(),
WireError::Type {
expected: concrete!(String),
found: Type::Ref(Box::new(concrete!(String))),
}
);
}
}