Skip to main content

flow_abi/
error.rs

1//! Where a value failed to cross, and why.
2
3use std::fmt;
4
5use crate::json::quote;
6
7/// A place inside a value, written the way `stdlib.md` writes
8/// `json.DecodeError`'s path: `steps[2].owner`.
9///
10/// A field or a constructor is its name, joined to what holds it by `.`; a
11/// list, set, tuple or payload element is its position in brackets; a member
12/// of an object keyed by text is the key as a JSON string in brackets,
13/// `labels["kind"]`. The whole value is the empty path.
14#[derive(Clone, Default, PartialEq, Eq, Debug)]
15pub(crate) struct Path(Vec<Step>);
16
17#[derive(Clone, PartialEq, Eq, Debug)]
18enum Step {
19    Name(String),
20    Index(usize),
21    Key(String),
22}
23
24impl Path {
25    pub(crate) fn name(&mut self, name: &str) {
26        self.0.push(Step::Name(name.to_owned()));
27    }
28
29    pub(crate) fn index(&mut self, index: usize) {
30        self.0.push(Step::Index(index));
31    }
32
33    pub(crate) fn key(&mut self, key: &str) {
34        self.0.push(Step::Key(key.to_owned()));
35    }
36
37    pub(crate) fn pop(&mut self) {
38        self.0.pop();
39    }
40}
41
42impl fmt::Display for Path {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        for (at, step) in self.0.iter().enumerate() {
45            match step {
46                Step::Name(name) if at == 0 => f.write_str(name)?,
47                Step::Name(name) => write!(f, ".{name}")?,
48                Step::Index(index) => write!(f, "[{index}]")?,
49                Step::Key(key) => write!(f, "[{}]", quote(key))?,
50            }
51        }
52        Ok(())
53    }
54}
55
56/// Why decoding refused. The `path` and `problem` fields are
57/// `json.DecodeError`'s shape (`stdlib.md`); `kind` preserves host refusal
58/// metadata. A new Tool reply that fails decoding is `BadReply` with this
59/// explanation (`abi.md`, *Decoding*).
60#[derive(Clone, PartialEq, Eq, Debug)]
61pub struct DecodeError {
62    /// The place in the value that failed, such as `steps[2].owner`; empty
63    /// for the whole value.
64    pub path: String,
65    /// What was wrong there.
66    pub problem: String,
67    /// Whether decoding found invalid data or could not finish within this
68    /// host's resources. This is host metadata, not a `json.DecodeError` field.
69    pub kind: DecodeErrorKind,
70}
71
72/// Why decoding refused, independently of its human-readable explanation.
73#[derive(Clone, Copy, PartialEq, Eq, Debug)]
74pub enum DecodeErrorKind {
75    /// Malformed input or a value that does not fit its declared type.
76    Invalid,
77    /// The host's size or depth bound prevented decoding.
78    Limit,
79}
80
81impl DecodeError {
82    pub(crate) fn new(path: &Path, problem: String) -> Self {
83        DecodeError {
84            path: path.to_string(),
85            problem,
86            kind: DecodeErrorKind::Invalid,
87        }
88    }
89
90    pub(crate) fn limited(path: &Path, problem: String) -> Self {
91        DecodeError {
92            path: path.to_string(),
93            problem,
94            kind: DecodeErrorKind::Limit,
95        }
96    }
97}
98
99impl fmt::Display for DecodeError {
100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101        if self.path.is_empty() {
102            write!(f, "the value {}", self.problem)
103        } else {
104            write!(f, "`{}` {}", self.path, self.problem)
105        }
106    }
107}
108
109impl std::error::Error for DecodeError {}
110
111/// Why a value could not be encoded at a type, or a type has no schema.
112///
113/// A checked program never meets one: it is a value that does not have the
114/// type it is encoded at, or a type with no encoding, such as a function's.
115#[derive(Clone, PartialEq, Eq, Debug)]
116pub struct EncodeError {
117    /// The place in the value, as in [`DecodeError::path`].
118    pub path: String,
119    /// What was wrong there.
120    pub problem: String,
121}
122
123impl EncodeError {
124    pub(crate) fn new(path: &Path, problem: impl Into<String>) -> Self {
125        EncodeError {
126            path: path.to_string(),
127            problem: problem.into(),
128        }
129    }
130}
131
132impl fmt::Display for EncodeError {
133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134        if self.path.is_empty() {
135            write!(f, "the value {}", self.problem)
136        } else {
137            write!(f, "`{}` {}", self.path, self.problem)
138        }
139    }
140}
141
142impl std::error::Error for EncodeError {}