byteflow-actors 0.9.24

Embeddable flow runtime: M:N scheduler, Atomic Hop (Message+Cap), supervisor — use byteflow::
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
use std::collections::HashMap;

use super::chunk::{Chunk, FunctionDef};
use super::instruction::Instruction;
use super::opcode::Opcode;
use super::value::Value;

/// An unresolved jump target, patched to a relative offset once its address
/// is known (see `ChunkBuilder::bind_label`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Label(u32);

/// Low-level fluent assembler for [`Chunk`]s (crate-internal).
///
/// External callers should use [`crate::Program`] / [`crate::Fn`]. This type
/// handles label back-patching and raw opcode emission for the public API.
pub(crate) struct ChunkBuilder {
    name: String,
    constants: Vec<Value>,
    code: Vec<Instruction>,
    functions: Vec<FunctionDef>,
    next_label: u32,
    label_targets: HashMap<Label, u32>,
    /// (instruction index, label) pairs awaiting patch.
    pending_jumps: Vec<(usize, Label)>,
    fn_starts: HashMap<String, u32>,
}

impl ChunkBuilder {
    pub fn new(name: impl Into<String>) -> Self {
        ChunkBuilder {
            name: name.into(),
            constants: Vec::with_capacity(32),
            code: Vec::with_capacity(128),
            functions: Vec::with_capacity(8),
            next_label: 0,
            label_targets: HashMap::with_capacity(16),
            pending_jumps: Vec::with_capacity(16),
            fn_starts: HashMap::with_capacity(8),
        }
    }

    pub fn const_(&mut self, v: Value) -> u32 {
        // Constant deduplication keeps hot small-int/bool literals from
        // bloating the pool across a large generated function.
        if let Some(pos) = self.constants.iter().position(|c| c == &v) {
            return pos as u32;
        }
        self.constants.push(v);
        (self.constants.len() - 1) as u32
    }

    pub fn new_label(&mut self) -> Label {
        let l = Label(self.next_label);
        self.next_label += 1;
        l
    }

    /// Bind `label` to the *next* instruction that will be emitted.
    pub fn bind_label(&mut self, label: Label) {
        self.label_targets.insert(label, self.code.len() as u32);
    }

    fn emit(&mut self, instr: Instruction) -> usize {
        self.code.push(instr);
        self.code.len() - 1
    }

    pub fn emit_halt(&mut self) {
        self.emit(Instruction::nullary(Opcode::Halt));
    }

    pub fn emit_load_const(&mut self, dst: u8, konst: u32) {
        self.emit(Instruction::new(Opcode::LoadConst, dst, 0, 0, konst as i32));
    }

    pub fn emit_load_imm(&mut self, dst: u8, imm: i32) {
        self.emit(Instruction::a_imm(Opcode::LoadImm, dst, imm));
    }

    pub fn emit_move(&mut self, dst: u8, src: u8) {
        if dst == src {
            return;
        }
        self.emit(Instruction::abc(Opcode::Move, dst, src, 0));
    }

    /// `r[dst] = r[src] + imm`. Does not allocate a scratch register.
    pub fn emit_add_imm(&mut self, dst: u8, src: u8, imm: i32) {
        self.emit(Instruction::new(Opcode::AddImm, dst, src, 0, imm));
    }

    pub fn emit_sub_imm(&mut self, dst: u8, src: u8, imm: i32) {
        self.emit(Instruction::new(Opcode::SubImm, dst, src, 0, imm));
    }

    pub fn emit_lt_imm(&mut self, dst: u8, src: u8, imm: i32) {
        self.emit(Instruction::new(Opcode::LtImm, dst, src, 0, imm));
    }

    /// `r[dst] = r[src] * imm`. Does not allocate a scratch register.
    pub fn emit_mul_imm(&mut self, dst: u8, src: u8, imm: i32) {
        self.emit(Instruction::new(Opcode::MulImm, dst, src, 0, imm));
    }

    /// `r[dst] = Bool(r[src] == Int(imm))`.
    pub fn emit_eq_imm(&mut self, dst: u8, src: u8, imm: i32) {
        self.emit(Instruction::new(Opcode::EqImm, dst, src, 0, imm));
    }

    /// `r[dst] = Bool(r[src] != Int(imm))`.
    #[allow(dead_code)]
    pub fn emit_ne_imm(&mut self, dst: u8, src: u8, imm: i32) {
        self.emit(Instruction::new(Opcode::NeImm, dst, src, 0, imm));
    }

    /// `r[dst] = Bool(r[src] <= imm)`.
    pub fn emit_le_imm(&mut self, dst: u8, src: u8, imm: i32) {
        self.emit(Instruction::new(Opcode::LeImm, dst, src, 0, imm));
    }

    /// `r[dst] = Bool(r[src] > imm)`.
    #[allow(dead_code)]
    pub fn emit_gt_imm(&mut self, dst: u8, src: u8, imm: i32) {
        self.emit(Instruction::new(Opcode::GtImm, dst, src, 0, imm));
    }

    /// `r[dst] = Bool(r[src] >= imm)`.
    #[allow(dead_code)]
    pub fn emit_ge_imm(&mut self, dst: u8, src: u8, imm: i32) {
        self.emit(Instruction::new(Opcode::GeImm, dst, src, 0, imm));
    }

    pub fn emit_bit_binop(&mut self, op: Opcode, dst: u8, lhs: u8, rhs: u8) {
        debug_assert!(matches!(
            op,
            Opcode::BitAnd
                | Opcode::BitOr
                | Opcode::BitXor
                | Opcode::Shl
                | Opcode::Shr
                | Opcode::Ushr
        ));
        self.emit(Instruction::abc(op, dst, lhs, rhs));
    }

    pub fn emit_bit_not(&mut self, dst: u8, src: u8) {
        self.emit(Instruction::abc(Opcode::BitNot, dst, src, 0));
    }

    pub fn emit_list_pack(&mut self, dst: u8, base: u8, count: i32) {
        self.emit(Instruction::new(Opcode::ListPack, dst, base, 0, count));
    }

    pub fn emit_list_get(&mut self, dst: u8, src: u8, index: i32) {
        self.emit(Instruction::new(Opcode::ListGet, dst, src, 0, index));
    }

    pub fn emit_list_len(&mut self, dst: u8, src: u8) {
        self.emit(Instruction::abc(Opcode::ListLen, dst, src, 0));
    }

    #[allow(dead_code)]
    pub fn emit_str_len(&mut self, dst: u8, src: u8) {
        self.emit(Instruction::abc(Opcode::StrLen, dst, src, 0));
    }

    #[allow(dead_code)]
    pub fn emit_bytes_len(&mut self, dst: u8, src: u8) {
        self.emit(Instruction::abc(Opcode::BytesLen, dst, src, 0));
    }

    pub fn emit_record_pack(&mut self, dst: u8, base: u8, count: i32) {
        self.emit(Instruction::new(Opcode::RecordPack, dst, base, 0, count));
    }

    pub fn emit_record_get(&mut self, dst: u8, src: u8, index: i32) {
        self.emit(Instruction::new(Opcode::RecordGet, dst, src, 0, index));
    }

    pub fn emit_record_len(&mut self, dst: u8, src: u8) {
        self.emit(Instruction::abc(Opcode::RecordLen, dst, src, 0));
    }

    pub fn emit_map_pack(&mut self, dst: u8, base: u8, pairs: i32) {
        self.emit(Instruction::new(Opcode::MapPack, dst, base, 0, pairs));
    }

    pub fn emit_map_get(&mut self, dst: u8, map: u8, key: u8) {
        self.emit(Instruction::abc(Opcode::MapGet, dst, map, key));
    }

    pub fn emit_map_len(&mut self, dst: u8, map: u8) {
        self.emit(Instruction::abc(Opcode::MapLen, dst, map, 0));
    }

    pub fn emit_receive_match_cmp(
        &mut self,
        dst: u8,
        tag: u8,
        bound: u8,
        cmp: super::opcode::IntCmp,
    ) {
        self.emit(Instruction::new(
            Opcode::ReceiveMatchCmp,
            dst,
            tag,
            bound,
            cmp.as_imm(),
        ));
    }

    pub fn emit_table_open(&mut self, dst: u8, name: u8) {
        self.emit(Instruction::abc(Opcode::TableOpen, dst, name, 0));
    }

    pub fn emit_table_get(&mut self, dst: u8, cap: u8, key: u8) {
        self.emit(Instruction::abc(Opcode::TableGet, dst, cap, key));
    }

    pub fn emit_table_put(&mut self, cap: u8, key: u8, value: u8) {
        self.emit(Instruction::abc(Opcode::TablePut, cap, key, value));
    }

    pub fn emit_binop(&mut self, op: Opcode, dst: u8, lhs: u8, rhs: u8) {
        debug_assert!(matches!(
            op,
            Opcode::Add
                | Opcode::Sub
                | Opcode::Mul
                | Opcode::Div
                | Opcode::Mod
                | Opcode::Eq
                | Opcode::Lt
                | Opcode::Le
        ));
        self.emit(Instruction::abc(op, dst, lhs, rhs));
    }

    pub fn emit_neg(&mut self, dst: u8, src: u8) {
        self.emit(Instruction::abc(Opcode::Neg, dst, src, 0));
    }

    pub fn emit_jump(&mut self, target: Label) {
        let idx = self.emit(Instruction::only_imm(Opcode::Jump, 0));
        self.pending_jumps.push((idx, target));
    }

    pub fn emit_branch(&mut self, cond: u8, target: Label) {
        let idx = self.emit(Instruction::a_imm(Opcode::Branch, cond, 0));
        self.pending_jumps.push((idx, target));
    }

    pub fn emit_spawn(&mut self, dst: u8, function: u32, argc: u8) {
        self.emit_spawn_with_rights(dst, function, argc, crate::bytecode::CapRights::FLOW);
    }

    /// Bytecode spawn with an explicit rights request (`instr.c`). `NONE` is
    /// confined: the child inherits no power until a later `Delegate`.
    pub fn emit_spawn_with_rights(
        &mut self,
        dst: u8,
        function: u32,
        argc: u8,
        rights: crate::bytecode::CapRights,
    ) {
        self.emit(Instruction::new(
            Opcode::Spawn,
            dst,
            argc,
            rights.bits_u8(),
            function as i32,
        ));
    }

    pub fn emit_delegate(&mut self, dst: u8, src_cap: u8, rights: crate::bytecode::CapRights) {
        self.emit_delegate_with_native(dst, src_cap, rights, None);
    }

    /// `c = 255` means no extra native-mask narrowing (VM keeps the source
    /// mask). Any other `c` is a Cap register whose `NATIVE` mask is AND-ed
    /// in — the only assembler path that emits `c ≠ 255`.
    pub fn emit_delegate_with_native(
        &mut self,
        dst: u8,
        src_cap: u8,
        rights: crate::bytecode::CapRights,
        native_cap: Option<u8>,
    ) {
        let native_reg = match native_cap {
            Some(reg) => reg,
            None => 255,
        };
        self.emit(Instruction::new(
            Opcode::Delegate,
            dst,
            src_cap,
            native_reg,
            rights.bits() as i32,
        ));
    }

    pub fn emit_yield(&mut self) {
        self.emit(Instruction::nullary(Opcode::Yield));
    }

    pub fn emit_sleep(&mut self, millis_reg: u8) {
        self.emit(Instruction::abc(Opcode::Sleep, millis_reg, 0, 0));
    }

    pub fn emit_exit(&mut self, reg: u8) {
        self.emit(Instruction::abc(Opcode::Exit, reg, 0, 0));
    }

    /// Write a **self Cap** ([`CapRights::ADDRESSING`](crate::CapRights::ADDRESSING))
    /// into `dst` (opcode still named `SelfPid`).
    pub fn emit_self_pid(&mut self, dst: u8) {
        self.emit(Instruction::abc(Opcode::SelfPid, dst, 0, 0));
    }

    /// Write the next per-flow correlation id into `dst`.
    pub fn emit_fresh_request_id(&mut self, dst: u8) {
        self.emit(Instruction::abc(Opcode::FreshRequestId, dst, 0, 0));
    }

    /// Fire-and-forget Atomic Hop: `r[target_cap_reg]` must be Cap; `r[msg_reg]` Message.
    pub fn emit_send(&mut self, target_cap_reg: u8, msg_reg: u8) {
        self.emit(Instruction::abc(Opcode::Send, target_cap_reg, msg_reg, 0));
    }

    pub fn emit_receive(&mut self, dst: u8) {
        self.emit(Instruction::abc(Opcode::Receive, dst, 0, 0));
    }

    pub fn emit_receive_timeout(&mut self, dst: u8, millis_reg: u8) {
        self.emit(Instruction::abc(Opcode::ReceiveTimeout, dst, millis_reg, 0));
    }

    /// Selective Atomic Hop: wait for `Message` with `tag == r[tag_reg]`.
    pub fn emit_receive_match(&mut self, dst: u8, tag_reg: u8) {
        self.emit(Instruction::abc(Opcode::ReceiveMatch, dst, tag_reg, 0));
    }

    /// Selective Atomic Hop with an immediate `u16` tag.
    pub fn emit_receive_match_imm(&mut self, dst: u8, tag: u16) {
        self.emit(Instruction::a_imm(
            Opcode::ReceiveMatchImm,
            dst,
            i32::from(tag),
        ));
    }

    /// Selective receive: `tag == r[tag_reg]` and `request_id == r[id_reg]`.
    pub fn emit_receive_match_corr(&mut self, dst: u8, tag_reg: u8, id_reg: u8) {
        self.emit(Instruction::abc(
            Opcode::ReceiveMatchCorr,
            dst,
            tag_reg,
            id_reg,
        ));
    }

    /// Selective receive with immediate tag and `request_id` from `id_reg`.
    pub fn emit_receive_match_corr_imm(&mut self, dst: u8, tag: u16, id_reg: u8) {
        self.emit(Instruction::new(
            Opcode::ReceiveMatchCorrImm,
            dst,
            id_reg,
            0,
            i32::from(tag),
        ));
    }

    /// Selective receive + `after`: `tag == r[tag_reg]`, timeout `r[millis_reg]`.
    pub fn emit_receive_match_timeout(&mut self, dst: u8, tag_reg: u8, millis_reg: u8) {
        self.emit(Instruction::abc(
            Opcode::ReceiveMatchTimeout,
            dst,
            tag_reg,
            millis_reg,
        ));
    }

    /// Selective receive + `after` with an immediate `u16` tag.
    pub fn emit_receive_match_imm_timeout(&mut self, dst: u8, tag: u16, millis_reg: u8) {
        self.emit(Instruction::new(
            Opcode::ReceiveMatchImmTimeout,
            dst,
            millis_reg,
            0,
            i32::from(tag),
        ));
    }

    /// BEAM `is_process_alive/1` for a held Cap.
    pub fn emit_is_alive(&mut self, dst: u8, cap_reg: u8) {
        self.emit(Instruction::abc(Opcode::IsAlive, dst, cap_reg, 0));
    }

    /// BEAM `exit/2`. `reason_reg` is a [`crate::FlowExitReason`] code.
    pub fn emit_exit_signal(&mut self, cap_reg: u8, reason_reg: u8) {
        self.emit(Instruction::abc(Opcode::ExitSignal, cap_reg, reason_reg, 0));
    }

    pub fn emit_dict_put(&mut self, dst: u8, key_reg: u8, value_reg: u8) {
        self.emit(Instruction::abc(Opcode::DictPut, dst, key_reg, value_reg));
    }

    pub fn emit_dict_get(&mut self, dst: u8, key_reg: u8) {
        self.emit(Instruction::abc(Opcode::DictGet, dst, key_reg, 0));
    }

    pub fn emit_dict_erase(&mut self, dst: u8, key_reg: u8) {
        self.emit(Instruction::abc(Opcode::DictErase, dst, key_reg, 0));
    }

    /// Selective receive: tag register + `Int` payload equality.
    pub fn emit_receive_match_eq(&mut self, dst: u8, tag_reg: u8, payload_reg: u8) {
        self.emit(Instruction::abc(
            Opcode::ReceiveMatchEq,
            dst,
            tag_reg,
            payload_reg,
        ));
    }

    /// Selective receive: tag register + structural payload equality.
    pub fn emit_receive_match_value(&mut self, dst: u8, tag_reg: u8, payload_reg: u8) {
        self.emit(Instruction::abc(
            Opcode::ReceiveMatchValue,
            dst,
            tag_reg,
            payload_reg,
        ));
    }

    /// Hand a hop to the host distribution bridge.
    pub fn emit_send_remote(&mut self, node_reg: u8, name_reg: u8, msg_reg: u8) {
        self.emit(Instruction::abc(
            Opcode::SendRemote,
            node_reg,
            name_reg,
            msg_reg,
        ));
    }

    /// Start a supervisor for this flow. `strategy` is `0..=2`.
    pub fn emit_start_supervisor(&mut self, strategy: u8) {
        self.emit(Instruction::only_imm(
            Opcode::StartSupervisor,
            i32::from(strategy),
        ));
    }

    /// Spawn `function` under this flow's supervisor. `policy` is `0..=2`.
    pub fn emit_start_child(&mut self, dst: u8, function: u32, policy: u8) {
        self.emit(Instruction::new(
            Opcode::StartChild,
            dst,
            policy,
            0,
            match i32::try_from(function) {
                Ok(n) => n,
                Err(_) => i32::MAX,
            },
        ));
    }

    /// Selective receive: wait for a hop whose payload wire-tag equals `kind`.
    pub fn emit_receive_match_kind(&mut self, dst: u8, kind: u8) {
        self.emit(Instruction::a_imm(
            Opcode::ReceiveMatchKind,
            dst,
            i32::from(kind),
        ));
    }

    /// Atomic request/reply hop: deliver `r[msg_reg]` to `r[target_cap_reg]` (Cap),
    /// then wait for a correlated reply into `dst`.
    ///
    /// Encoding: `Ask ra, rb, rc` → `a=dest`, `b=target Cap`, `c=request Message`.
    ///
    /// The worker authenticates the request (`sender` + `reply_cap`) before delivery
    /// and completes only when the reply’s `sender` equals the **resolved FlowId**.
    pub fn emit_ask(&mut self, dest: u8, target_cap_reg: u8, msg_reg: u8) {
        self.emit(Instruction::abc(Opcode::Ask, dest, target_cap_reg, msg_reg));
    }

    /// Like [`Self::emit_ask`], with a timeout register in `imm`.
    pub fn emit_ask_timeout(&mut self, dest: u8, target_cap_reg: u8, msg_reg: u8, millis_reg: u8) {
        self.emit(Instruction::new(
            Opcode::AskTimeout,
            dest,
            target_cap_reg,
            msg_reg,
            i32::from(millis_reg),
        ));
    }

    pub fn emit_monitor(&mut self, dest: u8, target_cap_reg: u8) {
        self.emit(Instruction::abc(Opcode::Monitor, dest, target_cap_reg, 0));
    }

    pub fn emit_demonitor(&mut self, monitor_reg: u8) {
        self.emit(Instruction::abc(Opcode::Demonitor, monitor_reg, 0, 0));
    }

    pub fn emit_link(&mut self, dest: u8, target_cap_reg: u8) {
        self.emit(Instruction::abc(Opcode::Link, dest, target_cap_reg, 0));
    }

    pub fn emit_unlink(&mut self, link_reg: u8) {
        self.emit(Instruction::abc(Opcode::Unlink, link_reg, 0, 0));
    }

    pub fn emit_set_trap_exit(&mut self, enabled_reg: u8) {
        self.emit(Instruction::abc(Opcode::SetTrapExit, enabled_reg, 0, 0));
    }

    /// `imm`: 0=Always, 1=OnFailure, 2=Never.
    pub fn emit_set_restart_policy(&mut self, policy: u8) {
        self.emit(Instruction::only_imm(
            Opcode::SetRestartPolicy,
            i32::from(policy),
        ));
    }

    /// Park for a host-side async completion into `dst`.
    ///
    /// Encoding: `HostAwait ra, rb, imm` → `a=dest`, `b=args`, `imm=op`.
    pub fn emit_host_await(&mut self, dst: u8, args_reg: u8, op: u32) {
        self.emit(Instruction::new(
            Opcode::HostAwait,
            dst,
            args_reg,
            0,
            op as i32,
        ));
    }

    pub fn emit_register_name(&mut self, name_reg: u8) {
        self.emit(Instruction::abc(Opcode::RegisterName, name_reg, 0, 0));
    }

    pub fn emit_whereis(&mut self, dst: u8, name_reg: u8) {
        self.emit(Instruction::abc(Opcode::Whereis, dst, name_reg, 0));
    }

    pub fn emit_trap(&mut self, code: i32) {
        self.emit(Instruction::only_imm(Opcode::Trap, code));
    }

    pub fn emit_call(&mut self, dst: u8, function: u32, argc: u8) {
        self.emit(Instruction::new(
            Opcode::Call,
            dst,
            argc,
            0,
            function as i32,
        ));
    }

    /// Emit a call through the runtime's native (FFI) function table
    /// (design notes §30-31). `native_index` is resolved by name against a
    /// [`crate::NativeTable`] at the call site — the assembler has no
    /// knowledge of what natives exist, on purpose (see
    /// [`crate::verify`]'s note on why `CallNative` targets aren't
    /// range-checked statically).
    pub fn emit_call_native(&mut self, dst: u8, native_index: u32, argc: u8) {
        self.emit(Instruction::new(
            Opcode::CallNative,
            dst,
            argc,
            0,
            native_index as i32,
        ));
    }

    /// `r[dst] = native_1(r[src])` as a single [`Opcode::CallNativeFrom`].
    ///
    /// `Opcode::CallNative` writes the result over its first argument. This
    /// form keeps `src` intact when `dst != src`, which is what unpacking one
    /// `Message` into several fields needs:
    ///
    /// ```text
    /// b.emit_native1_from(1, 0, native_msg_sender);   // r1 = sender(r0)
    /// b.emit_native1_from(2, 0, native_msg_request_id);
    /// ```
    ///
    /// A multi-arg native still uses [`Self::emit_call_native`]: the arguments
    /// have to sit in a contiguous window, and the result overwrites `r[base]`.
    pub fn emit_native1_from(&mut self, dst: u8, src: u8, native_index: u32) {
        self.emit(Instruction::new(
            Opcode::CallNativeFrom,
            dst,
            src,
            0,
            native_index as i32,
        ));
    }

    /// `CallNative(base, native_index, argc)` when `argc` args are **already**
    /// contiguous at `r[base..base+argc]`.
    ///
    /// No behavior beyond [`Self::emit_call_native`] — exists so the call site
    /// reads as "args already packed".
    pub fn emit_native_n(&mut self, base: u8, native_index: u32, argc: u8) {
        self.emit_call_native(base, native_index, argc);
    }

    pub fn emit_return(&mut self, reg: u8) {
        self.emit(Instruction::abc(Opcode::Return, reg, 0, 0));
    }

    /// Mark the start of a bytecode function at the current position and
    /// register it in the function table under `name`. Returns the function
    /// index, usable with [`ChunkBuilder::emit_call`]/[`ChunkBuilder::emit_spawn`]
    /// even before the function's body is emitted (functions may call
    /// themselves or each other, forward or backward).
    pub fn begin_function(&mut self, name: impl Into<String>, arity: u8, num_registers: u8) -> u32 {
        let name = name.into();
        let entry = self.code.len() as u32;
        let idx = self.functions.len() as u32;
        self.functions.push(FunctionDef {
            name: name.clone(),
            entry,
            arity,
            num_registers,
        });
        self.fn_starts.insert(name, idx);
        idx
    }

    pub fn function_index(&self, name: &str) -> Option<u32> {
        self.fn_starts.get(name).copied()
    }

    /// Patch the register-file size of an already-`begin_function`'d
    /// function. Exists for assemblers whose register count is only known
    /// *after* emitting the body — `begin_function` must still be called
    /// first so `entry` captures the current code position.
    pub fn set_num_registers(&mut self, function_index: u32, num_registers: u8) {
        if let Some(def) = self.functions.get_mut(function_index as usize) {
            def.num_registers = num_registers;
        }
    }

    /// Resolve every pending jump against its bound label and produce the
    /// final immutable [`Chunk`].
    ///
    /// An unbound label is a host assembly bug. This method does **not**
    /// panic: the jump becomes `Trap` so it cannot fall through as a no-op.
    /// A relative offset that does not fit in `i32` is the same trap.
    pub fn finish(mut self) -> Chunk {
        for (idx, label) in self.pending_jumps.drain(..) {
            let imm = self.label_targets.get(&label).and_then(|target| {
                // Relative offset from the instruction *after* this jump.
                let offset = i64::from(*target) - (idx as i64 + 1);
                i32::try_from(offset).ok()
            });
            match imm {
                Some(imm) => self.code[idx].imm = imm,
                None => {
                    self.code[idx].op = Opcode::Trap;
                    self.code[idx].imm = 0;
                }
            }
        }
        Chunk {
            name: self.name,
            constants: self.constants,
            code: self.code,
            functions: self.functions,
        }
    }
}
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unbound_label_becomes_a_trap() {
        let mut b = ChunkBuilder::new("t");
        b.begin_function("main", 0, 1);
        let missing = b.new_label();
        b.emit_jump(missing);
        b.emit_return(0);
        let chunk = b.finish();
        assert_eq!(chunk.code[0].op, Opcode::Trap);
    }

    #[test]
    fn emit_native1_from_never_clobbers_source_register() {
        let mut b = ChunkBuilder::new("clobber-test");
        b.begin_function("main", 0, 8);
        b.emit_native1_from(1, 0, 10);
        b.emit_native1_from(2, 0, 11);
        b.emit_native1_from(3, 0, 12);
        let chunk = b.finish();

        assert_eq!(chunk.code.len(), 3);
        for (idx, dest, expected_native) in [(0usize, 1u8, 10i32), (1, 2, 11), (2, 3, 12)] {
            let instr = chunk.code[idx];
            assert_eq!(instr.op, Opcode::CallNativeFrom);
            assert_eq!(instr.b, 0, "source register stays r0");
            assert_eq!(instr.a, dest);
            assert_ne!(instr.a, instr.b);
            assert_eq!(instr.imm, expected_native);
        }
    }

    #[test]
    fn emit_native_n_is_a_plain_call_native_with_no_extra_instructions() {
        let mut b = ChunkBuilder::new("native-n-test");
        b.begin_function("main", 0, 8);
        b.emit_load_imm(1, 7);
        b.emit_load_imm(2, 1);
        b.emit_native_n(1, 99, 2);
        let chunk = b.finish();

        assert_eq!(chunk.code.len(), 3);
        assert_eq!(chunk.code[2].op, Opcode::CallNative);
        assert_eq!(chunk.code[2].a, 1);
        assert_eq!(chunk.code[2].b, 2);
        assert_eq!(chunk.code[2].imm, 99);
    }
}