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 `Str` / `Bytes` register write.
111 QuotaExceeded(String),
112 /// Relative `Jump` / `Branch` target outside the code.
113 ///
114 /// Verified chunks never hit this — `verify` already proved every offset.
115 /// Unverified / corrupted jumps fail closed here instead of completing
116 /// as an implicit `return Unit`.
117 BadJump {
118 target: usize,
119 code_len: usize,
120 },
121}
122
123impl fmt::Display for Fault {
124 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125 match self {
126 Fault::DivideByZero => write!(f, "division by zero"),
127 Fault::RegisterOutOfRange { reg, frame_size } => {
128 write!(
129 f,
130 "register r{reg} out of range (frame has {frame_size} registers)"
131 )
132 }
133 Fault::BadConstant { index, pool_size } => {
134 write!(
135 f,
136 "constant index {index} out of range (pool size {pool_size})"
137 )
138 }
139 Fault::BadFunction { index, table_size } => {
140 write!(
141 f,
142 "function index {index} out of range (table size {table_size})"
143 )
144 }
145 Fault::BadArity { passed, expected } => {
146 write!(
147 f,
148 "call passed {passed} arguments, callee arity is {expected}"
149 )
150 }
151 Fault::RegisterIndexOverflow { base, offset } => write!(
152 f,
153 "register index r{base}+{offset} overflows the register index space (max r255)"
154 ),
155 Fault::CallStackOverflow { depth } => write!(f, "call stack overflow at depth {depth}"),
156 Fault::TypeMismatch { expected, got } => {
157 write!(f, "type mismatch: expected {expected}, got {got}")
158 }
159 Fault::BadNative { index, table_size } => {
160 write!(
161 f,
162 "native function index {index} out of range (table size {table_size})"
163 )
164 }
165 Fault::NativeError(msg) => write!(f, "native function error: {msg}"),
166 Fault::NativeDenied(err) => write!(f, "{err}"),
167 Fault::Explicit(code) => write!(f, "explicit trap (code {code})"),
168 Fault::Invariant(msg) => write!(f, "vm invariant broken: {msg}"),
169 Fault::QuotaExceeded(msg) => write!(f, "{msg}"),
170 Fault::BadJump { target, code_len } => {
171 write!(
172 f,
173 "jump target {target} out of range (code length {code_len})"
174 )
175 }
176 }
177 }
178}
179
180impl std::error::Error for Fault {}