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