Skip to main content

flow_abi/
form.rs

1//! What a value of a type is made of, with declarations looked up and their
2//! arguments put in place.
3//!
4//! A reader or writer that walks a value by its type — the binary encoding
5//! here, history's slots (`trace.md`, *Values*) — asks the same question at
6//! every step: is this a scalar written as a part, a text, a collection of
7//! what, a record of which fields, an enum of which constructors? [`form`]
8//! answers it once, so each walker matches on the answer rather than on
9//! [`Type`] and the [`Catalog`] separately. `Option` and `json.Value` are
10//! enums like any other here (`abi.md`, *Each type*).
11
12use std::borrow::Cow;
13use std::sync::Arc;
14
15use flow_types::{EnumShape, JsonValueCtor, OptionCtor, RecordShape, StdEnum};
16
17use crate::catalog::{Catalog, StdForm};
18use flow_types::{Body, Type};
19
20/// The types written as their encoding and nothing more, never in a slot of
21/// their own (`trace.md`, *Slots*).
22#[derive(Clone, Copy, PartialEq, Eq, Debug)]
23pub enum Scalar {
24    /// `Unit`: nothing.
25    Unit,
26    /// `Bool`: one byte, `0` or `1`.
27    Bool,
28    /// `Int`: a signed number.
29    Int,
30    /// `Decimal`: its coefficient and exponent, two signed numbers.
31    Decimal,
32    /// `Duration`: its seconds, a `Decimal`.
33    Duration,
34    /// `Instant`: its seconds after the epoch, a `Decimal`.
35    Instant,
36}
37
38/// What a value of a type is made of.
39#[derive(Clone, Debug)]
40pub enum Form<'t> {
41    /// A scalar.
42    Scalar(Scalar),
43    /// `Text`.
44    Text,
45    /// `Bytes`.
46    Bytes,
47    /// A host type, whose values are the host's tokens.
48    Host,
49    /// `List<T>`, of this element type.
50    List(&'t Type),
51    /// `Set<T>`, of this element type.
52    Set(&'t Type),
53    /// `Dict<K, V>`, of these key and value types.
54    Dict(&'t Type, &'t Type),
55    /// A tuple, of these part types in order.
56    Tuple(&'t [Type]),
57    /// A record.
58    Record(RecordForm<'t>),
59    /// An enum, `Option` and `json.Value` included.
60    Enum(EnumForm<'t>),
61    /// A newtype, written exactly as its base, this type with the
62    /// newtype's arguments in place (`abi.md`, *Each type*), and the form
63    /// its values are held to when it is a std type that has one: a value
64    /// out of that form is neither written nor read (`abi.md`, *Decoding*).
65    Newtype(Type, Option<StdForm>),
66    /// `task.Task<T>`, of this result type, which has no encoding outside a
67    /// checkpoint's arguments.
68    Task(&'t Type),
69    /// `Never`, which has no values.
70    Never,
71    /// A type with no encoding: a function, a nondata declaration, an
72    /// unbound type parameter, or an incomplete type.
73    NoEncoding,
74}
75
76impl<'t> Form<'t> {
77    /// The record this is a value of, if it is a record.
78    pub fn record(self) -> Option<RecordForm<'t>> {
79        if let Form::Record(record) = self {
80            Some(record)
81        } else {
82            None
83        }
84    }
85
86    /// The enum this is a value of, if it is an enum.
87    pub fn enumeration(self) -> Option<EnumForm<'t>> {
88        if let Form::Enum(form) = self {
89            Some(form)
90        } else {
91            None
92        }
93    }
94
95    /// The element type, if this is a list.
96    pub fn list(self) -> Option<&'t Type> {
97        if let Form::List(item) = self {
98            Some(item)
99        } else {
100            None
101        }
102    }
103}
104
105/// A record type: its shape, and its fields' types in declaration order with
106/// the record's arguments in place.
107#[derive(Clone, Debug)]
108pub struct RecordForm<'t> {
109    /// The shape its values are built with, which names the fields.
110    pub shape: &'t Arc<RecordShape>,
111    /// Each field's type, in declaration order.
112    pub fields: Vec<Type>,
113}
114
115/// An enum type: its shape, and each constructor's payload types.
116#[derive(Clone, Debug)]
117pub struct EnumForm<'t> {
118    /// The shape its values are built with, which names the constructors
119    /// and their payloads.
120    pub shape: &'t Arc<EnumShape>,
121    parts: Parts<'t>,
122}
123
124/// Where an enum's payload types come from.
125#[derive(Clone, Debug)]
126enum Parts<'t> {
127    /// A declaration's, with its arguments.
128    Declared {
129        ctors: &'t [Vec<Type>],
130        args: &'t [Type],
131    },
132    /// std's `Option<item>`, `Some` at this position.
133    Option { item: &'t Type, some: usize },
134    /// std's `json.Value`, its constructors bound.
135    Json(&'t StdEnum<JsonValueCtor>),
136}
137
138/// The payload types of `json.Value`'s constructor `ctor`.
139pub(crate) fn json_parts(ctor: JsonValueCtor) -> Vec<Type> {
140    match ctor {
141        JsonValueCtor::Null => Vec::new(),
142        JsonValueCtor::Bool => vec![Type::Bool],
143        JsonValueCtor::Number => vec![Type::Decimal],
144        JsonValueCtor::Text => vec![Type::Text],
145        JsonValueCtor::List => vec![Type::list(Type::Json)],
146        JsonValueCtor::Object => vec![Type::dict(Type::Text, Type::Json)],
147    }
148}
149
150impl<'t> EnumForm<'t> {
151    /// The payload types of the constructor numbered `ctor`, counted from 0
152    /// in declaration order, with the enum's arguments in place; `None` for
153    /// a number the enum has no constructor for. A part the enum's type
154    /// holds as it is, such as an `Option`'s item, is borrowed from it.
155    pub fn parts(&self, ctor: usize) -> Option<Vec<Cow<'t, Type>>> {
156        self.shape.constructor(ctor)?;
157        Some(match &self.parts {
158            Parts::Declared { ctors, args } => ctors
159                .get(ctor)?
160                .iter()
161                .map(|part| Cow::Owned(part.subst(args)))
162                .collect(),
163            Parts::Option { item, some } if ctor == *some => vec![Cow::Borrowed(*item)],
164            Parts::Option { .. } => Vec::new(),
165            Parts::Json(ctors) => ctors
166                .which(ctor)
167                .map(json_parts)
168                .unwrap_or_default()
169                .into_iter()
170                .map(Cow::Owned)
171                .collect(),
172        })
173    }
174}
175
176/// The types of the parts a value of `ty` holds by its structure alone:
177/// a list's, set's or `Option`'s item, a dictionary's key and value, a
178/// tuple's parts. Each is borrowed for as long as `ty` is, and taken out of
179/// it when it is owned.
180pub(crate) fn part_types<'a>(ty: &Cow<'a, Type>) -> Vec<Cow<'a, Type>> {
181    fn held(ty: &Type) -> Vec<&Type> {
182        match ty {
183            Type::List(item) | Type::Set(item) | Type::Option(item) => vec![&**item],
184            Type::Dict(key, item) => vec![&**key, &**item],
185            Type::Tuple(parts) => parts.iter().collect(),
186            Type::Unit
187            | Type::Bool
188            | Type::Int
189            | Type::Decimal
190            | Type::Text
191            | Type::Bytes
192            | Type::Duration
193            | Type::Instant
194            | Type::Json
195            | Type::Named(..)
196            | Type::Task(_)
197            | Type::Never
198            | Type::Param(_)
199            | Type::Function { .. }
200            | Type::NotData => Vec::new(),
201        }
202    }
203    match ty {
204        Cow::Borrowed(ty) => held(ty).into_iter().map(Cow::Borrowed).collect(),
205        Cow::Owned(ty) => held(ty).into_iter().cloned().map(Cow::Owned).collect(),
206    }
207}
208
209/// `ty` again, borrowed for as long as it is, or copied when it is owned.
210pub(crate) fn reborrow<'a>(ty: &Cow<'a, Type>) -> Cow<'a, Type> {
211    match ty {
212        Cow::Borrowed(ty) => Cow::Borrowed(ty),
213        Cow::Owned(ty) => Cow::Owned(ty.clone()),
214    }
215}
216
217/// What a value of `ty` is made of, its declaration looked up in `catalog`
218/// and its arguments put in place.
219///
220/// # Panics
221///
222/// When `ty` names a declaration `catalog` does not have, or is
223/// `json.Value` and `catalog` has no `json` module: a type and a catalog
224/// built from different programs.
225pub fn form<'t>(catalog: &'t Catalog, ty: &'t Type) -> Form<'t> {
226    match ty {
227        Type::Unit => Form::Scalar(Scalar::Unit),
228        Type::Bool => Form::Scalar(Scalar::Bool),
229        Type::Int => Form::Scalar(Scalar::Int),
230        Type::Decimal => Form::Scalar(Scalar::Decimal),
231        Type::Duration => Form::Scalar(Scalar::Duration),
232        Type::Instant => Form::Scalar(Scalar::Instant),
233        Type::Text => Form::Text,
234        Type::Bytes => Form::Bytes,
235        Type::List(item) => Form::List(item),
236        Type::Set(item) => Form::Set(item),
237        Type::Dict(key, value) => Form::Dict(key, value),
238        Type::Tuple(parts) => Form::Tuple(parts),
239        Type::Option(item) => {
240            let option = catalog.option();
241            Form::Enum(EnumForm {
242                shape: &option.shape,
243                parts: Parts::Option {
244                    item,
245                    some: option.ctors.index(OptionCtor::Some),
246                },
247            })
248        }
249        Type::Json => {
250            let json = catalog.json();
251            Form::Enum(EnumForm {
252                shape: &json.shape,
253                parts: Parts::Json(&json.ctors),
254            })
255        }
256        Type::Named(decl, args) => match &catalog.decl(*decl).body {
257            Body::Record(shape, fields) => Form::Record(RecordForm {
258                shape,
259                fields: fields.iter().map(|field| field.subst(args)).collect(),
260            }),
261            Body::Enum(shape, ctors) => Form::Enum(EnumForm {
262                shape,
263                parts: Parts::Declared { ctors, args },
264            }),
265            Body::Newtype(base) => {
266                Form::Newtype(base.subst(args), StdForm::of(catalog.decl(*decl)))
267            }
268            Body::Host => Form::Host,
269            Body::NonData => Form::NoEncoding,
270        },
271        Type::Task(result) => Form::Task(result),
272        Type::Never => Form::Never,
273        Type::Param(_) | Type::Function { .. } | Type::NotData => Form::NoEncoding,
274    }
275}