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
#![deny(warnings)]
#![forbid(unsafe_code)]
#![warn(missing_docs)]
#![warn(clippy::missing_docs_in_private_items)]

//! `wasm_component_layer` is a runtime agnostic implementation of the [WebAssembly component model](https://github.com/WebAssembly/component-model).
//! It supports loading and linking WASM components, inspecting and generating component interface types at runtime, and more atop any WebAssembly backend. The implementation is based upon the [`wasmtime`](https://github.com/bytecodealliance/wasmtime), [`js-component-bindgen`](https://github.com/bytecodealliance/jco), and [`wit-parser`](https://github.com/bytecodealliance/wasm-tools/tree/main) crates.
//!
//! ## Usage
//!
//! To use `wasm_component_layer`, a runtime is required. The [`wasm_runtime_layer`](https://github.com/DouglasDwyer/wasm_runtime_layer) crate provides the common interface used for WebAssembly runtimes, so when using this crate it must also be added to the `Cargo.toml` file with the appropriate runtime selected. For instance, the examples in this repository use the [`wasmi`](https://github.com/paritytech/wasmi) runtime:
//!
//! ```toml
//! wasm_component_layer = "0.1.0"
//! wasm_runtime_layer = { version = "0.1.1", features = [ "backend_wasmi" ] }
//! ```
//!
//! The following is a small overview of `wasm_component_layer`'s API. The complete example may be found in the [examples folder](/examples). Consider a WASM component with the following WIT:
//!
//! ```wit
//! package test:guest
//!
//! interface foo {
//!     // Selects the item in position n within list x
//!     select-nth: func(x: list<string>, n: u32) -> string
//! }
//!
//! world guest {
//!     export foo
//! }
//! ```
//!
//! The component can be loaded into `wasm_component_layer` and invoked as follows:
//!
//! ```ignore
//! use wasm_component_layer::*;
//!
//! // The bytes of the component.
//! const WASM: &[u8] = include_bytes!("single_component/component.wasm");
//!
//! pub fn main() {
//!     // Create a new engine for instantiating a component.
//!     let engine = Engine::new(wasmi::Engine::default());
//!
//!     // Create a store for managing WASM data and any custom user-defined state.
//!     let mut store = Store::new(&engine, ());
//!     
//!     // Parse the component bytes and load its imports and exports.
//!     let component = Component::new(&engine, WASM).unwrap();
//!     // Create a linker that will be used to resolve the component's imports, if any.
//!     let linker = Linker::default();
//!     // Create an instance of the component using the linker.
//!     let instance = linker.instantiate(&mut store, &component).unwrap();
//!
//!     // Get the interface that the interface exports.
//!     let interface = instance.exports().instance(&"test:guest/foo".try_into().unwrap()).unwrap();
//!     // Get the function for selecting a list element.
//!     let select_nth = interface.func("select-nth").unwrap().typed::<(Vec<String>, u32), (String,)>().unwrap();
//!
//!     // Create an example list to test upon.
//!     let example = ["a", "b", "c"].iter().map(ToString::to_string).collect::<Vec<_>>();
//!     
//!     println!("Calling select-nth({example:?}, 1) == {}", select_nth.call(&mut store, (example.clone(), 1)).unwrap().0);
//!     // Prints 'Calling select-nth(["a", "b", "c"], 1) == b'
//! }
//! ```
//!
//! ## Features
//!
//! `wasm_component_layer` supports the following major features:
//!
//! - Parsing and instantiating WASM component binaries
//! - Runtime generation of component interface types
//! - Specialized list types for faster
//! - Structural equality of component interface types, as mandated by the spec
//! - Support for guest resources
//! - Support for strongly-typed host resources with destructors
//!
//! The following features have yet to be implemented:
//!
//! - A macro for generating host bindings
//! - More comprehensive tests
//! - Subtyping

/// Implements the Canonical ABI conventions for converting between guest and host types.
mod abi;

/// Provides the ability to create and call component model functions.
mod func;

/// Defines identifiers for component packages and interfaces.
mod identifier;

/// Defines a macro that will either pattern-match results or throw an error.
mod require_matches;

/// Defines all types related to the component model.
mod types;

/// Provides the ability to instantiate component model types.
mod values;

use std::any::*;
use std::sync::atomic::*;
use std::sync::*;

use anyhow::*;
use fxhash::*;
use id_arena::*;

use slab::*;
pub use wasm_runtime_layer::Engine;
use wasm_runtime_layer::*;
use wasmtime_environ::component::*;
use wit_component::*;
use wit_parser::*;

pub use crate::func::*;
pub use crate::identifier::*;
use crate::require_matches::*;
pub use crate::types::*;
pub use crate::values::*;

/// A parsed and validated WebAssembly component, which may be used to instantiate [`Instance`]s.
#[derive(Clone, Debug)]
pub struct Component(Arc<ComponentInner>);

impl Component {
    /// Creates a new component with the given engine and binary data.
    pub fn new<E: backend::WasmEngine>(engine: &Engine<E>, bytes: &[u8]) -> Result<Self> {
        let (inner, types) = Self::generate_component(engine, bytes)?;
        Ok(Self(Arc::new(Self::generate_resources(
            Self::load_exports(Self::extract_initializers(inner, &types)?, &types)?,
        )?)))
    }

    /// The types and interfaces exported by this component.
    pub fn exports(&self) -> &ComponentTypes {
        &self.0.export_types
    }

    /// The types and interfaces imported by this component. To instantiate
    /// the component, all of these imports must be satisfied by the [`Linker`].
    pub fn imports(&self) -> &ComponentTypes {
        &self.0.import_types
    }

    /// The root package of this component.
    pub fn package(&self) -> &PackageIdentifier {
        &self.0.package
    }

    /// Parses the given bytes into a component, and creates an uninitialized component backing.
    fn generate_component<E: backend::WasmEngine>(
        engine: &Engine<E>,
        bytes: &[u8],
    ) -> Result<(ComponentInner, wasmtime_environ::component::ComponentTypes)> {
        /// A counter that uniquely identifies components.
        static ID_COUNTER: AtomicU64 = AtomicU64::new(0);

        let decoded = wit_component::decode(bytes)
            .context("Could not decode component information from bytes.")?;

        let (resolve, world_id) = match decoded {
            DecodedWasm::WitPackage(..) => bail!("Cannot instantiate WIT package as module."),
            DecodedWasm::Component(resolve, id) => (resolve, id),
        };

        let adapter_vec = wasmtime_environ::ScopeVec::new();
        let (translation, module_data, component_types) =
            Self::translate_modules(bytes, &adapter_vec)?;

        let export_mapping = Self::generate_export_mapping(&module_data);
        let mut modules =
            FxHashMap::with_capacity_and_hasher(module_data.len(), Default::default());

        for (id, module) in module_data {
            modules.insert(
                id,
                ModuleTranslation {
                    module: Module::new(engine, std::io::Cursor::new(module.wasm))?,
                    translation: module.module,
                },
            );
        }

        let mut size_align = SizeAlign::default();
        size_align.fill(&resolve);

        let package = (&resolve.packages[resolve.worlds[world_id]
            .package
            .context("No package associated with world.")?]
        .name)
            .into();

        let package_identifiers = Self::generate_package_identifiers(&resolve)?;
        let interface_identifiers =
            Self::generate_interface_identifiers(&resolve, &package_identifiers)?;

        Ok((
            ComponentInner {
                export_mapping,
                export_names: FxHashMap::default(),
                import_types: ComponentTypes::new(),
                export_types: ComponentTypes::new(),
                export_info: ExportTypes::default(),
                extracted_memories: FxHashMap::default(),
                extracted_reallocs: FxHashMap::default(),
                extracted_post_returns: FxHashMap::default(),
                id: ID_COUNTER.fetch_add(1, Ordering::AcqRel),
                generated_trampolines: FxHashMap::default(),
                instance_modules: wasmtime_environ::PrimaryMap::default(),
                interface_identifiers,
                modules,
                resource_map: vec![
                    TypeResourceTableIndex::from_u32(u32::MAX - 1);
                    resolve.types.len()
                ],
                resolve,
                size_align,
                translation,
                world_id,
                package,
            },
            component_types,
        ))
    }

    /// Creates a mapping from module index to entities, used to resolve component exports at link-time.
    fn generate_export_mapping(
        module_data: &wasmtime_environ::PrimaryMap<
            StaticModuleIndex,
            wasmtime_environ::ModuleTranslation,
        >,
    ) -> FxHashMap<StaticModuleIndex, FxHashMap<wasmtime_environ::EntityIndex, String>> {
        let mut export_mapping =
            FxHashMap::with_capacity_and_hasher(module_data.len(), Default::default());

        for (idx, module) in module_data {
            let entry: &mut FxHashMap<wasmtime_environ::EntityIndex, String> =
                export_mapping.entry(idx).or_default();
            for (name, index) in module.module.exports.clone() {
                entry.insert(index, name);
            }
        }

        export_mapping
    }

    /// Fills in the abstract resource types for the given component.
    fn generate_resources(mut inner: ComponentInner) -> Result<ComponentInner> {
        for (_key, item) in &inner.resolve.worlds[inner.world_id].imports {
            match item {
                WorldItem::Type(x) => {
                    if inner.resolve.types[*x].kind == TypeDefKind::Resource {
                        if let Some(name) = &inner.resolve.types[*x].name {
                            ensure!(
                                inner
                                    .import_types
                                    .root
                                    .resources
                                    .insert(
                                        name.as_str().into(),
                                        ResourceType::from_resolve(*x, &inner, None)?
                                    )
                                    .is_none(),
                                "Duplicate resource import."
                            );
                        }
                    }
                }
                WorldItem::Interface(x) => {
                    for (name, ty) in &inner.resolve.interfaces[*x].types {
                        if inner.resolve.types[*ty].kind == TypeDefKind::Resource {
                            let ty = ResourceType::from_resolve(*ty, &inner, None)?;
                            let entry = inner
                                .import_types
                                .instances
                                .entry(inner.interface_identifiers[x.index()].clone())
                                .or_insert_with(ComponentTypesInstance::new);
                            ensure!(
                                entry.resources.insert(name.as_str().into(), ty).is_none(),
                                "Duplicate resource import."
                            );
                        }
                    }
                }
                _ => {}
            }
        }

        for (_key, item) in &inner.resolve.worlds[inner.world_id].exports {
            match item {
                WorldItem::Type(x) => {
                    if inner.resolve.types[*x].kind == TypeDefKind::Resource {
                        if let Some(name) = &inner.resolve.types[*x].name {
                            ensure!(
                                inner
                                    .export_types
                                    .root
                                    .resources
                                    .insert(
                                        name.as_str().into(),
                                        ResourceType::from_resolve(*x, &inner, None)?
                                    )
                                    .is_none(),
                                "Duplicate resource export."
                            );
                        }
                    }
                }
                WorldItem::Interface(x) => {
                    for (name, ty) in &inner.resolve.interfaces[*x].types {
                        if inner.resolve.types[*ty].kind == TypeDefKind::Resource {
                            let ty = ResourceType::from_resolve(*ty, &inner, None)?;
                            let entry = inner
                                .export_types
                                .instances
                                .entry(inner.interface_identifiers[x.index()].clone())
                                .or_insert_with(ComponentTypesInstance::new);
                            ensure!(
                                entry.resources.insert(name.as_str().into(), ty).is_none(),
                                "Duplicate resource export."
                            );
                        }
                    }
                }
                _ => {}
            }
        }

        Ok(inner)
    }

    /// Parses all package identifiers.
    fn generate_package_identifiers(resolve: &Resolve) -> Result<Vec<PackageIdentifier>> {
        let mut res = Vec::with_capacity(resolve.packages.len());

        for (_, pkg) in &resolve.packages {
            res.push(PackageIdentifier::try_from(&pkg.name)?);
        }

        Ok(res)
    }

    /// Generates a mapping from interface ID to parsed interface identifier.
    fn generate_interface_identifiers(
        resolve: &Resolve,
        packages: &[PackageIdentifier],
    ) -> Result<Vec<InterfaceIdentifier>> {
        let mut res = Vec::with_capacity(resolve.interfaces.len());

        for (_, iface) in &resolve.interfaces {
            let pkg = iface
                .package
                .context("Interface did not have associated package.")?;
            res.push(InterfaceIdentifier::new(
                packages[pkg.index()].clone(),
                iface
                    .name
                    .as_deref()
                    .context("Exported interface did not have valid name.")?,
            ));
        }

        Ok(res)
    }

    /// Fills in all initialization data for the component.
    fn extract_initializers(
        mut inner: ComponentInner,
        types: &wasmtime_environ::component::ComponentTypes,
    ) -> Result<ComponentInner> {
        let lowering_options = Self::get_lowering_options_and_extract_trampolines(
            &inner.translation.trampolines,
            &mut inner.generated_trampolines,
        )?;
        let mut imports = FxHashMap::default();
        for (key, _) in &inner.resolve.worlds[inner.world_id].imports {
            let name = inner.resolve.name_world_key(key);
            imports.insert(name, key.clone());
        }

        let _root_name = Arc::<str>::from("$root");

        let mut destructors = FxHashMap::default();

        for initializer in &inner.translation.component.initializers {
            match initializer {
                GlobalInitializer::InstantiateModule(InstantiateModule::Static(idx, _def)) => {
                    inner.instance_modules.push(*idx);
                }
                GlobalInitializer::ExtractMemory(ExtractMemory { index, export }) => {
                    ensure!(
                        inner
                            .extracted_memories
                            .insert(*index, export.clone())
                            .is_none(),
                        "Extracted the same memory more than once."
                    );
                }
                GlobalInitializer::ExtractRealloc(ExtractRealloc { index, def }) => {
                    if let CoreDef::Export(export) = def {
                        ensure!(
                            inner
                                .extracted_reallocs
                                .insert(*index, export.clone())
                                .is_none(),
                            "Extracted the same memory more than once."
                        );
                    } else {
                        bail!("Unexpected post return definition type.");
                    }
                }
                GlobalInitializer::ExtractPostReturn(ExtractPostReturn { index, def }) => {
                    if let CoreDef::Export(export) = def {
                        ensure!(
                            inner
                                .extracted_post_returns
                                .insert(*index, export.clone())
                                .is_none(),
                            "Extracted the same memory more than once."
                        );
                    } else {
                        bail!("Unexpected post return definition type.");
                    }
                }
                GlobalInitializer::LowerImport { index, import } => {
                    let (idx, lowering_opts, index_ty) = lowering_options[*index];
                    let (import_index, path) = &inner.translation.component.imports[*import];
                    let (import_name, _) = &inner.translation.component.import_types[*import_index];
                    let world_key = &imports[import_name];

                    let imp = match &inner.resolve.worlds[inner.world_id].imports[world_key] {
                        WorldItem::Function(func) => {
                            assert_eq!(path.len(), 0);
                            ComponentImport {
                                instance: None,
                                name: import_name.as_str().into(),
                                func: func.clone(),
                                options: lowering_opts.clone(),
                            }
                        }
                        WorldItem::Interface(i) => {
                            assert_eq!(path.len(), 1);
                            let iface = &inner.resolve.interfaces[*i];
                            let func = &iface.functions[&path[0]];

                            ComponentImport {
                                instance: Some(inner.interface_identifiers[i.index()].clone()),
                                name: path[0].as_str().into(),
                                func: func.clone(),
                                options: lowering_opts.clone(),
                            }
                        }
                        WorldItem::Type(_) => unreachable!(),
                    };

                    let ty = crate::types::FuncType::from_component(&imp.func, &inner, None)?;
                    let inst = if let Some(inst) = &imp.instance {
                        inner
                            .import_types
                            .instances
                            .entry(inst.clone())
                            .or_insert_with(ComponentTypesInstance::new)
                    } else {
                        &mut inner.import_types.root
                    };

                    Self::update_resource_map(
                        &inner.resolve,
                        types,
                        &imp.func,
                        index_ty,
                        &mut inner.resource_map,
                    );

                    ensure!(
                        inst.functions.insert(imp.name.clone(), ty).is_none(),
                        "Attempted to insert duplicate import."
                    );

                    ensure!(
                        inner
                            .generated_trampolines
                            .insert(idx, GeneratedTrampoline::ImportedFunction(imp))
                            .is_none(),
                        "Attempted to insert duplicate import."
                    );
                }
                GlobalInitializer::Resource(x) => {
                    if let Some(destructor) = x.dtor.clone() {
                        ensure!(
                            destructors.insert(x.index, destructor).is_none(),
                            "Attempted to define duplicate resource."
                        );
                    }
                }
                _ => bail!("Not yet implemented {initializer:?}."),
            }
        }

        for trampoline in inner.generated_trampolines.values_mut() {
            if let GeneratedTrampoline::ResourceDrop(x, destructor) = trampoline {
                let resource = &types[*x];
                if let Some(resource_idx) = inner
                    .translation
                    .component
                    .defined_resource_index(resource.ty)
                {
                    *destructor = destructors.remove(&resource_idx);
                }
            }
        }

        Ok(inner)
    }

    /// Creates a mapping from lowered functions to trampoline data,
    /// and records any auxiliary trampolines in the map.
    fn get_lowering_options_and_extract_trampolines<'a>(
        trampolines: &'a wasmtime_environ::PrimaryMap<TrampolineIndex, Trampoline>,
        output_trampolines: &mut FxHashMap<TrampolineIndex, GeneratedTrampoline>,
    ) -> Result<
        wasmtime_environ::PrimaryMap<
            LoweredIndex,
            (TrampolineIndex, &'a CanonicalOptions, TypeFuncIndex),
        >,
    > {
        let mut lowers = wasmtime_environ::PrimaryMap::default();
        for (idx, trampoline) in trampolines {
            match trampoline {
                Trampoline::LowerImport {
                    index,
                    lower_ty,
                    options,
                } => assert!(
                    lowers.push((idx, options, *lower_ty)) == *index,
                    "Indices did not match."
                ),
                Trampoline::ResourceNew(x) => {
                    output_trampolines.insert(idx, GeneratedTrampoline::ResourceNew(*x));
                }
                Trampoline::ResourceRep(x) => {
                    output_trampolines.insert(idx, GeneratedTrampoline::ResourceRep(*x));
                }
                Trampoline::ResourceDrop(x) => {
                    output_trampolines.insert(idx, GeneratedTrampoline::ResourceDrop(*x, None));
                }
                _ => bail!("Trampoline not implemented."),
            }
        }
        Ok(lowers)
    }

    /// Translates the given bytes into component data and a set of core modules.
    fn translate_modules<'a>(
        bytes: &'a [u8],
        scope: &'a wasmtime_environ::ScopeVec<u8>,
    ) -> Result<(
        ComponentTranslation,
        wasmtime_environ::PrimaryMap<StaticModuleIndex, wasmtime_environ::ModuleTranslation<'a>>,
        wasmtime_environ::component::ComponentTypes,
    )> {
        let tunables = wasmtime_environ::Tunables::default();
        let mut types = ComponentTypesBuilder::default();
        let mut validator = Self::create_component_validator();

        let (translation, modules) = Translator::new(&tunables, &mut validator, &mut types, scope)
            .translate(bytes)
            .context("Could not translate input component to core WASM.")?;

        Ok((translation, modules, types.finish()))
    }

    /// Fills in all of the exports for a component.
    fn load_exports(
        mut inner: ComponentInner,
        types: &wasmtime_environ::component::ComponentTypes,
    ) -> Result<ComponentInner> {
        Self::export_names(&mut inner);

        for (export_name, export) in &inner.translation.component.exports {
            let world_key = &inner.export_names[export_name];
            let item = &inner.resolve.worlds[inner.world_id].exports[world_key];
            match export {
                wasmtime_environ::component::Export::LiftedFunction { ty, func, options } => {
                    let f = match item {
                        WorldItem::Function(f) => f,
                        WorldItem::Interface(_) | WorldItem::Type(_) => unreachable!(),
                    };

                    Self::update_resource_map(
                        &inner.resolve,
                        types,
                        f,
                        *ty,
                        &mut inner.resource_map,
                    );

                    let export_name = Arc::<str>::from(export_name.as_str());
                    let ty = crate::types::FuncType::from_component(f, &inner, None)?;

                    ensure!(
                        inner
                            .export_types
                            .root
                            .functions
                            .insert(export_name.clone(), ty.clone())
                            .is_none(),
                        "Duplicate function definition."
                    );

                    ensure!(
                        inner
                            .export_info
                            .root
                            .functions
                            .insert(
                                export_name,
                                ComponentExport {
                                    options: options.clone(),
                                    def: match func {
                                        CoreDef::Export(x) => x.clone(),
                                        _ => unreachable!(),
                                    },
                                    func: f.clone(),
                                    ty
                                }
                            )
                            .is_none(),
                        "Duplicate function definition."
                    );
                }
                wasmtime_environ::component::Export::Instance(iface) => {
                    let id = match item {
                        WorldItem::Interface(id) => *id,
                        WorldItem::Function(_) | WorldItem::Type(_) => unreachable!(),
                    };
                    for (func_name, export) in iface {
                        let (func, options, ty) = match export {
                            wasmtime_environ::component::Export::LiftedFunction {
                                func,
                                options,
                                ty,
                            } => (func, options, ty),
                            wasmtime_environ::component::Export::Type(_) => continue, // ignored
                            _ => unreachable!(),
                        };

                        let f = &inner.resolve.interfaces[id].functions[func_name];

                        Self::update_resource_map(
                            &inner.resolve,
                            types,
                            f,
                            *ty,
                            &mut inner.resource_map,
                        );
                        let exp = ComponentExport {
                            options: options.clone(),
                            def: match func {
                                CoreDef::Export(x) => x.clone(),
                                _ => unreachable!(),
                            },
                            func: f.clone(),
                            ty: crate::types::FuncType::from_component(f, &inner, None)?,
                        };
                        let func_name = Arc::<str>::from(func_name.as_str());
                        ensure!(
                            inner
                                .export_types
                                .instances
                                .entry(inner.interface_identifiers[id.index()].clone())
                                .or_insert_with(ComponentTypesInstance::new)
                                .functions
                                .insert(func_name.clone(), exp.ty.clone())
                                .is_none(),
                            "Duplicate function definition."
                        );
                        ensure!(
                            inner
                                .export_info
                                .instances
                                .entry(inner.interface_identifiers[id.index()].clone())
                                .or_default()
                                .functions
                                .insert(func_name, exp)
                                .is_none(),
                            "Duplicate function definition."
                        );
                    }
                }

                // ignore type exports for now
                wasmtime_environ::component::Export::Type(_) => {}

                // This can't be tested at this time so leave it unimplemented
                wasmtime_environ::component::Export::ModuleStatic(_) => {
                    bail!("Not yet implemented.")
                }
                wasmtime_environ::component::Export::ModuleImport(_) => {
                    bail!("Not yet implemented.")
                }
            }
        }

        Ok(inner)
    }

    /// Fills in the mapping of export names to the exports' respective worlds.
    fn export_names(inner: &mut ComponentInner) {
        let to_iter = &inner.resolve.worlds[inner.world_id].exports;
        let mut exports = FxHashMap::with_capacity_and_hasher(to_iter.len(), Default::default());
        for (key, _) in to_iter {
            let name = inner.resolve.name_world_key(key);
            exports.insert(name, key.clone());
        }
        inner.export_names = exports;
    }

    /// Updates the mapping from type IDs to table indices based upon the resources
    /// referenced by the provided function.
    fn update_resource_map(
        resolve: &Resolve,
        types: &wasmtime_environ::component::ComponentTypes,
        func: &Function,
        ty_func_idx: TypeFuncIndex,
        map: &mut Vec<TypeResourceTableIndex>,
    ) {
        let params_ty = &types[types[ty_func_idx].params];
        for ((_, ty), iface_ty) in func.params.iter().zip(params_ty.types.iter()) {
            Self::connect_resources(resolve, types, ty, iface_ty, map);
        }
        let results_ty = &types[types[ty_func_idx].results];
        for (ty, iface_ty) in func.results.iter_types().zip(results_ty.types.iter()) {
            Self::connect_resources(resolve, types, ty, iface_ty, map);
        }
    }

    /// Inspects the given type (and any referenced subtypes) for resources,
    /// and records the table indices of those resources in the map.
    fn connect_resources(
        resolve: &Resolve,
        types: &wasmtime_environ::component::ComponentTypes,
        ty: &Type,
        iface_ty: &InterfaceType,
        map: &mut Vec<TypeResourceTableIndex>,
    ) {
        let Type::Id(id) = ty else { return };
        match (&resolve.types[*id].kind, iface_ty) {
            (TypeDefKind::Flags(_), InterfaceType::Flags(_))
            | (TypeDefKind::Enum(_), InterfaceType::Enum(_)) => {}
            (TypeDefKind::Record(t1), InterfaceType::Record(t2)) => {
                let t2 = &types[*t2];
                for (f1, f2) in t1.fields.iter().zip(t2.fields.iter()) {
                    Self::connect_resources(resolve, types, &f1.ty, &f2.ty, map);
                }
            }
            (
                TypeDefKind::Handle(Handle::Own(t1) | Handle::Borrow(t1)),
                InterfaceType::Own(t2) | InterfaceType::Borrow(t2),
            ) => {
                map[t1.index()] = *t2;
            }
            (TypeDefKind::Tuple(t1), InterfaceType::Tuple(t2)) => {
                let t2 = &types[*t2];
                for (f1, f2) in t1.types.iter().zip(t2.types.iter()) {
                    Self::connect_resources(resolve, types, f1, f2, map);
                }
            }
            (TypeDefKind::Variant(t1), InterfaceType::Variant(t2)) => {
                let t2 = &types[*t2];
                for (f1, f2) in t1.cases.iter().zip(t2.cases.iter()) {
                    if let Some(t1) = &f1.ty {
                        Self::connect_resources(resolve, types, t1, f2.ty.as_ref().unwrap(), map);
                    }
                }
            }
            (TypeDefKind::Option(t1), InterfaceType::Option(t2)) => {
                let t2 = &types[*t2];
                Self::connect_resources(resolve, types, t1, &t2.ty, map);
            }
            (TypeDefKind::Result(t1), InterfaceType::Result(t2)) => {
                let t2 = &types[*t2];
                if let Some(t1) = &t1.ok {
                    Self::connect_resources(resolve, types, t1, &t2.ok.unwrap(), map);
                }
                if let Some(t1) = &t1.err {
                    Self::connect_resources(resolve, types, t1, &t2.err.unwrap(), map);
                }
            }
            (TypeDefKind::Union(t1), InterfaceType::Union(t2)) => {
                let t2 = &types[*t2];
                for (f1, f2) in t1.cases.iter().zip(t2.types.iter()) {
                    Self::connect_resources(resolve, types, &f1.ty, f2, map);
                }
            }
            (TypeDefKind::List(t1), InterfaceType::List(t2)) => {
                let t2 = &types[*t2];
                Self::connect_resources(resolve, types, t1, &t2.element, map);
            }
            (TypeDefKind::Type(ty), _) => {
                Self::connect_resources(resolve, types, ty, iface_ty, map);
            }
            (_, _) => unreachable!(),
        }
    }

    /// Creates a validator with the appropriate settings for component model resolution.
    fn create_component_validator() -> wasmtime_environ::wasmparser::Validator {
        wasmtime_environ::wasmparser::Validator::new_with_features(
            wasmtime_environ::wasmparser::WasmFeatures {
                relaxed_simd: true,
                threads: true,
                multi_memory: true,
                exceptions: true,
                memory64: true,
                extended_const: true,
                component_model: true,
                function_references: true,
                memory_control: true,
                gc: true,
                component_model_values: true,
                mutable_global: true,
                saturating_float_to_int: true,
                sign_extension: true,
                bulk_memory: true,
                multi_value: true,
                reference_types: true,
                tail_call: true,
                simd: true,
                floats: true,
            },
        )
    }
}

/// Holds the inner, immutable state of an instantiated component.
struct ComponentInner {
    /// Maps from module indices to export indices for linking.
    pub export_mapping:
        FxHashMap<StaticModuleIndex, FxHashMap<wasmtime_environ::EntityIndex, String>>,
    /// Maps between export names and world keys.
    pub export_names: FxHashMap<String, WorldKey>,
    /// The exports of the component.
    pub export_types: ComponentTypes,
    /// Holds internal information for linking exports.
    pub export_info: ExportTypes,
    /// The memories that this component instantiates and references.
    pub extracted_memories: FxHashMap<RuntimeMemoryIndex, CoreExport<MemoryIndex>>,
    /// The reallocation functions that this component instantiates and references.
    pub extracted_reallocs:
        FxHashMap<RuntimeReallocIndex, CoreExport<wasmtime_environ::EntityIndex>>,
    /// The post-return functions that this component instantiates and references.
    pub extracted_post_returns:
        FxHashMap<RuntimePostReturnIndex, CoreExport<wasmtime_environ::EntityIndex>>,
    /// A mapping from type indices to resource table indices.
    pub resource_map: Vec<TypeResourceTableIndex>,
    /// The set of trampolines required to use this resource.
    pub generated_trampolines: FxHashMap<TrampolineIndex, GeneratedTrampoline>,
    /// The component's globally-unique ID.
    pub id: u64,
    /// The imports of the component.
    pub import_types: ComponentTypes,
    /// A mapping from runtime module indices to static indices.
    pub instance_modules: wasmtime_environ::PrimaryMap<RuntimeInstanceIndex, StaticModuleIndex>,
    /// A mapping from interface ID to parsed identifier.
    pub interface_identifiers: Vec<InterfaceIdentifier>,
    /// The translated modules of this component.
    pub modules: FxHashMap<StaticModuleIndex, ModuleTranslation>,
    /// The resolved WIT of the component.
    pub resolve: Resolve,
    /// The size and alignment of component types.
    pub size_align: SizeAlign,
    /// The translated component data.
    pub translation: ComponentTranslation,
    /// The ID of the primary exported world.
    pub world_id: Id<World>,
    /// The package identifier for the component.
    pub package: PackageIdentifier,
}

impl std::fmt::Debug for ComponentInner {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ComponentInner").finish()
    }
}

/// A translated module.
struct ModuleTranslation {
    /// The instantiated module that was translated.
    pub module: Module,
    /// The translation data for the module.
    pub translation: wasmtime_environ::Module,
}

/// Details the set of types and functions exported by a component.
#[derive(Debug, Default)]
struct ExportTypes {
    /// The root instance for component exports.
    root: ExportTypesInstance,
    /// The interfaces exported by the component.
    instances: FxHashMap<InterfaceIdentifier, ExportTypesInstance>,
}

/// Represents an interface that has been exported by a component.
#[derive(Debug, Default)]
struct ExportTypesInstance {
    /// The functions in the interface.
    functions: FxHashMap<Arc<str>, ComponentExport>,
}

/// Details a set of types within a component.
#[derive(Debug)]
pub struct ComponentTypes {
    /// The package root of the component.
    root: ComponentTypesInstance,
    /// All instances owned by the component.
    instances: FxHashMap<InterfaceIdentifier, ComponentTypesInstance>,
}

impl ComponentTypes {
    /// Creates a new, initially empty component type set.
    pub(crate) fn new() -> Self {
        Self {
            root: ComponentTypesInstance::new(),
            instances: FxHashMap::default(),
        }
    }

    /// Gets the root instance.
    pub fn root(&self) -> &ComponentTypesInstance {
        &self.root
    }

    /// Gets the instance with the specified name, if any.
    pub fn instance(&self, name: &InterfaceIdentifier) -> Option<&ComponentTypesInstance> {
        self.instances.get(name)
    }

    /// Gets an iterator over all instances by identifier.
    #[allow(clippy::needless_lifetimes)]
    pub fn instances<'a>(
        &'a self,
    ) -> impl Iterator<Item = (&'a InterfaceIdentifier, &'a ComponentTypesInstance)> {
        self.instances.iter()
    }
}

/// Represents a specific interface from a component.
#[derive(Debug)]
pub struct ComponentTypesInstance {
    /// The functions of the interface.
    functions: FxHashMap<Arc<str>, crate::types::FuncType>,
    /// The resources of the interface.
    resources: FxHashMap<Arc<str>, ResourceType>,
}

impl ComponentTypesInstance {
    /// Creates a new, empty instance.
    pub(crate) fn new() -> Self {
        Self {
            functions: FxHashMap::default(),
            resources: FxHashMap::default(),
        }
    }

    /// Gets the associated function by name, if any.
    pub fn func(&self, name: impl AsRef<str>) -> Option<crate::types::FuncType> {
        self.functions.get(name.as_ref()).cloned()
    }

    /// Iterates over all associated functions by name.
    pub fn funcs(&self) -> impl Iterator<Item = (&'_ str, crate::types::FuncType)> {
        self.functions.iter().map(|(k, v)| (&**k, v.clone()))
    }

    /// Gets the associated abstract resource by name, if any.
    pub fn resource(&self, name: impl AsRef<str>) -> Option<ResourceType> {
        self.resources.get(name.as_ref()).cloned()
    }

    /// Iterates over all associated functions by name.
    pub fn resources(&self) -> impl Iterator<Item = (&'_ str, crate::types::ResourceType)> {
        self.resources.iter().map(|(k, v)| (&**k, v.clone()))
    }
}

/// Provides the ability to define imports for a component and create [`Instance`]s of it.
#[derive(Clone, Debug, Default)]
pub struct Linker {
    /// The root instance used for linking.
    root: LinkerInstance,
    /// The set of interfaces against which to link.
    instances: FxHashMap<InterfaceIdentifier, LinkerInstance>,
}

impl Linker {
    /// Immutably obtains the root interface for this linker.
    pub fn root(&self) -> &LinkerInstance {
        &self.root
    }

    /// Mutably obtains the root interface for this linker.
    pub fn root_mut(&mut self) -> &mut LinkerInstance {
        &mut self.root
    }

    /// Creates a new instance in the linker with the provided name. Returns an
    /// error if an instance with that name already exists.
    pub fn define_instance(&mut self, name: InterfaceIdentifier) -> Result<&mut LinkerInstance> {
        if self.instance(&name).is_none() {
            Ok(self.instances.entry(name).or_default())
        } else {
            bail!("Duplicate instance definition.");
        }
    }

    /// Immutably obtains the instance with the given name, if any.
    pub fn instance(&self, name: &InterfaceIdentifier) -> Option<&LinkerInstance> {
        self.instances.get(name)
    }

    /// Mutably obtains the instance with the given name, if any.
    pub fn instance_mut(&mut self, name: &InterfaceIdentifier) -> Option<&mut LinkerInstance> {
        self.instances.get_mut(name)
    }

    /// Instantiates a component for the provided store, filling in its imports with externals
    /// defined in this linker. All imports must be defined for instantiation to succeed.
    pub fn instantiate(&self, ctx: impl AsContextMut, component: &Component) -> Result<Instance> {
        Instance::new(ctx, component, self)
    }
}

/// Describes a concrete interface which components may import.
#[derive(Clone, Debug, Default)]
pub struct LinkerInstance {
    /// The functions in the interface.
    functions: FxHashMap<Arc<str>, crate::func::Func>,
    /// The resource types in the interface.
    resources: FxHashMap<Arc<str>, ResourceType>,
}

impl LinkerInstance {
    /// Defines a new function for this interface with the provided name.
    /// Fails if the function already exists.
    pub fn define_func(
        &mut self,
        name: impl Into<Arc<str>>,
        func: crate::func::Func,
    ) -> Result<()> {
        let n = Into::<Arc<str>>::into(name);
        if self.functions.contains_key(&n) {
            bail!("Duplicate function definition.");
        }

        self.functions.insert(n, func);
        Ok(())
    }

    /// Gets the function in this interface with the given name, if any.
    pub fn func(&self, name: impl AsRef<str>) -> Option<crate::func::Func> {
        self.functions.get(name.as_ref()).cloned()
    }

    /// Defines a new resource type for this interface with the provided name.
    /// Fails if the resource type already exists, or if the resource is abstract.
    pub fn define_resource(
        &mut self,
        name: impl Into<Arc<str>>,
        resource_ty: ResourceType,
    ) -> Result<()> {
        ensure!(
            resource_ty.is_instantiated(),
            "Cannot link with abstract resource type."
        );

        let n = Into::<Arc<str>>::into(name);
        if self.resources.contains_key(&n) {
            bail!("Duplicate resource definition.");
        }

        self.resources.insert(n, resource_ty);
        Ok(())
    }

    /// Gets the resource in this interface with the given name, if any.
    pub fn resource(&self, name: impl AsRef<str>) -> Option<ResourceType> {
        self.resources.get(name.as_ref()).cloned()
    }
}

/// An instantiated WebAssembly component.
#[derive(Clone, Debug)]
pub struct Instance(Arc<InstanceInner>);

impl Instance {
    /// Creates a new instance for the given component with the specified linker.
    pub(crate) fn new(
        mut ctx: impl AsContextMut,
        component: &Component,
        linker: &Linker,
    ) -> Result<Self> {
        /// A counter that uniquely identifies instances.
        static ID_COUNTER: AtomicU64 = AtomicU64::new(0);

        let mut instance_flags = wasmtime_environ::PrimaryMap::default();
        for _i in 0..component.0.instance_modules.len() {
            instance_flags.push(Global::new(
                ctx.as_context_mut().inner,
                wasm_runtime_layer::Value::I32(
                    wasmtime_environ::component::FLAG_MAY_LEAVE
                        | wasmtime_environ::component::FLAG_MAY_ENTER,
                ),
                true,
            ));
        }

        let id = ID_COUNTER.fetch_add(1, Ordering::AcqRel);
        let map = Self::create_resource_instantiation_map(id, component, linker)?;
        let types = Self::generate_types(component, &map)?;
        let resource_tables = Mutex::new(vec![
            HandleTable::default();
            component.0.translation.component.num_resource_tables
        ]);
        let instance = InstanceInner {
            component: component.clone(),
            exports: Exports::new(),
            id,
            instances: Default::default(),
            instance_flags,
            state_table: Arc::new(StateTable {
                dropped: AtomicBool::new(false),
                resource_tables,
            }),
            types,
            store_id: ctx.as_context().inner.data().id,
        };
        let initialized = Self::global_initialize(instance, &mut ctx, linker, &map)?;
        let exported = Self::load_exports(initialized, &ctx, &map)?;
        Ok(Self(Arc::new(exported)))
    }

    /// Gets the component associated with this instance.
    pub fn component(&self) -> &Component {
        &self.0.component
    }

    /// Gets the exports of this instance.
    pub fn exports(&self) -> &Exports {
        &self.0.exports
    }

    /// Drops the instance and all of its owned resources, removing its data from the given store.
    /// Returns the list of errors that occurred while dropping owned resources, but continues
    /// until all resources have been dropped.
    pub fn drop<T, E: backend::WasmEngine>(&self, ctx: &mut Store<T, E>) -> Result<Vec<Error>> {
        ensure!(self.0.store_id == ctx.inner.data().id, "Incorrect store.");
        self.0.state_table.dropped.store(true, Ordering::Release);

        let mut errors = Vec::new();

        let mut tables = self
            .0
            .state_table
            .resource_tables
            .try_lock()
            .expect("Could not lock resource tables.");
        for table in &mut *tables {
            if let Some(destructor) = table.destructor.as_ref() {
                for (_, val) in table.array.iter() {
                    if let Err(x) = destructor.call(
                        &mut ctx.inner,
                        &[wasm_runtime_layer::Value::I32(val.rep)],
                        &mut [],
                    ) {
                        errors.push(x);
                    }
                }
            }
        }

        Ok(errors)
    }

    /// Generates the concrete list of types for this instance, after replacing abstract resources with instantiated ones.
    fn generate_types(
        component: &Component,
        map: &FxHashMap<ResourceType, ResourceType>,
    ) -> Result<Arc<[crate::types::ValueType]>> {
        let mut types = Vec::with_capacity(component.0.resolve.types.len());
        for (id, val) in &component.0.resolve.types {
            assert!(
                types.len() == id.index(),
                "Type definition IDs were not equal."
            );
            if val.kind == TypeDefKind::Resource {
                types.push(crate::types::ValueType::Bool);
            } else {
                types.push(crate::types::ValueType::from_component_typedef(
                    id,
                    &component.0,
                    Some(map),
                )?);
            }
        }
        Ok(types.into())
    }

    /// Creates a mapping from component resources to instance resources,
    /// since resource types are unique per instantiation.
    fn create_resource_instantiation_map(
        instance_id: u64,
        component: &Component,
        linker: &Linker,
    ) -> Result<FxHashMap<ResourceType, ResourceType>> {
        let mut types = FxHashMap::default();

        for (name, resource) in component.imports().root().resources() {
            let instantiated = linker
                .root()
                .resource(name)
                .ok_or_else(|| Error::msg(format!("Could not find resource {name} in linker.")))?;
            types.insert(resource, instantiated);
        }

        for (id, interface) in component.imports().instances() {
            for (name, resource) in interface.resources() {
                let instantiated = linker
                    .instance(id)
                    .and_then(|x| x.resource(name))
                    .ok_or_else(|| {
                        Error::msg(format!(
                            "Could not find resource {name} from interface {id:?} in linker."
                        ))
                    })?;
                types.insert(resource, instantiated);
            }
        }

        for (_, resource) in component
            .exports()
            .instances()
            .flat_map(|(_, x)| x.resources())
            .chain(component.exports().root().resources())
        {
            let instantiated = resource.instantiate(instance_id)?;
            types.insert(resource, instantiated);
        }

        Ok(types)
    }

    /// Fills in the exports map for the instance.
    fn load_exports(
        mut inner: InstanceInner,
        ctx: impl AsContext,
        map: &FxHashMap<ResourceType, ResourceType>,
    ) -> Result<InstanceInner> {
        for (name, func) in &inner.component.0.export_info.root.functions {
            inner.exports.root.functions.insert(
                name.clone(),
                Self::export_function(&inner, &ctx, &func.def, &func.options, &func.func, map)?,
            );
        }
        for (name, res) in &inner.component.0.export_types.root.resources {
            inner
                .exports
                .root
                .resources
                .insert(name.clone(), res.instantiate(inner.id)?);
        }

        let mut generated_functions = Vec::new();
        for (inst_name, inst) in &inner.component.0.export_info.instances {
            for (name, func) in &inst.functions {
                let export =
                    Self::export_function(&inner, &ctx, &func.def, &func.options, &func.func, map)?;
                generated_functions.push((inst_name.clone(), name.clone(), export));
            }
        }

        for (inst_name, inst) in &inner.component.0.export_types.instances {
            for (name, res) in &inst.resources {
                inner
                    .exports
                    .instances
                    .entry(inst_name.clone())
                    .or_insert_with(ExportInstance::new)
                    .resources
                    .insert(name.clone(), res.instantiate(inner.id)?);
            }
        }

        for (inst_name, name, func) in generated_functions {
            let interface = inner
                .exports
                .instances
                .entry(inst_name)
                .or_insert_with(ExportInstance::new);
            interface.functions.insert(name, func);
        }

        Ok(inner)
    }

    /// Creates the options used to invoke an imported function.
    fn import_function(
        inner: &InstanceInner,
        ctx: impl AsContext,
        options: &CanonicalOptions,
        func: &Function,
    ) -> GuestInvokeOptions {
        let memory = options.memory.map(|idx| {
            Self::core_export(inner, &ctx, &inner.component.0.extracted_memories[&idx])
                .expect("Could not get runtime memory export.")
                .into_memory()
                .expect("Export was not of memory type.")
        });
        let realloc = options.realloc.map(|idx| {
            Self::core_export(inner, &ctx, &inner.component.0.extracted_reallocs[&idx])
                .expect("Could not get runtime realloc export.")
                .into_func()
                .expect("Export was not of func type.")
        });
        let post_return = options.post_return.map(|idx| {
            Self::core_export(inner, &ctx, &inner.component.0.extracted_post_returns[&idx])
                .expect("Could not get runtime post return export.")
                .into_func()
                .expect("Export was not of func type.")
        });

        GuestInvokeOptions {
            component: inner.component.0.clone(),
            encoding: options.string_encoding,
            function: func.clone(),
            memory,
            realloc,
            state_table: inner.state_table.clone(),
            post_return,
            types: inner.types.clone(),
            instance_id: inner.id,
            store_id: ctx.as_context().inner.data().id,
        }
    }

    /// Creates an exported function from the provided definitions.
    fn export_function(
        inner: &InstanceInner,
        ctx: impl AsContext,
        def: &CoreExport<wasmtime_environ::EntityIndex>,
        options: &CanonicalOptions,
        func: &Function,
        mapping: &FxHashMap<ResourceType, ResourceType>,
    ) -> Result<crate::func::Func> {
        let callee = Self::core_export(inner, &ctx, def)
            .expect("Could not get callee export.")
            .into_func()
            .expect("Export was not of func type.");
        let memory = options.memory.map(|idx| {
            Self::core_export(inner, &ctx, &inner.component.0.extracted_memories[&idx])
                .expect("Could not get runtime memory export.")
                .into_memory()
                .expect("Export was not of memory type.")
        });
        let realloc = options.realloc.map(|idx| {
            Self::core_export(inner, &ctx, &inner.component.0.extracted_reallocs[&idx])
                .expect("Could not get runtime realloc export.")
                .into_func()
                .expect("Export was not of func type.")
        });
        let post_return = options.post_return.map(|idx| {
            Self::core_export(inner, &ctx, &inner.component.0.extracted_post_returns[&idx])
                .expect("Could not get runtime post return export.")
                .into_func()
                .expect("Export was not of func type.")
        });

        Ok(crate::func::Func {
            store_id: ctx.as_context().inner.data().id,
            ty: crate::types::FuncType::from_component(func, &inner.component.0, Some(mapping))?,
            backing: FuncImpl::GuestFunc(Arc::new(GuestFunc {
                callee,
                component: inner.component.0.clone(),
                encoding: options.string_encoding,
                function: func.clone(),
                memory,
                realloc,
                state_table: inner.state_table.clone(),
                post_return,
                types: inner.types.clone(),
                instance_id: inner.id,
            })),
        })
    }

    /// Gets the core WASM import associated with the provided definition.
    fn core_import(
        inner: &InstanceInner,
        mut ctx: impl AsContextMut,
        def: &CoreDef,
        linker: &Linker,
        ty: ExternType,
        destructors: &mut Vec<TrampolineIndex>,
        resource_map: &FxHashMap<ResourceType, ResourceType>,
    ) -> Result<Extern> {
        match def {
            CoreDef::Export(x) => {
                Self::core_export(inner, ctx, x).context("Could not find exported function.")
            }
            CoreDef::Trampoline(x) => {
                let ty = if let ExternType::Func(x) = ty {
                    x
                } else {
                    bail!("Incorrect extern type.")
                };
                match inner
                    .component
                    .0
                    .generated_trampolines
                    .get(x)
                    .context("Could not find exported trampoline.")?
                {
                    GeneratedTrampoline::ImportedFunction(component_import) => {
                        let expected = crate::types::FuncType::from_component(
                            &component_import.func,
                            &inner.component.0,
                            Some(resource_map),
                        )?;
                        let func = Self::get_component_import(component_import, linker)?;
                        ensure!(
                            func.ty() == expected,
                            "Function import {} had type {:?}, but expected {expected:?}",
                            component_import.name,
                            func.ty()
                        );
                        let guest_options = Self::import_function(
                            inner,
                            &ctx,
                            &component_import.options,
                            &component_import.func,
                        );

                        Ok(Extern::Func(Func::new(
                            ctx.as_context_mut().inner,
                            ty,
                            move |ctx, args, results| {
                                let ctx = StoreContextMut { inner: ctx };
                                func.call_from_guest(ctx, &guest_options, args, results)
                            },
                        )))
                    }
                    GeneratedTrampoline::ResourceNew(x) => {
                        let x = x.as_u32();
                        let tables = inner.state_table.clone();
                        Ok(Extern::Func(Func::new(
                            ctx.as_context_mut().inner,
                            ty,
                            move |_ctx, args, results| {
                                let rep =
                                    require_matches!(args[0], wasm_runtime_layer::Value::I32(x), x);
                                let mut table_array = tables
                                    .resource_tables
                                    .try_lock()
                                    .expect("Could not get mutual reference to table.");
                                results[0] = wasm_runtime_layer::Value::I32(
                                    table_array[x as usize].add(HandleElement {
                                        rep,
                                        own: true,
                                        lend_count: 0,
                                    }),
                                );
                                Ok(())
                            },
                        )))
                    }
                    GeneratedTrampoline::ResourceRep(x) => {
                        let x = x.as_u32();
                        let tables = inner.state_table.clone();
                        Ok(Extern::Func(Func::new(
                            ctx.as_context_mut().inner,
                            ty,
                            move |_ctx, args, results| {
                                let idx =
                                    require_matches!(args[0], wasm_runtime_layer::Value::I32(x), x);
                                let table_array = tables
                                    .resource_tables
                                    .try_lock()
                                    .expect("Could not get mutual reference to table.");
                                results[0] = wasm_runtime_layer::Value::I32(
                                    table_array[x as usize].get(idx)?.rep,
                                );
                                Ok(())
                            },
                        )))
                    }
                    GeneratedTrampoline::ResourceDrop(y, _) => {
                        destructors.push(*x);
                        let x = y.as_u32();
                        let tables = inner.state_table.clone();
                        Ok(Extern::Func(Func::new(
                            ctx.as_context_mut().inner,
                            ty,
                            move |ctx, args, _results| {
                                let idx =
                                    require_matches!(args[0], wasm_runtime_layer::Value::I32(x), x);
                                let mut table_array = tables
                                    .resource_tables
                                    .try_lock()
                                    .expect("Could not get mutual reference to table.");
                                let current_table = &mut table_array[x as usize];

                                let elem_borrow = current_table.get(idx)?;

                                if elem_borrow.own {
                                    ensure!(
                                        elem_borrow.lend_count == 0,
                                        "Attempted to drop loaned resource."
                                    );
                                    let elem = current_table.remove(idx)?;
                                    if let Some(destructor) =
                                        table_array[x as usize].destructor().cloned()
                                    {
                                        drop(table_array);
                                        destructor.call(
                                            ctx,
                                            &[wasm_runtime_layer::Value::I32(elem.rep)],
                                            &mut [],
                                        )?;
                                    }
                                }
                                Ok(())
                            },
                        )))
                    }
                }
            }
            CoreDef::InstanceFlags(i) => Ok(Extern::Global(inner.instance_flags[*i].clone())),
        }
    }

    /// Gets the core WASM export associated with the provided definition.
    fn core_export<T: Copy + Into<wasmtime_environ::EntityIndex>>(
        inner: &InstanceInner,
        ctx: impl AsContext,
        export: &CoreExport<T>,
    ) -> Option<Extern> {
        let name = match &export.item {
            ExportItem::Index(idx) => {
                &inner.component.0.export_mapping
                    [&inner.component.0.instance_modules[export.instance]][&(*idx).into()]
            }
            ExportItem::Name(s) => s,
        };

        inner.instances[export.instance].get_export(&ctx.as_context().inner, name)
    }

    /// Handles all global initializers and instantiates the set of WASM modules for this component.
    fn global_initialize(
        mut inner: InstanceInner,
        mut ctx: impl AsContextMut,
        linker: &Linker,
        resource_map: &FxHashMap<ResourceType, ResourceType>,
    ) -> Result<InstanceInner> {
        let mut destructors = Vec::new();
        for initializer in &inner.component.0.translation.component.initializers {
            match initializer {
                GlobalInitializer::InstantiateModule(InstantiateModule::Static(idx, def)) => {
                    let module = &inner.component.0.modules[idx];
                    let imports = Self::generate_imports(
                        &inner,
                        &mut ctx,
                        linker,
                        module,
                        def,
                        &mut destructors,
                        resource_map,
                    )?;
                    let instance = wasm_runtime_layer::Instance::new(
                        &mut ctx.as_context_mut().inner,
                        &module.module,
                        &imports,
                    )?;
                    inner.instances.push(instance);
                }
                GlobalInitializer::ExtractMemory(_) => {}
                GlobalInitializer::ExtractRealloc(_) => {}
                GlobalInitializer::ExtractPostReturn(_) => {}
                GlobalInitializer::LowerImport { .. } => {}
                GlobalInitializer::Resource(_) => {}
                _ => bail!("Not yet implemented {initializer:?}."),
            }
        }

        Self::fill_destructors(inner, ctx, destructors, resource_map)
    }

    /// Generates the set of core WASM imports for this component.
    fn generate_imports(
        inner: &InstanceInner,
        mut store: impl AsContextMut,
        linker: &Linker,
        module: &ModuleTranslation,
        defs: &[CoreDef],
        destructors: &mut Vec<TrampolineIndex>,
        resource_map: &FxHashMap<ResourceType, ResourceType>,
    ) -> Result<Imports> {
        let mut import_ty_map = FxHashMap::default();

        let engine = store.as_context().engine().clone();
        for import in module.module.imports(&engine) {
            import_ty_map.insert((import.module, import.name), import.ty.clone());
        }

        let mut imports = Imports::default();

        for (host, name, def) in module
            .translation
            .imports()
            .zip(defs)
            .map(|((module, name, _), arg)| (module, name, arg))
        {
            let ty = import_ty_map
                .get(&(host, name))
                .context("Unrecognized import.")?
                .clone();
            imports.define(
                host,
                name,
                Self::core_import(
                    inner,
                    &mut store,
                    def,
                    linker,
                    ty,
                    destructors,
                    resource_map,
                )?,
            );
        }

        Ok(imports)
    }

    /// Gets an import from the linker for this component.
    fn get_component_import(
        import: &ComponentImport,
        linker: &Linker,
    ) -> Result<crate::func::Func> {
        let inst = if let Some(name) = &import.instance {
            linker
                .instance(name)
                .ok_or_else(|| Error::msg(format!("Could not find imported interface {name:?}")))?
        } else {
            linker.root()
        };

        inst.func(&import.name)
            .ok_or_else(|| Error::msg(format!("Could not find function import {}", import.name)))
    }

    /// Fills the resource tables with all resource destructors.
    fn fill_destructors(
        inner: InstanceInner,
        ctx: impl AsContext,
        destructors: Vec<TrampolineIndex>,
        resource_map: &FxHashMap<ResourceType, ResourceType>,
    ) -> Result<InstanceInner> {
        let mut tables = inner
            .state_table
            .resource_tables
            .try_lock()
            .expect("Could not get access to resource tables.");

        for index in destructors {
            let (x, def) = require_matches!(
                &inner.component.0.generated_trampolines[&index],
                GeneratedTrampoline::ResourceDrop(x, def),
                (x, def)
            );
            if let Some(def) = def {
                let export = require_matches!(def, CoreDef::Export(x), x);
                tables[x.as_u32() as usize].set_destructor(Some(require_matches!(
                    Self::core_export(&inner, &ctx, export),
                    Some(Extern::Func(x)),
                    x
                )));
            }
        }

        for (id, idx) in inner.component.0.resolve.types.iter().filter_map(|(i, _)| {
            let val = inner.component.0.resource_map[i.index()];
            (val.as_u32() < u32::MAX - 1).then_some((i, val))
        }) {
            let res = ResourceType::from_resolve(id, &inner.component.0, Some(resource_map))?;
            match res.host_destructor() {
                Some(Some(func)) => tables[idx.as_u32() as usize].set_destructor(Some(func)),
                Some(None) => tables[idx.as_u32() as usize]
                    .set_destructor(ctx.as_context().inner.data().drop_host_resource.clone()),
                _ => {}
            }
        }

        drop(tables);

        Ok(inner)
    }
}

/// Provides the exports for an instance.
#[derive(Debug)]
pub struct Exports {
    /// The root interface of this instance.
    root: ExportInstance,
    /// All of this instance's exported interfaces.
    instances: FxHashMap<InterfaceIdentifier, ExportInstance>,
}

impl Exports {
    /// Creates a new set of exports.
    pub(crate) fn new() -> Self {
        Self {
            root: ExportInstance::new(),
            instances: FxHashMap::default(),
        }
    }

    /// Gets the root instance.
    pub fn root(&self) -> &ExportInstance {
        &self.root
    }

    /// Gets the instance with the specified name, if any.
    pub fn instance(&self, name: &InterfaceIdentifier) -> Option<&ExportInstance> {
        self.instances.get(name)
    }

    /// Gets an iterator over all instances by identifier.
    #[allow(clippy::needless_lifetimes)]
    pub fn instances<'a>(
        &'a self,
    ) -> impl Iterator<Item = (&'a InterfaceIdentifier, &'a ExportInstance)> {
        self.instances.iter()
    }
}

/// Represents a specific interface from a instance.
#[derive(Debug)]
pub struct ExportInstance {
    /// The functions of the interface.
    functions: FxHashMap<Arc<str>, crate::func::Func>,
    /// The resources of the interface.
    resources: FxHashMap<Arc<str>, ResourceType>,
}

impl ExportInstance {
    /// Creates a new, empty instance.
    pub(crate) fn new() -> Self {
        Self {
            functions: FxHashMap::default(),
            resources: FxHashMap::default(),
        }
    }

    /// Gets the associated function by name, if any.
    pub fn func(&self, name: impl AsRef<str>) -> Option<crate::func::Func> {
        self.functions.get(name.as_ref()).cloned()
    }

    /// Iterates over all associated functions by name.
    pub fn funcs(&self) -> impl Iterator<Item = (&'_ str, crate::func::Func)> {
        self.functions.iter().map(|(k, v)| (&**k, v.clone()))
    }

    /// Gets the associated abstract resource by name, if any.
    pub fn resource(&self, name: impl AsRef<str>) -> Option<ResourceType> {
        self.resources.get(name.as_ref()).cloned()
    }

    /// Iterates over all associated functions by name.
    pub fn resources(&self) -> impl Iterator<Item = (&'_ str, ResourceType)> {
        self.resources.iter().map(|(k, v)| (&**k, v.clone()))
    }
}

/// Stores the internal state for an instance.
#[derive(Debug)]
struct InstanceInner {
    /// The component from which this instance was created.
    pub component: Component,
    /// The exports of this instance.
    pub exports: Exports,
    /// The unique ID of this instance.
    pub id: u64,
    /// The flags associated with this instance.
    pub instance_flags: wasmtime_environ::PrimaryMap<RuntimeComponentInstanceIndex, Global>,
    /// The underlying instantiated WASM modules for this instance.
    pub instances: wasmtime_environ::PrimaryMap<RuntimeInstanceIndex, wasm_runtime_layer::Instance>,
    /// Stores the instance-specific state.
    pub state_table: Arc<StateTable>,
    /// The list of types for this instance.
    pub types: Arc<[crate::types::ValueType]>,
    /// The store ID associated with this instance.
    pub store_id: u64,
}

/// Stores the instance-specific state for a component.
#[derive(Debug)]
struct StateTable {
    /// Whether this instance has been dropped.
    pub dropped: AtomicBool,
    /// The set of resource tables and destructors.
    pub resource_tables: Mutex<Vec<HandleTable>>,
}

/// Details an import for a component.
#[derive(Clone, Debug)]
struct ComponentImport {
    /// The interface from which this export originates.
    pub instance: Option<InterfaceIdentifier>,
    /// The name of the import.
    pub name: Arc<str>,
    /// The function associated with the import.
    pub func: Function,
    /// The canonical options with which the import will be called.
    pub options: CanonicalOptions,
}

/// Details an export from a component.
#[derive(Clone, Debug)]
struct ComponentExport {
    /// The canonical options with which the export will be called.
    pub options: CanonicalOptions,
    /// The function associated with the export.
    pub func: Function,
    /// The definition of the export.
    pub def: CoreExport<wasmtime_environ::EntityIndex>,
    /// The type of export.
    pub ty: crate::types::FuncType,
}

/// The store represents all global state that can be manipulated by
/// WebAssembly programs. It consists of the runtime representation
/// of all instances of functions, tables, memories, and globals that
/// have been allocated during the lifetime of the abstract machine.
///
/// The `Store` holds the engine (that is —amongst many things— used to compile
/// the Wasm bytes into a valid module artifact).
///
/// Spec: <https://webassembly.github.io/spec/core/exec/runtime.html#store>
pub struct Store<T, E: backend::WasmEngine> {
    /// The backing implementation.
    inner: wasm_runtime_layer::Store<StoreInner<T, E>, E>,
}

impl<T, E: backend::WasmEngine> Store<T, E> {
    /// Creates a new [`Store`] with a specific [`Engine`].
    pub fn new(engine: &Engine<E>, data: T) -> Self {
        /// A counter that uniquely identifies stores.
        static ID_COUNTER: AtomicU64 = AtomicU64::new(0);

        let mut inner = wasm_runtime_layer::Store::new(
            engine,
            StoreInner {
                id: ID_COUNTER.fetch_add(1, Ordering::AcqRel),
                data,
                host_functions: FuncVec::default(),
                host_resources: Slab::default(),
                drop_host_resource: None,
            },
        );

        inner.data_mut().drop_host_resource = Some(wasm_runtime_layer::Func::new(
            &mut inner,
            wasm_runtime_layer::FuncType::new([wasm_runtime_layer::ValueType::I32], []),
            |mut ctx, args, _| {
                if let wasm_runtime_layer::Value::I32(index) = &args[0] {
                    ctx.data_mut().host_resources.remove(*index as usize);
                    Ok(())
                } else {
                    bail!("Could not drop resource.");
                }
            },
        ));

        Self { inner }
    }

    /// Returns the [`Engine`] that this store is associated with.
    pub fn engine(&self) -> &Engine<E> {
        self.inner.engine()
    }

    /// Returns a shared reference to the user provided data owned by this [`Store`].
    pub fn data(&self) -> &T {
        &self.inner.data().data
    }

    /// Returns an exclusive reference to the user provided data owned by this [`Store`].
    pub fn data_mut(&mut self) -> &mut T {
        &mut self.inner.data_mut().data
    }

    /// Consumes `self` and returns its user provided data.
    pub fn into_data(self) -> T {
        self.inner.into_data().data
    }
}

/// A temporary handle to a [`&Store<T>`][`Store`].
///
/// This type is suitable for [`AsContext`] trait bounds on methods if desired.
/// For more information, see [`Store`].
pub struct StoreContext<'a, T: 'a, E: backend::WasmEngine> {
    /// The backing implementation.
    inner: wasm_runtime_layer::StoreContext<'a, StoreInner<T, E>, E>,
}

impl<'a, T: 'a, E: backend::WasmEngine> StoreContext<'a, T, E> {
    /// Returns the underlying [`Engine`] this store is connected to.
    pub fn engine(&self) -> &Engine<E> {
        self.inner.engine()
    }

    /// Access the underlying data owned by this store.
    ///
    /// Same as [`Store::data`].
    pub fn data(&self) -> &T {
        &self.inner.data().data
    }
}

/// A temporary handle to a [`&mut Store<T>`][`Store`].
///
/// This type is suitable for [`AsContextMut`] or [`AsContext`] trait bounds on methods if desired.
/// For more information, see [`Store`].
pub struct StoreContextMut<'a, T: 'a, E: backend::WasmEngine> {
    /// The backing implementation.
    inner: wasm_runtime_layer::StoreContextMut<'a, StoreInner<T, E>, E>,
}

impl<'a, T: 'a, E: backend::WasmEngine> StoreContextMut<'a, T, E> {
    /// Returns the underlying [`Engine`] this store is connected to.
    pub fn engine(&self) -> &Engine<E> {
        self.inner.engine()
    }

    /// Access the underlying data owned by this store.
    ///
    /// Same as [`Store::data`].    
    pub fn data(&self) -> &T {
        &self.inner.data().data
    }

    /// Access the underlying data owned by this store.
    ///
    /// Same as [`Store::data_mut`].
    pub fn data_mut(&mut self) -> &mut T {
        &mut self.inner.data_mut().data
    }
}

/// A trait used to get shared access to a [`Store`].
pub trait AsContext {
    /// The engine type associated with the context.
    type Engine: backend::WasmEngine;

    /// The user state associated with the [`Store`], aka the `T` in `Store<T>`.
    type UserState;

    /// Returns the store context that this type provides access to.
    fn as_context(&self) -> StoreContext<Self::UserState, Self::Engine>;
}

/// A trait used to get exclusive access to a [`Store`].
pub trait AsContextMut: AsContext {
    /// Returns the store context that this type provides access to.
    fn as_context_mut(&mut self) -> StoreContextMut<Self::UserState, Self::Engine>;
}

impl<T, E: backend::WasmEngine> AsContext for Store<T, E> {
    type Engine = E;

    type UserState = T;

    fn as_context(&self) -> StoreContext<Self::UserState, Self::Engine> {
        StoreContext {
            inner: wasm_runtime_layer::AsContext::as_context(&self.inner),
        }
    }
}

impl<T, E: backend::WasmEngine> AsContextMut for Store<T, E> {
    fn as_context_mut(&mut self) -> StoreContextMut<Self::UserState, Self::Engine> {
        StoreContextMut {
            inner: wasm_runtime_layer::AsContextMut::as_context_mut(&mut self.inner),
        }
    }
}

impl<T: AsContext> AsContext for &T {
    type Engine = T::Engine;

    type UserState = T::UserState;

    fn as_context(&self) -> StoreContext<Self::UserState, Self::Engine> {
        (**self).as_context()
    }
}

impl<T: AsContext> AsContext for &mut T {
    type Engine = T::Engine;

    type UserState = T::UserState;

    fn as_context(&self) -> StoreContext<Self::UserState, Self::Engine> {
        (**self).as_context()
    }
}

impl<T: AsContextMut> AsContextMut for &mut T {
    fn as_context_mut(&mut self) -> StoreContextMut<Self::UserState, Self::Engine> {
        (**self).as_context_mut()
    }
}

impl<'a, T: 'a, E: backend::WasmEngine> AsContext for StoreContext<'a, T, E> {
    type Engine = E;

    type UserState = T;

    fn as_context(&self) -> StoreContext<Self::UserState, Self::Engine> {
        StoreContext {
            inner: wasm_runtime_layer::AsContext::as_context(&self.inner),
        }
    }
}

impl<'a, T: 'a, E: backend::WasmEngine> AsContext for StoreContextMut<'a, T, E> {
    type Engine = E;

    type UserState = T;

    fn as_context(&self) -> StoreContext<Self::UserState, Self::Engine> {
        StoreContext {
            inner: wasm_runtime_layer::AsContext::as_context(&self.inner),
        }
    }
}

impl<'a, T: 'a, E: backend::WasmEngine> AsContextMut for StoreContextMut<'a, T, E> {
    fn as_context_mut(&mut self) -> StoreContextMut<Self::UserState, Self::Engine> {
        StoreContextMut {
            inner: wasm_runtime_layer::AsContextMut::as_context_mut(&mut self.inner),
        }
    }
}

/// Holds the inner mutable state for a component model implementation.
struct StoreInner<T, E: backend::WasmEngine> {
    /// The unique ID of this store.
    pub id: u64,
    /// The consumer's custom data.
    pub data: T,
    /// The table of host functions.
    pub host_functions: FuncVec<T, E>,
    /// The table of host resources.
    pub host_resources: Slab<Box<dyn Any + Send + Sync>>,
    /// A function that drops a host resource from this store.
    pub drop_host_resource: Option<wasm_runtime_layer::Func>,
}

/// Denotes a trampoline used by components to interact with the host.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug)]
enum GeneratedTrampoline {
    /// The guest would like to call an imported function.
    ImportedFunction(ComponentImport),
    /// The guest would like to create a new resource.
    ResourceNew(TypeResourceTableIndex),
    /// The guest would like to obtain the representation of a resource.
    ResourceRep(TypeResourceTableIndex),
    /// The guest would like to drop a resource.
    ResourceDrop(TypeResourceTableIndex, Option<CoreDef>),
}

/// Represents a resource handle owned by a guest instance.
#[derive(Copy, Clone, Debug, Default)]
struct HandleElement {
    /// The originating instance's representation of the handle.
    pub rep: i32,
    /// Whether this handle is owned by this instance.
    pub own: bool,
    /// The number of times that this handle has been lent, without any borrows being returned.
    pub lend_count: i32,
}

/// Stores a set of resource handles and associated type information.
#[derive(Clone, Debug, Default)]
struct HandleTable {
    /// The array of handles.
    array: Slab<HandleElement>,
    /// The destructor for this handle type.
    destructor: Option<wasm_runtime_layer::Func>,
}

impl HandleTable {
    /// Gets the destructor for this handle table.
    pub fn destructor(&self) -> Option<&wasm_runtime_layer::Func> {
        self.destructor.as_ref()
    }

    /// Sets the destructor for this handle table.
    pub fn set_destructor(&mut self, destructor: Option<wasm_runtime_layer::Func>) {
        self.destructor = destructor;
    }

    /// Gets the element at the specified slot, or fails if it is empty.
    pub fn get(&self, i: i32) -> Result<&HandleElement> {
        self.array.get(i as usize).context("Invalid handle index.")
    }

    /// Sets the element at the specified slot, panicking if an element was
    /// not already there.
    pub fn set(&mut self, i: i32, element: HandleElement) {
        *self
            .array
            .get_mut(i as usize)
            .expect("Invalid handle index.") = element;
    }

    /// Inserts a new handle into this table, returning its index.
    pub fn add(&mut self, handle: HandleElement) -> i32 {
        self.array.insert(handle) as i32
    }

    /// Removes the handle at the provided index from the table,
    /// or fails if there was no handle present.
    pub fn remove(&mut self, i: i32) -> Result<HandleElement> {
        Ok(self.array.remove(i as usize))
    }
}