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    /// Function call nesting exceeded `Vm::MAX_CALL_DEPTH`. Bytecode has no
70    /// native stack overflow (frames are heap-allocated `Vec<Value>`s), so
71    /// this is a deliberate, checked limit rather than a segfault.
72    CallStackOverflow {
73        depth: usize,
74    },
75    TypeMismatch {
76        expected: &'static str,
77        got: &'static str,
78    },
79    /// `CallNative` referenced a slot outside the runtime's registered
80    /// native function table (design notes §30-31). Distinct from
81    /// `BadFunction`, which is about the *bytecode* function table baked
82    /// into the chunk — natives are supplied by the embedder at `Vm`
83    /// construction time and can't be range-checked by
84    /// `crate::bytecode::verify`, which has no visibility into them.
85    BadNative {
86        index: u32,
87        table_size: u32,
88    },
89    /// A native function returned an error (host-side failure — I/O,
90    /// invalid argument the Rust side rejected, capability denied, etc).
91    /// The message is native-function-defined.
92    NativeError(String),
93    /// S7: `CallNative` failed the allowlist / NATIVE-right / revocation
94    /// check before the function pointer was touched.
95    NativeDenied(NativeCallError),
96    /// Explicit `Trap` opcode, e.g. an assertion emitted by a compiler.
97    Explicit(i32),
98    /// Broken VM invariant (e.g. empty frame stack while running). Category D
99    /// in the error model — surfaced as a Flow fault, never as `unwrap`.
100    Invariant(&'static str),
101    /// Per-flow heap quota refused a `Str` / `Bytes` register write.
102    QuotaExceeded(String),
103    /// Relative `Jump` / `Branch` target outside the code.
104    ///
105    /// Verified chunks never hit this — `verify` already proved every offset.
106    /// Unverified / corrupted jumps fail closed here instead of completing
107    /// as an implicit `return Unit`.
108    BadJump {
109        target: usize,
110        code_len: usize,
111    },
112}
113
114impl fmt::Display for Fault {
115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        match self {
117            Fault::DivideByZero => write!(f, "division by zero"),
118            Fault::RegisterOutOfRange { reg, frame_size } => {
119                write!(
120                    f,
121                    "register r{reg} out of range (frame has {frame_size} registers)"
122                )
123            }
124            Fault::BadConstant { index, pool_size } => {
125                write!(
126                    f,
127                    "constant index {index} out of range (pool size {pool_size})"
128                )
129            }
130            Fault::BadFunction { index, table_size } => {
131                write!(
132                    f,
133                    "function index {index} out of range (table size {table_size})"
134                )
135            }
136            Fault::RegisterIndexOverflow { base, offset } => write!(
137                f,
138                "register index r{base}+{offset} overflows the register index space (max r255)"
139            ),
140            Fault::CallStackOverflow { depth } => write!(f, "call stack overflow at depth {depth}"),
141            Fault::TypeMismatch { expected, got } => {
142                write!(f, "type mismatch: expected {expected}, got {got}")
143            }
144            Fault::BadNative { index, table_size } => {
145                write!(
146                    f,
147                    "native function index {index} out of range (table size {table_size})"
148                )
149            }
150            Fault::NativeError(msg) => write!(f, "native function error: {msg}"),
151            Fault::NativeDenied(err) => write!(f, "{err}"),
152            Fault::Explicit(code) => write!(f, "explicit trap (code {code})"),
153            Fault::Invariant(msg) => write!(f, "vm invariant broken: {msg}"),
154            Fault::QuotaExceeded(msg) => write!(f, "{msg}"),
155            Fault::BadJump { target, code_len } => {
156                write!(
157                    f,
158                    "jump target {target} out of range (code length {code_len})"
159                )
160            }
161        }
162    }
163}
164
165impl std::error::Error for Fault {}