tor-netdoc 0.42.0

Network document formats used with the Tor protocols.
Documentation
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
//! Multiplicity of fields (Items and Arguments)
//!
//! This module supports type-based handling of multiplicity,
//! of Items (within Documents) and Arguments (in Item keyword lines).
//!
//! It is **for use by macros**, rather than directly.
//!
//! See also `encode::multiplicity` which is the corresponding module for encoding.
//!
//! # Explanation
//!
//! We use autoref specialisation to allow macros to dispatch to
//! trait impls for `Vec<T: ItemValueParseable>`, `Option<T>` etc.
//! as well as simply unadorned `T`.
//!
//! We implement traits on a helper type `struct `[`MultiplicitySelector<Field>`].
//!
//! For Items we have `trait `[`ItemSetMethods`].
//!
//! `ItemSetMethods` is implemented for `MultiplicitySelector<Field>`
//! for each supported `Field`.
//! So, for `MultiplicitySelector<T>`, `MultiplicitySelector<Option<T>>`, and `MultiplicitySelector<Vec<T>>`.
//! *But*, for just `T`, the impl is on `&MultiplicitySelector<T>`.
//!
//! When methods on `MultiplicitySelector` are called, the compiler finds
//! the specific implementation for `MultiplicitySelector<Option<_>>` or `..Vec<_>`,
//! or, failing that, derefs and finds the blanket impl on `&MultiplicitySelector<T>`.
//!
//! For Arguments we have [`ArgumentSetMethods`],
//! and for Objects, [`ObjectSetMethods`],
//! which work similarly.
//!
//! (We need separate traits for each of the kinds of netdoc element,
//! for good support of inference in the derive macro.
//! Type inference is particularly difficult during parsing, since we need the type
//! information to flow from the field type, which is the *destination*
//!  to which a value is going to be stored.)

use super::*;
use crate::types::RetainedOrderVec;

/// Helper type that allows us to select an impl of `ItemSetMethods` etc.
///
/// **For use by macros**.
///
/// See the [module-level docs](multiplicity).
///
/// This is distinct from `encode::MultiplicitySelector`,
/// principally because it has the opposite variance.
#[derive(Educe)]
#[educe(Clone, Copy, Default)]
pub struct MultiplicitySelector<Field>(PhantomData<fn() -> Field>);

/// Helper type that allows us to implement Debug
///
/// Returned by [`ItemSetMethods::item_set_debug`] etc.,
/// using information from [`ItemSetMethods::debug_core`] etc.
#[derive(derive_more::Debug)]
#[debug("{}={}", self.0, self.1)]
#[allow(dead_code)] // yes, they are only read by the Debug impl - that's what they're for!
struct DebugHelper(
    /// scope, eg `items`
    &'static str,
    /// multiplicity type pattern, eg `Vec<_>` or `1`
    &'static str,
);

/// Methods for handling some multiplicity of Items, during parsing
///
/// **For use by macros**.
///
/// During parsing, we accumulate into a value of type `Option<Self::Field>`.
/// The semantics of this are item-set-implementation-dependent;
/// using a type which is generic over the field type in a simple way
/// allows the partially-parsed accumulation state for a whole netdoc to have a concrete type.
///
/// See the [module-level docs](multiplicity), and
/// [Field type in `NetdocParseable`](derive_deftly_template_NetdocParseable#field-type).
///
/// # Example
///
/// The code in the (derive) macro output is roughly like this:
///
/// ```
/// use tor_netdoc::parse2::multiplicity::{MultiplicitySelector, ItemSetMethods as _};
///
/// let selector = MultiplicitySelector::<Vec<i32>>::default();
/// let mut accum = None;
/// selector.accumulate(&mut accum, 12).unwrap();
/// let out = selector.finish(accum, "item-set").unwrap();
///
/// assert_eq!(out, [12]);
/// ```
//
// When implementing this, update the documentation in the `NetdocParseable` derive.
pub trait ItemSetMethods: Copy + Sized {
    /// The value for each Item.
    type Each: Sized;

    /// The output type: the type of the field in the netdoc struct.
    type Field: Sized;

    /// Can we accumulate another item ?
    ///
    /// Can be used to help predict whether `accumulate` will throw.
    fn can_accumulate(self, acc: &Option<Self::Field>) -> Result<(), EP>;

    /// Accumulate one value into the accumulator.
    fn accumulate(self, acc: &mut Option<Self::Field>, one: Self::Each) -> Result<(), EP>;

    /// Multiplicity representation for `#[deftly(netdoc(debug))]` output, core
    ///
    /// Should generally be in a form like `Vec<_>`.
    ///
    /// See also [`ItemSetMethods::item_set_debug`], which is what the derives call.
    //
    // This can't be a `Debug` supertrait, because that won't work
    // with the `&'_ MultiplicitySelector<T>` impl.
    fn debug_core(self) -> &'static str;

    /// Multiplicity representation for `#[deftly(netdoc(debug))]` output
    ///
    /// This adds a bit framing and type-fu that allows the derive macro's
    /// call to be as simple as possible.
    ///
    /// See also [`ItemSetMethods::debug_core`], which is what each multiplicity implements.
    //
    // dtrace!, which we use for debugging in the parser macros, doesn't print variable names,
    // thinking things are probably obvious enough.  But for the elector here we want to
    // include `items=`.
    fn item_set_debug(self) -> impl Debug {
        DebugHelper("items", self.debug_core())
    }

    /// Resolve the accumulator into the output.
    fn finish(
        self,
        acc: Option<Self::Field>,
        item_keyword: &'static str,
    ) -> Result<Self::Field, EP>;

    /// If the contained type is a sub-document, call its `is_intro_item_keyword`.
    fn is_intro_item_keyword(self, kw: KeywordRef<'_>) -> bool
    where
        Self::Each: NetdocParseable,
    {
        Self::Each::is_intro_item_keyword(kw)
    }

    /// If the contained type is a sub-document, call its `is_structural_keyword`.
    fn is_structural_keyword(self, kw: KeywordRef<'_>) -> Option<IsStructural>
    where
        Self::Each: NetdocParseable,
    {
        Self::Each::is_structural_keyword(kw)
    }

    /// `finish` for if the contained type is a wsub-document
    ///
    /// Obtain the sub-document's intro keyword from its `doctype_for_error`.
    fn finish_subdoc(self, acc: Option<Self::Field>) -> Result<Self::Field, EP>
    where
        Self::Each: NetdocParseable,
    {
        self.finish(acc, Self::Each::doctype_for_error())
    }

    /// Check that the element type is an Item
    ///
    /// For providing better error messages when struct fields don't implement the right trait.
    /// See `derive.rs`, and search for this method name.
    fn check_item_value_parseable(self)
    where
        Self::Each: ItemValueParseable,
    {
    }
    /// Check that the element type is a Signature
    fn check_signature_item_parseable<H>(self, _: &mut H)
    where
        Self::Each: SignatureItemParseable,
        H: AsMut<<Self::Each as SignatureItemParseable>::HashAccu>,
    {
    }
    /// Check that the element type is a sub-document
    fn check_subdoc_parseable(self)
    where
        Self::Each: NetdocParseable,
    {
    }
    /// Check that the element type is an argument
    fn check_item_argument_parseable(self)
    where
        Self::Each: ItemArgumentParseable,
    {
    }
}
impl<T> ItemSetMethods for MultiplicitySelector<Vec<T>> {
    type Each = T;
    type Field = Vec<T>;
    // We always have None, or Some(nonempty)
    fn can_accumulate(self, _acc: &Option<Vec<T>>) -> Result<(), EP> {
        Ok(())
    }
    fn accumulate(self, acc: &mut Option<Vec<T>>, item: T) -> Result<(), EP> {
        acc.get_or_insert_default().push(item);
        Ok(())
    }
    fn finish(self, acc: Option<Vec<T>>, _keyword: &'static str) -> Result<Vec<T>, EP> {
        Ok(acc.unwrap_or_default())
    }
    fn debug_core(self) -> &'static str {
        "Vec<_>"
    }
}
impl<T> ItemSetMethods for MultiplicitySelector<RetainedOrderVec<T>> {
    type Each = T;
    type Field = RetainedOrderVec<T>;
    // We always have None, or Some(nonempty)
    fn can_accumulate(self, _acc: &Option<RetainedOrderVec<T>>) -> Result<(), EP> {
        Ok(())
    }
    fn accumulate(self, acc: &mut Option<RetainedOrderVec<T>>, item: T) -> Result<(), EP> {
        acc.get_or_insert_default().0.push(item);
        Ok(())
    }
    fn finish(
        self,
        acc: Option<RetainedOrderVec<T>>,
        _keyword: &'static str,
    ) -> Result<RetainedOrderVec<T>, EP> {
        Ok(acc.unwrap_or_default())
    }
    fn debug_core(self) -> &'static str {
        "RetainedOrderVec<_>"
    }
}
impl<T: Ord> ItemSetMethods for MultiplicitySelector<BTreeSet<T>> {
    type Each = T;
    type Field = BTreeSet<T>;
    // We always have None, or Some(nonempty)
    fn can_accumulate(self, _acc: &Option<BTreeSet<T>>) -> Result<(), EP> {
        Ok(())
    }
    fn accumulate(self, acc: &mut Option<BTreeSet<T>>, item: T) -> Result<(), EP> {
        if !acc.get_or_insert_default().insert(item) {
            return Err(EP::ItemRepeated);
        }
        Ok(())
    }
    fn finish(self, acc: Option<BTreeSet<T>>, _keyword: &'static str) -> Result<BTreeSet<T>, EP> {
        Ok(acc.unwrap_or_default())
    }
    fn debug_core(self) -> &'static str {
        "BTreeSet<_>"
    }
}
impl<T> ItemSetMethods for MultiplicitySelector<Option<T>> {
    type Each = T;
    type Field = Option<T>;
    // We always have None, or Some(Some(_))
    fn can_accumulate(self, acc: &Option<Option<T>>) -> Result<(), EP> {
        if acc.is_some() {
            Err(EP::ItemRepeated)?;
        }
        Ok(())
    }
    // We always have None, or Some(Some(_))
    fn accumulate(self, acc: &mut Option<Option<T>>, item: T) -> Result<(), EP> {
        self.can_accumulate(acc)?;
        *acc = Some(Some(item));
        Ok(())
    }
    fn finish(self, acc: Option<Option<T>>, _keyword: &'static str) -> Result<Option<T>, EP> {
        Ok(acc.flatten())
    }
    fn debug_core(self) -> &'static str {
        "Option<_>"
    }
}
impl<T> ItemSetMethods for &'_ MultiplicitySelector<T> {
    type Each = T;
    type Field = T;
    fn can_accumulate(self, acc: &Option<T>) -> Result<(), EP> {
        if acc.is_some() {
            Err(EP::ItemRepeated)?;
        }
        Ok(())
    }
    fn accumulate(self, acc: &mut Option<T>, item: T) -> Result<(), EP> {
        self.can_accumulate(acc)?;
        *acc = Some(item);
        Ok(())
    }
    fn finish(self, acc: Option<T>, keyword: &'static str) -> Result<T, EP> {
        acc.ok_or(EP::MissingItem { keyword })
    }
    fn debug_core(self) -> &'static str {
        // This appears in #[deftly(netdoc(debug))] output for singleton fields.
        // We probably don't want the macros' users to have to think about our
        // autoref-specialisation.  So we don't write anything about `&` here.
        "1"
    }
}

/// Method for handling some multiplicity of Arguments
///
/// **For use by macros**.
///
/// See the [module-level docs](multiplicity), and
/// [Field type in `ItemValueParseable`](derive_deftly_template_ItemValueParseable#field-type).
///
/// # Example
///
/// The code in the (derive) macro output is roughly like this:
///
/// ```
/// use tor_netdoc::parse2::multiplicity::{MultiplicitySelector, ArgumentSetMethods as _};
/// use tor_netdoc::parse2::{ItemArgumentParseable, ItemStream, ParseInput};
/// let doc = "intro-item 12 66\n";
/// let input = ParseInput::new(doc, "<literal>");
/// let mut items = ItemStream::new(&input).unwrap();
/// let mut item = items.next().unwrap().unwrap();
///
/// let args = MultiplicitySelector::<Vec<i32>>::default()
///     .parse_with(item.args_mut(), ItemArgumentParseable::from_args)
///     .unwrap();
/// assert_eq!(args, [12, 66]);
/// ```
//
// When implementing this, update the documentation in the `ItemValueParseable` derive.
pub trait ArgumentSetMethods: Copy + Sized {
    /// The value for each Item.
    type Each: Sized;

    /// The output type: the type of the field in the Item struct.
    ///
    /// This is *not* the type of an individual netdoc argument;
    /// that is not explicitly represented in the trait.
    type Field: Sized;

    /// Parse zero or more argument(s) into `Self::Field`.
    fn parse_with<P>(self, args: &mut ArgumentStream<'_>, parser: P) -> Result<Self::Field, AE>
    where
        P: for<'s> Fn(&mut ArgumentStream<'s>) -> Result<Self::Each, AE>;

    /// Multiplicity representation for `#[deftly(netdoc(debug))]` output, core
    ///
    /// Should generally be in a form like `Vec<_>`.
    ///
    /// See [`ItemSetMethods::debug_core`] and [`ArgumentSetMethods::argument_set_debug`].
    fn debug_core(self) -> &'static str;

    /// Multiplicity representation for `#[deftly(netdoc(debug))]` output
    ///
    /// See [`ItemSetMethods::item_set_debug`] and [`ArgumentSetMethods::debug_core`].
    fn argument_set_debug(self) -> impl Debug {
        DebugHelper("args", self.debug_core())
    }

    /// Check that the element type is an Argument
    ///
    /// For providing better error messages when struct fields don't implement the right trait.
    /// See `derive.rs`, and search for this method name.
    fn check_argument_value_parseable(self)
    where
        Self::Each: ItemArgumentParseable,
    {
    }
}
impl<T> ArgumentSetMethods for MultiplicitySelector<Vec<T>> {
    type Each = T;
    type Field = Vec<T>;
    fn parse_with<P>(self, args: &mut ArgumentStream<'_>, parser: P) -> Result<Self::Field, AE>
    where
        P: for<'s> Fn(&mut ArgumentStream<'s>) -> Result<Self::Each, AE>,
    {
        let mut acc = vec![];
        while args.something_to_yield() {
            acc.push(parser(args)?);
        }
        Ok(acc)
    }
    fn debug_core(self) -> &'static str {
        "Vec<_>"
    }
}
impl<T: Ord> ArgumentSetMethods for MultiplicitySelector<BTreeSet<T>> {
    type Each = T;
    type Field = BTreeSet<T>;
    fn parse_with<P>(self, args: &mut ArgumentStream<'_>, parser: P) -> Result<Self::Field, AE>
    where
        P: for<'s> Fn(&mut ArgumentStream<'s>) -> Result<Self::Each, AE>,
    {
        let mut acc = BTreeSet::new();
        while args.something_to_yield() {
            if !acc.insert(parser(args)?) {
                return Err(AE::Invalid);
            }
        }
        Ok(acc)
    }
    fn debug_core(self) -> &'static str {
        "BTreeSet<_>"
    }
}
impl<T> ArgumentSetMethods for MultiplicitySelector<Option<T>> {
    type Each = T;
    type Field = Option<T>;
    fn parse_with<P>(self, args: &mut ArgumentStream<'_>, parser: P) -> Result<Self::Field, AE>
    where
        P: for<'s> Fn(&mut ArgumentStream<'s>) -> Result<Self::Each, AE>,
    {
        if !args.something_to_yield() {
            return Ok(None);
        }
        Ok(Some(parser(args)?))
    }
    fn debug_core(self) -> &'static str {
        "Option<_>"
    }
}
impl<T> ArgumentSetMethods for &MultiplicitySelector<T> {
    type Each = T;
    type Field = T;
    fn parse_with<P>(self, args: &mut ArgumentStream<'_>, parser: P) -> Result<Self::Field, AE>
    where
        P: for<'s> Fn(&mut ArgumentStream<'s>) -> Result<Self::Each, AE>,
    {
        parser(args)
    }
    fn debug_core(self) -> &'static str {
        "1"
    }
}

/// Method for handling some multiplicity of Objects
///
/// **For use by macros**.
///
/// See the [module-level docs](multiplicity), and
/// [Field type in `ItemValueParseable`](derive_deftly_template_ItemValueParseable#field-type).
///
/// # Example
///
/// The code in the (derive) macro output is roughly like this:
///
/// ```
/// use tor_netdoc::parse2::multiplicity::{MultiplicitySelector, ObjectSetMethods as _};
/// use tor_netdoc::parse2::{ItemStream, ParseInput};
/// let doc = "intro-item\n-----BEGIN OBJECT-----\naGVsbG8=\n-----END OBJECT-----\n";
/// let input = ParseInput::new(doc, "<literal>");
/// let mut items = ItemStream::new(&input).unwrap();
/// let mut item = items.next().unwrap().unwrap();
///
/// let selector = MultiplicitySelector::<Option<String>>::default();
/// let obj = item.object().map(|obj| {
///     let data = obj.decode_data().unwrap();
///     String::from_utf8(data)
/// }).transpose().unwrap();
/// let obj = selector.resolve_option(obj).unwrap();
/// assert_eq!(obj, Some("hello".to_owned()));
/// ```
pub trait ObjectSetMethods: Copy + Sized {
    /// The value for each Item.
    type Each: Sized;

    /// The output type: the type of the field in the Item struct.
    type Field: Sized;

    /// Parse zero or more argument(s) into `Self::Field`.
    fn resolve_option(self, found: Option<Self::Each>) -> Result<Self::Field, EP>;

    /// Multiplicity representation for `#[deftly(netdoc(debug))]` output, core
    ///
    /// Should generally be in a form like `Option<_>`.
    ///
    /// See [`ItemSetMethods::debug_core`] and [`ObjectSetMethods::object_set_debug`].
    fn debug_core(self) -> &'static str;

    /// Multiplicity representation for `#[deftly(netdoc(debug))]` output
    ///
    /// See [`ItemSetMethods::item_set_debug`] and [`ObjectSetMethods::debug_core`].
    fn object_set_debug(self) -> impl Debug {
        DebugHelper("object", self.debug_core())
    }

    /// If the contained type is `ItemObjectParseable`, call its `check_label`
    fn check_label(self, label: &str) -> Result<(), EP>
    where
        Self::Each: ItemObjectParseable,
    {
        Self::Each::check_label(label)
    }

    /// Check that the contained type can be parsed as an object
    fn check_object_parseable(self)
    where
        Self::Each: ItemObjectParseable,
    {
    }
}
impl<T> ObjectSetMethods for MultiplicitySelector<Option<T>> {
    type Field = Option<T>;
    type Each = T;
    fn resolve_option(self, found: Option<Self::Each>) -> Result<Self::Field, EP> {
        Ok(found)
    }
    fn debug_core(self) -> &'static str {
        "Option<_>"
    }
}
impl<T> ObjectSetMethods for &MultiplicitySelector<T> {
    type Field = T;
    type Each = T;
    fn resolve_option(self, found: Option<Self::Each>) -> Result<Self::Field, EP> {
        found.ok_or(EP::MissingObject)
    }
    fn debug_core(self) -> &'static str {
        "1"
    }
}