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
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
//! Which types a value may be built at or carried across a boundary as
//! (`tools.md`, *Decoding* and *Runtime-shaped data*; `abi.md`, *The JSON
//! form*).
//!
//! One judgment serves the checker and the value encoding alike. It walks a
//! type depth first, in the order its parts are written, with each
//! declaration's arguments substituted into its fields, and stops at the
//! first part its [`Settings`] refuse, with the way down to that part
//! ([`Refusal`]). "Contains" is judged of the type, not of a value: an
//! `Option` of an opaque type is refused even when the text holds `None`.
//! Each type parameter the walk reaches is reported with the settings it is
//! reached under, so a caller can ask them of the parameter's argument.
//!
//! The walk interns each type it meets once, so a declaration's arguments
//! are shared, never copied, into its fields, and walks each one once for
//! each crossing level its parts are entered at: walking it again so can
//! find nothing new. A recursive type reaches itself with its own parameters
//! unchanged (`types.md`, *Recursive types*), so every type has finitely
//! many parts, and the walk's work grows with the types it meets rather than
//! with the types written out. A record's or enum's parts cross as it does,
//! never held by an `Option` themselves, but a newtype's base stands in its
//! place: held by an `Option` that crosses, where `json.Value` itself is
//! refused, a newtype entered where it merely crosses is entered again.

use std::collections::{HashMap, HashSet};

use crate::names::{NameIndex, Spelling};

use crate::nested::{Fold, Nested};
use crate::types::{Body, Decl, DeclId, Type};

/// Whether a type crosses a boundary, which refuses an `Option<json.Value>`
/// part, since `None` and `Some(Null)` would be written the same way
/// (`tools.md`, *Runtime-shaped data*). Each variant asks more than the one
/// before it.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)]
pub enum Crossing {
    /// It stays inside the run, so it may hold anything data may.
    #[default]
    Stays,
    /// It crosses, so it has no `Option<json.Value>` part.
    Crosses,
    /// An `Option` of it crosses, so it is not `json.Value` either. The walk
    /// reaches this level under each such `Option`, and a type parameter
    /// reached there is reported with it.
    HeldByOption,
}

/// What a judgment asks of every part of a type.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct Settings {
    /// Every part is data: no function, task or other type that is not
    /// data. Without it nothing is refused, and the walk only reports the
    /// type parameters it reaches.
    pub data: bool,
    /// A host type may stand where data does.
    pub host_ok: bool,
    /// No part is `opaque`.
    pub no_opaque: bool,
    /// Whether the type crosses a boundary.
    pub crossing: Crossing,
    /// How decoding matches a name the text writes with one the type
    /// declares. Under [`Spelling::Relaxed`], a declaration two of whose
    /// names share a relaxed key is refused, since a name could mean either.
    pub names: Spelling,
}

/// What the part a judgment refuses is.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Reason {
    /// A function.
    Function,
    /// A host type where host values may not stand.
    Host,
    /// A task.
    Task,
    /// Some other type that is not data.
    NotData,
    /// An opaque type where no opaque part may stand.
    Opaque,
    /// `json.Value` held by an `Option` that crosses a boundary, which a
    /// judgment that starts held by one, as a type parameter's may, reports.
    JsonValue,
    /// An `Option<json.Value>` that crosses a boundary.
    OptionalJson,
    /// A declaration two of whose names share the relaxed key the judgment
    /// matches names by.
    SharedKey,
}

/// One step from a type down to a part of it.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Step {
    /// The `index`th field of the record `decl`.
    Field {
        /// The record.
        decl: DeclId,
        /// The field's position.
        index: usize,
    },
    /// The `index`th part of the `ctor`th constructor of the enum `decl`.
    Payload {
        /// The enum.
        decl: DeclId,
        /// The constructor's position.
        ctor: usize,
        /// The part's position in its payload.
        index: usize,
    },
    /// The base of the newtype `decl`, which stands in its place.
    Base(DeclId),
    /// A tuple position.
    Index(usize),
    /// An argument of a built-in or host type, such as a list's item.
    Element,
}

/// The first part of a type a judgment refuses, what it is, and the way
/// from the judged type down to it.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Refusal {
    /// The refused part, with the arguments it is reached with substituted.
    pub part: Type,
    /// What it is.
    pub reason: Reason,
    /// The steps from the judged type down to it.
    pub path: Vec<Step>,
}

/// Judges `ty`, a type over `decls`, where the `n`th is [`DeclId`] `n`,
/// against `settings`, passing each type parameter it reaches, with the
/// settings it is reached under, to `on_param`. Returns the first part
/// refused.
///
/// The walk keeps the parts still to visit on the heap, so a type nested
/// however deep never deepens the native stack.
pub fn judge(
    decls: &[Decl],
    ty: &Type,
    settings: Settings,
    on_param: &mut dyn FnMut(u32, Settings),
) -> Option<Refusal> {
    Walk::new(decls, on_param).judge(ty, settings)
}

/// One judgment's walk. Each type it meets is interned once, as a [`Node`]
/// whose parts are the ids of types met before, so substituting a
/// declaration's arguments into its fields builds only the fields' own
/// nodes, sharing the arguments however often they repeat. Each node is
/// walked once for each crossing level its parts are entered at.
struct Walk<'a> {
    decls: &'a [Decl],
    on_param: &'a mut dyn FnMut(u32, Settings),
    nodes: Vec<Node>,
    ids: HashMap<Node, Id>,
    walked: HashSet<(Id, Crossing)>,
    /// Parts entered, counted so tests can bound the walk.
    #[cfg(test)]
    steps: usize,
}

/// A type the walk has met: its place in [`Walk::nodes`].
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
struct Id(usize);

/// One type the walk has met, with its parts by [`Id`].
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
enum Node {
    /// A type with no parts other than a parameter: a scalar, `json.Value`
    /// or `NotData`.
    Leaf(Type),
    List(Id),
    Set(Id),
    Option(Id),
    Task(Id),
    Dict(Id, Id),
    Tuple(Vec<Id>),
    Named(DeclId, Vec<Id>),
    Param(u32),
    Function(Vec<Id>, Id),
}

/// A part to walk: the step that reaches it, if one is shown, the part and
/// what it is judged for.
type Part = (Option<Step>, Id, Settings);

/// The refused part, by its id, what it is and the way down to it.
struct Found {
    part: Id,
    reason: Reason,
    path: Vec<Step>,
}

/// What entering a type found.
enum Entered {
    /// The type itself is refused.
    Refused(Found),
    /// Its parts, in order, and what a refusal among them means for it.
    Parts(Vec<Part>, OnRefusal),
}

/// What a refusal found among a type's parts means for the type.
enum OnRefusal {
    /// It is the type's refusal, reached through the part.
    Through,
    /// The type is an `Option` that crosses: a `json.Value` it holds is its
    /// own fault, as an `Option<json.Value>`.
    Optional(Id),
}

/// A type whose parts are being walked.
struct Open {
    parts: std::vec::IntoIter<Part>,
    /// The step to the part being walked.
    step: Option<Step>,
    on_refusal: OnRefusal,
}

impl Open {
    /// This type's refusal, for `found` in the part being walked.
    fn refused(self, mut found: Found) -> Found {
        found.path.splice(0..0, self.step);
        match self.on_refusal {
            OnRefusal::Optional(part) if found.reason == Reason::JsonValue => Found {
                part,
                reason: Reason::OptionalJson,
                path: Vec::new(),
            },
            OnRefusal::Optional(_) | OnRefusal::Through => found,
        }
    }
}

impl<'a> Walk<'a> {
    fn new(decls: &'a [Decl], on_param: &'a mut dyn FnMut(u32, Settings)) -> Self {
        Walk {
            decls,
            on_param,
            nodes: Vec::new(),
            ids: HashMap::new(),
            walked: HashSet::new(),
            #[cfg(test)]
            steps: 0,
        }
    }

    /// Judges `ty` against `settings`: the first part refused.
    fn judge(&mut self, ty: &Type, settings: Settings) -> Option<Refusal> {
        let root = self.intern(ty, &[]);
        let mut open: Vec<Open> = Vec::new();
        let mut entered = self.enter(root, settings);
        loop {
            match entered {
                Entered::Refused(mut found) => {
                    while let Some(left) = open.pop() {
                        found = left.refused(found);
                    }
                    return Some(Refusal {
                        part: self.render(found.part),
                        reason: found.reason,
                        path: found.path,
                    });
                }
                Entered::Parts(parts, on_refusal) => open.push(Open {
                    parts: parts.into_iter(),
                    step: None,
                    on_refusal,
                }),
            }
            entered = loop {
                let top = open.last_mut()?;
                if let Some((step, part, settings)) = top.parts.next() {
                    top.step = step;
                    break self.enter(part, settings);
                }
                open.pop();
            };
        }
    }

    /// The id of `ty` with each parameter that has an argument in `args`
    /// replaced by it, interning each node it builds.
    fn intern(&mut self, ty: &Type, args: &[Id]) -> Id {
        ty.fold(&mut Interning { walk: self, args })
    }

    /// The type `id` stands for, written out.
    fn render(&self, id: Id) -> Type {
        let mut todo = vec![(id, false)];
        let mut done: Vec<Type> = Vec::new();
        while let Some((id, parts_done)) = todo.pop() {
            let node = &self.nodes[id.0];
            let parts = node.parts();
            if parts_done || parts.is_empty() {
                let built = done.split_off(done.len() - parts.len());
                done.push(node.ty(built));
            } else {
                todo.push((id, true));
                todo.extend(parts.into_iter().rev().map(|part| (part, false)));
            }
        }
        done.pop().expect("rendering a type yields it")
    }

    /// Enters `id`, judged for `settings`: refuses it, or lists its parts.
    fn enter(&mut self, id: Id, settings: Settings) -> Entered {
        #[cfg(test)]
        {
            self.steps += 1;
        }
        let inner = inner(settings);
        match self.nodes[id.0].clone() {
            Node::Param(index) => {
                (self.on_param)(index, settings);
                through(Vec::new(), inner)
            }
            Node::Leaf(Type::NotData) if settings.data => refused(id, Reason::NotData),
            Node::Task(_) if settings.data => refused(id, Reason::Task),
            Node::Leaf(Type::Json) if settings.crossing == Crossing::HeldByOption => {
                refused(id, Reason::JsonValue)
            }
            Node::Function(..) if settings.data => refused(id, Reason::Function),
            Node::Function(..)
            | Node::Task(_)
            | Node::List(_)
            | Node::Set(_)
            | Node::Option(_)
            | Node::Dict(..)
            | Node::Tuple(_)
                if !self.walked.insert((id, inner.crossing)) =>
            {
                through(Vec::new(), inner)
            }
            Node::Leaf(_) | Node::Function(..) | Node::Task(_) => through(Vec::new(), inner),
            Node::List(item) | Node::Set(item) => through(vec![(Some(Step::Element), item)], inner),
            Node::Dict(key, value) => through(
                vec![(Some(Step::Element), key), (Some(Step::Element), value)],
                inner,
            ),
            Node::Tuple(parts) => through(
                parts
                    .into_iter()
                    .enumerate()
                    .map(|(position, part)| (Some(Step::Index(position)), part))
                    .collect(),
                inner,
            ),
            // An `Option` that crosses holds no `json.Value` itself.
            Node::Option(held) if settings.crossing != Crossing::Stays => {
                let held_by = Settings {
                    crossing: Crossing::HeldByOption,
                    ..settings
                };
                Entered::Parts(vec![(None, held, held_by)], OnRefusal::Optional(id))
            }
            Node::Option(held) => through(vec![(None, held)], inner),
            Node::Named(decl, args) => self.declared(id, decl, &args, settings),
        }
    }

    /// Enters `id`, the declared type `decl` applied to `args`, judged
    /// for `settings`.
    fn declared(&mut self, id: Id, decl: DeclId, args: &[Id], settings: Settings) -> Entered {
        let inner = inner(settings);
        let declared = &self.decls[crate::index(decl.0)];
        match &declared.body {
            Body::Host if !settings.host_ok => refused(id, Reason::Host),
            Body::NonData if settings.data => refused(id, Reason::NotData),
            Body::Record(..) | Body::Enum(..) | Body::Newtype(_)
                if settings.no_opaque && declared.opaque =>
            {
                refused(id, Reason::Opaque)
            }
            Body::Record(..) | Body::Enum(..)
                if settings.names == Spelling::Relaxed
                    && NameIndex::of(&declared.body, Spelling::Relaxed).is_err() =>
            {
                refused(id, Reason::SharedKey)
            }
            Body::Newtype(_) if !self.walked.insert((id, settings.crossing)) => {
                through(Vec::new(), inner)
            }
            Body::Host | Body::NonData | Body::Record(..) | Body::Enum(..)
                if !self.walked.insert((id, inner.crossing)) =>
            {
                through(Vec::new(), inner)
            }
            Body::Host => through(
                args.iter().map(|arg| (Some(Step::Element), *arg)).collect(),
                inner,
            ),
            Body::NonData => through(Vec::new(), inner),
            // A newtype is judged as its base, in its place, so an `Option` of
            // one over `json.Value` is refused as `Option<json.Value>` is
            // (`abi.md`, *The JSON form*).
            Body::Newtype(base) => {
                let base = self.intern(base, args);
                Entered::Parts(
                    vec![(Some(Step::Base(decl)), base, settings)],
                    OnRefusal::Through,
                )
            }
            Body::Record(_, fields) => {
                let mut parts = Vec::with_capacity(fields.len());
                for (index, field) in fields.iter().enumerate() {
                    parts.push((Some(Step::Field { decl, index }), self.intern(field, args)));
                }
                through(parts, inner)
            }
            Body::Enum(_, ctors) => {
                let mut parts = Vec::new();
                for (ctor, payload) in ctors.iter().enumerate() {
                    for (index, part) in payload.iter().enumerate() {
                        let step = Step::Payload { decl, ctor, index };
                        parts.push((Some(step), self.intern(part, args)));
                    }
                }
                through(parts, inner)
            }
        }
    }
}

impl Node {
    /// Its parts, in order.
    fn parts(&self) -> Vec<Id> {
        match self {
            Node::Leaf(_) | Node::Param(_) => Vec::new(),
            Node::List(item) | Node::Set(item) | Node::Option(item) | Node::Task(item) => {
                vec![*item]
            }
            Node::Dict(key, value) => vec![*key, *value],
            Node::Tuple(parts) | Node::Named(_, parts) => parts.clone(),
            Node::Function(params, result) => params
                .iter()
                .copied()
                .chain(std::iter::once(*result))
                .collect(),
        }
    }

    /// The type it stands for, with `parts` written out in its parts' places.
    fn ty(&self, mut parts: Vec<Type>) -> Type {
        let mut part = || Box::new(parts.remove(0));
        match self {
            Node::Leaf(leaf) => leaf.clone(),
            Node::Param(index) => Type::Param(*index),
            Node::List(_) => Type::List(part()),
            Node::Set(_) => Type::Set(part()),
            Node::Option(_) => Type::Option(part()),
            Node::Task(_) => Type::Task(part()),
            Node::Dict(..) => Type::Dict(part(), part()),
            Node::Tuple(_) => Type::Tuple(parts),
            Node::Named(decl, _) => Type::Named(*decl, parts),
            Node::Function(..) => {
                let result = Box::new(parts.pop().expect("a function has a result"));
                Type::Function {
                    params: parts,
                    result,
                }
            }
        }
    }
}

/// [`Walk::intern`] as a fold: each type interned once its parts are, and a
/// parameter with an argument as the argument's node.
struct Interning<'w, 'a> {
    walk: &'w mut Walk<'a>,
    args: &'w [Id],
}

impl Fold<Type> for Interning<'_, '_> {
    type Made = Id;

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

    fn join(&mut self, ty: &Type, mut part: impl FnMut(&mut Self, &Type) -> Id) -> Id {
        let parts = ty.parts().map(|ty| part(self, ty)).collect();
        let walk = &mut *self.walk;
        let next = Id(walk.nodes.len());
        *walk.ids.entry(node(ty, parts)).or_insert_with_key(|node| {
            walk.nodes.push(node.clone());
            next
        })
    }
}

/// The node of `ty`, whose parts are `parts`, in order.
fn node(ty: &Type, mut parts: Vec<Id>) -> Node {
    match ty {
        Type::List(_) => Node::List(parts[0]),
        Type::Set(_) => Node::Set(parts[0]),
        Type::Option(_) => Node::Option(parts[0]),
        Type::Task(_) => Node::Task(parts[0]),
        Type::Dict(..) => Node::Dict(parts[0], parts[1]),
        Type::Tuple(_) => Node::Tuple(parts),
        Type::Named(decl, _) => Node::Named(*decl, parts),
        Type::Function { .. } => {
            let result = parts.pop().expect("a function has a result");
            Node::Function(parts, result)
        }
        Type::Param(index) => Node::Param(*index),
        Type::Int
        | Type::Decimal
        | Type::Bool
        | Type::Text
        | Type::Bytes
        | Type::Duration
        | Type::Instant
        | Type::Unit
        | Type::Never
        | Type::Json
        | Type::NotData => Node::Leaf(ty.clone()),
    }
}

/// What a type's own parts are judged for, under `settings`: they cross as
/// it does, but none is held by an `Option` for being its part.
fn inner(settings: Settings) -> Settings {
    Settings {
        crossing: settings.crossing.min(Crossing::Crosses),
        ..settings
    }
}

/// The refusal of `id` itself, as `reason`.
fn refused(id: Id, reason: Reason) -> Entered {
    Entered::Refused(Found {
        part: id,
        reason,
        path: Vec::new(),
    })
}

/// `parts`, each judged for `inner`, whose refusal is the type's.
fn through(parts: Vec<(Option<Step>, Id)>, inner: Settings) -> Entered {
    let parts = parts
        .into_iter()
        .map(|(step, part)| (step, part, inner))
        .collect();
    Entered::Parts(parts, OnRefusal::Through)
}

#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
    use super::{Crossing, Settings, Spelling, Walk};
    use crate::{Body, Decl, DeclId, Identity, ModulePath, RecordShape, Segments, Tree, Type};

    /// `type D0<T> { x: D1<(T, T)> }`, `type D1<T> { x: D2<(T, T)> }`, and so on to
    /// `type D{n-1}<T> { x: T }`: each declaration's argument written out is
    /// twice the one before.
    fn doubling(n: u32) -> Vec<Decl> {
        (0..n)
            .map(|at| {
                let field = if at + 1 == n {
                    Type::Param(0)
                } else {
                    Type::Named(
                        DeclId(at + 1),
                        vec![Type::Tuple(vec![Type::Param(0), Type::Param(0)])],
                    )
                };
                Decl {
                    lexical_ordinal: 1,
                    identity: Identity {
                        origin: ModulePath::new(
                            Tree::Local,
                            None,
                            Segments::from_names(["main"]).expect("a test path is a path"),
                        ),
                        version: None,
                        name: format!("D{at}"),
                    },
                    doc: None,
                    params: vec!["T".into()],
                    members: Vec::new(),
                    opaque: false,
                    body: Body::Record(RecordShape::new(&format!("D{at}"), ["x"]), vec![field]),
                }
            })
            .collect()
    }

    /// The parts judging `D0<Int>` over [`doubling`] enters.
    fn steps(n: u32) -> usize {
        let decls = doubling(n);
        let mut on_param = |_, _| {};
        let mut walk = Walk::new(&decls, &mut on_param);
        let settings = Settings {
            data: true,
            host_ok: true,
            no_opaque: true,
            crossing: Crossing::Crosses,
            names: Spelling::Exact,
        };
        assert!(
            walk.judge(&Type::Named(DeclId(0), vec![Type::Int]), settings)
                .is_none()
        );
        walk.steps
    }

    #[test]
    fn a_chain_doubling_its_argument_is_judged_in_steps_linear_in_its_length() {
        for n in 1..=30 {
            let steps = steps(n);
            assert!(
                steps <= 8 * crate::index(n),
                "{n} declarations took {steps} steps"
            );
        }
    }
}