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
use proc_macro::TokenStream;
use proc_macro_error::proc_macro_error;

#[cfg(any(feature = "extruct_from", doc))]
mod extruct_from;
#[cfg(any(feature = "fields", doc))]
mod fields;

/// A derive macro implements the [`Fields`](trait.Fields.html) trait for a struct.
///
/// [`Fields`] can annotate a named struct, a unit struct or an empty unnamed
/// (tuple-like) struct, including generic structs.
/// It collects names of the fields from the struct definition and represents
/// them as a list of string literals accessible through [`Fields::fields()`](trait.Fields.html#tymethod.fields).
///
/// ```rust
/// # use extruct_core as extruct;
/// # use extruct::Fields;
/// # use extruct_macros::Fields;
/// #[derive(Fields)]
/// struct NamedStruct {
///     one: String,
///     two: u32,
///     three: char,
/// }
/// assert_eq!(NamedStruct::fields(), ["one", "two", "three"]);
/// ```
#[cfg(any(feature = "fields", doc))]
#[proc_macro_error]
#[proc_macro_derive(Fields)]
pub fn get_struct_fields(item: TokenStream) -> TokenStream {
    let ast = fields::parse(item.into());
    let model = fields::analyze(ast);
    let code = fields::codegen(model);

    code.into()
}

/// An attribute macro implements the [`std::convert::From`](https://doc.rust-lang.org/std/convert/trait.From.html)
/// trait for an annotated non-generic named struct using a "superstruct" specified as
/// the attribute parameter as a source type.
///
/// [`extruct_from`](macro@extruct_from) accepts a single parameter which is a non-generic type name referring
/// to a named struct.
///
/// ```rust
/// # use extruct_macros::extruct_from;
/// struct SuperStruct {
///     one_field: String,
///     another_field: u32,
///     and_one_more: char,
/// }
///
/// #[extruct_from(SuperStruct)]
/// struct SubStruct {
///     and_one_more: String,
/// }
///
/// let sup = SuperStruct {
///     one_field: "str".to_owned(),
///     another_field: 1135,
///     and_one_more: 'x',
/// };
///
/// let sub: SubStruct = sup.into();
/// ```
#[cfg(any(feature = "extruct_from", doc))]
#[proc_macro_error]
#[proc_macro_attribute]
pub fn extruct_from(attr: TokenStream, item: TokenStream) -> TokenStream {
    let ast = extruct_from::parse(attr.into(), item.into());
    let model = extruct_from::analyze(ast);
    let code = extruct_from::codegen(model);

    code.into()
}