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    pub fn window(&mut self, count: u8) -> RegWindow {
185        let base_idx = self.next_reg;
186        for _ in 0..count {
187            let _ = self.local();
188        }
189        RegWindow {
190            base: Reg(base_idx),
191            len: count,
192        }
193    }
194
195    /// Fresh contiguous locals `r[start .. start+count]`, or `None` if that
196    /// window would leave the `u8` register space.
197    fn alloc_contig(&mut self, count: u8) -> Option<Reg> {
198        if count == 0 {
199            return None;
200        }
201        let start = self.next_reg;
202        if u16::from(start) + u16::from(count) > 256 {
203            return None;
204        }
205        for i in 0..count {
206            let r = self.local();
207            if r.0 != start.saturating_add(i) {
208                return None;
209            }
210        }
211        Some(Reg(start))
212    }
213
214    fn copy_window(&mut self, base: Reg, args: &[Reg]) {
215        for (i, &src) in args.iter().enumerate() {
216            let slot = match u8::try_from(i) {
217                Ok(off) => Reg(base.0.saturating_add(off)),
218                Err(_) => continue,
219            };
220            if slot != src {
221                self.b.emit_move(slot.0, src.0);
222            }
223        }
224    }
225
226    /// Fail-closed pack: Trap so the VM never runs a half-built Call/Spawn.
227    fn fail_pack(&mut self) -> Reg {
228        self.b.emit_trap(0);
229        self.local()
230    }
231
232    /// Load a small immediate into a new local.
233    pub fn load_i32(&mut self, n: i32) -> Reg {
234        let reg = self.local();
235        self.b.emit_load_imm(reg.0, n);
236        reg
237    }
238
239    /// Load a constant-pool integer into a new local.
240    pub fn load_int(&mut self, n: i64) -> Reg {
241        let konst = self.b.const_(Value::Int(n));
242        let reg = self.local();
243        self.b.emit_load_const(reg.0, konst);
244        reg
245    }
246
247    /// Store an immediate into an existing register.
248    pub fn set(&mut self, reg: Reg, imm: i32) {
249        self.b.emit_load_imm(reg.0, imm);
250    }
251
252    /// `dst = src`
253    pub fn mov(&mut self, dst: Reg, src: Reg) {
254        self.b.emit_move(dst.0, src.0);
255    }
256
257    fn binop(&mut self, op: Opcode, lhs: Reg, rhs: Reg) -> Reg {
258        let dst = self.local();
259        self.b.emit_binop(op, dst.0, lhs.0, rhs.0);
260        dst
261    }
262
263    /// `dst = lhs + rhs` into a new local.
264    pub fn add(&mut self, lhs: Reg, rhs: Reg) -> Reg {
265        self.binop(Opcode::Add, lhs, rhs)
266    }
267
268    /// `dst += imm` in place. One [`Opcode::AddImm`], no scratch register.
269    pub fn add_imm(&mut self, dst: Reg, imm: i32) {
270        self.b.emit_add_imm(dst.0, dst.0, imm);
271    }
272
273    /// `dst -= imm` in place. One [`Opcode::SubImm`].
274    pub fn sub_imm(&mut self, dst: Reg, imm: i32) {
275        self.b.emit_sub_imm(dst.0, dst.0, imm);
276    }
277
278    /// `lhs < imm` as `Bool`, in a fresh local. One [`Opcode::LtImm`].
279    pub fn lt_imm(&mut self, lhs: Reg, imm: i32) -> Reg {
280        let dst = self.local();
281        self.b.emit_lt_imm(dst.0, lhs.0, imm);
282        dst
283    }
284
285    /// `dst *= imm` in place. One [`Opcode::MulImm`]. Integer multiply wraps.
286    pub fn mul_imm(&mut self, dst: Reg, imm: i32) {
287        self.b.emit_mul_imm(dst.0, dst.0, imm);
288    }
289
290    /// `lhs <= imm` as `Bool`, in a fresh local. One [`Opcode::LeImm`].
291    pub fn le_imm(&mut self, lhs: Reg, imm: i32) -> Reg {
292        let dst = self.local();
293        self.b.emit_le_imm(dst.0, lhs.0, imm);
294        dst
295    }
296
297    /// `lhs & rhs` into a new local. Both operands must be `Int` at runtime.
298    pub fn bit_and(&mut self, lhs: Reg, rhs: Reg) -> Reg {
299        self.bitop(Opcode::BitAnd, lhs, rhs)
300    }
301
302    /// `lhs | rhs` into a new local.
303    pub fn bit_or(&mut self, lhs: Reg, rhs: Reg) -> Reg {
304        self.bitop(Opcode::BitOr, lhs, rhs)
305    }
306
307    /// `lhs ^ rhs` into a new local.
308    pub fn bit_xor(&mut self, lhs: Reg, rhs: Reg) -> Reg {
309        self.bitop(Opcode::BitXor, lhs, rhs)
310    }
311
312    /// `!src` into a new local.
313    pub fn bit_not(&mut self, src: Reg) -> Reg {
314        let dst = self.local();
315        self.b.emit_bit_not(dst.0, src.0);
316        dst
317    }
318
319    /// `lhs << rhs` into a new local. The count keeps its low 6 bits.
320    pub fn shl(&mut self, lhs: Reg, rhs: Reg) -> Reg {
321        self.bitop(Opcode::Shl, lhs, rhs)
322    }
323
324    /// Arithmetic `lhs >> rhs` into a new local. The count keeps its low 6 bits.
325    pub fn shr(&mut self, lhs: Reg, rhs: Reg) -> Reg {
326        self.bitop(Opcode::Shr, lhs, rhs)
327    }
328
329    fn bitop(&mut self, op: Opcode, lhs: Reg, rhs: Reg) -> Reg {
330        let dst = self.local();
331        self.b.emit_bit_binop(op, dst.0, lhs.0, rhs.0);
332        dst
333    }
334
335    /// Pack `items` into a new list local. `items` must already be contiguous
336    /// registers (`rN, rN+1, …`) and at most 32 long.
337    pub fn list_pack(&mut self, items: &[Reg]) -> Reg {
338        let dst = self.local();
339        let base = match items.first() {
340            Some(reg) => reg.0,
341            None => 0,
342        };
343        self.b.emit_list_pack(dst.0, base, items.len() as i32);
344        dst
345    }
346
347    pub fn list_get(&mut self, list: Reg, index: i32) -> Reg {
348        let dst = self.local();
349        self.b.emit_list_get(dst.0, list.0, index);
350        dst
351    }
352
353    pub fn list_len(&mut self, list: Reg) -> Reg {
354        let dst = self.local();
355        self.b.emit_list_len(dst.0, list.0);
356        dst
357    }
358
359    /// Pack `pairs` into a map. Each pair is `(key, value)` already in
360    /// registers. Keys are `Int` or `Str`. At most 32 pairs.
361    pub fn map_pack(&mut self, pairs: &[(Reg, Reg)]) -> Reg {
362        let dst = self.local();
363        let base = match pairs.first() {
364            Some((key, _)) => key.0,
365            None => 0,
366        };
367        self.b.emit_map_pack(dst.0, base, pairs.len() as i32);
368        dst
369    }
370
371    pub fn map_get(&mut self, map: Reg, key: Reg) -> Reg {
372        let dst = self.local();
373        self.b.emit_map_get(dst.0, map.0, key.0);
374        dst
375    }
376
377    pub fn map_len(&mut self, map: Reg) -> Reg {
378        let dst = self.local();
379        self.b.emit_map_len(dst.0, map.0);
380        dst
381    }
382
383    /// Open this flow's table and return its Cap (`SEND` and `RECV`).
384    pub fn table_open(&mut self, name: Reg) -> Reg {
385        let dst = self.local();
386        self.b.emit_table_open(dst.0, name.0);
387        dst
388    }
389
390    /// Read `key` from `table`. Missing key yields `Unit`.
391    pub fn table_get(&mut self, table: Reg, key: Reg) -> Reg {
392        let dst = self.local();
393        self.b.emit_table_get(dst.0, table.0, key.0);
394        dst
395    }
396
397    /// Store `value` at `key` in `table`.
398    pub fn table_put(&mut self, table: Reg, key: Reg, value: Reg) {
399        self.b.emit_table_put(table.0, key.0, value.0);
400    }
401
402    pub fn sub(&mut self, lhs: Reg, rhs: Reg) -> Reg {
403        self.binop(Opcode::Sub, lhs, rhs)
404    }
405
406    pub fn mul(&mut self, lhs: Reg, rhs: Reg) -> Reg {
407        self.binop(Opcode::Mul, lhs, rhs)
408    }
409
410    pub fn div(&mut self, lhs: Reg, rhs: Reg) -> Reg {
411        self.binop(Opcode::Div, lhs, rhs)
412    }
413
414    pub fn modulo(&mut self, lhs: Reg, rhs: Reg) -> Reg {
415        self.binop(Opcode::Mod, lhs, rhs)
416    }
417
418    pub fn neg(&mut self, src: Reg) -> Reg {
419        let dst = self.local();
420        self.b.emit_neg(dst.0, src.0);
421        dst
422    }
423
424    pub fn eq(&mut self, lhs: Reg, rhs: Reg) -> Reg {
425        self.binop(Opcode::Eq, lhs, rhs)
426    }
427
428    /// `lhs == imm` as `Bool`, in a fresh local. One [`Opcode::EqImm`].
429    ///
430    /// The immediate is an `Int`. A float in `lhs` compares unequal.
431    pub fn eq_imm(&mut self, lhs: Reg, imm: i32) -> Reg {
432        let dst = self.local();
433        self.b.emit_eq_imm(dst.0, lhs.0, imm);
434        dst
435    }
436
437    pub fn lt(&mut self, lhs: Reg, rhs: Reg) -> Reg {
438        self.binop(Opcode::Lt, lhs, rhs)
439    }
440
441    pub fn le(&mut self, lhs: Reg, rhs: Reg) -> Reg {
442        self.binop(Opcode::Le, lhs, rhs)
443    }
444
445    /// While `counter < limit` (interpreter `Branch` skips on falsy).
446    pub fn while_lt<F>(&mut self, counter: Reg, limit: Reg, body: F)
447    where
448        F: FnOnce(&mut Fn<'_>),
449    {
450        let head = self.b.new_label();
451        let done = self.b.new_label();
452        let cond = self.local();
453        self.b.bind_label(head);
454        self.b.emit_binop(Opcode::Lt, cond.0, counter.0, limit.0);
455        self.b.emit_branch(cond.0, done);
456        body(self);
457        self.b.emit_jump(head);
458        self.b.bind_label(done);
459    }
460
461    pub fn label(&mut self) -> Label {
462        self.b.new_label()
463    }
464
465    pub fn bind(&mut self, label: Label) {
466        self.b.bind_label(label);
467    }
468
469    pub fn move_reg(&mut self, dst: Reg, src: Reg) {
470        self.b.emit_move(dst.0, src.0);
471    }
472
473    pub fn jump(&mut self, label: Label) {
474        self.b.emit_jump(label);
475    }
476
477    /// Branch when `cond` is falsy (`0`).
478    pub fn branch_if_falsy(&mut self, cond: Reg, target: Label) {
479        self.b.emit_branch(cond.0, target);
480    }
481
482    pub fn return_(&mut self, value: Reg) {
483        self.b.emit_return(value.0);
484    }
485
486    /// Call `function` with `args` packed into a fresh `Call` window.
487    ///
488    /// The ISA reads `r[dst .. dst+argc]` and writes the result to `r[dst]`.
489    /// This copies `args` into that window so `call(fn, &[a, b])` after
490    /// `load_i32` actually passes those values — a bare argc does not.
491    pub fn call(&mut self, function: FuncId, args: &[Reg]) -> Reg {
492        let Some(argc) = u8::try_from(args.len()).ok() else {
493            return self.fail_pack();
494        };
495        let dst = if argc == 0 {
496            self.local()
497        } else {
498            match self.alloc_contig(argc) {
499                Some(base) => {
500                    self.copy_window(base, args);
501                    base
502                }
503                None => return self.fail_pack(),
504            }
505        };
506        self.b.emit_call(dst.0, function, argc);
507        dst
508    }
509
510    pub fn halt(&mut self) {
511        self.b.emit_halt();
512    }
513
514    pub fn yield_(&mut self) {
515        self.b.emit_yield();
516    }
517
518    pub fn sleep(&mut self, millis: Reg) {
519        self.b.emit_sleep(millis.0);
520    }
521
522    pub fn exit(&mut self, reg: Reg) {
523        self.b.emit_exit(reg.0);
524    }
525
526    /// Self Cap ([`CapRights::ADDRESSING`](crate::CapRights::ADDRESSING):
527    /// `SEND|ASK|LINK|MONITOR` for this flow).
528    ///
529    /// Despite the opcode name (`SelfPid`), the value is a [`crate::Value::Cap`],
530    /// not a Pid. In BEAM terms this is closer to a **reply address** grant
531    /// than to `self()` — use [`Self::hop_sender`] on a *delivered* hop for
532    /// authenticated origin identity.
533    pub fn self_cap(&mut self) -> Reg {
534        let cap = self.local();
535        self.b.emit_self_pid(cap.0);
536        cap
537    }
538
539    /// Alias for [`Self::self_cap`] — preferred name when coming from BEAM.
540    pub fn self_address(&mut self) -> Reg {
541        self.self_cap()
542    }
543
544    /// Spawn `function` with `args` packed into `r[cap+1 .. cap+1+argc]`.
545    ///
546    /// The ISA writes the child Cap into `r[cap]` and reads arguments from
547    /// the following slots — not from the registers you just `load_*`'d.
548    /// This allocates that window and copies `args` into it.
549    pub fn spawn(&mut self, function: FuncId, args: &[Reg]) -> Reg {
550        self.spawn_with_rights(function, args, crate::bytecode::CapRights::FLOW)
551    }
552
553    /// Spawn a child that receives only `rights` ⊆ parent authority.
554    pub fn spawn_with_rights(
555        &mut self,
556        function: FuncId,
557        args: &[Reg],
558        rights: crate::bytecode::CapRights,
559    ) -> Reg {
560        let Some(argc) = u8::try_from(args.len()).ok() else {
561            return self.fail_pack();
562        };
563        let Some(window) = argc.checked_add(1) else {
564            return self.fail_pack();
565        };
566        let Some(cap) = self.alloc_contig(window) else {
567            return self.fail_pack();
568        };
569        self.copy_window(Reg(cap.0.saturating_add(1)), args);
570        self.b.emit_spawn_with_rights(cap.0, function, argc, rights);
571        cap
572    }
573
574    /// Spawn with `rights = NONE` (confined by default).
575    pub fn spawn_confined(&mut self, function: FuncId, args: &[Reg]) -> Reg {
576        self.spawn_with_rights(function, args, crate::bytecode::CapRights::NONE)
577    }
578
579    /// Spawn into an explicit destination. Args must already sit in
580    /// `r[dst+1 .. dst+1+argc]` (see [`Self::window`]). Prefer [`Self::spawn`].
581    pub fn spawn_at(&mut self, dst: Reg, function: FuncId, argc: u8) {
582        self.b.emit_spawn(dst.0, function, argc);
583    }
584
585    /// Spawn into `dst` with an explicit rights mask. Same packing contract
586    /// as [`Self::spawn_at`].
587    pub fn spawn_at_with_rights(
588        &mut self,
589        dst: Reg,
590        function: FuncId,
591        argc: u8,
592        rights: crate::bytecode::CapRights,
593    ) {
594        self.b.emit_spawn_with_rights(dst.0, function, argc, rights);
595    }
596
597    /// Attenuate `src` into a new Cap (rights mask is an immediate).
598    /// Native mask is unchanged (`Delegate.c = 255`).
599    pub fn delegate(&mut self, src: Reg, rights: crate::bytecode::CapRights) -> Reg {
600        let dst = self.local();
601        self.b.emit_delegate(dst.0, src.0, rights);
602        dst
603    }
604
605    /// Like [`Self::delegate`], but AND the native mask from `native_cap`
606    /// (`Delegate.c` is that register, not 255). `native_cap` must carry
607    /// [`crate::CapRights::NATIVE`].
608    pub fn delegate_with_native(
609        &mut self,
610        src: Reg,
611        rights: crate::bytecode::CapRights,
612        native_cap: Reg,
613    ) -> Reg {
614        let dst = self.local();
615        self.b
616            .emit_delegate_with_native(dst.0, src.0, rights, Some(native_cap.0));
617        dst
618    }
619
620    pub fn send(&mut self, target_cap: Reg, msg: Reg) {
621        self.b.emit_send(target_cap.0, msg.0);
622    }
623
624    /// Fire-and-forget hop (BEAM `!` / `gen_server:cast`).
625    pub fn cast(&mut self, target_cap: Reg, msg: Reg) {
626        self.send(target_cap, msg);
627    }
628
629    pub fn receive(&mut self) -> Reg {
630        let msg = self.local();
631        self.b.emit_receive(msg.0);
632        msg
633    }
634
635    pub fn receive_timeout(&mut self, millis: Reg) -> Reg {
636        let msg = self.local();
637        self.b.emit_receive_timeout(msg.0, millis.0);
638        msg
639    }
640
641    pub fn receive_match(&mut self, tag: Reg) -> Reg {
642        let msg = self.local();
643        self.b.emit_receive_match(msg.0, tag.0);
644        msg
645    }
646
647    pub fn receive_match_imm(&mut self, tag: u16) -> Reg {
648        let msg = self.local();
649        self.b.emit_receive_match_imm(msg.0, tag);
650        msg
651    }
652
653    /// Selective receive with BEAM `after`: `Unit` if `millis` elapses first.
654    pub fn receive_match_timeout(&mut self, tag: Reg, millis: Reg) -> Reg {
655        let msg = self.local();
656        self.b.emit_receive_match_timeout(msg.0, tag.0, millis.0);
657        msg
658    }
659
660    /// Immediate-tag selective receive with BEAM `after`.
661    pub fn receive_match_imm_timeout(&mut self, tag: u16, millis: Reg) -> Reg {
662        let msg = self.local();
663        self.b.emit_receive_match_imm_timeout(msg.0, tag, millis.0);
664        msg
665    }
666
667    /// BEAM `is_process_alive/1` for a Cap this flow holds.
668    pub fn is_alive(&mut self, cap: Reg) -> Reg {
669        let dst = self.local();
670        self.b.emit_is_alive(dst.0, cap.0);
671        dst
672    }
673
674    /// BEAM `exit/2`. `reason` is a [`crate::FlowExitReason`] as `Int` (`0..=6`).
675    /// Needs `LINK` on `cap`. `Normal` does nothing. `Killed` ignores `trap_exit`.
676    pub fn exit_signal(&mut self, cap: Reg, reason: Reg) {
677        self.b.emit_exit_signal(cap.0, reason.0);
678    }
679
680    /// Process dictionary `put/2`. Returns the previous value or `Unit`.
681    /// The value is a scalar, `Str`, or `Bytes`. Heap values stay charged
682    /// after the source register is overwritten.
683    pub fn dict_put(&mut self, key: Reg, value: Reg) -> Reg {
684        let dst = self.local();
685        self.b.emit_dict_put(dst.0, key.0, value.0);
686        dst
687    }
688
689    /// Process dictionary `get/1`. Missing key → `Unit`.
690    pub fn dict_get(&mut self, key: Reg) -> Reg {
691        let dst = self.local();
692        self.b.emit_dict_get(dst.0, key.0);
693        dst
694    }
695
696    /// Process dictionary `erase/1`. Returns the removed value or `Unit`.
697    pub fn dict_erase(&mut self, key: Reg) -> Reg {
698        let dst = self.local();
699        self.b.emit_dict_erase(dst.0, key.0);
700        dst
701    }
702
703    /// Selective receive: tag and an `Int` payload compared with `bound`.
704    ///
705    /// `Eq`, `Lt`, and `Le` use signed integers. A hop whose payload is not
706    /// that `Int`, or that fails the comparison, stays in the mailbox.
707    pub fn receive_match_cmp(&mut self, tag: Reg, bound: Reg, cmp: crate::bytecode::IntCmp) -> Reg {
708        let msg = self.local();
709        self.b.emit_receive_match_cmp(msg.0, tag.0, bound.0, cmp);
710        msg
711    }
712
713    /// Selective receive: application tag **and** `Int` payload equality.
714    pub fn receive_match_eq(&mut self, tag: Reg, payload: Reg) -> Reg {
715        let msg = self.local();
716        self.b.emit_receive_match_eq(msg.0, tag.0, payload.0);
717        msg
718    }
719
720    /// Selective receive: tag **and** structural equality with `payload`.
721    ///
722    /// `payload` may be any value (`Str`, `Bytes`, `Bool`, `Float`, nested
723    /// hop). Non-matching hops stay queued.
724    pub fn receive_match_value(&mut self, tag: Reg, payload: Reg) -> Reg {
725        let msg = self.local();
726        self.b.emit_receive_match_value(msg.0, tag.0, payload.0);
727        msg
728    }
729
730    /// Deliver `msg` to `name` on `node` via [`crate::DistributionBridge`].
731    pub fn send_remote(&mut self, node: Reg, name: Reg, msg: Reg) {
732        self.b.emit_send_remote(node.0, name.0, msg.0);
733    }
734
735    /// Start a supervisor for this flow. Later [`Self::start_child`] attaches
736    /// to it. `strategy` is one-for-one, one-for-all, or rest-for-one.
737    pub fn start_supervisor(&mut self, strategy: crate::RestartStrategy) {
738        let byte = match strategy {
739            crate::RestartStrategy::OneForOne => 0,
740            crate::RestartStrategy::OneForAll => 1,
741            crate::RestartStrategy::RestForOne => 2,
742        };
743        self.b.emit_start_supervisor(byte);
744    }
745
746    /// OTP child of this flow's supervisor. Caller must have been started
747    /// by [`crate::Supervisor`]. `policy` is Always / OnFailure / Never.
748    pub fn start_child(&mut self, function: FuncId, policy: crate::RestartPolicy) -> Reg {
749        let dst = self.local();
750        self.b.emit_start_child(dst.0, function, policy.as_u8());
751        dst
752    }
753
754    /// Server loop: `receive_match_imm(tag)` → `body` → jump back.
755    pub fn actor_loop(&mut self, tag: u16, mut body: impl FnMut(&mut Self, Reg)) {
756        let loop_lbl = self.label();
757        self.bind(loop_lbl);
758        let req = self.receive_match_imm(tag);
759        body(self, req);
760        self.jump(loop_lbl);
761    }
762
763    /// Next per-flow correlation id (`Int`, starts at 1).
764    pub fn fresh_request_id(&mut self) -> Reg {
765        let dst = self.local();
766        self.b.emit_fresh_request_id(dst.0);
767        dst
768    }
769
770    /// Wait for `tag == tag_reg` and `request_id == id_reg` (FIFO skip).
771    pub fn receive_match_corr(&mut self, tag: Reg, request_id: Reg) -> Reg {
772        let msg = self.local();
773        self.b.emit_receive_match_corr(msg.0, tag.0, request_id.0);
774        msg
775    }
776
777    /// Wait for immediate `tag` and `request_id == id_reg` (FIFO skip).
778    pub fn receive_match_corr_imm(&mut self, tag: u16, request_id: Reg) -> Reg {
779        let msg = self.local();
780        self.b.emit_receive_match_corr_imm(msg.0, tag, request_id.0);
781        msg
782    }
783
784    /// Wait for a hop whose `payload.wire_tag() == kind` (`0..=10`, FIFO skip).
785    pub fn receive_match_kind(&mut self, kind: u8) -> Reg {
786        let msg = self.local();
787        self.b.emit_receive_match_kind(msg.0, kind);
788        msg
789    }
790
791    /// Build a hop with a freshly minted `request_id`.
792    ///
793    /// The id is written straight into the `make_msg` window, so the usual
794    /// copy from a temporary register is not emitted.
795    pub fn hop_fresh(&mut self, tag: i32, payload: Reg) -> Reg {
796        let w = self.window(3);
797        self.b.emit_fresh_request_id(w.at(0).0);
798        self.fill_msg_window(
799            w,
800            w.at(0),
801            tag,
802            payload,
803            crate::natives::std_native::MAKE_MSG,
804        )
805    }
806
807    /// RPC hop: deliver `msg` to `target_cap`, wait for correlated reply.
808    ///
809    /// If the target exits first, dest is a [`crate::TAG_SYS_EXIT`] hop
810    /// (not a hang).
811    pub fn ask(&mut self, target_cap: Reg, msg: Reg) -> Reg {
812        let reply = self.local();
813        self.b.emit_ask(reply.0, target_cap.0, msg.0);
814        reply
815    }
816
817    /// Like [`Self::ask`], but writes `Unit` into the dest if `millis` elapses.
818    pub fn ask_timeout(&mut self, target_cap: Reg, msg: Reg, millis: Reg) -> Reg {
819        let reply = self.local();
820        self.b
821            .emit_ask_timeout(reply.0, target_cap.0, msg.0, millis.0);
822        reply
823    }
824
825    /// One-way watch: when the flow addressed by `target_cap` exits, this
826    /// flow receives a [`crate::TAG_SYS_DOWN`] hop. Returns a monitor ref (`Int`).
827    pub fn monitor(&mut self, target_cap: Reg) -> Reg {
828        let dst = self.local();
829        self.b.emit_monitor(dst.0, target_cap.0);
830        dst
831    }
832
833    pub fn demonitor(&mut self, monitor: Reg) {
834        self.b.emit_demonitor(monitor.0);
835    }
836
837    /// Bidirectional link: without `trap_exit`, abnormal exit of either side
838    /// kills the peer. With [`Self::set_trap_exit`] on a peer, that peer gets
839    /// [`crate::TAG_SYS_EXIT`] hops instead (including `Normal`).
840    pub fn link(&mut self, target_cap: Reg) -> Reg {
841        let dst = self.local();
842        self.b.emit_link(dst.0, target_cap.0);
843        dst
844    }
845
846    pub fn unlink(&mut self, link: Reg) {
847        self.b.emit_unlink(link.0);
848    }
849
850    /// BEAM `process_flag(trap_exit, enabled)`. Truthy `enabled` converts
851    /// linked exits into [`crate::TAG_SYS_EXIT`] hops (including `Normal`)
852    /// instead of killing this flow / silently dropping the link.
853    pub fn set_trap_exit(&mut self, enabled: Reg) {
854        self.b.emit_set_trap_exit(enabled.0);
855    }
856
857    /// Set this flow's supervisor restart policy (bytecode slice of OTP
858    /// `child_spec` restart). Takes effect for the **current** incarnation;
859    /// the dying flow's policy is what the supervisor consults on exit.
860    pub fn set_restart_policy(&mut self, policy: super::RestartPolicy) {
861        self.b.emit_set_restart_policy(policy.as_u8());
862    }
863
864    /// Register a host operation and return the register that holds its ticket (`Int`).
865    ///
866    /// `op` is an opaque host discriminator (`imm`). `args` is a single
867    /// [`crate::Value`] handed to the bridge. The flow keeps running. The
868    /// host's result arrives later as a [`crate::TAG_SYS_AWAIT`] hop
869    /// (`request_id` = ticket); read it with [`Self::receive`].
870    pub fn host_await(&mut self, op: u32, args: Reg) -> Reg {
871        let dst = self.local();
872        self.b.emit_host_await(dst.0, args.0, op);
873        dst
874    }
875
876    /// Load a UTF-8 constant into a new local.
877    pub fn load_str(&mut self, s: impl AsRef<str>) -> Reg {
878        let konst = self.b.const_(Value::str(s));
879        let reg = self.local();
880        self.b.emit_load_const(reg.0, konst);
881        reg
882    }
883
884    /// Load a byte-buffer constant into a new local.
885    pub fn load_bytes(&mut self, bytes: impl AsRef<[u8]>) -> Reg {
886        let konst = self.b.const_(Value::bytes(bytes.as_ref()));
887        let reg = self.local();
888        self.b.emit_load_const(reg.0, konst);
889        reg
890    }
891
892    /// Publish `name` (`Str`) as this flow. Requires `SEND` on self-authority.
893    pub fn register_name(&mut self, name: Reg) {
894        self.b.emit_register_name(name.0);
895    }
896
897    /// Look up `name` (`Str`): SEND Cap for the caller, or `Unit`.
898    pub fn whereis(&mut self, name: Reg) -> Reg {
899        let dst = self.local();
900        self.b.emit_whereis(dst.0, name.0);
901        dst
902    }
903
904    pub fn trap(&mut self, code: i32) {
905        self.b.emit_trap(code);
906    }
907
908    /// Copy `src`, call a one-arg native, return the result in a new local.
909    ///
910    /// The source register is preserved (`CallNative` clobbers its argument slot).
911    pub fn native1_from(&mut self, src: Reg, native: u32) -> Reg {
912        let dst = self.local();
913        self.b.emit_native1_from(dst.0, src.0, native);
914        dst
915    }
916
917    /// Side-effect native on a copy of `src` (e.g. `print`).
918    pub fn native1_on(&mut self, src: Reg, native: u32) {
919        let tmp = self.local();
920        self.b.emit_native1_from(tmp.0, src.0, native);
921    }
922
923    /// `CallNative` with `argc` args already at `base..base+argc`.
924    pub fn native_n(&mut self, base: Reg, native: u32, argc: u8) {
925        self.b.emit_native_n(base.0, native, argc);
926    }
927
928    /// Call a native with `argc` args already in `base..base+argc`.
929    pub fn call_native(&mut self, base: Reg, native: u32, argc: u8) {
930        self.native_n(base, native, argc);
931    }
932
933    /// Call a zero-arg native; returns the result register.
934    pub fn call_native0(&mut self, native: u32) -> Reg {
935        let dst = self.local();
936        self.b.emit_call_native(dst.0, native, 0);
937        dst
938    }
939
940    /// Build an outgoing Atomic Hop (`request_id`, `tag`, `payload`).
941    ///
942    /// The scheduler overwrites `sender` and attaches `reply_cap` on [`Self::send`]
943    /// / [`Self::ask`]. Prefer [`Self::hop_fresh`] so `request_id` is unique.
944    /// Do not forge a sender (see [`crate::docs::security`]).
945    pub fn hop(&mut self, request_id: Reg, tag: i32, payload: Reg) -> Reg {
946        self.make_msg(
947            crate::natives::std_native::MAKE_MSG,
948            request_id,
949            tag,
950            payload,
951        )
952    }
953
954    /// Extract authenticated origin from a delivered hop (`Value::Pid`).
955    pub fn hop_sender(&mut self, msg: Reg) -> Reg {
956        self.native1_from(msg, crate::natives::std_native::MSG_SENDER)
957    }
958
959    pub fn hop_request_id(&mut self, msg: Reg) -> Reg {
960        self.native1_from(msg, crate::natives::std_native::MSG_REQUEST_ID)
961    }
962
963    pub fn hop_tag(&mut self, msg: Reg) -> Reg {
964        self.native1_from(msg, crate::natives::std_native::MSG_TAG)
965    }
966
967    pub fn hop_payload(&mut self, msg: Reg) -> Reg {
968        self.native1_from(msg, crate::natives::std_native::MSG_PAYLOAD)
969    }
970
971    /// Reply address grant minted for the original sender (`Value::Cap`).
972    pub fn hop_reply_cap(&mut self, msg: Reg) -> Reg {
973        self.native1_from(msg, crate::natives::std_native::MSG_REPLY_CAP)
974    }
975
976    /// Build a reply hop echoing `request_id` from `req`.
977    pub fn reply_to(&mut self, req: Reg, tag: i32, payload: Reg) -> Reg {
978        let req_id = self.hop_request_id(req);
979        self.hop(req_id, tag, payload)
980    }
981
982    /// Reply to `req` via its `reply_cap` (typical server pattern).
983    pub fn send_reply(&mut self, req: Reg, tag: i32, payload: Reg) {
984        let reply_cap = self.hop_reply_cap(req);
985        let reply = self.reply_to(req, tag, payload);
986        self.send(reply_cap, reply);
987    }
988
989    /// Build a [`Value::Message`] via `make_msg` at `native_index`.
990    ///
991    /// There is no sender operand — the scheduler stamps identity on `Send`.
992    /// A 4-arg legacy encoding is still accepted by the native (first arg
993    /// discarded) so forged-sender regressions keep compiling.
994    pub fn make_msg(&mut self, native_index: u32, request_id: Reg, tag: i32, payload: Reg) -> Reg {
995        let w = self.window(3);
996        self.fill_msg_window(w, request_id, tag, payload, native_index)
997    }
998
999    /// Pack `(request_id, tag, payload)` into `w` and call `make_msg`.
1000    ///
1001    /// A copy onto the same register is omitted, which is how
1002    /// [`Self::hop_fresh`] plants the new id in `w[0]` without a `Move`.
1003    fn fill_msg_window(
1004        &mut self,
1005        w: RegWindow,
1006        request_id: Reg,
1007        tag: i32,
1008        payload: Reg,
1009        native_index: u32,
1010    ) -> Reg {
1011        self.mov(w.at(0), request_id);
1012        self.set(w.at(1), tag);
1013        self.mov(w.at(2), payload);
1014        self.native_n(w.base(), native_index, 3);
1015        w.base()
1016    }
1017
1018    /// Legacy 4-arg `make_msg` (sender slot is ignored by the native).
1019    pub fn make_msg_legacy_sender(
1020        &mut self,
1021        native_index: u32,
1022        sender: Reg,
1023        request_id: Reg,
1024        tag: i32,
1025        payload: Reg,
1026    ) -> Reg {
1027        let w = self.window(4);
1028        self.mov(w.at(0), sender);
1029        self.mov(w.at(1), request_id);
1030        self.set(w.at(2), tag);
1031        self.mov(w.at(3), payload);
1032        self.native_n(w.base(), native_index, 4);
1033        w.base()
1034    }
1035}
1036
1037#[cfg(test)]
1038mod tests {
1039    use super::*;
1040    use crate::{NativeTable, Value, Vm, VmResult};
1041
1042    type TestResult = Result<(), Box<dyn std::error::Error>>;
1043
1044    fn count_to(n: i64) -> Chunk {
1045        let mut program = Program::new("count");
1046        program.function("main", 0, |f| {
1047            let limit = f.load_int(n);
1048            let counter = f.load_i32(0);
1049            f.while_lt(counter, limit, |f| f.add_imm(counter, 1));
1050            f.return_(counter);
1051        });
1052        program.build()
1053    }
1054
1055    #[test]
1056    fn local_past_the_register_file_traps() {
1057        let mut program = Program::new("full");
1058        program.function("main", 0, |f| {
1059            // Arity 0 starts at r0; fill through r254, then one more.
1060            while f.next_reg < u8::MAX {
1061                let _ = f.local();
1062            }
1063            let _ = f.local();
1064        });
1065        let chunk = program.build();
1066        assert!(
1067            chunk.code.iter().any(|instr| instr.op == Opcode::Trap),
1068            "the 256th register must not alias an existing slot"
1069        );
1070    }
1071
1072    #[test]
1073    fn function_raw_keeps_declared_register_file_for_verify() -> TestResult {
1074        let mut program = Program::new("malformed");
1075        program.function_raw("main", 3, 1, |f| {
1076            let r0 = f.reg(0);
1077            f.return_(r0);
1078        });
1079        let chunk = program.build();
1080        assert_eq!(chunk.functions[0].arity, 3);
1081        assert_eq!(chunk.functions[0].num_registers, 1);
1082        assert!(matches!(
1083            crate::verify(&chunk),
1084            Err(crate::VerifyError::ArityExceedsRegisters {
1085                function: 0,
1086                arity: 3,
1087                num_registers: 1,
1088            })
1089        ));
1090        Ok(())
1091    }
1092
1093    #[test]
1094    fn add_imm_is_one_instruction_and_frame_starts_at_r0() -> TestResult {
1095        let mut program = Program::new("compact");
1096        program.function("main", 0, |f| {
1097            let n = f.load_i32(1);
1098            f.add_imm(n, 41);
1099            f.return_(n);
1100        });
1101        let chunk = program.build();
1102        assert_eq!(chunk.functions[0].num_registers, 1);
1103        assert_eq!(chunk.code.len(), 3);
1104        assert_eq!(chunk.code[0].op, Opcode::LoadImm);
1105        assert_eq!(chunk.code[0].a, 0);
1106        assert_eq!(chunk.code[1].op, Opcode::AddImm);
1107        assert_eq!(chunk.code[1].a, 0);
1108        assert_eq!(chunk.code[1].b, 0);
1109        assert_eq!(chunk.code[1].imm, 41);
1110        let mut vm = Vm::new(std::sync::Arc::new(chunk), NativeTable::empty(), 0, &[])?;
1111        assert!(matches!(vm.run(10_000), VmResult::Complete(Value::Int(42))));
1112        Ok(())
1113    }
1114
1115    #[test]
1116    fn eq_imm_and_bitwise_are_single_instructions() -> TestResult {
1117        let mut program = Program::new("bits");
1118        program.function("main", 0, |f| {
1119            let n = f.load_i32(6);
1120            f.mul_imm(n, 7);
1121            let _same = f.eq_imm(n, 42);
1122            let one = f.load_i32(1);
1123            let shifted = f.shl(n, one);
1124            let _mask = f.bit_and(shifted, n);
1125            f.return_(n);
1126        });
1127        let chunk = program.build();
1128        assert!(chunk.code.iter().any(|instr| instr.op == Opcode::MulImm));
1129        assert!(chunk.code.iter().any(|instr| instr.op == Opcode::EqImm));
1130        assert!(chunk.code.iter().any(|instr| instr.op == Opcode::Shl));
1131        assert!(chunk.code.iter().any(|instr| instr.op == Opcode::BitAnd));
1132        assert!(!chunk
1133            .code
1134            .iter()
1135            .any(|instr| instr.op == Opcode::LoadImm && instr.imm == 42));
1136        let mut vm = Vm::new(std::sync::Arc::new(chunk), NativeTable::empty(), 0, &[])?;
1137        assert!(matches!(vm.run(10_000), VmResult::Complete(Value::Int(42))));
1138        Ok(())
1139    }
1140
1141    #[test]
1142    fn count_loop_returns_n() -> TestResult {
1143        let chunk = count_to(100);
1144        let mut vm = Vm::new(std::sync::Arc::new(chunk), NativeTable::empty(), 0, &[])?;
1145        assert!(matches!(
1146            vm.run(10_000),
1147            VmResult::Complete(Value::Int(100))
1148        ));
1149        Ok(())
1150    }
1151
1152    #[test]
1153    fn ping_pong_shape() -> TestResult {
1154        let chunk = crate::samples::ping_pong();
1155        crate::verify(&chunk)?;
1156        assert!(chunk.functions.iter().any(|f| f.name == "main"));
1157        assert!(chunk.functions.iter().any(|f| f.name == "pong"));
1158        Ok(())
1159    }
1160
1161    #[test]
1162    fn call_passes_loaded_ints() -> TestResult {
1163        let mut program = Program::new("call-args");
1164        let add = program.function("add", 2, |f| {
1165            let a = f.reg(0);
1166            let b = f.reg(1);
1167            let sum = f.add(a, b);
1168            f.return_(sum);
1169        });
1170        let main = program.function("main", 0, |f| {
1171            let a = f.load_i32(10);
1172            let b = f.load_i32(32);
1173            let out = f.call(add, &[a, b]);
1174            f.return_(out);
1175        });
1176        let chunk = program.build();
1177        crate::verify(&chunk)?;
1178        let mut vm = Vm::new(std::sync::Arc::new(chunk), NativeTable::empty(), main, &[])?;
1179        assert!(matches!(vm.run(10_000), VmResult::Complete(Value::Int(42))));
1180        Ok(())
1181    }
1182
1183    #[test]
1184    fn spawn_gathers_loaded_ints() -> TestResult {
1185        let mut program = Program::new("spawn-args");
1186        let child = program.function("child", 2, |f| {
1187            let a = f.reg(0);
1188            f.return_(a);
1189        });
1190        let main = program.function("main", 0, |f| {
1191            let a = f.load_i32(10);
1192            let b = f.load_i32(32);
1193            let _cap = f.spawn(child, &[a, b]);
1194            f.halt();
1195        });
1196        let chunk = program.build();
1197        crate::verify(&chunk)?;
1198        let mut vm = Vm::new(std::sync::Arc::new(chunk), NativeTable::empty(), main, &[])?;
1199        match vm.run(10_000) {
1200            VmResult::Spawn { function, args, .. } => {
1201                assert_eq!(function, child);
1202                assert_eq!(args, vec![Value::Int(10), Value::Int(32)]);
1203            }
1204            other => return Err(format!("expected Spawn, got {other:?}").into()),
1205        }
1206        Ok(())
1207    }
1208
1209    #[test]
1210    fn delegate_with_native_sets_c() -> TestResult {
1211        let mut program = Program::new("delegate-native");
1212        program.function("main", 0, |f| {
1213            let src = f.self_cap();
1214            let native = f.self_cap();
1215            let _rights_only = f.delegate(src, crate::bytecode::CapRights::SEND);
1216            let _narrowed = f.delegate_with_native(src, crate::bytecode::CapRights::SEND, native);
1217            f.return_(src);
1218        });
1219        let chunk = program.build();
1220        let delegates: Vec<_> = chunk
1221            .code
1222            .iter()
1223            .filter(|i| i.op == Opcode::Delegate)
1224            .collect();
1225        assert_eq!(delegates.len(), 2);
1226        assert_eq!(delegates[0].c, 255);
1227        assert_ne!(delegates[1].c, 255);
1228        Ok(())
1229    }
1230}