flow-abi 0.1.0-rc.5

The host boundary's value encoding: the binary encoding and the JSON form, the canonical form and its hash, JSON Schemas, Tool signatures, and the answers a Tool call passes.
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
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
//! Decoding a value of a declared type (`abi.md`, *Decoding*).
//!
//! Decoding is directed by the type and never coerces, guesses a
//! constructor, fills a default or repairs a value. Every failure names where
//! it happened and why.

use std::borrow::Cow;
use std::sync::Arc;

use flow_types::{JsonValueCtor, OptionCtor, Payload};
use flow_value::{Bytes, Decimal, Dict, Int, Set, Text, Value, Variant};
use num_bigint::BigInt;

use crate::build::{Begun, Frame, Make, Source, build, distinct_dict, distinct_set, normal};
use crate::catalog::{Catalog, StdForm};
use crate::error::{DecodeError, DecodeErrorKind, Place};
use crate::form::part_types;
use crate::json::{Json, parse, quote};
use crate::limits::Limits;
use crate::time;
use flow_types::{Body, Crossing, Settings, Spelling, Type};

/// What is being decoded, which decides what a field the type does not
/// declare means and which types decoding may build ([`Mode::settings`]).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Mode {
    /// A Tool reply: an undeclared field is ignored.
    Reply,
    /// The text `json.decode` reads: an undeclared field is ignored, and a
    /// host value is refused, as in a run's input.
    Decode,
    /// `json.decode` with `json.Names.Relaxed`: as [`Mode::Decode`], and
    /// each record field and enum constructor the type declares is matched
    /// by its relaxed key ([`Spelling::Relaxed`]).
    Relaxed,
    /// A run's input: an undeclared field is refused, and so is a host value,
    /// since input is data.
    Input,
    /// A value the program made, read back from its canonical text, such as
    /// a checkpoint's arguments on resume. This is not decoding (`abi.md`,
    /// *Decoding*): every type is rebuilt, opaque types and host tokens
    /// included, and a type with a part that has no encoding, such as a
    /// list of functions, whose text holds no value there. An undeclared
    /// field is refused, since the text is canonical.
    Rebuild,
}

impl Mode {
    /// What a type decoded in this mode is judged for.
    pub const fn settings(self) -> Settings {
        match self {
            Mode::Reply => REPLY,
            Mode::Decode | Mode::Input => INPUT,
            Mode::Relaxed => RELAXED,
            Mode::Rebuild => REBUILD,
        }
    }

    /// How a name the JSON writes is matched with a name the type declares.
    pub(crate) const fn spelling(self) -> Spelling {
        self.settings().names
    }
}

/// A Tool's reply: data that crosses the boundary, with no opaque part,
/// which may carry the host's tokens.
pub const REPLY: Settings = Settings {
    data: true,
    host_ok: true,
    no_opaque: true,
    crossing: Crossing::Crosses,
    names: Spelling::Exact,
};

/// A run's input, and what `json.decode` builds: data with no opaque part,
/// which carries no host token either, since only a Tool's answer may.
pub const INPUT: Settings = Settings {
    host_ok: false,
    ..REPLY
};

/// What `json.decode` with `json.Names.Relaxed` builds: as [`INPUT`], with
/// each name the type declares matched by its relaxed key.
pub(crate) const RELAXED: Settings = Settings {
    names: Spelling::Relaxed,
    ..INPUT
};

/// A generic Tool's type argument, which the call's types bind: data with
/// no opaque part, as a run's input is, but which crosses no boundary
/// unless the Tool's parameters or result carry it (`tools.md`, *Generic
/// Tools*).
pub const BINDING: Settings = Settings {
    crossing: Crossing::Stays,
    ..INPUT
};

/// A value the program made, rebuilt from its canonical text: no type is
/// refused, but one whose type parameter is unbound has no encoding.
pub const REBUILD: Settings = Settings {
    data: false,
    host_ok: true,
    no_opaque: false,
    crossing: Crossing::Stays,
    names: Spelling::Exact,
};

/// An existing value carried across a Tool boundary, which may be opaque
/// or hold the host's tokens.
pub const CROSSING: Settings = Settings {
    no_opaque: false,
    ..REPLY
};

/// Decodes `text` as a value of `ty`.
///
/// # Errors
///
/// A [`DecodeError`] when `text` is not JSON within `limits`, or the JSON
/// is not a value of `ty` in `mode`.
pub fn decode_text(
    catalog: &Catalog,
    ty: &Type,
    text: &str,
    mode: Mode,
    limits: &Limits,
) -> Result<Value, DecodeError> {
    decodable(catalog, ty, mode.settings())?;
    let json = parse(text, limits)?;
    run(catalog, ty, &json, mode, limits)
}

/// Decodes `json` as a value of `ty`.
///
/// # Errors
///
/// A [`DecodeError`] when `ty` cannot be decoded in `mode`, or `json` is
/// not a value of it within `limits`.
pub fn decode(
    catalog: &Catalog,
    ty: &Type,
    json: &Json,
    mode: Mode,
    limits: &Limits,
) -> Result<Value, DecodeError> {
    decodable(catalog, ty, mode.settings())?;
    run(catalog, ty, json, mode, limits)
}

fn run(
    catalog: &Catalog,
    ty: &Type,
    json: &Json,
    mode: Mode,
    limits: &Limits,
) -> Result<Value, DecodeError> {
    Decoder {
        catalog,
        mode,
        limits,
        path: Place::default(),
    }
    .value(ty, json, 0)
}

/// Whether a value of `ty` may be built or carried where `settings` judge
/// it, such as a mode's ([`Mode::settings`]) or [`CROSSING`]
/// (`tools.md`, *Decoding*). This is judged of the type, before any text is
/// read, so an absent part refuses as surely as a present one, and a type
/// parameter left unbound refuses every judgment.
///
/// # Errors
///
/// A [`DecodeError`] naming the first part of `ty` the judgment refuses.
pub fn decodable(catalog: &Catalog, ty: &Type, settings: Settings) -> Result<(), DecodeError> {
    match catalog.problem(ty, settings) {
        Some(problem) => Err(DecodeError::of(
            &Place::default(),
            DecodeErrorKind::Mismatch,
            problem,
        )),
        None => Ok(()),
    }
}

struct Decoder<'c> {
    catalog: &'c Catalog,
    mode: Mode,
    limits: &'c Limits,
    path: Place,
}

impl<'c> Decoder<'c> {
    fn refuse(&self, kind: DecodeErrorKind, problem: impl Into<String>) -> DecodeError {
        DecodeError::of(&self.path, kind, problem.into())
    }

    fn expected(&self, what: &str, json: &Json) -> DecodeError {
        self.refuse(
            DecodeErrorKind::Mismatch,
            format!("should be {what}, not {}", json.kind()),
        )
    }

    /// Enters an aggregate `level` deep, which [`Limits::depth`] bounds.
    fn enter(&self, level: usize) -> Result<usize, DecodeError> {
        let level = level + 1;
        if level > self.limits.depth {
            return Err(self.refuse(
                DecodeErrorKind::TooLarge,
                format!("nests deeper than {} levels", self.limits.depth),
            ));
        }
        Ok(level)
    }

    fn text(&self, text: &str) -> Result<Text, DecodeError> {
        if text.len() > self.limits.text_bytes {
            return Err(self.refuse(
                DecodeErrorKind::TooLarge,
                format!("is longer than {} bytes", self.limits.text_bytes),
            ));
        }
        Ok(Text::new(text))
    }

    /// Decodes a value of `ty` from `json`, `level` deep. The aggregates
    /// it is inside wait on a stack on the heap, so the native stack does
    /// not grow with the value's depth.
    fn value(&mut self, ty: &Type, json: &Json, level: usize) -> Result<Value, DecodeError> {
        let root = self.begin(&Cow::Borrowed(ty), json, level)?;
        build(self, root)
    }

    /// Begins decoding a value of `ty` from `json`: one that holds no other
    /// value is done at once, and an aggregate is opened.
    fn begin<'t, 'j>(
        &mut self,
        ty: &Cow<'t, Type>,
        json: &'j Json,
        level: usize,
    ) -> Result<Begun<Parts<'t, 'c, 'j>>, DecodeError> {
        let value = match (&**ty, json) {
            (Type::Int, Json::Number(number)) => Value::Int(self.int(number)?),
            (Type::Int, _) => return Err(self.expected("an integer", json)),
            (Type::Decimal, Json::Number(number)) => self.decimal(number)?,
            (Type::Decimal, _) => return Err(self.expected("a number", json)),
            (Type::Bool, Json::Bool(flag)) => Value::Bool(*flag),
            (Type::Bool, _) => return Err(self.expected("a boolean", json)),
            (Type::Text, Json::String(text)) => Value::Text(self.text(text)?),
            (Type::Text, _) => return Err(self.expected("a string", json)),
            (Type::Bytes, Json::String(text)) => Value::Bytes(self.bytes(text)?),
            (Type::Bytes, _) => return Err(self.expected("a base64 string", json)),
            (Type::Duration, Json::String(text)) => {
                Value::Duration(time::duration(text).ok_or_else(|| {
                    self.refuse(DecodeErrorKind::Mismatch, "should be an ISO 8601 duration")
                })?)
            }
            (Type::Duration, _) => return Err(self.expected("an ISO 8601 duration", json)),
            (Type::Instant, Json::String(text)) => {
                Value::Instant(time::instant(text).ok_or_else(|| {
                    self.refuse(
                        DecodeErrorKind::Mismatch,
                        "should be an ISO 8601 date and time",
                    )
                })?)
            }
            (Type::Instant, _) => return Err(self.expected("an ISO 8601 date and time", json)),
            (Type::Unit, Json::Array(items)) if items.is_empty() => Value::Unit,
            (Type::Unit, _) => return Err(self.expected("`[]`", json)),
            // Only rebuilding reaches a type with no encoding, and a value
            // the program made holds nothing of one: had it held one, no
            // checkpoint would have been taken.
            (Type::NotData | Type::Function { .. }, _) => {
                return Err(self.refuse(
                    DecodeErrorKind::Mismatch,
                    "has a type with no encoding, so it holds no value",
                ));
            }
            // Only `Never`, and a task outside a checkpoint, reach here of
            // these: the others were refused before any text was read.
            (Type::Never | Type::Param(_) | Type::Task(_), _) => {
                return Err(self.refuse(
                    DecodeErrorKind::Mismatch,
                    "has a type with no values to decode",
                ));
            }
            (Type::Json, _) => return self.raw(json, level),
            (Type::List(_), Json::Array(items)) => {
                let level = self.enter(level)?;
                return Ok(Frame::open(
                    Make::List,
                    Parts::Items(part_types(ty).swap_remove(0), items),
                    0,
                    level,
                ));
            }
            (Type::Set(_), Json::Array(items)) => {
                let level = self.enter(level)?;
                return Ok(Frame::open(
                    Make::Set,
                    Parts::Items(part_types(ty).swap_remove(0), items),
                    0,
                    level,
                ));
            }
            (Type::List(_) | Type::Set(_), _) => return Err(self.expected("an array", json)),
            (Type::Dict(..), _) => return self.dict(ty, json, level),
            (Type::Option(_), _) => {
                return self.option(part_types(ty).swap_remove(0), json, level);
            }
            (Type::Tuple(parts), Json::Array(items)) if parts.len() == items.len() => {
                let level = self.enter(level)?;
                return Ok(Frame::open(
                    Make::Tuple,
                    Parts::Indexed(part_types(ty), items),
                    0,
                    level,
                ));
            }
            (Type::Tuple(parts), _) => {
                return Err(self.expected(&format!("an array of {} elements", parts.len()), json));
            }
            (Type::Named(decl, args), _) => return self.named(ty, *decl, args, json, level),
        };
        Ok(Begun::Done(value))
    }
    fn decimal(&self, number: &Decimal) -> Result<Value, DecodeError> {
        if number.coefficient().bits() > self.limits.int_bits {
            return Err(self.refuse(
                DecodeErrorKind::TooLarge,
                format!(
                    "has a coefficient larger than {} bits",
                    self.limits.int_bits
                ),
            ));
        }
        Ok(Value::Decimal(number.clone()))
    }

    fn int(&self, number: &Decimal) -> Result<Int, DecodeError> {
        if number.exponent() < 0 {
            return Err(self.refuse(DecodeErrorKind::Mismatch, "should be a whole number"));
        }
        // The number is coefficient × 10^exponent with a nonzero coefficient
        // or a zero exponent, and 10^p has more than p bits, so an exponent
        // past the limit is refused without building a power of ten as long
        // as it; one within it is built and measured exactly.
        let too_large = || {
            self.refuse(
                DecodeErrorKind::TooLarge,
                format!("is an integer larger than {} bits", self.limits.int_bits),
            )
        };
        let places = number.exponent().unsigned_abs();
        if places > self.limits.int_bits {
            return Err(too_large());
        }
        let places = u32::try_from(places).expect("an exponent the limit bounds");
        crate::work::built(usize::try_from(places).map_or(usize::MAX, |places| places + 1));
        let value = number.coefficient() * BigInt::from(10).pow(places);
        if value.magnitude().bits() > self.limits.int_bits {
            return Err(too_large());
        }
        Ok(Int::from(value))
    }

    fn bytes(&self, text: &str) -> Result<Bytes, DecodeError> {
        let bytes = base64(text).ok_or_else(|| {
            self.refuse(
                DecodeErrorKind::Mismatch,
                "should be standard base64 with padding",
            )
        })?;
        if bytes.len() > self.limits.text_bytes {
            return Err(self.refuse(
                DecodeErrorKind::TooLarge,
                format!("is longer than {} bytes", self.limits.text_bytes),
            ));
        }
        Ok(Bytes::from(bytes))
    }

    /// Begins a named field's value from its member: an absent or `null`
    /// member is `None` for an `Option` field and refused for any other.
    fn field<'t, 'j>(
        &mut self,
        field: &Cow<'t, Type>,
        member: Option<&'j Json>,
        level: usize,
    ) -> Result<Begun<Parts<'t, 'c, 'j>>, DecodeError> {
        match (&*self.catalog.erase(field), member) {
            (Type::Option(item), member) => {
                self.option_field(Cow::Owned((**item).clone()), member, level)
            }
            (_, Some(Json::Null)) => Err(self.refuse(
                DecodeErrorKind::Mismatch,
                "is null, which only an Option field may be",
            )),
            (_, Some(json)) => self.begin(field, json, level),
            (_, None) => Err(self.refuse(DecodeErrorKind::Missing, "is missing")),
        }
    }

    fn dict<'t, 'j>(
        &mut self,
        ty: &Cow<'t, Type>,
        json: &'j Json,
        level: usize,
    ) -> Result<Begun<Parts<'t, 'c, 'j>>, DecodeError> {
        let [key, item]: [Cow<'t, Type>; 2] = part_types(ty)
            .try_into()
            .expect("a key type and a value type");
        let parts = match (&*self.catalog.erase(&key), json) {
            (Type::Text, Json::Object(members)) => Parts::Members(key, item, members),
            (Type::Text, _) => return Err(self.expected("an object", json)),
            (_, Json::Array(pairs)) => Parts::Pairs(key, item, pairs),
            _ => return Err(self.expected("an array of `[key, value]` pairs", json)),
        };
        let level = self.enter(level)?;
        Ok(Frame::open(Make::Dict, parts, 0, level))
    }

    fn option<'t, 'j>(
        &mut self,
        item: Cow<'t, Type>,
        json: &'j Json,
        level: usize,
    ) -> Result<Begun<Parts<'t, 'c, 'j>>, DecodeError> {
        let catalog = self.catalog;
        let option = catalog.option();
        let level = self.enter(level)?;
        let spelling = self.mode.spelling();
        let is = |written: &str, name: &str| spelling.key(written) == spelling.key(name);
        match json {
            Json::String(name) if is(name, OptionCtor::None.name()) => {
                Ok(Begun::Done(catalog.none()))
            }
            Json::Object(members)
                if members.len() == 1 && is(&members[0].0, OptionCtor::Some.name()) =>
            {
                self.path.constructor(OptionCtor::Some.name());
                Ok(Frame::open(
                    Make::Variant(
                        Arc::clone(&option.shape),
                        option.ctors.index(OptionCtor::Some),
                    ),
                    Parts::One(item, &members[0].1),
                    0,
                    level,
                ))
            }
            Json::String(name) => Err(self.unknown_option(name)),
            Json::Object(members) if members.len() == 1 => Err(self.unknown_option(&members[0].0)),
            Json::Null => Err(self.refuse(
                DecodeErrorKind::Mismatch,
                "is null, which only an Option field may be",
            )),
            _ => Err(self.expected("`\"None\"` or `{\"Some\": ...}`", json)),
        }
    }

    fn unknown_option(&self, name: &str) -> DecodeError {
        self.refuse(
            DecodeErrorKind::Unknown,
            format!(
                "names {}, which is not a constructor of Option",
                quote(name)
            ),
        )
    }

    /// The value of an `Option` field: absent or `null` is `None`, and
    /// anything else is the payload of `Some`.
    fn option_field<'t, 'j>(
        &mut self,
        item: Cow<'t, Type>,
        json: Option<&'j Json>,
        level: usize,
    ) -> Result<Begun<Parts<'t, 'c, 'j>>, DecodeError> {
        let catalog = self.catalog;
        let option = catalog.option();
        let level = self.enter(level)?;
        match json {
            None | Some(Json::Null) => Ok(Begun::Done(catalog.none())),
            Some(json) => Ok(Frame::open(
                Make::Unwritten(
                    Arc::clone(&option.shape),
                    option.ctors.index(OptionCtor::Some),
                ),
                Parts::One(item, json),
                0,
                level,
            )),
        }
    }

    fn named<'t, 'j>(
        &mut self,
        ty: &Type,
        decl: flow_types::DeclId,
        args: &[Type],
        json: &'j Json,
        level: usize,
    ) -> Result<Begun<Parts<'t, 'c, 'j>>, DecodeError> {
        let catalog = self.catalog;
        let declared = catalog.decl(decl);
        match &declared.body {
            Body::Record(shape, fields) => {
                let Json::Object(members) = json else {
                    return Err(self.expected("an object", json));
                };
                let level = self.enter(level)?;
                let names = shape.fields().collect();
                let fields = fields
                    .iter()
                    .map(|field| Cow::Owned(field.subst(args)))
                    .collect();
                let index = catalog.names(decl, self.mode);
                let parts =
                    self.fields(ty, names, fields, members, |written| index.member(written))?;
                Ok(Frame::open(
                    Make::Record(Arc::clone(shape)),
                    parts,
                    0,
                    level,
                ))
            }
            Body::Enum(shape, ctors) => {
                let (name, payload) = match json {
                    Json::String(name) => (name, None),
                    Json::Object(members) if members.len() == 1 => {
                        (&members[0].0, Some(&members[0].1))
                    }
                    _ => {
                        return Err(self
                            .expected("a constructor's name or an object with one member", json));
                    }
                };
                let names = catalog.names(decl, self.mode);
                let Some(index) = names.member(name) else {
                    return Err(self.refuse(
                        DecodeErrorKind::Unknown,
                        format!(
                            "names {}, which is not a constructor of {}",
                            quote(name),
                            self.catalog.name(ty)
                        ),
                    ));
                };
                let ctor = shape.constructor(index).expect("found above");
                let parts = ctors[index]
                    .iter()
                    .map(|part| Cow::Owned(part.subst(args)))
                    .collect();
                let level = self.enter(level)?;
                self.path.constructor(ctor.name());
                let parts = self.payload(ty, ctor.payload(), parts, payload, |written| {
                    names.payload_field(index, written)
                })?;
                Ok(Frame::open(
                    Make::Variant(Arc::clone(shape), index),
                    parts,
                    0,
                    level,
                ))
            }
            Body::Newtype(base) => Ok(Frame::open(
                Make::Newtype(StdForm::of(declared)),
                Parts::One(Cow::Owned(base.subst(args)), json),
                0,
                level,
            )),
            Body::NonData => Err(self.refuse(
                DecodeErrorKind::Mismatch,
                "has a type with no encoding, so it holds no value",
            )),
            Body::Host => match json {
                Json::String(token) => {
                    Ok(Begun::Done(Value::Host(flow_value::HostToken::new(token))))
                }
                _ => Err(self.expected("a host token string", json)),
            },
        }
    }

    /// Where the payload of a constructor of `ty`, whose parts are of
    /// `types`, comes from in `json`.
    fn payload<'t, 'j>(
        &mut self,
        ty: &Type,
        payload: &'c Payload,
        types: Vec<Cow<'t, Type>>,
        json: Option<&'j Json>,
        field: impl Fn(&str) -> Option<usize>,
    ) -> Result<Parts<'t, 'c, 'j>, DecodeError> {
        match (payload, json) {
            (Payload::None, None) => Ok(Parts::Indexed(Vec::new(), &[])),
            (Payload::None, Some(_)) => {
                Err(self.refuse(DecodeErrorKind::Mismatch, "carries no payload"))
            }
            (_, None) => Err(self.refuse(
                DecodeErrorKind::Mismatch,
                "carries a payload, so it is written as an object",
            )),
            (Payload::Positional(1), Some(json)) => Ok(Parts::One(
                types.into_iter().next().expect("one part"),
                json,
            )),
            (Payload::Positional(count), Some(Json::Array(items))) if items.len() == *count => {
                Ok(Parts::Indexed(types, items))
            }
            (Payload::Positional(count), Some(json)) => {
                Err(self.expected(&format!("an array of {count} elements"), json))
            }
            (Payload::Named(names), Some(Json::Object(members))) => {
                let names = names.iter().map(|name| &**name).collect();
                self.fields(ty, names, types, members, field)
            }
            (Payload::Named(_), Some(json)) => Err(self.expected("an object", json)),
        }
    }

    /// Named fields `names` of `types`, each read from the member of
    /// `members` whose name `field` finds it by. Each member is matched
    /// once, in the order of the text: one that names no field is ignored in
    /// a reply and refused otherwise, and one that names a field an earlier
    /// member named is refused.
    fn fields<'t, 'j>(
        &mut self,
        ty: &Type,
        names: Vec<&'c str>,
        types: Vec<Cow<'t, Type>>,
        members: &'j [(String, Json)],
        field: impl Fn(&str) -> Option<usize>,
    ) -> Result<Parts<'t, 'c, 'j>, DecodeError> {
        let mut found: Vec<Option<&'j (String, Json)>> = vec![None; names.len()];
        for member in members {
            match field(&member.0) {
                Some(at) => {
                    if let Some(first) = found[at] {
                        self.path.field(names[at]);
                        return Err(self.refuse(
                            DecodeErrorKind::Duplicate,
                            format!(
                                "is written twice, as {} and {}",
                                quote(&first.0),
                                quote(&member.0)
                            ),
                        ));
                    }
                    found[at] = Some(member);
                }
                None if matches!(self.mode, Mode::Input | Mode::Rebuild) => {
                    self.path.field(&member.0);
                    return Err(self.refuse(
                        DecodeErrorKind::Unknown,
                        format!("is not a field of {}", self.catalog.name(ty)),
                    ));
                }
                None => {}
            }
        }
        let members = found
            .into_iter()
            .map(|member| member.map(|(_, json)| json))
            .collect();
        Ok(Parts::Fields(names, types, members))
    }

    /// A `json.Value` standing for `json`.
    fn raw<'t, 'j>(
        &mut self,
        json: &'j Json,
        level: usize,
    ) -> Result<Begun<Parts<'t, 'c, 'j>>, DecodeError> {
        let catalog = self.catalog;
        let raw = catalog.json();
        let level = self.enter(level)?;
        let (ctor, payload) = match json {
            Json::Null => (JsonValueCtor::Null, Vec::new()),
            Json::Bool(value) => (JsonValueCtor::Bool, vec![Value::Bool(*value)]),
            Json::Number(value) => (JsonValueCtor::Number, vec![self.decimal(value)?]),
            Json::String(value) => (JsonValueCtor::Text, vec![Value::Text(self.text(value)?)]),
            Json::Array(_) => {
                return Ok(Frame::open(
                    Make::Unwritten(Arc::clone(&raw.shape), raw.ctors.index(JsonValueCtor::List)),
                    Parts::One(Cow::Owned(Type::list(Type::Json)), json),
                    0,
                    level,
                ));
            }
            Json::Object(_) => {
                return Ok(Frame::open(
                    Make::Unwritten(
                        Arc::clone(&raw.shape),
                        raw.ctors.index(JsonValueCtor::Object),
                    ),
                    Parts::One(Cow::Owned(Type::dict(Type::Text, Type::Json)), json),
                    0,
                    level,
                ));
            }
        };
        Ok(Begun::Done(Value::Variant(
            Variant::new(Arc::clone(&raw.shape), raw.ctors.index(ctor), payload)
                .expect("std's json.Value"),
        )))
    }
}

/// Where an aggregate's parts come from, and their types, each borrowed for
/// as long as the type of the whole value is when it is a part of it.
enum Parts<'t, 'c, 'j> {
    /// The elements of a list or a set, all of one type, each at its index.
    Items(Cow<'t, Type>, &'j [Json]),
    /// The elements of a tuple or a payload, each of its own type and at its
    /// index.
    Indexed(Vec<Cow<'t, Type>>, &'j [Json]),
    /// One value, read where the aggregate is.
    One(Cow<'t, Type>, &'j Json),
    /// Named fields of these types, each read from the member found for it,
    /// if any.
    Fields(Vec<&'c str>, Vec<Cow<'t, Type>>, Vec<Option<&'j Json>>),
    /// A dictionary's entries of these key and value types, written as an
    /// object's members.
    Members(Cow<'t, Type>, Cow<'t, Type>, &'j [(String, Json)]),
    /// A dictionary's entries of these key and value types, written as
    /// `[key, value]` pairs.
    Pairs(Cow<'t, Type>, Cow<'t, Type>, &'j [Json]),
}

impl<'t, 'c, 'j> Source<Parts<'t, 'c, 'j>> for Decoder<'c> {
    fn path(&mut self) -> &mut Place {
        &mut self.path
    }

    fn next(
        &mut self,
        frame: &mut Frame<Parts<'t, 'c, 'j>>,
    ) -> Result<Option<Begun<Parts<'t, 'c, 'j>>>, DecodeError> {
        let at = frame.values.len();
        let level = frame.level;
        let begun = match &frame.parts {
            Parts::Items(item, items) => {
                let Some(json) = items.get(at) else {
                    return Ok(None);
                };
                self.path.index(at);
                self.begin(item, json, level)?
            }
            Parts::Indexed(types, items) => {
                let Some((ty, json)) = types.get(at).zip(items.get(at)) else {
                    return Ok(None);
                };
                self.path.index(at);
                self.begin(ty, json, level)?
            }
            Parts::One(ty, json) => {
                if at > 0 {
                    return Ok(None);
                }
                self.begin(ty, json, level)?
            }
            Parts::Fields(names, types, members) => {
                let Some((name, ty)) = names.get(at).zip(types.get(at)) else {
                    return Ok(None);
                };
                self.path.field(name);
                let member = members[at];
                self.field(ty, member, level)?
            }
            Parts::Members(key, item, members) => {
                let Some((name, member)) = members.get(at / 2) else {
                    return Ok(None);
                };
                self.path.key(name);
                // The key is read through its own type, so a newtype with a
                // form holds it to that form.
                let key = self.value(key, &Json::String(name.clone()), level)?;
                frame.values.push(key);
                self.begin(item, member, level)?
            }
            Parts::Pairs(key, item, pairs) => {
                let Some(pair) = pairs.get(at / 2) else {
                    return Ok(None);
                };
                let parts = match pair {
                    Json::Array(parts) if parts.len() == 2 => parts,
                    _ => {
                        self.path.index(at / 2);
                        return Err(self.expected("a `[key, value]` pair", pair));
                    }
                };
                if at.is_multiple_of(2) {
                    self.path.index(at / 2);
                    self.path.index(0);
                    self.begin(key, &parts[0], level)?
                } else {
                    self.path.index(1);
                    self.begin(item, &parts[1], level)?
                }
            }
        };
        Ok(Some(begun))
    }

    fn steps(frame: &Frame<Parts<'t, 'c, 'j>>) -> usize {
        match frame.parts {
            Parts::One(..) => 0,
            // A pair's key leaves its index in the pair, and its value
            // leaves that and the pair's own.
            Parts::Pairs(..) if frame.values.len() % 2 == 1 => 1,
            Parts::Pairs(..) => 2,
            Parts::Items(..) | Parts::Indexed(..) | Parts::Fields(..) | Parts::Members(..) => 1,
        }
    }

    fn set(&self, items: Vec<Value>) -> Result<Set, DecodeError> {
        distinct_set(items, &self.path)
    }

    fn dict(&self, entries: Vec<(Value, Value)>) -> Result<Dict, DecodeError> {
        distinct_dict(entries, &self.path)
    }

    fn form(&self, form: StdForm, text: Text) -> Result<Value, DecodeError> {
        normal(form, &text, self.limits, &self.path)
    }
}

/// The bytes standard base64 with padding spells, or `None` for any other
/// text: a character outside the alphabet, missing or misplaced padding, or
/// bits set past the last byte.
pub fn base64(text: &str) -> Option<Vec<u8>> {
    let sextet = |byte: u8| -> Option<u32> {
        Some(u32::from(match byte {
            b'A'..=b'Z' => byte - b'A',
            b'a'..=b'z' => byte - b'a' + 26,
            b'0'..=b'9' => byte - b'0' + 52,
            b'+' => 62,
            b'/' => 63,
            _ => return None,
        }))
    };
    let bytes = text.as_bytes();
    if !bytes.len().is_multiple_of(4) {
        return None;
    }
    let mut out = Vec::with_capacity(bytes.len() / 4 * 3);
    let groups = bytes.len() / 4;
    for (at, group) in bytes.chunks(4).enumerate() {
        let padding = group.iter().rev().take_while(|byte| **byte == b'=').count();
        if padding > 2 || (padding > 0 && at + 1 != groups) {
            return None;
        }
        let mut bits = 0u32;
        for byte in &group[..4 - padding] {
            // The low six bits are clear, so adding places the sextet.
            bits = (bits << 6) + sextet(*byte)?;
        }
        bits <<= 6 * padding;
        let [_, first, second, third] = bits.to_be_bytes();
        let kept = 3 - padding;
        let unused = [first, second, third];
        if unused[kept..].iter().any(|byte| *byte != 0) {
            return None;
        }
        out.extend_from_slice(&unused[..kept]);
    }
    Some(out)
}

#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests;