flow-abi 0.1.0

The value encoding at the host boundary: type-directed JSON encoding and decoding, the canonical form and its hash, JSON Schemas, and Tool declaration fingerprints.
Documentation
//! The types the encoding is directed by, 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 [`Catalog`] 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 flow_value::{EnumShape, RecordShape};

use crate::decode::Mode;
use crate::judge::{Judgment, Summaries, judge, summarize};

/// A type, as the encoding sees it.
#[derive(Clone, PartialEq, Eq, Hash, 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 in a checkpoint's
    /// arguments: there a task is the id of the call it is parked on
    /// ([`crate::encode_checkpoint`], [`crate::rebuild`]).
    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 {
    /// `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 {
        match self {
            Type::Param(index) => args
                .get(*index as usize)
                .cloned()
                .unwrap_or_else(|| self.clone()),
            Type::List(item) => Type::list(item.subst(args)),
            Type::Set(item) => Type::set(item.subst(args)),
            Type::Option(item) => Type::option(item.subst(args)),
            Type::Task(item) => Type::Task(Box::new(item.subst(args))),
            Type::Function { params, result } => Type::Function {
                params: params.iter().map(|param| param.subst(args)).collect(),
                result: Box::new(result.subst(args)),
            },
            Type::Dict(key, value) => Type::dict(key.subst(args), value.subst(args)),
            Type::Tuple(parts) => Type::Tuple(parts.iter().map(|part| part.subst(args)).collect()),
            Type::Named(decl, inner) => {
                Type::Named(*decl, inner.iter().map(|arg| arg.subst(args)).collect())
            }
            _ => self.clone(),
        }
    }
}

/// A declaration's place in its [`Catalog`].
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct DeclId(pub u32);

/// Where a declaration lives: `abi.md`'s *Identity*.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub enum Origin {
    /// A public logical module in an independently versioned package.
    Package {
        /// Publisher and package name.
        package: String,
        /// Selected package version.
        version: String,
        /// Logical source-module key; empty for the default module.
        file: String,
    },
    /// A file in a repository at its resolved version, such as
    /// `github.com/acme/tools`, `v1.2.0` and `openai`; std is the repository
    /// `std` at its major version.
    Repository {
        /// The repository.
        repository: String,
        /// The version it resolved to.
        version: String,
        /// The file's path inside the repository, without its extension.
        file: String,
    },
    /// A file outside any repository, by its path.
    File {
        /// The path.
        path: String,
    },
}

/// A declaration's identity: where it lives and its name (`abi.md`,
/// *Identity and fingerprints*). Written `repository@version/file.Name`, or
/// `path.Name` for a file outside any repository.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct Identity {
    /// Where it lives.
    pub origin: Origin,
    /// Its name.
    pub name: String,
}

impl fmt::Display for Identity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.origin {
            Origin::Package {
                package,
                version,
                file,
            } => {
                write!(f, "{package}@{version}")?;
                if !file.is_empty() {
                    write!(f, "/{file}")?;
                }
                write!(f, ".{}", self.name)
            }
            Origin::Repository {
                repository,
                version,
                file,
            } => write!(f, "{repository}@{version}/{file}.{}", self.name),
            Origin::File { path } => write!(f, "{path}.{}", self.name),
        }
    }
}

/// 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 `@tool type`, whose values are the host's tokens.
    Host,
    /// A declared nondata type, retained by nominal identity only.
    NonData,
}

/// The declarations a set of types names, with the std enums whose values
/// the encoding builds itself.
#[derive(Clone, Debug)]
pub struct Catalog {
    decls: Vec<Decl>,
    summaries: Summaries,
    option: Lang<2>,
    json: Option<Lang<6>>,
}

/// A std enum and its constructors' positions, by name.
#[derive(Clone, Debug)]
pub(crate) struct Lang<const N: usize> {
    pub(crate) shape: Arc<EnumShape>,
    pub(crate) at: [usize; N],
}

impl<const N: usize> Lang<N> {
    fn find(shape: Arc<EnumShape>, names: [&str; N]) -> Option<Self> {
        let mut at = [0; N];
        for (slot, name) in at.iter_mut().zip(names) {
            *slot = (0..)
                .map_while(|index| shape.constructor(index))
                .position(|ctor| ctor.name() == name)?;
        }
        Some(Lang { shape, at })
    }
}

/// The constructors of `json.Value`, in the order [`Lang`] holds them.
pub(crate) const JSON_CTORS: [&str; 6] = ["Null", "Bool", "Number", "Text", "List", "Object"];

impl Catalog {
    /// Returns the catalog of `decls`, where the `n`th is [`DeclId`] `n`,
    /// with std's `Option` (`None`, `Some(T)`) and, when the program has it,
    /// `json.Value`.
    ///
    /// Returns `None` when either shape lacks a constructor std declares.
    pub fn new(
        decls: Vec<Decl>,
        option: Arc<EnumShape>,
        json: Option<Arc<EnumShape>>,
    ) -> Option<Self> {
        let option = Lang::find(option, ["None", "Some"])?;
        let json = match json {
            Some(shape) => Some(Lang::find(shape, JSON_CTORS)?),
            None => None,
        };
        Some(Catalog {
            summaries: summarize(&decls),
            decls,
            option,
            json,
        })
    }

    /// The declaration `id` names.
    ///
    /// # Panics
    ///
    /// When `id` is not one of this catalog's.
    pub fn decl(&self, id: DeclId) -> &Decl {
        &self.decls[id.0 as usize]
    }

    /// Every declaration, by id.
    pub fn decls(&self) -> impl ExactSizeIterator<Item = (DeclId, &Decl)> {
        self.decls.iter().enumerate().map(|(index, decl)| {
            (
                DeclId(u32::try_from(index).expect("a catalog fits 32-bit ids")),
                decl,
            )
        })
    }

    /// The first thing decoding can't build in `ty`, in `mode`, if any.
    pub(crate) fn judge(&self, ty: &Type, mode: Mode) -> Option<String> {
        judge(&self.decls, &self.summaries, ty, mode.into())
    }

    pub(crate) fn crossing_problem(&self, ty: &Type) -> Option<String> {
        judge(&self.decls, &self.summaries, ty, Judgment::Crossing)
    }

    pub(crate) fn option(&self) -> &Lang<2> {
        &self.option
    }

    pub(crate) fn json(&self) -> &Lang<6> {
        self.json
            .as_ref()
            .expect("a program that names json.Value has std's json module")
    }

    /// How `ty` is written in a schema's `$defs` key and in messages:
    /// built-in types by name, declarations by identity, with arguments.
    pub fn name(&self, ty: &Type) -> String {
        self.written(ty, true)
    }

    /// `ty` written as [`Catalog::name`] writes it, with or without each
    /// declaration's repository version.
    pub(crate) fn written(&self, ty: &Type, versions: bool) -> String {
        let join = |parts: &[Type]| {
            parts
                .iter()
                .map(|part| self.written(part, versions))
                .collect::<Vec<_>>()
                .join(", ")
        };
        let one = |item: &Type| self.written(item, versions);
        match ty {
            Type::Int => "Int".into(),
            Type::Decimal => "Decimal".into(),
            Type::Bool => "Bool".into(),
            Type::Text => "Text".into(),
            Type::Bytes => "Bytes".into(),
            Type::Duration => "Duration".into(),
            Type::Instant => "Instant".into(),
            Type::Unit => "Unit".into(),
            Type::Never => "Never".into(),
            Type::Json => "json.Value".into(),
            Type::List(item) => format!("List<{}>", one(item)),
            Type::Set(item) => format!("Set<{}>", one(item)),
            Type::Option(item) => format!("Option<{}>", one(item)),
            Type::Task(item) => format!("task.Task<{}>", one(item)),
            Type::Dict(key, value) => format!("Dict<{}, {}>", one(key), one(value)),
            Type::Tuple(parts) => format!("({})", join(parts)),
            Type::Named(decl, args) => {
                let identity = &self.decl(*decl).identity;
                let base = match (&identity.origin, versions) {
                    (Origin::Package { package, file, .. }, false) => {
                        if file.is_empty() {
                            format!("{package}.{}", identity.name)
                        } else {
                            format!("{package}/{file}.{}", identity.name)
                        }
                    }
                    (
                        Origin::Repository {
                            repository, file, ..
                        },
                        false,
                    ) => format!("{repository}/{file}.{}", identity.name),
                    _ => identity.to_string(),
                };
                if args.is_empty() {
                    base
                } else {
                    format!("{base}<{}>", join(args))
                }
            }
            Type::Param(index) => format!("${index}"),
            Type::Function { params, result } => format!("({}) -> {}", join(params), one(result)),
            Type::NotData => "a type that is not data".into(),
        }
    }
}