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        if dst == src {
83            return;
84        }
85        self.emit(Instruction::abc(Opcode::Move, dst, src, 0));
86    }
87
88    /// `r[dst] = r[src] + imm`. Does not allocate a scratch register.
89    pub fn emit_add_imm(&mut self, dst: u8, src: u8, imm: i32) {
90        self.emit(Instruction::new(Opcode::AddImm, dst, src, 0, imm));
91    }
92
93    pub fn emit_sub_imm(&mut self, dst: u8, src: u8, imm: i32) {
94        self.emit(Instruction::new(Opcode::SubImm, dst, src, 0, imm));
95    }
96
97    pub fn emit_lt_imm(&mut self, dst: u8, src: u8, imm: i32) {
98        self.emit(Instruction::new(Opcode::LtImm, dst, src, 0, imm));
99    }
100
101    pub fn emit_list_pack(&mut self, dst: u8, base: u8, count: i32) {
102        self.emit(Instruction::new(Opcode::ListPack, dst, base, 0, count));
103    }
104
105    pub fn emit_list_get(&mut self, dst: u8, src: u8, index: i32) {
106        self.emit(Instruction::new(Opcode::ListGet, dst, src, 0, index));
107    }
108
109    pub fn emit_list_len(&mut self, dst: u8, src: u8) {
110        self.emit(Instruction::abc(Opcode::ListLen, dst, src, 0));
111    }
112
113    pub fn emit_binop(&mut self, op: Opcode, dst: u8, lhs: u8, rhs: u8) {
114        debug_assert!(matches!(
115            op,
116            Opcode::Add
117                | Opcode::Sub
118                | Opcode::Mul
119                | Opcode::Div
120                | Opcode::Mod
121                | Opcode::Eq
122                | Opcode::Lt
123                | Opcode::Le
124        ));
125        self.emit(Instruction::abc(op, dst, lhs, rhs));
126    }
127
128    pub fn emit_neg(&mut self, dst: u8, src: u8) {
129        self.emit(Instruction::abc(Opcode::Neg, dst, src, 0));
130    }
131
132    pub fn emit_jump(&mut self, target: Label) {
133        let idx = self.emit(Instruction::only_imm(Opcode::Jump, 0));
134        self.pending_jumps.push((idx, target));
135    }
136
137    pub fn emit_branch(&mut self, cond: u8, target: Label) {
138        let idx = self.emit(Instruction::a_imm(Opcode::Branch, cond, 0));
139        self.pending_jumps.push((idx, target));
140    }
141
142    pub fn emit_spawn(&mut self, dst: u8, function: u32, argc: u8) {
143        self.emit_spawn_with_rights(dst, function, argc, crate::bytecode::CapRights::FLOW);
144    }
145
146    /// Bytecode spawn with an explicit rights request (`instr.c`). `NONE` is
147    /// confined: the child inherits no power until a later `Delegate`.
148    pub fn emit_spawn_with_rights(
149        &mut self,
150        dst: u8,
151        function: u32,
152        argc: u8,
153        rights: crate::bytecode::CapRights,
154    ) {
155        self.emit(Instruction::new(
156            Opcode::Spawn,
157            dst,
158            argc,
159            rights.bits_u8(),
160            function as i32,
161        ));
162    }
163
164    pub fn emit_delegate(&mut self, dst: u8, src_cap: u8, rights: crate::bytecode::CapRights) {
165        self.emit_delegate_with_native(dst, src_cap, rights, None);
166    }
167
168    /// `c = 255` means no extra native-mask narrowing (VM keeps the source
169    /// mask). Any other `c` is a Cap register whose `NATIVE` mask is AND-ed
170    /// in — the only assembler path that emits `c ≠ 255`.
171    pub fn emit_delegate_with_native(
172        &mut self,
173        dst: u8,
174        src_cap: u8,
175        rights: crate::bytecode::CapRights,
176        native_cap: Option<u8>,
177    ) {
178        let native_reg = match native_cap {
179            Some(reg) => reg,
180            None => 255,
181        };
182        self.emit(Instruction::new(
183            Opcode::Delegate,
184            dst,
185            src_cap,
186            native_reg,
187            rights.bits() as i32,
188        ));
189    }
190
191    pub fn emit_yield(&mut self) {
192        self.emit(Instruction::nullary(Opcode::Yield));
193    }
194
195    pub fn emit_sleep(&mut self, millis_reg: u8) {
196        self.emit(Instruction::abc(Opcode::Sleep, millis_reg, 0, 0));
197    }
198
199    pub fn emit_exit(&mut self, reg: u8) {
200        self.emit(Instruction::abc(Opcode::Exit, reg, 0, 0));
201    }
202
203    /// Write a **self Cap** ([`CapRights::ADDRESSING`](crate::CapRights::ADDRESSING))
204    /// into `dst` (opcode still named `SelfPid`).
205    pub fn emit_self_pid(&mut self, dst: u8) {
206        self.emit(Instruction::abc(Opcode::SelfPid, dst, 0, 0));
207    }
208
209    /// Write the next per-flow correlation id into `dst`.
210    pub fn emit_fresh_request_id(&mut self, dst: u8) {
211        self.emit(Instruction::abc(Opcode::FreshRequestId, dst, 0, 0));
212    }
213
214    /// Fire-and-forget Atomic Hop: `r[target_cap_reg]` must be Cap; `r[msg_reg]` Message.
215    pub fn emit_send(&mut self, target_cap_reg: u8, msg_reg: u8) {
216        self.emit(Instruction::abc(Opcode::Send, target_cap_reg, msg_reg, 0));
217    }
218
219    pub fn emit_receive(&mut self, dst: u8) {
220        self.emit(Instruction::abc(Opcode::Receive, dst, 0, 0));
221    }
222
223    pub fn emit_receive_timeout(&mut self, dst: u8, millis_reg: u8) {
224        self.emit(Instruction::abc(Opcode::ReceiveTimeout, dst, millis_reg, 0));
225    }
226
227    /// Selective Atomic Hop: wait for `Message` with `tag == r[tag_reg]`.
228    pub fn emit_receive_match(&mut self, dst: u8, tag_reg: u8) {
229        self.emit(Instruction::abc(Opcode::ReceiveMatch, dst, tag_reg, 0));
230    }
231
232    /// Selective Atomic Hop with an immediate `u16` tag.
233    pub fn emit_receive_match_imm(&mut self, dst: u8, tag: u16) {
234        self.emit(Instruction::a_imm(
235            Opcode::ReceiveMatchImm,
236            dst,
237            i32::from(tag),
238        ));
239    }
240
241    /// Selective receive: `tag == r[tag_reg]` and `request_id == r[id_reg]`.
242    pub fn emit_receive_match_corr(&mut self, dst: u8, tag_reg: u8, id_reg: u8) {
243        self.emit(Instruction::abc(
244            Opcode::ReceiveMatchCorr,
245            dst,
246            tag_reg,
247            id_reg,
248        ));
249    }
250
251    /// Selective receive with immediate tag and `request_id` from `id_reg`.
252    pub fn emit_receive_match_corr_imm(&mut self, dst: u8, tag: u16, id_reg: u8) {
253        self.emit(Instruction::new(
254            Opcode::ReceiveMatchCorrImm,
255            dst,
256            id_reg,
257            0,
258            i32::from(tag),
259        ));
260    }
261
262    /// Selective receive + `after`: `tag == r[tag_reg]`, timeout `r[millis_reg]`.
263    pub fn emit_receive_match_timeout(&mut self, dst: u8, tag_reg: u8, millis_reg: u8) {
264        self.emit(Instruction::abc(
265            Opcode::ReceiveMatchTimeout,
266            dst,
267            tag_reg,
268            millis_reg,
269        ));
270    }
271
272    /// Selective receive + `after` with an immediate `u16` tag.
273    pub fn emit_receive_match_imm_timeout(&mut self, dst: u8, tag: u16, millis_reg: u8) {
274        self.emit(Instruction::new(
275            Opcode::ReceiveMatchImmTimeout,
276            dst,
277            millis_reg,
278            0,
279            i32::from(tag),
280        ));
281    }
282
283    /// BEAM `is_process_alive/1` for a held Cap.
284    pub fn emit_is_alive(&mut self, dst: u8, cap_reg: u8) {
285        self.emit(Instruction::abc(Opcode::IsAlive, dst, cap_reg, 0));
286    }
287
288    /// BEAM `exit/2`. `reason_reg` is a [`crate::FlowExitReason`] code.
289    pub fn emit_exit_signal(&mut self, cap_reg: u8, reason_reg: u8) {
290        self.emit(Instruction::abc(Opcode::ExitSignal, cap_reg, reason_reg, 0));
291    }
292
293    pub fn emit_dict_put(&mut self, dst: u8, key_reg: u8, value_reg: u8) {
294        self.emit(Instruction::abc(Opcode::DictPut, dst, key_reg, value_reg));
295    }
296
297    pub fn emit_dict_get(&mut self, dst: u8, key_reg: u8) {
298        self.emit(Instruction::abc(Opcode::DictGet, dst, key_reg, 0));
299    }
300
301    pub fn emit_dict_erase(&mut self, dst: u8, key_reg: u8) {
302        self.emit(Instruction::abc(Opcode::DictErase, dst, key_reg, 0));
303    }
304
305    /// Selective receive: tag register + `Int` payload equality.
306    pub fn emit_receive_match_eq(&mut self, dst: u8, tag_reg: u8, payload_reg: u8) {
307        self.emit(Instruction::abc(
308            Opcode::ReceiveMatchEq,
309            dst,
310            tag_reg,
311            payload_reg,
312        ));
313    }
314
315    /// Selective receive: tag register + structural payload equality.
316    pub fn emit_receive_match_value(&mut self, dst: u8, tag_reg: u8, payload_reg: u8) {
317        self.emit(Instruction::abc(
318            Opcode::ReceiveMatchValue,
319            dst,
320            tag_reg,
321            payload_reg,
322        ));
323    }
324
325    /// Hand a hop to the host distribution bridge.
326    pub fn emit_send_remote(&mut self, node_reg: u8, name_reg: u8, msg_reg: u8) {
327        self.emit(Instruction::abc(
328            Opcode::SendRemote,
329            node_reg,
330            name_reg,
331            msg_reg,
332        ));
333    }
334
335    /// Start a supervisor for this flow. `strategy` is `0..=2`.
336    pub fn emit_start_supervisor(&mut self, strategy: u8) {
337        self.emit(Instruction::only_imm(
338            Opcode::StartSupervisor,
339            i32::from(strategy),
340        ));
341    }
342
343    /// Spawn `function` under this flow's supervisor. `policy` is `0..=2`.
344    pub fn emit_start_child(&mut self, dst: u8, function: u32, policy: u8) {
345        self.emit(Instruction::new(
346            Opcode::StartChild,
347            dst,
348            policy,
349            0,
350            match i32::try_from(function) {
351                Ok(n) => n,
352                Err(_) => i32::MAX,
353            },
354        ));
355    }
356
357    /// Selective receive: wait for a hop whose payload wire-tag equals `kind`.
358    pub fn emit_receive_match_kind(&mut self, dst: u8, kind: u8) {
359        self.emit(Instruction::a_imm(
360            Opcode::ReceiveMatchKind,
361            dst,
362            i32::from(kind),
363        ));
364    }
365
366    /// Atomic request/reply hop: deliver `r[msg_reg]` to `r[target_cap_reg]` (Cap),
367    /// then wait for a correlated reply into `dst`.
368    ///
369    /// Encoding: `Ask ra, rb, rc` → `a=dest`, `b=target Cap`, `c=request Message`.
370    ///
371    /// The worker authenticates the request (`sender` + `reply_cap`) before delivery
372    /// and completes only when the reply’s `sender` equals the **resolved FlowId**.
373    pub fn emit_ask(&mut self, dest: u8, target_cap_reg: u8, msg_reg: u8) {
374        self.emit(Instruction::abc(Opcode::Ask, dest, target_cap_reg, msg_reg));
375    }
376
377    /// Like [`Self::emit_ask`], with a timeout register in `imm`.
378    pub fn emit_ask_timeout(&mut self, dest: u8, target_cap_reg: u8, msg_reg: u8, millis_reg: u8) {
379        self.emit(Instruction::new(
380            Opcode::AskTimeout,
381            dest,
382            target_cap_reg,
383            msg_reg,
384            i32::from(millis_reg),
385        ));
386    }
387
388    pub fn emit_monitor(&mut self, dest: u8, target_cap_reg: u8) {
389        self.emit(Instruction::abc(Opcode::Monitor, dest, target_cap_reg, 0));
390    }
391
392    pub fn emit_demonitor(&mut self, monitor_reg: u8) {
393        self.emit(Instruction::abc(Opcode::Demonitor, monitor_reg, 0, 0));
394    }
395
396    pub fn emit_link(&mut self, dest: u8, target_cap_reg: u8) {
397        self.emit(Instruction::abc(Opcode::Link, dest, target_cap_reg, 0));
398    }
399
400    pub fn emit_unlink(&mut self, link_reg: u8) {
401        self.emit(Instruction::abc(Opcode::Unlink, link_reg, 0, 0));
402    }
403
404    pub fn emit_set_trap_exit(&mut self, enabled_reg: u8) {
405        self.emit(Instruction::abc(Opcode::SetTrapExit, enabled_reg, 0, 0));
406    }
407
408    /// `imm`: 0=Always, 1=OnFailure, 2=Never.
409    pub fn emit_set_restart_policy(&mut self, policy: u8) {
410        self.emit(Instruction::only_imm(
411            Opcode::SetRestartPolicy,
412            i32::from(policy),
413        ));
414    }
415
416    /// Park for a host-side async completion into `dst`.
417    ///
418    /// Encoding: `HostAwait ra, rb, imm` → `a=dest`, `b=args`, `imm=op`.
419    pub fn emit_host_await(&mut self, dst: u8, args_reg: u8, op: u32) {
420        self.emit(Instruction::new(
421            Opcode::HostAwait,
422            dst,
423            args_reg,
424            0,
425            op as i32,
426        ));
427    }
428
429    pub fn emit_register_name(&mut self, name_reg: u8) {
430        self.emit(Instruction::abc(Opcode::RegisterName, name_reg, 0, 0));
431    }
432
433    pub fn emit_whereis(&mut self, dst: u8, name_reg: u8) {
434        self.emit(Instruction::abc(Opcode::Whereis, dst, name_reg, 0));
435    }
436
437    pub fn emit_trap(&mut self, code: i32) {
438        self.emit(Instruction::only_imm(Opcode::Trap, code));
439    }
440
441    pub fn emit_call(&mut self, dst: u8, function: u32, argc: u8) {
442        self.emit(Instruction::new(
443            Opcode::Call,
444            dst,
445            argc,
446            0,
447            function as i32,
448        ));
449    }
450
451    /// Emit a call through the runtime's native (FFI) function table
452    /// (design notes §30-31). `native_index` is resolved by name against a
453    /// [`crate::NativeTable`] at the call site — the assembler has no
454    /// knowledge of what natives exist, on purpose (see
455    /// [`crate::verify`]'s note on why `CallNative` targets aren't
456    /// range-checked statically).
457    pub fn emit_call_native(&mut self, dst: u8, native_index: u32, argc: u8) {
458        self.emit(Instruction::new(
459            Opcode::CallNative,
460            dst,
461            argc,
462            0,
463            native_index as i32,
464        ));
465    }
466
467    /// `r[dst] = native_1(r[src])` as a single [`Opcode::CallNativeFrom`].
468    ///
469    /// `Opcode::CallNative` writes the result over its first argument. This
470    /// form keeps `src` intact when `dst != src`, which is what unpacking one
471    /// `Message` into several fields needs:
472    ///
473    /// ```text
474    /// b.emit_native1_from(1, 0, native_msg_sender);   // r1 = sender(r0)
475    /// b.emit_native1_from(2, 0, native_msg_request_id);
476    /// ```
477    ///
478    /// A multi-arg native still uses [`Self::emit_call_native`]: the arguments
479    /// have to sit in a contiguous window, and the result overwrites `r[base]`.
480    pub fn emit_native1_from(&mut self, dst: u8, src: u8, native_index: u32) {
481        self.emit(Instruction::new(
482            Opcode::CallNativeFrom,
483            dst,
484            src,
485            0,
486            native_index as i32,
487        ));
488    }
489
490    /// `CallNative(base, native_index, argc)` when `argc` args are **already**
491    /// contiguous at `r[base..base+argc]`.
492    ///
493    /// No behavior beyond [`Self::emit_call_native`] — exists so the call site
494    /// reads as "args already packed".
495    pub fn emit_native_n(&mut self, base: u8, native_index: u32, argc: u8) {
496        self.emit_call_native(base, native_index, argc);
497    }
498
499    pub fn emit_return(&mut self, reg: u8) {
500        self.emit(Instruction::abc(Opcode::Return, reg, 0, 0));
501    }
502
503    /// Mark the start of a bytecode function at the current position and
504    /// register it in the function table under `name`. Returns the function
505    /// index, usable with [`ChunkBuilder::emit_call`]/[`ChunkBuilder::emit_spawn`]
506    /// even before the function's body is emitted (functions may call
507    /// themselves or each other, forward or backward).
508    pub fn begin_function(&mut self, name: impl Into<String>, arity: u8, num_registers: u8) -> u32 {
509        let name = name.into();
510        let entry = self.code.len() as u32;
511        let idx = self.functions.len() as u32;
512        self.functions.push(FunctionDef {
513            name: name.clone(),
514            entry,
515            arity,
516            num_registers,
517        });
518        self.fn_starts.insert(name, idx);
519        idx
520    }
521
522    pub fn function_index(&self, name: &str) -> Option<u32> {
523        self.fn_starts.get(name).copied()
524    }
525
526    /// Patch the register-file size of an already-`begin_function`'d
527    /// function. Exists for assemblers whose register count is only known
528    /// *after* emitting the body — `begin_function` must still be called
529    /// first so `entry` captures the current code position.
530    pub fn set_num_registers(&mut self, function_index: u32, num_registers: u8) {
531        if let Some(def) = self.functions.get_mut(function_index as usize) {
532            def.num_registers = num_registers;
533        }
534    }
535
536    /// Resolve every pending jump against its bound label and produce the
537    /// final immutable [`Chunk`].
538    ///
539    /// An unbound label is a host assembly bug. This method does **not**
540    /// panic: the jump becomes `Trap` so it cannot fall through as a no-op.
541    /// A relative offset that does not fit in `i32` is the same trap.
542    pub fn finish(mut self) -> Chunk {
543        for (idx, label) in self.pending_jumps.drain(..) {
544            let imm = self.label_targets.get(&label).and_then(|target| {
545                // Relative offset from the instruction *after* this jump.
546                let offset = i64::from(*target) - (idx as i64 + 1);
547                i32::try_from(offset).ok()
548            });
549            match imm {
550                Some(imm) => self.code[idx].imm = imm,
551                None => {
552                    self.code[idx].op = Opcode::Trap;
553                    self.code[idx].imm = 0;
554                }
555            }
556        }
557        Chunk {
558            name: self.name,
559            constants: self.constants,
560            code: self.code,
561            functions: self.functions,
562        }
563    }
564}
565#[cfg(test)]
566mod tests {
567    use super::*;
568
569    #[test]
570    fn unbound_label_becomes_a_trap() {
571        let mut b = ChunkBuilder::new("t");
572        b.begin_function("main", 0, 1);
573        let missing = b.new_label();
574        b.emit_jump(missing);
575        b.emit_return(0);
576        let chunk = b.finish();
577        assert_eq!(chunk.code[0].op, Opcode::Trap);
578    }
579
580    #[test]
581    fn emit_native1_from_never_clobbers_source_register() {
582        let mut b = ChunkBuilder::new("clobber-test");
583        b.begin_function("main", 0, 8);
584        b.emit_native1_from(1, 0, 10);
585        b.emit_native1_from(2, 0, 11);
586        b.emit_native1_from(3, 0, 12);
587        let chunk = b.finish();
588
589        assert_eq!(chunk.code.len(), 3);
590        for (idx, dest, expected_native) in [(0usize, 1u8, 10i32), (1, 2, 11), (2, 3, 12)] {
591            let instr = chunk.code[idx];
592            assert_eq!(instr.op, Opcode::CallNativeFrom);
593            assert_eq!(instr.b, 0, "source register stays r0");
594            assert_eq!(instr.a, dest);
595            assert_ne!(instr.a, instr.b);
596            assert_eq!(instr.imm, expected_native);
597        }
598    }
599
600    #[test]
601    fn emit_native_n_is_a_plain_call_native_with_no_extra_instructions() {
602        let mut b = ChunkBuilder::new("native-n-test");
603        b.begin_function("main", 0, 8);
604        b.emit_load_imm(1, 7);
605        b.emit_load_imm(2, 1);
606        b.emit_native_n(1, 99, 2);
607        let chunk = b.finish();
608
609        assert_eq!(chunk.code.len(), 3);
610        assert_eq!(chunk.code[2].op, Opcode::CallNative);
611        assert_eq!(chunk.code[2].a, 1);
612        assert_eq!(chunk.code[2].b, 2);
613        assert_eq!(chunk.code[2].imm, 99);
614    }
615}