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

use std::fmt;

use crate::json::quote;

/// A place inside a value, written the way `stdlib.md` writes
/// `json.DecodeError`'s path: `steps[2].owner`.
///
/// A field or a constructor is its name, joined to what holds it by `.`; a
/// list, set, tuple or payload element is its position in brackets; a member
/// of an object keyed by text is the key as a JSON string in brackets,
/// `labels["kind"]`. The whole value is the empty path.
#[derive(Clone, Default, PartialEq, Eq, Debug)]
pub(crate) struct Path(Vec<Step>);

#[derive(Clone, PartialEq, Eq, Debug)]
enum Step {
    Name(String),
    Index(usize),
    Key(String),
}

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

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

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

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

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

/// Why decoding refused. The `path` and `problem` fields are
/// `json.DecodeError`'s shape (`stdlib.md`); `kind` preserves host refusal
/// metadata. A new Tool reply that fails decoding is `BadReply` with this
/// explanation (`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: String,
    /// What was wrong there.
    pub problem: String,
    /// Whether decoding found invalid data or could not finish within this
    /// host's resources. This is host metadata, not a `json.DecodeError` field.
    pub kind: DecodeErrorKind,
}

/// Why decoding refused, independently of its human-readable explanation.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum DecodeErrorKind {
    /// Malformed input or a value that does not fit its declared type.
    Invalid,
    /// The host's size or depth bound prevented decoding.
    Limit,
}

impl DecodeError {
    pub(crate) fn new(path: &Path, problem: String) -> Self {
        DecodeError {
            path: path.to_string(),
            problem,
            kind: DecodeErrorKind::Invalid,
        }
    }

    pub(crate) fn limited(path: &Path, problem: String) -> Self {
        DecodeError {
            path: path.to_string(),
            problem,
            kind: DecodeErrorKind::Limit,
        }
    }
}

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: String,
    /// What was wrong there.
    pub problem: String,
}

impl EncodeError {
    pub(crate) fn new(path: &Path, problem: impl Into<String>) -> Self {
        EncodeError {
            path: path.to_string(),
            problem: problem.into(),
        }
    }
}

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 {}