flow-abi 0.1.0-rc.5

The host boundary's value encoding: the binary encoding and the JSON form, the canonical form and its hash, JSON Schemas, Tool signatures, and the answers a Tool call passes.
Documentation
//! What a value of a type is made of, with declarations looked up and their
//! arguments put in place.
//!
//! A reader or writer that walks a value by its type — the binary encoding
//! here, history's slots (`trace.md`, *Values*) — asks the same question at
//! every step: is this a scalar written as a part, a text, a collection of
//! what, a record of which fields, an enum of which constructors? [`form`]
//! answers it once, so each walker matches on the answer rather than on
//! [`Type`] and the [`Catalog`] separately. `Option` and `json.Value` are
//! enums like any other here (`abi.md`, *Each type*).

use std::borrow::Cow;
use std::sync::Arc;

use flow_types::{EnumShape, JsonValueCtor, OptionCtor, RecordShape, StdEnum};

use crate::catalog::{Catalog, StdForm};
use flow_types::{Body, Type};

/// The types written as their encoding and nothing more, never in a slot of
/// their own (`trace.md`, *Slots*).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Scalar {
    /// `Unit`: nothing.
    Unit,
    /// `Bool`: one byte, `0` or `1`.
    Bool,
    /// `Int`: a signed number.
    Int,
    /// `Decimal`: its coefficient and exponent, two signed numbers.
    Decimal,
    /// `Duration`: its seconds, a `Decimal`.
    Duration,
    /// `Instant`: its seconds after the epoch, a `Decimal`.
    Instant,
}

/// What a value of a type is made of.
#[derive(Clone, Debug)]
pub enum Form<'t> {
    /// A scalar.
    Scalar(Scalar),
    /// `Text`.
    Text,
    /// `Bytes`.
    Bytes,
    /// A host type, whose values are the host's tokens.
    Host,
    /// `List<T>`, of this element type.
    List(&'t Type),
    /// `Set<T>`, of this element type.
    Set(&'t Type),
    /// `Dict<K, V>`, of these key and value types.
    Dict(&'t Type, &'t Type),
    /// A tuple, of these part types in order.
    Tuple(&'t [Type]),
    /// A record.
    Record(RecordForm<'t>),
    /// An enum, `Option` and `json.Value` included.
    Enum(EnumForm<'t>),
    /// A newtype, written exactly as its base, this type with the
    /// newtype's arguments in place (`abi.md`, *Each type*), and the form
    /// its values are held to when it is a std type that has one: a value
    /// out of that form is neither written nor read (`abi.md`, *Decoding*).
    Newtype(Type, Option<StdForm>),
    /// `task.Task<T>`, of this result type, which has no encoding outside a
    /// checkpoint's arguments.
    Task(&'t Type),
    /// `Never`, which has no values.
    Never,
    /// A type with no encoding: a function, a nondata declaration, an
    /// unbound type parameter, or an incomplete type.
    NoEncoding,
}

impl<'t> Form<'t> {
    /// The record this is a value of, if it is a record.
    pub fn record(self) -> Option<RecordForm<'t>> {
        if let Form::Record(record) = self {
            Some(record)
        } else {
            None
        }
    }

    /// The enum this is a value of, if it is an enum.
    pub fn enumeration(self) -> Option<EnumForm<'t>> {
        if let Form::Enum(form) = self {
            Some(form)
        } else {
            None
        }
    }

    /// The element type, if this is a list.
    pub fn list(self) -> Option<&'t Type> {
        if let Form::List(item) = self {
            Some(item)
        } else {
            None
        }
    }
}

/// A record type: its shape, and its fields' types in declaration order with
/// the record's arguments in place.
#[derive(Clone, Debug)]
pub struct RecordForm<'t> {
    /// The shape its values are built with, which names the fields.
    pub shape: &'t Arc<RecordShape>,
    /// Each field's type, in declaration order.
    pub fields: Vec<Type>,
}

/// An enum type: its shape, and each constructor's payload types.
#[derive(Clone, Debug)]
pub struct EnumForm<'t> {
    /// The shape its values are built with, which names the constructors
    /// and their payloads.
    pub shape: &'t Arc<EnumShape>,
    parts: Parts<'t>,
}

/// Where an enum's payload types come from.
#[derive(Clone, Debug)]
enum Parts<'t> {
    /// A declaration's, with its arguments.
    Declared {
        ctors: &'t [Vec<Type>],
        args: &'t [Type],
    },
    /// std's `Option<item>`, `Some` at this position.
    Option { item: &'t Type, some: usize },
    /// std's `json.Value`, its constructors bound.
    Json(&'t StdEnum<JsonValueCtor>),
}

/// The payload types of `json.Value`'s constructor `ctor`.
pub(crate) fn json_parts(ctor: JsonValueCtor) -> Vec<Type> {
    match ctor {
        JsonValueCtor::Null => Vec::new(),
        JsonValueCtor::Bool => vec![Type::Bool],
        JsonValueCtor::Number => vec![Type::Decimal],
        JsonValueCtor::Text => vec![Type::Text],
        JsonValueCtor::List => vec![Type::list(Type::Json)],
        JsonValueCtor::Object => vec![Type::dict(Type::Text, Type::Json)],
    }
}

impl<'t> EnumForm<'t> {
    /// The payload types of the constructor numbered `ctor`, counted from 0
    /// in declaration order, with the enum's arguments in place; `None` for
    /// a number the enum has no constructor for. A part the enum's type
    /// holds as it is, such as an `Option`'s item, is borrowed from it.
    pub fn parts(&self, ctor: usize) -> Option<Vec<Cow<'t, Type>>> {
        self.shape.constructor(ctor)?;
        Some(match &self.parts {
            Parts::Declared { ctors, args } => ctors
                .get(ctor)?
                .iter()
                .map(|part| Cow::Owned(part.subst(args)))
                .collect(),
            Parts::Option { item, some } if ctor == *some => vec![Cow::Borrowed(*item)],
            Parts::Option { .. } => Vec::new(),
            Parts::Json(ctors) => ctors
                .which(ctor)
                .map(json_parts)
                .unwrap_or_default()
                .into_iter()
                .map(Cow::Owned)
                .collect(),
        })
    }
}

/// The types of the parts a value of `ty` holds by its structure alone:
/// a list's, set's or `Option`'s item, a dictionary's key and value, a
/// tuple's parts. Each is borrowed for as long as `ty` is, and taken out of
/// it when it is owned.
pub(crate) fn part_types<'a>(ty: &Cow<'a, Type>) -> Vec<Cow<'a, Type>> {
    fn held(ty: &Type) -> Vec<&Type> {
        match ty {
            Type::List(item) | Type::Set(item) | Type::Option(item) => vec![&**item],
            Type::Dict(key, item) => vec![&**key, &**item],
            Type::Tuple(parts) => parts.iter().collect(),
            Type::Unit
            | Type::Bool
            | Type::Int
            | Type::Decimal
            | Type::Text
            | Type::Bytes
            | Type::Duration
            | Type::Instant
            | Type::Json
            | Type::Named(..)
            | Type::Task(_)
            | Type::Never
            | Type::Param(_)
            | Type::Function { .. }
            | Type::NotData => Vec::new(),
        }
    }
    match ty {
        Cow::Borrowed(ty) => held(ty).into_iter().map(Cow::Borrowed).collect(),
        Cow::Owned(ty) => held(ty).into_iter().cloned().map(Cow::Owned).collect(),
    }
}

/// `ty` again, borrowed for as long as it is, or copied when it is owned.
pub(crate) fn reborrow<'a>(ty: &Cow<'a, Type>) -> Cow<'a, Type> {
    match ty {
        Cow::Borrowed(ty) => Cow::Borrowed(ty),
        Cow::Owned(ty) => Cow::Owned(ty.clone()),
    }
}

/// What a value of `ty` is made of, its declaration looked up in `catalog`
/// and its arguments put in place.
///
/// # Panics
///
/// When `ty` names a declaration `catalog` does not have, or is
/// `json.Value` and `catalog` has no `json` module: a type and a catalog
/// built from different programs.
pub fn form<'t>(catalog: &'t Catalog, ty: &'t Type) -> Form<'t> {
    match ty {
        Type::Unit => Form::Scalar(Scalar::Unit),
        Type::Bool => Form::Scalar(Scalar::Bool),
        Type::Int => Form::Scalar(Scalar::Int),
        Type::Decimal => Form::Scalar(Scalar::Decimal),
        Type::Duration => Form::Scalar(Scalar::Duration),
        Type::Instant => Form::Scalar(Scalar::Instant),
        Type::Text => Form::Text,
        Type::Bytes => Form::Bytes,
        Type::List(item) => Form::List(item),
        Type::Set(item) => Form::Set(item),
        Type::Dict(key, value) => Form::Dict(key, value),
        Type::Tuple(parts) => Form::Tuple(parts),
        Type::Option(item) => {
            let option = catalog.option();
            Form::Enum(EnumForm {
                shape: &option.shape,
                parts: Parts::Option {
                    item,
                    some: option.ctors.index(OptionCtor::Some),
                },
            })
        }
        Type::Json => {
            let json = catalog.json();
            Form::Enum(EnumForm {
                shape: &json.shape,
                parts: Parts::Json(&json.ctors),
            })
        }
        Type::Named(decl, args) => match &catalog.decl(*decl).body {
            Body::Record(shape, fields) => Form::Record(RecordForm {
                shape,
                fields: fields.iter().map(|field| field.subst(args)).collect(),
            }),
            Body::Enum(shape, ctors) => Form::Enum(EnumForm {
                shape,
                parts: Parts::Declared { ctors, args },
            }),
            Body::Newtype(base) => {
                Form::Newtype(base.subst(args), StdForm::of(catalog.decl(*decl)))
            }
            Body::Host => Form::Host,
            Body::NonData => Form::NoEncoding,
        },
        Type::Task(result) => Form::Task(result),
        Type::Never => Form::Never,
        Type::Param(_) | Type::Function { .. } | Type::NotData => Form::NoEncoding,
    }
}