Skip to main content

byteflow/bytecode/
builder.rs

1use std::collections::HashMap;
2
3use super::chunk::{Chunk, FunctionDef};
4use super::instruction::Instruction;
5use super::opcode::Opcode;
6use super::value::Value;
7
8/// An unresolved jump target, patched to a relative offset once its address
9/// is known (see [`ChunkBuilder::bind_label`]).
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
11pub struct Label(u32);
12
13/// Low-level fluent assembler for [`Chunk`]s (crate-internal).
14///
15/// External callers should use [`crate::Program`] / [`crate::Fn`]. This type
16/// handles label back-patching and raw opcode emission for the public API.
17pub(crate) struct ChunkBuilder {
18    name: String,
19    constants: Vec<Value>,
20    code: Vec<Instruction>,
21    functions: Vec<FunctionDef>,
22    next_label: u32,
23    label_targets: HashMap<Label, u32>,
24    /// (instruction index, label) pairs awaiting patch.
25    pending_jumps: Vec<(usize, Label)>,
26    fn_starts: HashMap<String, u32>,
27}
28
29impl ChunkBuilder {
30    pub fn new(name: impl Into<String>) -> Self {
31        ChunkBuilder {
32            name: name.into(),
33            constants: Vec::new(),
34            code: Vec::new(),
35            functions: Vec::new(),
36            next_label: 0,
37            label_targets: HashMap::new(),
38            pending_jumps: Vec::new(),
39            fn_starts: HashMap::new(),
40        }
41    }
42
43    pub fn const_(&mut self, v: Value) -> u32 {
44        // Constant deduplication keeps hot small-int/bool literals from
45        // bloating the pool across a large generated function.
46        if let Some(pos) = self.constants.iter().position(|c| c == &v) {
47            return pos as u32;
48        }
49        self.constants.push(v);
50        (self.constants.len() - 1) as u32
51    }
52
53    pub fn new_label(&mut self) -> Label {
54        let l = Label(self.next_label);
55        self.next_label += 1;
56        l
57    }
58
59    /// Bind `label` to the *next* instruction that will be emitted.
60    pub fn bind_label(&mut self, label: Label) {
61        self.label_targets.insert(label, self.code.len() as u32);
62    }
63
64    fn emit(&mut self, instr: Instruction) -> usize {
65        self.code.push(instr);
66        self.code.len() - 1
67    }
68
69    pub fn emit_halt(&mut self) {
70        self.emit(Instruction::nullary(Opcode::Halt));
71    }
72
73    pub fn emit_load_const(&mut self, dst: u8, konst: u32) {
74        self.emit(Instruction::new(Opcode::LoadConst, dst, 0, 0, konst as i32));
75    }
76
77    pub fn emit_load_imm(&mut self, dst: u8, imm: i32) {
78        self.emit(Instruction::a_imm(Opcode::LoadImm, dst, imm));
79    }
80
81    pub fn emit_move(&mut self, dst: u8, src: u8) {
82        self.emit(Instruction::abc(Opcode::Move, dst, src, 0));
83    }
84
85    pub fn emit_binop(&mut self, op: Opcode, dst: u8, lhs: u8, rhs: u8) {
86        debug_assert!(matches!(
87            op,
88            Opcode::Add
89                | Opcode::Sub
90                | Opcode::Mul
91                | Opcode::Div
92                | Opcode::Mod
93                | Opcode::Eq
94                | Opcode::Lt
95                | Opcode::Le
96        ));
97        self.emit(Instruction::abc(op, dst, lhs, rhs));
98    }
99
100    pub fn emit_neg(&mut self, dst: u8, src: u8) {
101        self.emit(Instruction::abc(Opcode::Neg, dst, src, 0));
102    }
103
104    pub fn emit_jump(&mut self, target: Label) {
105        let idx = self.emit(Instruction::only_imm(Opcode::Jump, 0));
106        self.pending_jumps.push((idx, target));
107    }
108
109    pub fn emit_branch(&mut self, cond: u8, target: Label) {
110        let idx = self.emit(Instruction::a_imm(Opcode::Branch, cond, 0));
111        self.pending_jumps.push((idx, target));
112    }
113
114    pub fn emit_spawn(&mut self, dst: u8, function: u32, argc: u8) {
115        self.emit_spawn_with_rights(dst, function, argc, crate::bytecode::CapRights::FLOW);
116    }
117
118    /// Bytecode spawn with an explicit rights request (`instr.c`). `NONE` is
119    /// confined: the child inherits no power until a later `Delegate`.
120    pub fn emit_spawn_with_rights(
121        &mut self,
122        dst: u8,
123        function: u32,
124        argc: u8,
125        rights: crate::bytecode::CapRights,
126    ) {
127        self.emit(Instruction::new(
128            Opcode::Spawn,
129            dst,
130            argc,
131            rights.bits_u8(),
132            function as i32,
133        ));
134    }
135
136    pub fn emit_delegate(&mut self, dst: u8, src_cap: u8, rights: crate::bytecode::CapRights) {
137        self.emit(Instruction::new(
138            Opcode::Delegate,
139            dst,
140            src_cap,
141            255,
142            rights.bits() as i32,
143        ));
144    }
145
146    pub fn emit_yield(&mut self) {
147        self.emit(Instruction::nullary(Opcode::Yield));
148    }
149
150    pub fn emit_sleep(&mut self, millis_reg: u8) {
151        self.emit(Instruction::abc(Opcode::Sleep, millis_reg, 0, 0));
152    }
153
154    pub fn emit_exit(&mut self, reg: u8) {
155        self.emit(Instruction::abc(Opcode::Exit, reg, 0, 0));
156    }
157
158    /// Write a **self Cap** ([`CapRights::ADDRESSING`](crate::CapRights::ADDRESSING))
159    /// into `dst` (opcode still named `SelfPid`).
160    pub fn emit_self_pid(&mut self, dst: u8) {
161        self.emit(Instruction::abc(Opcode::SelfPid, dst, 0, 0));
162    }
163
164    /// Write the next per-flow correlation id into `dst`.
165    pub fn emit_fresh_request_id(&mut self, dst: u8) {
166        self.emit(Instruction::abc(Opcode::FreshRequestId, dst, 0, 0));
167    }
168
169    /// Fire-and-forget Atomic Hop: `r[target_cap_reg]` must be Cap; `r[msg_reg]` Message.
170    pub fn emit_send(&mut self, target_cap_reg: u8, msg_reg: u8) {
171        self.emit(Instruction::abc(Opcode::Send, target_cap_reg, msg_reg, 0));
172    }
173
174    pub fn emit_receive(&mut self, dst: u8) {
175        self.emit(Instruction::abc(Opcode::Receive, dst, 0, 0));
176    }
177
178    pub fn emit_receive_timeout(&mut self, dst: u8, millis_reg: u8) {
179        self.emit(Instruction::abc(Opcode::ReceiveTimeout, dst, millis_reg, 0));
180    }
181
182    /// Selective Atomic Hop: wait for `Message` with `tag == r[tag_reg]`.
183    pub fn emit_receive_match(&mut self, dst: u8, tag_reg: u8) {
184        self.emit(Instruction::abc(Opcode::ReceiveMatch, dst, tag_reg, 0));
185    }
186
187    /// Selective Atomic Hop with an immediate `u16` tag.
188    pub fn emit_receive_match_imm(&mut self, dst: u8, tag: u16) {
189        self.emit(Instruction::a_imm(
190            Opcode::ReceiveMatchImm,
191            dst,
192            i32::from(tag),
193        ));
194    }
195
196    /// Selective receive: `tag == r[tag_reg]` and `request_id == r[id_reg]`.
197    pub fn emit_receive_match_corr(&mut self, dst: u8, tag_reg: u8, id_reg: u8) {
198        self.emit(Instruction::abc(
199            Opcode::ReceiveMatchCorr,
200            dst,
201            tag_reg,
202            id_reg,
203        ));
204    }
205
206    /// Selective receive with immediate tag and `request_id` from `id_reg`.
207    pub fn emit_receive_match_corr_imm(&mut self, dst: u8, tag: u16, id_reg: u8) {
208        self.emit(Instruction::new(
209            Opcode::ReceiveMatchCorrImm,
210            dst,
211            id_reg,
212            0,
213            i32::from(tag),
214        ));
215    }
216
217    /// Selective receive + `after`: `tag == r[tag_reg]`, timeout `r[millis_reg]`.
218    pub fn emit_receive_match_timeout(&mut self, dst: u8, tag_reg: u8, millis_reg: u8) {
219        self.emit(Instruction::abc(
220            Opcode::ReceiveMatchTimeout,
221            dst,
222            tag_reg,
223            millis_reg,
224        ));
225    }
226
227    /// Selective receive + `after` with an immediate `u16` tag.
228    pub fn emit_receive_match_imm_timeout(&mut self, dst: u8, tag: u16, millis_reg: u8) {
229        self.emit(Instruction::new(
230            Opcode::ReceiveMatchImmTimeout,
231            dst,
232            millis_reg,
233            0,
234            i32::from(tag),
235        ));
236    }
237
238    /// BEAM `is_process_alive/1` for a held Cap.
239    pub fn emit_is_alive(&mut self, dst: u8, cap_reg: u8) {
240        self.emit(Instruction::abc(Opcode::IsAlive, dst, cap_reg, 0));
241    }
242
243    /// BEAM `exit/2`. `reason_reg` is a [`crate::FlowExitReason`] code.
244    pub fn emit_exit_signal(&mut self, cap_reg: u8, reason_reg: u8) {
245        self.emit(Instruction::abc(Opcode::ExitSignal, cap_reg, reason_reg, 0));
246    }
247
248    pub fn emit_dict_put(&mut self, dst: u8, key_reg: u8, value_reg: u8) {
249        self.emit(Instruction::abc(Opcode::DictPut, dst, key_reg, value_reg));
250    }
251
252    pub fn emit_dict_get(&mut self, dst: u8, key_reg: u8) {
253        self.emit(Instruction::abc(Opcode::DictGet, dst, key_reg, 0));
254    }
255
256    pub fn emit_dict_erase(&mut self, dst: u8, key_reg: u8) {
257        self.emit(Instruction::abc(Opcode::DictErase, dst, key_reg, 0));
258    }
259
260    /// Selective receive: tag register + `Int` payload equality.
261    pub fn emit_receive_match_eq(&mut self, dst: u8, tag_reg: u8, payload_reg: u8) {
262        self.emit(Instruction::abc(
263            Opcode::ReceiveMatchEq,
264            dst,
265            tag_reg,
266            payload_reg,
267        ));
268    }
269
270    /// Spawn `function` under this flow's supervisor. `policy` is `0..=2`.
271    pub fn emit_start_child(&mut self, dst: u8, function: u32, policy: u8) {
272        self.emit(Instruction::new(
273            Opcode::StartChild,
274            dst,
275            policy,
276            0,
277            i32::try_from(function).unwrap_or(i32::MAX),
278        ));
279    }
280
281    /// Selective receive: wait for a hop whose payload wire-tag equals `kind`.
282    pub fn emit_receive_match_kind(&mut self, dst: u8, kind: u8) {
283        self.emit(Instruction::a_imm(
284            Opcode::ReceiveMatchKind,
285            dst,
286            i32::from(kind),
287        ));
288    }
289
290    /// Atomic request/reply hop: deliver `r[msg_reg]` to `r[target_cap_reg]` (Cap),
291    /// then wait for a correlated reply into `dst`.
292    ///
293    /// Encoding: `Ask ra, rb, rc` → `a=dest`, `b=target Cap`, `c=request Message`.
294    ///
295    /// The worker authenticates the request (`sender` + `reply_cap`) before delivery
296    /// and completes only when the reply’s `sender` equals the **resolved FlowId**.
297    pub fn emit_ask(&mut self, dest: u8, target_cap_reg: u8, msg_reg: u8) {
298        self.emit(Instruction::abc(Opcode::Ask, dest, target_cap_reg, msg_reg));
299    }
300
301    /// Like [`Self::emit_ask`], with a timeout register in `imm`.
302    pub fn emit_ask_timeout(&mut self, dest: u8, target_cap_reg: u8, msg_reg: u8, millis_reg: u8) {
303        self.emit(Instruction::new(
304            Opcode::AskTimeout,
305            dest,
306            target_cap_reg,
307            msg_reg,
308            i32::from(millis_reg),
309        ));
310    }
311
312    pub fn emit_monitor(&mut self, dest: u8, target_cap_reg: u8) {
313        self.emit(Instruction::abc(Opcode::Monitor, dest, target_cap_reg, 0));
314    }
315
316    pub fn emit_demonitor(&mut self, monitor_reg: u8) {
317        self.emit(Instruction::abc(Opcode::Demonitor, monitor_reg, 0, 0));
318    }
319
320    pub fn emit_link(&mut self, dest: u8, target_cap_reg: u8) {
321        self.emit(Instruction::abc(Opcode::Link, dest, target_cap_reg, 0));
322    }
323
324    pub fn emit_unlink(&mut self, link_reg: u8) {
325        self.emit(Instruction::abc(Opcode::Unlink, link_reg, 0, 0));
326    }
327
328    pub fn emit_set_trap_exit(&mut self, enabled_reg: u8) {
329        self.emit(Instruction::abc(Opcode::SetTrapExit, enabled_reg, 0, 0));
330    }
331
332    /// `imm`: 0=Always, 1=OnFailure, 2=Never.
333    pub fn emit_set_restart_policy(&mut self, policy: u8) {
334        self.emit(Instruction::only_imm(
335            Opcode::SetRestartPolicy,
336            i32::from(policy),
337        ));
338    }
339
340    /// Park for a host-side async completion into `dst`.
341    ///
342    /// Encoding: `HostAwait ra, rb, imm` → `a=dest`, `b=args`, `imm=op`.
343    pub fn emit_host_await(&mut self, dst: u8, args_reg: u8, op: u32) {
344        self.emit(Instruction::new(
345            Opcode::HostAwait,
346            dst,
347            args_reg,
348            0,
349            op as i32,
350        ));
351    }
352
353    pub fn emit_register_name(&mut self, name_reg: u8) {
354        self.emit(Instruction::abc(Opcode::RegisterName, name_reg, 0, 0));
355    }
356
357    pub fn emit_whereis(&mut self, dst: u8, name_reg: u8) {
358        self.emit(Instruction::abc(Opcode::Whereis, dst, name_reg, 0));
359    }
360
361    pub fn emit_trap(&mut self, code: i32) {
362        self.emit(Instruction::only_imm(Opcode::Trap, code));
363    }
364
365    pub fn emit_call(&mut self, dst: u8, function: u32, argc: u8) {
366        self.emit(Instruction::new(
367            Opcode::Call,
368            dst,
369            argc,
370            0,
371            function as i32,
372        ));
373    }
374
375    /// Emit a call through the runtime's native (FFI) function table
376    /// (design notes §30-31). `native_index` is resolved by name against a
377    /// [`crate::NativeTable`] at the call site — the assembler has no
378    /// knowledge of what natives exist, on purpose (see
379    /// [`crate::verify`]'s note on why `CallNative` targets aren't
380    /// range-checked statically).
381    pub fn emit_call_native(&mut self, dst: u8, native_index: u32, argc: u8) {
382        self.emit(Instruction::new(
383            Opcode::CallNative,
384            dst,
385            argc,
386            0,
387            native_index as i32,
388        ));
389    }
390
391    /// Move `src` into `dst`, then `CallNative(dst, native_index, 1)`.
392    ///
393    /// # The contract this exists to protect: `CallNative` clobbers its argument
394    ///
395    /// `Opcode::CallNative ra, fb, nc` reads `nc` arguments from
396    /// `r[a..a+nc]` and writes the result back into `r[a]`. For `nc == 1`
397    /// the argument and result are the same slot — calling a one-arg native
398    /// straight on a register you still need destroys it.
399    ///
400    /// The textbook case is unpacking several fields from one `Message` in
401    /// `r0` (`msg_sender`, `msg_tag`, …). `emit_native1_from` always operates
402    /// on a **copy** (`dst`), so `src` survives:
403    ///
404    /// ```text
405    /// b.emit_native1_from(1, 0, native_msg_sender);   // r1 = sender(r0)
406    /// b.emit_native1_from(2, 0, native_msg_request_id);
407    /// ```
408    ///
409    /// If you don't need `src` afterwards, call `emit_call_native` directly —
410    /// the `Move` would be pure overhead. See [`crate::emit_native1_from`] for
411    /// the macro-sugar form that forwards here.
412    pub fn emit_native1_from(&mut self, dst: u8, src: u8, native_index: u32) {
413        self.emit_move(dst, src);
414        self.emit_call_native(dst, native_index, 1);
415    }
416
417    /// `CallNative(base, native_index, argc)` when `argc` args are **already**
418    /// contiguous at `r[base..base+argc]`.
419    ///
420    /// No behavior beyond [`Self::emit_call_native`] — exists so the call site
421    /// reads as "args already packed". See [`crate::emit_native_n`].
422    pub fn emit_native_n(&mut self, base: u8, native_index: u32, argc: u8) {
423        self.emit_call_native(base, native_index, argc);
424    }
425
426    pub fn emit_return(&mut self, reg: u8) {
427        self.emit(Instruction::abc(Opcode::Return, reg, 0, 0));
428    }
429
430    /// Mark the start of a bytecode function at the current position and
431    /// register it in the function table under `name`. Returns the function
432    /// index, usable with [`ChunkBuilder::emit_call`]/[`ChunkBuilder::emit_spawn`]
433    /// even before the function's body is emitted (functions may call
434    /// themselves or each other, forward or backward).
435    pub fn begin_function(&mut self, name: impl Into<String>, arity: u8, num_registers: u8) -> u32 {
436        let name = name.into();
437        let entry = self.code.len() as u32;
438        let idx = self.functions.len() as u32;
439        self.functions.push(FunctionDef {
440            name: name.clone(),
441            entry,
442            arity,
443            num_registers,
444        });
445        self.fn_starts.insert(name, idx);
446        idx
447    }
448
449    pub fn function_index(&self, name: &str) -> Option<u32> {
450        self.fn_starts.get(name).copied()
451    }
452
453    /// Patch the register-file size of an already-`begin_function`'d
454    /// function. Exists for assemblers whose register count is only known
455    /// *after* emitting the body — `begin_function` must still be called
456    /// first so `entry` captures the current code cursor.
457    pub fn set_num_registers(&mut self, function_index: u32, num_registers: u8) {
458        if let Some(def) = self.functions.get_mut(function_index as usize) {
459            def.num_registers = num_registers;
460        }
461    }
462
463    /// Resolve every pending jump against its bound label and produce the
464    /// final immutable [`Chunk`].
465    ///
466    /// An unbound label is a host assembly bug. This method does **not**
467    /// panic: the jump is left with relative offset `0` (falls through).
468    /// [`crate::verify`] / [`crate::Runtime::new`] then reject or run a
469    /// no-op jump rather than taking the process down at assemble time.
470    pub fn finish(mut self) -> Chunk {
471        for (idx, label) in self.pending_jumps.drain(..) {
472            match self.label_targets.get(&label) {
473                Some(target) => {
474                    // Relative offset from the instruction *after* this jump.
475                    let offset = *target as i64 - (idx as i64 + 1);
476                    self.code[idx].imm = offset as i32;
477                }
478                None => {
479                    // Fail-closed without panic: identity jump (offset 0).
480                    self.code[idx].imm = 0;
481                }
482            }
483        }
484        Chunk {
485            name: self.name,
486            constants: self.constants,
487            code: self.code,
488            functions: self.functions,
489        }
490    }
491}
492#[cfg(test)]
493mod tests {
494    use super::*;
495
496    #[test]
497    fn emit_native1_from_never_clobbers_source_register() {
498        let mut b = ChunkBuilder::new("clobber-test");
499        b.begin_function("main", 0, 8);
500        b.emit_native1_from(1, 0, 10);
501        b.emit_native1_from(2, 0, 11);
502        b.emit_native1_from(3, 0, 12);
503        let chunk = b.finish();
504
505        assert_eq!(chunk.code.len(), 6);
506        for (move_idx, call_idx, expected_native) in
507            [(0usize, 1usize, 10i32), (2, 3, 11), (4, 5, 12)]
508        {
509            assert_eq!(chunk.code[move_idx].op, Opcode::Move);
510            assert_eq!(chunk.code[move_idx].b, 0);
511            assert_eq!(chunk.code[call_idx].op, Opcode::CallNative);
512            assert_ne!(chunk.code[call_idx].a, 0);
513            assert_eq!(chunk.code[call_idx].imm, expected_native);
514        }
515    }
516
517    #[test]
518    fn emit_native_n_is_a_plain_call_native_with_no_extra_instructions() {
519        let mut b = ChunkBuilder::new("native-n-test");
520        b.begin_function("main", 0, 8);
521        b.emit_load_imm(1, 7);
522        b.emit_load_imm(2, 1);
523        b.emit_native_n(1, 99, 2);
524        let chunk = b.finish();
525
526        assert_eq!(chunk.code.len(), 3);
527        assert_eq!(chunk.code[2].op, Opcode::CallNative);
528        assert_eq!(chunk.code[2].a, 1);
529        assert_eq!(chunk.code[2].b, 2);
530        assert_eq!(chunk.code[2].imm, 99);
531    }
532
533    #[test]
534    fn macro_forms_produce_identical_bytecode_to_the_methods() {
535        let mut via_method = ChunkBuilder::new("via-method");
536        via_method.begin_function("main", 0, 8);
537        via_method.emit_native1_from(1, 0, 10);
538        via_method.emit_native_n(1, 99, 2);
539
540        let mut via_macro = ChunkBuilder::new("via-macro");
541        via_macro.begin_function("main", 0, 8);
542        crate::emit_native1_from!(via_macro, 1, 0, 10);
543        crate::emit_native_n!(via_macro, 1, 99, 2);
544
545        assert_eq!(via_method.finish().code, via_macro.finish().code);
546    }
547}