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// Docs ratchet: public items here predate `missing_docs`. Delete this
17// allow once they are documented; new files get the lint by default.
18#![allow(missing_docs)]
19
20/// A single Byteflow opcode.
21///
22/// Numeric values are part of the stable on-disk ABI (`byteflow-bytecode`
23/// module format, see [`super::chunk::MAGIC`]) — never renumber an existing
24/// variant, only append.
25#[repr(u8)]
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
27pub enum Opcode {
28 /// Stop the current Flow's VM loop. Terminal state.
29 Halt = 0x00,
30
31 // ---- data movement ----------------------------------------------------
32 /// `LoadConst ra, imm` → `r[a] = constants[imm]`
33 LoadConst = 0x01,
34 /// `Move ra, rb` → `r[a] = r[b]`
35 Move = 0x02,
36 /// `LoadImm ra, imm` → `r[a] = imm as i64` (fast path, skips const pool)
37 LoadImm = 0x03,
38
39 // ---- arithmetic (integer; float variants share the same encoding
40 // ---- but operate on Value::Float, selected by the operand's runtime tag)
41 Add = 0x10,
42 Sub = 0x11,
43 Mul = 0x12,
44 Div = 0x13,
45 Mod = 0x14,
46 Neg = 0x15,
47
48 // ---- comparison → writes a Value::Bool into ra
49 Eq = 0x18,
50 Lt = 0x19,
51 Le = 0x1A,
52
53 // ---- control flow -------------------------------------------------
54 /// `Jump imm` → unconditional relative jump (imm = signed offset in
55 /// instructions from the *next* pc).
56 Jump = 0x20,
57 /// `Branch ra, imm` → jump by `imm` iff `r[a]` is falsy (Bool(false),
58 /// Unit, or Int(0)). This is the only conditional branch; `if/else` and
59 /// loops both lower to Branch + Jump, keeping the interpreter's branch
60 /// predictor state small.
61 Branch = 0x21,
62
63 // ---- procedure calls (native Rust functions registered via FFI, or
64 // ---- other bytecode functions in the same chunk) ------------------
65 /// `Call ra, fb, nc` → call function `fb` with `nc` arguments taken from
66 /// `r[a..a+nc]`, result written back into `r[a]`.
67 Call = 0x30,
68 /// `Return ra` → return `r[a]` to the caller frame (or complete the
69 /// Flow if this is the outermost frame).
70 Return = 0x31,
71 /// `CallNative ra, fb, nc` → like `Call` but `fb` indexes the native
72 /// function table instead of the bytecode function table.
73 CallNative = 0x32,
74
75 // ---- Flow model --------------------------------------------------
76 /// `Spawn ra, fb, nc` → create a new virtual Flow starting at
77 /// function `fb`, passing `nc` arguments taken from `r[a+1..a+1+nc]`
78 /// (deliberately *not* overlapping `r[a]` itself, which is where the
79 /// scheduler writes a **Cap** to the child once created — FlowCap;
80 /// see [`crate::VmResult::Spawn`]).
81 Spawn = 0x40,
82 /// `Yield` → cooperative yield. Control returns to the scheduler, the
83 /// Flow is re-enqueued as `Ready` and may resume on any worker.
84 Yield = 0x41,
85 /// `Sleep ra` → suspend until `r[a]` (interpreted as milliseconds,
86 /// Value::Int) has elapsed. Registered on the timer wheel.
87 Sleep = 0x42,
88 /// `Exit ra` → terminate the Flow, `r[a]` is delivered to `.join()`.
89 Exit = 0x43,
90 /// `SelfPid ra` → `r[a] =` a **self Cap**
91 /// ([`CapRights::ADDRESSING`](crate::CapRights::ADDRESSING) =
92 /// `SEND|ASK|LINK|MONITOR`) for this flow.
93 /// (Opcode name kept for ABI; the value is `Value::Cap`, not Pid.)
94 /// The VM does not store its own id (it has no scheduler state); this
95 /// is a scheduler effect, same class as `Spawn`/`Receive`.
96 SelfPid = 0x44,
97
98 // ---- messaging --------------------------------------------------------
99 /// `Send ra, rb` → Atomic Hop: deliver `r[b]` (`Message`) to the Cap in
100 /// `r[a]`. With a full `Reject` inbox the sender parks (`WAITING_SEND`);
101 /// otherwise the hop is queued / handed off without blocking the worker
102 /// (see [`crate::docs::mailbox`]).
103 ///
104 /// VM requires Cap + Message; worker resolves Cap (SEND), stamps sender
105 /// + `reply_cap`, then pushes to the resolved mailbox.
106 Send = 0x50,
107 /// `Receive ra` → pop the next message into `r[a]`; if the mailbox is
108 /// empty, suspends the Flow in `Waiting` state until a message
109 /// arrives.
110 Receive = 0x51,
111 /// `ReceiveTimeout ra, rb` → like `Receive` but gives up after `r[b]`
112 /// milliseconds, writing `Value::Unit` into `r[a]` on timeout.
113 ReceiveTimeout = 0x52,
114 /// `ReceiveMatch ra, rb` → **Atomic Hop selective receive**: block until
115 /// a [`crate::Value::Message`] with `tag == r[b]` (as `u16`) is available.
116 /// Non-matching hops stay in the mailbox in FIFO order (skip, don't drop).
117 ReceiveMatch = 0x53,
118 /// `ReceiveMatchImm ra, imm` → like `ReceiveMatch` with an immediate tag
119 /// (`imm` must fit in `u16`).
120 ReceiveMatchImm = 0x54,
121 /// `Ask ra, rb, rc` → **atomic request/reply hop**.
122 ///
123 /// 1. Validate `r[b]` as Cap and `r[c]` as Message (VM).
124 /// 2. Scheduler resolves Cap (ASK), stamps `sender` + mints `reply_cap`.
125 /// 3. Deliver the request to the resolved FlowId (like `Send`).
126 /// 4. Suspend until a reply hop matches
127 /// `request_id == request.request_id && sender == resolved_FlowId`.
128 /// 5. Write the reply `Message` into `r[a]`.
129 ///
130 /// Append-only ABI slot (`0x55`).
131 Ask = 0x55,
132 /// `Monitor ra, rb` → install a one-way watch on Cap `r[b]`; write
133 /// [`crate::MonitorRef`] as `Int` into `r[a]`.
134 Monitor = 0x56,
135 /// `Demonitor ra` → drop the monitor in `r[a]` (`Int` ref).
136 Demonitor = 0x57,
137 /// `Link ra, rb` → bidirectional link with Cap `r[b]`; write
138 /// [`crate::LinkId`] as `Int` into `r[a]`. `0` means finalize already
139 /// consumed the row and propagated the exit; that value is not a link.
140 Link = 0x58,
141 /// `Unlink ra` → drop the link in `r[a]` (`Int` id). `0` does nothing.
142 Unlink = 0x59,
143 /// `AskTimeout ra, rb, rc, imm` → like `Ask`, but give up after
144 /// `r[imm]` milliseconds and write `Value::Unit` into `ra`.
145 ///
146 /// Encoding: `a=dest`, `b=cap`, `c=msg`, `imm=millis_reg`.
147 /// Append-only ABI slot (`0x5A`); `Trap` stays `0x60`.
148 AskTimeout = 0x5A,
149 /// `Delegate ra, rb, rights, rc?` → write an attenuated Cap into `r[a]`.
150 ///
151 /// `r[b]` is the source Cap; `imm` is the requested rights mask;
152 /// `c = 255` means no extra native-mask narrowing. The scheduler
153 /// calls `Cap::attenuate` — the only derivation path.
154 /// Append-only ABI slot (`0x5B`); `Trap` stays `0x60`.
155 Delegate = 0x5B,
156 /// `FreshRequestId ra` → `r[a] =` next per-flow correlation id (`Int`).
157 ///
158 /// Starts at 1; `0` is reserved as “unset” so `Send` / `Ask` can mint.
159 /// Not a capability — uniqueness, not unpredictability.
160 /// Append-only ABI slot (`0x5C`); `Trap` stays `0x60`.
161 FreshRequestId = 0x5C,
162 /// `ReceiveMatchCorr ra, rb, rc` → wait for a hop with
163 /// `tag == r[b]` and `request_id == r[c]`. Non-matching hops stay queued.
164 /// Append-only ABI slot (`0x5D`); `Trap` stays `0x60`.
165 ReceiveMatchCorr = 0x5D,
166 /// `ReceiveMatchCorrImm ra, rb, imm` → like [`Self::ReceiveMatchCorr`]
167 /// with immediate tag (`imm` as `u16`) and `request_id` from `r[b]`.
168 /// Append-only ABI slot (`0x5E`); `Trap` stays `0x60`.
169 ReceiveMatchCorrImm = 0x5E,
170 /// `SetTrapExit ra` → BEAM `process_flag(trap_exit, r[a])`.
171 ///
172 /// Truthy `r[a]` (same rules as [`Opcode::Branch`]) enables trapping:
173 /// this flow receives [`crate::TAG_SYS_EXIT`] when a linked peer exits
174 /// (including `Normal`), instead of being killed / silently dropping the
175 /// link.
176 /// Append-only ABI slot (`0x5F`); `Trap` stays `0x60`.
177 SetTrapExit = 0x5F,
178 /// `RegisterName ra` → publish `r[a]` (`Str`) as this flow's name.
179 /// Only the calling flow is registered. Requires `SEND` on self-authority
180 /// (confined spawn cannot squat names). Append-only (`0x62`).
181 RegisterName = 0x62,
182 /// `Whereis ra, rb` → look up `r[b]` (`Str`); write a **SEND** Cap for
183 /// the caller, or `Unit` if missing. Never a raw FlowId. (`0x63`)
184 Whereis = 0x63,
185 /// `ReceiveMatchKind ra, imm` → block until a [`crate::Value::Message`]
186 /// whose `payload.wire_tag() == imm` (BFV0 tag `0..=10`) is available.
187 /// Non-matching hops stay queued (FIFO skip). Append-only (`0x64`);
188 /// `Trap` stays `0x60`.
189 ReceiveMatchKind = 0x64,
190 /// `SetRestartPolicy imm` → set this flow's supervisor restart policy:
191 /// `0` = Always, `1` = OnFailure, `2` = Never. Invalid `imm` → Trap.
192 /// Append-only (`0x65`); `Trap` stays `0x60`.
193 SetRestartPolicy = 0x65,
194 /// `HostAwait ra, rb, imm` → register a host operation `(op=imm, args=r[b])`
195 /// and write its ticket id (`Int`) into `r[a]`. The flow keeps running.
196 /// The host completes with a [`crate::TAG_SYS_AWAIT`] hop (`request_id`
197 /// = ticket) that bytecode reads with `Receive`. Requires a bridge on
198 /// [`crate::RuntimeConfig`]; otherwise the flow fails.
199 /// Append-only (`0x66`); not a `CallNative` / std-native slot.
200 HostAwait = 0x66,
201 /// `ReceiveMatchTimeout ra, rb, rc` → like [`Self::ReceiveMatch`] but
202 /// give up after `r[c]` milliseconds and write `Value::Unit` (BEAM
203 /// `receive … after`). Non-matching hops stay queued. Append-only (`0x67`).
204 ReceiveMatchTimeout = 0x67,
205 /// `ReceiveMatchImmTimeout ra, rb, imm` → like [`Self::ReceiveMatchImm`]
206 /// with timeout register `r[b]` (imm = tag). Writes `Unit` on expiry.
207 /// Append-only (`0x68`).
208 ReceiveMatchImmTimeout = 0x68,
209 /// `IsAlive ra, rb` → `r[a] = Bool`: the Cap in `r[b]` is held by this
210 /// flow and still names a live flow (BEAM `is_process_alive/1`).
211 /// Unknown / not-held / revoked / non-flow target → `false` (no trap).
212 /// Append-only (`0x69`).
213 IsAlive = 0x69,
214 /// `ExitSignal ra, rb` → BEAM `exit/2`: signal the flow addressed by
215 /// Cap `r[a]` (needs `LINK`) with reason `r[b]` (`FlowExitReason` as `Int`).
216 /// `Normal` is ignored. `Killed` cannot be trapped. Other reasons become
217 /// a [`crate::TAG_SYS_EXIT`] hop when the target has `trap_exit`.
218 /// Append-only (`0x6A`).
219 ExitSignal = 0x6A,
220 /// `DictPut ra, rb, rc` → process dictionary: `r[a] = old`, key `r[b]`
221 /// (`Int`), value `r[c]` (scalar, `Str`, or `Bytes`). `Str` / `Bytes`
222 /// are charged on the flow quota for as long as the dictionary holds
223 /// them. Missing old → `Unit`. Append-only (`0x6B`).
224 DictPut = 0x6B,
225 /// `DictGet ra, rb` → `r[a] = dict[r[b]]` or `Unit`. Append-only (`0x6C`).
226 DictGet = 0x6C,
227 /// `DictErase ra, rb` → remove key `r[b]`, write the old value or `Unit`
228 /// into `r[a]`. Append-only (`0x6D`).
229 DictErase = 0x6D,
230 /// `ReceiveMatchEq ra, rb, rc` → selective receive: `tag == r[b]` and
231 /// payload `Int == r[c]`. Non-matching hops stay queued. Append-only (`0x6E`).
232 ReceiveMatchEq = 0x6E,
233 /// `StartChild ra, policy, fn` → spawn function `imm` as a supervised
234 /// child (`b` = restart policy `0..=2`). Writes an addressing Cap into
235 /// `r[a]`. Attaches to the supervisor this flow started with
236 /// [`Self::StartSupervisor`], otherwise to the host supervisor that
237 /// started this flow. With neither, the flow fails. Append-only (`0x6F`).
238 StartChild = 0x6F,
239 /// `ReceiveMatchValue ra, rb, rc` → selective receive: `tag == r[b]` and
240 /// payload structurally equal to `r[c]` (any [`crate::Value`], not only
241 /// `Int`). Non-matching hops stay queued. Append-only (`0x70`).
242 ReceiveMatchValue = 0x70,
243 /// `SendRemote ra, rb, rc` → deliver hop `r[c]` to node `r[a]` (`Int`)
244 /// service `r[b]` (`Str`). The host drains [`crate::DistributionBridge`].
245 /// Byteflow does not open a socket. Append-only (`0x71`).
246 SendRemote = 0x71,
247 /// `StartSupervisor imm` → start a supervisor owned by this flow.
248 /// `imm`: `0` one-for-one, `1` one-for-all, `2` rest-for-one.
249 /// Later `StartChild` attaches to it. Append-only (`0x72`).
250 StartSupervisor = 0x72,
251 /// `AddImm ra, rb, imm` → `r[a] = r[b] + imm` (`imm` sign-extended to
252 /// `i64`). Integer add wraps; a float in `r[b]` adds in `f64`. One
253 /// instruction instead of `LoadImm` plus `Add`, and no scratch register.
254 /// Append-only (`0x73`).
255 AddImm = 0x73,
256 /// `CallNativeFrom ra, rb, native` → `r[a] = native_1(r[b])`.
257 ///
258 /// Same FFI slot as [`Self::CallNative`] (`imm` is the native index) but
259 /// the argument is `r[b]` and the result lands in `r[a]`. `r[b]` survives
260 /// when `a != b`, so unpacking a `Message` does not need a preceding
261 /// `Move`. Append-only (`0x74`).
262 CallNativeFrom = 0x74,
263 /// `SubImm ra, rb, imm` → `r[a] = r[b] - imm` (`imm` sign-extended to
264 /// `i64`). Integer subtraction wraps; a float in `r[b]` subtracts in
265 /// `f64`. Append-only (`0x75`).
266 SubImm = 0x75,
267 /// `LtImm ra, rb, imm` → `r[a] = r[b] < imm` as `Bool`. Integers compare
268 /// as signed `i64`. Floats compare as `f64` (NaN is not less). `Bool`
269 /// is not a number here. Append-only (`0x76`).
270 LtImm = 0x76,
271 /// `ListPack ra, rb, imm` → `r[a]` becomes a list of `imm` values
272 /// starting at `r[b]`. `imm` is `0..=256`. Append-only (`0x77`).
273 ListPack = 0x77,
274 /// `ListGet ra, rb, imm` → `r[a] = r[b][imm]`. `r[b]` must be a list
275 /// and `imm` a valid index. Append-only (`0x78`).
276 ListGet = 0x78,
277 /// `ListLen ra, rb` → `r[a] = len(r[b])` as `Int`. Append-only (`0x79`).
278 ListLen = 0x79,
279 /// `MulImm ra, rb, imm` → `r[a] = r[b] * imm` (`imm` sign-extended to
280 /// `i64`). Integer multiply wraps; a float in `r[b]` multiplies in
281 /// `f64`. Append-only (`0x7A`).
282 MulImm = 0x7A,
283 /// `EqImm ra, rb, imm` → `r[a] = Bool(r[b] == Int(imm))`.
284 ///
285 /// The immediate is an integer. A float, bool, or string in `r[b]`
286 /// compares unequal, the same as [`Self::Eq`] against a `LoadImm`.
287 /// Append-only (`0x7B`).
288 EqImm = 0x7B,
289 /// `LeImm ra, rb, imm` → `r[a] = r[b] <= imm` as `Bool`. Integers
290 /// compare as signed `i64`. Floats compare as `f64` (NaN is not less
291 /// or equal). `Bool` is not a number here. Append-only (`0x7C`).
292 LeImm = 0x7C,
293 /// `BitAnd ra, rb, rc` → `r[a] = r[b] & r[c]`. Both operands must be
294 /// `Int`. Append-only (`0x7D`).
295 BitAnd = 0x7D,
296 /// `BitOr ra, rb, rc` → `r[a] = r[b] | r[c]`. Both operands must be
297 /// `Int`. Append-only (`0x7E`).
298 BitOr = 0x7E,
299 /// `BitXor ra, rb, rc` → `r[a] = r[b] ^ r[c]`. Both operands must be
300 /// `Int`. Append-only (`0x7F`).
301 BitXor = 0x7F,
302 /// `BitNot ra, rb` → `r[a] = !r[b]`. `r[b]` must be `Int`.
303 /// Append-only (`0x80`).
304 BitNot = 0x80,
305 /// `Shl ra, rb, rc` → `r[a] = r[b] << (r[c] & 63)`. Both operands must
306 /// be `Int`. The shift count keeps its low 6 bits, so a negative count
307 /// still names a shift in `0..64`. Append-only (`0x81`).
308 Shl = 0x81,
309 /// `Shr ra, rb, rc` → arithmetic `r[a] = r[b] >> (r[c] & 63)`. Both
310 /// operands must be `Int`. The sign bit fills the vacated bits.
311 /// Append-only (`0x82`).
312 Shr = 0x82,
313 /// `ReceiveMatchCmp ra, rb, rc, imm` → wait for tag `r[b]` and an `Int`
314 /// payload compared with `r[c]` by `imm` (`0` eq, `1` lt, `2` le).
315 /// A hop that fails the comparison stays queued. Append-only (`0x83`).
316 ReceiveMatchCmp = 0x83,
317 /// `MapPack ra, rb, imm` → `r[a]` becomes a map of `imm` pairs starting
318 /// at `r[b]` (`key`, `value`, `key`, `value`, …). `imm` is `0..=256`.
319 /// Keys are `Int` or `Str`. A duplicate key traps. Append-only (`0x84`).
320 MapPack = 0x84,
321 /// `MapGet ra, rb, rc` → `r[a] = r[b][r[c]]`. Missing key writes `Unit`.
322 /// Append-only (`0x85`).
323 MapGet = 0x85,
324 /// `MapLen ra, rb` → `r[a] = len(r[b])` as `Int`. Append-only (`0x86`).
325 MapLen = 0x86,
326 /// `TableOpen ra, rb` → this flow's table, named by the `Str` in `r[b]`.
327 /// Writes a Cap (`SEND|RECV`, target = that table) into `r[a]`.
328 /// A second open traps. Append-only (`0x87`).
329 TableOpen = 0x87,
330 /// `TableGet ra, rb, rc` → `r[a]` is the row of cap `r[b]` at key `r[c]`.
331 /// Requires `RECV`. Missing key writes `Unit`. Append-only (`0x88`).
332 TableGet = 0x88,
333 /// `TablePut ra, rb, rc` → store `r[c]` in cap `r[a]` at key `r[b]`.
334 /// Requires `SEND`. Append-only (`0x89`).
335 TablePut = 0x89,
336 /// `RecordPack ra, rb, imm` → `r[a]` becomes a positional record of
337 /// `imm` fields starting at `r[b]`. `imm` is `0..=256`. Append-only (`0x8A`).
338 RecordPack = 0x8A,
339 /// `RecordGet ra, rb, imm` → `r[a] = r[b][imm]`. `r[b]` must be a record.
340 /// Append-only (`0x8B`).
341 RecordGet = 0x8B,
342 /// `RecordLen ra, rb` → `r[a] = len(r[b])` as `Int`. Append-only (`0x8C`).
343 RecordLen = 0x8C,
344 /// `Ne ra, rb, rc` → `r[a] = Bool(r[b] != r[c])`. Append-only (`0x8D`).
345 Ne = 0x8D,
346 /// `Gt ra, rb, rc` → `r[a] = Bool(r[b] > r[c])`. Append-only (`0x8E`).
347 Gt = 0x8E,
348 /// `Ge ra, rb, rc` → `r[a] = Bool(r[b] >= r[c])`. Append-only (`0x8F`).
349 Ge = 0x8F,
350 /// `NeImm ra, rb, imm` → `r[a] = Bool(r[b] != Int(imm))`. Append-only (`0x90`).
351 NeImm = 0x90,
352 /// `GtImm ra, rb, imm` → `r[a] = Bool(r[b] > imm)`. Append-only (`0x91`).
353 GtImm = 0x91,
354 /// `GeImm ra, rb, imm` → `r[a] = Bool(r[b] >= imm)`. Append-only (`0x92`).
355 GeImm = 0x92,
356 /// `Ushr ra, rb, rc` → logical `r[a] = (r[b] as u64) >> (r[c] & 63)`. Both operands `Int`. Append-only (`0x93`).
357 Ushr = 0x93,
358 /// `BranchTrue ra, imm` → jump by `imm` iff `r[a]` is truthy. Append-only (`0x94`).
359 BranchTrue = 0x94,
360 /// `StrLen ra, rb` → `r[a] = len(r[b])` as `Int`. Append-only (`0x95`).
361 StrLen = 0x95,
362 /// `BytesLen ra, rb` → `r[a] = len(r[b])` as `Int`. Append-only (`0x96`).
363 BytesLen = 0x96,
364 /// `TailCall ra, fb, nc` → tail-recursive call replacing current frame. Append-only (`0x97`).
365 TailCall = 0x97,
366
367 // ---- diagnostics / safety ------------------------------------------
368 /// `Trap imm` → deliberate fault (assertion failure, div-by-zero, bad
369 /// opcode encountered by a corrupt/foreign module, capability
370 /// violation). Propagates to the Flow supervisor as [`crate::FlowOutcome::Failed`].
371 Trap = 0x60,
372 /// `Nop` → no-op, used by the assembler to pad jump targets.
373 Nop = 0x61,
374}
375
376impl Opcode {
377 /// Decode a raw byte into an `Opcode`, used when loading foreign/untrusted
378 /// modules. Rejects anything outside the currently defined ISA rather
379 /// than transmuting garbage into a jump-table index (which is exactly
380 /// the class of bug that turns a VM into a code-execution primitive).
381 #[inline]
382 pub fn from_u8(byte: u8) -> Option<Opcode> {
383 use Opcode::*;
384 Some(match byte {
385 0x00 => Halt,
386 0x01 => LoadConst,
387 0x02 => Move,
388 0x03 => LoadImm,
389 0x10 => Add,
390 0x11 => Sub,
391 0x12 => Mul,
392 0x13 => Div,
393 0x14 => Mod,
394 0x15 => Neg,
395 0x18 => Eq,
396 0x19 => Lt,
397 0x1A => Le,
398 0x20 => Jump,
399 0x21 => Branch,
400 0x30 => Call,
401 0x31 => Return,
402 0x32 => CallNative,
403 0x40 => Spawn,
404 0x41 => Yield,
405 0x42 => Sleep,
406 0x43 => Exit,
407 0x44 => SelfPid,
408 0x50 => Send,
409 0x51 => Receive,
410 0x52 => ReceiveTimeout,
411 0x53 => ReceiveMatch,
412 0x54 => ReceiveMatchImm,
413 0x55 => Ask,
414 0x56 => Monitor,
415 0x57 => Demonitor,
416 0x58 => Link,
417 0x59 => Unlink,
418 0x5A => AskTimeout,
419 0x5B => Delegate,
420 0x5C => FreshRequestId,
421 0x5D => ReceiveMatchCorr,
422 0x5E => ReceiveMatchCorrImm,
423 0x5F => SetTrapExit,
424 0x60 => Trap,
425 0x61 => Nop,
426 0x62 => RegisterName,
427 0x63 => Whereis,
428 0x64 => ReceiveMatchKind,
429 0x65 => SetRestartPolicy,
430 0x66 => HostAwait,
431 0x67 => ReceiveMatchTimeout,
432 0x68 => ReceiveMatchImmTimeout,
433 0x69 => IsAlive,
434 0x6A => ExitSignal,
435 0x6B => DictPut,
436 0x6C => DictGet,
437 0x6D => DictErase,
438 0x6E => ReceiveMatchEq,
439 0x6F => StartChild,
440 0x70 => ReceiveMatchValue,
441 0x71 => SendRemote,
442 0x72 => StartSupervisor,
443 0x73 => AddImm,
444 0x74 => CallNativeFrom,
445 0x75 => SubImm,
446 0x76 => LtImm,
447 0x77 => ListPack,
448 0x78 => ListGet,
449 0x79 => ListLen,
450 0x7A => MulImm,
451 0x7B => EqImm,
452 0x7C => LeImm,
453 0x7D => BitAnd,
454 0x7E => BitOr,
455 0x7F => BitXor,
456 0x80 => BitNot,
457 0x81 => Shl,
458 0x82 => Shr,
459 0x83 => ReceiveMatchCmp,
460 0x84 => MapPack,
461 0x85 => MapGet,
462 0x86 => MapLen,
463 0x87 => TableOpen,
464 0x88 => TableGet,
465 0x89 => TablePut,
466 0x8A => RecordPack,
467 0x8B => RecordGet,
468 0x8C => RecordLen,
469 0x8D => Ne,
470 0x8E => Gt,
471 0x8F => Ge,
472 0x90 => NeImm,
473 0x91 => GtImm,
474 0x92 => GeImm,
475 0x93 => Ushr,
476 0x94 => BranchTrue,
477 0x95 => StrLen,
478 0x96 => BytesLen,
479 0x97 => TailCall,
480 _ => return None,
481 })
482 }
483
484 #[inline]
485 pub fn as_u8(self) -> u8 {
486 self as u8
487 }
488}
489
490impl std::fmt::Display for Opcode {
491 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
492 let name = match self {
493 Opcode::Halt => "Halt",
494 Opcode::LoadConst => "LoadConst",
495 Opcode::Move => "Move",
496 Opcode::LoadImm => "LoadImm",
497 Opcode::Add => "Add",
498 Opcode::AddImm => "AddImm",
499 Opcode::SubImm => "SubImm",
500 Opcode::LtImm => "LtImm",
501 Opcode::ListPack => "ListPack",
502 Opcode::ListGet => "ListGet",
503 Opcode::ListLen => "ListLen",
504 Opcode::MulImm => "MulImm",
505 Opcode::EqImm => "EqImm",
506 Opcode::LeImm => "LeImm",
507 Opcode::BitAnd => "BitAnd",
508 Opcode::BitOr => "BitOr",
509 Opcode::BitXor => "BitXor",
510 Opcode::BitNot => "BitNot",
511 Opcode::Shl => "Shl",
512 Opcode::Shr => "Shr",
513 Opcode::ReceiveMatchCmp => "ReceiveMatchCmp",
514 Opcode::MapPack => "MapPack",
515 Opcode::MapGet => "MapGet",
516 Opcode::MapLen => "MapLen",
517 Opcode::TableOpen => "TableOpen",
518 Opcode::TableGet => "TableGet",
519 Opcode::TablePut => "TablePut",
520 Opcode::RecordPack => "RecordPack",
521 Opcode::RecordGet => "RecordGet",
522 Opcode::RecordLen => "RecordLen",
523 Opcode::Ne => "Ne",
524 Opcode::Gt => "Gt",
525 Opcode::Ge => "Ge",
526 Opcode::NeImm => "NeImm",
527 Opcode::GtImm => "GtImm",
528 Opcode::GeImm => "GeImm",
529 Opcode::Ushr => "Ushr",
530 Opcode::BranchTrue => "BranchTrue",
531 Opcode::StrLen => "StrLen",
532 Opcode::BytesLen => "BytesLen",
533 Opcode::TailCall => "TailCall",
534 Opcode::Sub => "Sub",
535 Opcode::Mul => "Mul",
536 Opcode::Div => "Div",
537 Opcode::Mod => "Mod",
538 Opcode::Neg => "Neg",
539 Opcode::Eq => "Eq",
540 Opcode::Lt => "Lt",
541 Opcode::Le => "Le",
542 Opcode::Jump => "Jump",
543 Opcode::Branch => "Branch",
544 Opcode::Call => "Call",
545 Opcode::Return => "Return",
546 Opcode::CallNative => "CallNative",
547 Opcode::CallNativeFrom => "CallNativeFrom",
548 Opcode::Spawn => "Spawn",
549 Opcode::Yield => "Yield",
550 Opcode::Sleep => "Sleep",
551 Opcode::Exit => "Exit",
552 Opcode::SelfPid => "SelfPid",
553 Opcode::Send => "Send",
554 Opcode::Receive => "Receive",
555 Opcode::ReceiveTimeout => "ReceiveTimeout",
556 Opcode::ReceiveMatch => "ReceiveMatch",
557 Opcode::ReceiveMatchImm => "ReceiveMatchImm",
558 Opcode::Ask => "Ask",
559 Opcode::Monitor => "Monitor",
560 Opcode::Demonitor => "Demonitor",
561 Opcode::Link => "Link",
562 Opcode::Unlink => "Unlink",
563 Opcode::AskTimeout => "AskTimeout",
564 Opcode::Delegate => "Delegate",
565 Opcode::FreshRequestId => "FreshRequestId",
566 Opcode::ReceiveMatchCorr => "ReceiveMatchCorr",
567 Opcode::ReceiveMatchCorrImm => "ReceiveMatchCorrImm",
568 Opcode::SetTrapExit => "SetTrapExit",
569 Opcode::RegisterName => "RegisterName",
570 Opcode::Whereis => "Whereis",
571 Opcode::ReceiveMatchKind => "ReceiveMatchKind",
572 Opcode::SetRestartPolicy => "SetRestartPolicy",
573 Opcode::HostAwait => "HostAwait",
574 Opcode::ReceiveMatchTimeout => "ReceiveMatchTimeout",
575 Opcode::ReceiveMatchImmTimeout => "ReceiveMatchImmTimeout",
576 Opcode::IsAlive => "IsAlive",
577 Opcode::ExitSignal => "ExitSignal",
578 Opcode::DictPut => "DictPut",
579 Opcode::DictGet => "DictGet",
580 Opcode::DictErase => "DictErase",
581 Opcode::ReceiveMatchEq => "ReceiveMatchEq",
582 Opcode::StartChild => "StartChild",
583 Opcode::ReceiveMatchValue => "ReceiveMatchValue",
584 Opcode::SendRemote => "SendRemote",
585 Opcode::StartSupervisor => "StartSupervisor",
586 Opcode::Trap => "Trap",
587 Opcode::Nop => "Nop",
588 };
589 f.write_str(name)
590 }
591}
592
593/// Integer comparison used by [`Opcode::ReceiveMatchCmp`].
594#[derive(Clone, Copy, Debug, PartialEq, Eq)]
595pub enum IntCmp {
596 Eq,
597 Lt,
598 Le,
599}
600
601impl IntCmp {
602 pub const fn from_imm(imm: i32) -> Option<Self> {
603 match imm {
604 0 => Some(Self::Eq),
605 1 => Some(Self::Lt),
606 2 => Some(Self::Le),
607 _ => None,
608 }
609 }
610
611 pub const fn as_imm(self) -> i32 {
612 match self {
613 Self::Eq => 0,
614 Self::Lt => 1,
615 Self::Le => 2,
616 }
617 }
618
619 pub fn holds(self, payload: i64, bound: i64) -> bool {
620 match self {
621 Self::Eq => payload == bound,
622 Self::Lt => payload < bound,
623 Self::Le => payload <= bound,
624 }
625 }
626}