Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_macro_utils/src/shape.rs
9353 views
1
use syn::{
2
punctuated::Punctuated, spanned::Spanned, token::Comma, Data, DataEnum, DataUnion, Error,
3
Field, Fields,
4
};
5
6
/// Get the fields of a data structure if that structure is a struct;
7
/// otherwise, return a compile error that points to the site of the macro invocation.
8
///
9
/// `meta` should be the name of the macro calling this function.
10
pub fn get_struct_fields<'a>(data: &'a Data, meta: &str) -> Result<&'a Fields, Error> {
11
match data {
12
Data::Struct(data_struct) => Ok(&data_struct.fields),
13
Data::Enum(DataEnum { enum_token, .. }) => Err(Error::new(
14
enum_token.span(),
15
format!("#[{meta}] only supports structs, not enums"),
16
)),
17
Data::Union(DataUnion { union_token, .. }) => Err(Error::new(
18
union_token.span(),
19
format!("#[{meta}] only supports structs, not unions"),
20
)),
21
}
22
}
23
24
/// Return an error if `Fields` is not `Fields::Named`
25
pub fn require_named<'a>(fields: &'a Fields) -> Result<&'a Punctuated<Field, Comma>, Error> {
26
if let Fields::Named(fields) = fields {
27
Ok(&fields.named)
28
} else {
29
Err(Error::new(
30
fields.span(),
31
"Unnamed fields are not supported here",
32
))
33
}
34
}
35
36