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