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(crate) 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(crate) 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(crate) 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(crate) 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(crate) fn emit_halt(&mut self) {
70        self.emit(Instruction::nullary(Opcode::Halt));
71    }
72
73    pub(crate) 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(crate) fn emit_load_imm(&mut self, dst: u8, imm: i32) {
78        self.emit(Instruction::a_imm(Opcode::LoadImm, dst, imm));
79    }
80
81    pub(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) fn emit_bit_not(&mut self, dst: u8, src: u8) {
148        self.emit(Instruction::abc(Opcode::BitNot, dst, src, 0));
149    }
150
151    pub(crate) 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(crate) 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(crate) 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(crate) 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(crate) fn emit_bytes_len(&mut self, dst: u8, src: u8) {
170        self.emit(Instruction::abc(Opcode::BytesLen, dst, src, 0));
171    }
172
173    pub(crate) 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(crate) 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(crate) fn emit_record_len(&mut self, dst: u8, src: u8) {
182        self.emit(Instruction::abc(Opcode::RecordLen, dst, src, 0));
183    }
184
185    pub(crate) 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(crate) 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(crate) fn emit_map_len(&mut self, dst: u8, map: u8) {
194        self.emit(Instruction::abc(Opcode::MapLen, dst, map, 0));
195    }
196
197    pub(crate) 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(crate) fn emit_table_open(&mut self, dst: u8, name: u8) {
214        self.emit(Instruction::abc(Opcode::TableOpen, dst, name, 0));
215    }
216
217    pub(crate) 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(crate) 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(crate) 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(crate) fn emit_neg(&mut self, dst: u8, src: u8) {
241        self.emit(Instruction::abc(Opcode::Neg, dst, src, 0));
242    }
243
244    pub(crate) 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(crate) 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(crate) 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(crate) 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(crate) fn emit_delegate(
277        &mut self,
278        dst: u8,
279        src_cap: u8,
280        rights: crate::bytecode::CapRights,
281    ) {
282        self.emit_delegate_with_native(dst, src_cap, rights, None);
283    }
284
285    /// `c = 255` means no extra native-mask narrowing (VM keeps the source
286    /// mask). Any other `c` is a Cap register whose `NATIVE` mask is AND-ed
287    /// in — the only assembler path that emits `c ≠ 255`.
288    pub(crate) fn emit_delegate_with_native(
289        &mut self,
290        dst: u8,
291        src_cap: u8,
292        rights: crate::bytecode::CapRights,
293        native_cap: Option<u8>,
294    ) {
295        let native_reg = match native_cap {
296            Some(reg) => reg,
297            None => 255,
298        };
299        self.emit(Instruction::new(
300            Opcode::Delegate,
301            dst,
302            src_cap,
303            native_reg,
304            rights.bits() as i32,
305        ));
306    }
307
308    pub(crate) fn emit_yield(&mut self) {
309        self.emit(Instruction::nullary(Opcode::Yield));
310    }
311
312    pub(crate) fn emit_sleep(&mut self, millis_reg: u8) {
313        self.emit(Instruction::abc(Opcode::Sleep, millis_reg, 0, 0));
314    }
315
316    pub(crate) fn emit_exit(&mut self, reg: u8) {
317        self.emit(Instruction::abc(Opcode::Exit, reg, 0, 0));
318    }
319
320    /// Write a **self Cap** ([`CapRights::ADDRESSING`](crate::CapRights::ADDRESSING))
321    /// into `dst` (opcode still named `SelfPid`).
322    pub(crate) fn emit_self_pid(&mut self, dst: u8) {
323        self.emit(Instruction::abc(Opcode::SelfPid, dst, 0, 0));
324    }
325
326    /// Write the next per-flow correlation id into `dst`.
327    pub(crate) fn emit_fresh_request_id(&mut self, dst: u8) {
328        self.emit(Instruction::abc(Opcode::FreshRequestId, dst, 0, 0));
329    }
330
331    /// Fire-and-forget Atomic Hop: `r[target_cap_reg]` must be Cap; `r[msg_reg]` Message.
332    pub(crate) fn emit_send(&mut self, target_cap_reg: u8, msg_reg: u8) {
333        self.emit(Instruction::abc(Opcode::Send, target_cap_reg, msg_reg, 0));
334    }
335
336    pub(crate) fn emit_receive(&mut self, dst: u8) {
337        self.emit(Instruction::abc(Opcode::Receive, dst, 0, 0));
338    }
339
340    pub(crate) fn emit_receive_timeout(&mut self, dst: u8, millis_reg: u8) {
341        self.emit(Instruction::abc(Opcode::ReceiveTimeout, dst, millis_reg, 0));
342    }
343
344    /// Selective Atomic Hop: wait for `Message` with `tag == r[tag_reg]`.
345    pub(crate) fn emit_receive_match(&mut self, dst: u8, tag_reg: u8) {
346        self.emit(Instruction::abc(Opcode::ReceiveMatch, dst, tag_reg, 0));
347    }
348
349    /// Selective Atomic Hop with an immediate `u16` tag.
350    pub(crate) fn emit_receive_match_imm(&mut self, dst: u8, tag: u16) {
351        self.emit(Instruction::a_imm(
352            Opcode::ReceiveMatchImm,
353            dst,
354            i32::from(tag),
355        ));
356    }
357
358    /// Selective receive: `tag == r[tag_reg]` and `request_id == r[id_reg]`.
359    pub(crate) fn emit_receive_match_corr(&mut self, dst: u8, tag_reg: u8, id_reg: u8) {
360        self.emit(Instruction::abc(
361            Opcode::ReceiveMatchCorr,
362            dst,
363            tag_reg,
364            id_reg,
365        ));
366    }
367
368    /// Selective receive with immediate tag and `request_id` from `id_reg`.
369    pub(crate) fn emit_receive_match_corr_imm(&mut self, dst: u8, tag: u16, id_reg: u8) {
370        self.emit(Instruction::new(
371            Opcode::ReceiveMatchCorrImm,
372            dst,
373            id_reg,
374            0,
375            i32::from(tag),
376        ));
377    }
378
379    /// Selective receive + `after`: `tag == r[tag_reg]`, timeout `r[millis_reg]`.
380    pub(crate) fn emit_receive_match_timeout(&mut self, dst: u8, tag_reg: u8, millis_reg: u8) {
381        self.emit(Instruction::abc(
382            Opcode::ReceiveMatchTimeout,
383            dst,
384            tag_reg,
385            millis_reg,
386        ));
387    }
388
389    /// Selective receive + `after` with an immediate `u16` tag.
390    pub(crate) fn emit_receive_match_imm_timeout(&mut self, dst: u8, tag: u16, millis_reg: u8) {
391        self.emit(Instruction::new(
392            Opcode::ReceiveMatchImmTimeout,
393            dst,
394            millis_reg,
395            0,
396            i32::from(tag),
397        ));
398    }
399
400    /// BEAM `is_process_alive/1` for a held Cap.
401    pub(crate) fn emit_is_alive(&mut self, dst: u8, cap_reg: u8) {
402        self.emit(Instruction::abc(Opcode::IsAlive, dst, cap_reg, 0));
403    }
404
405    /// BEAM `exit/2`. `reason_reg` is a [`crate::FlowExitReason`] code.
406    pub(crate) fn emit_exit_signal(&mut self, cap_reg: u8, reason_reg: u8) {
407        self.emit(Instruction::abc(Opcode::ExitSignal, cap_reg, reason_reg, 0));
408    }
409
410    pub(crate) fn emit_dict_put(&mut self, dst: u8, key_reg: u8, value_reg: u8) {
411        self.emit(Instruction::abc(Opcode::DictPut, dst, key_reg, value_reg));
412    }
413
414    pub(crate) fn emit_dict_get(&mut self, dst: u8, key_reg: u8) {
415        self.emit(Instruction::abc(Opcode::DictGet, dst, key_reg, 0));
416    }
417
418    pub(crate) fn emit_dict_erase(&mut self, dst: u8, key_reg: u8) {
419        self.emit(Instruction::abc(Opcode::DictErase, dst, key_reg, 0));
420    }
421
422    /// Selective receive: tag register + `Int` payload equality.
423    pub(crate) fn emit_receive_match_eq(&mut self, dst: u8, tag_reg: u8, payload_reg: u8) {
424        self.emit(Instruction::abc(
425            Opcode::ReceiveMatchEq,
426            dst,
427            tag_reg,
428            payload_reg,
429        ));
430    }
431
432    /// Selective receive: tag register + structural payload equality.
433    pub(crate) fn emit_receive_match_value(&mut self, dst: u8, tag_reg: u8, payload_reg: u8) {
434        self.emit(Instruction::abc(
435            Opcode::ReceiveMatchValue,
436            dst,
437            tag_reg,
438            payload_reg,
439        ));
440    }
441
442    /// Hand a hop to the host distribution bridge.
443    pub(crate) fn emit_send_remote(&mut self, node_reg: u8, name_reg: u8, msg_reg: u8) {
444        self.emit(Instruction::abc(
445            Opcode::SendRemote,
446            node_reg,
447            name_reg,
448            msg_reg,
449        ));
450    }
451
452    /// Start a supervisor for this flow. `strategy` is `0..=2`.
453    pub(crate) fn emit_start_supervisor(&mut self, strategy: u8) {
454        self.emit(Instruction::only_imm(
455            Opcode::StartSupervisor,
456            i32::from(strategy),
457        ));
458    }
459
460    /// Spawn `function` under this flow's supervisor. `policy` is `0..=2`.
461    pub(crate) fn emit_start_child(&mut self, dst: u8, function: u32, policy: u8) {
462        self.emit(Instruction::new(
463            Opcode::StartChild,
464            dst,
465            policy,
466            0,
467            match i32::try_from(function) {
468                Ok(n) => n,
469                Err(_) => i32::MAX,
470            },
471        ));
472    }
473
474    /// Selective receive: wait for a hop whose payload wire-tag equals `kind`.
475    pub(crate) fn emit_receive_match_kind(&mut self, dst: u8, kind: u8) {
476        self.emit(Instruction::a_imm(
477            Opcode::ReceiveMatchKind,
478            dst,
479            i32::from(kind),
480        ));
481    }
482
483    /// Atomic request/reply hop: deliver `r[msg_reg]` to `r[target_cap_reg]` (Cap),
484    /// then wait for a correlated reply into `dst`.
485    ///
486    /// Encoding: `Ask ra, rb, rc` → `a=dest`, `b=target Cap`, `c=request Message`.
487    ///
488    /// The worker authenticates the request (`sender` + `reply_cap`) before delivery
489    /// and completes only when the reply’s `sender` equals the **resolved FlowId**.
490    pub(crate) fn emit_ask(&mut self, dest: u8, target_cap_reg: u8, msg_reg: u8) {
491        self.emit(Instruction::abc(Opcode::Ask, dest, target_cap_reg, msg_reg));
492    }
493
494    /// Like [`Self::emit_ask`], with a timeout register in `imm`.
495    pub(crate) fn emit_ask_timeout(
496        &mut self,
497        dest: u8,
498        target_cap_reg: u8,
499        msg_reg: u8,
500        millis_reg: u8,
501    ) {
502        self.emit(Instruction::new(
503            Opcode::AskTimeout,
504            dest,
505            target_cap_reg,
506            msg_reg,
507            i32::from(millis_reg),
508        ));
509    }
510
511    pub(crate) fn emit_monitor(&mut self, dest: u8, target_cap_reg: u8) {
512        self.emit(Instruction::abc(Opcode::Monitor, dest, target_cap_reg, 0));
513    }
514
515    pub(crate) fn emit_demonitor(&mut self, monitor_reg: u8) {
516        self.emit(Instruction::abc(Opcode::Demonitor, monitor_reg, 0, 0));
517    }
518
519    pub(crate) fn emit_link(&mut self, dest: u8, target_cap_reg: u8) {
520        self.emit(Instruction::abc(Opcode::Link, dest, target_cap_reg, 0));
521    }
522
523    pub(crate) fn emit_unlink(&mut self, link_reg: u8) {
524        self.emit(Instruction::abc(Opcode::Unlink, link_reg, 0, 0));
525    }
526
527    pub(crate) fn emit_set_trap_exit(&mut self, enabled_reg: u8) {
528        self.emit(Instruction::abc(Opcode::SetTrapExit, enabled_reg, 0, 0));
529    }
530
531    /// `imm`: 0=Always, 1=OnFailure, 2=Never.
532    pub(crate) fn emit_set_restart_policy(&mut self, policy: u8) {
533        self.emit(Instruction::only_imm(
534            Opcode::SetRestartPolicy,
535            i32::from(policy),
536        ));
537    }
538
539    /// Park for a host-side async completion into `dst`.
540    ///
541    /// Encoding: `HostAwait ra, rb, imm` → `a=dest`, `b=args`, `imm=op`.
542    pub(crate) fn emit_host_await(&mut self, dst: u8, args_reg: u8, op: u32) {
543        self.emit(Instruction::new(
544            Opcode::HostAwait,
545            dst,
546            args_reg,
547            0,
548            op as i32,
549        ));
550    }
551
552    pub(crate) fn emit_register_name(&mut self, name_reg: u8) {
553        self.emit(Instruction::abc(Opcode::RegisterName, name_reg, 0, 0));
554    }
555
556    pub(crate) fn emit_whereis(&mut self, dst: u8, name_reg: u8) {
557        self.emit(Instruction::abc(Opcode::Whereis, dst, name_reg, 0));
558    }
559
560    pub(crate) fn emit_trap(&mut self, code: i32) {
561        self.emit(Instruction::only_imm(Opcode::Trap, code));
562    }
563
564    pub(crate) fn emit_call(&mut self, dst: u8, function: u32, argc: u8) {
565        self.emit(Instruction::new(
566            Opcode::Call,
567            dst,
568            argc,
569            0,
570            function as i32,
571        ));
572    }
573
574    /// Emit a call through the runtime's native (FFI) function table
575    /// (design notes §30-31). `native_index` is resolved by name against a
576    /// [`crate::NativeTable`] at the call site — the assembler has no
577    /// knowledge of what natives exist, on purpose (see
578    /// [`crate::verify`]'s note on why `CallNative` targets aren't
579    /// range-checked statically).
580    pub(crate) fn emit_call_native(&mut self, dst: u8, native_index: u32, argc: u8) {
581        self.emit(Instruction::new(
582            Opcode::CallNative,
583            dst,
584            argc,
585            0,
586            native_index as i32,
587        ));
588    }
589
590    /// `r[dst] = native_1(r[src])` as a single [`Opcode::CallNativeFrom`].
591    ///
592    /// `Opcode::CallNative` writes the result over its first argument. This
593    /// form keeps `src` intact when `dst != src`, which is what unpacking one
594    /// `Message` into several fields needs:
595    ///
596    /// ```text
597    /// b.emit_native1_from(1, 0, native_msg_sender);   // r1 = sender(r0)
598    /// b.emit_native1_from(2, 0, native_msg_request_id);
599    /// ```
600    ///
601    /// A multi-arg native still uses [`Self::emit_call_native`]: the arguments
602    /// have to sit in a contiguous window, and the result overwrites `r[base]`.
603    pub(crate) fn emit_native1_from(&mut self, dst: u8, src: u8, native_index: u32) {
604        self.emit(Instruction::new(
605            Opcode::CallNativeFrom,
606            dst,
607            src,
608            0,
609            native_index as i32,
610        ));
611    }
612
613    /// `CallNative(base, native_index, argc)` when `argc` args are **already**
614    /// contiguous at `r[base..base+argc]`.
615    ///
616    /// No behavior beyond [`Self::emit_call_native`] — exists so the call site
617    /// reads as "args already packed".
618    pub(crate) fn emit_native_n(&mut self, base: u8, native_index: u32, argc: u8) {
619        self.emit_call_native(base, native_index, argc);
620    }
621
622    pub(crate) fn emit_return(&mut self, reg: u8) {
623        self.emit(Instruction::abc(Opcode::Return, reg, 0, 0));
624    }
625
626    /// Mark the start of a bytecode function at the current position and
627    /// register it in the function table under `name`. Returns the function
628    /// index, usable with [`ChunkBuilder::emit_call`]/[`ChunkBuilder::emit_spawn`]
629    /// even before the function's body is emitted (functions may call
630    /// themselves or each other, forward or backward).
631    pub(crate) fn begin_function(
632        &mut self,
633        name: impl Into<String>,
634        arity: u8,
635        num_registers: u8,
636    ) -> u32 {
637        let name = name.into();
638        let entry = self.code.len() as u32;
639        let idx = self.functions.len() as u32;
640        self.functions.push(FunctionDef {
641            name: name.clone(),
642            entry,
643            arity,
644            num_registers,
645        });
646        self.fn_starts.insert(name, idx);
647        idx
648    }
649
650    pub(crate) fn function_index(&self, name: &str) -> Option<u32> {
651        self.fn_starts.get(name).copied()
652    }
653
654    /// Patch the register-file size of an already-`begin_function`'d
655    /// function. Exists for assemblers whose register count is only known
656    /// *after* emitting the body — `begin_function` must still be called
657    /// first so `entry` captures the current code position.
658    pub(crate) fn set_num_registers(&mut self, function_index: u32, num_registers: u8) {
659        if let Some(def) = self.functions.get_mut(function_index as usize) {
660            def.num_registers = num_registers;
661        }
662    }
663
664    /// Resolve every pending jump against its bound label and produce the
665    /// final immutable [`Chunk`].
666    ///
667    /// An unbound label is a host assembly bug. This method does **not**
668    /// panic: the jump becomes `Trap` so it cannot fall through as a no-op.
669    /// A relative offset that does not fit in `i32` is the same trap.
670    pub(crate) fn finish(mut self) -> Chunk {
671        for (idx, label) in self.pending_jumps.drain(..) {
672            let imm = self.label_targets.get(&label).and_then(|target| {
673                // Relative offset from the instruction *after* this jump.
674                let offset = i64::from(*target) - (idx as i64 + 1);
675                i32::try_from(offset).ok()
676            });
677            match imm {
678                Some(imm) => self.code[idx].imm = imm,
679                None => {
680                    self.code[idx].op = Opcode::Trap;
681                    self.code[idx].imm = 0;
682                }
683            }
684        }
685        Chunk {
686            name: self.name,
687            constants: self.constants,
688            code: self.code,
689            functions: self.functions,
690        }
691    }
692}
693#[cfg(test)]
694mod tests {
695    use super::*;
696
697    #[test]
698    fn unbound_label_becomes_a_trap() {
699        let mut b = ChunkBuilder::new("t");
700        b.begin_function("main", 0, 1);
701        let missing = b.new_label();
702        b.emit_jump(missing);
703        b.emit_return(0);
704        let chunk = b.finish();
705        assert_eq!(chunk.code[0].op, Opcode::Trap);
706    }
707
708    #[test]
709    fn emit_native1_from_never_clobbers_source_register() {
710        let mut b = ChunkBuilder::new("clobber-test");
711        b.begin_function("main", 0, 8);
712        b.emit_native1_from(1, 0, 10);
713        b.emit_native1_from(2, 0, 11);
714        b.emit_native1_from(3, 0, 12);
715        let chunk = b.finish();
716
717        assert_eq!(chunk.code.len(), 3);
718        for (idx, dest, expected_native) in [(0usize, 1u8, 10i32), (1, 2, 11), (2, 3, 12)] {
719            let instr = chunk.code[idx];
720            assert_eq!(instr.op, Opcode::CallNativeFrom);
721            assert_eq!(instr.b, 0, "source register stays r0");
722            assert_eq!(instr.a, dest);
723            assert_ne!(instr.a, instr.b);
724            assert_eq!(instr.imm, expected_native);
725        }
726    }
727
728    #[test]
729    fn emit_native_n_is_a_plain_call_native_with_no_extra_instructions() {
730        let mut b = ChunkBuilder::new("native-n-test");
731        b.begin_function("main", 0, 8);
732        b.emit_load_imm(1, 7);
733        b.emit_load_imm(2, 1);
734        b.emit_native_n(1, 99, 2);
735        let chunk = b.finish();
736
737        assert_eq!(chunk.code.len(), 3);
738        assert_eq!(chunk.code[2].op, Opcode::CallNative);
739        assert_eq!(chunk.code[2].a, 1);
740        assert_eq!(chunk.code[2].b, 2);
741        assert_eq!(chunk.code[2].imm, 99);
742    }
743}