Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_reflect/derive/src/lib.rs
6849 views
1
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
2
3
//! This crate contains macros used by Bevy's `Reflect` API.
4
//!
5
//! The main export of this crate is the derive macro for [`Reflect`]. This allows
6
//! types to easily implement `Reflect` along with other `bevy_reflect` traits,
7
//! such as `Struct`, `GetTypeRegistration`, and more— all with a single derive!
8
//!
9
//! Some other noteworthy exports include the derive macros for [`FromReflect`] and
10
//! [`TypePath`], as well as the [`reflect_trait`] attribute macro.
11
//!
12
//! [`Reflect`]: crate::derive_reflect
13
//! [`FromReflect`]: crate::derive_from_reflect
14
//! [`TypePath`]: crate::derive_type_path
15
//! [`reflect_trait`]: macro@reflect_trait
16
17
extern crate proc_macro;
18
19
mod container_attributes;
20
mod custom_attributes;
21
mod derive_data;
22
#[cfg(feature = "documentation")]
23
mod documentation;
24
mod enum_utility;
25
mod field_attributes;
26
mod from_reflect;
27
mod generics;
28
mod ident;
29
mod impls;
30
mod meta;
31
mod reflect_opaque;
32
mod registration;
33
mod remote;
34
mod serialization;
35
mod string_expr;
36
mod struct_utility;
37
mod trait_reflection;
38
mod type_path;
39
mod where_clause_options;
40
41
use std::{fs, io::Read, path::PathBuf};
42
43
use crate::derive_data::{ReflectDerive, ReflectMeta, ReflectStruct};
44
use container_attributes::ContainerAttributes;
45
use derive_data::{ReflectImplSource, ReflectProvenance, ReflectTraitToImpl, ReflectTypePath};
46
use proc_macro::TokenStream;
47
use quote::quote;
48
use reflect_opaque::ReflectOpaqueDef;
49
use syn::{parse_macro_input, DeriveInput};
50
use type_path::NamedTypePathDef;
51
52
pub(crate) static REFLECT_ATTRIBUTE_NAME: &str = "reflect";
53
pub(crate) static TYPE_PATH_ATTRIBUTE_NAME: &str = "type_path";
54
pub(crate) static TYPE_NAME_ATTRIBUTE_NAME: &str = "type_name";
55
56
/// Used both for [`impl_reflect`] and [`derive_reflect`].
57
///
58
/// [`impl_reflect`]: macro@impl_reflect
59
/// [`derive_reflect`]: derive_reflect()
60
fn match_reflect_impls(ast: DeriveInput, source: ReflectImplSource) -> TokenStream {
61
let derive_data = match ReflectDerive::from_input(
62
&ast,
63
ReflectProvenance {
64
source,
65
trait_: ReflectTraitToImpl::Reflect,
66
},
67
) {
68
Ok(data) => data,
69
Err(err) => return err.into_compile_error().into(),
70
};
71
72
let assertions = impls::impl_assertions(&derive_data);
73
74
let (reflect_impls, from_reflect_impl) = match derive_data {
75
ReflectDerive::Struct(struct_data) | ReflectDerive::UnitStruct(struct_data) => (
76
impls::impl_struct(&struct_data),
77
if struct_data.meta().from_reflect().should_auto_derive() {
78
Some(from_reflect::impl_struct(&struct_data))
79
} else {
80
None
81
},
82
),
83
ReflectDerive::TupleStruct(struct_data) => (
84
impls::impl_tuple_struct(&struct_data),
85
if struct_data.meta().from_reflect().should_auto_derive() {
86
Some(from_reflect::impl_tuple_struct(&struct_data))
87
} else {
88
None
89
},
90
),
91
ReflectDerive::Enum(enum_data) => (
92
impls::impl_enum(&enum_data),
93
if enum_data.meta().from_reflect().should_auto_derive() {
94
Some(from_reflect::impl_enum(&enum_data))
95
} else {
96
None
97
},
98
),
99
ReflectDerive::Opaque(meta) => (
100
impls::impl_opaque(&meta),
101
if meta.from_reflect().should_auto_derive() {
102
Some(from_reflect::impl_opaque(&meta))
103
} else {
104
None
105
},
106
),
107
};
108
109
TokenStream::from(quote! {
110
const _: () = {
111
#reflect_impls
112
113
#from_reflect_impl
114
115
#assertions
116
};
117
})
118
}
119
120
/// The main derive macro used by `bevy_reflect` for deriving its `Reflect` trait.
121
///
122
/// This macro can be used on all structs and enums (unions are not supported).
123
/// It will automatically generate implementations for `Reflect`, `Typed`, `GetTypeRegistration`, and `FromReflect`.
124
/// And, depending on the item's structure, will either implement `Struct`, `TupleStruct`, or `Enum`.
125
///
126
/// See the [`FromReflect`] derive macro for more information on how to customize the `FromReflect` implementation.
127
///
128
/// # Container Attributes
129
///
130
/// This macro comes with some helper attributes that can be added to the container item
131
/// in order to provide additional functionality or alter the generated implementations.
132
///
133
/// In addition to those listed, this macro can also use the attributes for [`TypePath`] derives.
134
///
135
/// ## `#[reflect(Ident)]`
136
///
137
/// The `#[reflect(Ident)]` attribute is used to add type data registrations to the `GetTypeRegistration`
138
/// implementation corresponding to the given identifier, prepended by `Reflect`.
139
///
140
/// For example, `#[reflect(Foo, Bar)]` would add two registrations:
141
/// one for `ReflectFoo` and another for `ReflectBar`.
142
/// This assumes these types are indeed in-scope wherever this macro is called.
143
///
144
/// This is often used with traits that have been marked by the [`#[reflect_trait]`](macro@reflect_trait)
145
/// macro in order to register the type's implementation of that trait.
146
///
147
/// ### Default Registrations
148
///
149
/// The following types are automatically registered when deriving `Reflect`:
150
///
151
/// * `ReflectFromReflect` (unless opting out of `FromReflect`)
152
/// * `SerializationData`
153
/// * `ReflectFromPtr`
154
///
155
/// ### Special Identifiers
156
///
157
/// There are a few "special" identifiers that work a bit differently:
158
///
159
/// * `#[reflect(Clone)]` will force the implementation of `Reflect::reflect_clone` to rely on
160
/// the type's [`Clone`] implementation.
161
/// A custom implementation may be provided using `#[reflect(Clone(my_clone_func))]` where
162
/// `my_clone_func` is the path to a function matching the signature:
163
/// `(&Self) -> Self`.
164
/// * `#[reflect(Debug)]` will force the implementation of `Reflect::reflect_debug` to rely on
165
/// the type's [`Debug`] implementation.
166
/// A custom implementation may be provided using `#[reflect(Debug(my_debug_func))]` where
167
/// `my_debug_func` is the path to a function matching the signature:
168
/// `(&Self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result`.
169
/// * `#[reflect(PartialEq)]` will force the implementation of `Reflect::reflect_partial_eq` to rely on
170
/// the type's [`PartialEq`] implementation.
171
/// A custom implementation may be provided using `#[reflect(PartialEq(my_partial_eq_func))]` where
172
/// `my_partial_eq_func` is the path to a function matching the signature:
173
/// `(&Self, value: &dyn #bevy_reflect_path::Reflect) -> bool`.
174
/// * `#[reflect(Hash)]` will force the implementation of `Reflect::reflect_hash` to rely on
175
/// the type's [`Hash`] implementation.
176
/// A custom implementation may be provided using `#[reflect(Hash(my_hash_func))]` where
177
/// `my_hash_func` is the path to a function matching the signature: `(&Self) -> u64`.
178
/// * `#[reflect(Default)]` will register the `ReflectDefault` type data as normal.
179
/// However, it will also affect how certain other operations are performed in order
180
/// to improve performance and/or robustness.
181
/// An example of where this is used is in the [`FromReflect`] derive macro,
182
/// where adding this attribute will cause the `FromReflect` implementation to create
183
/// a base value using its [`Default`] implementation avoiding issues with ignored fields
184
/// (for structs and tuple structs only).
185
///
186
/// ## `#[reflect(opaque)]`
187
///
188
/// The `#[reflect(opaque)]` attribute denotes that the item should implement `Reflect` as an opaque type,
189
/// hiding its structure and fields from the reflection API.
190
/// This means that it will forgo implementing `Struct`, `TupleStruct`, or `Enum`.
191
///
192
/// Furthermore, it requires that the type implements [`Clone`].
193
/// If planning to serialize this type using the reflection serializers,
194
/// then the `Serialize` and `Deserialize` traits will need to be implemented and registered as well.
195
///
196
/// ## `#[reflect(from_reflect = false)]`
197
///
198
/// This attribute will opt-out of the default `FromReflect` implementation.
199
///
200
/// This is useful for when a type can't or shouldn't implement `FromReflect`,
201
/// or if a manual implementation is desired.
202
///
203
/// Note that in the latter case, `ReflectFromReflect` will no longer be automatically registered.
204
///
205
/// ## `#[reflect(type_path = false)]`
206
///
207
/// This attribute will opt-out of the default `TypePath` implementation.
208
///
209
/// This is useful for when a type can't or shouldn't implement `TypePath`,
210
/// or if a manual implementation is desired.
211
///
212
/// ## `#[reflect(no_field_bounds)]`
213
///
214
/// This attribute will opt-out of the default trait bounds added to all field types
215
/// for the generated reflection trait impls.
216
///
217
/// Normally, all fields will have the bounds `TypePath`, and either `FromReflect` or `Reflect`
218
/// depending on if `#[reflect(from_reflect = false)]` is used.
219
/// However, this might not always be desirable, and so this attribute may be used to remove those bounds.
220
///
221
/// ### Example
222
///
223
/// If a type is recursive the default bounds will cause an overflow error when building:
224
///
225
/// ```ignore (bevy_reflect is not accessible from this crate)
226
/// #[derive(Reflect)] // ERROR: overflow evaluating the requirement `Foo: FromReflect`
227
/// struct Foo {
228
/// foo: Vec<Foo>,
229
/// }
230
///
231
/// // Generates a where clause like:
232
/// // impl bevy_reflect::Reflect for Foo
233
/// // where
234
/// // Foo: Any + Send + Sync,
235
/// // Vec<Foo>: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
236
/// ```
237
///
238
/// In this case, `Foo` is given the bounds `Vec<Foo>: FromReflect + ...`,
239
/// which requires that `Foo` implements `FromReflect`,
240
/// which requires that `Vec<Foo>` implements `FromReflect`,
241
/// and so on, resulting in the error.
242
///
243
/// To fix this, we can add `#[reflect(no_field_bounds)]` to `Foo` to remove the bounds on `Vec<Foo>`:
244
///
245
/// ```ignore (bevy_reflect is not accessible from this crate)
246
/// #[derive(Reflect)]
247
/// #[reflect(no_field_bounds)]
248
/// struct Foo {
249
/// foo: Vec<Foo>,
250
/// }
251
///
252
/// // Generates a where clause like:
253
/// // impl bevy_reflect::Reflect for Foo
254
/// // where
255
/// // Self: Any + Send + Sync,
256
/// ```
257
///
258
/// ## `#[reflect(where T: Trait, U::Assoc: Trait, ...)]`
259
///
260
/// This attribute can be used to add additional bounds to the generated reflection trait impls.
261
///
262
/// This is useful for when a type needs certain bounds only applied to the reflection impls
263
/// that are not otherwise automatically added by the derive macro.
264
///
265
/// ### Example
266
///
267
/// In the example below, we want to enforce that `T::Assoc: List` is required in order for
268
/// `Foo<T>` to be reflectable, but we don't want it to prevent `Foo<T>` from being used
269
/// in places where `T::Assoc: List` is not required.
270
///
271
/// ```ignore
272
/// trait Trait {
273
/// type Assoc;
274
/// }
275
///
276
/// #[derive(Reflect)]
277
/// #[reflect(where T::Assoc: List)]
278
/// struct Foo<T: Trait> where T::Assoc: Default {
279
/// value: T::Assoc,
280
/// }
281
///
282
/// // Generates a where clause like:
283
/// //
284
/// // impl<T: Trait> bevy_reflect::Reflect for Foo<T>
285
/// // where
286
/// // Foo<T>: Any + Send + Sync,
287
/// // T::Assoc: Default,
288
/// // T: TypePath,
289
/// // T::Assoc: FromReflect + TypePath + MaybeTyped + RegisterForReflection,
290
/// // T::Assoc: List,
291
/// // {/* ... */}
292
/// ```
293
///
294
/// ## `#[reflect(@...)]`
295
///
296
/// This attribute can be used to register custom attributes to the type's `TypeInfo`.
297
///
298
/// It accepts any expression after the `@` symbol that resolves to a value which implements `Reflect`.
299
///
300
/// Any number of custom attributes may be registered, however, each the type of each attribute must be unique.
301
/// If two attributes of the same type are registered, the last one will overwrite the first.
302
///
303
/// ### Example
304
///
305
/// ```ignore
306
/// #[derive(Reflect)]
307
/// struct Required;
308
///
309
/// #[derive(Reflect)]
310
/// struct EditorTooltip(String);
311
///
312
/// impl EditorTooltip {
313
/// fn new(text: &str) -> Self {
314
/// Self(text.to_string())
315
/// }
316
/// }
317
///
318
/// #[derive(Reflect)]
319
/// // Specify a "required" status and tooltip:
320
/// #[reflect(@Required, @EditorTooltip::new("An ID is required!"))]
321
/// struct Id(u8);
322
/// ```
323
/// ## `#[reflect(no_auto_register)]`
324
///
325
/// This attribute will opt-out of the automatic reflect type registration.
326
///
327
/// All non-generic types annotated with `#[derive(Reflect)]` are usually automatically registered on app startup.
328
/// If this behavior is not desired, this attribute may be used to disable it for the annotated type.
329
///
330
/// # Field Attributes
331
///
332
/// Along with the container attributes, this macro comes with some attributes that may be applied
333
/// to the contained fields themselves.
334
///
335
/// ## `#[reflect(ignore)]`
336
///
337
/// This attribute simply marks a field to be ignored by the reflection API.
338
///
339
/// This allows fields to completely opt-out of reflection,
340
/// which may be useful for maintaining invariants, keeping certain data private,
341
/// or allowing the use of types that do not implement `Reflect` within the container.
342
///
343
/// ## `#[reflect(skip_serializing)]`
344
///
345
/// This works similar to `#[reflect(ignore)]`, but rather than opting out of _all_ of reflection,
346
/// it simply opts the field out of both serialization and deserialization.
347
/// This can be useful when a field should be accessible via reflection, but may not make
348
/// sense in a serialized form, such as computed data.
349
///
350
/// What this does is register the `SerializationData` type within the `GetTypeRegistration` implementation,
351
/// which will be used by the reflection serializers to determine whether or not the field is serializable.
352
///
353
/// ## `#[reflect(clone)]`
354
///
355
/// This attribute affects the `Reflect::reflect_clone` implementation.
356
///
357
/// Without this attribute, the implementation will rely on the field's own `Reflect::reflect_clone` implementation.
358
/// When this attribute is present, the implementation will instead use the field's `Clone` implementation directly.
359
///
360
/// The attribute may also take the path to a custom function like `#[reflect(clone = "path::to::my_clone_func")]`,
361
/// where `my_clone_func` matches the signature `(&Self) -> Self`.
362
///
363
/// This attribute does nothing if the containing struct/enum has the `#[reflect(Clone)]` attribute.
364
///
365
/// ## `#[reflect(@...)]`
366
///
367
/// This attribute can be used to register custom attributes to the field's `TypeInfo`.
368
///
369
/// It accepts any expression after the `@` symbol that resolves to a value which implements `Reflect`.
370
///
371
/// Any number of custom attributes may be registered, however, each the type of each attribute must be unique.
372
/// If two attributes of the same type are registered, the last one will overwrite the first.
373
///
374
/// ### Example
375
///
376
/// ```ignore
377
/// #[derive(Reflect)]
378
/// struct EditorTooltip(String);
379
///
380
/// impl EditorTooltip {
381
/// fn new(text: &str) -> Self {
382
/// Self(text.to_string())
383
/// }
384
/// }
385
///
386
/// #[derive(Reflect)]
387
/// struct Slider {
388
/// // Specify a custom range and tooltip:
389
/// #[reflect(@0.0..=1.0, @EditorTooltip::new("Must be between 0 and 1"))]
390
/// value: f32,
391
/// }
392
/// ```
393
///
394
/// [`reflect_trait`]: macro@reflect_trait
395
#[proc_macro_derive(Reflect, attributes(reflect, type_path, type_name))]
396
pub fn derive_reflect(input: TokenStream) -> TokenStream {
397
let ast = parse_macro_input!(input as DeriveInput);
398
match_reflect_impls(ast, ReflectImplSource::DeriveLocalType)
399
}
400
401
/// Derives the `FromReflect` trait.
402
///
403
/// # Field Attributes
404
///
405
/// ## `#[reflect(ignore)]`
406
///
407
/// The `#[reflect(ignore)]` attribute is shared with the [`#[derive(Reflect)]`](Reflect) macro and has much of the same
408
/// functionality in that it denotes that a field will be ignored by the reflection API.
409
///
410
/// The only major difference is that using it with this derive requires that the field implements [`Default`].
411
/// Without this requirement, there would be no way for `FromReflect` to automatically construct missing fields
412
/// that have been ignored.
413
///
414
/// ## `#[reflect(default)]`
415
///
416
/// If a field cannot be read, this attribute specifies a default value to be used in its place.
417
///
418
/// By default, this attribute denotes that the field's type implements [`Default`].
419
/// However, it can also take in a path string to a user-defined function that will return the default value.
420
/// This takes the form: `#[reflect(default = "path::to::my_function")]` where `my_function` is a parameterless
421
/// function that must return some default value for the type.
422
///
423
/// Specifying a custom default can be used to give different fields their own specialized defaults,
424
/// or to remove the `Default` requirement on fields marked with `#[reflect(ignore)]`.
425
/// Additionally, either form of this attribute can be used to fill in fields that are simply missing,
426
/// such as when converting a partially-constructed dynamic type to a concrete one.
427
#[proc_macro_derive(FromReflect, attributes(reflect))]
428
pub fn derive_from_reflect(input: TokenStream) -> TokenStream {
429
let ast = parse_macro_input!(input as DeriveInput);
430
431
let derive_data = match ReflectDerive::from_input(
432
&ast,
433
ReflectProvenance {
434
source: ReflectImplSource::DeriveLocalType,
435
trait_: ReflectTraitToImpl::FromReflect,
436
},
437
) {
438
Ok(data) => data,
439
Err(err) => return err.into_compile_error().into(),
440
};
441
442
let from_reflect_impl = match derive_data {
443
ReflectDerive::Struct(struct_data) | ReflectDerive::UnitStruct(struct_data) => {
444
from_reflect::impl_struct(&struct_data)
445
}
446
ReflectDerive::TupleStruct(struct_data) => from_reflect::impl_tuple_struct(&struct_data),
447
ReflectDerive::Enum(meta) => from_reflect::impl_enum(&meta),
448
ReflectDerive::Opaque(meta) => from_reflect::impl_opaque(&meta),
449
};
450
451
TokenStream::from(quote! {
452
const _: () = {
453
#from_reflect_impl
454
};
455
})
456
}
457
458
/// Derives the `TypePath` trait, providing a stable alternative to [`std::any::type_name`].
459
///
460
/// # Container Attributes
461
///
462
/// ## `#[type_path = "my_crate::foo"]`
463
///
464
/// Optionally specifies a custom module path to use instead of [`module_path`].
465
///
466
/// This path does not include the final identifier.
467
///
468
/// ## `#[type_name = "RenamedType"]`
469
///
470
/// Optionally specifies a new terminating identifier for `TypePath`.
471
///
472
/// To use this attribute, `#[type_path = "..."]` must also be specified.
473
#[proc_macro_derive(TypePath, attributes(type_path, type_name))]
474
pub fn derive_type_path(input: TokenStream) -> TokenStream {
475
let ast = parse_macro_input!(input as DeriveInput);
476
let derive_data = match ReflectDerive::from_input(
477
&ast,
478
ReflectProvenance {
479
source: ReflectImplSource::DeriveLocalType,
480
trait_: ReflectTraitToImpl::TypePath,
481
},
482
) {
483
Ok(data) => data,
484
Err(err) => return err.into_compile_error().into(),
485
};
486
487
let type_path_impl = impls::impl_type_path(derive_data.meta());
488
489
TokenStream::from(quote! {
490
const _: () = {
491
#type_path_impl
492
};
493
})
494
}
495
496
/// A macro that automatically generates type data for traits, which their implementors can then register.
497
///
498
/// The output of this macro is a struct that takes reflected instances of the implementor's type
499
/// and returns the value as a trait object.
500
/// Because of this, **it can only be used on [object-safe] traits.**
501
///
502
/// For a trait named `MyTrait`, this will generate the struct `ReflectMyTrait`.
503
/// The generated struct can be created using `FromType` with any type that implements the trait.
504
/// The creation and registration of this generated struct as type data can be automatically handled
505
/// by [`#[derive(Reflect)]`](Reflect).
506
///
507
/// # Example
508
///
509
/// ```ignore (bevy_reflect is not accessible from this crate)
510
/// # use std::any::TypeId;
511
/// # use bevy_reflect_derive::{Reflect, reflect_trait};
512
/// #[reflect_trait] // Generates `ReflectMyTrait`
513
/// trait MyTrait {
514
/// fn print(&self) -> &str;
515
/// }
516
///
517
/// #[derive(Reflect)]
518
/// #[reflect(MyTrait)] // Automatically registers `ReflectMyTrait`
519
/// struct SomeStruct;
520
///
521
/// impl MyTrait for SomeStruct {
522
/// fn print(&self) -> &str {
523
/// "Hello, World!"
524
/// }
525
/// }
526
///
527
/// // We can create the type data manually if we wanted:
528
/// let my_trait: ReflectMyTrait = FromType::<SomeStruct>::from_type();
529
///
530
/// // Or we can simply get it from the registry:
531
/// let mut registry = TypeRegistry::default();
532
/// registry.register::<SomeStruct>();
533
/// let my_trait = registry
534
/// .get_type_data::<ReflectMyTrait>(TypeId::of::<SomeStruct>())
535
/// .unwrap();
536
///
537
/// // Then use it on reflected data
538
/// let reflected: Box<dyn Reflect> = Box::new(SomeStruct);
539
/// let reflected_my_trait: &dyn MyTrait = my_trait.get(&*reflected).unwrap();
540
/// assert_eq!("Hello, World!", reflected_my_trait.print());
541
/// ```
542
///
543
/// [object-safe]: https://doc.rust-lang.org/reference/items/traits.html#object-safety
544
#[proc_macro_attribute]
545
pub fn reflect_trait(args: TokenStream, input: TokenStream) -> TokenStream {
546
trait_reflection::reflect_trait(&args, input)
547
}
548
549
/// Generates a wrapper type that can be used to "derive `Reflect`" for remote types.
550
///
551
/// This works by wrapping the remote type in a generated wrapper that has the `#[repr(transparent)]` attribute.
552
/// This allows the two types to be safely [transmuted] back-and-forth.
553
///
554
/// # Defining the Wrapper
555
///
556
/// Before defining the wrapper type, please note that it is _required_ that all fields of the remote type are public.
557
/// The generated code will, at times, need to access or mutate them,
558
/// and we do not currently have a way to assign getters/setters to each field
559
/// (but this may change in the future).
560
///
561
/// The wrapper definition should match the remote type 1-to-1.
562
/// This includes the naming and ordering of the fields and variants.
563
///
564
/// Generics and lifetimes do _not_ need to have the same names, however, they _do_ need to follow the same order.
565
/// Additionally, whether generics are inlined or placed in a where clause should not matter.
566
///
567
/// Lastly, all macros and doc-comments should be placed __below__ this attribute.
568
/// If they are placed above, they will not be properly passed to the generated wrapper type.
569
///
570
/// # Example
571
///
572
/// Given a remote type, `RemoteType`:
573
///
574
/// ```
575
/// #[derive(Default)]
576
/// struct RemoteType<T>
577
/// where
578
/// T: Default + Clone,
579
/// {
580
/// pub foo: T,
581
/// pub bar: usize
582
/// }
583
/// ```
584
///
585
/// We would define our wrapper type as such:
586
///
587
/// ```ignore
588
/// use external_crate::RemoteType;
589
///
590
/// #[reflect_remote(RemoteType<T>)]
591
/// #[derive(Default)]
592
/// pub struct WrapperType<T: Default + Clone> {
593
/// pub foo: T,
594
/// pub bar: usize
595
/// }
596
/// ```
597
///
598
/// Apart from all the reflection trait implementations, this generates something like the following:
599
///
600
/// ```ignore
601
/// use external_crate::RemoteType;
602
///
603
/// #[derive(Default)]
604
/// #[repr(transparent)]
605
/// pub struct Wrapper<T: Default + Clone>(RemoteType<T>);
606
/// ```
607
///
608
/// # Usage as a Field
609
///
610
/// You can tell `Reflect` to use a remote type's wrapper internally on fields of a struct or enum.
611
/// This allows the real type to be used as usual while `Reflect` handles everything internally.
612
/// To do this, add the `#[reflect(remote = path::to::MyType)]` attribute to your field:
613
///
614
/// ```ignore
615
/// #[derive(Reflect)]
616
/// struct SomeStruct {
617
/// #[reflect(remote = RemoteTypeWrapper)]
618
/// data: RemoteType
619
/// }
620
/// ```
621
///
622
/// ## Safety
623
///
624
/// When using the `#[reflect(remote = path::to::MyType)]` field attribute, be sure you are defining the correct wrapper type.
625
/// Internally, this field will be unsafely [transmuted], and is only sound if using a wrapper generated for the remote type.
626
/// This also means keeping your wrapper definitions up-to-date with the remote types.
627
///
628
/// [transmuted]: std::mem::transmute
629
#[proc_macro_attribute]
630
pub fn reflect_remote(args: TokenStream, input: TokenStream) -> TokenStream {
631
remote::reflect_remote(args, input)
632
}
633
634
/// A macro used to generate reflection trait implementations for the given type.
635
///
636
/// This is functionally the same as [deriving `Reflect`] using the `#[reflect(opaque)]` container attribute.
637
///
638
/// The only reason for this macro's existence is so that `bevy_reflect` can easily implement the reflection traits
639
/// on primitives and other opaque types internally.
640
///
641
/// Since this macro also implements `TypePath`, the type path must be explicit.
642
/// See [`impl_type_path!`] for the exact syntax.
643
///
644
/// # Examples
645
///
646
/// Types can be passed with or without registering type data:
647
///
648
/// ```ignore (bevy_reflect is not accessible from this crate)
649
/// impl_reflect_opaque!(my_crate::Foo);
650
/// impl_reflect_opaque!(my_crate::Bar(Debug, Default, Serialize, Deserialize));
651
/// ```
652
///
653
/// Generic types can also specify their parameters and bounds:
654
///
655
/// ```ignore (bevy_reflect is not accessible from this crate)
656
/// impl_reflect_opaque!(my_crate::Foo<T1, T2: Baz> where T1: Bar (Default, Serialize, Deserialize));
657
/// ```
658
///
659
/// Custom type paths can be specified:
660
///
661
/// ```ignore (bevy_reflect is not accessible from this crate)
662
/// impl_reflect_opaque!((in not_my_crate as NotFoo) Foo(Debug, Default));
663
/// ```
664
///
665
/// [deriving `Reflect`]: Reflect
666
#[proc_macro]
667
pub fn impl_reflect_opaque(input: TokenStream) -> TokenStream {
668
let def = parse_macro_input!(input with ReflectOpaqueDef::parse_reflect);
669
670
let default_name = &def.type_path.segments.last().unwrap().ident;
671
let type_path = if def.type_path.leading_colon.is_none() && def.custom_path.is_none() {
672
ReflectTypePath::Primitive(default_name)
673
} else {
674
ReflectTypePath::External {
675
path: &def.type_path,
676
custom_path: def.custom_path.map(|path| path.into_path(default_name)),
677
generics: &def.generics,
678
}
679
};
680
681
let meta = ReflectMeta::new(type_path, def.traits.unwrap_or_default());
682
683
#[cfg(feature = "documentation")]
684
let meta = meta.with_docs(documentation::Documentation::from_attributes(&def.attrs));
685
686
let reflect_impls = impls::impl_opaque(&meta);
687
let from_reflect_impl = from_reflect::impl_opaque(&meta);
688
689
TokenStream::from(quote! {
690
const _: () = {
691
#reflect_impls
692
#from_reflect_impl
693
};
694
})
695
}
696
697
/// A replacement for `#[derive(Reflect)]` to be used with foreign types which
698
/// the definitions of cannot be altered.
699
///
700
/// This macro is an alternative to [`impl_reflect_opaque!`] and [`impl_from_reflect_opaque!`]
701
/// which implement foreign types as Opaque types. Note that there is no `impl_from_reflect`,
702
/// as this macro will do the job of both. This macro implements them using one of the reflect
703
/// variant traits (`bevy_reflect::{Struct, TupleStruct, Enum}`, etc.),
704
/// which have greater functionality. The type being reflected must be in scope, as you cannot
705
/// qualify it in the macro as e.g. `bevy::prelude::Vec3`.
706
///
707
/// It is necessary to add a `#[type_path = "my_crate::foo"]` attribute to all types.
708
///
709
/// It may be necessary to add `#[reflect(Default)]` for some types, specifically non-constructible
710
/// foreign types. Without `Default` reflected for such types, you will usually get an arcane
711
/// error message and fail to compile. If the type does not implement `Default`, it may not
712
/// be possible to reflect without extending the macro.
713
///
714
///
715
/// # Example
716
/// Implementing `Reflect` for `bevy::prelude::Vec3` as a struct type:
717
/// ```ignore (bevy_reflect is not accessible from this crate)
718
/// use bevy::prelude::Vec3;
719
///
720
/// impl_reflect!(
721
/// #[reflect(PartialEq, Serialize, Deserialize, Default)]
722
/// #[type_path = "bevy::prelude"]
723
/// struct Vec3 {
724
/// x: f32,
725
/// y: f32,
726
/// z: f32
727
/// }
728
/// );
729
/// ```
730
#[proc_macro]
731
pub fn impl_reflect(input: TokenStream) -> TokenStream {
732
let ast = parse_macro_input!(input as DeriveInput);
733
match_reflect_impls(ast, ReflectImplSource::ImplRemoteType)
734
}
735
736
/// A macro used to generate a `FromReflect` trait implementation for the given type.
737
///
738
/// This is functionally the same as [deriving `FromReflect`] on a type that [derives `Reflect`] using
739
/// the `#[reflect(opaque)]` container attribute.
740
///
741
/// The only reason this macro exists is so that `bevy_reflect` can easily implement `FromReflect` on
742
/// primitives and other opaque types internally.
743
///
744
/// Please note that this macro will not work with any type that [derives `Reflect`] normally
745
/// or makes use of the [`impl_reflect_opaque!`] macro, as those macros also implement `FromReflect`
746
/// by default.
747
///
748
/// # Examples
749
///
750
/// ```ignore (bevy_reflect is not accessible from this crate)
751
/// impl_from_reflect_opaque!(foo<T1, T2: Baz> where T1: Bar);
752
/// ```
753
///
754
/// [deriving `FromReflect`]: FromReflect
755
/// [derives `Reflect`]: Reflect
756
#[proc_macro]
757
pub fn impl_from_reflect_opaque(input: TokenStream) -> TokenStream {
758
let def = parse_macro_input!(input with ReflectOpaqueDef::parse_from_reflect);
759
760
let default_name = &def.type_path.segments.last().unwrap().ident;
761
let type_path = if def.type_path.leading_colon.is_none()
762
&& def.custom_path.is_none()
763
&& def.generics.params.is_empty()
764
{
765
ReflectTypePath::Primitive(default_name)
766
} else {
767
ReflectTypePath::External {
768
path: &def.type_path,
769
custom_path: def.custom_path.map(|alias| alias.into_path(default_name)),
770
generics: &def.generics,
771
}
772
};
773
774
let from_reflect_impl =
775
from_reflect::impl_opaque(&ReflectMeta::new(type_path, def.traits.unwrap_or_default()));
776
777
TokenStream::from(quote! {
778
const _: () = {
779
#from_reflect_impl
780
};
781
})
782
}
783
784
/// A replacement for [deriving `TypePath`] for use on foreign types.
785
///
786
/// Since (unlike the derive) this macro may be invoked in a different module to where the type is defined,
787
/// it requires an 'absolute' path definition.
788
///
789
/// Specifically, a leading `::` denoting a global path must be specified
790
/// or a preceding `(in my_crate::foo)` to specify the custom path must be used.
791
///
792
/// # Examples
793
///
794
/// Implementing `TypePath` on a foreign type:
795
/// ```ignore (bevy_reflect is not accessible from this crate)
796
/// impl_type_path!(::foreign_crate::foo::bar::Baz);
797
/// ```
798
///
799
/// On a generic type (this can also accept trait bounds):
800
/// ```ignore (bevy_reflect is not accessible from this crate)
801
/// impl_type_path!(::foreign_crate::Foo<T>);
802
/// impl_type_path!(::foreign_crate::Goo<T: ?Sized>);
803
/// ```
804
///
805
/// On a primitive (note this will not compile for a non-primitive type):
806
/// ```ignore (bevy_reflect is not accessible from this crate)
807
/// impl_type_path!(bool);
808
/// ```
809
///
810
/// With a custom type path:
811
/// ```ignore (bevy_reflect is not accessible from this crate)
812
/// impl_type_path!((in other_crate::foo::bar) Baz);
813
/// ```
814
///
815
/// With a custom type path and a custom type name:
816
/// ```ignore (bevy_reflect is not accessible from this crate)
817
/// impl_type_path!((in other_crate::foo as Baz) Bar);
818
/// ```
819
///
820
/// [deriving `TypePath`]: TypePath
821
#[proc_macro]
822
pub fn impl_type_path(input: TokenStream) -> TokenStream {
823
let def = parse_macro_input!(input as NamedTypePathDef);
824
825
let type_path = match def {
826
NamedTypePathDef::External {
827
ref path,
828
custom_path,
829
ref generics,
830
} => {
831
let default_name = &path.segments.last().unwrap().ident;
832
833
ReflectTypePath::External {
834
path,
835
custom_path: custom_path.map(|path| path.into_path(default_name)),
836
generics,
837
}
838
}
839
NamedTypePathDef::Primitive(ref ident) => ReflectTypePath::Primitive(ident),
840
};
841
842
let meta = ReflectMeta::new(type_path, ContainerAttributes::default());
843
844
let type_path_impl = impls::impl_type_path(&meta);
845
846
TokenStream::from(quote! {
847
const _: () = {
848
#type_path_impl
849
};
850
})
851
}
852
853
/// Collects and loads type registrations when using `auto_register_static` feature.
854
///
855
/// Correctly using this macro requires following:
856
/// 1. This macro must be called **last** during compilation. This can be achieved by putting your main function
857
/// in a separate crate or restructuring your project to be separated into `bin` and `lib`, and putting this macro in `bin`.
858
/// Any automatic type registrations using `#[derive(Reflect)]` within the same crate as this macro are not guaranteed to run.
859
/// 2. Your project must be compiled with `auto_register_static` feature **and** `BEVY_REFLECT_AUTO_REGISTER_STATIC=1` env variable.
860
/// Enabling the feature generates registration functions while setting the variable enables export and
861
/// caching of registration function names.
862
/// 3. Must be called before creating `App` or using `TypeRegistry::register_derived_types`.
863
///
864
/// If you're experiencing linking issues try running `cargo clean` before rebuilding.
865
#[proc_macro]
866
pub fn load_type_registrations(_input: TokenStream) -> TokenStream {
867
if !cfg!(feature = "auto_register_static") {
868
return TokenStream::new();
869
}
870
871
let Ok(dir) = fs::read_dir(PathBuf::from("target").join("bevy_reflect_type_registrations"))
872
else {
873
return TokenStream::new();
874
};
875
let mut str_buf = String::new();
876
let mut registration_fns = Vec::new();
877
for file_path in dir {
878
let mut file = fs::OpenOptions::new()
879
.read(true)
880
.open(file_path.unwrap().path())
881
.unwrap();
882
file.read_to_string(&mut str_buf).unwrap();
883
registration_fns.extend(str_buf.lines().filter(|s| !s.is_empty()).map(|s| {
884
s.parse::<proc_macro2::TokenStream>()
885
.expect("Unexpected function name")
886
}));
887
str_buf.clear();
888
}
889
let bevy_reflect_path = meta::get_bevy_reflect_path();
890
TokenStream::from(quote! {
891
{
892
fn _register_types(){
893
unsafe extern "Rust" {
894
#( safe fn #registration_fns(registry_ptr: &mut #bevy_reflect_path::TypeRegistry); )*
895
};
896
#( #bevy_reflect_path::__macro_exports::auto_register::push_registration_fn(#registration_fns); )*
897
}
898
_register_types();
899
}
900
})
901
}
902
903