tycho-vm 0.3.6

TON-compatible VM for the Tycho node.
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
use std::mem::ManuallyDrop;
use std::rc::Rc;

#[cfg(feature = "tracing")]
use tracing::instrument;
use tycho_types::error::Error;
use tycho_types::prelude::*;

use crate::error::VmResult;
use crate::saferc::{SafeDelete, SafeRc, SafeRcMakeMut};
use crate::stack::{
    RcStackValue, Stack, StackValue, StackValueType, Tuple, TupleExt, load_slice_as_stack_value,
    store_slice_as_stack_value,
};
use crate::state::VmState;
use crate::util::{OwnedCellSlice, Uint4, ensure_empty_slice};

/// Total state of VM.
#[derive(Debug, Default, Clone)]
pub struct ControlData {
    pub nargs: Option<u16>,
    pub stack: Option<SafeRc<Stack>>,
    pub save: ControlRegs,
    pub cp: Option<u16>,
}

impl ControlData {
    pub fn require_nargs(&self, copy: usize) -> VmResult<()> {
        if matches!(self.nargs, Some(nargs) if (nargs as usize) < copy) {
            vm_bail!(StackUnderflow(copy as _))
        }
        Ok(())
    }
}

impl Store for ControlData {
    fn store_into(
        &self,
        builder: &mut CellBuilder,
        context: &dyn CellContext,
    ) -> Result<(), Error> {
        match self.nargs {
            None => ok!(builder.store_bit_zero()),
            Some(nargs) if nargs <= 0x1fff => {
                ok!(builder.store_bit_one());
                ok!(builder.store_uint(nargs as _, 13));
            }
            Some(_) => return Err(Error::IntOverflow),
        }

        ok!(self.stack.as_deref().store_into(builder, context));
        ok!(self.save.store_into(builder, context));
        ok!(self.cp.store_into(builder, context));
        Ok(())
    }
}

impl Load<'_> for ControlData {
    fn load_from(slice: &mut CellSlice<'_>) -> Result<Self, Error> {
        Ok(ControlData {
            nargs: match ok!(slice.load_bit()) {
                false => None,
                true => Some(ok!(slice.load_uint(13)) as u16),
            },
            stack: match ok!(slice.load_bit()) {
                false => None,
                true => Some(ok!(SafeRc::<Stack>::load_from(slice))),
            },
            save: ok!(ControlRegs::load_from(slice)),
            cp: ok!(Load::load_from(slice)),
        })
    }
}

/// Control registers page.
#[derive(Default, Debug, Clone)]
pub struct ControlRegs {
    pub c: [Option<RcCont>; 4],
    pub d: [Option<Cell>; 2],
    pub c7: Option<SafeRc<Tuple>>,
}

impl ControlRegs {
    const CONT_REG_COUNT: usize = 4;
    const DATA_REG_OFFSET: usize = Self::CONT_REG_COUNT;
    const DATA_REG_COUNT: usize = 2;
    const DATA_REG_RANGE: std::ops::Range<usize> =
        Self::DATA_REG_OFFSET..Self::DATA_REG_OFFSET + Self::DATA_REG_COUNT;

    pub fn is_valid_idx(i: usize) -> bool {
        i < Self::CONT_REG_COUNT || Self::DATA_REG_RANGE.contains(&i) || i == 7
    }

    pub fn merge(&mut self, other: &ControlRegs) {
        for (c, other_c) in std::iter::zip(&mut self.c, &other.c) {
            Self::merge_stack_value(c, other_c);
        }
        for (d, other_d) in std::iter::zip(&mut self.d, &other.d) {
            Self::merge_cell_value(d, other_d)
        }
        Self::merge_stack_value(&mut self.c7, &other.c7)
    }

    pub fn preclear(&mut self, other: &ControlRegs) {
        for (c, other_c) in std::iter::zip(&mut self.c, &other.c) {
            if other_c.is_some() {
                *c = None;
            }
        }
        for (d, other_d) in std::iter::zip(&mut self.d, &other.d) {
            if other_d.is_some() {
                *d = None;
            }
        }
        if other.c7.is_some() {
            self.c7 = None;
        }
    }

    // TODO: use `&dyn StackValue` for value?
    pub fn set(&mut self, i: usize, value: RcStackValue) -> VmResult<()> {
        if i < Self::CONT_REG_COUNT {
            self.c[i] = Some(ok!(value.into_cont()));
        } else if Self::DATA_REG_RANGE.contains(&i) {
            let cell = ok!(value.into_cell());
            self.d[i - Self::DATA_REG_OFFSET] = Some(SafeRc::unwrap_or_clone(cell));
        } else if i == 7 {
            self.c7 = Some(ok!(value.into_tuple()));
        } else {
            vm_bail!(ControlRegisterOutOfRange(i))
        }
        Ok(())
    }

    pub fn set_c(&mut self, i: usize, cont: RcCont) -> bool {
        if i < Self::CONT_REG_COUNT {
            self.c[i] = Some(cont);
            true
        } else {
            false
        }
    }

    pub fn set_d(&mut self, mut i: usize, cell: Cell) -> bool {
        i = i.wrapping_sub(Self::DATA_REG_OFFSET);
        if i < Self::DATA_REG_COUNT {
            self.d[i] = Some(cell);
            true
        } else {
            false
        }
    }

    pub fn get_d(&self, mut i: usize) -> Option<Cell> {
        i = i.wrapping_sub(Self::DATA_REG_OFFSET);
        if i < Self::DATA_REG_COUNT {
            self.d[i].clone()
        } else {
            None
        }
    }

    pub fn set_c7(&mut self, tuple: SafeRc<Tuple>) {
        self.c7 = Some(tuple);
    }

    pub fn get_as_stack_value(&self, i: usize) -> Option<RcStackValue> {
        if i < Self::CONT_REG_COUNT {
            self.c.get(i)?.clone().map(SafeRc::into_dyn_value)
        } else if Self::DATA_REG_RANGE.contains(&i) {
            self.d[i - Self::DATA_REG_OFFSET]
                .clone()
                .map(SafeRc::new_dyn_value)
        } else if i == 7 {
            self.c7.clone().map(SafeRc::into_dyn_value)
        } else {
            None
        }
    }

    pub fn define_c0(&mut self, cont: &Option<RcCont>) {
        if self.c[0].is_none() {
            self.c[0].clone_from(cont)
        }
    }

    pub fn define_c1(&mut self, cont: &Option<RcCont>) {
        if self.c[1].is_none() {
            self.c[1].clone_from(cont)
        }
    }

    pub fn define_c2(&mut self, cont: &Option<RcCont>) {
        if self.c[2].is_none() {
            self.c[2].clone_from(cont)
        }
    }

    pub fn define(&mut self, i: usize, value: RcStackValue) -> VmResult<()> {
        if i < Self::CONT_REG_COUNT {
            let cont = ok!(value.into_cont());
            vm_ensure!(self.c[i].is_none(), ControlRegisterRedefined);
            self.c[i] = Some(cont);
        } else if Self::DATA_REG_RANGE.contains(&i) {
            let cell = ok!(value.into_cell());
            let d = &mut self.d[i - Self::DATA_REG_OFFSET];
            vm_ensure!(d.is_none(), ControlRegisterRedefined);
            *d = Some(SafeRc::unwrap_or_clone(cell));
        } else if i == 7 {
            let tuple = ok!(value.into_tuple());

            // NOTE: Value is ignored on redefinition
            if self.c7.is_none() {
                self.c7 = Some(tuple);
            }
        } else {
            vm_bail!(ControlRegisterOutOfRange(i))
        }
        Ok(())
    }

    pub fn get_c7_params(&self) -> VmResult<&[RcStackValue]> {
        let Some(c7) = self.c7.as_ref() else {
            vm_bail!(ControlRegisterOutOfRange(7))
        };

        c7.try_get_tuple_range(0, 0..=255)
    }

    fn merge_cell_value(lhs: &mut Option<Cell>, rhs: &Option<Cell>) {
        if let Some(rhs) = rhs {
            if let Some(lhs) = lhs {
                let lhs = lhs.as_ref() as *const _ as *const ();
                let rhs = rhs.as_ref() as *const _ as *const ();
                if std::ptr::eq(lhs, rhs) {
                    return;
                }
            }
            *lhs = Some(rhs.clone())
        }
    }

    fn merge_stack_value<T: SafeDelete + ?Sized>(
        lhs: &mut Option<SafeRc<T>>,
        rhs: &Option<SafeRc<T>>,
    ) {
        if let Some(rhs) = rhs {
            if let Some(lhs) = lhs
                && SafeRc::ptr_eq(lhs, rhs)
            {
                return;
            }
            *lhs = Some(rhs.clone())
        }
    }
}

impl Store for ControlRegs {
    fn store_into(
        &self,
        builder: &mut CellBuilder,
        context: &dyn CellContext,
    ) -> Result<(), Error> {
        #[repr(transparent)]
        struct AsDictValue<'a>(&'a dyn StackValue);

        impl Store for AsDictValue<'_> {
            #[inline]
            fn store_into(
                &self,
                builder: &mut CellBuilder,
                context: &dyn CellContext,
            ) -> Result<(), Error> {
                self.0.store_as_stack_value(builder, context)
            }
        }

        // TODO: optimize by building dict manually

        let mut dict = Dict::<Uint4, AsDictValue>::new();

        for (i, c) in self.c.iter().enumerate() {
            if let Some(c) = c {
                ok!(dict.set_ext(Uint4(i), AsDictValue(c.as_stack_value()), context));
            }
        }
        for (i, d) in self.d.iter().enumerate() {
            if let Some(d) = d {
                ok!(dict.set_ext(Uint4(i + Self::DATA_REG_OFFSET), AsDictValue(d), context));
            }
        }
        if let Some(c7) = &self.c7 {
            ok!(dict.set_ext(Uint4(7), AsDictValue(c7.as_ref()), context));
        }

        dict.store_into(builder, context)
    }
}

impl Load<'_> for ControlRegs {
    fn load_from(slice: &mut CellSlice<'_>) -> Result<Self, Error> {
        let dict = ok!(Dict::<Uint4, CellSlice<'_>>::load_from(slice));

        let mut result = ControlRegs::default();
        for entry in dict.iter() {
            let (key, ref mut slice) = ok!(entry);
            let value = ok!(Stack::load_stack_value(slice));
            ok!(ensure_empty_slice(slice));
            if result.set(key.0, value).is_err() {
                return Err(Error::InvalidData);
            }
        }

        Ok(result)
    }
}

/// Continuation interface.
pub trait Cont: Store + SafeDelete + dyn_clone::DynClone + std::fmt::Debug {
    fn rc_into_dyn(self: Rc<Self>) -> Rc<dyn StackValue>;

    fn as_stack_value(&self) -> &dyn StackValue;

    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;

    fn jump(self: Rc<Self>, state: &mut VmState, exit_code: &mut i32) -> VmResult<Option<RcCont>>;

    fn get_control_data(&self) -> Option<&ControlData> {
        None
    }

    fn get_control_data_mut(&mut self) -> Option<&mut ControlData> {
        None
    }
}

impl<T: Cont + 'static> StackValue for T {
    #[inline]
    fn rc_into_dyn(self: Rc<Self>) -> Rc<dyn StackValue> {
        self
    }

    fn raw_ty(&self) -> u8 {
        StackValueType::Cont as _
    }

    fn store_as_stack_value(
        &self,
        builder: &mut CellBuilder,
        context: &dyn CellContext,
    ) -> Result<(), Error> {
        ok!(builder.store_u8(0x06));
        self.store_into(builder, context)
    }

    fn fmt_dump(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        ok!(f.write_str("Cont{{"));
        ok!(<T as Cont>::fmt(self, f));
        f.write_str("}}")
    }

    fn as_cont(&self) -> Option<&dyn Cont> {
        Some(self)
    }

    fn rc_into_cont(self: Rc<Self>) -> VmResult<Rc<dyn Cont>> {
        Ok(self)
    }
}

/// Continuation.
pub type RcCont = SafeRc<dyn Cont>;

impl<'a> Load<'a> for RcCont {
    #[inline]
    fn load_from(slice: &mut CellSlice<'a>) -> Result<Self, Error> {
        load_cont(slice)
    }
}

impl dyn Cont {
    pub fn has_c0(&self) -> bool {
        if let Some(control) = self.get_control_data() {
            control.save.c[0].is_some()
        } else {
            false
        }
    }
}

impl SafeRcMakeMut for dyn Cont {
    #[inline]
    fn rc_make_mut(rc: &mut Rc<Self>) -> &mut Self {
        dyn_clone::rc_make_mut(rc)
    }
}

impl<T: Cont + 'static> SafeRc<T> {
    #[inline]
    pub fn into_dyn_cont(self) -> RcCont {
        let value = SafeRc::into_inner(self);
        SafeRc(ManuallyDrop::new(value))
    }
}

impl<T: Cont + 'static> From<T> for RcCont {
    #[inline]
    fn from(value: T) -> Self {
        Self(ManuallyDrop::new(Rc::new(value)))
    }
}

impl<T: Cont + 'static> From<Rc<T>> for RcCont {
    #[inline]
    fn from(value: Rc<T>) -> Self {
        Self(ManuallyDrop::new(value))
    }
}

pub(crate) fn load_cont(slice: &mut CellSlice) -> Result<RcCont, Error> {
    #[allow(clippy::unusual_byte_groupings)]
    const MASK: u64 = 0x1_007_01_1_1_0001_0001;

    // Prefetch slice prefix aligned to 6 bits
    let slice_bits = slice.size_bits();
    let n = if slice_bits < 6 {
        ok!(slice.get_small_uint(0, slice_bits)) << (6 - slice_bits)
    } else {
        ok!(slice.get_small_uint(0, 6))
    };

    // Count ones in first N bits of mask
    let n = (MASK & (2u64 << n).wrapping_sub(1)).count_ones() - 1;

    // Match bit count with tag ranges
    Ok(match n {
        // 00xxxx -> 0 (16)
        0 => SafeRc::from(ok!(OrdCont::load_from(slice))),
        // 01xxxx -> 1 (16)
        1 => SafeRc::from(ok!(ArgContExt::load_from(slice))),
        // 1000xx -> 2 (4)
        2 => SafeRc::from(ok!(QuitCont::load_from(slice))),
        // 1001xx -> 3 (4)
        3 => SafeRc::from(ok!(ExcQuitCont::load_from(slice))),
        // 10100x -> 4 (2)
        4 => SafeRc::from(ok!(RepeatCont::load_from(slice))),
        // 110000 -> 5 (1)
        5 => SafeRc::from(ok!(UntilCont::load_from(slice))),
        // 110001 -> 6 (1)
        6 => SafeRc::from(ok!(AgainCont::load_from(slice))),
        // 11001x -> 7 (2)
        7 => SafeRc::from(ok!(WhileCont::load_from(slice))),
        // 1111xx -> 8 (4)
        8 => SafeRc::from(ok!(PushIntCont::load_from(slice))),
        // all other
        _ => return Err(Error::InvalidTag),
    })
}

/// Continuation that represents the end of work of TVM.
#[derive(Debug, Copy, Clone)]
pub struct QuitCont {
    pub exit_code: i32,
}

impl QuitCont {
    const TAG: u8 = 0b1000;
}

impl Cont for QuitCont {
    #[inline]
    fn rc_into_dyn(self: Rc<Self>) -> Rc<dyn StackValue> {
        self
    }

    fn as_stack_value(&self) -> &dyn StackValue {
        self
    }

    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("vmc_quit")
    }

    #[cfg_attr(
        feature = "tracing",
        instrument(level = "trace", name = "quit_cont", skip_all)
    )]
    fn jump(self: Rc<Self>, _: &mut VmState, exit_code: &mut i32) -> VmResult<Option<RcCont>> {
        *exit_code = !self.exit_code;
        Ok(None)
    }
}

impl Store for QuitCont {
    fn store_into(&self, builder: &mut CellBuilder, _: &dyn CellContext) -> Result<(), Error> {
        ok!(builder.store_small_uint(Self::TAG, 4));
        builder.store_u32(self.exit_code as u32)
    }
}

impl Load<'_> for QuitCont {
    fn load_from(slice: &mut CellSlice<'_>) -> Result<Self, Error> {
        if ok!(slice.load_small_uint(4)) != Self::TAG {
            return Err(Error::InvalidTag);
        }

        Ok(Self {
            exit_code: ok!(slice.load_u32()) as i32,
        })
    }
}

/// Default exception handler continuation.
#[derive(Debug, Copy, Clone)]
pub struct ExcQuitCont;

impl ExcQuitCont {
    const TAG: u8 = 0b1001;
}

impl Cont for ExcQuitCont {
    #[inline]
    fn rc_into_dyn(self: Rc<Self>) -> Rc<dyn StackValue> {
        self
    }

    fn as_stack_value(&self) -> &dyn StackValue {
        self
    }

    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("vmc_quit_exc")
    }

    #[cfg_attr(
        feature = "tracing",
        instrument(level = "trace", name = "exc_quit_cont", skip_all)
    )]
    fn jump(self: Rc<Self>, state: &mut VmState, exit_code: &mut i32) -> VmResult<Option<RcCont>> {
        let n = SafeRc::make_mut(&mut state.stack)
            .pop_smallint_range(0, 0xffff)
            .unwrap_or_else(|e| e.as_exception() as u32);
        vm_log_trace!("terminating vm in the default exception handler: n={n}");
        *exit_code = !(n as i32);
        Ok(None)
    }
}

impl Store for ExcQuitCont {
    fn store_into(&self, builder: &mut CellBuilder, _: &dyn CellContext) -> Result<(), Error> {
        builder.store_small_uint(Self::TAG, 4)
    }
}

impl Load<'_> for ExcQuitCont {
    #[inline]
    fn load_from(slice: &mut CellSlice<'_>) -> Result<Self, Error> {
        if ok!(slice.load_small_uint(4)) == Self::TAG {
            Ok(Self)
        } else {
            Err(Error::InvalidTag)
        }
    }
}

/// Continuation that pushes a single integer to the stack.
#[derive(Debug, Clone)]
pub struct PushIntCont {
    pub value: i32,
    pub next: RcCont,
}

impl PushIntCont {
    const TAG: u8 = 0b1111;
}

impl Cont for PushIntCont {
    #[inline]
    fn rc_into_dyn(self: Rc<Self>) -> Rc<dyn StackValue> {
        self
    }

    fn as_stack_value(&self) -> &dyn StackValue {
        self
    }

    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("vmc_pushint")
    }

    #[cfg_attr(
        feature = "tracing",
        instrument(
            level = "trace",
            name = "push_int_cont",
            fields(value = self.value),
            skip_all,
        )
    )]
    fn jump(self: Rc<Self>, state: &mut VmState, _: &mut i32) -> VmResult<Option<RcCont>> {
        ok!(SafeRc::make_mut(&mut state.stack).push_int(self.value));
        Ok(Some(match Rc::try_unwrap(self) {
            Ok(this) => this.next,
            Err(this) => this.next.clone(),
        }))
    }
}

impl Store for PushIntCont {
    fn store_into(
        &self,
        builder: &mut CellBuilder,
        context: &dyn CellContext,
    ) -> Result<(), Error> {
        ok!(builder.store_small_uint(Self::TAG, 4));
        ok!(builder.store_u32(self.value as u32));
        builder.store_reference(ok!(CellBuilder::build_from_ext(&*self.next, context)))
    }
}

impl Load<'_> for PushIntCont {
    fn load_from(slice: &mut CellSlice<'_>) -> Result<Self, Error> {
        if ok!(slice.load_small_uint(4)) != Self::TAG {
            return Err(Error::InvalidTag);
        }

        Ok(Self {
            value: ok!(slice.load_u32()) as i32,
            next: ok!(load_cont(slice)),
        })
    }
}

/// Continuation that takes an integer `n` and a continuation `c`,
/// and executes `c` `n` times.
#[derive(Debug, Clone)]
pub struct RepeatCont {
    pub count: u64,
    pub body: RcCont,
    pub after: RcCont,
}

impl RepeatCont {
    const TAG: u8 = 0b1010;
    const MAX_COUNT: u64 = 0x8000000000000000;
}

impl Cont for RepeatCont {
    #[inline]
    fn rc_into_dyn(self: Rc<Self>) -> Rc<dyn StackValue> {
        self
    }

    fn as_stack_value(&self) -> &dyn StackValue {
        self
    }

    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("vmc_repeat")
    }

    #[cfg_attr(
        feature = "tracing",
        instrument(
            level = "trace",
            name = "repeat_cont",
            fields(value = self.count),
            skip_all,
        )
    )]
    fn jump(mut self: Rc<Self>, state: &mut VmState, _: &mut i32) -> VmResult<Option<RcCont>> {
        if self.count == 0 {
            return Ok(Some(self.after.clone()));
        }
        if self.body.has_c0() {
            return Ok(Some(self.body.clone()));
        }

        let body = self.body.clone();
        match Rc::get_mut(&mut self) {
            Some(this) => {
                this.count -= 1;
                state.set_c0(RcCont::from(self))
            }
            None => state.set_c0(SafeRc::from(RepeatCont {
                count: self.count - 1,
                body: self.body.clone(),
                after: self.after.clone(),
            })),
        }

        Ok(Some(body))
    }
}

impl Store for RepeatCont {
    fn store_into(
        &self,
        builder: &mut CellBuilder,
        context: &dyn CellContext,
    ) -> Result<(), Error> {
        if self.count >= Self::MAX_COUNT {
            return Err(Error::IntOverflow);
        }
        ok!(builder.store_small_uint(Self::TAG, 4));
        ok!(builder.store_u64(self.count));
        ok!(builder.store_reference(ok!(CellBuilder::build_from_ext(&*self.body, context))));
        builder.store_reference(ok!(CellBuilder::build_from_ext(&*self.after, context)))
    }
}

impl Load<'_> for RepeatCont {
    fn load_from(slice: &mut CellSlice<'_>) -> Result<Self, Error> {
        if ok!(slice.load_small_uint(4)) != Self::TAG {
            return Err(Error::InvalidTag);
        }

        Ok(Self {
            count: ok!(slice.load_u64()),
            body: ok!(load_cont(slice)),
            after: ok!(load_cont(slice)),
        })
    }
}

/// Continuation that executes its body infinitely many times.
///
/// A `RET` only begins a new iteration of the infinite loop, which can
/// be exited only by an exception, or a `RETALT` (or an explicit `JMPX`).
#[derive(Debug, Clone)]
pub struct AgainCont {
    pub body: RcCont,
}

impl AgainCont {
    const TAG: u8 = 0b110001;
}

impl Cont for AgainCont {
    #[inline]
    fn rc_into_dyn(self: Rc<Self>) -> Rc<dyn StackValue> {
        self
    }

    fn as_stack_value(&self) -> &dyn StackValue {
        self
    }

    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("vmc_again")
    }

    #[cfg_attr(
        feature = "tracing",
        instrument(level = "trace", name = "again_cont", skip_all)
    )]
    fn jump(self: Rc<Self>, state: &mut VmState, _: &mut i32) -> VmResult<Option<RcCont>> {
        if !self.body.has_c0() {
            state.set_c0(SafeRc::from(self.clone()))
        }
        Ok(Some(self.body.clone()))
    }
}

impl Store for AgainCont {
    fn store_into(
        &self,
        builder: &mut CellBuilder,
        context: &dyn CellContext,
    ) -> Result<(), Error> {
        ok!(builder.store_small_uint(Self::TAG, 6));
        builder.store_reference(ok!(CellBuilder::build_from_ext(&*self.body, context)))
    }
}

impl Load<'_> for AgainCont {
    fn load_from(slice: &mut CellSlice<'_>) -> Result<Self, Error> {
        if ok!(slice.load_small_uint(6)) != Self::TAG {
            return Err(Error::InvalidTag);
        }

        Ok(Self {
            body: ok!(load_cont(slice)),
        })
    }
}

/// Continuation of a loop with postcondition.
#[derive(Debug, Clone)]
pub struct UntilCont {
    pub body: RcCont,
    pub after: RcCont,
}

impl UntilCont {
    const TAG: u8 = 0b110000;
}

impl Cont for UntilCont {
    #[inline]
    fn rc_into_dyn(self: Rc<Self>) -> Rc<dyn StackValue> {
        self
    }

    fn as_stack_value(&self) -> &dyn StackValue {
        self
    }

    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("vmc_until")
    }

    #[cfg_attr(
        feature = "tracing",
        instrument(level = "trace", name = "until_cont", skip_all)
    )]
    fn jump(self: Rc<Self>, state: &mut VmState, _: &mut i32) -> VmResult<Option<RcCont>> {
        vm_log_trace!("until loop condition end");
        let terminated = ok!(SafeRc::make_mut(&mut state.stack).pop_bool());
        if terminated {
            vm_log_trace!("until loop terminated");
            return Ok(Some(self.after.clone()));
        }
        if !self.body.has_c0() {
            state.set_c0(RcCont::from(self.clone()));
        }
        Ok(Some(self.body.clone()))
    }
}

impl Store for UntilCont {
    fn store_into(
        &self,
        builder: &mut CellBuilder,
        context: &dyn CellContext,
    ) -> Result<(), Error> {
        ok!(builder.store_small_uint(Self::TAG, 6));
        ok!(builder.store_reference(ok!(CellBuilder::build_from_ext(&*self.body, context))));
        builder.store_reference(ok!(CellBuilder::build_from_ext(&*self.after, context)))
    }
}

impl Load<'_> for UntilCont {
    fn load_from(slice: &mut CellSlice<'_>) -> Result<Self, Error> {
        if ok!(slice.load_small_uint(6)) != Self::TAG {
            return Err(Error::InvalidTag);
        }

        Ok(Self {
            body: ok!(load_cont(slice)),
            after: ok!(load_cont(slice)),
        })
    }
}

/// Continuation of a loop with precondition.
#[derive(Debug, Clone)]
pub struct WhileCont {
    pub check_cond: bool,
    pub cond: RcCont,
    pub body: RcCont,
    pub after: RcCont,
}

impl WhileCont {
    const TAG: u8 = 0b11001;
}

impl Cont for WhileCont {
    #[inline]
    fn rc_into_dyn(self: Rc<Self>) -> Rc<dyn StackValue> {
        self
    }

    fn as_stack_value(&self) -> &dyn StackValue {
        self
    }

    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(if self.check_cond {
            "vmc_while_cond"
        } else {
            "vmc_while_body"
        })
    }

    #[cfg_attr(
        feature = "tracing",
        instrument(
            level = "trace",
            name = "while_cont",
            fields(check_cond = self.check_cond),
            skip_all,
        )
    )]
    fn jump(mut self: Rc<Self>, state: &mut VmState, _: &mut i32) -> VmResult<Option<RcCont>> {
        let next = if self.check_cond {
            vm_log_trace!("while loop condition end");
            if !ok!(SafeRc::make_mut(&mut state.stack).pop_bool()) {
                vm_log_trace!("while loop terminated");
                return Ok(Some(self.after.clone()));
            }
            self.body.clone()
        } else {
            vm_log_trace!("while loop body end");
            self.cond.clone()
        };

        if !next.has_c0() {
            match Rc::get_mut(&mut self) {
                Some(this) => {
                    this.check_cond = !this.check_cond;
                    state.set_c0(RcCont::from(self));
                }
                None => state.set_c0(SafeRc::from(WhileCont {
                    check_cond: !self.check_cond,
                    cond: self.cond.clone(),
                    body: self.body.clone(),
                    after: self.after.clone(),
                })),
            }
        }

        Ok(Some(next))
    }
}

impl Store for WhileCont {
    fn store_into(
        &self,
        builder: &mut CellBuilder,
        context: &dyn CellContext,
    ) -> Result<(), Error> {
        let tag = (Self::TAG << 1) | !self.check_cond as u8;
        ok!(builder.store_small_uint(tag, 6));
        ok!(builder.store_reference(ok!(CellBuilder::build_from_ext(&*self.cond, context))));
        ok!(builder.store_reference(ok!(CellBuilder::build_from_ext(&*self.body, context))));
        builder.store_reference(ok!(CellBuilder::build_from_ext(&*self.after, context)))
    }
}

impl Load<'_> for WhileCont {
    fn load_from(slice: &mut CellSlice<'_>) -> Result<Self, Error> {
        if ok!(slice.load_small_uint(5)) != Self::TAG {
            return Err(Error::InvalidTag);
        }

        Ok(Self {
            check_cond: ok!(slice.load_bit()),
            cond: ok!(load_cont(slice)),
            body: ok!(load_cont(slice)),
            after: ok!(load_cont(slice)),
        })
    }
}

/// Continuation with control data (arguments).
#[derive(Debug, Clone)]
pub struct ArgContExt {
    pub data: ControlData,
    pub ext: RcCont,
}

impl ArgContExt {
    const TAG: u8 = 0b01;
}

impl Cont for ArgContExt {
    #[inline]
    fn rc_into_dyn(self: Rc<Self>) -> Rc<dyn StackValue> {
        self
    }

    fn as_stack_value(&self) -> &dyn StackValue {
        self
    }

    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("vmc_envelope")
    }

    #[cfg_attr(
        feature = "tracing",
        instrument(level = "trace", name = "arg_cont", skip_all)
    )]
    fn jump(self: Rc<Self>, state: &mut VmState, _: &mut i32) -> VmResult<Option<RcCont>> {
        state.adjust_cr(&self.data.save);
        if let Some(cp) = self.data.cp {
            ok!(state.force_cp(cp));
        }

        Ok(Some(match Rc::try_unwrap(self) {
            Ok(this) => this.ext,
            Err(this) => this.ext.clone(),
        }))
    }

    fn get_control_data(&self) -> Option<&ControlData> {
        Some(&self.data)
    }

    fn get_control_data_mut(&mut self) -> Option<&mut ControlData> {
        Some(&mut self.data)
    }
}

impl Store for ArgContExt {
    fn store_into(
        &self,
        builder: &mut CellBuilder,
        context: &dyn CellContext,
    ) -> Result<(), Error> {
        ok!(builder.store_small_uint(Self::TAG, 2));
        self.ext.store_into(builder, context)
    }
}

impl Load<'_> for ArgContExt {
    fn load_from(slice: &mut CellSlice<'_>) -> Result<Self, Error> {
        if ok!(slice.load_small_uint(2)) != Self::TAG {
            return Err(Error::InvalidTag);
        }

        Ok(Self {
            data: ok!(ControlData::load_from(slice)),
            ext: ok!(load_cont(slice)),
        })
    }
}

/// Ordinary continuation.
#[derive(Debug, Clone)]
pub struct OrdCont {
    pub data: ControlData,
    pub code: OwnedCellSlice,
}

impl OrdCont {
    const TAG: u8 = 0b00;

    pub fn simple(code: OwnedCellSlice, cp: u16) -> Self {
        Self {
            data: ControlData {
                cp: Some(cp),
                ..Default::default()
            },
            code,
        }
    }
}

impl Cont for OrdCont {
    #[inline]
    fn rc_into_dyn(self: Rc<Self>) -> Rc<dyn StackValue> {
        self
    }

    fn as_stack_value(&self) -> &dyn StackValue {
        self
    }

    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("vmc_std")
    }

    #[cfg_attr(
        feature = "tracing",
        instrument(level = "trace", name = "ord_cont", skip_all)
    )]
    fn jump(self: Rc<Self>, state: &mut VmState, _: &mut i32) -> VmResult<Option<RcCont>> {
        state.adjust_cr(&self.data.save);
        let Some(cp) = self.data.cp else {
            vm_bail!(InvalidOpcode);
        };
        ok!(state.set_code(self.code.clone(), cp));
        Ok(None)
    }

    fn get_control_data(&self) -> Option<&ControlData> {
        Some(&self.data)
    }

    fn get_control_data_mut(&mut self) -> Option<&mut ControlData> {
        Some(&mut self.data)
    }
}

impl Store for OrdCont {
    fn store_into(
        &self,
        builder: &mut CellBuilder,
        context: &dyn CellContext,
    ) -> Result<(), Error> {
        ok!(builder.store_zeros(2));
        ok!(self.data.store_into(builder, context));
        store_slice_as_stack_value(&self.code, builder)
    }
}

impl Load<'_> for OrdCont {
    fn load_from(slice: &mut CellSlice<'_>) -> Result<Self, Error> {
        if ok!(slice.load_small_uint(2)) != Self::TAG {
            return Err(Error::InvalidTag);
        }

        Ok(Self {
            data: ok!(ControlData::load_from(slice)),
            code: ok!(load_slice_as_stack_value(slice)),
        })
    }
}