fusevm 0.14.19

Language-agnostic bytecode VM with fused superinstructions and a 3-tier Cranelift JIT (linear/block/tracing)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
//! Bytecode container — a compiled unit of execution.
//!
//! A `Chunk` holds the bytecodes, constant pool, name pool, and metadata
//! for one compilation unit (script, function, block). Language frontends
//! build Chunks via the `ChunkBuilder`.

use crate::op::Op;
use crate::value::Value;
use serde::{Deserialize, Serialize};

/// A compiled bytecode unit.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Chunk {
    /// Bytecode instructions
    pub ops: Vec<Op>,
    /// Constant pool: literals, patterns, format strings
    pub constants: Vec<Value>,
    /// Name pool: variable names, function names (interned/deduped)
    pub names: Vec<String>,
    /// Source line for each op (parallel array for error reporting)
    pub lines: Vec<u32>,
    /// Compiled subroutine entry points: (name_index, op_index)
    pub sub_entries: Vec<(u16, usize)>,
    /// Block regions for map/grep/sort/foreach: (start_ip, end_ip)
    pub block_ranges: Vec<(usize, usize)>,
    /// Sub-chunks for nested execution: `$(cmd)` bodies, `<(cmd)` /
    /// `>(cmd)` bodies, trap handlers, with-redirects bodies, function bodies
    /// when they're stored as separate chunks. Indexed by `Op::CmdSubst(u16)`,
    /// `Op::ProcessSubIn(u16)`, `Op::ProcessSubOut(u16)`, `Op::TrapSet(u16)`.
    pub sub_chunks: Vec<Chunk>,
    /// Source file name (for error messages)
    pub source: String,
    /// Opt-in: native codegen (AOT/JIT) treats integer `Add`/`Sub`/`Mul` as
    /// *overflow-checked* — on i64 overflow it deopts to the interpreter (which
    /// runs the op through the frontend's numeric hook) instead of wrapping. A
    /// frontend with arbitrary-precision integers (pythonrs) sets this so its
    /// native loops stay both fast (native i64 on the common path) and correct
    /// (bignum promotion on overflow). Default `false` keeps the raw-wrapping
    /// behavior awk/shell rely on, so existing frontends are byte-identical.
    #[serde(default)]
    pub int_overflow_deopt: bool,
    /// Cached hash of ops + constants (computed once at build time for O(1) JIT cache lookup)
    #[serde(skip)]
    pub op_hash: u64,
}

impl Chunk {
    /// Construct an empty `Chunk` — alias for `Chunk::default()`. Use
    /// `ChunkBuilder` for the incremental-build path.
    pub fn new() -> Self {
        Self::default()
    }

    /// Find a subroutine entry by name pool index.
    pub fn find_sub(&self, name_idx: u16) -> Option<usize> {
        self.sub_entries
            .iter()
            .find(|(n, _)| *n == name_idx)
            .map(|(_, ip)| *ip)
    }

    /// Human-readable disassembly listing of this chunk (and, recursively, its
    /// `sub_chunks`). Language frontends surface this behind a `--disasm` flag.
    ///
    /// Format (stable — consumed by frontend `--disasm` output and tests):
    /// - `; source: FILE` when `source` is non-empty
    /// - `; name[i] = NAME` for each name-pool entry
    /// - `; sub_entries:` then `;   NAME @ IP` for each subroutine entry
    ///   (`?` when the name index is out of bounds — never panics)
    /// - `IIII  LLLLL     Op` per op: 4-digit op index, right-aligned source
    ///   line, then the `Op` `Debug` form
    /// - `; --- sub_chunk[n] ---` headers with each nested chunk indented two
    ///   spaces deeper (compounding per nesting level)
    ///
    /// This lives here, on the shared VM's own `Chunk`, so every fusevm
    /// frontend gets identical disassembly without copying the formatter.
    pub fn disassemble(&self) -> String {
        let mut out = String::new();
        self.append_disasm(&mut out, "");
        out
    }

    fn append_disasm(&self, out: &mut String, indent: &str) {
        use std::fmt::Write;
        if !self.source.is_empty() {
            let _ = writeln!(out, "{indent}; source: {}", self.source);
        }
        for (i, n) in self.names.iter().enumerate() {
            let _ = writeln!(out, "{indent}; name[{i}] = {n}");
        }
        if !self.sub_entries.is_empty() {
            let _ = writeln!(out, "{indent}; sub_entries:");
            for (ni, ip) in &self.sub_entries {
                let name = self
                    .names
                    .get(*ni as usize)
                    .map(String::as_str)
                    .unwrap_or("?");
                let _ = writeln!(out, "{indent};   {name} @ {ip}");
            }
        }
        for (i, op) in self.ops.iter().enumerate() {
            let line = self.lines.get(i).copied().unwrap_or(0);
            let _ = writeln!(out, "{indent}{i:04} {line:>5}     {op:?}");
        }
        for (si, sub) in self.sub_chunks.iter().enumerate() {
            let _ = writeln!(out, "{indent}; --- sub_chunk[{si}] ---");
            let sub_indent = format!("{indent}  ");
            sub.append_disasm(out, &sub_indent);
        }
    }
}

/// Builder for constructing Chunks incrementally.
pub struct ChunkBuilder {
    chunk: Chunk,
    name_map: std::collections::HashMap<String, u16>,
}

impl ChunkBuilder {
    /// Construct a fresh builder with an empty chunk + an empty name
    /// intern table.
    pub fn new() -> Self {
        Self {
            chunk: Chunk::new(),
            name_map: std::collections::HashMap::new(),
        }
    }

    /// Opt in to overflow-checked native integer arithmetic for this chunk (see
    /// [`Chunk::int_overflow_deopt`]). Frontends with arbitrary-precision ints
    /// call this so native `Add`/`Sub`/`Mul` deopt to the interpreter on i64
    /// overflow instead of wrapping.
    pub fn set_int_overflow_deopt(&mut self, on: bool) {
        self.chunk.int_overflow_deopt = on;
    }

    /// Emit an op at the current position.
    pub fn emit(&mut self, op: Op, line: u32) -> usize {
        let idx = self.chunk.ops.len();
        self.chunk.ops.push(op);
        self.chunk.lines.push(line);
        idx
    }

    /// Add a constant to the pool, return its index.
    pub fn add_constant(&mut self, val: Value) -> u16 {
        let idx = self.chunk.constants.len();
        self.chunk.constants.push(val);
        idx as u16
    }

    /// Intern a name, return its pool index.
    pub fn add_name(&mut self, name: &str) -> u16 {
        if let Some(&idx) = self.name_map.get(name) {
            return idx;
        }
        let idx = self.chunk.names.len() as u16;
        self.chunk.names.push(name.to_string());
        self.name_map.insert(name.to_string(), idx);
        idx
    }

    /// Current bytecode position (for jump targets).
    pub fn current_pos(&self) -> usize {
        self.chunk.ops.len()
    }

    /// Patch a jump target at the given op index.
    pub fn patch_jump(&mut self, op_idx: usize, target: usize) {
        match &mut self.chunk.ops[op_idx] {
            Op::Jump(t)
            | Op::JumpIfTrue(t)
            | Op::JumpIfFalse(t)
            | Op::JumpIfTrueKeep(t)
            | Op::JumpIfFalseKeep(t) => *t = target,
            _ => panic!("patch_jump on non-jump op at {}", op_idx),
        }
    }

    /// Register a subroutine entry point.
    pub fn add_sub_entry(&mut self, name_idx: u16, ip: usize) {
        self.chunk.sub_entries.push((name_idx, ip));
    }

    /// Register a block region (for map/grep/sort).
    pub fn add_block_range(&mut self, start: usize, end: usize) -> u16 {
        let idx = self.chunk.block_ranges.len();
        self.chunk.block_ranges.push((start, end));
        idx as u16
    }

    /// Add a nested sub-chunk (for cmd subst, process subst, trap handlers,
    /// function bodies). Returns the index used by `Op::CmdSubst`,
    /// `Op::ProcessSubIn`/`Out`, `Op::TrapSet`.
    pub fn add_sub_chunk(&mut self, sub: Chunk) -> u16 {
        let idx = self.chunk.sub_chunks.len();
        self.chunk.sub_chunks.push(sub);
        idx as u16
    }

    /// Set source file name.
    pub fn set_source(&mut self, source: impl Into<String>) {
        self.chunk.source = source.into();
    }

    /// Finalize and return the chunk with precomputed op hash.
    pub fn build(mut self) -> Chunk {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut h = DefaultHasher::new();
        self.chunk.ops.hash(&mut h);
        self.chunk.constants.hash(&mut h);
        self.chunk.op_hash = h.finish();
        self.chunk
    }
}

impl Default for ChunkBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::op::Op;
    use crate::value::Value;

    #[test]
    fn new_and_default_are_equivalent() {
        let a = ChunkBuilder::new().build();
        let b = ChunkBuilder::default().build();
        assert_eq!(a.ops, b.ops);
        assert_eq!(a.names, b.names);
        assert_eq!(a.constants.len(), b.constants.len());
        assert_eq!(a.op_hash, b.op_hash);
    }

    #[test]
    fn find_sub_returns_first_match_when_duplicate_names_registered() {
        // Builder does not prevent duplicate sub_entries; lookup returns the first.
        let mut b = ChunkBuilder::new();
        let n = b.add_name("foo");
        b.add_sub_entry(n, 10);
        b.add_sub_entry(n, 20);
        let chunk = b.build();
        assert_eq!(chunk.find_sub(n), Some(10));
    }

    #[test]
    fn find_sub_distinguishes_multiple_subs() {
        let mut b = ChunkBuilder::new();
        let f = b.add_name("f");
        let g = b.add_name("g");
        b.add_sub_entry(f, 7);
        b.add_sub_entry(g, 13);
        let chunk = b.build();
        assert_eq!(chunk.find_sub(f), Some(7));
        assert_eq!(chunk.find_sub(g), Some(13));
    }

    #[test]
    fn add_sub_chunk_returns_sequential_indices() {
        let mut b = ChunkBuilder::new();
        let i0 = b.add_sub_chunk(Chunk::new());
        let i1 = b.add_sub_chunk(Chunk::new());
        let i2 = b.add_sub_chunk(Chunk::new());
        assert_eq!((i0, i1, i2), (0, 1, 2));
        assert_eq!(b.build().sub_chunks.len(), 3);
    }

    #[test]
    fn sub_chunks_preserve_inner_content() {
        let inner = {
            let mut ib = ChunkBuilder::new();
            ib.emit(Op::LoadInt(7), 1);
            ib.build()
        };
        let mut b = ChunkBuilder::new();
        let idx = b.add_sub_chunk(inner);
        let outer = b.build();
        assert_eq!(idx, 0);
        assert_eq!(outer.sub_chunks[0].ops, vec![Op::LoadInt(7)]);
    }

    #[test]
    fn add_constant_returns_monotonic_indices() {
        let mut b = ChunkBuilder::new();
        for i in 0..5u16 {
            assert_eq!(b.add_constant(Value::Int(i as i64)), i);
        }
    }

    #[test]
    fn add_name_first_index_is_zero() {
        let mut b = ChunkBuilder::new();
        assert_eq!(b.add_name("first"), 0);
        assert_eq!(b.add_name("second"), 1);
    }

    #[test]
    fn build_computes_nonzero_hash_for_nonempty_chunk() {
        let mut b = ChunkBuilder::new();
        b.emit(Op::LoadInt(1), 1);
        let c = b.build();
        // Extremely unlikely to be exactly 0 for a non-empty chunk.
        assert_ne!(c.op_hash, 0);
    }

    #[test]
    fn op_hash_ignores_line_and_name_pool() {
        // op_hash is derived from ops + constants only.
        let a = {
            let mut b = ChunkBuilder::new();
            b.add_name("alpha");
            b.emit(Op::LoadInt(1), 5);
            b.build()
        };
        let b = {
            let mut b = ChunkBuilder::new();
            b.add_name("beta");
            b.emit(Op::LoadInt(1), 99);
            b.build()
        };
        assert_eq!(a.op_hash, b.op_hash);
    }

    #[test]
    fn set_source_overwrites_previous_value() {
        let mut b = ChunkBuilder::new();
        b.set_source("first.fuse");
        b.set_source("second.fuse");
        assert_eq!(b.build().source, "second.fuse");
    }

    // ─── emit ──────────────────────────────────────────────────────────

    #[test]
    fn emit_returns_sequential_indices() {
        let mut b = ChunkBuilder::new();
        assert_eq!(b.emit(Op::LoadInt(1), 1), 0);
        assert_eq!(b.emit(Op::LoadInt(2), 1), 1);
        assert_eq!(b.emit(Op::Add, 1), 2);
    }

    #[test]
    fn emit_records_lines_parallel_to_ops() {
        let mut b = ChunkBuilder::new();
        b.emit(Op::LoadInt(1), 10);
        b.emit(Op::LoadInt(2), 20);
        b.emit(Op::Add, 30);
        let c = b.build();
        assert_eq!(c.ops.len(), c.lines.len());
        assert_eq!(c.lines, vec![10, 20, 30]);
    }

    #[test]
    fn current_pos_matches_op_count() {
        let mut b = ChunkBuilder::new();
        assert_eq!(b.current_pos(), 0);
        b.emit(Op::Nop, 1);
        assert_eq!(b.current_pos(), 1);
        b.emit(Op::Nop, 1);
        assert_eq!(b.current_pos(), 2);
    }

    // ─── add_name interning / dedup ───────────────────────────────────

    #[test]
    fn add_name_dedupes_same_name_to_same_index() {
        let mut b = ChunkBuilder::new();
        let a = b.add_name("foo");
        let bb = b.add_name("bar");
        let a2 = b.add_name("foo");
        assert_eq!(a, a2, "same name → same index");
        assert_ne!(a, bb);
        // Only 2 unique names in the pool.
        assert_eq!(b.build().names.len(), 2);
    }

    #[test]
    fn add_name_distinct_names_get_distinct_indices() {
        let mut b = ChunkBuilder::new();
        let mut seen = std::collections::HashSet::new();
        for s in ["a", "b", "c", "d", "e"] {
            assert!(seen.insert(b.add_name(s)));
        }
    }

    // ─── patch_jump ────────────────────────────────────────────────────

    #[test]
    fn patch_jump_updates_unconditional_jump() {
        let mut b = ChunkBuilder::new();
        let idx = b.emit(Op::Jump(0), 1); // placeholder target
        b.patch_jump(idx, 42);
        let c = b.build();
        assert_eq!(c.ops[idx], Op::Jump(42));
    }

    #[test]
    fn patch_jump_updates_all_conditional_variants() {
        for op in [
            Op::JumpIfTrue(0),
            Op::JumpIfFalse(0),
            Op::JumpIfTrueKeep(0),
            Op::JumpIfFalseKeep(0),
        ] {
            let mut b = ChunkBuilder::new();
            let idx = b.emit(op.clone(), 1);
            b.patch_jump(idx, 100);
            let c = b.build();
            match c.ops[idx] {
                Op::JumpIfTrue(100)
                | Op::JumpIfFalse(100)
                | Op::JumpIfTrueKeep(100)
                | Op::JumpIfFalseKeep(100) => {}
                ref other => panic!("patch failed for {op:?}, got {other:?}"),
            }
        }
    }

    #[test]
    #[should_panic(expected = "patch_jump on non-jump op")]
    fn patch_jump_panics_on_non_jump_op() {
        let mut b = ChunkBuilder::new();
        let idx = b.emit(Op::Nop, 1);
        b.patch_jump(idx, 0);
    }

    // ─── add_block_range ──────────────────────────────────────────────

    #[test]
    fn add_block_range_returns_sequential_indices_and_stores_pairs() {
        let mut b = ChunkBuilder::new();
        let i0 = b.add_block_range(0, 5);
        let i1 = b.add_block_range(10, 20);
        assert_eq!((i0, i1), (0, 1));
        let c = b.build();
        assert_eq!(c.block_ranges, vec![(0, 5), (10, 20)]);
    }

    // ─── find_sub ─────────────────────────────────────────────────────

    #[test]
    fn find_sub_returns_none_for_unknown_name_index() {
        // Empty sub_entries → always None regardless of index.
        let chunk = ChunkBuilder::new().build();
        assert!(chunk.find_sub(0).is_none());
        assert!(chunk.find_sub(99).is_none());
    }

    // ─── op_hash determinism + cross-content variance ─────────────────

    #[test]
    fn op_hash_is_deterministic_for_same_input() {
        let make = || {
            let mut b = ChunkBuilder::new();
            b.emit(Op::LoadInt(1), 1);
            b.emit(Op::LoadInt(2), 1);
            b.emit(Op::Add, 1);
            b.build()
        };
        assert_eq!(make().op_hash, make().op_hash);
    }

    #[test]
    fn op_hash_differs_when_constants_differ() {
        // Same ops, different constant pool → different hash.
        let a = {
            let mut b = ChunkBuilder::new();
            b.add_constant(Value::Int(1));
            b.emit(Op::Nop, 1);
            b.build()
        };
        let b = {
            let mut b = ChunkBuilder::new();
            b.add_constant(Value::Int(2));
            b.emit(Op::Nop, 1);
            b.build()
        };
        assert_ne!(
            a.op_hash, b.op_hash,
            "constants pool must contribute to hash"
        );
    }

    #[test]
    fn op_hash_differs_when_ops_differ() {
        let a = {
            let mut b = ChunkBuilder::new();
            b.emit(Op::Add, 1);
            b.build()
        };
        let b = {
            let mut b = ChunkBuilder::new();
            b.emit(Op::Sub, 1);
            b.build()
        };
        assert_ne!(a.op_hash, b.op_hash);
    }

    // ─── round-trip Chunk via serde JSON ──────────────────────────────

    #[test]
    fn chunk_serde_json_roundtrip() {
        // Chunk has Serialize/Deserialize; verify the full container survives.
        let mut b = ChunkBuilder::new();
        b.add_name("x");
        b.add_constant(Value::Int(42));
        b.emit(Op::LoadInt(42), 1);
        b.set_source("test.fuse");
        let chunk = b.build();
        let s = serde_json::to_string(&chunk).expect("serialize");
        let back: Chunk = serde_json::from_str(&s).expect("deserialize");
        assert_eq!(back.ops, chunk.ops);
        assert_eq!(back.names, chunk.names);
        assert_eq!(back.lines, chunk.lines);
        assert_eq!(back.source, chunk.source);
        // op_hash has #[serde(skip)] → does NOT survive round-trip.
        assert_eq!(back.op_hash, 0, "op_hash skipped by serde");
    }

    // ─── disassemble() — shared frontend `--disasm` listing ───────────

    #[test]
    fn disassemble_empty_chunk_is_empty() {
        // Default chunk has empty source/names/ops/sub_entries/sub_chunks —
        // nothing to list, so no lines at all.
        assert_eq!(Chunk::default().disassemble(), "");
    }

    #[test]
    fn disassemble_emits_source_only_when_present() {
        let mut c = Chunk::default();
        assert!(!c.disassemble().contains("; source:"));
        c.source = "a.fuse".to_string();
        assert_eq!(c.disassemble(), "; source: a.fuse\n");
    }

    #[test]
    fn disassemble_names_and_ops_numbered() {
        let mut b = ChunkBuilder::new();
        b.add_name("foo");
        b.emit(Op::Nop, 1);
        b.emit(Op::Nop, 2);
        let listing = b.build().disassemble();
        assert!(listing.contains("; name[0] = foo"));
        // 4-digit op index, right-aligned line, Op Debug.
        assert!(listing.contains("0000     1     Nop"), "{listing}");
        assert!(listing.contains("0001     2     Nop"), "{listing}");
    }

    #[test]
    fn disassemble_sub_entry_unknown_index_shows_question_mark() {
        // Out-of-bounds name index must not panic — renders as "?".
        let mut c = Chunk::default();
        c.sub_entries = vec![(99u16, 17usize)];
        assert!(c.disassemble().contains(";   ? @ 17"));
    }

    #[test]
    fn disassemble_recurses_sub_chunks_with_compounding_indent() {
        let mut deepest = Chunk::default();
        deepest.source = "deep.fuse".to_string();
        let mut middle = Chunk::default();
        middle.sub_chunks = vec![deepest];
        let mut outer = Chunk::default();
        outer.sub_chunks = vec![middle];
        let listing = outer.disassemble();
        assert!(listing.contains("; --- sub_chunk[0] ---"));
        // Two levels deep → 4-space indent on the inner source line.
        assert!(
            listing.contains("    ; source: deep.fuse"),
            "two-level nesting should indent 4 spaces:\n{listing}"
        );
    }

    #[test]
    fn disassemble_op_line_defaults_to_zero_when_lines_short() {
        let mut c = Chunk::default();
        c.ops = vec![Op::Nop, Op::Nop];
        c.lines = vec![5]; // one line entry for two ops
        let listing = c.disassemble();
        assert!(listing.contains("0000     5     Nop"));
        assert!(listing.contains("0001     0     Nop"), "missing line → 0");
    }
}