Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_reflect/derive/src/ident.rs
6599 views
1
use proc_macro2::{Ident, Span};
2
use syn::Member;
3
4
/// Returns the "reflected" ident for a given string.
5
///
6
/// # Example
7
///
8
/// ```
9
/// # use proc_macro2::Ident;
10
/// # // We can't import this method because of its visibility.
11
/// # fn get_reflect_ident(name: &str) -> Ident {
12
/// # let reflected = format!("Reflect{name}");
13
/// # Ident::new(&reflected, proc_macro2::Span::call_site())
14
/// # }
15
/// let reflected: Ident = get_reflect_ident("Hash");
16
/// assert_eq!("ReflectHash", reflected.to_string());
17
/// ```
18
pub(crate) fn get_reflect_ident(name: &str) -> Ident {
19
let reflected = format!("Reflect{name}");
20
Ident::new(&reflected, Span::call_site())
21
}
22
23
/// Returns a [`Member`] made of `ident` or `index` if `ident` is `None`.
24
///
25
/// Rust struct syntax allows for `Struct { foo: "string" }` with explicitly
26
/// named fields. It allows the `Struct { 0: "string" }` syntax when the struct
27
/// is declared as a tuple struct.
28
///
29
/// ```
30
/// struct Foo { field: &'static str }
31
/// struct Bar(&'static str);
32
/// let Foo { field } = Foo { field: "hi" };
33
/// let Bar { 0: field } = Bar { 0: "hello" };
34
/// let Bar(field) = Bar("hello"); // more common syntax
35
/// ```
36
///
37
/// This function helps field access in contexts where you are declaring either
38
/// a tuple struct or a struct with named fields. If you don't have a field name,
39
/// it means that you must access the field through an index.
40
pub(crate) fn ident_or_index(ident: Option<&Ident>, index: usize) -> Member {
41
ident.map_or_else(
42
|| Member::Unnamed(index.into()),
43
|ident| Member::Named(ident.clone()),
44
)
45
}
46
47