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, imm`  →  `r[a] = constants[imm]`
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]`. `0` means finalize already
135    /// consumed the row and propagated the exit; that value is not a link.
136    Link = 0x58,
137    /// `Unlink ra` → drop the link in `r[a]` (`Int` id). `0` does nothing.
138    Unlink = 0x59,
139    /// `AskTimeout ra, rb, rc, imm` → like `Ask`, but give up after
140    /// `r[imm]` milliseconds and write `Value::Unit` into `ra`.
141    ///
142    /// Encoding: `a=dest`, `b=cap`, `c=msg`, `imm=millis_reg`.
143    /// Append-only ABI slot (`0x5A`); `Trap` stays `0x60`.
144    AskTimeout = 0x5A,
145    /// `Delegate ra, rb, rights, rc?` → write an attenuated Cap into `r[a]`.
146    ///
147    /// `r[b]` is the source Cap; `imm` is the requested rights mask;
148    /// `c = 255` means no extra native-mask narrowing. The scheduler
149    /// calls `Cap::attenuate` — the only derivation path.
150    /// Append-only ABI slot (`0x5B`); `Trap` stays `0x60`.
151    Delegate = 0x5B,
152    /// `FreshRequestId ra` → `r[a] =` next per-flow correlation id (`Int`).
153    ///
154    /// Starts at 1; `0` is reserved as “unset” so `Send` / `Ask` can mint.
155    /// Not a capability — uniqueness, not unpredictability.
156    /// Append-only ABI slot (`0x5C`); `Trap` stays `0x60`.
157    FreshRequestId = 0x5C,
158    /// `ReceiveMatchCorr ra, rb, rc` → wait for a hop with
159    /// `tag == r[b]` and `request_id == r[c]`. Non-matching hops stay queued.
160    /// Append-only ABI slot (`0x5D`); `Trap` stays `0x60`.
161    ReceiveMatchCorr = 0x5D,
162    /// `ReceiveMatchCorrImm ra, rb, imm` → like [`Self::ReceiveMatchCorr`]
163    /// with immediate tag (`imm` as `u16`) and `request_id` from `r[b]`.
164    /// Append-only ABI slot (`0x5E`); `Trap` stays `0x60`.
165    ReceiveMatchCorrImm = 0x5E,
166    /// `SetTrapExit ra` → BEAM `process_flag(trap_exit, r[a])`.
167    ///
168    /// Truthy `r[a]` (same rules as [`Opcode::Branch`]) enables trapping:
169    /// this flow receives [`crate::TAG_SYS_EXIT`] when a linked peer exits
170    /// (including `Normal`), instead of being killed / silently dropping the
171    /// link.
172    /// Append-only ABI slot (`0x5F`); `Trap` stays `0x60`.
173    SetTrapExit = 0x5F,
174    /// `RegisterName ra` → publish `r[a]` (`Str`) as this flow's name.
175    /// Only the calling flow is registered. Requires `SEND` on self-authority
176    /// (confined spawn cannot squat names). Append-only (`0x62`).
177    RegisterName = 0x62,
178    /// `Whereis ra, rb` → look up `r[b]` (`Str`); write a **SEND** Cap for
179    /// the caller, or `Unit` if missing. Never a raw FlowId. (`0x63`)
180    Whereis = 0x63,
181    /// `ReceiveMatchKind ra, imm` → block until a [`crate::Value::Message`]
182    /// whose `payload.wire_tag() == imm` (BFV0 tag `0..=10`) is available.
183    /// Non-matching hops stay queued (FIFO skip). Append-only (`0x64`);
184    /// `Trap` stays `0x60`.
185    ReceiveMatchKind = 0x64,
186    /// `SetRestartPolicy imm` → set this flow's supervisor restart policy:
187    /// `0` = Always, `1` = OnFailure, `2` = Never. Invalid `imm` → Trap.
188    /// Append-only (`0x65`); `Trap` stays `0x60`.
189    SetRestartPolicy = 0x65,
190    /// `HostAwait ra, rb, imm` → register a host operation `(op=imm, args=r[b])`
191    /// and write its ticket id (`Int`) into `r[a]`. The flow keeps running.
192    /// The host completes with a [`crate::TAG_SYS_AWAIT`] hop (`request_id`
193    /// = ticket) that bytecode reads with `Receive`. Requires a bridge on
194    /// [`crate::RuntimeConfig`]; otherwise the flow fails.
195    /// Append-only (`0x66`); not a `CallNative` / std-native slot.
196    HostAwait = 0x66,
197    /// `ReceiveMatchTimeout ra, rb, rc` → like [`Self::ReceiveMatch`] but
198    /// give up after `r[c]` milliseconds and write `Value::Unit` (BEAM
199    /// `receive … after`). Non-matching hops stay queued. Append-only (`0x67`).
200    ReceiveMatchTimeout = 0x67,
201    /// `ReceiveMatchImmTimeout ra, rb, imm` → like [`Self::ReceiveMatchImm`]
202    /// with timeout register `r[b]` (imm = tag). Writes `Unit` on expiry.
203    /// Append-only (`0x68`).
204    ReceiveMatchImmTimeout = 0x68,
205    /// `IsAlive ra, rb` → `r[a] = Bool`: the Cap in `r[b]` is held by this
206    /// flow and still names a live flow (BEAM `is_process_alive/1`).
207    /// Unknown / not-held / revoked / non-flow target → `false` (no trap).
208    /// Append-only (`0x69`).
209    IsAlive = 0x69,
210    /// `ExitSignal ra, rb` → BEAM `exit/2`: signal the flow addressed by
211    /// Cap `r[a]` (needs `LINK`) with reason `r[b]` (`FlowExitReason` as `Int`).
212    /// `Normal` is ignored. `Killed` cannot be trapped. Other reasons become
213    /// a [`crate::TAG_SYS_EXIT`] hop when the target has `trap_exit`.
214    /// Append-only (`0x6A`).
215    ExitSignal = 0x6A,
216    /// `DictPut ra, rb, rc` → process dictionary: `r[a] = old`, key `r[b]`
217    /// (`Int`), value `r[c]` (scalar, `Str`, or `Bytes`). `Str` / `Bytes`
218    /// are charged on the flow quota for as long as the dictionary holds
219    /// them. Missing old → `Unit`. Append-only (`0x6B`).
220    DictPut = 0x6B,
221    /// `DictGet ra, rb` → `r[a] = dict[r[b]]` or `Unit`. Append-only (`0x6C`).
222    DictGet = 0x6C,
223    /// `DictErase ra, rb` → remove key `r[b]`, write the old value or `Unit`
224    /// into `r[a]`. Append-only (`0x6D`).
225    DictErase = 0x6D,
226    /// `ReceiveMatchEq ra, rb, rc` → selective receive: `tag == r[b]` and
227    /// payload `Int == r[c]`. Non-matching hops stay queued. Append-only (`0x6E`).
228    ReceiveMatchEq = 0x6E,
229    /// `StartChild ra, policy, fn` → spawn function `imm` as a supervised
230    /// child (`b` = restart policy `0..=2`). Writes an addressing Cap into
231    /// `r[a]`. Attaches to the supervisor this flow started with
232    /// [`Self::StartSupervisor`], otherwise to the host supervisor that
233    /// started this flow. With neither, the flow fails. Append-only (`0x6F`).
234    StartChild = 0x6F,
235    /// `ReceiveMatchValue ra, rb, rc` → selective receive: `tag == r[b]` and
236    /// payload structurally equal to `r[c]` (any [`crate::Value`], not only
237    /// `Int`). Non-matching hops stay queued. Append-only (`0x70`).
238    ReceiveMatchValue = 0x70,
239    /// `SendRemote ra, rb, rc` → deliver hop `r[c]` to node `r[a]` (`Int`)
240    /// service `r[b]` (`Str`). The host drains [`crate::DistributionBridge`].
241    /// Byteflow does not open a socket. Append-only (`0x71`).
242    SendRemote = 0x71,
243    /// `StartSupervisor imm` → start a supervisor owned by this flow.
244    /// `imm`: `0` one-for-one, `1` one-for-all, `2` rest-for-one.
245    /// Later `StartChild` attaches to it. Append-only (`0x72`).
246    StartSupervisor = 0x72,
247    /// `AddImm ra, rb, imm` → `r[a] = r[b] + imm` (`imm` sign-extended to
248    /// `i64`). Integer add wraps; a float in `r[b]` adds in `f64`. One
249    /// instruction instead of `LoadImm` plus `Add`, and no scratch register.
250    /// Append-only (`0x73`).
251    AddImm = 0x73,
252    /// `CallNativeFrom ra, rb, native` → `r[a] = native_1(r[b])`.
253    ///
254    /// Same FFI slot as [`Self::CallNative`] (`imm` is the native index) but
255    /// the argument is `r[b]` and the result lands in `r[a]`. `r[b]` survives
256    /// when `a != b`, so unpacking a `Message` does not need a preceding
257    /// `Move`. Append-only (`0x74`).
258    CallNativeFrom = 0x74,
259    /// `SubImm ra, rb, imm` → `r[a] = r[b] - imm` (`imm` sign-extended to
260    /// `i64`). Integer subtraction wraps; a float in `r[b]` subtracts in
261    /// `f64`. Append-only (`0x75`).
262    SubImm = 0x75,
263    /// `LtImm ra, rb, imm` → `r[a] = r[b] < imm` as `Bool`. Integers compare
264    /// as signed `i64`. Floats compare as `f64` (NaN is not less). `Bool`
265    /// is not a number here. Append-only (`0x76`).
266    LtImm = 0x76,
267    /// `ListPack ra, rb, imm` → `r[a]` becomes a list of `imm` values
268    /// starting at `r[b]`. `imm` is `0..=256`. Append-only (`0x77`).
269    ListPack = 0x77,
270    /// `ListGet ra, rb, imm` → `r[a] = r[b][imm]`. `r[b]` must be a list
271    /// and `imm` a valid index. Append-only (`0x78`).
272    ListGet = 0x78,
273    /// `ListLen ra, rb` → `r[a] = len(r[b])` as `Int`. Append-only (`0x79`).
274    ListLen = 0x79,
275    /// `MulImm ra, rb, imm` → `r[a] = r[b] * imm` (`imm` sign-extended to
276    /// `i64`). Integer multiply wraps; a float in `r[b]` multiplies in
277    /// `f64`. Append-only (`0x7A`).
278    MulImm = 0x7A,
279    /// `EqImm ra, rb, imm` → `r[a] = Bool(r[b] == Int(imm))`.
280    ///
281    /// The immediate is an integer. A float, bool, or string in `r[b]`
282    /// compares unequal, the same as [`Self::Eq`] against a `LoadImm`.
283    /// Append-only (`0x7B`).
284    EqImm = 0x7B,
285    /// `LeImm ra, rb, imm` → `r[a] = r[b] <= imm` as `Bool`. Integers
286    /// compare as signed `i64`. Floats compare as `f64` (NaN is not less
287    /// or equal). `Bool` is not a number here. Append-only (`0x7C`).
288    LeImm = 0x7C,
289    /// `BitAnd ra, rb, rc` → `r[a] = r[b] & r[c]`. Both operands must be
290    /// `Int`. Append-only (`0x7D`).
291    BitAnd = 0x7D,
292    /// `BitOr ra, rb, rc` → `r[a] = r[b] | r[c]`. Both operands must be
293    /// `Int`. Append-only (`0x7E`).
294    BitOr = 0x7E,
295    /// `BitXor ra, rb, rc` → `r[a] = r[b] ^ r[c]`. Both operands must be
296    /// `Int`. Append-only (`0x7F`).
297    BitXor = 0x7F,
298    /// `BitNot ra, rb` → `r[a] = !r[b]`. `r[b]` must be `Int`.
299    /// Append-only (`0x80`).
300    BitNot = 0x80,
301    /// `Shl ra, rb, rc` → `r[a] = r[b] << (r[c] & 63)`. Both operands must
302    /// be `Int`. The shift count keeps its low 6 bits, so a negative count
303    /// still names a shift in `0..64`. Append-only (`0x81`).
304    Shl = 0x81,
305    /// `Shr ra, rb, rc` → arithmetic `r[a] = r[b] >> (r[c] & 63)`. Both
306    /// operands must be `Int`. The sign bit fills the vacated bits.
307    /// Append-only (`0x82`).
308    Shr = 0x82,
309    /// `ReceiveMatchCmp ra, rb, rc, imm` → wait for tag `r[b]` and an `Int`
310    /// payload compared with `r[c]` by `imm` (`0` eq, `1` lt, `2` le).
311    /// A hop that fails the comparison stays queued. Append-only (`0x83`).
312    ReceiveMatchCmp = 0x83,
313    /// `MapPack ra, rb, imm` → `r[a]` becomes a map of `imm` pairs starting
314    /// at `r[b]` (`key`, `value`, `key`, `value`, …). `imm` is `0..=256`.
315    /// Keys are `Int` or `Str`. A duplicate key traps. Append-only (`0x84`).
316    MapPack = 0x84,
317    /// `MapGet ra, rb, rc` → `r[a] = r[b][r[c]]`. Missing key writes `Unit`.
318    /// Append-only (`0x85`).
319    MapGet = 0x85,
320    /// `MapLen ra, rb` → `r[a] = len(r[b])` as `Int`. Append-only (`0x86`).
321    MapLen = 0x86,
322    /// `TableOpen ra, rb` → this flow's table, named by the `Str` in `r[b]`.
323    /// Writes a Cap (`SEND|RECV`, target = that table) into `r[a]`.
324    /// A second open traps. Append-only (`0x87`).
325    TableOpen = 0x87,
326    /// `TableGet ra, rb, rc` → `r[a]` is the row of cap `r[b]` at key `r[c]`.
327    /// Requires `RECV`. Missing key writes `Unit`. Append-only (`0x88`).
328    TableGet = 0x88,
329    /// `TablePut ra, rb, rc` → store `r[c]` in cap `r[a]` at key `r[b]`.
330    /// Requires `SEND`. Append-only (`0x89`).
331    TablePut = 0x89,
332    /// `RecordPack ra, rb, imm` → `r[a]` becomes a positional record of
333    /// `imm` fields starting at `r[b]`. `imm` is `0..=256`. Append-only (`0x8A`).
334    RecordPack = 0x8A,
335    /// `RecordGet ra, rb, imm` → `r[a] = r[b][imm]`. `r[b]` must be a record.
336    /// Append-only (`0x8B`).
337    RecordGet = 0x8B,
338    /// `RecordLen ra, rb` → `r[a] = len(r[b])` as `Int`. Append-only (`0x8C`).
339    RecordLen = 0x8C,
340    /// `Ne ra, rb, rc` → `r[a] = Bool(r[b] != r[c])`. Append-only (`0x8D`).
341    Ne = 0x8D,
342    /// `Gt ra, rb, rc` → `r[a] = Bool(r[b] > r[c])`. Append-only (`0x8E`).
343    Gt = 0x8E,
344    /// `Ge ra, rb, rc` → `r[a] = Bool(r[b] >= r[c])`. Append-only (`0x8F`).
345    Ge = 0x8F,
346    /// `NeImm ra, rb, imm` → `r[a] = Bool(r[b] != Int(imm))`. Append-only (`0x90`).
347    NeImm = 0x90,
348    /// `GtImm ra, rb, imm` → `r[a] = Bool(r[b] > imm)`. Append-only (`0x91`).
349    GtImm = 0x91,
350    /// `GeImm ra, rb, imm` → `r[a] = Bool(r[b] >= imm)`. Append-only (`0x92`).
351    GeImm = 0x92,
352    /// `Ushr ra, rb, rc` → logical `r[a] = (r[b] as u64) >> (r[c] & 63)`. Both operands `Int`. Append-only (`0x93`).
353    Ushr = 0x93,
354    /// `BranchTrue ra, imm` → jump by `imm` iff `r[a]` is truthy. Append-only (`0x94`).
355    BranchTrue = 0x94,
356    /// `StrLen ra, rb` → `r[a] = len(r[b])` as `Int`. Append-only (`0x95`).
357    StrLen = 0x95,
358    /// `BytesLen ra, rb` → `r[a] = len(r[b])` as `Int`. Append-only (`0x96`).
359    BytesLen = 0x96,
360    /// `TailCall ra, fb, nc` → tail-recursive call replacing current frame. Append-only (`0x97`).
361    TailCall = 0x97,
362
363    // ---- diagnostics / safety ------------------------------------------
364    /// `Trap imm` → deliberate fault (assertion failure, div-by-zero, bad
365    /// opcode encountered by a corrupt/foreign module, capability
366    /// violation). Propagates to the Flow supervisor as [`crate::FlowOutcome::Failed`].
367    Trap = 0x60,
368    /// `Nop` → no-op, used by the assembler to pad jump targets.
369    Nop = 0x61,
370}
371
372impl Opcode {
373    /// Decode a raw byte into an `Opcode`, used when loading foreign/untrusted
374    /// modules. Rejects anything outside the currently defined ISA rather
375    /// than transmuting garbage into a jump-table index (which is exactly
376    /// the class of bug that turns a VM into a code-execution primitive).
377    #[inline]
378    pub fn from_u8(byte: u8) -> Option<Opcode> {
379        use Opcode::*;
380        Some(match byte {
381            0x00 => Halt,
382            0x01 => LoadConst,
383            0x02 => Move,
384            0x03 => LoadImm,
385            0x10 => Add,
386            0x11 => Sub,
387            0x12 => Mul,
388            0x13 => Div,
389            0x14 => Mod,
390            0x15 => Neg,
391            0x18 => Eq,
392            0x19 => Lt,
393            0x1A => Le,
394            0x20 => Jump,
395            0x21 => Branch,
396            0x30 => Call,
397            0x31 => Return,
398            0x32 => CallNative,
399            0x40 => Spawn,
400            0x41 => Yield,
401            0x42 => Sleep,
402            0x43 => Exit,
403            0x44 => SelfPid,
404            0x50 => Send,
405            0x51 => Receive,
406            0x52 => ReceiveTimeout,
407            0x53 => ReceiveMatch,
408            0x54 => ReceiveMatchImm,
409            0x55 => Ask,
410            0x56 => Monitor,
411            0x57 => Demonitor,
412            0x58 => Link,
413            0x59 => Unlink,
414            0x5A => AskTimeout,
415            0x5B => Delegate,
416            0x5C => FreshRequestId,
417            0x5D => ReceiveMatchCorr,
418            0x5E => ReceiveMatchCorrImm,
419            0x5F => SetTrapExit,
420            0x60 => Trap,
421            0x61 => Nop,
422            0x62 => RegisterName,
423            0x63 => Whereis,
424            0x64 => ReceiveMatchKind,
425            0x65 => SetRestartPolicy,
426            0x66 => HostAwait,
427            0x67 => ReceiveMatchTimeout,
428            0x68 => ReceiveMatchImmTimeout,
429            0x69 => IsAlive,
430            0x6A => ExitSignal,
431            0x6B => DictPut,
432            0x6C => DictGet,
433            0x6D => DictErase,
434            0x6E => ReceiveMatchEq,
435            0x6F => StartChild,
436            0x70 => ReceiveMatchValue,
437            0x71 => SendRemote,
438            0x72 => StartSupervisor,
439            0x73 => AddImm,
440            0x74 => CallNativeFrom,
441            0x75 => SubImm,
442            0x76 => LtImm,
443            0x77 => ListPack,
444            0x78 => ListGet,
445            0x79 => ListLen,
446            0x7A => MulImm,
447            0x7B => EqImm,
448            0x7C => LeImm,
449            0x7D => BitAnd,
450            0x7E => BitOr,
451            0x7F => BitXor,
452            0x80 => BitNot,
453            0x81 => Shl,
454            0x82 => Shr,
455            0x83 => ReceiveMatchCmp,
456            0x84 => MapPack,
457            0x85 => MapGet,
458            0x86 => MapLen,
459            0x87 => TableOpen,
460            0x88 => TableGet,
461            0x89 => TablePut,
462            0x8A => RecordPack,
463            0x8B => RecordGet,
464            0x8C => RecordLen,
465            0x8D => Ne,
466            0x8E => Gt,
467            0x8F => Ge,
468            0x90 => NeImm,
469            0x91 => GtImm,
470            0x92 => GeImm,
471            0x93 => Ushr,
472            0x94 => BranchTrue,
473            0x95 => StrLen,
474            0x96 => BytesLen,
475            0x97 => TailCall,
476            _ => return None,
477        })
478    }
479
480    #[inline]
481    pub fn as_u8(self) -> u8 {
482        self as u8
483    }
484}
485
486impl std::fmt::Display for Opcode {
487    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
488        let name = match self {
489            Opcode::Halt => "Halt",
490            Opcode::LoadConst => "LoadConst",
491            Opcode::Move => "Move",
492            Opcode::LoadImm => "LoadImm",
493            Opcode::Add => "Add",
494            Opcode::AddImm => "AddImm",
495            Opcode::SubImm => "SubImm",
496            Opcode::LtImm => "LtImm",
497            Opcode::ListPack => "ListPack",
498            Opcode::ListGet => "ListGet",
499            Opcode::ListLen => "ListLen",
500            Opcode::MulImm => "MulImm",
501            Opcode::EqImm => "EqImm",
502            Opcode::LeImm => "LeImm",
503            Opcode::BitAnd => "BitAnd",
504            Opcode::BitOr => "BitOr",
505            Opcode::BitXor => "BitXor",
506            Opcode::BitNot => "BitNot",
507            Opcode::Shl => "Shl",
508            Opcode::Shr => "Shr",
509            Opcode::ReceiveMatchCmp => "ReceiveMatchCmp",
510            Opcode::MapPack => "MapPack",
511            Opcode::MapGet => "MapGet",
512            Opcode::MapLen => "MapLen",
513            Opcode::TableOpen => "TableOpen",
514            Opcode::TableGet => "TableGet",
515            Opcode::TablePut => "TablePut",
516            Opcode::RecordPack => "RecordPack",
517            Opcode::RecordGet => "RecordGet",
518            Opcode::RecordLen => "RecordLen",
519            Opcode::Ne => "Ne",
520            Opcode::Gt => "Gt",
521            Opcode::Ge => "Ge",
522            Opcode::NeImm => "NeImm",
523            Opcode::GtImm => "GtImm",
524            Opcode::GeImm => "GeImm",
525            Opcode::Ushr => "Ushr",
526            Opcode::BranchTrue => "BranchTrue",
527            Opcode::StrLen => "StrLen",
528            Opcode::BytesLen => "BytesLen",
529            Opcode::TailCall => "TailCall",
530            Opcode::Sub => "Sub",
531            Opcode::Mul => "Mul",
532            Opcode::Div => "Div",
533            Opcode::Mod => "Mod",
534            Opcode::Neg => "Neg",
535            Opcode::Eq => "Eq",
536            Opcode::Lt => "Lt",
537            Opcode::Le => "Le",
538            Opcode::Jump => "Jump",
539            Opcode::Branch => "Branch",
540            Opcode::Call => "Call",
541            Opcode::Return => "Return",
542            Opcode::CallNative => "CallNative",
543            Opcode::CallNativeFrom => "CallNativeFrom",
544            Opcode::Spawn => "Spawn",
545            Opcode::Yield => "Yield",
546            Opcode::Sleep => "Sleep",
547            Opcode::Exit => "Exit",
548            Opcode::SelfPid => "SelfPid",
549            Opcode::Send => "Send",
550            Opcode::Receive => "Receive",
551            Opcode::ReceiveTimeout => "ReceiveTimeout",
552            Opcode::ReceiveMatch => "ReceiveMatch",
553            Opcode::ReceiveMatchImm => "ReceiveMatchImm",
554            Opcode::Ask => "Ask",
555            Opcode::Monitor => "Monitor",
556            Opcode::Demonitor => "Demonitor",
557            Opcode::Link => "Link",
558            Opcode::Unlink => "Unlink",
559            Opcode::AskTimeout => "AskTimeout",
560            Opcode::Delegate => "Delegate",
561            Opcode::FreshRequestId => "FreshRequestId",
562            Opcode::ReceiveMatchCorr => "ReceiveMatchCorr",
563            Opcode::ReceiveMatchCorrImm => "ReceiveMatchCorrImm",
564            Opcode::SetTrapExit => "SetTrapExit",
565            Opcode::RegisterName => "RegisterName",
566            Opcode::Whereis => "Whereis",
567            Opcode::ReceiveMatchKind => "ReceiveMatchKind",
568            Opcode::SetRestartPolicy => "SetRestartPolicy",
569            Opcode::HostAwait => "HostAwait",
570            Opcode::ReceiveMatchTimeout => "ReceiveMatchTimeout",
571            Opcode::ReceiveMatchImmTimeout => "ReceiveMatchImmTimeout",
572            Opcode::IsAlive => "IsAlive",
573            Opcode::ExitSignal => "ExitSignal",
574            Opcode::DictPut => "DictPut",
575            Opcode::DictGet => "DictGet",
576            Opcode::DictErase => "DictErase",
577            Opcode::ReceiveMatchEq => "ReceiveMatchEq",
578            Opcode::StartChild => "StartChild",
579            Opcode::ReceiveMatchValue => "ReceiveMatchValue",
580            Opcode::SendRemote => "SendRemote",
581            Opcode::StartSupervisor => "StartSupervisor",
582            Opcode::Trap => "Trap",
583            Opcode::Nop => "Nop",
584        };
585        f.write_str(name)
586    }
587}
588
589/// Integer comparison used by [`Opcode::ReceiveMatchCmp`].
590#[derive(Clone, Copy, Debug, PartialEq, Eq)]
591pub enum IntCmp {
592    Eq,
593    Lt,
594    Le,
595}
596
597impl IntCmp {
598    pub const fn from_imm(imm: i32) -> Option<Self> {
599        match imm {
600            0 => Some(Self::Eq),
601            1 => Some(Self::Lt),
602            2 => Some(Self::Le),
603            _ => None,
604        }
605    }
606
607    pub const fn as_imm(self) -> i32 {
608        match self {
609            Self::Eq => 0,
610            Self::Lt => 1,
611            Self::Le => 2,
612        }
613    }
614
615    pub fn holds(self, payload: i64, bound: i64) -> bool {
616        match self {
617            Self::Eq => payload == bound,
618            Self::Lt => payload < bound,
619            Self::Le => payload <= bound,
620        }
621    }
622}