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
465            .emit_spawn_with_rights(dst.0, function, argc, rights);
466    }
467
468    /// Attenuate `src` into a new Cap (rights mask is an immediate).
469    /// Native mask is unchanged (`Delegate.c = 255`).
470    pub fn delegate(&mut self, src: Reg, rights: crate::bytecode::CapRights) -> Reg {
471        let dst = self.local();
472        self.b.emit_delegate(dst.0, src.0, rights);
473        dst
474    }
475
476    /// Like [`Self::delegate`], but AND the native mask from `native_cap`
477    /// (`Delegate.c` is that register, not 255). `native_cap` must carry
478    /// [`crate::CapRights::NATIVE`].
479    pub fn delegate_with_native(
480        &mut self,
481        src: Reg,
482        rights: crate::bytecode::CapRights,
483        native_cap: Reg,
484    ) -> Reg {
485        let dst = self.local();
486        self.b
487            .emit_delegate_with_native(dst.0, src.0, rights, Some(native_cap.0));
488        dst
489    }
490
491    pub fn send(&mut self, target_cap: Reg, msg: Reg) {
492        self.b.emit_send(target_cap.0, msg.0);
493    }
494
495    /// Fire-and-forget hop (BEAM `!` / `gen_server:cast`).
496    pub fn cast(&mut self, target_cap: Reg, msg: Reg) {
497        self.send(target_cap, msg);
498    }
499
500    pub fn receive(&mut self) -> Reg {
501        let msg = self.local();
502        self.b.emit_receive(msg.0);
503        msg
504    }
505
506    pub fn receive_timeout(&mut self, millis: Reg) -> Reg {
507        let msg = self.local();
508        self.b.emit_receive_timeout(msg.0, millis.0);
509        msg
510    }
511
512    pub fn receive_match(&mut self, tag: Reg) -> Reg {
513        let msg = self.local();
514        self.b.emit_receive_match(msg.0, tag.0);
515        msg
516    }
517
518    pub fn receive_match_imm(&mut self, tag: u16) -> Reg {
519        let msg = self.local();
520        self.b.emit_receive_match_imm(msg.0, tag);
521        msg
522    }
523
524    /// Selective receive with BEAM `after`: `Unit` if `millis` elapses first.
525    pub fn receive_match_timeout(&mut self, tag: Reg, millis: Reg) -> Reg {
526        let msg = self.local();
527        self.b
528            .emit_receive_match_timeout(msg.0, tag.0, millis.0);
529        msg
530    }
531
532    /// Immediate-tag selective receive with BEAM `after`.
533    pub fn receive_match_imm_timeout(&mut self, tag: u16, millis: Reg) -> Reg {
534        let msg = self.local();
535        self.b
536            .emit_receive_match_imm_timeout(msg.0, tag, millis.0);
537        msg
538    }
539
540    /// BEAM `is_process_alive/1` for a Cap this flow holds.
541    pub fn is_alive(&mut self, cap: Reg) -> Reg {
542        let dst = self.local();
543        self.b.emit_is_alive(dst.0, cap.0);
544        dst
545    }
546
547    /// BEAM `exit/2`. `reason` is a [`crate::FlowExitReason`] as `Int` (`0..=6`).
548    /// Needs `LINK` on `cap`. `Normal` does nothing. `Killed` ignores `trap_exit`.
549    pub fn exit_signal(&mut self, cap: Reg, reason: Reg) {
550        self.b.emit_exit_signal(cap.0, reason.0);
551    }
552
553    /// Process dictionary `put/2`. Returns the previous value or `Unit`.
554    /// Value must be a scalar (Unit, Bool, Int, Float).
555    pub fn dict_put(&mut self, key: Reg, value: Reg) -> Reg {
556        let dst = self.local();
557        self.b.emit_dict_put(dst.0, key.0, value.0);
558        dst
559    }
560
561    /// Process dictionary `get/1`. Missing key → `Unit`.
562    pub fn dict_get(&mut self, key: Reg) -> Reg {
563        let dst = self.local();
564        self.b.emit_dict_get(dst.0, key.0);
565        dst
566    }
567
568    /// Process dictionary `erase/1`. Returns the removed value or `Unit`.
569    pub fn dict_erase(&mut self, key: Reg) -> Reg {
570        let dst = self.local();
571        self.b.emit_dict_erase(dst.0, key.0);
572        dst
573    }
574
575    /// Selective receive: application tag **and** `Int` payload equality.
576    pub fn receive_match_eq(&mut self, tag: Reg, payload: Reg) -> Reg {
577        let msg = self.local();
578        self.b.emit_receive_match_eq(msg.0, tag.0, payload.0);
579        msg
580    }
581
582    /// OTP child of this flow's supervisor. Caller must have been started
583    /// by [`crate::Supervisor`]. `policy` is Always / OnFailure / Never.
584    pub fn start_child(&mut self, function: FuncId, policy: crate::RestartPolicy) -> Reg {
585        let dst = self.local();
586        self.b
587            .emit_start_child(dst.0, function, policy.as_u8());
588        dst
589    }
590
591    /// Server loop: `receive_match_imm(tag)` → `body` → jump back.
592    pub fn actor_loop(&mut self, tag: u16, mut body: impl FnMut(&mut Self, Reg)) {
593        let loop_lbl = self.label();
594        self.bind(loop_lbl);
595        let req = self.receive_match_imm(tag);
596        body(self, req);
597        self.jump(loop_lbl);
598    }
599
600    /// Next per-flow correlation id (`Int`, starts at 1).
601    pub fn fresh_request_id(&mut self) -> Reg {
602        let dst = self.local();
603        self.b.emit_fresh_request_id(dst.0);
604        dst
605    }
606
607    /// Wait for `tag == tag_reg` and `request_id == id_reg` (FIFO skip).
608    pub fn receive_match_corr(&mut self, tag: Reg, request_id: Reg) -> Reg {
609        let msg = self.local();
610        self.b.emit_receive_match_corr(msg.0, tag.0, request_id.0);
611        msg
612    }
613
614    /// Wait for immediate `tag` and `request_id == id_reg` (FIFO skip).
615    pub fn receive_match_corr_imm(&mut self, tag: u16, request_id: Reg) -> Reg {
616        let msg = self.local();
617        self.b.emit_receive_match_corr_imm(msg.0, tag, request_id.0);
618        msg
619    }
620
621    /// Wait for a hop whose `payload.wire_tag() == kind` (`0..=8`, FIFO skip).
622    pub fn receive_match_kind(&mut self, kind: u8) -> Reg {
623        let msg = self.local();
624        self.b.emit_receive_match_kind(msg.0, kind);
625        msg
626    }
627
628    /// Build a hop with a freshly minted `request_id`.
629    pub fn hop_fresh(&mut self, tag: i32, payload: Reg) -> Reg {
630        let req_id = self.fresh_request_id();
631        self.hop(req_id, tag, payload)
632    }
633
634    /// RPC hop: deliver `msg` to `target_cap`, wait for correlated reply.
635    ///
636    /// If the target exits first, dest is a [`crate::TAG_SYS_EXIT`] hop
637    /// (not a hang).
638    pub fn ask(&mut self, target_cap: Reg, msg: Reg) -> Reg {
639        let reply = self.local();
640        self.b.emit_ask(reply.0, target_cap.0, msg.0);
641        reply
642    }
643
644    /// Like [`Self::ask`], but writes `Unit` into the dest if `millis` elapses.
645    pub fn ask_timeout(&mut self, target_cap: Reg, msg: Reg, millis: Reg) -> Reg {
646        let reply = self.local();
647        self.b
648            .emit_ask_timeout(reply.0, target_cap.0, msg.0, millis.0);
649        reply
650    }
651
652    /// One-way watch: when the flow addressed by `target_cap` exits, this
653    /// flow receives a [`crate::TAG_SYS_DOWN`] hop. Returns a monitor ref (`Int`).
654    pub fn monitor(&mut self, target_cap: Reg) -> Reg {
655        let dst = self.local();
656        self.b.emit_monitor(dst.0, target_cap.0);
657        dst
658    }
659
660    pub fn demonitor(&mut self, monitor: Reg) {
661        self.b.emit_demonitor(monitor.0);
662    }
663
664    /// Bidirectional link: without `trap_exit`, abnormal exit of either side
665    /// kills the peer. With [`Self::set_trap_exit`] on a peer, that peer gets
666    /// [`crate::TAG_SYS_EXIT`] hops instead (including `Normal`).
667    pub fn link(&mut self, target_cap: Reg) -> Reg {
668        let dst = self.local();
669        self.b.emit_link(dst.0, target_cap.0);
670        dst
671    }
672
673    pub fn unlink(&mut self, link: Reg) {
674        self.b.emit_unlink(link.0);
675    }
676
677    /// BEAM `process_flag(trap_exit, enabled)`. Truthy `enabled` converts
678    /// linked exits into [`crate::TAG_SYS_EXIT`] hops (including `Normal`)
679    /// instead of killing this flow / silently dropping the link.
680    pub fn set_trap_exit(&mut self, enabled: Reg) {
681        self.b.emit_set_trap_exit(enabled.0);
682    }
683
684    /// Set this flow's supervisor restart policy (bytecode slice of OTP
685    /// `child_spec` restart). Takes effect for the **current** incarnation;
686    /// the dying flow's policy is what the supervisor consults on exit.
687    pub fn set_restart_policy(&mut self, policy: super::RestartPolicy) {
688        self.b.emit_set_restart_policy(policy.as_u8());
689    }
690
691    /// Park until the host [`crate::HostAwaitBridge`] completes.
692    ///
693    /// `op` is an opaque host discriminator (`imm`). `args` is a single
694    /// [`crate::Value`] handed to the bridge. On success the result is
695    /// written into the returned register (Receive-style writeback).
696    pub fn host_await(&mut self, op: u32, args: Reg) -> Reg {
697        let dst = self.local();
698        self.b.emit_host_await(dst.0, args.0, op);
699        dst
700    }
701
702    /// Load a UTF-8 constant into a new local.
703    pub fn load_str(&mut self, s: impl AsRef<str>) -> Reg {
704        let konst = self.b.const_(Value::str(s));
705        let reg = self.local();
706        self.b.emit_load_const(reg.0, konst);
707        reg
708    }
709
710    /// Load a byte-buffer constant into a new local.
711    pub fn load_bytes(&mut self, bytes: impl AsRef<[u8]>) -> Reg {
712        let konst = self.b.const_(Value::bytes(bytes.as_ref()));
713        let reg = self.local();
714        self.b.emit_load_const(reg.0, konst);
715        reg
716    }
717
718    /// Publish `name` (`Str`) as this flow. Requires `SEND` on self-authority.
719    pub fn register_name(&mut self, name: Reg) {
720        self.b.emit_register_name(name.0);
721    }
722
723    /// Look up `name` (`Str`): SEND Cap for the caller, or `Unit`.
724    pub fn whereis(&mut self, name: Reg) -> Reg {
725        let dst = self.local();
726        self.b.emit_whereis(dst.0, name.0);
727        dst
728    }
729
730    pub fn trap(&mut self, code: i32) {
731        self.b.emit_trap(code);
732    }
733
734    /// Copy `src`, call a one-arg native, return the result in a new local.
735    ///
736    /// The source register is preserved (`CallNative` clobbers its argument slot).
737    pub fn native1_from(&mut self, src: Reg, native: u32) -> Reg {
738        let dst = self.local();
739        self.b.emit_native1_from(dst.0, src.0, native);
740        dst
741    }
742
743    /// Side-effect native on a copy of `src` (e.g. `print`).
744    pub fn native1_on(&mut self, src: Reg, native: u32) {
745        let tmp = self.local();
746        self.b.emit_native1_from(tmp.0, src.0, native);
747    }
748
749    /// `CallNative` with `argc` args already at `base..base+argc`.
750    pub fn native_n(&mut self, base: Reg, native: u32, argc: u8) {
751        self.b.emit_native_n(base.0, native, argc);
752    }
753
754    /// Call a native with `argc` args already in `base..base+argc`.
755    pub fn call_native(&mut self, base: Reg, native: u32, argc: u8) {
756        self.native_n(base, native, argc);
757    }
758
759    /// Call a zero-arg native; returns the result register.
760    pub fn call_native0(&mut self, native: u32) -> Reg {
761        let dst = self.local();
762        self.b.emit_call_native(dst.0, native, 0);
763        dst
764    }
765
766    /// Build an outgoing Atomic Hop (`request_id`, `tag`, `payload`).
767    ///
768    /// The scheduler overwrites `sender` and attaches `reply_cap` on [`Self::send`]
769    /// / [`Self::ask`]. Prefer [`Self::hop_fresh`] so `request_id` is unique.
770    /// Do not forge a sender (see [`crate::docs::security`]).
771    pub fn hop(&mut self, request_id: Reg, tag: i32, payload: Reg) -> Reg {
772        self.make_msg(
773            crate::natives::std_native::MAKE_MSG,
774            request_id,
775            tag,
776            payload,
777        )
778    }
779
780    /// Extract authenticated origin from a delivered hop (`Value::Pid`).
781    pub fn hop_sender(&mut self, msg: Reg) -> Reg {
782        self.native1_from(msg, crate::natives::std_native::MSG_SENDER)
783    }
784
785    pub fn hop_request_id(&mut self, msg: Reg) -> Reg {
786        self.native1_from(msg, crate::natives::std_native::MSG_REQUEST_ID)
787    }
788
789    pub fn hop_tag(&mut self, msg: Reg) -> Reg {
790        self.native1_from(msg, crate::natives::std_native::MSG_TAG)
791    }
792
793    pub fn hop_payload(&mut self, msg: Reg) -> Reg {
794        self.native1_from(msg, crate::natives::std_native::MSG_PAYLOAD)
795    }
796
797    /// Reply address grant minted for the original sender (`Value::Cap`).
798    pub fn hop_reply_cap(&mut self, msg: Reg) -> Reg {
799        self.native1_from(msg, crate::natives::std_native::MSG_REPLY_CAP)
800    }
801
802    /// Build a reply hop echoing `request_id` from `req`.
803    pub fn reply_to(&mut self, req: Reg, tag: i32, payload: Reg) -> Reg {
804        let req_id = self.hop_request_id(req);
805        self.hop(req_id, tag, payload)
806    }
807
808    /// Reply to `req` via its `reply_cap` (typical server pattern).
809    pub fn send_reply(&mut self, req: Reg, tag: i32, payload: Reg) {
810        let reply_cap = self.hop_reply_cap(req);
811        let reply = self.reply_to(req, tag, payload);
812        self.send(reply_cap, reply);
813    }
814
815    /// Build a [`Value::Message`] via `make_msg` at `native_index`.
816    ///
817    /// There is no sender operand — the scheduler stamps identity on `Send`.
818    /// A 4-arg legacy encoding is still accepted by the native (first arg
819    /// discarded) so forged-sender regressions keep compiling.
820    pub fn make_msg(&mut self, native_index: u32, request_id: Reg, tag: i32, payload: Reg) -> Reg {
821        let w = self.window(3);
822        self.mov(w.at(0), request_id);
823        self.set(w.at(1), tag);
824        self.mov(w.at(2), payload);
825        self.native_n(w.base(), native_index, 3);
826        w.base()
827    }
828
829    /// Legacy 4-arg `make_msg` (sender slot is ignored by the native).
830    pub fn make_msg_legacy_sender(
831        &mut self,
832        native_index: u32,
833        sender: Reg,
834        request_id: Reg,
835        tag: i32,
836        payload: Reg,
837    ) -> Reg {
838        let w = self.window(4);
839        self.mov(w.at(0), sender);
840        self.mov(w.at(1), request_id);
841        self.set(w.at(2), tag);
842        self.mov(w.at(3), payload);
843        self.native_n(w.base(), native_index, 4);
844        w.base()
845    }
846
847    fn temp(&mut self) -> Reg {
848        if let Some(scratch) = self.scratch {
849            return scratch;
850        }
851        let scratch = self.local();
852        self.scratch = Some(scratch);
853        scratch
854    }
855}
856
857#[cfg(test)]
858mod tests {
859    use super::*;
860    use crate::{NativeTable, Value, Vm, VmResult};
861
862    type TestResult = Result<(), Box<dyn std::error::Error>>;
863
864    fn count_to(n: i64) -> Chunk {
865        let mut program = Program::new("count");
866        program.function("main", 0, |f| {
867            let limit = f.load_int(n);
868            let counter = f.load_i32(0);
869            f.while_lt(counter, limit, |f| f.add_imm(counter, 1));
870            f.return_(counter);
871        });
872        program.build()
873    }
874
875    #[test]
876    fn local_past_the_register_file_traps() {
877        let mut program = Program::new("full");
878        program.function("main", 0, |f| {
879            // `open` starts at 4 registers; fill through r254, then one more.
880            while f.next_reg < u8::MAX {
881                let _ = f.local();
882            }
883            let _ = f.local();
884        });
885        let chunk = program.build();
886        assert!(
887            chunk.code.iter().any(|instr| instr.op == Opcode::Trap),
888            "the 256th register must not alias an existing slot"
889        );
890    }
891
892    #[test]
893    fn function_raw_keeps_declared_register_file_for_verify() -> TestResult {
894        let mut program = Program::new("malformed");
895        program.function_raw("main", 3, 1, |f| {
896            let r0 = f.reg(0);
897            f.return_(r0);
898        });
899        let chunk = program.build();
900        assert_eq!(chunk.functions[0].arity, 3);
901        assert_eq!(chunk.functions[0].num_registers, 1);
902        assert!(matches!(
903            crate::verify(&chunk),
904            Err(crate::VerifyError::ArityExceedsRegisters {
905                function: 0,
906                arity: 3,
907                num_registers: 1,
908            })
909        ));
910        Ok(())
911    }
912
913    #[test]
914    fn count_loop_returns_n() -> TestResult {
915        let chunk = count_to(100);
916        let mut vm = Vm::new(std::sync::Arc::new(chunk), NativeTable::empty(), 0, &[])?;
917        assert!(matches!(
918            vm.run(10_000),
919            VmResult::Complete(Value::Int(100))
920        ));
921        Ok(())
922    }
923
924    #[test]
925    fn ping_pong_shape() -> TestResult {
926        let chunk = crate::samples::ping_pong();
927        crate::verify(&chunk)?;
928        assert!(chunk.functions.iter().any(|f| f.name == "main"));
929        assert!(chunk.functions.iter().any(|f| f.name == "pong"));
930        Ok(())
931    }
932
933    #[test]
934    fn call_passes_loaded_ints() -> TestResult {
935        let mut program = Program::new("call-args");
936        let add = program.function("add", 2, |f| {
937            let a = f.reg(0);
938            let b = f.reg(1);
939            let sum = f.add(a, b);
940            f.return_(sum);
941        });
942        let main = program.function("main", 0, |f| {
943            let a = f.load_i32(10);
944            let b = f.load_i32(32);
945            let out = f.call(add, &[a, b]);
946            f.return_(out);
947        });
948        let chunk = program.build();
949        crate::verify(&chunk)?;
950        let mut vm = Vm::new(std::sync::Arc::new(chunk), NativeTable::empty(), main, &[])?;
951        assert!(matches!(
952            vm.run(10_000),
953            VmResult::Complete(Value::Int(42))
954        ));
955        Ok(())
956    }
957
958    #[test]
959    fn spawn_gathers_loaded_ints() -> TestResult {
960        let mut program = Program::new("spawn-args");
961        let child = program.function("child", 2, |f| {
962            let a = f.reg(0);
963            f.return_(a);
964        });
965        let main = program.function("main", 0, |f| {
966            let a = f.load_i32(10);
967            let b = f.load_i32(32);
968            let _cap = f.spawn(child, &[a, b]);
969            f.halt();
970        });
971        let chunk = program.build();
972        crate::verify(&chunk)?;
973        let mut vm = Vm::new(std::sync::Arc::new(chunk), NativeTable::empty(), main, &[])?;
974        match vm.run(10_000) {
975            VmResult::Spawn {
976                function,
977                args,
978                ..
979            } => {
980                assert_eq!(function, child);
981                assert_eq!(args, vec![Value::Int(10), Value::Int(32)]);
982            }
983            other => return Err(format!("expected Spawn, got {other:?}").into()),
984        }
985        Ok(())
986    }
987
988    #[test]
989    fn delegate_with_native_sets_c() -> TestResult {
990        let mut program = Program::new("delegate-native");
991        program.function("main", 0, |f| {
992            let src = f.self_cap();
993            let native = f.self_cap();
994            let _rights_only = f.delegate(src, crate::bytecode::CapRights::SEND);
995            let _narrowed =
996                f.delegate_with_native(src, crate::bytecode::CapRights::SEND, native);
997            f.return_(src);
998        });
999        let chunk = program.build();
1000        let delegates: Vec<_> = chunk
1001            .code
1002            .iter()
1003            .filter(|i| i.op == Opcode::Delegate)
1004            .collect();
1005        assert_eq!(delegates.len(), 2);
1006        assert_eq!(delegates[0].c, 255);
1007        assert_ne!(delegates[1].c, 255);
1008        Ok(())
1009    }
1010}