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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
use std::cell::RefCell;
use std::collections::hash_map::{Entry, HashMap};
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;

use ident_case;
use syn::{self, Lit, Meta, NestedMeta};

use {Error, Result};

/// Create an instance from an item in an attribute declaration.
///
/// # Implementing `FromMetaItem`
/// * Do not take a dependency on the `ident` of the passed-in meta item. The ident will be set by the field name of the containing struct.
/// * Implement only the `from_*` methods that you intend to support. The default implementations will return useful errors.
///
/// # Provided Implementations
/// ## bool
///
/// * Word with no value specified - becomes `true`.
/// * As a boolean literal, e.g. `foo = true`.
/// * As a string literal, e.g. `foo = "true"`.
///
/// ## String
/// * As a string literal, e.g. `foo = "hello"`.
/// * As a raw string literal, e.g. `foo = r#"hello "world""#`.
///
/// ## ()
/// * Word with no value specified, e.g. `foo`. This is best used with `Option`.
///   See `darling::util::Flag` for a more strongly-typed alternative.
///
/// ## Option
/// * Any format produces `Some`.
///
/// ## `Result<T, darling::Error>`
/// * Allows for fallible parsing; will populate the target field with the result of the
///   parse attempt.
pub trait FromMetaItem: Sized {
    fn from_nested_meta_item(item: &NestedMeta) -> Result<Self> {
        match *item {
            NestedMeta::Literal(ref lit) => Self::from_value(lit),
            NestedMeta::Meta(ref mi) => Self::from_meta_item(mi),
        }
    }

    /// Create an instance from a `syn::Meta` by dispatching to the format-appropriate
    /// trait function. This generally should not be overridden by implementers.
    fn from_meta_item(item: &Meta) -> Result<Self> {
        match *item {
            Meta::Word(_) => Self::from_word(),
            Meta::List(ref value) => Self::from_list(&value.nested.clone().into_iter().collect::<Vec<syn::NestedMeta>>()[..]),
            Meta::NameValue(ref value) => Self::from_value(&value.lit),
        }
    }

    /// Create an instance from the presence of the word in the attribute with no
    /// additional options specified.
    fn from_word() -> Result<Self> {
        Err(Error::unsupported_format("word"))
    }

    /// Create an instance from a list of nested meta items.
    #[allow(unused_variables)]
    fn from_list(items: &[NestedMeta]) -> Result<Self> {
        Err(Error::unsupported_format("list"))
    }

    /// Create an instance from a literal value of either `foo = "bar"` or `foo("bar")`.
    /// This dispatches to the appropriate method based on the type of literal encountered,
    /// and generally should not be overridden by implementers.
    fn from_value(value: &Lit) -> Result<Self> {
        match *value {
            Lit::Bool(ref b) => Self::from_bool(b.value),
            Lit::Str(ref s) => Self::from_string(&s.value()),
            ref _other => Err(Error::unexpected_type("other"))
        }
    }

    /// Create an instance from a char literal in a value position.
    #[allow(unused_variables)]
    fn from_char(value: char) -> Result<Self> {
        Err(Error::unexpected_type("char"))
    }

    /// Create an instance from a string literal in a value position.
    #[allow(unused_variables)]
    fn from_string(value: &str) -> Result<Self> {
        Err(Error::unexpected_type("string"))
    }

    /// Create an instance from a bool literal in a value position.
    #[allow(unused_variables)]
    fn from_bool(value: bool) -> Result<Self> {
        Err(Error::unexpected_type("bool"))
    }
}

// FromMetaItem impls for std and syn types.

impl FromMetaItem for () {
    fn from_word() -> Result<Self> {
        Ok(())
    }
}

impl FromMetaItem for bool {
    fn from_word() -> Result<Self> {
        Ok(true)
    }

    fn from_bool(value: bool) -> Result<Self> {
        Ok(value)
    }

    fn from_string(value: &str) -> Result<Self> {
        value.parse().or_else(|_| Err(Error::unknown_value(value)))
    }
}

impl FromMetaItem for AtomicBool {
    fn from_meta_item(mi: &Meta) -> Result<Self> {
        Ok(AtomicBool::new(FromMetaItem::from_meta_item(mi)?))
    }
}

impl FromMetaItem for String {
    fn from_string(s: &str) -> Result<Self> {
        Ok(s.to_string())
    }
}

impl FromMetaItem for u8 {
    fn from_string(s: &str) -> Result<Self> {
        s.parse().or_else(|_| Err(Error::unknown_value(s)))
    }
}

impl FromMetaItem for u16 {
    fn from_string(s: &str) -> Result<Self> {
        s.parse().or_else(|_| Err(Error::unknown_value(s)))
    }
}

impl FromMetaItem for u32 {
    fn from_string(s: &str) -> Result<Self> {
        s.parse().or_else(|_| Err(Error::unknown_value(s)))
    }
}

impl FromMetaItem for u64 {
    fn from_string(s: &str) -> Result<Self> {
        s.parse().or_else(|_| Err(Error::unknown_value(s)))
    }
}

impl FromMetaItem for usize {
    fn from_string(s: &str) -> Result<Self> {
        s.parse().or_else(|_| Err(Error::unknown_value(s)))
    }
}

impl FromMetaItem for i8 {
    fn from_string(s: &str) -> Result<Self> {
        s.parse().or_else(|_| Err(Error::unknown_value(s)))
    }
}

impl FromMetaItem for i16 {
    fn from_string(s: &str) -> Result<Self> {
        s.parse().or_else(|_| Err(Error::unknown_value(s)))
    }
}

impl FromMetaItem for i32 {
    fn from_string(s: &str) -> Result<Self> {
        s.parse().or_else(|_| Err(Error::unknown_value(s)))
    }
}

impl FromMetaItem for i64 {
    fn from_string(s: &str) -> Result<Self> {
        s.parse().or_else(|_| Err(Error::unknown_value(s)))
    }
}

impl FromMetaItem for isize {
    fn from_string(s: &str) -> Result<Self> {
        s.parse().or_else(|_| Err(Error::unknown_value(s)))
    }
}

impl FromMetaItem for syn::Ident {
    fn from_string(value: &str) -> Result<Self> {
        Ok(syn::Ident::new(value, ::proc_macro2::Span::call_site()))
    }
}

impl FromMetaItem for syn::Path {
    fn from_string(value: &str) -> Result<Self> {
        Ok(syn::parse_str::<syn::Path>(value).unwrap())
    }
}
/*
impl FromMetaItem for syn::TypeParamBound {
    fn from_string(value: &str) -> Result<Self> {
        Ok(syn::TypeParamBound::from(value))
    }
}
*/

impl FromMetaItem for syn::Meta {
    fn from_meta_item(value: &syn::Meta) -> Result<Self> {
        Ok(value.clone())
    }
}

impl FromMetaItem for syn::WhereClause {
    fn from_string(value: &str) -> Result<Self> {
        let ret: syn::WhereClause = syn::parse_str(value).unwrap();
        Ok(ret)
    }
}

impl FromMetaItem for Vec<syn::WherePredicate> {
    fn from_string(value: &str) -> Result<Self> {
        syn::WhereClause::from_string(&format!("where {}", value)).map(|c| c.predicates.into_iter().collect())
    }
}

impl FromMetaItem for ident_case::RenameRule {
    fn from_string(value: &str) -> Result<Self> {
        value.parse().or_else(|_| Err(Error::unknown_value(value)))
    }
}

impl<T: FromMetaItem> FromMetaItem for Option<T> {
    fn from_meta_item(item: &Meta) -> Result<Self> {
        Ok(Some(FromMetaItem::from_meta_item(item)?))
    }
}

impl<T: FromMetaItem> FromMetaItem for Box<T> {
    fn from_meta_item(item: &Meta) -> Result<Self> {
        Ok(Box::new(FromMetaItem::from_meta_item(item)?))
    }
}

impl<T: FromMetaItem> FromMetaItem for Result<T> {
    fn from_meta_item(item: &Meta) -> Result<Self> {
        Ok(FromMetaItem::from_meta_item(item))
    }
}

/// Parses the meta-item, and in case of error preserves a copy of the input for
/// later analysis.
impl<T: FromMetaItem> FromMetaItem for ::std::result::Result<T, Meta> {
    fn from_meta_item(item: &Meta) -> Result<Self> {
        T::from_meta_item(item).map(Ok).or_else(|_| Ok(Err(item.clone())))
    }
}

impl<T: FromMetaItem> FromMetaItem for Rc<T> {
    fn from_meta_item(item: &Meta) -> Result<Self> {
        Ok(Rc::new(FromMetaItem::from_meta_item(item)?))
    }
}

impl<T: FromMetaItem> FromMetaItem for Arc<T> {
    fn from_meta_item(item: &Meta) -> Result<Self> {
        Ok(Arc::new(FromMetaItem::from_meta_item(item)?))
    }
}

impl<T: FromMetaItem> FromMetaItem for RefCell<T> {
    fn from_meta_item(item: &Meta) -> Result<Self> {
        Ok(RefCell::new(FromMetaItem::from_meta_item(item)?))
    }
}

impl<V: FromMetaItem> FromMetaItem for HashMap<String, V> {
    fn from_list(nested: &[syn::NestedMeta]) -> Result<Self> {
        let mut map = HashMap::with_capacity(nested.len());
        for item in nested {
            if let syn::NestedMeta::Meta(ref inner) = *item {
                match map.entry(inner.name().to_string()) {
                    Entry::Occupied(_) => return Err(Error::duplicate_field(inner.name().as_ref())),
                    Entry::Vacant(entry) => {
                        entry.insert(
                            FromMetaItem::from_meta_item(inner).map_err(|e| e.at(inner.name()))?
                        );
                    }
                }
            }
        }

        Ok(map)
    }
}

/// Tests for `FromMetaItem` implementations. Wherever the word `ignore` appears in test input,
/// it should not be considered by the parsing.
#[cfg(test)]
mod tests {
    use syn;
    use quote::Tokens;

    use {FromMetaItem, Result};

    /// parse a string as a syn::Meta instance.
    fn pmi(tokens: Tokens) -> ::std::result::Result<syn::Meta, String> {
        let attribute: syn::Attribute = parse_quote!(#[#tokens]);
        attribute.interpret_meta().ok_or("Unable to parse".into())
    }

    fn fmi<T: FromMetaItem>(tokens: Tokens) -> T {
        FromMetaItem::from_meta_item(&pmi(tokens).expect("Tests should pass well-formed input"))
            .expect("Tests should pass valid input")
    }

    #[test]
    fn unit_succeeds() {
        assert_eq!(fmi::<()>(quote!(ignore)), ());
    }

    #[test]
    fn bool_succeeds() {
        // word format
        assert_eq!(fmi::<bool>(quote!(ignore)), true);

        // bool literal
        assert_eq!(fmi::<bool>(quote!(ignore = true)), true);
        assert_eq!(fmi::<bool>(quote!(ignore = false)), false);

        // string literals
        assert_eq!(fmi::<bool>(quote!(ignore = "true")), true);
        assert_eq!(fmi::<bool>(quote!(ignore = "false")), false);
    }

    #[test]
    fn string_succeeds() {
        // cooked form
        assert_eq!(&fmi::<String>(quote!(ignore = "world")), "world");

        // raw form
        assert_eq!(&fmi::<String>(quote!(ignore = r#"world"#)), "world");
    }

    #[test]
    fn number_succeeds() {
        assert_eq!(fmi::<u8>(quote!(ignore = "2")), 2u8);
        assert_eq!(fmi::<i16>(quote!(ignore="-25")), -25i16);
    }

    #[test]
    fn meta_item_succeeds() {
        use syn::Meta;

        assert_eq!(fmi::<Meta>(quote!(hello(world,today))), pmi(quote!(hello(world,today))).unwrap());
    }

    #[test]
    fn hash_map_succeeds() {
        use std::collections::HashMap;

        let comparison = {
            let mut c = HashMap::new();
            c.insert("hello".to_string(), true);
            c.insert("world".to_string(), false);
            c.insert("there".to_string(), true);
            c
        };

        assert_eq!(fmi::<HashMap<String, bool>>(quote!(ignore(hello, world = false, there = "true"))), comparison);
    }

    /// Tests that fallible parsing will always produce an outer `Ok` (from `fmi`),
    /// and will accurately preserve the inner contents.
    #[test]
    fn darling_result_succeeds() {
        fmi::<Result<()>>(quote!(ignore)).unwrap();
        fmi::<Result<()>>(quote!(ignore(world))).unwrap_err();
    }
}