Skip to main content

flow_runner/common/
error.rs

1//! Every error a host can get back, and the wording they share. Code in a
2//! message is in backticks.
3
4use crate::common::diagnostic::{Diagnostic, Diagnostics};
5use crate::common::limits::{MAX_LISTED_NAMES, MAX_TOKEN_STATE, MAX_VALUE_DEPTH};
6use std::fmt;
7use temple_dsl::{EvalError, Span, Value};
8
9/// Why a stored flow couldn't be loaded.
10#[derive(Debug, Clone)]
11#[non_exhaustive]
12pub enum LoadError {
13    /// The bytes are damaged, or aren't a flow blob.
14    Corrupt(String),
15    /// Saved with another blob layout. Compile the flow's source again.
16    IncompatibleVersion {
17        /// The blob's version.
18        found: u32,
19        /// [`BLOB_VERSION`](crate::BLOB_VERSION).
20        expected: u32,
21    },
22    /// The source compiles, but to another hash than the one saved with it:
23    /// this flow-runner reads the flow differently from the one that saved
24    /// it. Tokens made before won't run until
25    /// [rebound](crate::Flow::rebind); compile the source again to accept
26    /// the new hash.
27    HashChanged,
28    /// The source no longer compiles, e.g. it was saved by a newer
29    /// flow-runner that knows an edition this one doesn't.
30    Invalid(Diagnostics),
31}
32
33impl fmt::Display for LoadError {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        match self {
36            LoadError::Corrupt(why) => write!(f, "corrupt flow blob: {why}"),
37            LoadError::IncompatibleVersion { found, expected } => write!(
38                f,
39                "flow blob version {found} is not {expected}; compile the source again"
40            ),
41            LoadError::HashChanged => write!(
42                f,
43                "the flow now has another hash; tokens made before need rebinding"
44            ),
45            LoadError::Invalid(errors) => write!(f, "stored flow no longer compiles: {errors}"),
46        }
47    }
48}
49
50impl std::error::Error for LoadError {}
51
52impl LoadError {
53    /// Damaged bytes, and why they can't be read.
54    pub(crate) fn corrupt(why: impl Into<String>) -> Self {
55        LoadError::Corrupt(why.into())
56    }
57}
58
59/// Why a run failed.
60#[derive(Debug, Clone, PartialEq)]
61#[non_exhaustive]
62pub enum RunError {
63    /// An expression failed or ran out of budget.
64    Expression {
65        /// The node it is in; `None` for a flow-level let.
66        node: Option<String>,
67        /// What temple reported.
68        error: ExpressionError,
69    },
70    /// A guard produced something other than true or false.
71    GuardNotBool {
72        /// The node the guard is in.
73        node: String,
74        /// What it produced.
75        got: String,
76        /// Where the guard is in the source.
77        span: Span,
78    },
79    /// `wake` produced something other than a whole number of epoch seconds.
80    WakeNotTime {
81        /// The node the `wake` is in.
82        node: String,
83        /// What it produced.
84        got: String,
85        /// Where the `wake` expression is in the source.
86        span: Span,
87    },
88    /// More jumps in one run than [`Limits::jumps`](crate::Limits::jumps).
89    TooManyJumps {
90        /// The limit.
91        limit: u64,
92        /// The node that would have jumped once too often.
93        node: String,
94    },
95    /// More asks in one instance than [`Limits::asks`](crate::Limits::asks).
96    TooManyAsks {
97        /// The limit.
98        limit: u64,
99        /// The node that would have asked once too often.
100        node: String,
101    },
102    /// A value too deeply nested to store in a token.
103    ValueTooDeep {
104        /// The node that would have stored it.
105        node: String,
106    },
107    /// The node arguments and params a token would carry are over `limit`
108    /// bytes. Keep large data in the host and pass it in `input.data`.
109    TokenTooLarge {
110        /// The node that would have made the token.
111        node: String,
112        /// The limit, in bytes.
113        limit: u64,
114    },
115    /// A run that answered an ask reached `ignore`. An answer has to lead to
116    /// a value or another ask; otherwise it would be lost.
117    AnswerIgnored {
118        /// The node with the `ignore`.
119        node: String,
120    },
121    /// A run jumped, then reached `ignore`. A jump has to lead to a value or
122    /// an ask; otherwise the event that caused it would be lost.
123    JumpIgnored {
124        /// The node with the `ignore`.
125        node: String,
126    },
127}
128
129/// A temple evaluation error, flattened so [`RunError`] can compare equal.
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct ExpressionError {
132    /// What went wrong, as temple words it.
133    pub message: String,
134    /// Where in the flow's source, when temple knows.
135    pub span: Option<Span>,
136    /// The run used up [`Limits::steps`](crate::Limits::steps).
137    pub budget_exceeded: bool,
138}
139
140impl From<EvalError> for ExpressionError {
141    fn from(error: EvalError) -> Self {
142        ExpressionError {
143            message: error.to_string(),
144            span: error.span(),
145            budget_exceeded: error.is_budget_exceeded(),
146        }
147    }
148}
149
150impl RunError {
151    /// Where in the flow's source the run failed, when that is one place.
152    pub fn span(&self) -> Option<Span> {
153        match self {
154            RunError::Expression { error, .. } => error.span,
155            RunError::GuardNotBool { span, .. } | RunError::WakeNotTime { span, .. } => Some(*span),
156            _ => None,
157        }
158    }
159
160    /// Whether the run used up [`Limits::steps`](crate::Limits::steps).
161    pub fn is_budget_exceeded(&self) -> bool {
162        matches!(self, RunError::Expression { error, .. } if error.budget_exceeded)
163    }
164
165    /// An underlined snippet against the flow's source.
166    pub fn report(&self, src: &str) -> String {
167        match self.span() {
168            Some(span) => Diagnostic::error(span, self.to_string()).report(src),
169            None => format!("error: {self}"),
170        }
171    }
172}
173
174impl fmt::Display for RunError {
175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176        match self {
177            RunError::Expression {
178                node: Some(node),
179                error,
180            } => write!(f, "in node `{node}`: {}", error.message),
181            RunError::Expression { node: None, error } => {
182                write!(f, "in a flow-level let: {}", error.message)
183            }
184            RunError::GuardNotBool { node, got, .. } => write!(
185                f,
186                "in node `{node}`: a guard must be true or false, got {got}"
187            ),
188            RunError::WakeNotTime { node, got, .. } => write!(
189                f,
190                "in node `{node}`: `wake` must be a whole number of epoch seconds, got {got}"
191            ),
192            RunError::TooManyJumps { limit, node } => {
193                write!(f, "in node `{node}`: more than {limit} jumps in one run")
194            }
195            RunError::TooManyAsks { limit, node } => write!(
196                f,
197                "in node `{node}`: the instance would ask more than {limit} times"
198            ),
199            RunError::ValueTooDeep { node } => write!(
200                f,
201                "in node `{node}`: {}",
202                too_deep("a value the token would store", MAX_VALUE_DEPTH)
203            ),
204            RunError::TokenTooLarge { node, limit } => write!(
205                f,
206                "in node `{node}`: the state the token would carry is over {limit} bytes; keep large data in the host and pass it in `input.data`"
207            ),
208            RunError::AnswerIgnored { node } => write!(
209                f,
210                "in node `{node}`: the answer to an ask reached `ignore`, so it would be lost; after an ask, every path must end in a value or another ask"
211            ),
212            RunError::JumpIgnored { node } => write!(
213                f,
214                "in node `{node}`: the run jumped here and reached `ignore`, so the event would be lost; after a jump, every path must end in a value or an ask"
215            ),
216        }
217    }
218}
219
220impl std::error::Error for RunError {}
221
222/// A mistake by the host: the run didn't start, and nothing was evaluated.
223#[derive(Debug, Clone, PartialEq, Eq)]
224#[non_exhaustive]
225pub enum InputError {
226    /// No entry node has this name.
227    UnknownEntry(String),
228    /// The flow doesn't declare this event, and it isn't `tick`.
229    UnknownEvent(String),
230    /// The flow has no param with this name.
231    UnknownParam(String),
232    /// A param was given a different kind of value than its default.
233    ParamType {
234        /// The param.
235        name: String,
236        /// The kind of its default, such as "a number".
237        expected: String,
238        /// The kind given.
239        got: String,
240    },
241    /// A param's value nests too deeply to store in a token.
242    ParamTooDeep(String),
243    /// A param was given to a resume. Params are set when an instance
244    /// starts, and its token carries them from then on.
245    ParamOnResume(String),
246    /// The token is damaged, or isn't a flow token.
247    CorruptToken(String),
248    /// The token was made by a newer flow-runner than this one.
249    NewerToken,
250    /// The token belongs to another flow, named here.
251    OtherFlow(String),
252    /// The token was made by another version of this flow. Load the version
253    /// that made it, or [`Flow::rebind`](crate::Flow::rebind) it.
254    OtherVersion,
255    /// The token waits on an ask; resume it with a `result` or a `failure`.
256    AnswerMissing,
257    /// A `result` or `failure` was given to a start, or to a token that
258    /// isn't waiting on an ask.
259    AnswerUnexpected,
260    /// Both a `result` and a `failure` were given.
261    AnswerAmbiguous,
262    /// The `failure` given is `null`, which reads as no failure at all.
263    NullFailure,
264    /// An event was given to a token that waits on an ask.
265    EventDuringAsk,
266}
267
268impl fmt::Display for InputError {
269    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270        match self {
271            InputError::UnknownEntry(entry) => write!(f, "`{entry}` is not an entry of this flow"),
272            InputError::UnknownEvent(event) => {
273                write!(f, "`{event}` is not a declared event of this flow")
274            }
275            InputError::UnknownParam(param) => write!(f, "`{param}` is not a param of this flow"),
276            InputError::ParamType {
277                name,
278                expected,
279                got,
280            } => write!(f, "param `{name}` expects {expected}, got {got}"),
281            InputError::ParamTooDeep(param) => {
282                f.write_str(&too_deep(&format!("param `{param}`"), MAX_VALUE_DEPTH))
283            }
284            InputError::ParamOnResume(param) => write!(
285                f,
286                "param `{param}` was given to a resume; params are set when an instance starts"
287            ),
288            InputError::CorruptToken(why) => write!(f, "corrupt token: {why}"),
289            InputError::NewerToken => {
290                write!(f, "the token was made by a newer flow-runner than this one")
291            }
292            InputError::OtherFlow(flow) => write!(f, "the token belongs to flow `{flow}`"),
293            InputError::OtherVersion => write!(
294                f,
295                "the token was made by another version of this flow; load the version that made it, or rebind it with `Flow::rebind`"
296            ),
297            InputError::AnswerMissing => write!(
298                f,
299                "the token is waiting on an ask; resume it with a `result` or a `failure`"
300            ),
301            InputError::AnswerUnexpected => write!(
302                f,
303                "a `result` or `failure` was given, but the run isn't answering an ask"
304            ),
305            InputError::AnswerAmbiguous => write!(f, "give a `result` or a `failure`, not both"),
306            InputError::NullFailure => write!(
307                f,
308                "a `failure` can't be null, which reads as no failure; give a reason"
309            ),
310            InputError::EventDuringAsk => {
311                write!(f, "the token is waiting on an ask; it can't take an event")
312            }
313        }
314    }
315}
316
317impl std::error::Error for InputError {}
318
319impl InputError {
320    /// A damaged or hand-made token, and why it can't be read.
321    pub(crate) fn corrupt(why: impl Into<String>) -> Self {
322        InputError::CorruptToken(why.into())
323    }
324}
325
326/// Why [`Flow::rebind`](crate::Flow::rebind) refused a token.
327#[derive(Debug, Clone, PartialEq, Eq)]
328#[non_exhaustive]
329pub enum RebindError {
330    /// The token can't be used with this flow; the inner error says why.
331    Token(InputError),
332    /// The node the token points at no longer exists.
333    NodeGone(String),
334    /// The node takes another number of arguments, or changed whether it
335    /// continues an ask.
336    NodeChanged(String),
337    /// A param the instance was started with no longer exists.
338    ParamGone(String),
339    /// With the params added since it was made, the token would carry more
340    /// than a token may.
341    TooLarge,
342}
343
344impl fmt::Display for RebindError {
345    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
346        match self {
347            RebindError::Token(error) => write!(f, "{error}"),
348            RebindError::NodeGone(node) => write!(f, "node `{node}` no longer exists"),
349            RebindError::NodeChanged(node) => write!(
350                f,
351                "node `{node}` changed shape; the token can't continue there"
352            ),
353            RebindError::ParamGone(param) => write!(f, "param `{param}` no longer exists"),
354            RebindError::TooLarge => write!(
355                f,
356                "with the params added since it was made, the state the token would carry is over {MAX_TOKEN_STATE} bytes"
357            ),
358        }
359    }
360}
361
362impl std::error::Error for RebindError {}
363
364/// Why an edit was refused. The document is unchanged.
365#[derive(Debug, Clone, PartialEq)]
366#[non_exhaustive]
367pub enum EditError {
368    /// No node, branch, param, annotation, event or entry by that name or index.
369    NotFound(String),
370    /// The name is invalid, reserved or already taken.
371    BadName(String),
372    /// The text doesn't parse. Spans point into the text given: for
373    /// `AddBranch`, into its guard when that doesn't parse, and otherwise
374    /// into its outcome.
375    Syntax(Diagnostics),
376    /// The edit makes no sense here, such as a branch after `else`.
377    Invalid(String),
378}
379
380impl fmt::Display for EditError {
381    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
382        match self {
383            EditError::NotFound(what) => write!(f, "no {what}"),
384            EditError::BadName(why) | EditError::Invalid(why) => f.write_str(why),
385            EditError::Syntax(diagnostics) => {
386                let messages: Vec<&str> = diagnostics
387                    .errors()
388                    .map(|diagnostic| diagnostic.message.as_str())
389                    .collect();
390                write!(f, "the edit doesn't parse: {}", messages.join("; "))
391            }
392        }
393    }
394}
395
396impl std::error::Error for EditError {}
397
398/// A branch after `else`.
399pub(crate) const AFTER_ELSE: &str = "a branch after `else` never runs";
400
401/// The rule a branch after `else` breaks.
402pub(crate) const ELSE_LAST: &str = "`else` must be the last branch";
403
404/// `tick` in `events`.
405pub(crate) const TICK_DECLARED: &str = "`tick` is built in; it doesn't need declaring";
406
407/// A name given twice where each must be unique: "parameter `x` appears
408/// twice".
409pub(crate) fn twice(what: &str, name: &str) -> String {
410    format!("{what} `{name}` appears twice")
411}
412
413/// A name declared again: "`x` is already declared as a param".
414pub(crate) fn already_declared(name: &str, as_what: &str) -> String {
415    format!("`{name}` is already declared as {as_what}")
416}
417
418/// Something nested past a depth limit.
419pub(crate) fn too_deep(what: &str, limit: usize) -> String {
420    format!("{what} nests deeper than {limit} levels")
421}
422
423/// Something past a size limit.
424pub(crate) fn too_large(what: &str, bytes: usize, limit: usize) -> String {
425    format!("{what} is too large: {bytes} bytes exceeds the limit of {limit}")
426}
427
428/// Words as a list of choices for a message: "`a`, `b` or `c`".
429pub(crate) fn listed(words: &[&str]) -> String {
430    let quoted: Vec<String> = words.iter().map(|word| format!("`{word}`")).collect();
431    match quoted.split_last() {
432        Some((last, rest)) if !rest.is_empty() => format!("{} or {last}", rest.join(", ")),
433        _ => quoted.concat(),
434    }
435}
436
437/// Names for a message, the first [`MAX_LISTED_NAMES`] of them: "`a`, `b`
438/// and 3 more".
439pub(crate) fn names_listed(names: &[&str]) -> String {
440    let shown: Vec<String> = names
441        .iter()
442        .take(MAX_LISTED_NAMES)
443        .map(|name| format!("`{name}`"))
444        .collect();
445    let shown = shown.join(", ");
446    match names.len().saturating_sub(MAX_LISTED_NAMES) {
447        0 => shown,
448        more => format!("{shown} and {more} more"),
449    }
450}
451
452/// A value's kind as a phrase for messages: "a number", "a list".
453pub(crate) fn kind_phrase(value: &Value) -> &'static str {
454    match value {
455        Value::Null => "null",
456        Value::Bool(_) => "a boolean",
457        Value::Int(_) | Value::Decimal(_) => "a number",
458        Value::Str(_) => "a string",
459        Value::Arr(_) => "a list",
460        Value::Obj(_) => "an object",
461    }
462}
463
464/// A value for a message: a scalar with its value, anything else by kind.
465pub(crate) fn describe(value: &Value) -> String {
466    match value {
467        Value::Bool(flag) => flag.to_string(),
468        Value::Int(number) => format!("the number {number}"),
469        Value::Decimal(number) => format!("the number {number}"),
470        Value::Str(text) => format!("the string {text:?}"),
471        Value::Null | Value::Arr(_) | Value::Obj(_) => kind_phrase(value).to_string(),
472    }
473}