flow-types 0.1.0-rc.5

The Flow declaration model with no values: types, declarations and their identities, record and enum shapes, and which types decoding may build.
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
//! Types, and the declarations they name.
//!
//! This is the checker's type model cut down to what crosses the boundary:
//! the built-in data types, tuples, `Option` and `json.Value`, whose
//! encodings are their own, and declared types, including nondata types, kept
//! in a list by [`DeclId`] so a recursive type is a finite graph. A
//! function type retains its parameters and result in [`Type::Function`],
//! so nominal arguments can be described without granting an encoding. A task
//! type is [`Type::Task`], which has no encoding either, except in a
//! checkpoint's arguments (`trace.md`, *Checkpoints*).

use std::fmt;
use std::sync::Arc;

use crate::module::{ModulePath, Tree};
use crate::nested::{Fold, Nested};
use crate::shape::{EnumShape, RecordShape};

/// A type, as the encoding sees it.
///
/// A type's depth is not bounded: a polymorphically recursive function can
/// nest one as deep as its run goes. So nothing here recurses on it past a
/// few levels: it is a [`Nested`] tree, which cloning, substituting, hashing
/// and judging fold and which compares and drops over a stack on the heap
/// past those levels.
#[derive(Debug)]
pub enum Type {
    /// `Int`.
    Int,
    /// `Decimal`.
    Decimal,
    /// `Bool`.
    Bool,
    /// `Text`.
    Text,
    /// `Bytes`.
    Bytes,
    /// `Duration`.
    Duration,
    /// `Instant`.
    Instant,
    /// `Unit`.
    Unit,
    /// `Never`, which has no values.
    Never,
    /// `json.Value`, which encodes as the JSON value it stands for.
    Json,
    /// `List<T>`.
    List(Box<Type>),
    /// `Set<T>`.
    Set(Box<Type>),
    /// `Dict<K, V>`.
    Dict(Box<Type>, Box<Type>),
    /// `Option<T>`.
    Option(Box<Type>),
    /// A tuple of two or more parts.
    Tuple(Vec<Type>),
    /// A declared type, applied to its descriptive arguments.
    Named(DeclId, Vec<Type>),
    /// The `n`th type parameter of the declaration or signature it is
    /// written in.
    Param(u32),
    /// `task.Task<T>`, which has no encoding, except where a task is the id
    /// of the call it is parked on.
    Task(Box<Type>),
    /// A function, retained descriptively but without a value encoding.
    Function {
        /// Its parameter types, in order.
        params: Vec<Type>,
        /// Its result type.
        result: Box<Type>,
    },
    /// An incomplete or erroneous type, which cannot be published.
    NotData,
}

impl Type {
    /// The type arguments of a declared type, in order; none for any other
    /// type.
    pub fn args(&self) -> &[Type] {
        if let Type::Named(_, args) = self {
            args
        } else {
            &[]
        }
    }

    /// `List<item>`.
    pub fn list(item: Type) -> Type {
        Type::List(Box::new(item))
    }

    /// `Set<item>`.
    pub fn set(item: Type) -> Type {
        Type::Set(Box::new(item))
    }

    /// `Dict<key, value>`.
    pub fn dict(key: Type, value: Type) -> Type {
        Type::Dict(Box::new(key), Box::new(value))
    }

    /// `Option<item>`.
    pub fn option(item: Type) -> Type {
        Type::Option(Box::new(item))
    }

    /// This type with each [`Type::Param`] replaced by the argument at its
    /// position. A parameter with no argument is left as it is.
    #[must_use]
    pub fn subst(&self, args: &[Type]) -> Type {
        self.fold(&mut Substitution(args))
    }

    /// A node of `self`'s kind whose parts are what `part` makes of its
    /// own, each once, in [`Nested::parts`] order: what a [`Fold`] that
    /// makes a type joins a node with.
    #[must_use]
    pub fn map_parts(&self, mut part: impl FnMut(&Type) -> Type) -> Type {
        match self {
            Type::List(item) => Type::List(Box::new(part(item))),
            Type::Set(item) => Type::Set(Box::new(part(item))),
            Type::Option(item) => Type::Option(Box::new(part(item))),
            Type::Task(item) => Type::Task(Box::new(part(item))),
            Type::Dict(key, value) => {
                let key = Box::new(part(key));
                Type::Dict(key, Box::new(part(value)))
            }
            Type::Tuple(parts) => Type::Tuple(parts.iter().map(part).collect()),
            Type::Named(decl, args) => Type::Named(*decl, args.iter().map(part).collect()),
            Type::Function { params, result } => {
                let params = params.iter().map(&mut part).collect();
                Type::Function {
                    params,
                    result: Box::new(part(result)),
                }
            }
            Type::Int => Type::Int,
            Type::Decimal => Type::Decimal,
            Type::Bool => Type::Bool,
            Type::Text => Type::Text,
            Type::Bytes => Type::Bytes,
            Type::Duration => Type::Duration,
            Type::Instant => Type::Instant,
            Type::Unit => Type::Unit,
            Type::Never => Type::Never,
            Type::Json => Type::Json,
            Type::Param(index) => Type::Param(*index),
            Type::NotData => Type::NotData,
        }
    }

    /// Whether `self` and `other` are alike as single nodes: of one kind,
    /// declaration and parameter, with as many parts.
    fn same_node(&self, other: &Type) -> bool {
        match (self, other) {
            (Type::Named(a, xs), Type::Named(b, ys)) => a == b && xs.len() == ys.len(),
            (Type::Tuple(xs), Type::Tuple(ys))
            | (Type::Function { params: xs, .. }, Type::Function { params: ys, .. }) => {
                xs.len() == ys.len()
            }
            (Type::Param(a), Type::Param(b)) => a == b,
            _ => std::mem::discriminant(self) == std::mem::discriminant(other),
        }
    }
}

impl Nested for Type {
    const LEAF: Type = Type::NotData;

    /// The types `self` is made of, in order: an item, a key and a value,
    /// a tuple's parts, a declared type's arguments, or a function type's
    /// parameters and then its result.
    fn parts(&self) -> impl DoubleEndedIterator<Item = &Type> {
        let (list, boxed): (&[Type], [Option<&Type>; 2]) = match self {
            Type::List(item) | Type::Set(item) | Type::Option(item) | Type::Task(item) => {
                (&[], [Some(item), None])
            }
            Type::Dict(key, value) => (&[], [Some(key), Some(value)]),
            Type::Tuple(parts) | Type::Named(_, parts) => (parts, [None, None]),
            Type::Function { params, result } => (params, [Some(result), None]),
            Type::Int
            | Type::Decimal
            | Type::Bool
            | Type::Text
            | Type::Bytes
            | Type::Duration
            | Type::Instant
            | Type::Unit
            | Type::Never
            | Type::Json
            | Type::Param(_)
            | Type::NotData => (&[], [None, None]),
        };
        list.iter().chain(boxed.into_iter().flatten())
    }

    /// The types `self` is made of, in [`Nested::parts`] order, for moving out.
    fn parts_mut(&mut self) -> impl Iterator<Item = &mut Type> {
        let (list, boxed): (&mut [Type], [Option<&mut Box<Type>>; 2]) = match self {
            Type::List(item) | Type::Set(item) | Type::Option(item) | Type::Task(item) => {
                (&mut [], [Some(item), None])
            }
            Type::Dict(key, value) => (&mut [], [Some(key), Some(value)]),
            Type::Tuple(parts) | Type::Named(_, parts) => (parts, [None, None]),
            Type::Function { params, result } => (params, [Some(result), None]),
            Type::Int
            | Type::Decimal
            | Type::Bool
            | Type::Text
            | Type::Bytes
            | Type::Duration
            | Type::Instant
            | Type::Unit
            | Type::Never
            | Type::Json
            | Type::Param(_)
            | Type::NotData => (&mut [], [None, None]),
        };
        list.iter_mut()
            .chain(boxed.into_iter().flatten().map(|part| &mut **part))
    }
}

/// [`Type::subst`], with the arguments it puts in place of parameters.
struct Substitution<'a>(&'a [Type]);

impl Fold<Type> for Substitution<'_> {
    type Made = Type;

    fn open(&mut self, ty: &Type) -> Option<Type> {
        let Type::Param(index) = ty else {
            return None;
        };
        Some(self.0.get(crate::index(*index)).unwrap_or(ty).clone())
    }

    fn join(&mut self, ty: &Type, mut part: impl FnMut(&mut Self, &Type) -> Type) -> Type {
        ty.map_parts(|ty| part(self, ty))
    }
}

/// [`Type::clone`].
struct Cloning;

impl Fold<Type> for Cloning {
    type Made = Type;

    fn open(&mut self, _: &Type) -> Option<Type> {
        None
    }

    fn join(&mut self, ty: &Type, mut part: impl FnMut(&mut Self, &Type) -> Type) -> Type {
        ty.map_parts(|ty| part(self, ty))
    }
}

impl Clone for Type {
    fn clone(&self) -> Type {
        self.fold(&mut Cloning)
    }
}

/// Two types are equal when their nodes, read in pre-order, are alike one
/// by one: with each node's count of parts, that order spells the tree.
impl PartialEq for Type {
    fn eq(&self, other: &Type) -> bool {
        self.same_tree(other, Type::same_node)
    }
}

impl Eq for Type {}

/// Hashes each node's kind, declaration and parameter in pre-order: equal
/// types hash alike.
impl std::hash::Hash for Type {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.fold(&mut Hashing(state));
    }
}

/// [`Type::hash`]: each node hashed as it is opened.
struct Hashing<'h, H>(&'h mut H);

impl<H: std::hash::Hasher> Fold<Type> for Hashing<'_, H> {
    type Made = ();

    fn open(&mut self, ty: &Type) -> Option<()> {
        use std::hash::Hash as _;
        std::mem::discriminant(ty).hash(self.0);
        if let Type::Named(DeclId(number), _) | Type::Param(number) = ty {
            number.hash(self.0);
        }
        ty.parts().next().is_none().then_some(())
    }

    fn join(&mut self, ty: &Type, mut part: impl FnMut(&mut Self, &Type)) {
        for ty in ty.parts() {
            part(self, ty);
        }
    }
}

/// Dropping a type frees its nested parts first: the first few levels by
/// native recursion, and anything deeper over a stack on the heap, so a type
/// nested however deep drops on a native stack of fixed size.
impl Drop for Type {
    fn drop(&mut self) {
        self.free_parts();
    }
}

/// A declaration's place in the catalog that holds it (flow-abi's `Catalog`).
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct DeclId(pub u32);

/// A declaration's identity: where it lives and its name (`abi.md`,
/// *Identity and signatures*). Written `library@tag/module.Name` for a
/// remote library, `std@v1/module.Name` for std and `library/module.Name`
/// for a local one, without `/module` for a library's root module, and
/// `path.Name` for a module outside every library, from its tree.
///
/// Identity is a name: two identities are equal when they are written
/// alike, whatever else their origins hold.
#[derive(Clone, Debug)]
pub struct Identity {
    /// The module it is declared in.
    pub origin: ModulePath,
    /// The version its tree resolved to: the tag a remote import resolved,
    /// `v1` for std, and `None` for the local tree.
    pub version: Option<String>,
    /// Its name.
    pub name: String,
}

impl Identity {
    /// The identity as `code.show` writes it (`code.md`, *Reading the
    /// model*): std with its major version, a repository without its tag.
    pub fn shown(&self) -> String {
        let versions = match self.origin.tree() {
            Tree::Std => Versions::Shown,
            Tree::Repository(_) | Tree::Local => Versions::Hidden,
        };
        self.written(versions)
    }

    /// The identity written with or without its library's tag.
    pub fn written(&self, versions: Versions) -> String {
        let version = match versions {
            Versions::Shown => self.version.as_deref(),
            Versions::Hidden => None,
        };
        let module = self.origin.written(version);
        if module.is_empty() {
            self.name.clone()
        } else {
            format!("{module}.{}", self.name)
        }
    }
}

impl PartialEq for Identity {
    fn eq(&self, other: &Self) -> bool {
        self.written(Versions::Shown) == other.written(Versions::Shown)
    }
}

impl Eq for Identity {}

impl std::hash::Hash for Identity {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.written(Versions::Shown).hash(state);
    }
}

impl fmt::Display for Identity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.written(Versions::Shown))
    }
}

/// A declared type.
#[derive(Clone, Debug)]
pub struct Decl {
    /// Source-derived same-name ordinal, including aliases in its enumeration.
    pub lexical_ordinal: u32,
    /// Its identity.
    pub identity: Identity,
    /// Its `///` doc comment, with the markers removed, if it has one.
    pub doc: Option<String>,
    /// Its members' doc comments: for a record, one per field, and for an
    /// enum, one per constructor, in declaration order. A member past the
    /// end of the list has none.
    pub members: Vec<MemberDoc>,
    /// Its type parameters' names, which [`Type::Param`] counts.
    pub params: Vec<String>,
    /// Whether it is declared `opaque`, so that decoding cannot build it.
    pub opaque: bool,
    /// What it declares.
    pub body: Body,
}

/// The doc comments of a record's field or an enum's constructor.
#[derive(Clone, Default, PartialEq, Eq, Debug)]
pub struct MemberDoc {
    /// Its own `///` doc comment, written as [`Decl::doc`] is.
    pub doc: Option<String>,
    /// For a constructor with a named payload, each payload field's doc
    /// comment, in declaration order. A field past the end has none.
    pub fields: Vec<Option<String>>,
}

/// What a declaration declares.
#[derive(Clone, Debug)]
pub enum Body {
    /// A record: its shape, and each field's type in declaration order.
    Record(Arc<RecordShape>, Vec<Type>),
    /// An enum: its shape, and each constructor's payload types in
    /// declaration order.
    Enum(Arc<EnumShape>, Vec<Vec<Type>>),
    /// A newtype: its base, over the declaration's parameters. A value of
    /// it is its base's value, encoded, decoded and schemed as the base
    /// (`types.md`, *Erasure*).
    Newtype(Type),
    /// A host type, whose values are the host's tokens.
    Host,
    /// A declared nondata type, retained by nominal identity only.
    NonData,
}

/// Whether a declaration's name is written with its repository version.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Versions {
    /// With it, as `std@v1/path.Path`.
    Shown,
    /// Without it, as `std/path.Path`.
    Hidden,
}