derive_attr_parser/internals/
ast.rs

1use std::collections::HashMap;
2use std::fmt::{self, Display};
3use syn::{Ident, Path};
4
5/// The root Container for all
6///
7/// let root:Container  = from_ast(...)
8///
9#[derive(Debug, Clone)]
10pub struct Container<'a> {
11    /// The struct or enum name (without generics).
12    pub ident: syn::Ident,
13    /// Attributes on the structure.
14    pub attrs: HashMap<String, Val>,
15    /// The contents of the struct or enum.
16    pub data: Data<'a>,
17    /// Any generics on the struct or enum.
18    pub generics: &'a syn::Generics,
19    /// Original input.
20    pub original: &'a syn::DeriveInput,
21}
22
23/// The fields of a struct or enum.
24///
25/// Analogous to `syn::Data`.
26#[derive(Debug, Clone)]
27pub enum Data<'a> {
28    Enum(Vec<Variant<'a>>),
29    Struct(Style, Vec<Field<'a>>),
30}
31
32#[derive(Debug, Clone, Copy)]
33pub enum Style {
34    /// Named fields.
35    Struct,
36    /// Many unnamed fields.
37    Tuple,
38    /// One unnamed field.
39    Newtype,
40    /// No fields.
41    Unit,
42}
43
44/// A variant of an enum.
45#[derive(Debug, Clone)]
46pub struct Variant<'a> {
47    pub ident: syn::Ident,
48    pub attrs: HashMap<String, Val>,
49    pub style: Style,
50    pub fields: Vec<Field<'a>>,
51    pub original: &'a syn::Variant,
52}
53
54/// A field of a struct.
55#[derive(Debug, Clone)]
56pub struct Field<'a> {
57    pub member: syn::Member,
58    pub attrs: HashMap<String, Val>,
59    pub ty: &'a syn::Type,
60    pub original: &'a syn::Field,
61}
62
63/// The root of helper attr, eg #[root(...)]
64/// ```rust
65/// use derive_attr_parser::Symbol;
66/// const ROOT:Symbol = Symbol("root");
67/// //let root:Container  = from_ast(.. ROOT);
68/// ```
69#[derive(Copy, Clone)]
70pub struct Symbol(pub &'static str);
71
72impl PartialEq<Symbol> for Ident {
73    fn eq(&self, word: &Symbol) -> bool {
74        self == word.0
75    }
76}
77
78impl<'a> PartialEq<Symbol> for &'a Ident {
79    fn eq(&self, word: &Symbol) -> bool {
80        *self == word.0
81    }
82}
83
84impl PartialEq<Symbol> for Path {
85    fn eq(&self, word: &Symbol) -> bool {
86        self.is_ident(word.0)
87    }
88}
89
90impl<'a> PartialEq<Symbol> for &'a Path {
91    fn eq(&self, word: &Symbol) -> bool {
92        self.is_ident(word.0)
93    }
94}
95
96impl Display for Symbol {
97    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
98        formatter.write_str(self.0)
99    }
100}
101
102/// ### Represent val of attr
103/// ``` #[fsm(test, trans(to="B"))] ```
104/// parse into fsm{"test":Val::Empty, "trans" : Val::Map("to": Val::Str("B")}
105#[derive(Debug, Clone)]
106pub enum Val {
107    Empty,
108    Str(String),
109    Map(HashMap<String, Val>),
110}