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

// FIXME(#1000): component support in `wasm-smith` is a work in progress.
#![allow(unused_variables, dead_code)]

use crate::{arbitrary_loop, Config};
use arbitrary::{Arbitrary, Result, Unstructured};
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::{
    collections::{HashMap, HashSet},
    rc::Rc,
};
use wasm_encoder::{ComponentTypeRef, ComponentValType, PrimitiveValType, TypeBounds, ValType};

mod encode;

/// A pseudo-random WebAssembly [component].
///
/// Construct instances of this type with [the `Arbitrary`
/// trait](https://docs.rs/arbitrary/*/arbitrary/trait.Arbitrary.html).
///
/// [component]: https://github.com/WebAssembly/component-model/blob/ast-and-binary/design/MVP/Explainer.md
///
/// ## Configured Generated Components
///
/// The `Arbitrary` implementation uses the [`Config::default()`][crate::Config]
/// configuration. If you want to customize the shape of generated components,
/// create your own [`Config`][crate::Config] instance and pass it to
/// [`Component::new`][crate::Component::new].
#[derive(Debug)]
pub struct Component {
    sections: Vec<Section>,
}

/// A builder to create a component (and possibly a whole tree of nested
/// components).
///
/// Maintains a stack of components we are currently building, as well as
/// metadata about them. The split between `Component` and `ComponentBuilder` is
/// that the builder contains metadata that is purely used when generating
/// components and is unnecessary after we are done generating the structure of
/// the components and only need to encode an already-generated component to
/// bytes.
#[derive(Debug)]
struct ComponentBuilder {
    config: Config,

    // The set of core `valtype`s that we are configured to generate.
    core_valtypes: Vec<ValType>,

    // Stack of types scopes that are currently available.
    //
    // There is an entry in this stack for each component, but there can also be
    // additional entries for module/component/instance types, each of which
    // have their own scope.
    //
    // This stack is always non-empty and the last entry is always the current
    // scope.
    //
    // When a particular scope can alias outer types, it can alias from any
    // scope that is older than it (i.e. `types_scope[i]` can alias from
    // `types_scope[j]` when `j <= i`).
    types: Vec<TypesScope>,

    // The set of components we are currently building and their associated
    // metadata.
    components: Vec<ComponentContext>,

    // Whether we are in the final bits of generating this component and we just
    // need to ensure that the minimum number of entities configured have all
    // been generated. This changes the behavior of various
    // `arbitrary_<section>` methods to always fill in their minimums.
    fill_minimums: bool,

    // Our maximums for these entities are applied across the whole component
    // tree, not per-component.
    total_components: usize,
    total_modules: usize,
    total_instances: usize,
    total_values: usize,
}

#[derive(Debug, Clone)]
enum ComponentOrCoreFuncType {
    Component(Rc<FuncType>),
    Core(Rc<crate::core::FuncType>),
}

impl ComponentOrCoreFuncType {
    fn as_core(&self) -> &Rc<crate::core::FuncType> {
        match self {
            ComponentOrCoreFuncType::Core(t) => t,
            ComponentOrCoreFuncType::Component(_) => panic!("not a core func type"),
        }
    }

    fn as_component(&self) -> &Rc<FuncType> {
        match self {
            ComponentOrCoreFuncType::Core(_) => panic!("not a component func type"),
            ComponentOrCoreFuncType::Component(t) => t,
        }
    }
}

#[derive(Debug, Clone)]
enum ComponentOrCoreInstanceType {
    Component(Rc<InstanceType>),
    Core(BTreeMap<String, crate::core::EntityType>),
}

/// Metadata (e.g. contents of various index spaces) we keep track of on a
/// per-component basis.
#[derive(Debug)]
struct ComponentContext {
    // The actual component itself.
    component: Component,

    // The number of imports we have generated thus far.
    num_imports: usize,

    // The set of names of imports we've generated thus far.
    import_names: HashSet<String>,

    // The set of URLs of imports we've generated thus far.
    import_urls: HashSet<String>,

    // This component's function index space.
    funcs: Vec<ComponentOrCoreFuncType>,

    // Which entries in `funcs` are component functions?
    component_funcs: Vec<u32>,

    // Which entries in `component_funcs` are component functions that only use scalar
    // types?
    scalar_component_funcs: Vec<u32>,

    // Which entries in `funcs` are core Wasm functions?
    //
    // Note that a component can't import core functions, so these entries will
    // never point to a `Section::Import`.
    core_funcs: Vec<u32>,

    // This component's component index space.
    //
    // An indirect list of all directly-nested (not transitive) components
    // inside this component.
    //
    // Each entry is of the form `(i, j)` where `component.sections[i]` is
    // guaranteed to be either
    //
    // * a `Section::Component` and we are referencing the component defined in
    //   that section (in this case `j` must also be `0`, since a component
    //   section can only contain a single nested component), or
    //
    // * a `Section::Import` and we are referencing the `j`th import in that
    //   section, which is guaranteed to be a component import.
    components: Vec<(usize, usize)>,

    // This component's module index space.
    //
    // An indirect list of all directly-nested (not transitive) modules
    // inside this component.
    //
    // Each entry is of the form `(i, j)` where `component.sections[i]` is
    // guaranteed to be either
    //
    // * a `Section::Core` and we are referencing the module defined in that
    //   section (in this case `j` must also be `0`, since a core section can
    //   only contain a single nested module), or
    //
    // * a `Section::Import` and we are referencing the `j`th import in that
    //   section, which is guaranteed to be a module import.
    modules: Vec<(usize, usize)>,

    // This component's instance index space.
    instances: Vec<ComponentOrCoreInstanceType>,

    // This component's value index space.
    values: Vec<ComponentValType>,
}

impl ComponentContext {
    fn empty() -> Self {
        ComponentContext {
            component: Component::empty(),
            num_imports: 0,
            import_names: HashSet::default(),
            import_urls: HashSet::default(),
            funcs: vec![],
            component_funcs: vec![],
            scalar_component_funcs: vec![],
            core_funcs: vec![],
            components: vec![],
            modules: vec![],
            instances: vec![],
            values: vec![],
        }
    }

    fn num_modules(&self) -> usize {
        self.modules.len()
    }

    fn num_components(&self) -> usize {
        self.components.len()
    }

    fn num_instances(&self) -> usize {
        self.instances.len()
    }

    fn num_funcs(&self) -> usize {
        self.funcs.len()
    }

    fn num_values(&self) -> usize {
        self.values.len()
    }
}

#[derive(Debug, Default)]
struct TypesScope {
    // All core types in this scope, regardless of kind.
    core_types: Vec<Rc<CoreType>>,

    // The indices of all the entries in `core_types` that are core function types.
    core_func_types: Vec<u32>,

    // The indices of all the entries in `core_types` that are module types.
    module_types: Vec<u32>,

    // All component types in this index space, regardless of kind.
    types: Vec<Rc<Type>>,

    // The indices of all the entries in `types` that are defined value types.
    defined_types: Vec<u32>,

    // The indices of all the entries in `types` that are func types.
    func_types: Vec<u32>,

    // A map from function types to their indices in the types space.
    func_type_to_indices: HashMap<Rc<FuncType>, Vec<u32>>,

    // The indices of all the entries in `types` that are component types.
    component_types: Vec<u32>,

    // The indices of all the entries in `types` that are instance types.
    instance_types: Vec<u32>,
}

impl TypesScope {
    fn push(&mut self, ty: Rc<Type>) -> u32 {
        let ty_idx = u32::try_from(self.types.len()).unwrap();

        let kind_list = match &*ty {
            Type::Defined(_) => &mut self.defined_types,
            Type::Func(func_ty) => {
                self.func_type_to_indices
                    .entry(func_ty.clone())
                    .or_default()
                    .push(ty_idx);
                &mut self.func_types
            }
            Type::Component(_) => &mut self.component_types,
            Type::Instance(_) => &mut self.instance_types,
        };
        kind_list.push(ty_idx);

        self.types.push(ty);
        ty_idx
    }

    fn push_core(&mut self, ty: Rc<CoreType>) -> u32 {
        let ty_idx = u32::try_from(self.core_types.len()).unwrap();

        let kind_list = match &*ty {
            CoreType::Func(_) => &mut self.core_func_types,
            CoreType::Module(_) => &mut self.module_types,
        };
        kind_list.push(ty_idx);

        self.core_types.push(ty);
        ty_idx
    }

    fn get(&self, index: u32) -> &Rc<Type> {
        &self.types[index as usize]
    }

    fn get_core(&self, index: u32) -> &Rc<CoreType> {
        &self.core_types[index as usize]
    }

    fn get_func(&self, index: u32) -> &Rc<FuncType> {
        match &**self.get(index) {
            Type::Func(f) => f,
            _ => panic!("get_func on non-function type"),
        }
    }

    fn can_ref_type(&self) -> bool {
        // All component types and core module types may be referenced
        !self.types.is_empty() || !self.module_types.is_empty()
    }
}

impl<'a> Arbitrary<'a> for Component {
    fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
        Component::new(Config::default(), u)
    }
}

#[derive(Default)]
struct EntityCounts {
    globals: usize,
    tables: usize,
    memories: usize,
    tags: usize,
    funcs: usize,
}

impl Component {
    /// Construct a new `Component` using the given configuration.
    pub fn new(config: Config, u: &mut Unstructured) -> Result<Self> {
        let mut builder = ComponentBuilder::new(config);
        builder.build(u)
    }

    fn empty() -> Self {
        Component { sections: vec![] }
    }
}

#[must_use]
enum Step {
    Finished(Component),
    StillBuilding,
}

impl Step {
    fn unwrap_still_building(self) {
        match self {
            Step::Finished(_) => panic!(
                "`Step::unwrap_still_building` called on a `Step` that is not `StillBuilding`"
            ),
            Step::StillBuilding => {}
        }
    }
}

impl ComponentBuilder {
    fn new(config: Config) -> Self {
        ComponentBuilder {
            config,
            core_valtypes: vec![],
            types: vec![Default::default()],
            components: vec![ComponentContext::empty()],
            fill_minimums: false,
            total_components: 0,
            total_modules: 0,
            total_instances: 0,
            total_values: 0,
        }
    }

    fn build(&mut self, u: &mut Unstructured) -> Result<Component> {
        self.core_valtypes = crate::core::configured_valtypes(&self.config);

        let mut choices: Vec<fn(&mut ComponentBuilder, &mut Unstructured) -> Result<Step>> = vec![];

        loop {
            choices.clear();
            choices.push(Self::finish_component);

            // Only add any choice other than "finish what we've generated thus
            // far" when there is more arbitrary fuzzer data for us to consume.
            if !u.is_empty() {
                choices.push(Self::arbitrary_custom_section);

                // NB: we add each section as a choice even if we've already
                // generated our maximum number of entities in that section so that
                // we can exercise adding empty sections to the end of the module.
                choices.push(Self::arbitrary_core_type_section);
                choices.push(Self::arbitrary_type_section);
                choices.push(Self::arbitrary_import_section);
                choices.push(Self::arbitrary_canonical_section);

                if self.total_modules < self.config.max_modules {
                    choices.push(Self::arbitrary_core_module_section);
                }

                if self.components.len() < self.config.max_nesting_depth
                    && self.total_components < self.config.max_components
                {
                    choices.push(Self::arbitrary_component_section);
                }

                // FIXME(#1000)
                //
                // choices.push(Self::arbitrary_instance_section);
                // choices.push(Self::arbitrary_export_section);
                // choices.push(Self::arbitrary_start_section);
                // choices.push(Self::arbitrary_alias_section);
            }

            let f = u.choose(&choices)?;
            match f(self, u)? {
                Step::StillBuilding => {}
                Step::Finished(component) => {
                    if self.components.is_empty() {
                        // If we just finished the root component, then return it.
                        return Ok(component);
                    } else {
                        // Otherwise, add it as a nested component in the parent.
                        self.push_section(Section::Component(component));
                    }
                }
            }
        }
    }

    fn finish_component(&mut self, u: &mut Unstructured) -> Result<Step> {
        // Ensure we've generated all of our minimums.
        self.fill_minimums = true;
        {
            if self.current_type_scope().types.len() < self.config.min_types {
                self.arbitrary_type_section(u)?.unwrap_still_building();
            }
            if self.component().num_imports < self.config.min_imports {
                self.arbitrary_import_section(u)?.unwrap_still_building();
            }
            if self.component().funcs.len() < self.config.min_funcs {
                self.arbitrary_canonical_section(u)?.unwrap_still_building();
            }
        }
        self.fill_minimums = false;

        self.types
            .pop()
            .expect("should have a types scope for the component we are finishing");
        Ok(Step::Finished(self.components.pop().unwrap().component))
    }

    fn component(&self) -> &ComponentContext {
        self.components.last().unwrap()
    }

    fn component_mut(&mut self) -> &mut ComponentContext {
        self.components.last_mut().unwrap()
    }

    fn last_section(&self) -> Option<&Section> {
        self.component().component.sections.last()
    }

    fn last_section_mut(&mut self) -> Option<&mut Section> {
        self.component_mut().component.sections.last_mut()
    }

    fn push_section(&mut self, section: Section) {
        self.component_mut().component.sections.push(section);
    }

    fn ensure_section(
        &mut self,
        mut predicate: impl FnMut(&Section) -> bool,
        mut make_section: impl FnMut() -> Section,
    ) -> &mut Section {
        match self.last_section() {
            Some(sec) if predicate(sec) => {}
            _ => self.push_section(make_section()),
        }
        self.last_section_mut().unwrap()
    }

    fn arbitrary_custom_section(&mut self, u: &mut Unstructured) -> Result<Step> {
        self.push_section(Section::Custom(u.arbitrary()?));
        Ok(Step::StillBuilding)
    }

    fn push_type(&mut self, ty: Rc<Type>) -> u32 {
        match self.ensure_section(
            |s| matches!(s, Section::Type(_)),
            || Section::Type(TypeSection { types: vec![] }),
        ) {
            Section::Type(TypeSection { types }) => {
                types.push(ty.clone());
                self.current_type_scope_mut().push(ty)
            }
            _ => unreachable!(),
        }
    }

    fn push_core_type(&mut self, ty: Rc<CoreType>) -> u32 {
        match self.ensure_section(
            |s| matches!(s, Section::CoreType(_)),
            || Section::CoreType(CoreTypeSection { types: vec![] }),
        ) {
            Section::CoreType(CoreTypeSection { types }) => {
                types.push(ty.clone());
                self.current_type_scope_mut().push_core(ty)
            }
            _ => unreachable!(),
        }
    }

    fn arbitrary_core_type_section(&mut self, u: &mut Unstructured) -> Result<Step> {
        self.push_section(Section::CoreType(CoreTypeSection { types: vec![] }));

        let min = if self.fill_minimums {
            self.config
                .min_types
                .saturating_sub(self.current_type_scope().types.len())
        } else {
            0
        };

        let max = self.config.max_types - self.current_type_scope().types.len();

        arbitrary_loop(u, min, max, |u| {
            let mut type_fuel = self.config.max_type_size;
            let ty = self.arbitrary_core_type(u, &mut type_fuel)?;
            self.push_core_type(ty);
            Ok(true)
        })?;

        Ok(Step::StillBuilding)
    }

    fn arbitrary_core_type(
        &self,
        u: &mut Unstructured,
        type_fuel: &mut u32,
    ) -> Result<Rc<CoreType>> {
        *type_fuel = type_fuel.saturating_sub(1);
        if *type_fuel == 0 {
            return Ok(Rc::new(CoreType::Module(Rc::new(ModuleType::default()))));
        }

        let ty = match u.int_in_range::<u8>(0..=1)? {
            0 => CoreType::Func(crate::core::arbitrary_func_type(
                u,
                &self.config,
                &self.core_valtypes,
                if self.config.multi_value_enabled {
                    None
                } else {
                    Some(1)
                },
                0,
            )?),
            1 => CoreType::Module(self.arbitrary_module_type(u, type_fuel)?),
            _ => unreachable!(),
        };
        Ok(Rc::new(ty))
    }

    fn arbitrary_type_section(&mut self, u: &mut Unstructured) -> Result<Step> {
        self.push_section(Section::Type(TypeSection { types: vec![] }));

        let min = if self.fill_minimums {
            self.config
                .min_types
                .saturating_sub(self.current_type_scope().types.len())
        } else {
            0
        };

        let max = self.config.max_types - self.current_type_scope().types.len();

        arbitrary_loop(u, min, max, |u| {
            let mut type_fuel = self.config.max_type_size;
            let ty = self.arbitrary_type(u, &mut type_fuel)?;
            self.push_type(ty);
            Ok(true)
        })?;

        Ok(Step::StillBuilding)
    }

    fn arbitrary_type_ref<'a>(
        &self,
        u: &mut Unstructured<'a>,
        for_import: bool,
        for_type_def: bool,
    ) -> Result<Option<ComponentTypeRef>> {
        let mut choices: Vec<fn(&Self, &mut Unstructured) -> Result<ComponentTypeRef>> = Vec::new();
        let scope = self.current_type_scope();

        if !scope.module_types.is_empty()
            && (for_type_def || !for_import || self.total_modules < self.config.max_modules)
        {
            choices.push(|me, u| {
                Ok(ComponentTypeRef::Module(
                    *u.choose(&me.current_type_scope().module_types)?,
                ))
            });
        }

        // Types cannot be imported currently
        if !for_import
            && !scope.types.is_empty()
            && (for_type_def || scope.types.len() < self.config.max_types)
        {
            choices.push(|me, u| {
                Ok(ComponentTypeRef::Type(TypeBounds::Eq(u.int_in_range(
                    0..=u32::try_from(me.current_type_scope().types.len() - 1).unwrap(),
                )?)))
            });
        }

        // TODO: wasm-smith needs to ensure that every arbitrary value gets used exactly once.
        //       until that time, don't import values
        // if for_type_def || !for_import || self.total_values < self.config.max_values() {
        //     choices.push(|me, u| Ok(ComponentTypeRef::Value(me.arbitrary_component_val_type(u)?)));
        // }

        if !scope.func_types.is_empty()
            && (for_type_def || !for_import || self.component().num_funcs() < self.config.max_funcs)
        {
            choices.push(|me, u| {
                Ok(ComponentTypeRef::Func(
                    *u.choose(&me.current_type_scope().func_types)?,
                ))
            });
        }

        if !scope.component_types.is_empty()
            && (for_type_def || !for_import || self.total_components < self.config.max_components)
        {
            choices.push(|me, u| {
                Ok(ComponentTypeRef::Component(
                    *u.choose(&me.current_type_scope().component_types)?,
                ))
            });
        }

        if !scope.instance_types.is_empty()
            && (for_type_def || !for_import || self.total_instances < self.config.max_instances)
        {
            choices.push(|me, u| {
                Ok(ComponentTypeRef::Instance(
                    *u.choose(&me.current_type_scope().instance_types)?,
                ))
            });
        }

        if choices.is_empty() {
            return Ok(None);
        }

        let f = u.choose(&choices)?;
        f(self, u).map(Option::Some)
    }

    fn arbitrary_type(&mut self, u: &mut Unstructured, type_fuel: &mut u32) -> Result<Rc<Type>> {
        *type_fuel = type_fuel.saturating_sub(1);
        if *type_fuel == 0 {
            return Ok(Rc::new(Type::Defined(
                self.arbitrary_defined_type(u, type_fuel)?,
            )));
        }

        let ty = match u.int_in_range::<u8>(0..=3)? {
            0 => Type::Defined(self.arbitrary_defined_type(u, type_fuel)?),
            1 => Type::Func(self.arbitrary_func_type(u, type_fuel)?),
            2 => Type::Component(self.arbitrary_component_type(u, type_fuel)?),
            3 => Type::Instance(self.arbitrary_instance_type(u, type_fuel)?),
            _ => unreachable!(),
        };
        Ok(Rc::new(ty))
    }

    fn arbitrary_module_type(
        &self,
        u: &mut Unstructured,
        type_fuel: &mut u32,
    ) -> Result<Rc<ModuleType>> {
        let mut defs = vec![];
        let mut has_memory = false;
        let mut has_canonical_abi_realloc = false;
        let mut has_canonical_abi_free = false;
        let mut types: Vec<Rc<crate::core::FuncType>> = vec![];
        let mut imports = HashMap::new();
        let mut exports = HashSet::new();
        let mut counts = EntityCounts::default();

        // Special case the canonical ABI functions since certain types can only
        // be passed across the component boundary if they exist and
        // randomly generating them is extremely unlikely.

        // `memory`
        if counts.memories < self.config.max_memories && u.ratio::<u8>(99, 100)? {
            defs.push(ModuleTypeDef::Export(
                "memory".into(),
                crate::core::EntityType::Memory(self.arbitrary_core_memory_type(u)?),
            ));
            exports.insert("memory".into());
            counts.memories += 1;
            has_memory = true;
        }

        // `canonical_abi_realloc`
        if counts.funcs < self.config.max_funcs
            && types.len() < self.config.max_types
            && u.ratio::<u8>(99, 100)?
        {
            let realloc_ty = Rc::new(crate::core::FuncType {
                params: vec![ValType::I32, ValType::I32, ValType::I32, ValType::I32],
                results: vec![ValType::I32],
            });
            let ty_idx = u32::try_from(types.len()).unwrap();
            types.push(realloc_ty.clone());
            defs.push(ModuleTypeDef::TypeDef(crate::core::CompositeType::Func(
                realloc_ty.clone(),
            )));
            defs.push(ModuleTypeDef::Export(
                "canonical_abi_realloc".into(),
                crate::core::EntityType::Func(ty_idx, realloc_ty),
            ));
            exports.insert("canonical_abi_realloc".into());
            counts.funcs += 1;
            has_canonical_abi_realloc = true;
        }

        // `canonical_abi_free`
        if counts.funcs < self.config.max_funcs
            && types.len() < self.config.max_types
            && u.ratio::<u8>(99, 100)?
        {
            let free_ty = Rc::new(crate::core::FuncType {
                params: vec![ValType::I32, ValType::I32, ValType::I32],
                results: vec![],
            });
            let ty_idx = u32::try_from(types.len()).unwrap();
            types.push(free_ty.clone());
            defs.push(ModuleTypeDef::TypeDef(crate::core::CompositeType::Func(
                free_ty.clone(),
            )));
            defs.push(ModuleTypeDef::Export(
                "canonical_abi_free".into(),
                crate::core::EntityType::Func(ty_idx, free_ty),
            ));
            exports.insert("canonical_abi_free".into());
            counts.funcs += 1;
            has_canonical_abi_free = true;
        }

        let mut entity_choices: Vec<
            fn(
                &ComponentBuilder,
                &mut Unstructured,
                &mut EntityCounts,
                &[Rc<crate::core::FuncType>],
            ) -> Result<crate::core::EntityType>,
        > = Vec::with_capacity(5);

        arbitrary_loop(u, 0, 100, |u| {
            *type_fuel = type_fuel.saturating_sub(1);
            if *type_fuel == 0 {
                return Ok(false);
            }

            let max_choice = if types.len() < self.config.max_types {
                // Check if the parent scope has core function types to alias
                if !types.is_empty()
                    || (!self.types.is_empty()
                        && !self.types.last().unwrap().core_func_types.is_empty())
                {
                    // Imports, exports, types, and aliases
                    3
                } else {
                    // Imports, exports, and types
                    2
                }
            } else {
                // Imports and exports
                1
            };

            match u.int_in_range::<u8>(0..=max_choice)? {
                // Import.
                0 => {
                    let module = crate::limited_string(100, u)?;
                    let existing_module_imports = imports.entry(module.clone()).or_default();
                    let field = crate::unique_string(100, existing_module_imports, u)?;
                    let entity_type = match self.arbitrary_core_entity_type(
                        u,
                        &types,
                        &mut entity_choices,
                        &mut counts,
                    )? {
                        None => return Ok(false),
                        Some(x) => x,
                    };
                    defs.push(ModuleTypeDef::Import(crate::core::Import {
                        module,
                        field,
                        entity_type,
                    }));
                }

                // Export.
                1 => {
                    let name = crate::unique_string(100, &mut exports, u)?;
                    let entity_ty = match self.arbitrary_core_entity_type(
                        u,
                        &types,
                        &mut entity_choices,
                        &mut counts,
                    )? {
                        None => return Ok(false),
                        Some(x) => x,
                    };
                    defs.push(ModuleTypeDef::Export(name, entity_ty));
                }

                // Type definition.
                2 => {
                    let ty = crate::core::arbitrary_func_type(
                        u,
                        &self.config,
                        &self.core_valtypes,
                        if self.config.multi_value_enabled {
                            None
                        } else {
                            Some(1)
                        },
                        0,
                    )?;
                    types.push(ty.clone());
                    defs.push(ModuleTypeDef::TypeDef(crate::core::CompositeType::Func(ty)));
                }

                // Alias
                3 => {
                    let (count, index, kind) = self.arbitrary_outer_core_type_alias(u, &types)?;
                    let ty = match &kind {
                        CoreOuterAliasKind::Type(ty) => ty.clone(),
                    };
                    types.push(ty);
                    defs.push(ModuleTypeDef::OuterAlias {
                        count,
                        i: index,
                        kind,
                    });
                }

                _ => unreachable!(),
            }

            Ok(true)
        })?;

        Ok(Rc::new(ModuleType {
            defs,
            has_memory,
            has_canonical_abi_realloc,
            has_canonical_abi_free,
        }))
    }

    fn arbitrary_core_entity_type(
        &self,
        u: &mut Unstructured,
        types: &[Rc<crate::core::FuncType>],
        choices: &mut Vec<
            fn(
                &ComponentBuilder,
                &mut Unstructured,
                &mut EntityCounts,
                &[Rc<crate::core::FuncType>],
            ) -> Result<crate::core::EntityType>,
        >,
        counts: &mut EntityCounts,
    ) -> Result<Option<crate::core::EntityType>> {
        choices.clear();

        if counts.globals < self.config.max_globals {
            choices.push(|c, u, counts, _types| {
                counts.globals += 1;
                Ok(crate::core::EntityType::Global(
                    c.arbitrary_core_global_type(u)?,
                ))
            });
        }

        if counts.tables < self.config.max_tables {
            choices.push(|c, u, counts, _types| {
                counts.tables += 1;
                Ok(crate::core::EntityType::Table(
                    c.arbitrary_core_table_type(u)?,
                ))
            });
        }

        if counts.memories < self.config.max_memories {
            choices.push(|c, u, counts, _types| {
                counts.memories += 1;
                Ok(crate::core::EntityType::Memory(
                    c.arbitrary_core_memory_type(u)?,
                ))
            });
        }

        if types.iter().any(|ty| ty.results.is_empty())
            && self.config.exceptions_enabled
            && counts.tags < self.config.max_tags
        {
            choices.push(|c, u, counts, types| {
                counts.tags += 1;
                let tag_func_types = types
                    .iter()
                    .enumerate()
                    .filter(|(_, ty)| ty.results.is_empty())
                    .map(|(i, _)| u32::try_from(i).unwrap())
                    .collect::<Vec<_>>();
                Ok(crate::core::EntityType::Tag(
                    crate::core::arbitrary_tag_type(u, &tag_func_types, |idx| {
                        types[usize::try_from(idx).unwrap()].clone()
                    })?,
                ))
            });
        }

        if !types.is_empty() && counts.funcs < self.config.max_funcs {
            choices.push(|c, u, counts, types| {
                counts.funcs += 1;
                let ty_idx = u.int_in_range(0..=u32::try_from(types.len() - 1).unwrap())?;
                let ty = types[ty_idx as usize].clone();
                Ok(crate::core::EntityType::Func(ty_idx, ty))
            });
        }

        if choices.is_empty() {
            return Ok(None);
        }

        let f = u.choose(choices)?;
        let ty = f(self, u, counts, types)?;
        Ok(Some(ty))
    }

    fn arbitrary_core_valtype(&self, u: &mut Unstructured) -> Result<ValType> {
        Ok(*u.choose(&self.core_valtypes)?)
    }

    fn arbitrary_core_global_type(&self, u: &mut Unstructured) -> Result<crate::core::GlobalType> {
        Ok(crate::core::GlobalType {
            val_type: self.arbitrary_core_valtype(u)?,
            mutable: u.arbitrary()?,
        })
    }

    fn arbitrary_core_table_type(&self, u: &mut Unstructured) -> Result<crate::core::TableType> {
        crate::core::arbitrary_table_type(u, &self.config)
    }

    fn arbitrary_core_memory_type(&self, u: &mut Unstructured) -> Result<crate::core::MemoryType> {
        crate::core::arbitrary_memtype(u, &self.config)
    }

    fn with_types_scope<T>(&mut self, f: impl FnOnce(&mut Self) -> Result<T>) -> Result<T> {
        self.types.push(Default::default());
        let result = f(self);
        self.types.pop();
        result
    }

    fn current_type_scope(&self) -> &TypesScope {
        self.types.last().unwrap()
    }

    fn current_type_scope_mut(&mut self) -> &mut TypesScope {
        self.types.last_mut().unwrap()
    }

    fn outer_types_scope(&self, count: u32) -> &TypesScope {
        &self.types[self.types.len() - 1 - usize::try_from(count).unwrap()]
    }

    fn outer_type(&self, count: u32, i: u32) -> &Rc<Type> {
        &self.outer_types_scope(count).types[usize::try_from(i).unwrap()]
    }

    fn arbitrary_component_type(
        &mut self,
        u: &mut Unstructured,
        type_fuel: &mut u32,
    ) -> Result<Rc<ComponentType>> {
        let mut defs = vec![];
        let mut imports = HashSet::new();
        let mut import_urls = HashSet::new();
        let mut exports = HashSet::new();
        let mut export_urls = HashSet::new();

        self.with_types_scope(|me| {
            arbitrary_loop(u, 0, 100, |u| {
                *type_fuel = type_fuel.saturating_sub(1);
                if *type_fuel == 0 {
                    return Ok(false);
                }

                if me.current_type_scope().can_ref_type() && u.int_in_range::<u8>(0..=3)? == 0 {
                    if let Some(ty) = me.arbitrary_type_ref(u, true, true)? {
                        // Imports.
                        let name = crate::unique_kebab_string(100, &mut imports, u)?;
                        let url = if u.arbitrary()? {
                            Some(crate::unique_url(100, &mut import_urls, u)?)
                        } else {
                            None
                        };
                        defs.push(ComponentTypeDef::Import(Import { name, url, ty }));
                        return Ok(true);
                    }

                    // Can't reference an arbitrary type, fallback to another definition.
                }

                // Type definitions, exports, and aliases.
                let def =
                    me.arbitrary_instance_type_def(u, &mut exports, &mut export_urls, type_fuel)?;
                defs.push(def.into());
                Ok(true)
            })
        })?;

        Ok(Rc::new(ComponentType { defs }))
    }

    fn arbitrary_instance_type(
        &mut self,
        u: &mut Unstructured,
        type_fuel: &mut u32,
    ) -> Result<Rc<InstanceType>> {
        let mut defs = vec![];
        let mut exports = HashSet::new();
        let mut export_urls = HashSet::new();

        self.with_types_scope(|me| {
            arbitrary_loop(u, 0, 100, |u| {
                *type_fuel = type_fuel.saturating_sub(1);
                if *type_fuel == 0 {
                    return Ok(false);
                }

                defs.push(me.arbitrary_instance_type_def(
                    u,
                    &mut exports,
                    &mut export_urls,
                    type_fuel,
                )?);
                Ok(true)
            })
        })?;

        Ok(Rc::new(InstanceType { defs }))
    }

    fn arbitrary_instance_type_def(
        &mut self,
        u: &mut Unstructured,
        exports: &mut HashSet<String>,
        export_urls: &mut HashSet<String>,
        type_fuel: &mut u32,
    ) -> Result<InstanceTypeDecl> {
        let mut choices: Vec<
            fn(
                &mut ComponentBuilder,
                &mut HashSet<String>,
                &mut HashSet<String>,
                &mut Unstructured,
                &mut u32,
            ) -> Result<InstanceTypeDecl>,
        > = Vec::with_capacity(3);

        // Export.
        if self.current_type_scope().can_ref_type() {
            choices.push(|me, exports, export_urls, u, _type_fuel| {
                let ty = me.arbitrary_type_ref(u, false, true)?.unwrap();
                if let ComponentTypeRef::Type(TypeBounds::Eq(idx)) = ty {
                    let ty = me.current_type_scope().get(idx).clone();
                    me.current_type_scope_mut().push(ty);
                }
                Ok(InstanceTypeDecl::Export {
                    name: crate::unique_kebab_string(100, exports, u)?,
                    url: if u.arbitrary()? {
                        Some(crate::unique_url(100, export_urls, u)?)
                    } else {
                        None
                    },
                    ty,
                })
            });
        }

        // Outer type alias.
        if self
            .types
            .iter()
            .any(|scope| !scope.types.is_empty() || !scope.core_types.is_empty())
        {
            choices.push(|me, _exports, _export_urls, u, _type_fuel| {
                let alias = me.arbitrary_outer_type_alias(u)?;
                match &alias {
                    Alias::Outer {
                        kind: OuterAliasKind::Type(ty),
                        ..
                    } => me.current_type_scope_mut().push(ty.clone()),
                    Alias::Outer {
                        kind: OuterAliasKind::CoreType(ty),
                        ..
                    } => me.current_type_scope_mut().push_core(ty.clone()),
                    _ => unreachable!(),
                };
                Ok(InstanceTypeDecl::Alias(alias))
            });
        }

        // Core type definition.
        choices.push(|me, _exports, _export_urls, u, type_fuel| {
            let ty = me.arbitrary_core_type(u, type_fuel)?;
            me.current_type_scope_mut().push_core(ty.clone());
            Ok(InstanceTypeDecl::CoreType(ty))
        });

        // Type definition.
        if self.types.len() < self.config.max_nesting_depth {
            choices.push(|me, _exports, _export_urls, u, type_fuel| {
                let ty = me.arbitrary_type(u, type_fuel)?;
                me.current_type_scope_mut().push(ty.clone());
                Ok(InstanceTypeDecl::Type(ty))
            });
        }

        let f = u.choose(&choices)?;
        f(self, exports, export_urls, u, type_fuel)
    }

    fn arbitrary_outer_core_type_alias(
        &self,
        u: &mut Unstructured,
        local_types: &[Rc<crate::core::FuncType>],
    ) -> Result<(u32, u32, CoreOuterAliasKind)> {
        let enclosing_type_len = if !self.types.is_empty() {
            self.types.last().unwrap().core_func_types.len()
        } else {
            0
        };

        assert!(!local_types.is_empty() || enclosing_type_len > 0);

        let max = enclosing_type_len + local_types.len() - 1;
        let i = u.int_in_range(0..=max)?;
        let (count, index, ty) = if i < enclosing_type_len {
            let enclosing = self.types.last().unwrap();
            let index = enclosing.core_func_types[i];
            (
                1,
                index,
                match enclosing.get_core(index).as_ref() {
                    CoreType::Func(ty) => ty.clone(),
                    CoreType::Module(_) => unreachable!(),
                },
            )
        } else if i - enclosing_type_len < local_types.len() {
            let i = i - enclosing_type_len;
            (0, u32::try_from(i).unwrap(), local_types[i].clone())
        } else {
            unreachable!()
        };

        Ok((count, index, CoreOuterAliasKind::Type(ty)))
    }

    fn arbitrary_outer_type_alias(&self, u: &mut Unstructured) -> Result<Alias> {
        let non_empty_types_scopes: Vec<_> = self
            .types
            .iter()
            .rev()
            .enumerate()
            .filter(|(_, scope)| !scope.types.is_empty() || !scope.core_types.is_empty())
            .collect();
        assert!(
            !non_empty_types_scopes.is_empty(),
            "precondition: there are non-empty types scopes"
        );

        let (count, scope) = u.choose(&non_empty_types_scopes)?;
        let count = u32::try_from(*count).unwrap();
        assert!(!scope.types.is_empty() || !scope.core_types.is_empty());

        let max_type_in_scope = scope.types.len() + scope.core_types.len() - 1;
        let i = u.int_in_range(0..=max_type_in_scope)?;

        let (i, kind) = if i < scope.types.len() {
            let i = u32::try_from(i).unwrap();
            (i, OuterAliasKind::Type(Rc::clone(scope.get(i))))
        } else if i - scope.types.len() < scope.core_types.len() {
            let i = u32::try_from(i - scope.types.len()).unwrap();
            (i, OuterAliasKind::CoreType(Rc::clone(scope.get_core(i))))
        } else {
            unreachable!()
        };

        Ok(Alias::Outer { count, i, kind })
    }

    fn arbitrary_func_type(
        &self,
        u: &mut Unstructured,
        type_fuel: &mut u32,
    ) -> Result<Rc<FuncType>> {
        let mut params = Vec::new();
        let mut results = Vec::new();
        let mut names = HashSet::new();

        // Note: parameters are currently limited to a maximum of 16
        // because any additional parameters will require indirect access
        // via a pointer argument; when this occurs, validation of any
        // lowered function will fail because it will be missing a
        // memory option (not yet implemented).
        //
        // When options are correctly specified on canonical functions,
        // we should increase this maximum to test indirect parameter
        // passing.
        arbitrary_loop(u, 0, 16, |u| {
            *type_fuel = type_fuel.saturating_sub(1);
            if *type_fuel == 0 {
                return Ok(false);
            }

            let name = crate::unique_kebab_string(100, &mut names, u)?;
            let ty = self.arbitrary_component_val_type(u)?;

            params.push((name, ty));

            Ok(true)
        })?;

        names.clear();

        // Likewise, the limit for results is 1 before the memory option is
        // required. When the memory option is implemented, this restriction
        // should be relaxed.
        arbitrary_loop(u, 0, 1, |u| {
            *type_fuel = type_fuel.saturating_sub(1);
            if *type_fuel == 0 {
                return Ok(false);
            }

            // If the result list is empty (i.e. first push), then arbitrarily give
            // the result a name. Otherwise, all of the subsequent items must be named.
            let name = if results.is_empty() {
                // Most of the time we should have a single, unnamed result.
                u.ratio::<u8>(10, 100)?
                    .then(|| crate::unique_kebab_string(100, &mut names, u))
                    .transpose()?
            } else {
                Some(crate::unique_kebab_string(100, &mut names, u)?)
            };

            let ty = self.arbitrary_component_val_type(u)?;

            results.push((name, ty));

            // There can be only one unnamed result.
            if results.len() == 1 && results[0].0.is_none() {
                return Ok(false);
            }

            Ok(true)
        })?;

        Ok(Rc::new(FuncType { params, results }))
    }

    fn arbitrary_component_val_type(&self, u: &mut Unstructured) -> Result<ComponentValType> {
        let max_choices = if self.current_type_scope().defined_types.is_empty() {
            0
        } else {
            1
        };
        match u.int_in_range(0..=max_choices)? {
            0 => Ok(ComponentValType::Primitive(
                self.arbitrary_primitive_val_type(u)?,
            )),
            1 => {
                let index = *u.choose(&self.current_type_scope().defined_types)?;
                let ty = Rc::clone(self.current_type_scope().get(index));
                Ok(ComponentValType::Type(index))
            }
            _ => unreachable!(),
        }
    }

    fn arbitrary_primitive_val_type(&self, u: &mut Unstructured) -> Result<PrimitiveValType> {
        match u.int_in_range(0..=12)? {
            0 => Ok(PrimitiveValType::Bool),
            1 => Ok(PrimitiveValType::S8),
            2 => Ok(PrimitiveValType::U8),
            3 => Ok(PrimitiveValType::S16),
            4 => Ok(PrimitiveValType::U16),
            5 => Ok(PrimitiveValType::S32),
            6 => Ok(PrimitiveValType::U32),
            7 => Ok(PrimitiveValType::S64),
            8 => Ok(PrimitiveValType::U64),
            9 => Ok(PrimitiveValType::Float32),
            10 => Ok(PrimitiveValType::Float64),
            11 => Ok(PrimitiveValType::Char),
            12 => Ok(PrimitiveValType::String),
            _ => unreachable!(),
        }
    }

    fn arbitrary_record_type(
        &self,
        u: &mut Unstructured,
        type_fuel: &mut u32,
    ) -> Result<RecordType> {
        let mut fields = vec![];
        let mut field_names = HashSet::new();
        arbitrary_loop(u, 0, 100, |u| {
            *type_fuel = type_fuel.saturating_sub(1);
            if *type_fuel == 0 {
                return Ok(false);
            }

            let name = crate::unique_kebab_string(100, &mut field_names, u)?;
            let ty = self.arbitrary_component_val_type(u)?;

            fields.push((name, ty));
            Ok(true)
        })?;
        Ok(RecordType { fields })
    }

    fn arbitrary_variant_type(
        &self,
        u: &mut Unstructured,
        type_fuel: &mut u32,
    ) -> Result<VariantType> {
        let mut cases = vec![];
        let mut case_names = HashSet::new();
        arbitrary_loop(u, 1, 100, |u| {
            *type_fuel = type_fuel.saturating_sub(1);
            if *type_fuel == 0 {
                return Ok(false);
            }

            let name = crate::unique_kebab_string(100, &mut case_names, u)?;

            let ty = u
                .arbitrary::<bool>()?
                .then(|| self.arbitrary_component_val_type(u))
                .transpose()?;

            let refines = if !cases.is_empty() && u.arbitrary()? {
                let max_cases = u32::try_from(cases.len() - 1).unwrap();
                Some(u.int_in_range(0..=max_cases)?)
            } else {
                None
            };

            cases.push((name, ty, refines));
            Ok(true)
        })?;

        Ok(VariantType { cases })
    }

    fn arbitrary_list_type(&self, u: &mut Unstructured) -> Result<ListType> {
        Ok(ListType {
            elem_ty: self.arbitrary_component_val_type(u)?,
        })
    }

    fn arbitrary_tuple_type(&self, u: &mut Unstructured, type_fuel: &mut u32) -> Result<TupleType> {
        let mut fields = vec![];
        arbitrary_loop(u, 0, 100, |u| {
            *type_fuel = type_fuel.saturating_sub(1);
            if *type_fuel == 0 {
                return Ok(false);
            }

            fields.push(self.arbitrary_component_val_type(u)?);
            Ok(true)
        })?;
        Ok(TupleType { fields })
    }

    fn arbitrary_flags_type(&self, u: &mut Unstructured, type_fuel: &mut u32) -> Result<FlagsType> {
        let mut fields = vec![];
        let mut field_names = HashSet::new();
        arbitrary_loop(u, 0, 100, |u| {
            *type_fuel = type_fuel.saturating_sub(1);
            if *type_fuel == 0 {
                return Ok(false);
            }

            fields.push(crate::unique_kebab_string(100, &mut field_names, u)?);
            Ok(true)
        })?;
        Ok(FlagsType { fields })
    }

    fn arbitrary_enum_type(&self, u: &mut Unstructured, type_fuel: &mut u32) -> Result<EnumType> {
        let mut variants = vec![];
        let mut variant_names = HashSet::new();
        arbitrary_loop(u, 1, 100, |u| {
            *type_fuel = type_fuel.saturating_sub(1);
            if *type_fuel == 0 {
                return Ok(false);
            }

            variants.push(crate::unique_kebab_string(100, &mut variant_names, u)?);
            Ok(true)
        })?;
        Ok(EnumType { variants })
    }

    fn arbitrary_option_type(&self, u: &mut Unstructured) -> Result<OptionType> {
        Ok(OptionType {
            inner_ty: self.arbitrary_component_val_type(u)?,
        })
    }

    fn arbitrary_result_type(&self, u: &mut Unstructured) -> Result<ResultType> {
        Ok(ResultType {
            ok_ty: u
                .arbitrary::<bool>()?
                .then(|| self.arbitrary_component_val_type(u))
                .transpose()?,
            err_ty: u
                .arbitrary::<bool>()?
                .then(|| self.arbitrary_component_val_type(u))
                .transpose()?,
        })
    }

    fn arbitrary_defined_type(
        &self,
        u: &mut Unstructured,
        type_fuel: &mut u32,
    ) -> Result<DefinedType> {
        match u.int_in_range(0..=8)? {
            0 => Ok(DefinedType::Primitive(
                self.arbitrary_primitive_val_type(u)?,
            )),
            1 => Ok(DefinedType::Record(
                self.arbitrary_record_type(u, type_fuel)?,
            )),
            2 => Ok(DefinedType::Variant(
                self.arbitrary_variant_type(u, type_fuel)?,
            )),
            3 => Ok(DefinedType::List(self.arbitrary_list_type(u)?)),
            4 => Ok(DefinedType::Tuple(self.arbitrary_tuple_type(u, type_fuel)?)),
            5 => Ok(DefinedType::Flags(self.arbitrary_flags_type(u, type_fuel)?)),
            6 => Ok(DefinedType::Enum(self.arbitrary_enum_type(u, type_fuel)?)),
            7 => Ok(DefinedType::Option(self.arbitrary_option_type(u)?)),
            8 => Ok(DefinedType::Result(self.arbitrary_result_type(u)?)),
            _ => unreachable!(),
        }
    }

    fn push_import(&mut self, name: String, url: Option<String>, ty: ComponentTypeRef) {
        let nth = match self.ensure_section(
            |sec| matches!(sec, Section::Import(_)),
            || Section::Import(ImportSection { imports: vec![] }),
        ) {
            Section::Import(sec) => {
                sec.imports.push(Import { name, url, ty });
                sec.imports.len() - 1
            }
            _ => unreachable!(),
        };
        let section_index = self.component().component.sections.len() - 1;

        match ty {
            ComponentTypeRef::Module(_) => {
                self.total_modules += 1;
                self.component_mut().modules.push((section_index, nth));
            }
            ComponentTypeRef::Func(ty_index) => {
                let func_ty = match self.current_type_scope().get(ty_index).as_ref() {
                    Type::Func(ty) => ty.clone(),
                    _ => unreachable!(),
                };

                if func_ty.is_scalar() {
                    let func_index = u32::try_from(self.component().component_funcs.len()).unwrap();
                    self.component_mut().scalar_component_funcs.push(func_index);
                }

                let func_index = u32::try_from(self.component().funcs.len()).unwrap();
                self.component_mut()
                    .funcs
                    .push(ComponentOrCoreFuncType::Component(func_ty));

                self.component_mut().component_funcs.push(func_index);
            }
            ComponentTypeRef::Value(ty) => {
                self.total_values += 1;
                self.component_mut().values.push(ty);
            }
            ComponentTypeRef::Type(TypeBounds::Eq(ty_index)) => {
                let ty = self.current_type_scope().get(ty_index).clone();
                self.current_type_scope_mut().push(ty);
            }
            ComponentTypeRef::Type(TypeBounds::SubResource) => {
                unimplemented!()
            }
            ComponentTypeRef::Instance(ty_index) => {
                let instance_ty = match self.current_type_scope().get(ty_index).as_ref() {
                    Type::Instance(ty) => ty.clone(),
                    _ => unreachable!(),
                };

                self.total_instances += 1;
                self.component_mut()
                    .instances
                    .push(ComponentOrCoreInstanceType::Component(instance_ty));
            }
            ComponentTypeRef::Component(_) => {
                self.total_components += 1;
                self.component_mut().components.push((section_index, nth));
            }
        }
    }

    fn core_function_type(&self, core_func_index: u32) -> &Rc<crate::core::FuncType> {
        self.component().funcs[self.component().core_funcs[core_func_index as usize] as usize]
            .as_core()
    }

    fn component_function_type(&self, func_index: u32) -> &Rc<FuncType> {
        self.component().funcs[self.component().component_funcs[func_index as usize] as usize]
            .as_component()
    }

    fn push_func(&mut self, func: Func) {
        let nth = match self.component_mut().component.sections.last_mut() {
            Some(Section::Canonical(CanonicalSection { funcs })) => funcs.len(),
            _ => {
                self.push_section(Section::Canonical(CanonicalSection { funcs: vec![] }));
                0
            }
        };
        let section_index = self.component().component.sections.len() - 1;

        let func_index = u32::try_from(self.component().funcs.len()).unwrap();

        let ty = match &func {
            Func::CanonLift { func_ty, .. } => {
                let ty = Rc::clone(self.current_type_scope().get_func(*func_ty));
                if ty.is_scalar() {
                    let func_index = u32::try_from(self.component().component_funcs.len()).unwrap();
                    self.component_mut().scalar_component_funcs.push(func_index);
                }
                self.component_mut().component_funcs.push(func_index);
                ComponentOrCoreFuncType::Component(ty)
            }
            Func::CanonLower {
                func_index: comp_func_index,
                ..
            } => {
                let comp_func_ty = self.component_function_type(*comp_func_index);
                let core_func_ty = canonical_abi_for(comp_func_ty);
                self.component_mut().core_funcs.push(func_index);
                ComponentOrCoreFuncType::Core(core_func_ty)
            }
        };

        self.component_mut().funcs.push(ty);

        match self.component_mut().component.sections.last_mut() {
            Some(Section::Canonical(CanonicalSection { funcs })) => funcs.push(func),
            _ => unreachable!(),
        }
    }

    fn arbitrary_import_section(&mut self, u: &mut Unstructured) -> Result<Step> {
        self.push_section(Section::Import(ImportSection { imports: vec![] }));

        let min = if self.fill_minimums {
            self.config
                .min_imports
                .saturating_sub(self.component().num_imports)
        } else {
            // Allow generating empty sections. We can always fill in the required
            // minimum later.
            0
        };
        let max = self.config.max_imports - self.component().num_imports;

        crate::arbitrary_loop(u, min, max, |u| {
            match self.arbitrary_type_ref(u, true, false)? {
                Some(ty) => {
                    let name =
                        crate::unique_kebab_string(100, &mut self.component_mut().import_names, u)?;
                    let url = if u.arbitrary()? {
                        Some(crate::unique_url(
                            100,
                            &mut self.component_mut().import_urls,
                            u,
                        )?)
                    } else {
                        None
                    };
                    self.push_import(name, url, ty);
                    Ok(true)
                }
                None => Ok(false),
            }
        })?;

        Ok(Step::StillBuilding)
    }

    fn arbitrary_canonical_section(&mut self, u: &mut Unstructured) -> Result<Step> {
        self.push_section(Section::Canonical(CanonicalSection { funcs: vec![] }));

        let min = if self.fill_minimums {
            self.config
                .min_funcs
                .saturating_sub(self.component().funcs.len())
        } else {
            // Allow generating empty sections. We can always fill in the
            // required minimum later.
            0
        };
        let max = self.config.max_funcs - self.component().funcs.len();

        let mut choices: Vec<fn(&mut Unstructured, &mut ComponentBuilder) -> Result<Option<Func>>> =
            Vec::with_capacity(2);

        crate::arbitrary_loop(u, min, max, |u| {
            choices.clear();

            // NB: We only lift/lower scalar component functions.
            //
            // If we generated lifting and lowering of compound value types,
            // the probability of generating a corresponding Wasm module that
            // generates valid instances of the compound value types would
            // be vanishingly tiny (e.g. for `list<string>` we would have to
            // generate a core Wasm module that correctly produces a pointer and
            // length for a memory region that itself is a series of pointers
            // and lengths of valid strings, as well as `canonical_abi_realloc`
            // and `canonical_abi_free` functions that do the right thing).
            //
            // This is a pretty serious limitation of `wasm-smith`'s component
            // types support, but it is one we are intentionally
            // accepting. `wasm-smith` will focus on generating arbitrary
            // component sections, structures, and import/export topologies; not
            // component functions and core Wasm implementations of component
            // functions. In the future, we intend to build a new, distinct test
            // case generator specifically for exercising component functions
            // and the canonical ABI. This new generator won't emit arbitrary
            // component sections, structures, or import/export topologies, and
            // will instead leave that to `wasm-smith`.

            if !self.component().scalar_component_funcs.is_empty() {
                choices.push(|u, c| {
                    let func_index = *u.choose(&c.component().scalar_component_funcs)?;
                    Ok(Some(Func::CanonLower {
                        // Scalar component functions don't use any canonical options.
                        options: vec![],
                        func_index,
                    }))
                });
            }

            if !self.component().core_funcs.is_empty() {
                choices.push(|u, c| {
                    let core_func_index = u.int_in_range(
                        0..=u32::try_from(c.component().core_funcs.len() - 1).unwrap(),
                    )?;
                    let core_func_ty = c.core_function_type(core_func_index);
                    let comp_func_ty = inverse_scalar_canonical_abi_for(u, core_func_ty)?;

                    let func_ty = if let Some(indices) = c
                        .current_type_scope()
                        .func_type_to_indices
                        .get(&comp_func_ty)
                    {
                        // If we've already defined this component function type
                        // one or more times, then choose one of those
                        // definitions arbitrarily.
                        debug_assert!(!indices.is_empty());
                        *u.choose(indices)?
                    } else if c.current_type_scope().types.len() < c.config.max_types {
                        // If we haven't already defined this component function
                        // type, and we haven't defined the configured maximum
                        // amount of types yet, then just define this type.
                        let ty = Rc::new(Type::Func(Rc::new(comp_func_ty)));
                        c.push_type(ty)
                    } else {
                        // Otherwise, give up on lifting this function.
                        return Ok(None);
                    };

                    Ok(Some(Func::CanonLift {
                        func_ty,
                        // Scalar functions don't use any canonical options.
                        options: vec![],
                        core_func_index,
                    }))
                });
            }

            if choices.is_empty() {
                return Ok(false);
            }

            let f = u.choose(&choices)?;
            if let Some(func) = f(u, self)? {
                self.push_func(func);
            }

            Ok(true)
        })?;

        Ok(Step::StillBuilding)
    }

    fn arbitrary_core_module_section(&mut self, u: &mut Unstructured) -> Result<Step> {
        let module = crate::core::Module::new_internal(
            self.config.clone(),
            u,
            crate::core::DuplicateImportsBehavior::Disallowed,
        )?;
        self.push_section(Section::CoreModule(module));
        self.total_modules += 1;
        Ok(Step::StillBuilding)
    }

    fn arbitrary_component_section(&mut self, u: &mut Unstructured) -> Result<Step> {
        self.types.push(TypesScope::default());
        self.components.push(ComponentContext::empty());
        self.total_components += 1;
        Ok(Step::StillBuilding)
    }

    fn arbitrary_instance_section(&mut self, u: &mut Unstructured) -> Result<()> {
        todo!()
    }

    fn arbitrary_export_section(&mut self, u: &mut Unstructured) -> Result<()> {
        todo!()
    }

    fn arbitrary_start_section(&mut self, u: &mut Unstructured) -> Result<()> {
        todo!()
    }

    fn arbitrary_alias_section(&mut self, u: &mut Unstructured) -> Result<()> {
        todo!()
    }
}

fn canonical_abi_for(func_ty: &FuncType) -> Rc<crate::core::FuncType> {
    let to_core_ty = |ty| match ty {
        ComponentValType::Primitive(prim_ty) => match prim_ty {
            PrimitiveValType::Char
            | PrimitiveValType::Bool
            | PrimitiveValType::S8
            | PrimitiveValType::U8
            | PrimitiveValType::S16
            | PrimitiveValType::U16
            | PrimitiveValType::S32
            | PrimitiveValType::U32 => ValType::I32,
            PrimitiveValType::S64 | PrimitiveValType::U64 => ValType::I64,
            PrimitiveValType::Float32 => ValType::F32,
            PrimitiveValType::Float64 => ValType::F64,
            PrimitiveValType::String => {
                unimplemented!("non-scalar types are not supported yet")
            }
        },
        ComponentValType::Type(_) => unimplemented!("non-scalar types are not supported yet"),
    };

    Rc::new(crate::core::FuncType {
        params: func_ty
            .params
            .iter()
            .map(|(_, ty)| to_core_ty(*ty))
            .collect(),
        results: func_ty
            .results
            .iter()
            .map(|(_, ty)| to_core_ty(*ty))
            .collect(),
    })
}

fn inverse_scalar_canonical_abi_for(
    u: &mut Unstructured,
    core_func_ty: &crate::core::FuncType,
) -> Result<FuncType> {
    let from_core_ty = |u: &mut Unstructured, core_ty| match core_ty {
        ValType::I32 => u
            .choose(&[
                ComponentValType::Primitive(PrimitiveValType::Char),
                ComponentValType::Primitive(PrimitiveValType::Bool),
                ComponentValType::Primitive(PrimitiveValType::S8),
                ComponentValType::Primitive(PrimitiveValType::U8),
                ComponentValType::Primitive(PrimitiveValType::S16),
                ComponentValType::Primitive(PrimitiveValType::U16),
                ComponentValType::Primitive(PrimitiveValType::S32),
                ComponentValType::Primitive(PrimitiveValType::U32),
            ])
            .cloned(),
        ValType::I64 => u
            .choose(&[
                ComponentValType::Primitive(PrimitiveValType::S64),
                ComponentValType::Primitive(PrimitiveValType::U64),
            ])
            .cloned(),
        ValType::F32 => Ok(ComponentValType::Primitive(PrimitiveValType::Float32)),
        ValType::F64 => Ok(ComponentValType::Primitive(PrimitiveValType::Float64)),
        ValType::V128 | ValType::Ref(_) => {
            unreachable!("not used in canonical ABI")
        }
    };

    let mut names = HashSet::default();
    let mut params = vec![];

    for core_ty in &core_func_ty.params {
        params.push((
            crate::unique_kebab_string(100, &mut names, u)?,
            from_core_ty(u, *core_ty)?,
        ));
    }

    names.clear();

    let results = match core_func_ty.results.len() {
        0 => Vec::new(),
        1 => vec![(
            if u.arbitrary()? {
                Some(crate::unique_kebab_string(100, &mut names, u)?)
            } else {
                None
            },
            from_core_ty(u, core_func_ty.results[0])?,
        )],
        _ => unimplemented!("non-scalar types are not supported yet"),
    };

    Ok(FuncType { params, results })
}

#[derive(Debug)]
enum Section {
    Custom(CustomSection),
    CoreModule(crate::Module),
    CoreInstance(CoreInstanceSection),
    CoreType(CoreTypeSection),
    Component(Component),
    Instance(InstanceSection),
    Alias(AliasSection),
    Type(TypeSection),
    Canonical(CanonicalSection),
    Start(StartSection),
    Import(ImportSection),
    Export(ExportSection),
}

#[derive(Debug)]
struct CustomSection {
    name: String,
    data: Vec<u8>,
}

impl<'a> Arbitrary<'a> for CustomSection {
    fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
        let name = crate::limited_string(1_000, u)?;
        let data = u.arbitrary()?;
        Ok(CustomSection { name, data })
    }
}

#[derive(Debug)]
struct TypeSection {
    types: Vec<Rc<Type>>,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum CoreType {
    Func(Rc<crate::core::FuncType>),
    Module(Rc<ModuleType>),
}

#[derive(Clone, Debug, PartialEq, Eq, Hash, Default)]
struct ModuleType {
    defs: Vec<ModuleTypeDef>,
    has_memory: bool,
    has_canonical_abi_realloc: bool,
    has_canonical_abi_free: bool,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum ModuleTypeDef {
    TypeDef(crate::core::CompositeType),
    Import(crate::core::Import),
    OuterAlias {
        count: u32,
        i: u32,
        kind: CoreOuterAliasKind,
    },
    Export(String, crate::core::EntityType),
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum Type {
    Defined(DefinedType),
    Func(Rc<FuncType>),
    Component(Rc<ComponentType>),
    Instance(Rc<InstanceType>),
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum CoreInstanceExportAliasKind {
    Func,
    Table,
    Memory,
    Global,
    Tag,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum CoreOuterAliasKind {
    Type(Rc<crate::core::FuncType>),
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum Alias {
    InstanceExport {
        instance: u32,
        name: String,
        kind: InstanceExportAliasKind,
    },
    CoreInstanceExport {
        instance: u32,
        name: String,
        kind: CoreInstanceExportAliasKind,
    },
    Outer {
        count: u32,
        i: u32,
        kind: OuterAliasKind,
    },
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum InstanceExportAliasKind {
    Module,
    Component,
    Instance,
    Func,
    Value,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum OuterAliasKind {
    Module,
    Component,
    CoreType(Rc<CoreType>),
    Type(Rc<Type>),
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct ComponentType {
    defs: Vec<ComponentTypeDef>,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum ComponentTypeDef {
    CoreType(Rc<CoreType>),
    Type(Rc<Type>),
    Alias(Alias),
    Import(Import),
    Export {
        name: String,
        url: Option<String>,
        ty: ComponentTypeRef,
    },
}

impl From<InstanceTypeDecl> for ComponentTypeDef {
    fn from(def: InstanceTypeDecl) -> Self {
        match def {
            InstanceTypeDecl::CoreType(t) => Self::CoreType(t),
            InstanceTypeDecl::Type(t) => Self::Type(t),
            InstanceTypeDecl::Export { name, url, ty } => Self::Export { name, url, ty },
            InstanceTypeDecl::Alias(a) => Self::Alias(a),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct InstanceType {
    defs: Vec<InstanceTypeDecl>,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum InstanceTypeDecl {
    CoreType(Rc<CoreType>),
    Type(Rc<Type>),
    Alias(Alias),
    Export {
        name: String,
        url: Option<String>,
        ty: ComponentTypeRef,
    },
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct FuncType {
    params: Vec<(String, ComponentValType)>,
    results: Vec<(Option<String>, ComponentValType)>,
}

impl FuncType {
    fn unnamed_result_ty(&self) -> Option<ComponentValType> {
        if self.results.len() == 1 {
            let (name, ty) = &self.results[0];
            if name.is_none() {
                return Some(*ty);
            }
        }
        None
    }

    fn is_scalar(&self) -> bool {
        self.params.iter().all(|(_, ty)| is_scalar(ty))
            && self.results.len() == 1
            && is_scalar(&self.results[0].1)
    }
}

fn is_scalar(ty: &ComponentValType) -> bool {
    match ty {
        ComponentValType::Primitive(prim) => match prim {
            PrimitiveValType::Bool
            | PrimitiveValType::S8
            | PrimitiveValType::U8
            | PrimitiveValType::S16
            | PrimitiveValType::U16
            | PrimitiveValType::S32
            | PrimitiveValType::U32
            | PrimitiveValType::S64
            | PrimitiveValType::U64
            | PrimitiveValType::Float32
            | PrimitiveValType::Float64
            | PrimitiveValType::Char => true,
            PrimitiveValType::String => false,
        },
        ComponentValType::Type(_) => false,
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum DefinedType {
    Primitive(PrimitiveValType),
    Record(RecordType),
    Variant(VariantType),
    List(ListType),
    Tuple(TupleType),
    Flags(FlagsType),
    Enum(EnumType),
    Option(OptionType),
    Result(ResultType),
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct RecordType {
    fields: Vec<(String, ComponentValType)>,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct VariantType {
    cases: Vec<(String, Option<ComponentValType>, Option<u32>)>,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct ListType {
    elem_ty: ComponentValType,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct TupleType {
    fields: Vec<ComponentValType>,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct FlagsType {
    fields: Vec<String>,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct EnumType {
    variants: Vec<String>,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct OptionType {
    inner_ty: ComponentValType,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct ResultType {
    ok_ty: Option<ComponentValType>,
    err_ty: Option<ComponentValType>,
}

#[derive(Debug)]
struct ImportSection {
    imports: Vec<Import>,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct Import {
    name: String,
    url: Option<String>,
    ty: ComponentTypeRef,
}

#[derive(Debug)]
struct CanonicalSection {
    funcs: Vec<Func>,
}

#[derive(Debug)]
enum Func {
    CanonLift {
        func_ty: u32,
        options: Vec<CanonOpt>,
        core_func_index: u32,
    },
    CanonLower {
        options: Vec<CanonOpt>,
        func_index: u32,
    },
}

#[derive(Debug)]
enum CanonOpt {
    StringUtf8,
    StringUtf16,
    StringLatin1Utf16,
    Memory(u32),
    Realloc(u32),
    PostReturn(u32),
}

#[derive(Debug)]
struct InstanceSection {}

#[derive(Debug)]
struct ExportSection {}

#[derive(Debug)]
struct StartSection {}

#[derive(Debug)]
struct AliasSection {}

#[derive(Debug)]
struct CoreInstanceSection {}

#[derive(Debug)]
struct CoreTypeSection {
    types: Vec<Rc<CoreType>>,
}