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