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
// SPDX-License-Identifier: Apache-2.0

//! Solidity parse tree data structures.
//!
//! See also the [Solidity documentation][sol].
//!
//! [sol]: https://docs.soliditylang.org/en/latest/grammar.html

// backwards compatibility re-export
#[doc(hidden)]
pub use crate::helpers::{CodeLocation, OptionalCodeLocation};

#[cfg(feature = "pt-serde")]
use serde::{Deserialize, Serialize};

/// A code location.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub enum Loc {
    /// Builtin
    Builtin,
    /// Command line
    CommandLine,
    /// Implicit
    Implicit,
    /// Codegen
    Codegen,
    /// The file number, start offset and end offset in bytes of the source file.
    File(usize, usize, usize),
}

impl Default for Loc {
    fn default() -> Self {
        Self::File(0, 0, 0)
    }
}

#[inline(never)]
#[cold]
#[track_caller]
fn not_a_file() -> ! {
    panic!("location is not a file")
}

impl Loc {
    /// Returns this location's beginning range.
    #[inline]
    pub fn begin_range(&self) -> Self {
        match self {
            Loc::File(file_no, start, _) => Loc::File(*file_no, *start, *start),
            loc => *loc,
        }
    }

    /// Returns this location's end range.
    #[inline]
    pub fn end_range(&self) -> Self {
        match self {
            Loc::File(file_no, _, end) => Loc::File(*file_no, *end, *end),
            loc => *loc,
        }
    }

    /// Returns this location's file number.
    ///
    /// # Panics
    ///
    /// If this location is not a file.
    #[track_caller]
    #[inline]
    pub fn file_no(&self) -> usize {
        match self {
            Loc::File(file_no, _, _) => *file_no,
            _ => not_a_file(),
        }
    }

    /// Returns this location's file number if it is a file, otherwise `None`.
    #[inline]
    pub fn try_file_no(&self) -> Option<usize> {
        match self {
            Loc::File(file_no, _, _) => Some(*file_no),
            _ => None,
        }
    }

    /// Returns this location's start.
    ///
    /// # Panics
    ///
    /// If this location is not a file.
    #[track_caller]
    #[inline]
    pub fn start(&self) -> usize {
        match self {
            Loc::File(_, start, _) => *start,
            _ => not_a_file(),
        }
    }

    /// Returns this location's end.
    ///
    /// # Panics
    ///
    /// If this location is not a file.
    #[track_caller]
    #[inline]
    pub fn end(&self) -> usize {
        match self {
            Loc::File(_, _, end) => *end,
            _ => not_a_file(),
        }
    }

    /// Returns this location's end.
    /// The returned endpoint is not part of the range.
    /// This is used when a half-open range is needed.
    ///
    /// # Panics
    ///
    /// If this location is not a file.
    #[track_caller]
    #[inline]
    pub fn exclusive_end(&self) -> usize {
        self.end() + 1
    }

    /// Replaces this location's start with `other`'s.
    ///
    /// # Panics
    ///
    /// If this location is not a file.
    #[track_caller]
    #[inline]
    pub fn use_start_from(&mut self, other: &Loc) {
        match (self, other) {
            (Loc::File(_, start, _), Loc::File(_, other_start, _)) => {
                *start = *other_start;
            }
            _ => not_a_file(),
        }
    }

    /// Replaces this location's end with `other`'s.
    ///
    /// # Panics
    ///
    /// If this location is not a file.
    #[track_caller]
    #[inline]
    pub fn use_end_from(&mut self, other: &Loc) {
        match (self, other) {
            (Loc::File(_, _, end), Loc::File(_, _, other_end)) => {
                *end = *other_end;
            }
            _ => not_a_file(),
        }
    }

    /// See [`Loc::use_start_from`].
    ///
    /// # Panics
    ///
    /// If this location is not a file.
    #[track_caller]
    #[inline]
    pub fn with_start_from(mut self, other: &Self) -> Self {
        self.use_start_from(other);
        self
    }

    /// See [`Loc::use_end_from`].
    ///
    /// # Panics
    ///
    /// If this location is not a file.
    #[track_caller]
    #[inline]
    pub fn with_end_from(mut self, other: &Self) -> Self {
        self.use_end_from(other);
        self
    }

    /// Creates a new `Loc::File` by replacing `start`.
    ///
    /// # Panics
    ///
    /// If this location is not a file.
    #[track_caller]
    #[inline]
    pub fn with_start(self, start: usize) -> Self {
        match self {
            Self::File(no, _, end) => Self::File(no, start, end),
            _ => not_a_file(),
        }
    }

    /// Creates a new `Loc::File` by replacing `end`.
    ///
    /// # Panics
    ///
    /// If this location is not a file.
    #[track_caller]
    #[inline]
    pub fn with_end(self, end: usize) -> Self {
        match self {
            Self::File(no, start, _) => Self::File(no, start, end),
            _ => not_a_file(),
        }
    }

    /// Returns this location's range.
    ///
    /// # Panics
    ///
    /// If this location is not a file.
    #[track_caller]
    #[inline]
    pub fn range(self) -> std::ops::Range<usize> {
        match self {
            Self::File(_, start, end) => start..end,
            _ => not_a_file(),
        }
    }

    /// Performs the union of two locations
    pub fn union(&mut self, other: &Self) {
        match (self, other) {
            (Self::File(r_file, r_start, r_end), Self::File(l_file, l_start, l_end)) => {
                assert_eq!(r_file, l_file, "cannot perform union in different files");
                *r_start = std::cmp::min(*r_start, *l_start);
                *r_end = std::cmp::max(*r_end, *l_end);
            }

            _ => unimplemented!("cannot perform union in non File Loc"),
        }
    }
}

/// An identifier.
///
/// `<name>`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct Identifier {
    /// The code location.
    pub loc: Loc,
    /// The identifier string.
    pub name: String,
}

impl Identifier {
    /// Creates a new identifier.
    pub fn new(s: impl Into<String>) -> Self {
        Self {
            loc: Loc::default(),
            name: s.into(),
        }
    }
}

/// A qualified identifier.
///
/// `<identifiers>.*`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct IdentifierPath {
    /// The code location.
    pub loc: Loc,
    /// The list of identifiers.
    pub identifiers: Vec<Identifier>,
}

/// A comment or [doc comment][natspec].
///
/// [natspec]: https://docs.soliditylang.org/en/latest/natspec-format.html
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub enum Comment {
    /// A line comment.
    ///
    /// `// line comment`
    Line(Loc, String),

    /// A block doc comment.
    ///
    /// ` /* block comment */ `
    Block(Loc, String),

    /// A line doc comment.
    ///
    /// `/// line doc comment`
    DocLine(Loc, String),

    /// A block doc comment.
    ///
    /// ```text
    /// /**
    ///  * block doc comment
    ///  */
    /// ```
    DocBlock(Loc, String),
}

impl Comment {
    /// Returns the comment's value.
    #[inline]
    pub const fn value(&self) -> &String {
        match self {
            Self::Line(_, s) | Self::Block(_, s) | Self::DocLine(_, s) | Self::DocBlock(_, s) => s,
        }
    }

    /// Returns whether this is a doc comment.
    #[inline]
    pub const fn is_doc(&self) -> bool {
        matches!(self, Self::DocLine(..) | Self::DocBlock(..))
    }

    /// Returns whether this is a line comment.
    #[inline]
    pub const fn is_line(&self) -> bool {
        matches!(self, Self::Line(..) | Self::DocLine(..))
    }

    /// Returns whether this is a block comment.
    #[inline]
    pub const fn is_block(&self) -> bool {
        !self.is_line()
    }
}

/// The source unit of the parse tree.
///
/// Contains all of the parse tree's parts in a vector.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct SourceUnit(pub Vec<SourceUnitPart>);

/// A parse tree part.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub enum SourceUnitPart {
    /// A pragma directive.
    ///
    /// `pragma <1> <2>;`
    ///
    /// `1` and `2` are `None` only if an error occurred during parsing.
    PragmaDirective(Box<PragmaDirective>),

    /// An import directive.
    ImportDirective(Import),

    /// A contract definition.
    ContractDefinition(Box<ContractDefinition>),

    /// An enum definition.
    EnumDefinition(Box<EnumDefinition>),

    /// A struct definition.
    StructDefinition(Box<StructDefinition>),

    /// An event definition.
    EventDefinition(Box<EventDefinition>),

    /// An error definition.
    ErrorDefinition(Box<ErrorDefinition>),

    /// A function definition.
    FunctionDefinition(Box<FunctionDefinition>),

    /// A variable definition.
    VariableDefinition(Box<VariableDefinition>),

    /// A type definition.
    TypeDefinition(Box<TypeDefinition>),

    /// An annotation.
    Annotation(Box<Annotation>),

    /// A `using` directive.
    Using(Box<Using>),

    /// A stray semicolon.
    StraySemicolon(Loc),
}

/// An import statement.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub enum Import {
    /// `import <0>;`
    Plain(ImportPath, Loc),

    /// `import * as <1> from <0>;`
    ///
    /// or
    ///
    /// `import <0> as <1>;`
    GlobalSymbol(ImportPath, Identifier, Loc),

    /// `import { <<1.0> [as <1.1>]>,* } from <0>;`
    Rename(ImportPath, Vec<(Identifier, Option<Identifier>)>, Loc),
}

/// An import statement.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub enum ImportPath {
    /// "foo.sol"
    Filename(StringLiteral),
    /// std.stub (experimental Solidity feature)
    Path(IdentifierPath),
}

impl Import {
    /// Returns the import string.
    #[inline]
    pub const fn literal(&self) -> Option<&StringLiteral> {
        match self {
            Self::Plain(ImportPath::Filename(literal), _)
            | Self::GlobalSymbol(ImportPath::Filename(literal), _, _)
            | Self::Rename(ImportPath::Filename(literal), _, _) => Some(literal),
            _ => None,
        }
    }
}

/// Type alias for a list of function parameters.
pub type ParameterList = Vec<(Loc, Option<Parameter>)>;

/// A type.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub enum Type {
    /// `address`
    Address,

    /// `address payable`
    AddressPayable,

    /// `payable`
    ///
    /// Only used as a cast.
    Payable,

    /// `bool`
    Bool,

    /// `string`
    String,

    /// `int<n>`
    Int(u16),

    /// `uint<n>`
    Uint(u16),

    /// `bytes<n>`
    Bytes(u8),

    /// `fixed`
    Rational,

    /// `bytes`
    DynamicBytes,

    /// `mapping(<key> [key_name] => <value> [value_name])`
    Mapping {
        /// The code location.
        loc: Loc,
        /// The key expression.
        ///
        /// This is only allowed to be an elementary type or a user defined type.
        key: Box<Expression>,
        /// The optional key identifier.
        key_name: Option<Identifier>,
        /// The value expression.
        value: Box<Expression>,
        /// The optional value identifier.
        value_name: Option<Identifier>,
    },

    /// `function (<params>) <attributes> [returns]`
    Function {
        /// The list of parameters.
        params: ParameterList,
        /// The list of attributes.
        attributes: Vec<FunctionAttribute>,
        /// The optional list of return parameters.
        returns: Option<(ParameterList, Vec<FunctionAttribute>)>,
    },
}

/// Dynamic type location.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub enum StorageLocation {
    /// `memory`
    Memory(Loc),

    /// `storage`
    Storage(Loc),

    /// `calldata`
    Calldata(Loc),
}

/// A variable declaration.
///
/// `<ty> [storage] <name>`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct VariableDeclaration {
    /// The code location.
    pub loc: Loc,
    /// The type.
    pub ty: Expression,
    /// The optional memory location.
    pub storage: Option<StorageLocation>,
    /// The identifier.
    ///
    /// This field is `None` only if an error occurred during parsing.
    pub name: Option<Identifier>,
}

/// A struct definition.
///
/// `struct <name> { <fields>;* }`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct StructDefinition {
    /// The code location.
    pub loc: Loc,
    /// The identifier.
    ///
    /// This field is `None` only if an error occurred during parsing.
    pub name: Option<Identifier>,
    /// The list of fields.
    pub fields: Vec<VariableDeclaration>,
}

/// A contract part.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub enum ContractPart {
    /// A struct definition.
    StructDefinition(Box<StructDefinition>),

    /// An event definition.
    EventDefinition(Box<EventDefinition>),

    /// An enum definition.
    EnumDefinition(Box<EnumDefinition>),

    /// An error definition.
    ErrorDefinition(Box<ErrorDefinition>),

    /// A variable definition.
    VariableDefinition(Box<VariableDefinition>),

    /// A function definition.
    FunctionDefinition(Box<FunctionDefinition>),

    /// A type definition.
    TypeDefinition(Box<TypeDefinition>),

    /// A definition.
    Annotation(Box<Annotation>),

    /// A `using` directive.
    Using(Box<Using>),

    /// A stray semicolon.
    StraySemicolon(Loc),
}

/// A pragma directive
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub enum PragmaDirective {
    /// pragma a b;
    Identifier(Loc, Option<Identifier>, Option<Identifier>),
    /// pragma a "b";
    StringLiteral(Loc, Identifier, StringLiteral),
    /// pragma version =0.5.16;
    Version(Loc, Identifier, Vec<VersionComparator>),
}

/// A `version` list
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub enum VersionComparator {
    /// 0.8.22
    Plain {
        /// The code location.
        loc: Loc,
        /// List of versions: major, minor, patch. minor and patch are optional
        version: Vec<String>,
    },
    /// =0.5.16
    Operator {
        /// The code location.
        loc: Loc,
        /// Semver comparison operator
        op: VersionOp,
        /// version number
        version: Vec<String>,
    },
    /// foo || bar
    Or {
        /// The code location.
        loc: Loc,
        /// left part
        left: Box<VersionComparator>,
        /// right part
        right: Box<VersionComparator>,
    },
    /// 0.7.0 - 0.8.22
    Range {
        /// The code location.
        loc: Loc,
        /// start of range
        from: Vec<String>,
        /// end of range
        to: Vec<String>,
    },
}

/// Comparison operator
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub enum VersionOp {
    /// `=`
    Exact,
    /// `>`
    Greater,
    /// `>=`
    GreaterEq,
    /// `<`
    Less,
    /// `<=`
    LessEq,
    /// `~`
    Tilde,
    /// `^`
    Caret,
    /// `*`
    Wildcard,
}

/// A `using` list. See [Using].
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub enum UsingList {
    /// A single identifier path.
    Library(IdentifierPath),

    /// List of using functions.
    ///
    /// `{ <<identifier path> [ as <operator> ]>,* }`
    Functions(Vec<UsingFunction>),

    /// An error occurred during parsing.
    Error,
}

/// A `using` function. See [UsingList].
///
/// `<path> [ as <oper> ]`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct UsingFunction {
    /// The code location.
    pub loc: Loc,
    /// The identifier path.
    pub path: IdentifierPath,
    /// The optional user-defined operator.
    pub oper: Option<UserDefinedOperator>,
}

/// A user-defined operator.
///
/// See also the [Solidity blog post][ref] on user-defined operators.
///
/// [ref]: https://blog.soliditylang.org/2023/02/22/user-defined-operators/
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub enum UserDefinedOperator {
    /// `&`
    BitwiseAnd,
    /// `~`
    ///
    BitwiseNot,
    /// `-`
    ///
    /// Note that this is the same as `Subtract`, and that it is currently not being parsed.
    Negate,
    /// `|`
    BitwiseOr,
    /// `^`
    BitwiseXor,
    /// `+`
    Add,
    /// `/`
    Divide,
    /// `%`
    Modulo,
    /// `*`
    Multiply,
    /// `-`
    Subtract,
    /// `==`
    Equal,
    /// `>`
    More,
    /// `>=`
    MoreEqual,
    /// `<`
    Less,
    /// `<=`
    LessEqual,
    /// `!=`
    NotEqual,
}

impl UserDefinedOperator {
    /// Returns the number of arguments needed for this operator's operation.
    #[inline]
    pub const fn args(&self) -> usize {
        match self {
            UserDefinedOperator::BitwiseNot | UserDefinedOperator::Negate => 1,
            _ => 2,
        }
    }

    /// Returns whether `self` is a unary operator.
    #[inline]
    pub const fn is_unary(&self) -> bool {
        matches!(self, Self::BitwiseNot | Self::Negate)
    }

    /// Returns whether `self` is a binary operator.
    #[inline]
    pub const fn is_binary(&self) -> bool {
        !self.is_unary()
    }

    /// Returns whether `self` is a bitwise operator.
    #[inline]
    pub const fn is_bitwise(&self) -> bool {
        matches!(
            self,
            Self::BitwiseAnd | Self::BitwiseOr | Self::BitwiseXor | Self::BitwiseNot
        )
    }

    /// Returns whether `self` is an arithmetic operator.
    #[inline]
    pub const fn is_arithmetic(&self) -> bool {
        matches!(
            self,
            Self::Add | Self::Subtract | Self::Multiply | Self::Divide | Self::Modulo
        )
    }

    /// Returns whether this is a comparison operator.
    #[inline]
    pub const fn is_comparison(&self) -> bool {
        matches!(
            self,
            Self::Equal
                | Self::NotEqual
                | Self::Less
                | Self::LessEqual
                | Self::More
                | Self::MoreEqual
        )
    }
}

/// A `using` directive.
///
/// Can occur within contracts and libraries and at the file level.
///
/// `using <list> for <type | '*'> [global];`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct Using {
    /// The code location.
    pub loc: Loc,
    /// The list of `using` functions or a single identifier path.
    pub list: UsingList,
    /// The type.
    ///
    /// This field is `None` if an error occurred or the specified type is `*`.
    pub ty: Option<Expression>,
    /// The optional `global` identifier.
    pub global: Option<Identifier>,
}

/// The contract type.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub enum ContractTy {
    /// `abstract contract`
    Abstract(Loc),

    /// `contract`
    Contract(Loc),

    /// `interface`
    Interface(Loc),

    /// `library`
    Library(Loc),
}

/// A function modifier invocation (see [FunctionAttribute])
/// or a contract inheritance specifier (see [ContractDefinition]).
///
/// Both have the same semantics:
///
/// `<name>[(<args>,*)]`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct Base {
    /// The code location.
    pub loc: Loc,
    /// The identifier path.
    pub name: IdentifierPath,
    /// The optional arguments.
    pub args: Option<Vec<Expression>>,
}

/// A contract definition.
///
/// `<ty> <name> [<base>,*] { <parts>,* }`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct ContractDefinition {
    /// The code location.
    pub loc: Loc,
    /// The contract type.
    pub ty: ContractTy,
    /// The identifier.
    ///
    /// This field is `None` only if an error occurred during parsing.
    pub name: Option<Identifier>,
    /// The list of inheritance specifiers.
    pub base: Vec<Base>,
    /// The list of contract parts.
    pub parts: Vec<ContractPart>,
}

/// An event parameter.
///
/// `<ty> [indexed] [name]`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct EventParameter {
    /// The code location.
    pub loc: Loc,
    /// The type.
    pub ty: Expression,
    /// Whether this parameter is indexed.
    pub indexed: bool,
    /// The optional identifier.
    pub name: Option<Identifier>,
}

/// An event definition.
///
/// `event <name>(<fields>,*) [anonymous];`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct EventDefinition {
    /// The code location.
    pub loc: Loc,
    /// The identifier.
    ///
    /// This field is `None` only if an error occurred during parsing.
    pub name: Option<Identifier>,
    /// The list of event parameters.
    pub fields: Vec<EventParameter>,
    /// Whether this event is anonymous.
    pub anonymous: bool,
}

/// An error parameter.
///
/// `<ty> [name]`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct ErrorParameter {
    /// The code location.
    pub loc: Loc,
    /// The type.
    pub ty: Expression,
    /// The optional identifier.
    pub name: Option<Identifier>,
}

/// An error definition.
///
/// `error <name> (<fields>,*);`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct ErrorDefinition {
    /// The code location.
    pub loc: Loc,
    /// The `error` keyword.
    pub keyword: Expression,
    /// The identifier.
    ///
    /// This field is `None` only if an error occurred during parsing.
    pub name: Option<Identifier>,
    /// The list of error parameters.
    pub fields: Vec<ErrorParameter>,
}

/// An enum definition.
///
/// `enum <name> { <values>,* }`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct EnumDefinition {
    /// The code location.
    pub loc: Loc,
    /// The identifier.
    ///
    /// This field is `None` only if an error occurred during parsing.
    pub name: Option<Identifier>,
    /// The list of values.
    ///
    /// This field contains `None` only if an error occurred during parsing.
    pub values: Vec<Option<Identifier>>,
}

/// A variable attribute.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
#[repr(u8)] // for cmp; order of variants is important
pub enum VariableAttribute {
    /// The visibility.
    ///
    /// Only used for storage variables.
    Visibility(Visibility),

    /// `constant`
    Constant(Loc),

    /// `immutable`
    Immutable(Loc),

    /// `ovveride(<1>,*)`
    Override(Loc, Vec<IdentifierPath>),
}

/// A variable definition.
///
/// `<ty> <attrs>* <name> [= <initializer>]`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct VariableDefinition {
    /// The code location.
    pub loc: Loc,
    /// The type.
    pub ty: Expression,
    /// The list of variable attributes.
    pub attrs: Vec<VariableAttribute>,
    /// The identifier.
    ///
    /// This field is `None` only if an error occurred during parsing.
    pub name: Option<Identifier>,
    /// The optional initializer.
    pub initializer: Option<Expression>,
}

/// A user type definition.
///
/// `type <name> is <ty>;`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct TypeDefinition {
    /// The code location.
    pub loc: Loc,
    /// The user-defined type name.
    pub name: Identifier,
    /// The type expression.
    pub ty: Expression,
}

/// An annotation.
///
/// `@<id>(<value>)`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct Annotation {
    /// The code location.
    pub loc: Loc,
    /// The identifier.
    pub id: Identifier,
    /// The value.
    pub value: Option<Expression>,
}

/// A string literal.
///
/// `[unicode]"<string>"`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct StringLiteral {
    /// The code location.
    pub loc: Loc,
    /// Whether this is a unicode string.
    pub unicode: bool,
    /// The string literal.
    ///
    /// Does not contain the quotes or the `unicode` prefix.
    pub string: String,
}

/// A hex literal.
///
/// `hex"<literal>"`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct HexLiteral {
    /// The code location.
    pub loc: Loc,
    /// The hex literal.
    ///
    /// Contains the `hex` prefix.
    pub hex: String,
}

/// A named argument.
///
/// `<name>: <expr>`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct NamedArgument {
    /// The code location.
    pub loc: Loc,
    /// The identifier.
    pub name: Identifier,
    /// The value.
    pub expr: Expression,
}

/// An expression.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub enum Expression {
    /// `<1>++`
    PostIncrement(Loc, Box<Expression>),
    /// `<1>--`
    PostDecrement(Loc, Box<Expression>),
    /// `new <1>`
    New(Loc, Box<Expression>),
    /// `<1>\[ [2] \]`
    ArraySubscript(Loc, Box<Expression>, Option<Box<Expression>>),
    /// `<1>\[ [2] : [3] \]`
    ArraySlice(
        Loc,
        Box<Expression>,
        Option<Box<Expression>>,
        Option<Box<Expression>>,
    ),
    /// `(<1>)`
    Parenthesis(Loc, Box<Expression>),
    /// `<1>.<2>`
    MemberAccess(Loc, Box<Expression>, Identifier),
    /// `<1>(<2>,*)`
    FunctionCall(Loc, Box<Expression>, Vec<Expression>),
    /// `<1><2>` where <2> is a block.
    FunctionCallBlock(Loc, Box<Expression>, Box<Statement>),
    /// `<1>({ <2>,* })`
    NamedFunctionCall(Loc, Box<Expression>, Vec<NamedArgument>),
    /// `!<1>`
    Not(Loc, Box<Expression>),
    /// `~<1>`
    BitwiseNot(Loc, Box<Expression>),
    /// `delete <1>`
    Delete(Loc, Box<Expression>),
    /// `++<1>`
    PreIncrement(Loc, Box<Expression>),
    /// `--<1>`
    PreDecrement(Loc, Box<Expression>),
    /// `+<1>`
    ///
    /// Note that this isn't actually supported by Solidity.
    UnaryPlus(Loc, Box<Expression>),
    /// `-<1>`
    Negate(Loc, Box<Expression>),

    /// `<1> ** <2>`
    Power(Loc, Box<Expression>, Box<Expression>),
    /// `<1> * <2>`
    Multiply(Loc, Box<Expression>, Box<Expression>),
    /// `<1> / <2>`
    Divide(Loc, Box<Expression>, Box<Expression>),
    /// `<1> % <2>`
    Modulo(Loc, Box<Expression>, Box<Expression>),
    /// `<1> + <2>`
    Add(Loc, Box<Expression>, Box<Expression>),
    /// `<1> - <2>`
    Subtract(Loc, Box<Expression>, Box<Expression>),
    /// `<1> << <2>`
    ShiftLeft(Loc, Box<Expression>, Box<Expression>),
    /// `<1> >> <2>`
    ShiftRight(Loc, Box<Expression>, Box<Expression>),
    /// `<1> & <2>`
    BitwiseAnd(Loc, Box<Expression>, Box<Expression>),
    /// `<1> ^ <2>`
    BitwiseXor(Loc, Box<Expression>, Box<Expression>),
    /// `<1> | <2>`
    BitwiseOr(Loc, Box<Expression>, Box<Expression>),
    /// `<1> < <2>`
    Less(Loc, Box<Expression>, Box<Expression>),
    /// `<1> > <2>`
    More(Loc, Box<Expression>, Box<Expression>),
    /// `<1> <= <2>`
    LessEqual(Loc, Box<Expression>, Box<Expression>),
    /// `<1> >= <2>`
    MoreEqual(Loc, Box<Expression>, Box<Expression>),
    /// `<1> == <2>`
    Equal(Loc, Box<Expression>, Box<Expression>),
    /// `<1> != <2>`
    NotEqual(Loc, Box<Expression>, Box<Expression>),
    /// `<1> && <2>`
    And(Loc, Box<Expression>, Box<Expression>),
    /// `<1> || <2>`
    Or(Loc, Box<Expression>, Box<Expression>),
    /// `<1> ? <2> : <3>`
    ///
    /// AKA ternary operator.
    ConditionalOperator(Loc, Box<Expression>, Box<Expression>, Box<Expression>),
    /// `<1> = <2>`
    Assign(Loc, Box<Expression>, Box<Expression>),
    /// `<1> |= <2>`
    AssignOr(Loc, Box<Expression>, Box<Expression>),
    /// `<1> &= <2>`
    AssignAnd(Loc, Box<Expression>, Box<Expression>),
    /// `<1> ^= <2>`
    AssignXor(Loc, Box<Expression>, Box<Expression>),
    /// `<1> <<= <2>`
    AssignShiftLeft(Loc, Box<Expression>, Box<Expression>),
    /// `<1> >>= <2>`
    AssignShiftRight(Loc, Box<Expression>, Box<Expression>),
    /// `<1> += <2>`
    AssignAdd(Loc, Box<Expression>, Box<Expression>),
    /// `<1> -= <2>`
    AssignSubtract(Loc, Box<Expression>, Box<Expression>),
    /// `<1> *= <2>`
    AssignMultiply(Loc, Box<Expression>, Box<Expression>),
    /// `<1> /= <2>`
    AssignDivide(Loc, Box<Expression>, Box<Expression>),
    /// `<1> %= <2>`
    AssignModulo(Loc, Box<Expression>, Box<Expression>),

    /// `true` or `false`
    BoolLiteral(Loc, bool),
    /// ``
    NumberLiteral(Loc, String, String, Option<Identifier>),
    /// ``
    RationalNumberLiteral(Loc, String, String, String, Option<Identifier>),
    /// ``
    HexNumberLiteral(Loc, String, Option<Identifier>),
    /// `<1>+`. See [StringLiteral].
    StringLiteral(Vec<StringLiteral>),
    /// See [Type].
    Type(Loc, Type),
    /// `<1>+`. See [HexLiteral].
    HexLiteral(Vec<HexLiteral>),
    /// `0x[a-fA-F0-9]{40}`
    ///
    /// This [should be correctly checksummed][ref], but it currently isn't being enforced in the parser.
    ///
    /// [ref]: https://docs.soliditylang.org/en/latest/types.html#address-literals
    AddressLiteral(Loc, String),
    /// Any valid [Identifier].
    Variable(Identifier),
    /// `(<1>,*)`
    List(Loc, ParameterList),
    /// `\[ <1>.* \]`
    ArrayLiteral(Loc, Vec<Expression>),
}

/// See `Expression::components`.
macro_rules! expr_components {
    ($s:ident) => {
        match $s {
            // (Some, None)
            PostDecrement(_, expr) | PostIncrement(_, expr) => (Some(expr), None),

            // (None, Some)
            Not(_, expr)
            | BitwiseNot(_, expr)
            | New(_, expr)
            | Delete(_, expr)
            | UnaryPlus(_, expr)
            | Negate(_, expr)
            | PreDecrement(_, expr)
            | Parenthesis(_, expr)
            | PreIncrement(_, expr) => (None, Some(expr)),

            // (Some, Some)
            Power(_, left, right)
            | Multiply(_, left, right)
            | Divide(_, left, right)
            | Modulo(_, left, right)
            | Add(_, left, right)
            | Subtract(_, left, right)
            | ShiftLeft(_, left, right)
            | ShiftRight(_, left, right)
            | BitwiseAnd(_, left, right)
            | BitwiseXor(_, left, right)
            | BitwiseOr(_, left, right)
            | Less(_, left, right)
            | More(_, left, right)
            | LessEqual(_, left, right)
            | MoreEqual(_, left, right)
            | Equal(_, left, right)
            | NotEqual(_, left, right)
            | And(_, left, right)
            | Or(_, left, right)
            | Assign(_, left, right)
            | AssignOr(_, left, right)
            | AssignAnd(_, left, right)
            | AssignXor(_, left, right)
            | AssignShiftLeft(_, left, right)
            | AssignShiftRight(_, left, right)
            | AssignAdd(_, left, right)
            | AssignSubtract(_, left, right)
            | AssignMultiply(_, left, right)
            | AssignDivide(_, left, right)
            | AssignModulo(_, left, right) => (Some(left), Some(right)),

            // (None, None)
            MemberAccess(..)
            | ConditionalOperator(..)
            | ArraySubscript(..)
            | ArraySlice(..)
            | FunctionCall(..)
            | FunctionCallBlock(..)
            | NamedFunctionCall(..)
            | BoolLiteral(..)
            | NumberLiteral(..)
            | RationalNumberLiteral(..)
            | HexNumberLiteral(..)
            | StringLiteral(..)
            | Type(..)
            | HexLiteral(..)
            | AddressLiteral(..)
            | Variable(..)
            | List(..)
            | ArrayLiteral(..) => (None, None),
        }
    };
}

impl Expression {
    /// Removes one layer of parentheses.
    #[inline]
    pub fn remove_parenthesis(&self) -> &Expression {
        if let Expression::Parenthesis(_, expr) = self {
            expr
        } else {
            self
        }
    }

    /// Strips all parentheses recursively.
    pub fn strip_parentheses(&self) -> &Expression {
        match self {
            Expression::Parenthesis(_, expr) => expr.strip_parentheses(),
            _ => self,
        }
    }

    /// Returns shared references to the components of this expression.
    ///
    /// `(left_component, right_component)`
    ///
    /// # Examples
    ///
    /// ```
    /// use solang_parser::pt::{Expression, Identifier, Loc};
    ///
    /// // `a++`
    /// let var = Expression::Variable(Identifier::new("a"));
    /// let post_increment = Expression::PostIncrement(Loc::default(), Box::new(var.clone()));
    /// assert_eq!(post_increment.components(), (Some(&var), None));
    ///
    /// // `++a`
    /// let var = Expression::Variable(Identifier::new("a"));
    /// let pre_increment = Expression::PreIncrement(Loc::default(), Box::new(var.clone()));
    /// assert_eq!(pre_increment.components(), (None, Some(&var)));
    ///
    /// // `a + b`
    /// let var_a = Expression::Variable(Identifier::new("a"));
    /// let var_b = Expression::Variable(Identifier::new("b"));
    /// let pre_increment = Expression::Add(Loc::default(), Box::new(var_a.clone()), Box::new(var_b.clone()));
    /// assert_eq!(pre_increment.components(), (Some(&var_a), Some(&var_b)));
    /// ```
    #[inline]
    pub fn components(&self) -> (Option<&Self>, Option<&Self>) {
        use Expression::*;
        expr_components!(self)
    }

    /// Returns mutable references to the components of this expression.
    ///
    /// See also [`Expression::components`].
    #[inline]
    pub fn components_mut(&mut self) -> (Option<&mut Self>, Option<&mut Self>) {
        use Expression::*;
        expr_components!(self)
    }

    /// Returns whether this expression can be split across multiple lines.
    #[inline]
    pub const fn is_unsplittable(&self) -> bool {
        use Expression::*;
        matches!(
            self,
            BoolLiteral(..)
                | NumberLiteral(..)
                | RationalNumberLiteral(..)
                | HexNumberLiteral(..)
                | StringLiteral(..)
                | HexLiteral(..)
                | AddressLiteral(..)
                | Variable(..)
        )
    }

    /// Returns whether this expression has spaces around it.
    #[inline]
    pub const fn has_space_around(&self) -> bool {
        use Expression::*;
        !matches!(
            self,
            PostIncrement(..)
                | PreIncrement(..)
                | PostDecrement(..)
                | PreDecrement(..)
                | Not(..)
                | BitwiseNot(..)
                | UnaryPlus(..)
                | Negate(..)
        )
    }

    /// Returns if the expression is a literal
    pub fn is_literal(&self) -> bool {
        matches!(
            self,
            Expression::AddressLiteral(..)
                | Expression::HexLiteral(..)
                | Expression::BoolLiteral(..)
                | Expression::NumberLiteral(..)
                | Expression::ArrayLiteral(..)
                | Expression::HexNumberLiteral(..)
                | Expression::RationalNumberLiteral(..)
                | Expression::StringLiteral(..)
        )
    }
}

/// A parameter.
///
/// `<ty> [storage] <name>`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct Parameter {
    /// The code location.
    pub loc: Loc,
    /// An optional annotation '@annotation'.
    pub annotation: Option<Annotation>,
    /// The type.
    pub ty: Expression,
    /// The optional memory location.
    pub storage: Option<StorageLocation>,
    /// The optional identifier.
    pub name: Option<Identifier>,
}

/// Function mutability.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub enum Mutability {
    /// `pure`
    Pure(Loc),

    /// `view`
    View(Loc),

    /// `constant`
    Constant(Loc),

    /// `payable`
    Payable(Loc),
}

/// Function visibility.
///
/// Deprecated for [FunctionTy] other than `Function`.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
#[repr(u8)] // for cmp; order of variants is important
pub enum Visibility {
    /// `external`
    External(Option<Loc>),

    /// `public`
    Public(Option<Loc>),

    /// `internal`
    Internal(Option<Loc>),

    /// `private`
    Private(Option<Loc>),
}

/// A function attribute.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
#[repr(u8)] // for cmp; order of variants is important
pub enum FunctionAttribute {
    /// Visibility attribute.
    Visibility(Visibility),

    /// Mutability attribute.
    Mutability(Mutability),

    /// `virtual`
    Virtual(Loc),

    /// `immutable`
    Immutable(Loc),

    /// `override[(<identifier path>,*)]`
    Override(Loc, Vec<IdentifierPath>),

    /// A modifier or constructor invocation.
    BaseOrModifier(Loc, Base),

    /// An error occurred during parsing.
    Error(Loc),
}

/// A function's type.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub enum FunctionTy {
    /// `constructor`
    Constructor,

    /// `function`
    Function,

    /// `fallback`
    Fallback,

    /// `receive`
    Receive,

    /// `modifier`
    Modifier,
}

/// A function definition.
///
/// `<ty> [name](<params>,*) [attributes] [returns] [body]`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct FunctionDefinition {
    /// The function prototype location.
    pub loc_prototype: Loc,
    /// The code location.
    pub loc: Loc,
    /// The function type.
    pub ty: FunctionTy,
    /// The optional identifier.
    ///
    /// This can be `None` for old style fallback functions.
    pub name: Option<Identifier>,
    /// The identifier's code location.
    pub name_loc: Loc,
    /// The parameter list.
    pub params: ParameterList,
    /// The function attributes.
    pub attributes: Vec<FunctionAttribute>,
    /// The `returns` keyword's location. `Some` if this was `return`, not `returns`.
    pub return_not_returns: Option<Loc>,
    /// The return parameter list.
    pub returns: ParameterList,
    /// The function body.
    ///
    /// If `None`, the declaration ended with a semicolon.
    pub body: Option<Statement>,
}

impl FunctionDefinition {
    /// Returns `true` if the function has no return parameters.
    #[inline]
    pub fn is_void(&self) -> bool {
        self.returns.is_empty()
    }

    /// Returns `true` if the function body is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.body.as_ref().map_or(true, Statement::is_empty)
    }

    /// Sorts the function attributes.
    #[inline]
    pub fn sort_attributes(&mut self) {
        // we don't use unstable sort since there may be more that one `BaseOrModifier` attributes
        // which we want to preserve the order of
        self.attributes.sort();
    }
}

/// A statement.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
#[allow(clippy::large_enum_variant, clippy::type_complexity)]
pub enum Statement {
    /// `[unchecked] { <statements>* }`
    Block {
        /// The code location.
        loc: Loc,
        /// Whether this block is `unchecked`.
        unchecked: bool,
        /// The statements.
        statements: Vec<Statement>,
    },
    /// `assembly [dialect] [(<flags>,*)] <block>`
    Assembly {
        /// The code location.
        loc: Loc,
        /// The assembly dialect.
        dialect: Option<StringLiteral>,
        /// The assembly flags.
        flags: Option<Vec<StringLiteral>>,
        /// The assembly block.
        block: YulBlock,
    },
    /// `{ <1>,* }`
    Args(Loc, Vec<NamedArgument>),
    /// `if ({1}) <2> [else <3>]`
    ///
    /// Note that the `<1>` expression does not contain the parentheses.
    If(Loc, Expression, Box<Statement>, Option<Box<Statement>>),
    /// `while ({1}) <2>`
    ///
    /// Note that the `<1>` expression does not contain the parentheses.
    While(Loc, Expression, Box<Statement>),
    /// An [Expression].
    Expression(Loc, Expression),
    /// `<1> [= <2>];`
    VariableDefinition(Loc, VariableDeclaration, Option<Expression>),
    /// `for ([1]; [2]; [3]) [4]`
    ///
    /// The `[4]` block statement is `None` when the `for` statement ends with a semicolon.
    For(
        Loc,
        Option<Box<Statement>>,
        Option<Box<Expression>>,
        Option<Box<Expression>>,
        Option<Box<Statement>>,
    ),
    /// `do <1> while ({2});`
    ///
    /// Note that the `<2>` expression does not contain the parentheses.
    DoWhile(Loc, Box<Statement>, Expression),
    /// `continue;`
    Continue(Loc),
    /// `break;`
    Break(Loc),
    /// `return [1];`
    Return(Loc, Option<Expression>),
    /// `revert [1] (<2>,*);`
    Revert(Loc, Option<IdentifierPath>, Vec<Expression>),
    /// `revert [1] ({ <2>,* });`
    RevertNamedArgs(Loc, Option<IdentifierPath>, Vec<NamedArgument>),
    /// `emit <1>;`
    ///
    /// `<1>` is `FunctionCall`.
    Emit(Loc, Expression),
    /// `try <1> [returns (<2.1>,*) <2.2>] <3>*`
    ///
    /// `<1>` is either `New(FunctionCall)` or `FunctionCall`.
    Try(
        Loc,
        Expression,
        Option<(ParameterList, Box<Statement>)>,
        Vec<CatchClause>,
    ),
    /// An error occurred during parsing.
    Error(Loc),
}

impl Statement {
    /// Returns `true` if the block statement contains no elements.
    #[inline]
    pub fn is_empty(&self) -> bool {
        match self {
            Self::Block { statements, .. } => statements.is_empty(),
            Self::Assembly { block, .. } => block.is_empty(),
            Self::Args(_, args) => args.is_empty(),
            _ => false,
        }
    }
}

/// A catch clause. See [Statement].
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub enum CatchClause {
    /// `catch [(<1>)] <2>`
    Simple(Loc, Option<Parameter>, Statement),

    /// `catch <1> (<2>) <3>`
    Named(Loc, Identifier, Parameter, Statement),
}

/// A Yul statement.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub enum YulStatement {
    /// `<1>,+ = <2>`
    Assign(Loc, Vec<YulExpression>, YulExpression),
    /// `let <1>,+ [:= <2>]`
    VariableDeclaration(Loc, Vec<YulTypedIdentifier>, Option<YulExpression>),
    /// `if <1> <2>`
    If(Loc, YulExpression, YulBlock),
    /// A [YulFor] statement.
    For(YulFor),
    /// A [YulSwitch] statement.
    Switch(YulSwitch),
    /// `leave`
    Leave(Loc),
    /// `break`
    Break(Loc),
    /// `continue`
    Continue(Loc),
    /// A [YulBlock] statement.
    Block(YulBlock),
    /// A [YulFunctionDefinition] statement.
    FunctionDefinition(Box<YulFunctionDefinition>),
    /// A [YulFunctionCall] statement.
    FunctionCall(Box<YulFunctionCall>),
    /// An error occurred during parsing.
    Error(Loc),
}

/// A Yul switch statement.
///
/// `switch <condition> <cases>* [default <default>]`
///
/// Enforced by the parser:
///
/// - `cases` is guaranteed to be a `Vec` of `YulSwitchOptions::Case`.
/// - `default` is guaranteed to be `YulSwitchOptions::Default`.
/// - At least one of `cases` or `default` must be non-empty/`Some` respectively.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct YulSwitch {
    /// The code location.
    pub loc: Loc,
    /// The switch condition.
    pub condition: YulExpression,
    /// The switch cases.
    pub cases: Vec<YulSwitchOptions>,
    /// The optional default case.
    pub default: Option<YulSwitchOptions>,
}

/// A Yul for statement.
///
/// `for <init_block> <condition> <post_block> <execution_block>`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct YulFor {
    /// The code location.
    pub loc: Loc,
    /// The for statement init block.
    pub init_block: YulBlock,
    /// The for statement condition.
    pub condition: YulExpression,
    /// The for statement post block.
    pub post_block: YulBlock,
    /// The for statement execution block.
    pub execution_block: YulBlock,
}

/// A Yul block statement.
///
/// `{ <statements>* }`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct YulBlock {
    /// The code location.
    pub loc: Loc,
    /// The block statements.
    pub statements: Vec<YulStatement>,
}

impl YulBlock {
    /// Returns `true` if the block contains no elements.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.statements.is_empty()
    }
}

/// A Yul expression.
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub enum YulExpression {
    /// `<1> [: <2>]`
    BoolLiteral(Loc, bool, Option<Identifier>),
    /// `<1>[e<2>] [: <2>]`
    NumberLiteral(Loc, String, String, Option<Identifier>),
    /// `<1> [: <2>]`
    HexNumberLiteral(Loc, String, Option<Identifier>),
    /// `<0> [: <1>]`
    HexStringLiteral(HexLiteral, Option<Identifier>),
    /// `<0> [: <1>]`
    StringLiteral(StringLiteral, Option<Identifier>),
    /// Any valid [Identifier].
    Variable(Identifier),
    /// [YulFunctionCall].
    FunctionCall(Box<YulFunctionCall>),
    /// `<1>.<2>`
    SuffixAccess(Loc, Box<YulExpression>, Identifier),
}

/// A Yul typed identifier.
///
/// `<id> [: <ty>]`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct YulTypedIdentifier {
    /// The code location.
    pub loc: Loc,
    /// The identifier.
    pub id: Identifier,
    /// The optional type.
    pub ty: Option<Identifier>,
}

/// A Yul function definition.
///
/// `function <name> (<params>,*) [-> (<returns>,*)] <body>`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct YulFunctionDefinition {
    /// The code location.
    pub loc: Loc,
    /// The identifier.
    pub id: Identifier,
    /// The parameters.
    pub params: Vec<YulTypedIdentifier>,
    /// The return parameters.
    pub returns: Vec<YulTypedIdentifier>,
    /// The function body.
    pub body: YulBlock,
}

impl YulFunctionDefinition {
    /// Returns `true` if the function has no return parameters.
    #[inline]
    pub fn is_void(&self) -> bool {
        self.returns.is_empty()
    }

    /// Returns `true` if the function body is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.body.is_empty()
    }
}

/// A Yul function call.
///
/// `<id>(<arguments>,*)`
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub struct YulFunctionCall {
    /// The code location.
    pub loc: Loc,
    /// The identifier.
    pub id: Identifier,
    /// The function call arguments.
    pub arguments: Vec<YulExpression>,
}

/// A Yul switch case or default statement. See [YulSwitch].
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "pt-serde", derive(Serialize, Deserialize))]
pub enum YulSwitchOptions {
    /// `case <1> <2>`
    Case(Loc, YulExpression, YulBlock),
    /// `default <1>`
    Default(Loc, YulBlock),
}