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