Skip to main content

flow_types/
judge.rs

1//! Which types a value may be built at or carried across a boundary as
2//! (`tools.md`, *Decoding* and *Runtime-shaped data*; `abi.md`, *The JSON
3//! form*).
4//!
5//! One judgment serves the checker and the value encoding alike. It walks a
6//! type depth first, in the order its parts are written, with each
7//! declaration's arguments substituted into its fields, and stops at the
8//! first part its [`Settings`] refuse, with the way down to that part
9//! ([`Refusal`]). "Contains" is judged of the type, not of a value: an
10//! `Option` of an opaque type is refused even when the text holds `None`.
11//! Each type parameter the walk reaches is reported with the settings it is
12//! reached under, so a caller can ask them of the parameter's argument.
13//!
14//! The walk interns each type it meets once, so a declaration's arguments
15//! are shared, never copied, into its fields, and walks each one once for
16//! each crossing level its parts are entered at: walking it again so can
17//! find nothing new. A recursive type reaches itself with its own parameters
18//! unchanged (`types.md`, *Recursive types*), so every type has finitely
19//! many parts, and the walk's work grows with the types it meets rather than
20//! with the types written out. A record's or enum's parts cross as it does,
21//! never held by an `Option` themselves, but a newtype's base stands in its
22//! place: held by an `Option` that crosses, where `json.Value` itself is
23//! refused, a newtype entered where it merely crosses is entered again.
24
25use std::collections::{HashMap, HashSet};
26
27use crate::names::{NameIndex, Spelling};
28
29use crate::nested::{Fold, Nested};
30use crate::types::{Body, Decl, DeclId, Type};
31
32/// Whether a type crosses a boundary, which refuses an `Option<json.Value>`
33/// part, since `None` and `Some(Null)` would be written the same way
34/// (`tools.md`, *Runtime-shaped data*). Each variant asks more than the one
35/// before it.
36#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)]
37pub enum Crossing {
38    /// It stays inside the run, so it may hold anything data may.
39    #[default]
40    Stays,
41    /// It crosses, so it has no `Option<json.Value>` part.
42    Crosses,
43    /// An `Option` of it crosses, so it is not `json.Value` either. The walk
44    /// reaches this level under each such `Option`, and a type parameter
45    /// reached there is reported with it.
46    HeldByOption,
47}
48
49/// What a judgment asks of every part of a type.
50#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
51pub struct Settings {
52    /// Every part is data: no function, task or other type that is not
53    /// data. Without it nothing is refused, and the walk only reports the
54    /// type parameters it reaches.
55    pub data: bool,
56    /// A host type may stand where data does.
57    pub host_ok: bool,
58    /// No part is `opaque`.
59    pub no_opaque: bool,
60    /// Whether the type crosses a boundary.
61    pub crossing: Crossing,
62    /// How decoding matches a name the text writes with one the type
63    /// declares. Under [`Spelling::Relaxed`], a declaration two of whose
64    /// names share a relaxed key is refused, since a name could mean either.
65    pub names: Spelling,
66}
67
68/// What the part a judgment refuses is.
69#[derive(Clone, Copy, PartialEq, Eq, Debug)]
70pub enum Reason {
71    /// A function.
72    Function,
73    /// A host type where host values may not stand.
74    Host,
75    /// A task.
76    Task,
77    /// Some other type that is not data.
78    NotData,
79    /// An opaque type where no opaque part may stand.
80    Opaque,
81    /// `json.Value` held by an `Option` that crosses a boundary, which a
82    /// judgment that starts held by one, as a type parameter's may, reports.
83    JsonValue,
84    /// An `Option<json.Value>` that crosses a boundary.
85    OptionalJson,
86    /// A declaration two of whose names share the relaxed key the judgment
87    /// matches names by.
88    SharedKey,
89}
90
91/// One step from a type down to a part of it.
92#[derive(Clone, Copy, PartialEq, Eq, Debug)]
93pub enum Step {
94    /// The `index`th field of the record `decl`.
95    Field {
96        /// The record.
97        decl: DeclId,
98        /// The field's position.
99        index: usize,
100    },
101    /// The `index`th part of the `ctor`th constructor of the enum `decl`.
102    Payload {
103        /// The enum.
104        decl: DeclId,
105        /// The constructor's position.
106        ctor: usize,
107        /// The part's position in its payload.
108        index: usize,
109    },
110    /// The base of the newtype `decl`, which stands in its place.
111    Base(DeclId),
112    /// A tuple position.
113    Index(usize),
114    /// An argument of a built-in or host type, such as a list's item.
115    Element,
116}
117
118/// The first part of a type a judgment refuses, what it is, and the way
119/// from the judged type down to it.
120#[derive(Clone, PartialEq, Eq, Debug)]
121pub struct Refusal {
122    /// The refused part, with the arguments it is reached with substituted.
123    pub part: Type,
124    /// What it is.
125    pub reason: Reason,
126    /// The steps from the judged type down to it.
127    pub path: Vec<Step>,
128}
129
130/// Judges `ty`, a type over `decls`, where the `n`th is [`DeclId`] `n`,
131/// against `settings`, passing each type parameter it reaches, with the
132/// settings it is reached under, to `on_param`. Returns the first part
133/// refused.
134///
135/// The walk keeps the parts still to visit on the heap, so a type nested
136/// however deep never deepens the native stack.
137pub fn judge(
138    decls: &[Decl],
139    ty: &Type,
140    settings: Settings,
141    on_param: &mut dyn FnMut(u32, Settings),
142) -> Option<Refusal> {
143    Walk::new(decls, on_param).judge(ty, settings)
144}
145
146/// One judgment's walk. Each type it meets is interned once, as a [`Node`]
147/// whose parts are the ids of types met before, so substituting a
148/// declaration's arguments into its fields builds only the fields' own
149/// nodes, sharing the arguments however often they repeat. Each node is
150/// walked once for each crossing level its parts are entered at.
151struct Walk<'a> {
152    decls: &'a [Decl],
153    on_param: &'a mut dyn FnMut(u32, Settings),
154    nodes: Vec<Node>,
155    ids: HashMap<Node, Id>,
156    walked: HashSet<(Id, Crossing)>,
157    /// Parts entered, counted so tests can bound the walk.
158    #[cfg(test)]
159    steps: usize,
160}
161
162/// A type the walk has met: its place in [`Walk::nodes`].
163#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
164struct Id(usize);
165
166/// One type the walk has met, with its parts by [`Id`].
167#[derive(Clone, PartialEq, Eq, Hash, Debug)]
168enum Node {
169    /// A type with no parts other than a parameter: a scalar, `json.Value`
170    /// or `NotData`.
171    Leaf(Type),
172    List(Id),
173    Set(Id),
174    Option(Id),
175    Task(Id),
176    Dict(Id, Id),
177    Tuple(Vec<Id>),
178    Named(DeclId, Vec<Id>),
179    Param(u32),
180    Function(Vec<Id>, Id),
181}
182
183/// A part to walk: the step that reaches it, if one is shown, the part and
184/// what it is judged for.
185type Part = (Option<Step>, Id, Settings);
186
187/// The refused part, by its id, what it is and the way down to it.
188struct Found {
189    part: Id,
190    reason: Reason,
191    path: Vec<Step>,
192}
193
194/// What entering a type found.
195enum Entered {
196    /// The type itself is refused.
197    Refused(Found),
198    /// Its parts, in order, and what a refusal among them means for it.
199    Parts(Vec<Part>, OnRefusal),
200}
201
202/// What a refusal found among a type's parts means for the type.
203enum OnRefusal {
204    /// It is the type's refusal, reached through the part.
205    Through,
206    /// The type is an `Option` that crosses: a `json.Value` it holds is its
207    /// own fault, as an `Option<json.Value>`.
208    Optional(Id),
209}
210
211/// A type whose parts are being walked.
212struct Open {
213    parts: std::vec::IntoIter<Part>,
214    /// The step to the part being walked.
215    step: Option<Step>,
216    on_refusal: OnRefusal,
217}
218
219impl Open {
220    /// This type's refusal, for `found` in the part being walked.
221    fn refused(self, mut found: Found) -> Found {
222        found.path.splice(0..0, self.step);
223        match self.on_refusal {
224            OnRefusal::Optional(part) if found.reason == Reason::JsonValue => Found {
225                part,
226                reason: Reason::OptionalJson,
227                path: Vec::new(),
228            },
229            OnRefusal::Optional(_) | OnRefusal::Through => found,
230        }
231    }
232}
233
234impl<'a> Walk<'a> {
235    fn new(decls: &'a [Decl], on_param: &'a mut dyn FnMut(u32, Settings)) -> Self {
236        Walk {
237            decls,
238            on_param,
239            nodes: Vec::new(),
240            ids: HashMap::new(),
241            walked: HashSet::new(),
242            #[cfg(test)]
243            steps: 0,
244        }
245    }
246
247    /// Judges `ty` against `settings`: the first part refused.
248    fn judge(&mut self, ty: &Type, settings: Settings) -> Option<Refusal> {
249        let root = self.intern(ty, &[]);
250        let mut open: Vec<Open> = Vec::new();
251        let mut entered = self.enter(root, settings);
252        loop {
253            match entered {
254                Entered::Refused(mut found) => {
255                    while let Some(left) = open.pop() {
256                        found = left.refused(found);
257                    }
258                    return Some(Refusal {
259                        part: self.render(found.part),
260                        reason: found.reason,
261                        path: found.path,
262                    });
263                }
264                Entered::Parts(parts, on_refusal) => open.push(Open {
265                    parts: parts.into_iter(),
266                    step: None,
267                    on_refusal,
268                }),
269            }
270            entered = loop {
271                let top = open.last_mut()?;
272                if let Some((step, part, settings)) = top.parts.next() {
273                    top.step = step;
274                    break self.enter(part, settings);
275                }
276                open.pop();
277            };
278        }
279    }
280
281    /// The id of `ty` with each parameter that has an argument in `args`
282    /// replaced by it, interning each node it builds.
283    fn intern(&mut self, ty: &Type, args: &[Id]) -> Id {
284        ty.fold(&mut Interning { walk: self, args })
285    }
286
287    /// The type `id` stands for, written out.
288    fn render(&self, id: Id) -> Type {
289        let mut todo = vec![(id, false)];
290        let mut done: Vec<Type> = Vec::new();
291        while let Some((id, parts_done)) = todo.pop() {
292            let node = &self.nodes[id.0];
293            let parts = node.parts();
294            if parts_done || parts.is_empty() {
295                let built = done.split_off(done.len() - parts.len());
296                done.push(node.ty(built));
297            } else {
298                todo.push((id, true));
299                todo.extend(parts.into_iter().rev().map(|part| (part, false)));
300            }
301        }
302        done.pop().expect("rendering a type yields it")
303    }
304
305    /// Enters `id`, judged for `settings`: refuses it, or lists its parts.
306    fn enter(&mut self, id: Id, settings: Settings) -> Entered {
307        #[cfg(test)]
308        {
309            self.steps += 1;
310        }
311        let inner = inner(settings);
312        match self.nodes[id.0].clone() {
313            Node::Param(index) => {
314                (self.on_param)(index, settings);
315                through(Vec::new(), inner)
316            }
317            Node::Leaf(Type::NotData) if settings.data => refused(id, Reason::NotData),
318            Node::Task(_) if settings.data => refused(id, Reason::Task),
319            Node::Leaf(Type::Json) if settings.crossing == Crossing::HeldByOption => {
320                refused(id, Reason::JsonValue)
321            }
322            Node::Function(..) if settings.data => refused(id, Reason::Function),
323            Node::Function(..)
324            | Node::Task(_)
325            | Node::List(_)
326            | Node::Set(_)
327            | Node::Option(_)
328            | Node::Dict(..)
329            | Node::Tuple(_)
330                if !self.walked.insert((id, inner.crossing)) =>
331            {
332                through(Vec::new(), inner)
333            }
334            Node::Leaf(_) | Node::Function(..) | Node::Task(_) => through(Vec::new(), inner),
335            Node::List(item) | Node::Set(item) => through(vec![(Some(Step::Element), item)], inner),
336            Node::Dict(key, value) => through(
337                vec![(Some(Step::Element), key), (Some(Step::Element), value)],
338                inner,
339            ),
340            Node::Tuple(parts) => through(
341                parts
342                    .into_iter()
343                    .enumerate()
344                    .map(|(position, part)| (Some(Step::Index(position)), part))
345                    .collect(),
346                inner,
347            ),
348            // An `Option` that crosses holds no `json.Value` itself.
349            Node::Option(held) if settings.crossing != Crossing::Stays => {
350                let held_by = Settings {
351                    crossing: Crossing::HeldByOption,
352                    ..settings
353                };
354                Entered::Parts(vec![(None, held, held_by)], OnRefusal::Optional(id))
355            }
356            Node::Option(held) => through(vec![(None, held)], inner),
357            Node::Named(decl, args) => self.declared(id, decl, &args, settings),
358        }
359    }
360
361    /// Enters `id`, the declared type `decl` applied to `args`, judged
362    /// for `settings`.
363    fn declared(&mut self, id: Id, decl: DeclId, args: &[Id], settings: Settings) -> Entered {
364        let inner = inner(settings);
365        let declared = &self.decls[crate::index(decl.0)];
366        match &declared.body {
367            Body::Host if !settings.host_ok => refused(id, Reason::Host),
368            Body::NonData if settings.data => refused(id, Reason::NotData),
369            Body::Record(..) | Body::Enum(..) | Body::Newtype(_)
370                if settings.no_opaque && declared.opaque =>
371            {
372                refused(id, Reason::Opaque)
373            }
374            Body::Record(..) | Body::Enum(..)
375                if settings.names == Spelling::Relaxed
376                    && NameIndex::of(&declared.body, Spelling::Relaxed).is_err() =>
377            {
378                refused(id, Reason::SharedKey)
379            }
380            Body::Newtype(_) if !self.walked.insert((id, settings.crossing)) => {
381                through(Vec::new(), inner)
382            }
383            Body::Host | Body::NonData | Body::Record(..) | Body::Enum(..)
384                if !self.walked.insert((id, inner.crossing)) =>
385            {
386                through(Vec::new(), inner)
387            }
388            Body::Host => through(
389                args.iter().map(|arg| (Some(Step::Element), *arg)).collect(),
390                inner,
391            ),
392            Body::NonData => through(Vec::new(), inner),
393            // A newtype is judged as its base, in its place, so an `Option` of
394            // one over `json.Value` is refused as `Option<json.Value>` is
395            // (`abi.md`, *The JSON form*).
396            Body::Newtype(base) => {
397                let base = self.intern(base, args);
398                Entered::Parts(
399                    vec![(Some(Step::Base(decl)), base, settings)],
400                    OnRefusal::Through,
401                )
402            }
403            Body::Record(_, fields) => {
404                let mut parts = Vec::with_capacity(fields.len());
405                for (index, field) in fields.iter().enumerate() {
406                    parts.push((Some(Step::Field { decl, index }), self.intern(field, args)));
407                }
408                through(parts, inner)
409            }
410            Body::Enum(_, ctors) => {
411                let mut parts = Vec::new();
412                for (ctor, payload) in ctors.iter().enumerate() {
413                    for (index, part) in payload.iter().enumerate() {
414                        let step = Step::Payload { decl, ctor, index };
415                        parts.push((Some(step), self.intern(part, args)));
416                    }
417                }
418                through(parts, inner)
419            }
420        }
421    }
422}
423
424impl Node {
425    /// Its parts, in order.
426    fn parts(&self) -> Vec<Id> {
427        match self {
428            Node::Leaf(_) | Node::Param(_) => Vec::new(),
429            Node::List(item) | Node::Set(item) | Node::Option(item) | Node::Task(item) => {
430                vec![*item]
431            }
432            Node::Dict(key, value) => vec![*key, *value],
433            Node::Tuple(parts) | Node::Named(_, parts) => parts.clone(),
434            Node::Function(params, result) => params
435                .iter()
436                .copied()
437                .chain(std::iter::once(*result))
438                .collect(),
439        }
440    }
441
442    /// The type it stands for, with `parts` written out in its parts' places.
443    fn ty(&self, mut parts: Vec<Type>) -> Type {
444        let mut part = || Box::new(parts.remove(0));
445        match self {
446            Node::Leaf(leaf) => leaf.clone(),
447            Node::Param(index) => Type::Param(*index),
448            Node::List(_) => Type::List(part()),
449            Node::Set(_) => Type::Set(part()),
450            Node::Option(_) => Type::Option(part()),
451            Node::Task(_) => Type::Task(part()),
452            Node::Dict(..) => Type::Dict(part(), part()),
453            Node::Tuple(_) => Type::Tuple(parts),
454            Node::Named(decl, _) => Type::Named(*decl, parts),
455            Node::Function(..) => {
456                let result = Box::new(parts.pop().expect("a function has a result"));
457                Type::Function {
458                    params: parts,
459                    result,
460                }
461            }
462        }
463    }
464}
465
466/// [`Walk::intern`] as a fold: each type interned once its parts are, and a
467/// parameter with an argument as the argument's node.
468struct Interning<'w, 'a> {
469    walk: &'w mut Walk<'a>,
470    args: &'w [Id],
471}
472
473impl Fold<Type> for Interning<'_, '_> {
474    type Made = Id;
475
476    fn open(&mut self, ty: &Type) -> Option<Id> {
477        let Type::Param(index) = ty else {
478            return None;
479        };
480        self.args.get(crate::index(*index)).copied()
481    }
482
483    fn join(&mut self, ty: &Type, mut part: impl FnMut(&mut Self, &Type) -> Id) -> Id {
484        let parts = ty.parts().map(|ty| part(self, ty)).collect();
485        let walk = &mut *self.walk;
486        let next = Id(walk.nodes.len());
487        *walk.ids.entry(node(ty, parts)).or_insert_with_key(|node| {
488            walk.nodes.push(node.clone());
489            next
490        })
491    }
492}
493
494/// The node of `ty`, whose parts are `parts`, in order.
495fn node(ty: &Type, mut parts: Vec<Id>) -> Node {
496    match ty {
497        Type::List(_) => Node::List(parts[0]),
498        Type::Set(_) => Node::Set(parts[0]),
499        Type::Option(_) => Node::Option(parts[0]),
500        Type::Task(_) => Node::Task(parts[0]),
501        Type::Dict(..) => Node::Dict(parts[0], parts[1]),
502        Type::Tuple(_) => Node::Tuple(parts),
503        Type::Named(decl, _) => Node::Named(*decl, parts),
504        Type::Function { .. } => {
505            let result = parts.pop().expect("a function has a result");
506            Node::Function(parts, result)
507        }
508        Type::Param(index) => Node::Param(*index),
509        Type::Int
510        | Type::Decimal
511        | Type::Bool
512        | Type::Text
513        | Type::Bytes
514        | Type::Duration
515        | Type::Instant
516        | Type::Unit
517        | Type::Never
518        | Type::Json
519        | Type::NotData => Node::Leaf(ty.clone()),
520    }
521}
522
523/// What a type's own parts are judged for, under `settings`: they cross as
524/// it does, but none is held by an `Option` for being its part.
525fn inner(settings: Settings) -> Settings {
526    Settings {
527        crossing: settings.crossing.min(Crossing::Crosses),
528        ..settings
529    }
530}
531
532/// The refusal of `id` itself, as `reason`.
533fn refused(id: Id, reason: Reason) -> Entered {
534    Entered::Refused(Found {
535        part: id,
536        reason,
537        path: Vec::new(),
538    })
539}
540
541/// `parts`, each judged for `inner`, whose refusal is the type's.
542fn through(parts: Vec<(Option<Step>, Id)>, inner: Settings) -> Entered {
543    let parts = parts
544        .into_iter()
545        .map(|(step, part)| (step, part, inner))
546        .collect();
547    Entered::Parts(parts, OnRefusal::Through)
548}
549
550#[cfg(test)]
551#[cfg_attr(coverage, coverage(off))]
552mod tests {
553    use super::{Crossing, Settings, Spelling, Walk};
554    use crate::{Body, Decl, DeclId, Identity, ModulePath, RecordShape, Segments, Tree, Type};
555
556    /// `type D0<T> { x: D1<(T, T)> }`, `type D1<T> { x: D2<(T, T)> }`, and so on to
557    /// `type D{n-1}<T> { x: T }`: each declaration's argument written out is
558    /// twice the one before.
559    fn doubling(n: u32) -> Vec<Decl> {
560        (0..n)
561            .map(|at| {
562                let field = if at + 1 == n {
563                    Type::Param(0)
564                } else {
565                    Type::Named(
566                        DeclId(at + 1),
567                        vec![Type::Tuple(vec![Type::Param(0), Type::Param(0)])],
568                    )
569                };
570                Decl {
571                    lexical_ordinal: 1,
572                    identity: Identity {
573                        origin: ModulePath::new(
574                            Tree::Local,
575                            None,
576                            Segments::from_names(["main"]).expect("a test path is a path"),
577                        ),
578                        version: None,
579                        name: format!("D{at}"),
580                    },
581                    doc: None,
582                    params: vec!["T".into()],
583                    members: Vec::new(),
584                    opaque: false,
585                    body: Body::Record(RecordShape::new(&format!("D{at}"), ["x"]), vec![field]),
586                }
587            })
588            .collect()
589    }
590
591    /// The parts judging `D0<Int>` over [`doubling`] enters.
592    fn steps(n: u32) -> usize {
593        let decls = doubling(n);
594        let mut on_param = |_, _| {};
595        let mut walk = Walk::new(&decls, &mut on_param);
596        let settings = Settings {
597            data: true,
598            host_ok: true,
599            no_opaque: true,
600            crossing: Crossing::Crosses,
601            names: Spelling::Exact,
602        };
603        assert!(
604            walk.judge(&Type::Named(DeclId(0), vec![Type::Int]), settings)
605                .is_none()
606        );
607        walk.steps
608    }
609
610    #[test]
611    fn a_chain_doubling_its_argument_is_judged_in_steps_linear_in_its_length() {
612        for n in 1..=30 {
613            let steps = steps(n);
614            assert!(
615                steps <= 8 * crate::index(n),
616                "{n} declarations took {steps} steps"
617            );
618        }
619    }
620}