1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
use syn::parse::{Parse, ParseStream};
use syn::spanned::Spanned;
use syn::{Error, Path, Token};

use proc_macro2::Span;

use quote::ToTokens as _;

use std::ops::Deref;

/// Types that can be parsed from a [`Meta`] list.
///
/// # Deriving
/// ```ignore
/// use syn::LitStr;
///
/// #[derive(macrotk::FromMeta)]
/// pub struct MyMeta {
///     keyword: LitStr,
/// }
/// ```
///
/// # Implementing
/// When the `FromMeta` derive macro breaks, you can implement this yourself.
/// ```
/// # use macrotk_core as macrotk;
/// use syn::LitStr;
/// use syn::spanned::Spanned as _;
///
/// use macrotk::meta::{FromMeta, MetaStream};
///
/// pub struct MyMeta {
///     keyword: Option<LitStr>,
/// }
///
/// impl FromMeta for MyMeta {
///     fn from_meta(meta: MetaStream) -> Result<Self, syn::Error> {
///         let mut keyword: Option<LitStr> = None;
///
///         while let Some(name) = meta.next_name() {
///             let name = name?;
///
///             match name.as_str() {
///                 "keyword" => keyword = meta.next_value().transpose()?,
///                 s => return Err(syn::Error::new(name.span(), format!("unknown key: {}", s))),
///             }
///         }
///
///         Ok(MyMeta { keyword })
///     }
/// }
/// ```
pub trait FromMeta: Sized {
    fn from_meta(a: MetaStream) -> Result<Self, Error>;
}

/// Types that can be parsed as values of a [`Meta`] list.
pub trait FromMetaValue: Sized {
    fn from_meta_value(p: ParseStream) -> Result<Self, Error>;
}

/// A list of meta values that can be interpreted as a list or as a name-value
/// paired list.
pub struct MetaStream<'a>(ParseStream<'a>);

impl<'a> MetaStream<'a> {
    pub fn new(p: ParseStream<'a>) -> MetaStream<'a> {
        MetaStream(p)
    }

    /// Gets the next name of the meta.
    ///
    /// Returns `Ok(None)` if there are no more values.
    pub fn next_name(&self) -> Option<Result<Name, Error>> {
        if self.0.is_empty() {
            None
        } else {
            // get the next path
            let path = match self.0.parse::<Path>() {
                Ok(path) => path,
                Err(err) => return Some(Err(err)),
            };
            // eat the next equals
            match self.0.parse::<Token![=]>() {
                Ok(_) => (),
                Err(err) => return Some(Err(err)),
            }

            Some(Ok(Name::new(path)))
        }
    }

    /// Gets the next value of the meta.
    ///
    /// This can safely be called successively, as if you were interpreting a
    /// list.
    pub fn next_value<T>(&self) -> Option<Result<T, Error>>
    where
        T: FromMetaValue,
    {
        if self.0.is_empty() {
            None
        } else {
            // parse the type
            let result = match T::from_meta_value(self.0) {
                Ok(result) => result,
                Err(err) => return Some(Err(err)),
            };
            // eat the next comma, if it exists
            if !self.0.is_empty() {
                match self.0.parse::<Token![,]>() {
                    Ok(_) => (),
                    Err(err) => return Some(Err(err)),
                }
            }

            Some(Ok(result))
        }
    }
}

/// A name of a name-value paired [`Meta`] list.
///
/// This type can be matched with string literals.
/// ```
/// # use macrotk_core as macrotk;
/// use macrotk::meta::Name;
///
/// let name = Name::from("howdy");
///
/// match name.as_str() {
///     "howdy" => println!("How are you doing?"),
///     _ => panic!("Should match with \"howdy\""),
/// }
/// ```
pub struct Name {
    name: String,
    span: Span,
}

impl Name {
    /// Explicitly converts a `&Name` to a `&str`.
    pub fn as_str(&self) -> &str {
        &self
    }

    fn new(path: Path) -> Name {
        Name {
            span: path.span(),
            name: path.into_token_stream().to_string(),
        }
    }
}

impl<T> From<T> for Name
where
    T: Into<String>,
{
    fn from(s: T) -> Name {
        Name {
            name: s.into(),
            span: Span::call_site(),
        }
    }
}

impl Deref for Name {
    type Target = str;

    fn deref(&self) -> &str {
        &self.name
    }
}

impl Spanned for Name {
    fn span(&self) -> Span {
        self.span
    }
}

impl FromMetaValue for Name {
    fn from_meta_value(p: ParseStream) -> Result<Self, Error> {
        Ok(Name::new(p.parse::<Path>()?))
    }
}

/// A helper type for parsing `FromMeta` values from `TokenStream`s.
pub struct Meta<T>(pub T);

impl<T> Meta<T> {
    /// Extracts the inner `T`.
    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T> Deref for Meta<T> {
    type Target = T;

    fn deref(&self) -> &T {
        &self.0
    }
}

impl<T> Parse for Meta<T>
where
    T: FromMeta,
{
    fn parse(p: ParseStream) -> Result<Self, Error> {
        T::from_meta(MetaStream::new(p)).map(|t| Meta(t))
    }
}

// All `FromMeta` values can also be `FromMetaValue` with the use of `{ }`
impl<T> FromMetaValue for T
where
    T: FromMeta,
{
    fn from_meta_value(p: ParseStream) -> Result<Self, Error> {
        let content;
        syn::braced!(content in p);

        T::from_meta(MetaStream::new(&content))
    }
}

// OTHER MISC IMPLEMENTATIONS
impl FromMetaValue for syn::LitStr {
    fn from_meta_value(p: ParseStream) -> Result<Self, Error> {
        p.parse::<syn::LitStr>()
    }
}