byteflow-actors 0.9.19

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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
//! Primary API for assembling [`Chunk`] programs in host Rust.
//!
//! Use [`Program`] to define a module and [`Fn`] to emit each function with
//! named registers instead of manual `r0` / `emit_*` bookkeeping.
//!
//! ```rust
//! use byteflow::Program;
//!
//! let mut program = Program::new("count");
//! program.function("main", 0, |f| {
//!     let limit = f.load_int(100);
//!     let counter = f.load_i32(0);
//!     f.while_lt(counter, limit, |f| f.add_imm(counter, 1));
//!     f.return_(counter);
//! });
//! let chunk = program.build();
//! ```

use super::builder::ChunkBuilder;

pub use super::builder::Label;
use super::chunk::Chunk;
use super::opcode::Opcode;
use super::value::Value;

/// Function index returned by [`Program::function`].
pub type FuncId = u32;

/// A virtual register in the current function.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Reg(u8);

impl Reg {
    /// Underlying register index in the bytecode function frame.
    pub const fn index(self) -> u8 {
        self.0
    }
}

impl From<Reg> for u8 {
    fn from(r: Reg) -> u8 {
        r.0
    }
}

/// Contiguous register window (e.g. four slots for `make_msg` natives).
#[derive(Clone, Copy, Debug)]
pub struct RegWindow {
    base: Reg,
    len: u8,
}

impl RegWindow {
    /// First register in the window (native result lands here for `make_msg`).
    pub fn base(self) -> Reg {
        self.base
    }

    /// Register at offset `i` within the window (`0 <= i < len`).
    pub fn at(self, i: u8) -> Reg {
        debug_assert!(i < self.len, "RegWindow index out of bounds");
        match self.base.0.checked_add(i) {
            Some(idx) => Reg(idx),
            None => Reg(u8::MAX),
        }
    }
}

/// Assemble one bytecode module.
pub struct Program {
    inner: ChunkBuilder,
}

impl Program {
    /// Start a new module named `name`.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            inner: ChunkBuilder::new(name),
        }
    }

    /// Define a function and run `body` against a fresh [`Fn`] context.
    ///
    /// Returns the function index for [`Fn::spawn`] / [`Fn::call`]
    /// (pass argument registers as `&[Reg]`, not a bare argc).
    pub fn function(
        &mut self,
        name: impl Into<String>,
        arity: u8,
        body: impl FnOnce(&mut Fn<'_>),
    ) -> FuncId {
        let mut f = Fn::open(&mut self.inner, name, arity);
        let id = f.function;
        body(&mut f);
        id
    }

    /// Define a function with an explicit register-file size.
    ///
    /// Useful for fixed register layouts (`reg(255)`) or verification demos
    /// where `num_registers < arity` must fail static checks.
    pub fn function_raw(
        &mut self,
        name: impl Into<String>,
        arity: u8,
        num_registers: u8,
        body: impl FnOnce(&mut Fn<'_>),
    ) -> FuncId {
        let mut f = Fn::open_with(&mut self.inner, name, arity, num_registers);
        let id = f.function;
        body(&mut f);
        id
    }

    /// Look up a function index by name (available before [`Self::build`]).
    pub fn function_index(&self, name: &str) -> Option<FuncId> {
        self.inner.function_index(name)
    }

    /// Finish assembly and produce an immutable [`Chunk`].
    pub fn build(self) -> Chunk {
        self.inner.finish()
    }
}

/// Emit instructions for one bytecode function.
pub struct Fn<'a> {
    b: &'a mut ChunkBuilder,
    function: FuncId,
    next_reg: u8,
}

impl<'a> Fn<'a> {
    fn open(b: &'a mut ChunkBuilder, name: impl Into<String>, arity: u8) -> Self {
        // Parameters occupy `r0..arity`. Locals continue from there, so a
        // 0-arity function starts at `r0` instead of leaving four dead slots.
        Self::open_with(b, name, arity, arity)
    }

    fn open_with(
        b: &'a mut ChunkBuilder,
        name: impl Into<String>,
        arity: u8,
        num_registers: u8,
    ) -> Self {
        let function = b.begin_function(name, arity, num_registers);
        Self {
            b,
            function,
            next_reg: num_registers,
        }
    }

    /// Allocate a fresh local register.
    ///
    /// A frame is at most 255 slots (`num_registers` is a `u8`), so index
    /// 255 is not a real register. One more `local` emits `Trap` and returns
    /// `r0` instead of aliasing an existing slot.
    pub fn local(&mut self) -> Reg {
        if self.next_reg == u8::MAX {
            self.b.emit_trap(0);
            return Reg(0);
        }
        let reg = Reg(self.next_reg);
        self.next_reg += 1;
        self.b.set_num_registers(self.function, self.next_reg);
        reg
    }

    /// Bind to an explicit register index without growing the declared frame.
    pub fn reg(&mut self, index: u8) -> Reg {
        Reg(index)
    }

    /// Ensure the register file is at least `count` slots wide.
    pub fn reserve(&mut self, count: u8) {
        if count > self.next_reg {
            self.next_reg = count;
            self.b.set_num_registers(self.function, self.next_reg);
        }
    }

    /// Allocate `count` contiguous locals; useful before [`Self::native_n`].
    pub fn window(&mut self, count: u8) -> RegWindow {
        let base_idx = self.next_reg;
        for _ in 0..count {
            let _ = self.local();
        }
        RegWindow {
            base: Reg(base_idx),
            len: count,
        }
    }

    /// Fresh contiguous locals `r[start .. start+count]`, or `None` if that
    /// window would leave the `u8` register space.
    fn alloc_contig(&mut self, count: u8) -> Option<Reg> {
        if count == 0 {
            return None;
        }
        let start = self.next_reg;
        if u16::from(start) + u16::from(count) > 256 {
            return None;
        }
        for i in 0..count {
            let r = self.local();
            if r.0 != start.saturating_add(i) {
                return None;
            }
        }
        Some(Reg(start))
    }

    fn copy_window(&mut self, base: Reg, args: &[Reg]) {
        for (i, &src) in args.iter().enumerate() {
            let slot = match u8::try_from(i) {
                Ok(off) => Reg(base.0.saturating_add(off)),
                Err(_) => continue,
            };
            if slot != src {
                self.b.emit_move(slot.0, src.0);
            }
        }
    }

    /// Fail-closed pack: Trap so the VM never runs a half-built Call/Spawn.
    fn fail_pack(&mut self) -> Reg {
        self.b.emit_trap(0);
        self.local()
    }

    /// Load a small immediate into a new local.
    pub fn load_i32(&mut self, n: i32) -> Reg {
        let reg = self.local();
        self.b.emit_load_imm(reg.0, n);
        reg
    }

    /// Load a constant-pool integer into a new local.
    pub fn load_int(&mut self, n: i64) -> Reg {
        let konst = self.b.const_(Value::Int(n));
        let reg = self.local();
        self.b.emit_load_const(reg.0, konst);
        reg
    }

    /// Store an immediate into an existing register.
    pub fn set(&mut self, reg: Reg, imm: i32) {
        self.b.emit_load_imm(reg.0, imm);
    }

    /// `dst = src`
    pub fn mov(&mut self, dst: Reg, src: Reg) {
        self.b.emit_move(dst.0, src.0);
    }

    fn binop(&mut self, op: Opcode, lhs: Reg, rhs: Reg) -> Reg {
        let dst = self.local();
        self.b.emit_binop(op, dst.0, lhs.0, rhs.0);
        dst
    }

    /// `dst = lhs + rhs` into a new local.
    pub fn add(&mut self, lhs: Reg, rhs: Reg) -> Reg {
        self.binop(Opcode::Add, lhs, rhs)
    }

    /// `dst += imm` in place. One [`Opcode::AddImm`], no scratch register.
    pub fn add_imm(&mut self, dst: Reg, imm: i32) {
        self.b.emit_add_imm(dst.0, dst.0, imm);
    }

    /// `dst -= imm` in place. One [`Opcode::SubImm`].
    pub fn sub_imm(&mut self, dst: Reg, imm: i32) {
        self.b.emit_sub_imm(dst.0, dst.0, imm);
    }

    /// `lhs < imm` as `Bool`, in a fresh local. One [`Opcode::LtImm`].
    pub fn lt_imm(&mut self, lhs: Reg, imm: i32) -> Reg {
        let dst = self.local();
        self.b.emit_lt_imm(dst.0, lhs.0, imm);
        dst
    }

    /// `dst *= imm` in place. One [`Opcode::MulImm`]. Integer multiply wraps.
    pub fn mul_imm(&mut self, dst: Reg, imm: i32) {
        self.b.emit_mul_imm(dst.0, dst.0, imm);
    }

    /// `lhs <= imm` as `Bool`, in a fresh local. One [`Opcode::LeImm`].
    pub fn le_imm(&mut self, lhs: Reg, imm: i32) -> Reg {
        let dst = self.local();
        self.b.emit_le_imm(dst.0, lhs.0, imm);
        dst
    }

    /// `lhs & rhs` into a new local. Both operands must be `Int` at runtime.
    pub fn bit_and(&mut self, lhs: Reg, rhs: Reg) -> Reg {
        self.bitop(Opcode::BitAnd, lhs, rhs)
    }

    /// `lhs | rhs` into a new local.
    pub fn bit_or(&mut self, lhs: Reg, rhs: Reg) -> Reg {
        self.bitop(Opcode::BitOr, lhs, rhs)
    }

    /// `lhs ^ rhs` into a new local.
    pub fn bit_xor(&mut self, lhs: Reg, rhs: Reg) -> Reg {
        self.bitop(Opcode::BitXor, lhs, rhs)
    }

    /// `!src` into a new local.
    pub fn bit_not(&mut self, src: Reg) -> Reg {
        let dst = self.local();
        self.b.emit_bit_not(dst.0, src.0);
        dst
    }

    /// `lhs << rhs` into a new local. The count keeps its low 6 bits.
    pub fn shl(&mut self, lhs: Reg, rhs: Reg) -> Reg {
        self.bitop(Opcode::Shl, lhs, rhs)
    }

    /// Arithmetic `lhs >> rhs` into a new local. The count keeps its low 6 bits.
    pub fn shr(&mut self, lhs: Reg, rhs: Reg) -> Reg {
        self.bitop(Opcode::Shr, lhs, rhs)
    }

    fn bitop(&mut self, op: Opcode, lhs: Reg, rhs: Reg) -> Reg {
        let dst = self.local();
        self.b.emit_bit_binop(op, dst.0, lhs.0, rhs.0);
        dst
    }

    /// Pack `items` into a new list local. `items` must already be contiguous
    /// registers (`rN, rN+1, …`) and at most 32 long.
    pub fn list_pack(&mut self, items: &[Reg]) -> Reg {
        let dst = self.local();
        let base = match items.first() {
            Some(reg) => reg.0,
            None => 0,
        };
        self.b.emit_list_pack(dst.0, base, items.len() as i32);
        dst
    }

    pub fn list_get(&mut self, list: Reg, index: i32) -> Reg {
        let dst = self.local();
        self.b.emit_list_get(dst.0, list.0, index);
        dst
    }

    pub fn list_len(&mut self, list: Reg) -> Reg {
        let dst = self.local();
        self.b.emit_list_len(dst.0, list.0);
        dst
    }

    /// Pack `pairs` into a map. Each pair is `(key, value)` already in
    /// registers. Keys are `Int` or `Str`. At most 32 pairs.
    pub fn map_pack(&mut self, pairs: &[(Reg, Reg)]) -> Reg {
        let dst = self.local();
        let base = match pairs.first() {
            Some((key, _)) => key.0,
            None => 0,
        };
        self.b.emit_map_pack(dst.0, base, pairs.len() as i32);
        dst
    }

    pub fn map_get(&mut self, map: Reg, key: Reg) -> Reg {
        let dst = self.local();
        self.b.emit_map_get(dst.0, map.0, key.0);
        dst
    }

    pub fn map_len(&mut self, map: Reg) -> Reg {
        let dst = self.local();
        self.b.emit_map_len(dst.0, map.0);
        dst
    }

    /// Open this flow's table and return its Cap (`SEND` and `RECV`).
    pub fn table_open(&mut self, name: Reg) -> Reg {
        let dst = self.local();
        self.b.emit_table_open(dst.0, name.0);
        dst
    }

    /// Read `key` from `table`. Missing key yields `Unit`.
    pub fn table_get(&mut self, table: Reg, key: Reg) -> Reg {
        let dst = self.local();
        self.b.emit_table_get(dst.0, table.0, key.0);
        dst
    }

    /// Store `value` at `key` in `table`.
    pub fn table_put(&mut self, table: Reg, key: Reg, value: Reg) {
        self.b.emit_table_put(table.0, key.0, value.0);
    }

    pub fn sub(&mut self, lhs: Reg, rhs: Reg) -> Reg {
        self.binop(Opcode::Sub, lhs, rhs)
    }

    pub fn mul(&mut self, lhs: Reg, rhs: Reg) -> Reg {
        self.binop(Opcode::Mul, lhs, rhs)
    }

    pub fn div(&mut self, lhs: Reg, rhs: Reg) -> Reg {
        self.binop(Opcode::Div, lhs, rhs)
    }

    pub fn modulo(&mut self, lhs: Reg, rhs: Reg) -> Reg {
        self.binop(Opcode::Mod, lhs, rhs)
    }

    pub fn neg(&mut self, src: Reg) -> Reg {
        let dst = self.local();
        self.b.emit_neg(dst.0, src.0);
        dst
    }

    pub fn eq(&mut self, lhs: Reg, rhs: Reg) -> Reg {
        self.binop(Opcode::Eq, lhs, rhs)
    }

    /// `lhs == imm` as `Bool`, in a fresh local. One [`Opcode::EqImm`].
    ///
    /// The immediate is an `Int`. A float in `lhs` compares unequal.
    pub fn eq_imm(&mut self, lhs: Reg, imm: i32) -> Reg {
        let dst = self.local();
        self.b.emit_eq_imm(dst.0, lhs.0, imm);
        dst
    }

    pub fn lt(&mut self, lhs: Reg, rhs: Reg) -> Reg {
        self.binop(Opcode::Lt, lhs, rhs)
    }

    pub fn le(&mut self, lhs: Reg, rhs: Reg) -> Reg {
        self.binop(Opcode::Le, lhs, rhs)
    }

    /// While `counter < limit` (interpreter `Branch` skips on falsy).
    pub fn while_lt<F>(&mut self, counter: Reg, limit: Reg, body: F)
    where
        F: FnOnce(&mut Fn<'_>),
    {
        let head = self.b.new_label();
        let done = self.b.new_label();
        let cond = self.local();
        self.b.bind_label(head);
        self.b.emit_binop(Opcode::Lt, cond.0, counter.0, limit.0);
        self.b.emit_branch(cond.0, done);
        body(self);
        self.b.emit_jump(head);
        self.b.bind_label(done);
    }

    pub fn label(&mut self) -> Label {
        self.b.new_label()
    }

    pub fn bind(&mut self, label: Label) {
        self.b.bind_label(label);
    }

    pub fn move_reg(&mut self, dst: Reg, src: Reg) {
        self.b.emit_move(dst.0, src.0);
    }

    pub fn jump(&mut self, label: Label) {
        self.b.emit_jump(label);
    }

    /// Branch when `cond` is falsy (`0`).
    pub fn branch_if_falsy(&mut self, cond: Reg, target: Label) {
        self.b.emit_branch(cond.0, target);
    }

    pub fn return_(&mut self, value: Reg) {
        self.b.emit_return(value.0);
    }

    /// Call `function` with `args` packed into a fresh `Call` window.
    ///
    /// The ISA reads `r[dst .. dst+argc]` and writes the result to `r[dst]`.
    /// This copies `args` into that window so `call(fn, &[a, b])` after
    /// `load_i32` actually passes those values — a bare argc does not.
    pub fn call(&mut self, function: FuncId, args: &[Reg]) -> Reg {
        let Some(argc) = u8::try_from(args.len()).ok() else {
            return self.fail_pack();
        };
        let dst = if argc == 0 {
            self.local()
        } else {
            match self.alloc_contig(argc) {
                Some(base) => {
                    self.copy_window(base, args);
                    base
                }
                None => return self.fail_pack(),
            }
        };
        self.b.emit_call(dst.0, function, argc);
        dst
    }

    pub fn halt(&mut self) {
        self.b.emit_halt();
    }

    pub fn yield_(&mut self) {
        self.b.emit_yield();
    }

    pub fn sleep(&mut self, millis: Reg) {
        self.b.emit_sleep(millis.0);
    }

    pub fn exit(&mut self, reg: Reg) {
        self.b.emit_exit(reg.0);
    }

    /// Self Cap ([`CapRights::ADDRESSING`](crate::CapRights::ADDRESSING):
    /// `SEND|ASK|LINK|MONITOR` for this flow).
    ///
    /// Despite the opcode name (`SelfPid`), the value is a [`crate::Value::Cap`],
    /// not a Pid. In BEAM terms this is closer to a **reply address** grant
    /// than to `self()` — use [`Self::hop_sender`] on a *delivered* hop for
    /// authenticated origin identity.
    pub fn self_cap(&mut self) -> Reg {
        let cap = self.local();
        self.b.emit_self_pid(cap.0);
        cap
    }

    /// Alias for [`Self::self_cap`] — preferred name when coming from BEAM.
    pub fn self_address(&mut self) -> Reg {
        self.self_cap()
    }

    /// Spawn `function` with `args` packed into `r[cap+1 .. cap+1+argc]`.
    ///
    /// The ISA writes the child Cap into `r[cap]` and reads arguments from
    /// the following slots — not from the registers you just `load_*`'d.
    /// This allocates that window and copies `args` into it.
    pub fn spawn(&mut self, function: FuncId, args: &[Reg]) -> Reg {
        self.spawn_with_rights(function, args, crate::bytecode::CapRights::FLOW)
    }

    /// Spawn a child that receives only `rights` ⊆ parent authority.
    pub fn spawn_with_rights(
        &mut self,
        function: FuncId,
        args: &[Reg],
        rights: crate::bytecode::CapRights,
    ) -> Reg {
        let Some(argc) = u8::try_from(args.len()).ok() else {
            return self.fail_pack();
        };
        let Some(window) = argc.checked_add(1) else {
            return self.fail_pack();
        };
        let Some(cap) = self.alloc_contig(window) else {
            return self.fail_pack();
        };
        self.copy_window(Reg(cap.0.saturating_add(1)), args);
        self.b.emit_spawn_with_rights(cap.0, function, argc, rights);
        cap
    }

    /// Spawn with `rights = NONE` (confined by default).
    pub fn spawn_confined(&mut self, function: FuncId, args: &[Reg]) -> Reg {
        self.spawn_with_rights(function, args, crate::bytecode::CapRights::NONE)
    }

    /// Spawn into an explicit destination. Args must already sit in
    /// `r[dst+1 .. dst+1+argc]` (see [`Self::window`]). Prefer [`Self::spawn`].
    pub fn spawn_at(&mut self, dst: Reg, function: FuncId, argc: u8) {
        self.b.emit_spawn(dst.0, function, argc);
    }

    /// Spawn into `dst` with an explicit rights mask. Same packing contract
    /// as [`Self::spawn_at`].
    pub fn spawn_at_with_rights(
        &mut self,
        dst: Reg,
        function: FuncId,
        argc: u8,
        rights: crate::bytecode::CapRights,
    ) {
        self.b.emit_spawn_with_rights(dst.0, function, argc, rights);
    }

    /// Attenuate `src` into a new Cap (rights mask is an immediate).
    /// Native mask is unchanged (`Delegate.c = 255`).
    pub fn delegate(&mut self, src: Reg, rights: crate::bytecode::CapRights) -> Reg {
        let dst = self.local();
        self.b.emit_delegate(dst.0, src.0, rights);
        dst
    }

    /// Like [`Self::delegate`], but AND the native mask from `native_cap`
    /// (`Delegate.c` is that register, not 255). `native_cap` must carry
    /// [`crate::CapRights::NATIVE`].
    pub fn delegate_with_native(
        &mut self,
        src: Reg,
        rights: crate::bytecode::CapRights,
        native_cap: Reg,
    ) -> Reg {
        let dst = self.local();
        self.b
            .emit_delegate_with_native(dst.0, src.0, rights, Some(native_cap.0));
        dst
    }

    pub fn send(&mut self, target_cap: Reg, msg: Reg) {
        self.b.emit_send(target_cap.0, msg.0);
    }

    /// Fire-and-forget hop (BEAM `!` / `gen_server:cast`).
    pub fn cast(&mut self, target_cap: Reg, msg: Reg) {
        self.send(target_cap, msg);
    }

    pub fn receive(&mut self) -> Reg {
        let msg = self.local();
        self.b.emit_receive(msg.0);
        msg
    }

    pub fn receive_timeout(&mut self, millis: Reg) -> Reg {
        let msg = self.local();
        self.b.emit_receive_timeout(msg.0, millis.0);
        msg
    }

    pub fn receive_match(&mut self, tag: Reg) -> Reg {
        let msg = self.local();
        self.b.emit_receive_match(msg.0, tag.0);
        msg
    }

    pub fn receive_match_imm(&mut self, tag: u16) -> Reg {
        let msg = self.local();
        self.b.emit_receive_match_imm(msg.0, tag);
        msg
    }

    /// Selective receive with BEAM `after`: `Unit` if `millis` elapses first.
    pub fn receive_match_timeout(&mut self, tag: Reg, millis: Reg) -> Reg {
        let msg = self.local();
        self.b.emit_receive_match_timeout(msg.0, tag.0, millis.0);
        msg
    }

    /// Immediate-tag selective receive with BEAM `after`.
    pub fn receive_match_imm_timeout(&mut self, tag: u16, millis: Reg) -> Reg {
        let msg = self.local();
        self.b.emit_receive_match_imm_timeout(msg.0, tag, millis.0);
        msg
    }

    /// BEAM `is_process_alive/1` for a Cap this flow holds.
    pub fn is_alive(&mut self, cap: Reg) -> Reg {
        let dst = self.local();
        self.b.emit_is_alive(dst.0, cap.0);
        dst
    }

    /// BEAM `exit/2`. `reason` is a [`crate::FlowExitReason`] as `Int` (`0..=6`).
    /// Needs `LINK` on `cap`. `Normal` does nothing. `Killed` ignores `trap_exit`.
    pub fn exit_signal(&mut self, cap: Reg, reason: Reg) {
        self.b.emit_exit_signal(cap.0, reason.0);
    }

    /// Process dictionary `put/2`. Returns the previous value or `Unit`.
    /// The value is a scalar, `Str`, or `Bytes`. Heap values stay charged
    /// after the source register is overwritten.
    pub fn dict_put(&mut self, key: Reg, value: Reg) -> Reg {
        let dst = self.local();
        self.b.emit_dict_put(dst.0, key.0, value.0);
        dst
    }

    /// Process dictionary `get/1`. Missing key → `Unit`.
    pub fn dict_get(&mut self, key: Reg) -> Reg {
        let dst = self.local();
        self.b.emit_dict_get(dst.0, key.0);
        dst
    }

    /// Process dictionary `erase/1`. Returns the removed value or `Unit`.
    pub fn dict_erase(&mut self, key: Reg) -> Reg {
        let dst = self.local();
        self.b.emit_dict_erase(dst.0, key.0);
        dst
    }

    /// Selective receive: tag and an `Int` payload compared with `bound`.
    ///
    /// `Eq`, `Lt`, and `Le` use signed integers. A hop whose payload is not
    /// that `Int`, or that fails the comparison, stays in the mailbox.
    pub fn receive_match_cmp(&mut self, tag: Reg, bound: Reg, cmp: crate::bytecode::IntCmp) -> Reg {
        let msg = self.local();
        self.b.emit_receive_match_cmp(msg.0, tag.0, bound.0, cmp);
        msg
    }

    /// Selective receive: application tag **and** `Int` payload equality.
    pub fn receive_match_eq(&mut self, tag: Reg, payload: Reg) -> Reg {
        let msg = self.local();
        self.b.emit_receive_match_eq(msg.0, tag.0, payload.0);
        msg
    }

    /// Selective receive: tag **and** structural equality with `payload`.
    ///
    /// `payload` may be any value (`Str`, `Bytes`, `Bool`, `Float`, nested
    /// hop). Non-matching hops stay queued.
    pub fn receive_match_value(&mut self, tag: Reg, payload: Reg) -> Reg {
        let msg = self.local();
        self.b.emit_receive_match_value(msg.0, tag.0, payload.0);
        msg
    }

    /// Deliver `msg` to `name` on `node` via [`crate::DistributionBridge`].
    pub fn send_remote(&mut self, node: Reg, name: Reg, msg: Reg) {
        self.b.emit_send_remote(node.0, name.0, msg.0);
    }

    /// Start a supervisor for this flow. Later [`Self::start_child`] attaches
    /// to it. `strategy` is one-for-one, one-for-all, or rest-for-one.
    pub fn start_supervisor(&mut self, strategy: crate::RestartStrategy) {
        let byte = match strategy {
            crate::RestartStrategy::OneForOne => 0,
            crate::RestartStrategy::OneForAll => 1,
            crate::RestartStrategy::RestForOne => 2,
        };
        self.b.emit_start_supervisor(byte);
    }

    /// OTP child of this flow's supervisor. Caller must have been started
    /// by [`crate::Supervisor`]. `policy` is Always / OnFailure / Never.
    pub fn start_child(&mut self, function: FuncId, policy: crate::RestartPolicy) -> Reg {
        let dst = self.local();
        self.b.emit_start_child(dst.0, function, policy.as_u8());
        dst
    }

    /// Server loop: `receive_match_imm(tag)` → `body` → jump back.
    pub fn actor_loop(&mut self, tag: u16, mut body: impl FnMut(&mut Self, Reg)) {
        let loop_lbl = self.label();
        self.bind(loop_lbl);
        let req = self.receive_match_imm(tag);
        body(self, req);
        self.jump(loop_lbl);
    }

    /// Next per-flow correlation id (`Int`, starts at 1).
    pub fn fresh_request_id(&mut self) -> Reg {
        let dst = self.local();
        self.b.emit_fresh_request_id(dst.0);
        dst
    }

    /// Wait for `tag == tag_reg` and `request_id == id_reg` (FIFO skip).
    pub fn receive_match_corr(&mut self, tag: Reg, request_id: Reg) -> Reg {
        let msg = self.local();
        self.b.emit_receive_match_corr(msg.0, tag.0, request_id.0);
        msg
    }

    /// Wait for immediate `tag` and `request_id == id_reg` (FIFO skip).
    pub fn receive_match_corr_imm(&mut self, tag: u16, request_id: Reg) -> Reg {
        let msg = self.local();
        self.b.emit_receive_match_corr_imm(msg.0, tag, request_id.0);
        msg
    }

    /// Wait for a hop whose `payload.wire_tag() == kind` (`0..=10`, FIFO skip).
    pub fn receive_match_kind(&mut self, kind: u8) -> Reg {
        let msg = self.local();
        self.b.emit_receive_match_kind(msg.0, kind);
        msg
    }

    /// Build a hop with a freshly minted `request_id`.
    ///
    /// The id is written straight into the `make_msg` window, so the usual
    /// copy from a temporary register is not emitted.
    pub fn hop_fresh(&mut self, tag: i32, payload: Reg) -> Reg {
        let w = self.window(3);
        self.b.emit_fresh_request_id(w.at(0).0);
        self.fill_msg_window(
            w,
            w.at(0),
            tag,
            payload,
            crate::natives::std_native::MAKE_MSG,
        )
    }

    /// RPC hop: deliver `msg` to `target_cap`, wait for correlated reply.
    ///
    /// If the target exits first, dest is a [`crate::TAG_SYS_EXIT`] hop
    /// (not a hang).
    pub fn ask(&mut self, target_cap: Reg, msg: Reg) -> Reg {
        let reply = self.local();
        self.b.emit_ask(reply.0, target_cap.0, msg.0);
        reply
    }

    /// Like [`Self::ask`], but writes `Unit` into the dest if `millis` elapses.
    pub fn ask_timeout(&mut self, target_cap: Reg, msg: Reg, millis: Reg) -> Reg {
        let reply = self.local();
        self.b
            .emit_ask_timeout(reply.0, target_cap.0, msg.0, millis.0);
        reply
    }

    /// One-way watch: when the flow addressed by `target_cap` exits, this
    /// flow receives a [`crate::TAG_SYS_DOWN`] hop. Returns a monitor ref (`Int`).
    pub fn monitor(&mut self, target_cap: Reg) -> Reg {
        let dst = self.local();
        self.b.emit_monitor(dst.0, target_cap.0);
        dst
    }

    pub fn demonitor(&mut self, monitor: Reg) {
        self.b.emit_demonitor(monitor.0);
    }

    /// Bidirectional link: without `trap_exit`, abnormal exit of either side
    /// kills the peer. With [`Self::set_trap_exit`] on a peer, that peer gets
    /// [`crate::TAG_SYS_EXIT`] hops instead (including `Normal`).
    pub fn link(&mut self, target_cap: Reg) -> Reg {
        let dst = self.local();
        self.b.emit_link(dst.0, target_cap.0);
        dst
    }

    pub fn unlink(&mut self, link: Reg) {
        self.b.emit_unlink(link.0);
    }

    /// BEAM `process_flag(trap_exit, enabled)`. Truthy `enabled` converts
    /// linked exits into [`crate::TAG_SYS_EXIT`] hops (including `Normal`)
    /// instead of killing this flow / silently dropping the link.
    pub fn set_trap_exit(&mut self, enabled: Reg) {
        self.b.emit_set_trap_exit(enabled.0);
    }

    /// Set this flow's supervisor restart policy (bytecode slice of OTP
    /// `child_spec` restart). Takes effect for the **current** incarnation;
    /// the dying flow's policy is what the supervisor consults on exit.
    pub fn set_restart_policy(&mut self, policy: super::RestartPolicy) {
        self.b.emit_set_restart_policy(policy.as_u8());
    }

    /// Register a host operation and return the register that holds its ticket (`Int`).
    ///
    /// `op` is an opaque host discriminator (`imm`). `args` is a single
    /// [`crate::Value`] handed to the bridge. The flow keeps running. The
    /// host's result arrives later as a [`crate::TAG_SYS_AWAIT`] hop
    /// (`request_id` = ticket); read it with [`Self::receive`].
    pub fn host_await(&mut self, op: u32, args: Reg) -> Reg {
        let dst = self.local();
        self.b.emit_host_await(dst.0, args.0, op);
        dst
    }

    /// Load a UTF-8 constant into a new local.
    pub fn load_str(&mut self, s: impl AsRef<str>) -> Reg {
        let konst = self.b.const_(Value::str(s));
        let reg = self.local();
        self.b.emit_load_const(reg.0, konst);
        reg
    }

    /// Load a byte-buffer constant into a new local.
    pub fn load_bytes(&mut self, bytes: impl AsRef<[u8]>) -> Reg {
        let konst = self.b.const_(Value::bytes(bytes.as_ref()));
        let reg = self.local();
        self.b.emit_load_const(reg.0, konst);
        reg
    }

    /// Publish `name` (`Str`) as this flow. Requires `SEND` on self-authority.
    pub fn register_name(&mut self, name: Reg) {
        self.b.emit_register_name(name.0);
    }

    /// Look up `name` (`Str`): SEND Cap for the caller, or `Unit`.
    pub fn whereis(&mut self, name: Reg) -> Reg {
        let dst = self.local();
        self.b.emit_whereis(dst.0, name.0);
        dst
    }

    pub fn trap(&mut self, code: i32) {
        self.b.emit_trap(code);
    }

    /// Copy `src`, call a one-arg native, return the result in a new local.
    ///
    /// The source register is preserved (`CallNative` clobbers its argument slot).
    pub fn native1_from(&mut self, src: Reg, native: u32) -> Reg {
        let dst = self.local();
        self.b.emit_native1_from(dst.0, src.0, native);
        dst
    }

    /// Side-effect native on a copy of `src` (e.g. `print`).
    pub fn native1_on(&mut self, src: Reg, native: u32) {
        let tmp = self.local();
        self.b.emit_native1_from(tmp.0, src.0, native);
    }

    /// `CallNative` with `argc` args already at `base..base+argc`.
    pub fn native_n(&mut self, base: Reg, native: u32, argc: u8) {
        self.b.emit_native_n(base.0, native, argc);
    }

    /// Call a native with `argc` args already in `base..base+argc`.
    pub fn call_native(&mut self, base: Reg, native: u32, argc: u8) {
        self.native_n(base, native, argc);
    }

    /// Call a zero-arg native; returns the result register.
    pub fn call_native0(&mut self, native: u32) -> Reg {
        let dst = self.local();
        self.b.emit_call_native(dst.0, native, 0);
        dst
    }

    /// Build an outgoing Atomic Hop (`request_id`, `tag`, `payload`).
    ///
    /// The scheduler overwrites `sender` and attaches `reply_cap` on [`Self::send`]
    /// / [`Self::ask`]. Prefer [`Self::hop_fresh`] so `request_id` is unique.
    /// Do not forge a sender (see [`crate::docs::security`]).
    pub fn hop(&mut self, request_id: Reg, tag: i32, payload: Reg) -> Reg {
        self.make_msg(
            crate::natives::std_native::MAKE_MSG,
            request_id,
            tag,
            payload,
        )
    }

    /// Extract authenticated origin from a delivered hop (`Value::Pid`).
    pub fn hop_sender(&mut self, msg: Reg) -> Reg {
        self.native1_from(msg, crate::natives::std_native::MSG_SENDER)
    }

    pub fn hop_request_id(&mut self, msg: Reg) -> Reg {
        self.native1_from(msg, crate::natives::std_native::MSG_REQUEST_ID)
    }

    pub fn hop_tag(&mut self, msg: Reg) -> Reg {
        self.native1_from(msg, crate::natives::std_native::MSG_TAG)
    }

    pub fn hop_payload(&mut self, msg: Reg) -> Reg {
        self.native1_from(msg, crate::natives::std_native::MSG_PAYLOAD)
    }

    /// Reply address grant minted for the original sender (`Value::Cap`).
    pub fn hop_reply_cap(&mut self, msg: Reg) -> Reg {
        self.native1_from(msg, crate::natives::std_native::MSG_REPLY_CAP)
    }

    /// Build a reply hop echoing `request_id` from `req`.
    pub fn reply_to(&mut self, req: Reg, tag: i32, payload: Reg) -> Reg {
        let req_id = self.hop_request_id(req);
        self.hop(req_id, tag, payload)
    }

    /// Reply to `req` via its `reply_cap` (typical server pattern).
    pub fn send_reply(&mut self, req: Reg, tag: i32, payload: Reg) {
        let reply_cap = self.hop_reply_cap(req);
        let reply = self.reply_to(req, tag, payload);
        self.send(reply_cap, reply);
    }

    /// Build a [`Value::Message`] via `make_msg` at `native_index`.
    ///
    /// There is no sender operand — the scheduler stamps identity on `Send`.
    /// A 4-arg legacy encoding is still accepted by the native (first arg
    /// discarded) so forged-sender regressions keep compiling.
    pub fn make_msg(&mut self, native_index: u32, request_id: Reg, tag: i32, payload: Reg) -> Reg {
        let w = self.window(3);
        self.fill_msg_window(w, request_id, tag, payload, native_index)
    }

    /// Pack `(request_id, tag, payload)` into `w` and call `make_msg`.
    ///
    /// A copy onto the same register is omitted, which is how
    /// [`Self::hop_fresh`] plants the new id in `w[0]` without a `Move`.
    fn fill_msg_window(
        &mut self,
        w: RegWindow,
        request_id: Reg,
        tag: i32,
        payload: Reg,
        native_index: u32,
    ) -> Reg {
        self.mov(w.at(0), request_id);
        self.set(w.at(1), tag);
        self.mov(w.at(2), payload);
        self.native_n(w.base(), native_index, 3);
        w.base()
    }

    /// Legacy 4-arg `make_msg` (sender slot is ignored by the native).
    pub fn make_msg_legacy_sender(
        &mut self,
        native_index: u32,
        sender: Reg,
        request_id: Reg,
        tag: i32,
        payload: Reg,
    ) -> Reg {
        let w = self.window(4);
        self.mov(w.at(0), sender);
        self.mov(w.at(1), request_id);
        self.set(w.at(2), tag);
        self.mov(w.at(3), payload);
        self.native_n(w.base(), native_index, 4);
        w.base()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{NativeTable, Value, Vm, VmResult};

    type TestResult = Result<(), Box<dyn std::error::Error>>;

    fn count_to(n: i64) -> Chunk {
        let mut program = Program::new("count");
        program.function("main", 0, |f| {
            let limit = f.load_int(n);
            let counter = f.load_i32(0);
            f.while_lt(counter, limit, |f| f.add_imm(counter, 1));
            f.return_(counter);
        });
        program.build()
    }

    #[test]
    fn local_past_the_register_file_traps() {
        let mut program = Program::new("full");
        program.function("main", 0, |f| {
            // Arity 0 starts at r0; fill through r254, then one more.
            while f.next_reg < u8::MAX {
                let _ = f.local();
            }
            let _ = f.local();
        });
        let chunk = program.build();
        assert!(
            chunk.code.iter().any(|instr| instr.op == Opcode::Trap),
            "the 256th register must not alias an existing slot"
        );
    }

    #[test]
    fn function_raw_keeps_declared_register_file_for_verify() -> TestResult {
        let mut program = Program::new("malformed");
        program.function_raw("main", 3, 1, |f| {
            let r0 = f.reg(0);
            f.return_(r0);
        });
        let chunk = program.build();
        assert_eq!(chunk.functions[0].arity, 3);
        assert_eq!(chunk.functions[0].num_registers, 1);
        assert!(matches!(
            crate::verify(&chunk),
            Err(crate::VerifyError::ArityExceedsRegisters {
                function: 0,
                arity: 3,
                num_registers: 1,
            })
        ));
        Ok(())
    }

    #[test]
    fn add_imm_is_one_instruction_and_frame_starts_at_r0() -> TestResult {
        let mut program = Program::new("compact");
        program.function("main", 0, |f| {
            let n = f.load_i32(1);
            f.add_imm(n, 41);
            f.return_(n);
        });
        let chunk = program.build();
        assert_eq!(chunk.functions[0].num_registers, 1);
        assert_eq!(chunk.code.len(), 3);
        assert_eq!(chunk.code[0].op, Opcode::LoadImm);
        assert_eq!(chunk.code[0].a, 0);
        assert_eq!(chunk.code[1].op, Opcode::AddImm);
        assert_eq!(chunk.code[1].a, 0);
        assert_eq!(chunk.code[1].b, 0);
        assert_eq!(chunk.code[1].imm, 41);
        let mut vm = Vm::new(std::sync::Arc::new(chunk), NativeTable::empty(), 0, &[])?;
        assert!(matches!(vm.run(10_000), VmResult::Complete(Value::Int(42))));
        Ok(())
    }

    #[test]
    fn eq_imm_and_bitwise_are_single_instructions() -> TestResult {
        let mut program = Program::new("bits");
        program.function("main", 0, |f| {
            let n = f.load_i32(6);
            f.mul_imm(n, 7);
            let _same = f.eq_imm(n, 42);
            let one = f.load_i32(1);
            let shifted = f.shl(n, one);
            let _mask = f.bit_and(shifted, n);
            f.return_(n);
        });
        let chunk = program.build();
        assert!(chunk.code.iter().any(|instr| instr.op == Opcode::MulImm));
        assert!(chunk.code.iter().any(|instr| instr.op == Opcode::EqImm));
        assert!(chunk.code.iter().any(|instr| instr.op == Opcode::Shl));
        assert!(chunk.code.iter().any(|instr| instr.op == Opcode::BitAnd));
        assert!(!chunk
            .code
            .iter()
            .any(|instr| instr.op == Opcode::LoadImm && instr.imm == 42));
        let mut vm = Vm::new(std::sync::Arc::new(chunk), NativeTable::empty(), 0, &[])?;
        assert!(matches!(vm.run(10_000), VmResult::Complete(Value::Int(42))));
        Ok(())
    }

    #[test]
    fn count_loop_returns_n() -> TestResult {
        let chunk = count_to(100);
        let mut vm = Vm::new(std::sync::Arc::new(chunk), NativeTable::empty(), 0, &[])?;
        assert!(matches!(
            vm.run(10_000),
            VmResult::Complete(Value::Int(100))
        ));
        Ok(())
    }

    #[test]
    fn ping_pong_shape() -> TestResult {
        let chunk = crate::samples::ping_pong();
        crate::verify(&chunk)?;
        assert!(chunk.functions.iter().any(|f| f.name == "main"));
        assert!(chunk.functions.iter().any(|f| f.name == "pong"));
        Ok(())
    }

    #[test]
    fn call_passes_loaded_ints() -> TestResult {
        let mut program = Program::new("call-args");
        let add = program.function("add", 2, |f| {
            let a = f.reg(0);
            let b = f.reg(1);
            let sum = f.add(a, b);
            f.return_(sum);
        });
        let main = program.function("main", 0, |f| {
            let a = f.load_i32(10);
            let b = f.load_i32(32);
            let out = f.call(add, &[a, b]);
            f.return_(out);
        });
        let chunk = program.build();
        crate::verify(&chunk)?;
        let mut vm = Vm::new(std::sync::Arc::new(chunk), NativeTable::empty(), main, &[])?;
        assert!(matches!(vm.run(10_000), VmResult::Complete(Value::Int(42))));
        Ok(())
    }

    #[test]
    fn spawn_gathers_loaded_ints() -> TestResult {
        let mut program = Program::new("spawn-args");
        let child = program.function("child", 2, |f| {
            let a = f.reg(0);
            f.return_(a);
        });
        let main = program.function("main", 0, |f| {
            let a = f.load_i32(10);
            let b = f.load_i32(32);
            let _cap = f.spawn(child, &[a, b]);
            f.halt();
        });
        let chunk = program.build();
        crate::verify(&chunk)?;
        let mut vm = Vm::new(std::sync::Arc::new(chunk), NativeTable::empty(), main, &[])?;
        match vm.run(10_000) {
            VmResult::Spawn { function, args, .. } => {
                assert_eq!(function, child);
                assert_eq!(args, vec![Value::Int(10), Value::Int(32)]);
            }
            other => return Err(format!("expected Spawn, got {other:?}").into()),
        }
        Ok(())
    }

    #[test]
    fn delegate_with_native_sets_c() -> TestResult {
        let mut program = Program::new("delegate-native");
        program.function("main", 0, |f| {
            let src = f.self_cap();
            let native = f.self_cap();
            let _rights_only = f.delegate(src, crate::bytecode::CapRights::SEND);
            let _narrowed = f.delegate_with_native(src, crate::bytecode::CapRights::SEND, native);
            f.return_(src);
        });
        let chunk = program.build();
        let delegates: Vec<_> = chunk
            .code
            .iter()
            .filter(|i| i.op == Opcode::Delegate)
            .collect();
        assert_eq!(delegates.len(), 2);
        assert_eq!(delegates[0].c, 255);
        assert_ne!(delegates[1].c, 255);
        Ok(())
    }
}