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: `json.DecodeError`'s path (`stdlib.md`,
8/// *`json`*), one [`Step`] at a time from the whole value, which is the
9/// empty path.
10///
11/// Its text is the one `json.show_path` writes: a field or a constructor is
12/// its name, joined to what holds it by `.`; an element is its position in
13/// brackets; and a key of an object is the key as a JSON string in brackets:
14/// `steps[2].owner`, `labels["kind"]`.
15#[derive(Clone, Default, PartialEq, Eq, Debug)]
16#[must_use]
17pub struct Place(Vec<Step>);
18
19/// One step of a [`Place`], as `json.Step` names it.
20#[derive(Clone, PartialEq, Eq, Debug)]
21pub enum Step {
22    /// A record field or a named payload field.
23    Field(String),
24    /// The element at this index, counted from 0, of a list, a set, a tuple,
25    /// a positional payload or a `Dict` written as pairs.
26    Element(usize),
27    /// The value under this key of a `Dict` written as a JSON object.
28    Key(String),
29    /// The payload of the enum constructor of this name.
30    Constructor(String),
31}
32
33impl Place {
34    pub(crate) fn field(&mut self, name: &str) {
35        self.0.push(Step::Field(name.to_owned()));
36    }
37
38    pub(crate) fn constructor(&mut self, name: &str) {
39        self.0.push(Step::Constructor(name.to_owned()));
40    }
41
42    pub(crate) fn index(&mut self, index: usize) {
43        self.0.push(Step::Element(index));
44    }
45
46    pub(crate) fn key(&mut self, key: &str) {
47        self.0.push(Step::Key(key.to_owned()));
48    }
49
50    pub(crate) fn push(&mut self, step: Step) {
51        self.0.push(step);
52    }
53
54    pub(crate) fn pop(&mut self) {
55        self.0.pop();
56    }
57
58    /// This place inside the part `outer` reaches, so `outer` comes first.
59    pub fn within(mut self, outer: impl IntoIterator<Item = Step>) -> Place {
60        let mut steps: Vec<Step> = outer.into_iter().collect();
61        steps.append(&mut self.0);
62        Place(steps)
63    }
64
65    /// Its steps, from the whole value inward.
66    pub fn steps(&self) -> &[Step] {
67        &self.0
68    }
69
70    /// Whether it is the whole value.
71    pub fn is_empty(&self) -> bool {
72        self.0.is_empty()
73    }
74}
75
76impl fmt::Display for Place {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        for (at, step) in self.0.iter().enumerate() {
79            match step {
80                Step::Field(name) | Step::Constructor(name) if at == 0 => f.write_str(name)?,
81                Step::Field(name) | Step::Constructor(name) => write!(f, ".{name}")?,
82                Step::Element(index) => write!(f, "[{index}]")?,
83                Step::Key(key) => write!(f, "[{}]", quote(key))?,
84            }
85        }
86        Ok(())
87    }
88}
89
90/// A place equals the text it is written as.
91impl PartialEq<&str> for Place {
92    fn eq(&self, text: &&str) -> bool {
93        /// What is left of the text once each written piece is taken off
94        /// its front; a piece that does not match fails the write.
95        struct Rest<'a>(&'a str);
96        impl fmt::Write for Rest<'_> {
97            fn write_str(&mut self, piece: &str) -> fmt::Result {
98                self.0 = self.0.strip_prefix(piece).ok_or(fmt::Error)?;
99                Ok(())
100            }
101        }
102        let mut rest = Rest(text);
103        fmt::write(&mut rest, format_args!("{self}")).is_ok() && rest.0.is_empty()
104    }
105}
106
107/// Why decoding refused. `path` and `kind` are `json.DecodeError`'s
108/// `path` and `problem` (`stdlib.md`); `problem` says the same for a
109/// person. A Tool reply that fails decoding is no answer, and this explains
110/// why (`abi.md`, *Decoding*).
111#[derive(Clone, PartialEq, Eq, Debug)]
112pub struct DecodeError {
113    /// The place in the value that failed, such as `steps[2].owner`; empty
114    /// for the whole value.
115    pub path: Place,
116    /// What was wrong there, for a person.
117    pub problem: String,
118    /// Which refusal it is: `json.Problem`'s case.
119    pub kind: DecodeErrorKind,
120}
121
122/// Which refusal decoding made: the cases of `json.Problem` (`stdlib.md`).
123#[derive(Clone, Copy, PartialEq, Eq, Debug)]
124pub enum DecodeErrorKind {
125    /// The text is not JSON; `at` is the byte offset where it stops being.
126    Syntax {
127        /// The byte offset, counted from 0.
128        at: usize,
129    },
130    /// A required field is absent.
131    Missing,
132    /// A field or a constructor the type does not have.
133    Unknown,
134    /// One key twice in a JSON object, or two equal keys of a `Dict` or
135    /// elements of a `Set`.
136    Duplicate,
137    /// A value of the wrong kind or form for its type.
138    Mismatch,
139    /// A value past a bound of the host's limits.
140    TooLarge,
141}
142
143impl DecodeError {
144    pub(crate) fn of(path: &Place, kind: DecodeErrorKind, problem: String) -> Self {
145        DecodeError {
146            path: path.clone(),
147            problem,
148            kind,
149        }
150    }
151}
152
153impl DecodeError {
154    /// The error said of `subject`, the value that was decoded, such as an
155    /// input by its name: the subject and then the problem, or, for a place
156    /// inside the value, that place in the subject and then the problem.
157    pub fn for_subject(&self, subject: &str) -> String {
158        if self.path.is_empty() {
159            format!("{subject} {}", self.problem)
160        } else {
161            format!("`{}` in {subject} {}", self.path, self.problem)
162        }
163    }
164}
165
166impl fmt::Display for DecodeError {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        if self.path.is_empty() {
169            write!(f, "the value {}", self.problem)
170        } else {
171            write!(f, "`{}` {}", self.path, self.problem)
172        }
173    }
174}
175
176impl std::error::Error for DecodeError {}
177
178/// Why a value could not be encoded at a type, or a type has no schema.
179///
180/// A checked program never meets one: it is a value that does not have the
181/// type it is encoded at, or a type with no encoding, such as a function's.
182#[derive(Clone, PartialEq, Eq, Debug)]
183pub struct EncodeError {
184    /// The place in the value, as in [`DecodeError::path`].
185    pub path: Place,
186    /// What was wrong there, for a person.
187    pub problem: String,
188    /// Which refusal it is.
189    pub kind: EncodeErrorKind,
190}
191
192/// Which refusal encoding made.
193#[derive(Clone, Copy, PartialEq, Eq, Debug)]
194pub enum EncodeErrorKind {
195    /// The value is not of the type it is encoded at.
196    Mismatch,
197    /// The type has no encoding, such as a function's.
198    NoEncoding,
199    /// The type or a text is past a bound.
200    TooLarge,
201    /// The description written does not validate.
202    Invalid,
203}
204
205impl EncodeError {
206    pub(crate) fn new(path: &Place, kind: EncodeErrorKind, problem: impl Into<String>) -> Self {
207        EncodeError {
208            path: path.clone(),
209            problem: problem.into(),
210            kind,
211        }
212    }
213}
214
215/// A description that does not read back is one that does not validate.
216impl From<DecodeError> for EncodeError {
217    fn from(error: DecodeError) -> Self {
218        EncodeError {
219            path: error.path,
220            problem: error.problem,
221            kind: EncodeErrorKind::Invalid,
222        }
223    }
224}
225
226impl fmt::Display for EncodeError {
227    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228        if self.path.is_empty() {
229            write!(f, "the value {}", self.problem)
230        } else {
231            write!(f, "`{}` {}", self.path, self.problem)
232        }
233    }
234}
235
236impl std::error::Error for EncodeError {}