mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-09-15 22:28:10 +08:00
Name a type's live spelling beside its static one
This commit is contained in:
@@ -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<Graphic<'e>>`
|
||||
// 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::<syn::Ident>().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<TokenStream2> {
|
||||
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<P: Pixel>` 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<TokenStream2> {
|
||||
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<TokenStream2> {
|
||||
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.
|
||||
|
||||
@@ -142,6 +142,18 @@ where
|
||||
{
|
||||
type Static = <T as StaticType>::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 {
|
||||
|
||||
@@ -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<Io> {
|
||||
/// Gives access to APIs like resources.
|
||||
pub application_io: Option<Arc<Io>>,
|
||||
@@ -155,7 +157,3 @@ impl<T> Debug for EditorApi<T> {
|
||||
f.debug_struct("EditorApi").finish()
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl<T: StaticTypeSized> StaticType for EditorApi<T> {
|
||||
type Static = EditorApi<T::Static>;
|
||||
}
|
||||
|
||||
@@ -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<T>`, 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<T> {
|
||||
element: Vec<T>,
|
||||
attributes: Attributes,
|
||||
@@ -1192,12 +1195,6 @@ 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>;
|
||||
}
|
||||
|
||||
impl<T> FromIterator<Item<T>> for List<T> {
|
||||
/// Collects an iterator of [`Item`]s into a [`List`], pre-allocating based on the iterator's size hint.
|
||||
fn from_iter<I: IntoIterator<Item = Item<T>>>(iter: I) -> Self {
|
||||
@@ -1220,7 +1217,9 @@ impl<T> FromIterator<Item<T>> for List<T> {
|
||||
/// 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<T> {
|
||||
element: T,
|
||||
attributes: ItemAttributeValues,
|
||||
|
||||
@@ -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) -> <Graphic<'static> as Relift>::Live<'a> {
|
||||
let mut builder = RunBuilder::new(arena, element_write_hashed::<Vector>(), &[], 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) -> <Vector as Relift>::Live<'a> {
|
||||
vector
|
||||
}
|
||||
|
||||
assert_eq!(same(Vector::default()), Vector::default());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<P: Pixel> {
|
||||
pub width: u32,
|
||||
@@ -92,14 +92,6 @@ impl<P: Pixel + std::fmt::Debug> std::fmt::Debug for Image<P> {
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl<P> StaticType for Image<P>
|
||||
where
|
||||
P: dyn_any::StaticTypeSized + Pixel,
|
||||
P::Static: Pixel,
|
||||
{
|
||||
type Static = Image<P::Static>;
|
||||
}
|
||||
|
||||
impl<P: Copy + Pixel> Bitmap for Image<P> {
|
||||
type Pixel = P;
|
||||
#[inline(always)]
|
||||
|
||||
@@ -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<Stroke>,
|
||||
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user