Skip to main content

flow_abi/
metadata.rs

1//! Type descriptions (`abi.md`, *Type descriptions*): a Tool's `TypeSpec`,
2//! a generic call's `CallTypes` and a call's `ResultType`, and the
3//! `--contract` file that lists a program's Tools with theirs.
4//!
5//! Their bytes are [`crate::description`]'s types, which own the layout.
6//! Writing turns a catalog's types into those values, numbering the
7//! templates a description reaches in first-reach order, a depth-first walk
8//! that visits a template's members the first time it reaches it, so every
9//! type has one description and so one encoding. Reading turns the values
10//! back into types and refuses any other description: one out of that
11//! order, holding a template nothing reaches, naming a template or owner it
12//! does not hold, or repeating a name in one scope. It checks recursive
13//! substitutions and newtype bases before a catalog is built, and the
14//! catalog's crossing judgments own everything after that.
15//!
16//! A [`TypeSpec`] keeps its catalog, its signature and its bytes. Its
17//! comparable form, what binding compares ([`comparable`]), is the same
18//! description written again with every doc comment left out and every
19//! version empty.
20
21use std::collections::{HashMap, HashSet};
22use std::fmt::Write as _;
23use std::sync::Arc;
24
25use flow_types::{Constructor, EnumShape, Payload, RecordShape};
26
27use crate::build::{Begun, Frame, Walk, build};
28use crate::bytes::Reader;
29use crate::description::{self as described, Identity, Owner, Program, Template, Term};
30use crate::version::{DATA_VERSION, DataVersion, Versioned};
31use crate::wire::{AnyWire, Opened, Rest, Shaped, ValueReader, ValueWriter, Wire, WireForm};
32use crate::{
33    BINDING, Catalog, DecodeError, EncodeError, EncodeErrorKind, Place, REPLY, Signature, ToolDecl,
34    crossable, decodable, schema,
35};
36use flow_types::Versions;
37use flow_types::{Body, Decl, DeclId, Fold, MemberDoc, Nested, Type};
38use flow_value::Int;
39
40pub(crate) fn fail(problem: impl Into<String>) -> DecodeError {
41    DecodeError {
42        path: crate::Place::default(),
43        problem: problem.into(),
44        kind: crate::DecodeErrorKind::Mismatch,
45    }
46}
47
48fn unwritable(problem: &str) -> EncodeError {
49    EncodeError::new(&crate::Place::default(), EncodeErrorKind::Invalid, problem)
50}
51
52/// Whether a description is written to be read or to be compared.
53#[derive(Clone, Copy, PartialEq, Eq, Debug)]
54enum Form {
55    /// Docs and versions as they are.
56    Full,
57    /// Every doc and every library's version `None` (`abi.md`, *Identity
58    /// and signatures*).
59    Comparable,
60}
61
62impl Form {
63    fn identity(self, identity: Identity) -> Identity {
64        match self {
65            Form::Full => identity,
66            Form::Comparable => Identity {
67                library: identity.library.map(|library| described::Library {
68                    version: None,
69                    ..library
70                }),
71                ..identity
72            },
73        }
74    }
75
76    fn doc(self, doc: Option<&String>) -> Option<String> {
77        match self {
78            Form::Full => doc.cloned(),
79            Form::Comparable => None,
80        }
81    }
82}
83
84/// The terms of a description being made types, in one scope.
85struct Typing<'r> {
86    reading: &'r Reading,
87    scope: Scope,
88    path: Place,
89}
90
91/// The parts of a term still to be made types, in the order they are
92/// written.
93type Terms<'t> = std::vec::IntoIter<&'t Term>;
94
95/// What a term's parts make, once each is a type.
96enum Join {
97    List,
98    Set,
99    Option,
100    Task,
101    Dict,
102    Tuple,
103    Function,
104    Named(DeclId),
105}
106
107impl Typing<'_> {
108    /// The type `term` is when it has no parts, else its parts to make
109    /// types, once `term` itself is checked.
110    fn begin<'t>(&self, term: &'t Term) -> Result<Begun<Terms<'t>, Join, Type>, DecodeError> {
111        let open = |join, parts: Vec<&'t Term>| {
112            let room = parts.len();
113            Frame::open(join, parts.into_iter(), room, 0)
114        };
115        Ok(match term {
116            Term::Int => Begun::Done(Type::Int),
117            Term::Decimal => Begun::Done(Type::Decimal),
118            Term::Bool => Begun::Done(Type::Bool),
119            Term::Text => Begun::Done(Type::Text),
120            Term::Bytes => Begun::Done(Type::Bytes),
121            Term::Duration => Begun::Done(Type::Duration),
122            Term::Instant => Begun::Done(Type::Instant),
123            Term::Unit => Begun::Done(Type::Unit),
124            Term::Never => Begun::Done(Type::Never),
125            Term::JsonValue => Begun::Done(Type::Json),
126            Term::Param { owner, index } => {
127                Begun::Done(self.reading.param(owner, index, self.scope)?)
128            }
129            Term::List(item) => open(Join::List, vec![&**item]),
130            Term::Set(item) => open(Join::Set, vec![&**item]),
131            Term::Option(item) => open(Join::Option, vec![&**item]),
132            Term::Task(item) => open(Join::Task, vec![&**item]),
133            Term::Dict(key, value) => open(Join::Dict, vec![&**key, &**value]),
134            Term::Tuple(parts) => {
135                if parts.len() < 2 {
136                    return Err(fail("a tuple term holds fewer than two terms"));
137                }
138                open(Join::Tuple, parts.iter().collect())
139            }
140            Term::Function { params, result } => {
141                open(Join::Function, params.iter().chain([&**result]).collect())
142            }
143            Term::Named { declaration, args } => {
144                let at = read_place(declaration, "a declaration's place")?;
145                open(Join::Named(DeclId(at)), args.iter().collect())
146            }
147        })
148    }
149}
150
151impl<'t> Walk<Terms<'t>, Join, Type> for Typing<'_> {
152    type Error = DecodeError;
153
154    fn path(&mut self) -> &mut Place {
155        &mut self.path
156    }
157
158    fn next(
159        &mut self,
160        frame: &mut Frame<Terms<'t>, Join, Type>,
161    ) -> Result<Option<Begun<Terms<'t>, Join, Type>>, DecodeError> {
162        frame.parts.next().map(|term| self.begin(term)).transpose()
163    }
164
165    fn steps(_: &Frame<Terms<'t>, Join, Type>) -> usize {
166        0
167    }
168
169    fn finish(&mut self, frame: Frame<Terms<'t>, Join, Type>) -> Result<Type, DecodeError> {
170        let mut parts = frame.values;
171        let mut last = || parts.pop().expect("a term's parts, each a type");
172        Ok(match frame.make {
173            Join::List => Type::list(last()),
174            Join::Set => Type::set(last()),
175            Join::Option => Type::option(last()),
176            Join::Task => Type::Task(Box::new(last())),
177            Join::Dict => {
178                let value = last();
179                Type::dict(last(), value)
180            }
181            Join::Tuple => Type::Tuple(parts),
182            Join::Function => {
183                let result = Box::new(last());
184                Type::Function {
185                    params: parts,
186                    result,
187                }
188            }
189            Join::Named(id) => Type::Named(id, parts),
190        })
191    }
192}
193
194/// Who owns the type parameters a term may name.
195#[derive(Clone, Copy, PartialEq, Eq, Debug)]
196enum Scope {
197    /// A `TypeSpec`'s roots: the Tool's, this many.
198    Tool(usize),
199    /// A `CallTypes`'s roots: none.
200    Concrete,
201    /// The members of the template at this index, with this many.
202    Template(usize, usize),
203}
204
205/// The members of `decl` whose terms the walk visits, in declaration order.
206fn members(decl: &Decl) -> Vec<&Type> {
207    match &decl.body {
208        Body::Record(_, fields) => fields.iter().collect(),
209        Body::Enum(_, constructors) => constructors.iter().flatten().collect(),
210        Body::Newtype(base) => vec![base],
211        Body::Host | Body::NonData => Vec::new(),
212    }
213}
214
215/// Pushes the terms the walk visits inside `ty` itself, before any
216/// template: the last pushed is visited first.
217fn push_parts<'a>(stack: &mut Vec<&'a Type>, ty: &'a Type) {
218    match ty {
219        Type::List(item) | Type::Set(item) | Type::Option(item) | Type::Task(item) => {
220            stack.push(item);
221        }
222        Type::Dict(key, value) => {
223            stack.push(value);
224            stack.push(key);
225        }
226        Type::Tuple(parts) => stack.extend(parts.iter().rev()),
227        Type::Function { params, result } => {
228            stack.push(result);
229            stack.extend(params.iter().rev());
230        }
231        Type::Named(_, args) => stack.extend(args.iter().rev()),
232        Type::Int
233        | Type::Decimal
234        | Type::Bool
235        | Type::Text
236        | Type::Bytes
237        | Type::Duration
238        | Type::Instant
239        | Type::Unit
240        | Type::Never
241        | Type::Json
242        | Type::Param(_)
243        | Type::NotData => {}
244    }
245}
246
247/// Every declaration `roots` reach in `catalog`, in first-reach order
248/// (`abi.md`, *First-reach order*).
249fn first_reach<'a>(
250    catalog: &'a Catalog,
251    roots: impl IntoIterator<Item = &'a Type>,
252) -> Result<Vec<DeclId>, EncodeError> {
253    let count = catalog.decls().len();
254    let mut stack: Vec<&Type> = roots.into_iter().collect();
255    stack.reverse();
256    let mut reached = HashSet::new();
257    let mut order = Vec::new();
258    while let Some(ty) = stack.pop() {
259        push_parts(&mut stack, ty);
260        if let Type::Named(id, args) = ty {
261            if crate::bytes::index(id.0) >= count {
262                return Err(unwritable("a type names a declaration the catalog lacks"));
263            }
264            let decl = catalog.decl(*id);
265            if args.len() != decl.params.len() {
266                return Err(unwritable("a declaration's argument count differs"));
267            }
268            if reached.insert(*id) {
269                order.push(*id);
270                stack.extend(members(decl).into_iter().rev());
271            }
272        }
273    }
274    Ok(order)
275}
276
277// === Writing =================================================================
278
279/// Describes the types of one catalog, each declaration by its place in
280/// the description.
281struct Writer<'c> {
282    catalog: &'c Catalog,
283    form: Form,
284    index: HashMap<DeclId, usize>,
285}
286
287/// A place in a description as the `Int` it is written as.
288fn place(at: usize) -> Int {
289    Int::from(i64::try_from(at).expect("a place fits 63 bits"))
290}
291
292impl<'c> Writer<'c> {
293    fn new(catalog: &'c Catalog, form: Form, order: &[DeclId]) -> Self {
294        Writer {
295            catalog,
296            form,
297            index: order.iter().enumerate().map(|(at, id)| (*id, at)).collect(),
298        }
299    }
300
301    fn entries(
302        &self,
303        entries: &[(String, Type)],
304        scope: Scope,
305    ) -> Result<Vec<(String, Term)>, EncodeError> {
306        entries
307            .iter()
308            .map(|(name, ty)| Ok((name.clone(), self.term(ty, scope)?)))
309            .collect()
310    }
311
312    fn terms(&self, parts: &[Type], scope: Scope) -> Result<Vec<Term>, EncodeError> {
313        parts.iter().map(|part| self.term(part, scope)).collect()
314    }
315
316    /// The term of `ty`, or why the first part of it in pre-order that has
317    /// none has none.
318    fn term(&self, ty: &Type, scope: Scope) -> Result<Term, EncodeError> {
319        ty.fold(&mut Terming {
320            writer: self,
321            scope,
322        })
323    }
324
325    fn templates(&self, order: &[DeclId]) -> Result<Vec<Template>, EncodeError> {
326        order
327            .iter()
328            .enumerate()
329            .map(|(at, id)| self.template(at, *id))
330            .collect()
331    }
332
333    fn template(&self, at: usize, id: DeclId) -> Result<Template, EncodeError> {
334        let decl = self.catalog.decl(id);
335        let scope = Scope::Template(at, decl.params.len());
336        let member = |at: usize| decl.members.get(at);
337        let field = |name: &str, ty: &Type, doc: Option<&String>| {
338            Ok(described::Field {
339                name: name.to_owned(),
340                ty: self.term(ty, scope)?,
341                doc: self.form.doc(doc),
342            })
343        };
344        let body = match &decl.body {
345            Body::Record(shape, fields) => described::Body::Record(
346                shape
347                    .fields()
348                    .zip(fields)
349                    .enumerate()
350                    .map(|(at, (name, ty))| {
351                        field(name, ty, member(at).and_then(|m| m.doc.as_ref()))
352                    })
353                    .collect::<Result<_, EncodeError>>()?,
354            ),
355            Body::Enum(shape, constructors) => described::Body::Enum(
356                constructors
357                    .iter()
358                    .enumerate()
359                    .map(|(at, parts)| {
360                        let ctor = shape.constructor(at).expect(
361                            "a catalog's enum has one payload per constructor of its shape",
362                        );
363                        let payload = match ctor.payload() {
364                            Payload::None => described::Payload::Empty,
365                            Payload::Positional(_) => {
366                                described::Payload::Positional(self.terms(parts, scope)?)
367                            }
368                            Payload::Named(names) => described::Payload::Named(
369                                names
370                                    .iter()
371                                    .zip(parts)
372                                    .enumerate()
373                                    .map(|(at_field, (name, ty))| {
374                                        let doc = member(at)
375                                            .and_then(|m| m.fields.get(at_field))
376                                            .and_then(Option::as_ref);
377                                        field(name, ty, doc)
378                                    })
379                                    .collect::<Result<_, EncodeError>>()?,
380                            ),
381                        };
382                        Ok(described::Constructor {
383                            name: ctor.name().to_owned(),
384                            doc: self.form.doc(member(at).and_then(|m| m.doc.as_ref())),
385                            payload,
386                        })
387                    })
388                    .collect::<Result<_, EncodeError>>()?,
389            ),
390            Body::Newtype(base) => described::Body::Newtype(self.term(base, scope)?),
391            Body::Host => described::Body::Host,
392            Body::NonData => described::Body::Nondata,
393        };
394        Ok(Template {
395            name: decl.identity.name.clone(),
396            identity: self.form.identity(Identity::of(&decl.identity)),
397            lexical_ordinal: Int::from(i64::from(decl.lexical_ordinal)),
398            generic: decl.params.clone(),
399            opaque: decl.opaque,
400            doc: self.form.doc(decl.doc.as_ref()),
401            body,
402        })
403    }
404}
405
406/// [`Writer::term`] as a fold over the type.
407struct Terming<'w, 'c> {
408    writer: &'w Writer<'c>,
409    scope: Scope,
410}
411
412impl Fold<Type> for Terming<'_, '_> {
413    type Made = Result<Term, EncodeError>;
414
415    fn open(&mut self, _: &Type) -> Option<Self::Made> {
416        None
417    }
418
419    fn join(
420        &mut self,
421        ty: &Type,
422        mut part: impl FnMut(&mut Self, &Type) -> Self::Made,
423    ) -> Self::Made {
424        let (writer, scope) = (self.writer, self.scope);
425        let mut term = |ty: &Type| part(self, ty);
426        let mut terms = |parts: &[Type]| parts.iter().map(&mut term).collect::<Result<Vec<_>, _>>();
427        Ok(match ty {
428            Type::Int => Term::Int,
429            Type::Decimal => Term::Decimal,
430            Type::Bool => Term::Bool,
431            Type::Text => Term::Text,
432            Type::Bytes => Term::Bytes,
433            Type::Duration => Term::Duration,
434            Type::Instant => Term::Instant,
435            Type::Unit => Term::Unit,
436            Type::Never => Term::Never,
437            Type::Json => Term::JsonValue,
438            Type::List(item) => Term::List(Box::new(term(item)?)),
439            Type::Set(item) => Term::Set(Box::new(term(item)?)),
440            Type::Option(item) => Term::Option(Box::new(term(item)?)),
441            Type::Task(item) => Term::Task(Box::new(term(item)?)),
442            Type::Dict(key, value) => {
443                let key = Box::new(term(key)?);
444                Term::Dict(key, Box::new(term(value)?))
445            }
446            Type::Tuple(parts) if parts.len() >= 2 => Term::Tuple(terms(parts)?),
447            Type::Function { params, result } => {
448                let params = terms(params)?;
449                Term::Function {
450                    params,
451                    result: Box::new(term(result)?),
452                }
453            }
454            Type::Named(id, args) => Term::Named {
455                declaration: place(
456                    *writer
457                        .index
458                        .get(id)
459                        .expect("the walk indexes every declaration a type it writes names"),
460                ),
461                args: terms(args)?,
462            },
463            Type::Param(index) => {
464                let at = crate::bytes::index(*index);
465                let owner = match scope {
466                    Scope::Tool(arity) if at < arity => Owner::Tool,
467                    Scope::Template(owner, arity) if at < arity => Owner::Declaration(place(owner)),
468                    Scope::Tool(_) | Scope::Template(..) => {
469                        return Err(unwritable("a type parameter's index exceeds its owner's"));
470                    }
471                    Scope::Concrete => return Err(unwritable("a concrete type names a parameter")),
472                };
473                Term::Param {
474                    owner,
475                    index: Int::from(i64::from(*index)),
476                }
477            }
478            Type::Tuple(_) | Type::NotData => {
479                return Err(unwritable("a type that has no description"));
480            }
481        })
482    }
483}
484
485/// Writes a `TypeSpec` of `signature` in `catalog`.
486fn write_spec(
487    catalog: &Catalog,
488    signature: &Signature,
489    form: Form,
490) -> Result<Vec<u8>, EncodeError> {
491    let order = first_reach(catalog, signature_types(signature))?;
492    let writer = Writer::new(catalog, form, &order);
493    let scope = Scope::Tool(signature.generic.len());
494    Ok(described::TypeSpec {
495        generic: signature.generic.clone(),
496        params: writer.entries(&signature.params, scope)?,
497        result: writer.term(&signature.result, scope)?,
498        declarations: writer.templates(&order)?,
499    }
500    .bytes())
501}
502
503fn signature_types(signature: &Signature) -> impl Iterator<Item = &Type> + Clone {
504    signature
505        .params
506        .iter()
507        .map(|(_, ty)| ty)
508        .chain([&signature.result])
509}
510
511// === Reading =================================================================
512
513/// The roots and templates one description holds, turned into types but
514/// not yet checked against each other.
515struct Read {
516    generic: Vec<String>,
517    bindings: Vec<(String, Type)>,
518    params: Vec<(String, Type)>,
519    result: Type,
520    decls: Vec<Decl>,
521}
522
523impl Read {
524    fn signature(&self) -> Signature {
525        Signature {
526            generic: self.generic.clone(),
527            params: self.params.clone(),
528            result: self.result.clone(),
529        }
530    }
531
532    /// A `TypeSpec`'s roots and templates.
533    fn spec(spec: described::TypeSpec) -> Result<Read, DecodeError> {
534        unique(spec.generic.iter().map(String::as_str))?;
535        let scope = Scope::Tool(spec.generic.len());
536        let mut reading = Reading::default();
537        let params = reading.entries(spec.params, scope)?;
538        let result = reading.ty(&spec.result, scope)?;
539        Ok(Read {
540            generic: spec.generic,
541            bindings: Vec::new(),
542            params,
543            result,
544            decls: reading.decls(spec.declarations)?,
545        })
546    }
547
548    /// A `TypeSpec` in the `--contract` file, which has no templates of its
549    /// own.
550    fn listed(spec: described::TypeSpec) -> Result<Read, DecodeError> {
551        let read = Read::spec(spec)?;
552        if read.decls.is_empty() {
553            Ok(read)
554        } else {
555            Err(fail(
556                "a Tool in the contract file holds templates of its own",
557            ))
558        }
559    }
560
561    /// A `CallTypes`'s roots and templates.
562    fn call(types: described::CallTypes) -> Result<Read, DecodeError> {
563        let mut reading = Reading::default();
564        let bindings = reading.entries(types.bindings, Scope::Concrete)?;
565        let params = reading.entries(types.params, Scope::Concrete)?;
566        let result = reading.ty(&types.result, Scope::Concrete)?;
567        Ok(Read {
568            generic: Vec::new(),
569            bindings,
570            params,
571            result,
572            decls: reading.decls(types.declarations)?,
573        })
574    }
575}
576
577fn unique<'a>(names: impl Iterator<Item = &'a str>) -> Result<(), DecodeError> {
578    let mut seen = HashSet::new();
579    let mut names = names;
580    match names.find(|name| !seen.insert(*name)) {
581        Some(name) => Err(fail(format!(
582            "the name {name:?} appears twice in one scope"
583        ))),
584        None => Ok(()),
585    }
586}
587
588/// A non-negative `Int` that fits 32 bits, as a place or an ordinal.
589fn read_place(value: &Int, what: &str) -> Result<u32, DecodeError> {
590    u32::try_from(value.as_bigint())
591        .map_err(|_| fail(format!("{what} is {value}, which is no place")))
592}
593
594/// A record's or named payload's field names, types and doc comments.
595type Fields = (Vec<String>, Vec<Type>, Vec<Option<String>>);
596
597/// Turns a description's terms and templates into types and declarations,
598/// in the order their bytes are written, refusing what the bytes alone do
599/// not: a tuple of fewer than two parts, a place that is no place, a
600/// parameter its scope does not own, and a name twice in one scope.
601#[derive(Default)]
602struct Reading {
603    /// How many templates the description holds, once they are reached,
604    /// which judges a `Declaration` owner; `None` for the roots before them.
605    templates: Option<usize>,
606}
607
608impl Reading {
609    fn entries(
610        &self,
611        entries: Vec<(String, Term)>,
612        scope: Scope,
613    ) -> Result<Vec<(String, Type)>, DecodeError> {
614        let entries = entries
615            .into_iter()
616            .map(|(name, term)| Ok((name, self.ty(&term, scope)?)))
617            .collect::<Result<Vec<_>, DecodeError>>()?;
618        unique(entries.iter().map(|(name, _)| name.as_str()))?;
619        Ok(entries)
620    }
621
622    fn types(&self, terms: &[Term], scope: Scope) -> Result<Vec<Type>, DecodeError> {
623        terms.iter().map(|term| self.ty(term, scope)).collect()
624    }
625
626    /// The type `term` is, built by the walk every decoder shares
627    /// ([`crate::build`]): a term nests as deeply as its bytes do. Each term is
628    /// checked when it is begun, before its parts, and its parts in the order
629    /// they are written.
630    fn ty(&self, term: &Term, scope: Scope) -> Result<Type, DecodeError> {
631        let mut typing = Typing {
632            reading: self,
633            scope,
634            path: Place::default(),
635        };
636        let root = typing.begin(term)?;
637        build(&mut typing, root)
638    }
639
640    fn param(&self, owner: &Owner, index: &Int, scope: Scope) -> Result<Type, DecodeError> {
641        let owner = match owner {
642            Owner::Tool => None,
643            Owner::Declaration(owner) => Some(crate::bytes::index(read_place(
644                owner,
645                "a declaration owner",
646            )?)),
647        };
648        let index = read_place(index, "a type parameter's index")?;
649        let arity = match (scope, owner) {
650            (Scope::Tool(arity), None) => arity,
651            (Scope::Template(own, arity), Some(owner)) if owner == own => arity,
652            (_, Some(owner)) if self.templates.is_some_and(|count| owner >= count) => {
653                return Err(fail("a type parameter's owner is an unresolved reference"));
654            }
655            (Scope::Concrete, _) => return Err(fail("a concrete root names a type parameter")),
656            (Scope::Tool(_) | Scope::Template(..), _) => {
657                return Err(fail("a type parameter has the wrong owner"));
658            }
659        };
660        if crate::bytes::index(index) >= arity {
661            return Err(fail("a type parameter's index exceeds its owner's"));
662        }
663        Ok(Type::Param(index))
664    }
665
666    fn fields(&self, fields: Vec<described::Field>, scope: Scope) -> Result<Fields, DecodeError> {
667        let (mut names, mut types, mut docs) = (Vec::new(), Vec::new(), Vec::new());
668        for field in fields {
669            types.push(self.ty(&field.ty, scope)?);
670            names.push(field.name);
671            docs.push(field.doc);
672        }
673        unique(names.iter().map(String::as_str))?;
674        Ok((names, types, docs))
675    }
676
677    fn decls(&mut self, templates: Vec<Template>) -> Result<Vec<Decl>, DecodeError> {
678        self.templates = Some(templates.len());
679        templates
680            .into_iter()
681            .enumerate()
682            .map(|(at, template)| self.decl(at, template))
683            .collect()
684    }
685
686    fn decl(&self, at: usize, template: Template) -> Result<Decl, DecodeError> {
687        let Template {
688            name,
689            identity,
690            lexical_ordinal,
691            generic: params,
692            opaque,
693            doc,
694            body,
695        } = template;
696        if identity.name != name {
697            return Err(fail("a template's name differs from its identity's"));
698        }
699        let lexical_ordinal = read_place(&lexical_ordinal, "a lexical ordinal")?;
700        if lexical_ordinal == 0 {
701            return Err(fail("a lexical ordinal must be positive"));
702        }
703        unique(params.iter().map(String::as_str))?;
704        let scope = Scope::Template(at, params.len());
705        let mut members = Vec::new();
706        let body = match body {
707            described::Body::Record(fields) => {
708                let (names, types, docs) = self.fields(fields, scope)?;
709                members = docs
710                    .into_iter()
711                    .map(|doc| MemberDoc {
712                        doc,
713                        fields: Vec::new(),
714                    })
715                    .collect();
716                Body::Record(
717                    RecordShape::new(&name, names.iter().map(String::as_str)),
718                    types,
719                )
720            }
721            described::Body::Enum(ctors) => {
722                let mut constructors = Vec::new();
723                let mut payloads = Vec::new();
724                for ctor in ctors {
725                    let (payload, parts, fields) = match ctor.payload {
726                        described::Payload::Empty => (Payload::None, Vec::new(), Vec::new()),
727                        described::Payload::Positional(terms) => {
728                            let parts = self.types(&terms, scope)?;
729                            (Payload::Positional(parts.len()), parts, Vec::new())
730                        }
731                        described::Payload::Named(fields) => {
732                            let (names, types, docs) = self.fields(fields, scope)?;
733                            (
734                                Payload::Named(names.into_iter().map(Arc::from).collect()),
735                                types,
736                                docs,
737                            )
738                        }
739                    };
740                    constructors.push(Constructor::new(&ctor.name, payload));
741                    payloads.push(parts);
742                    members.push(MemberDoc {
743                        doc: ctor.doc,
744                        fields,
745                    });
746                }
747                unique(constructors.iter().map(Constructor::name))?;
748                Body::Enum(EnumShape::new(&name, constructors), payloads)
749            }
750            described::Body::Newtype(base) => Body::Newtype(self.ty(&base, scope)?),
751            described::Body::Host => Body::Host,
752            described::Body::Nondata => Body::NonData,
753        };
754        Ok(Decl {
755            identity: identity
756                .identity()
757                .map_err(|error| fail(error.to_string()))?,
758            lexical_ordinal,
759            params,
760            opaque,
761            doc,
762            members,
763            body,
764        })
765    }
766}
767
768/// Checks `decls` and the `roots` that reach them: every reference
769/// resolves, the templates are in first-reach order and each is reached,
770/// no two conflict, and recursion and newtype bases are regular. Returns the
771/// catalog they make.
772fn admit<'a>(
773    decls: Vec<Decl>,
774    roots: impl Iterator<Item = &'a Type> + Clone,
775) -> Result<Catalog, DecodeError> {
776    for ty in roots.clone() {
777        resolves(ty, &decls)?;
778    }
779    for ty in decls.iter().flat_map(members) {
780        resolves(ty, &decls)?;
781    }
782    in_first_reach_order(&decls, roots)?;
783    let mut identities = HashSet::new();
784    for decl in &decls {
785        if !identities.insert((decl.identity.clone(), decl.lexical_ordinal)) {
786            return Err(fail("two templates have one identity and lexical ordinal"));
787        }
788    }
789    newtypes_end(&decls)?;
790    Catalog::std(decls)
791}
792
793fn resolves(ty: &Type, decls: &[Decl]) -> Result<(), DecodeError> {
794    let mut stack = vec![ty];
795    while let Some(ty) = stack.pop() {
796        if let Type::Named(id, args) = ty {
797            let decl = decls
798                .get(crate::bytes::index(id.0))
799                .ok_or_else(|| fail("a Named term is an unresolved reference"))?;
800            if args.len() != decl.params.len() {
801                return Err(fail(
802                    "a Named term's argument count differs from its template's",
803                ));
804            }
805        }
806        push_parts(&mut stack, ty);
807    }
808    Ok(())
809}
810
811/// Refuses `decls` unless the walk from `roots` reaches each of them, the
812/// `n`th first as the `n`th template it reaches.
813fn in_first_reach_order<'a, 'r: 'a>(
814    decls: &'a [Decl],
815    roots: impl Iterator<Item = &'r Type>,
816) -> Result<(), DecodeError> {
817    let mut stack: Vec<&'a Type> = roots.map(|ty: &'r Type| -> &'a Type { ty }).collect();
818    stack.reverse();
819    let mut next = 0usize;
820    while let Some(ty) = stack.pop() {
821        push_parts(&mut stack, ty);
822        if let Type::Named(id, _) = ty {
823            let at = crate::bytes::index(id.0);
824            if at == next {
825                next += 1;
826                stack.extend(members(&decls[at]).into_iter().rev());
827            } else if at > next {
828                return Err(fail(format!(
829                    "the templates are not in first-reach order: template {at} is reached before template {next}"
830                )));
831            }
832        }
833    }
834    if next == decls.len() {
835        Ok(())
836    } else {
837        Err(fail(format!(
838            "template {next} is one nothing in the description reaches"
839        )))
840    }
841}
842
843/// Each declaration `ty` names, with its arguments, outermost first.
844fn references<'a>(ty: &'a Type, visit: &mut impl FnMut(DeclId, &'a [Type])) {
845    let mut stack = vec![ty];
846    while let Some(ty) = stack.pop() {
847        if let Type::Named(id, args) = ty {
848            visit(*id, args);
849        }
850        push_parts(&mut stack, ty);
851    }
852}
853
854/// Refuses a newtype template that, followed from base to base through
855/// newtypes alone, returns to itself (`types.md`, *Generics, recursion and
856/// bases*).
857fn newtypes_end(decls: &[Decl]) -> Result<(), DecodeError> {
858    for start in 0..decls.len() {
859        let mut at = start;
860        for _ in 0..decls.len() {
861            let Body::Newtype(Type::Named(next, _)) = &decls[at].body else {
862                break;
863            };
864            at = crate::bytes::index(next.0);
865            if at == start {
866                return Err(fail("a newtype template is its own base"));
867            }
868        }
869    }
870    Ok(())
871}
872
873/// Refuses recursion that does not substitute a template's own parameters
874/// back into it (`types.md`, *Recursive types*).
875pub(crate) fn regular(decls: &[Decl]) -> Result<(), DecodeError> {
876    let mut edges = vec![Vec::new(); decls.len()];
877    for (at, decl) in decls.iter().enumerate() {
878        for ty in members(decl) {
879            references(ty, &mut |id, args| {
880                edges[at].push((crate::bytes::index(id.0), args.to_vec()));
881            });
882        }
883    }
884    let component = components(&edges);
885    let mut done = vec![false; decls.len()];
886    for root in 0..decls.len() {
887        if std::mem::replace(&mut done[component[root]], true) {
888            continue;
889        }
890        let mut assignments: HashMap<usize, Vec<u32>> = HashMap::new();
891        assignments.insert(
892            root,
893            (0..u32::try_from(decls[root].params.len())
894                .expect("a declaration read within its bytes has fewer than 2^32 parameters"))
895                .collect(),
896        );
897        let mut pending = vec![root];
898        while let Some(source) = pending.pop() {
899            for (target, args) in &edges[source] {
900                if component[*target] != component[root] {
901                    continue;
902                }
903                let arity = decls[source].params.len();
904                if decls[*target].params.len() != arity || args.len() != arity {
905                    return Err(fail("recursive declaration arities differ"));
906                }
907                let permutation = args
908                    .iter()
909                    .map(|arg| match arg {
910                        Type::Param(index) => Ok(*index),
911                        _ => Err(fail("recursive arguments must be bare owner parameters")),
912                    })
913                    .collect::<Result<Vec<_>, _>>()?;
914                if permutation.iter().copied().collect::<HashSet<_>>().len() != arity {
915                    return Err(fail("recursive argument substitution is not bijective"));
916                }
917                let next: Vec<_> = permutation
918                    .iter()
919                    .map(|index| assignments[&source][crate::bytes::index(*index)])
920                    .collect();
921                if let Some(previous) = assignments.get(target) {
922                    if *previous != next {
923                        return Err(fail("recursive substitutions do not compose to identity"));
924                    }
925                } else {
926                    assignments.insert(*target, next);
927                    pending.push(*target);
928                }
929            }
930        }
931    }
932    Ok(())
933}
934
935/// The strongly connected component each node of the graph `edges` lies in,
936/// numbered from 0, by Tarjan's algorithm: one walk over every node and edge,
937/// with a stack of its own rather than recursion.
938fn components(edges: &[Vec<(usize, Vec<Type>)>]) -> Vec<usize> {
939    const UNSEEN: usize = usize::MAX;
940    let mut order = vec![UNSEEN; edges.len()];
941    let mut low = vec![0; edges.len()];
942    let mut on_stack = vec![false; edges.len()];
943    let mut component = vec![UNSEEN; edges.len()];
944    let mut stack = Vec::new();
945    let mut visited = 0;
946    let mut components = 0;
947    for start in 0..edges.len() {
948        if order[start] != UNSEEN {
949            continue;
950        }
951        let mut walk = vec![(start, 0)];
952        order[start] = visited;
953        low[start] = visited;
954        visited += 1;
955        stack.push(start);
956        on_stack[start] = true;
957        while let Some(&(node, edge)) = walk.last() {
958            if let Some((target, _)) = edges[node].get(edge) {
959                let target = *target;
960                let top = walk.len() - 1;
961                walk[top].1 += 1;
962                if order[target] == UNSEEN {
963                    order[target] = visited;
964                    low[target] = visited;
965                    visited += 1;
966                    stack.push(target);
967                    on_stack[target] = true;
968                    walk.push((target, 0));
969                } else if on_stack[target] {
970                    low[node] = low[node].min(order[target]);
971                }
972                continue;
973            }
974            walk.pop();
975            if let Some(&(parent, _)) = walk.last() {
976                low[parent] = low[parent].min(low[node]);
977            }
978            if low[node] == order[node] {
979                while let Some(member) = stack.pop() {
980                    on_stack[member] = false;
981                    component[member] = components;
982                    if member == node {
983                        break;
984                    }
985                }
986                components += 1;
987            }
988        }
989    }
990    component
991}
992
993// === Type specs ==============================================================
994
995/// A Tool's type description: its roots and the templates they reach, in
996/// first-reach order, validated.
997#[derive(Clone, Debug)]
998pub struct TypeSpec {
999    catalog: Catalog,
1000    signature: Signature,
1001    bytes: Arc<[u8]>,
1002}
1003
1004impl PartialEq for TypeSpec {
1005    /// Two descriptions are equal when their bytes are: a type has one.
1006    fn eq(&self, other: &Self) -> bool {
1007        self.bytes == other.bytes
1008    }
1009}
1010
1011impl Eq for TypeSpec {}
1012
1013impl TypeSpec {
1014    /// The description of `signature`, whose types `catalog` names.
1015    ///
1016    /// # Errors
1017    ///
1018    /// An [`EncodeError`] when a type the signature reaches has no term,
1019    /// such as an incomplete one, or the description does not validate.
1020    pub fn from_catalog(catalog: &Catalog, signature: &Signature) -> Result<Self, EncodeError> {
1021        let bytes = write_spec(catalog, signature, Form::Full)?;
1022        Ok(Self::read(&bytes)?)
1023    }
1024
1025    /// The description `bytes` hold, and nothing else.
1026    ///
1027    /// # Errors
1028    ///
1029    /// A [`DecodeError`] when the bytes are not one valid `TypeSpec`.
1030    pub fn read(bytes: &[u8]) -> Result<Self, DecodeError> {
1031        let mut reader = Reader::new(bytes);
1032        let spec = Self::read_from(&mut reader)?;
1033        if reader.is_empty() {
1034            Ok(spec)
1035        } else {
1036            Err(fail(format!(
1037                "a type description has {} bytes left over",
1038                reader.remaining()
1039            )))
1040        }
1041    }
1042
1043    /// The description at `reader`, which it reads past.
1044    ///
1045    /// # Errors
1046    ///
1047    /// A [`DecodeError`] when the bytes there are not a valid `TypeSpec`.
1048    pub fn read_from(reader: &mut Reader<'_>) -> Result<Self, DecodeError> {
1049        let start = reader.position();
1050        let spec = described::TypeSpec::read(reader)?;
1051        let bytes = reader.since(start).into();
1052        let read = Read::spec(spec)?;
1053        let signature = read.signature();
1054        let catalog = admit(read.decls, signature_types(&signature))?;
1055        Ok(TypeSpec {
1056            catalog,
1057            signature,
1058            bytes,
1059        })
1060    }
1061
1062    /// Its bytes in the value encoding.
1063    pub fn bytes(&self) -> &[u8] {
1064        &self.bytes
1065    }
1066
1067    /// The catalog of the declarations its roots reach, each [`DeclId`] its
1068    /// place in the description.
1069    pub fn catalog(&self) -> &Catalog {
1070        &self.catalog
1071    }
1072
1073    /// The served signature: its parameters and result, with [`Type::Param`]
1074    /// counting its type parameters.
1075    pub fn signature(&self) -> &Signature {
1076        &self.signature
1077    }
1078
1079    /// The description written to be compared: every doc comment `None`
1080    /// and every version empty.
1081    ///
1082    /// # Panics
1083    ///
1084    /// Never: a description that was read is written again.
1085    pub fn comparable(&self) -> Vec<u8> {
1086        write_spec(&self.catalog, &self.signature, Form::Comparable)
1087            .expect("a description read is written again")
1088    }
1089
1090    /// The signature as a message writes it when two differ: each parameter
1091    /// and the result, then each template's members, docs and versions left
1092    /// out.
1093    ///
1094    /// # Panics
1095    ///
1096    /// Never: a validated template's arity fits 32 bits.
1097    pub fn outline(&self) -> String {
1098        let name = |ty: &Type| self.catalog.written(ty, Versions::Hidden);
1099        let mut out = String::new();
1100        if !self.signature.generic.is_empty() {
1101            write!(out, "<{}>", self.signature.generic.join(", ")).expect("a string");
1102        }
1103        let params: Vec<String> = self
1104            .signature
1105            .params
1106            .iter()
1107            .map(|(key, ty)| format!("{key}: {}", name(ty)))
1108            .collect();
1109        write!(
1110            out,
1111            "({}) -> {}",
1112            params.join(", "),
1113            name(&self.signature.result)
1114        )
1115        .expect("a string");
1116        for (id, decl) in self.catalog.decls() {
1117            let shown = name(&Type::Named(
1118                id,
1119                (0..u32::try_from(decl.params.len()).expect("an arity"))
1120                    .map(Type::Param)
1121                    .collect(),
1122            ));
1123            let opaque = if decl.opaque { "opaque " } else { "" };
1124            let body = match &decl.body {
1125                Body::Record(shape, fields) => {
1126                    let fields: Vec<String> = shape
1127                        .fields()
1128                        .zip(fields)
1129                        .map(|(field, ty)| format!("{field}: {}", name(ty)))
1130                        .collect();
1131                    format!("{{ {} }}", fields.join(", "))
1132                }
1133                Body::Enum(shape, constructors) => {
1134                    let constructors: Vec<String> = constructors
1135                        .iter()
1136                        .enumerate()
1137                        .map(|(at, parts)| {
1138                            let ctor = shape.constructor(at).expect("a validated shape");
1139                            let parts: Vec<String> = match ctor.payload() {
1140                                Payload::None => return ctor.name().to_owned(),
1141                                Payload::Positional(_) => parts.iter().map(name).collect(),
1142                                Payload::Named(names) => names
1143                                    .iter()
1144                                    .zip(parts)
1145                                    .map(|(field, ty)| format!("{field}: {}", name(ty)))
1146                                    .collect(),
1147                            };
1148                            format!("{}({})", ctor.name(), parts.join(", "))
1149                        })
1150                        .collect();
1151                    format!("{{ {} }}", constructors.join(" | "))
1152                }
1153                Body::Newtype(base) => format!("({})", name(base)),
1154                Body::Host => "host".to_owned(),
1155                Body::NonData => "nondata".to_owned(),
1156            };
1157            write!(out, "; {opaque}type {shown} {body}").expect("a string");
1158        }
1159        out
1160    }
1161
1162    /// Validates a call's views against this description (`abi.md`, *A
1163    /// generic call's types*): none for a Tool that is not generic, and for
1164    /// a generic one a `CallTypes` whose bindings, parameters and result
1165    /// agree with this spec.
1166    ///
1167    /// # Errors
1168    ///
1169    /// A [`DecodeError`] when the views are missing or extra, are not a
1170    /// valid `CallTypes`, or do not fit this spec.
1171    pub fn validate_call(
1172        &self,
1173        generic: Option<&described::CallTypes>,
1174    ) -> Result<Option<ValidatedTypes>, DecodeError> {
1175        let Some(generic) = generic else {
1176            return if self.signature.generic.is_empty() {
1177                Ok(None)
1178            } else {
1179                Err(fail("a generic Tool's call carries no types"))
1180            };
1181        };
1182        if self.signature.generic.is_empty() {
1183            return Err(fail("a call to a Tool that is not generic carries types"));
1184        }
1185        let read = Read::call(generic.clone())?;
1186        if read
1187            .bindings
1188            .iter()
1189            .map(|(name, _)| name)
1190            .ne(self.signature.generic.iter())
1191        {
1192            return Err(fail(
1193                "the call's bindings differ from the Tool's type parameters in name, count or order",
1194            ));
1195        }
1196        let bindings = read.bindings.clone();
1197        let signature = read.signature();
1198        let catalog = admit(read.decls, call_roots(&bindings, &signature))?;
1199        let arguments: Vec<_> = bindings.iter().map(|(_, ty)| ty.clone()).collect();
1200        Equality::new(&self.catalog, &catalog).signature(
1201            &self.signature,
1202            &signature,
1203            &arguments,
1204        )?;
1205        for (_, ty) in &bindings {
1206            decodable(&catalog, ty, BINDING)?;
1207        }
1208        for (_, ty) in &signature.params {
1209            crossable(&catalog, ty)?;
1210        }
1211        crossable(&catalog, &signature.result)?;
1212        decodable(&catalog, &signature.result, REPLY)?;
1213        let schema = bound_schema(&catalog, &bindings)?;
1214        Ok(Some(ValidatedTypes {
1215            catalog,
1216            bindings,
1217            signature,
1218            schema,
1219            types: generic.bytes().into(),
1220        }))
1221    }
1222}
1223
1224fn call_roots<'a>(
1225    bindings: &'a [(String, Type)],
1226    signature: &'a Signature,
1227) -> impl Iterator<Item = &'a Type> + Clone {
1228    bindings
1229        .iter()
1230        .map(|(_, ty)| ty)
1231        .chain(signature_types(signature))
1232}
1233
1234/// The comparable form of a declaration's signature, `identity` and
1235/// `spec`: what binding compares by its bytes (`abi.md`, *Identity and
1236/// signatures*).
1237pub fn comparable(identity: &Identity, spec: &TypeSpec) -> Vec<u8> {
1238    let mut out = Form::Comparable.identity(identity.clone()).bytes();
1239    out.extend(spec.comparable());
1240    out
1241}
1242
1243/// A concrete generic call's description after complete validation.
1244#[derive(Clone, Debug)]
1245pub struct ValidatedTypes {
1246    catalog: Catalog,
1247    bindings: Vec<(String, Type)>,
1248    signature: Signature,
1249    schema: Option<String>,
1250    types: Arc<[u8]>,
1251}
1252
1253impl ValidatedTypes {
1254    /// The validated catalog, shared by every root in this view.
1255    pub fn catalog(&self) -> &Catalog {
1256        &self.catalog
1257    }
1258
1259    /// The concrete type bound to the type parameter `name`.
1260    pub fn binding(&self, name: &str) -> Option<&Type> {
1261        self.bindings
1262            .iter()
1263            .find(|(key, _)| key == name)
1264            .map(|(_, ty)| ty)
1265    }
1266
1267    /// The concrete bindings, in the Tool's type parameter order.
1268    pub fn bindings(&self) -> &[(String, Type)] {
1269        &self.bindings
1270    }
1271
1272    /// A parameter's concrete type, by its key.
1273    pub fn argument(&self, name: &str) -> Option<&Type> {
1274        self.signature
1275            .params
1276            .iter()
1277            .find(|(key, _)| key == name)
1278            .map(|(_, ty)| ty)
1279    }
1280
1281    /// The concrete parameters, in declaration order.
1282    pub fn params(&self) -> &[(String, Type)] {
1283        &self.signature.params
1284    }
1285
1286    /// The concrete result.
1287    pub fn result(&self) -> &Type {
1288        &self.signature.result
1289    }
1290
1291    /// For a Tool with one type parameter, the canonical text of the JSON
1292    /// Schema of the type the call binds to it (`abi.md`, *Schemas*).
1293    pub fn schema(&self) -> Option<&str> {
1294        self.schema.as_deref()
1295    }
1296
1297    /// The `CallTypes` bytes the call carried.
1298    pub fn types(&self) -> &[u8] {
1299        &self.types
1300    }
1301}
1302
1303/// The concrete result type of one call, for a client that answers it from
1304/// outside the call (`abi.md`, *Type descriptions* and *Replies from outside
1305/// a call*): the type and the templates it reaches, validated.
1306#[derive(Clone, Debug)]
1307pub struct ResultType {
1308    catalog: Catalog,
1309    result: Type,
1310    bytes: Arc<[u8]>,
1311}
1312
1313impl PartialEq for ResultType {
1314    /// Two descriptions are equal when their bytes are: a type has one.
1315    fn eq(&self, other: &Self) -> bool {
1316        self.bytes == other.bytes
1317    }
1318}
1319
1320impl Eq for ResultType {}
1321
1322impl ResultType {
1323    /// The description of `result`, a concrete type `catalog` names.
1324    ///
1325    /// # Errors
1326    ///
1327    /// An [`EncodeError`] when `result` has no term, names a type
1328    /// parameter, or the description does not validate.
1329    pub fn from_catalog(catalog: &Catalog, result: &Type) -> Result<Self, EncodeError> {
1330        let order = first_reach(catalog, [result])?;
1331        let writer = Writer::new(catalog, Form::Full, &order);
1332        let bytes = described::ResultType {
1333            result: writer.term(result, Scope::Concrete)?,
1334            declarations: writer.templates(&order)?,
1335        }
1336        .bytes();
1337        Self::read(&bytes).map_err(|error| unwritable(&error.problem))
1338    }
1339
1340    /// The description `bytes` hold, and nothing else.
1341    ///
1342    /// # Errors
1343    ///
1344    /// A [`DecodeError`] when the bytes are not one valid `ResultType`.
1345    pub fn read(bytes: &[u8]) -> Result<Self, DecodeError> {
1346        let mut reader = Reader::new(bytes);
1347        let result = Self::read_from(&mut reader)?;
1348        if reader.is_empty() {
1349            Ok(result)
1350        } else {
1351            Err(fail(format!(
1352                "a result type has {} bytes left over",
1353                reader.remaining()
1354            )))
1355        }
1356    }
1357
1358    /// The description at `reader`, which it reads past.
1359    ///
1360    /// # Errors
1361    ///
1362    /// A [`DecodeError`] when the bytes there are not a valid `ResultType`.
1363    pub fn read_from(reader: &mut Reader<'_>) -> Result<Self, DecodeError> {
1364        let start = reader.position();
1365        let described = described::ResultType::read(reader)?;
1366        let bytes = reader.since(start).into();
1367        let mut reading = Reading::default();
1368        let result = reading.ty(&described.result, Scope::Concrete)?;
1369        let decls = reading.decls(described.declarations)?;
1370        let catalog = admit(decls, std::iter::once(&result))?;
1371        Ok(ResultType {
1372            catalog,
1373            result,
1374            bytes,
1375        })
1376    }
1377
1378    /// Its bytes in the value encoding.
1379    pub fn bytes(&self) -> &[u8] {
1380        &self.bytes
1381    }
1382
1383    /// The catalog of the declarations the result reaches, each
1384    /// [`DeclId`] its place in the description.
1385    pub fn catalog(&self) -> &Catalog {
1386        &self.catalog
1387    }
1388
1389    /// The concrete result type.
1390    pub fn result(&self) -> &Type {
1391        &self.result
1392    }
1393}
1394
1395/// The canonical text of the schema of the one type in `bindings`, or
1396/// `None` for any other count (`abi.md`, *The Tool process protocol*).
1397fn bound_schema(
1398    catalog: &Catalog,
1399    bindings: &[(String, Type)],
1400) -> Result<Option<String>, DecodeError> {
1401    match bindings {
1402        [(_, bound)] => schema(catalog, bound)
1403            .map(|schema| Some(schema.canonical()))
1404            .map_err(|error| fail(error.problem)),
1405        _ => Ok(None),
1406    }
1407}
1408
1409/// The views a generic call to `signature` carries at `arguments`, whose
1410/// types `catalog` names: its `CallTypes`.
1411///
1412/// # Errors
1413///
1414/// An [`EncodeError`] when an argument has no term, or the arguments do not
1415/// bind the signature's type parameters.
1416pub fn call_views(
1417    catalog: &Catalog,
1418    signature: &Signature,
1419    arguments: &[Type],
1420) -> Result<described::CallTypes, EncodeError> {
1421    if arguments.len() != signature.generic.len() {
1422        return Err(unwritable("a generic call's argument count differs"));
1423    }
1424    let bindings: Vec<_> = signature
1425        .generic
1426        .iter()
1427        .cloned()
1428        .zip(arguments.iter().cloned())
1429        .collect();
1430    let concrete = Signature {
1431        generic: Vec::new(),
1432        params: signature
1433            .params
1434            .iter()
1435            .map(|(name, ty)| (name.clone(), ty.subst(arguments)))
1436            .collect(),
1437        result: signature.result.subst(arguments),
1438    };
1439    let order = first_reach(catalog, call_roots(&bindings, &concrete))?;
1440    let writer = Writer::new(catalog, Form::Full, &order);
1441    Ok(described::CallTypes {
1442        bindings: writer.entries(&bindings, Scope::Concrete)?,
1443        params: writer.entries(&concrete.params, Scope::Concrete)?,
1444        result: writer.term(&concrete.result, Scope::Concrete)?,
1445        declarations: writer.templates(&order)?,
1446    })
1447}
1448
1449/// The concrete bindings a `CallTypes`, `types`, gives, by name, and the
1450/// catalog they are named in.
1451///
1452/// # Errors
1453///
1454/// A [`DecodeError`] when `types` is not a valid `CallTypes`.
1455pub fn call_bindings(
1456    types: &described::CallTypes,
1457) -> Result<(Catalog, Vec<(String, Type)>), DecodeError> {
1458    let read = Read::call(types.clone())?;
1459    let bindings = read.bindings.clone();
1460    let signature = read.signature();
1461    let catalog = admit(read.decls, call_roots(&bindings, &signature))?;
1462    Ok((catalog, bindings))
1463}
1464
1465// === The contract file =======================================================
1466
1467/// One program's Tools as the `--contract` file lists them (`abi.md`,
1468/// *Binding*).
1469#[derive(Clone, Debug)]
1470pub struct ListedProgram {
1471    /// The program's root: the path of the file it was formed from.
1472    pub root: String,
1473    /// Each Tool's identity and its own description, in the file's order.
1474    pub tools: Vec<(Identity, TypeSpec)>,
1475}
1476
1477/// Why a `--contract` file lists nothing.
1478#[derive(Clone, PartialEq, Eq, Debug)]
1479pub enum ListingError {
1480    /// It is written in a data version this one does not read.
1481    Version(DataVersion),
1482    /// It is not a contract file, and why.
1483    Invalid(String),
1484}
1485
1486impl std::fmt::Display for ListingError {
1487    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1488        match self {
1489            ListingError::Version(version) => write!(
1490                f,
1491                "the contract file is written in data version {version}, not {DATA_VERSION}"
1492            ),
1493            ListingError::Invalid(problem) => write!(f, "the contract file is invalid: {problem}"),
1494        }
1495    }
1496}
1497
1498impl std::error::Error for ListingError {}
1499
1500/// The `--contract` file listing `tools` of the program formed from
1501/// `root`, whose types `catalog` names: the data version, one program,
1502/// each Tool's identity and description without templates, and the
1503/// program's type map in first-reach order over the Tools in this order.
1504///
1505/// # Errors
1506///
1507/// An [`EncodeError`] when a Tool's types have no description.
1508pub fn write_listing(
1509    root: &str,
1510    catalog: &Catalog,
1511    tools: &[&ToolDecl],
1512) -> Result<Vec<u8>, EncodeError> {
1513    let order = first_reach(
1514        catalog,
1515        tools
1516            .iter()
1517            .flat_map(|tool| signature_types(&tool.signature)),
1518    )?;
1519    let writer = Writer::new(catalog, Form::Full, &order);
1520    let tools = tools
1521        .iter()
1522        .map(|tool| {
1523            let signature = &tool.signature;
1524            let scope = Scope::Tool(signature.generic.len());
1525            let spec = described::TypeSpec {
1526                generic: signature.generic.clone(),
1527                params: writer.entries(&signature.params, scope)?,
1528                result: writer.term(&signature.result, scope)?,
1529                declarations: Vec::new(),
1530            };
1531            Ok((Identity::of(&tool.identity), spec))
1532        })
1533        .collect::<Result<_, EncodeError>>()?;
1534    let program = Program {
1535        root: root.to_owned(),
1536        tools,
1537        types: writer.templates(&order)?,
1538    };
1539    Ok(Versioned {
1540        version: DATA_VERSION,
1541        rest: Rest(vec![program].bytes()),
1542    }
1543    .bytes())
1544}
1545
1546/// The programs a `--contract` file lists, each Tool with its own
1547/// description: its templates taken from the program's type map and
1548/// numbered in its own first-reach order.
1549///
1550/// # Errors
1551///
1552/// A [`ListingError`] when the file is in a data version this one does not
1553/// read, or is not a valid contract file.
1554///
1555/// # Panics
1556///
1557/// Never for a file it admits: each Tool's types are checked against the
1558/// program's type map before its description is made.
1559pub fn read_listing(bytes: &[u8]) -> Result<Vec<ListedProgram>, ListingError> {
1560    let invalid = |error: DecodeError| ListingError::Invalid(error.problem);
1561    let Versioned { version, rest } = Versioned::decode(bytes).map_err(invalid)?;
1562    if !DATA_VERSION.reads(&version) {
1563        return Err(ListingError::Version(version));
1564    }
1565    let programs = Vec::<Program>::decode(&rest.0).map_err(invalid)?;
1566    programs
1567        .into_iter()
1568        .map(|program| {
1569            let listed = program
1570                .tools
1571                .into_iter()
1572                .map(|(identity, spec)| Ok((identity, Read::listed(spec)?.signature())))
1573                .collect::<Result<Vec<_>, DecodeError>>()?;
1574            let decls = Reading::default().decls(program.types)?;
1575            let catalog = admit(
1576                decls,
1577                listed
1578                    .iter()
1579                    .flat_map(|(_, signature)| signature_types(signature)),
1580            )?;
1581            let tools = listed
1582                .into_iter()
1583                .map(|(identity, signature)| {
1584                    let spec = TypeSpec::from_catalog(&catalog, &signature)
1585                        .expect("a Tool whose types the catalog admitted has a description");
1586                    (identity, spec)
1587                })
1588                .collect();
1589            Ok(ListedProgram {
1590                root: program.root,
1591                tools,
1592            })
1593        })
1594        .collect::<Result<_, DecodeError>>()
1595        .map_err(invalid)
1596}
1597
1598// === Fit of a call's types ===================================================
1599
1600struct Equality<'a> {
1601    served: &'a Catalog,
1602    caller: &'a Catalog,
1603    compared: HashSet<(DeclId, DeclId)>,
1604    mapping: HashMap<DeclId, DeclId>,
1605}
1606
1607impl<'a> Equality<'a> {
1608    fn new(served: &'a Catalog, caller: &'a Catalog) -> Self {
1609        Self {
1610            served,
1611            caller,
1612            compared: HashSet::new(),
1613            mapping: HashMap::new(),
1614        }
1615    }
1616
1617    fn signature(
1618        &mut self,
1619        served: &Signature,
1620        caller: &Signature,
1621        bindings: &[Type],
1622    ) -> Result<(), DecodeError> {
1623        if served
1624            .params
1625            .iter()
1626            .map(|(name, _)| name)
1627            .ne(caller.params.iter().map(|(name, _)| name))
1628        {
1629            return Err(fail("concrete parameters differ in name, count or order"));
1630        }
1631        for ((_, expected), (_, actual)) in served.params.iter().zip(&caller.params) {
1632            self.term(expected, actual, Some(bindings))?;
1633        }
1634        self.term(&served.result, &caller.result, Some(bindings))
1635    }
1636
1637    fn parts(
1638        &mut self,
1639        expected: &[Type],
1640        actual: &[Type],
1641        bindings: Option<&[Type]>,
1642    ) -> Result<(), DecodeError> {
1643        if expected.len() != actual.len() {
1644            return Err(fail("concrete type arity differs"));
1645        }
1646        for (expected, actual) in expected.iter().zip(actual) {
1647            self.term(expected, actual, bindings)?;
1648        }
1649        Ok(())
1650    }
1651
1652    fn term(
1653        &mut self,
1654        expected: &Type,
1655        actual: &Type,
1656        bindings: Option<&[Type]>,
1657    ) -> Result<(), DecodeError> {
1658        if let (Type::Param(index), Some(bindings)) = (expected, bindings) {
1659            return if bindings.get(crate::bytes::index(*index)) == Some(actual) {
1660                Ok(())
1661            } else {
1662                Err(fail("concrete root differs from its generic binding"))
1663            };
1664        }
1665        match (expected, actual) {
1666            (Type::Named(left, left_args), Type::Named(right, right_args)) => {
1667                self.parts(left_args, right_args, bindings)?;
1668                self.declaration(*left, *right)
1669            }
1670            (Type::List(left), Type::List(right))
1671            | (Type::Set(left), Type::Set(right))
1672            | (Type::Option(left), Type::Option(right))
1673            | (Type::Task(left), Type::Task(right)) => self.term(left, right, bindings),
1674            (Type::Dict(lk, lv), Type::Dict(rk, rv)) => {
1675                self.term(lk, rk, bindings)?;
1676                self.term(lv, rv, bindings)
1677            }
1678            (Type::Tuple(left), Type::Tuple(right)) => self.parts(left, right, bindings),
1679            (
1680                Type::Function {
1681                    params: lp,
1682                    result: lr,
1683                },
1684                Type::Function {
1685                    params: rp,
1686                    result: rr,
1687                },
1688            ) => {
1689                self.parts(lp, rp, bindings)?;
1690                self.term(lr, rr, bindings)
1691            }
1692            _ if expected == actual => Ok(()),
1693            _ => Err(fail("concrete type differs from served template")),
1694        }
1695    }
1696
1697    fn declaration(&mut self, left: DeclId, right: DeclId) -> Result<(), DecodeError> {
1698        if self
1699            .mapping
1700            .insert(left, right)
1701            .is_some_and(|previous| previous != right)
1702        {
1703            return Err(fail(
1704                "known declaration maps to conflicting caller templates",
1705            ));
1706        }
1707        if !self.compared.insert((left, right)) {
1708            return Ok(());
1709        }
1710        let left = self.served.decl(left);
1711        let right = self.caller.decl(right);
1712        if left.identity != right.identity
1713            || left.lexical_ordinal != right.lexical_ordinal
1714            || left.params.len() != right.params.len()
1715            || left.opaque != right.opaque
1716        {
1717            return Err(fail(
1718                "known declaration template identity or generic facts differ",
1719            ));
1720        }
1721        match (&left.body, &right.body) {
1722            (Body::Record(ls, lt), Body::Record(rs, rt)) if ls.fields().eq(rs.fields()) => {
1723                self.parts(lt, rt, None)
1724            }
1725            (Body::Enum(ls, lt), Body::Enum(rs, rt)) if lt.len() == rt.len() => {
1726                for (at, (left, right)) in lt.iter().zip(rt).enumerate() {
1727                    let lc = ls.constructor(at).expect("validated constructor");
1728                    let rc = rs.constructor(at).expect("validated constructor");
1729                    if lc.name() != rc.name() || lc.payload() != rc.payload() {
1730                        return Err(fail("known constructor order or payload differs"));
1731                    }
1732                    self.parts(left, right, None)?;
1733                }
1734                Ok(())
1735            }
1736            (Body::Newtype(left), Body::Newtype(right)) => self.term(left, right, None),
1737            (Body::Host, Body::Host) | (Body::NonData, Body::NonData) => Ok(()),
1738            _ => Err(fail("known declaration members or kind differ")),
1739        }
1740    }
1741}
1742
1743/// A validated description is written as the bytes it was read from, and read
1744/// as [`TypeSpec::read_from`] reads and validates it; its form and its value
1745/// are its declared description's.
1746impl Shaped for TypeSpec {
1747    const FORM: WireForm = <described::TypeSpec as Shaped>::FORM;
1748
1749    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
1750        described::TypeSpec::decode(self.bytes())
1751            .map_err(|_| out.refuse(ty))?
1752            .write_at(out, ty)
1753    }
1754
1755    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
1756        let described = described::TypeSpec::read_at(input, ty)?;
1757        Self::decode(&described.bytes()).map_err(|_| input.mismatch(ty))
1758    }
1759}
1760
1761impl Wire for TypeSpec {
1762    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
1763        out.extend_from_slice(self.bytes());
1764    }
1765
1766    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
1767        TypeSpec::read_from(reader).map(Opened::built)
1768    }
1769}
1770
1771/// As [`TypeSpec`]'s: the bytes it was read from, read and validated by
1772/// [`ResultType::read_from`].
1773impl Shaped for ResultType {
1774    const FORM: WireForm = <described::ResultType as Shaped>::FORM;
1775
1776    fn write_at(&self, out: &mut ValueWriter<'_, '_>, ty: &Type) -> Result<(), EncodeError> {
1777        described::ResultType::decode(self.bytes())
1778            .map_err(|_| out.refuse(ty))?
1779            .write_at(out, ty)
1780    }
1781
1782    fn read_at(input: &mut ValueReader<'_, '_, '_>, ty: &Type) -> Result<Self, DecodeError> {
1783        let described = described::ResultType::read_at(input, ty)?;
1784        Self::decode(&described.bytes()).map_err(|_| input.mismatch(ty))
1785    }
1786}
1787
1788impl Wire for ResultType {
1789    fn write_head<'a>(&'a self, out: &mut Vec<u8>, _: &mut Vec<&'a dyn AnyWire>) {
1790        out.extend_from_slice(self.bytes());
1791    }
1792
1793    fn open(reader: &mut Reader<'_>) -> Result<Opened, DecodeError> {
1794        ResultType::read_from(reader).map(Opened::built)
1795    }
1796}