Skip to main content

harn_vm/
chunk.rs

1use std::fmt;
2
3/// Bytecode opcodes for the Harn VM.
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5#[repr(u8)]
6pub enum Op {
7    /// Push a constant from the constant pool onto the stack.
8    Constant, // arg: u16 constant index
9    /// Push nil onto the stack.
10    Nil,
11    /// Push true onto the stack.
12    True,
13    /// Push false onto the stack.
14    False,
15
16    // --- Variable operations ---
17    /// Get a variable by name (from constant pool).
18    GetVar, // arg: u16 constant index (name)
19    /// Define a new immutable variable. Pops value from stack.
20    DefLet, // arg: u16 constant index (name)
21    /// Define a new mutable variable. Pops value from stack.
22    DefVar, // arg: u16 constant index (name)
23    /// Assign to an existing mutable variable. Pops value from stack.
24    SetVar, // arg: u16 constant index (name)
25
26    // --- Arithmetic ---
27    Add,
28    Sub,
29    Mul,
30    Div,
31    Mod,
32    Negate,
33
34    // --- Comparison ---
35    Equal,
36    NotEqual,
37    Less,
38    Greater,
39    LessEqual,
40    GreaterEqual,
41
42    // --- Logical ---
43    Not,
44
45    // --- Control flow ---
46    /// Jump unconditionally. arg: u16 offset.
47    Jump,
48    /// Jump if top of stack is falsy. Does not pop. arg: u16 offset.
49    JumpIfFalse,
50    /// Jump if top of stack is truthy. Does not pop. arg: u16 offset.
51    JumpIfTrue,
52    /// Pop top of stack (discard).
53    Pop,
54
55    // --- Functions ---
56    /// Call a function/builtin. arg: u8 = arg count. Name is on stack below args.
57    Call,
58    /// Tail call: like Call, but replaces the current frame instead of pushing
59    /// a new one. Used for `return f(x)` to enable tail call optimization.
60    /// For builtins, behaves like a regular Call (no frame to replace).
61    TailCall,
62    /// Return from current function. Pops return value.
63    Return,
64    /// Create a closure. arg: u16 = chunk index in function table.
65    Closure,
66
67    // --- Collections ---
68    /// Build a list. arg: u16 = element count. Elements are on stack.
69    BuildList,
70    /// Build a dict. arg: u16 = entry count. Key-value pairs on stack.
71    BuildDict,
72    /// Subscript access: stack has [object, index]. Pushes result.
73    Subscript,
74    /// Slice access: stack has [object, start_or_nil, end_or_nil]. Pushes sublist/substring.
75    Slice,
76
77    // --- Object operations ---
78    /// Property access. arg: u16 = constant index (property name).
79    GetProperty,
80    /// Optional property access (?.). Like GetProperty but returns nil
81    /// instead of erroring when the object is nil. arg: u16 = constant index.
82    GetPropertyOpt,
83    /// Property assignment. arg: u16 = constant index (property name).
84    /// Stack: [value] → assigns to the named variable's property.
85    SetProperty,
86    /// Subscript assignment. arg: u16 = constant index (variable name).
87    /// Stack: [index, value] → assigns to variable[index] = value.
88    SetSubscript,
89    /// Method call. arg1: u16 = constant index (method name), arg2: u8 = arg count.
90    MethodCall,
91    /// Optional method call (?.). Like MethodCall but returns nil if the
92    /// receiver is nil instead of dispatching. arg1: u16, arg2: u8.
93    MethodCallOpt,
94
95    // --- String ---
96    /// String concatenation of N parts. arg: u16 = part count.
97    Concat,
98
99    // --- Iteration ---
100    /// Set up a for-in loop. Expects iterable on stack. Pushes iterator state.
101    IterInit,
102    /// Advance iterator. If exhausted, jumps. arg: u16 = jump offset.
103    /// Pushes next value and the variable name is set via DefVar before the loop.
104    IterNext,
105
106    // --- Pipe ---
107    /// Pipe: pops [value, callable], invokes callable(value).
108    Pipe,
109
110    // --- Error handling ---
111    /// Pop value, raise as error.
112    Throw,
113    /// Push exception handler. arg: u16 = offset to catch handler.
114    TryCatchSetup,
115    /// Remove top exception handler (end of try body).
116    PopHandler,
117
118    // --- Concurrency ---
119    /// Execute closure N times sequentially, push results as list.
120    /// Stack: count, closure → result_list
121    Parallel,
122    /// Execute closure for each item in list, push results as list.
123    /// Stack: list, closure → result_list
124    ParallelMap,
125    /// Like ParallelMap but wraps each result in Result.Ok/Err, never fails.
126    /// Stack: list, closure → {results: [Result], succeeded: int, failed: int}
127    ParallelSettle,
128    /// Store closure for deferred execution, push TaskHandle.
129    /// Stack: closure → TaskHandle
130    Spawn,
131
132    // --- Imports ---
133    /// Import a file. arg: u16 = constant index (path string).
134    Import,
135    /// Selective import. arg1: u16 = path string, arg2: u16 = names list constant.
136    SelectiveImport,
137
138    // --- Deadline ---
139    /// Pop duration value, push deadline onto internal deadline stack.
140    DeadlineSetup,
141    /// Pop deadline from internal deadline stack.
142    DeadlineEnd,
143
144    // --- Enum ---
145    /// Build an enum variant value.
146    /// arg1: u16 = constant index (enum name), arg2: u16 = constant index (variant name),
147    /// arg3: u16 = field count. Fields are on stack.
148    BuildEnum,
149
150    // --- Match ---
151    /// Match an enum pattern. Checks enum_name + variant on the top of stack (dup'd match value).
152    /// arg1: u16 = constant index (enum name), arg2: u16 = constant index (variant name).
153    /// If match succeeds, pushes true; else pushes false.
154    MatchEnum,
155
156    // --- Loop control ---
157    /// Pop the top iterator from the iterator stack (cleanup on break from for-in).
158    PopIterator,
159
160    // --- Defaults ---
161    /// Push the number of arguments passed to the current function call.
162    GetArgc,
163
164    // --- Type checking ---
165    /// Runtime type check on a variable.
166    /// arg1: u16 = constant index (variable name),
167    /// arg2: u16 = constant index (expected type name).
168    /// Throws a TypeError if the variable's type doesn't match.
169    CheckType,
170
171    // --- Result try operator ---
172    /// Try-unwrap: if top is Result.Ok(v), replace with v. If Result.Err(e), return it.
173    TryUnwrap,
174
175    // --- Spread call ---
176    /// Call with spread arguments. Stack: [callee, args_list] -> result.
177    CallSpread,
178    /// Method call with spread arguments. Stack: [object, args_list] -> result.
179    /// Followed by 2 bytes for method name constant index.
180    MethodCallSpread,
181
182    // --- Misc ---
183    /// Duplicate top of stack.
184    Dup,
185    /// Swap top two stack values.
186    Swap,
187    /// Membership test: stack has [item, collection]. Pushes bool.
188    /// Works for lists (item in list), dicts (key in dict), strings (substr in string), and sets.
189    Contains,
190
191    /// Yield a value from a generator. Pops value, sends through channel, suspends.
192    Yield,
193}
194
195/// A constant value in the constant pool.
196#[derive(Debug, Clone, PartialEq)]
197pub enum Constant {
198    Int(i64),
199    Float(f64),
200    String(String),
201    Bool(bool),
202    Nil,
203    Duration(u64),
204}
205
206impl fmt::Display for Constant {
207    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208        match self {
209            Constant::Int(n) => write!(f, "{n}"),
210            Constant::Float(n) => write!(f, "{n}"),
211            Constant::String(s) => write!(f, "\"{s}\""),
212            Constant::Bool(b) => write!(f, "{b}"),
213            Constant::Nil => write!(f, "nil"),
214            Constant::Duration(ms) => write!(f, "{ms}ms"),
215        }
216    }
217}
218
219/// A compiled chunk of bytecode.
220#[derive(Debug, Clone)]
221pub struct Chunk {
222    /// The bytecode instructions.
223    pub code: Vec<u8>,
224    /// Constant pool.
225    pub constants: Vec<Constant>,
226    /// Source line numbers for each instruction (for error reporting).
227    pub lines: Vec<u32>,
228    /// Source column numbers for each instruction (for error reporting).
229    /// Parallel to `lines`; 0 means no column info available.
230    pub columns: Vec<u32>,
231    /// Current column to use when emitting instructions (set by compiler).
232    current_col: u32,
233    /// Compiled function bodies (for closures).
234    pub functions: Vec<CompiledFunction>,
235}
236
237/// A compiled function (closure body).
238#[derive(Debug, Clone)]
239pub struct CompiledFunction {
240    pub name: String,
241    pub params: Vec<String>,
242    /// Index of the first parameter with a default value, or None if all required.
243    pub default_start: Option<usize>,
244    pub chunk: Chunk,
245    /// True if the function body contains `yield` expressions (generator function).
246    pub is_generator: bool,
247}
248
249impl Chunk {
250    pub fn new() -> Self {
251        Self {
252            code: Vec::new(),
253            constants: Vec::new(),
254            lines: Vec::new(),
255            columns: Vec::new(),
256            current_col: 0,
257            functions: Vec::new(),
258        }
259    }
260
261    /// Set the current column for subsequent emit calls.
262    pub fn set_column(&mut self, col: u32) {
263        self.current_col = col;
264    }
265
266    /// Add a constant and return its index.
267    pub fn add_constant(&mut self, constant: Constant) -> u16 {
268        // Reuse existing constant if possible
269        for (i, c) in self.constants.iter().enumerate() {
270            if c == &constant {
271                return i as u16;
272            }
273        }
274        let idx = self.constants.len();
275        self.constants.push(constant);
276        idx as u16
277    }
278
279    /// Emit a single-byte instruction.
280    pub fn emit(&mut self, op: Op, line: u32) {
281        let col = self.current_col;
282        self.code.push(op as u8);
283        self.lines.push(line);
284        self.columns.push(col);
285    }
286
287    /// Emit an instruction with a u16 argument.
288    pub fn emit_u16(&mut self, op: Op, arg: u16, line: u32) {
289        let col = self.current_col;
290        self.code.push(op as u8);
291        self.code.push((arg >> 8) as u8);
292        self.code.push((arg & 0xFF) as u8);
293        self.lines.push(line);
294        self.lines.push(line);
295        self.lines.push(line);
296        self.columns.push(col);
297        self.columns.push(col);
298        self.columns.push(col);
299    }
300
301    /// Emit an instruction with a u8 argument.
302    pub fn emit_u8(&mut self, op: Op, arg: u8, line: u32) {
303        let col = self.current_col;
304        self.code.push(op as u8);
305        self.code.push(arg);
306        self.lines.push(line);
307        self.lines.push(line);
308        self.columns.push(col);
309        self.columns.push(col);
310    }
311
312    /// Emit a method call: op + u16 (method name) + u8 (arg count).
313    pub fn emit_method_call(&mut self, name_idx: u16, arg_count: u8, line: u32) {
314        self.emit_method_call_inner(Op::MethodCall, name_idx, arg_count, line);
315    }
316
317    /// Emit an optional method call (?.) — returns nil if receiver is nil.
318    pub fn emit_method_call_opt(&mut self, name_idx: u16, arg_count: u8, line: u32) {
319        self.emit_method_call_inner(Op::MethodCallOpt, name_idx, arg_count, line);
320    }
321
322    fn emit_method_call_inner(&mut self, op: Op, name_idx: u16, arg_count: u8, line: u32) {
323        let col = self.current_col;
324        self.code.push(op as u8);
325        self.code.push((name_idx >> 8) as u8);
326        self.code.push((name_idx & 0xFF) as u8);
327        self.code.push(arg_count);
328        self.lines.push(line);
329        self.lines.push(line);
330        self.lines.push(line);
331        self.lines.push(line);
332        self.columns.push(col);
333        self.columns.push(col);
334        self.columns.push(col);
335        self.columns.push(col);
336    }
337
338    /// Current code offset (for jump patching).
339    pub fn current_offset(&self) -> usize {
340        self.code.len()
341    }
342
343    /// Emit a jump instruction with a placeholder offset. Returns the position to patch.
344    pub fn emit_jump(&mut self, op: Op, line: u32) -> usize {
345        let col = self.current_col;
346        self.code.push(op as u8);
347        let patch_pos = self.code.len();
348        self.code.push(0xFF);
349        self.code.push(0xFF);
350        self.lines.push(line);
351        self.lines.push(line);
352        self.lines.push(line);
353        self.columns.push(col);
354        self.columns.push(col);
355        self.columns.push(col);
356        patch_pos
357    }
358
359    /// Patch a jump instruction at the given position to jump to the current offset.
360    pub fn patch_jump(&mut self, patch_pos: usize) {
361        let target = self.code.len() as u16;
362        self.code[patch_pos] = (target >> 8) as u8;
363        self.code[patch_pos + 1] = (target & 0xFF) as u8;
364    }
365
366    /// Patch a jump to a specific target position.
367    pub fn patch_jump_to(&mut self, patch_pos: usize, target: usize) {
368        let target = target as u16;
369        self.code[patch_pos] = (target >> 8) as u8;
370        self.code[patch_pos + 1] = (target & 0xFF) as u8;
371    }
372
373    /// Read a u16 argument at the given position.
374    pub fn read_u16(&self, pos: usize) -> u16 {
375        ((self.code[pos] as u16) << 8) | (self.code[pos + 1] as u16)
376    }
377
378    /// Disassemble for debugging.
379    pub fn disassemble(&self, name: &str) -> String {
380        let mut out = format!("== {name} ==\n");
381        let mut ip = 0;
382        while ip < self.code.len() {
383            let op = self.code[ip];
384            let line = self.lines.get(ip).copied().unwrap_or(0);
385            out.push_str(&format!("{:04} [{:>4}] ", ip, line));
386            ip += 1;
387
388            match op {
389                x if x == Op::Constant as u8 => {
390                    let idx = self.read_u16(ip);
391                    ip += 2;
392                    let val = &self.constants[idx as usize];
393                    out.push_str(&format!("CONSTANT {:>4} ({})\n", idx, val));
394                }
395                x if x == Op::Nil as u8 => out.push_str("NIL\n"),
396                x if x == Op::True as u8 => out.push_str("TRUE\n"),
397                x if x == Op::False as u8 => out.push_str("FALSE\n"),
398                x if x == Op::GetVar as u8 => {
399                    let idx = self.read_u16(ip);
400                    ip += 2;
401                    out.push_str(&format!(
402                        "GET_VAR {:>4} ({})\n",
403                        idx, self.constants[idx as usize]
404                    ));
405                }
406                x if x == Op::DefLet as u8 => {
407                    let idx = self.read_u16(ip);
408                    ip += 2;
409                    out.push_str(&format!(
410                        "DEF_LET {:>4} ({})\n",
411                        idx, self.constants[idx as usize]
412                    ));
413                }
414                x if x == Op::DefVar as u8 => {
415                    let idx = self.read_u16(ip);
416                    ip += 2;
417                    out.push_str(&format!(
418                        "DEF_VAR {:>4} ({})\n",
419                        idx, self.constants[idx as usize]
420                    ));
421                }
422                x if x == Op::SetVar as u8 => {
423                    let idx = self.read_u16(ip);
424                    ip += 2;
425                    out.push_str(&format!(
426                        "SET_VAR {:>4} ({})\n",
427                        idx, self.constants[idx as usize]
428                    ));
429                }
430                x if x == Op::Add as u8 => out.push_str("ADD\n"),
431                x if x == Op::Sub as u8 => out.push_str("SUB\n"),
432                x if x == Op::Mul as u8 => out.push_str("MUL\n"),
433                x if x == Op::Div as u8 => out.push_str("DIV\n"),
434                x if x == Op::Mod as u8 => out.push_str("MOD\n"),
435                x if x == Op::Negate as u8 => out.push_str("NEGATE\n"),
436                x if x == Op::Equal as u8 => out.push_str("EQUAL\n"),
437                x if x == Op::NotEqual as u8 => out.push_str("NOT_EQUAL\n"),
438                x if x == Op::Less as u8 => out.push_str("LESS\n"),
439                x if x == Op::Greater as u8 => out.push_str("GREATER\n"),
440                x if x == Op::LessEqual as u8 => out.push_str("LESS_EQUAL\n"),
441                x if x == Op::GreaterEqual as u8 => out.push_str("GREATER_EQUAL\n"),
442                x if x == Op::Contains as u8 => out.push_str("CONTAINS\n"),
443                x if x == Op::Not as u8 => out.push_str("NOT\n"),
444                x if x == Op::Jump as u8 => {
445                    let target = self.read_u16(ip);
446                    ip += 2;
447                    out.push_str(&format!("JUMP {:>4}\n", target));
448                }
449                x if x == Op::JumpIfFalse as u8 => {
450                    let target = self.read_u16(ip);
451                    ip += 2;
452                    out.push_str(&format!("JUMP_IF_FALSE {:>4}\n", target));
453                }
454                x if x == Op::JumpIfTrue as u8 => {
455                    let target = self.read_u16(ip);
456                    ip += 2;
457                    out.push_str(&format!("JUMP_IF_TRUE {:>4}\n", target));
458                }
459                x if x == Op::Pop as u8 => out.push_str("POP\n"),
460                x if x == Op::Call as u8 => {
461                    let argc = self.code[ip];
462                    ip += 1;
463                    out.push_str(&format!("CALL {:>4}\n", argc));
464                }
465                x if x == Op::TailCall as u8 => {
466                    let argc = self.code[ip];
467                    ip += 1;
468                    out.push_str(&format!("TAIL_CALL {:>4}\n", argc));
469                }
470                x if x == Op::Return as u8 => out.push_str("RETURN\n"),
471                x if x == Op::Closure as u8 => {
472                    let idx = self.read_u16(ip);
473                    ip += 2;
474                    out.push_str(&format!("CLOSURE {:>4}\n", idx));
475                }
476                x if x == Op::BuildList as u8 => {
477                    let count = self.read_u16(ip);
478                    ip += 2;
479                    out.push_str(&format!("BUILD_LIST {:>4}\n", count));
480                }
481                x if x == Op::BuildDict as u8 => {
482                    let count = self.read_u16(ip);
483                    ip += 2;
484                    out.push_str(&format!("BUILD_DICT {:>4}\n", count));
485                }
486                x if x == Op::Subscript as u8 => out.push_str("SUBSCRIPT\n"),
487                x if x == Op::Slice as u8 => out.push_str("SLICE\n"),
488                x if x == Op::GetProperty as u8 => {
489                    let idx = self.read_u16(ip);
490                    ip += 2;
491                    out.push_str(&format!(
492                        "GET_PROPERTY {:>4} ({})\n",
493                        idx, self.constants[idx as usize]
494                    ));
495                }
496                x if x == Op::GetPropertyOpt as u8 => {
497                    let idx = self.read_u16(ip);
498                    ip += 2;
499                    out.push_str(&format!(
500                        "GET_PROPERTY_OPT {:>4} ({})\n",
501                        idx, self.constants[idx as usize]
502                    ));
503                }
504                x if x == Op::SetProperty as u8 => {
505                    let idx = self.read_u16(ip);
506                    ip += 2;
507                    out.push_str(&format!(
508                        "SET_PROPERTY {:>4} ({})\n",
509                        idx, self.constants[idx as usize]
510                    ));
511                }
512                x if x == Op::SetSubscript as u8 => {
513                    let idx = self.read_u16(ip);
514                    ip += 2;
515                    out.push_str(&format!(
516                        "SET_SUBSCRIPT {:>4} ({})\n",
517                        idx, self.constants[idx as usize]
518                    ));
519                }
520                x if x == Op::MethodCall as u8 => {
521                    let idx = self.read_u16(ip);
522                    ip += 2;
523                    let argc = self.code[ip];
524                    ip += 1;
525                    out.push_str(&format!(
526                        "METHOD_CALL {:>4} ({}) argc={}\n",
527                        idx, self.constants[idx as usize], argc
528                    ));
529                }
530                x if x == Op::MethodCallOpt as u8 => {
531                    let idx = self.read_u16(ip);
532                    ip += 2;
533                    let argc = self.code[ip];
534                    ip += 1;
535                    out.push_str(&format!(
536                        "METHOD_CALL_OPT {:>4} ({}) argc={}\n",
537                        idx, self.constants[idx as usize], argc
538                    ));
539                }
540                x if x == Op::Concat as u8 => {
541                    let count = self.read_u16(ip);
542                    ip += 2;
543                    out.push_str(&format!("CONCAT {:>4}\n", count));
544                }
545                x if x == Op::IterInit as u8 => out.push_str("ITER_INIT\n"),
546                x if x == Op::IterNext as u8 => {
547                    let target = self.read_u16(ip);
548                    ip += 2;
549                    out.push_str(&format!("ITER_NEXT {:>4}\n", target));
550                }
551                x if x == Op::Throw as u8 => out.push_str("THROW\n"),
552                x if x == Op::TryCatchSetup as u8 => {
553                    let target = self.read_u16(ip);
554                    ip += 2;
555                    out.push_str(&format!("TRY_CATCH_SETUP {:>4}\n", target));
556                }
557                x if x == Op::PopHandler as u8 => out.push_str("POP_HANDLER\n"),
558                x if x == Op::Pipe as u8 => out.push_str("PIPE\n"),
559                x if x == Op::Parallel as u8 => out.push_str("PARALLEL\n"),
560                x if x == Op::ParallelMap as u8 => out.push_str("PARALLEL_MAP\n"),
561                x if x == Op::ParallelSettle as u8 => out.push_str("PARALLEL_SETTLE\n"),
562                x if x == Op::Spawn as u8 => out.push_str("SPAWN\n"),
563                x if x == Op::Import as u8 => {
564                    let idx = self.read_u16(ip);
565                    ip += 2;
566                    out.push_str(&format!(
567                        "IMPORT {:>4} ({})\n",
568                        idx, self.constants[idx as usize]
569                    ));
570                }
571                x if x == Op::SelectiveImport as u8 => {
572                    let path_idx = self.read_u16(ip);
573                    ip += 2;
574                    let names_idx = self.read_u16(ip);
575                    ip += 2;
576                    out.push_str(&format!(
577                        "SELECTIVE_IMPORT {:>4} ({}) names: {:>4} ({})\n",
578                        path_idx,
579                        self.constants[path_idx as usize],
580                        names_idx,
581                        self.constants[names_idx as usize]
582                    ));
583                }
584                x if x == Op::DeadlineSetup as u8 => out.push_str("DEADLINE_SETUP\n"),
585                x if x == Op::DeadlineEnd as u8 => out.push_str("DEADLINE_END\n"),
586                x if x == Op::BuildEnum as u8 => {
587                    let enum_idx = self.read_u16(ip);
588                    ip += 2;
589                    let variant_idx = self.read_u16(ip);
590                    ip += 2;
591                    let field_count = self.read_u16(ip);
592                    ip += 2;
593                    out.push_str(&format!(
594                        "BUILD_ENUM {:>4} ({}) {:>4} ({}) fields={}\n",
595                        enum_idx,
596                        self.constants[enum_idx as usize],
597                        variant_idx,
598                        self.constants[variant_idx as usize],
599                        field_count
600                    ));
601                }
602                x if x == Op::MatchEnum as u8 => {
603                    let enum_idx = self.read_u16(ip);
604                    ip += 2;
605                    let variant_idx = self.read_u16(ip);
606                    ip += 2;
607                    out.push_str(&format!(
608                        "MATCH_ENUM {:>4} ({}) {:>4} ({})\n",
609                        enum_idx,
610                        self.constants[enum_idx as usize],
611                        variant_idx,
612                        self.constants[variant_idx as usize]
613                    ));
614                }
615                x if x == Op::PopIterator as u8 => out.push_str("POP_ITERATOR\n"),
616                x if x == Op::TryUnwrap as u8 => out.push_str("TRY_UNWRAP\n"),
617                x if x == Op::CallSpread as u8 => out.push_str("CALL_SPREAD\n"),
618                x if x == Op::MethodCallSpread as u8 => {
619                    let idx = self.read_u16(ip + 1);
620                    ip += 2;
621                    out.push_str(&format!("METHOD_CALL_SPREAD {idx}\n"));
622                }
623                x if x == Op::Dup as u8 => out.push_str("DUP\n"),
624                x if x == Op::Swap as u8 => out.push_str("SWAP\n"),
625                x if x == Op::Yield as u8 => out.push_str("YIELD\n"),
626                _ => {
627                    out.push_str(&format!("UNKNOWN(0x{:02x})\n", op));
628                }
629            }
630        }
631        out
632    }
633}
634
635impl Default for Chunk {
636    fn default() -> Self {
637        Self::new()
638    }
639}