Skip to main content

flow_abi/
description.rs

1//! The type descriptions' own types (`abi.md`, *Type descriptions*),
2//! declared once: each is the bytes a description is written in, through its
3//! [`Wire`](crate::wire::Wire) codec, and the Flow type history stores one
4//! as, through [`Shape::project`](crate::wire::Shape::project).
5//!
6//! These are the bytes as they are, before they are checked against each
7//! other: [`crate::TypeSpec`], [`crate::ResultType`] and a call's validated
8//! types are a description read into these and then admitted.
9
10use std::hash::{Hash, Hasher};
11
12use flow_types::Identity as Declared;
13use flow_types::{Fold, ModulePath, Nested, Segments, SegmentsError, Tree};
14
15use flow_value::Int;
16
17use crate::wire;
18
19wire! {
20    /// A type term: a type with no name of its own, a declaration by its
21    /// place in the description with its arguments, or a type parameter.
22    #[derive(Debug)]
23    pub enum Term {
24        /// `Int`.
25        Int,
26        /// `Decimal`.
27        Decimal,
28        /// `Bool`.
29        Bool,
30        /// `Text`.
31        Text,
32        /// `Bytes`.
33        Bytes,
34        /// `Duration`.
35        Duration,
36        /// `Instant`.
37        Instant,
38        /// `Unit`.
39        Unit,
40        /// `Never`.
41        Never,
42        /// `json.Value`.
43        JsonValue,
44        /// `List` of this.
45        List(Box<Term>),
46        /// `Set` of this.
47        Set(Box<Term>),
48        /// `Option` of this.
49        Option(Box<Term>),
50        /// `task.Task` of this.
51        Task(Box<Term>),
52        /// `Dict` of these keys and values.
53        Dict(Box<Term>, Box<Term>),
54        /// A tuple of these parts, two or more.
55        Tuple(Vec<Term>),
56        /// A function.
57        Function {
58            /// Its parameters' terms.
59            params: Vec<Term>,
60            /// Its result's term.
61            result: Box<Term>,
62        },
63        /// A declaration.
64        Named {
65            /// Its template's place in the description.
66            declaration: Int,
67            /// Its arguments.
68            args: Vec<Term>,
69        },
70        /// A type parameter.
71        Param {
72            /// Whose parameter it is.
73            owner: Owner,
74            /// Its index among its owner's.
75            index: Int,
76        },
77    }
78}
79
80wire! {
81    /// Whose type parameter a `Param` term names.
82    #[derive(Clone, PartialEq, Eq, Hash, Debug)]
83    pub enum Owner {
84        /// The Tool's.
85        Tool,
86        /// The template's at this place.
87        Declaration(Int),
88    }
89}
90
91wire! {
92    /// An identity as a description writes it (`abi.md`, *Identity and
93    /// signatures*): the library that holds the declaration, the module
94    /// path in it and the declaration's name.
95    #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
96    pub struct Identity {
97        /// The library, or the tree for a module outside every library;
98        /// `None` for the local tree or a bundle.
99        pub library: Option<Library>,
100        /// The module path in the library or tree; empty for a root module.
101        pub module: String,
102        /// The declaration's name.
103        pub name: String,
104    }
105}
106
107wire! {
108    /// The library an [`Identity`] names.
109    #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
110    pub struct Library {
111        /// Its address: `std`, a repository's, or its root in the local
112        /// tree, `.` for the tree's root.
113        pub address: String,
114        /// The tag a remote import resolved, `v1` for std; `None` for a
115        /// library of the local tree.
116        pub version: Option<String>,
117    }
118}
119
120wire! {
121    /// One declaration a description reaches.
122    #[derive(Clone, PartialEq, Eq, Hash, Debug)]
123    pub struct Template {
124        /// Its name, which is its identity's.
125        pub name: String,
126        /// Its identity.
127        pub identity: Identity,
128        /// Which of the declarations of one identity it is, from 1.
129        pub lexical_ordinal: Int,
130        /// Its type parameters' names.
131        pub generic: Vec<String>,
132        /// Whether it is opaque.
133        pub opaque: bool,
134        /// Its doc comment.
135        pub doc: Option<String>,
136        /// What it declares.
137        pub body: Body,
138    }
139}
140
141wire! {
142    /// What a template declares.
143    #[derive(Clone, PartialEq, Eq, Hash, Debug)]
144    pub enum Body {
145        /// A record of these fields.
146        Record(Vec<Field>),
147        /// An enum of these constructors.
148        Enum(Vec<Constructor>),
149        /// A newtype over this base.
150        Newtype(Term),
151        /// A host type.
152        Host,
153        /// A type that is not data.
154        Nondata,
155    }
156}
157
158wire! {
159    /// A field of a record or of a named payload.
160    #[derive(Clone, PartialEq, Eq, Hash, Debug)]
161    pub struct Field {
162        /// Its name.
163        pub name: String,
164        /// Its term.
165        pub ty: Term,
166        /// Its doc comment.
167        pub doc: Option<String>,
168    }
169}
170
171wire! {
172    /// A constructor of an enum.
173    #[derive(Clone, PartialEq, Eq, Hash, Debug)]
174    pub struct Constructor {
175        /// Its name.
176        pub name: String,
177        /// Its doc comment.
178        pub doc: Option<String>,
179        /// Its payload.
180        pub payload: Payload,
181    }
182}
183
184wire! {
185    /// A constructor's payload.
186    #[derive(Clone, PartialEq, Eq, Hash, Debug)]
187    pub enum Payload {
188        /// None.
189        Empty,
190        /// Parts by position, of these terms.
191        Positional(Vec<Term>),
192        /// These named fields.
193        Named(Vec<Field>),
194    }
195}
196
197wire! {
198    /// A Tool's description.
199    #[derive(Clone, PartialEq, Eq, Hash, Debug)]
200    pub struct TypeSpec {
201        /// Its type parameters' names.
202        pub generic: Vec<String>,
203        /// Each parameter's key and term.
204        pub params: Vec<(String, Term)>,
205        /// Its result's term.
206        pub result: Term,
207        /// The templates they reach, in first-reach order.
208        pub declarations: Vec<Template>,
209    }
210}
211
212wire! {
213    /// A generic call's description.
214    #[derive(Clone, PartialEq, Eq, Hash, Debug)]
215    pub struct CallTypes {
216        /// The concrete type bound to each of the Tool's type parameters.
217        pub bindings: Vec<(String, Term)>,
218        /// Each parameter's key and concrete term.
219        pub params: Vec<(String, Term)>,
220        /// The concrete result's term.
221        pub result: Term,
222        /// The templates they reach, in first-reach order.
223        pub declarations: Vec<Template>,
224    }
225}
226
227wire! {
228    /// A call's concrete result type, for a client that answers it from
229    /// outside the call.
230    #[derive(Clone, PartialEq, Eq, Hash, Debug)]
231    pub struct ResultType {
232        /// The result's term.
233        pub result: Term,
234        /// The templates it reaches, in first-reach order.
235        pub declarations: Vec<Template>,
236    }
237}
238
239wire! {
240    /// One program as the `--contract` file lists it (`abi.md`, *Binding*).
241    #[derive(Clone, PartialEq, Eq, Hash, Debug)]
242    pub struct Program {
243        /// The path of the file it was formed from.
244        pub root: String,
245        /// Each Tool's identity and description, whose `declarations` are
246        /// empty: its terms index `types`.
247        pub tools: Vec<(Identity, TypeSpec)>,
248        /// The program's type map, in first-reach order over the Tools.
249        pub types: Vec<Template>,
250    }
251}
252
253impl Identity {
254    /// The parts of `identity`.
255    pub fn of(identity: &Declared) -> Self {
256        let origin = &identity.origin;
257        let library = match (origin.tree(), origin.library()) {
258            (Tree::Local, None) => None,
259            (Tree::Std | Tree::Repository(_) | Tree::Local, _) => Some(Library {
260                address: origin.address(),
261                version: identity.version.clone(),
262            }),
263        };
264        Identity {
265            library,
266            module: origin.module().to_string(),
267            name: identity.name.clone(),
268        }
269    }
270
271    /// The identity these parts write: the module whose library and module
272    /// path are these parts, so that writing it again gives them back. A
273    /// library with a version is a repository, or std; one without is a
274    /// library of the local tree, `.` its root; and no library is the
275    /// tree outside every library.
276    ///
277    /// # Errors
278    ///
279    /// The module path, or a library root of the local tree, that is no
280    /// path.
281    pub fn identity(&self) -> Result<Declared, SegmentsError> {
282        let module = self.module.parse()?;
283        let origin = match &self.library {
284            None => ModulePath::new(Tree::Local, None, module),
285            Some(Library {
286                address,
287                version: Some(_),
288            }) if address == Tree::STD => ModulePath::new(Tree::Std, None, module),
289            Some(Library {
290                address,
291                version: Some(_),
292            }) => ModulePath::new(Tree::Repository(address.clone()), None, module),
293            Some(Library {
294                address,
295                version: None,
296            }) if address == "." => ModulePath::new(Tree::Local, Some(Segments::root()), module),
297            Some(Library {
298                address,
299                version: None,
300            }) => ModulePath::new(Tree::Local, Some(address.parse()?), module),
301        };
302        Ok(Declared {
303            origin,
304            version: self
305                .library
306                .as_ref()
307                .and_then(|library| library.version.clone()),
308            name: self.name.clone(),
309        })
310    }
311}
312
313/// A term nests as deeply as its bytes do, so it is a [`Nested`] tree, which
314/// clones, compares, hashes and drops on a native stack of bounded size.
315impl Nested for Term {
316    const LEAF: Term = Term::Int;
317
318    /// An item, a key and a value, a tuple's parts, a declared type's
319    /// arguments, or a function's parameters and then its result.
320    fn parts(&self) -> impl DoubleEndedIterator<Item = &Term> {
321        let (list, boxed): (&[Term], [Option<&Term>; 2]) = match self {
322            Term::List(item) | Term::Set(item) | Term::Option(item) | Term::Task(item) => {
323                (&[], [Some(item), None])
324            }
325            Term::Dict(key, value) => (&[], [Some(key), Some(value)]),
326            Term::Tuple(parts) | Term::Named { args: parts, .. } => (parts, [None, None]),
327            Term::Function { params, result } => (params, [Some(result), None]),
328            Term::Int
329            | Term::Decimal
330            | Term::Bool
331            | Term::Text
332            | Term::Bytes
333            | Term::Duration
334            | Term::Instant
335            | Term::Unit
336            | Term::Never
337            | Term::JsonValue
338            | Term::Param { .. } => (&[], [None, None]),
339        };
340        list.iter().chain(boxed.into_iter().flatten())
341    }
342
343    fn parts_mut(&mut self) -> impl Iterator<Item = &mut Term> {
344        let (list, boxed): (&mut [Term], [Option<&mut Box<Term>>; 2]) = match self {
345            Term::List(item) | Term::Set(item) | Term::Option(item) | Term::Task(item) => {
346                (&mut [], [Some(item), None])
347            }
348            Term::Dict(key, value) => (&mut [], [Some(key), Some(value)]),
349            Term::Tuple(parts) | Term::Named { args: parts, .. } => (parts, [None, None]),
350            Term::Function { params, result } => (params, [Some(result), None]),
351            Term::Int
352            | Term::Decimal
353            | Term::Bool
354            | Term::Text
355            | Term::Bytes
356            | Term::Duration
357            | Term::Instant
358            | Term::Unit
359            | Term::Never
360            | Term::JsonValue
361            | Term::Param { .. } => (&mut [], [None, None]),
362        };
363        list.iter_mut()
364            .chain(boxed.into_iter().flatten().map(|part| &mut **part))
365    }
366}
367
368impl Term {
369    /// A node of `self`'s kind whose parts are what `part` makes of its
370    /// own, each once, in [`Nested::parts`] order.
371    fn map_parts(&self, mut part: impl FnMut(&Term) -> Term) -> Term {
372        match self {
373            Term::List(item) => Term::List(Box::new(part(item))),
374            Term::Set(item) => Term::Set(Box::new(part(item))),
375            Term::Option(item) => Term::Option(Box::new(part(item))),
376            Term::Task(item) => Term::Task(Box::new(part(item))),
377            Term::Dict(key, value) => {
378                let key = Box::new(part(key));
379                Term::Dict(key, Box::new(part(value)))
380            }
381            Term::Tuple(parts) => Term::Tuple(parts.iter().map(part).collect()),
382            Term::Named { declaration, args } => Term::Named {
383                declaration: declaration.clone(),
384                args: args.iter().map(part).collect(),
385            },
386            Term::Function { params, result } => {
387                let params = params.iter().map(&mut part).collect();
388                Term::Function {
389                    params,
390                    result: Box::new(part(result)),
391                }
392            }
393            Term::Int => Term::Int,
394            Term::Decimal => Term::Decimal,
395            Term::Bool => Term::Bool,
396            Term::Text => Term::Text,
397            Term::Bytes => Term::Bytes,
398            Term::Duration => Term::Duration,
399            Term::Instant => Term::Instant,
400            Term::Unit => Term::Unit,
401            Term::Never => Term::Never,
402            Term::JsonValue => Term::JsonValue,
403            Term::Param { owner, index } => Term::Param {
404                owner: owner.clone(),
405                index: index.clone(),
406            },
407        }
408    }
409
410    /// Whether `self` and `other` are alike as single nodes: of one kind,
411    /// declaration and parameter, with as many parts.
412    fn same_node(&self, other: &Term) -> bool {
413        match (self, other) {
414            (
415                Term::Named {
416                    declaration: a,
417                    args: xs,
418                },
419                Term::Named {
420                    declaration: b,
421                    args: ys,
422                },
423            ) => a == b && xs.len() == ys.len(),
424            (Term::Tuple(xs), Term::Tuple(ys))
425            | (Term::Function { params: xs, .. }, Term::Function { params: ys, .. }) => {
426                xs.len() == ys.len()
427            }
428            (Term::Param { owner: a, index: i }, Term::Param { owner: b, index: j }) => {
429                a == b && i == j
430            }
431            _ => std::mem::discriminant(self) == std::mem::discriminant(other),
432        }
433    }
434}
435
436/// [`Term::clone`].
437struct Cloning;
438
439impl Fold<Term> for Cloning {
440    type Made = Term;
441
442    fn open(&mut self, _: &Term) -> Option<Term> {
443        None
444    }
445
446    fn join(&mut self, term: &Term, mut part: impl FnMut(&mut Self, &Term) -> Term) -> Term {
447        term.map_parts(|term| part(self, term))
448    }
449}
450
451impl Clone for Term {
452    fn clone(&self) -> Term {
453        self.fold(&mut Cloning)
454    }
455}
456
457/// Two terms are equal when their nodes, read in pre-order, are alike one
458/// by one.
459impl PartialEq for Term {
460    fn eq(&self, other: &Term) -> bool {
461        self.same_tree(other, Term::same_node)
462    }
463}
464
465impl Eq for Term {}
466
467/// Hashes each node's kind, declaration and parameter in pre-order: equal
468/// terms hash alike.
469impl Hash for Term {
470    fn hash<H: Hasher>(&self, state: &mut H) {
471        self.fold(&mut Hashing(state));
472    }
473}
474
475/// [`Term::hash`]: each node hashed as it is opened.
476struct Hashing<'h, H>(&'h mut H);
477
478impl<H: Hasher> Fold<Term> for Hashing<'_, H> {
479    type Made = ();
480
481    fn open(&mut self, term: &Term) -> Option<()> {
482        std::mem::discriminant(term).hash(self.0);
483        match term {
484            Term::Named { declaration, .. } => declaration.hash(self.0),
485            Term::Param { owner, index } => {
486                owner.hash(self.0);
487                index.hash(self.0);
488            }
489            Term::Int
490            | Term::Decimal
491            | Term::Bool
492            | Term::Text
493            | Term::Bytes
494            | Term::Duration
495            | Term::Instant
496            | Term::Unit
497            | Term::Never
498            | Term::JsonValue
499            | Term::List(_)
500            | Term::Set(_)
501            | Term::Option(_)
502            | Term::Task(_)
503            | Term::Dict(_, _)
504            | Term::Tuple(_)
505            | Term::Function { .. } => {}
506        }
507        term.parts().next().is_none().then_some(())
508    }
509
510    fn join(&mut self, term: &Term, mut part: impl FnMut(&mut Self, &Term)) {
511        for term in term.parts() {
512            part(self, term);
513        }
514    }
515}
516
517impl Drop for Term {
518    fn drop(&mut self) {
519        self.free_parts();
520    }
521}
522
523#[cfg(test)]
524#[cfg_attr(coverage, coverage(off))]
525mod tests;