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
//! Encoding a value at its type (`abi.md`, *The value encoding*), and the
//! canonical text and hash taken over it.

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

use flow_types::{OptionCtor, Payload};
use flow_value::{Decimal, TaskId, Value, Variant};
use sha2::{Digest as _, Sha256};

use crate::build::{self, Walk};
use crate::bytes::wide;
use crate::catalog::{Catalog, StdForm};
use crate::error::{EncodeError, EncodeErrorKind, Place, Step};
use crate::form::{Form, form, part_types, reborrow};
use crate::json::Json;
use flow_types::{Body, Type};

/// Returns `value`, of type `ty`, as JSON.
///
/// The encoding carries no type tags: the type decides it.
///
/// # Errors
///
/// A value that does not have the type, and a type with no encoding, are
/// [`EncodeError`]s; a checked program reaches neither.
pub fn encode(catalog: &Catalog, ty: &Type, value: &Value) -> Result<Json, EncodeError> {
    Encoder::new(catalog, None, None).value(ty, value)
}

/// Returns `value`, of type `ty`, as [`encode`] writes it, except that a
/// task is the id of the call it is parked on, which `tasks` gives for the
/// task and the type of its result: how a viewer writes a value that holds
/// tasks.
///
/// # Errors
///
/// As [`encode`], and when `tasks` names no call for a task.
pub fn encode_naming_tasks(
    catalog: &Catalog,
    ty: &Type,
    value: &Value,
    tasks: &mut dyn FnMut(TaskId, &Type) -> Option<String>,
) -> Result<Json, EncodeError> {
    Encoder::new(catalog, Some(tasks), None).value(ty, value)
}

/// Returns `value`, of type `ty`, as [`encode`] writes it, except that
/// bytes holding valid UTF-8 are written as that text: the form a person
/// reads, which no decoder takes back.
///
/// # Errors
///
/// As [`encode`].
pub fn encode_for_reading(
    catalog: &Catalog,
    ty: &Type,
    value: &Value,
) -> Result<Json, EncodeError> {
    let mut encoder = Encoder::new(catalog, None, None);
    encoder.reading = true;
    encoder.value(ty, value)
}

/// Returns the canonical text of `value`, of type `ty`: the one text every
/// equal value's JSON form shares, which `json.encode` and a run's output
/// write (`abi.md`, *The canonical text*). History stores values in the
/// binary encoding, not in this text.
///
/// # Errors
///
/// As [`encode`].
pub fn canonical(catalog: &Catalog, ty: &Type, value: &Value) -> Result<String, EncodeError> {
    Ok(encode(catalog, ty, value)?.canonical())
}

/// Returns the canonical text of `value`, of type `ty`, when it takes at
/// most `max_bytes` bytes, and `None` otherwise.
///
/// The text is measured as the value is encoded, and encoding stops soon
/// after it passes `max_bytes`: a value whose text would be far longer, such
/// as a list holding one long text many times over, costs no more than the
/// bound and the one part that crossed it.
///
/// # Errors
///
/// As [`encode`], for the part of `value` encoded before it stopped.
pub fn canonical_within(
    catalog: &Catalog,
    ty: &Type,
    value: &Value,
    max_bytes: usize,
) -> Result<Option<String>, EncodeError> {
    let mut encoder = Encoder::new(catalog, None, Some(max_bytes));
    match encoder.value(ty, value) {
        Ok(json) => {
            let text = json.canonical();
            debug_assert_eq!(
                encoder.room.map(|room| room + text.len()),
                Some(max_bytes),
                "measured exactly"
            );
            Ok(Some(text))
        }
        Err(_) if encoder.over => Ok(None),
        Err(error) => Err(error),
    }
}

/// A SHA-256 hash, written `sha256:` followed by lowercase hex.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct Digest(pub [u8; 32]);

impl Digest {
    /// The hash of `bytes`.
    pub fn of(bytes: &[u8]) -> Digest {
        Digest(Sha256::digest(bytes).into())
    }

    /// The hash as lowercase hex, without the `sha256:` prefix.
    pub fn hex(&self) -> String {
        use fmt::Write as _;
        self.0
            .iter()
            .fold(String::with_capacity(64), |mut text, byte| {
                let _ = write!(text, "{byte:02x}");
                text
            })
    }
}

impl fmt::Display for Digest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "sha256:{}", self.hex())
    }
}

/// Whether two declarations are one: the same shape, or equal ones.
fn same<T: PartialEq>(a: &Arc<T>, b: &Arc<T>) -> bool {
    Arc::ptr_eq(a, b) || a == b
}

/// How a checkpoint names a task: by the id of its call, given the task and
/// the type of its result.
type Tasks<'c> = &'c mut dyn FnMut(TaskId, &Type) -> Option<String>;

struct Encoder<'c> {
    catalog: &'c Catalog,
    path: Place,
    /// How a checkpoint names a task; `None` outside one.
    tasks: Option<Tasks<'c>>,
    /// How many more bytes the canonical text may take; `None` for no
    /// bound.
    room: Option<usize>,
    /// Whether encoding stopped because the text passed its bound.
    over: bool,
    /// Whether bytes holding valid UTF-8 are written as that text.
    reading: bool,
}

impl<'c> Encoder<'c> {
    fn new(catalog: &'c Catalog, tasks: Option<Tasks<'c>>, room: Option<usize>) -> Self {
        Encoder {
            catalog,
            path: Place::default(),
            tasks,
            room,
            over: false,
            reading: false,
        }
    }

    /// Counts `bytes` more of canonical text, or stops encoding when they
    /// do not fit.
    fn spend(&mut self, bytes: u128) -> Result<(), EncodeError> {
        let Some(room) = &mut self.room else {
            return Ok(());
        };
        match usize::try_from(bytes) {
            Ok(bytes) if bytes <= *room => {
                *room -= bytes;
                Ok(())
            }
            _ => {
                self.over = true;
                Err(EncodeError::new(
                    &self.path,
                    EncodeErrorKind::TooLarge,
                    "has a text longer than its bound",
                ))
            }
        }
    }

    /// `text` as a JSON string.
    fn string(&mut self, text: &str) -> Result<Json, EncodeError> {
        self.spend(quoted_len(text))?;
        Ok(Json::String(text.to_owned()))
    }

    /// `number` as a JSON number.
    fn number(&mut self, number: Decimal) -> Result<Json, EncodeError> {
        self.spend(number.text_len())?;
        Ok(Json::Number(number))
    }

    /// The `[`, `]` and commas of an array of `items` elements, or the `{`,
    /// `}` and commas of an object of `items` members.
    fn brackets(&mut self, items: usize) -> Result<(), EncodeError> {
        self.spend(2 + u128::from(wide(items.saturating_sub(1))))
    }

    /// How many of `count` parts can fit what is left of the bound: each
    /// part's text is at least one byte, so a bounded encoding never
    /// reserves room for more parts than it has bytes left.
    fn room_for(&self, count: usize) -> usize {
        self.room.map_or(count, |room| count.min(room))
    }

    /// Opens the aggregate `join` makes of `parts`.
    fn open<'a>(&self, join: Join<'a>, parts: Parts<'a>) -> Begun<'a> {
        let count = match &parts {
            Parts::Items(_, value) => value.parts().len(),
            Parts::Pairs(.., value) => value.parts().len() / 2,
            Parts::Each(parts, _) => parts.len(),
            Parts::Pair(_) => 2,
            Parts::Members(..) | Parts::Fields(..) | Parts::One(..) | Parts::Payload(..) => 1,
            Parts::Done => 0,
        };
        build::Frame::open(join, parts, self.room_for(count), 0)
    }

    /// The key of an object member and the `:` after it.
    fn key(&mut self, name: &str) -> Result<(), EncodeError> {
        self.spend(quoted_len(name) + 1)
    }
    fn mismatch(&self, ty: &Type) -> EncodeError {
        EncodeError::new(
            &self.path,
            EncodeErrorKind::Mismatch,
            format!("is not a value of {}", self.catalog.name(ty)),
        )
    }

    /// Encodes `value`, of `ty`. 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, value: &Value) -> Result<Json, EncodeError> {
        let root = self.begin(&Cow::Borrowed(ty), value)?;
        build::build(self, root)
    }

    /// Begins encoding `value`, of `ty`: one that holds no other value is
    /// done at once, and an aggregate is opened with the parts it holds.
    fn begin<'a>(
        &mut self,
        ty: &Cow<'a, Type>,
        value: &'a Value,
    ) -> Result<Begun<'a>, EncodeError> {
        let json = match (&**ty, value) {
            (Type::Int, Value::Int(number)) => self.number(Decimal::from(number))?,
            (Type::Decimal, Value::Decimal(number)) => self.number(number.clone())?,
            (Type::Bool, Value::Bool(flag)) => self.boolean(*flag)?,
            (Type::Text, Value::Text(text)) => self.string(text.as_str())?,
            (Type::Bytes, Value::Bytes(bytes)) => {
                match self.reading.then(|| bytes.to_text()).flatten() {
                    Some(text) => self.string(text.as_str())?,
                    None => self.string(&bytes.to_base64())?,
                }
            }
            (Type::Duration, Value::Duration(span)) => self.string(&span.to_string())?,
            (Type::Instant, Value::Instant(at)) => self.string(&at.to_string())?,
            (Type::Unit, Value::Unit) => {
                self.brackets(0)?;
                Json::Array(Vec::new())
            }
            (Type::Json, Value::Variant(variant))
                if same(variant.shape(), &self.catalog.json().shape) =>
            {
                return self.raw(variant);
            }
            (Type::List(_), Value::List(_)) | (Type::Set(_), Value::Set(_)) => {
                let item = part_types(ty).swap_remove(0);
                return Ok(self.open(Join::Brackets, Parts::Items(item, value)));
            }
            (Type::Dict(key, _), Value::Dict(entries)) => {
                self.brackets(entries.len())?;
                let text = *self.catalog.erase(key) == Type::Text;
                let [key, item]: [Cow<'a, Type>; 2] = part_types(ty)
                    .try_into()
                    .expect("a key type and a value type");
                return Ok(if text {
                    self.open(
                        Join::Object(Vec::with_capacity(self.room_for(entries.len())), None),
                        Parts::Members(reborrow(ty), item, value, 0),
                    )
                } else {
                    self.open(Join::Array, Parts::Pairs(key, item, value))
                });
            }
            (Type::Option(_), Value::Variant(variant))
                if same(variant.shape(), &self.catalog.option().shape) =>
            {
                // A value of std's `Option` is `None` or `Some` of one value.
                let Some(inner) = variant.payload().first() else {
                    return Ok(Begun::Done(self.string(OptionCtor::None.name())?));
                };
                let some = OptionCtor::Some.name();
                self.brackets(1)?;
                self.key(some)?;
                let item = part_types(ty).swap_remove(0);
                let parts = Parts::One(Step::Constructor(some.to_owned()), item, inner);
                return Ok(self.open(Join::Member(some), parts));
            }
            (Type::Tuple(parts), Value::Tuple(tuple)) if parts.len() == tuple.parts().len() => {
                let parts = Parts::Each(part_types(ty), tuple.parts());
                return Ok(self.open(Join::Brackets, parts));
            }
            (Type::Named(..), _) => return self.named(ty, value),
            (Type::Task(result), Value::Task(task)) if self.tasks.is_some() => {
                let tasks = self.tasks.as_mut().expect("checked by the guard");
                let Some(call) = tasks(*task, result) else {
                    return Err(EncodeError::new(
                        &self.path,
                        EncodeErrorKind::Mismatch,
                        "is a task that is not parked on its only call",
                    ));
                };
                self.string(&call)?
            }
            (Type::NotData | Type::Function { .. } | Type::Param(_) | Type::Task(_), _) => {
                return Err(self.no_encoding());
            }
            _ => return Err(self.mismatch(ty)),
        };
        Ok(Begun::Done(json))
    }

    /// Begins a `json.Value` as the JSON value it stands for.
    fn raw<'a>(&mut self, variant: &'a Variant) -> Result<Begun<'a>, EncodeError> {
        // Each constructor of `json.Value` carries a payload of its own kind,
        // so the payload names the constructor.
        let json = match variant.payload() {
            [] => {
                self.spend(4)?;
                Json::Null
            }
            [Value::Bool(value)] => self.boolean(*value)?,
            [Value::Decimal(value)] => self.number(value.clone())?,
            [Value::Text(value)] => self.string(value.as_str())?,
            [list @ Value::List(_)] => {
                return Ok(self.open(Join::Brackets, Parts::Items(Cow::Borrowed(&JSON), list)));
            }
            [value @ Value::Dict(_)] => {
                return self.begin(&Cow::Owned(Type::dict(Type::Text, Type::Json)), value);
            }
            _ => return Err(self.mismatch(&Type::Json)),
        };
        Ok(Begun::Done(json))
    }

    /// Begins a value of a declared record, enum, newtype or host type.
    fn named<'a>(&mut self, ty: &Type, value: &'a Value) -> Result<Begun<'a>, EncodeError> {
        let Type::Named(decl, args) = ty else {
            unreachable!("a declared type")
        };
        if let Form::Newtype(base, held) = form(self.catalog, ty) {
            if let Some(problem) = StdForm::out_of(held, value) {
                return Err(EncodeError::new(
                    &self.path,
                    EncodeErrorKind::Mismatch,
                    problem,
                ));
            }
            return self.begin(&Cow::Owned(base), value);
        }
        match (&self.catalog.decl(*decl).body, value) {
            (Body::Record(shape, fields), Value::Record(record)) if same(record.shape(), shape) => {
                let fields: Vec<_> = record
                    .shape()
                    .fields()
                    .zip(fields.iter().map(|field| Cow::Owned(field.subst(args))))
                    .zip(record.fields())
                    .collect();
                let members = Vec::with_capacity(fields.len());
                Ok(self.open(Join::Fields(members, None), Parts::Fields(fields, 0)))
            }
            (Body::Enum(shape, ctors), Value::Variant(variant)) if same(variant.shape(), shape) => {
                let parts = ctors[variant.index()]
                    .iter()
                    .map(|part| Cow::Owned(part.subst(args)))
                    .collect();
                self.variant(variant, parts)
            }
            (Body::NonData, _) => Err(self.no_encoding()),
            (Body::Host, Value::Host(token)) => Ok(Begun::Done(self.string(token.as_str())?)),
            _ => Err(self.mismatch(ty)),
        }
    }

    fn no_encoding(&self) -> EncodeError {
        EncodeError::new(
            &self.path,
            EncodeErrorKind::NoEncoding,
            "has a type with no encoding",
        )
    }

    /// Begins an enum value: its constructor's name, alone or keying its
    /// payload of the types `parts`.
    fn variant<'a>(
        &mut self,
        variant: &'a Variant,
        mut parts: Vec<Cow<'a, Type>>,
    ) -> Result<Begun<'a>, EncodeError> {
        let ctor = variant.constructor();
        let name = ctor.name();
        let payload = match ctor.payload() {
            Payload::None => return Ok(Begun::Done(self.string(name)?)),
            Payload::Positional(1) => {
                let ty = parts.pop().expect("one part");
                Parts::One(
                    Step::Constructor(name.to_owned()),
                    ty,
                    &variant.payload()[0],
                )
            }
            Payload::Positional(_) => Parts::Payload(
                name,
                Box::new(Parts::Each(parts, variant.payload())),
                Join::Brackets,
            ),
            Payload::Named(names) => {
                let fields: Vec<_> = names
                    .iter()
                    .map(|name| &**name)
                    .zip(parts)
                    .zip(variant.payload())
                    .collect();
                let members = Vec::with_capacity(fields.len());
                Parts::Payload(
                    name,
                    Box::new(Parts::Fields(fields, 0)),
                    Join::Fields(members, None),
                )
            }
        };
        Ok(self.open(Join::Variant(name), payload))
    }

    /// `flag` as a JSON boolean.
    #[expect(
        clippy::fn_params_excessive_bools,
        reason = "the flag is the value written, not a choice of how to write it"
    )]
    fn boolean(&mut self, flag: bool) -> Result<Json, EncodeError> {
        self.spend(if flag { 4 } else { 5 })?;
        Ok(Json::Bool(flag))
    }
}

impl Encoder<'_> {
    /// Moves the part of `frame` made last into the object it is a member
    /// of, under its key.
    fn settle(&mut self, frame: &mut Frame<'_>) -> Result<(), EncodeError> {
        let (members, name) = match &mut frame.make {
            Join::Object(members, last) => match last.take() {
                Some(name) => (members, name),
                None => return Ok(()),
            },
            Join::Fields(members, last) => match last.take() {
                Some(name) => {
                    self.key(name)?;
                    (members, name)
                }
                None => return Ok(()),
            },
            Join::Array | Join::Brackets | Join::Member(_) | Join::Variant(_) => return Ok(()),
        };
        let value = frame.values.pop().expect("the member just made");
        members.push((name.to_owned(), value));
        Ok(())
    }

    /// Begins the next field of `frame`, a record's or a named payload's,
    /// that is written, and steps the path onto it.
    fn next_field<'a>(&mut self, frame: &mut Frame<'a>) -> Result<Option<Begun<'a>>, EncodeError> {
        let Parts::Fields(fields, index) = &mut frame.parts else {
            unreachable!("a frame of fields")
        };
        loop {
            let Some(((name, ty), value)) = fields.get_mut(*index) else {
                return Ok(None);
            };
            *index += 1;
            let (name, value): (&'a str, &'a Value) = (*name, *value);
            let ty = std::mem::replace(ty, Cow::Borrowed(&JSON));
            let payload = match (&*self.catalog.erase(&ty), value) {
                (Type::Option(item), Value::Variant(variant))
                    if same(variant.shape(), &self.catalog.option().shape) =>
                {
                    Some(
                        variant
                            .payload()
                            .first()
                            .map(|inner| (Cow::Owned((**item).clone()), inner)),
                    )
                }
                _ => None,
            };
            // An `Option` field holding `None` is left out, and one holding
            // `Some` is written as its payload.
            let Some((ty, value)) = payload.unwrap_or(Some((ty, value))) else {
                continue;
            };
            if let Join::Fields(_, last) = &mut frame.make {
                *last = Some(name);
            }
            self.path.field(name);
            return self.begin(&ty, value).map(Some);
        }
    }
}

/// `json.Value`, the type of each element of a JSON array.
static JSON: Type = Type::Json;

/// A value whose encoding has begun.
type Begun<'a> = build::Begun<Parts<'a>, Join<'a>, Json>;

/// An aggregate being encoded.
type Frame<'a> = build::Frame<Parts<'a>, Join<'a>, Json>;

/// Where the parts of an aggregate being encoded come from.
enum Parts<'a> {
    /// The elements of this list or set, all of this type, each at its
    /// index.
    Items(Cow<'a, Type>, &'a Value),
    /// Parts each of its own type, each at its index.
    Each(Vec<Cow<'a, Type>>, &'a [Value]),
    /// A dictionary of this type whose keys are text, its values of this
    /// type, each under its key: the entries of this dictionary, from the
    /// one at this index.
    Members(Cow<'a, Type>, Cow<'a, Type>, &'a Value, usize),
    /// A dictionary's entries of these key and value types, each a pair at
    /// its index: the entries of this dictionary.
    Pairs(Cow<'a, Type>, Cow<'a, Type>, &'a Value),
    /// One value of this type at this step, until it is taken.
    One(Step, Cow<'a, Type>, &'a Value),
    /// A key and a value, of these types, in turn.
    Pair([(Cow<'a, Type>, &'a Value); 2]),
    /// Named fields, each of its type, from the next one's.
    Fields(Vec<((&'a str, Cow<'a, Type>), &'a Value)>, usize),
    /// A constructor's payload of several parts, made by this join, until
    /// it is taken.
    Payload(&'a str, Box<Parts<'a>>, Join<'a>),
    /// Nothing more.
    Done,
}

/// What an aggregate's encoded parts make.
enum Join<'a> {
    /// An array of them, its brackets counted before they were.
    Array,
    /// An array of them, its brackets counted after.
    Brackets,
    /// An object of these members and one more under the key of the last
    /// part begun, once it is made; each key counted before its value.
    Object(Vec<(String, Json)>, Option<&'a str>),
    /// An object of these members and one more under the field name of the
    /// last part begun, once it is made; each name counted after its value.
    Fields(Vec<(String, Json)>, Option<&'a str>),
    /// An object of one member, the part, under this key, counted before.
    Member(&'a str),
    /// An object of one member, the part, under this constructor's name,
    /// counted after.
    Variant(&'a str),
}

impl<'a> Walk<Parts<'a>, Join<'a>, Json> for Encoder<'_> {
    type Error = EncodeError;

    fn path(&mut self) -> &mut Place {
        &mut self.path
    }

    fn next(&mut self, frame: &mut Frame<'a>) -> Result<Option<Begun<'a>>, EncodeError> {
        self.settle(frame)?;
        match &mut frame.parts {
            Parts::Items(ty, items) => {
                let at = frame.values.len();
                let Some(item) = items.part(at) else {
                    return Ok(None);
                };
                self.path.index(at);
                self.begin(ty, item).map(Some)
            }
            Parts::Each(parts, values) => {
                let at = frame.values.len();
                let Some((ty, value)) = parts.get(at).zip(values.get(at)) else {
                    return Ok(None);
                };
                self.path.index(at);
                self.begin(ty, value).map(Some)
            }
            Parts::Members(dict, item, entries, index) => {
                let at = 2 * *index;
                let Some((name, entry)) = entries.part(at).zip(entries.part(at + 1)) else {
                    return Ok(None);
                };
                *index += 1;
                let Value::Text(name) = name else {
                    return Err(self.mismatch(dict));
                };
                let name = name.as_str();
                self.key(name)?;
                if let Join::Object(_, last) = &mut frame.make {
                    *last = Some(name);
                }
                self.path.key(name);
                self.begin(item, entry).map(Some)
            }
            Parts::Pairs(key, item, entries) => {
                let at = 2 * frame.values.len();
                let Some((name, entry)) = entries.part(at).zip(entries.part(at + 1)) else {
                    return Ok(None);
                };
                self.path.index(frame.values.len());
                self.brackets(2)?;
                let pair = [(reborrow(key), name), (reborrow(item), entry)];
                Ok(Some(self.open(Join::Array, Parts::Pair(pair))))
            }
            Parts::One(..) => {
                let Parts::One(step, ty, value) = std::mem::replace(&mut frame.parts, Parts::Done)
                else {
                    unreachable!("matched above")
                };
                self.path.push(step);
                self.begin(&ty, value).map(Some)
            }
            Parts::Pair(pair) => {
                let index = frame.values.len();
                let Some((ty, value)) = pair.get(index) else {
                    return Ok(None);
                };
                self.path.index(index);
                self.begin(ty, value).map(Some)
            }
            Parts::Fields(..) => self.next_field(frame),
            Parts::Payload(..) => {
                let Parts::Payload(name, parts, join) =
                    std::mem::replace(&mut frame.parts, Parts::Done)
                else {
                    unreachable!("matched above")
                };
                self.path.constructor(name);
                Ok(Some(self.open(join, *parts)))
            }
            Parts::Done => Ok(None),
        }
    }

    fn steps(_: &Frame<'a>) -> usize {
        1
    }

    fn finish(&mut self, mut frame: Frame<'a>) -> Result<Json, EncodeError> {
        self.settle(&mut frame)?;
        let values = frame.values;
        Ok(match frame.make {
            Join::Array => Json::Array(values),
            Join::Brackets => {
                self.brackets(values.len())?;
                Json::Array(values)
            }
            Join::Object(members, _) => Json::Object(members),
            Join::Fields(members, _) => {
                self.brackets(members.len())?;
                Json::Object(members)
            }
            Join::Member(key) => Json::Object(vec![(key.to_owned(), one(values))]),
            Join::Variant(name) => {
                self.brackets(1)?;
                self.key(name)?;
                Json::Object(vec![(name.to_owned(), one(values))])
            }
        })
    }
}

/// The one value of a frame of one part.
fn one(values: Vec<Json>) -> Json {
    values.into_iter().next().expect("one part")
}

/// How many bytes `text` takes as a canonical JSON string, quotes included
/// (`abi.md`, *The canonical form*).
fn quoted_len(text: &str) -> u128 {
    let escaped: usize = text
        .chars()
        .map(|code_point| match code_point {
            '"' | '\\' | '\u{8}' | '\u{c}' | '\n' | '\r' | '\t' => 2,
            '\u{0}'..='\u{1f}' => 6,
            other => other.len_utf8(),
        })
        .sum();
    u128::from(wide(escaped)) + 2
}