Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(schema): support generic bounds in structs & enums #490

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 41 additions & 25 deletions framework_crates/bones_schema/macros/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use proc_macro::TokenStream;
use proc_macro2::{Punct, Spacing, TokenStream as TokenStream2, TokenTree as TokenTree2};
use quote::{format_ident, quote, quote_spanned, spanned::Spanned};
use venial::{GenericBound, StructFields};
use proc_macro2::{Ident, Punct, Spacing, TokenStream as TokenStream2, TokenTree as TokenTree2};
use quote::{format_ident, quote, quote_spanned, spanned::Spanned, TokenStreamExt};
use venial::StructFields;

/// Helper macro to bail out of the macro with a compile error.
macro_rules! throw {
Expand Down Expand Up @@ -282,19 +282,18 @@ pub fn derive_has_schema(input: TokenStream) -> TokenStream {

let register_schema = if input.generic_params().is_some() {
quote! {
static S: OnceLock<RwLock<HashMap<TypeId, &'static Schema>>> = OnceLock::new();
let schema = {
S.get_or_init(Default::default)
#schema_mod::registry::GENERIC_SCHEMA_CACHE
.read()
.get(&TypeId::of::<Self>())
.get(&(TypeId::of::<Self>(), #variant_schema_name))
.copied()
};
schema.unwrap_or_else(|| {
let schema = compute_schema();

S.get_or_init(Default::default)
#schema_mod::registry::GENERIC_SCHEMA_CACHE
.write()
.insert(TypeId::of::<Self>(), schema);
.insert((TypeId::of::<Self>(), #variant_schema_name), schema);

schema
})
Expand Down Expand Up @@ -350,6 +349,14 @@ pub fn derive_has_schema(input: TokenStream) -> TokenStream {
}
})();

if match &input {
venial::Declaration::Struct(s) => s.where_clause.is_some(),
venial::Declaration::Enum(e) => e.where_clause.is_some(),
_ => false,
} {
throw!(input, "Where clauses are not supported.");
}

let schema_register = quote! {
#schema_mod::registry::SCHEMA_REGISTRY.register(#schema_mod::SchemaData {
name: stringify!(#name).into(),
Expand All @@ -366,38 +373,47 @@ pub fn derive_has_schema(input: TokenStream) -> TokenStream {
};

if let Some(generic_params) = input.generic_params() {
let mut sync_send_generic_params = generic_params.clone();
for (param, _) in sync_send_generic_params.params.iter_mut() {
let clone_bound = if !no_clone { quote!(+ Clone) } else { quote!() };
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lmk if I'm missing anything - but I think we may have dropped the #[schema(no_clone] (i.e. no_clone bool) support here, if this attribute is present, we should not be requiring clone. If reading this right - a no_clone type with generic params will now require clone on its generic types, which previously did not - might not compile with the right instantiation. (we may not have any test coverage or usage that would break in code I'm guessing).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Really good catch. Fixed, and added a test that will fail to compile if the code gen is broken again.

param.bound = Some(GenericBound {
tk_colon: Punct::new(':', Spacing::Joint),
tokens: quote!(HasSchema #clone_bound ).into_iter().collect(),
});
let mut impl_bounds = TokenStream2::new();
for (param, comma) in generic_params.params.iter() {
let name = &param.name;
impl_bounds.extend(quote!(#name : HasSchema));
if !no_clone {
impl_bounds.append(Punct::new('+', Spacing::Alone));
impl_bounds.append(Ident::new("Clone", input.__span()));
}
if let Some(bound) = &param.bound {
impl_bounds.append(Punct::new('+', Spacing::Alone));
impl_bounds.extend(bound.tokens.iter().cloned());
}
impl_bounds.append(comma.clone());
}

let struct_params = generic_params
.params
.items()
.map(|param| &param.name)
.map(|name| quote!(#name,))
.collect::<TokenStream2>();

quote! {
unsafe impl #sync_send_generic_params #schema_mod::HasSchema for #name #generic_params {
unsafe impl<#impl_bounds> #schema_mod::HasSchema for #name<#struct_params> {
fn schema() -> &'static #schema_mod::Schema {
use ::std::sync::{OnceLock};
use ::std::any::TypeId;
use bones_utils::HashMap;
use parking_lot::RwLock;
static S: OnceLock<RwLock<HashMap<TypeId, &'static Schema>>> = OnceLock::new();
let schema = {
S.get_or_init(Default::default)
#schema_mod::registry::GENERIC_SCHEMA_CACHE
.read()
.get(&TypeId::of::<Self>())
.get(&(TypeId::of::<Self>(), stringify!(#name)))
.copied()
};
schema.unwrap_or_else(|| {
let schema = #schema_register;

S.get_or_init(Default::default)
#schema_mod::registry::GENERIC_SCHEMA_CACHE
.write()
.insert(TypeId::of::<Self>(), schema);
.insert((TypeId::of::<Self>(), stringify!(name)), schema);

schema
})

}
}
}
Expand Down
22 changes: 22 additions & 0 deletions framework_crates/bones_schema/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ mod test {
Set(T),
}

#[derive(HasSchema, Clone, Default)]
#[schema_module(crate)]
#[repr(C)]
struct WrapperWithDefault<T: Default>(T);

#[derive(HasSchema, Clone, Copy, Debug, PartialEq, Eq, Default)]
#[schema_module(crate)]
#[repr(u8)]
Expand Down Expand Up @@ -163,5 +168,22 @@ mod test {
assert_eq!(A::schema().layout(), B::schema().layout());
assert_eq!(C::schema().layout(), D::schema().layout());
}

#[test]
fn generic_no_clone() {
#[derive(HasSchema, Default)]
#[schema(no_clone)]
#[schema_module(crate)]
#[repr(C)]
struct Meta<T: HasSchema + Default>(T);

#[derive(HasSchema, Default)]
#[schema(no_clone)]
#[schema_module(crate)]
#[repr(C)]
struct NotClonable;

_ = Meta::<NotClonable>::schema();
}
}
}
14 changes: 12 additions & 2 deletions framework_crates/bones_schema/src/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,16 @@

use std::{
alloc::Layout,
sync::atomic::{AtomicU32, Ordering::SeqCst},
any::TypeId,
sync::{
atomic::{AtomicU32, Ordering::SeqCst},
LazyLock,
},
};

use append_only_vec::AppendOnlyVec;
use bones_utils::Deref;
use bones_utils::{Deref, HashMap};
use parking_lot::RwLock;

use crate::prelude::*;

Expand Down Expand Up @@ -143,6 +148,11 @@ pub static SCHEMA_REGISTRY: SchemaRegistry = SchemaRegistry {
schemas: AppendOnlyVec::new(),
};

#[doc(hidden)]
pub static GENERIC_SCHEMA_CACHE: LazyLock<
RwLock<HashMap<(TypeId, &'static str), &'static Schema>>,
> = LazyLock::new(Default::default);

#[cfg(test)]
mod test {
use bones_utils::default;
Expand Down
Loading