miden-assembly-syntax 0.22.1

Parsing and semantic analysis of the Miden 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
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
use alloc::{string::ToString, vec::Vec};

use miden_debug_types::{SourceSpan, Span};
use miden_utils_diagnostics::Report;
use pretty_assertions::assert_eq;

use crate::{
    Felt, PathBuf, assert_diagnostic, assert_diagnostic_lines,
    ast::{types::Type, *},
    parser::{IntValue, WordValue},
    regex, source_file,
    testing::SyntaxTestContext,
};

macro_rules! id {
    ($name:ident) => {
        Ident::new(stringify!($name)).unwrap()
    };

    ($name:ty) => {
        Ident::new(stringify!($name)).unwrap()
    };
}

macro_rules! path {
    ($path:literal) => {
        Span::unknown(PathBuf::new($path).expect("invalid path").into())
    };

    ($path:ident) => {
        Span::unknown(PathBuf::new(stringify!($path)).expect("invalid path").into())
    };

    ($path:ty) => {
        Span::unknown(PathBuf::new(stringify!($path)).expect("invalid path").into())
    };
}

macro_rules! inst {
    ($inst:ident($value:expr)) => {
        Op::Inst(Span::unknown(Instruction::$inst($value)))
    };

    ($inst:ident) => {
        Op::Inst(Span::unknown(Instruction::$inst))
    };
}

macro_rules! exec {
    ($name:ident) => {
        inst!(Exec(InvocationTarget::Symbol(
            stringify!($name).parse().expect("invalid procedure name")
        )))
    };

    ($name:path) => {{
        let path = stringify!($name).parse::<PathBuf>().expect("invalid procedure path");
        let path = path.into_boxed_path().into();

        inst!(Exec(InvocationTarget::Path(Span::unknown(path))))
    }};
}

#[expect(unused_macros)]
macro_rules! call {
    ($name:ident) => {
        inst!(Call(InvocationTarget::Symbol(stringify!($name).parse())))
    };

    ($name:path) => {{
        let path = stringify!($name).parse().expect("invalid procedure path");

        inst!(Call(InvocationTarget::Path(path)))
    }};
}

macro_rules! block {
    ($($insts:expr),+) => {
        Block::new(Default::default(), Vec::from([$($insts),*]))
    }
}

macro_rules! moduledoc {
    ($doc:literal) => {
        Form::ModuleDoc(Span::unknown($doc.to_string()))
    };

    ($doc:ident) => {
        Form::ModuleDoc(Span::unknown($doc.to_string()))
    };
}

macro_rules! doc {
    ($doc:literal) => {
        Form::Doc(Span::unknown($doc.to_string()))
    };

    ($doc:ident) => {
        Form::Doc(Span::unknown($doc.to_string()))
    };
}

macro_rules! begin {
    ($($insts:expr),+) => {
        Form::Begin(block!($($insts),*))
    }
}

macro_rules! if_true {
    ($then_blk:expr) => {
        Op::If {
            span: Default::default(),
            then_blk: $then_blk,
            else_blk: Block::default(),
        }
    };

    ($then_blk:expr, $else_blk:expr) => {
        Op::If {
            span: Default::default(),
            then_blk: $then_blk,
            else_blk: $else_blk,
        }
    };
}

macro_rules! while_true {
    ($body:expr) => {
        Op::While { span: Default::default(), body: $body }
    };
}

macro_rules! type_alias {
    ($alias:ident, $ty:expr) => {
        Form::Type(TypeAlias::new(Visibility::Private, id!($alias), $ty.into()))
    };

    ($alias:ty, $ty:expr) => {
        Form::Type(TypeAlias::new(Visibility::Private, id!($alias), $ty.into()))
    };
}

macro_rules! type_ref {
    ($path:literal) => {
        TypeExpr::Ref(path!($path))
    };

    ($alias:ident) => {
        TypeExpr::Ref(path!($alias))
    };

    ($alias:ty) => {
        TypeExpr::Ref(path!($alias))
    };
}

macro_rules! struct_ty {
    ($($field_name:ident : $field_ty:expr),+) => {
        __struct_ty!(None, $($field_name : $field_ty),*)
    };

    ($name:ident, $($field_name:ident : $field_ty:expr),+) => {
        __struct_ty!(Some(id!($name)), $($field_name : $field_ty),*)
    };

    ($name:ty, $($field_name:ident : $field_ty:expr),+) => {
        __struct_ty!(Some(id!($name)), $($field_name : $field_ty),*)
    }
}

macro_rules! __struct_ty {
    ($name:expr, $($field_name:ident : $field_ty:expr),+) => {
        TypeExpr::Struct(StructType::new($name, [
            $(
                StructField {
                    span: SourceSpan::UNKNOWN,
                    name: id!($field_name),
                    ty: $field_ty.into(),
                }
            ),*
        ]))
    }
}

macro_rules! array_ty {
    ($element_ty:expr, $arity:literal) => {
        TypeExpr::Array(ArrayType::new($element_ty.into(), $arity))
    };
}

macro_rules! function_ty {
    ($($arg_ty:expr),* => $($result_ty:expr),*) => {
        FunctionType::new(types::CallConv::Fast, vec![$($arg_ty),*], vec![$($result_ty),*])
    }
}

macro_rules! enum_ty {
    ($name:ident, $ty:expr, $($variant:expr),+) => {
        Form::Enum(EnumType::new(Visibility::Private, id!($name), $ty.into(), [$($variant),*]))
    };

    ($name:ty, $ty:expr, $($variant:expr),+) => {
        Form::Enum(EnumType::new(Visibility::Private, id!($name), $ty.into(), [$($variant),*]))
    };
}

macro_rules! variant {
    ($name:ident, $discriminant:expr) => {
        Variant::new(id!($name), $discriminant.into(), None)
    };
}

macro_rules! const_int {
    ($value:literal) => {
        ConstantExpr::Int(Span::unknown(IntValue::from($value)))
    };
}

macro_rules! const_ref {
    ($path:literal) => {
        ConstantExpr::Var(path!($path))
    };

    ($name:ident) => {
        ConstantExpr::Var(path!($name))
    };
}

macro_rules! const_mul {
    ($lhs:expr, $rhs:expr) => {
        ConstantExpr::BinaryOp {
            span: SourceSpan::UNKNOWN,
            op: ConstantOp::Mul,
            lhs: alloc::boxed::Box::new($lhs),
            rhs: alloc::boxed::Box::new($rhs),
        }
    };
}

macro_rules! const_add {
    ($lhs:expr, $rhs:expr) => {
        ConstantExpr::BinaryOp {
            span: SourceSpan::UNKNOWN,
            op: ConstantOp::Add,
            lhs: alloc::boxed::Box::new($lhs),
            rhs: alloc::boxed::Box::new($rhs),
        }
    };
}

macro_rules! import {
    ($name:literal) => {{
        let path = $name.parse::<PathBuf>().expect("invalid import path");
        let name = Ident::new(path.last().unwrap()).unwrap();
        Form::Alias(Alias::new(
            Visibility::Private,
            name,
            AliasTarget::Path(Span::unknown(path.into())),
        ))
    }};

    ($name:literal -> $alias:literal) => {
        let path = $name.parse::<PathBuf>().expect("invalid import path").into();
        let name = $alias.parse().expect("invalid import alias");
        Form::Alias(Alias::new(Visibility::Private, name, AliasTarget::Path(Span::unknown(path))))
    };
}

macro_rules! proc {
    ($name:ident, $num_locals:literal, $body:expr) => {
        Form::Procedure(Procedure::new(
            Default::default(),
            Visibility::Private,
            stringify!($name).parse().expect("invalid procedure name"),
            $num_locals,
            $body,
        ))
    };

    ([$($attr:expr),*], $name:ident, $num_locals:literal, $body:expr) => {
        Form::Procedure(
            Procedure::new(
                Default::default(),
                Visibility::Private,
                stringify!($name).parse().expect("invalid procedure name"),
                $num_locals,
                $body,
            )
            .with_attributes([$($attr),*]),
        )
    };

    ($docs:literal, $name:ident, $num_locals:literal, $body:expr) => {
        Form::Procedure(
            Procedure::new(
                Default::default(),
                Visibility::Private,
                stringify!($name).parse().expect("invalid procedure name"),
                $num_locals,
                $body,
            )
            .with_docs(Some(Span::unknown($docs.to_string()))),
        )
    };

    ($docs:literal, [$($attr:expr),*], $name:ident, $num_locals:literal, $body:expr) => {
        Form::Procedure(
            Procedure::new(
                Default::default(),
                Visibility::Private,
                stringify!($name).parse().expect("invalid procedure name"),
                $num_locals,
                $body,
            )
            .with_docs($docs)
            .with_attributes([$($attr),*]),
        )
    };
}

macro_rules! export {
    ($name:ident, $num_locals:literal, $body:expr) => {
        Form::Procedure(Procedure::new(
            Default::default(),
            Visibility::Public,
            stringify!($name).parse().expect("invalid procedure name"),
            $num_locals,
            $body,
        ))
    };

    ($docs:expr, $name:ident, $num_locals:literal, $body:expr) => {
        Form::Procedure(
            Procedure::new(
                Default::default(),
                Visibility::Public,
                stringify!($name).parse().expect("invalid procedure name"),
                $num_locals,
                $body,
            )
            .with_docs(Some(Span::unknown($docs.to_string()))),
        )
    };
}

macro_rules! typed_export {
    ($name:ident, $num_locals:literal, $signature:expr, $body:expr) => {
        Form::Procedure(
            Procedure::new(
                Default::default(),
                Visibility::Public,
                stringify!($name).parse().expect("invalid procedure name"),
                $num_locals,
                $body,
            )
            .with_signature($signature),
        )
    };

    ($docs:expr, $name:ident, $num_locals:literal, $signature:expr, $body:expr) => {
        Form::Procedure(
            Procedure::new(
                Default::default(),
                Visibility::Public,
                stringify!($name).parse().expect("invalid procedure name"),
                $num_locals,
                $body,
            )
            .with_signature($signature)
            .with_docs(Some(Span::unknown($docs.to_string()))),
        )
    };
}

macro_rules! module {
    ($($forms:expr),+) => {
        Vec::<Form>::from([
            $(
                Form::from($forms),
            )*
        ])
    }
}

macro_rules! assert_forms {
    ($context:ident, $source:expr, $expected:expr) => {
        match $context.parse_forms($source.clone()) {
            Ok(forms) => assert_eq!(forms, $expected),
            Err(report) => {
                panic!(
                    "expected parsing to succeed but failed with error:
{}",
                    crate::diagnostics::reporting::PrintDiagnostic::new_without_color(report)
                );
            },
        }
    };
}

macro_rules! assert_parse_diagnostic {
    ($source:expr, $expected:literal) => {{
        let source = $source.clone();
        let error = crate::parser::parse_forms(source.clone())
            .map_err(|err| Report::new(err).with_source_code(source))
            .expect_err("expected diagnostic to be raised, but parsing succeeded");
        assert_diagnostic!(error, $expected);
    }};

    ($source:expr, $expected:expr) => {{
        let source = $source.clone();
        let error = crate::parser::parse_forms(source.clone())
            .map_err(|err| Report::new(err).with_source_code(source))
            .expect_err("expected diagnostic to be raised, but parsing succeeded");
        assert_diagnostic!(error, $expected);
    }};
}

macro_rules! assert_parse_diagnostic_lines {
    ($source:expr, $($expected:literal),+) => {{
        let error = crate::parser::parse_forms(source.clone())
            .map_err(|err| Report::new(err).with_source_code(source))
            .expect_err("expected diagnostic to be raised, but parsing succeeded");
        assert_diagnostic_lines!(error, $($expected),*);
    }};

    ($source:expr, $($expected:expr),+) => {{
        let source = $source.clone();
        let error = crate::parser::parse_forms(source.clone())
            .map_err(|err| Report::new(err).with_source_code(source))
            .expect_err("expected diagnostic to be raised, but parsing succeeded");
        assert_diagnostic_lines!(error, $($expected),*);
    }};
}

macro_rules! assert_module_diagnostic_lines {
    ($context:ident, $source:expr, $($expected:literal),+) => {{
        let error = $context
            .parse_module($source)
            .expect_err("expected diagnostic to be raised, but parsing succeeded");
        assert_diagnostic_lines!(error, $($expected),*);
    }};

    ($context:ident, $source:expr, $($expected:expr),+) => {{
        let error = $context
            .parse_module($source)
            .expect_err("expected diagnostic to be raised, but parsing succeeded");
        assert_diagnostic_lines!(error, $($expected),*);
    }};
}

#[expect(unused_macros)]
macro_rules! assert_program_diagnostic_lines {
    ($context:ident, $source:expr, $($expected:literal),+) => {{
        let error = $context
            .parse_program($source)
            .expect_err("expected diagnostic to be raised, but parsing succeeded");
        assert_diagnostic_lines!(error, $($expected),*);
    }};

    ($context:ident, $source:expr, $($expected:expr),+) => {{
        let error = $context
            .parse_program($source)
            .expect_err("expected diagnostic to be raised, but parsing succeeded");
        assert_diagnostic_lines!(error, $($expected),*);
    }};
}

// UNIT TESTS
// ================================================================================================

/// Tests the AST parsing
#[test]
fn test_ast_parsing_program_simple() -> Result<(), Report> {
    let context = SyntaxTestContext::new();

    let source = source_file!(&context, "begin push.0 assertz add.1 end");
    let forms = module!(begin!(
        inst!(Push(Immediate::Value(Span::unknown(IntValue::U8(0).into())))),
        inst!(Assertz),
        inst!(Incr)
    ));

    assert_eq!(context.parse_forms(source)?, forms);

    Ok(())
}

#[test]
fn test_ast_parsing_program_push() -> Result<(), Report> {
    let context = SyntaxTestContext::new();

    let source = source_file!(
        &context,
        r#"
    begin
        push.10 push.500 push.70000 push.5000000000
        push.5000000000.7000000000.9000000000.11000000000
        push.5.7
        push.500.700
        push.70000.90000
        push.5000000000.7000000000

        push.0x0000000000000000010000000000000002000000000000000300000000000000
    end"#
    );
    let forms = module!(begin!(
        inst!(Push(Immediate::Value(Span::unknown(10u8.into())))),
        inst!(Push(Immediate::Value(Span::unknown(500u16.into())))),
        inst!(Push(Immediate::Value(Span::unknown(70000u32.into())))),
        inst!(Push(Immediate::Value(Span::unknown(Felt::new(5000000000_u64).into())))),
        inst!(Push(Immediate::Value(Span::unknown(Felt::new(5000000000_u64).into())))),
        inst!(Push(Immediate::Value(Span::unknown(Felt::new(7000000000_u64).into())))),
        inst!(Push(Immediate::Value(Span::unknown(Felt::new(9000000000_u64).into())))),
        inst!(Push(Immediate::Value(Span::unknown(Felt::new(11000000000_u64).into())))),
        inst!(Push(Immediate::Value(Span::unknown(5u8.into())))),
        inst!(Push(Immediate::Value(Span::unknown(7u8.into())))),
        inst!(Push(Immediate::Value(Span::unknown(500u16.into())))),
        inst!(Push(Immediate::Value(Span::unknown(700u16.into())))),
        inst!(Push(Immediate::Value(Span::unknown(70000u32.into())))),
        inst!(Push(Immediate::Value(Span::unknown(90000u32.into())))),
        inst!(Push(Immediate::Value(Span::unknown(Felt::new(5000000000_u64).into())))),
        inst!(Push(Immediate::Value(Span::unknown(Felt::new(7000000000_u64).into())))),
        inst!(Push(Immediate::Value(Span::unknown(
            WordValue([Felt::new(0), Felt::new(1), Felt::new(2), Felt::new(3)]).into()
        ))))
    ));

    assert_eq!(context.parse_forms(source)?, forms);

    // Push a hexadecimal string containing more than 4 values
    let source_too_long = source_file!(
        &context,
        "begin push.0x00000000000000001000000000000000200000000000000030000000000000004000000000000000"
    );
    assert_parse_diagnostic!(source_too_long, "long hex strings must contain exactly 64 digits");

    // Push a hexadecimal string containing less than 4 values
    let source_too_long = source_file!(&context, "begin push.0x00000000000000001000000000000000");
    assert_parse_diagnostic!(source_too_long, "expected 2, 4, 8, 16, or 64 hex digits");

    Ok(())
}

#[test]
fn test_ast_parsing_program_u32() -> Result<(), Report> {
    let context = SyntaxTestContext::new();

    let source = source_file!(
        &context,
        r#"
    begin
        push.3

        u32wrapping_add.5
        u32overflowing_add.5
        u32widening_add.5
        u32widening_add3

        u32wrapping_sub.1
        u32overflowing_sub.1

        u32wrapping_mul.2
        u32widening_mul.2

    end"#
    );
    let forms = module!(begin!(
        inst!(Push(Immediate::Value(Span::unknown(3u8.into())))),
        inst!(U32WrappingAddImm(5u32.into())),
        inst!(U32OverflowingAddImm(5u32.into())),
        inst!(U32WideningAddImm(5u32.into())),
        inst!(U32WideningAdd3),
        inst!(U32WrappingSubImm(1u32.into())),
        inst!(U32OverflowingSubImm(1u32.into())),
        inst!(U32WrappingMulImm(2u32.into())),
        inst!(U32WideningMulImm(2u32.into()))
    ));

    assert_eq!(context.parse_forms(source)?, forms);

    Ok(())
}

#[test]
fn test_ast_parsing_program_proc() -> Result<(), Report> {
    let context = SyntaxTestContext::new();

    let source = source_file!(
        &context,
        r#"
    @locals(1)
    proc foo
        loc_load.0
    end
    @locals(2)
    proc bar
        padw
    end
    begin
        exec.foo
        exec.bar
    end"#
    );

    let forms = module!(
        proc!(foo, 1, block!(inst!(LocLoad(0u16.into())))),
        proc!(bar, 2, block!(inst!(PadW))),
        begin!(exec!(foo), exec!(bar))
    );
    assert_eq!(context.parse_forms(source)?, forms);

    Ok(())
}

#[test]
fn test_ast_parsing_module() -> Result<(), Report> {
    let context = SyntaxTestContext::new();
    let source = source_file!(
        &context,
        r#"
    @locals(1)
    pub proc foo
        loc_load.0
    end"#
    );
    let forms = module!(export!(foo, 1, block!(inst!(LocLoad(0u16.into())))));
    assert_eq!(context.parse_forms(source)?, forms);
    Ok(())
}

#[test]
fn test_ast_parsing_adv_ops() -> Result<(), Report> {
    let context = SyntaxTestContext::new();
    let source = source_file!(&context, "begin adv_push.1 adv_loadw end");
    let forms = module!(begin!(inst!(AdvPush(1u8.into())), inst!(AdvLoadW)));
    assert_eq!(context.parse_forms(source)?, forms);
    Ok(())
}

#[test]
fn test_ast_parsing_adv_injection() -> Result<(), Report> {
    use super::SystemEventNode::*;

    let context = SyntaxTestContext::new();
    let source = source_file!(&context, "begin adv.push_mapval adv.insert_mem end");
    let forms = module!(begin!(inst!(SysEvent(PushMapVal)), inst!(SysEvent(InsertMem))));
    assert_eq!(context.parse_forms(source)?, forms);
    Ok(())
}

#[test]
fn test_ast_parsing_bitwise_counters() -> Result<(), Report> {
    let context = SyntaxTestContext::new();
    let source = source_file!(&context, "begin u32clz u32ctz u32clo u32cto end");
    let forms = module!(begin!(inst!(U32Clz), inst!(U32Ctz), inst!(U32Clo), inst!(U32Cto)));

    assert_eq!(context.parse_forms(source)?, forms);
    Ok(())
}

#[test]
fn test_ast_parsing_ilog2() -> Result<(), Report> {
    let context = SyntaxTestContext::new();
    let source = source_file!(&context, "begin push.8 ilog2 end");
    let forms =
        module!(begin!(inst!(Push(Immediate::Value(Span::unknown(8u8.into())))), inst!(ILog2)));

    assert_eq!(context.parse_forms(source)?, forms);
    Ok(())
}

#[test]
fn test_ast_parsing_use() -> Result<(), Report> {
    let context = SyntaxTestContext::new();
    let source = source_file!(
        &context,
        r#"
    use miden::core::abc::foo
    begin
        exec.foo::bar
    end"#
    );
    let forms = module!(import!("miden::core::abc::foo"), begin!(exec!(foo::bar)));
    assert_eq!(context.parse_forms(source)?, forms);
    // TODO: Assert fully-resolved name is `std::abc::foo::bar`
    Ok(())
}

#[test]
fn test_ast_parsing_module_nested_if() -> Result<(), Report> {
    let context = SyntaxTestContext::new();
    let source = source_file!(
        &context,
        r#"
    proc foo
        push.1
        if.true
            push.0
            push.1
            if.true
                push.0
                sub
            else
                push.1
                sub
            end
        end
    end"#
    );

    let forms = module!(proc!(
        foo,
        0,
        block!(
            inst!(Push(Immediate::Value(Span::unknown(1u8.into())))),
            if_true!(
                block!(
                    inst!(Push(Immediate::Value(Span::unknown(0u8.into())))),
                    inst!(Push(Immediate::Value(Span::unknown(1u8.into())))),
                    if_true!(
                        block!(
                            inst!(Push(Immediate::Value(Span::unknown(0u8.into())))),
                            inst!(Sub)
                        ),
                        block!(
                            inst!(Push(Immediate::Value(Span::unknown(1u8.into())))),
                            inst!(Sub)
                        )
                    )
                ),
                block!(inst!(Nop))
            )
        )
    ));
    assert_eq!(context.parse_forms(source)?, forms);
    Ok(())
}

#[test]
fn test_ast_parsing_module_sequential_if() -> Result<(), Report> {
    let context = SyntaxTestContext::new();
    let source = source_file!(
        &context,
        r#"
    proc foo
        push.1
        if.true
            push.5
            push.1
        end
        if.true
            push.0
            sub
        else
            push.1
            sub
        end
    end"#
    );

    let forms = module!(proc!(
        foo,
        0,
        block!(
            inst!(Push(Immediate::Value(Span::unknown(1u8.into())))),
            if_true!(
                block!(
                    inst!(Push(Immediate::Value(Span::unknown(5u8.into())))),
                    inst!(Push(Immediate::Value(Span::unknown(1u8.into()))))
                ),
                block!(inst!(Nop))
            ),
            if_true!(
                block!(inst!(Push(Immediate::Value(Span::unknown(0u8.into())))), inst!(Sub)),
                block!(inst!(Push(Immediate::Value(Span::unknown(1u8.into())))), inst!(Sub))
            )
        )
    ));

    assert_eq!(context.parse_forms(source)?, forms);
    Ok(())
}

#[test]
fn test_ast_parsing_while_if_body() {
    let context = SyntaxTestContext::new();
    let source = source_file!(
        &context,
        "\
    begin
        push.1
        while.true
            mul
        end
        add
        if.true
            div
        end
        mul
    end
    "
    );

    let forms = module!(begin!(
        inst!(Push(Immediate::Value(Span::unknown(1u8.into())))),
        while_true!(block!(inst!(Mul))),
        inst!(Add),
        if_true!(block!(inst!(Div)), block!(inst!(Nop))),
        inst!(Mul)
    ));

    assert_forms!(context, source, forms);
}

#[test]
fn test_ast_parsing_attributes() -> Result<(), Report> {
    let context = SyntaxTestContext::new();

    let source = source_file!(
        &context,
        r#"
    # Simple marker attribute
    @inline
    @locals(1)
    proc foo
        loc_load.0
    end

    # List attribute
    @inline(always)
    @locals(2)
    proc bar
        padw
    end

    # Key value attributes of various kinds
    @numbers(decimal = 1, hex = 0xdeadbeef)
    @props(name = baz)
    @props(string = "not a valid quoted identifier")
    @locals(2)
    proc baz
        padw
    end

    begin
        exec.foo
        exec.bar
        exec.baz
    end"#
    );

    let inline = Attribute::Marker(id!(inline));
    let inline_always = Attribute::List(MetaList::new(id!(inline), [MetaExpr::Ident(id!(always))]));
    let numbers = Attribute::new(
        id!(numbers),
        [(id!(decimal), MetaExpr::from(1u8)), (id!(hex), MetaExpr::from(0xdeadbeefu32))],
    );
    let props = Attribute::new(
        id!(props),
        [
            (id!(name), MetaExpr::from(id!(baz))),
            (id!(string), MetaExpr::from("not a valid quoted identifier")),
        ],
    );

    let forms = module!(
        proc!([inline], foo, 1, block!(inst!(LocLoad(0u16.into())))),
        proc!([inline_always], bar, 2, block!(inst!(PadW))),
        proc!([numbers, props], baz, 2, block!(inst!(PadW))),
        begin!(exec!(foo), exec!(bar), exec!(baz))
    );
    assert_eq!(context.parse_forms(source)?, forms);

    Ok(())
}

// INVALID BODY TESTS
// ================================================================================================

#[test]
fn test_use_in_proc_body() {
    let context = SyntaxTestContext::default();
    let source = source_file!(
        &context,
        r#"
    @locals(1)
    pub proc foo
        loc_load.0
        use
    end"#
    );

    assert_parse_diagnostic_lines!(
        source,
        "invalid syntax",
        regex!(r#",-\[test[\d]+:5:9\]"#),
        "4 |         loc_load.0",
        "5 |         use",
        " :         ^|^",
        "  :          `-- found a use here",
        "6 |     end",
        "  `----",
        r#" help: expected primitive opcode (e.g. "add"), or "end", or control flow opcode (e.g. "if.true")"#
    );
}

#[test]
fn test_unterminated_proc() {
    let context = SyntaxTestContext::default();
    let source = source_file!(&context, "proc foo add mul begin push.1 end");

    assert_parse_diagnostic_lines!(
        source,
        "invalid syntax",
        regex!(r#",-\[test[\d]+:1:18\]"#),
        "1 | proc foo add mul begin push.1 end",
        "  :                  ^^|^^",
        "  :                    `-- found a begin here",
        "  `----",
        r#" help: expected ".", or primitive opcode (e.g. "add"), or "end", or control flow opcode (e.g. "if.true")"#
    );
}

#[test]
fn test_unterminated_if() {
    let context = SyntaxTestContext::default();
    let source = source_file!(&context, "proc foo add mul if.true add.2 begin push.1 end");

    assert_parse_diagnostic_lines!(
        source,
        "invalid syntax",
        regex!(r#",-\[test[\d]+:1:32\]"#),
        "1 | proc foo add mul if.true add.2 begin push.1 end",
        "  :                                ^^|^^",
        "  :                                  `-- found a begin here",
        "  `----",
        r#" help: expected primitive opcode (e.g. "add"), or "else", or "end", or control flow opcode (e.g. "if.true")"#
    );
}

#[test]
fn test_invalid_mapvaln_pad() {
    let context = SyntaxTestContext::default();
    let source = source_file!(&context, "begin adv.push_mapvaln.3 end");

    assert_parse_diagnostic_lines!(
        source,
        "invalid padding value for the `adv.push_mapvaln` instruction: 3",
        regex!(r#",-\[test[\d]+:1:24\]"#),
        "1 | begin adv.push_mapvaln.3 end",
        "  :                        ^",
        "  `----",
        " help: valid padding values are 0, 4, and 8"
    );
}

// DOCUMENTATION PARSING TESTS
// ================================================================================================

#[test]
fn test_ast_parsing_simple_docs() -> Result<(), Report> {
    let context = SyntaxTestContext::new();
    let source = source_file!(
        &context,
        r#"
    #! proc doc
    @locals(1)
    pub proc foo
        loc_load.0
    end"#
    );

    let forms = module!(doc!("proc doc\n"), export!(foo, 1, block!(inst!(LocLoad(0u16.into())))));
    assert_eq!(context.parse_forms(source)?, forms);
    Ok(())
}

#[test]
fn locals_overflow_rejected() {
    let context = SyntaxTestContext::new();
    let source = source_file!(
        &context,
        r#"
    @locals(65535)
    pub proc foo
        push.1
    end"#
    );

    assert_parse_diagnostic!(source, "number of locals exceeds the maximum of 65532");
}

#[test]
fn locals_max_valid_accepted() -> Result<(), Report> {
    let context = SyntaxTestContext::new();
    let source = source_file!(
        &context,
        r#"
    @locals(65532)
    pub proc foo
        push.1
    end"#
    );

    context.parse_forms(source)?;
    Ok(())
}

#[test]
fn test_ast_parsing_module_docs_valid() {
    let context = SyntaxTestContext::new();

    let source = source_file!(
        &context,
        "\
#! Test documentation for the whole module in parsing test. Lorem ipsum dolor sit amet,
#! consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
#!
#! This comment is intentionally longer than 256 characters, since we need to be sure that the size
#! of the comments is correctly parsed. There was a bug here earlier.


#! Test documentation for export procedure foo in parsing test. Lorem ipsum dolor sit amet,
#! consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
#! This comment is intentionally longer than 256 characters, since we need to be sure that the size
#! of the comments is correctly parsed. There was a bug here earlier.
@locals(1)
pub proc foo
    loc_load.0
end

#! Test documentation for internal procedure bar in parsing test. Lorem ipsum dolor sit amet,
#! consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
#! aliqua.
@locals(2)
proc bar
    padw
end

#! Test documentation for export procedure baz in parsing test. Lorem ipsum dolor sit amet,
#! consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
#! aliqua.
@locals(3)
pub proc baz
    padw
    push.0
end"
    );

    const MODULE_DOC: &str = "Test documentation for the whole module in parsing test. \
    Lorem ipsum dolor sit amet,\n\
    consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\
    \n\n\
    This comment is intentionally longer than 256 characters, since we need to be sure that the size\n\
    of the comments is correctly parsed. There was a bug here earlier.\n";

    const FOO_DOC: &str = "Test documentation for export procedure foo in parsing test. \
    Lorem ipsum dolor sit amet,\n\
    consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n\
    This comment is intentionally longer than 256 characters, since we need to be sure that the size\n\
    of the comments is correctly parsed. There was a bug here earlier.\n";

    const BAR_DOC: &str = "Test documentation for internal procedure bar in parsing test. Lorem ipsum dolor sit amet,\n\
    consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna\n\
    aliqua.\n";

    const BAZ_DOC: &str = "Test documentation for export procedure baz in parsing test. Lorem ipsum dolor sit amet,\n\
    consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna\n\
    aliqua.\n";

    let expected_forms = module!(
        moduledoc!(MODULE_DOC),
        doc!(FOO_DOC),
        export!(foo, 1, block!(inst!(LocLoad(0u16.into())))),
        doc!(BAR_DOC),
        proc!(bar, 2, block!(inst!(PadW))),
        doc!(BAZ_DOC),
        export!(
            baz,
            3,
            block!(inst!(PadW), inst!(Push(Immediate::Value(Span::unknown(0u8.into())))))
        )
    );

    let actual_forms = context.parse_forms(source.clone()).unwrap();
    assert_eq!(actual_forms, expected_forms);

    let module = context.parse_module(source).unwrap();
    assert_eq!(module.docs(), Some(Span::unknown(MODULE_DOC)));
    let baz = "baz".parse().unwrap();
    let baz_idx = module.index_of_name(&baz).expect("could not find baz");
    let baz_docs = module.get(baz_idx).unwrap().docs();
    assert_eq!(baz_docs, Some(BAZ_DOC));
}

#[test]
fn test_ast_parsing_module_docs_fail() {
    let context = SyntaxTestContext::new().with_warnings_as_errors(true);
    let source = source_file!(
        &context,
        "\
    #! module doc

    #! proc doc
    @locals(1)
    pub proc foo
        loc_load.0
    end

    #! malformed doc
    "
    );
    assert_module_diagnostic_lines!(
        context,
        source,
        "syntax error",
        "help: see emitted diagnostics for details",
        "Warning:   ! unused docstring",
        regex!(r#",-\[test[\d]+:9:5\]"#),
        " 8 |",
        " 9 |     #! malformed doc",
        "   :     ^^^^^^^^^^^^^^^^^",
        "10 |",
        "   `----",
        "help: this docstring is immediately followed by at least one empty line, then another docstring,if you intended these to be a single docstring, you should remove the empty lines"
    );

    let source = source_file!(
        &context,
        "\
    #! proc doc
    @locals(1)
    pub proc foo
        loc_load.0
    end

    #! malformed doc
    "
    );
    assert_module_diagnostic_lines!(
        context,
        source,
        "syntax error",
        "help: see emitted diagnostics for details",
        "Warning:   ! unused docstring",
        regex!(r#",-\[test[\d]+:7:5\]"#),
        "6 |",
        "7 |     #! malformed doc",
        "  :     ^^^^^^^^^^^^^^^^^",
        "8 |",
        "  `----",
        "help: this docstring is immediately followed by at least one empty line, then another docstring,if you intended these to be a single docstring, you should remove the empty lines"
    );

    let source = source_file!(
        &context,
        "\
    #! module doc

    #! malformed doc
    "
    );
    assert_module_diagnostic_lines!(
        context,
        source,
        "syntax error",
        "help: see emitted diagnostics for details",
        "Warning:   ! unused docstring",
        regex!(r#",-\[test[\d]+:3:5\]"#),
        "2 |",
        "3 |     #! malformed doc",
        "  :     ^^^^^^^^^^^^^^^^^",
        "4 |",
        "  `----",
        "help: this docstring is immediately followed by at least one empty line, then another docstring,if you intended these to be a single docstring, you should remove the empty lines"
    );

    let source = source_file!(
        &context,
        "\
    @locals(1)
    pub proc foo
        loc_load.0
    end

    #! malformed doc
    "
    );
    assert_module_diagnostic_lines!(
        context,
        source,
        "syntax error",
        "help: see emitted diagnostics for details",
        "Warning:   ! unused docstring",
        regex!(r#",-\[test[\d]+:6:5\]"#),
        "5 |",
        "6 |     #! malformed doc",
        "  :     ^^^^^^^^^^^^^^^^^",
        "7 |",
        "  `----",
        "help: this docstring is immediately followed by at least one empty line, then another docstring,if you intended these to be a single docstring, you should remove the empty lines"
    );

    let source = source_file!(
        &context,
        "\
    #! module doc

    @locals(1)
    pub proc foo
        loc_load.0
    end

    #! malformed doc
    "
    );
    assert_module_diagnostic_lines!(
        context,
        source,
        "syntax error",
        "help: see emitted diagnostics for details",
        "Warning:   ! unused docstring",
        regex!(r#",-\[test[\d]+:8:5\]"#),
        "7 |",
        "8 |     #! malformed doc",
        "  :     ^^^^^^^^^^^^^^^^^",
        "9 |",
        "  `----",
        "help: this docstring is immediately followed by at least one empty line, then another docstring,if you intended these to be a single docstring, you should remove the empty lines"
    );

    let source = source_file!(
        &context,
        "\
    #! proc doc
    @locals(1)
    pub proc foo
        #! malformed doc
        loc_load.0
    end
    "
    );
    assert_module_diagnostic_lines!(
        context,
        source,
        "invalid syntax",
        regex!(r#",-\[test[\d]+:4:9\]"#),
        "3 |     pub proc foo",
        "4 |         #! malformed doc",
        "  :         ^^^^^^^^|^^^^^^^^",
        "  :                 `-- found a doc comment here",
        "5 |         loc_load.0",
        "6 |     end",
        "  `----",
        r#" help: expected "(", or primitive opcode (e.g. "add"), or control flow opcode (e.g. "if.true")"#
    );
}

// BEGIN
// ================================================================================================

#[test]
fn assert_parsing_line_unmatched_begin() {
    let context = SyntaxTestContext::default();
    let source = source_file!(
        &context,
        "\
        begin
          push.1.2

        add
        mul"
    );
    assert_parse_diagnostic_lines!(
        source,
        "unexpected end of file",
        regex!(r#",-\[test[\d]+:5:12\]"#),
        "4 |         add",
        "5 |         mul",
        "  `----",
        r#"help: expected ".", or primitive opcode (e.g. "add"), or "end", or control flow opcode (e.g. "if.true")"#
    );
}

#[test]
fn assert_parsing_line_extra_param() {
    let context = SyntaxTestContext::default();
    let source = source_file!(
        &context,
        "\
        begin
          add.1.2
        end"
    );
    assert_parse_diagnostic_lines!(
        source,
        "invalid syntax",
        regex!(r#",-\[test[\d]+:2:16\]"#),
        "1 | begin",
        "2 |           add.1.2",
        "  :                |",
        "  :                `-- found a . here",
        "3 |         end",
        "  `----",
        r#" help: expected primitive opcode (e.g. "add"), or "end", or control flow opcode (e.g. "if.true")"#
    );
}

#[test]
fn assert_parsing_line_invalid_op() {
    let context = SyntaxTestContext::default();
    let source = source_file!(
        &context,
        "\
    begin
        repeat.3
            push.1
            push.0.1
        end

        # some comments

        if.true
            and
            loc_store.0
        else
            padw
        end

        # more comments
        # to test if line is correct

        while.true
            push.5.7
            u32wrapping_add
            loc_store.4
            push.0
        end

        repeat.3
            push.2
            u32widening_mulx
        end

    end"
    );
    assert_parse_diagnostic_lines!(
        source,
        "invalid syntax",
        regex!(r#",-\[test[\d]+:28:13\]"#),
        "27 |             push.2",
        "28 |             u32widening_mulx",
        "   :             ^^^^^^^^|^^^^^^^",
        "   :                     `-- found a identifier here",
        "29 |         end",
        "   `----",
        r#" help: expected ".", or primitive opcode (e.g. "add"), or "end", or control flow opcode (e.g. "if.true")"#
    );
}

#[test]
fn assert_parsing_line_unexpected_token() {
    let context = SyntaxTestContext::default();
    let source = source_file!(
        &context,
        "\
    proc foo
      add
    end

    mul"
    );
    assert_parse_diagnostic_lines!(
        source,
        "invalid syntax",
        regex!(r#",-\[test[\d]+:5:5\]"#),
        "4 |",
        "5 |     mul",
        "  :     ^|^",
        "  :      `-- found a mul here",
        "  `----",
        r#" help: expected "@", or "adv_map", or "begin", or "const", or "enum", or "proc", or "pub", or "type", or "use", or end of file, or doc comment"#
    );
}

/// This test evaluates that we get the expected formatted Miden Assembly output when parsing some
/// Miden Assembly source code into the AST, and then formatting the AST.
///
/// NOTE: Due to current limitations of the parser, round-tripping is currently somewhat lossy:
///
/// - Line comments (i.e. not docstrings) are not preserved, and so do not end up in the output
/// - The original choice to place a sequence of instructions on the same line or multiple lines is
///   not preserved in the AST, so the formatter always places them on individual lines.
/// - References to constant values by name are replaced with their value during semantic analysis,
///   so no named constants appear in the formatted output.
/// - Constant declarations are not preserved by the parser, and so are not shown in the output
#[test]
fn test_roundtrip_formatting() {
    let source = "\
#! module doc
#!
#! with spaces

#! constant doc
#!
#! with spaces
const DEFAULT_CONST = 100

#! Perform `a + b`, `n` times
#!
#! with spaces
proc add_n_times # [n, b, a]
    dup.0
    push.0
    u32gt
    if.true
        push.0.1
        while.true  # [total, n, b, a]
            dup.3 dup.3
            u32wrapping_add3 # [total', n, b, a]
            swap.1
            push.1
            u32overflowing_sub  # [overflowed, n - 1, total', b, a]
            swap.1 movdn.3      # [overflowed, total', n', b, a]
            push.0              # [0, overflowed, total, n', total', b, a]
            dup.1               # [overflowed, 0, overflowed, total', n', b, a]
            cdrop               # [continue, total', n', b, a]
        end
        movdn.3
        drop drop drop
    else
        u32wrapping_add
    end
end

begin
    push.1.1.DEFAULT_CONST
    exec.add_n_times
    push.20
    assert_eq

    trace.DEFAULT_CONST
end
";

    let context = SyntaxTestContext::default();
    let source = source_file!(&context, source);

    let module =
        Module::parse(Path::exec_path(), ModuleKind::Executable, source, context.source_manager())
            .unwrap_or_else(|err| panic!("{err}"));

    let formatted = module.to_string();
    let expected = "\
#! module doc
#!
#! with spaces

#! constant doc
#!
#! with spaces
const DEFAULT_CONST = 100

#! Perform `a + b`, `n` times
#!
#! with spaces
proc add_n_times
    dup.0
    push.0
    u32gt
    if.true
        push.0
        push.1
        while.true
            dup.3
            dup.3
            u32wrapping_add3
            swap.1
            push.1
            u32overflowing_sub
            swap.1
            movdn.3
            push.0
            dup.1
            cdrop
        end
        movdn.3
        drop
        drop
        drop
    else
        u32wrapping_add
    end
end

begin
    push.1
    push.1
    push.100
    exec.add_n_times
    push.20
    assert_eq
    trace.100
end
";

    assert_eq!(&formatted, expected);
}

#[test]
fn test_words_roundtrip_formatting() {
    let source = "\
const A = 0x0200000000000000030000000000000004000000000000000500000000000000
const B = [2,3,4,5]
begin
    push.0x0200000000000000030000000000000004000000000000000500000000000000
    push.A.6
    push.B.6
    push.2.3.4.5
    push.A.B
end
";

    let context = SyntaxTestContext::default();
    let source = source_file!(&context, source);

    let module =
        Module::parse(Path::exec_path(), ModuleKind::Executable, source, context.source_manager())
            .unwrap();

    let formatted = module.to_string();
    let expected = "\
const A = [2,3,4,5]

const B = [2,3,4,5]

begin
    push.[2,3,4,5]
    push.[2,3,4,5]
    push.6
    push.[2,3,4,5]
    push.6
    push.2
    push.3
    push.4
    push.5
    push.[2,3,4,5]
    push.[2,3,4,5]
end
";

    assert_eq!(&formatted, expected);
}

#[test]
fn cannot_mem_store_word() {
    let context = SyntaxTestContext::default();
    let source = source_file!(
        &context,
        r#"
const A = [2,3,4,5]
begin
    mem_store.A
end"#
    );

    // Instead of the usual macro that does only parsing we need to use this
    // parse function that also performs the semantic analysis to realize that
    // the constant is of the wrong type.
    let error =
        Module::parse(Path::exec_path(), ModuleKind::Executable, source, context.source_manager())
            .expect_err("expected diagnostic to be raised, but parsing succeeded");

    assert_diagnostic_lines!(
        error,
        "syntax error",
        "help: see emitted diagnostics for details",
        "invalid constant",
        regex!(r#",-\[test[\d]+:4:15\]"#),
        "3 | begin",
        "4 |     mem_store.A",
        "  :               |",
        "  :               `-- expected u32",
        "5 | end",
        "  `----",
        r#" help: this constant does not resolve to a value of the right type"#
    );
}

// TYPES
// ================================================================================================

#[test]
fn test_type_declarations() -> Result<(), Report> {
    let context = SyntaxTestContext::new();
    let source = source_file!(
        &context,
        r#"
type t = felt
type Int8 = u8
type Int64 = struct { hi: u32, lo: u32 }
type Int128 = struct { hi: Int64, lo: Int64 }
type Hash = [u8; 32]
"#
    );

    let forms = module!(
        type_alias!(t, Type::Felt),
        type_alias!(Int8, Type::U8),
        type_alias!(Int64, struct_ty!(Int64, hi: Type::U32, lo: Type::U32)),
        type_alias!(Int128, struct_ty!(Int128, hi: type_ref!(Int64), lo: type_ref!(Int64))),
        type_alias!(Hash, array_ty!(Type::U8, 32))
    );
    assert_eq!(context.parse_forms(source)?, forms);
    Ok(())
}

#[test]
fn test_enum_declarations() -> Result<(), Report> {
    let context = SyntaxTestContext::new();
    let source = source_file!(
        &context,
        r#"
enum Tag : u8 {
    A,
    B = 2,
    C = B * 2,
    D,
}
"#
    );

    let forms = module!(enum_ty!(
        Tag,
        Type::U8,
        variant!(A, const_int!(0u8)),
        variant!(B, const_int!(2u8)),
        variant!(C, const_mul!(const_ref!(B), const_int!(2u8))),
        variant!(D, const_add!(const_ref!(C), const_int!(1u8)))
    ));
    assert_eq!(context.parse_forms(source)?, forms);
    Ok(())
}

#[test]
fn test_type_signatures() -> Result<(), Report> {
    let context = SyntaxTestContext::new();
    let source = source_file!(
        &context,
        r#"
use miden::core::math::u64

type Int64 = struct { hi: u32, lo: u32 }

pub proc mul(a: Int64, b: Int64) -> Int64
    exec.u64::wrapping_mul
end

enum Bool : i1 {
    FALSE,
    TRUE,
}

pub proc is_number(a: Int64) -> Bool
    push.TRUE
end
"#
    );

    let forms = module!(
        import!("miden::core::math::u64"),
        type_alias!(Int64, struct_ty!(Int64, hi: Type::U32, lo: Type::U32)),
        typed_export!(
            mul,
            0,
            function_ty!(type_ref!(Int64), type_ref!(Int64) => type_ref!(Int64)),
            block!(exec!(u64::wrapping_mul))
        ),
        enum_ty!(
            Bool,
            Type::I1,
            variant!(FALSE, const_int!(0u8)),
            variant!(TRUE, const_add!(const_ref!(FALSE), const_int!(1u8)))
        ),
        typed_export!(
            is_number,
            0,
            function_ty!(type_ref!(Int64) => type_ref!(Bool)),
            block!(inst!(Push(Immediate::Constant(id!(TRUE)))))
        )
    );
    assert_eq!(context.parse_forms(source)?, forms);
    Ok(())
}