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
//! Which types decoding may build and existing values may carry across a
//! boundary (`tools.md`, *Decoding* and *JSON*).
//!
//! A type decoding can't build is, or contains, an `opaque` type, a type with
//! no encoding, or — in a run's input, which is data — a host type. "Contains"
//! is judged of the type, not of a value: an `Option` of an opaque type is
//! refused even when the text holds `None`. Rebuilding a value the program
//! made is not decoding, and refuses no type but an unbound type parameter
//! (`abi.md`, *Decoding*): a part with no encoding, such as a function, is
//! rebuilt where it holds no value, as in an empty list, and refused by the
//! text where it holds one.
//!
//! The judgment is made once per declaration, when the catalog is built, as
//! a fixpoint over two facts each declaration can only gain: the first
//! problem its fields reach whatever its arguments, and which of its type
//! parameters its fields reach. A type is then judged by walking it alone and
//! consulting those facts at each declaration, so a declaration that applies
//! itself to ever larger arguments is judged as surely as any other, and no
//! instance of it is ever built.

use crate::DecodeError;
use crate::decode::Mode;
use crate::types::{Body, Catalog, Decl, Type};

/// What a declaration's fields reach, in one mode.
#[derive(Clone, Default, PartialEq, Eq, Debug)]
pub(crate) struct Summary {
    /// The first thing decoding can't build that the fields reach whatever
    /// the arguments are.
    problem: Option<String>,
    /// Whether the fields reach each type parameter, so that its argument
    /// must be judged too.
    uses: Vec<bool>,
    /// Parameters occurring as an Option operand after nominal substitution.
    /// Only a concrete json.Value operand makes that conditional crossing invalid.
    option_uses: Vec<bool>,
}

/// Whether an existing value can cross a Tool boundary. Opaque values and
/// host tokens may be sent; functions, tasks, nondata and ambiguous
/// `Option<json.Value>` parts may not. Nominal arguments unused by fields
/// are descriptions rather than value parts.
pub fn crossable(catalog: &Catalog, ty: &Type) -> Result<(), DecodeError> {
    match catalog.crossing_problem(ty) {
        Some(problem) => Err(DecodeError {
            path: String::new(),
            problem,
            kind: crate::DecodeErrorKind::Invalid,
        }),
        None => Ok(()),
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Judgment {
    Reply,
    Input,
    Rebuild,
    Crossing,
}
impl From<Mode> for Judgment {
    fn from(mode: Mode) -> Self {
        match mode {
            Mode::Reply => Self::Reply,
            Mode::Input => Self::Input,
            Mode::Rebuild => Self::Rebuild,
        }
    }
}
/// Cached judgments share the same field-use fixpoint.
pub(crate) type Summaries = Vec<[Summary; 4]>;
const MODES: [Judgment; 4] = [
    Judgment::Reply,
    Judgment::Input,
    Judgment::Rebuild,
    Judgment::Crossing,
];
fn slot(mode: Judgment) -> usize {
    match mode {
        Judgment::Reply => 0,
        Judgment::Input => 1,
        Judgment::Rebuild => 2,
        Judgment::Crossing => 3,
    }
}

/// Summarizes every declaration of `decls`.
pub(crate) fn summarize(decls: &[Decl]) -> Summaries {
    let mut summaries: Summaries = decls
        .iter()
        .map(|decl| {
            let blank = Summary {
                problem: None,
                uses: vec![false; decl.params.len()],
                option_uses: vec![false; decl.params.len()],
            };
            [blank.clone(), blank.clone(), blank.clone(), blank]
        })
        .collect();
    // Each round can only add facts, and a round that adds none ends the
    // search. Each mode's facts grow on their own, so the search needs at most
    // one round per fact a mode can hold, plus one.
    let facts: usize = decls.iter().map(|decl| 2 * decl.params.len() + 1).sum();
    for _ in 0..=facts {
        if !round(decls, &mut summaries) {
            break;
        }
    }
    summaries
}

/// One round of the search: every declaration's summaries recomputed from
/// the others'. Returns whether any changed.
fn round(decls: &[Decl], summaries: &mut Summaries) -> bool {
    let mut changed = false;
    for (index, decl) in decls.iter().enumerate() {
        for mode in MODES {
            let fields: Vec<&Type> = match &decl.body {
                Body::Record(_, fields) => fields.iter().collect(),
                Body::Enum(_, ctors) => ctors.iter().flatten().collect(),
                Body::Host | Body::NonData => Vec::new(),
            };
            let mut next = summaries[index][slot(mode)].clone();
            for field in fields {
                let problem = walk(
                    decls,
                    summaries,
                    mode,
                    field,
                    &mut |param, option_operand| {
                        if let Some(used) = next.uses.get_mut(param as usize) {
                            *used = true;
                        }
                        if option_operand
                            && let Some(used) = next.option_uses.get_mut(param as usize)
                        {
                            *used = true;
                        }
                    },
                );
                if next.problem.is_none() {
                    next.problem = problem;
                }
            }
            if next != summaries[index][slot(mode)] {
                summaries[index][slot(mode)] = next;
                changed = true;
            }
        }
    }
    changed
}

/// The first obstacle in `ty` for the selected judgment, if any.
pub(crate) fn judge(
    decls: &[Decl],
    summaries: &Summaries,
    ty: &Type,
    mode: Judgment,
) -> Option<String> {
    let mut unbound = false;
    let problem = walk(decls, summaries, mode, ty, &mut |_, _| unbound = true);
    problem.or_else(|| unbound.then(no_encoding))
}

fn no_encoding() -> String {
    "has a type with no encoding".into()
}

/// Walks `ty`, reporting each type parameter it reaches to `on_param`, and
/// returns the first obstacle the selected judgment reaches.
fn walk(
    decls: &[Decl],
    summaries: &Summaries,
    mode: Judgment,
    ty: &Type,
    on_param: &mut dyn FnMut(u32, bool),
) -> Option<String> {
    match ty {
        Type::Option(item) if mode == Judgment::Crossing => {
            option_operand(item, on_param).or_else(|| walk(decls, summaries, mode, item, on_param))
        }
        Type::List(item) | Type::Set(item) | Type::Option(item) => {
            walk(decls, summaries, mode, item, on_param)
        }
        Type::Dict(key, value) => walk(decls, summaries, mode, key, on_param)
            .or_else(|| walk(decls, summaries, mode, value, on_param)),
        Type::Tuple(parts) => parts
            .iter()
            .find_map(|part| walk(decls, summaries, mode, part, on_param)),
        Type::Named(id, args) => {
            let decl = &decls[id.0 as usize];
            if decl.opaque && matches!(mode, Judgment::Reply | Judgment::Input) {
                return Some(format!(
                    "has the type {}, which is opaque, so it can't be decoded",
                    decl.identity
                ));
            }
            if matches!(decl.body, Body::Host) && mode == Judgment::Input {
                return Some(format!(
                    "has the host type {}, which a run's input can't carry",
                    decl.identity
                ));
            }
            if matches!(decl.body, Body::NonData) && mode != Judgment::Rebuild {
                return Some(no_encoding());
            }
            let summary = &summaries[id.0 as usize][slot(mode)];
            if let Some(problem) = &summary.problem {
                return Some(problem.clone());
            }
            if mode == Judgment::Crossing {
                for (arg, used) in args.iter().zip(&summary.option_uses) {
                    if *used && let Some(problem) = option_operand(arg, on_param) {
                        return Some(problem);
                    }
                }
            }
            args.iter()
                .zip(&summary.uses)
                .filter(|(_, used)| **used)
                .find_map(|(arg, _)| walk(decls, summaries, mode, arg, on_param))
        }
        Type::Param(index) => {
            on_param(*index, false);
            None
        }
        Type::Task(_) | Type::Function { .. } | Type::NotData if mode == Judgment::Rebuild => None,
        Type::Task(_) | Type::Function { .. } | Type::NotData => Some(no_encoding()),
        Type::Int
        | Type::Decimal
        | Type::Bool
        | Type::Text
        | Type::Bytes
        | Type::Duration
        | Type::Instant
        | Type::Unit
        | Type::Never
        | Type::Json => None,
    }
}

/// An Option operand is ambiguous only when substitution makes it json.Value.
/// Other constructors preserve their outer identity under substitution.
fn option_operand(ty: &Type, on_param: &mut dyn FnMut(u32, bool)) -> Option<String> {
    match ty {
        Type::Json => Some("has an Option<json.Value> part, which cannot cross a boundary".into()),
        Type::Param(index) => {
            on_param(*index, true);
            None
        }
        _ => None,
    }
}