Skip to main content

byteflow/bytecode/
program.rs

1//! Primary API for assembling [`Chunk`] programs in host Rust.
2//!
3//! Use [`Program`] to define a module and [`Fn`] to emit each function with
4//! named registers instead of manual `r0` / `emit_*` bookkeeping.
5//!
6//! ```rust
7//! use byteflow::Program;
8//!
9//! let mut program = Program::new("count");
10//! program.function("main", 0, |f| {
11//!     let limit = f.load_int(100);
12//!     let counter = f.load_i32(0);
13//!     f.while_lt(counter, limit, |f| f.add_imm(counter, 1));
14//!     f.return_(counter);
15//! });
16//! let chunk = program.build();
17//! ```
18
19// Docs ratchet: public items here predate `missing_docs`. Delete this
20// allow once they are documented; new files get the lint by default.
21#![allow(missing_docs)]
22
23use super::builder::ChunkBuilder;
24
25pub use super::builder::Label;
26use super::chunk::Chunk;
27use super::opcode::Opcode;
28use super::value::Value;
29
30/// Function index returned by [`Program::function`].
31pub type FuncId = u32;
32
33/// A virtual register in the current function.
34#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
35pub struct Reg(u8);
36
37impl Reg {
38    /// Underlying register index in the bytecode function frame.
39    pub const fn index(self) -> u8 {
40        self.0
41    }
42}
43
44impl From<Reg> for u8 {
45    fn from(r: Reg) -> u8 {
46        r.0
47    }
48}
49
50/// Contiguous register window (e.g. four slots for `make_msg` natives).
51#[derive(Clone, Copy, Debug)]
52pub struct RegWindow {
53    base: Reg,
54    len: u8,
55}
56
57impl RegWindow {
58    /// First register in the window (native result lands here for `make_msg`).
59    pub fn base(self) -> Reg {
60        self.base
61    }
62
63    /// Register at offset `i` within the window (`0 <= i < len`).
64    pub fn at(self, i: u8) -> Reg {
65        debug_assert!(i < self.len, "RegWindow index out of bounds");
66        match self.base.0.checked_add(i) {
67            Some(idx) => Reg(idx),
68            None => Reg(u8::MAX),
69        }
70    }
71}
72
73/// Assemble one bytecode module.
74pub struct Program {
75    inner: ChunkBuilder,
76}
77
78impl Program {
79    /// Start a new module named `name`.
80    pub fn new(name: impl Into<String>) -> Self {
81        Self {
82            inner: ChunkBuilder::new(name),
83        }
84    }
85
86    /// Define a function and run `body` against a fresh [`Fn`] context.
87    ///
88    /// Returns the function index for [`Fn::spawn`] / [`Fn::call`]
89    /// (pass argument registers as `&[Reg]`, not a bare argc).
90    pub fn function(
91        &mut self,
92        name: impl Into<String>,
93        arity: u8,
94        body: impl FnOnce(&mut Fn<'_>),
95    ) -> FuncId {
96        let mut f = Fn::open(&mut self.inner, name, arity);
97        let id = f.function;
98        body(&mut f);
99        id
100    }
101
102    /// Define a function with an explicit register-file size.
103    ///
104    /// Useful for fixed register layouts (`reg(255)`) or verification demos
105    /// where `num_registers < arity` must fail static checks.
106    pub fn function_raw(
107        &mut self,
108        name: impl Into<String>,
109        arity: u8,
110        num_registers: u8,
111        body: impl FnOnce(&mut Fn<'_>),
112    ) -> FuncId {
113        let mut f = Fn::open_with(&mut self.inner, name, arity, num_registers);
114        let id = f.function;
115        body(&mut f);
116        id
117    }
118
119    /// Look up a function index by name (available before [`Self::build`]).
120    pub fn function_index(&self, name: &str) -> Option<FuncId> {
121        self.inner.function_index(name)
122    }
123
124    /// Finish assembly and produce an immutable [`Chunk`].
125    pub fn build(self) -> Chunk {
126        self.inner.finish()
127    }
128}
129
130/// Emit instructions for one bytecode function.
131pub struct Fn<'a> {
132    b: &'a mut ChunkBuilder,
133    function: FuncId,
134    next_reg: u8,
135}
136
137impl<'a> Fn<'a> {
138    fn open(b: &'a mut ChunkBuilder, name: impl Into<String>, arity: u8) -> Self {
139        // Parameters occupy `r0..arity`. Locals continue from there, so a
140        // 0-arity function starts at `r0` instead of leaving four dead slots.
141        Self::open_with(b, name, arity, arity)
142    }
143
144    fn open_with(
145        b: &'a mut ChunkBuilder,
146        name: impl Into<String>,
147        arity: u8,
148        num_registers: u8,
149    ) -> Self {
150        let function = b.begin_function(name, arity, num_registers);
151        Self {
152            b,
153            function,
154            next_reg: num_registers,
155        }
156    }
157
158    /// Allocate a fresh local register.
159    ///
160    /// A frame is at most 255 slots (`num_registers` is a `u8`), so index
161    /// 255 is not a real register. One more `local` emits `Trap` and returns
162    /// `r0` instead of aliasing an existing slot.
163    pub fn local(&mut self) -> Reg {
164        if self.next_reg == u8::MAX {
165            self.b.emit_trap(0);
166            return Reg(0);
167        }
168        let reg = Reg(self.next_reg);
169        self.next_reg += 1;
170        self.b.set_num_registers(self.function, self.next_reg);
171        reg
172    }
173
174    /// Bind to an explicit register index without growing the declared frame.
175    pub fn reg(&mut self, index: u8) -> Reg {
176        Reg(index)
177    }
178
179    /// Ensure the register file is at least `count` slots wide.
180    pub fn reserve(&mut self, count: u8) {
181        if count > self.next_reg {
182            self.next_reg = count;
183            self.b.set_num_registers(self.function, self.next_reg);
184        }
185    }
186
187    /// Allocate `count` contiguous locals; useful before [`Self::native_n`].
188    ///
189    /// When the window does not fit, one `Trap` is emitted and `next_reg`
190    /// stays put. Calling [`Self::local`] for the overflow used to emit a
191    /// trap per missing slot and still report the original length.
192    pub fn window(&mut self, count: u8) -> RegWindow {
193        let base_idx = self.next_reg;
194        if count > 0 && u16::from(base_idx) + u16::from(count) > 255 {
195            self.b.emit_trap(0);
196            return RegWindow {
197                base: Reg(base_idx),
198                len: count,
199            };
200        }
201        for _ in 0..count {
202            let _ = self.local();
203        }
204        RegWindow {
205            base: Reg(base_idx),
206            len: count,
207        }
208    }
209
210    /// Fresh contiguous locals `r[start .. start+count]`, or `None` if that
211    /// window would leave the register file.
212    ///
213    /// A frame holds at most 255 slots, indexes `0..=254`. The exclusive end
214    /// `start + count` is therefore at most 255. The old bound allowed 256,
215    /// so the last `local` emitted `Trap` and returned `r0` before this
216    /// function gave up.
217    fn alloc_contig(&mut self, count: u8) -> Option<Reg> {
218        if count == 0 {
219            return None;
220        }
221        let start = self.next_reg;
222        if u16::from(start) + u16::from(count) > 255 {
223            return None;
224        }
225        for i in 0..count {
226            let r = self.local();
227            if r.0 != start.saturating_add(i) {
228                return None;
229            }
230        }
231        Some(Reg(start))
232    }
233
234    fn copy_window(&mut self, base: Reg, args: &[Reg]) {
235        for (i, &src) in args.iter().enumerate() {
236            let Ok(off) = u8::try_from(i) else {
237                self.b.emit_trap(0);
238                return;
239            };
240            let Some(idx) = base.0.checked_add(off) else {
241                self.b.emit_trap(0);
242                return;
243            };
244            let slot = Reg(idx);
245            if slot != src {
246                self.b.emit_move(slot.0, src.0);
247            }
248        }
249    }
250
251    /// Fail-closed pack: Trap so the VM never runs a half-built Call/Spawn.
252    fn fail_pack(&mut self) -> Reg {
253        self.b.emit_trap(0);
254        self.local()
255    }
256
257    /// Load a small immediate into a new local.
258    pub fn load_i32(&mut self, n: i32) -> Reg {
259        let reg = self.local();
260        self.b.emit_load_imm(reg.0, n);
261        reg
262    }
263
264    /// Load a constant-pool integer into a new local.
265    pub fn load_int(&mut self, n: i64) -> Reg {
266        let konst = self.b.const_(Value::Int(n));
267        let reg = self.local();
268        self.b.emit_load_const(reg.0, konst);
269        reg
270    }
271
272    /// Store an immediate into an existing register.
273    pub fn set(&mut self, reg: Reg, imm: i32) {
274        self.b.emit_load_imm(reg.0, imm);
275    }
276
277    /// `dst = src`
278    pub fn mov(&mut self, dst: Reg, src: Reg) {
279        self.b.emit_move(dst.0, src.0);
280    }
281
282    fn binop(&mut self, op: Opcode, lhs: Reg, rhs: Reg) -> Reg {
283        let dst = self.local();
284        self.b.emit_binop(op, dst.0, lhs.0, rhs.0);
285        dst
286    }
287
288    /// `dst = lhs + rhs` into a new local.
289    pub fn add(&mut self, lhs: Reg, rhs: Reg) -> Reg {
290        self.binop(Opcode::Add, lhs, rhs)
291    }
292
293    /// `dst += imm` in place. One [`Opcode::AddImm`], no scratch register.
294    pub fn add_imm(&mut self, dst: Reg, imm: i32) {
295        self.b.emit_add_imm(dst.0, dst.0, imm);
296    }
297
298    /// `dst -= imm` in place. One [`Opcode::SubImm`].
299    pub fn sub_imm(&mut self, dst: Reg, imm: i32) {
300        self.b.emit_sub_imm(dst.0, dst.0, imm);
301    }
302
303    /// `lhs < imm` as `Bool`, in a fresh local. One [`Opcode::LtImm`].
304    pub fn lt_imm(&mut self, lhs: Reg, imm: i32) -> Reg {
305        let dst = self.local();
306        self.b.emit_lt_imm(dst.0, lhs.0, imm);
307        dst
308    }
309
310    /// `dst *= imm` in place. One [`Opcode::MulImm`]. Integer multiply wraps.
311    pub fn mul_imm(&mut self, dst: Reg, imm: i32) {
312        self.b.emit_mul_imm(dst.0, dst.0, imm);
313    }
314
315    /// `lhs <= imm` as `Bool`, in a fresh local. One [`Opcode::LeImm`].
316    pub fn le_imm(&mut self, lhs: Reg, imm: i32) -> Reg {
317        let dst = self.local();
318        self.b.emit_le_imm(dst.0, lhs.0, imm);
319        dst
320    }
321
322    /// `lhs & rhs` into a new local. Both operands must be `Int` at runtime.
323    pub fn bit_and(&mut self, lhs: Reg, rhs: Reg) -> Reg {
324        self.bitop(Opcode::BitAnd, lhs, rhs)
325    }
326
327    /// `lhs | rhs` into a new local.
328    pub fn bit_or(&mut self, lhs: Reg, rhs: Reg) -> Reg {
329        self.bitop(Opcode::BitOr, lhs, rhs)
330    }
331
332    /// `lhs ^ rhs` into a new local.
333    pub fn bit_xor(&mut self, lhs: Reg, rhs: Reg) -> Reg {
334        self.bitop(Opcode::BitXor, lhs, rhs)
335    }
336
337    /// `!src` into a new local.
338    pub fn bit_not(&mut self, src: Reg) -> Reg {
339        let dst = self.local();
340        self.b.emit_bit_not(dst.0, src.0);
341        dst
342    }
343
344    /// `lhs << rhs` into a new local. The count keeps its low 6 bits.
345    pub fn shl(&mut self, lhs: Reg, rhs: Reg) -> Reg {
346        self.bitop(Opcode::Shl, lhs, rhs)
347    }
348
349    /// Arithmetic `lhs >> rhs` into a new local. The count keeps its low 6 bits.
350    pub fn shr(&mut self, lhs: Reg, rhs: Reg) -> Reg {
351        self.bitop(Opcode::Shr, lhs, rhs)
352    }
353
354    fn bitop(&mut self, op: Opcode, lhs: Reg, rhs: Reg) -> Reg {
355        let dst = self.local();
356        self.b.emit_bit_binop(op, dst.0, lhs.0, rhs.0);
357        dst
358    }
359
360    /// Pack `items` into a new list local.
361    ///
362    /// `items` must be contiguous (`rN, rN+1, …`), at most
363    /// [`crate::MAX_LIST_LEN`] long, and inside indexes `0..=254`. A gap is
364    /// not packed from the first register: that used to read whatever sat
365    /// between the holes. The failure is a `Trap`, same as an unbound label.
366    pub fn list_pack(&mut self, items: &[Reg]) -> Reg {
367        self.pack_sequence(items, crate::MAX_LIST_LEN, true)
368    }
369
370    pub fn list_get(&mut self, list: Reg, index: i32) -> Reg {
371        let dst = self.local();
372        self.b.emit_list_get(dst.0, list.0, index);
373        dst
374    }
375
376    pub fn list_len(&mut self, list: Reg) -> Reg {
377        let dst = self.local();
378        self.b.emit_list_len(dst.0, list.0);
379        dst
380    }
381
382    /// Pack contiguous registers into a positional record. Same layout rules
383    /// as [`Self::list_pack`]. At most [`crate::MAX_RECORD_LEN`] fields.
384    pub fn record_pack(&mut self, fields: &[Reg]) -> Reg {
385        self.pack_sequence(fields, crate::MAX_RECORD_LEN, false)
386    }
387
388    pub fn record_get(&mut self, record: Reg, index: i32) -> Reg {
389        let dst = self.local();
390        self.b.emit_record_get(dst.0, record.0, index);
391        dst
392    }
393
394    pub fn record_len(&mut self, record: Reg) -> Reg {
395        let dst = self.local();
396        self.b.emit_record_len(dst.0, record.0);
397        dst
398    }
399
400    /// Pack `pairs` into a map. Each pair is `(key, value)` already in
401    /// registers, laid out as `key, value, key, value` from the first key.
402    /// Keys are `Int` or `Str`. At most [`crate::MAX_MAP_LEN`] pairs.
403    ///
404    /// A hole or a value that is not the next register traps. The previous
405    /// encoding counted the pairs and started at the first key, so the
406    /// instruction read the registers in between.
407    pub fn map_pack(&mut self, pairs: &[(Reg, Reg)]) -> Reg {
408        if !contiguous_pairs(pairs) {
409            return self.fail_pack();
410        }
411        let dst = self.local();
412        let base = match pairs.first() {
413            Some((key, _)) => key.0,
414            None => 0,
415        };
416        let count = match i32::try_from(pairs.len()) {
417            Ok(n) => n,
418            Err(_) => return self.fail_pack(),
419        };
420        self.b.emit_map_pack(dst.0, base, count);
421        dst
422    }
423
424    fn pack_sequence(&mut self, items: &[Reg], max_len: usize, list: bool) -> Reg {
425        if items.len() > max_len || !contiguous_regs(items) {
426            return self.fail_pack();
427        }
428        let dst = self.local();
429        let base = match items.first() {
430            Some(reg) => reg.0,
431            None => 0,
432        };
433        let count = match i32::try_from(items.len()) {
434            Ok(n) => n,
435            Err(_) => return self.fail_pack(),
436        };
437        if list {
438            self.b.emit_list_pack(dst.0, base, count);
439        } else {
440            self.b.emit_record_pack(dst.0, base, count);
441        }
442        dst
443    }
444
445    pub fn map_get(&mut self, map: Reg, key: Reg) -> Reg {
446        let dst = self.local();
447        self.b.emit_map_get(dst.0, map.0, key.0);
448        dst
449    }
450
451    pub fn map_len(&mut self, map: Reg) -> Reg {
452        let dst = self.local();
453        self.b.emit_map_len(dst.0, map.0);
454        dst
455    }
456
457    /// Open this flow's table and return its Cap (`SEND` and `RECV`).
458    pub fn table_open(&mut self, name: Reg) -> Reg {
459        let dst = self.local();
460        self.b.emit_table_open(dst.0, name.0);
461        dst
462    }
463
464    /// Read `key` from `table`. Missing key yields `Unit`.
465    pub fn table_get(&mut self, table: Reg, key: Reg) -> Reg {
466        let dst = self.local();
467        self.b.emit_table_get(dst.0, table.0, key.0);
468        dst
469    }
470
471    /// Store `value` at `key` in `table`.
472    pub fn table_put(&mut self, table: Reg, key: Reg, value: Reg) {
473        self.b.emit_table_put(table.0, key.0, value.0);
474    }
475
476    pub fn sub(&mut self, lhs: Reg, rhs: Reg) -> Reg {
477        self.binop(Opcode::Sub, lhs, rhs)
478    }
479
480    pub fn mul(&mut self, lhs: Reg, rhs: Reg) -> Reg {
481        self.binop(Opcode::Mul, lhs, rhs)
482    }
483
484    pub fn div(&mut self, lhs: Reg, rhs: Reg) -> Reg {
485        self.binop(Opcode::Div, lhs, rhs)
486    }
487
488    pub fn modulo(&mut self, lhs: Reg, rhs: Reg) -> Reg {
489        self.binop(Opcode::Mod, lhs, rhs)
490    }
491
492    pub fn neg(&mut self, src: Reg) -> Reg {
493        let dst = self.local();
494        self.b.emit_neg(dst.0, src.0);
495        dst
496    }
497
498    pub fn eq(&mut self, lhs: Reg, rhs: Reg) -> Reg {
499        self.binop(Opcode::Eq, lhs, rhs)
500    }
501
502    /// `lhs == imm` as `Bool`, in a fresh local. One [`Opcode::EqImm`].
503    ///
504    /// The immediate is an `Int`. A float in `lhs` compares unequal.
505    pub fn eq_imm(&mut self, lhs: Reg, imm: i32) -> Reg {
506        let dst = self.local();
507        self.b.emit_eq_imm(dst.0, lhs.0, imm);
508        dst
509    }
510
511    pub fn lt(&mut self, lhs: Reg, rhs: Reg) -> Reg {
512        self.binop(Opcode::Lt, lhs, rhs)
513    }
514
515    pub fn le(&mut self, lhs: Reg, rhs: Reg) -> Reg {
516        self.binop(Opcode::Le, lhs, rhs)
517    }
518
519    /// While `counter < limit` (interpreter `Branch` skips on falsy).
520    pub fn while_lt<F>(&mut self, counter: Reg, limit: Reg, body: F)
521    where
522        F: FnOnce(&mut Fn<'_>),
523    {
524        let head = self.b.new_label();
525        let done = self.b.new_label();
526        let cond = self.local();
527        self.b.bind_label(head);
528        self.b.emit_binop(Opcode::Lt, cond.0, counter.0, limit.0);
529        self.b.emit_branch(cond.0, done);
530        body(self);
531        self.b.emit_jump(head);
532        self.b.bind_label(done);
533    }
534
535    pub fn label(&mut self) -> Label {
536        self.b.new_label()
537    }
538
539    pub fn bind(&mut self, label: Label) {
540        self.b.bind_label(label);
541    }
542
543    pub fn move_reg(&mut self, dst: Reg, src: Reg) {
544        self.b.emit_move(dst.0, src.0);
545    }
546
547    pub fn jump(&mut self, label: Label) {
548        self.b.emit_jump(label);
549    }
550
551    /// Branch when `cond` is falsy (`0`).
552    pub fn branch_if_falsy(&mut self, cond: Reg, target: Label) {
553        self.b.emit_branch(cond.0, target);
554    }
555
556    pub fn return_(&mut self, value: Reg) {
557        self.b.emit_return(value.0);
558    }
559
560    /// Call `function` with `args` packed into a fresh `Call` window.
561    ///
562    /// The ISA reads `r[dst .. dst+argc]` and writes the result to `r[dst]`.
563    /// This copies `args` into that window so `call(fn, &[a, b])` after
564    /// `load_i32` actually passes those values — a bare argc does not.
565    pub fn call(&mut self, function: FuncId, args: &[Reg]) -> Reg {
566        let Some(argc) = u8::try_from(args.len()).ok() else {
567            return self.fail_pack();
568        };
569        let dst = if argc == 0 {
570            self.local()
571        } else {
572            match self.alloc_contig(argc) {
573                Some(base) => {
574                    self.copy_window(base, args);
575                    base
576                }
577                None => return self.fail_pack(),
578            }
579        };
580        self.b.emit_call(dst.0, function, argc);
581        dst
582    }
583
584    pub fn halt(&mut self) {
585        self.b.emit_halt();
586    }
587
588    pub fn yield_(&mut self) {
589        self.b.emit_yield();
590    }
591
592    pub fn sleep(&mut self, millis: Reg) {
593        self.b.emit_sleep(millis.0);
594    }
595
596    pub fn exit(&mut self, reg: Reg) {
597        self.b.emit_exit(reg.0);
598    }
599
600    /// Self Cap ([`CapRights::ADDRESSING`](crate::CapRights::ADDRESSING):
601    /// `SEND|ASK|LINK|MONITOR` for this flow).
602    ///
603    /// Despite the opcode name (`SelfPid`), the value is a [`crate::Value::Cap`],
604    /// not a Pid. In BEAM terms this is closer to a **reply address** grant
605    /// than to `self()` — use [`Self::hop_sender`] on a *delivered* hop for
606    /// authenticated origin identity.
607    pub fn self_cap(&mut self) -> Reg {
608        let cap = self.local();
609        self.b.emit_self_pid(cap.0);
610        cap
611    }
612
613    /// Alias for [`Self::self_cap`] — preferred name when coming from BEAM.
614    pub fn self_address(&mut self) -> Reg {
615        self.self_cap()
616    }
617
618    /// Spawn `function` with `args` packed into `r[cap+1 .. cap+1+argc]`.
619    ///
620    /// The ISA writes the child Cap into `r[cap]` and reads arguments from
621    /// the following slots — not from the registers you just `load_*`'d.
622    /// This allocates that window and copies `args` into it.
623    pub fn spawn(&mut self, function: FuncId, args: &[Reg]) -> Reg {
624        self.spawn_with_rights(function, args, crate::bytecode::CapRights::FLOW)
625    }
626
627    /// Spawn a child that receives only `rights` ⊆ parent authority.
628    pub fn spawn_with_rights(
629        &mut self,
630        function: FuncId,
631        args: &[Reg],
632        rights: crate::bytecode::CapRights,
633    ) -> Reg {
634        let Some(argc) = u8::try_from(args.len()).ok() else {
635            return self.fail_pack();
636        };
637        let Some(window) = argc.checked_add(1) else {
638            return self.fail_pack();
639        };
640        let Some(cap) = self.alloc_contig(window) else {
641            return self.fail_pack();
642        };
643        self.copy_window(Reg(cap.0.saturating_add(1)), args);
644        self.b.emit_spawn_with_rights(cap.0, function, argc, rights);
645        cap
646    }
647
648    /// Spawn with `rights = NONE` (confined by default).
649    pub fn spawn_confined(&mut self, function: FuncId, args: &[Reg]) -> Reg {
650        self.spawn_with_rights(function, args, crate::bytecode::CapRights::NONE)
651    }
652
653    /// Spawn into an explicit destination. Args must already sit in
654    /// `r[dst+1 .. dst+1+argc]` (see [`Self::window`]). Prefer [`Self::spawn`].
655    pub fn spawn_at(&mut self, dst: Reg, function: FuncId, argc: u8) {
656        self.b.emit_spawn(dst.0, function, argc);
657    }
658
659    /// Spawn into `dst` with an explicit rights mask. Same packing contract
660    /// as [`Self::spawn_at`].
661    pub fn spawn_at_with_rights(
662        &mut self,
663        dst: Reg,
664        function: FuncId,
665        argc: u8,
666        rights: crate::bytecode::CapRights,
667    ) {
668        self.b.emit_spawn_with_rights(dst.0, function, argc, rights);
669    }
670
671    /// Attenuate `src` into a new Cap (rights mask is an immediate).
672    /// Native mask is unchanged (`Delegate.c = 255`).
673    pub fn delegate(&mut self, src: Reg, rights: crate::bytecode::CapRights) -> Reg {
674        let dst = self.local();
675        self.b.emit_delegate(dst.0, src.0, rights);
676        dst
677    }
678
679    /// Like [`Self::delegate`], but AND the native mask from `native_cap`
680    /// (`Delegate.c` is that register, not 255). `native_cap` must carry
681    /// [`crate::CapRights::NATIVE`].
682    pub fn delegate_with_native(
683        &mut self,
684        src: Reg,
685        rights: crate::bytecode::CapRights,
686        native_cap: Reg,
687    ) -> Reg {
688        let dst = self.local();
689        self.b
690            .emit_delegate_with_native(dst.0, src.0, rights, Some(native_cap.0));
691        dst
692    }
693
694    pub fn send(&mut self, target_cap: Reg, msg: Reg) {
695        self.b.emit_send(target_cap.0, msg.0);
696    }
697
698    /// Fire-and-forget hop (BEAM `!` / `gen_server:cast`).
699    pub fn cast(&mut self, target_cap: Reg, msg: Reg) {
700        self.send(target_cap, msg);
701    }
702
703    pub fn receive(&mut self) -> Reg {
704        let msg = self.local();
705        self.b.emit_receive(msg.0);
706        msg
707    }
708
709    pub fn receive_timeout(&mut self, millis: Reg) -> Reg {
710        let msg = self.local();
711        self.b.emit_receive_timeout(msg.0, millis.0);
712        msg
713    }
714
715    pub fn receive_match(&mut self, tag: Reg) -> Reg {
716        let msg = self.local();
717        self.b.emit_receive_match(msg.0, tag.0);
718        msg
719    }
720
721    pub fn receive_match_imm(&mut self, tag: u16) -> Reg {
722        let msg = self.local();
723        self.b.emit_receive_match_imm(msg.0, tag);
724        msg
725    }
726
727    /// Selective receive with BEAM `after`: `Unit` if `millis` elapses first.
728    pub fn receive_match_timeout(&mut self, tag: Reg, millis: Reg) -> Reg {
729        let msg = self.local();
730        self.b.emit_receive_match_timeout(msg.0, tag.0, millis.0);
731        msg
732    }
733
734    /// Immediate-tag selective receive with BEAM `after`.
735    pub fn receive_match_imm_timeout(&mut self, tag: u16, millis: Reg) -> Reg {
736        let msg = self.local();
737        self.b.emit_receive_match_imm_timeout(msg.0, tag, millis.0);
738        msg
739    }
740
741    /// BEAM `is_process_alive/1` for a Cap this flow holds.
742    pub fn is_alive(&mut self, cap: Reg) -> Reg {
743        let dst = self.local();
744        self.b.emit_is_alive(dst.0, cap.0);
745        dst
746    }
747
748    /// BEAM `exit/2`. `reason` is a [`crate::FlowExitReason`] as `Int` (`0..=6`).
749    /// Needs `LINK` on `cap`. `Normal` does nothing. `Killed` ignores `trap_exit`.
750    pub fn exit_signal(&mut self, cap: Reg, reason: Reg) {
751        self.b.emit_exit_signal(cap.0, reason.0);
752    }
753
754    /// Process dictionary `put/2`. Returns the previous value or `Unit`.
755    /// The value is a scalar, `Str`, or `Bytes`. Heap values stay charged
756    /// after the source register is overwritten.
757    pub fn dict_put(&mut self, key: Reg, value: Reg) -> Reg {
758        let dst = self.local();
759        self.b.emit_dict_put(dst.0, key.0, value.0);
760        dst
761    }
762
763    /// Process dictionary `get/1`. Missing key → `Unit`.
764    pub fn dict_get(&mut self, key: Reg) -> Reg {
765        let dst = self.local();
766        self.b.emit_dict_get(dst.0, key.0);
767        dst
768    }
769
770    /// Process dictionary `erase/1`. Returns the removed value or `Unit`.
771    pub fn dict_erase(&mut self, key: Reg) -> Reg {
772        let dst = self.local();
773        self.b.emit_dict_erase(dst.0, key.0);
774        dst
775    }
776
777    /// Selective receive: tag and an `Int` payload compared with `bound`.
778    ///
779    /// `Eq`, `Lt`, and `Le` use signed integers. A hop whose payload is not
780    /// that `Int`, or that fails the comparison, stays in the mailbox.
781    pub fn receive_match_cmp(&mut self, tag: Reg, bound: Reg, cmp: crate::bytecode::IntCmp) -> Reg {
782        let msg = self.local();
783        self.b.emit_receive_match_cmp(msg.0, tag.0, bound.0, cmp);
784        msg
785    }
786
787    /// Selective receive: application tag **and** `Int` payload equality.
788    pub fn receive_match_eq(&mut self, tag: Reg, payload: Reg) -> Reg {
789        let msg = self.local();
790        self.b.emit_receive_match_eq(msg.0, tag.0, payload.0);
791        msg
792    }
793
794    /// Selective receive: tag **and** structural equality with `payload`.
795    ///
796    /// `payload` may be any value (`Str`, `Bytes`, `Bool`, `Float`, nested
797    /// hop). Non-matching hops stay queued.
798    pub fn receive_match_value(&mut self, tag: Reg, payload: Reg) -> Reg {
799        let msg = self.local();
800        self.b.emit_receive_match_value(msg.0, tag.0, payload.0);
801        msg
802    }
803
804    /// Deliver `msg` to `name` on `node` via [`crate::DistributionBridge`].
805    pub fn send_remote(&mut self, node: Reg, name: Reg, msg: Reg) {
806        self.b.emit_send_remote(node.0, name.0, msg.0);
807    }
808
809    /// Start a supervisor for this flow. Later [`Self::start_child`] attaches
810    /// to it. `strategy` is one-for-one, one-for-all, or rest-for-one.
811    pub fn start_supervisor(&mut self, strategy: crate::RestartStrategy) {
812        let byte = match strategy {
813            crate::RestartStrategy::OneForOne => 0,
814            crate::RestartStrategy::OneForAll => 1,
815            crate::RestartStrategy::RestForOne => 2,
816        };
817        self.b.emit_start_supervisor(byte);
818    }
819
820    /// OTP child of this flow's supervisor. Caller must have been started
821    /// by [`crate::Supervisor`]. `policy` is Always / OnFailure / Never.
822    pub fn start_child(&mut self, function: FuncId, policy: crate::RestartPolicy) -> Reg {
823        let dst = self.local();
824        self.b.emit_start_child(dst.0, function, policy.as_u8());
825        dst
826    }
827
828    /// Server loop: `receive_match_imm(tag)` → `body` → jump back.
829    pub fn actor_loop(&mut self, tag: u16, mut body: impl FnMut(&mut Self, Reg)) {
830        let loop_lbl = self.label();
831        self.bind(loop_lbl);
832        let req = self.receive_match_imm(tag);
833        body(self, req);
834        self.jump(loop_lbl);
835    }
836
837    /// Next per-flow correlation id (`Int`, starts at 1).
838    pub fn fresh_request_id(&mut self) -> Reg {
839        let dst = self.local();
840        self.b.emit_fresh_request_id(dst.0);
841        dst
842    }
843
844    /// Wait for `tag == tag_reg` and `request_id == id_reg` (FIFO skip).
845    pub fn receive_match_corr(&mut self, tag: Reg, request_id: Reg) -> Reg {
846        let msg = self.local();
847        self.b.emit_receive_match_corr(msg.0, tag.0, request_id.0);
848        msg
849    }
850
851    /// Wait for immediate `tag` and `request_id == id_reg` (FIFO skip).
852    pub fn receive_match_corr_imm(&mut self, tag: u16, request_id: Reg) -> Reg {
853        let msg = self.local();
854        self.b.emit_receive_match_corr_imm(msg.0, tag, request_id.0);
855        msg
856    }
857
858    /// Wait for a hop whose `payload.wire_tag() == kind` (`0..=10`, FIFO skip).
859    pub fn receive_match_kind(&mut self, kind: u8) -> Reg {
860        let msg = self.local();
861        self.b.emit_receive_match_kind(msg.0, kind);
862        msg
863    }
864
865    /// Build a hop with a freshly minted `request_id`.
866    ///
867    /// The id is written straight into the `make_msg` window, so the usual
868    /// copy from a temporary register is not emitted.
869    pub fn hop_fresh(&mut self, tag: i32, payload: Reg) -> Reg {
870        let w = self.window(3);
871        self.b.emit_fresh_request_id(w.at(0).0);
872        self.fill_msg_window(
873            w,
874            w.at(0),
875            tag,
876            payload,
877            crate::natives::std_native::MAKE_MSG,
878        )
879    }
880
881    /// RPC hop: deliver `msg` to `target_cap`, wait for correlated reply.
882    ///
883    /// If the target exits first, dest is a [`crate::TAG_SYS_EXIT`] hop
884    /// (not a hang).
885    pub fn ask(&mut self, target_cap: Reg, msg: Reg) -> Reg {
886        let reply = self.local();
887        self.b.emit_ask(reply.0, target_cap.0, msg.0);
888        reply
889    }
890
891    /// Like [`Self::ask`], but writes `Unit` into the dest if `millis` elapses.
892    pub fn ask_timeout(&mut self, target_cap: Reg, msg: Reg, millis: Reg) -> Reg {
893        let reply = self.local();
894        self.b
895            .emit_ask_timeout(reply.0, target_cap.0, msg.0, millis.0);
896        reply
897    }
898
899    /// One-way watch: when the flow addressed by `target_cap` exits, this
900    /// flow receives a [`crate::TAG_SYS_DOWN`] hop. Returns a monitor ref (`Int`).
901    pub fn monitor(&mut self, target_cap: Reg) -> Reg {
902        let dst = self.local();
903        self.b.emit_monitor(dst.0, target_cap.0);
904        dst
905    }
906
907    pub fn demonitor(&mut self, monitor: Reg) {
908        self.b.emit_demonitor(monitor.0);
909    }
910
911    /// Bidirectional link: without `trap_exit`, abnormal exit of either side
912    /// kills the peer. With [`Self::set_trap_exit`] on a peer, that peer gets
913    /// [`crate::TAG_SYS_EXIT`] hops instead (including `Normal`).
914    pub fn link(&mut self, target_cap: Reg) -> Reg {
915        let dst = self.local();
916        self.b.emit_link(dst.0, target_cap.0);
917        dst
918    }
919
920    pub fn unlink(&mut self, link: Reg) {
921        self.b.emit_unlink(link.0);
922    }
923
924    /// BEAM `process_flag(trap_exit, enabled)`. Truthy `enabled` converts
925    /// linked exits into [`crate::TAG_SYS_EXIT`] hops (including `Normal`)
926    /// instead of killing this flow / silently dropping the link.
927    pub fn set_trap_exit(&mut self, enabled: Reg) {
928        self.b.emit_set_trap_exit(enabled.0);
929    }
930
931    /// Set this flow's supervisor restart policy (bytecode slice of OTP
932    /// `child_spec` restart). Takes effect for the **current** incarnation;
933    /// the dying flow's policy is what the supervisor consults on exit.
934    pub fn set_restart_policy(&mut self, policy: super::RestartPolicy) {
935        self.b.emit_set_restart_policy(policy.as_u8());
936    }
937
938    /// Register a host operation and return the register that holds its ticket (`Int`).
939    ///
940    /// `op` is an opaque host discriminator (`imm`). `args` is a single
941    /// [`crate::Value`] handed to the bridge. The flow keeps running. The
942    /// host's result arrives later as a [`crate::TAG_SYS_AWAIT`] hop
943    /// (`request_id` = ticket); read it with [`Self::receive`].
944    pub fn host_await(&mut self, op: u32, args: Reg) -> Reg {
945        let dst = self.local();
946        self.b.emit_host_await(dst.0, args.0, op);
947        dst
948    }
949
950    /// Load a UTF-8 constant into a new local.
951    pub fn load_str(&mut self, s: impl AsRef<str>) -> Reg {
952        let konst = self.b.const_(Value::str(s));
953        let reg = self.local();
954        self.b.emit_load_const(reg.0, konst);
955        reg
956    }
957
958    /// Load a byte-buffer constant into a new local.
959    pub fn load_bytes(&mut self, bytes: impl AsRef<[u8]>) -> Reg {
960        let konst = self.b.const_(Value::bytes(bytes.as_ref()));
961        let reg = self.local();
962        self.b.emit_load_const(reg.0, konst);
963        reg
964    }
965
966    /// Publish `name` (`Str`) as this flow. Requires `SEND` on self-authority.
967    pub fn register_name(&mut self, name: Reg) {
968        self.b.emit_register_name(name.0);
969    }
970
971    /// Look up `name` (`Str`): SEND Cap for the caller, or `Unit`.
972    pub fn whereis(&mut self, name: Reg) -> Reg {
973        let dst = self.local();
974        self.b.emit_whereis(dst.0, name.0);
975        dst
976    }
977
978    pub fn trap(&mut self, code: i32) {
979        self.b.emit_trap(code);
980    }
981
982    /// Copy `src`, call a one-arg native, return the result in a new local.
983    ///
984    /// The source register is preserved (`CallNative` clobbers its argument slot).
985    pub fn native1_from(&mut self, src: Reg, native: u32) -> Reg {
986        let dst = self.local();
987        self.b.emit_native1_from(dst.0, src.0, native);
988        dst
989    }
990
991    /// Side-effect native on a copy of `src` (e.g. `print`).
992    pub fn native1_on(&mut self, src: Reg, native: u32) {
993        let tmp = self.local();
994        self.b.emit_native1_from(tmp.0, src.0, native);
995    }
996
997    /// `CallNative` with `argc` args already at `base..base+argc`.
998    pub fn native_n(&mut self, base: Reg, native: u32, argc: u8) {
999        self.b.emit_native_n(base.0, native, argc);
1000    }
1001
1002    /// Call a native with `argc` args already in `base..base+argc`.
1003    pub fn call_native(&mut self, base: Reg, native: u32, argc: u8) {
1004        self.native_n(base, native, argc);
1005    }
1006
1007    /// Call a zero-arg native; returns the result register.
1008    pub fn call_native0(&mut self, native: u32) -> Reg {
1009        let dst = self.local();
1010        self.b.emit_call_native(dst.0, native, 0);
1011        dst
1012    }
1013
1014    /// Build an outgoing Atomic Hop (`request_id`, `tag`, `payload`).
1015    ///
1016    /// The scheduler overwrites `sender` and attaches `reply_cap` on [`Self::send`]
1017    /// / [`Self::ask`]. Prefer [`Self::hop_fresh`] so `request_id` is unique.
1018    /// Do not forge a sender (see [`crate::docs::security`]).
1019    pub fn hop(&mut self, request_id: Reg, tag: i32, payload: Reg) -> Reg {
1020        self.make_msg(
1021            crate::natives::std_native::MAKE_MSG,
1022            request_id,
1023            tag,
1024            payload,
1025        )
1026    }
1027
1028    /// Extract authenticated origin from a delivered hop (`Value::Pid`).
1029    pub fn hop_sender(&mut self, msg: Reg) -> Reg {
1030        self.native1_from(msg, crate::natives::std_native::MSG_SENDER)
1031    }
1032
1033    pub fn hop_request_id(&mut self, msg: Reg) -> Reg {
1034        self.native1_from(msg, crate::natives::std_native::MSG_REQUEST_ID)
1035    }
1036
1037    pub fn hop_tag(&mut self, msg: Reg) -> Reg {
1038        self.native1_from(msg, crate::natives::std_native::MSG_TAG)
1039    }
1040
1041    pub fn hop_payload(&mut self, msg: Reg) -> Reg {
1042        self.native1_from(msg, crate::natives::std_native::MSG_PAYLOAD)
1043    }
1044
1045    /// Reply address grant minted for the original sender (`Value::Cap`).
1046    pub fn hop_reply_cap(&mut self, msg: Reg) -> Reg {
1047        self.native1_from(msg, crate::natives::std_native::MSG_REPLY_CAP)
1048    }
1049
1050    /// Build a reply hop echoing `request_id` from `req`.
1051    pub fn reply_to(&mut self, req: Reg, tag: i32, payload: Reg) -> Reg {
1052        let req_id = self.hop_request_id(req);
1053        self.hop(req_id, tag, payload)
1054    }
1055
1056    /// Reply to `req` via its `reply_cap` (typical server pattern).
1057    pub fn send_reply(&mut self, req: Reg, tag: i32, payload: Reg) {
1058        let reply_cap = self.hop_reply_cap(req);
1059        let reply = self.reply_to(req, tag, payload);
1060        self.send(reply_cap, reply);
1061    }
1062
1063    /// Build a [`Value::Message`] via `make_msg` at `native_index`.
1064    ///
1065    /// There is no sender operand — the scheduler stamps identity on `Send`.
1066    /// A 4-arg legacy encoding is still accepted by the native (first arg
1067    /// discarded) so forged-sender regressions keep compiling.
1068    pub fn make_msg(&mut self, native_index: u32, request_id: Reg, tag: i32, payload: Reg) -> Reg {
1069        let w = self.window(3);
1070        self.fill_msg_window(w, request_id, tag, payload, native_index)
1071    }
1072
1073    /// Pack `(request_id, tag, payload)` into `w` and call `make_msg`.
1074    ///
1075    /// A copy onto the same register is omitted, which is how
1076    /// [`Self::hop_fresh`] plants the new id in `w[0]` without a `Move`.
1077    fn fill_msg_window(
1078        &mut self,
1079        w: RegWindow,
1080        request_id: Reg,
1081        tag: i32,
1082        payload: Reg,
1083        native_index: u32,
1084    ) -> Reg {
1085        self.mov(w.at(0), request_id);
1086        self.set(w.at(1), tag);
1087        self.mov(w.at(2), payload);
1088        self.native_n(w.base(), native_index, 3);
1089        w.base()
1090    }
1091
1092    /// Legacy 4-arg `make_msg` (sender slot is ignored by the native).
1093    pub fn make_msg_legacy_sender(
1094        &mut self,
1095        native_index: u32,
1096        sender: Reg,
1097        request_id: Reg,
1098        tag: i32,
1099        payload: Reg,
1100    ) -> Reg {
1101        let w = self.window(4);
1102        self.mov(w.at(0), sender);
1103        self.mov(w.at(1), request_id);
1104        self.set(w.at(2), tag);
1105        self.mov(w.at(3), payload);
1106        self.native_n(w.base(), native_index, 4);
1107        w.base()
1108    }
1109}
1110
1111/// `r[start], r[start+1], …` with every index in `0..=254`.
1112fn contiguous_regs(regs: &[Reg]) -> bool {
1113    if regs.is_empty() {
1114        return true;
1115    }
1116    if regs.len() > 255 {
1117        return false;
1118    }
1119    let start = u16::from(regs[0].0);
1120    for (i, reg) in regs.iter().enumerate() {
1121        let expect = start + i as u16;
1122        if u16::from(reg.0) != expect || expect > 254 {
1123            return false;
1124        }
1125    }
1126    true
1127}
1128
1129/// Pairs occupy `r[start], r[start+1], r[start+2], r[start+3], …`.
1130fn contiguous_pairs(pairs: &[(Reg, Reg)]) -> bool {
1131    if pairs.is_empty() {
1132        return true;
1133    }
1134    if pairs.len() > crate::MAX_MAP_LEN {
1135        return false;
1136    }
1137    let start = u16::from(pairs[0].0 .0);
1138    for (i, (key, value)) in pairs.iter().enumerate() {
1139        let Some(step) = u16::try_from(i).ok().and_then(|n| n.checked_mul(2)) else {
1140            return false;
1141        };
1142        let Some(key_at) = start.checked_add(step) else {
1143            return false;
1144        };
1145        let Some(val_at) = key_at.checked_add(1) else {
1146            return false;
1147        };
1148        if u16::from(key.0) != key_at || u16::from(value.0) != val_at || val_at > 254 {
1149            return false;
1150        }
1151    }
1152    true
1153}
1154
1155#[cfg(test)]
1156mod tests {
1157    use super::*;
1158    use crate::{NativeTable, Value, Vm, VmResult};
1159
1160    type TestResult = Result<(), Box<dyn std::error::Error>>;
1161
1162    fn count_to(n: i64) -> Chunk {
1163        let mut program = Program::new("count");
1164        program.function("main", 0, |f| {
1165            let limit = f.load_int(n);
1166            let counter = f.load_i32(0);
1167            f.while_lt(counter, limit, |f| f.add_imm(counter, 1));
1168            f.return_(counter);
1169        });
1170        program.build()
1171    }
1172
1173    #[test]
1174    fn local_past_the_register_file_traps() {
1175        let mut program = Program::new("full");
1176        program.function("main", 0, |f| {
1177            // Arity 0 starts at r0; fill through r254, then one more.
1178            while f.next_reg < u8::MAX {
1179                let _ = f.local();
1180            }
1181            let _ = f.local();
1182        });
1183        let chunk = program.build();
1184        assert!(
1185            chunk.code.iter().any(|instr| instr.op == Opcode::Trap),
1186            "the 256th register must not alias an existing slot"
1187        );
1188    }
1189
1190    #[test]
1191    fn function_raw_keeps_declared_register_file_for_verify() -> TestResult {
1192        let mut program = Program::new("malformed");
1193        program.function_raw("main", 3, 1, |f| {
1194            let r0 = f.reg(0);
1195            f.return_(r0);
1196        });
1197        let chunk = program.build();
1198        assert_eq!(chunk.functions[0].arity, 3);
1199        assert_eq!(chunk.functions[0].num_registers, 1);
1200        assert!(matches!(
1201            crate::verify(&chunk),
1202            Err(crate::VerifyError::ArityExceedsRegisters {
1203                function: 0,
1204                arity: 3,
1205                num_registers: 1,
1206            })
1207        ));
1208        Ok(())
1209    }
1210
1211    #[test]
1212    fn add_imm_is_one_instruction_and_frame_starts_at_r0() -> TestResult {
1213        let mut program = Program::new("compact");
1214        program.function("main", 0, |f| {
1215            let n = f.load_i32(1);
1216            f.add_imm(n, 41);
1217            f.return_(n);
1218        });
1219        let chunk = program.build();
1220        assert_eq!(chunk.functions[0].num_registers, 1);
1221        assert_eq!(chunk.code.len(), 3);
1222        assert_eq!(chunk.code[0].op, Opcode::LoadImm);
1223        assert_eq!(chunk.code[0].a, 0);
1224        assert_eq!(chunk.code[1].op, Opcode::AddImm);
1225        assert_eq!(chunk.code[1].a, 0);
1226        assert_eq!(chunk.code[1].b, 0);
1227        assert_eq!(chunk.code[1].imm, 41);
1228        let mut vm = Vm::new(std::sync::Arc::new(chunk), NativeTable::empty(), 0, &[])?;
1229        assert!(matches!(vm.run(10_000), VmResult::Complete(Value::Int(42))));
1230        Ok(())
1231    }
1232
1233    #[test]
1234    fn eq_imm_and_bitwise_are_single_instructions() -> TestResult {
1235        let mut program = Program::new("bits");
1236        program.function("main", 0, |f| {
1237            let n = f.load_i32(6);
1238            f.mul_imm(n, 7);
1239            let _same = f.eq_imm(n, 42);
1240            let one = f.load_i32(1);
1241            let shifted = f.shl(n, one);
1242            let _mask = f.bit_and(shifted, n);
1243            f.return_(n);
1244        });
1245        let chunk = program.build();
1246        assert!(chunk.code.iter().any(|instr| instr.op == Opcode::MulImm));
1247        assert!(chunk.code.iter().any(|instr| instr.op == Opcode::EqImm));
1248        assert!(chunk.code.iter().any(|instr| instr.op == Opcode::Shl));
1249        assert!(chunk.code.iter().any(|instr| instr.op == Opcode::BitAnd));
1250        assert!(!chunk
1251            .code
1252            .iter()
1253            .any(|instr| instr.op == Opcode::LoadImm && instr.imm == 42));
1254        let mut vm = Vm::new(std::sync::Arc::new(chunk), NativeTable::empty(), 0, &[])?;
1255        assert!(matches!(vm.run(10_000), VmResult::Complete(Value::Int(42))));
1256        Ok(())
1257    }
1258
1259    #[test]
1260    fn count_loop_returns_n() -> TestResult {
1261        let chunk = count_to(100);
1262        let mut vm = Vm::new(std::sync::Arc::new(chunk), NativeTable::empty(), 0, &[])?;
1263        assert!(matches!(
1264            vm.run(10_000),
1265            VmResult::Complete(Value::Int(100))
1266        ));
1267        Ok(())
1268    }
1269
1270    #[test]
1271    fn ping_pong_shape() -> TestResult {
1272        let chunk = crate::samples::ping_pong();
1273        crate::verify(&chunk)?;
1274        assert!(chunk.functions.iter().any(|f| f.name == "main"));
1275        assert!(chunk.functions.iter().any(|f| f.name == "pong"));
1276        Ok(())
1277    }
1278
1279    #[test]
1280    fn call_passes_loaded_ints() -> TestResult {
1281        let mut program = Program::new("call-args");
1282        let add = program.function("add", 2, |f| {
1283            let a = f.reg(0);
1284            let b = f.reg(1);
1285            let sum = f.add(a, b);
1286            f.return_(sum);
1287        });
1288        let main = program.function("main", 0, |f| {
1289            let a = f.load_i32(10);
1290            let b = f.load_i32(32);
1291            let out = f.call(add, &[a, b]);
1292            f.return_(out);
1293        });
1294        let chunk = program.build();
1295        crate::verify(&chunk)?;
1296        let mut vm = Vm::new(std::sync::Arc::new(chunk), NativeTable::empty(), main, &[])?;
1297        assert!(matches!(vm.run(10_000), VmResult::Complete(Value::Int(42))));
1298        Ok(())
1299    }
1300
1301    #[test]
1302    fn spawn_gathers_loaded_ints() -> TestResult {
1303        let mut program = Program::new("spawn-args");
1304        let child = program.function("child", 2, |f| {
1305            let a = f.reg(0);
1306            f.return_(a);
1307        });
1308        let main = program.function("main", 0, |f| {
1309            let a = f.load_i32(10);
1310            let b = f.load_i32(32);
1311            let _cap = f.spawn(child, &[a, b]);
1312            f.halt();
1313        });
1314        let chunk = program.build();
1315        crate::verify(&chunk)?;
1316        let mut vm = Vm::new(std::sync::Arc::new(chunk), NativeTable::empty(), main, &[])?;
1317        match vm.run(10_000) {
1318            VmResult::Spawn { function, args, .. } => {
1319                assert_eq!(function, child);
1320                assert_eq!(args, vec![Value::Int(10), Value::Int(32)]);
1321            }
1322            other => return Err(format!("expected Spawn, got {other:?}").into()),
1323        }
1324        Ok(())
1325    }
1326
1327    #[test]
1328    fn delegate_with_native_sets_c() -> TestResult {
1329        let mut program = Program::new("delegate-native");
1330        program.function("main", 0, |f| {
1331            let src = f.self_cap();
1332            let native = f.self_cap();
1333            let _rights_only = f.delegate(src, crate::bytecode::CapRights::SEND);
1334            let _narrowed = f.delegate_with_native(src, crate::bytecode::CapRights::SEND, native);
1335            f.return_(src);
1336        });
1337        let chunk = program.build();
1338        let delegates: Vec<_> = chunk
1339            .code
1340            .iter()
1341            .filter(|i| i.op == Opcode::Delegate)
1342            .collect();
1343        assert_eq!(delegates.len(), 2);
1344        assert_eq!(delegates[0].c, 255);
1345        assert_ne!(delegates[1].c, 255);
1346        Ok(())
1347    }
1348
1349    #[test]
1350    fn list_and_map_pack_refuse_a_hole() {
1351        let mut program = Program::new("hole");
1352        program.function("main", 0, |f| {
1353            let a = f.load_i32(1);
1354            let b = f.load_i32(2);
1355            let c = f.load_i32(3);
1356            let _ = f.list_pack(&[a, c]);
1357            let _ = f.record_pack(&[a, c]);
1358            let k2 = f.load_i32(4);
1359            let v2 = f.load_i32(5);
1360            let _ = f.map_pack(&[(a, b), (k2, v2)]);
1361            f.return_(b);
1362        });
1363        let chunk = program.build();
1364        assert!(chunk.code.iter().any(|instr| instr.op == Opcode::Trap));
1365        assert!(chunk.code.iter().all(|instr| !matches!(
1366            instr.op,
1367            Opcode::ListPack | Opcode::RecordPack | Opcode::MapPack
1368        )));
1369    }
1370
1371    #[test]
1372    fn contiguous_pack_still_emits_the_window() -> TestResult {
1373        let mut program = Program::new("packed");
1374        program.function("main", 0, |f| {
1375            let a = f.load_i32(1);
1376            let b = f.load_i32(2);
1377            let packed = f.list_pack(&[a, b]);
1378            f.return_(packed);
1379        });
1380        let chunk = program.build();
1381        crate::verify(&chunk)?;
1382        assert!(chunk.code.iter().any(|instr| instr.op == Opcode::ListPack));
1383        Ok(())
1384    }
1385
1386    #[test]
1387    fn spawn_window_that_does_not_fit_traps_once() {
1388        let mut program = Program::new("edge");
1389        let child = program.function("child", 0, |f| {
1390            let n = f.load_i32(1);
1391            f.return_(n);
1392        });
1393        program.function("main", 0, |f| {
1394            while f.next_reg < 254 {
1395                let _ = f.local();
1396            }
1397            let arg = f.reg(0);
1398            let _ = f.spawn(child, &[arg]);
1399            f.halt();
1400        });
1401        let chunk = program.build();
1402        let traps = chunk
1403            .code
1404            .iter()
1405            .filter(|instr| instr.op == Opcode::Trap)
1406            .count();
1407        assert_eq!(traps, 1);
1408        assert!(chunk.code.iter().all(|instr| instr.op != Opcode::Spawn));
1409    }
1410
1411    #[test]
1412    fn window_past_the_file_does_not_grow_the_frame() {
1413        let mut program = Program::new("window");
1414        program.function("main", 0, |f| {
1415            while f.next_reg < 254 {
1416                let _ = f.local();
1417            }
1418            let _ = f.window(2);
1419            f.halt();
1420        });
1421        let chunk = program.build();
1422        let main = chunk.functions.iter().find(|def| def.name == "main");
1423        assert_eq!(main.map(|def| def.num_registers), Some(254));
1424        let traps = chunk
1425            .code
1426            .iter()
1427            .filter(|instr| instr.op == Opcode::Trap)
1428            .count();
1429        assert_eq!(traps, 1);
1430    }
1431}