Skip to main content

bvm_lang/
op.rs

1//! The instruction set executed by the VM.
2//!
3//! `bvm-lang` is a *register machine*: every instruction names the registers it
4//! reads and writes explicitly, rather than pushing and popping an operand stack.
5//! A register machine issues far fewer instructions for the same work — a
6//! three-address `Add { dst, lhs, rhs }` replaces a push/push/add/pop sequence —
7//! which means fewer dispatch iterations through the interpreter loop and better
8//! use of the CPU's branch predictor.
9//!
10//! Each [`Op`] is a fixed-size, already-decoded value: the operands are plain
11//! integer fields, so the interpreter never parses a byte stream at runtime. A
12//! program is just a `&[Op]` walked by a program counter, plus a pool of
13//! [`Value`](crate::Value) constants.
14
15/// A register index.
16///
17/// Registers are the VM's working storage. A [`Chunk`](crate::Chunk) sizes its
18/// register file to the highest index any of its instructions names, so indices
19/// are dense and start at zero. The 16-bit width allows up to 65 536 registers
20/// per chunk, far more than a single function body needs.
21pub type Reg = u16;
22
23/// A constant-pool index.
24///
25/// Constants are [`Value`](crate::Value)s too large or too varied to encode as an
26/// immediate (arbitrary floats, interned symbols). They live in the chunk's
27/// constant pool and are addressed by this index via [`Op::LoadConst`].
28pub type Const = u16;
29
30/// An instruction address within a chunk's code array.
31///
32/// Branch targets are absolute indices, not relative offsets: `Jump { target }`
33/// sets the program counter directly. Absolute targets keep back-patching during
34/// code generation trivial — the target is known once, and never shifts if
35/// earlier instructions change size (they never do).
36pub type Addr = u32;
37
38/// A single decoded instruction.
39///
40/// Instructions divide into data movement (`Move`, `Load*`), arithmetic
41/// (`Add`…`Neg`), comparison (`Eq`…`Ge`), the logical `Not`, control flow
42/// (`Jump`, `JumpIfTrue`, `JumpIfFalse`), and termination (`Return`, `Halt`).
43///
44/// Arithmetic and comparison operands are numeric: an integer combines with an
45/// integer to give an integer (with overflow checked), and any float operand
46/// promotes the result to float. Comparisons and `Not` produce booleans. See the
47/// individual variants and [the crate root](crate) for the exact semantics.
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
50#[non_exhaustive]
51pub enum Op {
52    /// Copy the value in `src` into `dst`.
53    Move {
54        /// Destination register.
55        dst: Reg,
56        /// Source register.
57        src: Reg,
58    },
59    /// Load the constant at pool position `index` into `dst`.
60    LoadConst {
61        /// Destination register.
62        dst: Reg,
63        /// Constant-pool index (see [`Chunk::constant`](crate::Chunk::constant)).
64        index: Const,
65    },
66    /// Load `nil` into `dst`.
67    LoadNil {
68        /// Destination register.
69        dst: Reg,
70    },
71    /// Load the boolean `val` into `dst`.
72    LoadBool {
73        /// Destination register.
74        dst: Reg,
75        /// Immediate boolean.
76        val: bool,
77    },
78    /// Load the 32-bit integer immediate `val` into `dst`.
79    ///
80    /// Small integers travel in the instruction itself, avoiding a constant-pool
81    /// round trip for the common case.
82    LoadInt {
83        /// Destination register.
84        dst: Reg,
85        /// Immediate integer.
86        val: i32,
87    },
88
89    /// `dst = lhs + rhs` (numeric; integer add is overflow-checked).
90    Add {
91        /// Destination register.
92        dst: Reg,
93        /// Left operand register.
94        lhs: Reg,
95        /// Right operand register.
96        rhs: Reg,
97    },
98    /// `dst = lhs - rhs` (numeric; integer subtract is overflow-checked).
99    Sub {
100        /// Destination register.
101        dst: Reg,
102        /// Left operand register.
103        lhs: Reg,
104        /// Right operand register.
105        rhs: Reg,
106    },
107    /// `dst = lhs * rhs` (numeric; integer multiply is overflow-checked).
108    Mul {
109        /// Destination register.
110        dst: Reg,
111        /// Left operand register.
112        lhs: Reg,
113        /// Right operand register.
114        rhs: Reg,
115    },
116    /// `dst = lhs / rhs` (numeric; integer divide-by-zero errors, float follows IEEE-754).
117    Div {
118        /// Destination register.
119        dst: Reg,
120        /// Left operand register.
121        lhs: Reg,
122        /// Right operand register.
123        rhs: Reg,
124    },
125    /// `dst = lhs % rhs` (numeric; integer remainder-by-zero errors).
126    Rem {
127        /// Destination register.
128        dst: Reg,
129        /// Left operand register.
130        lhs: Reg,
131        /// Right operand register.
132        rhs: Reg,
133    },
134    /// `dst = -src` (numeric; integer negation is overflow-checked).
135    Neg {
136        /// Destination register.
137        dst: Reg,
138        /// Source register.
139        src: Reg,
140    },
141
142    /// `dst = (lhs == rhs)` as a boolean. Numeric operands compare by value across
143    /// int/float; other kinds compare structurally. Floats use IEEE-754 equality.
144    Eq {
145        /// Destination register.
146        dst: Reg,
147        /// Left operand register.
148        lhs: Reg,
149        /// Right operand register.
150        rhs: Reg,
151    },
152    /// `dst = (lhs != rhs)` — the boolean negation of [`Op::Eq`].
153    Ne {
154        /// Destination register.
155        dst: Reg,
156        /// Left operand register.
157        lhs: Reg,
158        /// Right operand register.
159        rhs: Reg,
160    },
161    /// `dst = (lhs < rhs)` (numeric operands only).
162    Lt {
163        /// Destination register.
164        dst: Reg,
165        /// Left operand register.
166        lhs: Reg,
167        /// Right operand register.
168        rhs: Reg,
169    },
170    /// `dst = (lhs <= rhs)` (numeric operands only).
171    Le {
172        /// Destination register.
173        dst: Reg,
174        /// Left operand register.
175        lhs: Reg,
176        /// Right operand register.
177        rhs: Reg,
178    },
179    /// `dst = (lhs > rhs)` (numeric operands only).
180    Gt {
181        /// Destination register.
182        dst: Reg,
183        /// Left operand register.
184        lhs: Reg,
185        /// Right operand register.
186        rhs: Reg,
187    },
188    /// `dst = (lhs >= rhs)` (numeric operands only).
189    Ge {
190        /// Destination register.
191        dst: Reg,
192        /// Left operand register.
193        lhs: Reg,
194        /// Right operand register.
195        rhs: Reg,
196    },
197
198    /// `dst = !src`. `src` must be a boolean.
199    Not {
200        /// Destination register.
201        dst: Reg,
202        /// Source register.
203        src: Reg,
204    },
205
206    /// Unconditionally set the program counter to `target`.
207    Jump {
208        /// Absolute instruction address to continue from.
209        target: Addr,
210    },
211    /// Branch to `target` when `cond` holds a `true` boolean; otherwise fall
212    /// through. `cond` must be a boolean.
213    JumpIfTrue {
214        /// Condition register (must be a boolean).
215        cond: Reg,
216        /// Absolute instruction address taken when the condition is `true`.
217        target: Addr,
218    },
219    /// Branch to `target` when `cond` holds a `false` boolean; otherwise fall
220    /// through. `cond` must be a boolean.
221    JumpIfFalse {
222        /// Condition register (must be a boolean).
223        cond: Reg,
224        /// Absolute instruction address taken when the condition is `false`.
225        target: Addr,
226    },
227
228    /// Stop execution and yield the value in `src` as the run's result.
229    Return {
230        /// Register holding the value to return.
231        src: Reg,
232    },
233    /// Stop execution and yield `nil`.
234    Halt,
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240    use core::mem::size_of;
241
242    #[test]
243    fn test_op_is_compact_and_copy() {
244        // A decoded instruction must stay small enough to keep the code array
245        // cache-dense. Eight bytes is the target on 64-bit targets.
246        assert!(size_of::<Op>() <= 8, "Op grew to {} bytes", size_of::<Op>());
247        fn assert_copy<T: Copy>(_: T) {}
248        assert_copy(Op::Halt);
249    }
250}