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
//! Building a value directed by its type, over a stack on the heap.
//!
//! Decoding JSON ([`crate::decode`]), decoding the value encoding
//! ([`crate::binary`]) and rebuilding a value another program made
//! ([`crate::rebuild_by_name`]) differ only in where an aggregate's parts
//! come from. Each is a [`Source`]: it begins a value of a type, done at once
//! or opened as a [`Frame`], and begins a frame's parts one at a time. This
//! module drives them, reading the first few levels by native recursion and
//! keeping the frames deeper than those on the heap, so the native stack
//! does not grow with the value's depth, and makes each
//! aggregate from its parts by one rule. Its time is linear in the parts
//! read, and its memory in the depth of the value and the parts waiting.
//!
//! The loop, [`build`], drives any [`Walk`]: every [`Source`] is one that
//! builds [`Value`]s, and a declared message's reader ([`crate::wire`]) is one
//! that builds the message's own Rust types.

use std::sync::Arc;

use flow_types::{EnumShape, RecordShape};
use flow_value::{Dict, Record, Set, Text, Tuple, Value, Variant};

use crate::catalog::StdForm;
use crate::error::{DecodeError, DecodeErrorKind, Place};
use crate::json::quote;
use crate::limits::Limits;

/// A value whose building has begun: done, or an aggregate whose parts are
/// still to be read.
#[derive(Debug)]
pub(crate) enum Begun<P, M = Make, V = Value> {
    Done(V),
    Open(Frame<P, M, V>),
}

/// An aggregate being built: where its parts come from, what they make, and
/// the values of the parts read so far.
#[derive(Debug)]
pub(crate) struct Frame<P, M = Make, V = Value> {
    pub(crate) parts: P,
    pub(crate) make: M,
    pub(crate) values: Vec<V>,
    /// The level its parts are read at.
    pub(crate) level: usize,
}

impl<P, M, V> Frame<P, M, V> {
    /// Opens the aggregate `make` makes of `parts`, read `level` deep, with
    /// room set aside for `room` values.
    pub(crate) fn open(make: M, parts: P, room: usize, level: usize) -> Begun<P, M, V> {
        Begun::Open(Frame {
            parts,
            make,
            values: Vec::with_capacity(room),
            level,
        })
    }
}

/// What an aggregate's parts make once each is read.
pub(crate) enum Make {
    List,
    Set,
    Tuple,
    Dict,
    Record(Arc<RecordShape>),
    /// A value of the constructor at this index, which the path entered and
    /// leaves once the value is made.
    Variant(Arc<EnumShape>, usize),
    /// A value of the constructor at this index which the source leaves
    /// unwritten, so the path never entered it: an `Option` field's `Some`,
    /// or a `json.Value` read from raw JSON.
    Unwritten(Arc<EnumShape>, usize),
    /// A newtype's value, its base's, held to the std form it has, if any.
    Newtype(Option<StdForm>),
}

/// Where the parts of a value being built come from, and the rules that
/// differ between sources.
pub(crate) trait Source<P> {
    /// Where the source is in the value, for its errors.
    fn path(&mut self) -> &mut Place;

    /// Begins the next part of `frame` and steps the path onto it, or
    /// `None` once every part is read.
    fn next(&mut self, frame: &mut Frame<P>) -> Result<Option<Begun<P>>, DecodeError>;

    /// How many steps the path took onto the part of `frame` just read,
    /// whose value is now the last of `frame.values`.
    fn steps(frame: &Frame<P>) -> usize;

    /// The set of `items`, or why they make none.
    fn set(&self, items: Vec<Value>) -> Result<Set, DecodeError>;

    /// The dictionary of `entries`, or why they make none.
    fn dict(&self, entries: Vec<(Value, Value)>) -> Result<Dict, DecodeError>;

    /// The value of a newtype with the std form `form` whose base's value is
    /// `text`, or why it is none.
    fn form(&self, form: StdForm, text: Text) -> Result<Value, DecodeError>;
}

/// A walk building a `V` from frames of parts `P`, each made by an `M`.
pub(crate) trait Walk<P, M, V> {
    /// Why the walk stops short of a value.
    type Error;

    /// Where the walk is in what it builds, for its errors.
    fn path(&mut self) -> &mut Place;

    /// Begins the next part of `frame` and steps the path onto it, or
    /// `None` once every part is read.
    fn next(&mut self, frame: &mut Frame<P, M, V>) -> Result<Option<Begun<P, M, V>>, Self::Error>;

    /// How many steps the path took onto the part of `frame` just read,
    /// whose value is now the last of `frame.values`.
    fn steps(frame: &Frame<P, M, V>) -> usize;

    /// What `frame`'s parts make, once each is read.
    fn finish(&mut self, frame: Frame<P, M, V>) -> Result<V, Self::Error>;
}

impl<P, S: Source<P>> Walk<P, Make, Value> for S {
    type Error = DecodeError;

    fn path(&mut self) -> &mut Place {
        Source::path(self)
    }

    fn next(&mut self, frame: &mut Frame<P>) -> Result<Option<Begun<P>>, DecodeError> {
        Source::next(self, frame)
    }

    fn steps(frame: &Frame<P>) -> usize {
        <S as Source<P>>::steps(frame)
    }

    fn finish(&mut self, frame: Frame<P>) -> Result<Value, DecodeError> {
        finish(self, frame)
    }
}

/// How many levels of a value [`build`] reads by native recursion before it
/// goes on over a stack on the heap: as deep as most values nest, and few
/// enough that their frames fit a small thread's stack.
const NATIVE_DEPTH: usize = 8;

/// What `root` begins, its parts read by `walk`.
pub(crate) fn build<P, M, V, W: Walk<P, M, V>>(
    walk: &mut W,
    root: Begun<P, M, V>,
) -> Result<V, W::Error> {
    match root {
        Begun::Done(value) => Ok(value),
        Begun::Open(frame) => build_within(walk, frame, NATIVE_DEPTH),
    }
}

/// What `frame`'s parts make, read by native recursion for at most `room`
/// more levels and over a stack on the heap past them.
fn build_within<P, M, V, W: Walk<P, M, V>>(
    walk: &mut W,
    mut frame: Frame<P, M, V>,
    room: usize,
) -> Result<V, W::Error> {
    let Some(room) = room.checked_sub(1) else {
        return build_on_heap(walk, frame);
    };
    while let Some(part) = walk.next(&mut frame)? {
        let value = match part {
            Begun::Done(value) => value,
            Begun::Open(part) => build_within(walk, part, room)?,
        };
        made(walk, &mut frame, value);
    }
    walk.finish(frame)
}

/// What `root`'s parts make, the frames being read kept on the heap.
fn build_on_heap<P, M, V, W: Walk<P, M, V>>(
    walk: &mut W,
    root: Frame<P, M, V>,
) -> Result<V, W::Error> {
    let mut open = vec![root];
    loop {
        let frame = open
            .last_mut()
            .expect("a frame is open until the root is made");
        let value = match walk.next(frame)? {
            Some(Begun::Open(part)) => {
                open.push(part);
                continue;
            }
            Some(Begun::Done(value)) => value,
            None => {
                let frame = open.pop().expect("the frame just read");
                let value = walk.finish(frame)?;
                let Some(frame) = open.last_mut() else {
                    return Ok(value);
                };
                made(walk, frame, value);
                continue;
            }
        };
        made(walk, frame, value);
    }
}

/// Gives `frame` the value of the part just read, stepping the path back
/// off it.
fn made<P, M, V, W: Walk<P, M, V>>(walk: &mut W, frame: &mut Frame<P, M, V>, value: V) {
    frame.values.push(value);
    for _ in 0..W::steps(frame) {
        walk.path().pop();
    }
}

/// The value `frame`'s parts make, once each is read.
fn finish<P, S: Source<P>>(source: &mut S, frame: Frame<P>) -> Result<Value, DecodeError> {
    let mut values = frame.values.into_iter();
    Ok(match frame.make {
        Make::List => Value::List(values.collect()),
        Make::Set => Value::Set(source.set(values.collect())?),
        Make::Tuple => Value::Tuple(Tuple::new(values)),
        Make::Dict => {
            let entries = std::iter::from_fn(|| Some((values.next()?, values.next()?)));
            Value::Dict(source.dict(entries.collect())?)
        }
        Make::Record(shape) => {
            Value::Record(Record::new(shape, values.collect()).expect("one value per field"))
        }
        Make::Variant(shape, index) => {
            source.path().pop();
            Value::Variant(
                Variant::new(shape, index, values.collect()).expect("one value per part"),
            )
        }
        Make::Unwritten(shape, index) => Value::Variant(
            Variant::new(shape, index, values.collect()).expect("one value per part"),
        ),
        Make::Newtype(form) => match (form, values.next().expect("a newtype's one value")) {
            (Some(form), Value::Text(text)) => source.form(form, text)?,
            (_, value) => value,
        },
    })
}

/// The one value `text` denotes as a value of the std form `form`, from any
/// spelling of it, within `limits` (`abi.md`, *Decoding*); `path` names
/// where, if it is none.
pub(crate) fn normal(
    form: StdForm,
    text: &Text,
    limits: &Limits,
    path: &Place,
) -> Result<Value, DecodeError> {
    let Some(normal) = form.normal(text.as_str()) else {
        return Err(DecodeError::of(
            path,
            DecodeErrorKind::Mismatch,
            format!("is {}, which is not {}", quote(text.as_str()), form.noun()),
        ));
    };
    if normal.len() > limits.text_bytes {
        return Err(DecodeError::of(
            path,
            DecodeErrorKind::TooLarge,
            format!("is longer than {} bytes", limits.text_bytes),
        ));
    }
    Ok(Value::Text(Text::new(&normal)))
}

/// The set of `items`, refused when two are equal; `path` names where.
pub(crate) fn distinct_set(items: Vec<Value>, path: &Place) -> Result<Set, DecodeError> {
    let count = items.len();
    let set = Set::from_items(items).expect("values read at a set's type are data");
    if set.len() != count {
        return Err(DecodeError::of(
            path,
            DecodeErrorKind::Duplicate,
            "has two equal elements".to_owned(),
        ));
    }
    Ok(set)
}

/// The dictionary of `entries`, refused when two keys are equal; `path`
/// names where.
pub(crate) fn distinct_dict(
    entries: Vec<(Value, Value)>,
    path: &Place,
) -> Result<Dict, DecodeError> {
    let count = entries.len();
    let dict = Dict::from_entries(entries).expect("keys read at a dictionary's type are data");
    if dict.len() != count {
        return Err(DecodeError::of(
            path,
            crate::error::DecodeErrorKind::Duplicate,
            "has two equal keys".to_owned(),
        ));
    }
    Ok(dict)
}