1use 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#[derive(Clone, Copy, Debug)]
69pub enum WireForm {
70 Int,
72 Decimal,
74 Bool,
76 Text,
78 Bytes,
80 Duration,
82 Instant,
84 Unit,
86 Never,
88 RunId,
90 CallRef,
92 Number,
94 Rest,
96 Option(fn() -> WireForm),
98 List(fn() -> WireForm),
100 Set(fn() -> WireForm),
102 Dict(fn() -> WireForm, fn() -> WireForm),
104 Tuple(&'static [fn() -> WireForm]),
106 Declared(fn() -> &'static Shape),
108 Param(usize),
110 Applied(fn() -> &'static Shape, &'static [fn() -> WireForm]),
112 Std {
115 module: &'static str,
117 name: &'static str,
119 args: &'static [fn() -> WireForm],
121 },
122}
123
124#[derive(Debug)]
126pub struct Shape {
127 pub name: &'static str,
129 pub params: &'static [&'static str],
131 pub layout: Layout,
133 pub notes: Option<&'static Notes>,
135}
136
137#[derive(Debug)]
140pub struct Notes {
141 pub module: &'static str,
143 pub file: &'static str,
145 pub line: u32,
147 pub docs: &'static str,
149 pub members: &'static [Note],
152}
153
154#[derive(Debug)]
156pub struct Note {
157 pub docs: &'static str,
159 pub public: bool,
161 pub fields: &'static [Note],
163}
164
165#[derive(Debug)]
167pub enum Layout {
168 Record(&'static [Field]),
170 Enum(&'static [Ctor]),
172 Newtype(WireForm),
174 Host,
176}
177
178#[derive(Debug)]
180pub struct Field {
181 pub name: &'static str,
183 pub form: WireForm,
185}
186
187#[derive(Debug)]
189pub struct Ctor {
190 pub name: &'static str,
192 pub number: u64,
194 pub parts: Parts,
196}
197
198#[derive(Debug)]
200pub enum Parts {
201 Empty,
203 Positional(&'static [WireForm]),
205 Named(&'static [Field]),
207}
208
209pub trait Shaped: Sized + 'static {
213 const FORM: WireForm;
215
216 fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError>;
224
225 fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError>;
232}
233
234pub trait Part {
237 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
251pub trait Wire: Shaped {
254 fn write_head<'a>(&'a self, out: &mut Vec<u8>, parts: &mut Vec<&'a dyn AnyWire>);
257
258 fn write(&self, out: &mut Vec<u8>) {
262 write_parts(out, vec![self]);
263 }
264
265 fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError>;
272
273 fn read(reader: &mut Reader<'_>) -> Result<Self, DecodeError> {
279 let opened = Self::open(reader)?;
280 built(reader, opened)
281 }
282
283 fn bytes(&self) -> Vec<u8> {
285 let mut out = Vec::new();
286 self.write(&mut out);
287 out
288 }
289
290 fn decode(bytes: &[u8]) -> Result<Self, DecodeError> {
297 whole(bytes, Self::open)
298 }
299}
300
301pub trait AnyWire {
303 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
313fn 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
324fn 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
336fn 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
355pub 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
376pub type Open = fn(&mut Reader<'_>) -> Result<Opened, DecodeError>;
378
379pub type Join = fn(&mut Joined) -> Box<dyn Any>;
381
382#[derive(Debug)]
384pub struct Opened(Begun<Pending, Join, Box<dyn Any>>);
385
386#[derive(Debug)]
389enum Pending {
390 Each(Vec<Open>),
391 Items(Open, usize),
392}
393
394impl Opened {
395 pub fn built<T: 'static>(value: T) -> Self {
397 Self(Begun::Done(Box::new(value)))
398 }
399
400 #[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 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
423struct 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#[derive(Debug)]
468pub struct Joined(std::vec::IntoIter<Box<dyn Any>>);
469
470impl Joined {
471 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 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
495pub trait Declared: Shaped {
498 const SHAPE: Shape;
500
501 fn shape() -> &'static Shape {
503 &Self::SHAPE
504 }
505}
506
507pub trait Keyed: Declared + Wire {
513 fn payload<'a>(&'a self, parts: &mut Vec<&'a dyn AnyWire>);
516
517 fn open_payload(number: u64, at: usize) -> Result<Opened, DecodeError>;
524
525 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 fn decode_payload(number: u64, bytes: &[u8]) -> Result<Self, DecodeError> {
542 whole(bytes, |_| Self::open_payload(number, 0))
543 }
544}
545
546pub fn form_of<T: Shaped>() -> WireForm {
548 T::FORM
549}
550
551pub 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
564pub 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
581pub 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
594pub const MESSAGE: Limits = Limits {
596 text_bytes: usize::MAX,
597 ..Limits::LANGUAGE
598};
599
600pub fn position(number: u64) -> usize {
608 usize::try_from(number).expect("a constructor number fits a usize")
609}
610
611impl 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
703impl 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#[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#[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
774impl<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
806impl 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
832macro_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
858impl 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
874impl 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
893pub 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
902pub 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
928fn 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#[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
1046impl<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
1148type Ids = HashMap<*const Shape, DeclId>;
1153
1154impl Shape {
1155 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 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 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 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 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
1280pub 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
1304fn 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
1334fn 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
1346fn 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
1385fn 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#[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 (@kind $name:ident $gens:tt [$( $(#[$variant_meta:meta])* $variant:ident )*]) => {};
1610
1611 (@kind $name:ident [] [$( $(#[$variant_meta:meta])* $variant:ident )*] enum Self;) => {
1613 $crate::wire!(@kinds $name $name [$( $variant )*]);
1614 };
1615
1616 (@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 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 pub const ALL: &'static [$kind] = &[$( $kind::$variant ),*];
1643
1644 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 pub fn number(self) -> u64 {
1652 self.ctor().number
1653 }
1654
1655 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 (@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 (@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 (@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 (@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 (@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#[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}