Skip to main content

hexicon_vm/
error.rs

1//! Run-time errors.
2//!
3//! The error numbers and message texts are the reference VM's. Programs
4//! see both: the number as the
5//! `errno_` of a `RuntimeError`, and the text as its `exceptionMessage`.
6
7use std::fmt;
8
9use crate::value::ObjId;
10
11/// A value substituted into an error message.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub enum ErrParam {
14    /// A number, for `%d`, `%u`, and `%x`.
15    Int(i32),
16    /// Text, for `%s`.
17    Str(String),
18}
19
20/// An error raised by the VM itself, as opposed to an exception object a
21/// program throws.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct RuntimeError {
24    /// The error number; one of the constants in [`code`].
25    pub code: u32,
26    /// Values for the message's `%` fields, in order.
27    pub params: Vec<ErrParam>,
28    /// More about this occurrence, after the message: for a function
29    /// called with the wrong number of arguments, which one it was.
30    pub detail: Option<String>,
31}
32
33impl RuntimeError {
34    /// The error's message with its parameters filled in.
35    pub fn message(&self) -> String {
36        let message = match code::message(self.code) {
37            Some(template) => format_message(template, &self.params),
38            None => format!("VM Error: code {}", self.code),
39        };
40        match &self.detail {
41            Some(detail) => format!("{message}: {detail}"),
42            None => message,
43        }
44    }
45}
46
47impl fmt::Display for RuntimeError {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        f.write_str(&self.message())
50    }
51}
52
53/// Why execution stopped.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub enum VmError {
56    /// The VM raised an error. Inside a running program this becomes a
57    /// `RuntimeError` exception the program can catch.
58    Runtime(RuntimeError),
59    /// An exception object is propagating out of byte code.
60    Thrown(ObjId),
61    /// The program used a part of the VM that Hexicon does not have yet.
62    /// Programs cannot catch this.
63    Unimplemented(String),
64    /// The host has no input yet, so the program has to stop where it is
65    /// until it does. This is how the instruction that asked finds its
66    /// way out of the interpreter; it never reaches a program or a host.
67    Suspend,
68}
69
70impl VmError {
71    /// A VM error with no message parameters.
72    pub fn new(code: u32) -> Self {
73        Self::Runtime(RuntimeError {
74            code,
75            params: Vec::new(),
76            detail: None,
77        })
78    }
79
80    /// A VM error with message parameters.
81    pub fn with(code: u32, params: Vec<ErrParam>) -> Self {
82        Self::Runtime(RuntimeError {
83            code,
84            params,
85            detail: None,
86        })
87    }
88
89    /// A VM error with no message parameters and more about this
90    /// occurrence.
91    pub fn with_detail(code: u32, detail: String) -> Self {
92        Self::Runtime(RuntimeError {
93            code,
94            params: Vec::new(),
95            detail: Some(detail),
96        })
97    }
98
99    /// A report that a feature is missing.
100    pub fn unimplemented(what: impl Into<String>) -> Self {
101        Self::Unimplemented(what.into())
102    }
103}
104
105impl fmt::Display for VmError {
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        match self {
108            Self::Runtime(error) => write!(f, "VM Error: {error}"),
109            Self::Thrown(_) => f.write_str("unhandled exception"),
110            Self::Unimplemented(what) => write!(f, "not implemented: {what}"),
111            Self::Suspend => f.write_str("the program is waiting for input"),
112        }
113    }
114}
115
116impl std::error::Error for VmError {}
117
118/// The result of an operation that can raise a VM error.
119pub type VmResult<T> = Result<T, VmError>;
120
121/// Fill in a message template the way the reference VM does: each `%s`,
122/// `%d`, `%u`, or `%x` takes the next parameter; `%%` is a literal percent
123/// sign that also consumes a parameter; and once the parameters run out,
124/// the rest of the template is copied as it stands.
125pub fn format_message(template: &str, params: &[ErrParam]) -> String {
126    let mut out = String::new();
127    let mut next = 0;
128    let mut chars = template.chars().peekable();
129    while let Some(c) = chars.next() {
130        if c != '%' || next >= params.len() {
131            out.push(c);
132            continue;
133        }
134        let param = &params[next];
135        next += 1;
136        let Some(spec) = chars.next() else { break };
137        match (spec, param) {
138            ('s', ErrParam::Str(text)) => out.push_str(text),
139            ('d', ErrParam::Int(n)) => out.push_str(&n.to_string()),
140            ('u', ErrParam::Int(n)) => out.push_str(&(*n as u32).to_string()),
141            ('x', ErrParam::Int(n)) => out.push_str(&format!("{:x}", *n as u32)),
142            ('s' | 'd' | 'u' | 'x', _) => out.push(spec),
143            ('%', _) => out.push('%'),
144            (other, _) => {
145                out.push('%');
146                out.push(other);
147            }
148        }
149    }
150    out
151}
152
153macro_rules! error_codes {
154    ($( $name:ident = $number:literal, $message:literal; )*) => {
155        /// Error numbers and their messages.
156        pub mod code {
157            #![allow(missing_docs)]
158            $( pub const $name: u32 = $number; )*
159
160            /// The message template for an error number.
161            pub fn message(code: u32) -> Option<&'static str> {
162                match code {
163                    $( $number => Some($message), )*
164                    _ => None,
165                }
166            }
167        }
168    };
169}
170
171error_codes! {
172    READ_FILE = 101, "error reading file";
173    WRITE_FILE = 102, "error writing file";
174    FILE_NOT_FOUND = 103, "file not found";
175    CREATE_FILE = 104, "error creating file";
176    CLOSE_FILE = 105, "error closing file";
177    DELETE_FILE = 106, "error deleting file";
178    PACK_PARSE = 107, "data packer format string parsing error at character index %d";
179    PACK_ARG_MISMATCH = 108, "data packer argument type mismatch at format string index %d";
180    PACK_ARGC_MISMATCH = 109, "wrong number of data packer arguments at format string index %d";
181    NET_FILE_NOIMPL = 110, "this file operation isn't supported for storage server files";
182    RENAME_FILE = 111, "error renaming file";
183    OBJ_IN_USE = 201, "object ID in use - the image/save file might be corrupted";
184    OUT_OF_MEMORY = 202, "out of memory";
185    NO_MEM_FOR_PAGE = 203, "out of memory allocating pool page";
186    BAD_POOL_PAGE_SIZE = 204, "invalid page size - file is not valid";
187    OUT_OF_PROPIDS = 205, "no more property ID's are available";
188    CIRCULAR_INIT = 206, "circular initialization dependency in built-in class (internal error)";
189    UNKNOWN_METACLASS = 301, "this interpreter version cannot run this program (program requires built-in class %s, which is not available in this interpreter)";
190    UNKNOWN_FUNC_SET = 302, "this interpreter version cannot run this program (program requires built-in function set %s, which is not available in this interpreter)";
191    READ_PAST_IMG_END = 303, "reading past end of image file - program might be corrupted";
192    NOT_AN_IMAGE_FILE = 304, "this is not an image file (no valid signature found)";
193    UNKNOWN_IMAGE_BLOCK = 305, "this interpreter version cannot run this program (unknown block type in image file)";
194    IMAGE_BLOCK_TOO_SMALL = 306, "data block too small";
195    IMAGE_POOL_BEFORE_DEF = 307, "invalid image file: pool page before pool definition";
196    IMAGE_POOL_BAD_PAGE = 308, "invalid image file: pool page out of range of definition";
197    IMAGE_BAD_POOL_ID = 309, "invalid image file: invalid pool ID";
198    LOAD_BAD_PAGE_IDX = 310, "invalid image file: bad page index";
199    LOAD_UNDEF_PAGE = 311, "loading undefined pool page";
200    IMAGE_POOL_REDEF = 312, "invalid image file: pool is defined more than once";
201    IMAGE_METADEP_REDEF = 313, "invalid image file: multiple built-in class dependency tables found";
202    IMAGE_NO_METADEP = 314, "invalid image file: no built-in class dependency table found";
203    IMAGE_FUNCDEP_REDEF = 315, "invalid image file: multiple function set dependency tables found";
204    IMAGE_NO_FUNCDEP = 316, "invalid image file: no function set dependency table found";
205    IMAGE_ENTRYPT_REDEF = 317, "invalid image file: multiple entrypoints found";
206    IMAGE_NO_ENTRYPT = 318, "invalid image file: no entrypoint found";
207    IMAGE_INCOMPAT_VSN = 319, "incompatible image file format version";
208    IMAGE_NO_CODE = 320, "image contains no code";
209    IMAGE_INCOMPAT_HDR_FMT = 321, "incomptabile image file format: method header too old";
210    UNAVAIL_INTRINSIC = 322, "unavailable built-in function called (index %d in function set \"%s\")";
211    UNKNOWN_METACLASS_INTERNAL = 323, "unknown internal built-in class ID %x";
212    XOR_MASK_BAD_IN_MEM = 324, "page mask is not allowed for in-memory image file";
213    NO_IMAGE_IN_EXE = 325, "no embedded image file found in executable";
214    OBJ_SIZE_OVERFLOW = 326, "object size exceeds hardware limits of this computer";
215    METACLASS_TOO_OLD = 327, "this interpreter is too old to run this program (program requires built-in class version %s, interpreter provides version %s)";
216    INVAL_METACLASS_DATA = 328, "invalid built-in class data - image file may be corrupted";
217    BAD_STATIC_NEW = 329, "invalid object - class does not allow loading";
218    FUNCSET_TOO_OLD = 330, "this interpreter is too old to run this program (program requires function set version %s, interpreter provides version %s)";
219    INVAL_EXPORT_TYPE = 331, "exported name \"%s\" is of incorrect datatype";
220    INVAL_IMAGE_MACRO = 332, "invalid data in macro definitions in image file (error code %d)";
221    NO_MAINRESTORE = 333, "this program is not capable of restoring a saved state on startup";
222    IMAGE_INCOMPAT_VSN_DBG = 334, "image file is incompatible with debugger - recompile the program";
223    NETWORK_SAFETY = 400, "this operation is not allowed by the network safety level settings";
224    INVALID_SETPROP = 1001, "property cannot be set for object";
225    NOT_SAVED_STATE = 1201, "file is not a valid saved state file";
226    WRONG_SAVED_STATE = 1202, "saved state is for a different program or a different version of this program";
227    SAVED_META_TOO_LONG = 1203, "built-in class name in saved state file is too long";
228    SAVED_OBJ_ID_INVALID = 1206, "invalid object ID in saved state file";
229    BAD_SAVED_STATE = 1207, "saved state file is corrupted (incorrect checksum)";
230    BAD_SAVED_META_DATA = 1208, "invalid built-in class data in saved state file";
231    STORAGE_SERVER_ERR = 1209, "storage server error";
232    DESC_TAB_OVERFLOW = 1210, "saved file metadata table exceeds 64k bytes";
233    NO_STR_CONV = 2001, "cannot convert value to string";
234    CONV_BUF_OVF = 2002, "string conversion buffer overflow";
235    BAD_TYPE_ADD = 2003, "invalid datatypes for addition operator";
236    NUM_VAL_REQD = 2004, "numeric value required";
237    INT_VAL_REQD = 2005, "integer value required";
238    NO_LOG_CONV = 2006, "cannot convert value to logical (true/nil)";
239    BAD_TYPE_SUB = 2007, "invalid datatypes for subtraction operator";
240    DIVIDE_BY_ZERO = 2008, "division by zero";
241    INVALID_COMPARISON = 2009, "invalid comparison";
242    OBJ_VAL_REQD = 2010, "object value required";
243    PROPPTR_VAL_REQD = 2011, "property reference required";
244    LOG_VAL_REQD = 2012, "logical value required";
245    FUNCPTR_VAL_REQD = 2013, "function pointer required";
246    CANNOT_INDEX_TYPE = 2014, "invalid index operation - this type of value cannot be indexed";
247    INDEX_OUT_OF_RANGE = 2015, "index out of range";
248    BAD_METACLASS_INDEX = 2016, "invalid built-in class index";
249    BAD_DYNAMIC_NEW = 2017, "invalid dynamic object creation (built-in class does not support NEW)";
250    OBJ_VAL_REQD_SC = 2018, "object value required for base class";
251    STRING_VAL_REQD = 2019, "string value required";
252    LIST_VAL_REQD = 2020, "list value required";
253    DICT_NO_CONST = 2021, "list or string reference found in dictionary (entry \"%s\") - this dictionary cannot be saved in the image file";
254    INVAL_OBJ_TYPE = 2022, "invalid object type - cannot convert to required object type";
255    NUM_OVERFLOW = 2023, "numeric overflow";
256    BAD_TYPE_MUL = 2024, "invalid datatypes for multiplication operator";
257    BAD_TYPE_DIV = 2025, "invalid datatypes for division operator";
258    BAD_TYPE_NEG = 2026, "invalid datatype for arithmetic negation operator";
259    OUT_OF_RANGE = 2027, "value is out of range";
260    STR_TOO_LONG = 2028, "string is too long";
261    LIST_TOO_LONG = 2029, "list too long";
262    TREE_TOO_DEEP_EQ = 2030, "maximum equality test/hash recursion depth exceeded";
263    NO_INT_CONV = 2031, "cannot convert value to integer";
264    BAD_TYPE_MOD = 2032, "invalid datatype for modulo operator";
265    BAD_TYPE_BIT_AND = 2033, "invalid datatype for bitwise AND operator";
266    BAD_TYPE_BIT_OR = 2034, "invalid datatype for bitwise OR operator";
267    BAD_TYPE_XOR = 2035, "invalid datatype for XOR operator";
268    BAD_TYPE_SHL = 2036, "invalid datatype for left-shift operator '<<'";
269    BAD_TYPE_ASHR = 2037, "invalid datatype for arithmetic right-shift operator '>>'";
270    BAD_TYPE_BIT_NOT = 2038, "invalid datatype for bitwise NOT operator";
271    CODEPTR_VAL_REQD = 2039, "code pointer value required";
272    EXCEPTION_OBJ_REQD = 2040, "exception object required, but 'new' did not yield an object";
273    NO_DOUBLE_CONV = 2041, "cannot convert value to native floating point";
274    NO_NUM_CONV = 2042, "cannot convert value to a numeric type";
275    BAD_TYPE_LSHR = 2043, "invalid datatype for logical right-shift operator '>>>'";
276    WRONG_NUM_OF_ARGS = 2201, "wrong number of arguments";
277    WRONG_NUM_OF_ARGS_CALLING = 2202, "argument mismatch calling %s - function definition is incorrect";
278    NIL_DEREF = 2203, "nil object reference";
279    MISSING_NAMED_ARG = 2204, "missing named argument '%s'";
280    BAD_TYPE_CALL = 2205, "invalid type for call";
281    NIL_SELF = 2206, "nil 'self' value is not allowed";
282    CANNOT_CREATE_INST = 2270, "cannot create instance of object - object is not a class";
283    ILLEGAL_NEW = 2271, "cannot create instance - class does not allow dynamic construction";
284    INVALID_OPCODE = 2301, "invalid opcode - possible image file corruption";
285    UNHANDLED_EXC = 2302, "unhandled exception";
286    STACK_OVERFLOW = 2303, "stack overflow";
287    BAD_TYPE_BIF = 2304, "invalid type for built-in function argument";
288    SAY_IS_NOT_DEFINED = 2305, "default output function is not defined";
289    BAD_VAL_BIF = 2306, "invalid value for built-in function argument";
290    BREAKPOINT = 2307, "breakpoint encountered";
291    CALLEXT_NOT_IMPL = 2308, "external function calls are not implemented in this version";
292    INVALID_OPCODE_MOD = 2309, "invalid opcode modifier - possible image file corruption";
293    NO_CHARMAP_FILE = 2310, "No mapping file available for local character set \"%.32s\"";
294    UNHANDLED_EXC_PARAM = 2311, "Unhandled exception: %s";
295    VM_EXC_PARAM = 2312, "VM Error: %s";
296    VM_EXC_CODE = 2313, "VM Error: code %d";
297    EXC_IN_STATIC_INIT = 2314, "Exception in static initializer for %s.%s: %s";
298    INTCLS_GENERAL_ERROR = 2315, "built-in class exception: %s";
299    STACK_OUT_OF_BOUNDS = 2316, "stack access is out of bounds";
300    DBG_ABORT = 2391, "'abort' signal";
301    DBG_RESTART = 2392, "'restart' signal";
302    DBG_HALT = 2394, "debugger VM halt";
303    DBG_INTERRUPT = 2395, "interrupted by user";
304    NO_DEBUGGER = 2396, "no debugger available";
305    BAD_FRAME = 2500, "invalid frame in debugger local/parameter evaluation";
306    BAD_SPEC_EVAL = 2501, "invalid speculative expression";
307    INVAL_DBG_EXPR = 2502, "invalid debugger expression";
308    NO_IMAGE_DBG_INFO = 2503, "image file has no debugging information - recompile for debugging";
309    BIGNUM_NO_REGS = 2600, "out of temporary floating point registers (calculation too complex)";
310    NO_BIGNUM_CONV = 2601, "cannot convert value to Decimal";
311}