Skip to main content

flow_abi/
catalog.rs

1//! The catalog the encoding reads declared types in, and the std types held
2//! to forms of their own.
3//!
4//! A [`Catalog`] keeps a program's declarations by [`DeclId`], their names
5//! indexed once when it is built ([`NameIndex`]), with what
6//! [`flow_types::judge`] has said of the types decoding asked about, and the
7//! shapes of std's
8//! `Option` and `json.Value`, whose values the encoding builds itself. A
9//! [`StdForm`] is the normal form decoding holds `path.Path`, `url.Url`,
10//! `media.MediaType`, `code.RunId` and `code.TaskPath` to.
11
12use std::borrow::Cow;
13use std::collections::HashMap;
14use std::fmt::Write as _;
15use std::sync::{Arc, Mutex, PoisonError};
16
17use flow_span::{RunId, TaskPath};
18use flow_types::{
19    Body, Decl, DeclId, EnumShape, JsonValueCtor, Members, Mismatch, NameIndex, Nested, OptionCtor,
20    Reason, Role, Settings, Shape, Spelling, StdEnum, Tree, Type, Versions, judge,
21};
22use flow_value::{Value, Variant};
23
24use crate::DecodeError;
25use crate::decode::{CROSSING, Mode};
26use crate::form::{Form, form};
27use crate::json::quote;
28
29/// A std type over `Text` whose values are held to a form of their own.
30#[derive(Clone, Copy, PartialEq, Eq, Debug)]
31pub enum StdForm {
32    /// `path.Path`: any text names a path, in its normal form.
33    Path,
34    /// `url.Url`: a URI by RFC 3986, in the normal form of its ยง6.2.2.
35    Url,
36    /// `media.MediaType`: a media type by RFC 9110, in its normal form.
37    MediaType,
38    /// `code.RunId`: a run's id, 32 lowercase hexadecimal digits
39    /// (`history.md`, *Keys*), its own normal form.
40    RunId,
41    /// `code.TaskPath`: a task's id, `root` and then `/` and a positive count
42    /// any number of times (`history.md`, *Identity*), its own normal form.
43    TaskPath,
44}
45
46impl StdForm {
47    /// The form of its own `decl`'s values are held to, when it is one of
48    /// the std types that have one (`stdlib.md`, *`@lang`
49    /// declarations*): JSON decoding reads any spelling of the form as the
50    /// one value it denotes, and binary decoding accepts only the normal
51    /// text (`abi.md`, *Decoding*). It is known by its std identity alone.
52    pub fn of(decl: &Decl) -> Option<StdForm> {
53        let identity = &decl.identity;
54        if *identity.origin.tree() != Tree::Std || identity.version.as_deref() != Some("v1") {
55            return None;
56        }
57        let role = Role::of(identity.origin.module().as_str(), identity.name.as_str())?;
58        [
59            StdForm::Path,
60            StdForm::Url,
61            StdForm::MediaType,
62            StdForm::RunId,
63            StdForm::TaskPath,
64        ]
65        .into_iter()
66        .find(|form| form.role() == role)
67    }
68
69    /// The role std marks its type with.
70    pub fn role(self) -> Role {
71        match self {
72            StdForm::Path => Role::Path,
73            StdForm::Url => Role::Url,
74            StdForm::MediaType => Role::MediaType,
75            StdForm::RunId => Role::RunId,
76            StdForm::TaskPath => Role::TaskPath,
77        }
78    }
79
80    /// The normal text of the value `text` spells, or `None` when it spells
81    /// none.
82    pub fn normal(self, text: &str) -> Option<String> {
83        match self {
84            StdForm::Path => Some(flow_types::normal_path(text)),
85            StdForm::Url => crate::url::normal_url(text),
86            StdForm::MediaType => crate::media::normal_media_type(text),
87            StdForm::RunId => RunId::parse(text).ok().map(|run| run.to_string()),
88            StdForm::TaskPath => TaskPath::parse(text).ok().map(|task| task.to_string()),
89        }
90    }
91
92    /// The value of this form `text` spells, held as its normal text, or
93    /// `None` when it spells none: the one way std makes a value of it, so
94    /// every value of a form is in it and [`StdForm::out_of`] finds nothing
95    /// in what a run made.
96    pub fn make(self, text: &str) -> Option<Value> {
97        self.normal(text).map(|normal| Value::Text(normal.into()))
98    }
99
100    /// Why `text` is not a value of this form written as its normal text,
101    /// or `None` when it is: the one encoding such a value has (`abi.md`,
102    /// *Decoding*).
103    pub fn refusal(self, text: &str) -> Option<String> {
104        match self.normal(text) {
105            Some(normal) if normal == text => None,
106            Some(normal) => Some(format!(
107                "is {} written {}, which is not its normal form {}",
108                self.noun(),
109                quote(text),
110                quote(&normal)
111            )),
112            None => Some(format!("is {}, which is not {}", quote(text), self.noun())),
113        }
114    }
115
116    /// Why `value`, a value of a newtype held to `form`, is out of it, or
117    /// `None` when it is in it or the newtype has no form: the one check
118    /// every walker that writes or reads such a value makes, so that no
119    /// encoder writes what a decoder refuses.
120    pub fn out_of(form: Option<StdForm>, value: &Value) -> Option<String> {
121        match (form, value) {
122            (Some(form), Value::Text(text)) => form.refusal(text.as_str()),
123            _ => None,
124        }
125    }
126
127    /// Why a value `value` holds anywhere, read at `ty`, is out of the form
128    /// its newtype holds it to, the first in a walk of the value, or `None`
129    /// when every one is in its form: the check a store that keeps such a
130    /// value as its erasure, a `Text`, makes of the whole value, since the
131    /// erasure alone cannot tell.
132    pub fn first_out_of(catalog: &Catalog, ty: &Type, value: &Value) -> Option<String> {
133        let mut pending: Vec<(Type, &Value)> = vec![(ty.clone(), value)];
134        while let Some((ty, value)) = pending.pop() {
135            match (form(catalog, &ty), value) {
136                (Form::Newtype(base, held), _) => {
137                    if let Some(problem) = StdForm::out_of(held, value) {
138                        return Some(problem);
139                    }
140                    pending.push((base, value));
141                }
142                (Form::List(item), Value::List(items)) => {
143                    pending.extend(items.iter().map(|part| (item.clone(), part)));
144                }
145                (Form::Set(item), Value::Set(items)) => {
146                    pending.extend(items.iter().map(|part| (item.clone(), part)));
147                }
148                (Form::Dict(key, item), Value::Dict(entries)) => {
149                    for (k, v) in entries.iter() {
150                        pending.push((key.clone(), k));
151                        pending.push((item.clone(), v));
152                    }
153                }
154                (Form::Tuple(parts), Value::Tuple(tuple)) => {
155                    pending.extend(parts.iter().cloned().zip(tuple.parts()));
156                }
157                (Form::Record(record), Value::Record(fields)) => {
158                    pending.extend(record.fields.into_iter().zip(fields.fields()));
159                }
160                (Form::Enum(shape), Value::Variant(variant)) => {
161                    let parts = shape.parts(variant.index()).unwrap_or_default();
162                    pending.extend(
163                        parts
164                            .into_iter()
165                            .map(Cow::into_owned)
166                            .zip(variant.payload()),
167                    );
168                }
169                _ => {}
170            }
171        }
172        None
173    }
174
175    /// What a value of it is, for a refusal: "a path".
176    pub(crate) fn noun(self) -> &'static str {
177        match self {
178            StdForm::Path => "a path",
179            StdForm::Url => "a URL",
180            StdForm::MediaType => "a media type",
181            StdForm::RunId => "a run's id",
182            StdForm::TaskPath => "a task's id",
183        }
184    }
185}
186
187/// The declarations a set of types names, with the std enums whose values
188/// the encoding builds itself.
189#[derive(Clone, Debug)]
190pub struct Catalog {
191    decls: Vec<Decl>,
192    judged: Judged,
193    names: Vec<Names>,
194    option: Bound<OptionCtor>,
195    json: Option<Bound<JsonValueCtor>>,
196}
197
198/// What [`judge`] said of each type decoding has asked about, under the
199/// settings it asked with, as decoding words it. It is a cache of that one
200/// judgment, kept only so that the check each decode makes first costs a
201/// lookup: an entry is what a fresh walk of its type would say, since the
202/// declarations it was judged over never change.
203#[derive(Debug, Default)]
204struct Judged(Mutex<HashMap<(Type, Settings), Option<String>>>);
205
206impl Clone for Judged {
207    fn clone(&self) -> Self {
208        Judged(Mutex::new(self.entries().clone()))
209    }
210}
211
212impl Judged {
213    fn entries(&self) -> std::sync::MutexGuard<'_, HashMap<(Type, Settings), Option<String>>> {
214        self.0.lock().unwrap_or_else(PoisonError::into_inner)
215    }
216}
217
218/// A declaration's names, indexed once for each spelling decoding reads
219/// them in.
220#[derive(Clone, Debug)]
221struct Names {
222    exact: NameIndex,
223    /// `None` when two of its names share a relaxed key, which judging
224    /// refuses before any text is read.
225    relaxed: Option<NameIndex>,
226}
227
228impl Names {
229    fn of(decls: &[Decl]) -> Vec<Names> {
230        decls
231            .iter()
232            .map(|decl| Names {
233                exact: NameIndex::of(&decl.body, Spelling::Exact)
234                    .expect("a declaration's names are distinct"),
235                relaxed: NameIndex::of(&decl.body, Spelling::Relaxed).ok(),
236            })
237            .collect()
238    }
239}
240
241/// A std enum the encoding builds values of itself, with its constructors
242/// of `C` bound once.
243#[derive(Clone, Debug)]
244pub(crate) struct Bound<C> {
245    pub(crate) shape: Arc<EnumShape>,
246    pub(crate) ctors: StdEnum<C>,
247}
248
249impl<C: Members> Bound<C> {
250    fn of(shape: Arc<EnumShape>) -> Result<Self, Mismatch> {
251        Ok(Bound {
252            ctors: StdEnum::of(&shape)?,
253            shape,
254        })
255    }
256}
257
258/// The shape std declares the enum that plays `role` with, as the bundled
259/// std's sources give it ([`Role::shape`]).
260///
261/// # Panics
262///
263/// When std declares no enum for `role`.
264pub fn std_enum(role: Role) -> Arc<EnumShape> {
265    match role.shape() {
266        Some(Shape::Enum(shape)) => shape,
267        _ => panic!("std declares no enum for {role:?}"),
268    }
269}
270
271/// How a type parameter on the left of [`Catalog::matches`] matches a
272/// type of the other catalog.
273pub trait Params {
274    /// Whether the type parameter numbered `index` matches `other_ty`, a
275    /// type of `other`.
276    fn matches(&mut self, index: u32, other: &Catalog, other_ty: &Type) -> bool;
277}
278
279/// A type parameter matches only the same type parameter, as it does
280/// between two declarations of one generic signature.
281#[derive(Clone, Copy, Debug)]
282pub struct Exact;
283
284impl Params for Exact {
285    fn matches(&mut self, index: u32, _: &Catalog, other_ty: &Type) -> bool {
286        matches!(other_ty, Type::Param(other_index) if *other_index == index)
287    }
288}
289
290/// Each type parameter is fixed to one type of the other catalog wherever
291/// it appears, as a call to a generic declaration fixes it
292/// (`types.md`, *Generics*).
293#[derive(Clone, Debug, Default)]
294pub struct Fixing {
295    fixed: std::collections::BTreeMap<u32, Type>,
296}
297
298impl Params for Fixing {
299    fn matches(&mut self, index: u32, other: &Catalog, other_ty: &Type) -> bool {
300        match self.fixed.entry(index) {
301            std::collections::btree_map::Entry::Occupied(fixed) => {
302                other.same(fixed.get(), other, other_ty)
303            }
304            std::collections::btree_map::Entry::Vacant(free) => {
305                free.insert(other_ty.clone());
306                true
307            }
308        }
309    }
310}
311
312impl Catalog {
313    /// Returns the catalog of `decls`, where the `n`th is [`DeclId`] `n`,
314    /// with std's `Option` (`None`, `Some(T)`) and, when the program has it,
315    /// `json.Value`.
316    ///
317    /// # Errors
318    ///
319    /// When either shape lacks a constructor std declares, or when a
320    /// declaration's recursion is not regular (`types.md`, *Recursive
321    /// types*), which every judgment of the catalog's types relies on to end.
322    pub fn new(
323        decls: Vec<Decl>,
324        option: Arc<EnumShape>,
325        json: Option<Arc<EnumShape>>,
326    ) -> Result<Self, DecodeError> {
327        let lacking = |mismatch: Mismatch| crate::metadata::fail(mismatch.to_string());
328        let option = Bound::of(option).map_err(lacking)?;
329        let json = json.map(Bound::of).transpose().map_err(lacking)?;
330        crate::metadata::regular(&decls)?;
331        Ok(Catalog {
332            names: Names::of(&decls),
333            decls,
334            judged: Judged::default(),
335            option,
336            json,
337        })
338    }
339
340    /// The catalog of `decls`, with the `Option` and `json.Value` shapes
341    /// of the bundled std ([`std_enum`]), whose tests hold them to the
342    /// constructors the encoding builds.
343    ///
344    /// # Errors
345    ///
346    /// When a declaration's recursion is not regular, as [`Catalog::new`].
347    pub fn std(decls: Vec<Decl>) -> Result<Catalog, DecodeError> {
348        Catalog::new(
349            decls,
350            std_enum(Role::Option),
351            Some(std_enum(Role::JsonValue)),
352        )
353    }
354
355    /// This catalog with `more` declared after its own declarations,
356    /// numbered on from them.
357    pub(crate) fn extended(&self, more: Vec<Decl>) -> Catalog {
358        let mut decls = self.decls.clone();
359        decls.extend(more);
360        Catalog {
361            names: Names::of(&decls),
362            decls,
363            judged: Judged::default(),
364            option: self.option.clone(),
365            json: self.json.clone(),
366        }
367    }
368
369    /// The declaration `id` names.
370    ///
371    /// # Panics
372    ///
373    /// When `id` is not one of this catalog's.
374    pub fn decl(&self, id: DeclId) -> &Decl {
375        &self.decls[crate::bytes::index(id.0)]
376    }
377
378    /// Every declaration, by id.
379    ///
380    /// # Panics
381    ///
382    /// When the catalog holds more declarations than a 32-bit id numbers.
383    pub fn decls(&self) -> impl ExactSizeIterator<Item = (DeclId, &Decl)> {
384        self.decls.iter().enumerate().map(|(index, decl)| {
385            (
386                DeclId(u32::try_from(index).expect("a catalog fits 32-bit ids")),
387                decl,
388            )
389        })
390    }
391
392    /// Whether `ty`, named in this catalog, is the type `other_ty` is in
393    /// `other`: the same former over the same parts, each declared type
394    /// known by its identity and ordinal, so that a newtype is never its
395    /// base (`types.md`, *Erasure*).
396    pub fn same(&self, ty: &Type, other: &Catalog, other_ty: &Type) -> bool {
397        self.matches(ty, other, other_ty, &mut Exact)
398    }
399
400    /// Whether `ty`, named in this catalog, is the type `other_ty` is in
401    /// `other`, as [`Catalog::same`] compares them, except that each type
402    /// parameter of `ty` matches as `params` decides.
403    pub fn matches(
404        &self,
405        ty: &Type,
406        other: &Catalog,
407        other_ty: &Type,
408        params: &mut impl Params,
409    ) -> bool {
410        let mut todo = vec![(ty, other_ty)];
411        while let Some((ty, other_ty)) = todo.pop() {
412            if let Type::Param(index) = ty {
413                if !params.matches(*index, other, other_ty) {
414                    return false;
415                }
416                continue;
417            }
418            let named_alike = match (ty, other_ty) {
419                (Type::Named(decl, _), Type::Named(other_decl, _)) => {
420                    let (declared, other_declared) = (self.decl(*decl), other.decl(*other_decl));
421                    declared.identity == other_declared.identity
422                        && declared.lexical_ordinal == other_declared.lexical_ordinal
423                }
424                (Type::NotData, _) => false,
425                _ => true,
426            };
427            let alike = named_alike
428                && std::mem::discriminant(ty) == std::mem::discriminant(other_ty)
429                && ty.parts().count() == other_ty.parts().count();
430            if !alike {
431                return false;
432            }
433            todo.extend(ty.parts().rev().zip(other_ty.parts().rev()));
434        }
435        true
436    }
437
438    /// The erasure of `ty`: `ty` itself when it is no newtype, and
439    /// otherwise the erasure of its base at its arguments (`types.md`,
440    /// *Erasure*). Every rule that reads a position's type reads this.
441    ///
442    /// A cycle of newtypes, which the checker and a description's
443    /// validation both refuse, erases to [`Type::NotData`].
444    pub fn erase<'t>(&self, ty: &'t Type) -> Cow<'t, Type> {
445        let mut current = Cow::Borrowed(ty);
446        for _ in 0..=self.decls.len() {
447            let Type::Named(decl, args) = &*current else {
448                return current;
449            };
450            let Body::Newtype(base) = &self.decl(*decl).body else {
451                return current;
452            };
453            current = Cow::Owned(base.subst(args));
454        }
455        Cow::Owned(Type::NotData)
456    }
457
458    /// The form a value of `ty` is held to: that of the std type with a
459    /// form ([`StdForm::of`]) that `ty` is, or erases through on the way
460    /// to its erasure, if any.
461    pub fn std_form(&self, ty: &Type) -> Option<StdForm> {
462        let mut current = Cow::Borrowed(ty);
463        for _ in 0..=self.decls.len() {
464            let Type::Named(decl, args) = &*current else {
465                break;
466            };
467            let decl = self.decl(*decl);
468            if let Some(form) = StdForm::of(decl) {
469                return Some(form);
470            }
471            let Body::Newtype(base) = &decl.body else {
472                break;
473            };
474            current = Cow::Owned(base.subst(args));
475        }
476        None
477    }
478
479    /// The first part of `ty` a judgment under `settings` refuses, as
480    /// decoding words it, if any. A type parameter the judgment reaches is
481    /// unbound, so a value of it has no encoding.
482    pub(crate) fn problem(&self, ty: &Type, settings: Settings) -> Option<String> {
483        let key = (ty.clone(), settings);
484        if let Some(problem) = self.judged.entries().get(&key) {
485            return problem.clone();
486        }
487        let mut unbound = false;
488        let problem = match judge(&self.decls, ty, settings, &mut |_, _| unbound = true) {
489            Some(refusal) => Some(match refusal.reason {
490                Reason::Opaque => format!(
491                    "has the type {}, which is opaque, so it can't be decoded",
492                    self.declared(&refusal.part)
493                ),
494                Reason::Host => format!(
495                    "has the host type {}, which a run's input can't carry",
496                    self.declared(&refusal.part)
497                ),
498                Reason::SharedKey => {
499                    let decl = self.decl_of(&refusal.part);
500                    let shared = NameIndex::of(&decl.body, Spelling::Relaxed).expect_err(
501                        "the judge refuses only a declaration whose relaxed keys collide",
502                    );
503                    format!(
504                        "has the type {}, whose names `{}` and `{}` share the relaxed key `{}`",
505                        decl.identity, shared.first, shared.second, shared.key
506                    )
507                }
508                Reason::JsonValue | Reason::OptionalJson => {
509                    "has an Option<json.Value> part, which cannot cross a boundary".into()
510                }
511                Reason::Function | Reason::Task | Reason::NotData => no_encoding(),
512            }),
513            None => unbound.then(no_encoding),
514        };
515        self.judged.entries().insert(key, problem.clone());
516        problem
517    }
518
519    /// The names `decl` declares, indexed by their key in `mode`.
520    ///
521    /// # Panics
522    ///
523    /// When `mode` reads relaxed keys and two of `decl`'s names share one:
524    /// judging refuses every type that reaches it before decoding begins.
525    pub(crate) fn names(&self, decl: DeclId, mode: Mode) -> &NameIndex {
526        let names = &self.names[crate::bytes::index(decl.0)];
527        match mode.spelling() {
528            Spelling::Exact => &names.exact,
529            Spelling::Relaxed => names
530                .relaxed
531                .as_ref()
532                .expect("judging refuses a declaration whose relaxed keys collide"),
533        }
534    }
535
536    /// The identity of the declared type `part` applies.
537    fn declared(&self, part: &Type) -> &flow_types::Identity {
538        &self.decl_of(part).identity
539    }
540
541    /// The declaration the declared type `part` applies.
542    fn decl_of(&self, part: &Type) -> &Decl {
543        let Type::Named(decl, _) = part else {
544            unreachable!("only a declared type is refused for what it declares")
545        };
546        self.decl(*decl)
547    }
548
549    pub(crate) fn option(&self) -> &Bound<OptionCtor> {
550        &self.option
551    }
552
553    /// std's `None`: the value of every type that erases to an `Option`
554    /// and is absent.
555    ///
556    /// # Panics
557    ///
558    /// Never: `None` is a case of std's `Option` that carries nothing.
559    pub fn none(&self) -> Value {
560        Value::Variant(
561            Variant::new(
562                Arc::clone(&self.option.shape),
563                self.option.ctors.index(OptionCtor::None),
564                Vec::new(),
565            )
566            .expect("None carries nothing"),
567        )
568    }
569
570    /// std's `Some(value)`.
571    ///
572    /// # Panics
573    ///
574    /// Never: `Some` is a case of std's `Option` that carries one value.
575    pub fn some(&self, value: Value) -> Value {
576        Value::Variant(
577            Variant::new(
578                Arc::clone(&self.option.shape),
579                self.option.ctors.index(OptionCtor::Some),
580                vec![value],
581            )
582            .expect("Some carries one value"),
583        )
584    }
585
586    pub(crate) fn json(&self) -> &Bound<JsonValueCtor> {
587        self.json
588            .as_ref()
589            .expect("a program that names json.Value has std's json module")
590    }
591
592    /// How `ty` is written in a schema's `$defs` key and in messages:
593    /// built-in types by name, declarations by identity, with arguments.
594    pub fn name(&self, ty: &Type) -> String {
595        self.written(ty, Versions::Shown)
596    }
597
598    /// `ty` written as [`Catalog::name`] writes it, with or without each
599    /// declaration's repository version.
600    ///
601    /// It writes over a stack on the heap, each type's text once, in the
602    /// order it is read.
603    pub(crate) fn written(&self, ty: &Type, versions: Versions) -> String {
604        enum Next<'t> {
605            Type(&'t Type),
606            Text(&'static str),
607        }
608        let mut out = String::new();
609        let mut todo = vec![Next::Type(ty)];
610        while let Some(next) = todo.pop() {
611            let ty = match next {
612                Next::Text(text) => {
613                    out.push_str(text);
614                    continue;
615                }
616                Next::Type(ty) => ty,
617            };
618            let (open, close) = match ty {
619                Type::Int => ("Int", ""),
620                Type::Decimal => ("Decimal", ""),
621                Type::Bool => ("Bool", ""),
622                Type::Text => ("Text", ""),
623                Type::Bytes => ("Bytes", ""),
624                Type::Duration => ("Duration", ""),
625                Type::Instant => ("Instant", ""),
626                Type::Unit => ("Unit", ""),
627                Type::Never => ("Never", ""),
628                Type::Json => ("json.Value", ""),
629                Type::List(_) => ("List<", ">"),
630                Type::Set(_) => ("Set<", ">"),
631                Type::Option(_) => ("Option<", ">"),
632                Type::Task(_) => ("task.Task<", ">"),
633                Type::Dict(..) => ("Dict<", ">"),
634                Type::Tuple(_) | Type::Function { .. } => ("(", ""),
635                Type::Named(decl, args) => {
636                    let declared = self.decl(*decl);
637                    out.push_str(&declared.identity.written(versions));
638                    if declared.lexical_ordinal > 1 {
639                        write!(out, "#{}", declared.lexical_ordinal).expect("writing to a string");
640                    }
641                    if args.is_empty() {
642                        ("", "")
643                    } else {
644                        ("<", ">")
645                    }
646                }
647                Type::Param(index) => {
648                    write!(out, "${index}").expect("writing to a string");
649                    ("", "")
650                }
651                Type::NotData => ("a type that is not data", ""),
652            };
653            out.push_str(open);
654            todo.push(Next::Text(close));
655            let mut parts: Vec<&Type> = ty.parts().collect();
656            if let Type::Function { .. } = ty {
657                let result = parts.pop().expect("a function type has a result");
658                todo.push(Next::Type(result));
659                todo.push(Next::Text(") -> "));
660            } else if let Type::Tuple(_) = ty {
661                todo.push(Next::Text(")"));
662            }
663            for (at, part) in parts.into_iter().enumerate().rev() {
664                todo.push(Next::Type(part));
665                if at > 0 {
666                    todo.push(Next::Text(", "));
667                }
668            }
669        }
670        out
671    }
672}
673
674fn no_encoding() -> String {
675    "has a type with no encoding".into()
676}
677
678/// Whether an existing value can cross a Tool boundary. Opaque values and
679/// host tokens may be sent; functions, tasks, nondata and ambiguous
680/// `Option<json.Value>` parts may not. Nominal arguments unused by fields
681/// are descriptions rather than value parts.
682///
683/// # Errors
684///
685/// A [`DecodeError`] naming the first part of `ty` that may not cross.
686pub fn crossable(catalog: &Catalog, ty: &Type) -> Result<(), DecodeError> {
687    crate::decodable(catalog, ty, CROSSING)
688}