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
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
//! The binary value encoding (`abi.md`, *The value encoding*): what crosses
//! to a Tool process and what history stores a value in.
//!
//! Both sides know the declared type, so the bytes carry no names and no
//! type tags; with the type they mean one value, and equal values have one
//! encoding. Decoding refuses every byte string that is not exactly the one
//! encoding of a value of the type: a number in more bytes than it needs, a
//! `Decimal` that is not normalized, a set or dictionary out of order or
//! with a repeat, and bytes left over.
//!
//! [`write_scalar`] and [`read_scalar`] write and read the scalar types
//! alone, for history, which writes those as parts inside its own slots
//! (`trace.md`, *Slots*).

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

use flow_types::Payload;
use flow_value::{
    Bytes, Decimal, Dict, Duration, HostToken, Instant, Int, Set, Text, Value, compare,
};

use crate::build::{Begun, Frame, Make, Source, Walk, build};
use crate::bytes::{Reader, wide, write_bytes, write_int, write_signed, write_text, write_uint};
use crate::catalog::{Catalog, StdForm};
use crate::decode::{Mode, decodable};
use crate::error::{DecodeError, DecodeErrorKind, EncodeError, EncodeErrorKind, Place};
use crate::form::{EnumForm, Form, Scalar, form};
use crate::limits::Limits;
use flow_types::Type;

// === Encoding ===============================================================

/// Returns the encoding of `value`, of type `ty`.
///
/// # Errors
///
/// A value that does not have the type, and a type with no encoding, such
/// as a function's or a task's, are [`EncodeError`]s; a checked program
/// reaches neither.
pub fn encode_bytes(catalog: &Catalog, ty: &Type, value: &Value) -> Result<Vec<u8>, EncodeError> {
    let mut out = Vec::new();
    write_value(&mut out, catalog, ty, value)?;
    Ok(out)
}

/// Appends the encoding of `value`, of type `ty`, to `out`.
///
/// # Errors
///
/// As [`encode_bytes`]; `out` then holds whatever was written before the
/// error.
pub fn write_value(
    out: &mut Vec<u8>,
    catalog: &Catalog,
    ty: &Type,
    value: &Value,
) -> Result<(), EncodeError> {
    ValueWriter {
        catalog,
        out,
        path: Place::default(),
    }
    .value(ty, value)
}

/// Appends the encoding of `value`, a value of the scalar type `scalar`,
/// to `out`, as history writes a part that takes no slot.
///
/// # Errors
///
/// An [`EncodeError`] when `value` is not a value of `scalar`; nothing is
/// written then.
pub fn write_scalar(out: &mut Vec<u8>, scalar: Scalar, value: &Value) -> Result<(), EncodeError> {
    scalar_into(out, scalar, value).ok_or_else(|| {
        EncodeError::new(
            &Place::default(),
            EncodeErrorKind::Mismatch,
            format!("is not a value of {}", scalar_name(scalar)),
        )
    })
}

fn scalar_into(out: &mut Vec<u8>, scalar: Scalar, value: &Value) -> Option<()> {
    match (scalar, value) {
        (Scalar::Unit, Value::Unit) => {}
        (Scalar::Bool, Value::Bool(flag)) => out.push(u8::from(*flag)),
        (Scalar::Int, Value::Int(number)) => write_int(out, number.as_bigint()),
        (Scalar::Decimal, Value::Decimal(number)) => decimal_into(out, number),
        (Scalar::Duration, Value::Duration(span)) => decimal_into(out, span.seconds()),
        (Scalar::Instant, Value::Instant(at)) => decimal_into(out, at.unix_seconds()),
        _ => return None,
    }
    Some(())
}

pub(crate) fn decimal_into(out: &mut Vec<u8>, number: &Decimal) {
    write_int(out, number.coefficient());
    write_signed(out, number.exponent());
}

fn scalar_name(scalar: Scalar) -> &'static str {
    match scalar {
        Scalar::Unit => "Unit",
        Scalar::Bool => "Bool",
        Scalar::Int => "Int",
        Scalar::Decimal => "Decimal",
        Scalar::Duration => "Duration",
        Scalar::Instant => "Instant",
    }
}

/// 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
}

/// Writes values at their types into a buffer: the runtime's own values
/// ([`write_value`]), and a Rust value its [`Shaped`](crate::wire::Shaped)
/// mapping writes part by part, with no runtime value between.
#[derive(Debug)]
pub struct ValueWriter<'c, 'o> {
    pub(crate) catalog: &'c Catalog,
    pub(crate) out: &'o mut Vec<u8>,
    pub(crate) path: Place,
}

impl<'c> ValueWriter<'c, '_> {
    pub(crate) fn mismatch(&self, ty: &Type) -> EncodeError {
        EncodeError::new(
            &self.path,
            EncodeErrorKind::Mismatch,
            format!("is not a value of {}", self.catalog.name(ty)),
        )
    }

    pub(crate) fn at(
        &mut self,
        step: impl FnOnce(&mut Place),
        go: impl FnOnce(&mut Self) -> Result<(), EncodeError>,
    ) -> Result<(), EncodeError> {
        step(&mut self.path);
        go(self)?;
        self.path.pop();
        Ok(())
    }

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

    /// Writes what `value`, of `ty`, writes before its parts: all of it,
    /// for one that holds no other value, and an aggregate is opened with
    /// the parts it holds.
    #[inline]
    fn begin<'a>(
        &mut self,
        ty: &Cow<'a, Type>,
        value: &'a Value,
    ) -> Result<Writing<'a>, EncodeError>
    where
        'c: 'a,
    {
        match ty {
            Cow::Borrowed(ty) => self.open(form(self.catalog, ty), ty, value, Cow::Borrowed),
            Cow::Owned(ty) => self.open(form(self.catalog, ty), ty, value, |part: &Type| {
                Cow::Owned(part.clone())
            }),
        }
    }

    /// [`ValueWriter::begin`] of `value`, of `ty`, whose form is `form`,
    /// each part's type kept by `keep`.
    #[inline]
    fn open<'f, 'a>(
        &mut self,
        form: Form<'f>,
        ty: &Type,
        value: &'a Value,
        keep: impl Fn(&'f Type) -> Cow<'a, Type>,
    ) -> Result<Writing<'a>, EncodeError>
    where
        'c: 'a,
    {
        match self.leaf(&form, ty, value) {
            Some(written) => written.map(Begun::Done),
            None => self.open_aggregate(form, ty, value, keep),
        }
    }

    /// Writes `value`, of `ty`, whose form is `form`, when that form holds
    /// no other value; `None` for one that does.
    #[inline]
    fn leaf(
        &mut self,
        form: &Form<'_>,
        ty: &Type,
        value: &Value,
    ) -> Option<Result<(), EncodeError>> {
        match (form, value) {
            (Form::Scalar(scalar), _) => {
                return Some(
                    scalar_into(self.out, *scalar, value).ok_or_else(|| self.mismatch(ty)),
                );
            }
            (Form::Text, Value::Text(text)) => write_text(self.out, text.as_str()),
            (Form::Bytes, Value::Bytes(bytes)) => write_bytes(self.out, bytes.as_slice()),
            (Form::Host, Value::Host(token)) => write_text(self.out, token.as_str()),
            (Form::Text | Form::Bytes | Form::Host, _) => return Some(Err(self.mismatch(ty))),
            _ => return None,
        }
        Some(Ok(()))
    }

    /// [`ValueWriter::open`] of a value that holds others.
    fn open_aggregate<'f, 'a>(
        &mut self,
        form: Form<'f>,
        ty: &Type,
        value: &'a Value,
        keep: impl Fn(&'f Type) -> Cow<'a, Type>,
    ) -> Result<Writing<'a>, EncodeError>
    where
        'c: 'a,
    {
        let (make, types) = match (form, value) {
            (Form::List(item), Value::List(items)) => {
                write_uint(self.out, wide(items.len()));
                (Make::List, Parts::Items(keep(item), items.len()))
            }
            (Form::Set(item), Value::Set(items)) => {
                write_uint(self.out, wide(items.len()));
                (Make::Set, Parts::Items(keep(item), items.len()))
            }
            (Form::Dict(key, item), Value::Dict(entries)) => {
                write_uint(self.out, wide(entries.len()));
                (
                    Make::Dict,
                    Parts::Entries(keep(key), keep(item), entries.len()),
                )
            }
            (Form::Tuple(parts), Value::Tuple(tuple)) if parts.len() == tuple.parts().len() => {
                (Make::Tuple, Parts::Each(parts.iter().map(keep).collect()))
            }
            (Form::Record(record), Value::Record(value)) if same(value.shape(), record.shape) => {
                let fields = record.fields.into_iter().map(Cow::Owned).collect();
                (Make::Record(Arc::clone(record.shape)), Parts::Each(fields))
            }
            (Form::Enum(shape), Value::Variant(variant)) if same(variant.shape(), shape.shape) => {
                let parts = shape
                    .parts(variant.index())
                    .expect("a variant's constructor is its shape's");
                write_uint(self.out, wide(variant.index()));
                self.path.constructor(variant.constructor().name());
                let parts = parts.into_iter().map(|part| kept(part, &keep)).collect();
                let make = Make::Variant(Arc::clone(shape.shape), variant.index());
                (make, Parts::Each(parts))
            }
            (Form::Newtype(base, held), _) => {
                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);
            }
            (Form::Task(_) | Form::NoEncoding, _) => {
                return Err(EncodeError::new(
                    &self.path,
                    EncodeErrorKind::NoEncoding,
                    "has a type with no encoding",
                ));
            }
            _ => return Err(self.mismatch(ty)),
        };
        Ok(Frame::open(make, Writes { types, value }, 0, 0))
    }
}

/// A value whose writing has begun.
type Writing<'a> = Begun<Writes<'a>, Make, ()>;

/// An aggregate's parts still to be written: their types, as reading them
/// takes them, and the value that holds them.
struct Writes<'a> {
    types: Parts<'a>,
    value: &'a Value,
}

impl<'a, 'c: 'a> Walk<Writes<'a>, Make, ()> for ValueWriter<'c, '_> {
    type Error = EncodeError;

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

    fn next(
        &mut self,
        frame: &mut Frame<Writes<'a>, Make, ()>,
    ) -> Result<Option<Writing<'a>>, EncodeError> {
        // Elements of a built-in type whose form holds no other value are
        // written in one pass, their form found once.
        if let Parts::Items(item, count) = &frame.parts.types
            && frame.values.is_empty()
            && !matches!(**item, Type::Named(..))
        {
            let form = form(self.catalog, item);
            if matches!(
                form,
                Form::Scalar(_) | Form::Text | Form::Bytes | Form::Host
            ) {
                for (at, value) in frame.parts.value.parts().enumerate() {
                    self.path.index(at);
                    self.leaf(&form, item, value)
                        .expect("a form that holds no other value")?;
                    self.path.pop();
                }
                frame.values.resize(*count, ());
                return Ok(None);
            }
        }
        loop {
            let at = frame.values.len();
            let Some(ty) = next_part(&frame.parts.types, &frame.make, at, &mut self.path) else {
                return Ok(None);
            };
            let value = frame
                .parts
                .value
                .part(at)
                .expect("a value holds a part for each of its type's");
            // A part that holds no other is written at once, without a turn
            // of the walk.
            match self.begin(ty, value)? {
                Begun::Done(()) => {
                    frame.values.push(());
                    for _ in 0..part_steps(&frame.parts.types, frame.values.len()) {
                        self.path.pop();
                    }
                }
                open @ Begun::Open(_) => return Ok(Some(open)),
            }
        }
    }

    fn steps(frame: &Frame<Writes<'a>, Make, ()>) -> usize {
        part_steps(&frame.parts.types, frame.values.len())
    }

    fn finish(&mut self, frame: Frame<Writes<'a>, Make, ()>) -> Result<(), EncodeError> {
        if let Make::Variant(..) = frame.make {
            self.path.pop();
        }
        Ok(())
    }
}

/// The step from a constructor to the payload part at `index`: its name for
/// a named payload, and its position otherwise.
pub(crate) fn payload_step(path: &mut Place, payload: &Payload, index: usize) {
    match payload {
        Payload::Named(names) => path.field(&names[index]),
        _ => path.index(index),
    }
}

// === Decoding ===============================================================

/// Decodes `bytes` as the one value of `ty` they encode, in `mode` and
/// within `limits`. Bytes left over after the value are refused.
///
/// # Errors
///
/// A [`DecodeError`] when the bytes are not exactly one value's encoding of
/// `ty`, or the value passes `limits`.
pub fn decode_bytes(
    catalog: &Catalog,
    ty: &Type,
    bytes: &[u8],
    mode: Mode,
    limits: &Limits,
) -> Result<Value, DecodeError> {
    let mut reader = Reader::new(bytes);
    let value = read_value(&mut reader, catalog, ty, mode, limits)?;
    if !reader.is_empty() {
        return Err(DecodeError::of(
            &Place::default(),
            DecodeErrorKind::Syntax {
                at: reader.position(),
            },
            format!(
                "ends at byte {}, before the {} bytes given do",
                reader.position(),
                bytes.len()
            ),
        ));
    }
    Ok(value)
}

/// Reads one value of `ty` from `reader`, in `mode` and within `limits`,
/// leaving the reader just past it: for a value inside a larger message.
///
/// Whether `ty` can be decoded at all in `mode` is judged first, before
/// any byte is read, as [`crate::decodable`] judges it.
///
/// # Errors
///
/// A [`DecodeError`] when `ty` cannot be decoded in `mode`, or the bytes
/// that follow do not begin with a value's encoding of it within `limits`.
pub fn read_value(
    reader: &mut Reader<'_>,
    catalog: &Catalog,
    ty: &Type,
    mode: Mode,
    limits: &Limits,
) -> Result<Value, DecodeError> {
    decodable(catalog, ty, mode.settings())?;
    ValueReader {
        catalog,
        limits,
        path: Place::default(),
        reader,
        zero_width_left: limits.text_bytes,
        level: 0,
    }
    .value(ty, 0)
}

/// Reads one value of the scalar type `scalar` from `reader`, within
/// `limits`, as history reads a part that takes no slot.
///
/// # Errors
///
/// A [`DecodeError`] when the bytes that follow are not a value of
/// `scalar` written in the fewest bytes, or the value passes `limits`.
pub fn read_scalar(
    reader: &mut Reader<'_>,
    scalar: Scalar,
    limits: &Limits,
) -> Result<Value, DecodeError> {
    Ok(match scalar {
        Scalar::Unit => Value::Unit,
        Scalar::Bool => Value::Bool(reader.bool()?),
        Scalar::Int => Value::Int(Int::from(reader.int(limits)?)),
        Scalar::Decimal => Value::Decimal(read_decimal(reader, limits)?),
        Scalar::Duration => Value::Duration(Duration::from_seconds(read_decimal(reader, limits)?)),
        Scalar::Instant => {
            Value::Instant(Instant::from_unix_seconds(read_decimal(reader, limits)?))
        }
    })
}

/// Writes `at` as the value encoding writes an `Instant`.
pub fn write_instant(out: &mut Vec<u8>, at: &Instant) {
    decimal_into(out, at.unix_seconds());
}

/// Reads an `Instant` as the value encoding writes one.
///
/// # Errors
///
/// When the bytes do not hold a decimal within `limits`.
pub fn read_instant(reader: &mut Reader<'_>, limits: &Limits) -> Result<Instant, DecodeError> {
    Ok(Instant::from_unix_seconds(read_decimal(reader, limits)?))
}

pub(crate) fn read_decimal(
    reader: &mut Reader<'_>,
    limits: &Limits,
) -> Result<Decimal, DecodeError> {
    let at = reader.position();
    let coefficient = reader.int(limits)?;
    let exponent = reader.signed()?;
    let unnormalized = || {
        DecodeError::of(
            &Place::default(),
            DecodeErrorKind::Syntax { at },
            format!("has a Decimal that is not normalized at byte {at}"),
        )
    };
    let normalized = if coefficient.magnitude().bits() == 0 {
        exponent == 0
    } else {
        (coefficient.magnitude() % 10u32).bits() != 0
    };
    if !normalized {
        return Err(unnormalized());
    }
    let number = Decimal::new(coefficient, exponent).map_err(|_| unnormalized())?;
    debug_assert_eq!(number.exponent(), exponent, "already normalized");
    Ok(number)
}

/// Reads values at their types from bytes, within limits: the runtime's
/// own values ([`read_value`]), and a Rust value its
/// [`Shaped`](crate::wire::Shaped) mapping reads part by part, with no
/// runtime value between.
#[derive(Debug)]
pub struct ValueReader<'c, 'r, 'b> {
    pub(crate) catalog: &'c Catalog,
    pub(crate) limits: &'c Limits,
    pub(crate) path: Place,
    pub(crate) reader: &'r mut Reader<'b>,
    /// How many more elements written in no bytes this value may hold, in
    /// all of its collections together: [`Limits::text_bytes`] at the start.
    pub(crate) zero_width_left: usize,
    /// How deep the aggregate a Rust value is read inside nests.
    pub(crate) level: usize,
}

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

    /// `error`, which the reader made without a path, at this one.
    pub(crate) fn here(&self, mut error: DecodeError) -> DecodeError {
        error.path = self.path.clone();
        error
    }

    /// Enters an aggregate `level` deep, which [`Limits::depth`] bounds.
    pub(crate) 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)
    }

    /// Decodes a value of `ty`, `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.
    pub(crate) fn value(&mut self, ty: &Type, level: usize) -> Result<Value, DecodeError> {
        let root = self.begin(&Cow::Borrowed(ty), level)?;
        build(self, root)
    }

    /// Begins decoding a value of `ty`: one that holds no other value is
    /// done at once, and an aggregate is opened.
    fn begin<'t>(
        &mut self,
        ty: &Cow<'t, Type>,
        level: usize,
    ) -> Result<Begun<Parts<'t>>, DecodeError>
    where
        'c: 't,
    {
        match ty {
            Cow::Borrowed(ty) => self.open(form(self.catalog, ty), ty, level, Cow::Borrowed),
            Cow::Owned(ty) => self.open(form(self.catalog, ty), ty, level, |part: &Type| {
                Cow::Owned(part.clone())
            }),
        }
    }

    /// [`ValueReader::begin`] of a value of `ty`, whose form is `form`, each
    /// part's type kept by `keep`.
    fn open<'f, 't>(
        &mut self,
        form: Form<'f>,
        ty: &Type,
        level: usize,
        keep: impl Fn(&'f Type) -> Cow<'t, Type>,
    ) -> Result<Begun<Parts<'t>>, DecodeError> {
        let value = match form {
            Form::Scalar(scalar) => {
                read_scalar(self.reader, scalar, self.limits).map_err(|error| self.here(error))?
            }
            Form::Text => {
                let text = self
                    .reader
                    .text(self.limits)
                    .map_err(|error| self.here(error))?;
                Value::Text(Text::new(text))
            }
            Form::Bytes => {
                let bytes = self
                    .reader
                    .bytes(self.limits)
                    .map_err(|error| self.here(error))?;
                Value::Bytes(Bytes::new(bytes))
            }
            Form::Host => {
                let token = self
                    .reader
                    .text(self.limits)
                    .map_err(|error| self.here(error))?;
                Value::Host(HostToken::new(token))
            }
            Form::List(item) => {
                let level = self.enter(level)?;
                let count = self.count(&[item])?;
                let room = self.backed(count);
                return Ok(Frame::open(
                    Make::List,
                    Parts::Items(keep(item), count),
                    room,
                    level,
                ));
            }
            Form::Set(item) => {
                let level = self.enter(level)?;
                let count = self.count(&[item])?;
                let room = self.backed(count);
                return Ok(Frame::open(
                    Make::Set,
                    Parts::Items(keep(item), count),
                    room,
                    level,
                ));
            }
            Form::Dict(key, item) => {
                let level = self.enter(level)?;
                let count = self.count(&[key, item])?;
                let room = self.backed(count).saturating_mul(2);
                let parts = Parts::Entries(keep(key), keep(item), count);
                return Ok(Frame::open(Make::Dict, parts, room, level));
            }
            Form::Tuple(parts) => {
                let level = self.enter(level)?;
                let parts = Parts::Each(parts.iter().map(keep).collect());
                return Ok(Frame::open(Make::Tuple, parts, 0, level));
            }
            Form::Record(record) => {
                let level = self.enter(level)?;
                let make = Make::Record(Arc::clone(record.shape));
                let fields = record.fields.into_iter().map(Cow::Owned).collect();
                return Ok(Frame::open(make, Parts::Each(fields), 0, level));
            }
            Form::Enum(shape) => return self.begin_variant(ty, &shape, level, keep),
            Form::Newtype(base, held) => {
                let parts = Parts::One(Cow::Owned(base));
                return Ok(Frame::open(Make::Newtype(held), parts, 1, level));
            }
            // Only rebuilding reaches a type with no encoding, and a value
            // the program made holds nothing of one.
            Form::NoEncoding => {
                return Err(self.refuse(
                    DecodeErrorKind::Mismatch,
                    "has a type with no encoding, so it holds no value",
                ));
            }
            // `Never`, and a task, which only a checkpoint's slots hold.
            Form::Never | Form::Task(_) => {
                return Err(self.refuse(
                    DecodeErrorKind::Mismatch,
                    "has a type with no values to decode",
                ));
            }
        };
        Ok(Begun::Done(value))
    }
    /// A collection's count of elements, each made of values of `types`.
    ///
    /// Each element takes at least one byte, so a count larger than the
    /// bytes left is refused before anything is set aside for it. Elements
    /// that take none, such as `Unit`, are bounded together instead: the
    /// whole value holds at most [`Limits::text_bytes`] of them, however
    /// many collections they are spread over, so a few bytes cannot ask
    /// for more elements than that.
    pub(crate) fn count(&mut self, types: &[&Type]) -> Result<usize, DecodeError> {
        let count = self.reader.count().map_err(|error| self.here(error))?;
        if types.iter().all(|ty| empty(self.catalog, ty, 0)) {
            let Some(left) = self.zero_width_left.checked_sub(count) else {
                return Err(self.refuse(
                    DecodeErrorKind::TooLarge,
                    format!(
                        "holds more than {} elements written in no bytes",
                        self.limits.text_bytes
                    ),
                ));
            };
            self.zero_width_left = left;
        } else if count > self.reader.remaining() {
            return Err(self.refuse(
                DecodeErrorKind::Mismatch,
                format!(
                    "holds {count} elements, more than the {} bytes left can",
                    self.reader.remaining()
                ),
            ));
        }
        Ok(count)
    }

    /// How many of `count` elements to set aside room for: no more than the
    /// bytes left could hold, so room grows with what is read rather than
    /// with what a count claims.
    pub(crate) fn backed(&self, count: usize) -> usize {
        count.min(self.reader.remaining())
    }

    /// Refuses `items`, each a `what`, unless each is greater than the one
    /// before it.
    pub(crate) fn ascending<'v>(
        &self,
        what: &str,
        items: impl Iterator<Item = &'v Value>,
    ) -> Result<(), DecodeError> {
        let mut previous: Option<&Value> = None;
        for (index, item) in items.enumerate() {
            if let Some(before) = previous {
                self.after(what, index, before, item)?;
            }
            previous = Some(item);
        }
        Ok(())
    }

    /// Refuses `item`, the `what` at `index`, unless it is greater than
    /// `before`, the one before it.
    pub(crate) fn after(
        &self,
        what: &str,
        index: usize,
        before: &Value,
        item: &Value,
    ) -> Result<(), DecodeError> {
        match compare(before, item) {
            Ok(Ordering::Less) => Ok(()),
            Ok(Ordering::Equal) => Err(self.refuse(
                DecodeErrorKind::Duplicate,
                format!("repeats {what} {}", index - 1),
            )),
            Ok(Ordering::Greater) => Err(self.refuse(
                DecodeErrorKind::Mismatch,
                format!(
                    "has {what} {index} out of ascending order, after {what} {}",
                    index - 1
                ),
            )),
            Err(_) => Err(self.refuse(
                DecodeErrorKind::Mismatch,
                format!("has {what}s that are not data"),
            )),
        }
    }

    fn begin_variant<'f, 't>(
        &mut self,
        ty: &Type,
        shape: &EnumForm<'f>,
        level: usize,
        keep: impl Fn(&'f Type) -> Cow<'t, Type>,
    ) -> Result<Begun<Parts<'t>>, DecodeError> {
        let index = self.reader.count().map_err(|error| self.here(error))?;
        let Some(parts) = shape.parts(index) else {
            return Err(self.refuse(
                DecodeErrorKind::Mismatch,
                format!(
                    "names constructor {index}, which {} does not have",
                    self.catalog.name(ty)
                ),
            ));
        };
        let level = self.enter(level)?;
        let ctor = shape.shape.constructor(index).expect("found above");
        self.path.constructor(ctor.name());
        let make = Make::Variant(Arc::clone(shape.shape), index);
        let parts = parts.into_iter().map(|part| kept(part, &keep)).collect();
        Ok(Frame::open(make, Parts::Each(parts), 0, level))
    }
}

/// The types of an aggregate's parts, each borrowed for as long as the
/// type of the whole value is when it is a part of it.
enum Parts<'t> {
    /// This many elements of a list or a set, all of one type.
    Items(Cow<'t, Type>, usize),
    /// The fields of a tuple, a record or a payload, each of its own type.
    Each(Vec<Cow<'t, Type>>),
    /// This many entries of a dictionary, of these key and value types.
    Entries(Cow<'t, Type>, Cow<'t, Type>, usize),
    /// A newtype's base, read where the newtype is.
    One(Cow<'t, Type>),
}

/// `part`, a part's type taken from a form, kept by `keep` when the form
/// borrows it.
fn kept<'f, 't>(part: Cow<'f, Type>, keep: impl Fn(&'f Type) -> Cow<'t, Type>) -> Cow<'t, Type> {
    match part {
        Cow::Borrowed(part) => keep(part),
        Cow::Owned(part) => Cow::Owned(part),
    }
}

/// The type of the part at `at` of an aggregate whose parts are of
/// `parts`, made by `make`, stepping `path` onto it; `None` once every part
/// is read or written.
#[inline]
fn next_part<'p, 't>(
    parts: &'p Parts<'t>,
    make: &Make,
    at: usize,
    path: &mut Place,
) -> Option<&'p Cow<'t, Type>> {
    match parts {
        Parts::Items(item, count) => {
            if at == *count {
                return None;
            }
            path.index(at);
            Some(item)
        }
        Parts::Each(types) => {
            let ty = types.get(at)?;
            match make {
                Make::Record(shape) => path.field(shape.field(at).expect("a name per field")),
                Make::Variant(shape, index) | Make::Unwritten(shape, index) => {
                    let ctor = shape.constructor(*index).expect("found when opened");
                    payload_step(path, ctor.payload(), at);
                }
                Make::Tuple | Make::List | Make::Set | Make::Dict | Make::Newtype(_) => {
                    path.index(at);
                }
            }
            Some(ty)
        }
        Parts::Entries(key, item, count) => {
            if at / 2 == *count {
                return None;
            }
            if at.is_multiple_of(2) {
                path.index(at / 2);
                path.index(0);
                Some(key)
            } else {
                path.index(1);
                Some(item)
            }
        }
        Parts::One(ty) => (at == 0).then_some(ty),
    }
}

/// How many steps the path took onto the part just done of an aggregate
/// whose parts are of `parts`, `done` of them done.
fn part_steps(parts: &Parts<'_>, done: usize) -> usize {
    match parts {
        Parts::One(_) => 0,
        // An entry's key leaves its index in the entry, and its value
        // leaves that and the entry's own.
        Parts::Entries(..) if done % 2 == 1 => 1,
        Parts::Entries(..) => 2,
        Parts::Items(..) | Parts::Each(_) => 1,
    }
}

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

    fn next(
        &mut self,
        frame: &mut Frame<Parts<'t>>,
    ) -> Result<Option<Begun<Parts<'t>>>, DecodeError> {
        let at = frame.values.len();
        let Some(ty) = next_part(&frame.parts, &frame.make, at, &mut self.path) else {
            return Ok(None);
        };
        self.begin(ty, frame.level).map(Some)
    }

    fn steps(frame: &Frame<Parts<'t>>) -> usize {
        part_steps(&frame.parts, frame.values.len())
    }

    fn set(&self, items: Vec<Value>) -> Result<Set, DecodeError> {
        self.ascending("element", items.iter())?;
        Ok(Set::from_items(items).expect("decoded values are data"))
    }

    fn dict(&self, entries: Vec<(Value, Value)>) -> Result<Dict, DecodeError> {
        self.ascending("key", entries.iter().map(|(key, _)| key))?;
        Ok(Dict::from_entries(entries).expect("decoded keys are data"))
    }

    fn form(&self, form: StdForm, text: Text) -> Result<Value, DecodeError> {
        match form.refusal(text.as_str()) {
            Some(problem) => Err(self.refuse(DecodeErrorKind::Mismatch, problem)),
            None => Ok(Value::Text(text)),
        }
    }
}

/// Whether every value of `ty` is written in no bytes: `Unit`, and tuples
/// and records of nothing else. A type that holds itself through such parts
/// alone has no values, and counts as one that takes bytes.
fn empty(catalog: &Catalog, ty: &Type, depth: usize) -> bool {
    if depth > 32 {
        return false;
    }
    match form(catalog, ty) {
        Form::Scalar(Scalar::Unit) => true,
        Form::Tuple(parts) => parts.iter().all(|part| empty(catalog, part, depth + 1)),
        Form::Record(record) => record
            .fields
            .iter()
            .all(|field| empty(catalog, field, depth + 1)),
        Form::Newtype(base, _) => empty(catalog, &base, depth + 1),
        _ => false,
    }
}