1use 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#[derive(Debug, Clone)]
11#[non_exhaustive]
12pub enum LoadError {
13 Corrupt(String),
15 IncompatibleVersion {
17 found: u32,
19 expected: u32,
21 },
22 HashChanged,
28 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 pub(crate) fn corrupt(why: impl Into<String>) -> Self {
55 LoadError::Corrupt(why.into())
56 }
57}
58
59#[derive(Debug, Clone, PartialEq)]
61#[non_exhaustive]
62pub enum RunError {
63 Expression {
65 node: Option<String>,
67 error: ExpressionError,
69 },
70 GuardNotBool {
72 node: String,
74 got: String,
76 span: Span,
78 },
79 WakeNotTime {
81 node: String,
83 got: String,
85 span: Span,
87 },
88 TooManyJumps {
90 limit: u64,
92 node: String,
94 },
95 TooManyAsks {
97 limit: u64,
99 node: String,
101 },
102 ValueTooDeep {
104 node: String,
106 },
107 TokenTooLarge {
110 node: String,
112 limit: u64,
114 },
115 AnswerIgnored {
118 node: String,
120 },
121 JumpIgnored {
124 node: String,
126 },
127}
128
129#[derive(Debug, Clone, PartialEq, Eq)]
131pub struct ExpressionError {
132 pub message: String,
134 pub span: Option<Span>,
136 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 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 pub fn is_budget_exceeded(&self) -> bool {
162 matches!(self, RunError::Expression { error, .. } if error.budget_exceeded)
163 }
164
165 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#[derive(Debug, Clone, PartialEq, Eq)]
224#[non_exhaustive]
225pub enum InputError {
226 UnknownEntry(String),
228 UnknownEvent(String),
230 UnknownParam(String),
232 ParamType {
234 name: String,
236 expected: String,
238 got: String,
240 },
241 ParamTooDeep(String),
243 ParamOnResume(String),
246 CorruptToken(String),
248 NewerToken,
250 OtherFlow(String),
252 OtherVersion,
255 AnswerMissing,
257 AnswerUnexpected,
260 AnswerAmbiguous,
262 NullFailure,
264 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 pub(crate) fn corrupt(why: impl Into<String>) -> Self {
322 InputError::CorruptToken(why.into())
323 }
324}
325
326#[derive(Debug, Clone, PartialEq, Eq)]
328#[non_exhaustive]
329pub enum RebindError {
330 Token(InputError),
332 NodeGone(String),
334 NodeChanged(String),
337 ParamGone(String),
339 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#[derive(Debug, Clone, PartialEq)]
366#[non_exhaustive]
367pub enum EditError {
368 NotFound(String),
370 BadName(String),
372 Syntax(Diagnostics),
376 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
398pub(crate) const AFTER_ELSE: &str = "a branch after `else` never runs";
400
401pub(crate) const ELSE_LAST: &str = "`else` must be the last branch";
403
404pub(crate) const TICK_DECLARED: &str = "`tick` is built in; it doesn't need declaring";
406
407pub(crate) fn twice(what: &str, name: &str) -> String {
410 format!("{what} `{name}` appears twice")
411}
412
413pub(crate) fn already_declared(name: &str, as_what: &str) -> String {
415 format!("`{name}` is already declared as {as_what}")
416}
417
418pub(crate) fn too_deep(what: &str, limit: usize) -> String {
420 format!("{what} nests deeper than {limit} levels")
421}
422
423pub(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
428pub(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
437pub(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
452pub(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
464pub(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}