Skip to main content

yomi_core/package/
error.rs

1//! Errors of commands and of migrating state slices.
2
3use super::*;
4
5/// The kind of command failure.
6#[non_exhaustive]
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum CommandErrorKind {
9    /// A code decided by the package and named arguments (no message text; displaying it is the host's job).
10    Failed {
11        /// A stable English identifier in the form `package.error_name` (the core's own are `core.…`).
12        code: String,
13        /// Named arguments determined by each code.
14        args: Vec<(&'static str, DiagArg)>,
15    },
16    /// Integer overflow (treated the same as `VmErrorKind::IntegerOverflow`).
17    IntegerOverflow,
18    /// A `float` result became `NaN` or `±∞` (`VmErrorKind::NonFiniteFloat`).
19    NonFiniteFloat,
20    /// A `float` does not fit in the range of `int` (`VmErrorKind::FloatOutOfRange`).
21    FloatOutOfRange,
22    /// Divided by 0 (`VmErrorKind::DivisionByZero`).
23    DivisionByZero,
24    /// The command stopped because an interrupt was requested (`VmErrorKind::Interrupted`).
25    Interrupted,
26}
27
28/// A failure returned by a command function. When `Err` is returned, the VM returns it from `run` as a runtime error (the
29/// VM adds the position).
30///
31/// The core has no error messages. It holds only codes and arguments; turning them into messages is the host's job (the
32/// CLI uses FTL).
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct CommandError {
35    pub(super) kind: CommandErrorKind,
36}
37
38impl CommandError {
39    /// Makes a failure with a code and named arguments. The code is `package.error_name` (such as
40    /// `input.integer_out_of_range`).
41    ///
42    /// Argument values are [`DiagArg`]s (strings or integers; can be made with `.into()`). Pass decimals as strings.
43    pub fn with_code<I>(code: impl Into<String>, args: I) -> Self
44    where
45        I: IntoIterator<Item = (&'static str, DiagArg)>,
46    {
47        Self {
48            kind: CommandErrorKind::Failed {
49                code: code.into(),
50                args: args.into_iter().collect(),
51            },
52        }
53    }
54
55    /// Adds one named argument (used instead of passing an array to `with_code` when value types are mixed).
56    #[must_use]
57    pub fn arg(mut self, name: &'static str, value: impl Into<DiagArg>) -> Self {
58        if let CommandErrorKind::Failed { args, .. } = &mut self.kind {
59            args.push((name, value.into()));
60        }
61        self
62    }
63
64    /// Integer overflow.
65    pub fn integer_overflow() -> Self {
66        Self {
67            kind: CommandErrorKind::IntegerOverflow,
68        }
69    }
70
71    /// A `float` result became `NaN` or `±∞`.
72    pub fn non_finite_float() -> Self {
73        Self {
74            kind: CommandErrorKind::NonFiniteFloat,
75        }
76    }
77
78    /// A `float` does not fit in the range of `int`.
79    pub fn float_out_of_range() -> Self {
80        Self {
81            kind: CommandErrorKind::FloatOutOfRange,
82        }
83    }
84
85    /// Divided by 0.
86    pub fn division_by_zero() -> Self {
87        Self {
88            kind: CommandErrorKind::DivisionByZero,
89        }
90    }
91
92    /// The command stopped because an interrupt was requested ([`Ctx::interrupted`]).
93    pub fn interrupted() -> Self {
94        Self {
95            kind: CommandErrorKind::Interrupted,
96        }
97    }
98
99    /// The kind of failure.
100    pub fn kind(&self) -> &CommandErrorKind {
101        &self.kind
102    }
103
104    /// The code. For the same kinds as the core's runtime errors, their English names (such as `integer_overflow`).
105    pub fn code(&self) -> &str {
106        match &self.kind {
107            CommandErrorKind::Failed { code, .. } => code,
108            CommandErrorKind::IntegerOverflow => "integer_overflow",
109            CommandErrorKind::NonFiniteFloat => "non_finite_float",
110            CommandErrorKind::FloatOutOfRange => "float_out_of_range",
111            CommandErrorKind::DivisionByZero => "division_by_zero",
112            CommandErrorKind::Interrupted => "interrupted",
113        }
114    }
115
116    /// Named arguments. Empty for the same kinds as the core's runtime errors.
117    pub fn args(&self) -> &[(&'static str, DiagArg)] {
118        match &self.kind {
119            CommandErrorKind::Failed { args, .. } => args,
120            _ => &[],
121        }
122    }
123
124    /// Turns it into the kind of a VM runtime error.
125    pub(crate) fn into_vm_kind(self) -> VmErrorKind {
126        match self.kind {
127            CommandErrorKind::Failed { code, args } => VmErrorKind::CommandFailed { code, args },
128            CommandErrorKind::IntegerOverflow => VmErrorKind::IntegerOverflow,
129            CommandErrorKind::NonFiniteFloat => VmErrorKind::NonFiniteFloat,
130            CommandErrorKind::FloatOutOfRange => VmErrorKind::FloatOutOfRange,
131            CommandErrorKind::DivisionByZero => VmErrorKind::DivisionByZero,
132            CommandErrorKind::Interrupted => VmErrorKind::Interrupted,
133        }
134    }
135}
136
137/// In the form `code (name=value, …)` (for logs; not a message for users).
138impl std::fmt::Display for CommandError {
139    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140        write!(f, "{}", self.code())?;
141        let args = self.args();
142        if !args.is_empty() {
143            write!(f, " (")?;
144            for (i, (name, value)) in args.iter().enumerate() {
145                if i > 0 {
146                    write!(f, ", ")?;
147                }
148                write!(f, "{name}={value}")?;
149            }
150            write!(f, ")")?;
151        }
152        Ok(())
153    }
154}
155
156impl std::error::Error for CommandError {}
157
158/// A failure of a slice's `migrate`. The load fails with `LoadErrorKind::PackageSlice`.
159#[derive(Debug, Clone, PartialEq, Eq)]
160pub struct MigrateError {
161    pub(super) message: String,
162}
163
164impl MigrateError {
165    /// Makes a failure with a message.
166    pub fn new(message: impl Into<String>) -> Self {
167        Self {
168            message: message.into(),
169        }
170    }
171
172    /// A slice of an unknown older version.
173    pub fn unsupported_version(old_version: u32) -> Self {
174        Self::new(format!("unsupported slice version {old_version}"))
175    }
176
177    /// The message.
178    pub fn message(&self) -> &str {
179        &self.message
180    }
181}
182
183impl std::fmt::Display for MigrateError {
184    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
185        write!(f, "{}", self.message)
186    }
187}
188
189impl std::error::Error for MigrateError {}
190
191/// Turns the bytes of a slice (`postcard`) back into a type. Used by `migrate` to read bytes of an older version (the core
192/// provides this so that packages need not depend on `postcard`).
193pub fn decode_slice<T: DeserializeOwned>(raw: &[u8]) -> Result<T, MigrateError> {
194    postcard::from_bytes(raw).map_err(|e| MigrateError::new(format!("decode: {e}")))
195}
196
197/// Turns a value into the bytes of a slice (`postcard`) (used in tests of `migrate` and so on).
198pub fn encode_slice<T: Serialize>(value: &T) -> Result<Vec<u8>, MigrateError> {
199    postcard::to_stdvec(value).map_err(|e| MigrateError::new(format!("encode: {e}")))
200}