sway_error/
error.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
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
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
use crate::convert_parse_tree_error::ConvertParseTreeError;
use crate::diagnostic::{Code, Diagnostic, Hint, Issue, Reason, ToDiagnostic};
use crate::formatting::*;
use crate::lex_error::LexError;
use crate::parser_error::{ParseError, ParseErrorKind};
use crate::type_error::TypeError;

use core::fmt;
use std::fmt::Formatter;
use sway_types::constants::STORAGE_PURITY_ATTRIBUTE_NAME;
use sway_types::style::to_snake_case;
use sway_types::{BaseIdent, Ident, IdentUnique, SourceEngine, Span, Spanned};
use thiserror::Error;

use self::ShadowingSource::*;
use self::StructFieldUsageContext::*;

#[derive(Error, Debug, Clone, PartialEq, Eq, Hash)]
pub enum InterfaceName {
    Abi(Ident),
    Trait(Ident),
}

impl fmt::Display for InterfaceName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            InterfaceName::Abi(name) => write!(f, "ABI \"{name}\""),
            InterfaceName::Trait(name) => write!(f, "trait \"{name}\""),
        }
    }
}

// TODO: Since moving to using Idents instead of strings, there are a lot of redundant spans in
//       this type. When replacing Strings + Spans with Idents, be aware of the rule explained below.

// When defining error structures that display identifiers, we prefer passing Idents over Strings.
// The error span can come from that same Ident or can be a different span.
// We handle those two cases in the following way:
//   - If the error span equals Ident's span, we use IdentUnique and never the plain Ident.
//   - If the error span is different then Ident's span, we pass Ident and Span as two separate fields.
//
// The reason for this rule is clearly communicating the difference of the two cases in every error,
// as well as avoiding issues with the error message deduplication explained below.
//
// Deduplication of error messages might remove errors that are actually not duplicates because
// although they point to the same Ident (in terms of the identifier's name), the span can be different.
// Deduplication works on hashes and Ident's hash contains only the name and not the span.
// That's why we always use IdentUnique whenever we extract the span from the provided Ident.
// Using IdentUnique also clearly communicates that we are extracting the span from the
// provided identifier.
#[derive(Error, Debug, Clone, PartialEq, Eq, Hash)]
pub enum CompileError {
    #[error(
        "There was an error while evaluating the evaluation order for the module dependency graph."
    )]
    ModuleDepGraphEvaluationError {},
    #[error("A cyclic reference was found between the modules: {}.",
        modules.iter().map(|ident| ident.as_str().to_string())
    .collect::<Vec<_>>()
    .join(", "))]
    ModuleDepGraphCyclicReference { modules: Vec<BaseIdent> },

    #[error("Variable \"{var_name}\" does not exist in this scope.")]
    UnknownVariable { var_name: Ident, span: Span },
    #[error("Identifier \"{name}\" was used as a variable, but it is actually a {what_it_is}.")]
    NotAVariable {
        name: Ident,
        what_it_is: &'static str,
        span: Span,
    },
    #[error("{feature} is currently not implemented.")]
    Unimplemented {
        /// The description of the unimplemented feature,
        /// formulated in a way that fits into common ending
        /// "is currently not implemented."
        /// E.g., "Using something".
        feature: String,
        /// Help lines. Empty if there is no additional help.
        /// To get an empty line between the help lines,
        /// insert a [String] containing only a space: `" ".to_string()`.
        help: Vec<String>,
        span: Span,
    },
    #[error("{0}")]
    TypeError(TypeError),
    #[error("Error parsing input: {err:?}")]
    ParseError { span: Span, err: String },
    #[error(
        "Internal compiler error: {0}\nPlease file an issue on the repository and include the \
         code that triggered this error."
    )]
    Internal(&'static str, Span),
    #[error(
        "Internal compiler error: {0}\nPlease file an issue on the repository and include the \
         code that triggered this error."
    )]
    InternalOwned(String, Span),
    #[error(
        "Predicate declaration contains no main function. Predicates require a main function."
    )]
    NoPredicateMainFunction(Span),
    #[error("A predicate's main function must return a boolean.")]
    PredicateMainDoesNotReturnBool(Span),
    #[error("Script declaration contains no main function. Scripts require a main function.")]
    NoScriptMainFunction(Span),
    #[error("Fallback function already defined in scope.")]
    MultipleDefinitionsOfFallbackFunction { name: Ident, span: Span },
    #[error("Function \"{name}\" was already defined in scope.")]
    MultipleDefinitionsOfFunction { name: Ident, span: Span },
    #[error("Name \"{name}\" is defined multiple times.")]
    MultipleDefinitionsOfName { name: Ident, span: Span },
    #[error("Constant \"{name}\" was already defined in scope.")]
    MultipleDefinitionsOfConstant { name: Ident, span: Span },
    #[error("Type \"{name}\" was already defined in scope.")]
    MultipleDefinitionsOfType { name: Ident, span: Span },
    #[error("Variable \"{}\" is already defined in match arm.", first_definition.as_str())]
    MultipleDefinitionsOfMatchArmVariable {
        match_value: Span,
        match_type: String,
        first_definition: Span,
        first_definition_is_struct_field: bool,
        duplicate: Span,
        duplicate_is_struct_field: bool,
    },
    #[error(
        "Assignment to an immutable variable. Variable \"{decl_name} is not declared as mutable."
    )]
    AssignmentToNonMutableVariable {
        /// Variable name pointing to the name in the variable declaration.
        decl_name: Ident,
        /// The complete left-hand side of the assignment.
        lhs_span: Span,
    },
    #[error(
        "Assignment to a {}. {} cannot be assigned to.",
        if *is_configurable {
            "configurable"
        } else {
            "constant"
        },
        if *is_configurable {
            "Configurables"
        } else {
            "Constants"
        }
    )]
    AssignmentToConstantOrConfigurable {
        /// Constant or configurable name pointing to the name in the constant declaration.
        decl_name: Ident,
        is_configurable: bool,
        /// The complete left-hand side of the assignment.
        lhs_span: Span,
    },
    #[error(
        "This assignment target cannot be assigned to, because {} is {}{decl_friendly_type_name} and not a mutable variable.",
        if let Some(decl_name) = decl_name {
            format!("\"{decl_name}\"")
        } else {
            "this".to_string()
        },
        a_or_an(decl_friendly_type_name)
    )]
    DeclAssignmentTargetCannotBeAssignedTo {
        /// Name of the declared variant, pointing to the name in the declaration.
        decl_name: Option<Ident>,
        /// Friendly name of the type of the declaration. E.g., "function", or "struct".
        decl_friendly_type_name: &'static str,
        /// The complete left-hand side of the assignment.
        lhs_span: Span,
    },
    #[error("This reference is not a reference to a mutable value (`&mut`).")]
    AssignmentViaNonMutableReference {
        /// Name of the reference, if the left-hand side of the assignment is a reference variable,
        /// pointing to the name in the reference variable declaration.
        ///
        /// `None` if the assignment LHS is an arbitrary expression and not a variable.
        decl_reference_name: Option<Ident>,
        /// [Span] of the right-hand side of the reference variable definition,
        /// if the left-hand side of the assignment is a reference variable.
        decl_reference_rhs: Option<Span>,
        /// The type of the reference, if the left-hand side of the assignment is a reference variable,
        /// expected to start with `&`.
        decl_reference_type: String,
        span: Span,
    },
    #[error(
        "Cannot call method \"{method_name}\" on variable \"{variable_name}\" because \
            \"{variable_name}\" is not declared as mutable."
    )]
    MethodRequiresMutableSelf {
        method_name: Ident,
        variable_name: Ident,
        span: Span,
    },
    #[error(
        "This parameter was declared as mutable, which is not supported yet, did you mean to use ref mut?"
    )]
    MutableParameterNotSupported { param_name: Ident, span: Span },
    #[error("Cannot pass immutable argument to mutable parameter.")]
    ImmutableArgumentToMutableParameter { span: Span },
    #[error("ref mut or mut parameter is not allowed for contract ABI function.")]
    RefMutableNotAllowedInContractAbi { param_name: Ident, span: Span },
    #[error("Reference to a mutable value cannot reference a constant.")]
    RefMutCannotReferenceConstant {
        /// Constant, as accessed in code. E.g.:
        ///  - `MY_CONST`
        ///  - `LIB_CONST_ALIAS`
        ///  - `::lib::module::SOME_CONST`
        constant: String,
        span: Span,
    },
    #[error("Reference to a mutable value cannot reference an immutable variable.")]
    RefMutCannotReferenceImmutableVariable {
        /// Variable name pointing to the name in the variable declaration.
        decl_name: Ident,
        span: Span,
    },
    #[error(
        "Cannot call associated function \"{fn_name}\" as a method. Use associated function \
        syntax instead."
    )]
    AssociatedFunctionCalledAsMethod { fn_name: Ident, span: Span },
    #[error(
        "Generic type \"{name}\" is not in scope. Perhaps you meant to specify type parameters in \
         the function signature? For example: \n`fn \
         {fn_name}<{comma_separated_generic_params}>({args}) -> ... `"
    )]
    TypeParameterNotInTypeScope {
        name: Ident,
        span: Span,
        comma_separated_generic_params: String,
        fn_name: Ident,
        args: String,
    },
    #[error(
        "expected: {expected} \n\
         found:    {given} \n\
         help:     The definition of this {decl_type} must \
         match the one in the {interface_name} declaration."
    )]
    MismatchedTypeInInterfaceSurface {
        interface_name: InterfaceName,
        span: Span,
        decl_type: String,
        given: String,
        expected: String,
    },
    #[error("Trait \"{name}\" cannot be found in the current scope.")]
    UnknownTrait { span: Span, name: Ident },
    #[error("Function \"{name}\" is not a part of {interface_name}'s interface surface.")]
    FunctionNotAPartOfInterfaceSurface {
        name: Ident,
        interface_name: InterfaceName,
        span: Span,
    },
    #[error("Constant \"{name}\" is not a part of {interface_name}'s interface surface.")]
    ConstantNotAPartOfInterfaceSurface {
        name: Ident,
        interface_name: InterfaceName,
        span: Span,
    },
    #[error("Type \"{name}\" is not a part of {interface_name}'s interface surface.")]
    TypeNotAPartOfInterfaceSurface {
        name: Ident,
        interface_name: InterfaceName,
        span: Span,
    },
    #[error("Constants are missing from this trait implementation: {}",
        missing_constants.iter().map(|ident| ident.as_str().to_string())
        .collect::<Vec<_>>()
        .join("\n"))]
    MissingInterfaceSurfaceConstants {
        missing_constants: Vec<BaseIdent>,
        span: Span,
    },
    #[error("Associated types are missing from this trait implementation: {}",
        missing_types.iter().map(|ident| ident.as_str().to_string())
        .collect::<Vec<_>>()
        .join("\n"))]
    MissingInterfaceSurfaceTypes {
        missing_types: Vec<BaseIdent>,
        span: Span,
    },
    #[error("Functions are missing from this trait implementation: {}",
        missing_functions.iter().map(|ident| ident.as_str().to_string())
        .collect::<Vec<_>>()
        .join("\n"))]
    MissingInterfaceSurfaceMethods {
        missing_functions: Vec<BaseIdent>,
        span: Span,
    },
    #[error("Expected {} type {} for \"{name}\", but instead found {}.", expected, if *expected == 1usize { "argument" } else { "arguments" }, given)]
    IncorrectNumberOfTypeArguments {
        name: Ident,
        given: usize,
        expected: usize,
        span: Span,
    },
    #[error("\"{name}\" does not take type arguments.")]
    DoesNotTakeTypeArguments { name: Ident, span: Span },
    #[error("\"{name}\" does not take type arguments as prefix.")]
    DoesNotTakeTypeArgumentsAsPrefix { name: Ident, span: Span },
    #[error("Type arguments are not allowed for this type.")]
    TypeArgumentsNotAllowed { span: Span },
    #[error("\"{name}\" needs type arguments.")]
    NeedsTypeArguments { name: Ident, span: Span },
    #[error(
        "Enum with name \"{name}\" could not be found in this scope. Perhaps you need to import \
         it?"
    )]
    EnumNotFound { name: Ident, span: Span },
    /// This error is used only for error recovery and is not emitted as a compiler
    /// error to the final compilation output. The compiler emits the cumulative error
    /// [CompileError::StructInstantiationMissingFields] given below, and that one also
    /// only if the struct can actually be instantiated.
    #[error("Instantiation of the struct \"{struct_name}\" is missing field \"{field_name}\".")]
    StructInstantiationMissingFieldForErrorRecovery {
        field_name: Ident,
        /// Original, non-aliased struct name.
        struct_name: Ident,
        span: Span,
    },
    #[error("Instantiation of the struct \"{struct_name}\" is missing {} {}.",
        if field_names.len() == 1 { "field" } else { "fields" },
        field_names.iter().map(|name| format!("\"{name}\"")).collect::<Vec::<_>>().join(", "))]
    StructInstantiationMissingFields {
        field_names: Vec<Ident>,
        /// Original, non-aliased struct name.
        struct_name: Ident,
        span: Span,
        struct_decl_span: Span,
        total_number_of_fields: usize,
    },
    #[error("Struct \"{struct_name}\" cannot be instantiated here because it has private fields.")]
    StructCannotBeInstantiated {
        /// Original, non-aliased struct name.
        struct_name: Ident,
        span: Span,
        struct_decl_span: Span,
        private_fields: Vec<Ident>,
        /// All available public constructors if `is_in_storage_declaration` is false,
        /// or only the public constructors that potentially evaluate to a constant
        /// if `is_in_storage_declaration` is true.
        constructors: Vec<String>,
        /// True if the struct has only private fields.
        all_fields_are_private: bool,
        is_in_storage_declaration: bool,
        struct_can_be_changed: bool,
    },
    #[error("Field \"{field_name}\" of the struct \"{struct_name}\" is private.")]
    StructFieldIsPrivate {
        field_name: IdentUnique,
        /// Original, non-aliased struct name.
        struct_name: Ident,
        field_decl_span: Span,
        struct_can_be_changed: bool,
        usage_context: StructFieldUsageContext,
    },
    #[error("Field \"{field_name}\" does not exist in struct \"{struct_name}\".")]
    StructFieldDoesNotExist {
        field_name: IdentUnique,
        /// Only public fields if `is_public_struct_access` is true.
        available_fields: Vec<Ident>,
        is_public_struct_access: bool,
        /// Original, non-aliased struct name.
        struct_name: Ident,
        struct_decl_span: Span,
        struct_is_empty: bool,
        usage_context: StructFieldUsageContext,
    },
    #[error("Field \"{field_name}\" has multiple definitions.")]
    StructFieldDuplicated { field_name: Ident, duplicate: Ident },
    #[error("No method \"{method}\" found for type \"{type_name}\".{}", 
        if matching_method_strings.is_empty() {
            "".to_string()
        } else {
            format!("  \nMatching method{}:\n{}", if matching_method_strings.len()> 1 {"s"} else {""},
            matching_method_strings.iter().map(|m| format!("    {m}")).collect::<Vec<_>>().join("\n"))
        }
    )]
    MethodNotFound {
        method: String,
        type_name: String,
        matching_method_strings: Vec<String>,
        span: Span,
    },
    #[error("Module \"{name}\" could not be found.")]
    ModuleNotFound { span: Span, name: String },
    #[error("This expression has type \"{actually}\", which is not a struct. Fields can only be accessed on structs.")]
    FieldAccessOnNonStruct {
        actually: String,
        /// Name of the storage variable, if the field access
        /// happens within the access to a storage variable.
        storage_variable: Option<String>,
        /// Name of the field that is tried to be accessed.
        field_name: IdentUnique,
        span: Span,
    },
    #[error("This expression has type \"{actually}\", which is not a tuple. Elements can only be accessed on tuples.")]
    TupleElementAccessOnNonTuple {
        actually: String,
        span: Span,
        index: usize,
        index_span: Span,
    },
    #[error("This expression has type \"{actually}\", which is not an indexable type.")]
    NotIndexable { actually: String, span: Span },
    #[error("\"{name}\" is a {actually}, not an enum.")]
    NotAnEnum {
        name: String,
        span: Span,
        actually: String,
    },
    #[error("This is a {actually}, not a struct.")]
    NotAStruct { span: Span, actually: String },
    #[error("This is a {actually}, not an enum.")]
    DeclIsNotAnEnum { actually: String, span: Span },
    #[error("This is a {actually}, not a struct.")]
    DeclIsNotAStruct { actually: String, span: Span },
    #[error("This is a {actually}, not a function.")]
    DeclIsNotAFunction { actually: String, span: Span },
    #[error("This is a {actually}, not a variable.")]
    DeclIsNotAVariable { actually: String, span: Span },
    #[error("This is a {actually}, not an ABI.")]
    DeclIsNotAnAbi { actually: String, span: Span },
    #[error("This is a {actually}, not a trait.")]
    DeclIsNotATrait { actually: String, span: Span },
    #[error("This is a {actually}, not an impl block.")]
    DeclIsNotAnImplTrait { actually: String, span: Span },
    #[error("This is a {actually}, not a trait function.")]
    DeclIsNotATraitFn { actually: String, span: Span },
    #[error("This is a {actually}, not storage.")]
    DeclIsNotStorage { actually: String, span: Span },
    #[error("This is a {actually}, not a constant")]
    DeclIsNotAConstant { actually: String, span: Span },
    #[error("This is a {actually}, not a type alias")]
    DeclIsNotATypeAlias { actually: String, span: Span },
    #[error("Could not find symbol \"{name}\" in this scope.")]
    SymbolNotFound { name: Ident, span: Span },
    #[error("Found multiple bindings for \"{name}\" in this scope.")]
    SymbolWithMultipleBindings {
        name: Ident,
        paths: Vec<String>,
        span: Span,
    },
    #[error("Symbol \"{name}\" is private.")]
    ImportPrivateSymbol { name: Ident, span: Span },
    #[error("Module \"{name}\" is private.")]
    ImportPrivateModule { name: Ident, span: Span },
    #[error(
        "Because this if expression's value is used, an \"else\" branch is required and it must \
         return type \"{r#type}\""
    )]
    NoElseBranch { span: Span, r#type: String },
    #[error(
        "Symbol \"{name}\" does not refer to a type, it refers to a {actually_is}. It cannot be \
         used in this position."
    )]
    NotAType {
        span: Span,
        name: String,
        actually_is: &'static str,
    },
    #[error(
        "This enum variant requires an instantiation expression. Try initializing it with \
         arguments in parentheses."
    )]
    MissingEnumInstantiator { span: Span },
    #[error(
        "This path must return a value of type \"{ty}\" from function \"{function_name}\", but it \
         does not."
    )]
    PathDoesNotReturn {
        span: Span,
        ty: String,
        function_name: Ident,
    },
    #[error(
        "Expected Module level doc comment. All other attributes are unsupported at this level."
    )]
    ExpectedModuleDocComment { span: Span },
    #[error(
        "This register was not initialized in the initialization section of the ASM expression. \
         Initialized registers are: {initialized_registers}"
    )]
    UnknownRegister {
        span: Span,
        initialized_registers: String,
    },
    #[error("This opcode takes an immediate value but none was provided.")]
    MissingImmediate { span: Span },
    #[error("This immediate value is invalid.")]
    InvalidImmediateValue { span: Span },
    #[error("Variant \"{variant_name}\" does not exist on enum \"{enum_name}\"")]
    UnknownEnumVariant {
        enum_name: Ident,
        variant_name: Ident,
        span: Span,
    },
    #[error("Unknown opcode: \"{op_name}\".")]
    UnrecognizedOp { op_name: Ident, span: Span },
    #[error("Cannot infer type for type parameter \"{ty}\". Insufficient type information provided. Try annotating its type.")]
    UnableToInferGeneric { ty: String, span: Span },
    #[error("The generic type parameter \"{ty}\" is unconstrained.")]
    UnconstrainedGenericParameter { ty: String, span: Span },
    #[error("Trait \"{trait_name}\" is not implemented for type \"{ty}\".")]
    TraitConstraintNotSatisfied {
        type_id: usize, // Used to filter errors in method application type check.
        ty: String,
        trait_name: String,
        span: Span,
    },
    #[error(
        "Expects trait constraint \"{param}: {trait_name}\" which is missing from type parameter \"{param}\"."
    )]
    TraitConstraintMissing {
        param: String,
        trait_name: String,
        span: Span,
    },
    #[error("The value \"{val}\" is too large to fit in this 6-bit immediate spot.")]
    Immediate06TooLarge { val: u64, span: Span },
    #[error("The value \"{val}\" is too large to fit in this 12-bit immediate spot.")]
    Immediate12TooLarge { val: u64, span: Span },
    #[error("The value \"{val}\" is too large to fit in this 18-bit immediate spot.")]
    Immediate18TooLarge { val: u64, span: Span },
    #[error("The value \"{val}\" is too large to fit in this 24-bit immediate spot.")]
    Immediate24TooLarge { val: u64, span: Span },
    #[error(
        "This op expects {expected} register(s) as arguments, but you provided {received} register(s)."
    )]
    IncorrectNumberOfAsmRegisters {
        span: Span,
        expected: usize,
        received: usize,
    },
    #[error("This op does not take an immediate value.")]
    UnnecessaryImmediate { span: Span },
    #[error("This reference is ambiguous, and could refer to a module, enum, or function of the same name. Try qualifying the name with a path.")]
    AmbiguousPath { span: Span },
    #[error("This is a module path, and not an expression.")]
    ModulePathIsNotAnExpression { module_path: String, span: Span },
    #[error("Unknown type name.")]
    UnknownType { span: Span },
    #[error("Unknown type name \"{name}\".")]
    UnknownTypeName { name: String, span: Span },
    #[error("The file {file_path} could not be read: {stringified_error}")]
    FileCouldNotBeRead {
        span: Span,
        file_path: String,
        stringified_error: String,
    },
    #[error("This imported file must be a library. It must start with \"library;\"")]
    ImportMustBeLibrary { span: Span },
    #[error("An enum instantiaton cannot contain more than one value. This should be a single value of type {ty}.")]
    MoreThanOneEnumInstantiator { span: Span, ty: String },
    #[error("This enum variant represents the unit type, so it should not be instantiated with any value.")]
    UnnecessaryEnumInstantiator { span: Span },
    #[error("The enum variant `{ty}` is of type `unit`, so its constructor does not take arguments or parentheses. Try removing the ().")]
    UnitVariantWithParenthesesEnumInstantiator { span: Span, ty: String },
    #[error("Cannot find trait \"{name}\" in this scope.")]
    TraitNotFound { name: String, span: Span },
    #[error("Trait \"{trait_name}\" is not imported when calling \"{function_name}\".\nThe import is needed because \"{function_name}\" uses \"{trait_name}\" in one of its trait constraints.")]
    TraitNotImportedAtFunctionApplication {
        trait_name: String,
        function_name: String,
        function_call_site_span: Span,
        trait_constraint_span: Span,
        trait_candidates: Vec<String>,
    },
    #[error("This expression is not valid on the left hand side of a reassignment.")]
    InvalidExpressionOnLhs { span: Span },
    #[error("This code cannot be evaluated to a constant")]
    CannotBeEvaluatedToConst { span: Span },
    #[error(
        "This code cannot be evaluated to a configurable because its size is not always limited."
    )]
    CannotBeEvaluatedToConfigurableSizeUnknown { span: Span },
    #[error("{} \"{method_name}\" expects {expected} {} but you provided {received}.",
        if *dot_syntax_used { "Method" } else { "Function" },
        if *expected == 1usize { "argument" } else {"arguments"},
    )]
    TooManyArgumentsForFunction {
        span: Span,
        method_name: Ident,
        dot_syntax_used: bool,
        expected: usize,
        received: usize,
    },
    #[error("{} \"{method_name}\" expects {expected} {} but you provided {received}.",
        if *dot_syntax_used { "Method" } else { "Function" },
        if *expected == 1usize { "argument" } else {"arguments"},
    )]
    TooFewArgumentsForFunction {
        span: Span,
        method_name: Ident,
        dot_syntax_used: bool,
        expected: usize,
        received: usize,
    },
    #[error("The function \"{method_name}\" was called without parentheses. Try adding ().")]
    MissingParenthesesForFunction { span: Span, method_name: Ident },
    #[error("This type is invalid in a function selector. A contract ABI function selector must be a known sized type, not generic.")]
    InvalidAbiType { span: Span },
    #[error("This is a {actually_is}, not an ABI. An ABI cast requires a valid ABI to cast the address to.")]
    NotAnAbi {
        span: Span,
        actually_is: &'static str,
    },
    #[error("An ABI can only be implemented for the `Contract` type, so this implementation of an ABI for type \"{ty}\" is invalid.")]
    ImplAbiForNonContract { span: Span, ty: String },
    #[error("Conflicting implementations of trait \"{trait_name}\" for type \"{type_implementing_for}\".")]
    ConflictingImplsForTraitAndType {
        trait_name: String,
        type_implementing_for: String,
        existing_impl_span: Span,
        second_impl_span: Span,
    },
    #[error("Duplicate definitions for the {decl_kind} \"{decl_name}\" for type \"{type_implementing_for}\".")]
    DuplicateDeclDefinedForType {
        decl_kind: String,
        decl_name: String,
        type_implementing_for: String,
        span: Span,
    },
    #[error("The function \"{fn_name}\" in {interface_name} is defined with {num_parameters} parameters, but the provided implementation has {provided_parameters} parameters.")]
    IncorrectNumberOfInterfaceSurfaceFunctionParameters {
        fn_name: Ident,
        interface_name: InterfaceName,
        num_parameters: usize,
        provided_parameters: usize,
        span: Span,
    },
    #[error("This parameter was declared as type {should_be}, but argument of type {provided} was provided.")]
    ArgumentParameterTypeMismatch {
        span: Span,
        should_be: String,
        provided: String,
    },
    #[error("Function {fn_name} is recursive, which is unsupported at this time.")]
    RecursiveCall { fn_name: Ident, span: Span },
    #[error(
        "Function {fn_name} is recursive via {call_chain}, which is unsupported at this time."
    )]
    RecursiveCallChain {
        fn_name: Ident,
        call_chain: String, // Pretty list of symbols, e.g., "a, b and c".
        span: Span,
    },
    #[error("Type {name} is recursive, which is unsupported at this time.")]
    RecursiveType { name: Ident, span: Span },
    #[error("Type {name} is recursive via {type_chain}, which is unsupported at this time.")]
    RecursiveTypeChain {
        name: Ident,
        type_chain: String, // Pretty list of symbols, e.g., "a, b and c".
        span: Span,
    },
    #[error("The GM (get-metadata) opcode, when called from an external context, will cause the VM to panic.")]
    GMFromExternalContext { span: Span },
    #[error("The MINT opcode cannot be used in an external context.")]
    MintFromExternalContext { span: Span },
    #[error("The BURN opcode cannot be used in an external context.")]
    BurnFromExternalContext { span: Span },
    #[error("Contract storage cannot be used in an external context.")]
    ContractStorageFromExternalContext { span: Span },
    #[error("The {opcode} opcode cannot be used in a predicate.")]
    InvalidOpcodeFromPredicate { opcode: String, span: Span },
    #[error("Index out of bounds; the length is {count} but the index is {index}.")]
    ArrayOutOfBounds { index: u64, count: u64, span: Span },
    #[error(
        "Invalid range; the range end at index {end} is smaller than its start at index {start}"
    )]
    InvalidRangeEndGreaterThanStart { start: u64, end: u64, span: Span },
    #[error("Tuple index {index} is out of bounds. The tuple has {count} element{}.", plural_s(*count))]
    TupleIndexOutOfBounds {
        index: usize,
        count: usize,
        tuple_type: String,
        span: Span,
        prefix_span: Span,
    },
    #[error("Constants cannot be shadowed. {shadowing_source} \"{name}\" shadows constant of the same name.")]
    ConstantsCannotBeShadowed {
        /// Defines what shadows the constant.
        ///
        /// Although being ready in the diagnostic, the `PatternMatchingStructFieldVar` option
        /// is currently not used. Getting the information about imports and aliases while
        /// type checking match branches is too much effort at the moment, compared to gained
        /// additional clarity of the error message. We might add support for this option in
        /// the future.
        shadowing_source: ShadowingSource,
        name: IdentUnique,
        constant_span: Span,
        constant_decl_span: Span,
        is_alias: bool,
    },
    #[error("Configurables cannot be shadowed. {shadowing_source} \"{name}\" shadows configurable of the same name.")]
    ConfigurablesCannotBeShadowed {
        /// Defines what shadows the configurable.
        ///
        /// Using configurable in pattern matching, expecting to behave same as a constant,
        /// will result in [CompileError::ConfigurablesCannotBeMatchedAgainst].
        /// Otherwise, we would end up with a very confusing error message that
        /// a configurable cannot be shadowed by a variable.
        /// In the, unlikely but equally confusing, case of a struct field pattern variable
        /// named same as the configurable we also want to provide a better explanation
        /// and `shadowing_source` helps us distinguish that case as well.
        shadowing_source: ShadowingSource,
        name: IdentUnique,
        configurable_span: Span,
    },
    #[error("Configurables cannot be matched against. Configurable \"{name}\" cannot be used in pattern matching.")]
    ConfigurablesCannotBeMatchedAgainst {
        name: IdentUnique,
        configurable_span: Span,
    },
    #[error(
        "Constants cannot shadow variables. Constant \"{name}\" shadows variable of the same name."
    )]
    ConstantShadowsVariable {
        name: IdentUnique,
        variable_span: Span,
    },
    #[error("{existing_constant_or_configurable} of the name \"{name}\" already exists.")]
    ConstantDuplicatesConstantOrConfigurable {
        /// Text "Constant" or "Configurable". Denotes already declared constant or configurable.
        existing_constant_or_configurable: &'static str,
        /// Text "Constant" or "Configurable". Denotes constant or configurable attempted to be declared.
        new_constant_or_configurable: &'static str,
        name: IdentUnique,
        existing_span: Span,
    },
    #[error("Imported symbol \"{name}\" shadows another symbol of the same name.")]
    ShadowsOtherSymbol { name: IdentUnique },
    #[error("The name \"{name}\" is already used for a generic parameter in this scope.")]
    GenericShadowsGeneric { name: IdentUnique },
    #[error("Non-exhaustive match expression. Missing patterns {missing_patterns}")]
    MatchExpressionNonExhaustive {
        missing_patterns: String,
        span: Span,
    },
    #[error("Struct pattern is missing the {}field{} {}.",
        if *missing_fields_are_public { "public " } else { "" },
        plural_s(missing_fields.len()),
        sequence_to_str(missing_fields, Enclosing::DoubleQuote, 2)
    )]
    MatchStructPatternMissingFields {
        missing_fields: Vec<Ident>,
        missing_fields_are_public: bool,
        /// Original, non-aliased struct name.
        struct_name: Ident,
        struct_decl_span: Span,
        total_number_of_fields: usize,
        span: Span,
    },
    #[error("Struct pattern must ignore inaccessible private field{} {}.",
        plural_s(private_fields.len()),
        sequence_to_str(private_fields, Enclosing::DoubleQuote, 2))]
    MatchStructPatternMustIgnorePrivateFields {
        private_fields: Vec<Ident>,
        /// Original, non-aliased struct name.
        struct_name: Ident,
        struct_decl_span: Span,
        all_fields_are_private: bool,
        span: Span,
    },
    #[error("Variable \"{variable}\" is not defined in all alternatives.")]
    MatchArmVariableNotDefinedInAllAlternatives {
        match_value: Span,
        match_type: String,
        variable: Ident,
        missing_in_alternatives: Vec<Span>,
    },
    #[error(
        "Variable \"{variable}\" is expected to be of type \"{expected}\", but is \"{received}\"."
    )]
    MatchArmVariableMismatchedType {
        match_value: Span,
        match_type: String,
        variable: Ident,
        first_definition: Span,
        expected: String,
        received: String,
    },
    #[error("This cannot be matched.")]
    MatchedValueIsNotValid {
        /// Common message describing which Sway types
        /// are currently supported in match expressions.
        supported_types_message: Vec<&'static str>,
        span: Span,
    },
    #[error(
        "The function \"{fn_name}\" in {interface_name} is pure, but this \
        implementation is not.  The \"{STORAGE_PURITY_ATTRIBUTE_NAME}\" annotation must be \
        removed, or the trait declaration must be changed to \
        \"#[{STORAGE_PURITY_ATTRIBUTE_NAME}({attrs})]\"."
    )]
    TraitDeclPureImplImpure {
        fn_name: Ident,
        interface_name: InterfaceName,
        attrs: String,
        span: Span,
    },
    #[error(
        "Storage attribute access mismatch. The function \"{fn_name}\" in \
        {interface_name} requires the storage attribute(s) #[{STORAGE_PURITY_ATTRIBUTE_NAME}({attrs})]."
    )]
    TraitImplPurityMismatch {
        fn_name: Ident,
        interface_name: InterfaceName,
        attrs: String,
        span: Span,
    },
    #[error("Impure function inside of non-contract. Contract storage is only accessible from contracts.")]
    ImpureInNonContract { span: Span },
    #[error(
        "This function performs storage access but does not have the required storage \
        attribute(s). Try adding \"#[{STORAGE_PURITY_ATTRIBUTE_NAME}({suggested_attributes})]\" to the function \
        declaration."
    )]
    StorageAccessMismatched {
        /// True if the function with mismatched access is pure.
        is_pure: bool,
        storage_access_violations: Vec<(Span, StorageAccess)>,
        suggested_attributes: String,
        /// Span pointing to the name of the function in the function declaration,
        /// whose storage attributes mismatch the storage access patterns.
        span: Span,
    },
    #[error(
        "Parameter reference type or mutability mismatch between the trait function declaration and its implementation."
    )]
    ParameterRefMutabilityMismatch { span: Span },
    #[error("Literal value is too large for type {ty}.")]
    IntegerTooLarge { span: Span, ty: String },
    #[error("Literal value underflows type {ty}.")]
    IntegerTooSmall { span: Span, ty: String },
    #[error("Literal value contains digits which are not valid for type {ty}.")]
    IntegerContainsInvalidDigit { span: Span, ty: String },
    #[error("A trait cannot be a subtrait of an ABI.")]
    AbiAsSupertrait { span: Span },
    #[error(
        "Implementation of trait \"{supertrait_name}\" is required by this bound in \"{trait_name}\""
    )]
    SupertraitImplRequired {
        supertrait_name: String,
        trait_name: Ident,
        span: Span,
    },
    #[error(
        "Contract ABI method parameter \"{param_name}\" is set multiple times for this contract ABI method call"
    )]
    ContractCallParamRepeated { param_name: String, span: Span },
    #[error(
        "Unrecognized contract ABI method parameter \"{param_name}\". The only available parameters are \"gas\", \"coins\", and \"asset_id\""
    )]
    UnrecognizedContractParam { param_name: String, span: Span },
    #[error("Attempting to specify a contract method parameter for a non-contract function call")]
    CallParamForNonContractCallMethod { span: Span },
    #[error("Storage field \"{field_name}\" does not exist.")]
    StorageFieldDoesNotExist {
        field_name: IdentUnique,
        available_fields: Vec<(Vec<Ident>, Ident)>,
        storage_decl_span: Span,
    },
    #[error("No storage has been declared")]
    NoDeclaredStorage { span: Span },
    #[error("Multiple storage declarations were found")]
    MultipleStorageDeclarations { span: Span },
    #[error("Type {ty} can only be declared directly as a storage field")]
    InvalidStorageOnlyTypeDecl { ty: String, span: Span },
    #[error(
        "Internal compiler error: Unexpected {decl_type} declaration found.\n\
        Please file an issue on the repository and include the code that triggered this error."
    )]
    UnexpectedDeclaration { decl_type: &'static str, span: Span },
    #[error("This contract caller has no known address. Try instantiating a contract caller with a known contract address instead.")]
    ContractAddressMustBeKnown { span: Span },
    #[error("{}", error)]
    ConvertParseTree {
        #[from]
        error: ConvertParseTreeError,
    },
    #[error("{}", error)]
    Lex { error: LexError },
    #[error("{}", error)]
    Parse { error: ParseError },
    #[error("Could not evaluate initializer to a const declaration.")]
    NonConstantDeclValue { span: Span },
    #[error("Declaring storage in a {program_kind} is not allowed.")]
    StorageDeclarationInNonContract { program_kind: String, span: Span },
    #[error("Unsupported argument type to intrinsic \"{name}\".{}", if hint.is_empty() { "".to_string() } else { format!(" Hint: {hint}") })]
    IntrinsicUnsupportedArgType {
        name: String,
        span: Span,
        hint: String,
    },
    #[error("Call to \"{name}\" expects {expected} arguments")]
    IntrinsicIncorrectNumArgs {
        name: String,
        expected: u64,
        span: Span,
    },
    #[error("Call to \"{name}\" expects {expected} type arguments")]
    IntrinsicIncorrectNumTArgs {
        name: String,
        expected: u64,
        span: Span,
    },
    #[error("Expected string literal")]
    ExpectedStringLiteral { span: Span },
    #[error("\"break\" used outside of a loop")]
    BreakOutsideLoop { span: Span },
    #[error("\"continue\" used outside of a loop")]
    ContinueOutsideLoop { span: Span },
    /// This will be removed once loading contract IDs in a dependency namespace is refactored and no longer manual:
    /// https://github.com/FuelLabs/sway/issues/3077
    #[error("Contract ID is not a constant item.")]
    ContractIdConstantNotAConstDecl { span: Span },
    /// This will be removed once loading contract IDs in a dependency namespace is refactored and no longer manual:
    /// https://github.com/FuelLabs/sway/issues/3077
    #[error("Contract ID value is not a literal.")]
    ContractIdValueNotALiteral { span: Span },

    #[error("{reason}")]
    TypeNotAllowed {
        reason: TypeNotAllowedReason,
        span: Span,
    },
    #[error("ref mut parameter not allowed for main()")]
    RefMutableNotAllowedInMain { param_name: Ident, span: Span },
    #[error(
        "Register \"{name}\" is initialized and later reassigned which is not allowed. \
            Consider assigning to a different register inside the ASM block."
    )]
    InitializedRegisterReassignment { name: String, span: Span },
    #[error("Control flow VM instructions are not allowed in assembly blocks.")]
    DisallowedControlFlowInstruction { name: String, span: Span },
    #[error("Calling private library method {name} is not allowed.")]
    CallingPrivateLibraryMethod { name: String, span: Span },
    #[error("Using intrinsic \"{intrinsic}\" in a predicate is not allowed.")]
    DisallowedIntrinsicInPredicate { intrinsic: String, span: Span },
    #[error("Possibly non-zero amount of coins transferred to non-payable contract method \"{fn_name}\".")]
    CoinsPassedToNonPayableMethod { fn_name: Ident, span: Span },
    #[error(
        "Payable attribute mismatch. The \"{fn_name}\" method implementation \
         {} in its signature in {interface_name}.",
        if *missing_impl_attribute {
            "is missing #[payable] attribute specified"
        } else {
            "has extra #[payable] attribute not mentioned"
        }
    )]
    TraitImplPayabilityMismatch {
        fn_name: Ident,
        interface_name: InterfaceName,
        missing_impl_attribute: bool,
        span: Span,
    },
    #[error("Configurable constants are not allowed in libraries.")]
    ConfigurableInLibrary { span: Span },
    #[error("Multiple applicable items in scope. {}", {
        let mut candidates = "".to_string();
        let mut as_traits = as_traits.clone();
        // Make order deterministic
        as_traits.sort_by_key(|a| a.0.to_lowercase());
        for (index, as_trait) in as_traits.iter().enumerate() {
            candidates = format!("{candidates}\n  Disambiguate the associated {item_kind} for candidate #{index}\n    <{} as {}>::{item_name}", as_trait.1, as_trait.0);
        }
        candidates
    })]
    MultipleApplicableItemsInScope {
        span: Span,
        item_name: String,
        item_kind: String,
        as_traits: Vec<(String, String)>,
    },
    #[error("Provided generic type is not of type str.")]
    NonStrGenericType { span: Span },
    #[error("A contract method cannot call methods belonging to the same ABI")]
    ContractCallsItsOwnMethod { span: Span },
    #[error("ABI cannot define a method of the same name as its super-ABI \"{superabi}\"")]
    AbiShadowsSuperAbiMethod { span: Span, superabi: Ident },
    #[error("ABI cannot inherit samely named method (\"{method_name}\") from several super-ABIs: \"{superabi1}\" and \"{superabi2}\"")]
    ConflictingSuperAbiMethods {
        span: Span,
        method_name: String,
        superabi1: String,
        superabi2: String,
    },
    #[error("Associated types not supported in ABI.")]
    AssociatedTypeNotSupportedInAbi { span: Span },
    #[error("Cannot call ABI supertrait's method as a contract method: \"{fn_name}\"")]
    AbiSupertraitMethodCallAsContractCall { fn_name: Ident, span: Span },
    #[error("{invalid_type} is not a valid type in the self type of an impl block.")]
    TypeIsNotValidAsImplementingFor {
        invalid_type: InvalidImplementingForType,
        /// Name of the trait if the impl implements a trait, `None` otherwise.
        trait_name: Option<String>,
        span: Span,
    },
    #[error("Uninitialized register is being read before being written")]
    UninitRegisterInAsmBlockBeingRead { span: Span },
    #[error("Expression of type \"{expression_type}\" cannot be dereferenced.")]
    ExpressionCannotBeDereferenced { expression_type: String, span: Span },
    #[error("Fallback functions can only exist in contracts")]
    FallbackFnsAreContractOnly { span: Span },
    #[error("Fallback functions cannot have parameters")]
    FallbackFnsCannotHaveParameters { span: Span },
    #[error("Could not generate the entry method. See errors above for more details.")]
    CouldNotGenerateEntry { span: Span },
    #[error("Missing `core` in dependencies.")]
    CouldNotGenerateEntryMissingCore { span: Span },
    #[error("Type \"{ty}\" does not implement AbiEncode or AbiDecode.")]
    CouldNotGenerateEntryMissingImpl { ty: String, span: Span },
    #[error("Only bool, u8, u16, u32, u64, u256, b256, string arrays and string slices can be used here.")]
    EncodingUnsupportedType { span: Span },
    #[error("Configurables need a function named \"abi_decode_in_place\" to be in scope.")]
    ConfigurableMissingAbiDecodeInPlace { span: Span },
    #[error("Collision detected between two different types.\n  Shared hash:{hash}\n  First type:{first_type}\n  Second type:{second_type}")]
    ABIHashCollision {
        span: Span,
        hash: String,
        first_type: String,
        second_type: String,
    },
    #[error("Type must be known at this point")]
    TypeMustBeKnownAtThisPoint { span: Span, internal: String },
    #[error("Multiple impls satisfying trait for type.")]
    MultipleImplsSatisfyingTraitForType {
        span: Span,
        type_annotation: String,
        trait_names: Vec<String>,
        trait_types_and_names: Vec<(String, String)>,
    },
}

impl std::convert::From<TypeError> for CompileError {
    fn from(other: TypeError) -> CompileError {
        CompileError::TypeError(other)
    }
}

impl Spanned for CompileError {
    fn span(&self) -> Span {
        use CompileError::*;
        match self {
            ModuleDepGraphEvaluationError { .. } => Span::dummy(),
            ModuleDepGraphCyclicReference { .. } => Span::dummy(),
            UnknownVariable { span, .. } => span.clone(),
            NotAVariable { span, .. } => span.clone(),
            Unimplemented { span, .. } => span.clone(),
            TypeError(err) => err.span(),
            ParseError { span, .. } => span.clone(),
            Internal(_, span) => span.clone(),
            InternalOwned(_, span) => span.clone(),
            NoPredicateMainFunction(span) => span.clone(),
            PredicateMainDoesNotReturnBool(span) => span.clone(),
            NoScriptMainFunction(span) => span.clone(),
            MultipleDefinitionsOfFunction { span, .. } => span.clone(),
            MultipleDefinitionsOfName { span, .. } => span.clone(),
            MultipleDefinitionsOfConstant { span, .. } => span.clone(),
            MultipleDefinitionsOfType { span, .. } => span.clone(),
            MultipleDefinitionsOfMatchArmVariable { duplicate, .. } => duplicate.clone(),
            MultipleDefinitionsOfFallbackFunction { span, .. } => span.clone(),
            AssignmentToNonMutableVariable { lhs_span, .. } => lhs_span.clone(),
            AssignmentToConstantOrConfigurable { lhs_span, .. } => lhs_span.clone(),
            DeclAssignmentTargetCannotBeAssignedTo { lhs_span, .. } => lhs_span.clone(),
            AssignmentViaNonMutableReference { span, .. } => span.clone(),
            MutableParameterNotSupported { span, .. } => span.clone(),
            ImmutableArgumentToMutableParameter { span } => span.clone(),
            RefMutableNotAllowedInContractAbi { span, .. } => span.clone(),
            RefMutCannotReferenceConstant { span, .. } => span.clone(),
            RefMutCannotReferenceImmutableVariable { span, .. } => span.clone(),
            MethodRequiresMutableSelf { span, .. } => span.clone(),
            AssociatedFunctionCalledAsMethod { span, .. } => span.clone(),
            TypeParameterNotInTypeScope { span, .. } => span.clone(),
            MismatchedTypeInInterfaceSurface { span, .. } => span.clone(),
            UnknownTrait { span, .. } => span.clone(),
            FunctionNotAPartOfInterfaceSurface { span, .. } => span.clone(),
            ConstantNotAPartOfInterfaceSurface { span, .. } => span.clone(),
            TypeNotAPartOfInterfaceSurface { span, .. } => span.clone(),
            MissingInterfaceSurfaceConstants { span, .. } => span.clone(),
            MissingInterfaceSurfaceTypes { span, .. } => span.clone(),
            MissingInterfaceSurfaceMethods { span, .. } => span.clone(),
            IncorrectNumberOfTypeArguments { span, .. } => span.clone(),
            DoesNotTakeTypeArguments { span, .. } => span.clone(),
            DoesNotTakeTypeArgumentsAsPrefix { span, .. } => span.clone(),
            TypeArgumentsNotAllowed { span } => span.clone(),
            NeedsTypeArguments { span, .. } => span.clone(),
            StructInstantiationMissingFieldForErrorRecovery { span, .. } => span.clone(),
            StructInstantiationMissingFields { span, .. } => span.clone(),
            StructCannotBeInstantiated { span, .. } => span.clone(),
            StructFieldIsPrivate { field_name, .. } => field_name.span(),
            StructFieldDoesNotExist { field_name, .. } => field_name.span(),
            StructFieldDuplicated { field_name, .. } => field_name.span(),
            MethodNotFound { span, .. } => span.clone(),
            ModuleNotFound { span, .. } => span.clone(),
            TupleElementAccessOnNonTuple { span, .. } => span.clone(),
            NotAStruct { span, .. } => span.clone(),
            NotIndexable { span, .. } => span.clone(),
            FieldAccessOnNonStruct { span, .. } => span.clone(),
            SymbolNotFound { span, .. } => span.clone(),
            SymbolWithMultipleBindings { span, .. } => span.clone(),
            ImportPrivateSymbol { span, .. } => span.clone(),
            ImportPrivateModule { span, .. } => span.clone(),
            NoElseBranch { span, .. } => span.clone(),
            NotAType { span, .. } => span.clone(),
            MissingEnumInstantiator { span, .. } => span.clone(),
            PathDoesNotReturn { span, .. } => span.clone(),
            ExpectedModuleDocComment { span } => span.clone(),
            UnknownRegister { span, .. } => span.clone(),
            MissingImmediate { span, .. } => span.clone(),
            InvalidImmediateValue { span, .. } => span.clone(),
            UnknownEnumVariant { span, .. } => span.clone(),
            UnrecognizedOp { span, .. } => span.clone(),
            UnableToInferGeneric { span, .. } => span.clone(),
            UnconstrainedGenericParameter { span, .. } => span.clone(),
            TraitConstraintNotSatisfied { span, .. } => span.clone(),
            TraitConstraintMissing { span, .. } => span.clone(),
            Immediate06TooLarge { span, .. } => span.clone(),
            Immediate12TooLarge { span, .. } => span.clone(),
            Immediate18TooLarge { span, .. } => span.clone(),
            Immediate24TooLarge { span, .. } => span.clone(),
            IncorrectNumberOfAsmRegisters { span, .. } => span.clone(),
            UnnecessaryImmediate { span, .. } => span.clone(),
            AmbiguousPath { span } => span.clone(),
            ModulePathIsNotAnExpression { span, .. } => span.clone(),
            UnknownType { span, .. } => span.clone(),
            UnknownTypeName { span, .. } => span.clone(),
            FileCouldNotBeRead { span, .. } => span.clone(),
            ImportMustBeLibrary { span, .. } => span.clone(),
            MoreThanOneEnumInstantiator { span, .. } => span.clone(),
            UnnecessaryEnumInstantiator { span, .. } => span.clone(),
            UnitVariantWithParenthesesEnumInstantiator { span, .. } => span.clone(),
            TraitNotFound { span, .. } => span.clone(),
            TraitNotImportedAtFunctionApplication {
                function_call_site_span,
                ..
            } => function_call_site_span.clone(),
            InvalidExpressionOnLhs { span, .. } => span.clone(),
            TooManyArgumentsForFunction { span, .. } => span.clone(),
            TooFewArgumentsForFunction { span, .. } => span.clone(),
            MissingParenthesesForFunction { span, .. } => span.clone(),
            InvalidAbiType { span, .. } => span.clone(),
            NotAnAbi { span, .. } => span.clone(),
            ImplAbiForNonContract { span, .. } => span.clone(),
            ConflictingImplsForTraitAndType {
                second_impl_span, ..
            } => second_impl_span.clone(),
            DuplicateDeclDefinedForType { span, .. } => span.clone(),
            IncorrectNumberOfInterfaceSurfaceFunctionParameters { span, .. } => span.clone(),
            ArgumentParameterTypeMismatch { span, .. } => span.clone(),
            RecursiveCall { span, .. } => span.clone(),
            RecursiveCallChain { span, .. } => span.clone(),
            RecursiveType { span, .. } => span.clone(),
            RecursiveTypeChain { span, .. } => span.clone(),
            GMFromExternalContext { span, .. } => span.clone(),
            MintFromExternalContext { span, .. } => span.clone(),
            BurnFromExternalContext { span, .. } => span.clone(),
            ContractStorageFromExternalContext { span, .. } => span.clone(),
            InvalidOpcodeFromPredicate { span, .. } => span.clone(),
            ArrayOutOfBounds { span, .. } => span.clone(),
            ConstantsCannotBeShadowed { name, .. } => name.span(),
            ConfigurablesCannotBeShadowed { name, .. } => name.span(),
            ConfigurablesCannotBeMatchedAgainst { name, .. } => name.span(),
            ConstantShadowsVariable { name, .. } => name.span(),
            ConstantDuplicatesConstantOrConfigurable { name, .. } => name.span(),
            ShadowsOtherSymbol { name } => name.span(),
            GenericShadowsGeneric { name } => name.span(),
            MatchExpressionNonExhaustive { span, .. } => span.clone(),
            MatchStructPatternMissingFields { span, .. } => span.clone(),
            MatchStructPatternMustIgnorePrivateFields { span, .. } => span.clone(),
            MatchArmVariableNotDefinedInAllAlternatives { variable, .. } => variable.span(),
            MatchArmVariableMismatchedType { variable, .. } => variable.span(),
            MatchedValueIsNotValid { span, .. } => span.clone(),
            NotAnEnum { span, .. } => span.clone(),
            TraitDeclPureImplImpure { span, .. } => span.clone(),
            TraitImplPurityMismatch { span, .. } => span.clone(),
            DeclIsNotAnEnum { span, .. } => span.clone(),
            DeclIsNotAStruct { span, .. } => span.clone(),
            DeclIsNotAFunction { span, .. } => span.clone(),
            DeclIsNotAVariable { span, .. } => span.clone(),
            DeclIsNotAnAbi { span, .. } => span.clone(),
            DeclIsNotATrait { span, .. } => span.clone(),
            DeclIsNotAnImplTrait { span, .. } => span.clone(),
            DeclIsNotATraitFn { span, .. } => span.clone(),
            DeclIsNotStorage { span, .. } => span.clone(),
            DeclIsNotAConstant { span, .. } => span.clone(),
            DeclIsNotATypeAlias { span, .. } => span.clone(),
            ImpureInNonContract { span, .. } => span.clone(),
            StorageAccessMismatched { span, .. } => span.clone(),
            ParameterRefMutabilityMismatch { span, .. } => span.clone(),
            IntegerTooLarge { span, .. } => span.clone(),
            IntegerTooSmall { span, .. } => span.clone(),
            IntegerContainsInvalidDigit { span, .. } => span.clone(),
            AbiAsSupertrait { span, .. } => span.clone(),
            SupertraitImplRequired { span, .. } => span.clone(),
            ContractCallParamRepeated { span, .. } => span.clone(),
            UnrecognizedContractParam { span, .. } => span.clone(),
            CallParamForNonContractCallMethod { span, .. } => span.clone(),
            StorageFieldDoesNotExist { field_name, .. } => field_name.span(),
            InvalidStorageOnlyTypeDecl { span, .. } => span.clone(),
            NoDeclaredStorage { span, .. } => span.clone(),
            MultipleStorageDeclarations { span, .. } => span.clone(),
            UnexpectedDeclaration { span, .. } => span.clone(),
            ContractAddressMustBeKnown { span, .. } => span.clone(),
            ConvertParseTree { error } => error.span(),
            Lex { error } => error.span(),
            Parse { error } => error.span.clone(),
            EnumNotFound { span, .. } => span.clone(),
            TupleIndexOutOfBounds { span, .. } => span.clone(),
            NonConstantDeclValue { span, .. } => span.clone(),
            StorageDeclarationInNonContract { span, .. } => span.clone(),
            IntrinsicUnsupportedArgType { span, .. } => span.clone(),
            IntrinsicIncorrectNumArgs { span, .. } => span.clone(),
            IntrinsicIncorrectNumTArgs { span, .. } => span.clone(),
            BreakOutsideLoop { span } => span.clone(),
            ContinueOutsideLoop { span } => span.clone(),
            ContractIdConstantNotAConstDecl { span } => span.clone(),
            ContractIdValueNotALiteral { span } => span.clone(),
            RefMutableNotAllowedInMain { span, .. } => span.clone(),
            InitializedRegisterReassignment { span, .. } => span.clone(),
            DisallowedControlFlowInstruction { span, .. } => span.clone(),
            CallingPrivateLibraryMethod { span, .. } => span.clone(),
            DisallowedIntrinsicInPredicate { span, .. } => span.clone(),
            CoinsPassedToNonPayableMethod { span, .. } => span.clone(),
            TraitImplPayabilityMismatch { span, .. } => span.clone(),
            ConfigurableInLibrary { span } => span.clone(),
            MultipleApplicableItemsInScope { span, .. } => span.clone(),
            NonStrGenericType { span } => span.clone(),
            CannotBeEvaluatedToConst { span } => span.clone(),
            ContractCallsItsOwnMethod { span } => span.clone(),
            AbiShadowsSuperAbiMethod { span, .. } => span.clone(),
            ConflictingSuperAbiMethods { span, .. } => span.clone(),
            AssociatedTypeNotSupportedInAbi { span, .. } => span.clone(),
            AbiSupertraitMethodCallAsContractCall { span, .. } => span.clone(),
            TypeNotAllowed { span, .. } => span.clone(),
            ExpectedStringLiteral { span } => span.clone(),
            TypeIsNotValidAsImplementingFor { span, .. } => span.clone(),
            UninitRegisterInAsmBlockBeingRead { span } => span.clone(),
            ExpressionCannotBeDereferenced { span, .. } => span.clone(),
            FallbackFnsAreContractOnly { span } => span.clone(),
            FallbackFnsCannotHaveParameters { span } => span.clone(),
            CouldNotGenerateEntry { span } => span.clone(),
            CouldNotGenerateEntryMissingCore { span } => span.clone(),
            CouldNotGenerateEntryMissingImpl { span, .. } => span.clone(),
            CannotBeEvaluatedToConfigurableSizeUnknown { span } => span.clone(),
            EncodingUnsupportedType { span } => span.clone(),
            ConfigurableMissingAbiDecodeInPlace { span } => span.clone(),
            ABIHashCollision { span, .. } => span.clone(),
            InvalidRangeEndGreaterThanStart { span, .. } => span.clone(),
            TypeMustBeKnownAtThisPoint { span, .. } => span.clone(),
            MultipleImplsSatisfyingTraitForType { span, .. } => span.clone(),
        }
    }
}

// When implementing diagnostics, follow these two guidelines outlined in the Expressive Diagnostics RFC:
// - Guide-level explanation: https://github.com/FuelLabs/sway-rfcs/blob/master/rfcs/0011-expressive-diagnostics.md#guide-level-explanation
// - Wording guidelines: https://github.com/FuelLabs/sway-rfcs/blob/master/rfcs/0011-expressive-diagnostics.md#wording-guidelines
// For concrete examples, look at the existing diagnostics.
//
// The issue and the hints are not displayed if set to `Span::dummy()`.
//
// NOTE: Issue level should actually be the part of the reason. But it would complicate handling of labels in the transitional
//       period when we still have "old-style" diagnostics.
//       Let's leave it like this. Refactoring currently doesn't pay off.
//       And our #[error] macro will anyhow encapsulate it and ensure consistency.
impl ToDiagnostic for CompileError {
    fn to_diagnostic(&self, source_engine: &SourceEngine) -> Diagnostic {
        let code = Code::semantic_analysis;
        use CompileError::*;
        match self {
            ConstantsCannotBeShadowed { shadowing_source, name, constant_span, constant_decl_span, is_alias } => Diagnostic {
                reason: Some(Reason::new(code(1), "Constants cannot be shadowed".to_string())),
                issue: Issue::error(
                    source_engine,
                    name.span(),
                    format!(
                        // Variable "x" shadows constant with of same name.
                        //  or
                        // Constant "x" shadows imported constant of the same name.
                        //  or
                        // ...
                        "{shadowing_source} \"{name}\" shadows {}constant of the same name.",
                        if constant_decl_span.clone() != Span::dummy() { "imported " } else { "" }
                    )
                ),
                hints: vec![
                    Hint::info(
                        source_engine,
                        constant_span.clone(),
                        format!(
                            // Shadowed constant "x" is declared here.
                            //  or
                            // Shadowed constant "x" gets imported here.
                            //  or
                            // ...
                            "Shadowed constant \"{name}\" {} here{}.",
                            if constant_decl_span.clone() != Span::dummy() { "gets imported" } else { "is declared" },
                            if *is_alias { " as alias" } else { "" }
                        )
                    ),
                    if matches!(shadowing_source, PatternMatchingStructFieldVar) {
                        Hint::help(
                            source_engine,
                            name.span(),
                            format!("\"{name}\" is a struct field that defines a pattern variable of the same name.")
                        )
                    } else {
                        Hint::none()
                    },
                    Hint::info( // Ignored if the `constant_decl_span` is `Span::dummy()`.
                        source_engine,
                        constant_decl_span.clone(),
                        format!("This is the original declaration of the imported constant \"{name}\".")
                    ),
                ],
                help: vec![
                    "Unlike variables, constants cannot be shadowed by other constants or variables.".to_string(),
                    match (shadowing_source, *constant_decl_span != Span::dummy()) {
                        (LetVar | PatternMatchingStructFieldVar, false) => format!("Consider renaming either the {} \"{name}\" or the constant \"{name}\".", 
                            format!("{shadowing_source}").to_lowercase(),
                        ),
                        (Const, false) => "Consider renaming one of the constants.".to_string(),
                        (shadowing_source, true) => format!(
                            "Consider renaming the {} \"{name}\" or using {} for the imported constant.",
                            format!("{shadowing_source}").to_lowercase(),
                            if *is_alias { "a different alias" } else { "an alias" }
                        ),
                    },
                    if matches!(shadowing_source, PatternMatchingStructFieldVar) {
                        format!("To rename the pattern variable use the `:`. E.g.: `{name}: some_other_name`.")
                    } else {
                        Diagnostic::help_none()
                    }
                ],
            },
            ConfigurablesCannotBeShadowed { shadowing_source, name, configurable_span } => Diagnostic {
                reason: Some(Reason::new(code(1), "Configurables cannot be shadowed".to_string())),
                issue: Issue::error(
                    source_engine,
                    name.span(),
                    format!("{shadowing_source} \"{name}\" shadows configurable of the same name.")
                ),
                hints: vec![
                    Hint::info(
                        source_engine,
                        configurable_span.clone(),
                        format!("Shadowed configurable \"{name}\" is declared here.")
                    ),
                    if matches!(shadowing_source, PatternMatchingStructFieldVar) {
                        Hint::help(
                            source_engine,
                            name.span(),
                            format!("\"{name}\" is a struct field that defines a pattern variable of the same name.")
                        )
                    } else {
                        Hint::none()
                    },
                ],
                help: vec![
                    "Unlike variables, configurables cannot be shadowed by constants or variables.".to_string(),
                    format!(
                        "Consider renaming either the {} \"{name}\" or the configurable \"{name}\".",
                        format!("{shadowing_source}").to_lowercase()
                    ),
                    if matches!(shadowing_source, PatternMatchingStructFieldVar) {
                        format!("To rename the pattern variable use the `:`. E.g.: `{name}: some_other_name`.")
                    } else {
                        Diagnostic::help_none()
                    }
                ],
            },
            ConfigurablesCannotBeMatchedAgainst { name, configurable_span } => Diagnostic {
                reason: Some(Reason::new(code(1), "Configurables cannot be matched against".to_string())),
                issue: Issue::error(
                    source_engine,
                    name.span(),
                    format!("\"{name}\" is a configurable and configurables cannot be matched against.")
                ),
                hints: {
                    let mut hints = vec![
                        Hint::info(
                            source_engine,
                            configurable_span.clone(),
                            format!("Configurable \"{name}\" is declared here.")
                        ),
                    ];

                    hints.append(&mut Hint::multi_help(source_engine, &name.span(), vec![
                        format!("Are you trying to define a pattern variable named \"{name}\"?"),
                        format!("In that case, use some other name for the pattern variable,"),
                        format!("or consider renaming the configurable \"{name}\"."),
                    ]));

                    hints
                },
                help: vec![
                    "Unlike constants, configurables cannot be matched against in pattern matching.".to_string(),
                    "That's not possible, because patterns to match against must be compile-time constants.".to_string(),
                    "Configurables are run-time constants. Their values are defined during the deployment.".to_string(),
                    Diagnostic::help_empty_line(),
                    "To test against a configurable, consider:".to_string(),
                    format!("{}- replacing the `match` expression with `if-else`s altogether.", Indent::Single),
                    format!("{}- matching against a variable and comparing that variable afterwards with the configurable.", Indent::Single),
                    format!("{}  E.g., instead of:", Indent::Single),
                    Diagnostic::help_empty_line(),
                    format!("{}  SomeStruct {{ x: A_CONFIGURABLE, y: 42 }} => {{", Indent::Double),
                    format!("{}      do_something();", Indent::Double),
                    format!("{}  }}", Indent::Double),
                    Diagnostic::help_empty_line(),
                    format!("{}  to have:", Indent::Single),
                    Diagnostic::help_empty_line(),
                    format!("{}  SomeStruct {{ x, y: 42 }} => {{", Indent::Double),
                    format!("{}      if x == A_CONFIGURABLE {{", Indent::Double),
                    format!("{}          do_something();", Indent::Double),
                    format!("{}      }}", Indent::Double),
                    format!("{}  }}", Indent::Double),
                ],
            },
            ConstantShadowsVariable { name , variable_span } => Diagnostic {
                reason: Some(Reason::new(code(1), "Constants cannot shadow variables".to_string())),
                issue: Issue::error(
                    source_engine,
                    name.span(),
                    format!("Constant \"{name}\" shadows variable of the same name.")
                ),
                hints: vec![
                    Hint::info(
                        source_engine,
                        variable_span.clone(),
                        format!("This is the shadowed variable \"{name}\".")
                    ),
                ],
                help: vec![
                    format!("Variables can shadow other variables, but constants cannot."),
                    format!("Consider renaming either the variable or the constant."),
                ],
            },
            ConstantDuplicatesConstantOrConfigurable { existing_constant_or_configurable, new_constant_or_configurable, name, existing_span } => Diagnostic {
                reason: Some(Reason::new(code(1), match (*existing_constant_or_configurable, *new_constant_or_configurable) {
                    ("Constant", "Constant") => "Constant of the same name already exists".to_string(),
                    ("Constant", "Configurable") => "Constant of the same name as configurable already exists".to_string(),
                    ("Configurable", "Constant") => "Configurable of the same name as constant already exists".to_string(),
                    _ => unreachable!("We can have only the listed combinations. Configurable duplicating configurable is not a valid combination.")
                })),
                issue: Issue::error(
                    source_engine,
                    name.span(),
                    format!("{new_constant_or_configurable} \"{name}\" has the same name as an already declared {}.",
                        existing_constant_or_configurable.to_lowercase()
                    )
                ),
                hints: vec![
                    Hint::info(
                        source_engine,
                        existing_span.clone(),
                        format!("{existing_constant_or_configurable} \"{name}\" is {}declared here.",
                            // If a constant clashes with an already declared constant.
                            if existing_constant_or_configurable == new_constant_or_configurable {
                                "already "
                            } else {
                                ""
                            }
                        )
                    ),
                ],
                help: vec![
                    match (*existing_constant_or_configurable, *new_constant_or_configurable) {
                        ("Constant", "Constant") => "Consider renaming one of the constants, or in case of imported constants, using an alias.".to_string(),
                        _ => "Consider renaming either the configurable or the constant, or in case of an imported constant, using an alias.".to_string(),
                    },
                ],
            },
            MultipleDefinitionsOfMatchArmVariable { match_value, match_type, first_definition, first_definition_is_struct_field, duplicate, duplicate_is_struct_field } => Diagnostic {
                reason: Some(Reason::new(code(1), "Match pattern variable is already defined".to_string())),
                issue: Issue::error(
                    source_engine,
                    duplicate.clone(),
                    format!("Variable \"{}\" is already defined in this match arm.", first_definition.as_str())
                ),
                hints: vec![
                    Hint::help(
                        source_engine,
                        if *duplicate_is_struct_field {
                            duplicate.clone()
                        }
                        else {
                            Span::dummy()
                        },
                        format!("Struct field \"{0}\" is just a shorthand notation for `{0}: {0}`. It defines a variable \"{0}\".", first_definition.as_str())
                    ),
                    Hint::info(
                        source_engine,
                        first_definition.clone(),
                        format!(
                            "This {}is the first definition of the variable \"{}\".",
                            if *first_definition_is_struct_field {
                                format!("struct field \"{}\" ", first_definition.as_str())
                            }
                            else {
                                "".to_string()
                            },
                            first_definition.as_str(),
                        )
                    ),
                    Hint::help(
                        source_engine,
                        if *first_definition_is_struct_field && !*duplicate_is_struct_field {
                            first_definition.clone()
                        }
                        else {
                            Span::dummy()
                        },
                        format!("Struct field \"{0}\" is just a shorthand notation for `{0}: {0}`. It defines a variable \"{0}\".", first_definition.as_str()),
                    ),
                    Hint::info(
                        source_engine,
                        match_value.clone(),
                        format!("The expression to match on is of type \"{match_type}\".")
                    ),
                ],
                help: vec![
                    format!("Variables used in match arm patterns must be unique within a pattern, except in alternatives."),
                    match (*first_definition_is_struct_field, *duplicate_is_struct_field) {
                        (true, true) => format!("Consider declaring a variable with different name for either of the fields. E.g., `{0}: var_{0}`.", first_definition.as_str()),
                        (true, false) | (false, true) => format!("Consider declaring a variable for the field \"{0}\" (e.g., `{0}: var_{0}`), or renaming the variable \"{0}\".", first_definition.as_str()),
                        (false, false) => "Consider renaming either of the variables.".to_string(),
                    },
                ],
            },
            MatchArmVariableMismatchedType { match_value, match_type, variable, first_definition, expected, received } => Diagnostic {
                reason: Some(Reason::new(code(1), "Match pattern variable has mismatched type".to_string())),
                issue: Issue::error(
                    source_engine,
                    variable.span(),
                    format!("Variable \"{variable}\" is expected to be of type \"{expected}\", but is \"{received}\".")
                ),
                hints: vec![
                    Hint::info(
                        source_engine,
                        first_definition.clone(),
                        format!("\"{variable}\" is first defined here with type \"{expected}\".")
                    ),
                    Hint::info(
                        source_engine,
                        match_value.clone(),
                        format!("The expression to match on is of type \"{match_type}\".")
                    ),
                ],
                help: vec![
                    format!("In the same match arm, a variable must have the same type in all alternatives."),
                ],
            },
            MatchArmVariableNotDefinedInAllAlternatives { match_value, match_type, variable, missing_in_alternatives} => Diagnostic {
                reason: Some(Reason::new(code(1), "Match pattern variable is not defined in all alternatives".to_string())),
                issue: Issue::error(
                    source_engine,
                    variable.span(),
                    format!("Variable \"{variable}\" is not defined in all alternatives.")
                ),
                hints: {
                    let mut hints = vec![
                        Hint::info(
                            source_engine,
                            match_value.clone(),
                            format!("The expression to match on is of type \"{match_type}\".")
                        ),
                    ];

                    for (i, alternative) in missing_in_alternatives.iter().enumerate() {
                        hints.push(
                            Hint::info(
                                source_engine,
                                alternative.clone(),
                                format!("\"{variable}\" is {}missing in this alternative.", if i != 0 { "also " } else { "" }),
                            )
                        )
                    }

                    hints
                },
                help: vec![
                    format!("Consider removing the variable \"{variable}\" altogether, or adding it to all alternatives."),
                ],
            },
            MatchStructPatternMissingFields { missing_fields, missing_fields_are_public, struct_name, struct_decl_span, total_number_of_fields, span } => Diagnostic {
                reason: Some(Reason::new(code(1), "Struct pattern has missing fields".to_string())),
                issue: Issue::error(
                    source_engine,
                    span.clone(),
                    format!("Struct pattern is missing the {}field{} {}.",
                        if *missing_fields_are_public { "public " } else { "" },
                        plural_s(missing_fields.len()),
                        sequence_to_str(missing_fields, Enclosing::DoubleQuote, 2)
                    )
                ),
                hints: vec![
                    Hint::help(
                        source_engine,
                        span.clone(),
                        "Struct pattern must either contain or ignore each struct field.".to_string()
                    ),
                    Hint::info(
                        source_engine,
                        struct_decl_span.clone(),
                        format!("Struct \"{struct_name}\" is declared here, and has {} field{}.",
                            number_to_str(*total_number_of_fields),
                            plural_s(*total_number_of_fields),
                        )
                    ),
                ],
                help: vec![
                    // Consider ignoring the field "x_1" by using the `_` pattern: `x_1: _`.
                    //  or
                    // Consider ignoring individual fields by using the `_` pattern. E.g, `x_1: _`.
                    format!("Consider ignoring {} field{} {}by using the `_` pattern{} `{}: _`.",
                        singular_plural(missing_fields.len(), "the", "individual"),
                        plural_s(missing_fields.len()),
                        singular_plural(missing_fields.len(), &format!("\"{}\" ", missing_fields[0]), ""),
                        singular_plural(missing_fields.len(), ":", ". E.g.,"),
                        missing_fields[0]
                    ),
                    "Alternatively, consider ignoring all the missing fields by ending the struct pattern with `..`.".to_string(),
                ],
            },
            MatchStructPatternMustIgnorePrivateFields { private_fields, struct_name, struct_decl_span, all_fields_are_private, span } => Diagnostic {
                reason: Some(Reason::new(code(1), "Struct pattern must ignore inaccessible private fields".to_string())),
                issue: Issue::error(
                    source_engine,
                    span.clone(),
                    format!("Struct pattern must ignore inaccessible private field{} {}.",
                        plural_s(private_fields.len()),
                        sequence_to_str(private_fields, Enclosing::DoubleQuote, 2)
                    )
                ),
                hints: vec![
                    Hint::help(
                        source_engine,
                        span.clone(),
                        format!("To ignore the private field{}, end the struct pattern with `..`.",
                            plural_s(private_fields.len()),
                        )
                    ),
                    Hint::info(
                        source_engine,
                        struct_decl_span.clone(),
                        format!("Struct \"{struct_name}\" is declared here, and has {}.",
                            if *all_fields_are_private {
                                "all private fields".to_string()
                            } else {
                                format!("private field{} {}",
                                    plural_s(private_fields.len()),
                                    sequence_to_str(private_fields, Enclosing::DoubleQuote, 2)
                                )
                            }
                        )
                    ),
                ],
                help: vec![],
            },
            TraitNotImportedAtFunctionApplication { trait_name, function_name, function_call_site_span, trait_constraint_span, trait_candidates } => {
                // Make candidates order deterministic.
                let mut trait_candidates = trait_candidates.clone();
                trait_candidates.sort();
                let trait_candidates = &trait_candidates; // Remove mutability.

                Diagnostic {
                    reason: Some(Reason::new(code(1), "Trait is not imported".to_string())),
                    issue: Issue::error(
                        source_engine,
                        function_call_site_span.clone(),
                        format!(
                            "Trait \"{trait_name}\" is not imported {}when calling \"{function_name}\".",
                            get_file_name(source_engine, function_call_site_span.source_id())
                                .map_or("".to_string(), |file_name| format!("into \"{file_name}\" "))
                        )
                    ),
                    hints: {
                        let mut hints = vec![
                            Hint::help(
                                source_engine,
                                function_call_site_span.clone(),
                                format!("This import is needed because \"{function_name}\" requires \"{trait_name}\" in one of its trait constraints.")
                            ),
                            Hint::info(
                                source_engine,
                                trait_constraint_span.clone(),
                                format!("In the definition of \"{function_name}\", \"{trait_name}\" is used in this trait constraint.")
                            ),
                        ];

                        match trait_candidates.len() {
                            // If no candidates are found, that means that an alias was used in the trait constraint definition.
                            // The way how constraint checking works now, the trait will not be found when we try to check if
                            // the trait constraints are satisfied for type, and we will never end up in this case here.
                            // So we will simply ignore it.
                            0 => (),
                            // The most common case. Exactly one known trait with the given name.
                            1 => hints.push(Hint::help(
                                    source_engine,
                                    function_call_site_span.clone(),
                                    format!(
                                        "Import the \"{trait_name}\" trait {}by using: `use {};`.",
                                        get_file_name(source_engine, function_call_site_span.source_id())
                                            .map_or("".to_string(), |file_name| format!("into \"{file_name}\" ")),
                                        trait_candidates[0]
                                    )
                                )),
                            // Unlikely (for now) case of having several traits with the same name.
                            _ => hints.push(Hint::help(
                                    source_engine,
                                    function_call_site_span.clone(),
                                    format!(
                                        "To import the proper \"{trait_name}\" {}follow the detailed instructions given below.",
                                        get_file_name(source_engine, function_call_site_span.source_id())
                                            .map_or("".to_string(), |file_name| format!("into \"{file_name}\" "))
                                    )
                                )),
                        }

                        hints
                    },
                    help: {
                        let mut help = vec![];

                        if trait_candidates.len() > 1 {
                            help.push(format!("There are these {} traits with the name \"{trait_name}\" available in the modules:", number_to_str(trait_candidates.len())));
                            for trait_candidate in trait_candidates.iter() {
                                help.push(format!("{}- {trait_candidate}", Indent::Single));
                            }
                            help.push("To import the proper one follow these steps:".to_string());
                            help.push(format!(
                                "{}1. Look at the definition of the \"{function_name}\"{}.",
                                    Indent::Single,
                                    get_file_name(source_engine, trait_constraint_span.source_id())
                                        .map_or("".to_string(), |file_name| format!(" in the \"{file_name}\""))
                            ));
                            help.push(format!(
                                "{}2. Detect which exact \"{trait_name}\" is used in the trait constraint in the \"{function_name}\".",
                                Indent::Single
                            ));
                            help.push(format!(
                                "{}3. Import that \"{trait_name}\"{}.",
                                Indent::Single,
                                get_file_name(source_engine, function_call_site_span.source_id())
                                    .map_or("".to_string(), |file_name| format!(" into \"{file_name}\""))
                            ));
                            help.push(format!("{} E.g., assuming it is the first one on the list, use: `use {};`", Indent::Double, trait_candidates[0]));
                        }

                        help
                    },
                }
            },
            // TODO-IG: Extend error messages to pointers, once typed pointers are defined and can be dereferenced.
            ExpressionCannotBeDereferenced { expression_type, span } => Diagnostic {
                reason: Some(Reason::new(code(1), "Expression cannot be dereferenced".to_string())),
                issue: Issue::error(
                    source_engine,
                    span.clone(),
                    format!("This expression cannot be dereferenced, because it is of type \"{expression_type}\", which is not a reference type.")
                ),
                hints: vec![
                    Hint::help(
                        source_engine,
                        span.clone(),
                        "In Sway, only references can be dereferenced.".to_string()
                    ),
                    Hint::help(
                        source_engine,
                        span.clone(),
                        "Are you missing the reference operator `&` somewhere in the code?".to_string()
                    ),
                ],
                help: vec![],
            },
            StructInstantiationMissingFields { field_names, struct_name, span, struct_decl_span, total_number_of_fields } => Diagnostic {
                reason: Some(Reason::new(code(1), "Struct instantiation has missing fields".to_string())),
                issue: Issue::error(
                    source_engine,
                    span.clone(),
                    format!("Instantiation of the struct \"{struct_name}\" is missing the field{} {}.",
                            plural_s(field_names.len()),
                            sequence_to_str(field_names, Enclosing::DoubleQuote, 2)
                        )
                ),
                hints: vec![
                    Hint::help(
                        source_engine,
                        span.clone(),
                        "Struct instantiation must initialize all the fields of the struct.".to_string()
                    ),
                    Hint::info(
                        source_engine,
                        struct_decl_span.clone(),
                        format!("Struct \"{struct_name}\" is declared here, and has {} field{}.",
                            number_to_str(*total_number_of_fields),
                            plural_s(*total_number_of_fields),
                        )
                    ),
                ],
                help: vec![],
            },
            StructCannotBeInstantiated { struct_name, span, struct_decl_span, private_fields, constructors, all_fields_are_private, is_in_storage_declaration, struct_can_be_changed } => Diagnostic {
                reason: Some(Reason::new(code(1), "Struct cannot be instantiated due to inaccessible private fields".to_string())),
                issue: Issue::error(
                    source_engine,
                    span.clone(),
                    format!("\"{struct_name}\" cannot be {}instantiated in this {}, due to {}inaccessible private field{}.",
                        if *is_in_storage_declaration { "" } else { "directly " },
                        if *is_in_storage_declaration { "storage declaration" } else { "module" },
                        singular_plural(private_fields.len(), "an ", ""),
                        plural_s(private_fields.len())
                    )
                ),
                hints: vec![
                    Hint::help(
                        source_engine,
                        span.clone(),
                        format!("Inaccessible field{} {} {}.",
                            plural_s(private_fields.len()),
                            is_are(private_fields.len()),
                            sequence_to_str(private_fields, Enclosing::DoubleQuote, 5)
                        )
                    ),
                    Hint::help(
                        source_engine,
                        span.clone(),
                        if *is_in_storage_declaration {
                            "Structs with private fields can be instantiated in storage declarations only if they are declared in the same module as the storage.".to_string()
                        } else {
                            "Structs with private fields can be instantiated only within the module in which they are declared.".to_string()
                        }
                    ),
                    if *is_in_storage_declaration {
                        Hint::help(
                            source_engine,
                            span.clone(),
                            "They can still be initialized in storage declarations if they have public constructors that evaluate to a constant.".to_string()
                        )
                    } else {
                        Hint::none()
                    },
                    if *is_in_storage_declaration {
                        Hint::help(
                            source_engine,
                            span.clone(),
                            "They can always be stored in storage by using the `read` and `write` functions provided in the `std::storage::storage_api`.".to_string()
                        )
                    } else {
                        Hint::none()
                    },
                    if !*is_in_storage_declaration && !constructors.is_empty() {
                        Hint::help(
                            source_engine,
                            span.clone(),
                            format!("\"{struct_name}\" can be instantiated via public constructors suggested below.")
                        )
                    } else {
                        Hint::none()
                    },
                    Hint::info(
                        source_engine,
                        struct_decl_span.clone(),
                        format!("Struct \"{struct_name}\" is declared here, and has {}.",
                            if *all_fields_are_private {
                                "all private fields".to_string()
                            } else {
                                format!("private field{} {}",
                                    plural_s(private_fields.len()),
                                    sequence_to_str(private_fields, Enclosing::DoubleQuote, 2)
                                )
                            }
                        )
                    ),
                ],
                help: {
                    let mut help = vec![];

                    if *is_in_storage_declaration {
                        help.push(format!("Consider initializing \"{struct_name}\" by finding an available constructor that evaluates to a constant{}.",
                            if *struct_can_be_changed {
                                ", or implement a new one"
                            } else {
                                ""
                            }
                        ));

                        if !constructors.is_empty() {
                            help.push("Check these already available constructors. They might evaluate to a constant:".to_string());
                            // We always expect a very few candidates here. So let's list all of them by using `usize::MAX`.
                            for constructor in sequence_to_list(constructors, Indent::Single, usize::MAX) {
                                help.push(constructor);
                            }
                        };

                        help.push(Diagnostic::help_empty_line());

                        help.push(format!("Or you can always store instances of \"{struct_name}\" in the contract storage, by using the `std::storage::storage_api`:"));
                        help.push(format!("{}use std::storage::storage_api::{{read, write}};", Indent::Single));
                        help.push(format!("{}write(STORAGE_KEY, 0, my_{});", Indent::Single, to_snake_case(struct_name.as_str())));
                        help.push(format!("{}let my_{}_option = read::<{struct_name}>(STORAGE_KEY, 0);", Indent::Single, to_snake_case(struct_name.as_str())));
                    }
                    else if !constructors.is_empty() {
                        help.push(format!("Consider instantiating \"{struct_name}\" by using one of the available constructors{}:",
                            if *struct_can_be_changed {
                                ", or implement a new one"
                            } else {
                                ""
                            }
                        ));
                        for constructor in sequence_to_list(constructors, Indent::Single, 5) {
                            help.push(constructor);
                        }
                    }

                    if *struct_can_be_changed {
                        if *is_in_storage_declaration || !constructors.is_empty() {
                            help.push(Diagnostic::help_empty_line());
                        }

                        if !*is_in_storage_declaration && constructors.is_empty() {
                            help.push(format!("Consider implementing a public constructor for \"{struct_name}\"."));
                        };

                        help.push(
                            // Alternatively, consider declaring the field "f" as public in "Struct": `pub f: ...,`.
                            //  or
                            // Alternatively, consider declaring the fields "f" and "g" as public in "Struct": `pub <field>: ...,`.
                            //  or
                            // Alternatively, consider declaring all fields as public in "Struct": `pub <field>: ...,`.
                            format!("Alternatively, consider declaring {} as public in \"{struct_name}\": `pub {}: ...,`.",
                                if *all_fields_are_private {
                                    "all fields".to_string()
                                } else {
                                    format!("{} {}",
                                        singular_plural(private_fields.len(), "the field", "the fields"),
                                        sequence_to_str(private_fields, Enclosing::DoubleQuote, 2)
                                    )
                                },
                                if *all_fields_are_private {
                                    "<field>".to_string()
                                } else {
                                    match &private_fields[..] {
                                        [field] => format!("{field}"),
                                        _ => "<field>".to_string(),
                                    }
                                },
                            )
                        )
                    };

                    help
                }
            },
            StructFieldIsPrivate { field_name, struct_name, field_decl_span, struct_can_be_changed, usage_context } => Diagnostic {
                reason: Some(Reason::new(code(1), "Private struct field is inaccessible".to_string())),
                issue: Issue::error(
                    source_engine,
                    field_name.span(),
                    format!("Private field \"{field_name}\" {}is inaccessible in this module.",
                        match usage_context {
                            StructInstantiation { .. } | StorageDeclaration { .. } | PatternMatching { .. } => "".to_string(),
                            StorageAccess | StructFieldAccess => format!("of the struct \"{struct_name}\" "),
                        }
                    )
                ),
                hints: vec![
                    Hint::help(
                        source_engine,
                        field_name.span(),
                        format!("Private fields can only be {} within the module in which their struct is declared.",
                            match usage_context {
                                StructInstantiation { .. } | StorageDeclaration { .. } => "initialized",
                                StorageAccess | StructFieldAccess => "accessed",
                                PatternMatching { .. } => "matched",
                            }
                        )
                    ),
                    if matches!(usage_context, PatternMatching { has_rest_pattern } if !has_rest_pattern) {
                        Hint::help(
                            source_engine,
                            field_name.span(),
                            "Otherwise, they must be ignored by ending the struct pattern with `..`.".to_string()
                        )
                    } else {
                        Hint::none()
                    },
                    Hint::info(
                        source_engine,
                        field_decl_span.clone(),
                        format!("Field \"{field_name}\" {}is declared here as private.",
                            match usage_context {
                                StructInstantiation { .. } | StorageDeclaration { .. } | PatternMatching { .. } => format!("of the struct \"{struct_name}\" "),
                                StorageAccess | StructFieldAccess => "".to_string(),
                            }
                        )
                    ),
                ],
                help: vec![
                    if matches!(usage_context, PatternMatching { has_rest_pattern } if !has_rest_pattern) {
                        format!("Consider removing the field \"{field_name}\" from the struct pattern, and ending the pattern with `..`.")
                    } else {
                        Diagnostic::help_none()
                    },
                    if *struct_can_be_changed {
                        match usage_context {
                            StorageAccess | StructFieldAccess | PatternMatching { .. } => {
                                format!("{} declaring the field \"{field_name}\" as public in \"{struct_name}\": `pub {field_name}: ...,`.",
                                    if matches!(usage_context, PatternMatching { has_rest_pattern } if !has_rest_pattern) {
                                        "Alternatively, consider"
                                    } else {
                                        "Consider"
                                    }
                                )
                            },
                            // For all other usages, detailed instructions are already given in specific messages.
                            _ => Diagnostic::help_none(),
                        }
                    } else {
                        Diagnostic::help_none()
                    },
                ],
            },
            StructFieldDoesNotExist { field_name, available_fields, is_public_struct_access, struct_name, struct_decl_span, struct_is_empty, usage_context } => Diagnostic {
                reason: Some(Reason::new(code(1), "Struct field does not exist".to_string())),
                issue: Issue::error(
                    source_engine,
                    field_name.span(),
                    format!("Field \"{field_name}\" does not exist in the struct \"{struct_name}\".")
                ),
                hints: {
                    let public = if *is_public_struct_access { "public " } else { "" };

                    let (hint, show_struct_decl) = if *struct_is_empty {
                        (Some(format!("\"{struct_name}\" is an empty struct. It doesn't have any fields.")), false)
                    }
                    // If the struct anyhow cannot be instantiated (in the struct instantiation or storage declaration),
                    // we don't show any additional hints.
                    // Showing any available fields would be inconsistent and misleading, because they anyhow cannot be used.
                    // Besides, "Struct cannot be instantiated" error will provide all the explanations and suggestions.
                    else if (matches!(usage_context, StorageAccess) && *is_public_struct_access && available_fields.is_empty())
                            ||
                            (matches!(usage_context, StructInstantiation { struct_can_be_instantiated: false } | StorageDeclaration { struct_can_be_instantiated: false })) {
                        // If the struct anyhow cannot be instantiated in the storage, don't show any additional hint
                        // if there is an attempt to access a non existing field of such non-instantiable struct.
                        //   or
                        // Likewise, if we are in the struct instantiation or storage declaration and the struct
                        // cannot be instantiated.
                        (None, false)
                    } else if !available_fields.is_empty() {
                        // In all other cases, show the available fields.
                        const NUM_OF_FIELDS_TO_DISPLAY: usize = 4;
                        match &available_fields[..] {
                            [field] => (Some(format!("Only available {public}field is \"{field}\".")), false),
                            _ => (Some(format!("Available {public}fields are {}.", sequence_to_str(available_fields, Enclosing::DoubleQuote, NUM_OF_FIELDS_TO_DISPLAY))),
                                    available_fields.len() > NUM_OF_FIELDS_TO_DISPLAY
                                ),
                        }
                    }
                    else {
                        (None, false)
                    };

                    let mut hints = vec![];

                    if let Some(hint) = hint {
                        hints.push(Hint::help(source_engine, field_name.span(), hint));
                    };

                    if show_struct_decl {
                        hints.push(Hint::info(
                            source_engine,
                            struct_decl_span.clone(),
                            format!("Struct \"{struct_name}\" is declared here, and has {} {public}fields.",
                                number_to_str(available_fields.len())
                            )
                        ));
                    }

                    hints
                },
                help: vec![],
            },
            StructFieldDuplicated { field_name, duplicate } => Diagnostic {
                reason: Some(Reason::new(code(1), "Struct field has multiple definitions".to_string())),
                issue: Issue::error(
                    source_engine,
                    field_name.span(),
                    format!("Field \"{field_name}\" has multiple definitions.")
                ),
                hints: {
                    vec![
                        Hint::info(
                            source_engine,
                            duplicate.span(),
                            "Field definition duplicated here.".into(),
                        )
                   ]
                },
                help: vec![],
            },
            NotIndexable { actually, span } => Diagnostic {
                reason: Some(Reason::new(code(1), "Type is not indexable".to_string())),
                issue: Issue::error(
                    source_engine,
                    span.clone(),
                    format!("This expression has type \"{actually}\", which is not an indexable type.")
                ),
                hints: vec![],
                help: vec![
                    "Index operator `[]` can be used only on indexable types.".to_string(),
                    "In Sway, indexable types are:".to_string(),
                    format!("{}- arrays. E.g., `[u64;3]`.", Indent::Single),
                    format!("{}- references, direct or indirect, to arrays. E.g., `&[u64;3]` or `&&&[u64;3]`.", Indent::Single),
                ],
            },
            FieldAccessOnNonStruct { actually, storage_variable, field_name, span } => Diagnostic {
                reason: Some(Reason::new(code(1), "Field access requires a struct".to_string())),
                issue: Issue::error(
                    source_engine,
                    span.clone(),
                    format!("{} has type \"{actually}\", which is not a struct{}.",
                        if let Some(storage_variable) = storage_variable {
                            format!("Storage variable \"{storage_variable}\"")
                        } else {
                            "This expression".to_string()
                        },
                        if storage_variable.is_some() {
                            ""
                        } else {
                            " or a reference to a struct"
                        }
                    )
                ),
                hints: vec![
                    Hint::info(
                        source_engine,
                        field_name.span(),
                        format!("Field access happens here, on \"{field_name}\".")
                    )
                ],
                help: if storage_variable.is_some() {
                    vec![
                        "Fields can only be accessed on storage variables that are structs.".to_string(),
                    ]
                } else {
                    vec![
                        "In Sway, fields can be accessed on:".to_string(),
                        format!("{}- structs. E.g., `my_struct.field`.", Indent::Single),
                        format!("{}- references, direct or indirect, to structs. E.g., `(&my_struct).field` or `(&&&my_struct).field`.", Indent::Single),
                    ]
                }
            },
	    SymbolWithMultipleBindings { name, paths, span } => Diagnostic {
		reason: Some(Reason::new(code(1), "Multiple bindings for symbol in this scope".to_string())),
		issue: Issue::error(
		    source_engine,
		    span.clone(),
		    format!("The following paths are all valid bindings for symbol \"{}\": {}", name, paths.iter().map(|path| format!("{path}::{name}")).collect::<Vec<_>>().join(", ")),
		),
		hints: paths.iter().map(|path| Hint::info(source_engine, Span::dummy(), format!("{path}::{}", name.as_str()))).collect(),
		help: vec![format!("Consider using a fully qualified name, e.g., {}::{}", paths[0], name.as_str())],
	    },
            StorageFieldDoesNotExist { field_name, available_fields, storage_decl_span } => Diagnostic {
                reason: Some(Reason::new(code(1), "Storage field does not exist".to_string())),
                issue: Issue::error(
                    source_engine,
                    field_name.span(),
                    format!("Storage field \"{field_name}\" does not exist in the storage.")
                ),
                hints: {
                    let (hint, show_storage_decl) = if available_fields.is_empty() {
                        ("The storage is empty. It doesn't have any fields.".to_string(), false)
                    } else {
                        const NUM_OF_FIELDS_TO_DISPLAY: usize = 4;
                        let display_fields = available_fields.iter().map(|(path, field_name)| {
                            let path = path.iter().map(ToString::to_string).collect::<Vec<_>>().join("::");
                            if path.is_empty() {
                                format!("storage.{field_name}")
                            } else {
                                format!("storage::{path}.{field_name}")
                            }
                        }).collect::<Vec<_>>();
                        match &display_fields[..] {
                            [field] => (format!("Only available storage field is \"{field}\"."), false),
                            _ => (format!("Available storage fields are {}.", sequence_to_str(&display_fields, Enclosing::DoubleQuote, NUM_OF_FIELDS_TO_DISPLAY)),
                                    available_fields.len() > NUM_OF_FIELDS_TO_DISPLAY
                                ),
                        }
                    };

                    let mut hints = vec![];

                    hints.push(Hint::help(source_engine, field_name.span(), hint));

                    if show_storage_decl {
                        hints.push(Hint::info(
                            source_engine,
                            storage_decl_span.clone(),
                            format!("Storage is declared here, and has {} fields.",
                                number_to_str(available_fields.len())
                            )
                        ));
                    }

                    hints
                },
                help: vec![],
            },
            TupleIndexOutOfBounds { index, count, tuple_type, span, prefix_span } => Diagnostic {
                reason: Some(Reason::new(code(1), "Tuple index is out of bounds".to_string())),
                issue: Issue::error(
                    source_engine,
                    span.clone(),
                    format!("Tuple index {index} is out of bounds. The tuple has only {count} element{}.", plural_s(*count))
                ),
                hints: vec![
                    Hint::info(
                        source_engine,
                        prefix_span.clone(),
                        format!("This expression has type \"{tuple_type}\".")
                    ),
                ],
                help: vec![],
            },
            TupleElementAccessOnNonTuple { actually, span, index, index_span } => Diagnostic {
                reason: Some(Reason::new(code(1), "Tuple element access requires a tuple".to_string())),
                issue: Issue::error(
                    source_engine,
                    span.clone(),
                    format!("This expression has type \"{actually}\", which is not a tuple or a reference to a tuple.")
                ),
                hints: vec![
                    Hint::info(
                        source_engine,
                        index_span.clone(),
                        format!("Tuple element access happens here, on the index {index}.")
                    )
                ],
                help: vec![
                    "In Sway, tuple elements can be accessed on:".to_string(),
                    format!("{}- tuples. E.g., `my_tuple.1`.", Indent::Single),
                    format!("{}- references, direct or indirect, to tuples. E.g., `(&my_tuple).1` or `(&&&my_tuple).1`.", Indent::Single),
                ],
            },
            RefMutCannotReferenceConstant { constant, span } => Diagnostic {
                reason: Some(Reason::new(code(1), "References to mutable values cannot reference constants".to_string())),
                issue: Issue::error(
                    source_engine,
                    span.clone(),
                    format!("\"{constant}\" is a constant. `&mut` cannot reference constants.")
                ),
                hints: vec![],
                help: vec![
                    "Consider:".to_string(),
                    format!("{}- taking a reference without `mut`: `&{constant}`.", Indent::Single),
                    format!("{}- referencing a mutable copy of the constant, by returning it from a block: `&mut {{ {constant} }}`.", Indent::Single)
                ],
            },
            RefMutCannotReferenceImmutableVariable { decl_name, span } => Diagnostic {
                reason: Some(Reason::new(code(1), "References to mutable values cannot reference immutable variables".to_string())),
                issue: Issue::error(
                    source_engine,
                    span.clone(),
                    format!("\"{decl_name}\" is an immutable variable. `&mut` cannot reference immutable variables.")
                ),
                hints: vec![
                    Hint::info(
                        source_engine,
                        decl_name.span(),
                        format!("Variable \"{decl_name}\" is declared here as immutable.")
                    ),
                ],
                help: vec![
                    "Consider:".to_string(),
                    // TODO-IG: Once desugaring information becomes available, do not show the first suggestion if declaring variable as mutable is not possible.
                    format!("{}- declaring \"{decl_name}\" as mutable.", Indent::Single),
                    format!("{}- taking a reference without `mut`: `&{decl_name}`.", Indent::Single),
                    format!("{}- referencing a mutable copy of \"{decl_name}\", by returning it from a block: `&mut {{ {decl_name} }}`.", Indent::Single)
                ],
            },
            ConflictingImplsForTraitAndType { trait_name, type_implementing_for, existing_impl_span, second_impl_span } => Diagnostic {
                reason: Some(Reason::new(code(1), "Trait is already implemented for type".to_string())),
                issue: Issue::error(
                    source_engine,
                    second_impl_span.clone(),
                    format!("Trait \"{trait_name}\" is already implemented for type \"{type_implementing_for}\".")
                ),
                hints: vec![
                    Hint::info(
                        source_engine,
                        existing_impl_span.clone(),
                        format!("This is the already existing implementation of \"{}\" for \"{type_implementing_for}\".",
                            call_path_suffix_with_args(trait_name)
                        )
                    ),
                ],
                help: vec![
                    "In Sway, there can be at most one implementation of a trait for any given type.".to_string(),
                    "This property is called \"trait coherence\".".to_string(),
                ],
            },
            AssignmentToNonMutableVariable { lhs_span, decl_name } => Diagnostic {
                reason: Some(Reason::new(code(1), "Immutable variables cannot be assigned to".to_string())),
                issue: Issue::error(
                    source_engine,
                    lhs_span.clone(),
                    // "x" cannot be assigned to, because it is an immutable variable.
                    //  or
                    // This expression cannot be assigned to, because "x" is an immutable variable.
                    format!("{} cannot be assigned to, because {} is an immutable variable.",
                        if decl_name.as_str() == lhs_span.as_str() { // We have just a single variable in the expression.
                            format!("\"{decl_name}\"")
                        } else {
                            "This expression".to_string()
                        },
                        if decl_name.as_str() == lhs_span.as_str() {
                            "it".to_string()
                        } else {
                            format!("\"{decl_name}\"")
                        }
                    )
                ),
                hints: vec![
                    Hint::info(
                        source_engine,
                        decl_name.span(),
                        format!("Variable \"{decl_name}\" is declared here as immutable.")
                    ),
                ],
                help: vec![
                    // TODO-IG: Once desugaring information becomes available, do not show this suggestion if declaring variable as mutable is not possible.
                    format!("Consider declaring \"{decl_name}\" as mutable."),
                ],
            },
            AssignmentToConstantOrConfigurable { lhs_span, is_configurable, decl_name } => Diagnostic {
                reason: Some(Reason::new(code(1), format!("{} cannot be assigned to",
                    if *is_configurable {
                        "Configurables"
                    } else {
                        "Constants"
                    }
                ))),
                issue: Issue::error(
                    source_engine,
                    lhs_span.clone(),
                    // "x" cannot be assigned to, because it is a constant/configurable.
                    //  or
                    // This expression cannot be assigned to, because "x" is a constant/configurable.
                    format!("{} cannot be assigned to, because {} is a {}.",
                        if decl_name.as_str() == lhs_span.as_str() { // We have just the constant in the expression.
                            format!("\"{decl_name}\"")
                        } else {
                            "This expression".to_string()
                        },
                        if decl_name.as_str() == lhs_span.as_str() {
                            "it".to_string()
                        } else {
                            format!("\"{decl_name}\"")
                        },
                        if *is_configurable {
                            "configurable"
                        } else {
                            "constant"
                        }
                    )
                ),
                hints: vec![
                    Hint::info(
                        source_engine,
                        decl_name.span(),
                        format!("{} \"{decl_name}\" is declared here.",
                            if *is_configurable {
                                "Configurable"
                            } else {
                                "Constant"
                            }
                        )
                    ),
                ],
                help: vec![],
            },
            DeclAssignmentTargetCannotBeAssignedTo { decl_name, decl_friendly_type_name, lhs_span } => Diagnostic {
                reason: Some(Reason::new(code(1), "Assignment target cannot be assigned to".to_string())),
                issue: Issue::error(
                    source_engine,
                    lhs_span.clone(),
                    // "x" cannot be assigned to, because it is a trait/function/ etc and not a mutable variable.
                    //  or
                    // This cannot be assigned to, because "x" is a trait/function/ etc and not a mutable variable.
                    format!("{} cannot be assigned to, because {} is {}{decl_friendly_type_name} and not a mutable variable.",
                        match decl_name {
                            Some(decl_name) if decl_name.as_str() == lhs_span.as_str() => // We have just the decl name in the expression.
                                format!("\"{decl_name}\""),
                            _ => "This".to_string(),
                        },
                        match decl_name {
                            Some(decl_name) if decl_name.as_str() == lhs_span.as_str() =>
                                "it".to_string(),
                            Some(decl_name) => format!("\"{}\"", decl_name.as_str()),
                            _ => "it".to_string(),
                        },
                        a_or_an(decl_friendly_type_name)
                    )
                ),
                hints: vec![
                    match decl_name {
                        Some(decl_name) => Hint::info(
                            source_engine,
                            decl_name.span(),
                            format!("{} \"{decl_name}\" is declared here.", ascii_sentence_case(&decl_friendly_type_name.to_string()))
                        ),
                        _ => Hint::none(),
                    }
                ],
                help: vec![],
            },
            AssignmentViaNonMutableReference { decl_reference_name, decl_reference_rhs, decl_reference_type, span } => Diagnostic {
                reason: Some(Reason::new(code(1), "Reference is not a reference to a mutable value (`&mut`)".to_string())),
                issue: Issue::error(
                    source_engine,
                    span.clone(),
                    // This reference expression is not a reference to a mutable value (`&mut`).
                    //  or
                    // Reference "ref_xyz" is not a reference to a mutable value (`&mut`).
                    format!("{} is not a reference to a mutable value (`&mut`).",
                        match decl_reference_name {
                            Some(decl_reference_name) => format!("Reference \"{decl_reference_name}\""),
                            _ => "This reference expression".to_string(),
                        }
                    )
                ),
                hints: vec![
                    match decl_reference_name {
                        Some(decl_reference_name) => Hint::info(
                            source_engine,
                            decl_reference_name.span(),
                            format!("Reference \"{decl_reference_name}\" is declared here as a reference to immutable value.")
                        ),
                        _ => Hint::none(),
                    },
                    match decl_reference_rhs {
                        Some(decl_reference_rhs) => Hint::info(
                            source_engine,
                            decl_reference_rhs.clone(),
                            format!("This expression has type \"{decl_reference_type}\" instead of \"&mut {}\".",
                                &decl_reference_type[1..]
                            )
                        ),
                        _ => Hint::info(
                            source_engine,
                            span.clone(),
                            format!("It has type \"{decl_reference_type}\" instead of \"&mut {}\".",
                                &decl_reference_type[1..]
                            )
                        ),
                    },
                    match decl_reference_rhs {
                        Some(decl_reference_rhs) if decl_reference_rhs.as_str().starts_with('&') => Hint::help(
                            source_engine,
                            decl_reference_rhs.clone(),
                            format!("Consider taking here a reference to a mutable value: `&mut {}`.",
                                first_line(decl_reference_rhs.as_str()[1..].trim(), true)
                            )
                        ),
                        _ => Hint::none(),
                    },
                ],
                help: vec![
                    format!("{} dereferenced in assignment targets must {} references to mutable values (`&mut`).",
                        if decl_reference_name.is_some() {
                            "References"
                        } else {
                            "Reference expressions"
                        },
                        if decl_reference_name.is_some() {
                            "be"
                        } else {
                            "result in"
                        }
                    ),
                ],
            },
            Unimplemented { feature, help, span } => Diagnostic {
                reason: Some(Reason::new(code(1), "Used feature is currently not implemented".to_string())),
                issue: Issue::error(
                    source_engine,
                    span.clone(),
                    format!("{feature} is currently not implemented.")
                ),
                hints: vec![],
                help: help.clone(),
            },
            MatchedValueIsNotValid { supported_types_message, span } => Diagnostic {
                reason: Some(Reason::new(code(1), "Matched value is not valid".to_string())),
                issue: Issue::error(
                    source_engine,
                    span.clone(),
                    "This cannot be matched.".to_string()
                ),
                hints: vec![],
                help: {
                    let mut help = vec![];

                    help.push("Matched value must be an expression whose result is of one of the types supported in pattern matching.".to_string());
                    help.push(Diagnostic::help_empty_line());
                    for msg in supported_types_message {
                        help.push(msg.to_string());
                    }

                    help
                }
            },
            TypeIsNotValidAsImplementingFor { invalid_type, trait_name, span } => Diagnostic {
                reason: Some(Reason::new(code(1), "Self type of an impl block is not valid".to_string())),
                issue: Issue::error(
                    source_engine,
                    span.clone(),
                    format!("{invalid_type} is not a valid type in the self type of {} impl block.",
                        match trait_name {
                            Some(_) => "a trait",
                            None => "an",
                        }
                    )
                ),
                hints: vec![
                    if matches!(invalid_type, InvalidImplementingForType::SelfType) {
                        Hint::help(
                            source_engine,
                            span.clone(),
                            format!("Replace {invalid_type} with the actual type that you want to implement for.")
                        )
                    } else {
                        Hint::none()
                    }
                ],
                help: {
                    if matches!(invalid_type, InvalidImplementingForType::Placeholder) {
                        vec![
                            format!("Are you trying to implement {} for any type?",
                                match trait_name {
                                    Some(trait_name) => format!("trait \"{trait_name}\""),
                                    None => "functionality".to_string(),
                                }
                            ),
                            Diagnostic::help_empty_line(),
                            "If so, use generic type parameters instead.".to_string(),
                            "E.g., instead of:".to_string(),
                            // The trait `trait_name` could represent an arbitrary complex trait.
                            // E.g., `with generic arguments, etc. So we don't want to deal
                            // with the complexity of representing it properly
                            // but rather use a simplified but clearly instructive
                            // sample trait name here, `SomeTrait`.
                            // impl _
                            //   or
                            // impl SomeTrait for _
                            format!("{}impl {}_",
                                Indent::Single,
                                match trait_name {
                                    Some(_) => "SomeTrait for ",
                                    None => "",
                                }
                            ),
                            "use:".to_string(),
                            format!("{}impl<T> {}T",
                                Indent::Single,
                                match trait_name {
                                    Some(_) => "SomeTrait for ",
                                    None => "",
                                }
                            ),
                        ]
                    } else {
                        vec![]
                    }
                }
            },
            ModulePathIsNotAnExpression { module_path, span } => Diagnostic {
                reason: Some(Reason::new(code(1), "Module path is not an expression".to_string())),
                issue: Issue::error(
                    source_engine,
                    span.clone(),
                    "This is a module path, and not an expression.".to_string()
                ),
                hints: vec![
                    Hint::help(
                        source_engine,
                        span.clone(),
                        "An expression is expected at this location, but a module path is found.".to_string()
                    ),
                ],
                help: vec![
                    "In expressions, module paths can only be used to fully qualify names with a path.".to_string(),
                    format!("E.g., `{module_path}::SOME_CONSTANT` or `{module_path}::some_function()`."),
                ]
            },
            Parse { error } => {
                match &error.kind {
                    ParseErrorKind::UnassignableExpression { erroneous_expression_kind, erroneous_expression_span } => Diagnostic {
                        reason: Some(Reason::new(code(1), "Expression cannot be assigned to".to_string())),
                        // A bit of a special handling for parentheses, because they are the only
                        // expression kind whose friendly name is in plural. Having it in singular
                        // or without this simple special handling gives very odd sounding sentences.
                        // Therefore, just a bit of a special handling.
                        issue: Issue::error(
                            source_engine,
                            error.span.clone(),
                            format!("This expression cannot be assigned to, because it {} {}{}.",
                                if &error.span == erroneous_expression_span { // If the whole expression is erroneous.
                                    "is"
                                } else {
                                    "contains"
                                },
                                if *erroneous_expression_kind == "parentheses" {
                                    ""
                                } else {
                                    a_or_an(erroneous_expression_kind)
                                },
                                erroneous_expression_kind
                            )
                        ),
                        hints: vec![
                            if &error.span != erroneous_expression_span {
                                Hint::info(
                                    source_engine,
                                    erroneous_expression_span.clone(),
                                    format!("{} the contained {erroneous_expression_kind}.",
                                        if *erroneous_expression_kind == "parentheses" {
                                            "These are"
                                        } else {
                                            "This is"
                                        }
                                    )
                                )
                            } else {
                                Hint::none()
                            },
                        ],
                        help: vec![
                            format!("{} cannot be {}an assignment target.",
                                ascii_sentence_case(&erroneous_expression_kind.to_string()),
                                if &error.span == erroneous_expression_span {
                                    ""
                                } else {
                                    "a part of "
                                }
                            ),
                            Diagnostic::help_empty_line(),
                            "In Sway, assignment targets must be one of the following:".to_string(),
                            format!("{}- Expressions starting with a mutable variable, optionally having", Indent::Single),
                            format!("{}  array or tuple element accesses, struct field accesses,", Indent::Single),
                            format!("{}  or arbitrary combinations of those.", Indent::Single),
                            format!("{}  E.g., `mut_var` or `mut_struct.field` or `mut_array[x + y].field.1`.", Indent::Single),
                            Diagnostic::help_empty_line(),
                            format!("{}- Dereferencing of an arbitrary expression that results", Indent::Single),
                            format!("{}  in a reference to a mutable value.", Indent::Single),
                            format!("{}  E.g., `*ref_to_mutable_value` or `*max_mut(&mut x, &mut y)`.", Indent::Single),
                        ]
                    },
                    ParseErrorKind::UnrecognizedOpCode { known_op_codes } => Diagnostic {
                        reason: Some(Reason::new(code(1), "Assembly instruction is unknown".to_string())),
                        issue: Issue::error(
                            source_engine,
                            error.span.clone(),
                            format!("\"{}\" is not a known assembly instruction.",
                                error.span.as_str()
                            )
                        ),
                        hints: {
                            let suggestions = &did_you_mean(error.span.as_str(), known_op_codes.iter(), 2);
                            if suggestions.is_empty() {
                                vec![]
                            } else {
                                vec![
                                    Hint::help(
                                        source_engine,
                                        error.span.clone(),
                                        format!("Did you mean {}?", sequence_to_str_or(suggestions, Enclosing::DoubleQuote, 2))
                                    ),
                                ]
                            }
                        },
                        help: vec![]
                    },
                    _ => Diagnostic {
                                // TODO: Temporary we use self here to achieve backward compatibility.
                                //       In general, self must not be used and will not be used once we
                                //       switch to our own #[error] macro. All the values for the formatting
                                //       of a diagnostic must come from the enum variant parameters.
                                issue: Issue::error(source_engine, self.span(), format!("{}", self)),
                                ..Default::default()
                        },
                }
            },
            ConfigurableMissingAbiDecodeInPlace { span } => Diagnostic {
                reason: Some(Reason::new(code(1), "Configurables need a function named \"abi_decode_in_place\" to be in scope".to_string())),
                issue: Issue::error(
                    source_engine,
                    span.clone(),
                    String::new()
                ),
                hints: vec![],
                help: vec![
                    "The function \"abi_decode_in_place\" is usually defined in the standard library module \"core::codec\".".into(),
                    "Verify that you are using a version of the \"core\" standard library that contains this function.".into(),
                ],
            },
            StorageAccessMismatched { span, is_pure, suggested_attributes, storage_access_violations } => Diagnostic {
                // Pure function cannot access storage
                //   or
                // Storage read-only function cannot write to storage
                reason: Some(Reason::new(code(1), format!("{} function cannot {} storage",
                    if *is_pure {
                        "Pure"
                    } else {
                        "Storage read-only"
                    },
                    if *is_pure {
                        "access"
                    } else {
                        "write to"
                    }
                ))),
                issue: Issue::error(
                    source_engine,
                    span.clone(),
                    format!("Function \"{}\" is {} and cannot {} storage.",
                        span.as_str(),
                        if *is_pure {
                            "pure"
                        } else {
                            "declared as `#[storage(read)]`"
                        },
                        if *is_pure {
                            "access"
                        } else {
                            "write to"
                        },
                    )
                ),
                hints: storage_access_violations
                    .iter()
                    .map(|(span, storage_access)| Hint::info(
                        source_engine,
                        span.clone(),
                        format!("{storage_access}")
                    ))
                    .collect(),
                help: vec![
                    format!("Consider declaring the function \"{}\" as `#[{STORAGE_PURITY_ATTRIBUTE_NAME}({suggested_attributes})]`,",
                        span.as_str()
                    ),
                    format!("or removing the {} from the function body.",
                        if *is_pure {
                            "storage access code".to_string()
                        } else {
                            format!("storage write{}", plural_s(storage_access_violations.len()))
                        }
                    ),
                ],
            },
            MultipleImplsSatisfyingTraitForType { span, type_annotation , trait_names, trait_types_and_names: trait_types_and_spans } => Diagnostic {
                reason: Some(Reason::new(code(1), format!("Multiple impls satisfying {} for {}", trait_names.join("+"), type_annotation))),
                issue: Issue::error(
                    source_engine,
                    span.clone(),
                    String::new()
                ),
                hints: vec![],
                help: vec![format!("Trait{} implemented for types:\n{}", if trait_names.len() > 1 {"s"} else {""}, trait_types_and_spans.iter().enumerate().map(|(e, (type_id, name))| 
                    format!("#{} {} for {}", e, name, type_id.clone())
                ).collect::<Vec<_>>().join("\n"))],
            },
           _ => Diagnostic {
                    // TODO: Temporary we use self here to achieve backward compatibility.
                    //       In general, self must not be used and will not be used once we
                    //       switch to our own #[error] macro. All the values for the formatting
                    //       of a diagnostic must come from the enum variant parameters.
                    issue: Issue::error(source_engine, self.span(), format!("{}", self)),
                    ..Default::default()
            }
        }
    }
}

#[derive(Error, Debug, Clone, PartialEq, Eq, Hash)]
pub enum TypeNotAllowedReason {
    #[error(
        "Returning a type containing `raw_slice` from `main()` is not allowed. \
            Consider converting it into a flat `raw_slice` first."
    )]
    NestedSliceReturnNotAllowedInMain,

    #[error("The type \"{ty}\" is not allowed in storage.")]
    TypeNotAllowedInContractStorage { ty: String },

    #[error("`str` or a type containing `str` on `main()` arguments is not allowed.")]
    StringSliceInMainParameters,

    #[error("Returning `str` or a type containing `str` from `main()` is not allowed.")]
    StringSliceInMainReturn,

    #[error("`str` or a type containing `str` on `configurables` is not allowed.")]
    StringSliceInConfigurables,

    #[error("`str` or a type containing `str` on `const` is not allowed.")]
    StringSliceInConst,

    #[error("slices or types containing slices on `const` are not allowed.")]
    SliceInConst,

    #[error("references, pointers, slices, string slices or types containing any of these are not allowed.")]
    NotAllowedInTransmute,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum StructFieldUsageContext {
    StructInstantiation { struct_can_be_instantiated: bool },
    StorageDeclaration { struct_can_be_instantiated: bool },
    StorageAccess,
    PatternMatching { has_rest_pattern: bool },
    StructFieldAccess,
    // TODO: Distinguish between struct field access and destructing
    //       once https://github.com/FuelLabs/sway/issues/5478 is implemented
    //       and provide specific suggestions for these two cases.
    //       (Destructing desugars to plain struct field access.)
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum InvalidImplementingForType {
    SelfType,
    Placeholder,
    Other,
}

impl fmt::Display for InvalidImplementingForType {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::SelfType => f.write_str("\"Self\""),
            Self::Placeholder => f.write_str("Placeholder `_`"),
            Self::Other => f.write_str("This"),
        }
    }
}

/// Defines what shadows a constant or a configurable.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ShadowingSource {
    /// A constant or a configurable is shadowed by a constant.
    Const,
    /// A constant or a configurable is shadowed by a local variable declared with the `let` keyword.
    LetVar,
    /// A constant or a configurable is shadowed by a variable declared in pattern matching,
    /// being a struct field. E.g., `S { some_field }`.
    PatternMatchingStructFieldVar,
}

impl fmt::Display for ShadowingSource {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Const => f.write_str("Constant"),
            Self::LetVar => f.write_str("Variable"),
            Self::PatternMatchingStructFieldVar => f.write_str("Pattern variable"),
        }
    }
}

/// Defines how a storage gets accessed within a function body.
/// E.g., calling `__state_clear` intrinsic or using `scwq` ASM instruction
/// represent a [StorageAccess::Clear] access.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum StorageAccess {
    Clear,
    ReadWord,
    ReadSlots,
    WriteWord,
    WriteSlots,
    /// Storage access happens via call to an impure function.
    /// The parameters are the call path span and if the called function
    /// reads from and writes to the storage: (call_path, reads, writes).
    ImpureFunctionCall(Span, bool, bool),
}

impl StorageAccess {
    pub fn is_write(&self) -> bool {
        matches!(
            self,
            Self::Clear | Self::WriteWord | Self::WriteSlots | Self::ImpureFunctionCall(_, _, true)
        )
    }
}

impl fmt::Display for StorageAccess {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Clear => f.write_str("Clearing the storage happens here."),
            Self::ReadWord => f.write_str("Reading a word from the storage happens here."),
            Self::ReadSlots => f.write_str("Reading storage slots happens here."),
            Self::WriteWord => f.write_str("Writing a word to the storage happens here."),
            Self::WriteSlots => f.write_str("Writing to storage slots happens here."),
            Self::ImpureFunctionCall(call_path, reads, writes) => f.write_fmt(format_args!(
                "Function \"{}\" {} the storage.",
                call_path_suffix_with_args(&call_path.as_str().to_string()),
                match (reads, writes) {
                    (true, true) => "reads from and writes to",
                    (true, false) => "reads from",
                    (false, true) => "writes to",
                    (false, false) => unreachable!(
                        "Function \"{}\" is impure, so it must read from or write to the storage.",
                        call_path.as_str()
                    ),
                }
            )),
        }
    }
}