Skip to main content

pepl_stdlib/
error.rs

1use thiserror::Error;
2
3/// Errors that can occur when calling stdlib functions.
4#[derive(Debug, Clone, Error)]
5pub enum StdlibError {
6    /// Wrong number of arguments passed to a function.
7    #[error("{function}: expected {expected} argument(s), got {got}")]
8    WrongArgCount {
9        function: String,
10        expected: usize,
11        got: usize,
12    },
13
14    /// Argument has the wrong type.
15    #[error("{function}: argument {position} expected {expected}, got {got}")]
16    TypeMismatch {
17        function: String,
18        position: usize,
19        expected: String,
20        got: String,
21    },
22
23    /// `core.assert` failed.
24    #[error("Assertion failed: {message}")]
25    AssertionFailed { message: String },
26
27    /// Unknown function in module.
28    #[error("Unknown function: {module}.{function}")]
29    UnknownFunction { module: String, function: String },
30
31    /// Generic runtime error (e.g., NaN would be produced, division by zero).
32    #[error("{0}")]
33    RuntimeError(String),
34
35    /// Capability call — cannot be executed locally, must be routed to host.
36    /// The caller should use `cap_id` and `fn_id` for `env.host_call` dispatch.
37    #[error("{module}.{function}: capability call requires host (cap_id={cap_id}, fn_id={fn_id})")]
38    CapabilityCall {
39        module: String,
40        function: String,
41        cap_id: u32,
42        fn_id: u32,
43        args: Vec<crate::value::Value>,
44    },
45}
46
47impl StdlibError {
48    /// Create a `WrongArgCount` error.
49    pub fn wrong_args(function: &str, expected: usize, got: usize) -> Self {
50        Self::WrongArgCount {
51            function: function.to_string(),
52            expected,
53            got,
54        }
55    }
56
57    /// Create a `TypeMismatch` error.
58    pub fn type_mismatch(function: &str, position: usize, expected: &str, got: &str) -> Self {
59        Self::TypeMismatch {
60            function: function.to_string(),
61            position,
62            expected: expected.to_string(),
63            got: got.to_string(),
64        }
65    }
66
67    /// Create an `UnknownFunction` error.
68    pub fn unknown_function(module: &str, function: &str) -> Self {
69        Self::UnknownFunction {
70            module: module.to_string(),
71            function: function.to_string(),
72        }
73    }
74
75    /// Create a `CapabilityCall` error — signals that this call must be routed to the host.
76    pub fn capability_call(
77        module: &str,
78        function: &str,
79        cap_id: u32,
80        fn_id: u32,
81        args: Vec<crate::value::Value>,
82    ) -> Self {
83        Self::CapabilityCall {
84            module: module.to_string(),
85            function: function.to_string(),
86            cap_id,
87            fn_id,
88            args,
89        }
90    }
91}