flow-abi 0.1.0-rc.5

The host boundary's value encoding: the binary encoding and the JSON form, the canonical form and its hash, JSON Schemas, Tool signatures, and the answers a Tool call passes.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
//! The catalog the encoding reads declared types in, and the std types held
//! to forms of their own.
//!
//! A [`Catalog`] keeps a program's declarations by [`DeclId`], their names
//! indexed once when it is built ([`NameIndex`]), with what
//! [`flow_types::judge`] has said of the types decoding asked about, and the
//! shapes of std's
//! `Option` and `json.Value`, whose values the encoding builds itself. A
//! [`StdForm`] is the normal form decoding holds `path.Path`, `url.Url`,
//! `media.MediaType`, `code.RunId` and `code.TaskPath` to.

use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt::Write as _;
use std::sync::{Arc, Mutex, PoisonError};

use flow_span::{RunId, TaskPath};
use flow_types::{
    Body, Decl, DeclId, EnumShape, JsonValueCtor, Members, Mismatch, NameIndex, Nested, OptionCtor,
    Reason, Role, Settings, Shape, Spelling, StdEnum, Tree, Type, Versions, judge,
};
use flow_value::{Value, Variant};

use crate::DecodeError;
use crate::decode::{CROSSING, Mode};
use crate::form::{Form, form};
use crate::json::quote;

/// A std type over `Text` whose values are held to a form of their own.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum StdForm {
    /// `path.Path`: any text names a path, in its normal form.
    Path,
    /// `url.Url`: a URI by RFC 3986, in the normal form of its ยง6.2.2.
    Url,
    /// `media.MediaType`: a media type by RFC 9110, in its normal form.
    MediaType,
    /// `code.RunId`: a run's id, 32 lowercase hexadecimal digits
    /// (`history.md`, *Keys*), its own normal form.
    RunId,
    /// `code.TaskPath`: a task's id, `root` and then `/` and a positive count
    /// any number of times (`history.md`, *Identity*), its own normal form.
    TaskPath,
}

impl StdForm {
    /// The form of its own `decl`'s values are held to, when it is one of
    /// the std types that have one (`stdlib.md`, *`@lang`
    /// declarations*): JSON decoding reads any spelling of the form as the
    /// one value it denotes, and binary decoding accepts only the normal
    /// text (`abi.md`, *Decoding*). It is known by its std identity alone.
    pub fn of(decl: &Decl) -> Option<StdForm> {
        let identity = &decl.identity;
        if *identity.origin.tree() != Tree::Std || identity.version.as_deref() != Some("v1") {
            return None;
        }
        let role = Role::of(identity.origin.module().as_str(), identity.name.as_str())?;
        [
            StdForm::Path,
            StdForm::Url,
            StdForm::MediaType,
            StdForm::RunId,
            StdForm::TaskPath,
        ]
        .into_iter()
        .find(|form| form.role() == role)
    }

    /// The role std marks its type with.
    pub fn role(self) -> Role {
        match self {
            StdForm::Path => Role::Path,
            StdForm::Url => Role::Url,
            StdForm::MediaType => Role::MediaType,
            StdForm::RunId => Role::RunId,
            StdForm::TaskPath => Role::TaskPath,
        }
    }

    /// The normal text of the value `text` spells, or `None` when it spells
    /// none.
    pub fn normal(self, text: &str) -> Option<String> {
        match self {
            StdForm::Path => Some(flow_types::normal_path(text)),
            StdForm::Url => crate::url::normal_url(text),
            StdForm::MediaType => crate::media::normal_media_type(text),
            StdForm::RunId => RunId::parse(text).ok().map(|run| run.to_string()),
            StdForm::TaskPath => TaskPath::parse(text).ok().map(|task| task.to_string()),
        }
    }

    /// The value of this form `text` spells, held as its normal text, or
    /// `None` when it spells none: the one way std makes a value of it, so
    /// every value of a form is in it and [`StdForm::out_of`] finds nothing
    /// in what a run made.
    pub fn make(self, text: &str) -> Option<Value> {
        self.normal(text).map(|normal| Value::Text(normal.into()))
    }

    /// Why `text` is not a value of this form written as its normal text,
    /// or `None` when it is: the one encoding such a value has (`abi.md`,
    /// *Decoding*).
    pub fn refusal(self, text: &str) -> Option<String> {
        match self.normal(text) {
            Some(normal) if normal == text => None,
            Some(normal) => Some(format!(
                "is {} written {}, which is not its normal form {}",
                self.noun(),
                quote(text),
                quote(&normal)
            )),
            None => Some(format!("is {}, which is not {}", quote(text), self.noun())),
        }
    }

    /// Why `value`, a value of a newtype held to `form`, is out of it, or
    /// `None` when it is in it or the newtype has no form: the one check
    /// every walker that writes or reads such a value makes, so that no
    /// encoder writes what a decoder refuses.
    pub fn out_of(form: Option<StdForm>, value: &Value) -> Option<String> {
        match (form, value) {
            (Some(form), Value::Text(text)) => form.refusal(text.as_str()),
            _ => None,
        }
    }

    /// Why a value `value` holds anywhere, read at `ty`, is out of the form
    /// its newtype holds it to, the first in a walk of the value, or `None`
    /// when every one is in its form: the check a store that keeps such a
    /// value as its erasure, a `Text`, makes of the whole value, since the
    /// erasure alone cannot tell.
    pub fn first_out_of(catalog: &Catalog, ty: &Type, value: &Value) -> Option<String> {
        let mut pending: Vec<(Type, &Value)> = vec![(ty.clone(), value)];
        while let Some((ty, value)) = pending.pop() {
            match (form(catalog, &ty), value) {
                (Form::Newtype(base, held), _) => {
                    if let Some(problem) = StdForm::out_of(held, value) {
                        return Some(problem);
                    }
                    pending.push((base, value));
                }
                (Form::List(item), Value::List(items)) => {
                    pending.extend(items.iter().map(|part| (item.clone(), part)));
                }
                (Form::Set(item), Value::Set(items)) => {
                    pending.extend(items.iter().map(|part| (item.clone(), part)));
                }
                (Form::Dict(key, item), Value::Dict(entries)) => {
                    for (k, v) in entries.iter() {
                        pending.push((key.clone(), k));
                        pending.push((item.clone(), v));
                    }
                }
                (Form::Tuple(parts), Value::Tuple(tuple)) => {
                    pending.extend(parts.iter().cloned().zip(tuple.parts()));
                }
                (Form::Record(record), Value::Record(fields)) => {
                    pending.extend(record.fields.into_iter().zip(fields.fields()));
                }
                (Form::Enum(shape), Value::Variant(variant)) => {
                    let parts = shape.parts(variant.index()).unwrap_or_default();
                    pending.extend(
                        parts
                            .into_iter()
                            .map(Cow::into_owned)
                            .zip(variant.payload()),
                    );
                }
                _ => {}
            }
        }
        None
    }

    /// What a value of it is, for a refusal: "a path".
    pub(crate) fn noun(self) -> &'static str {
        match self {
            StdForm::Path => "a path",
            StdForm::Url => "a URL",
            StdForm::MediaType => "a media type",
            StdForm::RunId => "a run's id",
            StdForm::TaskPath => "a task's id",
        }
    }
}

/// The declarations a set of types names, with the std enums whose values
/// the encoding builds itself.
#[derive(Clone, Debug)]
pub struct Catalog {
    decls: Vec<Decl>,
    judged: Judged,
    names: Vec<Names>,
    option: Bound<OptionCtor>,
    json: Option<Bound<JsonValueCtor>>,
}

/// What [`judge`] said of each type decoding has asked about, under the
/// settings it asked with, as decoding words it. It is a cache of that one
/// judgment, kept only so that the check each decode makes first costs a
/// lookup: an entry is what a fresh walk of its type would say, since the
/// declarations it was judged over never change.
#[derive(Debug, Default)]
struct Judged(Mutex<HashMap<(Type, Settings), Option<String>>>);

impl Clone for Judged {
    fn clone(&self) -> Self {
        Judged(Mutex::new(self.entries().clone()))
    }
}

impl Judged {
    fn entries(&self) -> std::sync::MutexGuard<'_, HashMap<(Type, Settings), Option<String>>> {
        self.0.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

/// A declaration's names, indexed once for each spelling decoding reads
/// them in.
#[derive(Clone, Debug)]
struct Names {
    exact: NameIndex,
    /// `None` when two of its names share a relaxed key, which judging
    /// refuses before any text is read.
    relaxed: Option<NameIndex>,
}

impl Names {
    fn of(decls: &[Decl]) -> Vec<Names> {
        decls
            .iter()
            .map(|decl| Names {
                exact: NameIndex::of(&decl.body, Spelling::Exact)
                    .expect("a declaration's names are distinct"),
                relaxed: NameIndex::of(&decl.body, Spelling::Relaxed).ok(),
            })
            .collect()
    }
}

/// A std enum the encoding builds values of itself, with its constructors
/// of `C` bound once.
#[derive(Clone, Debug)]
pub(crate) struct Bound<C> {
    pub(crate) shape: Arc<EnumShape>,
    pub(crate) ctors: StdEnum<C>,
}

impl<C: Members> Bound<C> {
    fn of(shape: Arc<EnumShape>) -> Result<Self, Mismatch> {
        Ok(Bound {
            ctors: StdEnum::of(&shape)?,
            shape,
        })
    }
}

/// The shape std declares the enum that plays `role` with, as the bundled
/// std's sources give it ([`Role::shape`]).
///
/// # Panics
///
/// When std declares no enum for `role`.
pub fn std_enum(role: Role) -> Arc<EnumShape> {
    match role.shape() {
        Some(Shape::Enum(shape)) => shape,
        _ => panic!("std declares no enum for {role:?}"),
    }
}

/// How a type parameter on the left of [`Catalog::matches`] matches a
/// type of the other catalog.
pub trait Params {
    /// Whether the type parameter numbered `index` matches `other_ty`, a
    /// type of `other`.
    fn matches(&mut self, index: u32, other: &Catalog, other_ty: &Type) -> bool;
}

/// A type parameter matches only the same type parameter, as it does
/// between two declarations of one generic signature.
#[derive(Clone, Copy, Debug)]
pub struct Exact;

impl Params for Exact {
    fn matches(&mut self, index: u32, _: &Catalog, other_ty: &Type) -> bool {
        matches!(other_ty, Type::Param(other_index) if *other_index == index)
    }
}

/// Each type parameter is fixed to one type of the other catalog wherever
/// it appears, as a call to a generic declaration fixes it
/// (`types.md`, *Generics*).
#[derive(Clone, Debug, Default)]
pub struct Fixing {
    fixed: std::collections::BTreeMap<u32, Type>,
}

impl Params for Fixing {
    fn matches(&mut self, index: u32, other: &Catalog, other_ty: &Type) -> bool {
        match self.fixed.entry(index) {
            std::collections::btree_map::Entry::Occupied(fixed) => {
                other.same(fixed.get(), other, other_ty)
            }
            std::collections::btree_map::Entry::Vacant(free) => {
                free.insert(other_ty.clone());
                true
            }
        }
    }
}

impl Catalog {
    /// Returns the catalog of `decls`, where the `n`th is [`DeclId`] `n`,
    /// with std's `Option` (`None`, `Some(T)`) and, when the program has it,
    /// `json.Value`.
    ///
    /// # Errors
    ///
    /// When either shape lacks a constructor std declares, or when a
    /// declaration's recursion is not regular (`types.md`, *Recursive
    /// types*), which every judgment of the catalog's types relies on to end.
    pub fn new(
        decls: Vec<Decl>,
        option: Arc<EnumShape>,
        json: Option<Arc<EnumShape>>,
    ) -> Result<Self, DecodeError> {
        let lacking = |mismatch: Mismatch| crate::metadata::fail(mismatch.to_string());
        let option = Bound::of(option).map_err(lacking)?;
        let json = json.map(Bound::of).transpose().map_err(lacking)?;
        crate::metadata::regular(&decls)?;
        Ok(Catalog {
            names: Names::of(&decls),
            decls,
            judged: Judged::default(),
            option,
            json,
        })
    }

    /// The catalog of `decls`, with the `Option` and `json.Value` shapes
    /// of the bundled std ([`std_enum`]), whose tests hold them to the
    /// constructors the encoding builds.
    ///
    /// # Errors
    ///
    /// When a declaration's recursion is not regular, as [`Catalog::new`].
    pub fn std(decls: Vec<Decl>) -> Result<Catalog, DecodeError> {
        Catalog::new(
            decls,
            std_enum(Role::Option),
            Some(std_enum(Role::JsonValue)),
        )
    }

    /// This catalog with `more` declared after its own declarations,
    /// numbered on from them.
    pub(crate) fn extended(&self, more: Vec<Decl>) -> Catalog {
        let mut decls = self.decls.clone();
        decls.extend(more);
        Catalog {
            names: Names::of(&decls),
            decls,
            judged: Judged::default(),
            option: self.option.clone(),
            json: self.json.clone(),
        }
    }

    /// The declaration `id` names.
    ///
    /// # Panics
    ///
    /// When `id` is not one of this catalog's.
    pub fn decl(&self, id: DeclId) -> &Decl {
        &self.decls[crate::bytes::index(id.0)]
    }

    /// Every declaration, by id.
    ///
    /// # Panics
    ///
    /// When the catalog holds more declarations than a 32-bit id numbers.
    pub fn decls(&self) -> impl ExactSizeIterator<Item = (DeclId, &Decl)> {
        self.decls.iter().enumerate().map(|(index, decl)| {
            (
                DeclId(u32::try_from(index).expect("a catalog fits 32-bit ids")),
                decl,
            )
        })
    }

    /// Whether `ty`, named in this catalog, is the type `other_ty` is in
    /// `other`: the same former over the same parts, each declared type
    /// known by its identity and ordinal, so that a newtype is never its
    /// base (`types.md`, *Erasure*).
    pub fn same(&self, ty: &Type, other: &Catalog, other_ty: &Type) -> bool {
        self.matches(ty, other, other_ty, &mut Exact)
    }

    /// Whether `ty`, named in this catalog, is the type `other_ty` is in
    /// `other`, as [`Catalog::same`] compares them, except that each type
    /// parameter of `ty` matches as `params` decides.
    pub fn matches(
        &self,
        ty: &Type,
        other: &Catalog,
        other_ty: &Type,
        params: &mut impl Params,
    ) -> bool {
        let mut todo = vec![(ty, other_ty)];
        while let Some((ty, other_ty)) = todo.pop() {
            if let Type::Param(index) = ty {
                if !params.matches(*index, other, other_ty) {
                    return false;
                }
                continue;
            }
            let named_alike = match (ty, other_ty) {
                (Type::Named(decl, _), Type::Named(other_decl, _)) => {
                    let (declared, other_declared) = (self.decl(*decl), other.decl(*other_decl));
                    declared.identity == other_declared.identity
                        && declared.lexical_ordinal == other_declared.lexical_ordinal
                }
                (Type::NotData, _) => false,
                _ => true,
            };
            let alike = named_alike
                && std::mem::discriminant(ty) == std::mem::discriminant(other_ty)
                && ty.parts().count() == other_ty.parts().count();
            if !alike {
                return false;
            }
            todo.extend(ty.parts().rev().zip(other_ty.parts().rev()));
        }
        true
    }

    /// The erasure of `ty`: `ty` itself when it is no newtype, and
    /// otherwise the erasure of its base at its arguments (`types.md`,
    /// *Erasure*). Every rule that reads a position's type reads this.
    ///
    /// A cycle of newtypes, which the checker and a description's
    /// validation both refuse, erases to [`Type::NotData`].
    pub fn erase<'t>(&self, ty: &'t Type) -> Cow<'t, Type> {
        let mut current = Cow::Borrowed(ty);
        for _ in 0..=self.decls.len() {
            let Type::Named(decl, args) = &*current else {
                return current;
            };
            let Body::Newtype(base) = &self.decl(*decl).body else {
                return current;
            };
            current = Cow::Owned(base.subst(args));
        }
        Cow::Owned(Type::NotData)
    }

    /// The form a value of `ty` is held to: that of the std type with a
    /// form ([`StdForm::of`]) that `ty` is, or erases through on the way
    /// to its erasure, if any.
    pub fn std_form(&self, ty: &Type) -> Option<StdForm> {
        let mut current = Cow::Borrowed(ty);
        for _ in 0..=self.decls.len() {
            let Type::Named(decl, args) = &*current else {
                break;
            };
            let decl = self.decl(*decl);
            if let Some(form) = StdForm::of(decl) {
                return Some(form);
            }
            let Body::Newtype(base) = &decl.body else {
                break;
            };
            current = Cow::Owned(base.subst(args));
        }
        None
    }

    /// The first part of `ty` a judgment under `settings` refuses, as
    /// decoding words it, if any. A type parameter the judgment reaches is
    /// unbound, so a value of it has no encoding.
    pub(crate) fn problem(&self, ty: &Type, settings: Settings) -> Option<String> {
        let key = (ty.clone(), settings);
        if let Some(problem) = self.judged.entries().get(&key) {
            return problem.clone();
        }
        let mut unbound = false;
        let problem = match judge(&self.decls, ty, settings, &mut |_, _| unbound = true) {
            Some(refusal) => Some(match refusal.reason {
                Reason::Opaque => format!(
                    "has the type {}, which is opaque, so it can't be decoded",
                    self.declared(&refusal.part)
                ),
                Reason::Host => format!(
                    "has the host type {}, which a run's input can't carry",
                    self.declared(&refusal.part)
                ),
                Reason::SharedKey => {
                    let decl = self.decl_of(&refusal.part);
                    let shared = NameIndex::of(&decl.body, Spelling::Relaxed).expect_err(
                        "the judge refuses only a declaration whose relaxed keys collide",
                    );
                    format!(
                        "has the type {}, whose names `{}` and `{}` share the relaxed key `{}`",
                        decl.identity, shared.first, shared.second, shared.key
                    )
                }
                Reason::JsonValue | Reason::OptionalJson => {
                    "has an Option<json.Value> part, which cannot cross a boundary".into()
                }
                Reason::Function | Reason::Task | Reason::NotData => no_encoding(),
            }),
            None => unbound.then(no_encoding),
        };
        self.judged.entries().insert(key, problem.clone());
        problem
    }

    /// The names `decl` declares, indexed by their key in `mode`.
    ///
    /// # Panics
    ///
    /// When `mode` reads relaxed keys and two of `decl`'s names share one:
    /// judging refuses every type that reaches it before decoding begins.
    pub(crate) fn names(&self, decl: DeclId, mode: Mode) -> &NameIndex {
        let names = &self.names[crate::bytes::index(decl.0)];
        match mode.spelling() {
            Spelling::Exact => &names.exact,
            Spelling::Relaxed => names
                .relaxed
                .as_ref()
                .expect("judging refuses a declaration whose relaxed keys collide"),
        }
    }

    /// The identity of the declared type `part` applies.
    fn declared(&self, part: &Type) -> &flow_types::Identity {
        &self.decl_of(part).identity
    }

    /// The declaration the declared type `part` applies.
    fn decl_of(&self, part: &Type) -> &Decl {
        let Type::Named(decl, _) = part else {
            unreachable!("only a declared type is refused for what it declares")
        };
        self.decl(*decl)
    }

    pub(crate) fn option(&self) -> &Bound<OptionCtor> {
        &self.option
    }

    /// std's `None`: the value of every type that erases to an `Option`
    /// and is absent.
    ///
    /// # Panics
    ///
    /// Never: `None` is a case of std's `Option` that carries nothing.
    pub fn none(&self) -> Value {
        Value::Variant(
            Variant::new(
                Arc::clone(&self.option.shape),
                self.option.ctors.index(OptionCtor::None),
                Vec::new(),
            )
            .expect("None carries nothing"),
        )
    }

    /// std's `Some(value)`.
    ///
    /// # Panics
    ///
    /// Never: `Some` is a case of std's `Option` that carries one value.
    pub fn some(&self, value: Value) -> Value {
        Value::Variant(
            Variant::new(
                Arc::clone(&self.option.shape),
                self.option.ctors.index(OptionCtor::Some),
                vec![value],
            )
            .expect("Some carries one value"),
        )
    }

    pub(crate) fn json(&self) -> &Bound<JsonValueCtor> {
        self.json
            .as_ref()
            .expect("a program that names json.Value has std's json module")
    }

    /// How `ty` is written in a schema's `$defs` key and in messages:
    /// built-in types by name, declarations by identity, with arguments.
    pub fn name(&self, ty: &Type) -> String {
        self.written(ty, Versions::Shown)
    }

    /// `ty` written as [`Catalog::name`] writes it, with or without each
    /// declaration's repository version.
    ///
    /// It writes over a stack on the heap, each type's text once, in the
    /// order it is read.
    pub(crate) fn written(&self, ty: &Type, versions: Versions) -> String {
        enum Next<'t> {
            Type(&'t Type),
            Text(&'static str),
        }
        let mut out = String::new();
        let mut todo = vec![Next::Type(ty)];
        while let Some(next) = todo.pop() {
            let ty = match next {
                Next::Text(text) => {
                    out.push_str(text);
                    continue;
                }
                Next::Type(ty) => ty,
            };
            let (open, close) = match ty {
                Type::Int => ("Int", ""),
                Type::Decimal => ("Decimal", ""),
                Type::Bool => ("Bool", ""),
                Type::Text => ("Text", ""),
                Type::Bytes => ("Bytes", ""),
                Type::Duration => ("Duration", ""),
                Type::Instant => ("Instant", ""),
                Type::Unit => ("Unit", ""),
                Type::Never => ("Never", ""),
                Type::Json => ("json.Value", ""),
                Type::List(_) => ("List<", ">"),
                Type::Set(_) => ("Set<", ">"),
                Type::Option(_) => ("Option<", ">"),
                Type::Task(_) => ("task.Task<", ">"),
                Type::Dict(..) => ("Dict<", ">"),
                Type::Tuple(_) | Type::Function { .. } => ("(", ""),
                Type::Named(decl, args) => {
                    let declared = self.decl(*decl);
                    out.push_str(&declared.identity.written(versions));
                    if declared.lexical_ordinal > 1 {
                        write!(out, "#{}", declared.lexical_ordinal).expect("writing to a string");
                    }
                    if args.is_empty() {
                        ("", "")
                    } else {
                        ("<", ">")
                    }
                }
                Type::Param(index) => {
                    write!(out, "${index}").expect("writing to a string");
                    ("", "")
                }
                Type::NotData => ("a type that is not data", ""),
            };
            out.push_str(open);
            todo.push(Next::Text(close));
            let mut parts: Vec<&Type> = ty.parts().collect();
            if let Type::Function { .. } = ty {
                let result = parts.pop().expect("a function type has a result");
                todo.push(Next::Type(result));
                todo.push(Next::Text(") -> "));
            } else if let Type::Tuple(_) = ty {
                todo.push(Next::Text(")"));
            }
            for (at, part) in parts.into_iter().enumerate().rev() {
                todo.push(Next::Type(part));
                if at > 0 {
                    todo.push(Next::Text(", "));
                }
            }
        }
        out
    }
}

fn no_encoding() -> String {
    "has a type with no encoding".into()
}

/// Whether an existing value can cross a Tool boundary. Opaque values and
/// host tokens may be sent; functions, tasks, nondata and ambiguous
/// `Option<json.Value>` parts may not. Nominal arguments unused by fields
/// are descriptions rather than value parts.
///
/// # Errors
///
/// A [`DecodeError`] naming the first part of `ty` that may not cross.
pub fn crossable(catalog: &Catalog, ty: &Type) -> Result<(), DecodeError> {
    crate::decodable(catalog, ty, CROSSING)
}