diff --git a/libraries/dyn-any/derive/src/lib.rs b/libraries/dyn-any/derive/src/lib.rs index 59c76c73cf..edd7cd5cf6 100644 --- a/libraries/dyn-any/derive/src/lib.rs +++ b/libraries/dyn-any/derive/src/lib.rs @@ -4,6 +4,7 @@ extern crate proc_macro; use proc_macro::TokenStream; use proc_macro2::Span; +use proc_macro2::TokenStream as TokenStream2; use quote::quote; use syn::{DeriveInput, GenericParam, Lifetime, TypeParamBound, parse_macro_input}; @@ -40,25 +41,110 @@ pub fn system_desc_derive(input: TokenStream) -> TokenStream { let struct_name = &ast.ident; let generics = &ast.generics; - let static_params = generic_arguments(generics, "'static"); - let dyn_params = generic_arguments(generics, "'dyn_any"); + // A container's type parameter maps through its own projection, so `List>` + // erases and relifts its contents. A value type whose parameter carries trait bounds + // cannot: the projected type need not satisfy them, so it passes through instead, and + // the `'static` bound keeps it borrow-free. `#[dyn_any_derive(project)]` picks the first. + let projects = ast + .attrs + .iter() + .any(|attr| attr.path().is_ident("dyn_any_derive") && attr.parse_args::().is_ok_and(|arg| arg == "project")); + + let dyn_params = generic_arguments(generics, "'dyn_any"); + let static_params = match projects { + true => projected_arguments(generics, "'static", |ident| quote! { <#ident as dyn_any::StaticTypeSized>::Static }), + false => projected_arguments(generics, "'static", |ident| quote! { #ident }), + }; + let live_params = match projects { + true => projected_arguments(generics, "'dyn_any_live", |ident| quote! { <#ident as dyn_any::Relift>::Live<'dyn_any_live> }), + false => projected_arguments(generics, "'dyn_any_live", |ident| quote! { #ident }), + }; + let self_params = projected_arguments(generics, "'static", |ident| quote! { #ident }); + + // The declared bounds come along, since the impl restates the struct's own parameters. + let bounded = |bound: TypeParamBound| -> Vec { + generics + .params + .iter() + .filter_map(|param| match param { + GenericParam::Type(t) => { + let mut t = t.clone(); + t.bounds.push(bound.clone()); + Some(quote! { #t }) + } + GenericParam::Const(c) => Some(quote! { #c }), + GenericParam::Lifetime(_) => None, + }) + .collect() + }; + let static_bound: TypeParamBound = match projects { + true => syn::parse_quote!(dyn_any::StaticTypeSized), + false => TypeParamBound::Lifetime(Lifetime::new("'static", Span::call_site())), + }; + let relift_bound: TypeParamBound = match projects { + true => syn::parse_quote!(dyn_any::Relift), + false => TypeParamBound::Lifetime(Lifetime::new("'static", Span::call_site())), + }; + let static_bounds = bounded(static_bound); + let relift_bounds = bounded(relift_bound); + + // A projected parameter must still satisfy what the struct declared of it, which only + // the author can promise: `Image` needs `P::Static: Pixel` to name its own + // static form. The relift side quantifies over the lifetime the associated type takes. + let declared_bounds = |project: &dyn Fn(&syn::Ident) -> TokenStream2| -> Vec { + generics + .params + .iter() + .filter_map(|param| match param { + GenericParam::Type(t) if projects && !t.bounds.is_empty() => { + let projected = project(&t.ident); + let bounds = &t.bounds; + Some(quote! { #projected: #bounds }) + } + _ => None, + }) + .collect() + }; + let static_where = declared_bounds(&|ident| quote! { <#ident as dyn_any::StaticTypeSized>::Static }); + let relift_where = declared_bounds(&|ident| quote! { <#ident as dyn_any::Relift>::Live<'dyn_any_live> }); + let relift_where = (!relift_where.is_empty()).then(|| quote! { where for<'dyn_any_live> #(#relift_where),* }); - let impl_params = generics.params.iter().map(|param| match param { - GenericParam::Type(t) => { - let mut t = t.clone(); - t.bounds.push(TypeParamBound::Lifetime(Lifetime::new("'static", Span::call_site()))); - quote! {#t} - } - param => quote! {#param}, - }); quote! { - unsafe impl<'dyn_any, #(#impl_params,)*> dyn_any::StaticType for #struct_name <#(#dyn_params,)*> { + unsafe impl<'dyn_any, #(#static_bounds,)*> dyn_any::StaticType for #struct_name <#(#dyn_params,)*> + where #(#static_where,)* + { type Static = #struct_name <#(#static_params,)*>; } + + unsafe impl<#(#relift_bounds,)*> dyn_any::Relift for #struct_name <#(#self_params,)*> + #relift_where + { + type Live<'dyn_any_live> = #struct_name <#(#live_params,)*>; + } } .into() } +/// The struct's generic arguments with lifetimes replaced and type parameters put +/// through `project`, so a container's argument can be mapped rather than passed on. +fn projected_arguments(generics: &syn::Generics, replacement: &str, project: impl Fn(&syn::Ident) -> TokenStream2) -> Vec { + generics + .params + .iter() + .map(|param| match param { + GenericParam::Lifetime(_) => { + let lifetime = Lifetime::new(replacement, Span::call_site()); + quote! {#lifetime} + } + GenericParam::Type(t) => project(&t.ident), + GenericParam::Const(c) => { + let ident = &c.ident; + quote! {#ident} + } + }) + .collect() +} + /// The struct's generic parameters as argument tokens: bare idents for type /// and const parameters (bounds are illegal in argument position), the /// replacement for lifetimes. diff --git a/libraries/dyn-any/src/lib.rs b/libraries/dyn-any/src/lib.rs index 047557a4b4..74ecf40e38 100644 --- a/libraries/dyn-any/src/lib.rs +++ b/libraries/dyn-any/src/lib.rs @@ -142,6 +142,18 @@ where { type Static = ::Static; } +/// The inverse of [`StaticType`]: the `'static` spelling of a type re-stated at a +/// live lifetime. Where `StaticType` erases borrows so a value can be keyed and +/// stored, `Relift` names the borrowing form again so code holding the borrow can +/// be typed. A type without lifetimes relifts to itself. +/// +/// # Safety +/// `Live<'a>` must be `Self` with every lifetime replaced by `'a`, so the two +/// spellings differ in nothing but the borrows they claim. +pub unsafe trait Relift { + type Live<'a>; +} + pub unsafe trait StaticTypeClone { type Static: 'static + Clone; fn type_id(&self) -> core::any::TypeId { diff --git a/node-graph/libraries/application-io/src/lib.rs b/node-graph/libraries/application-io/src/lib.rs index 80a2012b17..567431fcf1 100644 --- a/node-graph/libraries/application-io/src/lib.rs +++ b/node-graph/libraries/application-io/src/lib.rs @@ -1,5 +1,5 @@ use core_types::transform::Footprint; -use dyn_any::{DynAny, StaticType, StaticTypeSized}; +use dyn_any::DynAny; use glam::DVec2; use std::fmt::Debug; use std::hash::{Hash, Hasher}; @@ -106,6 +106,8 @@ impl GetEditorPreferences for DummyPreferences { } } +#[derive(dyn_any::DynAny)] +#[dyn_any_derive(project)] pub struct EditorApi { /// Gives access to APIs like resources. pub application_io: Option>, @@ -155,7 +157,3 @@ impl Debug for EditorApi { f.debug_struct("EditorApi").finish() } } - -unsafe impl StaticType for EditorApi { - type Static = EditorApi; -} diff --git a/node-graph/libraries/core-types/src/list.rs b/node-graph/libraries/core-types/src/list.rs index 3018627955..6ab21ecc0b 100644 --- a/node-graph/libraries/core-types/src/list.rs +++ b/node-graph/libraries/core-types/src/list.rs @@ -1,7 +1,7 @@ use crate::attribute::Attribute as _; use crate::bounds::{BoundingBox, RenderBoundingBox}; use crate::transform::ApplyTransform; -use dyn_any::{StaticType, StaticTypeSized}; +use dyn_any::StaticType; use glam::DAffine2; use graphene_hash::CacheHash; use std::fmt::Debug; @@ -879,7 +879,10 @@ impl Attributes { /// Elements are stored contiguously in a `Vec`, while attributes live in an internal /// [`Attributes`] store that keeps one attribute per attribute key. Items are accessed by /// index through element/attribute accessor methods, or consumed as owned [`Item`]s via iteration. -#[derive(Clone, Debug)] +// The list carries its lifetime only through T, so its parameter projects: substituting +// T's static form substitutes the list's and keeps the layout identical. +#[derive(Clone, Debug, dyn_any::DynAny)] +#[dyn_any_derive(project)] pub struct List { element: Vec, attributes: Attributes, @@ -1192,12 +1195,6 @@ impl ApplyTransform for List { } } -// 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 StaticType for List { - type Static = List; -} - impl FromIterator> for List { /// Collects an iterator of [`Item`]s into a [`List`], pre-allocating based on the iterator's size hint. fn from_iter>>(iter: I) -> Self { @@ -1220,7 +1217,9 @@ impl FromIterator> for List { /// An owned item containing an element of type `T` and a set of type-erased scalar attributes. /// /// Used to build individual items before pushing them into a [`List`], or when consuming items out of a list via [`IntoIterator`]. -#[derive(Clone, Debug)] +// As for `List`, the item's lifetime rides its element alone, so the parameter projects. +#[derive(Clone, Debug, dyn_any::DynAny)] +#[dyn_any_derive(project)] pub struct Item { element: T, attributes: ItemAttributeValues, diff --git a/node-graph/libraries/graphic-types/src/graphic/mod.rs b/node-graph/libraries/graphic-types/src/graphic/mod.rs index 62ae5e3db4..f05631539e 100644 --- a/node-graph/libraries/graphic-types/src/graphic/mod.rs +++ b/node-graph/libraries/graphic-types/src/graphic/mod.rs @@ -695,3 +695,39 @@ mod test_support { List::new_from_element(Graphic::Group(core_types::record::Group { row: None, content: builder.finish() })) } } + +#[cfg(test)] +mod relift_tests { + use super::Graphic; + use core_types::arena::Arena; + use core_types::record::{Group, RunBuilder, element_write_hashed}; + use dyn_any::Relift; + use vector_types::Vector; + + /// `Relift` inverts the erasure a registry row keys on, so an element's `'static` + /// spelling names the borrowing form that live code needs. + #[test] + fn a_graphic_relifts_to_the_arena_lifetime() { + fn resident<'a>(arena: &'a Arena) -> as Relift>::Live<'a> { + let mut builder = RunBuilder::new(arena, element_write_hashed::(), &[], 1).unwrap(); + builder.push(Vector::default()).unwrap(); + + Graphic::Group(Group { row: None, content: builder.finish() }) + } + + let arena = Arena::new(1 << 16).unwrap(); + let live: Graphic<'_> = resident(&arena); + + assert!(matches!(live, Graphic::Group(_)), "the relifted spelling is the same type, only its borrows differ"); + } + + /// A borrow-free element relifts to itself, so code over it never spells a lifetime. + #[test] + fn a_borrow_free_element_relifts_to_itself() { + fn same<'a>(vector: Vector) -> ::Live<'a> { + vector + } + + assert_eq!(same(Vector::default()), Vector::default()); + } +} diff --git a/node-graph/libraries/raster-types/src/image.rs b/node-graph/libraries/raster-types/src/image.rs index 16d4d5955a..767e608bd3 100644 --- a/node-graph/libraries/raster-types/src/image.rs +++ b/node-graph/libraries/raster-types/src/image.rs @@ -3,7 +3,6 @@ use core_types::Color; use core_types::color::float_to_srgb_u8; // use crate::vector::Vector; // TODO: Check if Vector is actually used, if so handle differently use core_types::color::*; -use dyn_any::StaticType; use glam::{DAffine2, DVec2}; use std::vec::Vec; @@ -49,7 +48,8 @@ mod base64_serde { } #[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[derive(Clone, Eq, Default)] +#[derive(Clone, Eq, Default, dyn_any::DynAny)] +#[dyn_any_derive(project)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Image { pub width: u32, @@ -92,14 +92,6 @@ impl std::fmt::Debug for Image

{ } } -unsafe impl

StaticType for Image

-where - P: dyn_any::StaticTypeSized + Pixel, - P::Static: Pixel, -{ - type Static = Image; -} - impl Bitmap for Image

{ type Pixel = P; #[inline(always)] diff --git a/node-graph/libraries/vector-types/src/vector/vector_types.rs b/node-graph/libraries/vector-types/src/vector/vector_types.rs index 38809ae5f5..fae04411fe 100644 --- a/node-graph/libraries/vector-types/src/vector/vector_types.rs +++ b/node-graph/libraries/vector-types/src/vector/vector_types.rs @@ -9,13 +9,12 @@ use core::borrow::Borrow; use core_types::bounds::{BoundingBox, RenderBoundingBox}; use core_types::render_complexity::RenderComplexity; use core_types::transform::Transform; -use dyn_any::StaticType; use glam::{DAffine2, DVec2}; use kurbo::{Affine, BezPath, Rect, Shape}; use std::collections::HashMap; /// Represents vector graphics data, composed of Bézier curves in a path or mesh arrangement. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, dyn_any::DynAny)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Vector { pub stroke: Option, @@ -28,9 +27,6 @@ pub struct Vector { pub segment_domain: SegmentDomain, pub region_domain: RegionDomain, } -unsafe impl StaticType for Vector { - type Static = Self; -} impl Default for Vector { fn default() -> Self {