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
//! Where a value failed to cross, and why.

use std::fmt;

use crate::json::quote;

/// A place inside a value: `json.DecodeError`'s path (`stdlib.md`,
/// *`json`*), one [`Step`] at a time from the whole value, which is the
/// empty path.
///
/// Its text is the one `json.show_path` writes: a field or a constructor is
/// its name, joined to what holds it by `.`; an element is its position in
/// brackets; and a key of an object is the key as a JSON string in brackets:
/// `steps[2].owner`, `labels["kind"]`.
#[derive(Clone, Default, PartialEq, Eq, Debug)]
#[must_use]
pub struct Place(Vec<Step>);

/// One step of a [`Place`], as `json.Step` names it.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Step {
    /// A record field or a named payload field.
    Field(String),
    /// The element at this index, counted from 0, of a list, a set, a tuple,
    /// a positional payload or a `Dict` written as pairs.
    Element(usize),
    /// The value under this key of a `Dict` written as a JSON object.
    Key(String),
    /// The payload of the enum constructor of this name.
    Constructor(String),
}

impl Place {
    pub(crate) fn field(&mut self, name: &str) {
        self.0.push(Step::Field(name.to_owned()));
    }

    pub(crate) fn constructor(&mut self, name: &str) {
        self.0.push(Step::Constructor(name.to_owned()));
    }

    pub(crate) fn index(&mut self, index: usize) {
        self.0.push(Step::Element(index));
    }

    pub(crate) fn key(&mut self, key: &str) {
        self.0.push(Step::Key(key.to_owned()));
    }

    pub(crate) fn push(&mut self, step: Step) {
        self.0.push(step);
    }

    pub(crate) fn pop(&mut self) {
        self.0.pop();
    }

    /// This place inside the part `outer` reaches, so `outer` comes first.
    pub fn within(mut self, outer: impl IntoIterator<Item = Step>) -> Place {
        let mut steps: Vec<Step> = outer.into_iter().collect();
        steps.append(&mut self.0);
        Place(steps)
    }

    /// Its steps, from the whole value inward.
    pub fn steps(&self) -> &[Step] {
        &self.0
    }

    /// Whether it is the whole value.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl fmt::Display for Place {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (at, step) in self.0.iter().enumerate() {
            match step {
                Step::Field(name) | Step::Constructor(name) if at == 0 => f.write_str(name)?,
                Step::Field(name) | Step::Constructor(name) => write!(f, ".{name}")?,
                Step::Element(index) => write!(f, "[{index}]")?,
                Step::Key(key) => write!(f, "[{}]", quote(key))?,
            }
        }
        Ok(())
    }
}

/// A place equals the text it is written as.
impl PartialEq<&str> for Place {
    fn eq(&self, text: &&str) -> bool {
        /// What is left of the text once each written piece is taken off
        /// its front; a piece that does not match fails the write.
        struct Rest<'a>(&'a str);
        impl fmt::Write for Rest<'_> {
            fn write_str(&mut self, piece: &str) -> fmt::Result {
                self.0 = self.0.strip_prefix(piece).ok_or(fmt::Error)?;
                Ok(())
            }
        }
        let mut rest = Rest(text);
        fmt::write(&mut rest, format_args!("{self}")).is_ok() && rest.0.is_empty()
    }
}

/// Why decoding refused. `path` and `kind` are `json.DecodeError`'s
/// `path` and `problem` (`stdlib.md`); `problem` says the same for a
/// person. A Tool reply that fails decoding is no answer, and this explains
/// why (`abi.md`, *Decoding*).
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct DecodeError {
    /// The place in the value that failed, such as `steps[2].owner`; empty
    /// for the whole value.
    pub path: Place,
    /// What was wrong there, for a person.
    pub problem: String,
    /// Which refusal it is: `json.Problem`'s case.
    pub kind: DecodeErrorKind,
}

/// Which refusal decoding made: the cases of `json.Problem` (`stdlib.md`).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum DecodeErrorKind {
    /// The text is not JSON; `at` is the byte offset where it stops being.
    Syntax {
        /// The byte offset, counted from 0.
        at: usize,
    },
    /// A required field is absent.
    Missing,
    /// A field or a constructor the type does not have.
    Unknown,
    /// One key twice in a JSON object, or two equal keys of a `Dict` or
    /// elements of a `Set`.
    Duplicate,
    /// A value of the wrong kind or form for its type.
    Mismatch,
    /// A value past a bound of the host's limits.
    TooLarge,
}

impl DecodeError {
    pub(crate) fn of(path: &Place, kind: DecodeErrorKind, problem: String) -> Self {
        DecodeError {
            path: path.clone(),
            problem,
            kind,
        }
    }
}

impl DecodeError {
    /// The error said of `subject`, the value that was decoded, such as an
    /// input by its name: the subject and then the problem, or, for a place
    /// inside the value, that place in the subject and then the problem.
    pub fn for_subject(&self, subject: &str) -> String {
        if self.path.is_empty() {
            format!("{subject} {}", self.problem)
        } else {
            format!("`{}` in {subject} {}", self.path, self.problem)
        }
    }
}

impl fmt::Display for DecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.path.is_empty() {
            write!(f, "the value {}", self.problem)
        } else {
            write!(f, "`{}` {}", self.path, self.problem)
        }
    }
}

impl std::error::Error for DecodeError {}

/// Why a value could not be encoded at a type, or a type has no schema.
///
/// A checked program never meets one: it is a value that does not have the
/// type it is encoded at, or a type with no encoding, such as a function's.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct EncodeError {
    /// The place in the value, as in [`DecodeError::path`].
    pub path: Place,
    /// What was wrong there, for a person.
    pub problem: String,
    /// Which refusal it is.
    pub kind: EncodeErrorKind,
}

/// Which refusal encoding made.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum EncodeErrorKind {
    /// The value is not of the type it is encoded at.
    Mismatch,
    /// The type has no encoding, such as a function's.
    NoEncoding,
    /// The type or a text is past a bound.
    TooLarge,
    /// The description written does not validate.
    Invalid,
}

impl EncodeError {
    pub(crate) fn new(path: &Place, kind: EncodeErrorKind, problem: impl Into<String>) -> Self {
        EncodeError {
            path: path.clone(),
            problem: problem.into(),
            kind,
        }
    }
}

/// A description that does not read back is one that does not validate.
impl From<DecodeError> for EncodeError {
    fn from(error: DecodeError) -> Self {
        EncodeError {
            path: error.path,
            problem: error.problem,
            kind: EncodeErrorKind::Invalid,
        }
    }
}

impl fmt::Display for EncodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.path.is_empty() {
            write!(f, "the value {}", self.problem)
        } else {
            write!(f, "`{}` {}", self.path, self.problem)
        }
    }
}

impl std::error::Error for EncodeError {}