introspect_core/
entity.rs

1use proc_macro2::TokenStream;
2use quote::ToTokens;
3
4use crate::Enum;
5use crate::Struct;
6
7/// A member of a Rust construct.
8#[derive(Debug)]
9pub enum Entity {
10    /// An enum.
11    Enum(Enum),
12
13    /// A struct.
14    Struct(Struct),
15}
16
17impl std::fmt::Display for Entity {
18    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19        match self {
20            Entity::Struct(struct_) => write!(f, "::introspect::Entity::Struct({})", struct_),
21            Entity::Enum(enum_) => write!(f, "::introspect::Entity::Enum({})", enum_),
22        }
23    }
24}
25
26impl ToTokens for Entity {
27    fn to_tokens(&self, tokens: &mut TokenStream) {
28        // SAFETY: this unwrap should never fail as we exhaustively test converting a
29        // [`Entity`] to a string that eventually parses to a token stream.
30        tokens.extend(self.to_string().parse::<TokenStream>().unwrap())
31    }
32}
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37
38    #[test]
39    fn an_enum_converts_to_string_correctly() {
40        let member = Entity::Enum(Enum::new("Name".into(), Some("Documentation.".into())));
41
42        assert_eq!(member.to_string(), "::introspect::Entity::Enum(::introspect::Enum::new(r#\"Name\"#.into(), Some(r#\"Documentation.\"#.into())))");
43    }
44
45    #[test]
46    fn a_struct_converts_to_string_correctly() {
47        let member = Entity::Struct(Struct::new("Name".into(), Some("Documentation.".into())));
48
49        assert_eq!(member.to_string(), "::introspect::Entity::Struct(::introspect::Struct::new(r#\"Name\"#.into(), Some(r#\"Documentation.\"#.into())))");
50    }
51}