triton_isa/
instruction.rs

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
use std::collections::HashMap;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;
use std::num::TryFromIntError;
use std::result;

use arbitrary::Arbitrary;
use arbitrary::Unstructured;
use get_size::GetSize;
use itertools::Itertools;
use lazy_static::lazy_static;
use num_traits::ConstZero;
use serde::Deserialize;
use serde::Serialize;
use strum::EnumCount;
use strum::EnumIter;
use strum::IntoEnumIterator;
use thiserror::Error;
use twenty_first::prelude::*;

use crate::op_stack::NumberOfWords;
use crate::op_stack::OpStackElement;
use crate::op_stack::OpStackError;

type Result<T> = result::Result<T, InstructionError>;

/// An `Instruction` has `call` addresses encoded as absolute integers.
pub type Instruction = AnInstruction<BFieldElement>;

pub const ALL_INSTRUCTIONS: [Instruction; Instruction::COUNT] = [
    Instruction::Pop(NumberOfWords::N1),
    Instruction::Push(BFieldElement::ZERO),
    Instruction::Divine(NumberOfWords::N1),
    Instruction::Pick(OpStackElement::ST0),
    Instruction::Place(OpStackElement::ST0),
    Instruction::Dup(OpStackElement::ST0),
    Instruction::Swap(OpStackElement::ST0),
    Instruction::Halt,
    Instruction::Nop,
    Instruction::Skiz,
    Instruction::Call(BFieldElement::ZERO),
    Instruction::Return,
    Instruction::Recurse,
    Instruction::RecurseOrReturn,
    Instruction::Assert,
    Instruction::ReadMem(NumberOfWords::N1),
    Instruction::WriteMem(NumberOfWords::N1),
    Instruction::Hash,
    Instruction::AssertVector,
    Instruction::SpongeInit,
    Instruction::SpongeAbsorb,
    Instruction::SpongeAbsorbMem,
    Instruction::SpongeSqueeze,
    Instruction::Add,
    Instruction::AddI(BFieldElement::ZERO),
    Instruction::Mul,
    Instruction::Invert,
    Instruction::Eq,
    Instruction::Split,
    Instruction::Lt,
    Instruction::And,
    Instruction::Xor,
    Instruction::Log2Floor,
    Instruction::Pow,
    Instruction::DivMod,
    Instruction::PopCount,
    Instruction::XxAdd,
    Instruction::XxMul,
    Instruction::XInvert,
    Instruction::XbMul,
    Instruction::ReadIo(NumberOfWords::N1),
    Instruction::WriteIo(NumberOfWords::N1),
    Instruction::MerkleStep,
    Instruction::MerkleStepMem,
    Instruction::XxDotStep,
    Instruction::XbDotStep,
];

pub const ALL_INSTRUCTION_NAMES: [&str; Instruction::COUNT] = {
    let mut names = [""; Instruction::COUNT];
    let mut i = 0;
    while i < Instruction::COUNT {
        names[i] = ALL_INSTRUCTIONS[i].name();
        i += 1;
    }
    names
};

lazy_static! {
    pub static ref OPCODE_TO_INSTRUCTION_MAP: HashMap<u32, Instruction> = {
        let mut opcode_to_instruction_map = HashMap::new();
        for instruction in Instruction::iter() {
            opcode_to_instruction_map.insert(instruction.opcode(), instruction);
        }
        opcode_to_instruction_map
    };
}

/// A `LabelledInstruction` has `call` addresses encoded as label names.
#[derive(Debug, Clone, Eq, PartialEq, Hash, EnumCount)]
pub enum LabelledInstruction {
    /// An instructions from the [instruction set architecture][isa].
    ///
    /// [isa]: https://triton-vm.org/spec/isa.html
    Instruction(AnInstruction<String>),

    /// Labels look like "`<name>:`" and are translated into absolute addresses.
    Label(String),

    Breakpoint,

    TypeHint(TypeHint),

    AssertionContext(AssertionContext),
}

/// A hint about a range of stack elements. Helps debugging programs written for Triton VM.
/// **Does not enforce types.**
///
/// Usually constructed by parsing special annotations in the assembly code, for example:
/// ```tasm
/// hint variable_name: the_type = stack[0]
/// hint my_list = stack[1..4]
/// ```
#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, GetSize)]
pub struct TypeHint {
    pub starting_index: usize,
    pub length: usize,

    /// The name of the type, _e.g._, `u32`, `list`, `Digest`, et cetera.
    pub type_name: Option<String>,

    /// The name of the variable.
    pub variable_name: String,
}

/// Context to help debugging failing instructions [`assert`](Instruction::Assert) or
/// [`assert_vector`](Instruction::AssertVector).
#[non_exhaustive]
#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, GetSize, Arbitrary)]
pub enum AssertionContext {
    ID(i128),
    // Message(String),
}

impl LabelledInstruction {
    pub const fn op_stack_size_influence(&self) -> i32 {
        match self {
            LabelledInstruction::Instruction(instruction) => instruction.op_stack_size_influence(),
            _ => 0,
        }
    }
}

impl Display for LabelledInstruction {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        match self {
            LabelledInstruction::Instruction(instruction) => write!(f, "{instruction}"),
            LabelledInstruction::Label(label) => write!(f, "{label}:"),
            LabelledInstruction::Breakpoint => write!(f, "break"),
            LabelledInstruction::TypeHint(type_hint) => write!(f, "{type_hint}"),
            LabelledInstruction::AssertionContext(ctx) => write!(f, "{ctx}"),
        }
    }
}

impl Display for TypeHint {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let variable = &self.variable_name;

        let format_type = |t| format!(": {t}");
        let maybe_type = self.type_name.as_ref();
        let type_name = maybe_type.map(format_type).unwrap_or_default();

        let start = self.starting_index;
        let range = match self.length {
            1 => format!("{start}"),
            _ => format!("{start}..{end}", end = start + self.length),
        };

        write!(f, "hint {variable}{type_name} = stack[{range}]")
    }
}

impl Display for AssertionContext {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let Self::ID(id) = self;
        write!(f, "error_id {id}")
    }
}

impl<'a> Arbitrary<'a> for TypeHint {
    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
        let starting_index = u.arbitrary()?;
        let length = u.int_in_range(1..=500)?;
        let type_name = if u.arbitrary()? {
            Some(u.arbitrary::<TypeHintTypeName>()?.into())
        } else {
            None
        };
        let variable_name = u.arbitrary::<TypeHintVariableName>()?.into();

        let type_hint = Self {
            starting_index,
            length,
            type_name,
            variable_name,
        };
        Ok(type_hint)
    }
}

/// A Triton VM instruction. See the
/// [Instruction Set Architecture](https://triton-vm.org/spec/isa.html)
/// for more details.
///
/// The type parameter `Dest` describes the type of addresses (absolute or labels).
#[derive(
    Debug,
    Copy,
    Clone,
    Eq,
    PartialEq,
    Hash,
    EnumCount,
    EnumIter,
    Serialize,
    Deserialize,
    GetSize,
    Arbitrary,
)]
pub enum AnInstruction<Dest: PartialEq + Default> {
    // OpStack manipulation
    Pop(NumberOfWords),
    Push(BFieldElement),
    Divine(NumberOfWords),
    Pick(OpStackElement),
    Place(OpStackElement),
    Dup(OpStackElement),
    Swap(OpStackElement),

    // Control flow
    Halt,
    Nop,
    Skiz,
    Call(Dest),
    Return,
    Recurse,
    RecurseOrReturn,
    Assert,

    // Memory access
    ReadMem(NumberOfWords),
    WriteMem(NumberOfWords),

    // Hashing-related
    Hash,
    AssertVector,
    SpongeInit,
    SpongeAbsorb,
    SpongeAbsorbMem,
    SpongeSqueeze,

    // Base field arithmetic on stack
    Add,
    AddI(BFieldElement),
    Mul,
    Invert,
    Eq,

    // Bitwise arithmetic on stack
    Split,
    Lt,
    And,
    Xor,
    Log2Floor,
    Pow,
    DivMod,
    PopCount,

    // Extension field arithmetic on stack
    XxAdd,
    XxMul,
    XInvert,
    XbMul,

    // Read/write
    ReadIo(NumberOfWords),
    WriteIo(NumberOfWords),

    // Many-in-One
    MerkleStep,
    MerkleStepMem,
    XxDotStep,
    XbDotStep,
}

impl<Dest: PartialEq + Default> AnInstruction<Dest> {
    /// Assign a unique positive integer to each `Instruction`.
    pub const fn opcode(&self) -> u32 {
        match self {
            AnInstruction::Pop(_) => 3,
            AnInstruction::Push(_) => 1,
            AnInstruction::Divine(_) => 9,
            AnInstruction::Pick(_) => 17,
            AnInstruction::Place(_) => 25,
            AnInstruction::Dup(_) => 33,
            AnInstruction::Swap(_) => 41,
            AnInstruction::Halt => 0,
            AnInstruction::Nop => 8,
            AnInstruction::Skiz => 2,
            AnInstruction::Call(_) => 49,
            AnInstruction::Return => 16,
            AnInstruction::Recurse => 24,
            AnInstruction::RecurseOrReturn => 32,
            AnInstruction::Assert => 10,
            AnInstruction::ReadMem(_) => 57,
            AnInstruction::WriteMem(_) => 11,
            AnInstruction::Hash => 18,
            AnInstruction::AssertVector => 26,
            AnInstruction::SpongeInit => 40,
            AnInstruction::SpongeAbsorb => 34,
            AnInstruction::SpongeAbsorbMem => 48,
            AnInstruction::SpongeSqueeze => 56,
            AnInstruction::Add => 42,
            AnInstruction::AddI(_) => 65,
            AnInstruction::Mul => 50,
            AnInstruction::Invert => 64,
            AnInstruction::Eq => 58,
            AnInstruction::Split => 4,
            AnInstruction::Lt => 6,
            AnInstruction::And => 14,
            AnInstruction::Xor => 22,
            AnInstruction::Log2Floor => 12,
            AnInstruction::Pow => 30,
            AnInstruction::DivMod => 20,
            AnInstruction::PopCount => 28,
            AnInstruction::XxAdd => 66,
            AnInstruction::XxMul => 74,
            AnInstruction::XInvert => 72,
            AnInstruction::XbMul => 82,
            AnInstruction::ReadIo(_) => 73,
            AnInstruction::WriteIo(_) => 19,
            AnInstruction::MerkleStep => 36,
            AnInstruction::MerkleStepMem => 44,
            AnInstruction::XxDotStep => 80,
            AnInstruction::XbDotStep => 88,
        }
    }

    pub const fn name(&self) -> &'static str {
        match self {
            AnInstruction::Pop(_) => "pop",
            AnInstruction::Push(_) => "push",
            AnInstruction::Divine(_) => "divine",
            AnInstruction::Pick(_) => "pick",
            AnInstruction::Place(_) => "place",
            AnInstruction::Dup(_) => "dup",
            AnInstruction::Swap(_) => "swap",
            AnInstruction::Halt => "halt",
            AnInstruction::Nop => "nop",
            AnInstruction::Skiz => "skiz",
            AnInstruction::Call(_) => "call",
            AnInstruction::Return => "return",
            AnInstruction::Recurse => "recurse",
            AnInstruction::RecurseOrReturn => "recurse_or_return",
            AnInstruction::Assert => "assert",
            AnInstruction::ReadMem(_) => "read_mem",
            AnInstruction::WriteMem(_) => "write_mem",
            AnInstruction::Hash => "hash",
            AnInstruction::AssertVector => "assert_vector",
            AnInstruction::SpongeInit => "sponge_init",
            AnInstruction::SpongeAbsorb => "sponge_absorb",
            AnInstruction::SpongeAbsorbMem => "sponge_absorb_mem",
            AnInstruction::SpongeSqueeze => "sponge_squeeze",
            AnInstruction::Add => "add",
            AnInstruction::AddI(_) => "addi",
            AnInstruction::Mul => "mul",
            AnInstruction::Invert => "invert",
            AnInstruction::Eq => "eq",
            AnInstruction::Split => "split",
            AnInstruction::Lt => "lt",
            AnInstruction::And => "and",
            AnInstruction::Xor => "xor",
            AnInstruction::Log2Floor => "log_2_floor",
            AnInstruction::Pow => "pow",
            AnInstruction::DivMod => "div_mod",
            AnInstruction::PopCount => "pop_count",
            AnInstruction::XxAdd => "xx_add",
            AnInstruction::XxMul => "xx_mul",
            AnInstruction::XInvert => "x_invert",
            AnInstruction::XbMul => "xb_mul",
            AnInstruction::ReadIo(_) => "read_io",
            AnInstruction::WriteIo(_) => "write_io",
            AnInstruction::MerkleStep => "merkle_step",
            AnInstruction::MerkleStepMem => "merkle_step_mem",
            AnInstruction::XxDotStep => "xx_dot_step",
            AnInstruction::XbDotStep => "xb_dot_step",
        }
    }

    pub const fn opcode_b(&self) -> BFieldElement {
        BFieldElement::new(self.opcode() as u64)
    }

    /// Number of words required to represent the instruction.
    pub fn size(&self) -> usize {
        match self {
            AnInstruction::Pop(_) | AnInstruction::Push(_) => 2,
            AnInstruction::Divine(_) => 2,
            AnInstruction::Pick(_) | AnInstruction::Place(_) => 2,
            AnInstruction::Dup(_) | AnInstruction::Swap(_) => 2,
            AnInstruction::Call(_) => 2,
            AnInstruction::ReadMem(_) | AnInstruction::WriteMem(_) => 2,
            AnInstruction::AddI(_) => 2,
            AnInstruction::ReadIo(_) | AnInstruction::WriteIo(_) => 2,
            _ => 1,
        }
    }

    /// Get the i'th instruction bit
    pub fn ib(&self, arg: InstructionBit) -> BFieldElement {
        bfe!((self.opcode() >> usize::from(arg)) & 1)
    }

    pub fn map_call_address<F, NewDest>(&self, f: F) -> AnInstruction<NewDest>
    where
        F: FnOnce(&Dest) -> NewDest,
        NewDest: PartialEq + Default,
    {
        match self {
            AnInstruction::Pop(x) => AnInstruction::Pop(*x),
            AnInstruction::Push(x) => AnInstruction::Push(*x),
            AnInstruction::Divine(x) => AnInstruction::Divine(*x),
            AnInstruction::Pick(x) => AnInstruction::Pick(*x),
            AnInstruction::Place(x) => AnInstruction::Place(*x),
            AnInstruction::Dup(x) => AnInstruction::Dup(*x),
            AnInstruction::Swap(x) => AnInstruction::Swap(*x),
            AnInstruction::Halt => AnInstruction::Halt,
            AnInstruction::Nop => AnInstruction::Nop,
            AnInstruction::Skiz => AnInstruction::Skiz,
            AnInstruction::Call(label) => AnInstruction::Call(f(label)),
            AnInstruction::Return => AnInstruction::Return,
            AnInstruction::Recurse => AnInstruction::Recurse,
            AnInstruction::RecurseOrReturn => AnInstruction::RecurseOrReturn,
            AnInstruction::Assert => AnInstruction::Assert,
            AnInstruction::ReadMem(x) => AnInstruction::ReadMem(*x),
            AnInstruction::WriteMem(x) => AnInstruction::WriteMem(*x),
            AnInstruction::Hash => AnInstruction::Hash,
            AnInstruction::AssertVector => AnInstruction::AssertVector,
            AnInstruction::SpongeInit => AnInstruction::SpongeInit,
            AnInstruction::SpongeAbsorb => AnInstruction::SpongeAbsorb,
            AnInstruction::SpongeAbsorbMem => AnInstruction::SpongeAbsorbMem,
            AnInstruction::SpongeSqueeze => AnInstruction::SpongeSqueeze,
            AnInstruction::Add => AnInstruction::Add,
            AnInstruction::AddI(x) => AnInstruction::AddI(*x),
            AnInstruction::Mul => AnInstruction::Mul,
            AnInstruction::Invert => AnInstruction::Invert,
            AnInstruction::Eq => AnInstruction::Eq,
            AnInstruction::Split => AnInstruction::Split,
            AnInstruction::Lt => AnInstruction::Lt,
            AnInstruction::And => AnInstruction::And,
            AnInstruction::Xor => AnInstruction::Xor,
            AnInstruction::Log2Floor => AnInstruction::Log2Floor,
            AnInstruction::Pow => AnInstruction::Pow,
            AnInstruction::DivMod => AnInstruction::DivMod,
            AnInstruction::PopCount => AnInstruction::PopCount,
            AnInstruction::XxAdd => AnInstruction::XxAdd,
            AnInstruction::XxMul => AnInstruction::XxMul,
            AnInstruction::XInvert => AnInstruction::XInvert,
            AnInstruction::XbMul => AnInstruction::XbMul,
            AnInstruction::ReadIo(x) => AnInstruction::ReadIo(*x),
            AnInstruction::WriteIo(x) => AnInstruction::WriteIo(*x),
            AnInstruction::MerkleStep => AnInstruction::MerkleStep,
            AnInstruction::MerkleStepMem => AnInstruction::MerkleStepMem,
            AnInstruction::XxDotStep => AnInstruction::XxDotStep,
            AnInstruction::XbDotStep => AnInstruction::XbDotStep,
        }
    }

    pub const fn op_stack_size_influence(&self) -> i32 {
        match self {
            AnInstruction::Pop(n) => -(n.num_words() as i32),
            AnInstruction::Push(_) => 1,
            AnInstruction::Divine(n) => n.num_words() as i32,
            AnInstruction::Pick(_) => 0,
            AnInstruction::Place(_) => 0,
            AnInstruction::Dup(_) => 1,
            AnInstruction::Swap(_) => 0,
            AnInstruction::Halt => 0,
            AnInstruction::Nop => 0,
            AnInstruction::Skiz => -1,
            AnInstruction::Call(_) => 0,
            AnInstruction::Return => 0,
            AnInstruction::Recurse => 0,
            AnInstruction::RecurseOrReturn => 0,
            AnInstruction::Assert => -1,
            AnInstruction::ReadMem(n) => n.num_words() as i32,
            AnInstruction::WriteMem(n) => -(n.num_words() as i32),
            AnInstruction::Hash => -5,
            AnInstruction::AssertVector => -5,
            AnInstruction::SpongeInit => 0,
            AnInstruction::SpongeAbsorb => -10,
            AnInstruction::SpongeAbsorbMem => 0,
            AnInstruction::SpongeSqueeze => 10,
            AnInstruction::Add => -1,
            AnInstruction::AddI(_) => 0,
            AnInstruction::Mul => -1,
            AnInstruction::Invert => 0,
            AnInstruction::Eq => -1,
            AnInstruction::Split => 1,
            AnInstruction::Lt => -1,
            AnInstruction::And => -1,
            AnInstruction::Xor => -1,
            AnInstruction::Log2Floor => 0,
            AnInstruction::Pow => -1,
            AnInstruction::DivMod => 0,
            AnInstruction::PopCount => 0,
            AnInstruction::XxAdd => -3,
            AnInstruction::XxMul => -3,
            AnInstruction::XInvert => 0,
            AnInstruction::XbMul => -1,
            AnInstruction::ReadIo(n) => n.num_words() as i32,
            AnInstruction::WriteIo(n) => -(n.num_words() as i32),
            AnInstruction::MerkleStep => 0,
            AnInstruction::MerkleStepMem => 0,
            AnInstruction::XxDotStep => 0,
            AnInstruction::XbDotStep => 0,
        }
    }

    /// Indicates whether the instruction operates on base field elements that are also u32s.
    pub fn is_u32_instruction(&self) -> bool {
        matches!(
            self,
            AnInstruction::Split
                | AnInstruction::Lt
                | AnInstruction::And
                | AnInstruction::Xor
                | AnInstruction::Log2Floor
                | AnInstruction::Pow
                | AnInstruction::DivMod
                | AnInstruction::PopCount
                | AnInstruction::MerkleStep
                | AnInstruction::MerkleStepMem
        )
    }
}

impl<Dest: Display + PartialEq + Default> Display for AnInstruction<Dest> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        write!(f, "{}", self.name())?;
        match self {
            AnInstruction::Push(arg) => write!(f, " {arg}"),
            AnInstruction::Pick(arg) => write!(f, " {arg}"),
            AnInstruction::Place(arg) => write!(f, " {arg}"),
            AnInstruction::Pop(arg) => write!(f, " {arg}"),
            AnInstruction::Divine(arg) => write!(f, " {arg}"),
            AnInstruction::Dup(arg) => write!(f, " {arg}"),
            AnInstruction::Swap(arg) => write!(f, " {arg}"),
            AnInstruction::Call(arg) => write!(f, " {arg}"),
            AnInstruction::ReadMem(arg) => write!(f, " {arg}"),
            AnInstruction::WriteMem(arg) => write!(f, " {arg}"),
            AnInstruction::AddI(arg) => write!(f, " {arg}"),
            AnInstruction::ReadIo(arg) => write!(f, " {arg}"),
            AnInstruction::WriteIo(arg) => write!(f, " {arg}"),
            _ => Ok(()),
        }
    }
}

impl Instruction {
    /// Get the argument of the instruction, if it has one.
    pub fn arg(&self) -> Option<BFieldElement> {
        match self {
            AnInstruction::Push(arg) => Some(*arg),
            AnInstruction::Call(arg) => Some(*arg),
            AnInstruction::Pop(arg) => Some(arg.into()),
            AnInstruction::Divine(arg) => Some(arg.into()),
            AnInstruction::Pick(arg) => Some(arg.into()),
            AnInstruction::Place(arg) => Some(arg.into()),
            AnInstruction::Dup(arg) => Some(arg.into()),
            AnInstruction::Swap(arg) => Some(arg.into()),
            AnInstruction::ReadMem(arg) => Some(arg.into()),
            AnInstruction::WriteMem(arg) => Some(arg.into()),
            AnInstruction::AddI(arg) => Some(*arg),
            AnInstruction::ReadIo(arg) => Some(arg.into()),
            AnInstruction::WriteIo(arg) => Some(arg.into()),
            _ => None,
        }
    }

    /// Change the argument of the instruction, if it has one. Returns an `Err` if the instruction
    /// does not have an argument or if the argument is out of range.
    pub fn change_arg(self, new_arg: BFieldElement) -> Result<Self> {
        let illegal_argument_error = || InstructionError::IllegalArgument(self, new_arg);
        let num_words = new_arg.try_into().map_err(|_| illegal_argument_error());
        let op_stack_element = new_arg.try_into().map_err(|_| illegal_argument_error());

        let new_instruction = match self {
            AnInstruction::Pop(_) => AnInstruction::Pop(num_words?),
            AnInstruction::Push(_) => AnInstruction::Push(new_arg),
            AnInstruction::Divine(_) => AnInstruction::Divine(num_words?),
            AnInstruction::Pick(_) => AnInstruction::Pick(op_stack_element?),
            AnInstruction::Place(_) => AnInstruction::Place(op_stack_element?),
            AnInstruction::Dup(_) => AnInstruction::Dup(op_stack_element?),
            AnInstruction::Swap(_) => AnInstruction::Swap(op_stack_element?),
            AnInstruction::Call(_) => AnInstruction::Call(new_arg),
            AnInstruction::ReadMem(_) => AnInstruction::ReadMem(num_words?),
            AnInstruction::WriteMem(_) => AnInstruction::WriteMem(num_words?),
            AnInstruction::AddI(_) => AnInstruction::AddI(new_arg),
            AnInstruction::ReadIo(_) => AnInstruction::ReadIo(num_words?),
            AnInstruction::WriteIo(_) => AnInstruction::WriteIo(num_words?),
            _ => return Err(illegal_argument_error()),
        };

        Ok(new_instruction)
    }
}

impl TryFrom<u32> for Instruction {
    type Error = InstructionError;

    fn try_from(opcode: u32) -> Result<Self> {
        OPCODE_TO_INSTRUCTION_MAP
            .get(&opcode)
            .copied()
            .ok_or(InstructionError::InvalidOpcode(opcode))
    }
}

impl TryFrom<u64> for Instruction {
    type Error = InstructionError;

    fn try_from(opcode: u64) -> Result<Self> {
        let opcode = u32::try_from(opcode)?;
        opcode.try_into()
    }
}

impl TryFrom<usize> for Instruction {
    type Error = InstructionError;

    fn try_from(opcode: usize) -> Result<Self> {
        let opcode = u32::try_from(opcode)?;
        opcode.try_into()
    }
}

impl TryFrom<BFieldElement> for Instruction {
    type Error = InstructionError;

    fn try_from(opcode: BFieldElement) -> Result<Self> {
        let opcode = u32::try_from(opcode)?;
        opcode.try_into()
    }
}

/// Indicators for all the possible bits in an [`Instruction`].
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, EnumCount, EnumIter)]
pub enum InstructionBit {
    #[default]
    IB0,
    IB1,
    IB2,
    IB3,
    IB4,
    IB5,
    IB6,
}

impl Display for InstructionBit {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let bit_index = usize::from(*self);
        write!(f, "{bit_index}")
    }
}

impl From<InstructionBit> for usize {
    fn from(instruction_bit: InstructionBit) -> Self {
        match instruction_bit {
            InstructionBit::IB0 => 0,
            InstructionBit::IB1 => 1,
            InstructionBit::IB2 => 2,
            InstructionBit::IB3 => 3,
            InstructionBit::IB4 => 4,
            InstructionBit::IB5 => 5,
            InstructionBit::IB6 => 6,
        }
    }
}

impl TryFrom<usize> for InstructionBit {
    type Error = String;

    fn try_from(bit_index: usize) -> result::Result<Self, Self::Error> {
        match bit_index {
            0 => Ok(InstructionBit::IB0),
            1 => Ok(InstructionBit::IB1),
            2 => Ok(InstructionBit::IB2),
            3 => Ok(InstructionBit::IB3),
            4 => Ok(InstructionBit::IB4),
            5 => Ok(InstructionBit::IB5),
            6 => Ok(InstructionBit::IB6),
            _ => Err(format!(
                "Index {bit_index} is out of range for `InstructionBit`."
            )),
        }
    }
}

impl<'a> Arbitrary<'a> for LabelledInstruction {
    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
        let instruction = match u.choose_index(LabelledInstruction::COUNT)? {
            0 => u.arbitrary::<AnInstruction<String>>()?,
            1 => return Ok(Self::Label(u.arbitrary::<InstructionLabel>()?.into())),
            2 => return Ok(Self::Breakpoint),
            3 => return Ok(Self::TypeHint(u.arbitrary()?)),
            4 => return Ok(Self::AssertionContext(u.arbitrary()?)),
            _ => unreachable!(),
        };
        let legal_label = String::from(u.arbitrary::<InstructionLabel>()?);
        let instruction = instruction.map_call_address(|_| legal_label.clone());

        Ok(Self::Instruction(instruction))
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Hash)]
struct InstructionLabel(String);

impl From<InstructionLabel> for String {
    fn from(label: InstructionLabel) -> Self {
        label.0
    }
}

impl<'a> Arbitrary<'a> for InstructionLabel {
    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
        let legal_start_characters = ('a'..='z').chain('A'..='Z').chain('_'..='_');
        let legal_characters = legal_start_characters
            .clone()
            .chain('0'..='9')
            .chain('-'..='-')
            .collect_vec();

        let mut label = u.choose(&legal_start_characters.collect_vec())?.to_string();
        for _ in 0..u.arbitrary_len::<char>()? {
            label.push(*u.choose(&legal_characters)?);
        }
        while ALL_INSTRUCTION_NAMES.contains(&label.as_str()) {
            label.push(*u.choose(&legal_characters)?);
        }
        Ok(Self(label))
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Hash)]
struct TypeHintVariableName(String);

impl From<TypeHintVariableName> for String {
    fn from(label: TypeHintVariableName) -> Self {
        label.0
    }
}

impl<'a> Arbitrary<'a> for TypeHintVariableName {
    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
        let legal_start_characters = 'a'..='z';
        let legal_characters = legal_start_characters
            .clone()
            .chain('0'..='9')
            .chain('_'..='_')
            .collect_vec();

        let mut variable_name = u.choose(&legal_start_characters.collect_vec())?.to_string();
        for _ in 0..u.arbitrary_len::<char>()? {
            variable_name.push(*u.choose(&legal_characters)?);
        }
        Ok(Self(variable_name))
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Hash)]
struct TypeHintTypeName(String);

impl From<TypeHintTypeName> for String {
    fn from(label: TypeHintTypeName) -> Self {
        label.0
    }
}

impl<'a> Arbitrary<'a> for TypeHintTypeName {
    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
        let legal_start_characters = ('a'..='z').chain('A'..='Z');
        let legal_characters = legal_start_characters
            .clone()
            .chain('0'..='9')
            .collect_vec();

        let mut type_name = u.choose(&legal_start_characters.collect_vec())?.to_string();
        for _ in 0..u.arbitrary_len::<char>()? {
            type_name.push(*u.choose(&legal_characters)?);
        }
        Ok(Self(type_name))
    }
}

#[non_exhaustive]
#[derive(Debug, Clone, Eq, PartialEq, Error)]
pub enum InstructionError {
    #[error("opcode {0} is invalid")]
    InvalidOpcode(u32),

    #[error("opcode is out of range: {0}")]
    OutOfRangeOpcode(#[from] TryFromIntError),

    #[error("invalid argument {1} for instruction `{0}`")]
    IllegalArgument(Instruction, BFieldElement),

    #[error("instruction pointer points outside of program")]
    InstructionPointerOverflow,

    #[error("jump stack is empty")]
    JumpStackIsEmpty,

    #[error("assertion failed: {0}")]
    AssertionFailed(AssertionError),

    #[error("vector assertion failed because stack[{0}] != stack[{r}]: {1}", r = .0 + Digest::LEN)]
    VectorAssertionFailed(usize, AssertionError),

    #[error("0 does not have a multiplicative inverse")]
    InverseOfZero,

    #[error("division by 0 is impossible")]
    DivisionByZero,

    #[error("the Sponge state must be initialized before it can be used")]
    SpongeNotInitialized,

    #[error("the logarithm of 0 does not exist")]
    LogarithmOfZero,

    #[error("public input buffer is empty after {0} reads")]
    EmptyPublicInput(usize),

    #[error("secret input buffer is empty after {0} reads")]
    EmptySecretInput(usize),

    #[error("no more secret digests available")]
    EmptySecretDigestInput,

    #[error("Triton VM has halted and cannot execute any further instructions")]
    MachineHalted,

    #[error(transparent)]
    OpStackError(#[from] OpStackError),
}

/// An error giving additional context to any failed assertion.
#[non_exhaustive]
#[derive(Debug, Clone, Eq, PartialEq, Error)]
pub struct AssertionError {
    /// The [element](BFieldElement) expected by the assertion.
    pub expected: BFieldElement,

    /// The actual [element](BFieldElement) encountered when executing the assertion.
    pub actual: BFieldElement,

    /// A user-defined error ID. Only has user-defined, no inherent, semantics.
    pub id: Option<i128>,
    //
    // /// A user-defined error message supplying context to the failed assertion.
    // pub message: Option<String>,
}

impl Display for AssertionError {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        if let Some(id) = self.id {
            write!(f, "[{id}] ")?;
        }
        write!(f, "expected {}, got {}", self.expected, self.actual)
    }
}

impl AssertionError {
    pub fn new(expected: impl Into<BFieldElement>, actual: impl Into<BFieldElement>) -> Self {
        Self {
            expected: expected.into(),
            actual: actual.into(),
            id: None,
        }
    }

    #[must_use]
    pub fn with_context(mut self, context: AssertionContext) -> Self {
        match context {
            AssertionContext::ID(id) => self.id = Some(id),
        };
        self
    }
}

#[cfg(test)]
pub mod tests {
    use std::collections::HashMap;

    use assert2::assert;
    use itertools::Itertools;
    use num_traits::One;
    use num_traits::Zero;
    use rand::thread_rng;
    use rand::Rng;
    use strum::EnumCount;
    use strum::IntoEnumIterator;
    use strum::VariantNames;
    use twenty_first::prelude::*;

    use crate::triton_asm;
    use crate::triton_program;

    use super::*;

    #[derive(Debug, Copy, Clone, EnumCount, EnumIter, VariantNames)]
    pub enum InstructionBucket {
        HasArg,
        ShrinksStack,
        IsU32,
    }

    impl InstructionBucket {
        pub fn contains(self, instruction: Instruction) -> bool {
            match self {
                InstructionBucket::HasArg => instruction.arg().is_some(),
                InstructionBucket::ShrinksStack => instruction.op_stack_size_influence() < 0,
                InstructionBucket::IsU32 => instruction.is_u32_instruction(),
            }
        }

        pub fn flag(self) -> u32 {
            match self {
                InstructionBucket::HasArg => 1,
                InstructionBucket::ShrinksStack => 1 << 1,
                InstructionBucket::IsU32 => 1 << 2,
            }
        }
    }

    impl Instruction {
        pub fn flag_set(self) -> u32 {
            InstructionBucket::iter()
                .map(|bucket| u32::from(bucket.contains(self)) * bucket.flag())
                .fold(0, |acc, bit_flag| acc | bit_flag)
        }

        fn computed_opcode(self) -> u32 {
            let mut index_within_flag_set = 0;
            for other_instruction in Instruction::iter() {
                if other_instruction == self {
                    break;
                }
                if other_instruction.flag_set() == self.flag_set() {
                    index_within_flag_set += 1;
                }
            }

            index_within_flag_set * 2_u32.pow(InstructionBucket::COUNT as u32) + self.flag_set()
        }
    }

    #[test]
    fn computed_and_actual_opcodes_are_identical() {
        for instruction in Instruction::iter() {
            let opcode = instruction.computed_opcode();
            let name = instruction.name();
            println!("{opcode: >3} {name}");
        }

        for instruction in Instruction::iter() {
            let expected_opcode = instruction.computed_opcode();
            let opcode = instruction.opcode();
            assert!(expected_opcode == opcode, "{instruction}");
        }
    }

    #[test]
    fn opcodes_are_unique() {
        let mut opcodes_to_instruction_map = HashMap::new();
        for instruction in Instruction::iter() {
            let opcode = instruction.opcode();
            let maybe_entry = opcodes_to_instruction_map.insert(opcode, instruction);
            if let Some(other_instruction) = maybe_entry {
                panic!("{other_instruction} and {instruction} both have opcode {opcode}.");
            }
        }
    }

    #[test]
    fn number_of_instruction_bits_is_correct() {
        let all_opcodes = Instruction::iter().map(|instruction| instruction.opcode());
        let highest_opcode = all_opcodes.max().unwrap();
        let num_required_bits_for_highest_opcode = highest_opcode.ilog2() + 1;
        assert!(InstructionBit::COUNT == num_required_bits_for_highest_opcode as usize);
    }

    #[test]
    fn parse_push_pop() {
        let program = triton_program!(push 1 push 1 add pop 2);
        let instructions = program.into_iter().collect_vec();
        let expected = vec![
            Instruction::Push(bfe!(1)),
            Instruction::Push(bfe!(1)),
            Instruction::Add,
            Instruction::Pop(NumberOfWords::N2),
        ];

        assert!(expected == instructions);
    }

    #[test]
    #[should_panic(expected = "Duplicate label: foo")]
    fn fail_on_duplicate_labels() {
        triton_program!(
            push 2
            call foo
            bar: push 2
            foo: push 3
            foo: push 4
            halt
        );
    }

    #[test]
    fn ib_registers_are_binary() {
        for instruction in ALL_INSTRUCTIONS {
            for instruction_bit in InstructionBit::iter() {
                let ib_value = instruction.ib(instruction_bit);
                assert!(ib_value.is_zero() ^ ib_value.is_one());
            }
        }
    }

    #[test]
    fn instruction_to_opcode_to_instruction_is_consistent() {
        for instr in ALL_INSTRUCTIONS {
            assert!(instr == instr.opcode().try_into().unwrap());
        }
    }

    /// While the correct _number_ of instructions (respectively instruction names)
    /// is guaranteed at compile time, this test ensures the absence of repetitions.
    #[test]
    fn list_of_all_instructions_contains_unique_instructions() {
        assert!(ALL_INSTRUCTIONS.into_iter().all_unique());
        assert!(ALL_INSTRUCTION_NAMES.into_iter().all_unique());
    }

    #[test]
    fn convert_various_types_to_instructions() {
        let _push = Instruction::try_from(1_usize).unwrap();
        let _dup = Instruction::try_from(9_u64).unwrap();
        let _swap = Instruction::try_from(17_u32).unwrap();
        let _pop = Instruction::try_from(3_usize).unwrap();
    }

    #[test]
    fn change_arguments_of_various_instructions() {
        assert!(Instruction::Push(bfe!(0)).change_arg(bfe!(7)).is_ok());
        assert!(Instruction::Dup(OpStackElement::ST0)
            .change_arg(bfe!(1024))
            .is_err());
        assert!(Instruction::Swap(OpStackElement::ST0)
            .change_arg(bfe!(1337))
            .is_err());
        assert!(Instruction::Swap(OpStackElement::ST0)
            .change_arg(bfe!(0))
            .is_ok());
        assert!(Instruction::Swap(OpStackElement::ST0)
            .change_arg(bfe!(1))
            .is_ok());
        assert!(Instruction::Pop(NumberOfWords::N4)
            .change_arg(bfe!(0))
            .is_err());
        assert!(Instruction::Pop(NumberOfWords::N1)
            .change_arg(bfe!(2))
            .is_ok());
        assert!(Instruction::Nop.change_arg(bfe!(7)).is_err());
    }

    #[test]
    fn print_various_instructions() {
        println!("instruction_push: {:?}", Instruction::Push(bfe!(7)));
        println!("instruction_assert: {}", Instruction::Assert);
        println!("instruction_invert: {:?}", Instruction::Invert);
        println!(
            "instruction_dup: {}",
            Instruction::Dup(OpStackElement::ST14)
        );
    }

    #[test]
    fn instruction_size_is_consistent_with_having_arguments() {
        for instruction in Instruction::iter() {
            match instruction.arg() {
                Some(_) => assert!(2 == instruction.size()),
                None => assert!(1 == instruction.size()),
            }
        }
    }

    #[test]
    fn opcodes_are_consistent_with_argument_indication_bit() {
        let argument_indicator_bit_mask = 1;
        for instruction in Instruction::iter() {
            let opcode = instruction.opcode();
            println!("Testing instruction {instruction} with opcode {opcode}.");
            let has_arg = instruction.arg().is_some();
            assert!(has_arg == (opcode & argument_indicator_bit_mask != 0));
        }
    }

    #[test]
    fn opcodes_are_consistent_with_shrink_stack_indication_bit() {
        let shrink_stack_indicator_bit_mask = 2;
        for instruction in Instruction::iter() {
            let opcode = instruction.opcode();
            println!("Testing instruction {instruction} with opcode {opcode}.");
            let shrinks_stack = instruction.op_stack_size_influence() < 0;
            assert!(shrinks_stack == (opcode & shrink_stack_indicator_bit_mask != 0));
        }
    }

    #[test]
    fn opcodes_are_consistent_with_u32_indication_bit() {
        let u32_indicator_bit_mask = 4;
        for instruction in Instruction::iter() {
            let opcode = instruction.opcode();
            println!("Testing instruction {instruction} with opcode {opcode}.");
            assert!(instruction.is_u32_instruction() == (opcode & u32_indicator_bit_mask != 0));
        }
    }

    #[test]
    fn instruction_bits_are_consistent() {
        for instruction_bit in InstructionBit::iter() {
            println!("Testing instruction bit {instruction_bit}.");
            let bit_index = usize::from(instruction_bit);
            let recovered_instruction_bit = InstructionBit::try_from(bit_index).unwrap();
            assert!(instruction_bit == recovered_instruction_bit);
        }
    }

    #[test]
    fn instruction_bit_conversion_fails_for_invalid_bit_index() {
        let invalid_bit_index = thread_rng().gen_range(InstructionBit::COUNT..=usize::MAX);
        let maybe_instruction_bit = InstructionBit::try_from(invalid_bit_index);
        assert!(maybe_instruction_bit.is_err());
    }

    #[test]
    fn stringify_some_instructions() {
        let instructions = triton_asm!(push 3 invert push 2 mul push 1 add write_io 1 halt);
        let code = instructions.iter().join("\n");
        println!("{code}");
    }

    #[test]
    fn labelled_instructions_act_on_op_stack_as_indicated() {
        for instruction in ALL_INSTRUCTIONS {
            let labelled_instruction = instruction.map_call_address(|_| "dummy_label".to_string());
            let labelled_instruction = LabelledInstruction::Instruction(labelled_instruction);

            assert!(
                instruction.op_stack_size_influence()
                    == labelled_instruction.op_stack_size_influence()
            );
        }
    }

    #[test]
    fn labels_indicate_no_change_to_op_stack() {
        let labelled_instruction = LabelledInstruction::Label("dummy_label".to_string());
        assert!(0 == labelled_instruction.op_stack_size_influence());
    }

    #[test]
    fn can_change_arg() {
        for instr in ALL_INSTRUCTIONS {
            if let Some(arg) = instr.arg() {
                let new_instr = instr.change_arg(arg + bfe!(1)).unwrap();
                assert_eq!(instr.opcode(), new_instr.opcode());
                assert_ne!(instr, new_instr);
            } else {
                assert!(instr.change_arg(bfe!(0)).is_err())
            }
        }
    }
}