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