vibe/bytecode/op.rs
1//! VibeScript bytecode opcodes (`vibe-bc-0.1`).
2//!
3//! Stack-based bytecode for the VibeScript 0.1 language. Each opcode is a
4//! single byte, optionally followed by operand bytes. The VM is a simple
5//! stack machine: expressions push values onto the stack, statements
6//! consume them.
7//!
8//! ## Encoding
9//!
10//! ```text
11//! ┌─────────────────────────────────────────────────────────────┐
12//! │ Chunk │
13//! │ ┌──────────┬──────────────┬───────────────────────────────┐ │
14//! │ │ magic │ version │ constants + code + functions │ │
15//! │ │ 4 bytes │ 2 bytes │ ... │ │
16//! │ └──────────┴──────────────┴───────────────────────────────┘ │
17//! └─────────────────────────────────────────────────────────────┘
18//! ```
19//!
20//! ## Opcode table
21//!
22//! | Opcode | Hex | Operand | Stack effect |
23//! |-----------------|------|------------------|----------------------|
24//! | `PUSH_NULL` | 0x00 | — | → null |
25//! | `PUSH_BOOL` | 0x01 | u8 (0 or 1) | → bool |
26//! | `PUSH_INT` | 0x02 | i64 LE | → i64 |
27//! | `PUSH_UINT` | 0x03 | u64 LE | → u64 |
28//! | `PUSH_FLOAT` | 0x04 | f64 LE bits | → f64 |
29//! | `PUSH_STRING` | 0x05 | u16 const_idx | → string |
30//! | `PUSH_IRI` | 0x06 | u16 const_idx | → iri |
31//! | `LOAD_VAR` | 0x07 | u16 slot | → value |
32//! | `STORE_VAR` | 0x08 | u16 slot | value → |
33//! | `POP` | 0x09 | — | value → |
34//! | `DUP` | 0x0A | — | value → value value |
35//! | `ADD` | 0x10 | — | a b → a+b |
36//! | `SUB` | 0x11 | — | a b → a-b |
37//! | `MUL` | 0x12 | — | a b → a*b |
38//! | `DIV` | 0x13 | — | a b → a/b |
39//! | `REM` | 0x14 | — | a b → a%b |
40//! | `NEG` | 0x15 | — | a → -a |
41//! | `NOT` | 0x16 | — | a → !a |
42//! | `EQ` | 0x17 | — | a b → a==b |
43//! | `NE` | 0x18 | — | a b → a!=b |
44//! | `LT` | 0x19 | — | a b → a<b |
45//! | `LE` | 0x1A | — | a b → a<=b |
46//! | `GT` | 0x1B | — | a b → a>b |
47//! | `GE` | 0x1C | — | a b → a>=b |
48//! | `AND` | 0x1D | — | a b → a&&b |
49//! | `OR` | 0x1E | — | a b → a||b |
50//! | `JUMP` | 0x20 | u16 offset | — |
51//! | `JUMP_IF_FALSE` | 0x21 | u16 offset | bool → |
52//! | `JUMP_IF_TRUE` | 0x22 | u16 offset | bool → |
53//! | `CALL_FN` | 0x30 | u16 fn_idx | args... → result |
54//! | `CALL_HOST` | 0x31 | u16 path_idx u8 | args... → result |
55//! | `CALL_USER` | 0x32 | u16 fn_idx u8 | args... → result |
56//! | `RETURN` | 0x33 | — | value → (return) |
57//! | `MAKE_LIST` | 0x40 | u16 count | values... → list |
58//! | `MAKE_RECORD` | 0x41 | u16 count | kv... → record |
59//! | `GET_MEMBER` | 0x42 | u16 name_idx | record → value |
60//! | `GET_INDEX` | 0x43 | — | list index → value |
61//! | `TRY` | 0x44 | u16 catch_off | value → unwrapped |
62//! | `EFFECT` | 0x45 | — | value → |
63//! | `HALT` | 0xFF | — | — |
64
65/// Magic bytes identifying a `vibe-bc-0.1` chunk.
66pub const MAGIC: [u8; 4] = *b"VBC1";
67
68/// Bytecode format version.
69pub const VERSION: u16 = 1;
70
71/// Maximum number of constants in a chunk.
72pub const MAX_CONSTANTS: usize = 65535;
73
74/// Maximum number of local variable slots.
75pub const MAX_LOCALS: usize = 65535;
76
77/// Maximum number of user-defined functions.
78pub const MAX_FUNCTIONS: usize = 65535;
79
80/// Maximum code size in bytes.
81pub const MAX_CODE: usize = 65535;
82
83/// A single bytecode opcode.
84#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
85#[repr(u8)]
86pub enum Op {
87 /// Push `null` onto the stack.
88 PushNull = 0x00,
89 /// Push a boolean. Operand: 1 byte (0 = false, 1 = true).
90 PushBool = 0x01,
91 /// Push an i64. Operand: 8 bytes little-endian.
92 PushInt = 0x02,
93 /// Push a u64. Operand: 8 bytes little-endian.
94 PushUInt = 0x03,
95 /// Push an f64. Operand: 8 bytes (f64 bits, little-endian).
96 PushFloat = 0x04,
97 /// Push a string from the constant pool. Operand: u16 const index.
98 PushString = 0x05,
99 /// Push an IRI from the constant pool. Operand: u16 const index.
100 PushIri = 0x06,
101 /// Load a local variable. Operand: u16 slot index.
102 LoadVar = 0x07,
103 /// Store top of stack to a local variable. Operand: u16 slot index.
104 StoreVar = 0x08,
105 /// Pop and discard the top of stack.
106 Pop = 0x09,
107 /// Duplicate the top of stack.
108 Dup = 0x0A,
109 /// Push a quantity: f64 bits (8) then u16 constant-pool unit string.
110 PushQuantity = 0x0B,
111
112 // ── Arithmetic ──────────────────────────────────────────────
113 Add = 0x10,
114 Sub = 0x11,
115 Mul = 0x12,
116 Div = 0x13,
117 Rem = 0x14,
118 Neg = 0x15,
119 Not = 0x16,
120
121 // ── Comparison ──────────────────────────────────────────────
122 Eq = 0x17,
123 Ne = 0x18,
124 Lt = 0x19,
125 Le = 0x1A,
126 Gt = 0x1B,
127 Ge = 0x1C,
128 And = 0x1D,
129 Or = 0x1E,
130
131 // ── Control flow ────────────────────────────────────────────
132 /// Unconditional jump. Operand: u16 code offset.
133 Jump = 0x20,
134 /// Jump if top of stack is falsy. Operand: u16 code offset. Pops the condition.
135 JumpIfFalse = 0x21,
136 /// Jump if top of stack is truthy. Operand: u16 code offset. Pops the condition.
137 JumpIfTrue = 0x22,
138
139 // ── Calls ───────────────────────────────────────────────────
140 /// Call a host capability. Operands: u16 path const index, u8 arg count.
141 CallHost = 0x30,
142 /// Call a user-defined function. Operands: u16 function index, u8 arg count.
143 CallUser = 0x31,
144 /// Return from the current function. Pops the return value.
145 Return = 0x32,
146 /// Return null (void) from the current function.
147 ReturnNull = 0x33,
148 /// Call a host capability with explicit positional and named args.
149 /// Operands: u16 path const index, u8 positional count, u8 named pair count.
150 CallHostNamed = 0x34,
151
152 // ── Data structures ─────────────────────────────────────────
153 /// Create a list from N stack elements. Operand: u16 count.
154 MakeList = 0x40,
155 /// Create a record from N key-value pairs. Operand: u16 pair count.
156 /// Keys are string constants (u16 const index pushed before each value).
157 MakeRecord = 0x41,
158 /// Get a named member from a record. Operand: u16 name const index.
159 GetMember = 0x42,
160 /// Get an indexed element from a list. Pops index then list.
161 GetIndex = 0x43,
162 /// Unwrap a Try (Ok → value, Err → catch or diagnostic). Operand: u16 catch offset.
163 TryUnwrap = 0x44,
164 /// Execute an effect expression (pop and discard, for side effects).
165 Effect = 0x45,
166 /// Pop top of stack, push Bool indicating whether it is `Value::Ok(_)`.
167 IsOk = 0x46,
168 /// Pop `Value::Ok(inner)` and push `*inner`.
169 UnwrapOk = 0x47,
170 /// Pop top of stack, push Bool indicating whether it is `Value::Err(_)`.
171 IsErr = 0x48,
172 /// Pop `Value::Err(inner)` and push `*inner`.
173 UnwrapErr = 0x49,
174 /// Pop top of stack, push Bool matching enum/variant/arity.
175 /// Operands: u16 enum name const, u16 variant name const, u8 field count.
176 IsVariant = 0x4A,
177 /// Pop `Value::Enum(e)` and push `e.payload[idx]`. Operand: u8 field index.
178 GetVariantField = 0x4B,
179 /// Pop top of stack, push Bool indicating `Value::Record(_)`.
180 IsRecord = 0x4C,
181 /// Pop `Value::Record(r)` and push Bool indicating `r.contains_key(name)`. Operand: u16 key const.
182 HasMember = 0x4D,
183 /// Pop top of stack, push Bool indicating `Value::List(xs)` of length `len`. Operand: u16 len.
184 IsListLen = 0x4E,
185 /// Fail execution with a destructuring pattern mismatch diagnostic.
186 TrapMatch = 0x4F,
187 /// Construct a `Value::Enum` from N stack payload args.
188 /// Operands: u16 enum name const, u16 variant name const, u8 arg count.
189 MakeVariant = 0x50,
190 /// Pop value, push `Value::Ok(Box::new(v))`.
191 MakeOk = 0x51,
192 /// Pop value, push `Value::Err(Box::new(v))`.
193 MakeErr = 0x52,
194
195 // ── Special ─────────────────────────────────────────────────
196 /// Halt execution (end of code segment).
197 Halt = 0xFF,
198}
199
200impl Op {
201 /// Decode an opcode from a byte.
202 pub fn from_byte(b: u8) -> Option<Self> {
203 Some(match b {
204 0x00 => Self::PushNull,
205 0x01 => Self::PushBool,
206 0x02 => Self::PushInt,
207 0x03 => Self::PushUInt,
208 0x04 => Self::PushFloat,
209 0x05 => Self::PushString,
210 0x06 => Self::PushIri,
211 0x07 => Self::LoadVar,
212 0x08 => Self::StoreVar,
213 0x09 => Self::Pop,
214 0x0A => Self::Dup,
215 0x0B => Self::PushQuantity,
216 0x10 => Self::Add,
217 0x11 => Self::Sub,
218 0x12 => Self::Mul,
219 0x13 => Self::Div,
220 0x14 => Self::Rem,
221 0x15 => Self::Neg,
222 0x16 => Self::Not,
223 0x17 => Self::Eq,
224 0x18 => Self::Ne,
225 0x19 => Self::Lt,
226 0x1A => Self::Le,
227 0x1B => Self::Gt,
228 0x1C => Self::Ge,
229 0x1D => Self::And,
230 0x1E => Self::Or,
231 0x20 => Self::Jump,
232 0x21 => Self::JumpIfFalse,
233 0x22 => Self::JumpIfTrue,
234 0x30 => Self::CallHost,
235 0x31 => Self::CallUser,
236 0x32 => Self::Return,
237 0x33 => Self::ReturnNull,
238 0x34 => Self::CallHostNamed,
239 0x40 => Self::MakeList,
240 0x41 => Self::MakeRecord,
241 0x42 => Self::GetMember,
242 0x43 => Self::GetIndex,
243 0x44 => Self::TryUnwrap,
244 0x45 => Self::Effect,
245 0x46 => Self::IsOk,
246 0x47 => Self::UnwrapOk,
247 0x48 => Self::IsErr,
248 0x49 => Self::UnwrapErr,
249 0x4A => Self::IsVariant,
250 0x4B => Self::GetVariantField,
251 0x4C => Self::IsRecord,
252 0x4D => Self::HasMember,
253 0x4E => Self::IsListLen,
254 0x4F => Self::TrapMatch,
255 0x50 => Self::MakeVariant,
256 0x51 => Self::MakeOk,
257 0x52 => Self::MakeErr,
258 0xFF => Self::Halt,
259 _ => return None,
260 })
261 }
262
263 /// Number of operand bytes following this opcode (not counting the opcode itself).
264 pub fn operand_size(self) -> usize {
265 match self {
266 Self::PushNull
267 | Self::Pop
268 | Self::Dup
269 | Self::Add
270 | Self::Sub
271 | Self::Mul
272 | Self::Div
273 | Self::Rem
274 | Self::Neg
275 | Self::Not
276 | Self::Eq
277 | Self::Ne
278 | Self::Lt
279 | Self::Le
280 | Self::Gt
281 | Self::Ge
282 | Self::And
283 | Self::Or
284 | Self::Return
285 | Self::ReturnNull
286 | Self::GetIndex
287 | Self::Effect
288 | Self::IsOk
289 | Self::UnwrapOk
290 | Self::IsErr
291 | Self::UnwrapErr
292 | Self::IsRecord
293 | Self::TrapMatch
294 | Self::MakeOk
295 | Self::MakeErr
296 | Self::Halt => 0,
297 Self::PushBool | Self::GetVariantField => 1,
298 Self::PushInt | Self::PushUInt | Self::PushFloat => 8,
299 Self::PushQuantity => 10,
300 Self::PushString
301 | Self::PushIri
302 | Self::LoadVar
303 | Self::StoreVar
304 | Self::Jump
305 | Self::JumpIfFalse
306 | Self::JumpIfTrue
307 | Self::MakeList
308 | Self::MakeRecord
309 | Self::GetMember
310 | Self::TryUnwrap
311 | Self::HasMember
312 | Self::IsListLen => 2,
313 Self::CallHost | Self::CallUser => 3, // u16 path/function + u8 argc
314 Self::CallHostNamed => 4, // u16 path + u8 pos_argc + u8 named_pairs
315 Self::IsVariant | Self::MakeVariant => 5, // u16 enum + u16 variant + u8 argc
316 }
317 }
318}
319
320/// A constant value in the constant pool.
321#[derive(Debug, Clone, PartialEq)]
322pub enum Const {
323 String(String),
324 Iri(String),
325}
326
327/// Metadata for a compiled user-defined function.
328#[derive(Debug, Clone, PartialEq)]
329pub struct FuncMeta {
330 /// Function name (for lookup by name).
331 pub name: String,
332 /// Number of parameters.
333 pub param_count: u8,
334 /// Number of local variable slots (params + locals).
335 pub local_count: u16,
336 /// Code offset where the function body begins.
337 pub code_offset: u16,
338 /// Budget steps (0 = no budget).
339 pub budget_steps: u64,
340}
341
342/// A compiled bytecode chunk — the unit of compilation and execution.
343#[derive(Debug, Clone, PartialEq)]
344pub struct Chunk {
345 /// Constant pool (strings, IRIs).
346 pub constants: Vec<Const>,
347 /// Bytecode instructions.
348 pub code: Vec<u8>,
349 /// User-defined function metadata.
350 pub functions: Vec<FuncMeta>,
351 /// Module-level local count (for top-level execution).
352 pub top_locals: u16,
353}
354
355impl Chunk {
356 /// Create an empty chunk.
357 pub fn new() -> Self {
358 Self {
359 constants: Vec::new(),
360 code: Vec::new(),
361 functions: Vec::new(),
362 top_locals: 0,
363 }
364 }
365
366 /// Add a string constant and return its index.
367 pub fn add_string(&mut self, s: &str) -> u16 {
368 if let Some(idx) = self
369 .constants
370 .iter()
371 .position(|c| matches!(c, Const::String(x) if x == s))
372 {
373 return idx as u16;
374 }
375 let idx = self.constants.len();
376 self.constants.push(Const::String(s.to_string()));
377 idx as u16
378 }
379
380 /// Add an IRI constant and return its index.
381 pub fn add_iri(&mut self, s: &str) -> u16 {
382 if let Some(idx) = self
383 .constants
384 .iter()
385 .position(|c| matches!(c, Const::Iri(x) if x == s))
386 {
387 return idx as u16;
388 }
389 let idx = self.constants.len();
390 self.constants.push(Const::Iri(s.to_string()));
391 idx as u16
392 }
393
394 /// Find a function by name. Returns its index in `functions`.
395 pub fn find_function(&self, name: &str) -> Option<u16> {
396 self.functions
397 .iter()
398 .position(|f| f.name == name)
399 .map(|i| i as u16)
400 }
401
402 /// Current code offset (where the next instruction will be emitted).
403 pub fn current_offset(&self) -> u16 {
404 self.code.len() as u16
405 }
406
407 /// Emit a raw byte.
408 pub fn emit(&mut self, b: u8) {
409 self.code.push(b);
410 }
411
412 /// Emit an opcode.
413 pub fn emit_op(&mut self, op: Op) {
414 self.emit(op as u8);
415 }
416
417 /// Emit a u16 operand (little-endian).
418 pub fn emit_u16(&mut self, v: u16) {
419 self.code.push((v & 0xFF) as u8);
420 self.code.push((v >> 8) as u8);
421 }
422
423 /// Emit a u8 operand.
424 pub fn emit_u8(&mut self, v: u8) {
425 self.code.push(v);
426 }
427
428 /// Emit an i64 operand (little-endian).
429 pub fn emit_i64(&mut self, v: i64) {
430 self.code.extend_from_slice(&v.to_le_bytes());
431 }
432
433 /// Emit a u64 operand (little-endian).
434 pub fn emit_u64(&mut self, v: u64) {
435 self.code.extend_from_slice(&v.to_le_bytes());
436 }
437
438 /// Emit an f64 operand (little-endian bits).
439 pub fn emit_f64(&mut self, v: f64) {
440 self.code.extend_from_slice(&v.to_le_bytes());
441 }
442
443 /// Patch a u16 operand at the given code offset.
444 pub fn patch_u16(&mut self, offset: usize, value: u16) {
445 self.code[offset] = (value & 0xFF) as u8;
446 self.code[offset + 1] = (value >> 8) as u8;
447 }
448}
449
450impl Default for Chunk {
451 fn default() -> Self {
452 Self::new()
453 }
454}
455
456#[cfg(test)]
457mod tests {
458 use super::*;
459
460 #[test]
461 fn op_roundtrip() {
462 for b in 0..=255u8 {
463 if let Some(op) = Op::from_byte(b) {
464 assert_eq!(op as u8, b, "opcode roundtrip failed for 0x{b:02X}");
465 }
466 }
467 }
468
469 #[test]
470 fn chunk_add_string_dedup() {
471 let mut c = Chunk::new();
472 let a = c.add_string("hello");
473 let b = c.add_string("hello");
474 assert_eq!(a, b, "string constants should be deduplicated");
475 let d = c.add_string("world");
476 assert_ne!(a, d, "different strings should have different indices");
477 }
478
479 #[test]
480 fn chunk_emit_and_patch() {
481 let mut c = Chunk::new();
482 c.emit_op(Op::Jump);
483 let patch_off = c.code.len();
484 c.emit_u16(0); // placeholder
485 c.emit_op(Op::Halt);
486 c.patch_u16(patch_off, 42);
487 assert_eq!(c.code, vec![Op::Jump as u8, 42, 0, Op::Halt as u8]);
488 }
489
490 #[test]
491 fn chunk_find_function() {
492 let mut c = Chunk::new();
493 c.functions.push(FuncMeta {
494 name: "foo".into(),
495 param_count: 2,
496 local_count: 3,
497 code_offset: 10,
498 budget_steps: 1000,
499 });
500 assert_eq!(c.find_function("foo"), Some(0));
501 assert_eq!(c.find_function("bar"), None);
502 }
503}