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