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