scale-type-resolver 0.2.0

A low level trait to be generic over how to resolve SCALE type information
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
// Copyright (C) 2024 Parity Technologies (UK) Ltd. (admin@parity.io)
// This file is a part of the scale-decode crate.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//         http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(clippy::type_complexity)]

use crate::{
    BitsOrderFormat, BitsStoreFormat, Field, FieldIter, PathIter, Primitive, ResolvedTypeVisitor,
    UnhandledKind, Variant, VariantIter,
};
use smallvec::SmallVec;

/// A concrete iterator over struct or variant fields information.
pub struct ConcreteFieldIter<'resolver, TypeId> {
    fields: SmallVec<[Option<Field<'resolver, TypeId>>; 16]>,
    idx: usize,
}

impl<'resolver, TypeId> Iterator for ConcreteFieldIter<'resolver, TypeId> {
    type Item = Field<'resolver, TypeId>;
    fn next(&mut self) -> Option<Self::Item> {
        let field = self
            .fields
            .get_mut(self.idx)?
            .take()
            .expect("Expected a field but got None");
        self.idx += 1;
        Some(field)
    }
}

impl<'resolver, TypeId> ExactSizeIterator for ConcreteFieldIter<'resolver, TypeId> {
    fn len(&self) -> usize {
        self.fields.len()
    }
}

/// This is a concrete visitor which implements [`ResolvedTypeVisitor`]. It's instantiated by
/// calling the **standalone** [`new`] function; see the docs there for more information.
pub struct ConcreteResolvedTypeVisitor<
    'resolver,
    Context,
    TypeId,
    Output,
    UnhandledFn,
    NotFoundFn,
    CompositeFn,
    VariantFn,
    SequenceFn,
    ArrayFn,
    TupleFn,
    PrimitiveFn,
    CompactFn,
    BitSequenceFn,
> {
    _marker: core::marker::PhantomData<(TypeId, Output, &'resolver ())>,
    context: Context,
    visit_unhandled: UnhandledFn,
    visit_not_found: NotFoundFn,
    visit_composite: CompositeFn,
    visit_variant: VariantFn,
    visit_sequence: SequenceFn,
    visit_array: ArrayFn,
    visit_tuple: TupleFn,
    visit_primitive: PrimitiveFn,
    visit_compact: CompactFn,
    visit_bit_sequence: BitSequenceFn,
}

/// Instantiate a new [`ConcreteResolvedTypeVisitor`] by providing a closure which is
/// called by default if we don't add any explicit handler for a given SCALE type.
///
/// It's expected that you'll attach handlers for any types you're interested in getting
/// more details about like so:
///
/// ```rust
/// use scale_type_resolver::{ TypeResolver, ResolvedTypeVisitor };
///
/// // Some dummy type that we're saying can resolve types:
/// struct MyTypeResolver;
/// impl TypeResolver for MyTypeResolver {
///     type TypeId = u32;
///     type Error = u8;
///     fn resolve_type<'this, V: ResolvedTypeVisitor<'this, TypeId = Self::TypeId>>(
///         &'this self,
///         type_id: Self::TypeId,
///         visitor: V,
///     ) -> Result<V::Value, Self::Error> {
///         Ok(visitor.visit_not_found())
///     }
/// }
///
/// // Now, we can create a visitor using this `visitor::new` function.
/// // This has specific handling for composite and variant types, falling
/// // back to returning `1u64` if some other type was found.
/// let context = ();
/// let visitor = scale_type_resolver::visitor::new(context, |_context, _unhandled_kind| 1u64)
///     .visit_composite(|_context, _composite_path, _composite_fields| 2)
///     .visit_primitive(|_context, _primitive_type| 3);
///
/// // Now, when we provide the visitor to a type resolver, we'll get back a result
/// // containing either the value returned from the matched `visit_*` call above, or
/// // an error if the type resolver itself had an issue.
/// MyTypeResolver.resolve_type(123, visitor);
/// ```
///
/// The `visit_*` methods provided each take closures which have a similar type signature to the
/// underlying trait methods on [`ResolvedTypeVisitor`], with small differences where necessary to
/// avoid type and ownership issues. The first argument to every function is some arbitrary context
/// which is provided as the first argument to [`crate::visitor::new()`].
///
/// Using this concrete visitor is expected to be almost as optimal as implementing the
/// [`ResolvedTypeVisitor`] trait manually. One area where it makes a small sacrifice to this is in
/// the [`ConcreteResolvedTypeVisitor::visit_variant()`] method, which must collect the variant
/// fields into a [`smallvec::SmallVec`] to avoid ownership issues. This will only allocate if more
/// than 16 variant fields exist. The default "unhandled" function here must also implement `Clone`,
/// which isn't necessary in a raw trait implementation, since it will, by default, be called in all
/// of the other impls if no methods are provided.
pub fn new<'resolver, Context, TypeId, Output, NewUnhandledFn>(
    context: Context,
    unhandled_fn: NewUnhandledFn,
) -> ConcreteResolvedTypeVisitor<
    'resolver,
    Context,
    TypeId,
    Output,
    NewUnhandledFn,
    impl FnOnce(Context) -> Output,
    impl FnOnce(
        Context,
        &mut dyn PathIter<'resolver>,
        &'_ mut dyn FieldIter<'resolver, TypeId>,
    ) -> Output,
    impl FnOnce(
        Context,
        &mut dyn PathIter<'resolver>,
        &'_ mut dyn VariantIter<'resolver, ConcreteFieldIter<'resolver, TypeId>>,
    ) -> Output,
    impl FnOnce(Context, &mut dyn PathIter<'resolver>, TypeId) -> Output,
    impl FnOnce(Context, TypeId, usize) -> Output,
    impl FnOnce(Context, &'_ mut dyn ExactSizeIterator<Item = TypeId>) -> Output,
    impl FnOnce(Context, Primitive) -> Output,
    impl FnOnce(Context, TypeId) -> Output,
    impl FnOnce(Context, BitsStoreFormat, BitsOrderFormat) -> Output,
>
where
    NewUnhandledFn: FnOnce(Context, UnhandledKind) -> Output + Clone,
{
    let visit_unhandled = unhandled_fn.clone();

    // We explicitly define all of the other impls here so that the full concrete
    // type of ConcreteResolvedTypeVisitor is known immediately (albeit using unnameable
    // types). If we used `Option`s here instead, we'd struggle to resolve the concrete
    // `T` in each `Option<T>, and our goal is to have good type inference when using this.
    let visit_not_found = {
        let u = unhandled_fn.clone();
        move |ctx| u(ctx, UnhandledKind::NotFound)
    };
    let visit_composite = {
        let u = unhandled_fn.clone();
        move |ctx, _: &mut dyn PathIter<'resolver>, _: &mut dyn FieldIter<'resolver, TypeId>| {
            u(ctx, UnhandledKind::Composite)
        }
    };
    let visit_variant = {
        let u = unhandled_fn.clone();
        move |ctx,
              _: &mut dyn PathIter<'resolver>,
              _: &mut dyn VariantIter<'resolver, ConcreteFieldIter<'resolver, TypeId>>| {
            u(ctx, UnhandledKind::Variant)
        }
    };
    let visit_sequence = {
        let u = unhandled_fn.clone();
        move |ctx, _: &mut dyn PathIter<'resolver>, _| u(ctx, UnhandledKind::Sequence)
    };
    let visit_array = {
        let u = unhandled_fn.clone();
        move |ctx, _, _| u(ctx, UnhandledKind::Array)
    };
    let visit_tuple = {
        let u = unhandled_fn.clone();
        move |ctx, _: &mut dyn ExactSizeIterator<Item = TypeId>| u(ctx, UnhandledKind::Tuple)
    };
    let visit_primitive = {
        let u = unhandled_fn.clone();
        move |ctx, _| u(ctx, UnhandledKind::Primitive)
    };
    let visit_compact = {
        let u = unhandled_fn.clone();
        move |ctx, _| u(ctx, UnhandledKind::Compact)
    };
    let visit_bit_sequence = {
        let u = unhandled_fn.clone();
        move |ctx, _, _| u(ctx, UnhandledKind::BitSequence)
    };

    ConcreteResolvedTypeVisitor {
        _marker: core::marker::PhantomData,
        context,
        visit_unhandled,
        visit_not_found,
        visit_composite,
        visit_variant,
        visit_sequence,
        visit_array,
        visit_tuple,
        visit_primitive,
        visit_compact,
        visit_bit_sequence,
    }
}

impl<
        'resolver,
        Context,
        TypeId,
        Output,
        UnhandledFn,
        NotFoundFn,
        CompositeFn,
        VariantFn,
        SequenceFn,
        ArrayFn,
        TupleFn,
        PrimitiveFn,
        CompactFn,
        BitSequenceFn,
    >
    ConcreteResolvedTypeVisitor<
        'resolver,
        Context,
        TypeId,
        Output,
        UnhandledFn,
        NotFoundFn,
        CompositeFn,
        VariantFn,
        SequenceFn,
        ArrayFn,
        TupleFn,
        PrimitiveFn,
        CompactFn,
        BitSequenceFn,
    >
{
    /// Provide a closure that's called when [`ResolvedTypeVisitor::visit_not_found()`] is.
    pub fn visit_not_found<NewNotFoundFn>(
        self,
        new_not_found_fn: NewNotFoundFn,
    ) -> ConcreteResolvedTypeVisitor<
        'resolver,
        Context,
        TypeId,
        Output,
        UnhandledFn,
        NewNotFoundFn,
        CompositeFn,
        VariantFn,
        SequenceFn,
        ArrayFn,
        TupleFn,
        PrimitiveFn,
        CompactFn,
        BitSequenceFn,
    >
    where
        NewNotFoundFn: FnOnce(Context) -> Output,
    {
        ConcreteResolvedTypeVisitor {
            _marker: core::marker::PhantomData,
            context: self.context,
            visit_unhandled: self.visit_unhandled,
            visit_not_found: new_not_found_fn,
            visit_composite: self.visit_composite,
            visit_variant: self.visit_variant,
            visit_sequence: self.visit_sequence,
            visit_array: self.visit_array,
            visit_tuple: self.visit_tuple,
            visit_primitive: self.visit_primitive,
            visit_compact: self.visit_compact,
            visit_bit_sequence: self.visit_bit_sequence,
        }
    }

    /// Provide a closure that's called when [`ResolvedTypeVisitor::visit_composite()`] is.
    pub fn visit_composite<NewCompositeFn>(
        self,
        new_composite_fn: NewCompositeFn,
    ) -> ConcreteResolvedTypeVisitor<
        'resolver,
        Context,
        TypeId,
        Output,
        UnhandledFn,
        NotFoundFn,
        NewCompositeFn,
        VariantFn,
        SequenceFn,
        ArrayFn,
        TupleFn,
        PrimitiveFn,
        CompactFn,
        BitSequenceFn,
    >
    where
        NewCompositeFn: FnOnce(
            Context,
            &mut dyn PathIter<'resolver>,
            &mut dyn FieldIter<'resolver, TypeId>,
        ) -> Output,
    {
        ConcreteResolvedTypeVisitor {
            _marker: core::marker::PhantomData,
            context: self.context,
            visit_unhandled: self.visit_unhandled,
            visit_not_found: self.visit_not_found,
            visit_composite: new_composite_fn,
            visit_variant: self.visit_variant,
            visit_sequence: self.visit_sequence,
            visit_array: self.visit_array,
            visit_tuple: self.visit_tuple,
            visit_primitive: self.visit_primitive,
            visit_compact: self.visit_compact,
            visit_bit_sequence: self.visit_bit_sequence,
        }
    }

    /// Provide a closure that's called when [`ResolvedTypeVisitor::visit_variant()`] is.
    pub fn visit_variant<NewVariantFn>(
        self,
        new_variant_fn: NewVariantFn,
    ) -> ConcreteResolvedTypeVisitor<
        'resolver,
        Context,
        TypeId,
        Output,
        UnhandledFn,
        NotFoundFn,
        CompositeFn,
        NewVariantFn,
        SequenceFn,
        ArrayFn,
        TupleFn,
        PrimitiveFn,
        CompactFn,
        BitSequenceFn,
    >
    where
        NewVariantFn: FnOnce(
            Context,
            &mut dyn PathIter<'resolver>,
            &mut dyn VariantIter<'resolver, ConcreteFieldIter<'resolver, TypeId>>,
        ) -> Output,
    {
        ConcreteResolvedTypeVisitor {
            _marker: core::marker::PhantomData,
            context: self.context,
            visit_unhandled: self.visit_unhandled,
            visit_not_found: self.visit_not_found,
            visit_composite: self.visit_composite,
            visit_variant: new_variant_fn,
            visit_sequence: self.visit_sequence,
            visit_array: self.visit_array,
            visit_tuple: self.visit_tuple,
            visit_primitive: self.visit_primitive,
            visit_compact: self.visit_compact,
            visit_bit_sequence: self.visit_bit_sequence,
        }
    }

    /// Provide a closure that's called when [`ResolvedTypeVisitor::visit_sequence()`] is.
    pub fn visit_sequence<NewSequenceFn>(
        self,
        new_sequence_fn: NewSequenceFn,
    ) -> ConcreteResolvedTypeVisitor<
        'resolver,
        Context,
        TypeId,
        Output,
        UnhandledFn,
        NotFoundFn,
        CompositeFn,
        VariantFn,
        NewSequenceFn,
        ArrayFn,
        TupleFn,
        PrimitiveFn,
        CompactFn,
        BitSequenceFn,
    >
    where
        NewSequenceFn: FnOnce(Context, &mut dyn PathIter<'resolver>, TypeId) -> Output,
        TypeId: 'resolver,
    {
        ConcreteResolvedTypeVisitor {
            _marker: core::marker::PhantomData,
            context: self.context,
            visit_unhandled: self.visit_unhandled,
            visit_not_found: self.visit_not_found,
            visit_composite: self.visit_composite,
            visit_variant: self.visit_variant,
            visit_sequence: new_sequence_fn,
            visit_array: self.visit_array,
            visit_tuple: self.visit_tuple,
            visit_primitive: self.visit_primitive,
            visit_compact: self.visit_compact,
            visit_bit_sequence: self.visit_bit_sequence,
        }
    }

    /// Provide a closure that's called when [`ResolvedTypeVisitor::visit_array()`] is.
    pub fn visit_array<NewArrayFn>(
        self,
        new_array_fn: NewArrayFn,
    ) -> ConcreteResolvedTypeVisitor<
        'resolver,
        Context,
        TypeId,
        Output,
        UnhandledFn,
        NotFoundFn,
        CompositeFn,
        VariantFn,
        SequenceFn,
        NewArrayFn,
        TupleFn,
        PrimitiveFn,
        CompactFn,
        BitSequenceFn,
    >
    where
        NewArrayFn: FnOnce(Context, TypeId, usize) -> Output,
        TypeId: 'resolver,
    {
        ConcreteResolvedTypeVisitor {
            _marker: core::marker::PhantomData,
            context: self.context,
            visit_unhandled: self.visit_unhandled,
            visit_not_found: self.visit_not_found,
            visit_composite: self.visit_composite,
            visit_variant: self.visit_variant,
            visit_sequence: self.visit_sequence,
            visit_array: new_array_fn,
            visit_tuple: self.visit_tuple,
            visit_primitive: self.visit_primitive,
            visit_compact: self.visit_compact,
            visit_bit_sequence: self.visit_bit_sequence,
        }
    }

    /// Provide a closure that's called when [`ResolvedTypeVisitor::visit_tuple()`] is.
    pub fn visit_tuple<NewTupleFn>(
        self,
        new_tuple_fn: NewTupleFn,
    ) -> ConcreteResolvedTypeVisitor<
        'resolver,
        Context,
        TypeId,
        Output,
        UnhandledFn,
        NotFoundFn,
        CompositeFn,
        VariantFn,
        SequenceFn,
        ArrayFn,
        NewTupleFn,
        PrimitiveFn,
        CompactFn,
        BitSequenceFn,
    >
    where
        NewTupleFn: FnOnce(Context, &mut dyn ExactSizeIterator<Item = TypeId>) -> Output,
    {
        ConcreteResolvedTypeVisitor {
            _marker: core::marker::PhantomData,
            context: self.context,
            visit_unhandled: self.visit_unhandled,
            visit_not_found: self.visit_not_found,
            visit_composite: self.visit_composite,
            visit_variant: self.visit_variant,
            visit_sequence: self.visit_sequence,
            visit_array: self.visit_array,
            visit_tuple: new_tuple_fn,
            visit_primitive: self.visit_primitive,
            visit_compact: self.visit_compact,
            visit_bit_sequence: self.visit_bit_sequence,
        }
    }

    /// Provide a closure that's called when [`ResolvedTypeVisitor::visit_primitive()`] is.
    pub fn visit_primitive<NewPrimitiveFn>(
        self,
        new_primitive_fn: NewPrimitiveFn,
    ) -> ConcreteResolvedTypeVisitor<
        'resolver,
        Context,
        TypeId,
        Output,
        UnhandledFn,
        NotFoundFn,
        CompositeFn,
        VariantFn,
        SequenceFn,
        ArrayFn,
        TupleFn,
        NewPrimitiveFn,
        CompactFn,
        BitSequenceFn,
    >
    where
        NewPrimitiveFn: FnOnce(Context, Primitive) -> Output,
    {
        ConcreteResolvedTypeVisitor {
            _marker: core::marker::PhantomData,
            context: self.context,
            visit_unhandled: self.visit_unhandled,
            visit_not_found: self.visit_not_found,
            visit_composite: self.visit_composite,
            visit_variant: self.visit_variant,
            visit_sequence: self.visit_sequence,
            visit_array: self.visit_array,
            visit_tuple: self.visit_tuple,
            visit_primitive: new_primitive_fn,
            visit_compact: self.visit_compact,
            visit_bit_sequence: self.visit_bit_sequence,
        }
    }

    /// Provide a closure that's called when [`ResolvedTypeVisitor::visit_compact()`] is.
    pub fn visit_compact<NewCompactFn>(
        self,
        new_compact_fn: NewCompactFn,
    ) -> ConcreteResolvedTypeVisitor<
        'resolver,
        Context,
        TypeId,
        Output,
        UnhandledFn,
        NotFoundFn,
        CompositeFn,
        VariantFn,
        SequenceFn,
        ArrayFn,
        TupleFn,
        PrimitiveFn,
        NewCompactFn,
        BitSequenceFn,
    >
    where
        NewCompactFn: FnOnce(Context, TypeId) -> Output,
        TypeId: 'resolver,
    {
        ConcreteResolvedTypeVisitor {
            _marker: core::marker::PhantomData,
            context: self.context,
            visit_unhandled: self.visit_unhandled,
            visit_not_found: self.visit_not_found,
            visit_composite: self.visit_composite,
            visit_variant: self.visit_variant,
            visit_sequence: self.visit_sequence,
            visit_array: self.visit_array,
            visit_tuple: self.visit_tuple,
            visit_primitive: self.visit_primitive,
            visit_compact: new_compact_fn,
            visit_bit_sequence: self.visit_bit_sequence,
        }
    }

    /// Provide a closure that's called when [`ResolvedTypeVisitor::visit_bit_sequence()`] is.
    pub fn visit_bit_sequence<NewBitSequenceFn>(
        self,
        new_bit_sequence_fn: NewBitSequenceFn,
    ) -> ConcreteResolvedTypeVisitor<
        'resolver,
        Context,
        TypeId,
        Output,
        UnhandledFn,
        NotFoundFn,
        CompositeFn,
        VariantFn,
        SequenceFn,
        ArrayFn,
        TupleFn,
        PrimitiveFn,
        CompactFn,
        NewBitSequenceFn,
    >
    where
        NewBitSequenceFn: FnOnce(Context, BitsStoreFormat, BitsOrderFormat) -> Output,
    {
        ConcreteResolvedTypeVisitor {
            _marker: core::marker::PhantomData,
            context: self.context,
            visit_unhandled: self.visit_unhandled,
            visit_not_found: self.visit_not_found,
            visit_composite: self.visit_composite,
            visit_variant: self.visit_variant,
            visit_sequence: self.visit_sequence,
            visit_array: self.visit_array,
            visit_tuple: self.visit_tuple,
            visit_primitive: self.visit_primitive,
            visit_compact: self.visit_compact,
            visit_bit_sequence: new_bit_sequence_fn,
        }
    }
}

// our actual implementation of `ResolvedTypeVisitor` just delegates to the provided callbacks.
impl<
        'resolver,
        Context,
        TypeId,
        Output,
        UnhandledFn,
        NotFoundFn,
        CompositeFn,
        VariantFn,
        SequenceFn,
        ArrayFn,
        TupleFn,
        PrimitiveFn,
        CompactFn,
        BitSequenceFn,
    > ResolvedTypeVisitor<'resolver>
    for ConcreteResolvedTypeVisitor<
        'resolver,
        Context,
        TypeId,
        Output,
        UnhandledFn,
        NotFoundFn,
        CompositeFn,
        VariantFn,
        SequenceFn,
        ArrayFn,
        TupleFn,
        PrimitiveFn,
        CompactFn,
        BitSequenceFn,
    >
where
    TypeId: Clone + Default + core::fmt::Debug + 'static,
    UnhandledFn: FnOnce(Context, UnhandledKind) -> Output,
    NotFoundFn: FnOnce(Context) -> Output,
    CompositeFn: FnOnce(
        Context,
        &mut dyn PathIter<'resolver>,
        &mut dyn FieldIter<'resolver, TypeId>,
    ) -> Output,
    VariantFn: FnOnce(
        Context,
        &mut dyn PathIter<'resolver>,
        &mut dyn VariantIter<'resolver, ConcreteFieldIter<'resolver, TypeId>>,
    ) -> Output,
    SequenceFn: FnOnce(Context, &mut dyn PathIter<'resolver>, TypeId) -> Output,
    ArrayFn: FnOnce(Context, TypeId, usize) -> Output,
    TupleFn: FnOnce(Context, &mut dyn ExactSizeIterator<Item = TypeId>) -> Output,
    PrimitiveFn: FnOnce(Context, Primitive) -> Output,
    CompactFn: FnOnce(Context, TypeId) -> Output,
    BitSequenceFn: FnOnce(Context, BitsStoreFormat, BitsOrderFormat) -> Output,
{
    type TypeId = TypeId;
    type Value = Output;

    fn visit_unhandled(self, kind: UnhandledKind) -> Self::Value {
        (self.visit_unhandled)(self.context, kind)
    }

    fn visit_not_found(self) -> Self::Value {
        (self.visit_not_found)(self.context)
    }

    fn visit_composite<Path, Fields>(self, mut path: Path, mut fields: Fields) -> Self::Value
    where
        Path: PathIter<'resolver>,
        Fields: FieldIter<'resolver, Self::TypeId>,
    {
        (self.visit_composite)(
            self.context,
            &mut path,
            &mut fields as &mut dyn FieldIter<'resolver, Self::TypeId>,
        )
    }

    fn visit_variant<Path, Fields, Var>(self, mut path: Path, variants: Var) -> Self::Value
    where
        Path: PathIter<'resolver>,
        Fields: FieldIter<'resolver, Self::TypeId>,
        Var: VariantIter<'resolver, Fields>,
    {
        // We need to collect the fields of each variant into a
        // concrete type because the Var iterator owns them. We use
        // smallvec to avoid allocating except in exceptional cases.
        let mut var_iter = variants.map(|v| Variant {
            index: v.index,
            name: v.name,
            fields: ConcreteFieldIter {
                fields: v.fields.map(Some).collect(),
                idx: 0,
            },
        });

        (self.visit_variant)(self.context, &mut path, &mut var_iter)
    }

    fn visit_sequence<Path>(self, mut path: Path, type_id: Self::TypeId) -> Self::Value
    where
        Path: PathIter<'resolver>,
    {
        (self.visit_sequence)(self.context, &mut path, type_id)
    }

    fn visit_array(self, type_id: Self::TypeId, len: usize) -> Self::Value {
        (self.visit_array)(self.context, type_id, len)
    }

    fn visit_tuple<TypeIds>(self, mut type_ids: TypeIds) -> Self::Value
    where
        TypeIds: ExactSizeIterator<Item = Self::TypeId>,
    {
        (self.visit_tuple)(
            self.context,
            &mut type_ids as &mut dyn ExactSizeIterator<Item = Self::TypeId>,
        )
    }

    fn visit_primitive(self, primitive: Primitive) -> Self::Value {
        (self.visit_primitive)(self.context, primitive)
    }

    fn visit_compact(self, type_id: Self::TypeId) -> Self::Value {
        (self.visit_compact)(self.context, type_id)
    }

    fn visit_bit_sequence(
        self,
        store_format: BitsStoreFormat,
        order_format: BitsOrderFormat,
    ) -> Self::Value {
        (self.visit_bit_sequence)(self.context, store_format, order_format)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::TypeResolver;

    // This is mainly just to check that we can instantiate a visitor
    // without needing to provide lots of explicit types.
    #[test]
    fn check_type_inference() {
        let visitor = new((), |_, _| 1u64)
            .visit_array(|_, _, _| 2)
            .visit_composite(|_, _, _| 3)
            .visit_bit_sequence(|_, _, _| 4)
            .visit_compact(|_, _| 5)
            .visit_not_found(|_| 6)
            .visit_tuple(|_, _| 8)
            .visit_variant(|_, _, _| 9);
        // We deliberately don't implement all methods to prove that
        // type inference works regardless:
        // .visit_primitive(|_,_| 7)
        // .visit_sequence(|_,_| 10);

        struct Foo;
        impl crate::TypeResolver for Foo {
            type TypeId = u32;
            type Error = u8;

            fn resolve_type<'this, V: ResolvedTypeVisitor<'this, TypeId = Self::TypeId>>(
                &'this self,
                _type_id: Self::TypeId,
                visitor: V,
            ) -> Result<V::Value, Self::Error> {
                Ok(visitor.visit_not_found())
            }
        }

        assert_eq!(Foo.resolve_type(123, visitor).unwrap(), 6);
    }
}