solar-sema 0.2.0

Solidity and Yul semantic analysis
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
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
//! High-level intermediate representation (HIR).

use crate::{builtins::Builtin, ty::Gcx};
use derive_more::derive::From;
use either::Either;
use rayon::prelude::*;
use solar_ast as ast;
use solar_data_structures::{
    BumpExt,
    index::{Idx, IndexVec},
    newtype_index,
};
use solar_interface::{Ident, Span, Symbol, diagnostics::ErrorGuaranteed, source_map::SourceFile};
use std::{cell::Cell, fmt, ops::ControlFlow, sync::Arc};
use strum::EnumIs;

pub use ast::{
    BinOp, BinOpKind, ContractKind, DataLocation, ElementaryType, FunctionKind, Lit, NatSpecItem,
    NatSpecKind, StateMutability, UnOp, UnOpKind, VarMut, Visibility,
};

mod print;
pub use print::HirPrinter;

mod visit;
pub use visit::Visit;

/// HIR arena allocator.
pub struct Arena {
    bump: bumpalo::Bump,
}

impl Arena {
    /// Creates a new AST arena.
    pub fn new() -> Self {
        Self { bump: bumpalo::Bump::new() }
    }

    /// Returns a reference to the arena's bump allocator.
    pub fn bump(&self) -> &bumpalo::Bump {
        &self.bump
    }

    /// Returns a mutable reference to the arena's bump allocator.
    pub fn bump_mut(&mut self) -> &mut bumpalo::Bump {
        &mut self.bump
    }

    /// Calculates the number of bytes currently allocated in the entire arena.
    pub fn allocated_bytes(&self) -> usize {
        self.bump.allocated_bytes()
    }

    /// Returns the number of bytes currently in use.
    pub fn used_bytes(&self) -> usize {
        self.bump.used_bytes()
    }
}

impl Default for Arena {
    fn default() -> Self {
        Self::new()
    }
}

impl std::ops::Deref for Arena {
    type Target = bumpalo::Bump;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.bump
    }
}

/// The high-level intermediate representation (HIR).
///
/// This struct contains all the information about the entire program.
#[derive(Debug)]
pub struct Hir<'hir> {
    /// All sources.
    pub(crate) sources: IndexVec<SourceId, Source<'hir>>,
    /// All documentation comments.
    pub(crate) docs: IndexVec<DocId, Doc<'hir>>,
    /// All contracts.
    pub(crate) contracts: IndexVec<ContractId, Contract<'hir>>,
    /// All functions.
    pub(crate) functions: IndexVec<FunctionId, Function<'hir>>,
    /// All structs.
    pub(crate) structs: IndexVec<StructId, Struct<'hir>>,
    /// All enums.
    pub(crate) enums: IndexVec<EnumId, Enum<'hir>>,
    /// All user-defined value types.
    pub(crate) udvts: IndexVec<UdvtId, Udvt<'hir>>,
    /// All events.
    pub(crate) events: IndexVec<EventId, Event<'hir>>,
    /// All custom errors.
    pub(crate) errors: IndexVec<ErrorId, Error<'hir>>,
    /// All constants and variables.
    pub(crate) variables: IndexVec<VariableId, Variable<'hir>>,
}

macro_rules! indexvec_methods {
    ($($singular:ident => $plural:ident, $id:ty => $type:ty;)*) => { paste::paste! {
        $(
            #[doc = "Returns the " $singular " associated with the given ID."]
            #[inline]
            #[cfg_attr(debug_assertions, track_caller)]
            pub fn $singular(&self, id: $id) -> &$type {
                if cfg!(debug_assertions) {
                    &self.$plural[id]
                } else {
                    unsafe { self.$plural.raw.get_unchecked(id.index()) }
                }
            }

            #[doc = "Returns an iterator over all of the " $singular " IDs."]
            #[inline]
            pub fn [<$singular _ids>](&self) -> impl ExactSizeIterator<Item = $id> + Clone + use<> {
                // SAFETY: `$plural` is an IndexVec, which guarantees that all indexes are in bounds
                // of the respective index type.
                (0..self.$plural.len()).map(|id| unsafe { $id::from_usize_unchecked(id) })
            }

            #[doc = "Returns a parallel iterator over all of the " $singular " IDs."]
            #[inline]
            pub fn [<par_ $singular _ids>](&self) -> impl IndexedParallelIterator<Item = $id> + use<> {
                // SAFETY: `$plural` is an IndexVec, which guarantees that all indexes are in bounds
                // of the respective index type.
                (0..self.$plural.len()).into_par_iter().map(|id| unsafe { $id::from_usize_unchecked(id) })
            }

            #[doc = "Returns an iterator over all of the " $singular " values."]
            #[inline]
            pub fn $plural(&self) -> impl ExactSizeIterator<Item = &$type> + Clone {
                self.$plural.raw.iter()
            }

            #[doc = "Returns a parallel iterator over all of the " $singular " values."]
            #[inline]
            pub fn [<par_ $plural>](&self) -> impl IndexedParallelIterator<Item = &$type> {
                self.$plural.raw.par_iter()
            }

            #[doc = "Returns an iterator over all of the " $singular " IDs and their associated values."]
            #[inline]
            pub fn [<$plural _enumerated>](&self) -> impl ExactSizeIterator<Item = ($id, &$type)> + Clone {
                // SAFETY: `$plural` is an IndexVec, which guarantees that all indexes are in bounds
                // of the respective index type.
                self.$plural().enumerate().map(|(i, v)| (unsafe { $id::from_usize_unchecked(i) }, v))
            }

            #[doc = "Returns an iterator over all of the " $singular " IDs and their associated values."]
            #[inline]
            pub fn [<par_ $plural _enumerated>](&self) -> impl IndexedParallelIterator<Item = ($id, &$type)> {
                // SAFETY: `$plural` is an IndexVec, which guarantees that all indexes are in bounds
                // of the respective index type.
                self.[<par_ $plural>]().enumerate().map(|(i, v)| (unsafe { $id::from_usize_unchecked(i) }, v))
            }
        )*

        pub(crate) fn shrink_to_fit(&mut self) {
            $(
                self.$plural.shrink_to_fit();
            )*
        }
    }};
}

impl<'hir> Hir<'hir> {
    pub(crate) fn new() -> Self {
        let mut docs = IndexVec::new();
        let empty_doc_id = docs.push(Doc {
            source: SourceId::MAX,
            item: ItemId::Contract(ContractId::MAX),
            ast_comments: ast::DocComments::default(),
        });
        debug_assert_eq!(empty_doc_id, DocId::EMPTY);

        Self {
            sources: IndexVec::new(),
            docs,
            contracts: IndexVec::new(),
            functions: IndexVec::new(),
            structs: IndexVec::new(),
            enums: IndexVec::new(),
            udvts: IndexVec::new(),
            events: IndexVec::new(),
            errors: IndexVec::new(),
            variables: IndexVec::new(),
        }
    }

    indexvec_methods! {
        source => sources, SourceId => Source<'hir>;
        doc => docs, DocId => Doc<'hir>;
        contract => contracts, ContractId => Contract<'hir>;
        function => functions, FunctionId => Function<'hir>;
        strukt => structs, StructId => Struct<'hir>;
        enumm => enums, EnumId => Enum<'hir>;
        udvt => udvts, UdvtId => Udvt<'hir>;
        event => events, EventId => Event<'hir>;
        error => errors, ErrorId => Error<'hir>;
        variable => variables, VariableId => Variable<'hir>;
    }

    /// Returns the item associated with the given ID.
    #[inline]
    pub fn item(&self, id: impl Into<ItemId>) -> Item<'_, 'hir> {
        match id.into() {
            ItemId::Contract(id) => Item::Contract(self.contract(id)),
            ItemId::Function(id) => Item::Function(self.function(id)),
            ItemId::Variable(id) => Item::Variable(self.variable(id)),
            ItemId::Struct(id) => Item::Struct(self.strukt(id)),
            ItemId::Enum(id) => Item::Enum(self.enumm(id)),
            ItemId::Udvt(id) => Item::Udvt(self.udvt(id)),
            ItemId::Error(id) => Item::Error(self.error(id)),
            ItemId::Event(id) => Item::Event(self.event(id)),
        }
    }

    /// Returns an iterator over all item IDs.
    pub fn item_ids(&self) -> impl Iterator<Item = ItemId> + Clone {
        self.item_ids_vec().into_iter()
    }

    /// Returns a parallel iterator over all item IDs.
    pub fn par_item_ids(&self) -> impl ParallelIterator<Item = ItemId> {
        self.item_ids_vec().into_par_iter()
    }

    fn item_ids_vec(&self) -> Vec<ItemId> {
        // NOTE: This is essentially an unrolled `.chain().chain() ... .collect()` since it's not
        // very efficient.
        #[rustfmt::skip]
        let len =
              self.contracts.len()
            + self.functions.len()
            + self.variables.len()
            + self.structs.len()
            + self.enums.len()
            + self.udvts.len()
            + self.errors.len()
            + self.events.len();
        let mut v = Vec::<ItemId>::with_capacity(len);
        let mut items = v.spare_capacity_mut().iter_mut();
        macro_rules! extend_unchecked {
            ($iter:expr) => {
                for item in $iter {
                    unsafe { items.next().unwrap_unchecked().write(item) };
                }
            };
        }
        extend_unchecked!(self.contract_ids().map(ItemId::from));
        extend_unchecked!(self.function_ids().map(ItemId::from));
        extend_unchecked!(self.variable_ids().map(ItemId::from));
        extend_unchecked!(self.strukt_ids().map(ItemId::from));
        extend_unchecked!(self.enumm_ids().map(ItemId::from));
        extend_unchecked!(self.udvt_ids().map(ItemId::from));
        extend_unchecked!(self.error_ids().map(ItemId::from));
        extend_unchecked!(self.event_ids().map(ItemId::from));

        debug_assert!(items.next().is_none());
        unsafe { v.set_len(len) };
        debug_assert_eq!(v.len(), len);
        debug_assert_eq!(v.capacity(), len);

        v
    }

    /// Returns an iterator over all item IDs in a contract, including inheritance.
    pub fn contract_item_ids(
        &self,
        id: ContractId,
    ) -> impl Iterator<Item = ItemId> + Clone + use<'_, 'hir> {
        self.contract(id)
            .linearized_bases
            .iter()
            .copied()
            .flat_map(|base| self.contract(base).items.iter().copied())
    }

    /// Returns an iterator over all items in a contract, including inheritance.
    pub fn contract_items(&self, id: ContractId) -> impl Iterator<Item = Item<'_, 'hir>> + Clone {
        self.contract_item_ids(id).map(move |id| self.item(id))
    }

    /// Creates a builder for constructing HIR nodes.
    pub fn builder<'id>(
        arena: &'hir bumpalo::Bump,
        next_id: &'id IdCounter,
    ) -> HirBuilder<'hir, 'id> {
        HirBuilder::new(arena, next_id)
    }
}

/// A counter for generating unique IDs.
pub struct IdCounter {
    counter: Cell<u32>,
}

impl Default for IdCounter {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl IdCounter {
    /// Creates a new ID counter.
    #[inline]
    pub fn new() -> Self {
        Self { counter: Cell::new(0) }
    }

    /// Generates the next ID.
    #[inline]
    pub fn next<I: Idx>(&self) -> I {
        I::from_usize(self.next_usize())
    }

    /// Generates the next ID as a usize.
    #[inline]
    pub fn next_usize(&self) -> usize {
        let x = self.counter.get();
        self.counter.set(x + 1);
        x as usize
    }
}

/// A builder for constructing HIR nodes.
pub struct HirBuilder<'hir, 'id> {
    arena: &'hir bumpalo::Bump,
    next_id: &'id IdCounter,
}

impl<'hir, 'id> HirBuilder<'hir, 'id> {
    /// Creates a new HIR builder.
    pub fn new(arena: &'hir bumpalo::Bump, next_id: &'id IdCounter) -> Self {
        Self { arena, next_id }
    }

    /// Generates the next expression ID.
    pub fn next_expr_id(&self) -> ExprId {
        self.next_id.next()
    }

    /// Creates a HIR expression with ID, kind and span.
    pub fn expr(&self, id: ExprId, kind: ExprKind<'hir>, span: Span) -> &'hir Expr<'hir> {
        self.arena.alloc(Expr { id, kind, span })
    }

    /// Creates a HIR expression with the given kind (as requested in GitHub issue).
    pub fn expr_kind(&self, kind: ExprKind<'hir>) -> Expr<'hir> {
        Expr { id: self.next_expr_id(), kind, span: Span::DUMMY }
    }

    /// Creates an allocated HIR expression.
    pub fn expr_alloc(&self, id: ExprId, kind: ExprKind<'hir>, span: Span) -> &'hir Expr<'hir> {
        self.arena.alloc(Expr { id, kind, span })
    }

    /// Creates an allocated HIR statement.
    pub fn stmt_alloc(&self, kind: StmtKind<'hir>, span: Span) -> &'hir Stmt<'hir> {
        self.arena.alloc(Stmt { kind, span })
    }

    /// Creates a break statement.
    pub fn break_stmt(&self, span: Span) -> &'hir Stmt<'hir> {
        self.stmt_alloc(StmtKind::Break, span)
    }

    /// Creates a continue statement.
    pub fn continue_stmt(&self, span: Span) -> &'hir Stmt<'hir> {
        self.stmt_alloc(StmtKind::Continue, span)
    }

    /// Creates a return statement.
    pub fn return_stmt(&self, expr: Option<&'hir Expr<'hir>>, span: Span) -> &'hir Stmt<'hir> {
        self.stmt_alloc(StmtKind::Return(expr), span)
    }

    /// Creates a binary expression kind.
    pub fn binary_expr(
        &self,
        left: &'hir Expr<'hir>,
        op: BinOp,
        right: &'hir Expr<'hir>,
    ) -> ExprKind<'hir> {
        ExprKind::Binary(left, op, right)
    }

    /// Creates a literal expression kind.
    pub fn lit_expr(&self, lit: &'hir Lit<'hir>) -> ExprKind<'hir> {
        ExprKind::Lit(lit)
    }

    /// Creates an owned HIR expression with the given ID, kind and span.
    pub fn expr_owned(&self, id: ExprId, kind: ExprKind<'hir>, span: Span) -> Expr<'hir> {
        Expr { id, kind, span }
    }

    /// Creates an owned HIR expression with automatically generated ID.
    pub fn expr_auto(&self, kind: ExprKind<'hir>, span: Span) -> Expr<'hir> {
        Expr { id: self.next_expr_id(), kind, span }
    }

    /// Creates a HIR statement with the given kind and span.
    pub fn stmt(&self, kind: StmtKind<'hir>, span: Span) -> Stmt<'hir> {
        Stmt { kind, span }
    }

    /// Creates a HIR block with the given statements and span.
    pub fn block(&self, stmts: &'hir [Stmt<'hir>], span: Span) -> Block<'hir> {
        Block { stmts, span }
    }
}

newtype_index! {
    /// A [`Source`] ID.
    pub struct SourceId;

    /// A [`Doc`] ID.
    ///
    /// Use [`Gcx::natspec_doc_comments`] to access validated and resolved NatSpec items.
    pub struct DocId;

    /// A [`Contract`] ID.
    pub struct ContractId;

    /// A [`Function`] ID.
    pub struct FunctionId;

    /// A [`Struct`] ID.
    pub struct StructId;

    /// An [`Enum`] ID.
    pub struct EnumId;

    /// An [`Udvt`] ID.
    pub struct UdvtId;

    /// An [`Event`] ID.
    pub struct EventId;

    /// An [`Error`] ID.
    pub struct ErrorId;

    /// A [`Variable`] ID.
    pub struct VariableId;

    /// An [`Expr`] ID.
    pub struct ExprId;
}

impl DocId {
    /// The empty documentation id.
    ///
    /// This is reserved as index 0 and represents items with no documentation.
    pub const EMPTY: Self = Self::new(0);

    /// Whether a documentation id is empty or not.
    pub fn is_empty(&self) -> bool {
        self == &Self::EMPTY
    }
}

/// A source file.
pub struct Source<'hir> {
    pub file: Arc<SourceFile>,
    /// The individual imports with their resolved source IDs.
    ///
    /// Note that the source IDs may not be unique, as multiple imports may resolve to the same
    /// source.
    pub imports: &'hir [(ast::ItemId, SourceId)],
    /// The source items.
    pub items: &'hir [ItemId],
    /// The source-level `using for` directives.
    pub usings: &'hir [UsingDirective<'hir>],
    /// The source docs.
    pub docs: &'hir [DocId],
}

impl fmt::Debug for Source<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Source")
            .field("file", &self.file.name)
            .field("imports", &self.imports)
            .field("items", &self.items)
            .finish()
    }
}

/// The documentation of an item.
///
/// Use [`Gcx::natspec_doc_comments`] with the corresponding [`DocId`] to access validated and
/// resolved NatSpec items.
#[derive(Debug)]
pub struct Doc<'hir> {
    /// The source this documentation is defined in.
    pub source: SourceId,
    /// The item this documentation is defined in.
    pub item: ItemId,
    /// Reference to the raw AST documentation comments.
    ///
    /// Use [`Gcx::natspec_doc_comments`] for the validated and resolved NatSpec view.
    pub(crate) ast_comments: ast::DocComments<'hir>,
}

#[derive(Clone, Copy, Debug, EnumIs)]
pub enum Item<'a, 'hir> {
    Contract(&'a Contract<'hir>),
    Function(&'a Function<'hir>),
    Struct(&'a Struct<'hir>),
    Enum(&'a Enum<'hir>),
    Udvt(&'a Udvt<'hir>),
    Error(&'a Error<'hir>),
    Event(&'a Event<'hir>),
    Variable(&'a Variable<'hir>),
}

impl<'hir> Item<'_, 'hir> {
    /// Returns the name of the item.
    #[inline]
    pub fn name(self) -> Option<Ident> {
        match self {
            Item::Contract(c) => Some(c.name),
            Item::Function(f) => f.name,
            Item::Struct(s) => Some(s.name),
            Item::Enum(e) => Some(e.name),
            Item::Udvt(u) => Some(u.name),
            Item::Error(e) => Some(e.name),
            Item::Event(e) => Some(e.name),
            Item::Variable(v) => v.name,
        }
    }

    /// Returns the description of the item.
    #[inline]
    pub fn description(self) -> &'static str {
        match self {
            Item::Contract(c) => c.description(),
            Item::Function(f) => f.description(),
            Item::Struct(_) => "struct",
            Item::Enum(_) => "enum",
            Item::Udvt(_) => "UDVT",
            Item::Error(_) => "error",
            Item::Event(_) => "event",
            Item::Variable(_) => "variable",
        }
    }

    /// Returns the span of the item.
    #[inline]
    pub fn span(self) -> Span {
        match self {
            Item::Contract(c) => c.span,
            Item::Function(f) => f.span,
            Item::Struct(s) => s.span,
            Item::Enum(e) => e.span,
            Item::Udvt(u) => u.span,
            Item::Error(e) => e.span,
            Item::Event(e) => e.span,
            Item::Variable(v) => v.span,
        }
    }

    /// Returns the contract ID if this item is part of a contract.
    #[inline]
    pub fn contract(self) -> Option<ContractId> {
        match self {
            Item::Contract(_) => None,
            Item::Function(f) => f.contract,
            Item::Struct(s) => s.contract,
            Item::Enum(e) => e.contract,
            Item::Udvt(u) => u.contract,
            Item::Error(e) => e.contract,
            Item::Event(e) => e.contract,
            Item::Variable(v) => v.contract,
        }
    }

    /// Returns the parent item that owns this item's lexical scope, if any.
    #[inline]
    pub fn parent(self) -> Option<ItemId> {
        match self {
            Item::Variable(v) => v.parent.or_else(|| v.contract.map(ItemId::Contract)),
            _ => self.contract().map(ItemId::Contract),
        }
    }

    /// Returns the source ID where this item is defined.
    #[inline]
    pub fn source(self) -> SourceId {
        match self {
            Item::Contract(c) => c.source,
            Item::Function(f) => f.source,
            Item::Struct(s) => s.source,
            Item::Enum(e) => e.source,
            Item::Udvt(u) => u.source,
            Item::Error(e) => e.source,
            Item::Event(e) => e.source,
            Item::Variable(v) => v.source,
        }
    }

    /// Returns the documentation comments associated with this item.
    #[inline]
    pub fn doc(self) -> DocId {
        match self {
            Item::Contract(c) => c.doc,
            Item::Function(f) => f.doc,
            Item::Struct(s) => s.doc,
            Item::Enum(e) => e.doc,
            Item::Udvt(u) => u.doc,
            Item::Error(e) => e.doc,
            Item::Event(e) => e.doc,
            Item::Variable(v) => v.doc,
        }
    }

    /// Returns the parameters of the item.
    #[inline]
    pub fn parameters(self) -> Option<&'hir [VariableId]> {
        Some(match self {
            Item::Struct(s) => s.fields,
            Item::Function(f) => f.parameters,
            Item::Event(e) => e.parameters,
            Item::Error(e) => e.parameters,
            _ => return None,
        })
    }

    /// Returns `true` if the item is visible in derived contracts.
    #[inline]
    pub fn is_visible_in_derived_contracts(self) -> bool {
        self.is_visible_in_contract() && self.visibility() >= Visibility::Internal
    }

    /// Returns `true` if the item is visible in the contract.
    #[inline]
    pub fn is_visible_in_contract(self) -> bool {
        (if let Item::Function(f) = self {
            matches!(f.kind, FunctionKind::Function | FunctionKind::Modifier)
        } else {
            true
        }) && self.visibility() != Visibility::External
    }

    /// Returns `true` if the item is visible as a library member.
    #[inline]
    pub fn is_visible_as_library_member(self) -> bool {
        self.visibility() >= Visibility::Internal
    }

    /// Returns `true` if the item is visible through contract type access.
    #[inline]
    pub fn is_visible_via_contract_type_access(self) -> bool {
        match self {
            Item::Function(f) => f.is_ordinary() && f.visibility >= Visibility::Public,
            Item::Struct(_) | Item::Enum(_) | Item::Udvt(_) | Item::Error(_) | Item::Event(_) => {
                true
            }
            Item::Contract(_) | Item::Variable(_) => false,
        }
    }

    /// Returns `true` if the item is public or external.
    #[inline]
    pub fn is_public(&self) -> bool {
        self.visibility() >= Visibility::Public
    }

    /// Returns the visibility of the item.
    #[inline]
    pub fn visibility(self) -> Visibility {
        match self {
            Item::Variable(v) => v.visibility.unwrap_or(Visibility::Internal),
            Item::Contract(_)
            | Item::Function(_)
            | Item::Struct(_)
            | Item::Enum(_)
            | Item::Udvt(_)
            | Item::Error(_)
            | Item::Event(_) => Visibility::Public,
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Hash, From, EnumIs)]
pub enum ItemId {
    Contract(ContractId),
    Function(FunctionId),
    Variable(VariableId),
    Struct(StructId),
    Enum(EnumId),
    Udvt(UdvtId),
    Error(ErrorId),
    Event(EventId),
}

impl fmt::Debug for ItemId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("ItemId::")?;
        match self {
            Self::Contract(id) => id.fmt(f),
            Self::Function(id) => id.fmt(f),
            Self::Variable(id) => id.fmt(f),
            Self::Struct(id) => id.fmt(f),
            Self::Enum(id) => id.fmt(f),
            Self::Udvt(id) => id.fmt(f),
            Self::Error(id) => id.fmt(f),
            Self::Event(id) => id.fmt(f),
        }
    }
}

impl ItemId {
    /// Returns the description of the item.
    pub fn description(&self) -> &'static str {
        match self {
            Self::Contract(_) => "contract",
            Self::Function(_) => "function",
            Self::Variable(_) => "variable",
            Self::Struct(_) => "struct",
            Self::Enum(_) => "enum",
            Self::Udvt(_) => "UDVT",
            Self::Error(_) => "error",
            Self::Event(_) => "event",
        }
    }

    /// Returns `true` if the **item kinds** match.
    #[inline]
    pub fn matches(&self, other: &Self) -> bool {
        std::mem::discriminant(self) == std::mem::discriminant(other)
    }

    /// Returns the parent item that owns this item's lexical scope, if any.
    #[inline]
    pub fn parent(self, hir: &Hir<'_>) -> Option<Self> {
        hir.item(self).parent()
    }

    /// Returns the contract ID if this is a contract.
    pub fn as_contract(&self) -> Option<ContractId> {
        if let Self::Contract(v) = *self { Some(v) } else { None }
    }

    /// Returns the function ID if this is a function.
    pub fn as_function(&self) -> Option<FunctionId> {
        if let Self::Function(v) = *self { Some(v) } else { None }
    }

    /// Returns the struct ID if this is a struct.
    pub fn as_struct(&self) -> Option<StructId> {
        if let Self::Struct(v) = *self { Some(v) } else { None }
    }

    /// Returns the variable ID if this is a variable.
    pub fn as_variable(&self) -> Option<VariableId> {
        if let Self::Variable(v) = *self { Some(v) } else { None }
    }
}

/// A contract, interface, or library.
#[derive(Debug)]
pub struct Contract<'hir> {
    /// The source this contract is defined in.
    pub source: SourceId,
    /// The documentation of this contract.
    pub doc: DocId,
    /// The contract span.
    pub span: Span,
    /// The contract name.
    pub name: Ident,
    /// The contract kind.
    pub kind: ContractKind,
    /// The storage layout base slot expression, if specified.
    pub layout: Option<&'hir Expr<'hir>>,
    /// The contract bases, as declared in the source code.
    pub bases: &'hir [ContractId],
    /// The base arguments, as declared in the source code.
    pub bases_args: &'hir [Modifier<'hir>],
    /// The linearized contract bases.
    ///
    /// The first element is always the contract itself, followed by its bases in order of
    /// inheritance. The bases may not be present if the inheritance linearization failed. See
    /// [`Contract::linearization_failed`].
    pub linearized_bases: &'hir [ContractId],
    /// The constructor base arguments (if any).
    ///
    /// The index maps to the position in `linearized_bases[1..]`.
    ///
    /// The reference points to either `bases_args` in the original contract, or `modifiers` in the
    /// constructor.
    pub linearized_bases_args: &'hir [Option<&'hir Modifier<'hir>>],
    /// The resolved constructor function.
    pub ctor: Option<FunctionId>,
    /// The resolved `fallback` function.
    pub fallback: Option<FunctionId>,
    /// The resolved `receive` function.
    pub receive: Option<FunctionId>,
    /// The contract items.
    ///
    /// Note that this only includes items defined in the contract itself, not inherited items.
    /// For getting all items, use [`Hir::contract_items`].
    pub items: &'hir [ItemId],
    /// The contract-level `using for` directives.
    pub usings: &'hir [UsingDirective<'hir>],
}

impl Contract<'_> {
    /// Returns `true` if the inheritance linearization failed.
    pub fn linearization_failed(&self) -> bool {
        self.linearized_bases.is_empty()
            || (!self.bases.is_empty() && self.linearized_bases.len() == 1)
    }

    /// Returns an iterator over functions declared in the contract.
    ///
    /// Note that this does not include the constructor and fallback functions, as they are stored
    /// separately. Use [`Contract::all_functions`] to include them.
    pub fn functions(&self) -> impl Iterator<Item = FunctionId> + Clone + use<'_> {
        self.items.iter().filter_map(ItemId::as_function)
    }

    /// Returns an iterator over all functions declared in the contract.
    pub fn all_functions(&self) -> impl Iterator<Item = FunctionId> + Clone + use<'_> {
        self.functions().chain(self.ctor).chain(self.fallback).chain(self.receive)
    }

    /// Returns an iterator over all variables declared in the contract.
    pub fn variables(&self) -> impl Iterator<Item = VariableId> + Clone + use<'_> {
        self.items.iter().filter_map(ItemId::as_variable)
    }

    /// Returns `true` if the contract can be deployed.
    pub fn can_be_deployed(&self) -> bool {
        matches!(self.kind, ContractKind::Contract | ContractKind::Library)
    }

    /// Returns `true` if this is an abstract contract.
    pub fn is_abstract(&self) -> bool {
        self.kind.is_abstract_contract()
    }

    /// Returns the description of the contract.
    pub fn description(&self) -> &'static str {
        self.kind.to_str()
    }
}

/// Returns `true` if the contract can receive ether.
///
/// A contract can receive ether if it has:
/// - A `receive()` function, OR
/// - A `fallback()` function with `payable` state mutability
pub fn can_receive_ether(contract: &Contract<'_>, gcx: Gcx<'_>) -> bool {
    // Check if contract has receive function
    if contract.receive.is_some() {
        return true;
    }

    // Check if contract has payable fallback function
    if let Some(fallback_id) = contract.fallback {
        let fallback = gcx.hir.function(fallback_id);
        if fallback.state_mutability == StateMutability::Payable {
            return true;
        }
    }

    false
}

/// A modifier or base class call.
#[derive(Clone, Copy, Debug)]
pub struct Modifier<'hir> {
    /// The span of the modifier or base class call.
    pub span: Span,
    /// The modifier or base class ID.
    pub id: ItemId,
    /// The arguments to the modifier or base class call.
    pub args: CallArgs<'hir>,
}

/// A resolved `using for` directive.
#[derive(Debug)]
pub struct UsingDirective<'hir> {
    /// The directive span.
    pub span: Span,
    /// The source this directive is defined in.
    pub source: SourceId,
    /// The contract this directive is defined in, if any.
    pub contract: Option<ContractId>,
    /// The type this directive applies to. `None` means `*`.
    pub ty: Option<Type<'hir>>,
    /// Whether this is a global directive.
    pub global: bool,
    /// The attached library/functions.
    pub entries: &'hir [UsingEntry<'hir>],
}

/// A resolved entry in a `using for` directive.
#[derive(Debug)]
pub struct UsingEntry<'hir> {
    /// The path span.
    pub span: Span,
    /// The member name introduced by a braced function entry.
    pub name: Option<Symbol>,
    /// The attached item.
    pub kind: UsingEntryKind<'hir>,
    /// The operator this entry defines, if any.
    pub operator: Option<ast::UserDefinableOperator>,
}

/// A resolved `using for` entry kind.
#[derive(Debug)]
pub enum UsingEntryKind<'hir> {
    /// `using L for T`.
    Library(ContractId),
    /// `using { f } for T`.
    Functions(&'hir [FunctionId]),
    /// An erroneous entry.
    Err(ErrorGuaranteed),
}

/// A function.
#[derive(Debug)]
pub struct Function<'hir> {
    /// The source this function is defined in.
    pub source: SourceId,
    /// The documentation of this function.
    pub doc: DocId,
    /// The contract this function is defined in, if any.
    pub contract: Option<ContractId>,
    /// The function span.
    pub span: Span,
    /// The function name.
    /// Only `None` if this is a constructor, fallback, or receive function.
    pub name: Option<Ident>,
    /// The function kind.
    pub kind: FunctionKind,
    /// Whether this function was lowered from a Yul function definition.
    pub is_yul: bool,
    /// The visibility of the function.
    pub visibility: Visibility,
    /// The state mutability of the function.
    pub state_mutability: StateMutability,
    /// Modifiers, or base classes if this is a constructor.
    pub modifiers: &'hir [Modifier<'hir>],
    /// Whether this function is marked with the `virtual` keyword.
    pub marked_virtual: bool,
    /// Whether this function is marked with the `virtual` keyword or is defined in an interface.
    pub virtual_: bool,
    /// Whether this function is marked with the `override` keyword.
    pub override_: bool,
    pub overrides: &'hir [ContractId],
    /// The function parameters.
    pub parameters: &'hir [VariableId],
    /// The function returns.
    pub returns: &'hir [VariableId],
    /// The function body.
    pub body: Option<Block<'hir>>,
    /// The function body span.
    pub body_span: Span,
    /// The variable this function is a getter of, if any.
    pub gettee: Option<VariableId>,
}

impl Function<'_> {
    /// Returns the span of the `kind` keyword.
    pub fn keyword_span(&self) -> Span {
        self.span.with_hi(self.span.lo() + self.kind.to_str().len() as u32)
    }

    /// Returns `true` if this is a free function, meaning it is not part of a contract.
    pub fn is_free(&self) -> bool {
        self.contract.is_none()
    }

    pub fn is_ordinary(&self) -> bool {
        self.kind.is_ordinary()
    }

    /// Returns `true` if this is a getter function of a variable.
    pub fn is_getter(&self) -> bool {
        self.gettee.is_some()
    }

    pub fn is_part_of_external_interface(&self) -> bool {
        self.is_ordinary() && self.visibility >= Visibility::Public
    }

    /// Returns `true` if this is a receive or fallback function
    pub fn is_special(&self) -> bool {
        // https://docs.soliditylang.org/en/latest/contracts.html#special-functions
        matches!(self.kind, FunctionKind::Receive | FunctionKind::Fallback)
    }

    /// Returns `true` if this is a constructor
    pub fn is_constructor(&self) -> bool {
        matches!(self.kind, FunctionKind::Constructor)
    }

    /// Returns `true` if this function mutates state
    pub fn mutates_state(&self) -> bool {
        self.state_mutability >= StateMutability::Payable
    }

    /// Returns an iterator over all variables in the function.
    pub fn variables(&self) -> impl DoubleEndedIterator<Item = VariableId> + Clone + use<'_> {
        self.parameters.iter().copied().chain(self.returns.iter().copied())
    }

    /// Returns the description of the function.
    pub fn description(&self) -> &'static str {
        if self.is_getter() { "getter function" } else { self.kind.to_str() }
    }
}

/// A struct.
#[derive(Debug)]
pub struct Struct<'hir> {
    /// The source this struct is defined in.
    pub source: SourceId,
    /// The documentation of this struct.
    pub doc: DocId,
    /// The contract this struct is defined in, if any.
    pub contract: Option<ContractId>,
    /// The struct span.
    pub span: Span,
    /// The struct name.
    pub name: Ident,
    pub fields: &'hir [VariableId],
}

/// An enum.
#[derive(Debug)]
pub struct Enum<'hir> {
    /// The source this enum is defined in.
    pub source: SourceId,
    /// The documentation of this enum.
    pub doc: DocId,
    /// The contract this enum is defined in, if any.
    pub contract: Option<ContractId>,
    /// The enum span.
    pub span: Span,
    /// The enum name.
    pub name: Ident,
    /// The enum variants.
    pub variants: &'hir [Ident],
}

/// A user-defined value type.
#[derive(Debug)]
pub struct Udvt<'hir> {
    /// The source this UDVT is defined in.
    pub source: SourceId,
    /// The documentation of this UDVT.
    pub doc: DocId,
    /// The contract this UDVT is defined in, if any.
    pub contract: Option<ContractId>,
    /// The UDVT span.
    pub span: Span,
    /// The UDVT name.
    pub name: Ident,
    /// The UDVT type.
    pub ty: Type<'hir>,
}

/// An event.
#[derive(Debug)]
pub struct Event<'hir> {
    /// The source this event is defined in.
    pub source: SourceId,
    /// The documentation of this event.
    pub doc: DocId,
    /// The contract this event is defined in, if any.
    pub contract: Option<ContractId>,
    /// The event span.
    pub span: Span,
    /// The event name.
    pub name: Ident,
    /// Whether this event is anonymous.
    pub anonymous: bool,
    pub parameters: &'hir [VariableId],
}

/// A custom error.
#[derive(Debug)]
pub struct Error<'hir> {
    /// The source this error is defined in.
    pub source: SourceId,
    /// The documentation of this error.
    pub doc: DocId,
    /// The contract this error is defined in, if any.
    pub contract: Option<ContractId>,
    /// The error span.
    pub span: Span,
    /// The error name.
    pub name: Ident,
    pub parameters: &'hir [VariableId],
}

/// A constant or variable declaration.
#[derive(Debug)]
pub struct Variable<'hir> {
    /// The source this variable is defined in.
    pub source: SourceId,
    /// The documentation of this variable.
    pub doc: DocId,
    /// The contract this variable is defined in, if any.
    pub contract: Option<ContractId>,
    /// The parent item containing this variable.
    ///
    /// - Struct fields → the struct
    /// - Event/Error parameters → the event/error
    /// - Function parameters/returns/locals → the function
    /// - State/Global variables → `None`, as they are items themselves
    pub parent: Option<ItemId>,
    /// The variable's span.
    pub span: Span,
    /// The kind of variable.
    pub kind: VarKind,
    /// The variable's type.
    pub ty: Type<'hir>,
    /// The variable's name.
    pub name: Option<Ident>,
    /// The visibility of the variable.
    pub visibility: Option<Visibility>,
    pub mutability: Option<VarMut>,
    pub data_location: Option<DataLocation>,
    pub override_: bool,
    pub overrides: &'hir [ContractId],
    pub indexed: bool,
    pub initializer: Option<&'hir Expr<'hir>>,
    /// The compiler-generated getter function, if any.
    pub getter: Option<FunctionId>,
}

impl<'hir> Variable<'hir> {
    /// Creates a new variable.
    pub fn new(
        source: SourceId,
        doc: DocId,
        ty: Type<'hir>,
        name: Option<Ident>,
        kind: VarKind,
    ) -> Self {
        Self {
            source,
            doc,
            contract: None,
            parent: None,
            span: Span::DUMMY,
            kind,
            ty,
            name,
            visibility: None,
            mutability: None,
            data_location: None,
            override_: false,
            overrides: &[],
            indexed: false,
            initializer: None,
            getter: None,
        }
    }

    /// Creates a new variable statement.
    pub fn new_stmt(
        source: SourceId,
        docs: DocId,
        contract: ContractId,
        function: FunctionId,
        ty: Type<'hir>,
        name: Ident,
    ) -> Self {
        Self {
            contract: Some(contract),
            parent: Some(ItemId::Function(function)),
            ..Self::new(source, docs, ty, Some(name), VarKind::Statement)
        }
    }

    /// Returns the description of the variable.
    pub fn description(&self) -> &'static str {
        self.kind.to_str()
    }

    /// Returns `true` if the variable is [`constant`](VarMut::Constant).
    pub fn is_constant(&self) -> bool {
        self.mutability == Some(VarMut::Constant)
    }

    /// Returns `true` if the variable is [`immutable`](VarMut::Immutable).
    pub fn is_immutable(&self) -> bool {
        self.mutability == Some(VarMut::Immutable)
    }

    pub fn is_l_value(&self) -> bool {
        !self.is_constant()
    }

    pub fn is_struct_member(&self) -> bool {
        matches!(self.kind, VarKind::Struct)
    }

    pub fn is_event_or_error_parameter(&self) -> bool {
        matches!(self.kind, VarKind::Event | VarKind::Error)
    }

    pub fn is_local_variable(&self) -> bool {
        matches!(
            self.kind,
            VarKind::FunctionTyParam
                | VarKind::FunctionTyReturn
                | VarKind::Event
                | VarKind::Error
                | VarKind::FunctionParam
                | VarKind::FunctionReturn
                | VarKind::Statement
                | VarKind::TryCatch
        )
    }

    pub fn is_callable_or_catch_parameter(&self) -> bool {
        matches!(
            self.kind,
            VarKind::Event
                | VarKind::Error
                | VarKind::FunctionParam
                | VarKind::FunctionTyParam
                | VarKind::FunctionReturn
                | VarKind::FunctionTyReturn
                | VarKind::TryCatch
        )
    }

    pub fn is_local_or_return(&self) -> bool {
        self.is_return_parameter()
            || (self.is_local_variable() && !self.is_callable_or_catch_parameter())
    }

    pub fn is_return_parameter(&self) -> bool {
        matches!(self.kind, VarKind::FunctionReturn | VarKind::FunctionTyReturn)
    }

    pub fn is_try_catch_parameter(&self) -> bool {
        matches!(self.kind, VarKind::TryCatch)
    }

    /// Returns `true` if the variable is a state variable.
    pub fn is_state_variable(&self) -> bool {
        self.kind.is_state()
    }

    pub fn is_file_level_variable(&self) -> bool {
        matches!(self.kind, VarKind::Global)
    }

    /// Returns `true` if the variable is public.
    pub fn is_public(&self) -> bool {
        self.visibility >= Some(Visibility::Public)
    }
}

/// The kind of variable.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, EnumIs)]
pub enum VarKind {
    /// Defined at the top level.
    Global,
    /// Defined in a contract.
    State,
    /// Defined in a struct.
    Struct,
    /// Defined in an event.
    Event,
    /// Defined in an error.
    Error,
    /// Defined as a function parameter.
    FunctionParam,
    /// Defined as a function return.
    FunctionReturn,
    /// Defined as a function type parameter.
    FunctionTyParam,
    /// Defined as a function type return.
    FunctionTyReturn,
    /// Defined as a statement, inside of a function, block or `for` statement.
    Statement,
    /// Defined in a catch clause.
    TryCatch,
}

impl VarKind {
    pub fn to_str(self) -> &'static str {
        match self {
            Self::Global => "file-level variable",
            Self::State => "state variable",
            Self::Struct => "struct field",
            Self::Event => "event parameter",
            Self::Error => "error parameter",
            Self::FunctionParam | Self::FunctionTyParam => "function parameter",
            Self::FunctionReturn | Self::FunctionTyReturn => "function return parameter",
            Self::Statement => "variable",
            Self::TryCatch => "try/catch clause",
        }
    }
}

/// A block of statements.
#[derive(Clone, Copy, Debug)]
pub struct Block<'hir> {
    /// The span of the block, including the `{` and `}`.
    pub span: Span,
    /// The statements in the block.
    pub stmts: &'hir [Stmt<'hir>],
}

impl<'hir> std::ops::Deref for Block<'hir> {
    type Target = [Stmt<'hir>];

    fn deref(&self) -> &Self::Target {
        self.stmts
    }
}

/// A statement.
#[derive(Debug)]
pub struct Stmt<'hir> {
    /// The statement span.
    pub span: Span,
    pub kind: StmtKind<'hir>,
}

/// A kind of statement.
#[derive(Debug)]
pub enum StmtKind<'hir> {
    /// A single-variable declaration statement: `uint256 foo = 42;`.
    DeclSingle(VariableId),

    /// A multi-variable declaration statement: `(bool success, bytes memory value) = ...;`.
    ///
    /// Multi-assignments require an expression on the right-hand side.
    DeclMulti(&'hir [Option<VariableId>], &'hir Expr<'hir>),

    /// A blocked scope: `{ ... }`.
    Block(Block<'hir>),

    /// An unchecked block: `unchecked { ... }`.
    UncheckedBlock(Block<'hir>),

    /// An inline assembly block: `assembly { ... }`.
    AssemblyBlock(Block<'hir>),

    /// An emit statement: `emit Foo.bar(42);`.
    ///
    /// Always contains an `ExprKind::Call`.
    Emit(&'hir Expr<'hir>),

    /// A revert statement: `revert Foo.bar(42);`.
    ///
    /// Always contains an `ExprKind::Call`.
    Revert(&'hir Expr<'hir>),

    /// A return statement: `return 42;`.
    Return(Option<&'hir Expr<'hir>>),

    /// A break statement: `break;`.
    Break,

    /// A continue statement: `continue;`.
    Continue,

    /// A loop statement. This is desugared from all `for`, `while`, and `do while` statements.
    Loop(Block<'hir>, LoopSource),

    /// An `if` statement with an optional `else` block: `if (expr) { ... } else { ... }`.
    If(&'hir Expr<'hir>, &'hir Stmt<'hir>, Option<&'hir Stmt<'hir>>),

    /// A switch statement: `switch expr case 0 { ... } default { ... }`.
    Switch(&'hir StmtSwitch<'hir>),

    /// A try statement: `try fooBar(42) returns (...) { ... } catch (...) { ... }`.
    Try(&'hir StmtTry<'hir>),

    /// An expression with a trailing semicolon.
    Expr(&'hir Expr<'hir>),

    /// A modifier placeholder statement: `_;`.
    Placeholder,

    Err(ErrorGuaranteed),
}

/// A switch statement: `switch expr case 0 { ... } default { ... }`.
#[derive(Debug)]
pub struct StmtSwitch<'hir> {
    /// The switch selector.
    pub selector: &'hir Expr<'hir>,
    /// The cases of the switch statement. Includes the default case in the last position, if any.
    pub cases: &'hir [StmtSwitchCase<'hir>],
}

/// A case of a switch statement.
#[derive(Debug)]
pub struct StmtSwitchCase<'hir> {
    /// The span of the entire case, from `case` or `default` to the closing brace of the block.
    pub span: Span,
    /// The constant of the case, if any. `None` for the default case.
    pub constant: Option<&'hir Lit<'hir>>,
    /// The case body.
    pub body: Block<'hir>,
}

/// A try statement: `try fooBar(42) returns (...) { ... } catch (...) { ... }`.
///
/// Reference: <https://docs.soliditylang.org/en/latest/grammar.html#a4.SolidityParser.tryStatement>
#[derive(Debug)]
pub struct StmtTry<'hir> {
    /// The call expression.
    pub expr: Expr<'hir>,
    /// The list of clauses. Never empty.
    ///
    /// The first item is always the `returns` clause.
    pub clauses: &'hir [TryCatchClause<'hir>],
}

/// Clause of a try/catch block: `returns/catch (...) { ... }`.
///
/// Includes both the successful case and the unsuccessful cases.
/// Names are only allowed for unsuccessful cases.
///
/// Reference: <https://docs.soliditylang.org/en/latest/grammar.html#a4.SolidityParser.catchClause>
#[derive(Debug)]
pub struct TryCatchClause<'hir> {
    /// The span of the entire clause, from the `returns` and `catch`
    /// keywords, to the closing brace of the block.
    pub span: Span,
    /// The catch clause name: `Error`, `Panic`, or custom.
    pub name: Option<Ident>,
    /// The parameter list for the clause.
    pub args: &'hir [VariableId],
    /// A block of statements
    pub block: Block<'hir>,
}

/// The loop type that yielded an [`StmtKind::Loop`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LoopSource {
    /// A `for (...) { ... }` loop.
    For,
    /// A `while (...) { ... }` loop.
    While,
    /// A `do { ... } while (...);` loop.
    DoWhile,
}

impl LoopSource {
    /// Returns the name of the loop source.
    pub fn name(self) -> &'static str {
        match self {
            Self::For => "for",
            Self::While => "while",
            Self::DoWhile => "do while",
        }
    }
}

/// Resolved name.
#[derive(Clone, Copy, PartialEq, Eq, Hash, From, EnumIs)]
pub enum Res {
    /// A resolved item.
    Item(ItemId),
    /// Synthetic import namespace, X in `import * as X from "path"` or `import "path" as X`.
    Namespace(SourceId),
    /// A builtin symbol.
    Builtin(Builtin),
    /// An error occurred while resolving the item. Silences further errors regarding this name.
    Err(ErrorGuaranteed),
}

impl fmt::Debug for Res {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Res::")?;
        match self {
            Self::Item(id) => write!(f, "Item({id:?})"),
            Self::Namespace(id) => write!(f, "Namespace({id:?})"),
            Self::Builtin(b) => write!(f, "Builtin({b:?})"),
            Self::Err(_) => f.write_str("Err"),
        }
    }
}

macro_rules! impl_try_from {
    ($($t:ty => $pat:pat => $e:expr),* $(,)?) => {
        $(
            impl TryFrom<Res> for $t {
                type Error = ();

                fn try_from(decl: Res) -> Result<Self, ()> {
                    match decl {
                        $pat => $e,
                        _ => Err(()),
                    }
                }
            }
        )*
    };
}

impl_try_from!(
    ItemId => Res::Item(id) => Ok(id),
    ContractId => Res::Item(ItemId::Contract(id)) => Ok(id),
    // FunctionId => Res::Item(ItemId::Function(id)) => Ok(id),
    EventId => Res::Item(ItemId::Event(id)) => Ok(id),
    ErrorId => Res::Item(ItemId::Error(id)) => Ok(id),
);

impl Res {
    pub fn description(&self) -> &'static str {
        match self {
            Self::Item(item) => item.description(),
            Self::Namespace(_) => "namespace",
            Self::Builtin(_) => "builtin",
            Self::Err(_) => "<error>",
        }
    }

    pub fn matches(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Item(a), Self::Item(b)) => a.matches(b),
            _ => std::mem::discriminant(self) == std::mem::discriminant(other),
        }
    }

    pub fn as_variable(&self) -> Option<VariableId> {
        if let Self::Item(id) = self { id.as_variable() } else { None }
    }
}

/// An expression.
#[derive(Debug)]
pub struct Expr<'hir> {
    pub id: ExprId,
    pub kind: ExprKind<'hir>,
    /// The expression span.
    pub span: Span,
}

impl Expr<'_> {
    /// Peels off unnecessary parentheses from the expression.
    pub fn peel_parens(&self) -> &Self {
        let mut expr = self;
        while let ExprKind::Tuple([Some(inner)]) = expr.kind {
            expr = inner;
        }
        expr
    }
}

/// A kind of expression.
#[derive(Debug)]
pub enum ExprKind<'hir> {
    /// An array literal expression: `[a, b, c, d]`.
    Array(&'hir [Expr<'hir>]),

    /// An assignment: `a = b`, `a += b`.
    Assign(&'hir Expr<'hir>, Option<BinOp>, &'hir Expr<'hir>),

    /// A binary operation: `a + b`, `a >> b`.
    Binary(&'hir Expr<'hir>, BinOp, &'hir Expr<'hir>),

    /// A function call expression: `foo(42)`, `foo({ bar: 42 })`, `foo{ gas: 100_000 }(42)`.
    Call(&'hir Expr<'hir>, CallArgs<'hir>, Option<&'hir CallOptions<'hir>>),

    // TODO: Add a MethodCall variant
    /// A unary `delete` expression: `delete vector`.
    Delete(&'hir Expr<'hir>),

    /// A resolved symbol: `foo`.
    ///
    /// Potentially multiple references if it refers to something like an overloaded function.
    Ident(&'hir [Res]),

    /// A square bracketed indexing expression: `vector[index]`, `MyType[]`.
    Index(&'hir Expr<'hir>, Option<&'hir Expr<'hir>>),

    /// A square bracketed slice expression: `slice[l:r]`.
    Slice(&'hir Expr<'hir>, Option<&'hir Expr<'hir>>, Option<&'hir Expr<'hir>>),

    /// A literal: `hex"1234"`, `5.6 ether`.
    Lit(&'hir Lit<'hir>),

    /// Access of a named member: `obj.k`.
    Member(&'hir Expr<'hir>, Ident),

    /// A `new` expression: `new Contract`.
    New(Type<'hir>),

    /// A `payable` expression: `payable(address(0x...))`.
    Payable(&'hir Expr<'hir>),

    /// A ternary (AKA conditional) expression: `foo ? bar : baz`.
    Ternary(&'hir Expr<'hir>, &'hir Expr<'hir>, &'hir Expr<'hir>),

    /// A tuple expression: `(a,,, b, c, d)`.
    Tuple(&'hir [Option<&'hir Expr<'hir>>]),

    /// A `type()` expression: `type(uint256)`.
    TypeCall(Type<'hir>),

    /// An elementary type name: `uint256`.
    Type(Type<'hir>),

    /// A unary operation: `!x`, `-x`, `x++`.
    Unary(UnOp, &'hir Expr<'hir>),

    /// A dotted Yul identifier path.
    YulMember(&'hir Expr<'hir>, Ident),

    Err(ErrorGuaranteed),
}

/// A named argument: `name: value`.
#[derive(Debug)]
pub struct NamedArg<'hir> {
    pub name: Ident,
    pub value: Expr<'hir>,
}

/// Function call options: `foo{ gas: 100_000 }`.
#[derive(Clone, Copy, Debug)]
pub struct CallOptions<'hir> {
    pub span: Span,
    pub args: &'hir [NamedArg<'hir>],
}

/// A list of function call arguments.
#[derive(Clone, Copy, Debug)]
pub struct CallArgs<'hir> {
    /// The span of the arguments. This points to the parenthesized list of arguments.
    ///
    /// If the list is empty, this points to the empty `()`/`({})` or to where the `(` would be.
    pub span: Span,
    pub kind: CallArgsKind<'hir>,
}

impl<'hir> Default for CallArgs<'hir> {
    fn default() -> Self {
        Self::empty(Span::DUMMY)
    }
}

impl<'hir> CallArgs<'hir> {
    /// Creates a new empty list of arguments.
    ///
    /// `span` should be an empty span.
    pub fn empty(span: Span) -> Self {
        Self { span, kind: CallArgsKind::empty() }
    }

    /// Returns `true` if the argument list is not present in the source code.
    ///
    /// For example, a modifier `m` can be invoked in a function declaration as `m` or `m()`. In the
    /// first case, this returns `true`, and the span will point to after `m`. In the second case,
    /// this returns `false`.
    pub fn is_dummy(&self) -> bool {
        self.span.lo() == self.span.hi()
    }

    /// Returns the length of the arguments.
    pub fn len(&self) -> usize {
        self.kind.len()
    }

    /// Returns `true` if the list of arguments is empty.
    pub fn is_empty(&self) -> bool {
        self.kind.is_empty()
    }

    /// Returns an iterator over the expressions.
    pub fn exprs(
        &self,
    ) -> impl ExactSizeIterator<Item = &Expr<'hir>> + DoubleEndedIterator + Clone {
        self.kind.exprs()
    }
}

/// A list of function call argument expressions.
#[derive(Clone, Copy, Debug)]
pub enum CallArgsKind<'hir> {
    /// A list of unnamed arguments: `(1, 2, 3)`.
    Unnamed(&'hir [Expr<'hir>]),

    /// A list of named arguments: `({x: 1, y: 2, z: 3})`.
    Named(&'hir [NamedArg<'hir>]),
}

impl Default for CallArgsKind<'_> {
    fn default() -> Self {
        Self::empty()
    }
}

impl<'hir> CallArgsKind<'hir> {
    /// Creates a new empty list of unnamed arguments.
    pub fn empty() -> Self {
        Self::Unnamed(Default::default())
    }

    /// Returns the length of the arguments.
    pub fn len(&self) -> usize {
        match self {
            Self::Unnamed(exprs) => exprs.len(),
            Self::Named(args) => args.len(),
        }
    }

    /// Returns `true` if the list of arguments is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns an iterator over the expressions.
    pub fn exprs(
        &self,
    ) -> impl ExactSizeIterator<Item = &Expr<'hir>> + DoubleEndedIterator + Clone {
        match self {
            Self::Unnamed(exprs) => Either::Left(exprs.iter()),
            Self::Named(args) => Either::Right(args.iter().map(|arg| &arg.value)),
        }
    }

    /// Returns the span of the argument expressions. Does not include the parentheses.
    pub fn span(&self) -> Option<Span> {
        if self.is_empty() {
            return None;
        }
        Some(Span::join_first_last(self.exprs().map(|e| e.span)))
    }
}

/// A type name.
#[derive(Clone, Debug)]
pub struct Type<'hir> {
    pub span: Span,
    pub kind: TypeKind<'hir>,
}

impl<'hir> Type<'hir> {
    /// Dummy placeholder type.
    pub const DUMMY: Self =
        Self { span: Span::DUMMY, kind: TypeKind::Err(ErrorGuaranteed::new_unchecked()) };

    /// Returns `true` if the type is a dummy type.
    pub fn is_dummy(&self) -> bool {
        self.span == Span::DUMMY && matches!(self.kind, TypeKind::Err(_))
    }

    pub fn visit<T>(
        &self,
        hir: &Hir<'hir>,
        f: &mut impl FnMut(&Self) -> ControlFlow<T>,
    ) -> ControlFlow<T> {
        f(self)?;
        match self.kind {
            TypeKind::Elementary(_) => ControlFlow::Continue(()),
            TypeKind::Array(ty) => ty.element.visit(hir, f),
            TypeKind::Function(ty) => {
                for &param in ty.parameters {
                    hir.variable(param).ty.visit(hir, f)?;
                }
                for &ret in ty.returns {
                    hir.variable(ret).ty.visit(hir, f)?;
                }
                ControlFlow::Continue(())
            }
            TypeKind::Mapping(ty) => {
                ty.key.visit(hir, f)?;
                ty.value.visit(hir, f)
            }
            TypeKind::Custom(_) => ControlFlow::Continue(()),
            TypeKind::Err(_) => ControlFlow::Continue(()),
        }
    }
}

/// The kind of a type.
#[derive(Clone, Debug)]
pub enum TypeKind<'hir> {
    /// An elementary/primitive type.
    Elementary(ElementaryType),

    /// `$element[$($size)?]`
    Array(&'hir TypeArray<'hir>),
    /// `function($($parameters),*) $($attributes)* $(returns ($($returns),+))?`
    Function(&'hir TypeFunction<'hir>),
    /// `mapping($key $($key_name)? => $value $($value_name)?)`
    Mapping(&'hir TypeMapping<'hir>),

    /// A custom type name.
    Custom(ItemId),

    Err(ErrorGuaranteed),
}

impl TypeKind<'_> {
    /// Returns `true` if the type is an elementary type.
    pub fn is_elementary(&self) -> bool {
        matches!(self, Self::Elementary(_))
    }

    /// Returns `true` if the type is a reference type.
    #[inline]
    pub fn is_reference_type(&self) -> bool {
        match self {
            TypeKind::Elementary(t) => t.is_reference_type(),
            TypeKind::Custom(ItemId::Struct(_)) | TypeKind::Array(_) | TypeKind::Mapping(_) => true,
            _ => false,
        }
    }
}

/// An array type.
#[derive(Debug)]
pub struct TypeArray<'hir> {
    pub element: Type<'hir>,
    pub size: Option<&'hir Expr<'hir>>,
}

/// A function type name.
#[derive(Debug)]
pub struct TypeFunction<'hir> {
    pub parameters: &'hir [VariableId],
    pub visibility: Visibility,
    pub state_mutability: StateMutability,
    pub returns: &'hir [VariableId],
}

/// A mapping type.
#[derive(Debug)]
pub struct TypeMapping<'hir> {
    pub key: Type<'hir>,
    pub key_name: Option<Ident>,
    pub value: Type<'hir>,
    pub value_name: Option<Ident>,
}

#[cfg(test)]
mod tests {
    use super::*;

    // Ensure that we track the size of individual HIR nodes.
    #[test]
    #[cfg_attr(not(target_pointer_width = "64"), ignore = "64-bit only")]
    #[cfg_attr(feature = "nightly", ignore = "stable only")]
    fn sizes() {
        use snapbox::{assert_data_eq, str};
        #[track_caller]
        fn assert_size<T>(size: impl snapbox::IntoData) {
            assert_size_(std::mem::size_of::<T>(), size.into_data());
        }
        #[track_caller]
        fn assert_size_(actual: usize, expected: snapbox::Data) {
            assert_data_eq!(actual.to_string(), expected);
        }

        assert_size::<Hir<'_>>(str!["240"]);

        assert_size::<Item<'_, '_>>(str!["16"]);
        assert_size::<Contract<'_>>(str!["152"]);
        assert_size::<Function<'_>>(str!["144"]);
        assert_size::<Struct<'_>>(str!["48"]);
        assert_size::<Enum<'_>>(str!["48"]);
        assert_size::<Udvt<'_>>(str!["56"]);
        assert_size::<Error<'_>>(str!["48"]);
        assert_size::<Event<'_>>(str!["56"]);
        assert_size::<Variable<'_>>(str!["104"]);

        assert_size::<TypeKind<'_>>(str!["16"]);
        assert_size::<Type<'_>>(str!["24"]);

        assert_size::<ExprKind<'_>>(str!["48"]);
        assert_size::<Expr<'_>>(str!["64"]);

        assert_size::<StmtKind<'_>>(str!["32"]);
        assert_size::<Stmt<'_>>(str!["40"]);
        assert_size::<Block<'_>>(str!["24"]);
    }
}