1
//! Deriving `NetdocParseable`
2

            
3
use super::*;
4

            
5
//==================== Common definitions used by many of the macros ====================
6

            
7
/// Helper to implemnet `dtrace!` inside `NetdocParseable` derive-deftly macro.
8
#[doc(hidden)]
9
#[allow(clippy::print_stderr)]
10
54
pub fn netdoc_parseable_derive_debug(ttype: &str, msg: &str, vals: &[&dyn Debug]) {
11
    // We use `eprintln!` so that the output is captured as expected under cargo test.
12
    // We buffer the output into a string so that it a;ll appears at once,
13
    // rather than possibly being interleaved with similar output for other types.
14
54
    let mut out = String::new();
15
54
    (|| {
16
54
        write!(out, "netdoc {ttype} parse: {msg}")?;
17
54
        for val in vals {
18
99
            write!(out, ", {val:?}")?;
19
        }
20
54
        writeln!(out)
21
    })()
22
54
    .expect("write to string failed");
23

            
24
54
    eprint!("{out}");
25
54
}
26

            
27
define_derive_deftly_module! {
28
    /// Common definitions for all parsing macros.
29
    NetdocParseAnyCommon beta_deftly:
30

            
31
    // Convenience alias for our prelude
32
    ${define P { $crate::parse2::internal_prelude }}
33

            
34
    // Defines the `dtrace` macro.
35
    ${define DEFINE_DTRACE {
36
        #[allow(unused_macros)]
37
        macro_rules! dtrace { { $$msg:literal $$(, $$val:expr )* $$(,)? } => {
38
          ${if tmeta(netdoc(debug)) {
39
              $P::netdoc_parseable_derive_debug(
40
                  ${concat $ttype},
41
                  $$msg,
42
                  &[ $$( &&$$val as _, )* ],
43
              )
44
          }}
45
        }}
46
    }}
47
}
48

            
49
define_derive_deftly_module! {
50
    /// Common definitions for `NetdocParseableFields` and `NetdocParseableSignatures`
51
    NetdocFieldsParseableCommon beta_deftly:
52

            
53
    ${define DEFINE_IS_ITEM_KEYWORD {
54
12345069
        fn is_item_keyword(
55
12345069
            #[allow(unused_variables)] // If there are no fields, this is unused
56
12345069
            kw: $P::KeywordRef<'_>,
57
12345069
        ) -> bool {
58
            #[allow(unused_imports)] // false positives in some situations
59
            use $P::*;
60

            
61
          ${for fields {
62
            ${when not(F_FLATTEN)}
63
            ${when not(F_SKIP)}
64
            kw == $F_KEYWORD ||
65
          }}
66
          ${for fields {
67
            ${when F_FLATTEN}
68
            ${when not(F_SKIP)}
69
            <$ftype as NetdocParseableFields>::is_item_keyword(kw) ||
70
          }}
71
            false
72
        }
73
    }}
74
}
75

            
76
define_derive_deftly_module! {
77
    /// Common definitions for `NetdocParseable`, `NetdocParseableFields`,
78
    /// and `NetdocParseableSignatures`
79
    ///
80
    /// The including macro is expected to define:
81
    ///
82
    ///  * **`ITEM_STREAM`**: The input `ItemStream<'_>`.
83
    ///
84
    ///  * **`THIS_ITEM`**: consumes the next item and evaluates to it as an `UnparsedItem`.
85
    ///    See the definition in `NetdocParseable`.
86
    ///
87
    ///  * **`F_ACCUMULATE_VAR`** the variable or field into which to accumulate
88
    ///    normal items for this field.  Must be of type `&mut $F_ACCUMULATE_TYPE`.
89
    ///
90
    /// Importer must also import `NetdocSomeItemsDeriveCommon` and `NetdocDeriveAnyCommon`.
91
    NetdocSomeItemsParseableCommon beta_deftly:
92

            
93
    // The effective field type for parsing.
94
    //
95
    // Handles #[deftly(netdoc(default))], in which case we parse as if the field was Option,
96
    // and substitute in the default at the end.
97
    //
98
    ${define F_EFFECTIVE_TYPE {
99
        ${if all(fmeta(netdoc(default))) {
100
            Option::<$ftype>
101
        } else {
102
            $ftype
103
        }}
104
    }}
105

            
106
    // Provide `$<selector_ $fname>` for every (suitable) field.
107
    ${define ITEM_SET_SELECTORS {
108
        $(
109
          ${when not(any(F_FLATTEN, F_SKIP))}
110

            
111
          // See `mod multiplicity`.
112
        ${if not(all(F_INTRO, fmeta(netdoc(with)))) {
113
          // If the intro it has `with`, we don't check its trait impl, and this ends up unused
114
          let $<selector_ $fname> = $F_SELECTOR_VALUE;
115
        }}
116
        )
117
    }}
118
    // The item set selector for this field.
119
    // We must provide this, rather than expanding $<selector_ $fname> at the use sites,
120
    // because the identifier `selector_` has different macro_rules hygiene here vs there!
121
    // TODO derive-deftly#130
122
23626723
    ${define F_SELECTOR $<selector_ $fname>}
123
    // The selector value for this field.  Used where we don't want to bind a selector
124
    // for every field with $ITEM_SET_SELECTORS (and within $ITEM_SET_SELECTORS).
125
    ${define F_SELECTOR_VALUE {( MultiplicitySelector::<$F_EFFECTIVE_TYPE>::default() )}}
126
    // Check that every field type implements the necessary trait.
127
    ${define CHECK_FIELD_TYPES_PARSEABLE {
128
        $(
129
          ${when not(any(F_FLATTEN, F_SKIP))}
130

            
131
          // Expands to `selector_FIELD.check_SOMETHING();`
132
          //
133
          // If the relevant trait isn't implemented, rustc reports the error by
134
          // pointing at the `check-something` call.  We re-span that identifier
135
          // to point to the field name, so that's where the error is reported.
136
          //
137
          // Without this, we just get a report that `item` doesn't implement the required
138
          // trait - but `item` is a local variable here, so the error points into the macro
139
        ${if not(all(any(F_INTRO, F_NORMAL), fmeta(netdoc(with)))) {
140
          $<selector_ $fname> . ${paste_spanned $fname ${select1
141
                  any(F_INTRO, F_NORMAL){
142
                      // For the intro item, this is not completely precise, because the
143
                      // it will allow Option<> and Vec<> which aren't allowed there.
144
                      ${if
145
                        fmeta(netdoc(single_arg)) { check_item_argument_parseable }
146
                        else { check_item_value_parseable }
147
                      }
148
                  }
149
                  F_SIGNATURE { check_signature_item_parseable }
150
                  F_SUBDOC    { check_subdoc_parseable         }
151
          }} (
152
              ${if F_SIGNATURE { sig_hashes, }}
153
          );
154
        }}
155
        )
156
    }}
157

            
158
    // Convert the UnparsedItem (in `item` to the value (to accumulate).
159
    // Expands to an expression.
160
    ${define ITEM_VALUE_FROM_UNPARSED {
161
        ${if fmeta(netdoc(with)) {
162
          ${fmeta(netdoc(with)) as path}
163
              ::${paste_spanned $fname from_unparsed}
164
              (item)?
165
        } else if fmeta(netdoc(single_arg)) { {
166
          let item = ItemValueParseable::from_unparsed(item)?;
167
          let (item,) = item;
168
          item
169
        } } else {
170
          ItemValueParseable::from_unparsed(item)?
171
        }}
172
    }}
173

            
174
    // Type into which we accumulate value(s) of this field
175
    ${define F_ACCUMULATE_TYPE {
176
        ${if F_FLATTEN {
177
            <$ftype as $P::NetdocParseableFields>::Accumulator
178
        } else {
179
            Option::<$F_EFFECTIVE_TYPE>
180
        }
181
    }}}
182

            
183
    // Parse the intro item and bind `$fpatname` accumulator for each field.
184
    //
185
    // For the intro item, parse it and bind it to $fpatname.
186
    //
187
    // For other items, set up a mutable $fpatname, initialised to `default()` (normally None).
188
    ${define INIT_ACCUMULATE_VARS {
189
        $( ${select1 F_INTRO {
190

            
191
          let item = input.next_item()?.ok_or(EP::EmptyDocument)?;
192
          dtrace!("intro", item);
193
          if !Self::is_intro_item_keyword(item.keyword()) {
194
              Err(EP::WrongDocumentType)?;
195
          }
196
          let $fpatname: $ftype = $ITEM_VALUE_FROM_UNPARSED;
197

            
198
        } F_SKIP {
199

            
200
        } else {
201

            
202
          let mut $fpatname = $F_ACCUMULATE_TYPE::default();
203

            
204
        }})
205
    }}
206

            
207
    // Accumulates `item` (which must be `ItemSetMethods::Each`) into `$F_ACCUMULATE_VAR`
208
    ${define ACCUMULATE_ITEM_VALUE { {
209
        dtrace!($"accumulating $fname", $F_SELECTOR.item_set_debug());
210
        $F_SELECTOR.${paste_spanned $fname accumulate}($F_ACCUMULATE_VAR, item)?;
211
    } }}
212

            
213
    // Handle a nonstructural field, parsing and accumulating its value
214
    //
215
    // Looks at `kw` for the keyword.
216
    //
217
    // Expands to a series of `if ... { ... } else`.
218
    // The use site must provide (maybe further arms) and a fallback block!
219
    //
220
    // If the item is the intro item for this document, evaluates `break` -
221
    // so if `f_INTRO` is not trivially false, must be expanded within a field loop.
222
    ${define NONSTRUCTURAL_ACCUMULATE_ELSE {
223
        ${for fields {
224
          ${when not(any(F_FLATTEN, F_SUBDOC, F_SKIP))}
225

            
226
          if kw == $F_KEYWORD {
227
            ${select1
228
              F_NORMAL {
229
                let item = $THIS_ITEM;
230
                dtrace!("is normal", item);
231
                let item = $ITEM_VALUE_FROM_UNPARSED;
232
                $ACCUMULATE_ITEM_VALUE
233
              }
234
              F_SIGNATURE {
235
                let hash_inputs = input
236
                      .peek_signature_hash_inputs(signed_doc_body)?
237
                      .expect("not eof, we peeked kw");
238

            
239
                let item = $THIS_ITEM;
240
                dtrace!("is signature", item);
241
                let item = SignatureItemParseable::from_unparsed_and_body(
242
                    item,
243
                    &hash_inputs,
244
                    AsMut::as_mut(sig_hashes),
245
                )?;
246
                $ACCUMULATE_ITEM_VALUE
247
              }
248
              F_INTRO {
249
                dtrace!("is intro", kw);
250
                break;
251
              } // start of next similar document
252
            }
253
          } else
254
        }}
255
        ${for fields {
256
          ${when F_FLATTEN}
257

            
258
          if <$ftype>::is_item_keyword(kw) {
259
              dtrace!(${concat "is flatten in " $fname}, kw);
260
              let item = $THIS_ITEM;
261
              <$ftype as NetdocParseableFields>::accumulate_item($F_ACCUMULATE_VAR, item)?;
262
          } else
263
        }}
264
    }}
265

            
266
    // Completes a document
267
    //
268
    // The fields accumulated so far must be in `$fpatname` (as a value, not a ref,
269
    // and therefore not in $F_ACCUMULATE_VAR).
270
    //
271
    // Expands to code which resolves the fields, and ends with `Ok(document value)`.
272
    ${define FINISH_RESOLVE {
273
        ${for fields {
274
            ${select1
275
              F_INTRO {}
276
              any(F_NORMAL, F_SIGNATURE) {
277
                  let $fpatname = $F_SELECTOR.finish($fpatname, $F_KEYWORD_REPORT)?;
278
              }
279
              F_FLATTEN {
280
                  let $fpatname = <$ftype as NetdocParseableFields>::finish(
281
                      $fpatname,
282
                      $ITEM_STREAM,
283
                  )?;
284
              }
285
              F_SUBDOC {
286
                  let $fpatname = $F_SELECTOR.finish_subdoc($fpatname)?;
287
              }
288
              F_SKIP {
289
                  #[allow(non_snake_case)]
290
                  let $fpatname = Default::default();
291
              }
292
            }
293
        }}
294
        $(
295
            ${when not(any(F_INTRO, F_SKIP))}
296
            // These conditions are mirrored in NetdocSomeItemsEncodableCommon,
297
            // which is supposed to recognise netdoc(default) precisely when we do.
298
          ${if fmeta(netdoc(default)) {
299
            let $fpatname = Option::unwrap_or_default($fpatname);
300
          }}
301
        )
302

            
303
        #[allow(deprecated)]
304
        Ok($vpat)
305
    }}
306
}
307

            
308
//==================== Main whole document parsing impl ====================
309
//
310
// deftly module ` NetdocParseable`:
311
//
312
//   * IMPL_NETDOC_PARSEABLE expanding to `impl NetdocParseable { ... }`
313
//
314
// Much of the heavy lifting is done in the NetdocSomeItemsParseableCommon deftly module.
315

            
316
define_derive_deftly_module! {
317
    /// Provides `IMPL_NETDOC_PARSEABLE` which impls `NetdocParseable`
318
    ///
319
    /// Used by the `NetdocParseable` and `NetdocParseableUnverified` derives.
320
    NetdocParseable beta_deftly:
321

            
322
    use NetdocDeriveAnyCommon;
323
    use NetdocParseAnyCommon;
324
    use NetdocEntireDeriveCommon;
325
    use NetdocSomeItemsDeriveCommon;
326
    use NetdocSomeItemsParseableCommon;
327

            
328
    ${define ITEM_STREAM input}
329
    ${define F_ACCUMULATE_VAR { (&mut $fpatname) }}
330

            
331
  ${define IMPL_NETDOC_PARSEABLE {
332
    impl<$tgens> $P::NetdocParseable for $NETDOC_PARSEABLE_TTYPE {
333
91676
        fn doctype_for_error() -> &'static str {
334
            ${tmeta(netdoc(doctype_for_error)) as expr,
335
              default ${concat ${for fields { ${when F_INTRO} $F_KEYWORD_STR }}}}
336
        }
337

            
338
36509383
        fn is_intro_item_keyword(kw: $P::KeywordRef<'_>) -> bool {
339
            use $P::*;
340

            
341
            ${for fields {
342
                ${when F_INTRO}
343
                ${loop_exactly_1 "internal error, somehow not exactly one intro item!"}
344
                kw == $F_KEYWORD
345
            }}
346
        }
347

            
348
1694
        fn is_structural_keyword(kw: $P::KeywordRef<'_>) -> Option<$P::IsStructural> {
349
            #[allow(unused_imports)] // not used if there are no subdocs
350
            use $P::*;
351

            
352
            if Self::is_intro_item_keyword(kw) {
353
                return Some(IsStructural)
354
            }
355

            
356
            ${for fields {
357
                ${when F_SUBDOC}
358
                if let y @ Some(_) = $F_SELECTOR_VALUE.is_structural_keyword(kw) {
359
                    return y;
360
                }
361
            }}
362

            
363
            None
364
        }
365

            
366
        //##### main parsing function #####
367

            
368
        #[allow(clippy::redundant_locals)] // let item = $THIS_ITEM, which might be item
369
879468
        fn from_items<'s>(
370
879468
            input: &mut $P::ItemStream<'s>,
371
879468
            outer_stop: $P::stop_at!(),
372
879468
        ) -> $P::Result<Self, $P::ErrorProblem> {
373
            use $P::*;
374
            $DEFINE_DTRACE
375
            $FIELD_ORDERING_CHECK
376

            
377
            //----- prepare item set selectors for every field -----
378
            $ITEM_SET_SELECTORS
379
            $CHECK_FIELD_TYPES_PARSEABLE
380

            
381
            // Is this an intro item keyword ?
382
            //
383
            // Expands to an appropriate `is_intro_item_keyword` method invocation,
384
            // but *without arguments*.  So, something a bit like an expression of type
385
            //    fn(KeywordRef) -> bool
386
            ${define F_SUBDOC_IS_INTRO_ITEM_KEYWORD {
387
                ${if not(F_SUBDOC) { ${error "internal-error: subdoc kw, but not subdoc field"} }}
388
                $F_SELECTOR.is_intro_item_keyword
389
            }}
390

            
391
            //----- Helper fragments for parsing individual pieces of the document -----
392

            
393
            // Peeks a keyword, and returns it but only if it's part of this (sub)doc.
394
            // Return `None` if it was in outer_stop
395
6285156
            let peek_keyword = |input: &mut ItemStream<'s>| -> Result<Option<KeywordRef<'s>>, EP> {
396
                let Some(kw) = input.peek_keyword()? else {
397
                    dtrace!("stopping, because EOF");
398
                    return Ok(None)
399
                };
400
                if outer_stop.stop_at(kw) {
401
                    dtrace!("stopping, because peeked", kw);
402
                    return Ok(None)
403
                }
404
                Ok(Some(kw))
405
            };
406

            
407
            // Returns the actual item as an UnparsedItem, committing to consuming it.
408
            // Can panic if called without previous `peek_keyword`.
409
            ${define THIS_ITEM  {
410
                input.next_item()?.expect("peeked")
411
            }}
412

            
413
            //----- keyword classification closures -----
414

            
415
            // Is this a keyword for one of our sub-documents?
416
            let is_subdoc_kw = ${for fields {
417
                ${when F_SUBDOC}
418
                StopAt(|kw: KeywordRef<'_>| $F_SUBDOC_IS_INTRO_ITEM_KEYWORD(kw)) |
419
              }}
420
                StopAt(false)
421
            ;
422
            // Is this a keyword for one of our parents or sub-documents?
423
            let inner_stop = outer_stop | is_subdoc_kw;
424

            
425
            //========== actual parsing ==========
426

            
427
            // For each parsing loop/section, where we aren't looking for precisely one thing,
428
            // we should explicitly decide what to do with each of:
429
            //   - F_INTRO - intro item for this document (maybe next instance in parent)
430
            //   - F_NORMAL - normal items
431
            //   - subdocuments, is_subdoc_kw and F_SUBDOC
432
            //   - our parent's structural keywords, outer_stop
433
            //     (this includes signature items for the signed version of this doc)
434
            // 5 cases in all.
435

            
436
            //----- Parse the intro item, and introduce bindings for the other items. -----
437

            
438
            dtrace!("looking for intro item");
439
            $INIT_ACCUMULATE_VARS
440

            
441
            //----- Parse the normal items -----
442
            dtrace!("looking for normal items");
443

            
444
            while let Some(kw) = peek_keyword(input)? {
445
                dtrace!("for normal, peeked", kw);
446
                if inner_stop.stop_at(kw) {
447
                    dtrace!("is inner stop", kw);
448
                    break;
449
                };
450

            
451
                $NONSTRUCTURAL_ACCUMULATE_ELSE
452
                {
453
                    dtrace!("is unknown (in normal)");
454
                    let _: UnparsedItem = $THIS_ITEM;
455
                }
456
            }
457

            
458
            //----- Parse the subdocs, in order -----
459
            dtrace!("looking for subdocs");
460

            
461
          ${for fields {
462
            ${when F_SUBDOC}
463
            dtrace!("looking for subdoc", $F_KEYWORD_REPORT);
464

            
465
            loop {
466
                let Some(kw) = peek_keyword(input)? else { break };
467
                dtrace!("for subdoc, peek", kw);
468

            
469
                if !$F_SUBDOC_IS_INTRO_ITEM_KEYWORD(kw) {
470
                    dtrace!("is not this subdoc", kw);
471
                    break;
472
                };
473

            
474
                $F_SELECTOR.can_accumulate(&mut $fpatname)?;
475

            
476
                dtrace!("is this subdoc", kw);
477
                let item = NetdocParseable::from_items(input, inner_stop);
478
                dtrace!("parsed this subdoc", item.as_ref().map(|_| ()));
479
                let item = item?;
480

            
481
                $ACCUMULATE_ITEM_VALUE
482
            }
483
          }}
484

            
485
            // Resolve all the fields
486
            dtrace!("reached end, resolving");
487

            
488
            $FINISH_RESOLVE_PARSEABLE
489
        }
490
    }
491
  }}
492
}
493

            
494
//==================== NetdocParseable user-facing derive macro ====================
495
//
496
// deftly template `NetdocParseable`:
497
//
498
//  * main entrypoint for deriving the `NetdocParseable` trait
499
//  * docs for the meta attributes we support during document parsing
500
//
501
// The actual implementation is in  the `NetdocParseable` deftly module, above.
502

            
503
define_derive_deftly! {
504
    use NetdocParseable;
505

            
506
    /// Derive [`NetdocParseable`] for a document (or sub-document)
507
    ///
508
    // NB there is very similar wording in the NetdocEncodable derive docs.
509
    // If editing any of this derive's documentation, considering editing that too.
510
    //
511
    /// ### Expected input structure
512
    ///
513
    /// Should be applied named-field struct, where each field is
514
    /// an Item which may appear in the document,
515
    /// or a sub-document.
516
    ///
517
    /// The first field will be the document's intro Item.
518
    /// The expected Keyword for each Item will be kebab-case of the field name.
519
    ///
520
    /// ### Field type
521
    ///
522
    /// Each field must be
523
    ///  * `impl `[`ItemValueParseable`] for an "exactly once" field,
524
    ///  * `Vec<T: ItemValueParseable>` for "zero or more", or
525
    ///  * `BTreeSet<T: ItemValueParseable + Ord>`, or
526
    ///  * `Option<T: ItemValueParseable>` for "zero or one".
527
    ///
528
    /// We don't directly support "at least once":
529
    /// the parsed network document doesn't imply the invariant
530
    /// that at least one such item was present.
531
    // We could invent a `NonemptyVec` or something for this.
532
    ///
533
    /// (This is implemented via types in the [`multiplicity`] module,
534
    /// specifically [`ItemSetSelector`].)
535
    ///
536
    /// ### Signed documents
537
    ///
538
    /// To handle signed documents:
539
    ///
540
    ///  * Define `struct Foo`, containing only the content, not the signatures.
541
    ///    Derive [`NetdocParseableUnverified`](crate::derive_deftly_template_NetdocParseableUnverified).
542
    ///  * Define `struct FooSignatures`, containing only the signatures.
543
    ///    Derive `NetdocParseableSignatures`.
544
    ///
545
    ///  * Implement a suitable `FooUnverified::verify`.
546
    ///    See [`NetdocParseableUnverified`](crate::derive_deftly_template_NetdocParseableUnverified)
547
    ///    for guidance.
548
    ///
549
    /// Don't mix signature items with non-signature items in the same struct.
550
    /// (This wouldn't compile, because the field type would implement the wrong trait.)
551
    ///
552
    /// ### Top-level attributes:
553
    ///
554
    /// * **`#[deftly(netdoc(doctype_for_error = EXPRESSION))]`**:
555
    ///
556
    ///   Specifies the value to be returned from
557
    ///   [`NetdocParseable::doctype_for_error`].
558
    ///
559
    ///   Note, must be an expression, so for a literal, nested `""` are needed.
560
    ///
561
    ///   The default is the intro item keyword.
562
    ///
563
    /// * **`#[deftly(netdoc(debug))]`**:
564
    ///
565
    ///   The generated implementation will generate copious debug output
566
    ///   to the program's stderr when it is run.
567
    ///   Do not enable in production!
568
    ///
569
    /// ### Field-level attributes:
570
    ///
571
    /// * **`#[deftly(netdoc(keyword = STR))]`**:
572
    ///
573
    ///   Use `STR` as the Keyword for this Item.
574
    ///
575
    /// * **`#[deftly(netdoc(single_arg))]`**:
576
    ///
577
    ///   The field type implements `ItemArgumentParseable`,
578
    ///   instead of `ItemValueParseable`,
579
    ///   and is parsed as if `(FIELD_TYPE,)` had been written.
580
    ///
581
    /// * **`#[deftly(netdoc(with = MODULE))]`**:
582
    ///
583
    ///   Instead of `ItemValueParseable`, the item is parsed with `MODULE::from_unparsed`,
584
    ///   which must have the same signature as [`ItemValueParseable::from_unparsed`].
585
    ///
586
    ///   (Not supported for sub-documents, signature items, or field collections.)
587
    ///
588
    /// * **`#[deftly(netdoc(default))]`**:
589
    ///
590
    ///   This field is optional ("at most once");
591
    ///   if not present, `FIELD_TYPE::default()` will be used.
592
    ///
593
    ///   This is an alternative to declaring the field type as `Option`
594
    ///   With `netdoc(default)`, the field value doesn't need unwrapping.
595
    ///   With `Option` it is possible to see if the field was provided.
596
    ///
597
    ///   `#[deftly(netdoc(default(skip)))]` is meaningful only for
598
    ///   [NetdocEncodable](crate::derive_deftly_template_NetdocEncodable) and
599
    ///   [NetdocEncodableFields](crate::derive_deftly_template_NetdocEncodableFields).
600
    ///
601
    /// * **`#[deftly(netdoc(flatten))]`**:
602
    ///
603
    ///   This field is a struct containing further individual normal fields.
604
    ///   The Items for those individual fields can appear in *this*
605
    ///   outer document in any order, interspersed with other normal fields.
606
    ///
607
    ///   The field type must implement [`NetdocParseableFields`].
608
    ///
609
    /// * **`#[deftly(netdoc(skip))]`**:
610
    ///
611
    ///   This field doesn't really appear in the network document.
612
    ///   It won't be recognised during parsing.
613
    ///   Instead, `Default::default()` will be used for the field value.
614
    ///
615
    /// * **`#[deftly(netdoc(subdoc))]`**:
616
    ///
617
    ///   This field is a sub-document.
618
    ///   The value type `T` must implement [`NetdocParseable`]
619
    ///   *instead of* `ItemValueParseable`.
620
    ///
621
    ///   The field name is not used for parsging;
622
    ///   the sub-document's intro keyword is used instead.
623
    ///
624
    ///   Sub-documents are expected to appear after all normal items,
625
    ///   in the order presented in the struct definition.
626
    ///
627
    /// # Example
628
    ///
629
    /// ```
630
    /// use derive_deftly::Deftly;
631
    /// use tor_checkable::{TimeBound, timed::TimeRangeBound};
632
    /// use tor_netdoc::derive_deftly_template_AsMutSelf;
633
    /// use tor_netdoc::derive_deftly_template_NetdocParseableSignatures;
634
    /// use tor_netdoc::derive_deftly_template_NetdocParseableUnverified;
635
    /// use tor_netdoc::derive_deftly_template_ItemValueParseable;
636
    /// use tor_netdoc::parse2::{
637
    ///     parse_netdoc, ErrorProblem, ParseInput, VerifyFailed,
638
    ///     SignatureItemParseable, SignatureHashesAccumulator, SignatureHashInputs,
639
    /// };
640
    ///
641
    /// #[derive(Deftly, Debug, Clone)]
642
    /// #[derive_deftly(NetdocParseableUnverified)]
643
    /// pub struct NdThing {
644
    ///     pub thing_start: (),
645
    ///     pub value: (String,),
646
    /// }
647
    ///
648
    /// #[derive(Deftly, Debug, Clone)]
649
    /// #[derive_deftly(NetdocParseableSignatures)]
650
    /// #[deftly(netdoc(signatures(hashes_accu = UseLengthAsFoolishHash)))]
651
    /// pub struct NdThingSignatures {
652
    ///     pub signature: FoolishSignature,
653
    /// }
654
    ///
655
    /// #[derive(Deftly, Debug, Clone)]
656
    /// #[derive_deftly(ItemValueParseable)]
657
    /// #[deftly(netdoc(signature(hash_accu = UseLengthAsFoolishHash)))]
658
    /// pub struct FoolishSignature {
659
    ///     pub doc_len: usize,
660
    /// }
661
    ///
662
    /// #[derive(Deftly, Debug, Default, Clone)]
663
    /// #[derive_deftly(AsMutSelf)]
664
    /// pub struct UseLengthAsFoolishHash {
665
    ///     pub doc_len_actual_pretending_to_be_hash: Option<usize>,
666
    /// }
667
    /// impl SignatureHashesAccumulator for UseLengthAsFoolishHash {
668
    ///     fn update_from_netdoc_body(
669
    ///         &mut self,
670
    ///         document_body: &SignatureHashInputs<'_>,
671
    ///     ) -> Result<(), ErrorProblem> {
672
    ///         self
673
    ///             .doc_len_actual_pretending_to_be_hash
674
    ///             .get_or_insert_with(|| document_body.body().body().len());
675
    ///         Ok(())
676
    ///     }
677
    /// }
678
    ///
679
    /// let doc_text =
680
    /// r#"thing-start
681
    /// value something
682
    /// signature 28
683
    /// "#;
684
    ///
685
    /// impl NdThingUnverified {
686
    ///     pub fn verify_foolish(self) -> Result<TimeRangeBound<NdThing>, VerifyFailed> {
687
    ///         // See docs for derive_deftly_template_NetdocParseableUnverified
688
    ///         // for how to write a verify function.
689
    ///
690
    ///         let sig = &self.sigs.sigs.signature;
691
    ///         let hash = self.sigs.hashes.doc_len_actual_pretending_to_be_hash
692
    ///             .as_ref().ok_or(VerifyFailed::Bug)?;
693
    ///         if sig.doc_len != *hash {
694
    ///             return Err(VerifyFailed::VerifyFailed);
695
    ///         }
696
    ///         let foolish_lack_of_validity_time_info = ..;
697
    ///         let body = TimeRangeBound::new(self.body, foolish_lack_of_validity_time_info);
698
    ///         Ok(body)
699
    ///     }
700
    /// }
701
    ///
702
    /// let input = ParseInput::new(doc_text, "<input>");
703
    /// let doc: NdThingUnverified = parse_netdoc(&input).unwrap();
704
    /// let doc = doc.verify_foolish().unwrap().dangerously_assume_timely();
705
    /// assert_eq!(doc.value.0, "something");
706
    /// ```
707
    export NetdocParseable for struct, meta_quoted rigorous, expect items, beta_deftly:
708

            
709
    ${define NETDOC_PARSEABLE_TTYPE { $ttype }}
710
    ${define FINISH_RESOLVE_PARSEABLE $FINISH_RESOLVE}
711

            
712
    $IMPL_NETDOC_PARSEABLE
713
}
714

            
715
//==================== NetdocParseableSignatures user-facing derive macro ====================
716
//
717
// deftly template `NetdocParseableSignatures`:
718
//
719
//  * entrypoint for deriving the `NetdocParseableSignatures` trait
720
//  * docs for the signatures-section-specific attributes
721
//  * implementation of that derive
722
//
723
// Much of the heavy lifting is done in the NetdocSomeItemsParseableCommon deftly module.
724

            
725
define_derive_deftly! {
726
    use NetdocDeriveAnyCommon;
727
    use NetdocParseAnyCommon;
728
    use NetdocFieldsDeriveCommon;
729
    use NetdocFieldsParseableCommon;
730
    use NetdocSomeItemsDeriveCommon;
731
    use NetdocSomeItemsParseableCommon;
732

            
733
    /// Derive [`NetdocParseable`] for the signatures section of a network document
734
    ///
735
    /// This type is the signatures section of another document.
736
    /// Signature sections have no separate intro keyword:
737
    /// every field is structural and they are recognised in any order.
738
    ///
739
    /// This signatures sub-document will typically be included in a
740
    /// `FooUnverified` struct derived with
741
    /// [`NetdocParseableUnverified`](crate::derive_deftly_template_NetdocParseableUnverified),
742
    /// rather than included anywhere manually.
743
    ///
744
    /// ### Expected input structure
745
    ///
746
    /// Should be applied named-field struct, where each field
747
    /// implements [`SignatureItemParseable`],
748
    /// or is a `SignatureItemParseable` in `Vec` or `BTreeSet` or `Option`.
749
    ///
750
    /// ### Attributes
751
    ///
752
    ///  * The following top-level attributes are supported:
753
    ///    `#[deftly(netdoc(debug))]`
754
    ///
755
    $DOC_NETDOC_FIELDS_DERIVE_SUPPORTED
756
    ///
757
    /// ### Signature item ordering, and signatures covering signatures
758
    ///
759
    /// The derived code does not impose any mutual ordering of signatures.
760
    /// If signatures are independent, hashing can be done with [`SignedDocumentBody`]
761
    /// (from [`SignatureHashInputs::body`]).
762
    ///
763
    /// In sane netdoc signature scheme, no signatures would cover other signatures,
764
    /// and there would be no ordering requirement on signatures on the same document.
765
    ///  A relying party would verify the signatures that they are proposing to rely on
766
    /// (which would generally include signatures for *one* algorithm, not several)
767
    /// and ignore the others.
768
    ///
769
    /// (Such a signature, which also does not include any of its own item encoding
770
    /// in its hash, is called Orderly.  See [SignedDocumentBody].)
771
    ///
772
    /// Unfortunately, many Tor netdocs have signature schemes
773
    /// which are not sane (by this definition).
774
    ///
775
    /// When signatures are specified to cover other signatures,
776
    /// the signature item implementation must contain ad-hoc code in
777
    /// [`SignatureItemParseable::from_unparsed_and_body`].
778
    /// to hash not only the body, but also the prior signatures.
779
    /// Methods on [`SignatureHashInputs`] are available to get
780
    /// the relevant parts of the input document text
781
    /// (eg, [`document_sofar`](SignatureHashInputs::document_sofar)).
782
    ///
783
    /// When the spec states a required ordering on signature items,
784
    /// this should be enforced by ad-hoc code in implementation(s) of
785
    /// `SignatureItemParseable`.
786
    /// The implementation should use
787
    /// [`HashAccu`](SignatureItemParseable::HashAccu)
788
    /// to store any necessary state.
789
    /// Usually, this can be achieved by using the same Rust struct for the
790
    /// `HashAccu` of each of the signature items:
791
    /// that will make the signature hashes computed so far, for items seen so far,
792
    /// visible to subsequent items;
793
    /// the subsequent items can check that the prior items filled in the hash,
794
    /// thus imposing an ordering.
795
    ///
796
    /// Alternatively, the ordering could be enforced in the user-supplied
797
    /// ad-hoc `verify` function(s) on `FooUUnverified`.
798
    ///
799
    /// Note that this enforcement should be done for protocol compliance
800
    /// and availability reasons, but is not a security issue.
801
    /// There is not a security risk from accepting documents some of whose signatures
802
    /// aren't covered by other signatures even though the protocol specifies they should be:
803
    /// relying parties *verify* the signatures but do not treat them as trusted data.
804
    /// So there is no engineered safeguard against failing to implement
805
    /// signature item ordering checks.
806
    export NetdocParseableSignatures for struct, meta_quoted rigorous, expect items, beta_deftly:
807

            
808
    ${defcond T_SIGNATURES true}
809

            
810
    // NetdocParseableSignatures::HashesAccu
811
    ${define SIGS_HASHES_ACCU_TYPE { ${tmeta(netdoc(signatures(hashes_accu))) as ty} }}
812

            
813
    ${define ITEM_STREAM input}
814
    ${define THIS_ITEM { input.next_item()?.expect("peeked") }}
815
    ${define F_ACCUMULATE_VAR { (&mut $fpatname) }}
816

            
817
    ${impl $P::NetdocParseableSignatures} {
818
        type HashesAccu = $SIGS_HASHES_ACCU_TYPE;
819

            
820
        $DEFINE_IS_ITEM_KEYWORD
821

            
822
        #[allow(clippy::redundant_locals)] // let item = $THIS_ITEM, which might be item
823
74065
        fn from_items<'s>(
824
74065
            input: &mut $P::ItemStream<'s>,
825
74065
            signed_doc_body: $P::SignedDocumentBody<'s>,
826
74065
            sig_hashes: &mut $SIGS_HASHES_ACCU_TYPE,
827
74065
            outer_stop: $P::stop_at!(),
828
74065
        ) -> $P::Result<$ttype, $P::ErrorProblem> {
829
            use $P::*;
830
            $DEFINE_DTRACE
831

            
832
            //----- prepare item set selectors for every field -----
833
            $ITEM_SET_SELECTORS
834
            $CHECK_FIELD_TYPES_PARSEABLE
835
            $INIT_ACCUMULATE_VARS
836

            
837
            //----- parse the items -----
838
            dtrace!("looking for signature items");
839

            
840
307603
            while let Some(kw) = input.peek_keyword()? {
841
                dtrace!("for signatures, peeked", kw);
842
254380
                if outer_stop.stop_at(kw) {
843
                    dtrace!("is outer stop", kw);
844
20842
                    break;
845
233538
                };
846

            
847
                $NONSTRUCTURAL_ACCUMULATE_ELSE
848
                {
849
                    dtrace!("is unknown (in signatures)");
850
                    let _: UnparsedItem = $THIS_ITEM;
851
                }
852
            }
853

            
854
            // Resolve all the fields
855
            dtrace!("reached end, resolving");
856

            
857
            $FINISH_RESOLVE
858
74065
        }
859
    }
860
}
861

            
862
//==================== NetdocParseableFields user-facing derive macro ====================
863
//
864
// deftly template `NetdocParseableFields`
865
//
866
//  * entrypoint for deriving the `NetdocParseableFields` trait
867
//  * docs and implementation for that derive
868
//
869
// Much of the heavy lifting is done in the NetdocSomeItemsParseableCommon deftly module.
870

            
871
define_derive_deftly! {
872
    use NetdocDeriveAnyCommon;
873
    use NetdocParseAnyCommon;
874
    use NetdocFieldsDeriveCommon;
875
    use NetdocFieldsParseableCommon;
876
    use NetdocSomeItemsDeriveCommon;
877
    use NetdocSomeItemsParseableCommon;
878

            
879
    /// Derive [`NetdocParseableFields`] for a struct with individual items
880
    ///
881
    /// Defines a struct `FooNetdocParseAccumulator` to be the
882
    /// `NetdocParseableFields::Accumulator`.
883
    ///
884
    /// Similar to
885
    /// [`#[derive_deftly(NetdocParseable)]`](derive_deftly_template_NetdocParseable),
886
    /// but:
887
    ///
888
    ///  * Derives [`NetdocParseableFields`]
889
    $DOC_NETDOC_FIELDS_NORMAL_ONLY
890
    $DOC_NETDOC_FIELDS_DERIVE_SUPPORTED
891
    ///
892
    export NetdocParseableFields for struct , meta_quoted rigorous, expect items, beta_deftly:
893

            
894
    ${defcond T_SIGNATURES false}
895
    ${define ITEM_STREAM items}
896
    ${define THIS_ITEM item}
897
    ${define F_ACCUMULATE_VAR { (&mut acc.$fname) }}
898

            
899
    #[doc = ${concat "Partially parsed `" $tname "`"}]
900
    ///
901
    /// Used for [`${concat $P::NetdocParseableFields::Accumulator}`].
902
    #[derive(Default, Debug)]
903
    $tvis struct $<$tname NetdocParseAccumulator><$tdefgens> { $(
904
        $fname: $F_ACCUMULATE_TYPE,
905
    ) }
906

            
907
    ${impl $P::NetdocParseableFields} {
908
        type Accumulator = $<$ttype NetdocParseAccumulator>;
909

            
910
        $DEFINE_IS_ITEM_KEYWORD
911

            
912
        #[allow(clippy::redundant_locals)] // let item = $THIS_ITEM, which might be item
913
960307
        fn accumulate_item(
914
960307
            #[allow(unused_variables)] // If there are no fields, this is unused
915
960307
            acc: &mut Self::Accumulator,
916
960307
            #[allow(unused_variables)] // If there are no fields, this is unused
917
960307
            item: $P::UnparsedItem<'_>,
918
960307
        ) -> $P::Result<(), $P::ErrorProblem> {
919
            #[allow(unused_imports)] // false positives in some situations
920
            use $P::*;
921
            $DEFINE_DTRACE
922

            
923
            $ITEM_SET_SELECTORS
924
            $CHECK_FIELD_TYPES_PARSEABLE
925

            
926
            #[allow(unused_variables)] // If there are no fields, this is unused
927
960307
            let kw = item.keyword();
928

            
929
            $NONSTRUCTURAL_ACCUMULATE_ELSE
930
            {
931
                panic!("accumulate_item called though is_item_keyword returns false");
932
            }
933

            
934
            #[allow(unreachable_code)] // If there are no fields!
935
            #[allow(deprecated)]
936
960307
            Ok(())
937
960307
        }
938

            
939
229030
        fn finish(
940
229030
            #[allow(unused_variables)] // If there are no fields, this is unused
941
229030
            acc: Self::Accumulator,
942
229030
            #[allow(unused_variables)] // often unused
943
229030
            items: &$P::ItemStream<'_>,
944
229030
        ) -> $P::Result<Self, $P::ErrorProblem> {
945
            #[allow(unused_imports)] // false positives in some situations
946
            use $P::*;
947
            $DEFINE_DTRACE
948

            
949
            dtrace!("finish, resolving");
950

            
951
            $ITEM_SET_SELECTORS
952

            
953
         $(
954
            ${when not(F_SKIP)}
955
228902
            let $fpatname = acc.$fname;
956
         )
957
            $FINISH_RESOLVE
958
229030
        }
959
    }
960
}
961

            
962
//==================== NetdocParseableUnverified user-facing derive macro ====================
963
//
964
// deftly template `NetdocParseableUnverified`
965
//
966
//  * entrypoint for deriving the `FooUnverified` struct implementing `NetdocParseable`
967
//    (and supporting items such as `FooUnverifiedParsedBody` structs and its impl).
968
//  * docs for that derive, including doc-level signatures-related attributes
969
//  * implementation glue for those derived impls
970
//
971
// The principal derived parsing impl on the body type `Foo` is expanded by this macro,
972
// but that is implemented via IMPL_NETDOC_PARSEABLE in the NetdocParseable deftly module.
973
//
974
// The substantive code to implement `NetdocParseable` for `FooUnverified` is
975
// in the `ItemStream::parse_signed` helper function; a call to that is expanded here.
976

            
977
define_derive_deftly! {
978
    use NetdocParseable;
979

            
980
    /// Derive `NetdocParseable` for a top-level signed document
981
    ///
982
    /// ### Expected input structure
983
    ///
984
    /// Apply this derive to the main body struct `Foo`,
985
    /// which should meet all the requirements to derive
986
    /// [`NetdocParseable`](derive_deftly_template_NetdocParseable).
987
    ///
988
    /// Usually, the caller will provide suitable ad-hoc `.verify_...` methods
989
    /// on `FooUnverified`.
990
    ///
991
    /// The `verify` method should:
992
    ///
993
    ///   * Take as an argument(s) the expected (trustworthy) signer(s),
994
    ///     (if the document is not always just supposed to be self-signed).
995
    ///
996
    ///   * Work directly with the fields `body` and `sigs` in `FooUnverified`.
997
    ///
998
    ///   * Verify all the signatures, including any [`EmbeddedCert`]s in the body.
999
    ///
    ///   * Cross-check any information that is supposed to be duplicated.
    ///
    ///   * Determine the validity period, from the validity time
    ///     information contained in the document or signatures.
    ///
    ///   * Return `TimeRangebound<Foo>`.
    ///
    /// ### Generated code
    ///
    /// Supposing your input structure is `Foo`, this macro will
    /// generate a **`struct FooUnverified`**
    /// implementing [`NetdocParseable`] and [`NetdocParseableUnverified`]:
    ///
    /// ```rust,ignore
    /// # struct Foo; struct FooSignatures;
    /// pub struct FooUnverified {
    ///     body: Foo,
    ///     pub sigs: SignaturesData<FooUnverified>,
    /// }
    /// ```
    ///
    /// Also generated is `FooUnverifiedParsedBody`
    /// and an impl of [`HasUnverifiedParsedBody`] on `Foo`.
    /// These allow the generated code to call [`ItemStream::parse_signed`]
    /// and it should not normally be necessary to use them elsewhere.
    ///
    /// ### Required top-level attributes:
    ///
    /// * **`#[deftly(netdoc(signature = TYPE))]`**:
    ///   Type of the signature(s) section.
    ///
    ///   TYPE must implement `NetdocParseable`,
    ///   with `is_intro_item_keyword` reporting *every* signature keyword.
    ///   Normally this is achieved with
    ///   `#[derive_deftly(NetdocParseable)] #[deftly(netdoc(signatures))]`.
    ///
    /// ### Optional attributes
    ///
    /// All the attributes supported by the `NetdocParseable` derive are supported.
    //
    // We don't make NetdocParseableUnverified a generic struct because
    //  - the defining module (crate) will want to add verification methods,
    //    which means they must define the struct
    //  - that lets the actual `body` field be private to the defining module.
    export NetdocParseableUnverified for struct, meta_quoted rigorous, expect items, beta_deftly:
    ${define NETDOC_PARSEABLE_TTYPE { $<$ttype UnverifiedParsedBody> }}
    ${define FINISH_RESOLVE_PARSEABLE {
        { $FINISH_RESOLVE }
74065
        .map(|unverified| $<$tname UnverifiedParsedBody> { unverified })
    }}
    $IMPL_NETDOC_PARSEABLE
    // FooSignatures (type name)
    ${define SIGS_TYPE { $< ${tmeta(netdoc(signatures)) as ty, default $<$ttype Signatures>} > }}
    ${define SIGS_DATA_TYPE { $P::SignaturesData<$<$ttype Unverified>> }}
    ${define SIGS_HASHES_ACCU_TYPE { <$SIGS_TYPE as $P::NetdocParseableSignatures>::HashesAccu }}
   $///Signed (unverified) form of [`$tname`]
    ///
    /// Embodies:
    ///
   $///  * **[`$tname`]**: document body
   $///  * **[`$SIGS_TYPE`]**: signatures
    ///
    /// If this type was parsed from a document text,
    /// the signatures have *not* yet been verified.
    ///
    /// Use a `.verify_...` method to obtain useable, verified, contents.
    #[derive(Debug, Clone)]
    $tvis struct $<$ttype Unverified> {
        /// The actual body
        //
        // Misuse is prevented by this field not being public.
        // It can be accessed only in this module, where the verification functions are.
        body: $ttype,
        /// Signatures
        $tvis sigs: $SIGS_DATA_TYPE,
    }
    /// The parsed but unverified body part of a signed network document (working type)
    ///
   $/// Contains a [`$tname`] which has been parsed
    /// as part of a signed document,
    /// but the signatures aren't embodied here, and have not been verified.
    ///
   $/// Not very useful to callers, who should use the `${tname}Unverified` type instead,
    /// and its implementation of `NetdocParseable`.
    //
    // We implement NetdocParseable on FooUnverified using ItemStream::parse_signed.
    // ItemStream::parse_signed is a fairly normal but ad-hoc
    // implementation of NetdocParseable which uses as subroutines implementations
    // of NetdocParseable for the body and NetdocParseableSignatures for the signatures.
    //
    // We need a newtype because we don't want to implement `NetdocParseable`
    // for a type which is just the body.  Such an impl would be usable by mistake,
    // via the top-level parse2 functions, and it would then simply discard the signatures
    // and return unverified data, bypassing our efforts to prevent such bugs.
    //
    // Ideally we would have a generic `UnverifiedParsedBody<B>` type or something
    // but then this macro, invoked in other crates, couldn't impl NetdocParseable for
    // UnverifiedParsedBody<TheirType>, due to trait coherence rules.
    //
    #[derive(derive_more::From)]
    pub struct $NETDOC_PARSEABLE_TTYPE<$tdefgens> {
        /// The unverified body
        unverified: $ttype,
    }
    ${impl $P::NetdocParseable for $<$ttype Unverified>} {
160
        fn doctype_for_error() -> &'static str {
            $NETDOC_PARSEABLE_TTYPE::doctype_for_error()
160
        }
        fn is_intro_item_keyword(kw: $P::KeywordRef<'_>) -> bool {
            $NETDOC_PARSEABLE_TTYPE::is_intro_item_keyword(kw)
        }
        fn is_structural_keyword(kw: $P::KeywordRef<'_>) -> Option<$P::IsStructural> {
            $NETDOC_PARSEABLE_TTYPE::is_structural_keyword(kw).or_else(
                || <$SIGS_TYPE as $P::NetdocParseableSignatures>
                    ::is_item_keyword(kw).then_some($P::IsStructural)
            )
        }
74225
        fn from_items<'s>(
74225
            input: &mut $P::ItemStream<'s>,
74225
            outer_stop: $P::stop_at!(),
74225
        ) -> $P::Result<$<$ttype Unverified>, $P::ErrorProblem> {
            $EMIT_DEBUG_PLACEHOLDER
74225
            input.parse_signed(outer_stop)
74225
        }
    }
    ${impl $P::NetdocParseableUnverified for $<$ttype Unverified>} {
        type Body = $ttype;
        type Signatures = $SIGS_TYPE;
3181
        fn inspect_unverified(&self) -> (&Self::Body, &$SIGS_DATA_TYPE) {
3181
            (&self.body, &self.sigs)
3181
        }
63143
        fn unwrap_unverified(self) -> (Self::Body, $SIGS_DATA_TYPE) {
63143
            (self.body, self.sigs)
63143
        }
74069
        fn from_parts(body: Self::Body, sigs: $SIGS_DATA_TYPE) -> Self {
74069
            Self { body, sigs }
74069
        }
    }
    ${impl $P::HasUnverifiedParsedBody} {
        type UnverifiedParsedBody = $NETDOC_PARSEABLE_TTYPE;
74065
        fn unverified_into_inner_unchecked(unverified: Self::UnverifiedParsedBody) -> Self {
74065
            unverified.unverified
74065
        }
    }
}
//==================== ItemValueParseable user-facing derive macro ====================
//
// deftly template `ItemValueParseable`
//
//  * entrypoint for deriving the `ItemValueParseable` and `SignatureItemParseable` traits
//  * docs for the meta attributes we support during *item* parsing
//  * implementation of those derives
define_derive_deftly! {
    use NetdocDeriveAnyCommon;
    use NetdocParseAnyCommon;
    use NetdocItemDeriveCommon;
    /// Derive `ItemValueParseable` (or `SignatureItemParseable`)
    ///
    // NB there is very similar wording in the ItemValueEncodable derive docs.
    // If editing any of this derive's documentation, considering editing that too.
    //
    /// Fields in the struct are parsed from the keyword line arguments,
    /// in the order they appear in the struct.
    ///
    /// ### Field type
    ///
    /// Each field should be:
    ///
    ///  * `impl `[`ItemArgumentParseable`] (one argument),
    ///  * `Option<impl ItemArgumentParseable>` (one optional argument),
    ///  * `Vec<impl ItemArgumentParseable>` (zero or more arguments), or
    ///  * `BTreeSet<impl ItemArgumentParseable + Ord>` (zero or more arguments).
    ///
    /// `ItemArgumentParseable` can be implemented via `impl FromStr`,
    /// by writing `impl NormalItemArgument`.
    ///
    /// For `Option` or `Vec`, we expect that *if* there are any further arguments,
    /// they are for this field.
    /// So absence of any optional argument means absence of following arguments,
    /// and no arguments can follow a `Vec`.
    ///
    /// Some Tor netdocs have optional arguments followed by other data,
    /// with unclear/ambiguous parsing rules.
    /// These cases typically require manual implementation of [`ItemValueParseable`].
    ///
    /// (Multiplicity is implemented via types in the [`multiplicity`] module,
    /// specifically [`ArgumentSetSelector`] and [`ArgumentSetMethods`].)
    ///
    /// ### Top-level attributes:
    ///
    ///  * **`#[deftly(netdoc(no_extra_args))]**:
    ///
    ///    Reject, rather than ignore, additional arguments found in the document
    ///    which aren't described by the struct.
    ///
    ///  * **`#[deftly(netdoc(signature(hash_accu = HASH_ACCU))]**:
    ///
    ///    This item is a signature item.
    ///    [`SignatureItemParseable`] will be implemented instead of [`ItemValueParseable`].
    ///
    ///    **`HASH_ACCU`** is the type in which the hash(es) for this item will be accumulated,
    ///    and must implement [`SignatureHashesAccumulator`].
    ///    It is used as [`SignatureItemParseable::HashAccu`].
    ///
    /// * **`#[deftly(netdoc(debug))]`**:
    ///
    ///   Currently implemented only as a placeholder
    ///
    ///   The generated implementation may in future generate copious debug output
    ///   to the program's stderr when it is run.
    ///   Do not enable in production!
    ///
    $DOC_DEBUG_PLACEHOLDER
    ///
    /// ### Field-level attributes:
    ///
    ///  * **`#[deftly(netdoc(rest))]**:
    ///
    ///    The field is the whole rest of the line.
    ///    Must come after any other normal argument fields.
    ///    Only allowed once.
    ///
    ///    The field type must implement `FromStr`.
    ///    (I.e. `Vec` , `Option` etc., are not allowed, and `ItemArgumentParseable` is not used.)
    ///
    ///  * **`#[deftly(netdoc(object))]**:
    ///
    ///    The field is the Object.
    ///    It must implement [`ItemObjectParseable`]
    ///    (or be `Option<impl ItemObjectParseable>`).
    ///
    ///    Only allowed once.
    ///    If omittted, any object is rejected.
    ///
    ///  * **`#[deftly(netdoc(object(label = "LABEL")))]**:
    ///
    ///    Sets the expected label for an Object.
    ///    If not supplied, uses [`ItemObjectParseable::check_label`].
    ///
    ///  * **`#[deftly(netdoc(with = MODULE)]**:
    ///
    ///    Instead of `ItemArgumentParseable`, the argument is parsed with `MODULE::from_args`,
    ///    which must have the same signature as [`ItemArgumentParseable::from_args`].
    ///
    ///    With `#[deftly(netdoc(rest))]`, the argument is parsed with `MODULE::from_args_rest`,
    ///    must have the signature
    ///    `fn from_args_rest(s: &str) -> Result<FIELD, _>`).
    ///    and replaces `<FIELD as FromStr>::from_str`.
    ///
    ///    With `#[deftly(netdoc(object))]`, uses `MODULE::try_from`
    ///    which must have the signature `fn(Vec<u8>) -> Result<OBJECT, _>`;
    ///    like `TryFrom::<Vec<u8>>>::try_from`.
    ///    LABEL must also be specified
    ///    unless the object also implements `ItemObjectParseable`.
    ///    Errors from parsing will all be collapsed into
    ///    [`ErrorProblem::ObjectInvalidData`].
    ///
    ///  * **`#[deftly(netdoc(skip))]**:
    ///
    ///    Do not parse this field; fill it in with `Default::default()` instead.
    export ItemValueParseable for struct, meta_quoted rigorous, expect items, beta_deftly:
    ${define TRAIT ${if T_IS_SIGNATURE { SignatureItemParseable } else { ItemValueParseable }}}
    ${define METHOD ${if T_IS_SIGNATURE { from_unparsed_and_body } else { from_unparsed }}}
    // SignatureItemParseable::HashAccu
    ${define SIG_HASH_ACCU_TYPE ${tmeta(netdoc(signature(hash_accu))) as ty}}
    // Avoid that someone wanting to parse a signed netdoc
    //   - tries to use parse2 on Foo rather than FooUnverified
    //   - fails to notice the impl on FooUnverified
    //   - adds a derive of NetdocParseable
    //   - calls that parser
    // thereby completely ignoring the signatures.
    $P::assert_not_impl! {
        [signed_documents_should_be_parsed_only_as_foo_unverified <$tgens>]
        $ttype: $P::NetdocParseable
    }
    ${impl $P::$TRAIT} {
      ${if T_IS_SIGNATURE {
        type HashAccu = $SIG_HASH_ACCU_TYPE;
      }}
1558357
        fn $METHOD<'s>(
1558357
            mut input: $P::UnparsedItem<'s>,
1558357
          ${if T_IS_SIGNATURE {
1558357
            document_body: &SignatureHashInputs<'_>,
1558357
            hash_accu: &mut $SIG_HASH_ACCU_TYPE,
1558357
          }}
1558357
        ) -> $P::Result<Self, $P::EP>
        {
            #[allow(unused_imports)] // false positive when macro is used with prelude in scope
            use $P::*;
            $DEFINE_DTRACE
9
            dtrace!(
9
                "item start",
9
                input.keyword().as_str(),
9
                input.args_copy().into_remaining(),
9
                input.object().map(|o| o.label()),
            );
            ${if T_IS_SIGNATURE {
5935
                <$SIG_HASH_ACCU_TYPE as SignatureHashesAccumulator>::update_from_netdoc_body(
5935
                    hash_accu,
5935
                    document_body
5935
                )?;
            }}
1558357
            let object = input.object();
            #[allow(unused)]
1558357
            let mut args = input.args_mut();
          $(
            #[allow(non_snake_case)]
            let $fpatname = ${select1
              F_NORMAL { {
1479988
                  let selector = MultiplicitySelector::<$ftype>::default();
9
                  dtrace!(
9
                      $"field $fname, normal",
9
                      selector.argument_set_debug(),
9
                      args.clone().into_remaining(),
                  );
                ${if not(fmeta(netdoc(with))) {
1479987
                  selector.${paste_spanned $fname check_argument_value_parseable}();
                }}
1479987
                  selector.parse_with(
1297446
                      &mut args,
1297446
                      ${fmeta(netdoc(with))
1297446
                        as path,
1297446
                        default { ItemArgumentParseable }}::${paste_spanned $fname from_args},
1297446
                  ).map_err(args.error_handler(stringify!($fname)))?
              } }
              F_OBJECT { {
283260
                  let selector = MultiplicitySelector::<$ftype>::default();
9
                  dtrace!(
9
                      $"field $fname, object",
9
                      selector.object_set_debug(),
9
                      object.as_ref().map(|o| (o.label(), o.decode_data().map(|d| d.len()))),
                  );
283260
                  let object = object.map(|object| {
272364
                      let data = object.decode_data()?;
                      ${if fmeta(netdoc(object(label))) {
188482
                          if object.label() != ${fmeta(netdoc(object(label))) as str} {
1
                              return Err(EP::ObjectIncorrectLabel)
188481
                          }
                      } else {
83881
                          selector.${paste_spanned $fname check_label}(object.label())?;
                      }}
                      ${if fmeta(netdoc(with)) {
                          ${fmeta(netdoc(with)) as path}::${paste_spanned $fname try_from}
188481
                              (data)
                              .map_err(|_| EP::ObjectInvalidData)
                      } else {
83879
                          selector.${paste_spanned $fname check_object_parseable}();
83879
                          ItemObjectParseable::from_bytes(&data)
                      }}
272364
                  }).transpose()?;
283255
                  selector.resolve_option(object)?
              } }
              F_REST { {
                  dtrace!($"field $fname, rest", args.clone().into_remaining());
                  // consumes `args`, leading to compile error if the rest field
                  // isn't last (or is combined with no_extra_args).
11
                  let args_consume = args;
                  ${if fmeta(netdoc(with)) {
                      ${fmeta(netdoc(with)) as path}::${paste_spanned $fname from_args_rest}
                  } else {
8
                      <$ftype as FromStr>::from_str
8
                  }}
8
                      (args_consume.into_remaining())
                      .map_err(|_| AE::Invalid)
8
                      .map_err(args_consume.error_handler(stringify!($fname)))?
              } }
              F_SKIP { {
1139030
                  <$ftype as Default>::default()
              } }
            };
          )
          ${if approx_equal({}, $( ${when F_OBJECT} $fname )) {
1275087
            if object.is_some() {
                return Err(EP::ObjectUnexpected);
1275087
            }
          }}
          ${if tmeta(netdoc(no_extra_args)) {
68588
            args.reject_extra_args()?;
          }}
9
            dtrace!("item complete Ok");
            #[allow(deprecated)]
1558340
            Ok($tname { $( $fname: $fpatname, ) })
1558357
        }
    }
}