moore-svlog 0.14.0

The SystemVerilog implementation of the moore compiler framework.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
// Copyright (c) 2016-2021 Fabian Schuiki

//! A generalized SystemVerilog type system.
//!
//! This module covers all types that may arise in a SystemVerilog source file,
//! plus some additional things like modules/interfaces to streamline the
//! handling of hierarchical names and interface signals/modports throughout the
//! compiler.
//!
//! ## Packed Types
//!
//! Packed types are the core types of SystemVerilog. They combine a core packed
//! type with an optional sign and zero or more packed dimensions. The core
//! packed types are:
//!
//! - Integer vector types: `bit`, `logic`, `reg`
//! - Integer atom types: `byte`, `shortint`, `int`, `longint`, `integer`,
//!   `time`
//! - Packed structs and unions
//! - Enums
//! - Packed named types
//! - Packed type references
//!
//! The packed dimensions can be:
//!
//! - Unsized (`[]`)
//! - Ranges (`[x:y]`)
//!
//! Packed types are implemented by the [`PackedType`](struct.PackedType.html)
//! struct.
//!
//! ## Unpacked Types
//!
//! Unpacked types are a second level of types in SystemVerilog. They extend a
//! core unpacked type with a variety of unpacked dimensions, depending on which
//! syntactic construct generated the type (variable or otherwise). The core
//! unpacked types are:
//!
//! - Packed types
//! - Non-integer types: `shortreal`, `real`, `realtime`
//! - Unpacked structs and unions
//! - `string`, `chandle`, `event`
//! - Virtual interfaces
//! - Class types
//! - Covergroups
//! - Unpacked named types
//! - Unpacked type references
//! - Modules and interfaces
//!
//! The unpacked dimensions are:
//!
//! - Unsized (`[]`)
//! - Arrays (`[x]`)
//! - Ranges (`[x:y]`)
//! - Associative (`[T]` or `[*]`)
//! - Queues (`[$]` or `[$:x]`)
//!
//! Unpacked types are implemented by the [`UnpackedType`](struct.UnpackedType.html)
//! struct.
//!
//! ## Simple Bit Vector Types
//!
//! Some packed types may be converted into an equivalent Simple Bit Vector Type
//! (SBVT), which has an identical bit pattern as the original type, but
//! consists only of an integer vector type with a single optional packed
//! dimension. An SBVT can be converted back into a packed type. SBVTs can be
//! range-cast, which changes the width of their single dimension.
//!
//! SBVTs track whether the original packed type explicitly had a dimension or
//! used an integer atom type, or was named. When converting back to a packed
//! type, the SBVT attempts to restore this information, depending on how many
//! changes were applied.
//!
//! ## Sign
//!
//! All packed types have an associated sign, indicating whether they are
//! *signed* or *unsigned*. The types have a default sign, which means that
//! the sign may have been omitted in the source file. Packed types can be
//! sign-cast, which changes only their sign.
//!
//! ## Domain
//!
//! All packed types consist of bits that can either carry two or four values.
//! An aggregate type is two-valued iff *all* its constituent types are
//! two-valued, otherwise it is four-valued. Packed types can be domain-cast,
//! which changes only their value domain.

use crate::crate_prelude::*;
use crate::{common::arenas::TypedArena, ParamEnv};
use once_cell::sync::Lazy;
use std::{
    cell::RefCell,
    collections::HashSet,
    fmt::{Debug, Display},
    hash::{Hash, Hasher},
};

/// A packed type.
#[derive(Clone)]
pub struct PackedType<'a> {
    /// The core packed type.
    pub core: PackedCore<'a>,
    /// The type sign.
    pub sign: Sign,
    /// Whether the sign was explicit in the source code.
    pub sign_explicit: bool,
    /// The packed dimensions.
    pub dims: Vec<PackedDim>,
    /// This type with one level of name/reference resolved.
    resolved: Option<&'a Self>,
    /// This type with all names/references recursively resolved.
    resolved_full: Option<&'a Self>,
}

/// A core packed type.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum PackedCore<'a> {
    /// An error occurred during type computation.
    Error,
    /// Void.
    Void,
    /// An integer vector type.
    IntVec(IntVecType),
    /// An integer atom type.
    IntAtom(IntAtomType),
    /// A packed struct.
    Struct(StructType<'a>),
    /// An enum.
    Enum(EnumType<'a>),
    /// A named type.
    Named {
        /// How the user originally called the type.
        name: Spanned<Name>,
        /// The type this name expands to.
        ty: &'a PackedType<'a>,
    },
    /// A type reference.
    Ref {
        /// Location of the `type(...)` in the source file.
        span: Span,
        /// The type that this reference expands to.
        ty: &'a PackedType<'a>,
    },
}

/// A packed dimension.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PackedDim {
    /// A range dimension, like `[a:b]`.
    Range(Range),
    /// A unsized dimension, like `[]`.
    Unsized,
}

/// An integer vector type.
///
/// These are the builtin single-bit integer types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IntVecType {
    /// A `bit`.
    Bit,
    /// A `logic`.
    Logic,
    /// A `reg`.
    Reg,
}

/// An integer atom type.
///
/// These are the builtin multi-bit integer types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IntAtomType {
    /// A `byte`.
    Byte,
    /// A `shortint`.
    ShortInt,
    /// An `int`.
    Int,
    /// A `longint`.
    LongInt,
    /// An `integer`.
    Integer,
    /// A `time`.
    Time,
}

/// The number of values each bit of a type can assume.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Domain {
    /// Two-valued types such as `bit` or `int`.
    TwoValued,
    /// Four-valued types such as `logic` or `integer`.
    FourValued,
}

/// Whether a type is signed or unsigned.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum Sign {
    /// A `signed` type.
    Signed,
    /// An `unsigned` type.
    Unsigned,
}

/// The `[a:b]` part in a vector/array type such as `logic [a:b]`.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Range {
    /// The total number of bits, given as `|a-b|+1`.
    pub size: usize,
    /// The direction of the vector, i.e. whether `a > b` or `a < b`.
    pub dir: RangeDir,
    /// The starting offset of the range.
    pub offset: isize,
}

/// Which side is greater in a range `[a:b]`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RangeDir {
    /// `a < b`
    Up,
    /// `a > b`
    Down,
}

/// An unpacked type.
#[derive(Clone)]
pub struct UnpackedType<'a> {
    /// The core unpacked type.
    pub core: UnpackedCore<'a>,
    /// The unpacked dimensions.
    pub dims: Vec<UnpackedDim<'a>>,
    /// This type with one level of name/reference resolved.
    resolved: Option<&'a Self>,
    /// This type with all names/references recursively resolved.
    resolved_full: Option<&'a Self>,
}

/// A core unpacked type.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum UnpackedCore<'a> {
    /// An error occurred during type computation.
    Error,
    /// A packed type.
    Packed(&'a PackedType<'a>),
    /// A real type.
    Real(RealType),
    /// A unpacked struct.
    Struct(StructType<'a>),
    /// A string.
    String,
    /// A chandle.
    Chandle,
    /// An event.
    Event,
    // TODO: Add virtual interfaces
    // TODO: Add class types
    // TODO: Add covergroups
    /// A named type.
    Named {
        /// How the user originally called the type.
        name: Spanned<Name>,
        /// The type this name expands to.
        ty: &'a UnpackedType<'a>,
    },
    /// A type reference.
    Ref {
        /// Location of the `type(...)` in the source file.
        span: Span,
        /// The type that this reference expands to.
        ty: &'a UnpackedType<'a>,
    },
    /// A module instance.
    Module(ModuleType<'a>),
    /// An interface instance.
    Interface(InterfaceType<'a>),
}

/// An unpacked dimension.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum UnpackedDim<'a> {
    /// A unsized dimension, like `[]`.
    Unsized,
    /// An array dimension, like `[a]`.
    Array(usize),
    /// A range dimension, like `[a:b]`.
    Range(Range),
    /// An associative dimension, like `[T]` or `[*]`.
    Assoc(Option<&'a UnpackedType<'a>>),
    /// A queue dimension, like `[$]` or `[$:a]`.
    Queue(Option<usize>),
}

/// A real type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RealType {
    /// A `shortreal`.
    ShortReal,
    /// A `real`.
    Real,
    /// A `realtime`.
    RealTime,
}

/// A struct type.
///
/// This represents both packed and unpacked structs. Which one it is depends on
/// whether this struct is embedded in a `PackedType` or `UnpackedType`. For the
/// packed version the struct inherits its sign from its parent `PackedType`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct StructType<'a> {
    /// The corresponding AST node of this struct definition.
    pub ast: &'a ast::Struct<'a>,
    /// The AST node of the corresponding type.
    pub ast_type: &'a ast::Type<'a>,
    /// Whether this is a `struct`, `union` or `union tagged`.
    pub kind: ast::StructKind,
    /// The list of members.
    pub members: Vec<StructMember<'a>>,
}

/// A member of a struct type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct StructMember<'a> {
    /// The name.
    pub name: Spanned<Name>,
    /// The type.
    pub ty: &'a UnpackedType<'a>,
    /// The AST node of the member declaration.
    pub ast_member: &'a ast::StructMember<'a>,
    /// The AST node of the member name.
    pub ast_name: &'a ast::VarDeclName<'a>,
}

/// An enum type.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct EnumType<'a> {
    /// The corresponding AST node of this enum definition.
    pub ast: &'a ast::Enum<'a>,
    /// The base type of this enum.
    pub base: &'a PackedType<'a>,
    /// Whether the base type was explicit in the source code.
    pub base_explicit: bool,
    /// The list of variants.
    pub variants: Vec<(Spanned<Name>, &'a ast::EnumName<'a>)>,
}

/// A module instance.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ModuleType<'a> {
    /// The AST node of the module.
    pub ast: &'a ast::Module<'a>,
    /// The parametrization of the module.
    pub env: ParamEnv,
}

/// An interface instance.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct InterfaceType<'a> {
    /// The AST node of the interface.
    pub ast: &'a ast::Interface<'a>,
    /// The parametrization of the interface.
    pub env: ParamEnv,
    /// The optional modport that was specified together with the interface.
    pub modport: Option<&'a ast::ModportName<'a>>,
}

/// A simple bit vector type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SbvType {
    /// The domain, which dictates whether this is a `bit` or `logic` vector.
    pub domain: Domain,
    /// Whether the type used an integer atom like `int` in the source text.
    pub used_atom: bool,
    /// The sign.
    pub sign: Sign,
    /// Whether the sign was explicit in the source text.
    pub sign_explicit: bool,
    /// The size of the vector.
    pub size: usize,
    /// Whether the single-bit vector had an explicit range in the source text.
    /// Essentially whether it was `bit` or `bit[a:a]`.
    pub size_explicit: bool,
}

/// A packed or unpacked dimension.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Dim<'a> {
    /// A packed dimension.
    Packed(PackedDim),
    /// An unpacked dimension.
    Unpacked(UnpackedDim<'a>),
}

impl<'a> PackedType<'a> {
    /// Create a new type with default sign and no packed dimensions.
    ///
    /// This creates the type on the stack. In general you will want to use the
    /// `make_*` functions to create a type that is interned into a context.
    pub fn new(core: impl Into<PackedCore<'a>>) -> Self {
        Self::with_dims(core, vec![])
    }

    /// Create a new type with default sign and packed dimensions.
    ///
    /// This creates the type on the stack. In general you will want to use the
    /// `make_*` functions to create a type that is interned into a context.
    pub fn with_dims(core: impl Into<PackedCore<'a>>, dims: Vec<PackedDim>) -> Self {
        let core = core.into();
        let sign = match &core {
            PackedCore::IntAtom(IntAtomType::Time)
            | PackedCore::IntVec(_)
            | PackedCore::Error
            | PackedCore::Void
            | PackedCore::Struct(_)
            | PackedCore::Enum(_)
            | PackedCore::Named { .. }
            | PackedCore::Ref { .. } => Sign::Unsigned,
            PackedCore::IntAtom(_) => Sign::Signed,
        };
        Self::with_sign_and_dims(core, sign, false, dims)
    }

    /// Create a new type with no packed dimensions.
    ///
    /// This creates the type on the stack. In general you will want to use the
    /// `make_*` functions to create a type that is interned into a context.
    pub fn with_sign(core: impl Into<PackedCore<'a>>, sign: Sign, sign_explicit: bool) -> Self {
        Self::with_sign_and_dims(core, sign, sign_explicit, vec![])
    }

    /// Create a new type with packed dimensions.
    ///
    /// This creates the type on the stack. In general you will want to use the
    /// `make_*` functions to create a type that is interned into a context.
    pub fn with_sign_and_dims(
        core: impl Into<PackedCore<'a>>,
        sign: Sign,
        sign_explicit: bool,
        dims: Vec<PackedDim>,
    ) -> Self {
        Self {
            core: core.into(),
            sign,
            sign_explicit,
            dims,
            resolved: None,
            resolved_full: None,
        }
    }

    /// Create a new type from an SBVT.
    pub fn with_simple_bit_vector(sbv: SbvType) -> Self {
        let atom = match (sbv.size, sbv.domain) {
            (8, Domain::TwoValued) => Some(IntAtomType::Byte),
            (16, Domain::TwoValued) => Some(IntAtomType::ShortInt),
            (32, Domain::TwoValued) => Some(IntAtomType::Int),
            (32, Domain::FourValued) => Some(IntAtomType::Integer),
            (64, Domain::TwoValued) => Some(IntAtomType::LongInt),
            _ => None,
        };
        match atom {
            Some(atom) if sbv.used_atom => Self::with_sign(atom, sbv.sign, sbv.sign_explicit),
            _ => Self::with_sign_and_dims(
                match sbv.domain {
                    Domain::TwoValued => IntVecType::Bit,
                    Domain::FourValued => IntVecType::Logic,
                },
                sbv.sign,
                sbv.sign_explicit,
                if sbv.size > 1 || sbv.size_explicit {
                    vec![PackedDim::Range(sbv.range())]
                } else {
                    vec![]
                },
            ),
        }
    }

    /// Create an interned type with default sign and no packed dimensions.
    pub fn make(cx: &impl TypeContext<'a>, core: impl Into<PackedCore<'a>>) -> &'a Self {
        Self::new(core).intern(cx)
    }

    /// Create an interned type with default sign and packed dimensions.
    pub fn make_dims(
        cx: &impl TypeContext<'a>,
        core: impl Into<PackedCore<'a>>,
        dims: Vec<PackedDim>,
    ) -> &'a Self {
        Self::with_dims(core, dims).intern(cx)
    }

    /// Create an interned type with no packed dimensions.
    pub fn make_sign(
        cx: &impl TypeContext<'a>,
        core: impl Into<PackedCore<'a>>,
        sign: Sign,
        sign_explicit: bool,
    ) -> &'a Self {
        Self::with_sign(core, sign, sign_explicit).intern(cx)
    }

    /// Create an interned type with packed dimensions.
    pub fn make_sign_and_dims(
        cx: &impl TypeContext<'a>,
        core: impl Into<PackedCore<'a>>,
        sign: Sign,
        sign_explicit: bool,
        dims: Vec<PackedDim>,
    ) -> &'a Self {
        Self::with_sign_and_dims(core, sign, sign_explicit, dims).intern(cx)
    }

    /// Create an interned type from an SBVT.
    pub fn make_simple_bit_vector(cx: &impl TypeContext<'a>, sbv: SbvType) -> &'a Self {
        Self::with_simple_bit_vector(sbv).intern(cx)
    }

    /// Create a tombstone.
    pub fn make_error() -> &'a Self {
        static TYPE: Lazy<PackedType> = Lazy::new(|| PackedType::new(PackedCore::Error));
        let ty: &PackedType = &TYPE;
        // SAFETY: This is safe since the cell which causes 'a to need to
        // outlive 'static is actually never mutated after AST construction.
        unsafe { std::mem::transmute(ty) }
    }

    /// Create a `void` type.
    pub fn make_void() -> &'a Self {
        static TYPE: Lazy<PackedType> = Lazy::new(|| PackedType::new(PackedCore::Void));
        let ty: &PackedType = &TYPE;
        // SAFETY: This is safe since the cell which causes 'a to need to
        // outlive 'static is actually never mutated after AST construction.
        unsafe { std::mem::transmute(ty) }
    }

    /// Create a `logic` type.
    pub fn make_logic() -> &'a Self {
        static TYPE: Lazy<PackedType> = Lazy::new(|| PackedType::new(IntVecType::Logic));
        let ty: &PackedType = &TYPE;
        // SAFETY: This is safe since the cell which causes 'a to need to
        // outlive 'static is actually never mutated after AST construction.
        unsafe { std::mem::transmute(ty) }
    }

    /// Create a `time` type.
    pub fn make_time() -> &'a Self {
        static TYPE: Lazy<PackedType> = Lazy::new(|| PackedType::new(IntAtomType::Time));
        let ty: &PackedType = &TYPE;
        // SAFETY: This is safe since the cell which causes 'a to need to
        // outlive 'static is actually never mutated after AST construction.
        unsafe { std::mem::transmute(ty) }
    }

    /// Internalize this type in a context and resolve it.
    pub fn intern(mut self, cx: &impl TypeContext<'a>) -> &'a Self {
        let inner = match self.core {
            PackedCore::Named { ty, .. } => Some(ty),
            PackedCore::Ref { ty, .. } => Some(ty),
            _ => None,
        };
        self.resolved = inner.map(|ty| self.apply_to_inner(cx, ty));
        self.resolved_full = inner.map(|ty| self.apply_to_inner(cx, ty.resolve_full()));
        if let Some(x) = self.resolved {
            trace!("Type `{}` resolves to `{}`", self, x);
        }
        if let Some(x) = self.resolved_full {
            trace!("Type `{}` fully resolves to `{}`", self, x);
        }
        cx.intern_packed(self)
    }

    /// Apply the sign and dimensions to a core type that expanded to another
    /// type.
    fn apply_to_inner(&self, cx: &impl TypeContext<'a>, inner: &'a Self) -> &'a Self {
        if self.dims.is_empty()
            && self.sign == inner.sign
            && self.sign_explicit == inner.sign_explicit
        {
            return inner;
        }
        let out = Self {
            core: inner.core.clone(),
            sign: self.sign,
            sign_explicit: self.sign_explicit,
            dims: self
                .dims
                .iter()
                .cloned()
                .chain(inner.dims.iter().cloned())
                .collect(),
            resolved: None,
            resolved_full: None,
        };
        out.intern(cx)
    }

    /// Wrap this packed type up in an unpacked type.
    pub fn to_unpacked(&'a self, cx: &impl TypeContext<'a>) -> &'a UnpackedType<'a> {
        UnpackedType::make(cx, self)
    }

    /// Resolve one level of name or type reference indirection.
    ///
    /// For example, given `typedef int foo; typedef foo bar;`, resolves `bar`
    /// to `foo`.
    pub fn resolve(&self) -> &Self {
        self.resolved.unwrap_or(self)
    }

    /// Resolve all name or type reference indirections recursively.
    ///
    /// For example, given `typedef int foo; typedef foo bar;`, resolves `bar`
    /// to `int`.
    pub fn resolve_full(&self) -> &Self {
        self.resolved_full.unwrap_or(self)
    }

    /// Check if this is a tombstone.
    pub fn is_error(&self) -> bool {
        self.core.is_error()
    }

    /// Check if this type is equal to another one.
    ///
    /// Types which coalesce to `iN` in LLHD are checked for equality of their
    /// SBVT.
    pub fn is_identical(&self, other: &Self) -> bool {
        let a = self.resolve_full();
        let b = other.resolve_full();
        if a.coalesces_to_llhd_scalar() && b.coalesces_to_llhd_scalar() {
            a.get_simple_bit_vector().map(|x| x.forget())
                == b.get_simple_bit_vector().map(|x| x.forget())
        } else {
            a.is_strictly_identical(b)
        }
    }

    /// Check if this type is strictly equal to another one.
    pub fn is_strictly_identical(&self, other: &Self) -> bool {
        let a = self.resolve_full();
        let b = other.resolve_full();
        a.core.is_identical(&b.core) && a.sign == b.sign && a.dims == b.dims
    }

    /// Get the domain for this type.
    pub fn domain(&self) -> Domain {
        match &self.core {
            PackedCore::Error => Domain::TwoValued,
            PackedCore::Void => Domain::TwoValued,
            PackedCore::IntVec(x) => x.domain(),
            PackedCore::IntAtom(x) => x.domain(),
            PackedCore::Struct(x) => x.domain(),
            PackedCore::Enum(x) => x.base.domain(),
            PackedCore::Named { ty, .. } | PackedCore::Ref { ty, .. } => ty.domain(),
        }
    }

    /// Get the sign for this type.
    pub fn sign(&self) -> Sign {
        self.sign
    }

    /// Compute the size of this type in bits.
    ///
    /// Returns `None` if one of the type's dimensions is `[]`.
    pub fn get_bit_size(&self) -> Option<usize> {
        let ty = self.resolve_full();
        let mut size = match &ty.core {
            PackedCore::Error => 0,
            PackedCore::Void => 0,
            PackedCore::IntVec(..) => 1,
            PackedCore::IntAtom(x) => x.bit_size(),
            PackedCore::Struct(x) => x.get_bit_size()?,
            PackedCore::Enum(x) => x.base.get_bit_size()?,
            PackedCore::Named { ty, .. } | PackedCore::Ref { ty, .. } => ty.get_bit_size()?,
        };
        for &dim in &self.dims {
            match dim {
                PackedDim::Unsized => return None,
                PackedDim::Range(r) => size *= r.size,
            }
        }
        Some(size)
    }

    /// Check if this is a void type.
    pub fn is_void(&self) -> bool {
        let ty = self.resolve_full();
        match ty.core {
            PackedCore::Void => ty.dims.is_empty(),
            _ => false,
        }
    }

    /// Check if this type is trivially a SBVT.
    pub fn is_simple_bit_vector(&self) -> bool {
        // NOTE: It's important that this does not use resolve_full(), since
        // otherwise the type casting breaks.
        match self.core {
            PackedCore::IntVec(..) if self.dims.len() == 1 => match self.dims[0] {
                PackedDim::Range(Range {
                    offset: 0,
                    dir: RangeDir::Down,
                    ..
                }) => true,
                _ => false,
            },
            _ => false,
        }
    }

    /// Check if this type is a simple integer vector type, like `logic [x:y]`
    /// or `logic`.
    pub fn is_integer_vec(&self) -> bool {
        let ty = self.resolve_full();
        match ty.core {
            PackedCore::IntVec(..) => ty.dims.len() <= 1,
            _ => false,
        }
    }

    /// Check if this type is an integer atom type, like `int`.
    pub fn is_integer_atom(&self) -> bool {
        let ty = self.resolve_full();
        match ty.core {
            PackedCore::IntAtom(..) => ty.dims.len() == 0,
            _ => false,
        }
    }

    /// Check if this type is a single bit type, like `bit`.
    pub fn is_single_bit(&self) -> bool {
        let ty = self.resolve_full();
        match ty.core {
            PackedCore::IntVec(..) => ty.dims.len() == 0,
            _ => false,
        }
    }

    /// Check if this type is the `time` type.
    pub fn is_time(&self) -> bool {
        let ty = self.resolve_full();
        match ty.core {
            PackedCore::IntAtom(IntAtomType::Time) => ty.dims.len() == 0,
            _ => false,
        }
    }

    /// Check if this type will coalesce to a scalar type in LLHD, like `i42`.
    pub fn coalesces_to_llhd_scalar(&self) -> bool {
        if let Some(enm) = self.get_enum() {
            enm.base.coalesces_to_llhd_scalar()
        } else {
            !self.is_time()
                && (self.is_integer_vec() || self.is_integer_atom() || self.is_single_bit())
        }
    }

    /// Convert this type into an SBVT if possible.
    pub fn get_simple_bit_vector(&self) -> Option<SbvType> {
        let ty = self.resolve_full();
        Some(SbvType {
            domain: ty.domain(),
            used_atom: match self.core {
                PackedCore::IntAtom(..) => true,
                _ => false,
            },
            sign: ty.sign,
            sign_explicit: ty.sign_explicit,
            size: ty.get_bit_size()?,
            size_explicit: !ty.dims.is_empty(),
        })
    }

    /// Convert this type into an SBVT, or report a bug with the given span.
    pub fn simple_bit_vector(&self, cx: &impl DiagEmitter, span: Span) -> SbvType {
        match self.get_simple_bit_vector() {
            Some(sbv) => sbv,
            None => bug_span!(span, cx, "`{}` has no simple bit vector equivalent", self),
        }
    }

    /// Pop the outermost dimension off the type.
    ///
    /// For example, maps `bit [3:0][7:0]` to `bit [7:0]`.
    pub fn pop_dim(&self, cx: &impl TypeContext<'a>) -> Option<&'a Self> {
        let ty = self.resolve_full();
        if !ty.dims.is_empty() {
            let mut new = ty.clone();
            new.dims.remove(0);
            Some(new.intern(cx))
        } else {
            None
        }
    }

    /// Replace the outermost dimension of the type.
    ///
    /// Panics if the type has no dimensions.
    pub fn replace_dim(&self, cx: &impl TypeContext<'a>, dim: PackedDim) -> &'a Self {
        let ty = self.resolve_full();
        if !ty.dims.is_empty() {
            let mut new = ty.clone();
            new.dims[0] = dim;
            new.intern(cx)
        } else {
            panic!("no dimension in `{}` to substitute with `{}`", self, dim);
        }
    }

    /// Get the outermost dimension of the type.
    ///
    /// For example, yields the `[3:0]` in `bit [3:0][7:0]`.
    pub fn outermost_dim(&self) -> Option<PackedDim> {
        self.resolve_full().dims.iter().cloned().next()
    }

    /// Get the underlying struct, or `None` if the type is no struct.
    pub fn get_struct(&self) -> Option<&StructType<'a>> {
        let ty = self.resolve_full();
        match ty.core {
            PackedCore::Struct(ref x) if ty.dims.is_empty() => Some(x),
            _ => None,
        }
    }

    /// Get the underlying enum, or `None` if the type is no enum.
    pub fn get_enum(&self) -> Option<&EnumType<'a>> {
        let ty = self.resolve_full();
        match ty.core {
            PackedCore::Enum(ref x) if ty.dims.is_empty() => Some(x),
            _ => None,
        }
    }
}

// Compare and hash `PackedType` by reference.
impl Eq for PackedType<'_> {}
impl PartialEq for PackedType<'_> {
    fn eq(&self, other: &Self) -> bool {
        std::ptr::eq(self, other)
    }
}
impl Hash for PackedType<'_> {
    fn hash<H: Hasher>(&self, h: &mut H) {
        std::ptr::hash(self, h)
    }
}

// Compare and hash `Intern<PackedType>` by value.
impl Eq for Intern<PackedType<'_>> {}
impl PartialEq for Intern<PackedType<'_>> {
    fn eq(&self, other: &Self) -> bool {
        self.0.core == other.0.core
            && self.0.sign == other.0.sign
            && self.0.sign_explicit == other.0.sign_explicit
            && self.0.dims == other.0.dims
            && self.0.resolved == other.0.resolved
            && self.0.resolved_full == other.0.resolved_full
    }
}
impl Hash for Intern<PackedType<'_>> {
    fn hash<H: Hasher>(&self, h: &mut H) {
        self.0.core.hash(h);
        self.0.sign.hash(h);
        self.0.sign_explicit.hash(h);
        self.0.dims.hash(h);
        self.0.resolved.hash(h);
        self.0.resolved_full.hash(h);
    }
}

impl Display for PackedType<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        self.core.format(
            f,
            if self.sign != self.core.default_sign() || self.sign_explicit {
                Some(self.sign)
            } else {
                None
            },
        )?;
        if !self.dims.is_empty() {
            write!(f, " ")?;
            for dim in &self.dims {
                write!(f, "{}", dim)?;
            }
        }
        Ok(())
    }
}

impl Debug for PackedType<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        Display::fmt(self.resolve_full(), f)
    }
}

impl<'a> PackedCore<'a> {
    /// Check if this is a tombstone.
    pub fn is_error(&self) -> bool {
        match self {
            Self::Error => true,
            Self::Named { ty, .. } | Self::Ref { ty, .. } => ty.is_error(),
            _ => false,
        }
    }

    /// Get the default sign for this type.
    pub fn default_sign(&self) -> Sign {
        match self {
            Self::Error => Sign::Unsigned,
            Self::Void => Sign::Unsigned,
            Self::IntVec(_) => Sign::Unsigned,
            Self::IntAtom(x) => x.default_sign(),
            Self::Struct(_) => Sign::Unsigned,
            Self::Enum(_) => Sign::Unsigned,
            Self::Named { ty, .. } => ty.sign,
            Self::Ref { ty, .. } => ty.sign,
        }
    }

    /// Check if this type is identical to another one.
    pub fn is_identical(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Error, Self::Error) => true,
            (Self::Void, Self::Void) => true,
            (Self::IntVec(a), Self::IntVec(b)) => {
                (match *a {
                    IntVecType::Reg => IntVecType::Logic,
                    x => x,
                }) == (match *b {
                    IntVecType::Reg => IntVecType::Logic,
                    x => x,
                })
            }
            (Self::IntAtom(a), Self::IntAtom(b)) => a == b,
            (Self::Struct(a), Self::Struct(b)) => a == b,
            (Self::Enum(a), Self::Enum(b)) => a == b,
            (Self::Named { ty: a, .. }, Self::Named { ty: b, .. }) => a.is_identical(b),
            (Self::Ref { ty: a, .. }, Self::Ref { ty: b, .. }) => a.is_identical(b),
            _ => false,
        }
    }

    /// Helper function to format this core packed type.
    fn format(&self, f: &mut std::fmt::Formatter, sign: Option<Sign>) -> std::fmt::Result {
        match self {
            Self::Error => write!(f, "<error>"),
            Self::Void => write!(f, "void"),
            Self::IntVec(x) => {
                write!(f, "{}", x)?;
                if let Some(sign) = sign {
                    write!(f, " {}", sign)?;
                }
                Ok(())
            }
            Self::IntAtom(x) => {
                write!(f, "{}", x)?;
                if let Some(sign) = sign {
                    write!(f, " {}", sign)?;
                }
                Ok(())
            }
            Self::Struct(x) => x.format(f, true, sign),
            Self::Enum(x) => write!(f, "{}", x),
            Self::Named { name, .. } => write!(f, "{}", name),
            Self::Ref { span, .. } => write!(f, "{}", span.extract()),
        }
    }
}

impl<'a> From<IntVecType> for PackedCore<'a> {
    fn from(inner: IntVecType) -> Self {
        PackedCore::IntVec(inner)
    }
}

impl<'a> From<IntAtomType> for PackedCore<'a> {
    fn from(inner: IntAtomType) -> Self {
        PackedCore::IntAtom(inner)
    }
}

impl<'a> From<StructType<'a>> for PackedCore<'a> {
    fn from(inner: StructType<'a>) -> Self {
        PackedCore::Struct(inner)
    }
}

impl<'a> From<EnumType<'a>> for PackedCore<'a> {
    fn from(inner: EnumType<'a>) -> Self {
        PackedCore::Enum(inner)
    }
}

impl Display for PackedCore<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        self.format(f, None)
    }
}

impl PackedDim {
    /// Get the dimension's range, or `None` if it is unsized.
    pub fn get_range(&self) -> Option<Range> {
        match *self {
            Self::Range(x) => Some(x),
            Self::Unsized => None,
        }
    }

    /// Get the dimension's size, or `None` if it is unsized.
    pub fn get_size(&self) -> Option<usize> {
        self.get_range().map(|r| r.size)
    }
}

impl From<Range> for PackedDim {
    fn from(range: Range) -> Self {
        Self::Range(range)
    }
}

impl Display for PackedDim {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::Range(x) => write!(f, "{}", x),
            Self::Unsized => write!(f, "[]"),
        }
    }
}

impl IntVecType {
    /// Get the domain for this type.
    pub fn domain(&self) -> Domain {
        match self {
            Self::Bit => Domain::TwoValued,
            Self::Logic => Domain::FourValued,
            Self::Reg => Domain::FourValued,
        }
    }
}

impl Display for IntVecType {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::Bit => write!(f, "bit"),
            Self::Logic => write!(f, "logic"),
            Self::Reg => write!(f, "reg"),
        }
    }
}

impl IntAtomType {
    /// Get the domain for this type.
    pub fn domain(&self) -> Domain {
        match self {
            Self::Byte => Domain::TwoValued,
            Self::ShortInt => Domain::TwoValued,
            Self::Int => Domain::TwoValued,
            Self::LongInt => Domain::TwoValued,
            Self::Integer => Domain::FourValued,
            Self::Time => Domain::TwoValued,
        }
    }

    /// Compute the size of this type.
    pub fn bit_size(&self) -> usize {
        match self {
            Self::Byte => 8,
            Self::ShortInt => 16,
            Self::Int => 32,
            Self::LongInt => 64,
            Self::Integer => 32,
            Self::Time => 64,
        }
    }
    /// Get the default sign for this type.
    pub fn default_sign(&self) -> Sign {
        match self {
            Self::Byte => Sign::Signed,
            Self::ShortInt => Sign::Signed,
            Self::Int => Sign::Signed,
            Self::LongInt => Sign::Signed,
            Self::Integer => Sign::Signed,
            Self::Time => Sign::Unsigned,
        }
    }
}

impl Display for IntAtomType {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::Byte => write!(f, "byte"),
            Self::ShortInt => write!(f, "shortint"),
            Self::Int => write!(f, "int"),
            Self::LongInt => write!(f, "longint"),
            Self::Integer => write!(f, "integer"),
            Self::Time => write!(f, "time"),
        }
    }
}
impl Domain {
    /// Return the single-bit type for this domain (`bit` or `logic`).
    pub fn bit_type(&self) -> IntVecType {
        match self {
            Domain::TwoValued => IntVecType::Bit,
            Domain::FourValued => IntVecType::Logic,
        }
    }
}

impl Sign {
    /// Check whether the type is unsigned.
    ///
    /// Returns false for types which have no sign.
    pub fn is_unsigned(&self) -> bool {
        *self == Sign::Unsigned
    }

    /// Check whether the type is signed.
    ///
    /// Returns false for types which have no sign.
    pub fn is_signed(&self) -> bool {
        *self == Sign::Signed
    }
}

impl Display for Sign {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Sign::Signed => write!(f, "signed"),
            Sign::Unsigned => write!(f, "unsigned"),
        }
    }
}

impl Debug for Sign {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        Display::fmt(self, f)
    }
}

impl Range {
    /// Create a new `[<size>-1:0]` range.
    pub fn with_size(size: usize) -> Self {
        Self {
            size,
            dir: RangeDir::Down,
            offset: 0,
        }
    }

    /// The `$left` dimension.
    pub fn left(self) -> isize {
        match self.dir {
            RangeDir::Up => self.low(),
            RangeDir::Down => self.high(),
        }
    }

    /// The `$right` dimension.
    pub fn right(self) -> isize {
        match self.dir {
            RangeDir::Up => self.high(),
            RangeDir::Down => self.low(),
        }
    }

    /// The `$low` dimension.
    pub fn low(self) -> isize {
        self.offset
    }

    /// The `$high` dimension.
    pub fn high(self) -> isize {
        self.offset + self.size as isize - 1
    }

    /// The `$increment` dimension.
    pub fn increment(self) -> isize {
        match self.dir {
            RangeDir::Up => 1,
            RangeDir::Down => -1,
        }
    }
}

impl Display for Range {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let lo = self.offset;
        let hi = lo + self.size as isize - 1;
        let (lhs, rhs) = match self.dir {
            RangeDir::Up => (lo, hi),
            RangeDir::Down => (hi, lo),
        };
        write!(f, "[{}:{}]", lhs, rhs)
    }
}

impl Debug for Range {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        Display::fmt(self, f)
    }
}

impl<'a> UnpackedType<'a> {
    /// Create a new type with no unpacked dimensions.
    ///
    /// This creates the type on the stack. In general you will want to use the
    /// `make_*` functions to create a type that is interned into a context.
    pub fn new(core: impl Into<UnpackedCore<'a>>) -> Self {
        Self::with_dims(core, vec![])
    }

    /// Create a new type with unpacked dimensions.
    ///
    /// This creates the type on the stack. In general you will want to use the
    /// `make_*` functions to create a type that is interned into a context.
    pub fn with_dims(core: impl Into<UnpackedCore<'a>>, dims: Vec<UnpackedDim<'a>>) -> Self {
        Self {
            core: core.into(),
            dims,
            resolved: None,
            resolved_full: None,
        }
    }

    /// Create an interned type with no unpacked dimensions.
    pub fn make(cx: &impl TypeContext<'a>, core: impl Into<UnpackedCore<'a>>) -> &'a Self {
        Self::make_dims(cx, core, vec![])
    }

    /// Create an interned type with unpacked dimensions.
    pub fn make_dims(
        cx: &impl TypeContext<'a>,
        core: impl Into<UnpackedCore<'a>>,
        dims: Vec<UnpackedDim<'a>>,
    ) -> &'a Self {
        Self::with_dims(core, dims).intern(cx)
    }

    /// Create a tombstone.
    pub fn make_error() -> &'a Self {
        static TYPE: Lazy<UnpackedType> = Lazy::new(|| UnpackedType::new(UnpackedCore::Error));
        let ty: &UnpackedType = &TYPE;
        // SAFETY: This is safe since the cell which causes 'a to need to
        // outlive 'static is actually never mutated after AST construction.
        unsafe { std::mem::transmute(ty) }
    }

    /// Create a `void` type.
    pub fn make_void() -> &'a Self {
        static TYPE: Lazy<UnpackedType> = Lazy::new(|| UnpackedType::new(PackedType::make_void()));
        let ty: &UnpackedType = &TYPE;
        // SAFETY: This is safe since the cell which causes 'a to need to
        // outlive 'static is actually never mutated after AST construction.
        unsafe { std::mem::transmute(ty) }
    }

    /// Create a `logic` type.
    pub fn make_logic() -> &'a Self {
        static TYPE: Lazy<UnpackedType> = Lazy::new(|| UnpackedType::new(PackedType::make_logic()));
        let ty: &UnpackedType = &TYPE;
        // SAFETY: This is safe since the cell which causes 'a to need to
        // outlive 'static is actually never mutated after AST construction.
        unsafe { std::mem::transmute(ty) }
    }

    /// Create a `time` type.
    pub fn make_time() -> &'a Self {
        static TYPE: Lazy<UnpackedType> = Lazy::new(|| UnpackedType::new(PackedType::make_time()));
        let ty: &UnpackedType = &TYPE;
        // SAFETY: This is safe since the cell which causes 'a to need to
        // outlive 'static is actually never mutated after AST construction.
        unsafe { std::mem::transmute(ty) }
    }

    /// Internalize this type in a context and resolve it.
    pub fn intern(mut self, cx: &impl TypeContext<'a>) -> &'a Self {
        let inner = match self.core {
            UnpackedCore::Named { ty, .. } | UnpackedCore::Ref { ty, .. } => {
                (Some(ty), Some(ty.resolve_full()))
            }
            UnpackedCore::Packed(ty) => (
                ty.resolved.map(|p| p.to_unpacked(cx)),
                ty.resolved_full.map(|p| p.to_unpacked(cx)),
            ),
            _ => (None, None),
        };
        self.resolved = inner.0.map(|ty| self.apply_to_inner(cx, ty));
        self.resolved_full = inner.1.map(|ty| self.apply_to_inner(cx, ty));
        if let Some(x) = self.resolved {
            trace!("Type `{}` resolves to `{}`", self, x);
        }
        if let Some(x) = self.resolved_full {
            trace!("Type `{}` fully resolves to `{}`", self, x);
        }
        cx.intern_unpacked(self)
    }

    /// Apply the sign and dimensions to a core type that expanded to another
    /// type.
    fn apply_to_inner(&self, cx: &impl TypeContext<'a>, inner: &'a Self) -> &'a Self {
        if self.dims.is_empty() {
            return inner;
        }
        let out = Self {
            core: inner.core.clone(),
            dims: self
                .dims
                .iter()
                .cloned()
                .chain(inner.dims.iter().cloned())
                .collect(),
            resolved: None,
            resolved_full: None,
        };
        out.intern(cx)
    }

    /// Resolve one level of name or type reference indirection.
    ///
    /// For example, given `typedef int foo; typedef foo bar;`, resolves `bar`
    /// to `foo`.
    pub fn resolve(&self) -> &Self {
        self.resolved.unwrap_or(self)
    }

    /// Resolve all name or type reference indirections recursively.
    ///
    /// For example, given `typedef int foo; typedef foo bar;`, resolves `bar`
    /// to `int`.
    pub fn resolve_full(&self) -> &Self {
        self.resolved_full.unwrap_or(self)
    }

    /// Check if this is a tombstone.
    pub fn is_error(&self) -> bool {
        self.core.is_error()
    }

    /// Check if this type is equal to another one.
    ///
    /// Types which coalesce to `iN` in LLHD are checked for equality of their
    /// SBVT.
    pub fn is_identical(&self, other: &Self) -> bool {
        let a = self.resolve_full();
        let b = other.resolve_full();
        a.core.is_identical(&b.core) && a.dims == b.dims
    }

    /// Check if this type is strictly equal to another one.
    pub fn is_strictly_identical(&self, other: &Self) -> bool {
        let a = self.resolve_full();
        let b = other.resolve_full();
        a.core.is_strictly_identical(&b.core) && a.dims == b.dims
    }

    /// Check if this type is strictly a packed type.
    pub fn is_packed(&self) -> bool {
        self.get_packed().is_some()
    }

    /// If this type is strictly a packed type, convert it.
    pub fn get_packed(&self) -> Option<&'a PackedType<'a>> {
        if self.dims.is_empty() {
            self.core.get_packed()
        } else {
            None
        }
    }

    /// Get the domain for this type.
    pub fn domain(&self) -> Domain {
        match &self.core {
            UnpackedCore::Packed(x) => x.domain(),
            UnpackedCore::Struct(x) => x.domain(),
            UnpackedCore::Named { ty, .. } | UnpackedCore::Ref { ty, .. } => ty.domain(),
            UnpackedCore::Error
            | UnpackedCore::Real(_)
            | UnpackedCore::String
            | UnpackedCore::Chandle
            | UnpackedCore::Event
            | UnpackedCore::Module { .. }
            | UnpackedCore::Interface { .. } => Domain::TwoValued,
        }
    }

    /// Get the sign for this type.
    pub fn sign(&self) -> Sign {
        match &self.core {
            UnpackedCore::Packed(x) => x.sign(),
            UnpackedCore::Struct(_) => Sign::Unsigned, // TODO(fschuiki): This is probably an error
            UnpackedCore::Named { ty, .. } | UnpackedCore::Ref { ty, .. } => ty.sign(),
            UnpackedCore::Error
            | UnpackedCore::Real(_)
            | UnpackedCore::String
            | UnpackedCore::Chandle
            | UnpackedCore::Event
            | UnpackedCore::Module { .. }
            | UnpackedCore::Interface { .. } => Sign::Unsigned,
        }
    }

    /// Compute the size of this type in bits.
    ///
    /// Returns `None` if one of the type's dimensions is unsized, associative,
    /// or a queue, or the core type has no known size.
    pub fn get_bit_size(&self) -> Option<usize> {
        let ty = self.resolve_full();
        let mut size = match &ty.core {
            UnpackedCore::Packed(x) => x.get_bit_size()?,
            UnpackedCore::Real(x) => x.bit_size(),
            UnpackedCore::Struct(x) => x.get_bit_size()?,
            UnpackedCore::Named { ty, .. } | UnpackedCore::Ref { ty, .. } => ty.get_bit_size()?,
            UnpackedCore::Error
            | UnpackedCore::String
            | UnpackedCore::Chandle
            | UnpackedCore::Event
            | UnpackedCore::Module { .. }
            | UnpackedCore::Interface { .. } => return None,
        };
        for &dim in &self.dims {
            match dim {
                UnpackedDim::Array(r) => size *= r,
                UnpackedDim::Range(r) => size *= r.size,
                UnpackedDim::Unsized | UnpackedDim::Assoc(..) | UnpackedDim::Queue(..) => {
                    return None
                }
            }
        }
        Some(size)
    }

    /// Check if this is a void type.
    pub fn is_void(&self) -> bool {
        self.get_packed().map(|ty| ty.is_void()).unwrap_or(false)
    }

    /// Check if this type is trivially a SBVT.
    pub fn is_simple_bit_vector(&self) -> bool {
        self.get_packed()
            .map(|ty| ty.is_simple_bit_vector())
            .unwrap_or(false)
    }

    /// Check if this type is an integer atom type, like `int`.
    pub fn is_integer_atom(&self) -> bool {
        self.get_packed()
            .map(|ty| ty.is_integer_atom())
            .unwrap_or(false)
    }

    /// Check if this type is a single bit type, like `bit`.
    pub fn is_single_bit(&self) -> bool {
        self.get_packed()
            .map(|ty| ty.is_single_bit())
            .unwrap_or(false)
    }

    /// Check if this type is a string, like `string`.
    pub fn is_string(&self) -> bool {
        self.dims.is_empty() && self.resolve_full().core == UnpackedCore::String
    }

    /// Check if this type will coalesce to a scalar type in LLHD, like `i42`.
    pub fn coalesces_to_llhd_scalar(&self) -> bool {
        self.get_packed()
            .map(|ty| ty.coalesces_to_llhd_scalar())
            .unwrap_or(false)
    }

    /// Convert this type into an SBVT if possible.
    pub fn get_simple_bit_vector(&self) -> Option<SbvType> {
        self.get_packed().and_then(|ty| ty.get_simple_bit_vector())
    }

    /// Convert this type into an SBVT, or report a bug with the given span.
    pub fn simple_bit_vector(&self, cx: &impl DiagEmitter, span: Span) -> SbvType {
        match self.get_simple_bit_vector() {
            Some(sbv) => sbv,
            None => bug_span!(span, cx, "`{}` has no simple bit vector equivalent", self),
        }
    }

    /// Get an iterator over the type's packed dimensions, slowest-varying
    /// first.
    ///
    /// For example, produces `[3:0], [7:0]` for `bit [3:0][7:0] $ [1][2]`.
    pub fn packed_dims(&self) -> impl Iterator<Item = PackedDim> + 'a {
        self.resolve_full()
            .core
            .get_packed()
            .into_iter()
            .flat_map(|p| p.dims.iter().cloned())
    }

    /// Get an iterator over the type's unpacked dimensions, slowest-varying
    /// first.
    ///
    /// For example, produces `[1], [2]` for `bit [3:0][7:0] $ [1][2]`.
    pub fn unpacked_dims<'s>(&'s self) -> impl Iterator<Item = UnpackedDim<'a>> + 's {
        self.resolve_full().dims.iter().cloned()
    }

    /// Get an iterator over the type's dimensions. slowest-varying first.
    ///
    /// For example, produces `[1], [2], [3:0], [7:0]` for `bit [3:0][7:0] $
    /// [1][2]`.
    pub fn dims<'s>(&'s self) -> impl Iterator<Item = Dim<'a>> + 's {
        self.unpacked_dims()
            .map(Dim::Unpacked)
            .chain(self.packed_dims().map(Dim::Packed))
    }

    /// Pop the outermost dimension off the type.
    ///
    /// For example, maps `bit $ [1][2]` to `bit $ [2]`. Pops off the packed
    /// type as well, mapping `bit [7:0] $` to `bit $`.
    pub fn pop_dim(&self, cx: &impl TypeContext<'a>) -> Option<&'a Self> {
        let ty = self.resolve_full();
        if !ty.dims.is_empty() {
            let mut new = ty.clone();
            new.dims.remove(0);
            Some(new.intern(cx))
        } else {
            self.get_packed()
                .and_then(|p| p.pop_dim(cx))
                .map(|p| p.to_unpacked(cx))
        }
    }

    /// Replace the outermost dimension of the type.
    ///
    /// Panics if the type has no dimensions, or a packed dimension is replaced
    /// with an unpacked dimension, or vice-versa.
    pub fn replace_dim(&self, cx: &impl TypeContext<'a>, dim: Dim<'a>) -> &'a Self {
        let ty = self.resolve_full();
        if !ty.dims.is_empty() {
            let mut new = ty.clone();
            let dim = match dim {
                Dim::Unpacked(d) => d,
                Dim::Packed(d) => panic!(
                    "substituting {:?} for type `{}` whose outermost dimension is unpacked",
                    d, self
                ),
            };
            new.dims[0] = dim;
            new.intern(cx)
        } else {
            let packed = match self.get_packed() {
                Some(packed) => packed,
                None => panic!("no dimension in `{}` to substitute with `{}`", self, dim),
            };
            let dim = match dim {
                Dim::Packed(d) => d,
                Dim::Unpacked(d) => panic!(
                    "substituting {:?} for type `{}` whose outermost dimension is packed",
                    d, self
                ),
            };
            packed.replace_dim(cx, dim).to_unpacked(cx)
        }
    }

    /// Get the outermost dimension of the type.
    ///
    /// For example, yields the `[1]` in `bit $ [1][2]`.
    pub fn outermost_dim(&self) -> Option<Dim<'a>> {
        self.dims().next()
    }

    /// Get the underlying struct, or `None` if the type is no struct.
    pub fn get_struct(&self) -> Option<&StructType<'a>> {
        if self.dims.is_empty() {
            self.resolve_full().core.get_struct()
        } else {
            None
        }
    }

    /// Get the underlying enum, or `None` if the type is no enum.
    pub fn get_enum(&self) -> Option<&EnumType<'a>> {
        if self.dims.is_empty() {
            self.resolve_full().core.get_enum()
        } else {
            None
        }
    }

    /// Get the underlying module, or `None` if the type is not a module.
    pub fn get_module(&self) -> Option<&ModuleType<'a>> {
        if self.dims.is_empty() {
            self.resolve_full().core.get_module()
        } else {
            None
        }
    }

    /// Get the underlying interface, or `None` if the type is not a interface.
    pub fn get_interface(&self) -> Option<&InterfaceType<'a>> {
        if self.dims.is_empty() {
            self.resolve_full().core.get_interface()
        } else {
            None
        }
    }

    /// Helper function to format this type around a declaration name.
    fn format_around(
        &self,
        f: &mut std::fmt::Formatter,
        around: Option<impl Display>,
    ) -> std::fmt::Result {
        write!(f, "{}", self.core)?;
        if let Some(around) = around {
            write!(f, " {}", around)?;
        }
        if !self.dims.is_empty() {
            write!(f, " ")?;
            for dim in &self.dims {
                write!(f, "{}", dim)?;
            }
        }
        Ok(())
    }
}

// Compare and hash `UnpackedType` by reference.
impl Eq for UnpackedType<'_> {}
impl PartialEq for UnpackedType<'_> {
    fn eq(&self, other: &Self) -> bool {
        std::ptr::eq(self, other)
    }
}
impl Hash for UnpackedType<'_> {
    fn hash<H: Hasher>(&self, h: &mut H) {
        std::ptr::hash(self, h)
    }
}

// Compare and hash `Intern<UnpackedType>` by value.
impl Eq for Intern<UnpackedType<'_>> {}
impl PartialEq for Intern<UnpackedType<'_>> {
    fn eq(&self, other: &Self) -> bool {
        self.0.core == other.0.core
            && self.0.dims == other.0.dims
            && self.0.resolved == other.0.resolved
            && self.0.resolved_full == other.0.resolved_full
    }
}
impl Hash for Intern<UnpackedType<'_>> {
    fn hash<H: Hasher>(&self, h: &mut H) {
        self.0.core.hash(h);
        self.0.dims.hash(h);
        self.0.resolved.hash(h);
        self.0.resolved_full.hash(h);
    }
}

impl Display for UnpackedType<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        self.format_around(
            f,
            if self.dims.is_empty() {
                None
            } else {
                Some("$")
            },
        )
    }
}

impl Debug for UnpackedType<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        Display::fmt(self.resolve_full(), f)
    }
}

impl<'a> UnpackedCore<'a> {
    /// Check if this is a tombstone.
    pub fn is_error(&self) -> bool {
        match self {
            Self::Error => true,
            Self::Packed(ty) => ty.is_error(),
            Self::Named { ty, .. } | Self::Ref { ty, .. } => ty.is_error(),
            _ => false,
        }
    }

    /// Check if this type is identical to another one.
    pub fn is_identical(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Error, Self::Error) => true,
            (Self::Packed(a), Self::Packed(b)) => a.is_identical(b),
            (Self::Real(a), Self::Real(b)) => a == b,
            (Self::Struct(a), Self::Struct(b)) => a == b,
            (Self::String, Self::String) => true,
            (Self::Chandle, Self::Chandle) => true,
            (Self::Event, Self::Event) => true,
            (Self::Named { ty: a, .. }, Self::Named { ty: b, .. }) => a.is_identical(b),
            (Self::Ref { ty: a, .. }, Self::Ref { ty: b, .. }) => a.is_identical(b),
            (Self::Module(a), Self::Module(b)) => a == b,
            (Self::Interface(a), Self::Interface(b)) => a == b,
            _ => false,
        }
    }

    /// Check if this type is strictly identical to another one.
    pub fn is_strictly_identical(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Error, Self::Error) => true,
            (Self::Packed(a), Self::Packed(b)) => a.is_strictly_identical(b),
            (Self::Real(a), Self::Real(b)) => a == b,
            (Self::Struct(a), Self::Struct(b)) => a == b,
            (Self::String, Self::String) => true,
            (Self::Chandle, Self::Chandle) => true,
            (Self::Event, Self::Event) => true,
            (Self::Named { ty: a, .. }, Self::Named { ty: b, .. }) => a.is_strictly_identical(b),
            (Self::Ref { ty: a, .. }, Self::Ref { ty: b, .. }) => a.is_strictly_identical(b),
            (Self::Module(a), Self::Module(b)) => a == b,
            (Self::Interface(a), Self::Interface(b)) => a == b,
            _ => false,
        }
    }

    /// If this type is strictly a packed type, convert it.
    pub fn get_packed(&self) -> Option<&'a PackedType<'a>> {
        match *self {
            UnpackedCore::Packed(inner) => Some(inner),
            UnpackedCore::Named { ty, .. } | UnpackedCore::Ref { ty, .. } => ty.get_packed(),
            _ => None,
        }
    }

    /// Get the underlying struct, or `None` if the type is no struct.
    pub fn get_struct(&self) -> Option<&StructType<'a>> {
        match *self {
            UnpackedCore::Packed(x) => x.get_struct(),
            UnpackedCore::Struct(ref x) => Some(x),
            UnpackedCore::Named { ty, .. } | UnpackedCore::Ref { ty, .. } => ty.get_struct(),
            _ => None,
        }
    }

    /// Get the underlying enum, or `None` if the type is no enum.
    pub fn get_enum(&self) -> Option<&EnumType<'a>> {
        self.get_packed().and_then(|packed| packed.get_enum())
    }

    /// Get the underlying module, or `None` if the type is not a module.
    pub fn get_module(&self) -> Option<&ModuleType<'a>> {
        match *self {
            UnpackedCore::Module(ref x) => Some(x),
            UnpackedCore::Named { ty, .. } | UnpackedCore::Ref { ty, .. } => ty.get_module(),
            _ => None,
        }
    }

    /// Get the underlying interface, or `None` if the type is not a interface.
    pub fn get_interface(&self) -> Option<&InterfaceType<'a>> {
        match *self {
            UnpackedCore::Interface(ref x) => Some(x),
            UnpackedCore::Named { ty, .. } | UnpackedCore::Ref { ty, .. } => ty.get_interface(),
            _ => None,
        }
    }
}

impl<'a> From<&'a PackedType<'a>> for UnpackedCore<'a> {
    fn from(inner: &'a PackedType<'a>) -> Self {
        Self::Packed(inner)
    }
}

impl<'a> From<RealType> for UnpackedCore<'a> {
    fn from(inner: RealType) -> Self {
        Self::Real(inner)
    }
}

impl<'a> From<StructType<'a>> for UnpackedCore<'a> {
    fn from(inner: StructType<'a>) -> Self {
        Self::Struct(inner)
    }
}

impl<'a> From<ModuleType<'a>> for UnpackedCore<'a> {
    fn from(inner: ModuleType<'a>) -> Self {
        Self::Module(inner)
    }
}

impl<'a> From<InterfaceType<'a>> for UnpackedCore<'a> {
    fn from(inner: InterfaceType<'a>) -> Self {
        Self::Interface(inner)
    }
}

impl Display for UnpackedCore<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::Error => write!(f, "<error>"),
            Self::Packed(x) => write!(f, "{}", x),
            Self::Real(x) => write!(f, "{}", x),
            Self::Struct(x) => x.format(f, false, None),
            Self::String => write!(f, "string"),
            Self::Chandle => write!(f, "chandle"),
            Self::Event => write!(f, "event"),
            Self::Module(x) => write!(f, "{}", x.ast.name),
            Self::Interface(x) => match x.modport {
                Some(y) => write!(f, "{}.{}", x.ast.name, y.name),
                None => write!(f, "{}", x.ast.name),
            },
            Self::Named { name, .. } => write!(f, "{}", name),
            Self::Ref { span, .. } => write!(f, "{}", span.extract()),
        }
    }
}

impl UnpackedDim<'_> {
    /// Get the dimension's range, or `None` if it is unsized.
    pub fn get_range(&self) -> Option<Range> {
        match *self {
            Self::Range(x) => Some(x),
            _ => None,
        }
    }

    /// Get the dimension's size, or `None` if it is unsized.
    pub fn get_size(&self) -> Option<usize> {
        match *self {
            Self::Array(x) => Some(x),
            Self::Range(x) => Some(x.size),
            _ => None,
        }
    }
}

impl From<usize> for UnpackedDim<'_> {
    fn from(size: usize) -> Self {
        Self::Array(size)
    }
}
impl From<Range> for UnpackedDim<'_> {
    fn from(range: Range) -> Self {
        Self::Range(range)
    }
}

impl Display for UnpackedDim<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::Unsized => write!(f, "[]"),
            Self::Array(x) => write!(f, "[{}]", x),
            Self::Range(x) => write!(f, "{}", x),
            Self::Assoc(Some(x)) => write!(f, "[{}]", x),
            Self::Assoc(None) => write!(f, "[*]"),
            Self::Queue(Some(x)) => write!(f, "[$:{}]", x),
            Self::Queue(None) => write!(f, "[$]"),
        }
    }
}

impl RealType {
    /// Compute the size of this type.
    pub fn bit_size(&self) -> usize {
        match self {
            Self::ShortReal => 32,
            Self::Real => 64,
            Self::RealTime => 64,
        }
    }
}

impl Display for RealType {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::ShortReal => write!(f, "shortreal"),
            Self::Real => write!(f, "real"),
            Self::RealTime => write!(f, "realtime"),
        }
    }
}

impl<'a> StructType<'a> {
    /// Get the domain for this struct.
    pub fn domain(&self) -> Domain {
        let any_four_valued = self
            .members
            .iter()
            .any(|m| m.ty.domain() == Domain::FourValued);
        match any_four_valued {
            true => Domain::FourValued,
            false => Domain::TwoValued,
        }
    }

    /// Compute the size of this struct in bits.
    ///
    /// Returns `None` if any member of the type has a `[]` dimension.
    pub fn get_bit_size(&self) -> Option<usize> {
        let mut size = 0;
        for m in &self.members {
            size += m.ty.get_bit_size()?;
        }
        Some(size)
    }

    /// Helper function to format this struct.
    fn format(
        &self,
        f: &mut std::fmt::Formatter,
        packed: bool,
        sign: Option<Sign>,
    ) -> std::fmt::Result {
        write!(f, "{}", self.kind)?;
        if packed {
            write!(f, " packed")?;
            if let Some(sign) = sign {
                write!(f, " {}", sign)?;
            }
        }
        write!(f, " {{ ")?;
        for member in &self.members {
            write!(f, "{}; ", member)?;
        }
        write!(f, "}}")?;
        Ok(())
    }
}

impl Display for StructType<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        self.format(f, false, None)
    }
}

impl Display for StructMember<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        self.ty.format_around(f, Some(self.name))
    }
}

impl Display for EnumType<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "enum")?;
        if self.base_explicit {
            write!(f, " {}", self.base)?;
        }
        write!(f, " {{")?;
        let mut first = true;
        for (name, _) in &self.variants {
            if !first {
                write!(f, ",")?;
            }
            write!(f, " ")?;
            first = false;
            write!(f, "{}", name)?;
        }
        write!(f, " }}")?;
        Ok(())
    }
}

impl SbvType {
    /// Create a new SBVT which expands exactly to `<domain> <sign>
    /// [<size>-1:0]`.
    pub fn new(domain: Domain, sign: Sign, size: usize) -> Self {
        Self {
            domain,
            used_atom: false,
            sign,
            sign_explicit: false,
            size,
            size_explicit: true,
        }
    }

    /// Create a new SBVT which expands to most terse representation possible.
    ///
    /// For example, creating a signed, two-value, 32 bit SBVT will expand to
    /// `int`.
    pub fn nice(domain: Domain, sign: Sign, size: usize) -> Self {
        Self {
            domain,
            used_atom: true,
            sign,
            sign_explicit: false,
            size,
            size_explicit: false,
        }
    }

    /// Convert the SBVT to a packed type.
    pub fn to_packed<'a>(&self, cx: &impl TypeContext<'a>) -> &'a PackedType<'a> {
        PackedType::make_simple_bit_vector(cx, *self)
    }

    /// Convert the SBVT to an unpacked type.
    pub fn to_unpacked<'a>(&self, cx: &impl TypeContext<'a>) -> &'a UnpackedType<'a> {
        self.to_packed(cx).to_unpacked(cx)
    }

    /// Check whether the type is unsigned.
    pub fn is_unsigned(&self) -> bool {
        self.sign == Sign::Unsigned
    }

    /// Check whether the type is signed.
    pub fn is_signed(&self) -> bool {
        self.sign == Sign::Signed
    }

    /// Get the range of the type.
    pub fn range(&self) -> Range {
        Range {
            size: self.size,
            dir: RangeDir::Down,
            offset: 0,
        }
    }

    /// Change the size of the type.
    pub fn change_size(&self, size: usize) -> SbvType {
        SbvType {
            used_atom: self.used_atom && self.size == size,
            size: size,
            ..*self
        }
    }

    /// Change the domain of the type.
    pub fn change_domain(&self, domain: Domain) -> SbvType {
        SbvType { domain, ..*self }
    }

    /// Change the sign of the type.
    pub fn change_sign(&self, sign: Sign) -> SbvType {
        SbvType {
            sign,
            sign_explicit: self.sign_explicit || self.sign != sign,
            ..*self
        }
    }

    /// Check whether this type is identical to another one.
    pub fn is_identical(&self, other: &Self) -> bool {
        self.domain == other.domain && self.sign == other.sign && self.size == other.size
    }

    /// Return a new SBVT that strictly converts to an IntVecType with one
    /// dimension.
    pub fn forget(&self) -> SbvType {
        SbvType {
            used_atom: false,
            sign_explicit: false,
            size_explicit: true,
            ..*self
        }
    }
}

impl Display for SbvType {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self.domain {
            Domain::TwoValued => write!(f, "bit")?,
            Domain::FourValued => write!(f, "logic")?,
        }
        if self.sign != Sign::Unsigned || self.sign_explicit {
            write!(f, " {}", self.sign)?;
        }
        if self.size > 1 || self.size_explicit {
            write!(f, " {}", self.range())?;
        }
        Ok(())
    }
}

impl Dim<'_> {
    /// Get the dimension's range, or `None` if it has no range.
    pub fn get_range(&self) -> Option<Range> {
        match self {
            Self::Packed(x) => x.get_range(),
            Self::Unpacked(x) => x.get_range(),
        }
    }

    /// Get the dimension's size, or `None` if it has no size.
    pub fn get_size(&self) -> Option<usize> {
        match self {
            Self::Packed(x) => x.get_size(),
            Self::Unpacked(x) => x.get_size(),
        }
    }
}

impl Display for Dim<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::Packed(x) => write!(f, "{}", x),
            Self::Unpacked(x) => write!(f, "{}", x),
        }
    }
}

/// A container for type operations.
pub trait TypeContext<'a> {
    /// Internalize a packed type.
    fn intern_packed(&self, ty: PackedType<'a>) -> &'a PackedType<'a>;

    /// Internalize an unpacked type.
    fn intern_unpacked(&self, ty: UnpackedType<'a>) -> &'a UnpackedType<'a>;
}

/// An arena that can internalize type data.
#[derive(Default)]
pub struct TypeStorage<'a> {
    packed: TypedArena<Intern<PackedType<'a>>>,
    unpacked: TypedArena<Intern<UnpackedType<'a>>>,
    cached_packed: RefCell<HashSet<&'a Intern<PackedType<'a>>>>,
    cached_unpacked: RefCell<HashSet<&'a Intern<UnpackedType<'a>>>>,
}

/// An object that has type storage.
pub trait HasTypeStorage<'a> {
    /// Get the type storage.
    fn type_storage(&self) -> &'a TypeStorage<'a>;
}

/// An wrapper around types that hash/compare by pointer, but must hash/compare
/// by value for interning.
struct Intern<T>(T);

impl<'a, T> TypeContext<'a> for T
where
    T: HasTypeStorage<'a>,
{
    fn intern_packed(&self, ty: PackedType<'a>) -> &'a PackedType<'a> {
        let ty = Intern(ty);
        let st = self.type_storage();
        if let Some(x) = st.cached_packed.borrow().get(&ty) {
            return &x.0;
        }
        let ty = st.packed.alloc(ty);
        st.cached_packed.borrow_mut().insert(ty);
        &ty.0
    }

    fn intern_unpacked(&self, ty: UnpackedType<'a>) -> &'a UnpackedType<'a> {
        let ty = Intern(ty);
        let st = self.type_storage();
        if let Some(x) = st.cached_unpacked.borrow().get(&ty) {
            return &x.0;
        }
        let ty = st.unpacked.alloc(ty);
        st.cached_unpacked.borrow_mut().insert(ty);
        &ty.0
    }
}

impl<'a> HasTypeStorage<'a> for &'a TypeStorage<'a> {
    fn type_storage(&self) -> &'a TypeStorage<'a> {
        *self
    }
}