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