Skip to main content

flow_types/
types.rs

1//! Types, and the declarations they name.
2//!
3//! This is the checker's type model cut down to what crosses the boundary:
4//! the built-in data types, tuples, `Option` and `json.Value`, whose
5//! encodings are their own, and declared types, including nondata types, kept
6//! in a list by [`DeclId`] so a recursive type is a finite graph. A
7//! function type retains its parameters and result in [`Type::Function`],
8//! so nominal arguments can be described without granting an encoding. A task
9//! type is [`Type::Task`], which has no encoding either, except in a
10//! checkpoint's arguments (`trace.md`, *Checkpoints*).
11
12use std::fmt;
13use std::sync::Arc;
14
15use crate::module::{ModulePath, Tree};
16use crate::nested::{Fold, Nested};
17use crate::shape::{EnumShape, RecordShape};
18
19/// A type, as the encoding sees it.
20///
21/// A type's depth is not bounded: a polymorphically recursive function can
22/// nest one as deep as its run goes. So nothing here recurses on it past a
23/// few levels: it is a [`Nested`] tree, which cloning, substituting, hashing
24/// and judging fold and which compares and drops over a stack on the heap
25/// past those levels.
26#[derive(Debug)]
27pub enum Type {
28    /// `Int`.
29    Int,
30    /// `Decimal`.
31    Decimal,
32    /// `Bool`.
33    Bool,
34    /// `Text`.
35    Text,
36    /// `Bytes`.
37    Bytes,
38    /// `Duration`.
39    Duration,
40    /// `Instant`.
41    Instant,
42    /// `Unit`.
43    Unit,
44    /// `Never`, which has no values.
45    Never,
46    /// `json.Value`, which encodes as the JSON value it stands for.
47    Json,
48    /// `List<T>`.
49    List(Box<Type>),
50    /// `Set<T>`.
51    Set(Box<Type>),
52    /// `Dict<K, V>`.
53    Dict(Box<Type>, Box<Type>),
54    /// `Option<T>`.
55    Option(Box<Type>),
56    /// A tuple of two or more parts.
57    Tuple(Vec<Type>),
58    /// A declared type, applied to its descriptive arguments.
59    Named(DeclId, Vec<Type>),
60    /// The `n`th type parameter of the declaration or signature it is
61    /// written in.
62    Param(u32),
63    /// `task.Task<T>`, which has no encoding, except where a task is the id
64    /// of the call it is parked on.
65    Task(Box<Type>),
66    /// A function, retained descriptively but without a value encoding.
67    Function {
68        /// Its parameter types, in order.
69        params: Vec<Type>,
70        /// Its result type.
71        result: Box<Type>,
72    },
73    /// An incomplete or erroneous type, which cannot be published.
74    NotData,
75}
76
77impl Type {
78    /// The type arguments of a declared type, in order; none for any other
79    /// type.
80    pub fn args(&self) -> &[Type] {
81        if let Type::Named(_, args) = self {
82            args
83        } else {
84            &[]
85        }
86    }
87
88    /// `List<item>`.
89    pub fn list(item: Type) -> Type {
90        Type::List(Box::new(item))
91    }
92
93    /// `Set<item>`.
94    pub fn set(item: Type) -> Type {
95        Type::Set(Box::new(item))
96    }
97
98    /// `Dict<key, value>`.
99    pub fn dict(key: Type, value: Type) -> Type {
100        Type::Dict(Box::new(key), Box::new(value))
101    }
102
103    /// `Option<item>`.
104    pub fn option(item: Type) -> Type {
105        Type::Option(Box::new(item))
106    }
107
108    /// This type with each [`Type::Param`] replaced by the argument at its
109    /// position. A parameter with no argument is left as it is.
110    #[must_use]
111    pub fn subst(&self, args: &[Type]) -> Type {
112        self.fold(&mut Substitution(args))
113    }
114
115    /// A node of `self`'s kind whose parts are what `part` makes of its
116    /// own, each once, in [`Nested::parts`] order: what a [`Fold`] that
117    /// makes a type joins a node with.
118    #[must_use]
119    pub fn map_parts(&self, mut part: impl FnMut(&Type) -> Type) -> Type {
120        match self {
121            Type::List(item) => Type::List(Box::new(part(item))),
122            Type::Set(item) => Type::Set(Box::new(part(item))),
123            Type::Option(item) => Type::Option(Box::new(part(item))),
124            Type::Task(item) => Type::Task(Box::new(part(item))),
125            Type::Dict(key, value) => {
126                let key = Box::new(part(key));
127                Type::Dict(key, Box::new(part(value)))
128            }
129            Type::Tuple(parts) => Type::Tuple(parts.iter().map(part).collect()),
130            Type::Named(decl, args) => Type::Named(*decl, args.iter().map(part).collect()),
131            Type::Function { params, result } => {
132                let params = params.iter().map(&mut part).collect();
133                Type::Function {
134                    params,
135                    result: Box::new(part(result)),
136                }
137            }
138            Type::Int => Type::Int,
139            Type::Decimal => Type::Decimal,
140            Type::Bool => Type::Bool,
141            Type::Text => Type::Text,
142            Type::Bytes => Type::Bytes,
143            Type::Duration => Type::Duration,
144            Type::Instant => Type::Instant,
145            Type::Unit => Type::Unit,
146            Type::Never => Type::Never,
147            Type::Json => Type::Json,
148            Type::Param(index) => Type::Param(*index),
149            Type::NotData => Type::NotData,
150        }
151    }
152
153    /// Whether `self` and `other` are alike as single nodes: of one kind,
154    /// declaration and parameter, with as many parts.
155    fn same_node(&self, other: &Type) -> bool {
156        match (self, other) {
157            (Type::Named(a, xs), Type::Named(b, ys)) => a == b && xs.len() == ys.len(),
158            (Type::Tuple(xs), Type::Tuple(ys))
159            | (Type::Function { params: xs, .. }, Type::Function { params: ys, .. }) => {
160                xs.len() == ys.len()
161            }
162            (Type::Param(a), Type::Param(b)) => a == b,
163            _ => std::mem::discriminant(self) == std::mem::discriminant(other),
164        }
165    }
166}
167
168impl Nested for Type {
169    const LEAF: Type = Type::NotData;
170
171    /// The types `self` is made of, in order: an item, a key and a value,
172    /// a tuple's parts, a declared type's arguments, or a function type's
173    /// parameters and then its result.
174    fn parts(&self) -> impl DoubleEndedIterator<Item = &Type> {
175        let (list, boxed): (&[Type], [Option<&Type>; 2]) = match self {
176            Type::List(item) | Type::Set(item) | Type::Option(item) | Type::Task(item) => {
177                (&[], [Some(item), None])
178            }
179            Type::Dict(key, value) => (&[], [Some(key), Some(value)]),
180            Type::Tuple(parts) | Type::Named(_, parts) => (parts, [None, None]),
181            Type::Function { params, result } => (params, [Some(result), None]),
182            Type::Int
183            | Type::Decimal
184            | Type::Bool
185            | Type::Text
186            | Type::Bytes
187            | Type::Duration
188            | Type::Instant
189            | Type::Unit
190            | Type::Never
191            | Type::Json
192            | Type::Param(_)
193            | Type::NotData => (&[], [None, None]),
194        };
195        list.iter().chain(boxed.into_iter().flatten())
196    }
197
198    /// The types `self` is made of, in [`Nested::parts`] order, for moving out.
199    fn parts_mut(&mut self) -> impl Iterator<Item = &mut Type> {
200        let (list, boxed): (&mut [Type], [Option<&mut Box<Type>>; 2]) = match self {
201            Type::List(item) | Type::Set(item) | Type::Option(item) | Type::Task(item) => {
202                (&mut [], [Some(item), None])
203            }
204            Type::Dict(key, value) => (&mut [], [Some(key), Some(value)]),
205            Type::Tuple(parts) | Type::Named(_, parts) => (parts, [None, None]),
206            Type::Function { params, result } => (params, [Some(result), None]),
207            Type::Int
208            | Type::Decimal
209            | Type::Bool
210            | Type::Text
211            | Type::Bytes
212            | Type::Duration
213            | Type::Instant
214            | Type::Unit
215            | Type::Never
216            | Type::Json
217            | Type::Param(_)
218            | Type::NotData => (&mut [], [None, None]),
219        };
220        list.iter_mut()
221            .chain(boxed.into_iter().flatten().map(|part| &mut **part))
222    }
223}
224
225/// [`Type::subst`], with the arguments it puts in place of parameters.
226struct Substitution<'a>(&'a [Type]);
227
228impl Fold<Type> for Substitution<'_> {
229    type Made = Type;
230
231    fn open(&mut self, ty: &Type) -> Option<Type> {
232        let Type::Param(index) = ty else {
233            return None;
234        };
235        Some(self.0.get(crate::index(*index)).unwrap_or(ty).clone())
236    }
237
238    fn join(&mut self, ty: &Type, mut part: impl FnMut(&mut Self, &Type) -> Type) -> Type {
239        ty.map_parts(|ty| part(self, ty))
240    }
241}
242
243/// [`Type::clone`].
244struct Cloning;
245
246impl Fold<Type> for Cloning {
247    type Made = Type;
248
249    fn open(&mut self, _: &Type) -> Option<Type> {
250        None
251    }
252
253    fn join(&mut self, ty: &Type, mut part: impl FnMut(&mut Self, &Type) -> Type) -> Type {
254        ty.map_parts(|ty| part(self, ty))
255    }
256}
257
258impl Clone for Type {
259    fn clone(&self) -> Type {
260        self.fold(&mut Cloning)
261    }
262}
263
264/// Two types are equal when their nodes, read in pre-order, are alike one
265/// by one: with each node's count of parts, that order spells the tree.
266impl PartialEq for Type {
267    fn eq(&self, other: &Type) -> bool {
268        self.same_tree(other, Type::same_node)
269    }
270}
271
272impl Eq for Type {}
273
274/// Hashes each node's kind, declaration and parameter in pre-order: equal
275/// types hash alike.
276impl std::hash::Hash for Type {
277    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
278        self.fold(&mut Hashing(state));
279    }
280}
281
282/// [`Type::hash`]: each node hashed as it is opened.
283struct Hashing<'h, H>(&'h mut H);
284
285impl<H: std::hash::Hasher> Fold<Type> for Hashing<'_, H> {
286    type Made = ();
287
288    fn open(&mut self, ty: &Type) -> Option<()> {
289        use std::hash::Hash as _;
290        std::mem::discriminant(ty).hash(self.0);
291        if let Type::Named(DeclId(number), _) | Type::Param(number) = ty {
292            number.hash(self.0);
293        }
294        ty.parts().next().is_none().then_some(())
295    }
296
297    fn join(&mut self, ty: &Type, mut part: impl FnMut(&mut Self, &Type)) {
298        for ty in ty.parts() {
299            part(self, ty);
300        }
301    }
302}
303
304/// Dropping a type frees its nested parts first: the first few levels by
305/// native recursion, and anything deeper over a stack on the heap, so a type
306/// nested however deep drops on a native stack of fixed size.
307impl Drop for Type {
308    fn drop(&mut self) {
309        self.free_parts();
310    }
311}
312
313/// A declaration's place in the catalog that holds it (flow-abi's `Catalog`).
314#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
315pub struct DeclId(pub u32);
316
317/// A declaration's identity: where it lives and its name (`abi.md`,
318/// *Identity and signatures*). Written `library@tag/module.Name` for a
319/// remote library, `std@v1/module.Name` for std and `library/module.Name`
320/// for a local one, without `/module` for a library's root module, and
321/// `path.Name` for a module outside every library, from its tree.
322///
323/// Identity is a name: two identities are equal when they are written
324/// alike, whatever else their origins hold.
325#[derive(Clone, Debug)]
326pub struct Identity {
327    /// The module it is declared in.
328    pub origin: ModulePath,
329    /// The version its tree resolved to: the tag a remote import resolved,
330    /// `v1` for std, and `None` for the local tree.
331    pub version: Option<String>,
332    /// Its name.
333    pub name: String,
334}
335
336impl Identity {
337    /// The identity as `code.show` writes it (`code.md`, *Reading the
338    /// model*): std with its major version, a repository without its tag.
339    pub fn shown(&self) -> String {
340        let versions = match self.origin.tree() {
341            Tree::Std => Versions::Shown,
342            Tree::Repository(_) | Tree::Local => Versions::Hidden,
343        };
344        self.written(versions)
345    }
346
347    /// The identity written with or without its library's tag.
348    pub fn written(&self, versions: Versions) -> String {
349        let version = match versions {
350            Versions::Shown => self.version.as_deref(),
351            Versions::Hidden => None,
352        };
353        let module = self.origin.written(version);
354        if module.is_empty() {
355            self.name.clone()
356        } else {
357            format!("{module}.{}", self.name)
358        }
359    }
360}
361
362impl PartialEq for Identity {
363    fn eq(&self, other: &Self) -> bool {
364        self.written(Versions::Shown) == other.written(Versions::Shown)
365    }
366}
367
368impl Eq for Identity {}
369
370impl std::hash::Hash for Identity {
371    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
372        self.written(Versions::Shown).hash(state);
373    }
374}
375
376impl fmt::Display for Identity {
377    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
378        f.write_str(&self.written(Versions::Shown))
379    }
380}
381
382/// A declared type.
383#[derive(Clone, Debug)]
384pub struct Decl {
385    /// Source-derived same-name ordinal, including aliases in its enumeration.
386    pub lexical_ordinal: u32,
387    /// Its identity.
388    pub identity: Identity,
389    /// Its `///` doc comment, with the markers removed, if it has one.
390    pub doc: Option<String>,
391    /// Its members' doc comments: for a record, one per field, and for an
392    /// enum, one per constructor, in declaration order. A member past the
393    /// end of the list has none.
394    pub members: Vec<MemberDoc>,
395    /// Its type parameters' names, which [`Type::Param`] counts.
396    pub params: Vec<String>,
397    /// Whether it is declared `opaque`, so that decoding cannot build it.
398    pub opaque: bool,
399    /// What it declares.
400    pub body: Body,
401}
402
403/// The doc comments of a record's field or an enum's constructor.
404#[derive(Clone, Default, PartialEq, Eq, Debug)]
405pub struct MemberDoc {
406    /// Its own `///` doc comment, written as [`Decl::doc`] is.
407    pub doc: Option<String>,
408    /// For a constructor with a named payload, each payload field's doc
409    /// comment, in declaration order. A field past the end has none.
410    pub fields: Vec<Option<String>>,
411}
412
413/// What a declaration declares.
414#[derive(Clone, Debug)]
415pub enum Body {
416    /// A record: its shape, and each field's type in declaration order.
417    Record(Arc<RecordShape>, Vec<Type>),
418    /// An enum: its shape, and each constructor's payload types in
419    /// declaration order.
420    Enum(Arc<EnumShape>, Vec<Vec<Type>>),
421    /// A newtype: its base, over the declaration's parameters. A value of
422    /// it is its base's value, encoded, decoded and schemed as the base
423    /// (`types.md`, *Erasure*).
424    Newtype(Type),
425    /// A host type, whose values are the host's tokens.
426    Host,
427    /// A declared nondata type, retained by nominal identity only.
428    NonData,
429}
430
431/// Whether a declaration's name is written with its repository version.
432#[derive(Clone, Copy, PartialEq, Eq, Debug)]
433pub enum Versions {
434    /// With it, as `std@v1/path.Path`.
435    Shown,
436    /// Without it, as `std/path.Path`.
437    Hidden,
438}