use crate::common::diagnostic::{Diagnostic, Diagnostics};
use crate::common::limits::{MAX_LISTED_NAMES, MAX_TOKEN_STATE, MAX_VALUE_DEPTH};
use std::fmt;
use temple_dsl::{EvalError, Span, Value};
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum LoadError {
Corrupt(String),
IncompatibleVersion {
found: u32,
expected: u32,
},
HashChanged,
Invalid(Diagnostics),
}
impl fmt::Display for LoadError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
LoadError::Corrupt(why) => write!(f, "corrupt flow blob: {why}"),
LoadError::IncompatibleVersion { found, expected } => write!(
f,
"flow blob version {found} is not {expected}; compile the source again"
),
LoadError::HashChanged => write!(
f,
"the flow now has another hash; tokens made before need rebinding"
),
LoadError::Invalid(errors) => write!(f, "stored flow no longer compiles: {errors}"),
}
}
}
impl std::error::Error for LoadError {}
impl LoadError {
pub(crate) fn corrupt(why: impl Into<String>) -> Self {
LoadError::Corrupt(why.into())
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum RunError {
Expression {
node: Option<String>,
error: ExpressionError,
},
GuardNotBool {
node: String,
got: String,
span: Span,
},
WakeNotTime {
node: String,
got: String,
span: Span,
},
TooManyJumps {
limit: u64,
node: String,
},
TooManyAsks {
limit: u64,
node: String,
},
ValueTooDeep {
node: String,
},
TokenTooLarge {
node: String,
limit: u64,
},
AnswerIgnored {
node: String,
},
JumpIgnored {
node: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExpressionError {
pub message: String,
pub span: Option<Span>,
pub budget_exceeded: bool,
}
impl From<EvalError> for ExpressionError {
fn from(error: EvalError) -> Self {
ExpressionError {
message: error.to_string(),
span: error.span(),
budget_exceeded: error.is_budget_exceeded(),
}
}
}
impl RunError {
pub fn span(&self) -> Option<Span> {
match self {
RunError::Expression { error, .. } => error.span,
RunError::GuardNotBool { span, .. } | RunError::WakeNotTime { span, .. } => Some(*span),
_ => None,
}
}
pub fn is_budget_exceeded(&self) -> bool {
matches!(self, RunError::Expression { error, .. } if error.budget_exceeded)
}
pub fn report(&self, src: &str) -> String {
match self.span() {
Some(span) => Diagnostic::error(span, self.to_string()).report(src),
None => format!("error: {self}"),
}
}
}
impl fmt::Display for RunError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RunError::Expression {
node: Some(node),
error,
} => write!(f, "in node `{node}`: {}", error.message),
RunError::Expression { node: None, error } => {
write!(f, "in a flow-level let: {}", error.message)
}
RunError::GuardNotBool { node, got, .. } => write!(
f,
"in node `{node}`: a guard must be true or false, got {got}"
),
RunError::WakeNotTime { node, got, .. } => write!(
f,
"in node `{node}`: `wake` must be a whole number of epoch seconds, got {got}"
),
RunError::TooManyJumps { limit, node } => {
write!(f, "in node `{node}`: more than {limit} jumps in one run")
}
RunError::TooManyAsks { limit, node } => write!(
f,
"in node `{node}`: the instance would ask more than {limit} times"
),
RunError::ValueTooDeep { node } => write!(
f,
"in node `{node}`: {}",
too_deep("a value the token would store", MAX_VALUE_DEPTH)
),
RunError::TokenTooLarge { node, limit } => write!(
f,
"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`"
),
RunError::AnswerIgnored { node } => write!(
f,
"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"
),
RunError::JumpIgnored { node } => write!(
f,
"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"
),
}
}
}
impl std::error::Error for RunError {}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum InputError {
UnknownEntry(String),
UnknownEvent(String),
UnknownParam(String),
ParamType {
name: String,
expected: String,
got: String,
},
ParamTooDeep(String),
ParamOnResume(String),
CorruptToken(String),
NewerToken,
OtherFlow(String),
OtherVersion,
AnswerMissing,
AnswerUnexpected,
AnswerAmbiguous,
NullFailure,
EventDuringAsk,
}
impl fmt::Display for InputError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
InputError::UnknownEntry(entry) => write!(f, "`{entry}` is not an entry of this flow"),
InputError::UnknownEvent(event) => {
write!(f, "`{event}` is not a declared event of this flow")
}
InputError::UnknownParam(param) => write!(f, "`{param}` is not a param of this flow"),
InputError::ParamType {
name,
expected,
got,
} => write!(f, "param `{name}` expects {expected}, got {got}"),
InputError::ParamTooDeep(param) => {
f.write_str(&too_deep(&format!("param `{param}`"), MAX_VALUE_DEPTH))
}
InputError::ParamOnResume(param) => write!(
f,
"param `{param}` was given to a resume; params are set when an instance starts"
),
InputError::CorruptToken(why) => write!(f, "corrupt token: {why}"),
InputError::NewerToken => {
write!(f, "the token was made by a newer flow-runner than this one")
}
InputError::OtherFlow(flow) => write!(f, "the token belongs to flow `{flow}`"),
InputError::OtherVersion => write!(
f,
"the token was made by another version of this flow; load the version that made it, or rebind it with `Flow::rebind`"
),
InputError::AnswerMissing => write!(
f,
"the token is waiting on an ask; resume it with a `result` or a `failure`"
),
InputError::AnswerUnexpected => write!(
f,
"a `result` or `failure` was given, but the run isn't answering an ask"
),
InputError::AnswerAmbiguous => write!(f, "give a `result` or a `failure`, not both"),
InputError::NullFailure => write!(
f,
"a `failure` can't be null, which reads as no failure; give a reason"
),
InputError::EventDuringAsk => {
write!(f, "the token is waiting on an ask; it can't take an event")
}
}
}
}
impl std::error::Error for InputError {}
impl InputError {
pub(crate) fn corrupt(why: impl Into<String>) -> Self {
InputError::CorruptToken(why.into())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum RebindError {
Token(InputError),
NodeGone(String),
NodeChanged(String),
ParamGone(String),
TooLarge,
}
impl fmt::Display for RebindError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RebindError::Token(error) => write!(f, "{error}"),
RebindError::NodeGone(node) => write!(f, "node `{node}` no longer exists"),
RebindError::NodeChanged(node) => write!(
f,
"node `{node}` changed shape; the token can't continue there"
),
RebindError::ParamGone(param) => write!(f, "param `{param}` no longer exists"),
RebindError::TooLarge => write!(
f,
"with the params added since it was made, the state the token would carry is over {MAX_TOKEN_STATE} bytes"
),
}
}
}
impl std::error::Error for RebindError {}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum EditError {
NotFound(String),
BadName(String),
Syntax(Diagnostics),
Invalid(String),
}
impl fmt::Display for EditError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
EditError::NotFound(what) => write!(f, "no {what}"),
EditError::BadName(why) | EditError::Invalid(why) => f.write_str(why),
EditError::Syntax(diagnostics) => {
let messages: Vec<&str> = diagnostics
.errors()
.map(|diagnostic| diagnostic.message.as_str())
.collect();
write!(f, "the edit doesn't parse: {}", messages.join("; "))
}
}
}
}
impl std::error::Error for EditError {}
pub(crate) const AFTER_ELSE: &str = "a branch after `else` never runs";
pub(crate) const ELSE_LAST: &str = "`else` must be the last branch";
pub(crate) const TICK_DECLARED: &str = "`tick` is built in; it doesn't need declaring";
pub(crate) fn twice(what: &str, name: &str) -> String {
format!("{what} `{name}` appears twice")
}
pub(crate) fn already_declared(name: &str, as_what: &str) -> String {
format!("`{name}` is already declared as {as_what}")
}
pub(crate) fn too_deep(what: &str, limit: usize) -> String {
format!("{what} nests deeper than {limit} levels")
}
pub(crate) fn too_large(what: &str, bytes: usize, limit: usize) -> String {
format!("{what} is too large: {bytes} bytes exceeds the limit of {limit}")
}
pub(crate) fn listed(words: &[&str]) -> String {
let quoted: Vec<String> = words.iter().map(|word| format!("`{word}`")).collect();
match quoted.split_last() {
Some((last, rest)) if !rest.is_empty() => format!("{} or {last}", rest.join(", ")),
_ => quoted.concat(),
}
}
pub(crate) fn names_listed(names: &[&str]) -> String {
let shown: Vec<String> = names
.iter()
.take(MAX_LISTED_NAMES)
.map(|name| format!("`{name}`"))
.collect();
let shown = shown.join(", ");
match names.len().saturating_sub(MAX_LISTED_NAMES) {
0 => shown,
more => format!("{shown} and {more} more"),
}
}
pub(crate) fn kind_phrase(value: &Value) -> &'static str {
match value {
Value::Null => "null",
Value::Bool(_) => "a boolean",
Value::Int(_) | Value::Decimal(_) => "a number",
Value::Str(_) => "a string",
Value::Arr(_) => "a list",
Value::Obj(_) => "an object",
}
}
pub(crate) fn describe(value: &Value) -> String {
match value {
Value::Bool(flag) => flag.to_string(),
Value::Int(number) => format!("the number {number}"),
Value::Decimal(number) => format!("the number {number}"),
Value::Str(text) => format!("the string {text:?}"),
Value::Null | Value::Arr(_) | Value::Obj(_) => kind_phrase(value).to_string(),
}
}