1
//! Common macro elements for deriving parsers and encoders
2

            
3
use derive_deftly::{define_derive_deftly, define_derive_deftly_module};
4

            
5
define_derive_deftly! {
6
    /// Defines a constructor struct and method
7
    //
8
    // TODO maybe move this out of tor-netdoc, to a lower-level dependency
9
    ///
10
    /// "Constructor" is a more lightweight alternative to the builder pattern.
11
    ///
12
    /// # Comparison to builders
13
    ///
14
    ///  * Suitable for transparent, rather than opaque, structs.
15
    ///  * Missing fields during construction are detected at compile-time.
16
    ///  * Construction is infallible at runtime.
17
    ///  * Making a previously-required field optional is an API break.
18
    ///
19
    /// # Input
20
    ///
21
    ///  * `struct Thing`.  (enums and unions are not supported.)
22
    ///
23
    ///  * Each field must impl `Default` or be annotated `#[deftly(constructor)]`
24
    ///
25
    ///  * `Thing` must contain `#[doc(hidden)] pub __non_exhaustive: ()`
26
    ///    rather than being `#[non_exhaustive]`.
27
    ///    (Because struct literal syntax is not available otherwise.)
28
    ///
29
    /// # Generated items
30
    ///
31
    ///  * **`pub struct ThingConstructor`**:
32
    ///    contains all the required (non-optional) fields from `Thing`.
33
    ///    `ThingConstructor` is `exhaustive`.
34
    ///
35
    ///  * **`fn ThingConstructor::construct(self) -> Thing`**:
36
    ///    fills in all the default values.
37
    ///
38
    ///  * `impl From<ThingConstructor> for Thing`
39
    ///
40
    /// # Attributes
41
    ///
42
    /// ## Field attributes
43
    ///
44
    ///  * **`#[deftly(constructor)]`**:
45
    ///    Include this field in `ThingConstructor`.
46
    ///    The caller must provide a value.
47
    ///
48
    ///  * **`#[deftly(constructor(default = EXPR))]`**:
49
    ///    Instead of `Default::default()`, the default value is EXPR.
50
    ///    EXPR cannot refer to anything in `ThingConstructor`.
51
    //     If we want that we would need to invent a feature for it.
52
    ///
53
    /// # Example
54
    ///
55
    /// ```
56
    /// use derive_deftly::Deftly;
57
    /// use tor_netdoc::derive_deftly_template_Constructor;
58
    ///
59
    /// #[derive(Deftly, PartialEq, Debug)]
60
    /// #[derive_deftly(Constructor)]
61
    /// #[allow(clippy::exhaustive_structs)]
62
    /// pub struct Thing {
63
    ///     /// Required field
64
    ///     #[deftly(constructor)]
65
    ///     pub required: i32,
66
    ///
67
    ///     /// Optional field
68
    ///     pub optional: Option<i32>,
69
    ///
70
    ///     /// Optional field with fixed default
71
    ///     #[deftly(constructor(default = 7))]
72
    ///     pub defaulted: i32,
73
    ///
74
    ///     #[doc(hidden)]
75
    ///     pub __non_exhaustive: (),
76
    /// }
77
    ///
78
    /// let thing = Thing {
79
    ///     optional: Some(23),
80
    ///     ..ThingConstructor {
81
    ///         required: 12,
82
    ///     }.construct()
83
    /// };
84
    ///
85
    /// assert_eq!(
86
    ///     thing,
87
    ///     Thing {
88
    ///         required: 12,
89
    ///         optional: Some(23),
90
    ///         defaulted: 7,
91
    ///         __non_exhaustive: (),
92
    ///     }
93
    /// );
94
    /// ```
95
    ///
96
    /// # Note
97
    export Constructor for struct, meta_quoted rigorous, beta_deftly:
98

            
99
    ${define CONSTRUCTOR_NAME $<$tname Constructor>}
100
    ${define CONSTRUCTOR $<$ttype Constructor>}
101

            
102
    ${defcond F_DEFAULT_EXPR fmeta(constructor(default))}
103
    ${defcond F_DEFAULT_TRAIT not(fmeta(constructor))}
104
    ${defcond F_REQUIRED not(any(F_DEFAULT_EXPR, F_DEFAULT_TRAIT))}
105

            
106
    ${for fields {
107
        ${loop_exactly_1 "need a `__non_exhaustive` field (instead of `#[non_exhaustive]`"}
108
        ${when all(
109
            approx_equal($fname, __non_exhaustive),
110
            approx_equal({}, ${tattrs non_exhaustive}),
111
        )}
112
    }}
113

            
114
    $/// Constructor (required fields) for `$tname`
115
    $///
116
    $/// See [`$tname`].
117
    $///
118
    $/// This constructor struct contains precisely the required fields.
119
    $/// You can make a `$tname` out of it with [`.construct()`]($CONSTRUCTOR_NAME::construct),
120
    $/// or the `From` impl,
121
    $/// and use the result as a basis for further modifications.
122
    $///
123
    $/// # Example
124
    $///
125
    $/// ```rust,ignore
126
    $/// let ${snake_case $tname} = $tname {
127
  ${for fields { ${when any(fmeta(constructor(default)), not(fmeta(constructor)))}
128
    $///     $fname: /* optional field value */,
129
  }}
130
    $///     ..$CONSTRUCTOR_NAME {
131
  ${for fields { ${when not(any(fmeta(constructor(default)), not(fmeta(constructor))))}
132
    $///         $fname: /* required field value */,
133
  }}
134
    $///     }.construct()
135
    $/// };
136
    $/// ```
137
    #[allow(clippy::exhaustive_structs)]
138
    $tvis struct $CONSTRUCTOR_NAME<$tdefgens> where $twheres { $(
139
        ${when F_REQUIRED}
140

            
141
        ${fattrs doc}
142
        $fdefvis $fname: $ftype,
143
    ) }
144

            
145
    impl<$tgens> $CONSTRUCTOR where $twheres {
146
        $/// Construct a minimal `$tname`
147
        $///
148
        $/// In the returned [`$tname`],
149
        $/// optional fields all get the default values.
150
2
        $tvis fn construct(self) -> $ttype {
151
            $tname { $(
152
                $fname: ${select1
153
                    F_REQUIRED {
154
                        self.$fname
155
                    }
156
                    F_DEFAULT_TRAIT {
157
                        <$ftype as ::std::default::Default>::default()
158
                    }
159
                    F_DEFAULT_EXPR {
160
                        ${fmeta(constructor(default)) as expr}
161
                    }
162
                },
163
            ) }
164
        }
165
    }
166

            
167
    impl<$tgens> From<$CONSTRUCTOR> for $ttype where $twheres {
168
        fn from(constructor: $CONSTRUCTOR) -> $ttype {
169
            constructor.construct()
170
        }
171
    }
172
}
173

            
174
/// Macro to help check that netdoc items in a derive input are in the right order
175
///
176
/// Used only by the `NetdocParseable` derive-deftly macro.
177
#[doc(hidden)]
178
#[macro_export]
179
macro_rules! netdoc_ordering_check {
180
    { } => { compile_error!("netdoc must have an intro item so cannot be empty"); };
181

            
182
    // When we have   K0 P0 K1 P1 ...
183
    //   * Check that P0 and P1 have a consistent ordr
184
    //   * Continue with   K1 P1 ...
185
    // So we check each consecutive pair of fields.
186
    { $k0:ident $f0:ident $k1:ident $f1:ident $($rest:tt)* } => {
187
        $crate::netdoc_ordering_check! { <=? $k0 $k1 $f1 }
188
        $crate::netdoc_ordering_check! { $k1 $f1 $($rest)* }
189
    };
190
    { $k0:ident $f0:ident } => {}; // finished
191

            
192
    // Individual ordering checks for K0 <=? K1
193
    //
194
    // We write out each of the allowed this-kind next-kind combinations:
195
    { <=? intro     $any:ident $f1:ident } => {};
196
    { <=? normal    normal     $f1:ident } => {};
197
    { <=? normal    subdoc     $f1:ident } => {};
198
    { <=? subdoc    subdoc     $f1:ident } => {};
199
    // Not in the allowed list, must be an error:
200
    { <=? $k0:ident $k1:ident  $f1:ident } => {
201
        compile_error!(concat!(
202
            "in netdoc, ", stringify!($k1)," field ", stringify!($f1),
203
            " may not come after ", stringify!($k0),
204
        ));
205
    };
206
}
207

            
208
define_derive_deftly_module! {
209
    /// Common definitions for any netdoc derives
210
    NetdocDeriveAnyCommon beta_deftly:
211

            
212
    // Emit an eprintln with deftly(netdoc(debug)), just so that we don't get surprises
213
    // where someone leaves a (debug) in where it's not implemented, and we later implement it.
214
    ${define EMIT_DEBUG_PLACEHOLDER {
215
        ${if tmeta(netdoc(debug)) {
216
            use std::io::Write as _;
217

            
218
            // This messing about with std::io::stderr() mirrors netdoc_parseable_derive_debug.
219
            // (We could use eprintln! #[test] captures eprintln! but not io::stderr.)
220
            writeln!(
221
                std::io::stderr().lock(),
222
                ${concat "#[deftly(netdoc(debug))] applied to " $tname},
223
            ).expect("write to stderr failed");
224
        }}
225
    }}
226
    ${define DOC_DEBUG_PLACEHOLDER {
227
        /// * **`#[deftly(netdoc(debug))]`**:
228
        ///
229
        ///   Currently implemented only as a placeholder
230
        ///
231
        ///   The generated implementation may in future generate copious debug output
232
        ///   to the program's stderr when it is run.
233
        ///   Do not enable in production!
234
    }}
235
}
236

            
237
define_derive_deftly_module! {
238
    /// Common definitions for derives of structs containing items
239
    ///
240
    /// Used by `NetdocParseable`, `NetdocParseableFields`,
241
    /// `NetdocEncodable` and `NetdocEncodableFields`.
242
    ///
243
    /// Importing template must define these:
244
    ///
245
    ///  * **`F_INTRO`**, **`F_SUBDOC`**, **`F_SIGNATURE`**
246
    ///    conditions for the fundamental field kinds which aren't supported everywhere.
247
    ///
248
    ///    The `F_FLATTEN`, `F_SKIP`, `F_NORMAL` field type conditions are defined here.
249
    ///
250
    /// Importer must also import `NetdocDeriveAnyCommon`.
251
    //
252
    // We have the call sites import the other modules, rather than using them here, because:
253
    //  - This avoids the human reader having to chase breadcrumbs
254
    //    to find out what a particular template is using.
255
    //  - The dependency graph is not a tree, so some things would be included twice
256
    //    and derive-deftly cannot deduplicate them.
257
    NetdocSomeItemsDeriveCommon beta_deftly:
258

            
259
    // Is this field `flatten`?
260
    ${defcond F_FLATTEN fmeta(netdoc(flatten))}
261
    // Is this field `skip`?
262
    ${defcond F_SKIP fmeta(netdoc(skip))}
263
    // Is this field normal (non-structural)?
264
    ${defcond F_NORMAL not(any(F_SIGNATURE, F_INTRO, F_FLATTEN, F_SUBDOC, F_SKIP))}
265

            
266
    // Field keyword as `&str`
267
    ${define F_KEYWORD_STR { ${concat
268
        ${if any(F_FLATTEN, F_SUBDOC, F_SKIP) {
269
          ${if F_INTRO {
270
            ${error "#[deftly(netdoc(subdoc))] (flatten) and (skip) not supported for intro items"}
271
          } else {
272
            // Sub-documents and flattened fields have their keywords inside;
273
            // if we ask for the field-based keyword name for one of those then that's a bug.
274
            ${error "internal error, subdoc or skip KeywordRef"}
275
          }}
276
        }}
277
        ${fmeta(netdoc(keyword)) as str,
278
          default ${concat ${kebab_case $fname}}}
279
    }}}
280
    // Field keyword as `&str` for debugging and error reporting
281
    ${define F_KEYWORD_REPORT ${concat
282
        ${if any(F_FLATTEN, F_SUBDOC, F_SKIP) { $fname }
283
             else { $F_KEYWORD_STR }}
284
    }}
285
    // Field keyword as `KeywordRef`
286
    ${define F_KEYWORD { (KeywordRef::new_const($F_KEYWORD_STR)) }}
287
}
288

            
289
define_derive_deftly_module! {
290
    /// Common definitions for derives of whole network documents
291
    ///
292
    /// Used by `NetdocParseable` and `NetdocEncodable`.
293
    ///
294
    /// Importer must also import `NetdocSomeItemsDeriveCommon` and `NetdocDeriveAnyCommon`.
295
    NetdocEntireDeriveCommon beta_deftly:
296

            
297
    // Predicate for the toplevel
298
    ${defcond T_SIGNATURES false}
299

            
300
    // Predicates for the field kinds
301
    ${defcond F_INTRO approx_equal($findex, 0)}
302
    ${defcond F_SUBDOC fmeta(netdoc(subdoc))}
303
    ${defcond F_SIGNATURE T_SIGNATURES} // signatures section documents have only signature fields
304

            
305
    // compile-time check that fields are in the right order in the struct
306
    ${define FIELD_ORDERING_CHECK {
307
        ${if not(T_SIGNATURES) { // signatures structs have only signature fields
308
          netdoc_ordering_check! {
309
            $(
310
                ${when not(F_SKIP)}
311

            
312
                ${select1
313
                  F_INTRO     { intro     }
314
                  F_NORMAL    { normal    }
315
                  F_FLATTEN   { normal    }
316
                  F_SUBDOC    { subdoc    }
317
                }
318
                $fname
319
            )
320
          }
321
        }}
322
    }}
323
}
324

            
325
define_derive_deftly_module! {
326
    /// Common definitions for derives of flattenable network document fields structs
327
    ///
328
    /// Used by `NetdocParseableFields` and `NetdocEncodableFields`.
329
    ///
330
    /// Importer must also import `NetdocSomeItemsDeriveCommon` and `NetdocDeriveAnyCommon`.
331
    NetdocFieldsDeriveCommon beta_deftly:
332

            
333
    // Predicates for the field kinds, used by NetdocSomeItemsDeriveCommon etc.
334
    ${defcond F_INTRO false}
335
    ${defcond F_SUBDOC false}
336
    ${defcond F_SIGNATURE false}
337

            
338
    ${define DOC_NETDOC_FIELDS_DERIVE_SUPPORTED {
339
        ///  * The input struct can contain only normal non-structural items
340
        ///    (so it's not a sub-document with an intro item).
341
        ///  * The only attributes supported are the field attributes
342
        ///    `#[deftly(netdoc(keyword = STR))]`
343
        ///    `#[deftly(netdoc(default))]`
344
        ///    `#[deftly(netdoc(single_arg))]`
345
        ///    `#[deftly(netdoc(with = MODULE))]`
346
        ///    `#[deftly(netdoc(flatten))]`
347
        ///    `#[deftly(netdoc(skip))]`
348
    }}
349
}
350

            
351
define_derive_deftly_module! {
352
    /// Common definitions for derives of network document item value structs
353
    ///
354
    /// Used by `ItemValueParseable` and `ItemValueEncodable`.
355
    ///
356
    /// Importer must also import `NetdocDeriveAnyCommon`.
357
    NetdocItemDeriveCommon beta_deftly:
358

            
359
    ${defcond F_REST fmeta(netdoc(rest))}
360
    ${defcond F_OBJECT fmeta(netdoc(object))}
361
    ${defcond F_SKIP fmeta(netdoc(skip))}
362
    ${defcond F_NORMAL not(any(F_REST, F_OBJECT, F_SKIP))}
363

            
364
    ${defcond T_IS_SIGNATURE tmeta(netdoc(signature))}
365
}