Skip to main content

flow_abi/
wire.rs

1//! Messages declared once: [`wire!`](crate::wire!) takes a record or enum
2//! definition and gives the type, its [`Wire`] codec and its [`Shape`].
3//!
4//! The codec is the value encoding's rules (`abi.md`, *The value
5//! encoding*) applied by calls into [`crate::primitives`], in declaration
6//! order, with no [`Value`] in between: a record is its fields in order, an
7//! enum is its constructor's number and then its payload's parts, an
8//! `Option` is `None` or `Some` and its value, a list is its count and its
9//! items. Every field's form is its Rust type's ([`WireForm`]):
10//! [`flow_value::Int`] is an `Int`, `bool` a `Bool`, `String` a `Text`,
11//! [`flow_value::Bytes`] and `[u8; N]` `Bytes`, [`flow_value::Instant`] an `Instant`,
12//! `Option<T>`, `Result<T, E>`, `Vec<T>` and a pair `(A, B)` are `Option`,
13//! `Result`, `List` and a tuple, `Box<T>` is `T`, and another declared
14//! type is itself. Four forms have no Flow type: `u64`, a number written as
15//! itself, [`RunId`] and [`CallRef`], a text their own parse admits, and
16//! [`Rest`], the bytes left in a message, which only a last field may be.
17//!
18//! A message is read by the walk every value decoder shares (the crate's
19//! `build` module), its frames on the heap: each type's [`Wire::open`]
20//! reads its own head, such as a constructor's number or a list's count, and
21//! gives the value or its parts to open and how they are joined. A message
22//! nests as deeply as its bytes do, since a description's nesting has no
23//! limit (`abi.md`, *Type descriptions*), and the native stack stays the same
24//! however deep it is.
25//!
26//! A [`Shape`] is the declaration as data: its name, and its fields or its
27//! constructors with their numbers. [`Shape::project`] makes the Flow type of
28//! a shape with neither form, declared in a catalog, so a declared message
29//! is a Flow value too, which [`Shaped::write_at`] writes a message as. A
30//! constructor's number is its position unless the declaration gives it,
31//! as `Name { .. } = 1`. An enum may name a fieldless companion, its
32//! constructors' kinds, which says which constructor a value is and finds
33//! one by its number. Where the constructor is told apart outside the bytes,
34//! an enum is written as its payload alone ([`Keyed`]).
35
36use std::any::Any;
37use std::collections::HashMap;
38use std::num::NonZeroU64;
39use std::ops::Range;
40use std::sync::Arc;
41
42use flow_span::{CallRef, RunId, TaskPath};
43use flow_types::{
44    Body, Constructor, Decl, DeclId, EnumShape, Identity, ModulePath, OptionCtor, Payload,
45    RecordShape, Segments, Tree,
46};
47
48use crate::binary::{read_instant, write_instant};
49use crate::build::{Begun, Frame, Walk, build};
50use crate::bytes::{
51    ERR, NONE, OK, Reader, SOME, wide, write_bytes, write_int, write_text, write_uint,
52};
53use crate::catalog::Catalog;
54use crate::error::{DecodeError, DecodeErrorKind, EncodeError, Place};
55use crate::limits::Limits;
56
57mod shaped;
58
59pub use crate::binary::{ValueReader, ValueWriter};
60pub use crate::crossing::Fields;
61pub use flow_types::Type;
62pub use flow_value::Value;
63pub use shaped::{Param, instant_of};
64
65/// How a field or payload part is written, as its Rust type says: the
66/// one mapping from a Rust type to a Flow type's shape, which a message's
67/// codec and a toolkit's contract both read.
68#[derive(Clone, Copy, Debug)]
69pub enum WireForm {
70    /// [`flow_value::Int`]: a signed number, a Flow `Int`.
71    Int,
72    /// [`flow_value::Decimal`]: a Flow `Decimal`.
73    Decimal,
74    /// `bool`: one byte, `0` or `1`.
75    Bool,
76    /// `String`: a text.
77    Text,
78    /// [`flow_value::Bytes`]: a run of bytes.
79    Bytes,
80    /// [`flow_value::Duration`]: std's `duration.Duration`.
81    Duration,
82    /// [`flow_value::Instant`]: std's `time.Instant`.
83    Instant,
84    /// `()`: `Unit`, written as nothing.
85    Unit,
86    /// [`std::convert::Infallible`]: `Never`, which has no values.
87    Never,
88    /// [`RunId`]: a text that is a run's id, which no Flow type checks.
89    RunId,
90    /// [`CallRef`]: a text that is a call's id, which no Flow type checks.
91    CallRef,
92    /// `u64`: a number, which no Flow type writes.
93    Number,
94    /// [`Rest`]: every byte left in the message, unframed.
95    Rest,
96    /// `Option<T>`, of `T`'s form.
97    Option(fn() -> WireForm),
98    /// `Vec<T>`, a list of `T`'s form.
99    List(fn() -> WireForm),
100    /// A set of `T`'s form.
101    Set(fn() -> WireForm),
102    /// A dictionary of these key and value forms.
103    Dict(fn() -> WireForm, fn() -> WireForm),
104    /// A tuple of these forms, in order.
105    Tuple(&'static [fn() -> WireForm]),
106    /// A declared type with no type parameters.
107    Declared(fn() -> &'static Shape),
108    /// The declaration's type parameter at this position.
109    Param(usize),
110    /// A declared type with type parameters, applied to these arguments.
111    Applied(fn() -> &'static Shape, &'static [fn() -> WireForm]),
112    /// A std declaration, of this module and name, applied to these
113    /// arguments: a prelude one, such as `Result`, has the empty module.
114    Std {
115        /// The std module that declares it; empty for the prelude.
116        module: &'static str,
117        /// Its name.
118        name: &'static str,
119        /// The forms of its type arguments.
120        args: &'static [fn() -> WireForm],
121    },
122}
123
124/// A declared message: its name, and what it is made of.
125#[derive(Debug)]
126pub struct Shape {
127    /// The type's name, which is its Flow type's.
128    pub name: &'static str,
129    /// Its type parameters' names, in order.
130    pub params: &'static [&'static str],
131    /// Its fields or its constructors.
132    pub layout: Layout,
133    /// What a declaration's text says beside its shape, when it has one.
134    pub notes: Option<&'static Notes>,
135}
136
137/// What a declaration's text says beside its shape: where its Rust type is
138/// defined, its doc comment, and each member's.
139#[derive(Debug)]
140pub struct Notes {
141    /// The Rust module that defines it, as `module_path!()` spells it.
142    pub module: &'static str,
143    /// The file that defines it, as `file!()` spells it.
144    pub file: &'static str,
145    /// The line it is defined at.
146    pub line: u32,
147    /// Its doc comment's text, one line each.
148    pub docs: &'static str,
149    /// A record's fields, an enum's constructors or a newtype's one field,
150    /// in declaration order.
151    pub members: &'static [Note],
152}
153
154/// What a declaration's text says of one member.
155#[derive(Debug)]
156pub struct Note {
157    /// Its doc comment's text, one line each.
158    pub docs: &'static str,
159    /// Whether it is public.
160    pub public: bool,
161    /// A constructor's named fields.
162    pub fields: &'static [Note],
163}
164
165/// What a declared message is made of.
166#[derive(Debug)]
167pub enum Layout {
168    /// A record of these fields, in order.
169    Record(&'static [Field]),
170    /// An enum of these constructors, in declaration order.
171    Enum(&'static [Ctor]),
172    /// A newtype over this form.
173    Newtype(WireForm),
174    /// A host type, whose values are the host's tokens.
175    Host,
176}
177
178/// A named field of a record or a payload.
179#[derive(Debug)]
180pub struct Field {
181    /// The field's name.
182    pub name: &'static str,
183    /// How it is written.
184    pub form: WireForm,
185}
186
187/// A constructor of a declared enum.
188#[derive(Debug)]
189pub struct Ctor {
190    /// The constructor's name.
191    pub name: &'static str,
192    /// The number its value is written with.
193    pub number: u64,
194    /// Its payload.
195    pub parts: Parts,
196}
197
198/// A constructor's payload.
199#[derive(Debug)]
200pub enum Parts {
201    /// None.
202    Empty,
203    /// Parts by position, of these forms.
204    Positional(&'static [WireForm]),
205    /// Named fields.
206    Named(&'static [Field]),
207}
208
209/// A Rust type mapped to a Flow type: its [`WireForm`], and its values
210/// written and read at the Flow type its form projects to, part by part,
211/// as the value encoding has them.
212pub trait Shaped: Sized + 'static {
213    /// How a value of it is written.
214    const FORM: WireForm;
215
216    /// Writes it as a value of `ty`, the Flow type its form projects to in
217    /// `out`'s catalog.
218    ///
219    /// # Errors
220    ///
221    /// An [`EncodeError`] when its form has no Flow type, `ty` is not that
222    /// type, or the value is out of a form its type holds it to.
223    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError>;
224
225    /// Reads one, a value of `ty` in `input`'s catalog.
226    ///
227    /// # Errors
228    ///
229    /// A [`DecodeError`] when `ty` is not the type its form projects to, or
230    /// the bytes are not a value of `ty` that is one of its own.
231    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError>;
232}
233
234/// A part of an aggregate a [`ValueWriter`] writes: any [`Shaped`] value,
235/// whatever its Rust type.
236pub trait Part {
237    /// Writes it as a value of `ty`, as [`Shaped::write_at`] does.
238    ///
239    /// # Errors
240    ///
241    /// As [`Shaped::write_at`].
242    fn write_part(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError>;
243}
244
245impl<T: Shaped> Part for T {
246    fn write_part(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
247        self.write_at(out, ty)
248    }
249}
250
251/// A type with a binary form of its own: written and read part by part, as
252/// its [`WireForm`] says.
253pub trait Wire: Shaped {
254    /// Appends the bytes it writes before its parts to `out`, and pushes
255    /// its parts to `parts` in the order they are written after them.
256    fn write_head<'a>(&'a self, out: &mut Vec<u8>, parts: &mut Vec<&'a dyn AnyWire>);
257
258    /// Appends its bytes to `out`: its head, and then each part's bytes in
259    /// order, written over a stack on the heap, so a value nested however
260    /// deep is written on a native stack of fixed size.
261    fn write(&self, out: &mut Vec<u8>) {
262        write_parts(out, vec![self]);
263    }
264
265    /// Reads its head at `reader`: the value itself when it has no parts,
266    /// else its parts to read and what joins them.
267    ///
268    /// # Errors
269    ///
270    /// A [`DecodeError`] when the bytes there are not one's head.
271    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError>;
272
273    /// Reads one from `reader`, leaving the reader just past it.
274    ///
275    /// # Errors
276    ///
277    /// A [`DecodeError`] when the bytes there are not one's.
278    fn read(reader: &mut Reader<'_>) -> Result<Self, DecodeError> {
279        let opened = Self::open(reader)?;
280        built(reader, opened)
281    }
282
283    /// Its bytes.
284    fn bytes(&self) -> Vec<u8> {
285        let mut out = Vec::new();
286        self.write(&mut out);
287        out
288    }
289
290    /// The one value `bytes` hold, and nothing else.
291    ///
292    /// # Errors
293    ///
294    /// A [`DecodeError`] when the bytes are not one's, or bytes are left
295    /// over.
296    fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
297        whole(bytes, Self::open)
298    }
299}
300
301/// A [`Wire`] value as the writer's stack holds it, whatever its Rust type.
302pub trait AnyWire {
303    /// As [`Wire::write_head`].
304    fn write_head<'a>(&'a self, out: &mut Vec<u8>, parts: &mut Vec<&'a dyn AnyWire>);
305}
306
307impl<T: Wire> AnyWire for T {
308    fn write_head<'a>(&'a self, out: &mut Vec<u8>, parts: &mut Vec<&'a dyn AnyWire>) {
309        Wire::write_head(self, out, parts);
310    }
311}
312
313/// Appends the bytes of each of `parts` to `out`, in order: a head, then
314/// its parts' bytes before the next part's.
315fn write_parts(out: &mut Vec<u8>, mut parts: Vec<&dyn AnyWire>) {
316    parts.reverse();
317    while let Some(next) = parts.pop() {
318        let at = parts.len();
319        next.write_head(out, &mut parts);
320        parts[at..].reverse();
321    }
322}
323
324/// The value `opened` began at `reader`, its parts read from there.
325fn built<T: 'static>(reader: &mut Reader<'_>, opened: Opened) -> Result<T, DecodeError> {
326    let built = build(
327        &mut Reading {
328            reader,
329            path: Place::default(),
330        },
331        opened.0,
332    )?;
333    Ok(Joined(vec![built].into_iter()).part())
334}
335
336/// The one value `bytes` hold, begun by `open`, and nothing else.
337fn whole<T: 'static>(
338    bytes: &[u8],
339    open: impl FnOnce(&mut Reader<'_>) -> Result<Opened, DecodeError>,
340) -> Result<T, DecodeError> {
341    let mut reader = Reader::new(bytes);
342    let opened = open(&mut reader)?;
343    let value = built(&mut reader, opened)?;
344    if reader.is_empty() {
345        Ok(value)
346    } else {
347        Err(DecodeError::of(
348            &Place::default(),
349            DecodeErrorKind::Mismatch,
350            format!("has {} bytes left over", reader.remaining()),
351        ))
352    }
353}
354
355/// The values of `T` written one after another in `bytes` with no count
356/// before them, as a file appended to value by value holds them, each with
357/// the range of bytes it was read from; and, when the rest does not read as
358/// one, the byte it starts at: a tail a write did not finish, bytes that
359/// are not a `T`, or a `T` that reads no bytes and so cannot go on.
360pub fn stream<T: Wire>(bytes: &[u8]) -> (Vec<(Range<usize>, T)>, Option<usize>) {
361    let mut reader = Reader::new(bytes);
362    let mut values = Vec::new();
363    while !reader.is_empty() {
364        let at = reader.position();
365        let Ok(value) = T::read(&mut reader) else {
366            return (values, Some(at));
367        };
368        if reader.position() == at {
369            return (values, Some(at));
370        }
371        values.push((at..reader.position(), value));
372    }
373    (values, None)
374}
375
376/// What opens one value at a reader: [`Wire::open`] of its type.
377pub type Open = fn(&mut Reader<'_>) -> Result<Opened, DecodeError>;
378
379/// What makes one value of the parts its open listed, in their order.
380pub type Join = fn(&mut Joined) -> Box<dyn Any>;
381
382/// A value whose reading has begun: built, or its parts still to read.
383#[derive(Debug)]
384pub struct Opened(Begun<Pending, Join, Box<dyn Any>>);
385
386/// The parts of a value still to read: each opened by its own type, the
387/// next last, or this many items of one type.
388#[derive(Debug)]
389enum Pending {
390    Each(Vec<Open>),
391    Items(Open, usize),
392}
393
394impl Opened {
395    /// A value with no parts, built.
396    pub fn built<T: 'static>(value: T) -> Self {
397        Self(Begun::Done(Box::new(value)))
398    }
399
400    /// A value of `opens.len()` parts, opened in order, then joined.
401    #[must_use]
402    pub fn parts(join: Join, opens: &[Open]) -> Self {
403        Self(Frame::open(
404            join,
405            Pending::Each(opens.iter().rev().copied().collect()),
406            opens.len(),
407            0,
408        ))
409    }
410
411    /// A value of `count` parts, each opened by `open`, then joined; room
412    /// is set aside only for as many as `reader` has bytes left.
413    fn items(join: Join, open: Open, count: usize, reader: &Reader<'_>) -> Self {
414        Self(Frame::open(
415            join,
416            Pending::Items(open, count),
417            count.min(reader.remaining()),
418            0,
419        ))
420    }
421}
422
423/// A message being read from its bytes, by the walk every decoder shares.
424struct Reading<'r, 'b> {
425    reader: &'r mut Reader<'b>,
426    path: Place,
427}
428
429impl Walk<Pending, Join, Box<dyn Any>> for Reading<'_, '_> {
430    type Error = DecodeError;
431
432    fn path(&mut self) -> &mut Place {
433        &mut self.path
434    }
435
436    fn next(
437        &mut self,
438        frame: &mut Frame<Pending, Join, Box<dyn Any>>,
439    ) -> Result<Option<Begun<Pending, Join, Box<dyn Any>>>, DecodeError> {
440        let open = match &mut frame.parts {
441            Pending::Each(opens) => opens.pop(),
442            Pending::Items(open, left) => {
443                let open = *open;
444                left.checked_sub(1).map(|rest| {
445                    *left = rest;
446                    open
447                })
448            }
449        };
450        open.map(|open| open(self.reader).map(|opened| opened.0))
451            .transpose()
452    }
453
454    fn steps(_: &Frame<Pending, Join, Box<dyn Any>>) -> usize {
455        0
456    }
457
458    fn finish(
459        &mut self,
460        frame: Frame<Pending, Join, Box<dyn Any>>,
461    ) -> Result<Box<dyn Any>, DecodeError> {
462        Ok((frame.make)(&mut Joined(frame.values.into_iter())))
463    }
464}
465
466/// The parts of a value, built, in the order its open listed them.
467#[derive(Debug)]
468pub struct Joined(std::vec::IntoIter<Box<dyn Any>>);
469
470impl Joined {
471    /// The next part, a `T`.
472    ///
473    /// # Panics
474    ///
475    /// When no part is left or it is not a `T`: a join takes exactly the
476    /// parts its open listed.
477    pub fn part<T: 'static>(&mut self) -> T {
478        *self
479            .0
480            .next()
481            .and_then(|part| part.downcast().ok())
482            .expect("a join takes the parts its open listed")
483    }
484
485    /// Every part left, each a `T`.
486    fn rest<T: 'static>(&mut self) -> Vec<T> {
487        let mut items = Vec::with_capacity(self.0.len());
488        while self.0.len() > 0 {
489            items.push(self.part());
490        }
491        items
492    }
493}
494
495/// A type [`wire!`](crate::wire!) or [`wire_impl!`](crate::wire_impl!)
496/// declared, whose [`Shape`] is data.
497pub trait Declared: Shaped {
498    /// Its declaration, the only one.
499    const SHAPE: Shape;
500
501    /// Its shape.
502    fn shape() -> &'static Shape {
503        &Self::SHAPE
504    }
505}
506
507/// An enum written as one constructor's payload alone, its constructor
508/// told apart outside the bytes, as a host note's name tells which note it
509/// is (`trace.md`, *Host notes*). [`wire!`](crate::wire!) gives it to
510/// every enum, whose [`Wire::write`] is its constructor's number and then
511/// this.
512pub trait Keyed: Declared + Wire {
513    /// Pushes its payload's parts to `parts`, in the order they are
514    /// written, without its constructor's number.
515    fn payload<'a>(&'a self, parts: &mut Vec<&'a dyn AnyWire>);
516
517    /// Opens the payload of the constructor written with `number`, the
518    /// number read at byte `at`.
519    ///
520    /// # Errors
521    ///
522    /// A [`DecodeError`] when no constructor is written with `number`.
523    fn open_payload(number: u64, at: usize) -> Result<Opened, DecodeError>;
524
525    /// Its payload's bytes.
526    fn payload_bytes(&self) -> Vec<u8> {
527        let mut parts = Vec::new();
528        self.payload(&mut parts);
529        let mut out = Vec::new();
530        write_parts(&mut out, parts);
531        out
532    }
533
534    /// The one value of the constructor written with `number` whose
535    /// payload `bytes` hold, and nothing else.
536    ///
537    /// # Errors
538    ///
539    /// A [`DecodeError`] when no constructor is written with `number`,
540    /// the bytes are not its payload's, or bytes are left over.
541    fn decode_payload(number: u64, bytes: &[u8]) -> Result<Self, DecodeError> {
542        whole(bytes, |_| Self::open_payload(number, 0))
543    }
544}
545
546/// `T`'s form, as a [`WireForm`] holds a part's.
547pub fn form_of<T: Shaped>() -> WireForm {
548    T::FORM
549}
550
551/// Whether no form in `forms` but the last is [`WireForm::Rest`], which
552/// [`wire!`](crate::wire!) holds every declaration to.
553pub const fn rest_is_last(forms: &[WireForm]) -> bool {
554    let mut at = 0;
555    while at + 1 < forms.len() {
556        if matches!(forms[at], WireForm::Rest) {
557            return false;
558        }
559        at += 1;
560    }
561    true
562}
563
564/// Whether no two of `ctors` have one number, which [`wire!`](crate::wire!)
565/// holds every enum to.
566pub const fn numbers_are_distinct(ctors: &[Ctor]) -> bool {
567    let mut at = 0;
568    while at < ctors.len() {
569        let mut other = at + 1;
570        while other < ctors.len() {
571            if ctors[at].number == ctors[other].number {
572                return false;
573            }
574            other += 1;
575        }
576        at += 1;
577    }
578    true
579}
580
581/// The refusal of a constructor number `shape` has no constructor for,
582/// read at byte `at`.
583pub fn unknown(shape: &Shape, number: u64, at: usize) -> DecodeError {
584    DecodeError::of(
585        &Place::default(),
586        DecodeErrorKind::Mismatch,
587        format!(
588            "names constructor {number}, which {} does not have, at byte {at}",
589            shape.name
590        ),
591    )
592}
593
594/// A message's texts and bytes are bounded by its own length.
595pub const MESSAGE: Limits = Limits {
596    text_bytes: usize::MAX,
597    ..Limits::LANGUAGE
598};
599
600/// The position of the constructor a declared message writes with `number`
601/// among its type's constructors, which number them from 0.
602///
603/// # Panics
604///
605/// Never on a 64-bit target; on a narrower one, for a number past its
606/// `usize`.
607pub fn position(number: u64) -> usize {
608    usize::try_from(number).expect("a constructor number fits a usize")
609}
610
611// === The forms ==============================================================
612
613impl Shaped for flow_value::Int {
614    const FORM: WireForm = WireForm::Int;
615
616    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
617        out.int(ty, self)
618    }
619
620    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
621        input.int(ty)
622    }
623}
624
625impl Wire for flow_value::Int {
626    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
627        write_int(out, self.as_bigint());
628    }
629
630    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
631        Ok(Opened::built(flow_value::Int::from(reader.int(&MESSAGE)?)))
632    }
633}
634
635impl Shaped for bool {
636    const FORM: WireForm = WireForm::Bool;
637
638    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
639        out.bool(ty, *self)
640    }
641
642    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
643        input.bool(ty)
644    }
645}
646
647impl Wire for bool {
648    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
649        out.push(u8::from(*self));
650    }
651
652    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
653        Ok(Opened::built(reader.bool()?))
654    }
655}
656
657impl Shaped for String {
658    const FORM: WireForm = WireForm::Text;
659
660    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
661        out.text(ty, self)
662    }
663
664    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
665        input.text(ty).map(str::to_owned)
666    }
667}
668
669impl Wire for String {
670    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
671        write_text(out, self);
672    }
673
674    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
675        Ok(Opened::built(reader.text(&MESSAGE)?.to_owned()))
676    }
677}
678
679impl Shaped for flow_value::Bytes {
680    const FORM: WireForm = WireForm::Bytes;
681
682    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
683        out.bytes(ty, self.as_slice())
684    }
685
686    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
687        input.bytes(ty).map(flow_value::Bytes::new)
688    }
689}
690
691impl Wire for flow_value::Bytes {
692    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
693        write_bytes(out, self.as_slice());
694    }
695
696    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
697        Ok(Opened::built(flow_value::Bytes::new(
698            reader.bytes(&MESSAGE)?,
699        )))
700    }
701}
702
703/// An OS string is written as its bytes, as `Bytes` is, never through a
704/// lossy text: the platform's own encoding of it, which off Unix is a superset
705/// of UTF-8. Off Unix it reads back only when those bytes are UTF-8, and is
706/// refused otherwise.
707impl Shaped for std::ffi::OsString {
708    const FORM: WireForm = WireForm::Bytes;
709
710    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
711        out.bytes(ty, self.as_encoded_bytes())
712    }
713
714    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
715        os_string(input.bytes(ty))
716    }
717}
718
719impl Wire for std::ffi::OsString {
720    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
721        write_bytes(out, self.as_encoded_bytes());
722    }
723
724    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
725        os_string(reader.bytes(&MESSAGE)).map(Opened::built)
726    }
727}
728
729/// The OS string written as the bytes read.
730#[cfg(unix)]
731fn os_string(bytes: Result<&[u8], DecodeError>) -> Result<std::ffi::OsString, DecodeError> {
732    use std::os::unix::ffi::OsStringExt as _;
733    bytes.map(|bytes| std::ffi::OsString::from_vec(bytes.to_vec()))
734}
735
736/// The OS string written as the bytes read, which must be UTF-8: the one
737/// encoding of an OS string read here without unsafe code.
738#[cfg(not(unix))]
739fn os_string(bytes: Result<&[u8], DecodeError>) -> Result<std::ffi::OsString, DecodeError> {
740    std::str::from_utf8(bytes?)
741        .map(std::ffi::OsString::from)
742        .map_err(|_| {
743            DecodeError::of(
744                &Place::default(),
745                DecodeErrorKind::Mismatch,
746                "holds an OS string that is not UTF-8, which this platform does not read"
747                    .to_owned(),
748            )
749        })
750}
751
752impl Shaped for flow_value::Instant {
753    const FORM: WireForm = WireForm::Instant;
754
755    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
756        out.instant(ty, self)
757    }
758
759    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
760        input.instant(ty)
761    }
762}
763
764impl Wire for flow_value::Instant {
765    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
766        write_instant(out, self);
767    }
768
769    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
770        Ok(Opened::built(read_instant(reader, &Limits::LANGUAGE)?))
771    }
772}
773
774/// A run of exactly `N` bytes, written as `Bytes` are: a run of any other
775/// length is not one.
776impl<const N: usize> Shaped for [u8; N] {
777    const FORM: WireForm = WireForm::Bytes;
778
779    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
780        out.bytes(ty, self)
781    }
782
783    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
784        input.bytes(ty)?.try_into().map_err(|_| input.mismatch(ty))
785    }
786}
787
788impl<const N: usize> Wire for [u8; N] {
789    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
790        write_bytes(out, self);
791    }
792
793    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
794        let at = reader.position();
795        let bytes: [u8; N] = reader.bytes(&MESSAGE)?.try_into().map_err(|_| {
796            DecodeError::of(
797                &Place::default(),
798                DecodeErrorKind::Mismatch,
799                format!("has bytes at byte {at} that are not {N} long"),
800            )
801        })?;
802        Ok(Opened::built(bytes))
803    }
804}
805
806/// A digest is written as its 32 bytes.
807impl Shaped for crate::Digest {
808    const FORM: WireForm = WireForm::Bytes;
809
810    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
811        self.0.write_at(out, ty)
812    }
813
814    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
815        <[u8; 32]>::read_at(input, ty).map(crate::Digest)
816    }
817}
818
819impl Wire for crate::Digest {
820    fn write_head<'a>(&'a self, _: &mut Vec<u8>, parts: &mut Vec<&'a dyn AnyWire>) {
821        parts.push(&self.0);
822    }
823
824    fn open(_: &mut Reader<'_>) -> Result<Opened, DecodeError> {
825        Ok(Opened::parts(
826            |parts| -> Box<dyn Any> { Box::new(crate::Digest(parts.part())) },
827            &[<[u8; 32]>::open],
828        ))
829    }
830}
831
832/// A form no Flow type has: its values are none of a Flow type's.
833macro_rules! unshaped {
834    ($rust:ty, $form:expr) => {
835        impl Shaped for $rust {
836            const FORM: WireForm = $form;
837
838            fn write_at(
839                &self,
840                out: &mut ValueWriter<'_, '_>,
841                ty: &Type,
842            ) -> Result<(), EncodeError> {
843                Err(out.refuse(ty))
844            }
845
846            fn read_at(
847                input: &mut ValueReader<'_, '_, '_>,
848                ty: &Type,
849            ) -> Result<Self, DecodeError> {
850                Err(input.mismatch(ty))
851            }
852        }
853    };
854}
855
856unshaped!(RunId, WireForm::RunId);
857
858/// A run id is its 16 bits, most significant byte first, with no length
859/// (`abi.md`, *Numbers and text*).
860impl Wire for RunId {
861    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
862        out.extend_from_slice(&self.bits());
863    }
864
865    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
866        let mut bits = [0; 16];
867        bits.copy_from_slice(reader.take(16)?);
868        Ok(Opened::built(RunId::from_bits(bits)))
869    }
870}
871
872unshaped!(CallRef, WireForm::CallRef);
873
874/// A call id is written as history writes it (`trace.md`, *Facts*): its
875/// segment, its task id and its counter.
876impl Wire for CallRef {
877    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
878        write_uint(out, self.segment());
879        write_task(out, self.task());
880        write_uint(out, self.index().get());
881    }
882
883    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
884        let segment = reader.uint()?;
885        let task = read_task(reader)?;
886        let at = reader.position();
887        let index = NonZeroU64::new(reader.uint()?)
888            .ok_or_else(|| zero(at, "a call's counter, which counts from 1"))?;
889        Ok(Opened::built(CallRef::new(segment, task, index)))
890    }
891}
892
893/// Writes `task`'s id: how many spawn counters its path has, then those
894/// counters (`trace.md`, *Facts*).
895pub fn write_task(out: &mut Vec<u8>, task: &TaskPath) {
896    write_uint(out, wide(task.counts().len()));
897    for count in task.counts() {
898        write_uint(out, count.get());
899    }
900}
901
902/// Reads a task id [`write_task`] wrote.
903///
904/// # Errors
905///
906/// A [`DecodeError`] when the input ends inside it or a counter is `0`.
907pub fn read_task(reader: &mut Reader<'_>) -> Result<TaskPath, DecodeError> {
908    let at = reader.position();
909    let count = reader.count()?;
910    if count > reader.remaining() {
911        return Err(DecodeError::of(
912            &Place::default(),
913            DecodeErrorKind::Syntax { at },
914            format!("has a task id of {count} counters at byte {at}, past its end"),
915        ));
916    }
917    let mut counts = Vec::with_capacity(count);
918    for _ in 0..count {
919        let at = reader.position();
920        counts.push(
921            NonZeroU64::new(reader.uint()?)
922                .ok_or_else(|| zero(at, "a spawn counter, which counts from 1"))?,
923        );
924    }
925    Ok(TaskPath::new(counts))
926}
927
928/// The error of a `0` at byte `at` where `what` stands.
929fn zero(at: usize, what: &str) -> DecodeError {
930    DecodeError::of(
931        &Place::default(),
932        DecodeErrorKind::Mismatch,
933        format!("has 0 for {what}, at byte {at}"),
934    )
935}
936
937unshaped!(u64, WireForm::Number);
938
939impl Wire for u64 {
940    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
941        write_uint(out, *self);
942    }
943
944    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
945        Ok(Opened::built(reader.uint()?))
946    }
947}
948
949/// Every byte left in a message, unframed: a part whose type the message's
950/// head names, read once the head is.
951#[derive(Clone, PartialEq, Eq, Debug, Default)]
952pub struct Rest(pub Vec<u8>);
953
954unshaped!(Rest, WireForm::Rest);
955
956impl Wire for Rest {
957    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
958        out.extend_from_slice(&self.0);
959    }
960
961    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
962        Ok(Opened::built(Rest(
963            reader.take(reader.remaining())?.to_vec(),
964        )))
965    }
966}
967
968impl<T: Shaped> Shaped for Box<T> {
969    const FORM: WireForm = T::FORM;
970
971    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
972        T::write_at(self, out, ty)
973    }
974
975    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
976        T::read_at(input, ty).map(Box::new)
977    }
978}
979
980impl<T: Wire> Wire for Box<T> {
981    fn write_head<'a>(&'a self, _: &mut Vec<u8>, parts: &mut Vec<&'a dyn AnyWire>) {
982        parts.push(&**self);
983    }
984
985    fn open(_: &mut Reader<'_>) -> Result<Opened, DecodeError> {
986        Ok(Opened::parts(
987            |parts| -> Box<dyn Any> { Box::new(Box::new(parts.part::<T>())) },
988            &[T::open],
989        ))
990    }
991}
992
993impl<T: Shaped> Shaped for Option<T> {
994    const FORM: WireForm = WireForm::Option(form_of::<T>);
995
996    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
997        let ctors = &out.catalog().option().ctors;
998        match self {
999            None => out.variant(ty, ctors.index(OptionCtor::None), &[]),
1000            Some(value) => out.variant(ty, ctors.index(OptionCtor::Some), &[value]),
1001        }
1002    }
1003
1004    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
1005        if !matches!(ty, Type::Option(_)) {
1006            return Err(input.mismatch(ty));
1007        }
1008        input.variant(ty, |input, index, payload| {
1009            match input.catalog().option().ctors.which(index) {
1010                Some(OptionCtor::None) => Ok(None),
1011                Some(OptionCtor::Some) => payload.read(input).map(Some),
1012                None => Err(input.mismatch(ty)),
1013            }
1014        })
1015    }
1016}
1017
1018impl<T: Wire> Wire for Option<T> {
1019    fn write_head<'a>(&'a self, out: &mut Vec<u8>, parts: &mut Vec<&'a dyn AnyWire>) {
1020        match self {
1021            None => write_uint(out, NONE),
1022            Some(item) => {
1023                write_uint(out, SOME);
1024                parts.push(item);
1025            }
1026        }
1027    }
1028
1029    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
1030        let at = reader.position();
1031        match reader.uint()? {
1032            NONE => Ok(Opened::built(None::<T>)),
1033            SOME => Ok(Opened::parts(
1034                |parts| -> Box<dyn Any> { Box::new(Some(parts.part::<T>())) },
1035                &[T::open],
1036            )),
1037            other => Err(DecodeError::of(
1038                &Place::default(),
1039                DecodeErrorKind::Mismatch,
1040                format!("names constructor {other}, which Option does not have, at byte {at}"),
1041            )),
1042        }
1043    }
1044}
1045
1046/// std's `Result`: `Ok` then `Err`, as std declares them, whichever
1047/// numbers a catalog gives them.
1048impl<T: Shaped, E: Shaped> Shaped for Result<T, E> {
1049    const FORM: WireForm = WireForm::Std {
1050        module: "",
1051        name: "Result",
1052        args: &[form_of::<T>, form_of::<E>],
1053    };
1054
1055    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
1056        match self {
1057            Ok(value) => out.variant(ty, position(OK), &[value]),
1058            Err(error) => out.variant(ty, position(ERR), &[error]),
1059        }
1060    }
1061
1062    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
1063        input.variant(ty, |input, at, payload| match wide(at) {
1064            OK => payload.read(input).map(Ok),
1065            ERR => payload.read(input).map(Err),
1066            _ => Err(input.mismatch(ty)),
1067        })
1068    }
1069}
1070
1071impl<T: Wire, E: Wire> Wire for Result<T, E> {
1072    fn write_head<'a>(&'a self, out: &mut Vec<u8>, parts: &mut Vec<&'a dyn AnyWire>) {
1073        match self {
1074            Ok(value) => {
1075                write_uint(out, OK);
1076                parts.push(value);
1077            }
1078            Err(error) => {
1079                write_uint(out, ERR);
1080                parts.push(error);
1081            }
1082        }
1083    }
1084
1085    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
1086        let at = reader.position();
1087        match reader.uint()? {
1088            OK => Ok(Opened::parts(
1089                |parts| -> Box<dyn Any> { Box::new(Ok::<T, E>(parts.part::<T>())) },
1090                &[T::open],
1091            )),
1092            ERR => Ok(Opened::parts(
1093                |parts| -> Box<dyn Any> { Box::new(Err::<T, E>(parts.part::<E>())) },
1094                &[E::open],
1095            )),
1096            other => Err(DecodeError::of(
1097                &Place::default(),
1098                DecodeErrorKind::Mismatch,
1099                format!("names constructor {other}, which Result does not have, at byte {at}"),
1100            )),
1101        }
1102    }
1103}
1104
1105impl<T: Shaped> Shaped for Vec<T> {
1106    const FORM: WireForm = WireForm::List(form_of::<T>);
1107
1108    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
1109        out.list(ty, self.iter())
1110    }
1111
1112    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
1113        input.list(ty)
1114    }
1115}
1116
1117impl<T: Wire> Wire for Vec<T> {
1118    fn write_head<'a>(&'a self, out: &mut Vec<u8>, parts: &mut Vec<&'a dyn AnyWire>) {
1119        write_uint(out, wide(self.len()));
1120        parts.extend(self.iter().map(|item| -> &dyn AnyWire { item }));
1121    }
1122
1123    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
1124        let count = reader.count()?;
1125        Ok(Opened::items(
1126            |parts| -> Box<dyn Any> { Box::new(parts.rest::<T>()) },
1127            T::open,
1128            count,
1129            reader,
1130        ))
1131    }
1132}
1133
1134impl<A: Wire, B: Wire> Wire for (A, B) {
1135    fn write_head<'a>(&'a self, _: &mut Vec<u8>, parts: &mut Vec<&'a dyn AnyWire>) {
1136        parts.push(&self.0);
1137        parts.push(&self.1);
1138    }
1139
1140    fn open(_: &mut Reader<'_>) -> Result<Opened, DecodeError> {
1141        Ok(Opened::parts(
1142            |parts| -> Box<dyn Any> { Box::new((parts.part::<A>(), parts.part::<B>())) },
1143            &[A::open, B::open],
1144        ))
1145    }
1146}
1147
1148// === Projection =============================================================
1149
1150/// The declarations a projection makes, each shape's by its address: two
1151/// shapes of one name are two declarations.
1152type Ids = HashMap<*const Shape, DeclId>;
1153
1154impl Shape {
1155    /// Its constructors; none for a record.
1156    pub fn ctors(&self) -> &'static [Ctor] {
1157        match self.layout {
1158            Layout::Record(_) | Layout::Newtype(_) | Layout::Host => &[],
1159            Layout::Enum(ctors) => ctors,
1160        }
1161    }
1162
1163    /// Each constructor's name as a constant spells it, the shape's name
1164    /// and the constructor's in capitals joined by `_`, and its number:
1165    /// `TERM_JSON_VALUE` for `Term::JsonValue`. A toolkit in another
1166    /// language takes its numbers from these.
1167    pub fn constants(&self) -> Vec<(String, u64)> {
1168        let constant = |name: &str| {
1169            let mut out = String::new();
1170            for (at, letter) in name.chars().enumerate() {
1171                if letter.is_uppercase() && at > 0 {
1172                    out.push('_');
1173                }
1174                out.push(letter.to_ascii_uppercase());
1175            }
1176            out
1177        };
1178        self.ctors()
1179            .iter()
1180            .map(|ctor| {
1181                (
1182                    format!("{}_{}", constant(self.name), constant(ctor.name)),
1183                    ctor.number,
1184                )
1185            })
1186            .collect()
1187    }
1188
1189    /// `catalog` with this shape and every shape it reaches declared, and
1190    /// the type this shape is there, as [`project`] gives them.
1191    ///
1192    /// # Panics
1193    ///
1194    /// As [`project`]'s.
1195    pub fn project(&'static self, catalog: &Catalog) -> Option<(Catalog, Type)> {
1196        let (extended, ids) = declared(vec![self], catalog)?;
1197        Some((
1198            extended,
1199            Type::Named(ids[&std::ptr::from_ref(self)], Vec::new()),
1200        ))
1201    }
1202
1203    /// Calls `visit` with each part's form, in declaration order.
1204    fn each_form(&self, mut visit: impl FnMut(WireForm)) {
1205        match self.layout {
1206            Layout::Record(fields) => fields.iter().for_each(|field| visit(field.form)),
1207            Layout::Newtype(base) => visit(base),
1208            Layout::Host => {}
1209            Layout::Enum(ctors) => {
1210                for ctor in ctors {
1211                    match ctor.parts {
1212                        Parts::Empty => {}
1213                        Parts::Positional(forms) => forms.iter().copied().for_each(&mut visit),
1214                        Parts::Named(fields) => fields.iter().for_each(|field| visit(field.form)),
1215                    }
1216                }
1217            }
1218        }
1219    }
1220
1221    /// This shape's declaration, of lexical ordinal `ordinal`, each shape
1222    /// it names by its id in `ids`.
1223    fn decl(&self, ordinal: u32, ids: &Ids, catalog: &Catalog) -> Option<Decl> {
1224        let ty = |form| projected(form, ids, catalog);
1225        let body = match self.layout {
1226            Layout::Record(fields) => Body::Record(
1227                RecordShape::new(self.name, fields.iter().map(|field| field.name)),
1228                fields
1229                    .iter()
1230                    .map(|field| ty(field.form))
1231                    .collect::<Option<_>>()?,
1232            ),
1233            Layout::Enum(ctors) => {
1234                let mut constructors = Vec::new();
1235                let mut payloads = Vec::new();
1236                for (at, ctor) in ctors.iter().enumerate() {
1237                    if ctor.number != wide(at) {
1238                        return None;
1239                    }
1240                    let (payload, parts) = match ctor.parts {
1241                        Parts::Empty => (Payload::None, Vec::new()),
1242                        Parts::Positional(forms) => (
1243                            Payload::Positional(forms.len()),
1244                            forms.iter().map(|form| ty(*form)).collect::<Option<_>>()?,
1245                        ),
1246                        Parts::Named(fields) => (
1247                            Payload::Named(
1248                                fields.iter().map(|field| Arc::from(field.name)).collect(),
1249                            ),
1250                            fields
1251                                .iter()
1252                                .map(|field| ty(field.form))
1253                                .collect::<Option<_>>()?,
1254                        ),
1255                    };
1256                    constructors.push(Constructor::new(ctor.name, payload));
1257                    payloads.push(parts);
1258                }
1259                Body::Enum(EnumShape::new(self.name, constructors), payloads)
1260            }
1261            Layout::Newtype(base) => Body::Newtype(ty(base)?),
1262            Layout::Host => Body::Host,
1263        };
1264        Some(Decl {
1265            lexical_ordinal: ordinal,
1266            identity: Identity {
1267                origin: ModulePath::new(Tree::Local, None, Segments::from_names(["abi"])?),
1268                version: None,
1269                name: self.name.to_owned(),
1270            },
1271            doc: None,
1272            members: Vec::new(),
1273            params: self.params.iter().map(|name| (*name).to_owned()).collect(),
1274            opaque: false,
1275            body,
1276        })
1277    }
1278}
1279
1280/// `catalog` with the shape a value of `form`'s Rust type is declared
1281/// after its own declarations, with every shape it reaches, in first-reach
1282/// order, and the Flow type of `form` there. `Option` is std's, whose
1283/// constructors the catalog found by name, and a std form names the
1284/// declaration of its module and name that `catalog` holds; a std form of
1285/// no module, such as `Result`'s, names the std declaration of its name.
1286/// Shapes of one name are told apart by their lexical ordinals, in the
1287/// order they are reached. `None` when a shape it reaches has a form with
1288/// no Flow type, such as a [`WireForm::Number`] or a [`WireForm::Rest`],
1289/// names a std declaration `catalog` does not hold, or numbers a
1290/// constructor other than by its position: no Flow type writes those bytes.
1291///
1292/// # Panics
1293///
1294/// When the catalog and the shapes hold more declarations than a 32-bit
1295/// id numbers.
1296pub fn project(form: WireForm, catalog: &Catalog) -> Option<(Catalog, Type)> {
1297    let mut roots = Vec::new();
1298    reaches(form, &mut roots);
1299    let (extended, ids) = declared(roots, catalog)?;
1300    let ty = projected(form, &ids, catalog)?;
1301    Some((extended, ty))
1302}
1303
1304/// `catalog` with `roots` and every shape they reach declared after its
1305/// own declarations, in first-reach order, and the id each shape has.
1306fn declared(roots: Vec<&'static Shape>, catalog: &Catalog) -> Option<(Catalog, Ids)> {
1307    let first = catalog.decls().len();
1308    let mut order: Vec<&'static Shape> = Vec::new();
1309    let mut ids = Ids::new();
1310    let mut pending: Vec<&'static Shape> = roots.into_iter().rev().collect();
1311    while let Some(shape) = pending.pop() {
1312        if ids.contains_key(&std::ptr::from_ref(shape)) {
1313            continue;
1314        }
1315        let id = u32::try_from(first + order.len()).expect("a catalog fits 32-bit ids");
1316        ids.insert(std::ptr::from_ref(shape), DeclId(id));
1317        order.push(shape);
1318        let mut reached = Vec::new();
1319        shape.each_form(|form| reaches(form, &mut reached));
1320        pending.extend(reached.into_iter().rev());
1321    }
1322    let mut ordinals: HashMap<&str, u32> = HashMap::new();
1323    let decls = order
1324        .iter()
1325        .map(|shape| {
1326            let ordinal = ordinals.entry(shape.name).or_default();
1327            *ordinal += 1;
1328            shape.decl(*ordinal, &ids, catalog)
1329        })
1330        .collect::<Option<Vec<Decl>>>()?;
1331    Some((catalog.extended(decls), ids))
1332}
1333
1334/// The std declaration `catalog` holds for the std form of `module` and
1335/// `name`; a form of no module names a declaration of std's prelude.
1336fn std_decl(catalog: &Catalog, module: &str, name: &str) -> Option<DeclId> {
1337    catalog.decls().find_map(|(id, decl)| {
1338        let origin = &decl.identity.origin;
1339        (*origin.tree() == Tree::Std
1340            && decl.identity.name == name
1341            && (module.is_empty() || *origin.segments() == module))
1342            .then_some(id)
1343    })
1344}
1345
1346/// Pushes the declared shapes `form` names onto `reached`, in order.
1347fn reaches(form: WireForm, reached: &mut Vec<&'static Shape>) {
1348    match form {
1349        WireForm::Int
1350        | WireForm::Decimal
1351        | WireForm::Bool
1352        | WireForm::Text
1353        | WireForm::Bytes
1354        | WireForm::Duration
1355        | WireForm::Instant
1356        | WireForm::Unit
1357        | WireForm::Never
1358        | WireForm::RunId
1359        | WireForm::CallRef
1360        | WireForm::Number
1361        | WireForm::Rest
1362        | WireForm::Param(_) => {}
1363        WireForm::Option(item) | WireForm::List(item) | WireForm::Set(item) => {
1364            reaches(item(), reached);
1365        }
1366        WireForm::Dict(key, value) => {
1367            reaches(key(), reached);
1368            reaches(value(), reached);
1369        }
1370        WireForm::Tuple(parts) | WireForm::Std { args: parts, .. } => {
1371            for part in parts {
1372                reaches(part(), reached);
1373            }
1374        }
1375        WireForm::Declared(shape) => reached.push(shape()),
1376        WireForm::Applied(shape, args) => {
1377            reached.push(shape());
1378            for arg in args {
1379                reaches(arg(), reached);
1380            }
1381        }
1382    }
1383}
1384
1385/// The Flow type of `form`, each shape it names by its id in `ids` and
1386/// each std form by its declaration in `catalog`.
1387fn projected(form: WireForm, ids: &Ids, catalog: &Catalog) -> Option<Type> {
1388    let all = |forms: &[fn() -> WireForm]| {
1389        forms
1390            .iter()
1391            .map(|part| projected(part(), ids, catalog))
1392            .collect::<Option<Vec<Type>>>()
1393    };
1394    Some(match form {
1395        WireForm::Int => Type::Int,
1396        WireForm::Decimal => Type::Decimal,
1397        WireForm::Bool => Type::Bool,
1398        WireForm::Text => Type::Text,
1399        WireForm::Bytes => Type::Bytes,
1400        WireForm::Duration => Type::Duration,
1401        WireForm::Instant => Type::Instant,
1402        WireForm::Unit => Type::Unit,
1403        WireForm::Never => Type::Never,
1404        WireForm::RunId | WireForm::CallRef | WireForm::Number | WireForm::Rest => return None,
1405        WireForm::Std {
1406            module: "json",
1407            name: "Value",
1408            args: [],
1409        } => Type::Json,
1410        WireForm::Std { module, name, args } => {
1411            Type::Named(std_decl(catalog, module, name)?, all(args)?)
1412        }
1413        WireForm::Option(item) => Type::option(projected(item(), ids, catalog)?),
1414        WireForm::List(item) => Type::list(projected(item(), ids, catalog)?),
1415        WireForm::Set(item) => Type::set(projected(item(), ids, catalog)?),
1416        WireForm::Dict(key, value) => Type::dict(
1417            projected(key(), ids, catalog)?,
1418            projected(value(), ids, catalog)?,
1419        ),
1420        WireForm::Tuple(parts) => Type::Tuple(all(parts)?),
1421        WireForm::Param(at) => Type::Param(u32::try_from(at).ok()?),
1422        WireForm::Declared(shape) => Type::Named(ids[&std::ptr::from_ref(shape())], Vec::new()),
1423        WireForm::Applied(shape, args) => {
1424            Type::Named(ids[&std::ptr::from_ref(shape())], all(args)?)
1425        }
1426    })
1427}
1428
1429// === The macro ==============================================================
1430
1431/// Declares a record or an enum once: the type itself, its
1432/// [`Wire`](crate::wire::Wire) codec and its [`Shape`](crate::wire::Shape).
1433/// Doc comments and attributes pass through.
1434///
1435/// ```
1436/// use flow_abi::wire::{Keyed, Wire};
1437///
1438/// flow_abi::wire! {
1439///     /// What a request asks for.
1440///     #[derive(Clone, Debug, PartialEq)]
1441///     pub enum Request {
1442///         /// What the server is doing.
1443///         Status,
1444///         /// Move, by three flags.
1445///         Move(bool, String, bool),
1446///         /// Stop, and why.
1447///         Stop { reason: String } = 5,
1448///     }
1449///     /// Which request one is.
1450///     pub enum RequestKind;
1451/// }
1452///
1453/// let stop = Request::Stop { reason: "done".to_owned() };
1454/// assert_eq!(stop.bytes(), [5, 4, b'd', b'o', b'n', b'e']);
1455/// assert_eq!(Request::decode(&stop.bytes()), Ok(stop.clone()));
1456/// assert_eq!(stop.payload_bytes(), [4, b'd', b'o', b'n', b'e']);
1457/// assert_eq!(Request::decode_payload(5, &stop.payload_bytes()), Ok(stop));
1458/// let moved = Request::Move(true, "a".to_owned(), false);
1459/// assert_eq!(moved.bytes(), [1, 1, 1, b'a', 0]);
1460/// assert_eq!(Request::decode(&moved.bytes()), Ok(moved));
1461/// assert_eq!(RequestKind::of(5), Some(RequestKind::Stop));
1462/// assert_eq!(RequestKind::Status.number(), 0);
1463/// ```
1464///
1465/// A constructor's number is its position unless given after `=`. An enum
1466/// may take type parameters, each a part's type, and may name after it a
1467/// fieldless companion enum of its constructors' kinds, which for an enum
1468/// with type parameters needs each to have a default; an enum whose
1469/// constructors carry nothing names itself, `enum Self;`.
1470///
1471/// A declaration that could not read back what it writes does not compile:
1472/// a [`Rest`](crate::wire::Rest) before the last part of a record, a named
1473/// payload or a positional one,
1474///
1475/// ```compile_fail,E0080
1476/// flow_abi::wire! {
1477///     pub enum Message {
1478///         Case(flow_abi::wire::Rest, String),
1479///     }
1480/// }
1481/// ```
1482///
1483/// and two constructors of one number.
1484///
1485/// ```compile_fail,E0080
1486/// flow_abi::wire! {
1487///     pub enum Message {
1488///         A = 5,
1489///         B = 5,
1490///     }
1491/// }
1492/// ```
1493#[macro_export]
1494macro_rules! wire {
1495    (
1496        $(#[$meta:meta])*
1497        $vis:vis struct $name:ident {
1498            $( $(#[$field_meta:meta])* $field_vis:vis $field:ident : $ty:ty ),* $(,)?
1499        }
1500    ) => {
1501        $(#[$meta])*
1502        $vis struct $name {
1503            $( $(#[$field_meta])* $field_vis $field : $ty ),*
1504        }
1505
1506        const _: () = assert!(
1507            $crate::wire::rest_is_last(&[$( <$ty as $crate::wire::Shaped>::FORM ),*]),
1508            "only a message's last field may be its rest"
1509        );
1510
1511        impl $crate::wire::Declared for $name {
1512            const SHAPE: $crate::wire::Shape = $crate::wire::Shape {
1513                name: stringify!($name),
1514                params: &[],
1515                layout: $crate::wire::Layout::Record(&[$(
1516                    $crate::wire::Field {
1517                        name: stringify!($field),
1518                        form: <$ty as $crate::wire::Shaped>::FORM,
1519                    }
1520                ),*]),
1521                notes: None,
1522            };
1523        }
1524
1525        impl $crate::wire::Shaped for $name {
1526            const FORM: $crate::wire::WireForm =
1527                $crate::wire::WireForm::Declared(<Self as $crate::wire::Declared>::shape);
1528
1529            fn write_at(
1530                &self,
1531                out: &mut $crate::wire::ValueWriter<'_, '_>,
1532                ty: &$crate::wire::Type,
1533            ) -> Result<(), $crate::EncodeError> {
1534                out.record(ty, &[$( &self.$field ),*])
1535            }
1536
1537            fn read_at(
1538                input: &mut $crate::wire::ValueReader<'_, '_, '_>,
1539                ty: &$crate::wire::Type,
1540            ) -> Result<Self, $crate::DecodeError> {
1541                input.record(ty, |input, fields| {
1542                    let _ = (&input, &fields);
1543                    Ok(Self { $( $field: fields.read::<$ty>(input)?, )* })
1544                })
1545            }
1546        }
1547
1548        impl $crate::wire::Wire for $name {
1549            fn write_head<'a>(
1550                &'a self,
1551                _: &mut Vec<u8>,
1552                parts: &mut Vec<&'a dyn $crate::wire::AnyWire>,
1553            ) {
1554                let _ = &parts;
1555                $( parts.push(&self.$field); )*
1556            }
1557
1558            fn open(
1559                _: &mut $crate::primitives::Reader<'_>,
1560            ) -> Result<$crate::wire::Opened, $crate::DecodeError> {
1561                Ok($crate::wire::Opened::parts(
1562                    |parts| -> Box<dyn ::std::any::Any> {
1563                        Box::new(Self { $( $field: parts.part::<$ty>(), )* })
1564                    },
1565                    &[$( <$ty as $crate::wire::Wire>::open ),*],
1566                ))
1567            }
1568        }
1569    };
1570
1571    (
1572        $(#[$meta:meta])*
1573        $vis:vis enum $name:ident $( < $( $gen:ident $( = $default:ty )? ),+ > )? {
1574            $(
1575                $(#[$variant_meta:meta])*
1576                $variant:ident
1577                $( ( $($part:ty),+ $(,)? ) )?
1578                $( { $( $(#[$member_meta:meta])* $member:ident : $member_ty:ty ),* $(,)? } )?
1579                $( = $number:literal )?
1580            ),* $(,)?
1581        }
1582        $($kind:tt)*
1583    ) => {
1584        $(#[$meta])*
1585        $vis enum $name $( < $( $gen $( = $default )? ),+ > )? {
1586            $(
1587                $(#[$variant_meta])*
1588                $variant
1589                $( ( $($part),+ ) )?
1590                $( { $( $(#[$member_meta])* $member : $member_ty ),* } )?
1591            ),*
1592        }
1593
1594        $crate::wire!(@enum $name [$( $($gen),+ )?] [out head catalog ty parts] [0u64] [] [] [] [] [] $(
1595            $variant
1596            $( ( $($part),+ ) )?
1597            $( { $( $member : $member_ty ),* } )?
1598            $( = $number )?;
1599        )*);
1600
1601        $crate::wire!(@kind $name [$( $($gen),+ )?] [$( $(#[$variant_meta])* $variant )*]
1602            $($kind)*);
1603    };
1604
1605    (@number $at:expr) => { $at };
1606    (@number $at:expr, $number:literal) => { $number };
1607
1608    // No companion of kinds.
1609    (@kind $name:ident $gens:tt [$( $(#[$variant_meta:meta])* $variant:ident )*]) => {};
1610
1611    // An enum whose constructors carry nothing, its own kinds.
1612    (@kind $name:ident [] [$( $(#[$variant_meta:meta])* $variant:ident )*] enum Self;) => {
1613        $crate::wire!(@kinds $name $name [$( $variant )*]);
1614    };
1615
1616    // The companion of kinds; an enum with type parameters names its
1617    // companion's constructors by the shape its defaults give it.
1618    (@kind $name:ident [$( $gen:ident ),*] [$( $(#[$variant_meta:meta])* $variant:ident )*]
1619        $(#[$kind_meta:meta])* $kind_vis:vis enum $kind:ident;
1620    ) => {
1621        $(#[$kind_meta])*
1622        #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1623        $kind_vis enum $kind {
1624            $( $(#[$variant_meta])* $variant ),*
1625        }
1626
1627        $crate::wire!(@kinds $name $kind [$( $variant )*]);
1628
1629        impl<$( $gen ),*> $name<$( $gen ),*> {
1630            /// Which constructor it is.
1631            pub fn kind(&self) -> $kind {
1632                match self {
1633                    $( Self::$variant { .. } => $kind::$variant, )*
1634                }
1635            }
1636        }
1637    };
1638
1639    (@kinds $name:ident $kind:ident [$( $variant:ident )*]) => {
1640        impl $kind {
1641            /// Every kind, in declaration order.
1642            pub const ALL: &'static [$kind] = &[$( $kind::$variant ),*];
1643
1644            /// Its constructor's declaration.
1645            pub fn ctor(self) -> &'static $crate::wire::Ctor {
1646                let at = $crate::wire!(@position self $kind [] 0usize; $( $variant )*);
1647                &<$name as $crate::wire::Declared>::shape().ctors()[at]
1648            }
1649
1650            /// The number its constructor is written with.
1651            pub fn number(self) -> u64 {
1652                self.ctor().number
1653            }
1654
1655            /// The kind whose constructor is written with `number`, if any.
1656            pub fn of(number: u64) -> Option<$kind> {
1657                let at = <$name as $crate::wire::Declared>::shape()
1658                    .ctors()
1659                    .iter()
1660                    .position(|ctor| ctor.number == number)?;
1661                Some(Self::ALL[at])
1662            }
1663        }
1664    };
1665
1666    // A kind's position among its enum's constructors, by one match: an
1667    // enum that is its own kinds may give its constructors numbers, which
1668    // are then its discriminants, so a cast would give the number and not
1669    // the position.
1670    (@position $self:ident $kind:ident [$( $arms:tt )*] $at:expr;) => {
1671        match $self { $( $arms )* }
1672    };
1673    (@position $self:ident $kind:ident [$( $arms:tt )*] $at:expr; $variant:ident $( $rest:ident )*) => {
1674        $crate::wire!(@position $self $kind [$( $arms )* $kind::$variant => $at,] $at + 1; $( $rest )*)
1675    };
1676
1677    // A constructor with no payload.
1678    (@enum $name:ident $gens:tt [$out:ident $head:ident $catalog:ident $ty:ident $parts:ident] [$at:expr]
1679        [$($shape:tt)*] [$($write:tt)*] [$($open:tt)*] [$($value:tt)*] [$($of:tt)*]
1680        $variant:ident $( = $number:literal )?; $($rest:tt)*
1681    ) => {
1682        $crate::wire!(@enum $name $gens [$out $head $catalog $ty $parts] [$at + 1]
1683            [$($shape)* $crate::wire::Ctor {
1684                name: stringify!($variant),
1685                number: $crate::wire!(@number $at $(, $number)?),
1686                parts: $crate::wire::Parts::Empty,
1687            },]
1688            [$($write)* Self::$variant => {
1689                $head($out, $crate::wire!(@number $at $(, $number)?));
1690            }]
1691            [$($open)* number if number == $crate::wire!(@number $at $(, $number)?) => {
1692                $crate::wire::Opened::built(Self::$variant)
1693            }]
1694            [$($value)* Self::$variant => $catalog.variant(
1695                $ty, $crate::wire::position($crate::wire!(@number $at $(, $number)?)), &[],
1696            ),]
1697            [$($of)* index if u64::try_from(index).ok() == Some($at) => Self::$variant,]
1698            $($rest)*
1699        );
1700    };
1701
1702    // A constructor of parts by position: each part gets a name of its own,
1703    // one at a time, and then the constructor is declared.
1704    (@enum $name:ident $gens:tt $context:tt $at:tt $shape:tt $write:tt $open:tt $value:tt $of:tt
1705        $variant:ident ( $($part:ty),+ ) $( = $number:literal )?; $($rest:tt)*
1706    ) => {
1707        $crate::wire!(@positional [$name $gens $context $at $shape $write $open $value $of]
1708            [$variant [$($number)?]] [] [$($part),+] $($rest)*
1709        );
1710    };
1711
1712    (@positional $state:tt $variant:tt [$($named:tt)*] [$part:ty $(, $more:ty)*]
1713        $($rest:tt)*
1714    ) => {
1715        $crate::wire!(@positional $state $variant [$($named)* (part: $part)] [$($more),*]
1716            $($rest)*
1717        );
1718    };
1719
1720    (@positional
1721        [$name:ident $gens:tt [$out:ident $head:ident $catalog:ident $ty:ident $parts:ident] [$at:expr]
1722            [$($shape:tt)*] [$($write:tt)*] [$($open:tt)*] [$($value:tt)*] [$($of:tt)*]]
1723        [$variant:ident [$($number:literal)?]] [$( ($each:ident : $each_ty:ty) )+] []
1724        $($rest:tt)*
1725    ) => {
1726        $crate::wire!(@enum $name $gens [$out $head $catalog $ty $parts] [$at + 1]
1727            [$($shape)* $crate::wire::Ctor {
1728                name: stringify!($variant),
1729                number: $crate::wire!(@number $at $(, $number)?),
1730                parts: $crate::wire::Parts::Positional(&[
1731                    $( <$each_ty as $crate::wire::Shaped>::FORM, )+
1732                ]),
1733            },]
1734            [$($write)* Self::$variant($($each),+) => {
1735                $head($out, $crate::wire!(@number $at $(, $number)?));
1736                $( $parts.push($each); )+
1737            }]
1738            [$($open)* number if number == $crate::wire!(@number $at $(, $number)?) => {
1739                const {
1740                    assert!(
1741                        $crate::wire::rest_is_last(
1742                            &[$( <$each_ty as $crate::wire::Shaped>::FORM ),+],
1743                        ),
1744                        "only a message's last field may be its rest"
1745                    );
1746                }
1747                $crate::wire::Opened::parts(
1748                    |parts| -> Box<dyn ::std::any::Any> {
1749                        Box::new(Self::$variant($( parts.part::<$each_ty>() ),+))
1750                    },
1751                    &[$( <$each_ty as $crate::wire::Wire>::open ),+],
1752                )
1753            }]
1754            [$($value)* Self::$variant($($each),+) => $catalog.variant(
1755                $ty, $crate::wire::position($crate::wire!(@number $at $(, $number)?)), &[$($each),+],
1756            ),]
1757            [$($of)* index if u64::try_from(index).ok() == Some($at) => Self::$variant(
1758                $( $parts.read::<$each_ty>($catalog)? ),+
1759            ),]
1760            $($rest)*
1761        );
1762    };
1763
1764    // A constructor of named fields.
1765    (@enum $name:ident $gens:tt [$out:ident $head:ident $catalog:ident $ty:ident $parts:ident] [$at:expr]
1766        [$($shape:tt)*] [$($write:tt)*] [$($open:tt)*] [$($value:tt)*] [$($of:tt)*]
1767        $variant:ident { $( $member:ident : $member_ty:ty ),* } $( = $number:literal )?;
1768        $($rest:tt)*
1769    ) => {
1770        $crate::wire!(@enum $name $gens [$out $head $catalog $ty $parts] [$at + 1]
1771            [$($shape)* $crate::wire::Ctor {
1772                name: stringify!($variant),
1773                number: $crate::wire!(@number $at $(, $number)?),
1774                parts: $crate::wire::Parts::Named(&[$(
1775                    $crate::wire::Field {
1776                        name: stringify!($member),
1777                        form: <$member_ty as $crate::wire::Shaped>::FORM,
1778                    }
1779                ),*]),
1780            },]
1781            [$($write)* Self::$variant { $($member),* } => {
1782                $head($out, $crate::wire!(@number $at $(, $number)?));
1783                $( $parts.push($member); )*
1784            }]
1785            [$($open)* number if number == $crate::wire!(@number $at $(, $number)?) => {
1786                const {
1787                    assert!(
1788                        $crate::wire::rest_is_last(
1789                            &[$( <$member_ty as $crate::wire::Shaped>::FORM ),*],
1790                        ),
1791                        "only a message's last field may be its rest"
1792                    );
1793                }
1794                $crate::wire::Opened::parts(
1795                    |parts| -> Box<dyn ::std::any::Any> {
1796                        Box::new(Self::$variant { $( $member: parts.part::<$member_ty>(), )* })
1797                    },
1798                    &[$( <$member_ty as $crate::wire::Wire>::open ),*],
1799                )
1800            }]
1801            [$($value)* Self::$variant { $($member),* } => $catalog.variant(
1802                $ty, $crate::wire::position($crate::wire!(@number $at $(, $number)?)), &[$($member),*],
1803            ),]
1804            [$($of)* index if u64::try_from(index).ok() == Some($at) => Self::$variant {
1805                $( $member: $parts.read::<$member_ty>($catalog)?, )*
1806            },]
1807            $($rest)*
1808        );
1809    };
1810
1811    // Every constructor taken: the impls.
1812    (@enum $name:ident [$($gen:ident),*] [$out:ident $head:ident $catalog:ident $ty:ident $parts:ident] [$at:expr]
1813        [$($shape:tt)*] [$($write:tt)*] [$($open:tt)*] [$($value:tt)*] [$($of:tt)*]
1814    ) => {
1815        impl<$($gen: $crate::wire::Shaped),*> $crate::wire::Declared for $name<$($gen),*> {
1816            const SHAPE: $crate::wire::Shape = $crate::wire::Shape {
1817                name: stringify!($name),
1818                params: &[],
1819                layout: $crate::wire::Layout::Enum(&[$($shape)*]),
1820                notes: None,
1821            };
1822        }
1823
1824        impl<$($gen: $crate::wire::Shaped),*> $crate::wire::Shaped for $name<$($gen),*> {
1825            const FORM: $crate::wire::WireForm =
1826                $crate::wire::WireForm::Declared(<Self as $crate::wire::Declared>::shape);
1827
1828            fn write_at(
1829                &self,
1830                $catalog: &mut $crate::wire::ValueWriter<'_, '_>,
1831                $ty: &$crate::wire::Type,
1832            ) -> Result<(), $crate::EncodeError> {
1833                match self {
1834                    $($value)*
1835                }
1836            }
1837
1838            fn read_at(
1839                $catalog: &mut $crate::wire::ValueReader<'_, '_, '_>,
1840                $ty: &$crate::wire::Type,
1841            ) -> Result<Self, $crate::DecodeError> {
1842                $catalog.variant($ty, |$catalog, index, $parts| {
1843                    let _ = (&$catalog, &$parts);
1844                    Ok(match index {
1845                        $($of)*
1846                        _ => return Err($catalog.mismatch($ty)),
1847                    })
1848                })
1849            }
1850        }
1851
1852        impl<$($gen: $crate::wire::Wire),*> $crate::wire::Keyed for $name<$($gen),*> {
1853            fn payload<'a>(&'a self, $parts: &mut Vec<&'a dyn $crate::wire::AnyWire>) {
1854                let $out = &mut Vec::new();
1855                let $head = |_: &mut Vec<u8>, _: u64| {};
1856                let _ = (&$out, &$parts);
1857                match self {
1858                    $($write)*
1859                }
1860            }
1861
1862            fn open_payload(
1863                number: u64,
1864                at: usize,
1865            ) -> Result<$crate::wire::Opened, $crate::DecodeError> {
1866                const {
1867                    assert!(
1868                        $crate::wire::numbers_are_distinct(&[$($shape)*]),
1869                        "no two constructors may have one number"
1870                    );
1871                }
1872                Ok(match number {
1873                    $($open)*
1874                    other => {
1875                        return Err($crate::wire::unknown(
1876                            <Self as $crate::wire::Declared>::shape(),
1877                            other,
1878                            at,
1879                        ));
1880                    }
1881                })
1882            }
1883        }
1884
1885        impl<$($gen: $crate::wire::Wire),*> $crate::wire::Wire for $name<$($gen),*> {
1886            fn write_head<'a>(
1887                &'a self,
1888                $out: &mut Vec<u8>,
1889                $parts: &mut Vec<&'a dyn $crate::wire::AnyWire>,
1890            ) {
1891                let $head = $crate::primitives::write_uint;
1892                let _ = &$parts;
1893                match self {
1894                    $($write)*
1895                }
1896            }
1897
1898            fn open(
1899                reader: &mut $crate::primitives::Reader<'_>,
1900            ) -> Result<$crate::wire::Opened, $crate::DecodeError> {
1901                let at = reader.position();
1902                <Self as $crate::wire::Keyed>::open_payload(reader.uint()?, at)
1903            }
1904        }
1905    };
1906}
1907
1908/// Gives a record, an enum or a newtype defined elsewhere its
1909/// [`Shape`](crate::wire::Shape) and its [`Shaped`](crate::wire::Shaped)
1910/// mapping, from its field list: `#[derive(Flow)]` expands to it. The
1911/// type's parameters come with their positions, and any bounds its
1912/// definition puts on them in brackets after `where`; each field, constructor
1913/// part and constructor field with its Flow name, and each part with the
1914/// name its value is bound to; and a constructor with its number, which is
1915/// its position, and whether its payload is `Empty`, `Positional` or
1916/// `Named`. Fields of `PhantomData` are listed after `phantom`, and
1917/// what the declaration's text says beside its shape after `notes`.
1918///
1919/// ```
1920/// use flow_abi::wire::{Declared, Layout, Shaped, WireForm};
1921///
1922/// pub struct Pair<T> {
1923///     pub first: T,
1924///     pub rest: Vec<T>,
1925/// }
1926/// pub enum Turn {
1927///     Stop,
1928///     Move(bool),
1929///     Say { text: String },
1930/// }
1931///
1932/// flow_abi::wire_impl! {
1933///     impl Pair [T = 0] record {
1934///         first "first": T,
1935///         rest "rest": Vec<T>,
1936///     } phantom []
1937/// }
1938/// flow_abi::wire_impl! {
1939///     impl Turn [] enum {
1940///         Stop = 0 Empty {},
1941///         Move = 1 Positional { 0 (flag) "": bool },
1942///         Say = 2 Named { text (text) "text": String },
1943///     }
1944/// }
1945///
1946/// assert!(matches!(<Pair<bool> as Shaped>::FORM, WireForm::Applied(..)));
1947/// assert!(matches!(<Turn as Declared>::shape().layout, Layout::Enum(ctors) if ctors.len() == 3));
1948/// ```
1949#[macro_export]
1950macro_rules! wire_impl {
1951    (
1952        impl $name:ident [$( $gen:ident = $index:literal ),*] $( where [$( $pred:tt )*] )? record {
1953            $( $field:tt $flow:literal : $ty:ty ),* $(,)?
1954        } phantom [$( $phantom:tt ),*] $( notes $notes:expr )?
1955    ) => {
1956        impl<$( $gen: $crate::wire::Shaped ),*> $crate::wire::Declared for $name<$( $gen ),*>
1957        where $( $( $pred )* )?
1958        {
1959            const SHAPE: $crate::wire::Shape = $crate::wire::Shape {
1960                name: stringify!($name),
1961                params: &[$( stringify!($gen) ),*],
1962                layout: $crate::wire::Layout::Record(&[$(
1963                    $crate::wire::Field {
1964                        name: $flow,
1965                        form: <$ty as $crate::wire::Shaped>::FORM,
1966                    }
1967                ),*]),
1968                notes: $crate::wire_impl!(@notes $( $notes )?),
1969            };
1970        }
1971
1972        impl<$( $gen: $crate::wire::Shaped ),*> $crate::wire::Shaped for $name<$( $gen ),*>
1973        where $( $( $pred )* )?
1974        {
1975            const FORM: $crate::wire::WireForm =
1976                $crate::wire_impl!(@form $name [$( $gen = $index ),*]);
1977
1978            fn write_at(
1979                &self,
1980                out: &mut $crate::wire::ValueWriter<'_, '_>,
1981                ty: &$crate::wire::Type,
1982            ) -> Result<(), $crate::EncodeError> {
1983                out.record(ty, &[$( &self.$field ),*])
1984            }
1985
1986            fn read_at(
1987                input: &mut $crate::wire::ValueReader<'_, '_, '_>,
1988                ty: &$crate::wire::Type,
1989            ) -> Result<Self, $crate::DecodeError> {
1990                input.record(ty, |input, fields| {
1991                    let _ = (&input, &fields);
1992                    Ok(Self {
1993                        $( $field: fields.read::<$ty>(input)?, )*
1994                        $( $phantom: ::core::marker::PhantomData, )*
1995                    })
1996                })
1997            }
1998        }
1999    };
2000
2001    (
2002        impl $name:ident [$( $gen:ident = $index:literal ),*] $( where [$( $pred:tt )*] )? enum {
2003            $(
2004                $variant:ident = $number:literal $kind:ident {
2005                    $( $member:tt ($bind:ident) $member_flow:literal : $member_ty:ty ),* $(,)?
2006                }
2007            ),* $(,)?
2008        } $( notes $notes:expr )?
2009    ) => {
2010        impl<$( $gen: $crate::wire::Shaped ),*> $crate::wire::Declared for $name<$( $gen ),*>
2011        where $( $( $pred )* )?
2012        {
2013            const SHAPE: $crate::wire::Shape = $crate::wire::Shape {
2014                name: stringify!($name),
2015                params: &[$( stringify!($gen) ),*],
2016                layout: $crate::wire::Layout::Enum(&[$(
2017                    $crate::wire::Ctor {
2018                        name: stringify!($variant),
2019                        number: $number,
2020                        parts: $crate::wire_impl!(@parts $kind [$( $member_flow : $member_ty ),*]),
2021                    }
2022                ),*]),
2023                notes: $crate::wire_impl!(@notes $( $notes )?),
2024            };
2025        }
2026
2027        impl<$( $gen: $crate::wire::Shaped ),*> $crate::wire::Shaped for $name<$( $gen ),*>
2028        where $( $( $pred )* )?
2029        {
2030            const FORM: $crate::wire::WireForm =
2031                $crate::wire_impl!(@form $name [$( $gen = $index ),*]);
2032
2033            fn write_at(
2034                &self,
2035                out: &mut $crate::wire::ValueWriter<'_, '_>,
2036                ty: &$crate::wire::Type,
2037            ) -> Result<(), $crate::EncodeError> {
2038                match self {
2039                    $( Self::$variant { $( $member: $bind ),* } => out.variant(
2040                        ty,
2041                        $crate::wire::position($number),
2042                        &[$( $bind ),*],
2043                    ), )*
2044                }
2045            }
2046
2047            fn read_at(
2048                input: &mut $crate::wire::ValueReader<'_, '_, '_>,
2049                ty: &$crate::wire::Type,
2050            ) -> Result<Self, $crate::DecodeError> {
2051                input.variant(ty, |input, index, fields| {
2052                    let _ = (&input, &fields);
2053                    Ok(match index {
2054                        $( $number => Self::$variant {
2055                            $( $member: fields.read::<$member_ty>(input)?, )*
2056                        }, )*
2057                        _ => return Err(input.mismatch(ty)),
2058                    })
2059                })
2060            }
2061        }
2062    };
2063
2064    (
2065        impl $name:ident [$( $gen:ident = $index:literal ),*] $( where [$( $pred:tt )*] )? newtype {
2066            $field:tt : $ty:ty
2067        } phantom [$( $phantom:tt ),*] $( notes $notes:expr )?
2068    ) => {
2069        impl<$( $gen: $crate::wire::Shaped ),*> $crate::wire::Declared for $name<$( $gen ),*>
2070        where $( $( $pred )* )?
2071        {
2072            const SHAPE: $crate::wire::Shape = $crate::wire::Shape {
2073                name: stringify!($name),
2074                params: &[$( stringify!($gen) ),*],
2075                layout: $crate::wire::Layout::Newtype(<$ty as $crate::wire::Shaped>::FORM),
2076                notes: $crate::wire_impl!(@notes $( $notes )?),
2077            };
2078        }
2079
2080        impl<$( $gen: $crate::wire::Shaped ),*> $crate::wire::Shaped for $name<$( $gen ),*>
2081        where $( $( $pred )* )?
2082        {
2083            const FORM: $crate::wire::WireForm =
2084                $crate::wire_impl!(@form $name [$( $gen = $index ),*]);
2085
2086            fn write_at(
2087                &self,
2088                out: &mut $crate::wire::ValueWriter<'_, '_>,
2089                ty: &$crate::wire::Type,
2090            ) -> Result<(), $crate::EncodeError> {
2091                out.newtype(ty, &self.$field)
2092            }
2093
2094            fn read_at(
2095                input: &mut $crate::wire::ValueReader<'_, '_, '_>,
2096                ty: &$crate::wire::Type,
2097            ) -> Result<Self, $crate::DecodeError> {
2098                Ok(Self {
2099                    $field: input.newtype::<$ty>(ty)?,
2100                    $( $phantom: ::core::marker::PhantomData, )*
2101                })
2102            }
2103        }
2104    };
2105
2106    (@notes) => { None };
2107    (@notes $notes:expr) => { Some(&$notes) };
2108
2109    (@form $name:ident []) => {
2110        $crate::wire::WireForm::Declared(<Self as $crate::wire::Declared>::shape)
2111    };
2112    (@form $name:ident [$( $gen:ident = $index:literal ),+]) => {
2113        $crate::wire::WireForm::Applied(
2114            <$name<$( $crate::wire::Param<$index> ),+> as $crate::wire::Declared>::shape,
2115            &[$( $crate::wire::form_of::<$gen> ),+],
2116        )
2117    };
2118
2119    (@parts Empty []) => { $crate::wire::Parts::Empty };
2120    (@parts Positional [$( $flow:literal : $ty:ty ),+]) => {
2121        $crate::wire::Parts::Positional(&[$( <$ty as $crate::wire::Shaped>::FORM ),+])
2122    };
2123    (@parts Named [$( $flow:literal : $ty:ty ),*]) => {
2124        $crate::wire::Parts::Named(&[$(
2125            $crate::wire::Field {
2126                name: $flow,
2127                form: <$ty as $crate::wire::Shaped>::FORM,
2128            }
2129        ),*])
2130    };
2131}