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
//! This module provides the `assign!` macro to allow mutating a struct value in
//! a declarative style.
//!
//! It is an alternative to [struct update syntax][] that works with
//! [non-exhaustive][] structs.
//!
//! [struct update syntax]: https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax
//! [non-exhaustive]: https://doc.rust-lang.org/reference/attributes/type_system.html#the-non_exhaustive-attribute
//!
//! It is used as
//!
//! ```
//! # use assign::assign;
//! # struct Struct { field: u8 }
//! # let init_expression = Struct { field: 0 };
//! # let new_field_value = 1;
//! let foo = assign!(init_expression, {
//!     field: new_field_value,
//!     // other_field: new_other_field_value,
//!     // ...
//! });
//! ```
//!
//! For details and examples, see the documentation for the macro itself.
#![no_std]

/// Mutate a struct value in a declarative style.
///
/// # Basic usage
///
/// ```
/// # use assign::assign;
/// #
/// #[non_exhaustive]
/// #[derive(Debug, PartialEq)]
/// struct SomeStruct {
///     a: u32,
///     b: Option<f32>,
///     c: String,
/// }
///
/// impl SomeStruct {
///     fn new() -> Self {
///         // ...
/// #       SomeStruct {
/// #           a: 1u32,
/// #           b: None,
/// #           c: String::from("old"),
/// #       }
///     }
/// }
///
/// let instance1 = assign!(SomeStruct::new(), {
///     a: 2,
///     c: "new".into(),
/// });
///
/// // The same thing using mutation explicitly.
/// // This is what the above expands to.
/// let instance2 = {
///     let mut item = SomeStruct::new();
///     item.a = 2;
///     item.c = "new".into();
///     item
/// };
///
/// // The same thing using struct update syntax (does not work for
/// // non-exhaustive structs defined in external crates).
/// let instance3 = SomeStruct {
///     a: 2,
///     c: "new".into(),
///     ..SomeStruct::new()
/// };
///
/// assert_eq!(instance1, instance2);
/// assert_eq!(instance1, instance3);
/// ```
///
/// # Slightly more realistic example
///
/// ```
/// # struct Arg {}
/// # impl Arg { fn new(_opt: ArgOptions) -> Self { Self {} } }
/// // in awesome_cli_lib
/// #[non_exhaustive]
/// # #[derive(Default)]
/// struct ArgOptions {
///     pub name: String,
///     pub short: Option<String>,
///     pub long: Option<String>,
///     pub help: Option<String>,
///     pub required: bool,
///     pub takes_value: bool,
///     pub multiple: bool,
///     pub default_value: Option<String>,
/// }
///
/// impl ArgOptions {
///     pub fn new(name: String) -> Self {
///         // ...
/// #       Self { name, ..Default::default() }
///     }
/// }
///
/// // your crate
/// use assign::assign;
///
/// let arg = Arg::new(assign!(ArgOptions::new("version".into()), {
///     short: Some("V".into()),
///     long: Some("version".into()),
///     help: Some("prints the version and quits.".into()),
/// }));
/// ```
#[macro_export]
macro_rules! assign {
    ($initial_value:expr, {
        $( $field:ident $( : $value:expr )? ),+ $(,)?
    }) => ({
        let mut item = $initial_value;
        $( $crate::assign!(@assign item $field $( : $value )?); )+
        item
    });
    (@assign $item:ident $field:ident : $value:expr) => {
        $item.$field = $value;
    };
    (@assign $item:ident $field:ident) => {
        $item.$field = $field;
    };
}

#[cfg(test)]
mod tests {
    #[derive(Debug, Default, PartialEq)]
    struct SomeStruct {
        a: u32,
        b: Option<f32>,
        c: Option<u64>,
    }

    #[test]
    fn basic() {
        let res = assign!(SomeStruct::default(), {
            a: 5,
            b: None,
        });

        assert_eq!(
            res,
            SomeStruct {
                a: 5,
                b: None,
                c: None
            }
        );
    }

    #[test]
    fn shorthand() {
        let def = SomeStruct::default();
        let a = 5;
        let res = assign!(def, { a });

        assert_eq!(
            res,
            SomeStruct {
                a: 5,
                b: None,
                c: None
            }
        );
    }

    #[test]
    fn field_expr_inference() {
        let b = 0.0.into();
        let res = assign!(SomeStruct::default(), {
            b,
            c: 1.into(),
        });

        assert_eq!(
            res,
            SomeStruct {
                a: 0,
                b: Some(0.0),
                c: Some(1)
            }
        );
    }

    #[test]
    fn all_fields() {
        let a = 1;
        let b = Some(1.0);

        let res = assign!(SomeStruct::default(), {
            a,
            b,
            c: 1.into(),
        });

        assert_eq!(
            res,
            SomeStruct {
                a: 1,
                b: Some(1.0),
                c: Some(1),
            }
        );
    }
}