Skip to main content

byteflow/vm/
fault.rs

1use std::fmt;
2
3use crate::bytecode::NativeIdx;
4
5/// Why a `CallNative` was refused before the function pointer ran.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum NativeCallError {
8    NoNativeRight,
9    IndexNotAllowlisted(NativeIdx),
10    IndexOutOfRange(NativeIdx),
11    Revoked,
12}
13
14impl fmt::Display for NativeCallError {
15    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16        match self {
17            NativeCallError::NoNativeRight => f.write_str("CALL_NATIVE: flow lacks NATIVE right"),
18            NativeCallError::IndexNotAllowlisted(idx) => {
19                write!(f, "CALL_NATIVE: index {idx} not on allowlist")
20            }
21            NativeCallError::IndexOutOfRange(idx) => {
22                write!(f, "CALL_NATIVE: index {idx} out of range")
23            }
24            NativeCallError::Revoked => f.write_str("CALL_NATIVE: capability revoked"),
25        }
26    }
27}
28
29impl std::error::Error for NativeCallError {}
30
31/// Anything that can go wrong *inside* a running Flow's VM.
32///
33/// A `Fault` is never a Rust panic — panics are reserved for genuine host
34/// bugs and are caught at the worker boundary (see
35/// `crate::scheduler::worker`) precisely so that one Flow's
36/// bug (division by zero, a corrupt jump target that slipped past the
37/// verifier, an out-of-range register) can never take down a worker thread,
38/// let alone the whole runtime. A `Fault` instead becomes
39/// [`crate::FlowOutcome::Failed`] and is handed to the Flow's supervisor, which
40/// decides whether to restart it (design notes §15-16).
41#[derive(Clone, Debug, PartialEq, Eq)]
42pub enum Fault {
43    DivideByZero,
44    RegisterOutOfRange {
45        reg: u8,
46        frame_size: u8,
47    },
48    /// An instruction's register operand plus the offset it gathers at does
49    /// not fit the register index space *at all* — e.g. `Spawn a=255`, which
50    /// reads its arguments from `a+1..`.
51    ///
52    /// Distinct from [`Fault::RegisterOutOfRange`], which is about an index
53    /// that is perfectly representable and merely absent from this frame.
54    /// Kept separate so the fault cannot lie: reporting "register 255 is out
55    /// of range" for a request that was really for register 256 would send
56    /// whoever reads it looking in the wrong place.
57    RegisterIndexOverflow {
58        base: u8,
59        offset: u8,
60    },
61    BadConstant {
62        index: u32,
63        pool_size: u32,
64    },
65    BadFunction {
66        index: u32,
67        table_size: u32,
68    },
69    /// `Call` passed a different argument count than the callee declares.
70    ///
71    /// The interpreter used to drop the extras and leave the missing
72    /// registers as `Unit`. That disagrees with [`crate::VerifyError::CallArity`]:
73    /// a chunk that skips `verify` must still fail closed.
74    BadArity {
75        passed: usize,
76        expected: u8,
77    },
78    /// Function call nesting exceeded `Vm::MAX_CALL_DEPTH`. Bytecode has no
79    /// native stack overflow (frames are heap-allocated `Vec<Value>`s), so
80    /// this is a deliberate, checked limit rather than a segfault.
81    CallStackOverflow {
82        depth: usize,
83    },
84    TypeMismatch {
85        expected: &'static str,
86        got: &'static str,
87    },
88    /// `CallNative` referenced a slot outside the runtime's registered
89    /// native function table (design notes §30-31). Distinct from
90    /// `BadFunction`, which is about the *bytecode* function table baked
91    /// into the chunk — natives are supplied by the embedder at `Vm`
92    /// construction time and can't be range-checked by
93    /// `crate::bytecode::verify`, which has no visibility into them.
94    BadNative {
95        index: u32,
96        table_size: u32,
97    },
98    /// A native function returned an error (host-side failure — I/O,
99    /// invalid argument the Rust side rejected, capability denied, etc).
100    /// The message is native-function-defined.
101    NativeError(String),
102    /// S7: `CallNative` failed the allowlist / NATIVE-right / revocation
103    /// check before the function pointer was touched.
104    NativeDenied(NativeCallError),
105    /// Explicit `Trap` opcode, e.g. an assertion emitted by a compiler.
106    Explicit(i32),
107    /// Broken VM invariant (e.g. empty frame stack while running). Category D
108    /// in the error model — surfaced as a Flow fault, never as `unwrap`.
109    Invariant(&'static str),
110    /// Per-flow heap quota refused a register write (`Str` / `Bytes`, including
111    /// those nested in a `Message`), or the value is nested past the decoder
112    /// ceiling and cannot be charged.
113    QuotaExceeded(String),
114    /// Relative `Jump` / `Branch` target outside the code.
115    ///
116    /// Verified chunks never hit this — `verify` already proved every offset.
117    /// Unverified / corrupted jumps fail closed here instead of completing
118    /// as an implicit `return Unit`.
119    BadJump {
120        target: usize,
121        code_len: usize,
122    },
123}
124
125impl fmt::Display for Fault {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        match self {
128            Fault::DivideByZero => write!(f, "division by zero"),
129            Fault::RegisterOutOfRange { reg, frame_size } => {
130                write!(
131                    f,
132                    "register r{reg} out of range (frame has {frame_size} registers)"
133                )
134            }
135            Fault::BadConstant { index, pool_size } => {
136                write!(
137                    f,
138                    "constant index {index} out of range (pool size {pool_size})"
139                )
140            }
141            Fault::BadFunction { index, table_size } => {
142                write!(
143                    f,
144                    "function index {index} out of range (table size {table_size})"
145                )
146            }
147            Fault::BadArity { passed, expected } => {
148                write!(
149                    f,
150                    "call passed {passed} arguments, callee arity is {expected}"
151                )
152            }
153            Fault::RegisterIndexOverflow { base, offset } => write!(
154                f,
155                "register index r{base}+{offset} overflows the register index space (max r255)"
156            ),
157            Fault::CallStackOverflow { depth } => write!(f, "call stack overflow at depth {depth}"),
158            Fault::TypeMismatch { expected, got } => {
159                write!(f, "type mismatch: expected {expected}, got {got}")
160            }
161            Fault::BadNative { index, table_size } => {
162                write!(
163                    f,
164                    "native function index {index} out of range (table size {table_size})"
165                )
166            }
167            Fault::NativeError(msg) => write!(f, "native function error: {msg}"),
168            Fault::NativeDenied(err) => write!(f, "{err}"),
169            Fault::Explicit(code) => write!(f, "explicit trap (code {code})"),
170            Fault::Invariant(msg) => write!(f, "vm invariant broken: {msg}"),
171            Fault::QuotaExceeded(msg) => write!(f, "{msg}"),
172            Fault::BadJump { target, code_len } => {
173                write!(
174                    f,
175                    "jump target {target} out of range (code length {code_len})"
176                )
177            }
178        }
179    }
180}
181
182impl std::error::Error for Fault {}