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