Skip to main content

byteflow/bytecode/
opcode.rs

1//! The Byteflow instruction set architecture (ISA v0).
2//!
3//! Byteflow is register-based (à la Lua 5.x / Dalvik) rather than stack-based
4//! (à la JVM/CPython). Register machines need roughly 40-50% fewer dispatched
5//! instructions than an equivalent stack machine because they avoid PUSH/POP
6//! traffic for every intermediate value, at the cost of slightly larger
7//! instruction words. For an interpreter whose steady-state cost is dominated
8//! by dispatch (branch prediction + icache misses), fewer instructions per
9//! logical operation wins.
10//!
11//! Every opcode fits in a single byte so a `Vec<Instruction>` is dense and
12//! the dispatch table (see `byteflow-vm::interp`) can be a flat jump table
13//! indexed directly by discriminant, with no bounds check in release builds
14//! (enforced instead at decode/verification time, see [`crate::verify`]).
15
16/// A single Byteflow opcode.
17///
18/// Numeric values are part of the stable on-disk ABI (`byteflow-bytecode`
19/// module format, see [`super::chunk::MAGIC`]) — never renumber an existing
20/// variant, only append.
21#[repr(u8)]
22#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
23pub enum Opcode {
24    /// Stop the current Flow's VM loop. Terminal state.
25    Halt = 0x00,
26
27    // ---- data movement ----------------------------------------------------
28    /// `LoadConst ra, kb`  →  `r[a] = constants[b]`
29    LoadConst = 0x01,
30    /// `Move ra, rb`  →  `r[a] = r[b]`
31    Move = 0x02,
32    /// `LoadImm ra, imm`  →  `r[a] = imm as i64` (fast path, skips const pool)
33    LoadImm = 0x03,
34
35    // ---- arithmetic (integer; float variants share the same encoding
36    // ---- but operate on Value::Float, selected by the operand's runtime tag)
37    Add = 0x10,
38    Sub = 0x11,
39    Mul = 0x12,
40    Div = 0x13,
41    Mod = 0x14,
42    Neg = 0x15,
43
44    // ---- comparison → writes a Value::Bool into ra
45    Eq = 0x18,
46    Lt = 0x19,
47    Le = 0x1A,
48
49    // ---- control flow -------------------------------------------------
50    /// `Jump imm` → unconditional relative jump (imm = signed offset in
51    /// instructions from the *next* pc).
52    Jump = 0x20,
53    /// `Branch ra, imm` → jump by `imm` iff `r[a]` is falsy (Bool(false),
54    /// Unit, or Int(0)). This is the only conditional branch; `if/else` and
55    /// loops both lower to Branch + Jump, keeping the interpreter's branch
56    /// predictor state small.
57    Branch = 0x21,
58
59    // ---- procedure calls (native Rust functions registered via FFI, or
60    // ---- other bytecode functions in the same chunk) ------------------
61    /// `Call ra, fb, nc` → call function `fb` with `nc` arguments taken from
62    /// `r[a..a+nc]`, result written back into `r[a]`.
63    Call = 0x30,
64    /// `Return ra` → return `r[a]` to the caller frame (or complete the
65    /// Flow if this is the outermost frame).
66    Return = 0x31,
67    /// `CallNative ra, fb, nc` → like `Call` but `fb` indexes the native
68    /// function table instead of the bytecode function table.
69    CallNative = 0x32,
70
71    // ---- Flow model --------------------------------------------------
72    /// `Spawn ra, fb, nc` → create a new virtual Flow starting at
73    /// function `fb`, passing `nc` arguments taken from `r[a+1..a+1+nc]`
74    /// (deliberately *not* overlapping `r[a]` itself, which is where the
75    /// scheduler writes a **Cap** to the child once created — FlowCap;
76    /// see [`crate::VmResult::Spawn`]).
77    Spawn = 0x40,
78    /// `Yield` → cooperative yield. Control returns to the scheduler, the
79    /// Flow is re-enqueued as `Ready` and may resume on any worker.
80    Yield = 0x41,
81    /// `Sleep ra` → suspend until `r[a]` (interpreted as milliseconds,
82    /// Value::Int) has elapsed. Registered on the timer wheel.
83    Sleep = 0x42,
84    /// `Exit ra` → terminate the Flow, `r[a]` is delivered to `.join()`.
85    Exit = 0x43,
86    /// `SelfPid ra` → `r[a] =` a **self Cap**
87    /// ([`CapRights::ADDRESSING`](crate::CapRights::ADDRESSING) =
88    /// `SEND|ASK|LINK|MONITOR`) for this flow.
89    /// (Opcode name kept for ABI; the value is `Value::Cap`, not Pid.)
90    /// The VM does not store its own id (it has no scheduler state); this
91    /// is a scheduler effect, same class as `Spawn`/`Receive`.
92    SelfPid = 0x44,
93
94    // ---- messaging --------------------------------------------------------
95    /// `Send ra, rb` → Atomic Hop: deliver `r[b]` (`Message`) to the Cap in
96    /// `r[a]`. With a full `Reject` inbox the sender parks (`WAITING_SEND`);
97    /// otherwise the hop is queued / handed off without blocking the worker
98    /// (see [`crate::docs::mailbox`]).
99    ///
100    /// VM requires Cap + Message; worker resolves Cap (SEND), stamps sender
101    /// + `reply_cap`, then pushes to the resolved mailbox.
102    Send = 0x50,
103    /// `Receive ra` → pop the next message into `r[a]`; if the mailbox is
104    /// empty, suspends the Flow in `Waiting` state until a message
105    /// arrives.
106    Receive = 0x51,
107    /// `ReceiveTimeout ra, rb` → like `Receive` but gives up after `r[b]`
108    /// milliseconds, writing `Value::Unit` into `r[a]` on timeout.
109    ReceiveTimeout = 0x52,
110    /// `ReceiveMatch ra, rb` → **Atomic Hop selective receive**: block until
111    /// a [`crate::Value::Message`] with `tag == r[b]` (as `u16`) is available.
112    /// Non-matching hops stay in the mailbox in FIFO order (skip, don't drop).
113    ReceiveMatch = 0x53,
114    /// `ReceiveMatchImm ra, imm` → like `ReceiveMatch` with an immediate tag
115    /// (`imm` must fit in `u16`).
116    ReceiveMatchImm = 0x54,
117    /// `Ask ra, rb, rc` → **atomic request/reply hop**.
118    ///
119    /// 1. Validate `r[b]` as Cap and `r[c]` as Message (VM).
120    /// 2. Scheduler resolves Cap (ASK), stamps `sender` + mints `reply_cap`.
121    /// 3. Deliver the request to the resolved FlowId (like `Send`).
122    /// 4. Suspend until a reply hop matches
123    ///    `request_id == request.request_id && sender == resolved_FlowId`.
124    /// 5. Write the reply `Message` into `r[a]`.
125    ///
126    /// Append-only ABI slot (`0x55`).
127    Ask = 0x55,
128    /// `Monitor ra, rb` → install a one-way watch on Cap `r[b]`; write
129    /// [`crate::MonitorRef`] as `Int` into `r[a]`.
130    Monitor = 0x56,
131    /// `Demonitor ra` → drop the monitor in `r[a]` (`Int` ref).
132    Demonitor = 0x57,
133    /// `Link ra, rb` → bidirectional link with Cap `r[b]`; write
134    /// [`crate::LinkId`] as `Int` into `r[a]`.
135    Link = 0x58,
136    /// `Unlink ra` → drop the link in `r[a]` (`Int` id).
137    Unlink = 0x59,
138    /// `AskTimeout ra, rb, rc, rd` → like `Ask`, but give up after
139    /// `r[imm]` milliseconds and write `Value::Unit` into `ra`.
140    ///
141    /// Encoding: `a=dest`, `b=cap`, `c=msg`, `imm=millis_reg`.
142    /// Append-only ABI slot (`0x5A`); `Trap` stays `0x60`.
143    AskTimeout = 0x5A,
144    /// `Delegate ra, rb, rights, rc?` → write an attenuated Cap into `r[a]`.
145    ///
146    /// `r[b]` is the source Cap; `imm` is the requested rights mask;
147    /// `c = 255` means no extra native-mask narrowing. The scheduler
148    /// calls `Cap::attenuate` — the only derivation path.
149    /// Append-only ABI slot (`0x5B`); `Trap` stays `0x60`.
150    Delegate = 0x5B,
151    /// `FreshRequestId ra` → `r[a] =` next per-flow correlation id (`Int`).
152    ///
153    /// Starts at 1; `0` is reserved as “unset” so `Send` / `Ask` can mint.
154    /// Not a capability — uniqueness, not unpredictability.
155    /// Append-only ABI slot (`0x5C`); `Trap` stays `0x60`.
156    FreshRequestId = 0x5C,
157    /// `ReceiveMatchCorr ra, rb, rc` → wait for a hop with
158    /// `tag == r[b]` and `request_id == r[c]`. Non-matching hops stay queued.
159    /// Append-only ABI slot (`0x5D`); `Trap` stays `0x60`.
160    ReceiveMatchCorr = 0x5D,
161    /// `ReceiveMatchCorrImm ra, rb, imm` → like [`Self::ReceiveMatchCorr`]
162    /// with immediate tag (`imm` as `u16`) and `request_id` from `r[b]`.
163    /// Append-only ABI slot (`0x5E`); `Trap` stays `0x60`.
164    ReceiveMatchCorrImm = 0x5E,
165    /// `SetTrapExit ra` → BEAM `process_flag(trap_exit, r[a])`.
166    ///
167    /// Truthy `r[a]` (same rules as [`Opcode::Branch`]) enables trapping:
168    /// this flow receives [`crate::TAG_SYS_EXIT`] when a linked peer exits
169    /// (including `Normal`), instead of being killed / silently dropping the
170    /// link.
171    /// Append-only ABI slot (`0x5F`); `Trap` stays `0x60`.
172    SetTrapExit = 0x5F,
173    /// `RegisterName ra` → publish `r[a]` (`Str`) as this flow's name.
174    /// Only the calling flow is registered. Requires `SEND` on self-authority
175    /// (confined spawn cannot squat names). Append-only (`0x62`).
176    RegisterName = 0x62,
177    /// `Whereis ra, rb` → look up `r[b]` (`Str`); write a **SEND** Cap for
178    /// the caller, or `Unit` if missing. Never a raw FlowId. (`0x63`)
179    Whereis = 0x63,
180    /// `ReceiveMatchKind ra, imm` → block until a [`crate::Value::Message`]
181    /// whose `payload.wire_tag() == imm` (BFV0 tag `0..=8`) is available.
182    /// Non-matching hops stay queued (FIFO skip). Append-only (`0x64`);
183    /// `Trap` stays `0x60`.
184    ReceiveMatchKind = 0x64,
185    /// `SetRestartPolicy imm` → set this flow's supervisor restart policy:
186    /// `0` = Always, `1` = OnFailure, `2` = Never. Invalid `imm` → Trap.
187    /// Append-only (`0x65`); `Trap` stays `0x60`.
188    SetRestartPolicy = 0x65,
189    /// `HostAwait ra, rb, imm` → park this flow and hand `(op=imm, args=r[b])`
190    /// to the host [`crate::HostAwaitBridge`]. On completion the host writes
191    /// a [`crate::Value`] into `r[a]` (register writeback, like `Receive`).
192    /// Requires a bridge on [`crate::RuntimeConfig`]; otherwise the flow fails.
193    /// Append-only (`0x66`); not a `CallNative` / std-native slot.
194    HostAwait = 0x66,
195    /// `ReceiveMatchTimeout ra, rb, rc` → like [`Self::ReceiveMatch`] but
196    /// give up after `r[c]` milliseconds and write `Value::Unit` (BEAM
197    /// `receive … after`). Non-matching hops stay queued. Append-only (`0x67`).
198    ReceiveMatchTimeout = 0x67,
199    /// `ReceiveMatchImmTimeout ra, rb, imm` → like [`Self::ReceiveMatchImm`]
200    /// with timeout register `r[b]` (imm = tag). Writes `Unit` on expiry.
201    /// Append-only (`0x68`).
202    ReceiveMatchImmTimeout = 0x68,
203    /// `IsAlive ra, rb` → `r[a] = Bool`: the Cap in `r[b]` is held by this
204    /// flow and still names a live flow (BEAM `is_process_alive/1`).
205    /// Unknown / not-held / revoked / non-flow target → `false` (no trap).
206    /// Append-only (`0x69`).
207    IsAlive = 0x69,
208    /// `ExitSignal ra, rb` → BEAM `exit/2`: signal the flow addressed by
209    /// Cap `r[a]` (needs `LINK`) with reason `r[b]` (`FlowExitReason` as `Int`).
210    /// `Normal` is ignored. `Killed` cannot be trapped. Other reasons become
211    /// a [`crate::TAG_SYS_EXIT`] hop when the target has `trap_exit`.
212    /// Append-only (`0x6A`).
213    ExitSignal = 0x6A,
214    /// `DictPut ra, rb, rc` → process dictionary: `r[a] = old`, key `r[b]`
215    /// (`Int`), value `r[c]` (scalar: Unit/Bool/Int/Float). Missing old → `Unit`.
216    /// Append-only (`0x6B`).
217    DictPut = 0x6B,
218    /// `DictGet ra, rb` → `r[a] = dict[r[b]]` or `Unit`. Append-only (`0x6C`).
219    DictGet = 0x6C,
220    /// `DictErase ra, rb` → remove key `r[b]`, write the old value or `Unit`
221    /// into `r[a]`. Append-only (`0x6D`).
222    DictErase = 0x6D,
223    /// `ReceiveMatchEq ra, rb, rc` → selective receive: `tag == r[b]` and
224    /// payload `Int == r[c]`. Non-matching hops stay queued. Append-only (`0x6E`).
225    ReceiveMatchEq = 0x6E,
226    /// `StartChild ra, policy, fn` → spawn function `imm` as a supervised
227    /// child of **this** flow's supervisor (`b` = restart policy `0..=2`).
228    /// Writes an addressing Cap into `r[a]`. The caller must itself have
229    /// been started by a host [`crate::Supervisor`]. Append-only (`0x6F`).
230    StartChild = 0x6F,
231
232    // ---- diagnostics / safety ------------------------------------------
233    /// `Trap imm` → deliberate fault (assertion failure, div-by-zero, bad
234    /// opcode encountered by a corrupt/foreign module, capability
235    /// violation). Propagates to the Flow supervisor as [`crate::FlowOutcome::Failed`].
236    Trap = 0x60,
237    /// `Nop` → no-op, used by the assembler to pad jump targets.
238    Nop = 0x61,
239}
240
241impl Opcode {
242    /// Decode a raw byte into an `Opcode`, used when loading foreign/untrusted
243    /// modules. Rejects anything outside the currently defined ISA rather
244    /// than transmuting garbage into a jump-table index (which is exactly
245    /// the class of bug that turns a VM into a code-execution primitive).
246    #[inline]
247    pub fn from_u8(byte: u8) -> Option<Opcode> {
248        use Opcode::*;
249        Some(match byte {
250            0x00 => Halt,
251            0x01 => LoadConst,
252            0x02 => Move,
253            0x03 => LoadImm,
254            0x10 => Add,
255            0x11 => Sub,
256            0x12 => Mul,
257            0x13 => Div,
258            0x14 => Mod,
259            0x15 => Neg,
260            0x18 => Eq,
261            0x19 => Lt,
262            0x1A => Le,
263            0x20 => Jump,
264            0x21 => Branch,
265            0x30 => Call,
266            0x31 => Return,
267            0x32 => CallNative,
268            0x40 => Spawn,
269            0x41 => Yield,
270            0x42 => Sleep,
271            0x43 => Exit,
272            0x44 => SelfPid,
273            0x50 => Send,
274            0x51 => Receive,
275            0x52 => ReceiveTimeout,
276            0x53 => ReceiveMatch,
277            0x54 => ReceiveMatchImm,
278            0x55 => Ask,
279            0x56 => Monitor,
280            0x57 => Demonitor,
281            0x58 => Link,
282            0x59 => Unlink,
283            0x5A => AskTimeout,
284            0x5B => Delegate,
285            0x5C => FreshRequestId,
286            0x5D => ReceiveMatchCorr,
287            0x5E => ReceiveMatchCorrImm,
288            0x5F => SetTrapExit,
289            0x60 => Trap,
290            0x62 => RegisterName,
291            0x63 => Whereis,
292            0x64 => ReceiveMatchKind,
293            0x65 => SetRestartPolicy,
294            0x66 => HostAwait,
295            0x67 => ReceiveMatchTimeout,
296            0x68 => ReceiveMatchImmTimeout,
297            0x69 => IsAlive,
298            0x6A => ExitSignal,
299            0x6B => DictPut,
300            0x6C => DictGet,
301            0x6D => DictErase,
302            0x6E => ReceiveMatchEq,
303            0x6F => StartChild,
304            0x61 => Nop,
305            _ => return None,
306        })
307    }
308
309    #[inline]
310    pub fn as_u8(self) -> u8 {
311        self as u8
312    }
313}
314
315impl std::fmt::Display for Opcode {
316    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
317        let name = match self {
318            Opcode::Halt => "Halt",
319            Opcode::LoadConst => "LoadConst",
320            Opcode::Move => "Move",
321            Opcode::LoadImm => "LoadImm",
322            Opcode::Add => "Add",
323            Opcode::Sub => "Sub",
324            Opcode::Mul => "Mul",
325            Opcode::Div => "Div",
326            Opcode::Mod => "Mod",
327            Opcode::Neg => "Neg",
328            Opcode::Eq => "Eq",
329            Opcode::Lt => "Lt",
330            Opcode::Le => "Le",
331            Opcode::Jump => "Jump",
332            Opcode::Branch => "Branch",
333            Opcode::Call => "Call",
334            Opcode::Return => "Return",
335            Opcode::CallNative => "CallNative",
336            Opcode::Spawn => "Spawn",
337            Opcode::Yield => "Yield",
338            Opcode::Sleep => "Sleep",
339            Opcode::Exit => "Exit",
340            Opcode::SelfPid => "SelfPid",
341            Opcode::Send => "Send",
342            Opcode::Receive => "Receive",
343            Opcode::ReceiveTimeout => "ReceiveTimeout",
344            Opcode::ReceiveMatch => "ReceiveMatch",
345            Opcode::ReceiveMatchImm => "ReceiveMatchImm",
346            Opcode::Ask => "Ask",
347            Opcode::Monitor => "Monitor",
348            Opcode::Demonitor => "Demonitor",
349            Opcode::Link => "Link",
350            Opcode::Unlink => "Unlink",
351            Opcode::AskTimeout => "AskTimeout",
352            Opcode::Delegate => "Delegate",
353            Opcode::FreshRequestId => "FreshRequestId",
354            Opcode::ReceiveMatchCorr => "ReceiveMatchCorr",
355            Opcode::ReceiveMatchCorrImm => "ReceiveMatchCorrImm",
356            Opcode::SetTrapExit => "SetTrapExit",
357            Opcode::RegisterName => "RegisterName",
358            Opcode::Whereis => "Whereis",
359            Opcode::ReceiveMatchKind => "ReceiveMatchKind",
360            Opcode::SetRestartPolicy => "SetRestartPolicy",
361            Opcode::HostAwait => "HostAwait",
362            Opcode::ReceiveMatchTimeout => "ReceiveMatchTimeout",
363            Opcode::ReceiveMatchImmTimeout => "ReceiveMatchImmTimeout",
364            Opcode::IsAlive => "IsAlive",
365            Opcode::ExitSignal => "ExitSignal",
366            Opcode::DictPut => "DictPut",
367            Opcode::DictGet => "DictGet",
368            Opcode::DictErase => "DictErase",
369            Opcode::ReceiveMatchEq => "ReceiveMatchEq",
370            Opcode::StartChild => "StartChild",
371            Opcode::Trap => "Trap",
372            Opcode::Nop => "Nop",
373        };
374        f.write_str(name)
375    }
376}