summaryrefslogtreecommitdiffstats
path: root/third_party/rust/darling/tests/defaults.rs
blob: 05ab1ed1dba3d482b8677016340d108dd4f443d2 (plain)
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
use darling::FromDeriveInput;
use syn::parse_quote;

mod foo {
    pub mod bar {
        pub fn init() -> String {
            String::from("hello")
        }
    }
}

#[derive(FromDeriveInput)]
#[darling(attributes(speak))]
pub struct SpeakerOpts {
    #[darling(default = "foo::bar::init")]
    first_word: String,
}

#[test]
fn path_default() {
    let speaker: SpeakerOpts = FromDeriveInput::from_derive_input(&parse_quote! {
        struct Foo;
    })
    .expect("Unit struct with no attrs should parse");

    assert_eq!(speaker.first_word, "hello");
}

/// Tests in this module capture the somewhat-confusing behavior observed when defaults
/// are set at both the field and container level.
///
/// The general rule is that more-specific declarations preempt less-specific ones; this is
/// unsurprising and allows for granular control over what happens when parsing an AST.
mod stacked_defaults {
    use darling::{FromDeriveInput, FromMeta};
    use syn::parse_quote;

    fn jane() -> String {
        "Jane".into()
    }

    #[derive(FromMeta)]
    #[darling(default)]
    struct PersonName {
        #[darling(default = "jane")]
        first: String,
        #[darling(default)]
        middle: String,
        last: String,
    }

    impl Default for PersonName {
        fn default() -> Self {
            Self {
                first: "John".into(),
                middle: "T".into(),
                last: "Doe".into(),
            }
        }
    }

    #[derive(FromDeriveInput)]
    #[darling(attributes(person))]
    struct Person {
        #[darling(default)]
        name: PersonName,
        age: u8,
    }

    #[test]
    fn name_first_only() {
        let person = Person::from_derive_input(&parse_quote! {
            #[person(name(first = "Bill"), age = 5)]
            struct Foo;
        })
        .unwrap();

        assert_eq!(person.name.first, "Bill");
        assert_eq!(
            person.name.middle, "",
            "Explicit field-level default should preempt container-level default"
        );
        assert_eq!(
            person.name.last, "Doe",
            "Absence of a field-level default falls back to container-level default"
        );
    }

    /// This is the most surprising case. The presence of `name()` means we invoke
    /// `PersonName::from_list(&[])`. When that finishes parsing each of the zero nested
    /// items it has received, it will then start filling in missing fields, using the
    /// explicit field-level defaults for `first` and `middle`, while for `last` it will
    /// use the `last` field from the container-level default.
    #[test]
    fn name_empty_list() {
        let person = Person::from_derive_input(&parse_quote! {
            #[person(name(), age = 5)]
            struct Foo;
        })
        .unwrap();

        assert_eq!(person.name.first, "Jane");
        assert_eq!(person.name.middle, "");
        assert_eq!(person.name.last, "Doe");
    }

    #[test]
    fn no_name() {
        let person = Person::from_derive_input(&parse_quote! {
            #[person(age = 5)]
            struct Foo;
        })
        .unwrap();

        assert_eq!(person.age, 5);
        assert_eq!(
            person.name.first, "John",
            "If `name` is not specified, `Person`'s field-level default should be used"
        );
        assert_eq!(person.name.middle, "T");
        assert_eq!(person.name.last, "Doe");
    }
}

mod implicit_default {
    use darling::{util::Flag, FromDeriveInput};
    use syn::parse_quote;

    // No use of `darling(default)` here at all!
    // This struct will fill in missing fields using FromMeta::from_none.
    #[derive(FromDeriveInput)]
    #[darling(attributes(person))]
    struct Person {
        first_name: String,
        last_name: Option<String>,
        lefty: Flag,
    }

    #[test]
    fn missing_fields_fill() {
        let person = Person::from_derive_input(&parse_quote! {
            #[person(first_name = "James")]
            struct Foo;
        })
        .unwrap();

        assert_eq!(person.first_name, "James");
        assert_eq!(person.last_name, None);
        assert!(!person.lefty.is_present());
    }
}

/// Test that a field-level implicit default using FromMeta::from_none is superseded
/// by the parent declaring `#[darling(default)]`.
mod overridden_implicit_default {
    use darling::{util::Flag, FromDeriveInput};
    use syn::parse_quote;

    #[derive(FromDeriveInput)]
    #[darling(default, attributes(person))]
    struct Person {
        first_name: String,
        last_name: Option<String>,
        lefty: Flag,
    }

    impl Default for Person {
        fn default() -> Self {
            Self {
                first_name: "Jane".into(),
                last_name: Some("Doe".into()),
                lefty: Flag::default(),
            }
        }
    }

    #[test]
    fn fill_missing() {
        let person = Person::from_derive_input(&parse_quote!(
            #[person(last_name = "Archer")]
            struct Foo;
        ))
        .unwrap();

        assert_eq!(person.first_name, "Jane");
        assert_eq!(person.last_name, Some("Archer".into()));
        assert!(!person.lefty.is_present());
    }
}