1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
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};
/// Helper macro to bail out of the macro with a compile error.
macro_rules! throw {
($hasSpan:expr, $err:literal) => {
let span = $hasSpan.__span();
return quote_spanned!(span =>
compile_error!($err);
).into();
};
}
/// Derive macro for the HasSchema trait.
///
/// ## Usage with #[repr(C)]
/// HasSchema works with the #[repr(C)] annotation to fully implement its features.
///
/// If there is no #[repr(C)] annotation, the SchemaKind of your type's schema will be Opaque.
///
/// This means if you don't know the kind of type, like in the case of a SchemaBox, you'll be unable
/// to read the fields.
///
/// This applies to bones' lua scripting since SchemaBox is effectively the "lua type".
/// See SchemaBox.
///
/// If you intend a type to be opaque even though it has #[repr(C)] you can use #[schema(opaque)]
/// to force an opaque schema representation.
///
/// Keep in mind, enums deriving HasSchema with a #[repr(C)] annotation must also specify an
/// enum tag type like #[repr(C, u8)] where u8 could be either u16 or u32 if you need
/// more than 256 enum variants.
///
/// ## no_default & no_clone attributes
/// HasSchema derive requires the type to implement Default & Clone, if either of these cannot be
/// implemented you can use the no_default & no_clone schema attributes respectively to ignore
/// these requirements.
/// ```ignore
/// #[derive(HasSchema, Default)]
/// #[schema(no_clone)]
/// struct DoesntImplClone;
///
/// #[derive(HasSchema, Clone)]
/// #[schema(no_default)]
/// struct DoesntImplDefault;
/// ```
/// The caveat for putting no_default on your type is that it cannot be created from a Schema.
/// This is necessary if you want to create your type within a bones lua script.
///
/// Since the fields that need to be initialized to create a complete version of your type cannot be
/// determined, Schema needs a default function to initialize the data properly.
///
/// The caveat for putting no_clone on your type is that it cannot be cloned in the form of a
/// SchemaBox.
///
/// This is critical in the case of bones' networking which will panic if your type is in the world
/// and does not implement clone during the network rollback.
///
/// ## type_data attribute
/// This attribute takes an expression and stores that value in what is basically
/// a type keyed map accessible from your type's Schema.
///
/// ## derive_type_data attribute
/// This attribute is simply a shortcut equivalent to using the type_data attribute
/// with any type's `FromType<YourHasSchemaType>` implementation like so:
/// ```ignore
/// #[derive(HasSchema, Clone, Default)]
/// #[type_data(<OtherType as FromType<Data>>::from_type())]
/// struct Data;
/// ```
/// Simply specify a type instead of an expression:
/// ```ignore
/// #[derive(HasSchema, Clone, Default)]
/// #[derive_type_data(OtherType)] // OtherType implements FromType<Data>
/// struct Data;
/// ```
/// ## Known Limitations
///
/// Currently it isn't possible to construct a struct that contains itself. For example, this will
/// not work:
///
/// ```ignore
/// #[derive(HasSchema)]
/// struct Data {
/// others: Vec<Data>,
/// }
/// ```
///
/// If this is a problem for your use-case, please open an issue.
#[proc_macro_derive(
HasSchema,
attributes(schema, derive_type_data, type_data, schema_module)
)]
pub fn derive_has_schema(input: TokenStream) -> TokenStream {
let input = venial::parse_declaration(input.into()).unwrap();
let name = input.name().expect("Type must have a name");
// Get the schema module, reading optionally from the `schema_module` attribute, so that we can
// set the module to `crate` when we want to use it within the `bones_schema` crate itself.
let schema_mod = input
.attributes()
.iter()
.find_map(|attr| {
(attr.path.len() == 1 && attr.path[0].to_string() == "schema_module").then(|| {
attr.value
.get_value_tokens()
.iter()
.cloned()
.collect::<TokenStream2>()
})
})
.unwrap_or_else(|| quote!(bones_schema));
// Get the type datas that have been added and derived
let derive_type_data_flags = get_flags_for_attr(&input, "derive_type_data");
let type_datas = {
let add_derive_type_datas = derive_type_data_flags.into_iter().map(|ty| {
let ty = format_ident!("{ty}");
quote! {
tds.insert(<#ty as #schema_mod::FromType<#name>>::from_type()).unwrap();
}
});
let add_type_datas = input
.attributes()
.iter()
.filter(|x| x.path.len() == 1 && x.path[0].to_string() == "type_data")
.map(|x| x.get_value_tokens())
.map(|x| x.iter().cloned().collect::<TokenStream2>());
quote! {
{
let tds = #schema_mod::alloc::TypeDatas::default();
#(#add_derive_type_datas),*
#(
tds.insert(#add_type_datas).unwrap();
),*
tds
}
}
};
// Collect repr tags
let mut repr_flags = get_flags_for_attr(&input, "repr");
repr_flags.iter_mut().for_each(|x| *x = x.to_lowercase());
let repr_c = repr_flags.iter().any(|x| x == "c");
let primitive_repr = repr_flags.iter().find_map(|x| match x.as_ref() {
"u8" => Some(quote!(U8)),
"u16" => Some(quote!(U16)),
"u32" => Some(quote!(U32)),
_ => None,
});
// Collect schema flags
let schema_flags = get_flags_for_attr(&input, "schema");
let no_clone = schema_flags.iter().any(|x| x.as_str() == "no_clone");
let no_default = schema_flags.iter().any(|x| x.as_str() == "no_default");
let is_opaque = schema_flags.iter().any(|x| x.as_str() == "opaque")
|| !(repr_c || primitive_repr.is_some());
// Get the clone and default functions based on the flags
let clone_fn = if no_clone {
quote!(None)
} else {
quote!(Some(<Self as #schema_mod::raw_fns::RawClone>::raw_clone_cb()))
};
let default_fn = if no_default {
quote!(None)
} else {
quote!(Some(<Self as #schema_mod::raw_fns::RawDefault>::raw_default_cb()))
};
// Get the schema kind
let schema_kind = (|| {
if is_opaque {
return quote! {
{
let layout = ::std::alloc::Layout::new::<Self>();
#schema_mod::SchemaKind::Primitive(#schema_mod::Primitive::Opaque {
size: layout.size(),
align: layout.align(),
})
}
};
}
// Helper to parse struct fields from structs or enum variants
let parse_struct_fields = |fields: &StructFields| {
match fields {
venial::StructFields::Tuple(tuple) => tuple
.fields
.iter()
.map(|(field, _)| {
let ty = &field.ty;
quote_spanned! {field.ty.__span() =>
#schema_mod::StructFieldInfo {
name: None,
schema: <#ty as #schema_mod::HasSchema>::schema(),
}
}
})
.collect::<Vec<_>>(),
venial::StructFields::Named(named) => named
.fields
.iter()
.map(|(field, _)| {
let name = &field.name;
let ty = &field.ty;
let opaque = field.attributes.iter().any(|attr| {
&attr.path[0].to_string() == "schema"
&& &attr.value.get_value_tokens()[0].to_string() == "opaque"
});
if opaque {
quote_spanned! {field.ty.__span() =>
#schema_mod::StructFieldInfo {
name: Some(stringify!(#name).into()),
schema: {
let layout = ::std::alloc::Layout::new::<#ty>();
#schema_mod::registry::SCHEMA_REGISTRY.register(#schema_mod::SchemaData {
name: stringify!(#ty).into(),
full_name: concat!(module_path!(), "::", stringify!(#ty)).into(),
kind: #schema_mod::SchemaKind::Primitive(#schema_mod::Primitive::Opaque {
size: layout.size(),
align: layout.align(),
}),
type_id: Some(std::any::TypeId::of::<#ty>()),
type_data: #type_datas,
clone_fn: #clone_fn,
default_fn: #default_fn,
eq_fn: None,
hash_fn: None,
drop_fn: Some(<Self as #schema_mod::raw_fns::RawDrop>::raw_drop_cb()),
})
},
}
}
} else {
quote_spanned! {field.ty.__span() =>
#schema_mod::StructFieldInfo {
name: Some(stringify!(#name).into()),
schema: <#ty as #schema_mod::HasSchema>::schema(),
}
}
}
})
.collect::<Vec<_>>(),
venial::StructFields::Unit => Vec::new(),
}
};
// Match on the the type we are deriving on and return its SchemaData
match &input {
venial::Declaration::Struct(s) => {
let fields = parse_struct_fields(&s.fields);
quote! {
#schema_mod::SchemaKind::Struct(#schema_mod::StructSchemaInfo {
fields: vec![
#(#fields),*
]
})
}
}
venial::Declaration::Enum(e) => {
let Some(tag_type) = primitive_repr else {
throw!(
e,
"Enums deriving HasSchema with a `#[repr(C)]` annotation \
must also specify an enum tag type like `#[repr(C, u8)]` where \
`u8` could be either `u16` or `u32` if you need more than 256 enum \
variants."
);
};
let mut variants = Vec::new();
for v in e.variants.items() {
let name = v.name.to_string();
let variant_schema_name = format!("{}::{}", e.name, name);
let fields = parse_struct_fields(&v.contents);
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)
.read()
.get(&TypeId::of::<Self>())
.copied()
};
schema.unwrap_or_else(|| {
let schema = compute_schema();
S.get_or_init(Default::default)
.write()
.insert(TypeId::of::<Self>(), schema);
schema
})
}
} else {
quote! {
static S: ::std::sync::OnceLock<&'static #schema_mod::Schema> = ::std::sync::OnceLock::new();
S.get_or_init(compute_schema)
}
};
variants.push(quote! {
#schema_mod::VariantInfo {
name: #name.into(),
schema: {
let compute_schema = || {
#schema_mod::registry::SCHEMA_REGISTRY.register(#schema_mod::SchemaData {
name: #variant_schema_name.into(),
full_name: concat!(module_path!(), "::", #variant_schema_name).into(),
type_id: None,
kind: #schema_mod::SchemaKind::Struct(#schema_mod::StructSchemaInfo {
fields: vec![
#(#fields),*
]
}),
type_data: Default::default(),
default_fn: None,
clone_fn: None,
eq_fn: None,
hash_fn: None,
drop_fn: None,
})
};
#register_schema
}
}
})
}
quote! {
#schema_mod::SchemaKind::Enum(#schema_mod::EnumSchemaInfo {
tag_type: #schema_mod::EnumTagType::#tag_type,
variants: vec![#(#variants),*],
})
}
}
_ => {
throw!(
input,
"You may only derive HasSchema for structs and enums."
);
}
}
})();
let schema_register = quote! {
#schema_mod::registry::SCHEMA_REGISTRY.register(#schema_mod::SchemaData {
name: stringify!(#name).into(),
full_name: concat!(module_path!(), "::", stringify!(#name)).into(),
type_id: Some(::std::any::TypeId::of::<Self>()),
kind: #schema_kind,
type_data: #type_datas,
default_fn: #default_fn,
clone_fn: #clone_fn,
eq_fn: None,
hash_fn: None,
drop_fn: Some(<Self as #schema_mod::raw_fns::RawDrop>::raw_drop_cb()),
})
};
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!() };
param.bound = Some(GenericBound {
tk_colon: Punct::new(':', Spacing::Joint),
tokens: quote!(HasSchema #clone_bound ).into_iter().collect(),
});
}
quote! {
unsafe impl #sync_send_generic_params #schema_mod::HasSchema for #name #generic_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)
.read()
.get(&TypeId::of::<Self>())
.copied()
};
schema.unwrap_or_else(|| {
let schema = #schema_register;
S.get_or_init(Default::default)
.write()
.insert(TypeId::of::<Self>(), schema);
schema
})
}
}
}
} else {
quote! {
unsafe impl #schema_mod::HasSchema for #name {
fn schema() -> &'static #schema_mod::Schema {
static S: ::std::sync::OnceLock<&'static #schema_mod::Schema> = ::std::sync::OnceLock::new();
S.get_or_init(|| {
#schema_register
})
}
}
}
}
.into()
}
//
// Helpers
//
/// Look for an attribute with the given name and get all of the comma-separated flags that are
/// in that attribute.
///
/// For example, with the given struct:
///
/// ```ignore
/// #[example(test)]
/// #[my_attr(hello, world)]
/// struct Hello;
/// ```
///
/// Calling `get_flags_for_attr("my_attr")` would return `vec!["hello", "world"]`.
fn get_flags_for_attr(input: &venial::Declaration, attr_name: &str) -> Vec<String> {
let attrs = input
.attributes()
.iter()
.filter(|attr| attr.path.len() == 1 && attr.path[0].to_string() == attr_name)
.collect::<Vec<_>>();
attrs
.iter()
.map(|attr| match &attr.value {
venial::AttributeValue::Group(_, value) => {
let mut flags = Vec::new();
let mut current_flag = proc_macro2::TokenStream::new();
for token in value {
match token {
TokenTree2::Punct(x) if x.as_char() == ',' => {
flags.push(current_flag.to_string());
current_flag = Default::default();
}
x => current_flag.extend(std::iter::once(x.clone())),
}
}
flags.push(current_flag.to_string());
flags
}
venial::AttributeValue::Equals(_, _) => {
// TODO: Improve macro error message span.
panic!("Unsupported attribute format");
}
venial::AttributeValue::Empty => Vec::new(),
})
.fold(Vec::new(), |mut acc, item| {
acc.extend(item);
acc
})
}