miden-assembly 0.31.0

Miden VM assembly language
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
// CONSTANTS
// ================================================================================================

use super::*;

#[test]
fn simple_constant() -> TestResult {
    let context = TestContext::default();
    let source = source_file!(
        &context,
        "\
    const TEST_CONSTANT = 7
    begin
        push.TEST_CONSTANT
    end"
    );
    let program = context.assemble(source)?;
    insta::assert_snapshot!(program);
    Ok(())
}

#[test]
fn enum_explicit_discriminants() -> TestResult {
    let context = TestContext::default();
    let source = source_file!(
        &context,
        r#"
enum Status : u16 {
    OK = 200,
    NOT_FOUND = 404,
    SERVER_ERROR = 500,
}

begin
    push.OK
    push.NOT_FOUND
    push.SERVER_ERROR
end
"#
    );
    let _program = context.assemble(source)?;
    Ok(())
}

#[test]
fn enum_discriminants_can_reference_constants() -> TestResult {
    let context = TestContext::default();
    let source = source_file!(
        &context,
        r#"
const BASE = 10

enum Status : u16 {
    OK = BASE,
    NOT_FOUND = OK + 1,
}

begin
    push.OK
    push.NOT_FOUND
end
"#
    );
    let _program = context.assemble(source)?;
    Ok(())
}

#[test]
fn enum_felt_repr_variants() -> TestResult {
    let context = TestContext::default();
    let source = source_file!(
        &context,
        r#"
enum Status : felt {
    OK = 1,
}

begin
    push.OK
end
"#
    );
    let _program = context.assemble(source)?;
    Ok(())
}

#[test]
fn enum_felt_discriminant_negative_is_rejected() {
    let context = TestContext::default();
    let source = source_file!(
        &context,
        r#"
enum Status : felt {
    BAD = 0 - 1,
}

begin
    push.BAD
end
"#
    );
    let err = context
        .assemble(source)
        .expect_err("expected negative discriminant to be rejected");
    assert_diagnostic!(err, "invalid constant expression: value is larger than expected range");
}

#[test]
fn enum_felt_discriminant_too_large_is_rejected() {
    let context = TestContext::default();
    let modulus = Felt::ORDER_U64;
    let source = source_file!(
        &context,
        format!(
            r#"
enum Status : felt {{
    BAD = {modulus},
}}

begin
    push.BAD
end
"#
        )
    );
    let err = context
        .assemble(source)
        .expect_err("expected out-of-range felt discriminant to be rejected");
    assert_diagnostic!(err, "invalid literal: value overflowed the field modulus");
}

#[test]
fn constant_expression_overflow_is_rejected() {
    let context = TestContext::default();
    let modulus_minus_one = Felt::ORDER_U64 - 1;
    let source = source_file!(
        &context,
        format!(
            "const TOO_BIG = {modulus_minus_one} + {modulus_minus_one}\nbegin\n    push.TOO_BIG\nend\n"
        )
    );
    let err = context
        .assemble(source)
        .expect_err("expected constant expression overflow to be rejected");
    assert_diagnostic!(err, "invalid constant expression: value is larger than expected range");
}

#[test]
fn multiple_constants_push() -> TestResult {
    let context = TestContext::default();
    let source = source_file!(
        &context,
        "\
    const CONSTANT_1 = 21 \
    const CONSTANT_2 = 44 \
    begin \
    push.CONSTANT_1.64.CONSTANT_2.72 \
    end"
    );
    let program = context.assemble(source)?;
    insta::assert_snapshot!(program);
    Ok(())
}

#[test]
fn constant_numeric_expression() -> TestResult {
    let context = TestContext::default();
    let source = source_file!(
        &context,
        "\
    const TEST_CONSTANT = 11-2+4*(12-(10+1))+9+8//4*2 \
    begin \
    push.TEST_CONSTANT \
    end \
    "
    );
    let program = context.assemble(source)?;
    insta::assert_snapshot!(program);
    Ok(())
}

#[test]
fn constant_alphanumeric_expression() -> TestResult {
    let context = TestContext::default();
    let source = source_file!(
        &context,
        "\
    const TEST_CONSTANT_1 = (18-1+10)*6-((13+7)*2) \
    const TEST_CONSTANT_2 = 11-2+4*(12-(10+1))+9
    const TEST_CONSTANT_3 = (TEST_CONSTANT_1-(TEST_CONSTANT_2+10))//5+3
    begin \
    push.TEST_CONSTANT_3 \
    end \
    "
    );
    let program = context.assemble(source)?;
    insta::assert_snapshot!(program);
    Ok(())
}

#[test]
fn constant_hexadecimal_value() -> TestResult {
    let context = TestContext::default();
    let source = source_file!(
        &context,
        "\
    const TEST_CONSTANT = 0xFF \
    begin \
    push.TEST_CONSTANT \
    end \
    "
    );
    let program = context.assemble(source)?;
    insta::assert_snapshot!(program);
    Ok(())
}

#[test]
fn constant_field_division() -> TestResult {
    let context = TestContext::default();
    let source = source_file!(
        &context,
        "\
    const TEST_CONSTANT = (17//4)/4*(1//2)+2 \
    begin \
    push.TEST_CONSTANT \
    end \
    "
    );
    let program = context.assemble(source)?;
    insta::assert_snapshot!(program);
    Ok(())
}

#[test]
fn constant_err_const_not_initialized() {
    let context = TestContext::default();
    let source = source_file!(
        &context,
        "\
    const TEST_CONSTANT = 5+A \
    begin \
    push.TEST_CONSTANT \
    end"
    );
    let err = context.assemble(source).expect_err("expected undefined constant diagnostic");
    assert_diagnostic!(&err, "undefined constant 'A'");
    assert_diagnostic!(&err, "the constant referenced here is not defined in the current scope");
    assert_diagnostic!(&err, "are you missing an import?");
}

#[test]
fn constant_err_div_by_zero() {
    let context = TestContext::default();
    let source = source_file!(
        &context,
        "\
    const TEST_CONSTANT = 5/0 \
    begin \
    push.TEST_CONSTANT \
    end"
    );
    let err = context.assemble(source).expect_err("expected division by zero diagnostic");
    assert_diagnostic!(&err, "invalid constant expression: division by zero");
    assert_diagnostic!(&err, "const TEST_CONSTANT = 5/0");

    let source = source_file!(
        &context,
        "\
    const TEST_CONSTANT = 5//0 \
    begin \
    push.TEST_CONSTANT \
    end"
    );
    let err = context.assemble(source).expect_err("expected division by zero diagnostic");
    assert_diagnostic!(&err, "invalid constant expression: division by zero");
    assert_diagnostic!(&err, "const TEST_CONSTANT = 5//0");
}

#[test]
fn constant_err_div_by_zero_indirect() {
    let context = TestContext::default();

    let source = source_file!(
        &context,
        "\
    const NUMERATOR = 10
    const DENOMINATOR = 0
    const BAD_DIV = NUMERATOR / DENOMINATOR

    begin
        push.BAD_DIV
    end"
    );

    let err = context.assemble(source).expect_err("expected division by zero diagnostic");
    assert_diagnostic!(&err, "invalid constant expression: division by zero");
    assert_diagnostic!(&err, "const BAD_DIV = NUMERATOR / DENOMINATOR");
}

#[test]
fn constant_err_div_by_zero_link_time() -> TestResult {
    let mut context = TestContext::default();

    let module_a = source_file!(
        &context,
        "namespace module_a

        pub const NUMERATOR = 10
        pub const DENOMINATOR = 0"
    );

    context.add_module(module_a)?;

    let source = source_file!(
        &context,
        "\
    use {NUMERATOR, DENOMINATOR} from module_a

    const BAD_DIV = NUMERATOR / DENOMINATOR

    begin
        push.BAD_DIV
    end"
    );

    let err = context.assemble(source).expect_err("expected division by zero diagnostic");
    assert_diagnostic!(&err, "invalid constant expression: division by zero");
    assert_diagnostic!(&err, "const BAD_DIV = NUMERATOR / DENOMINATOR");

    Ok(())
}

#[test]
fn constants_must_be_uppercase() {
    let context = TestContext::default();
    let source = source_file!(
        &context,
        "\
    const constant_1 = 12 \
    begin \
    push.constant_1 \
    end"
    );

    let err = context.assemble(source).expect_err("expected lowercase constant diagnostic");
    assert_diagnostic!(
        &err,
        "invalid identifier: only uppercase characters or underscores are allowed"
    );
    assert_diagnostic!(&err, "const constant_1 = 12");
}

#[test]
fn duplicate_constant_name() {
    let context = TestContext::default();
    let source = source_file!(
        &context,
        "\
    const CONSTANT = 12 \
    const CONSTANT = 14 \
    begin \
    push.CONSTANT \
    end"
    );

    let err = context.assemble(source).expect_err("expected duplicate constant diagnostic");
    assert_diagnostic!(&err, "symbol conflict: found duplicate definitions of the same name");
    assert_diagnostic!(&err, "conflict occurs here");
    assert_diagnostic!(&err, "previously defined here");
}

#[test]
fn constant_must_be_valid_felt() {
    let context = TestContext::default();
    let source = source_file!(
        &context,
        "\
    const CONSTANT = 1122INVALID \
    begin \
    push.CONSTANT \
    end"
    );

    let err = context.assemble(source).expect_err("expected invalid felt diagnostic");
    assert_diagnostic!(&err, "invalid syntax: unexpected trailing tokens in expression");
    assert_diagnostic!(&err, "unexpected trailing tokens in expression");
}

#[test]
fn constant_must_be_within_valid_felt_range() {
    let context = TestContext::default();

    // test the u64::MAX value
    let source = source_file!(
        &context,
        "\
    const CONSTANT = 18446744073709551615 \
    begin \
    push.CONSTANT \
    end"
    );

    let err = context.assemble(source).expect_err("expected felt overflow diagnostic");
    assert_diagnostic!(&err, "invalid literal: value overflowed the field modulus");
    assert_diagnostic!(&err, "18446744073709551615");

    // test the field modulus value in u64 form
    let source = source_file!(
        &context,
        "\
    const CONSTANT = 18446744069414584321 \
    begin \
    push.CONSTANT \
    end"
    );

    let err = context.assemble(source).expect_err("expected felt overflow diagnostic");
    assert_diagnostic!(&err, "invalid literal: value overflowed the field modulus");
    assert_diagnostic!(&err, "18446744069414584321");

    // test the field modulus value in hex form
    let source = source_file!(
        &context,
        "\
    const CONSTANT = 0xFFFFFFFF00000001 \
    begin \
    push.CONSTANT \
    end"
    );

    let err = context.assemble(source).expect_err("expected felt overflow diagnostic");
    assert_diagnostic!(&err, "invalid literal: value overflowed the field modulus");
    assert_diagnostic!(&err, "0xFFFFFFFF00000001");
}

#[test]
fn constants_defined_in_global_scope() {
    let context = TestContext::default();
    let source = source_file!(
        &context,
        "
    begin \
    const CONSTANT = 12
    push.CONSTANT \
    end"
    );

    let err = context
        .assemble(source)
        .expect_err("expected block-local constants to be rejected");
    assert_diagnostic!(&err, "Multiple syntax errors were identified");
    assert_diagnostic!(&err, "expected `end` to close `begin` block before top-level item");
    assert_diagnostic!(&err, "unexpected top-level token");
}

#[test]
fn constant_not_found() {
    let context = TestContext::new();
    let source = source_file!(
        &context,
        "
    begin \
    push.CONSTANT \
    end"
    );

    assert_assembler_diagnostic!(
        context,
        source,
        "syntax error",
        "help: see emitted diagnostics for details",
        "undefined constant 'CONSTANT'",
        regex!(r#",-\[test[\d]+:2:16\]"#),
        "1 |",
        "2 |     begin push.CONSTANT end",
        "  :                ^^^^|^^^",
        "  :                    `-- the constant referenced here is not defined in the current scope",
        "  `----",
        "help: are you missing an import?"
    );
}

#[test]
fn mem_operations_with_constants() -> TestResult {
    let context = TestContext::default();

    // Define constant values
    const PROC_LOC_STORE_PTR: u64 = 0;
    const PROC_LOC_LOAD_PTR: u64 = 1;
    const PROC_LOC_STOREW_PTR: u64 = 4;
    const PROC_LOC_LOADW_PTR: u64 = 8;
    const GLOBAL_STORE_PTR: u64 = 12;
    const GLOBAL_LOAD_PTR: u64 = 13;
    const GLOBAL_STOREW_PTR: u64 = 16;
    const GLOBAL_LOADW_PTR: u64 = 20;

    let source = source_file!(
        &context,
        format!(
            "\
    const PROC_LOC_STORE_PTR = {PROC_LOC_STORE_PTR}
    const PROC_LOC_LOAD_PTR = {PROC_LOC_LOAD_PTR}
    const PROC_LOC_STOREW_PTR = {PROC_LOC_STOREW_PTR}
    const PROC_LOC_LOADW_PTR = {PROC_LOC_LOADW_PTR}
    const GLOBAL_STORE_PTR = {GLOBAL_STORE_PTR}
    const GLOBAL_LOAD_PTR = {GLOBAL_LOAD_PTR}
    const GLOBAL_STOREW_PTR = {GLOBAL_STOREW_PTR}
    const GLOBAL_LOADW_PTR = {GLOBAL_LOADW_PTR}

    @locals(12)
    proc test_const_loc
        # constant should resolve using locaddr operation
        locaddr.PROC_LOC_STORE_PTR

        # constant should resolve using loc_store operation
        loc_store.PROC_LOC_STORE_PTR

        # constant should resolve using loc_load operation
        loc_load.PROC_LOC_LOAD_PTR

        # constant should resolve using loc_storew_be operation
        loc_storew_be.PROC_LOC_STOREW_PTR

        # constant should resolve using loc_loadw_be opeartion
        loc_loadw_be.PROC_LOC_LOADW_PTR
    end

    begin
        # inline procedure
        exec.test_const_loc

        # constant should resolve using mem_store operation
        mem_store.GLOBAL_STORE_PTR

        # constant should resolve using mem_load operation
        mem_load.GLOBAL_LOAD_PTR

        # constant should resolve using mem_storew_be operation
        mem_storew_be.GLOBAL_STOREW_PTR

        # constant should resolve using mem_loadw_be operation
        mem_loadw_be.GLOBAL_LOADW_PTR
    end
    "
        )
    );
    let program = context.assemble(source)?;

    // Define expected
    let expected = source_file!(
        &context,
        format!(
            "\
    @locals(12)
    proc test_const_loc
        # constant should resolve using locaddr operation
        locaddr.{PROC_LOC_STORE_PTR}

        # constant should resolve using loc_store operation
        loc_store.{PROC_LOC_STORE_PTR}

        # constant should resolve using loc_load operation
        loc_load.{PROC_LOC_LOAD_PTR}

        # constant should resolve using loc_storew_be operation
        loc_storew_be.{PROC_LOC_STOREW_PTR}

        # constant should resolve using loc_loadw_be opeartion
        loc_loadw_be.{PROC_LOC_LOADW_PTR}
    end

    begin
        # inline procedure
        exec.test_const_loc

        # constant should resolve using mem_store operation
        mem_store.{GLOBAL_STORE_PTR}

        # constant should resolve using mem_load operation
        mem_load.{GLOBAL_LOAD_PTR}

        # constant should resolve using mem_storew_be operation
        mem_storew_be.{GLOBAL_STOREW_PTR}

        # constant should resolve using mem_loadw_be operation
        mem_loadw_be.{GLOBAL_LOADW_PTR}
    end
    "
        )
    );
    let expected_program = context.assemble(expected)?;
    assert_eq!(expected_program.to_string(), program.to_string());
    Ok(())
}

#[test]
fn const_conversion_failed_to_u16() {
    // Define constant value greater than u16::MAX
    let constant_value: u64 = u16::MAX as u64 + 1;

    let context = TestContext::default();
    let source = source_file!(
        &context,
        format!(
            "\
    const CONSTANT = {constant_value}

    @locals(1)
    proc test_constant_overflow
        loc_load.CONSTANT
    end

    begin
        exec.test_constant_overflow
    end
    "
        )
    );

    assert_assembler_diagnostic!(
        context,
        source,
        "syntax error",
        "help: see emitted diagnostics for details",
        "invalid immediate: value is larger than expected range",
        regex!(r#",-\[test[\d]+:5:18\]"#),
        "4 |     proc test_constant_overflow",
        "5 |         loc_load.CONSTANT",
        "  :                  ^^^^^^^^",
        "6 |     end",
        "  `----"
    );
}

#[test]
fn const_conversion_failed_to_u32() {
    let context = TestContext::default();
    // Define constant value greater than u16::MAX
    let constant_value: u64 = u32::MAX as u64 + 1;

    let source = source_file!(
        &context,
        format!(
            "\
    const CONSTANT = {constant_value}

    begin
        mem_load.CONSTANT
    end
    "
        )
    );

    assert_assembler_diagnostic!(
        context,
        source,
        "syntax error",
        "help: see emitted diagnostics for details",
        "invalid immediate: value is larger than expected range",
        regex!(r#",-\[test[\d]+:4:18\]"#),
        "3 |     begin",
        "4 |         mem_load.CONSTANT",
        "  :                  ^^^^^^^^",
        "5 |     end",
        "  `----"
    );
}

#[test]
fn deprecated_mem_loadw_instruction() {
    let context = TestContext::default();

    let source = source_file!(
        &context,
        "\
    begin
        mem_loadw
    end
    "
    );

    assert_assembler_diagnostic!(
        context,
        source,
        "deprecated instruction: `mem_loadw` has been removed",
        regex!(r#",-\[test[\d]+:2:9\]"#),
        "1 | begin",
        "2 |         mem_loadw",
        regex!(r#"^ *: *\^+"#),
        regex!(r#"this instruction is no longer supported"#),
        "3 |     end",
        "  `----",
        regex!(r#"help:.*use.*mem_loadw_be.*instead"#)
    );
}

#[test]
fn deprecated_loc_loadw_instruction() {
    let context = TestContext::default();

    let source = source_file!(
        &context,
        "\
    @locals(8)
    proc foo
        loc_loadw.0
    end
    begin
        exec.foo
    end
    "
    );

    assert_assembler_diagnostic!(
        context,
        source,
        "deprecated instruction: `loc_loadw` has been removed",
        regex!(r#",-\[test[\d]+:3:9\]"#),
        "2 |     proc foo",
        "3 |         loc_loadw.0",
        regex!(r#"^ *: *\^+"#),
        regex!(r#"this instruction is no longer supported"#),
        "4 |     end",
        "  `----",
        regex!(r#"help:.*use.*loc_loadw_be.*instead"#)
    );
}

#[test]
fn deprecated_loc_storew_instruction() {
    let context = TestContext::default();

    let source = source_file!(
        &context,
        "\
    @locals(8)
    proc foo
        loc_storew.0
    end
    begin
        exec.foo
    end
    "
    );

    assert_assembler_diagnostic!(
        context,
        source,
        "deprecated instruction: `loc_storew` has been removed",
        regex!(r#",-\[test[\d]+:3:9\]"#),
        "2 |     proc foo",
        "3 |         loc_storew.0",
        regex!(r#"^ *: *\^+"#),
        regex!(r#"this instruction is no longer supported"#),
        "4 |     end",
        "  `----",
        regex!(r#"help:.*use.*loc_storew_be.*instead"#)
    );
}

#[test]
fn const_word_from_string() -> TestResult {
    let context = TestContext::default();
    let sample_source_string = "lorem ipsum";

    let source = source_file!(
        &context,
        format!(
            r#"
    const SAMPLE_WORD = word("{sample_source_string}")

    begin
        push.SAMPLE_WORD
    end
    "#
        )
    );
    let program = context.assemble(source)?;

    insta::assert_snapshot!(program);

    Ok(())
}

/// Check that the event ID conversion during compilation is consistent with
/// string_to_event_id.
#[test]
fn const_event_from_string() -> TestResult {
    let context = TestContext::default();
    let sample_event_name = "miden::test::constant";
    let expected_felt = EventId::from_name(sample_event_name);

    let source1 = source_file!(
        &context,
        format!(
            r#"
    begin
        emit.event("{sample_event_name}")
    end
    "#
        )
    );
    let source2 = source_file!(
        &context,
        format!(
            r#"
    begin
        push.{expected_felt}
        emit
        drop
    end
    "#
        )
    );

    let program1 = context.assemble(source1)?;
    let program2 = context.assemble(source2)?;
    assert_eq!(program1.hash(), program2.hash());

    Ok(())
}

#[test]
fn test_push_word_slice() -> TestResult {
    let context = TestContext::default();
    let source = source_file!(
        &context,
        "\
    const SAMPLE_WORD = [2, 3, 4, 5]
    const SAMPLE_HEX_WORD = 0x0600000000000000070000000000000008000000000000000900000000000000

    begin
        push.SAMPLE_WORD[1..3]
        push.SAMPLE_WORD[0]
        push.[10, 11, 12, 13][1..3]

        push.SAMPLE_HEX_WORD[2..4]
        push.0x0600000000000000070000000000000008000000000000000900000000000000[0..2]
    end
    "
    );
    let program = context.assemble(source)?;

    insta::assert_snapshot!(program);
    Ok(())
}

#[test]
fn test_push_word_slice_invalid() {
    let context = TestContext::default();
    let source_invalid_range = source_file!(
        &context,
        "\
    const SAMPLE_WORD = [2, 3, 4, 5]

    begin
        push.SAMPLE_WORD[6..3]
    end
    "
    );
    assert!(context.assemble(source_invalid_range).is_err());

    let source_empty_range = source_file!(
        &context,
        "\
    const SAMPLE_WORD = [2, 3, 4, 5]

    begin
        push.SAMPLE_WORD[2..2]
    end
    "
    );
    assert!(context.assemble(source_empty_range).is_err());

    let source_invalid_constant_type = source_file!(
        &context,
        "\
    const SAMPLE_VALUE = 6
    begin
        push.SAMPLE_VALUE[1..3]
    end
    "
    );
    assert!(context.assemble(source_invalid_constant_type).is_err());

    let source_invalid_constant_type = source_file!(
        &context,
        "\
    begin
        push.5[0..2]
    end
    "
    );
    assert!(context.assemble(source_invalid_constant_type).is_err());
}

#[test]
fn link_time_const_evaluation_succeeds() -> TestResult {
    let context = TestContext::default();
    let a = r#"
            namespace lib::a

            pub const FOO = 1
            pub proc f
                push.FOO
            end
        "#;
    let a = parse_module!(&context, a);

    let lib =
        Assembler::new(context.source_manager()).assemble_library("lib", a, None::<Box<Module>>)?;

    let program_source = source_file!(
        &context,
        "\
        use lib::a
        use {FOO} from lib::a
        begin
            push.FOO
            exec.a::f
            add
            add
        end"
    );

    let program = Assembler::new(context.source_manager())
        .with_package(Arc::from(lib), Linkage::Dynamic)?
        .assemble_program("program", program_source)?
        .unwrap_program();
    insta::assert_snapshot!(program);

    Ok(())
}

#[test]
fn link_time_const_evaluation_deferred_expressions_succeed() -> TestResult {
    let context = TestContext::default();
    let constants = parse_module!(
        &context,
        r#"
            namespace lib::constants

            pub const WORD_NUM_ELEMENTS = 4

            pub proc noop
                nop
            end
        "#
    );
    let lib = Assembler::new(context.source_manager()).assemble_library(
        "lib",
        constants,
        None::<Box<Module>>,
    )?;

    let program = source_file!(
        &context,
        r#"
            use {WORD_NUM_ELEMENTS} from lib::constants

            const OFFSET_1 = WORD_NUM_ELEMENTS + 1
            const OFFSET_2 = OFFSET_1 + 1
            const IMPORTED_ON_RHS = 10 - WORD_NUM_ELEMENTS
            const MULTIPLE_DEFERRED_SUBTREES =
                (WORD_NUM_ELEMENTS + 1) * (WORD_NUM_ELEMENTS - 1)
            const FIELD_DIVISION = WORD_NUM_ELEMENTS / 2
            const INTEGER_DIVISION = (WORD_NUM_ELEMENTS + 3) // 2

            begin
                push.OFFSET_2
                push.6
                assert_eq

                push.IMPORTED_ON_RHS
                push.6
                assert_eq

                push.MULTIPLE_DEFERRED_SUBTREES
                push.15
                assert_eq

                push.FIELD_DIVISION
                push.2
                assert_eq

                push.INTEGER_DIVISION
                push.3
                assert_eq
            end
        "#
    );

    Assembler::new(context.source_manager())
        .with_package(Arc::from(lib), Linkage::Dynamic)?
        .assemble_program("program", program)?;

    Ok(())
}

#[test]
fn link_time_event_constants_must_be_event_hashes() -> TestResult {
    let context = TestContext::default();
    let constants = parse_module!(
        &context,
        r#"
            namespace lib::constants

            pub const INT = 100
            pub const WORD = word("foo")
            pub const EVENT = event("miden::test::imported")

            pub proc noop
                nop
            end
        "#
    );
    let lib: Arc<Package> = Arc::from(Assembler::new(context.source_manager()).assemble_library(
        "lib",
        constants,
        None::<Box<Module>>,
    )?);

    for (instruction, constant) in
        [("emit", "INT"), ("emit", "WORD"), ("trace", "INT"), ("trace", "WORD")]
    {
        let program = source_file!(
            &context,
            format!(
                "use {{{constant}}} from lib::constants\nbegin\n    {instruction}.{constant}\nend"
            )
        );
        let err = Assembler::new(context.source_manager())
            .with_package(lib.clone(), Linkage::Dynamic)?
            .assemble_program("program", program)
            .expect_err("imported event constant must be defined via event() hashing");
        assert_diagnostic!(&err, "expected an event name");
    }

    let program = source_file!(
        &context,
        "use {EVENT} from lib::constants\nbegin\n    emit.EVENT\n    trace.EVENT\nend"
    );
    Assembler::new(context.source_manager())
        .with_package(lib, Linkage::Dynamic)?
        .assemble_program("program", program)?;

    Ok(())
}

#[test]
fn link_time_const_evaluation_undefined_symbol() -> TestResult {
    let context = TestContext::default();
    let a = r#"
            namespace lib::a

            pub proc f
                push.1
            end
        "#;
    let a = parse_module!(&context, a);

    let lib =
        Assembler::new(context.source_manager()).assemble_library("lib", a, None::<Box<Module>>)?;

    let source = source_file!(
        &context,
        "\
        use {FOO} from lib::a
        begin
            push.FOO
            exec.lib::a::f
            add
        end"
    );

    let error = Assembler::new(context.source_manager())
        .with_package(Arc::from(lib), Linkage::Dynamic)?
        .assemble_program("program", source)
        .expect_err("expected diagnostic to be raised, but compilation succeeded");
    assert_diagnostic_lines!(
        error,
        "undefined item 'lib::a::FOO'",
        regex!(r#",-\[test[\d]+:1:6\]"#),
        "1 | use {FOO} from lib::a",
        "  :      ^^^",
        "2 |         begin",
        "  `----",
        "help: you might be missing an import, or the containing library has not been linked"
    );

    Ok(())
}

#[test]
fn link_time_const_evaluation_invalid_constant() -> TestResult {
    let context = TestContext::default();
    let a = r#"
            namespace lib::a

            pub proc f
                push.1
            end
        "#;
    let a = parse_module!(&context, a);

    let lib =
        Assembler::new(context.source_manager()).assemble_library("lib", a, None::<Box<Module>>)?;

    let source = source_file!(
        &context,
        "\
    use {f} from lib::a
    begin
        push.f
    end"
    );

    let error = Assembler::new(context.source_manager())
        .with_package(Arc::from(lib), Linkage::Dynamic)?
        .assemble_program("program", source)
        .expect_err("expected diagnostic to be raised, but compilation succeeded");

    assert_diagnostic_lines!(
        error,
        "invalid identifier: only uppercase characters or underscores are allowed, and must start with an alphabetic character",
        "invalid identifier: only uppercase characters or underscores are allowed, and must start with an alphabetic character",
        regex!(r#",-\[test[\d]+:3:14\]"#),
        "2 |     begin",
        "3 |         push.f",
        "  :              ^",
        "4 |     end",
        "  `----",
        "help: bare identifiers must be lowercase alphanumeric with '_', quoted identifiers can include any graphical character"
    );

    Ok(())
}