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
use anyhow::{anyhow, bail, Context, Result};
use indexmap::{IndexMap, IndexSet};
use std::collections::HashMap;
use std::mem;
use wasmparser::{
    names::{ComponentName, ComponentNameKind},
    types, ComponentExport, ComponentExternalKind, ComponentImport, Parser, Payload,
    PrimitiveValType, ValidPayload, Validator, WasmFeatures,
};
use wit_parser::*;

use crate::encoding::docs::{PackageDocs, PACKAGE_DOCS_SECTION_NAME};

/// Represents information about a decoded WebAssembly component.
struct ComponentInfo<'a> {
    /// Wasmparser-defined type information learned after a component is fully
    /// validated.
    types: types::Types,
    /// List of all imports and exports from this component.
    externs: Vec<(&'a str, Extern<'a>)>,
    /// Decoded package docs
    package_docs: Option<PackageDocs>,
}

enum Extern<'a> {
    Import(ComponentImport<'a>),
    Export(ComponentExport<'a>),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WitEncodingVersion {
    V1,
    V2,
}

impl<'a> ComponentInfo<'a> {
    /// Creates a new component info by parsing the given WebAssembly component bytes.
    fn new(bytes: &'a [u8]) -> Result<Self> {
        let mut validator = Validator::new_with_features(WasmFeatures::all());
        let mut externs = Vec::new();
        let mut depth = 1;
        let mut types = None;
        let mut package_docs = None;

        for payload in Parser::new(0).parse_all(bytes) {
            let payload = payload?;

            match validator.payload(&payload)? {
                ValidPayload::Ok => {}
                ValidPayload::Parser(_) => depth += 1,
                ValidPayload::End(t) => {
                    depth -= 1;
                    if depth == 0 {
                        types = Some(t);
                    }
                }
                ValidPayload::Func(..) => {}
            }

            match payload {
                Payload::ComponentImportSection(s) if depth == 1 => {
                    for import in s {
                        let import = import?;
                        externs.push((import.name.0, Extern::Import(import)));
                    }
                }
                Payload::ComponentExportSection(s) if depth == 1 => {
                    for export in s {
                        let export = export?;
                        externs.push((export.name.0, Extern::Export(export)));
                    }
                }
                Payload::CustomSection(s) if s.name() == PACKAGE_DOCS_SECTION_NAME => {
                    if package_docs.is_some() {
                        bail!("multiple {PACKAGE_DOCS_SECTION_NAME:?} sections");
                    }
                    package_docs = Some(PackageDocs::decode(s.data())?);
                }
                _ => {}
            }
        }
        Ok(Self {
            types: types.unwrap(),
            externs,
            package_docs,
        })
    }

    fn is_wit_package(&self) -> Option<WitEncodingVersion> {
        // all wit package exports must be component types, and there must be at
        // least one
        if self.externs.is_empty() {
            return None;
        }

        if !self.externs.iter().all(|(_, item)| {
            let export = match item {
                Extern::Export(e) => e,
                _ => return false,
            };
            match export.kind {
                ComponentExternalKind::Type => matches!(
                    self.types.component_any_type_at(export.index),
                    types::ComponentAnyTypeId::Component(_)
                ),
                _ => false,
            }
        }) {
            return None;
        }

        // The distinction between v1 and v2 encoding formats is the structure of the export
        // strings for each component. The v1 format uses "<namespace>:<package>/wit" as the name
        // for the top-level exports, while the v2 format uses the unqualified name of the encoded
        // entity.
        match ComponentName::new(self.externs[0].0, 0).ok()?.kind() {
            ComponentNameKind::Interface(name) if name.interface().as_str() == "wit" => {
                Some(WitEncodingVersion::V1)
            }
            ComponentNameKind::Label(_) => Some(WitEncodingVersion::V2),
            _ => None,
        }
    }

    fn decode_wit_v1_package(&self) -> Result<(Resolve, PackageId)> {
        let mut decoder = WitPackageDecoder::new(&self.types);

        let mut pkg = None;
        for (name, item) in self.externs.iter() {
            let export = match item {
                Extern::Export(e) => e,
                _ => unreachable!(),
            };
            let id = self.types.component_type_at(export.index);
            let ty = &self.types[id];
            if pkg.is_some() {
                bail!("more than one top-level exported component type found");
            }
            let name = ComponentName::new(*name, 0).unwrap();
            pkg = Some(
                decoder
                    .decode_v1_package(&name, ty)
                    .with_context(|| format!("failed to decode document `{name}`"))?,
            );
        }

        let pkg = pkg.ok_or_else(|| anyhow!("no exported component type found"))?;
        let (mut resolve, package) = decoder.finish(pkg);
        if let Some(package_docs) = &self.package_docs {
            package_docs.inject(&mut resolve, package)?;
        }
        Ok((resolve, package))
    }

    fn decode_wit_v2_package(&self) -> Result<(Resolve, PackageId)> {
        let mut decoder = WitPackageDecoder::new(&self.types);

        let mut pkg_name = None;

        let mut interfaces = IndexMap::new();
        let mut worlds = IndexMap::new();
        let mut fields = PackageFields {
            interfaces: &mut interfaces,
            worlds: &mut worlds,
        };

        for (_, item) in self.externs.iter() {
            let export = match item {
                Extern::Export(e) => e,
                _ => unreachable!(),
            };

            let index = export.index;
            let id = self.types.component_type_at(index);
            let component = &self.types[id];

            // The single export of this component will determine if it's a world or an interface:
            // worlds export a component, while interfaces export an instance.
            if component.exports.len() != 1 {
                bail!(
                    "Expected a single export, but found {} instead",
                    component.exports.len()
                );
            }

            let name = component.exports.keys().nth(0).unwrap();

            let name = match component.exports[name] {
                types::ComponentEntityType::Component(ty) => {
                    let package_name =
                        decoder.decode_world(name.as_str(), &self.types[ty], &mut fields)?;
                    package_name
                }
                types::ComponentEntityType::Instance(ty) => {
                    let package_name = decoder.decode_interface(
                        name.as_str(),
                        &component.imports,
                        &self.types[ty],
                        &mut fields,
                    )?;
                    package_name
                }
                _ => unreachable!(),
            };

            if let Some(pkg_name) = pkg_name.as_ref() {
                // TODO: when we have fully switched to the v2 format, we should switch to parsing
                // multiple wit documents instead of bailing.
                if pkg_name != &name {
                    bail!("item defined with mismatched package name")
                }
            } else {
                pkg_name.replace(name);
            }
        }

        let pkg = if let Some(name) = pkg_name {
            Package {
                name,
                docs: Docs::default(),
                interfaces,
                worlds,
            }
        } else {
            bail!("no exported component type found");
        };

        let (mut resolve, package) = decoder.finish(pkg);
        if let Some(package_docs) = &self.package_docs {
            package_docs.inject(&mut resolve, package)?;
        }
        Ok((resolve, package))
    }

    fn decode_component(&self) -> Result<(Resolve, WorldId)> {
        assert!(self.is_wit_package().is_none());
        let mut decoder = WitPackageDecoder::new(&self.types);
        // Note that this name is arbitrarily chosen. We may one day perhaps
        // want to encode this in the component binary format itself, but for
        // now it shouldn't be an issue to have a defaulted name here.
        let world_name = "root";
        let world = decoder.resolve.worlds.alloc(World {
            name: world_name.to_string(),
            docs: Default::default(),
            imports: Default::default(),
            exports: Default::default(),
            package: None,
            includes: Default::default(),
            include_names: Default::default(),
        });
        let mut package = Package {
            // Similar to `world_name` above this is arbitrarily chosen as it's
            // not otherwise encoded in a binary component. This theoretically
            // shouldn't cause issues, however.
            name: PackageName {
                namespace: "root".to_string(),
                version: None,
                name: "component".to_string(),
            },
            docs: Default::default(),
            worlds: [(world_name.to_string(), world)].into_iter().collect(),
            interfaces: Default::default(),
        };

        let mut fields = PackageFields {
            worlds: &mut package.worlds,
            interfaces: &mut package.interfaces,
        };

        for (_name, item) in self.externs.iter() {
            match item {
                Extern::Import(import) => {
                    decoder.decode_component_import(import, world, &mut fields)?
                }
                Extern::Export(export) => {
                    decoder.decode_component_export(export, world, &mut fields)?
                }
            }
        }

        let (resolve, _) = decoder.finish(package);
        Ok((resolve, world))
    }
}

/// Result of the [`decode`] function.
pub enum DecodedWasm {
    /// The input to [`decode`] was a binary-encoded WIT package.
    ///
    /// The full resolve graph is here plus the identifier of the package that
    /// was encoded. Note that other packages may be within the resolve if this
    /// package refers to foreign packages.
    WitPackage(Resolve, PackageId),

    /// The input to [`decode`] was a component and its interface is specified
    /// by the world here.
    Component(Resolve, WorldId),
}

impl DecodedWasm {
    /// Returns the [`Resolve`] for WIT types contained.
    pub fn resolve(&self) -> &Resolve {
        match self {
            DecodedWasm::WitPackage(resolve, _) => resolve,
            DecodedWasm::Component(resolve, _) => resolve,
        }
    }

    /// Returns the main package of what was decoded.
    pub fn package(&self) -> PackageId {
        match self {
            DecodedWasm::WitPackage(_, id) => *id,
            DecodedWasm::Component(resolve, world) => resolve.worlds[*world].package.unwrap(),
        }
    }
}

/// Decodes an in-memory WebAssembly binary into a WIT [`Resolve`] and
/// associated metadata.
///
/// The WebAssembly binary provided here can either be a
/// WIT-package-encoded-as-binary or an actual component itself. A [`Resolve`]
/// is always created and the return value indicates which was detected.
pub fn decode(bytes: &[u8]) -> Result<DecodedWasm> {
    let info = ComponentInfo::new(bytes)?;

    if let Some(version) = info.is_wit_package() {
        match version {
            WitEncodingVersion::V1 => {
                log::debug!("decoding a v1 WIT package encoded as wasm");
                let (resolve, pkg) = info.decode_wit_v1_package()?;
                Ok(DecodedWasm::WitPackage(resolve, pkg))
            }
            WitEncodingVersion::V2 => {
                log::debug!("decoding a v2 WIT package encoded as wasm");
                let (resolve, pkg) = info.decode_wit_v2_package()?;
                Ok(DecodedWasm::WitPackage(resolve, pkg))
            }
        }
    } else {
        log::debug!("inferring the WIT of a concrete component");
        let (resolve, world) = info.decode_component()?;
        Ok(DecodedWasm::Component(resolve, world))
    }
}

/// Decodes the single component type `world` specified as a WIT world.
///
/// The `name` provided should be a full ID such as `foo:bar/baz`.
pub(crate) fn decode_world(
    types: &types::Types,
    name: &str,
    world: types::ComponentTypeId,
) -> Result<(Resolve, WorldId)> {
    let mut decoder = WitPackageDecoder::new(types);
    let mut interfaces = IndexMap::new();
    let mut worlds = IndexMap::new();
    let name = decoder.decode_world(
        name,
        &types[world],
        &mut PackageFields {
            interfaces: &mut interfaces,
            worlds: &mut worlds,
        },
    )?;
    let (resolve, pkg) = decoder.finish(Package {
        name,
        interfaces,
        worlds,
        docs: Default::default(),
    });
    // The package decoded here should only have a single world so extract that
    // here to return.
    let world = *resolve.packages[pkg].worlds.iter().next().unwrap().1;
    Ok((resolve, world))
}

struct PackageFields<'a> {
    interfaces: &'a mut IndexMap<String, InterfaceId>,
    worlds: &'a mut IndexMap<String, WorldId>,
}

struct WitPackageDecoder<'a> {
    resolve: Resolve,
    types: &'a types::Types,
    foreign_packages: IndexMap<String, Package>,
    iface_to_package_index: HashMap<InterfaceId, usize>,
    named_interfaces: HashMap<String, InterfaceId>,

    /// A map which tracks named resources to what their corresponding `TypeId`
    /// is. This first layer of key in this map is the owner scope of a
    /// resource, more-or-less the `world` or `interface` that it's defined
    /// within. The second layer of this map is keyed by name of the resource
    /// and points to the actual ID of the resource.
    ///
    /// This map is populated in `register_type_export`.
    resources: HashMap<TypeOwner, HashMap<String, TypeId>>,

    /// A map from a type id to what it's been translated to.
    type_map: HashMap<types::ComponentAnyTypeId, TypeId>,
}

impl WitPackageDecoder<'_> {
    fn new<'a>(types: &'a types::Types) -> WitPackageDecoder<'a> {
        WitPackageDecoder {
            resolve: Resolve::default(),
            types,
            type_map: HashMap::new(),
            foreign_packages: Default::default(),
            iface_to_package_index: Default::default(),
            named_interfaces: Default::default(),
            resources: Default::default(),
        }
    }

    fn decode_v1_package(
        &mut self,
        name: &ComponentName,
        ty: &types::ComponentType,
    ) -> Result<Package> {
        // Process all imports for this package first, where imports are
        // importing from remote packages.
        for (name, ty) in ty.imports.iter() {
            let ty = match ty {
                types::ComponentEntityType::Instance(idx) => &self.types[*idx],
                _ => bail!("import `{name}` is not an instance"),
            };
            self.register_import(name, ty)
                .with_context(|| format!("failed to process import `{name}`"))?;
        }

        let mut package = Package {
            // The name encoded for packages must be of the form `foo:bar/wit`
            // where "wit" is just a placeholder for now. The package name in
            // this case would be `foo:bar`.
            name: match name.kind() {
                ComponentNameKind::Interface(name) if name.interface().as_str() == "wit" => {
                    name.to_package_name()
                }
                _ => bail!("package name is not a valid id: {name}"),
            },
            docs: Default::default(),
            interfaces: Default::default(),
            worlds: Default::default(),
        };

        let mut fields = PackageFields {
            interfaces: &mut package.interfaces,
            worlds: &mut package.worlds,
        };

        for (name, ty) in ty.exports.iter() {
            match ty {
                types::ComponentEntityType::Instance(idx) => {
                    let ty = &self.types[*idx];
                    self.register_interface(name.as_str(), ty, &mut fields)
                        .with_context(|| format!("failed to process export `{name}`"))?;
                }
                types::ComponentEntityType::Component(idx) => {
                    let ty = &self.types[*idx];
                    self.register_world(name.as_str(), ty, &mut fields)
                        .with_context(|| format!("failed to process export `{name}`"))?;
                }
                _ => bail!("component export `{name}` is not an instance or component"),
            }
        }
        Ok(package)
    }

    fn decode_interface<'a>(
        &mut self,
        name: &str,
        imports: &IndexMap<String, types::ComponentEntityType>,
        ty: &types::ComponentInstanceType,
        fields: &mut PackageFields<'a>,
    ) -> Result<PackageName> {
        let component_name = self
            .parse_component_name(name)
            .context("expected world name to have an ID form")?;

        let package = match component_name.kind() {
            ComponentNameKind::Interface(name) => name.to_package_name(),
            _ => bail!("expected world name to be fully qualified"),
        };

        for (name, ty) in imports.iter() {
            let ty = match ty {
                types::ComponentEntityType::Instance(idx) => &self.types[*idx],
                _ => bail!("import `{name}` is not an instance"),
            };
            self.register_import(name, ty)
                .with_context(|| format!("failed to process import `{name}`"))?;
        }

        let _ = self.register_interface(name, ty, fields)?;

        Ok(package)
    }

    fn decode_world<'a>(
        &mut self,
        name: &str,
        ty: &types::ComponentType,
        fields: &mut PackageFields<'a>,
    ) -> Result<PackageName> {
        let kebab_name = self
            .parse_component_name(name)
            .context("expected world name to have an ID form")?;

        let package = match kebab_name.kind() {
            ComponentNameKind::Interface(name) => name.to_package_name(),
            _ => bail!("expected world name to be fully qualified"),
        };

        let _ = self.register_world(name, ty, fields)?;

        Ok(package)
    }

    fn decode_component_import<'a>(
        &mut self,
        import: &ComponentImport<'_>,
        world: WorldId,
        package: &mut PackageFields<'a>,
    ) -> Result<()> {
        let name = import.name.0;
        log::debug!("decoding component import `{name}`");
        let ty = self.types.component_entity_type_of_import(name).unwrap();
        let owner = TypeOwner::World(world);
        let (name, item) = match ty {
            types::ComponentEntityType::Instance(i) => {
                let ty = &self.types[i];
                let (name, id) = if name.contains('/') {
                    let id = self.register_import(name, ty)?;
                    (WorldKey::Interface(id), id)
                } else {
                    self.register_interface(name, ty, package)
                        .with_context(|| format!("failed to decode WIT from import `{name}`"))?
                };
                (name, WorldItem::Interface(id))
            }
            types::ComponentEntityType::Func(i) => {
                let ty = &self.types[i];
                let func = self
                    .convert_function(name, ty, owner)
                    .with_context(|| format!("failed to decode function from import `{name}`"))?;
                (WorldKey::Name(name.to_string()), WorldItem::Function(func))
            }
            types::ComponentEntityType::Type {
                referenced,
                created,
            } => {
                let id = self
                    .register_type_export(name, owner, referenced, created)
                    .with_context(|| format!("failed to decode type from export `{name}`"))?;
                (WorldKey::Name(name.to_string()), WorldItem::Type(id))
            }
            // All other imports do not form part of the component's world
            _ => return Ok(()),
        };
        self.resolve.worlds[world].imports.insert(name, item);
        Ok(())
    }

    fn decode_component_export<'a>(
        &mut self,
        export: &ComponentExport<'_>,
        world: WorldId,
        package: &mut PackageFields<'a>,
    ) -> Result<()> {
        let name = export.name.0;
        log::debug!("decoding component export `{name}`");
        let types = &self.types;
        let ty = types.component_entity_type_of_export(name).unwrap();
        let (name, item) = match ty {
            types::ComponentEntityType::Func(i) => {
                let ty = &types[i];
                let func = self
                    .convert_function(name, ty, TypeOwner::World(world))
                    .with_context(|| format!("failed to decode function from export `{name}`"))?;

                (WorldKey::Name(name.to_string()), WorldItem::Function(func))
            }
            types::ComponentEntityType::Instance(i) => {
                let ty = &types[i];
                let (name, id) = if name.contains('/') {
                    let id = self.register_import(name, ty)?;
                    (WorldKey::Interface(id), id)
                } else {
                    self.register_interface(name, ty, package)
                        .with_context(|| format!("failed to decode WIT from export `{name}`"))?
                };
                (name, WorldItem::Interface(id))
            }
            _ => {
                bail!("component export `{name}` was not a function or instance")
            }
        };
        self.resolve.worlds[world].exports.insert(name, item);
        Ok(())
    }

    /// Registers that the `name` provided is either imported interface from a
    /// foreign package or  referencing a previously defined interface in this
    /// package.
    ///
    /// This function will internally ensure that `name` is well-structured and
    /// will fill in any information as necessary. For example with a foreign
    /// dependency the foreign package structure, types, etc, all need to be
    /// created. For a local dependency it's instead ensured that all the types
    /// line up with the previous definitions.
    fn register_import(
        &mut self,
        name: &str,
        ty: &types::ComponentInstanceType,
    ) -> Result<InterfaceId> {
        let (is_local, interface) = match self.named_interfaces.get(name) {
            Some(id) => (true, *id),
            None => (false, self.extract_dep_interface(name)?),
        };
        let owner = TypeOwner::Interface(interface);
        for (name, ty) in ty.exports.iter() {
            log::debug!("decoding import instance export `{name}`");
            match *ty {
                types::ComponentEntityType::Type {
                    referenced,
                    created,
                } => {
                    match self.resolve.interfaces[interface]
                        .types
                        .get(name.as_str())
                        .copied()
                    {
                        // If this name is already defined as a type in the
                        // specified interface then that's ok. For package-local
                        // interfaces that's expected since the interface was
                        // fully defined. For remote interfaces it means we're
                        // using something that was already used elsewhere. In
                        // both cases continue along.
                        //
                        // Notably for the remotely defined case this will also
                        // walk over the structure of the type and register
                        // internal wasmparser ids with wit-parser ids. This is
                        // necessary to ensure that anonymous types like
                        // `list<u8>` defined in original definitions are
                        // unified with anonymous types when duplicated inside
                        // of worlds. Overall this prevents, for example, extra
                        // `list<u8>` types from popping up when decoding. This
                        // is not strictly necessary but assists with
                        // roundtripping assertions during fuzzing.
                        Some(id) => {
                            log::debug!("type already exist");
                            match referenced {
                                types::ComponentAnyTypeId::Defined(ty) => {
                                    self.register_defined(id, &self.types[ty])?;
                                }
                                types::ComponentAnyTypeId::Resource(_) => {}
                                _ => unreachable!(),
                            }
                            let prev = self.type_map.insert(created, id);
                            assert!(prev.is_none());
                        }

                        // If the name is not defined, however, then there's two
                        // possibilities:
                        //
                        // * For package-local interfaces this is an error
                        //   because the package-local interface defined
                        //   everything already and this is referencing
                        //   something that isn't defined.
                        //
                        // * For remote interfaces they're never fully declared
                        //   so it's lazily filled in here. This means that the
                        //   view of remote interfaces ends up being the minimal
                        //   slice needed for this resolve, which is what's
                        //   intended.
                        None => {
                            if is_local {
                                bail!("instance type export `{name}` not defined in interface");
                            }
                            let id = self.register_type_export(
                                name.as_str(),
                                owner,
                                referenced,
                                created,
                            )?;
                            let prev = self.resolve.interfaces[interface]
                                .types
                                .insert(name.to_string(), id);
                            assert!(prev.is_none());
                        }
                    }
                }

                // This has similar logic to types above where we lazily fill in
                // functions for remote dependencies and otherwise assert
                // they're already defined for local dependencies.
                types::ComponentEntityType::Func(ty) => {
                    let def = &self.types[ty];
                    if self.resolve.interfaces[interface]
                        .functions
                        .contains_key(name.as_str())
                    {
                        // TODO: should ideally verify that function signatures
                        // match.
                        continue;
                    }
                    if is_local {
                        bail!("instance function export `{name}` not defined in interface");
                    }
                    let func = self.convert_function(name.as_str(), def, owner)?;
                    let prev = self.resolve.interfaces[interface]
                        .functions
                        .insert(name.to_string(), func);
                    assert!(prev.is_none());
                }

                _ => bail!("instance type export `{name}` is not a type"),
            }
        }

        Ok(interface)
    }

    fn find_alias(&self, id: types::ComponentAnyTypeId) -> Option<TypeId> {
        // Consult `type_map` for `referenced` or anything in its
        // chain of aliases to determine what it maps to. This may
        // bottom out in `None` in the case that this type is
        // just now being defined, but this should otherwise follow
        // chains of aliases to determine what exactly this was a
        // `use` of if it exists.
        let mut prev = None;
        let mut cur = id;
        while prev.is_none() {
            prev = self.type_map.get(&cur).copied();
            cur = match self.types.peel_alias(cur) {
                Some(next) => next,
                None => break,
            };
        }
        prev
    }

    /// This will parse the `name_string` as a component model ID string and
    /// ensure that there's an `InterfaceId` corresponding to its components.
    fn extract_dep_interface(&mut self, name_string: &str) -> Result<InterfaceId> {
        let name = ComponentName::new(name_string, 0).unwrap();
        let name = match name.kind() {
            ComponentNameKind::Interface(name) => name,
            _ => bail!("package name is not a valid id: {name_string}"),
        };
        let package_name = name.to_package_name();
        // Lazily create a `Package` as necessary, along with the interface.
        let package = self
            .foreign_packages
            .entry(package_name.to_string())
            .or_insert_with(|| Package {
                name: package_name.clone(),
                docs: Default::default(),
                interfaces: Default::default(),
                worlds: Default::default(),
            });
        let interface = *package
            .interfaces
            .entry(name.interface().to_string())
            .or_insert_with(|| {
                self.resolve.interfaces.alloc(Interface {
                    name: Some(name.interface().to_string()),
                    docs: Default::default(),
                    types: IndexMap::default(),
                    functions: IndexMap::new(),
                    package: None,
                })
            });

        // Record a mapping of which foreign package this interface belongs to
        self.iface_to_package_index.insert(
            interface,
            self.foreign_packages
                .get_full(&package_name.to_string())
                .unwrap()
                .0,
        );
        Ok(interface)
    }

    /// A general-purpose helper function to translate a component instance
    /// into a WIT interface.
    ///
    /// This is one of the main workhorses of this module. This handles
    /// interfaces both at the type level, for concrete components, and
    /// internally within worlds as well.
    ///
    /// The `name` provided is the contextual ID or name of the interface. This
    /// could be a kebab-name in the case of a world import or export or it can
    /// also be an ID. This is used to guide insertion into various maps.
    ///
    /// The `ty` provided is the actual component type being decoded.
    ///
    /// The `package` is where to insert the final interface if `name` is an ID
    /// meaning it's registered as a named standalone item within the package.
    fn register_interface<'a>(
        &mut self,
        name: &str,
        ty: &types::ComponentInstanceType,
        package: &mut PackageFields<'a>,
    ) -> Result<(WorldKey, InterfaceId)> {
        // If this interface's name is already known then that means this is an
        // interface that's both imported and exported.  Use `register_import`
        // to draw connections between types and this interface's types.
        if self.named_interfaces.contains_key(name) {
            let id = self.register_import(name, ty)?;
            return Ok((WorldKey::Interface(id), id));
        }

        // If this is a bare kebab-name for an interface then the interface's
        // listed name is `None` and the name goes out through the key.
        // Otherwise this name is extracted from `name` interpreted as an ID.
        let interface_name = self.extract_interface_name_from_component_name(name)?;

        let mut interface = Interface {
            name: interface_name.clone(),
            docs: Default::default(),
            types: IndexMap::default(),
            functions: IndexMap::new(),
            package: None,
        };

        let owner = TypeOwner::Interface(self.resolve.interfaces.next_id());
        for (name, ty) in ty.exports.iter() {
            match *ty {
                types::ComponentEntityType::Type {
                    referenced,
                    created,
                } => {
                    let ty = self
                        .register_type_export(name.as_str(), owner, referenced, created)
                        .with_context(|| format!("failed to register type export '{name}'"))?;
                    let prev = interface.types.insert(name.to_string(), ty);
                    assert!(prev.is_none());
                }

                types::ComponentEntityType::Func(ty) => {
                    let ty = &self.types[ty];
                    let func = self
                        .convert_function(name.as_str(), ty, owner)
                        .with_context(|| format!("failed to convert function '{name}'"))?;
                    let prev = interface.functions.insert(name.to_string(), func);
                    assert!(prev.is_none());
                }
                _ => bail!("instance type export `{name}` is not a type or function"),
            };
        }
        let id = self.resolve.interfaces.alloc(interface);
        let key = match interface_name {
            // If this interface is named then it's part of the package, so
            // insert it. Additionally register it in `named_interfaces` so
            // further use comes back to this original definition.
            Some(interface_name) => {
                let prev = package.interfaces.insert(interface_name, id);
                assert!(prev.is_none(), "duplicate interface added for {name:?}");
                let prev = self.named_interfaces.insert(name.to_string(), id);
                assert!(prev.is_none());
                WorldKey::Interface(id)
            }

            // If this interface isn't named then its key is always a
            // kebab-name.
            None => WorldKey::Name(name.to_string()),
        };
        Ok((key, id))
    }

    fn parse_component_name(&self, name: &str) -> Result<ComponentName> {
        ComponentName::new(name, 0)
            .with_context(|| format!("cannot extract item name from: {name}"))
    }

    fn extract_interface_name_from_component_name(&self, name: &str) -> Result<Option<String>> {
        let component_name = self.parse_component_name(name)?;
        match component_name.kind() {
            ComponentNameKind::Interface(name) => Ok(Some(name.interface().to_string())),
            ComponentNameKind::Label(_name) => Ok(None),
            _ => bail!("cannot extract item name from: {name}"),
        }
    }

    fn register_type_export(
        &mut self,
        name: &str,
        owner: TypeOwner,
        referenced: types::ComponentAnyTypeId,
        created: types::ComponentAnyTypeId,
    ) -> Result<TypeId> {
        let kind = match self.find_alias(referenced) {
            // If this `TypeId` points to a type which has
            // previously been defined, meaning we're aliasing a
            // prior definition.
            Some(prev) => {
                log::debug!("type export for `{name}` is an alias");
                TypeDefKind::Type(Type::Id(prev))
            }

            // ... or this `TypeId`'s source definition has never
            // been seen before, so declare the full type.
            None => {
                log::debug!("type export for `{name}` is a new type");
                match referenced {
                    types::ComponentAnyTypeId::Defined(ty) => self
                        .convert_defined(&self.types[ty])
                        .context("failed to convert unaliased type")?,
                    types::ComponentAnyTypeId::Resource(_) => TypeDefKind::Resource,
                    _ => unreachable!(),
                }
            }
        };
        let ty = self.resolve.types.alloc(TypeDef {
            name: Some(name.to_string()),
            kind,
            docs: Default::default(),
            owner,
        });

        // If this is a resource then doubly-register it in `self.resources` so
        // the ID allocated here can be looked up via name later on during
        // `convert_function`.
        if let TypeDefKind::Resource = self.resolve.types[ty].kind {
            let prev = self
                .resources
                .entry(owner)
                .or_insert(HashMap::new())
                .insert(name.to_string(), ty);
            assert!(prev.is_none());
        }

        let prev = self.type_map.insert(created, ty);
        assert!(prev.is_none());
        Ok(ty)
    }

    fn register_world<'a>(
        &mut self,
        name: &str,
        ty: &types::ComponentType,
        package: &mut PackageFields<'a>,
    ) -> Result<WorldId> {
        let name = self
            .extract_interface_name_from_component_name(name)?
            .context("expected world name to have an ID form")?;
        let mut world = World {
            name: name.clone(),
            docs: Default::default(),
            imports: Default::default(),
            exports: Default::default(),
            includes: Default::default(),
            include_names: Default::default(),
            package: None,
        };

        let owner = TypeOwner::World(self.resolve.worlds.next_id());
        for (name, ty) in ty.imports.iter() {
            let (name, item) = match ty {
                types::ComponentEntityType::Instance(idx) => {
                    let ty = &self.types[*idx];
                    let (name, id) = if name.contains('/') {
                        // If a name is an interface import then it is either to
                        // a package-local or foreign interface, and both
                        // situations are handled in `register_import`.
                        let id = self.register_import(name, ty)?;
                        (WorldKey::Interface(id), id)
                    } else {
                        // A plain kebab-name indicates an inline interface that
                        // wasn't declared explicitly elsewhere with a name, and
                        // `register_interface` will create a new `Interface`
                        // with no name.
                        self.register_interface(name, ty, package)?
                    };
                    (name, WorldItem::Interface(id))
                }
                types::ComponentEntityType::Type {
                    created,
                    referenced,
                } => {
                    let ty =
                        self.register_type_export(name.as_str(), owner, *referenced, *created)?;
                    (WorldKey::Name(name.to_string()), WorldItem::Type(ty))
                }
                types::ComponentEntityType::Func(idx) => {
                    let ty = &self.types[*idx];
                    let func = self.convert_function(name.as_str(), ty, owner)?;
                    (WorldKey::Name(name.to_string()), WorldItem::Function(func))
                }
                _ => bail!("component import `{name}` is not an instance, func, or type"),
            };
            world.imports.insert(name, item);
        }

        for (name, ty) in ty.exports.iter() {
            let (name, item) = match ty {
                types::ComponentEntityType::Instance(idx) => {
                    let ty = &self.types[*idx];
                    let (name, id) = if name.contains('/') {
                        // Note that despite this being an export this is
                        // calling `register_import`. With a URL this interface
                        // must have been previously defined so this will
                        // trigger the logic of either filling in a remotely
                        // defined interface or connecting items to local
                        // definitions of our own interface.
                        let id = self.register_import(name, ty)?;
                        (WorldKey::Interface(id), id)
                    } else {
                        self.register_interface(name, ty, package)?
                    };
                    (name, WorldItem::Interface(id))
                }

                types::ComponentEntityType::Func(idx) => {
                    let ty = &self.types[*idx];
                    let func = self.convert_function(name.as_str(), ty, owner)?;
                    (WorldKey::Name(name.to_string()), WorldItem::Function(func))
                }

                _ => bail!("component export `{name}` is not an instance or function"),
            };
            world.exports.insert(name, item);
        }
        let id = self.resolve.worlds.alloc(world);
        let prev = package.worlds.insert(name, id);
        assert!(prev.is_none());
        Ok(id)
    }

    fn convert_function(
        &mut self,
        name: &str,
        ty: &types::ComponentFuncType,
        owner: TypeOwner,
    ) -> Result<Function> {
        let name = ComponentName::new(name, 0).unwrap();
        let params = ty
            .params
            .iter()
            .map(|(name, ty)| Ok((name.to_string(), self.convert_valtype(ty)?)))
            .collect::<Result<Vec<_>>>()
            .context("failed to convert params")?;
        let results = if ty.results.len() == 1 && ty.results[0].0.is_none() {
            Results::Anon(
                self.convert_valtype(&ty.results[0].1)
                    .context("failed to convert anonymous result type")?,
            )
        } else {
            Results::Named(
                ty.results
                    .iter()
                    .map(|(name, ty)| {
                        Ok((
                            name.as_ref().unwrap().to_string(),
                            self.convert_valtype(ty)?,
                        ))
                    })
                    .collect::<Result<Vec<_>>>()
                    .context("failed to convert named result types")?,
            )
        };
        Ok(Function {
            docs: Default::default(),
            kind: match name.kind() {
                ComponentNameKind::Label(_) => FunctionKind::Freestanding,
                ComponentNameKind::Constructor(resource) => {
                    FunctionKind::Constructor(self.resources[&owner][resource.as_str()])
                }
                ComponentNameKind::Method(name) => {
                    FunctionKind::Method(self.resources[&owner][name.resource().as_str()])
                }
                ComponentNameKind::Static(name) => {
                    FunctionKind::Static(self.resources[&owner][name.resource().as_str()])
                }

                // Functions shouldn't have ID-based names at this time.
                ComponentNameKind::Interface(_)
                | ComponentNameKind::Url(_)
                | ComponentNameKind::Hash(_)
                | ComponentNameKind::Dependency(_) => unreachable!(),
            },

            // Note that this name includes "name mangling" such as
            // `[method]foo.bar` which is intentional. The `FunctionKind`
            // discriminant calculated above indicates how to interpret this
            // name.
            name: name.to_string(),
            params,
            results,
        })
    }

    fn convert_valtype(&mut self, ty: &types::ComponentValType) -> Result<Type> {
        let id = match ty {
            types::ComponentValType::Primitive(ty) => return Ok(self.convert_primitive(*ty)),
            types::ComponentValType::Type(id) => *id,
        };

        // Don't create duplicate types for anything previously created.
        if let Some(ret) = self.type_map.get(&id.into()) {
            return Ok(Type::Id(*ret));
        }

        // Otherwise create a new `TypeDef` without a name since this is an
        // anonymous valtype. Note that this is invalid for some types so return
        // errors on those types, but eventually the `bail!` here  is
        // more-or-less unreachable due to expected validation to be added to
        // the component model binary format itself.
        let def = &self.types[id];
        let kind = self.convert_defined(def)?;
        match &kind {
            TypeDefKind::Type(_)
            | TypeDefKind::List(_)
            | TypeDefKind::Tuple(_)
            | TypeDefKind::Option(_)
            | TypeDefKind::Result(_)
            | TypeDefKind::Handle(_) => {}

            TypeDefKind::Resource
            | TypeDefKind::Record(_)
            | TypeDefKind::Enum(_)
            | TypeDefKind::Variant(_)
            | TypeDefKind::Flags(_)
            | TypeDefKind::Future(_)
            | TypeDefKind::Stream(_) => {
                bail!("unexpected unnamed type of kind '{}'", kind.as_str());
            }
            TypeDefKind::Unknown => unreachable!(),
        }
        let ty = self.resolve.types.alloc(TypeDef {
            name: None,
            docs: Default::default(),
            owner: TypeOwner::None,
            kind,
        });
        let prev = self.type_map.insert(id.into(), ty);
        assert!(prev.is_none());
        Ok(Type::Id(ty))
    }

    /// Converts a wasmparser `ComponentDefinedType`, the definition of a type
    /// in the component model, to a WIT `TypeDefKind` to get inserted into the
    /// types arena by the caller.
    fn convert_defined(&mut self, ty: &types::ComponentDefinedType) -> Result<TypeDefKind> {
        match ty {
            types::ComponentDefinedType::Primitive(t) => {
                Ok(TypeDefKind::Type(self.convert_primitive(*t)))
            }

            types::ComponentDefinedType::List(t) => {
                let t = self.convert_valtype(t)?;
                Ok(TypeDefKind::List(t))
            }

            types::ComponentDefinedType::Tuple(t) => {
                let types = t
                    .types
                    .iter()
                    .map(|t| self.convert_valtype(t))
                    .collect::<Result<_>>()?;
                Ok(TypeDefKind::Tuple(Tuple { types }))
            }

            types::ComponentDefinedType::Option(t) => {
                let t = self.convert_valtype(t)?;
                Ok(TypeDefKind::Option(t))
            }

            types::ComponentDefinedType::Result { ok, err } => {
                let ok = match ok {
                    Some(t) => Some(self.convert_valtype(t)?),
                    None => None,
                };
                let err = match err {
                    Some(t) => Some(self.convert_valtype(t)?),
                    None => None,
                };
                Ok(TypeDefKind::Result(Result_ { ok, err }))
            }

            types::ComponentDefinedType::Record(r) => {
                let fields = r
                    .fields
                    .iter()
                    .map(|(name, ty)| {
                        Ok(Field {
                            name: name.to_string(),
                            ty: self.convert_valtype(ty).with_context(|| {
                                format!("failed to convert record field '{name}'")
                            })?,
                            docs: Default::default(),
                        })
                    })
                    .collect::<Result<_>>()?;
                Ok(TypeDefKind::Record(Record { fields }))
            }

            types::ComponentDefinedType::Variant(v) => {
                let cases = v
                    .cases
                    .iter()
                    .map(|(name, case)| {
                        if case.refines.is_some() {
                            bail!("unimplemented support for `refines`");
                        }
                        Ok(Case {
                            name: name.to_string(),
                            ty: match &case.ty {
                                Some(ty) => Some(self.convert_valtype(ty)?),
                                None => None,
                            },
                            docs: Default::default(),
                        })
                    })
                    .collect::<Result<_>>()?;
                Ok(TypeDefKind::Variant(Variant { cases }))
            }

            types::ComponentDefinedType::Flags(f) => {
                let flags = f
                    .iter()
                    .map(|name| Flag {
                        name: name.to_string(),
                        docs: Default::default(),
                    })
                    .collect();
                Ok(TypeDefKind::Flags(Flags { flags }))
            }

            types::ComponentDefinedType::Enum(e) => {
                let cases = e
                    .iter()
                    .cloned()
                    .map(|name| EnumCase {
                        name: name.into(),
                        docs: Default::default(),
                    })
                    .collect();
                Ok(TypeDefKind::Enum(Enum { cases }))
            }

            types::ComponentDefinedType::Own(id) => {
                let id = self.type_map[&(*id).into()];
                Ok(TypeDefKind::Handle(Handle::Own(id)))
            }

            types::ComponentDefinedType::Borrow(id) => {
                let id = self.type_map[&(*id).into()];
                Ok(TypeDefKind::Handle(Handle::Borrow(id)))
            }
        }
    }

    fn convert_primitive(&self, ty: PrimitiveValType) -> Type {
        match ty {
            PrimitiveValType::U8 => Type::U8,
            PrimitiveValType::S8 => Type::S8,
            PrimitiveValType::U16 => Type::U16,
            PrimitiveValType::S16 => Type::S16,
            PrimitiveValType::U32 => Type::U32,
            PrimitiveValType::S32 => Type::S32,
            PrimitiveValType::U64 => Type::U64,
            PrimitiveValType::S64 => Type::S64,
            PrimitiveValType::Bool => Type::Bool,
            PrimitiveValType::Char => Type::Char,
            PrimitiveValType::String => Type::String,
            PrimitiveValType::Float32 => Type::Float32,
            PrimitiveValType::Float64 => Type::Float64,
        }
    }

    fn register_defined(&mut self, id: TypeId, def: &types::ComponentDefinedType) -> Result<()> {
        Registrar {
            types: &self.types,
            type_map: &mut self.type_map,
            resolve: &self.resolve,
        }
        .defined(id, def)
    }

    /// Completes the decoding of this resolve by finalizing all packages into
    /// their topological ordering within the returned `Resolve`.
    ///
    /// Takes the root package as an argument to insert.
    fn finish(mut self, package: Package) -> (Resolve, PackageId) {
        // Build a topological ordering is then calculated by visiting all the
        // transitive dependencies of packages.
        let mut order = IndexSet::new();
        for i in 0..self.foreign_packages.len() {
            self.visit_package(i, &mut order);
        }

        // Using the topological ordering create a temporary map from
        // index-in-`foreign_packages` to index-in-`order`
        let mut idx_to_pos = vec![0; self.foreign_packages.len()];
        for (pos, idx) in order.iter().enumerate() {
            idx_to_pos[*idx] = pos;
        }
        // .. and then using `idx_to_pos` sort the `foreign_packages` array based
        // on the position it's at in the topological ordering
        let mut deps = mem::take(&mut self.foreign_packages)
            .into_iter()
            .enumerate()
            .collect::<Vec<_>>();
        deps.sort_by_key(|(idx, _)| idx_to_pos[*idx]);

        // .. and finally insert the packages, in their final topological
        // ordering, into the returned array.
        for (_idx, (_url, pkg)) in deps {
            self.insert_package(pkg);
        }

        let id = self.insert_package(package);
        assert!(self.resolve.worlds.iter().all(|(_, w)| w.package.is_some()));
        assert!(self
            .resolve
            .interfaces
            .iter()
            .all(|(_, i)| i.package.is_some()));
        (self.resolve, id)
    }

    fn insert_package(&mut self, package: Package) -> PackageId {
        let Package {
            name,
            interfaces,
            worlds,
            docs,
        } = package;

        // Most of the time the `package` being inserted is not already present
        // in `self.resolve`, but in the case of the top-level `decode_world`
        // function this isn't the case. This shouldn't in general be a problem
        // so union-up the packages here while asserting that nothing gets
        // replaced by accident which would indicate a bug.
        let pkg = self
            .resolve
            .package_names
            .get(&name)
            .copied()
            .unwrap_or_else(|| {
                let id = self.resolve.packages.alloc(Package {
                    name: name.clone(),
                    interfaces: Default::default(),
                    worlds: Default::default(),
                    docs,
                });
                let prev = self.resolve.package_names.insert(name, id);
                assert!(prev.is_none());
                id
            });

        for (name, id) in interfaces {
            let prev = self.resolve.packages[pkg].interfaces.insert(name, id);
            assert!(prev.is_none());
            self.resolve.interfaces[id].package = Some(pkg);
        }

        for (name, id) in worlds {
            let prev = self.resolve.packages[pkg].worlds.insert(name, id);
            assert!(prev.is_none());
            let world = &mut self.resolve.worlds[id];
            world.package = Some(pkg);
            for (name, item) in world.imports.iter().chain(world.exports.iter()) {
                if let WorldKey::Name(_) = name {
                    if let WorldItem::Interface(iface) = item {
                        self.resolve.interfaces[*iface].package = Some(pkg);
                    }
                }
            }
        }

        pkg
    }

    fn visit_package(&self, idx: usize, order: &mut IndexSet<usize>) {
        if order.contains(&idx) {
            return;
        }

        let (_name, pkg) = self.foreign_packages.get_index(idx).unwrap();
        let interfaces = pkg.interfaces.values().copied().chain(
            pkg.worlds
                .values()
                .flat_map(|w| {
                    let world = &self.resolve.worlds[*w];
                    world.imports.values().chain(world.exports.values())
                })
                .filter_map(|item| match item {
                    WorldItem::Interface(id) => Some(*id),
                    WorldItem::Function(_) | WorldItem::Type(_) => None,
                }),
        );
        for iface in interfaces {
            for dep in self.resolve.interface_direct_deps(iface) {
                let dep_idx = self.iface_to_package_index[&dep];
                if dep_idx != idx {
                    self.visit_package(dep_idx, order);
                }
            }
        }

        assert!(order.insert(idx));
    }
}

/// Helper type to register the structure of a wasm-defined type against a
/// wit-defined type.
struct Registrar<'a> {
    types: &'a types::Types,
    type_map: &'a mut HashMap<types::ComponentAnyTypeId, TypeId>,
    resolve: &'a Resolve,
}

impl Registrar<'_> {
    /// Verifies that the wasm structure of `def` matches the wit structure of
    /// `id` and recursively registers types.
    fn defined(&mut self, id: TypeId, def: &types::ComponentDefinedType) -> Result<()> {
        match def {
            types::ComponentDefinedType::Primitive(_) => Ok(()),

            types::ComponentDefinedType::List(t) => {
                let ty = match &self.resolve.types[id].kind {
                    TypeDefKind::List(r) => r,
                    // Note that all cases below have this match and the general
                    // idea is that once a type is named or otherwise identified
                    // here there's no need to recurse. The purpose of this
                    // registrar is to build connections for anonymous types
                    // that don't otherwise have a name to ensure that they're
                    // decoded to reuse the same constructs consistently. For
                    // that reason once something is named we can bail out.
                    TypeDefKind::Type(Type::Id(_)) => return Ok(()),
                    _ => bail!("expected a list"),
                };
                self.valtype(t, ty)
            }

            types::ComponentDefinedType::Tuple(t) => {
                let ty = match &self.resolve.types[id].kind {
                    TypeDefKind::Tuple(r) => r,
                    TypeDefKind::Type(Type::Id(_)) => return Ok(()),
                    _ => bail!("expected a tuple"),
                };
                if ty.types.len() != t.types.len() {
                    bail!("mismatched number of tuple fields");
                }
                for (a, b) in t.types.iter().zip(ty.types.iter()) {
                    self.valtype(a, b)?;
                }
                Ok(())
            }

            types::ComponentDefinedType::Option(t) => {
                let ty = match &self.resolve.types[id].kind {
                    TypeDefKind::Option(r) => r,
                    TypeDefKind::Type(Type::Id(_)) => return Ok(()),
                    _ => bail!("expected an option"),
                };
                self.valtype(t, ty)
            }

            types::ComponentDefinedType::Result { ok, err } => {
                let ty = match &self.resolve.types[id].kind {
                    TypeDefKind::Result(r) => r,
                    TypeDefKind::Type(Type::Id(_)) => return Ok(()),
                    _ => bail!("expected a result"),
                };
                match (ok, &ty.ok) {
                    (Some(a), Some(b)) => self.valtype(a, b)?,
                    (None, None) => {}
                    _ => bail!("disagreement on result structure"),
                }
                match (err, &ty.err) {
                    (Some(a), Some(b)) => self.valtype(a, b)?,
                    (None, None) => {}
                    _ => bail!("disagreement on result structure"),
                }
                Ok(())
            }

            types::ComponentDefinedType::Record(def) => {
                let ty = match &self.resolve.types[id].kind {
                    TypeDefKind::Record(r) => r,
                    TypeDefKind::Type(Type::Id(_)) => return Ok(()),
                    _ => bail!("expected a record"),
                };
                if def.fields.len() != ty.fields.len() {
                    bail!("mismatched number of record fields");
                }
                for ((name, ty), field) in def.fields.iter().zip(&ty.fields) {
                    if name.as_str() != field.name {
                        bail!("mismatched field order");
                    }
                    self.valtype(ty, &field.ty)?;
                }
                Ok(())
            }

            types::ComponentDefinedType::Variant(def) => {
                let ty = match &self.resolve.types[id].kind {
                    TypeDefKind::Variant(r) => r,
                    TypeDefKind::Type(Type::Id(_)) => return Ok(()),
                    _ => bail!("expected a variant"),
                };
                if def.cases.len() != ty.cases.len() {
                    bail!("mismatched number of variant cases");
                }
                for ((name, ty), case) in def.cases.iter().zip(&ty.cases) {
                    if name.as_str() != case.name {
                        bail!("mismatched case order");
                    }
                    match (&ty.ty, &case.ty) {
                        (Some(a), Some(b)) => self.valtype(a, b)?,
                        (None, None) => {}
                        _ => bail!("disagreement on case type"),
                    }
                }
                Ok(())
            }

            // These have no recursive structure so they can bail out.
            types::ComponentDefinedType::Flags(_)
            | types::ComponentDefinedType::Enum(_)
            | types::ComponentDefinedType::Own(_)
            | types::ComponentDefinedType::Borrow(_) => Ok(()),
        }
    }

    fn valtype(&mut self, wasm: &types::ComponentValType, wit: &Type) -> Result<()> {
        let wasm = match wasm {
            types::ComponentValType::Type(wasm) => *wasm,
            types::ComponentValType::Primitive(_wasm) => {
                assert!(!matches!(wit, Type::Id(_)));
                return Ok(());
            }
        };
        let wit = match wit {
            Type::Id(id) => *id,
            _ => bail!("expected id-based type"),
        };
        let prev = match self.type_map.insert(wasm.into(), wit) {
            Some(prev) => prev,
            None => {
                let wasm = &self.types[wasm];
                return self.defined(wit, wasm);
            }
        };
        // If `wit` matches `prev` then we've just rediscovered what we already
        // knew which is that the `wasm` id maps to the `wit` id.
        //
        // If, however, `wit` is not equal to `prev` then that's more
        // interesting. Consider a component such as:
        //
        // ```wasm
        // (component
        //   (import (interface "a:b/name") (instance
        //      (type $l (list string))
        //      (type $foo (variant (case "l" $l)))
        //      (export "foo" (type (eq $foo)))
        //   ))
        //   (component $c
        //     (type $l (list string))
        //     (type $bar (variant (case "n" u16) (case "l" $l)))
        //     (export "bar" (type $bar))
        //     (type $foo (variant (case "l" $l)))
        //     (export "foo" (type $foo))
        //   )
        //   (instance $i (instantiate $c))
        //   (export (interface "a:b/name") (instance $i))
        // )
        // ```
        //
        // This roughly corresponds to:
        //
        // ```wit
        // package a:b
        //
        // interface name {
        //   variant bar {
        //     n(u16),
        //     l(list<string>),
        //   }
        //
        //   variant foo {
        //     l(list<string>),
        //   }
        // }
        //
        // world module {
        //   import name
        //   export name
        // }
        // ```
        //
        // In this situation first we'll see the `import` which records type
        // information for the `foo` type in `interface name`. Later on the full
        // picture of `interface name` becomes apparent with the export of a
        // component which has full type information. When walking over this
        // first `bar` is seen and its recursive structure.
        //
        // The problem arises when walking over the `foo` type. In this
        // situation the code path we're currently on will be hit because
        // there's a preexisting definition of `foo` from the import and it's
        // now going to be unified with what we've seen in the export. When
        // visiting the `list<string>` case of the `foo` variant this ends up
        // being different than the `list<string>` used by the `bar` variant. The
        // reason for this is that when visiting `bar` the wasm-defined `(list
        // string)` hasn't been seen before so a new type is allocated. Later
        // though this same wasm type is unified with the first `(list string)`
        // type in the `import`.
        //
        // All-in-all this ends up meaning that it's possible for `prev` to not
        // match `wit`. In this situation it means the decoded WIT interface
        // will have duplicate definitions of `list<string>`. This is,
        // theoretically, not that big of a problem because the same underlying
        // definition is still there and the meaning of the type is the same.
        // This can, however, perhaps be a problem for consumers where it's
        // assumed that all `list<string>` are equal and there's only one. For
        // example a bindings generator for C may assume that `list<string>`
        // will only appear once and generate a single name for it, but with two
        // different types in play here it may generate two types of the same
        // name (or something like that).
        //
        // For now though this is left for a future refactoring. Fixing this
        // issue would require tracking anonymous types during type translation
        // so the decoding process for the `bar` export would reuse the
        // `list<string>` type created from decoding the `foo` import. That's
        // somewhat nontrivial at this time, so it's left for a future
        // refactoring.
        let _ = prev;
        Ok(())
    }
}

pub(crate) trait InterfaceNameExt {
    fn to_package_name(&self) -> PackageName;
}

impl InterfaceNameExt for wasmparser::names::InterfaceName<'_> {
    fn to_package_name(&self) -> PackageName {
        PackageName {
            namespace: self.namespace().to_string(),
            name: self.package().to_string(),
            version: self.version(),
        }
    }
}