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
use anyhow::{anyhow, bail, Context, Result};
use indexmap::IndexMap;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use url::Url;
use wasmparser::{
    types, ComponentExport, ComponentExternalKind, ComponentImport, ComponentTypeRef, Parser,
    Payload, PrimitiveValType, ValidPayload, Validator, WasmFeatures,
};
use wit_parser::*;

/// Represents information about a decoded WebAssembly component.
struct ComponentInfo<'a> {
    /// Wasmparser-defined type information learned after a component is fully
    /// validated.
    types: types::Types,
    /// Map of imports and what type they're importing.
    imports: IndexMap<&'a str, ComponentImport<'a>>,
    /// Map of exports and what they're exporting.
    exports: IndexMap<&'a str, ComponentExport<'a>>,
}

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 {
            component_model: true,
            ..Default::default()
        });
        let mut exports = IndexMap::new();
        let mut imports = IndexMap::new();
        let mut depth = 1;
        let mut types = 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?;
                        let prev = imports.insert(import.name, import);
                        assert!(prev.is_none());
                    }
                }
                Payload::ComponentExportSection(s) if depth == 1 => {
                    for export in s {
                        let export = export?;
                        let prev = exports.insert(export.name, export);
                        assert!(prev.is_none());
                    }
                }
                _ => {}
            }
        }
        Ok(Self {
            types: types.unwrap(),
            imports,
            exports,
        })
    }

    fn is_wit_package(&self) -> bool {
        // wit packages only export component types and must export at least one
        if !self.imports.is_empty() || self.exports.is_empty() {
            return false;
        }

        // all wit package exports must be component types
        self.exports.iter().all(|(_, export)| match export.kind {
            ComponentExternalKind::Type => match self.types.type_at(export.index, false) {
                Some(types::Type::Component(_)) => true,
                _ => false,
            },
            _ => false,
        })
    }

    fn decode_wit_package(&self, name: &str) -> Result<(Resolve, PackageId)> {
        assert!(self.is_wit_package());
        let resolve = Resolve::default();
        let mut decoder = WitPackageDecoder {
            resolve,
            info: self,
            url_to_package: HashMap::default(),
            type_map: HashMap::new(),
            type_src_map: HashMap::new(),
            url_to_interface: HashMap::new(),
        };

        let mut docs = Vec::new();
        for (doc, export) in self.exports.iter() {
            let ty = match self.types.type_at(export.index, false) {
                Some(types::Type::Component(ty)) => ty,
                _ => unreachable!(),
            };
            let id = decoder
                .decode_document(doc, ty)
                .with_context(|| format!("failed to decode document `{doc}`"))?;
            docs.push((doc, id));
        }

        let mut resolve = decoder.resolve;
        let package = resolve.packages.alloc(Package {
            name: name.to_string(),
            documents: docs
                .iter()
                .map(|(name, d)| (name.to_string(), *d))
                .collect(),
            url: None,
        });
        for (_, doc) in docs.iter() {
            resolve.documents[*doc].package = Some(package);
        }

        Ok((resolve, package))
    }

    fn decode_component(&self, name: &str) -> Result<(Resolve, WorldId)> {
        assert!(!self.is_wit_package());
        let mut resolve = Resolve::default();
        let package = resolve.packages.alloc(Package {
            name: name.to_string(),
            documents: Default::default(),
            url: None,
        });
        let doc = resolve.documents.alloc(Document {
            name: "root".to_string(),
            interfaces: Default::default(),
            worlds: Default::default(),
            default_interface: None,
            default_world: None,
            package: Some(package),
        });
        let world = resolve.worlds.alloc(World {
            name: name.to_string(),
            docs: Default::default(),
            imports: Default::default(),
            exports: Default::default(),
            document: doc,
        });
        resolve.documents[doc]
            .worlds
            .insert(name.to_string(), world);
        resolve.documents[doc].default_world = Some(world);
        let mut decoder = WitPackageDecoder {
            resolve,
            info: self,
            url_to_package: HashMap::default(),
            type_map: HashMap::new(),
            type_src_map: HashMap::new(),
            url_to_interface: HashMap::new(),
        };

        for (name, import) in self.imports.iter() {
            let item = match import.ty {
                ComponentTypeRef::Instance(i) => {
                    let ty = match self.types.type_at(i, false) {
                        Some(types::Type::ComponentInstance(ty)) => ty,
                        _ => unreachable!(),
                    };
                    let id = decoder
                        .register_interface(doc, Some(name), ty)
                        .with_context(|| format!("failed to decode WIT from import `{name}`"))?;
                    decoder.resolve.documents[doc]
                        .interfaces
                        .insert(name.to_string(), id);
                    WorldItem::Interface(id)
                }
                ComponentTypeRef::Func(i) => {
                    let ty = match self.types.type_at(i, false) {
                        Some(types::Type::ComponentFunc(ty)) => ty,
                        _ => unreachable!(),
                    };
                    let func = decoder.convert_function(name, ty).with_context(|| {
                        format!("failed to decode function from import `{name}`")
                    })?;
                    WorldItem::Function(func)
                }
                _ => bail!("component import `{name}` was neither a function nor instance"),
            };
            decoder.resolve.worlds[world]
                .imports
                .insert(name.to_string(), item);
        }
        for (name, export) in self.exports.iter() {
            let item = match export.kind {
                ComponentExternalKind::Func => {
                    let ty = self.types.component_function_at(export.index).unwrap();
                    let func = decoder.convert_function(name, ty).with_context(|| {
                        format!("failed to decode function from export `{name}`")
                    })?;

                    WorldItem::Function(func)
                }
                ComponentExternalKind::Instance => {
                    let ty = self.types.component_instance_at(export.index).unwrap();
                    let id = decoder
                        .register_interface(doc, Some(name), ty)
                        .with_context(|| format!("failed to decode WIT from export `{name}`"))?;
                    decoder.resolve.documents[doc]
                        .interfaces
                        .insert(name.to_string(), id);
                    WorldItem::Interface(id)
                }
                _ => bail!("component export `{name}` was neither a function nor instance"),
            };
            decoder.resolve.worlds[world]
                .exports
                .insert(name.to_string(), item);
        }
        Ok((decoder.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) => {
                let doc = resolve.worlds[*world].document;
                resolve.documents[doc].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(name: &str, bytes: &[u8]) -> Result<DecodedWasm> {
    let info = ComponentInfo::new(bytes)?;

    if info.is_wit_package() {
        let (resolve, pkg) = info.decode_wit_package(name)?;
        Ok(DecodedWasm::WitPackage(resolve, pkg))
    } else {
        let (resolve, world) = info.decode_component(name)?;
        Ok(DecodedWasm::Component(resolve, world))
    }
}

struct WitPackageDecoder<'a> {
    resolve: Resolve,
    info: &'a ComponentInfo<'a>,
    url_to_package: HashMap<Url, PackageId>,
    url_to_interface: HashMap<Url, InterfaceId>,

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

    /// A second map, similar to `type_map`, which is keyed off a pointer hash
    /// instead of `TypeId`.
    ///
    /// The purpose of this is to detect when a type is aliased as there will
    /// be two unique `TypeId` structures pointing at the same `types::Type`
    /// structure, so the second layer of map here ensures that types are
    /// only defined once and the second `TypeId` referring to a type will end
    /// up as an alias and/or import.
    type_src_map: HashMap<PtrHash<'a, types::ComponentDefinedType>, TypeId>,
}

impl WitPackageDecoder<'_> {
    fn decode_document(&mut self, name: &str, ty: &types::ComponentType) -> Result<DocumentId> {
        // Process all imports for this document first, where imports are either
        // importing interfaces from previously defined documents or from remote
        // packages. Note that the URL must be specified here for these
        // reconstruction purposes.
        for (name, (url, ty)) in ty.imports.iter() {
            let url = match url {
                Some(url) => url,
                None => bail!("no url specified for import `{name}`"),
            };
            let ty = match ty {
                types::ComponentEntityType::Instance(idx) => {
                    match self.info.types.type_from_id(*idx) {
                        Some(types::Type::ComponentInstance(ty)) => ty,
                        _ => unreachable!(),
                    }
                }
                _ => bail!("import `{name}` is not an instance"),
            };
            self.register_import(url, ty)
                .with_context(|| format!("failed to process import `{name}`"))?;
        }

        let doc = self.resolve.documents.alloc(Document {
            name: name.to_string(),
            interfaces: IndexMap::new(),
            worlds: IndexMap::new(),
            default_interface: None,
            default_world: None,
            package: None,
        });

        for (name, (url, ty)) in ty.exports.iter() {
            match ty {
                types::ComponentEntityType::Instance(idx) => {
                    let ty = match self.info.types.type_from_id(*idx) {
                        Some(types::Type::ComponentInstance(ty)) => ty,
                        _ => unreachable!(),
                    };
                    let id = self
                        .register_interface(doc, Some(name), ty)
                        .with_context(|| format!("failed to process export `{name}`"))?;
                    let prev = self.resolve.documents[doc]
                        .interfaces
                        .insert(name.to_string(), id);
                    assert!(prev.is_none());
                    if let Some(url) = url {
                        let prev = self.url_to_interface.insert(url.clone(), id);
                        assert!(prev.is_none());
                    }
                }
                types::ComponentEntityType::Component(idx) => {
                    let ty = match self.info.types.type_from_id(*idx) {
                        Some(types::Type::Component(ty)) => ty,
                        _ => unreachable!(),
                    };
                    let id = self
                        .register_world(doc, name, ty)
                        .with_context(|| format!("failed to process export `{name}`"))?;
                    let prev = self.resolve.documents[doc]
                        .worlds
                        .insert(name.to_string(), id);
                    assert!(prev.is_none());
                }
                _ => bail!("component export `{name}` is not an instance or component"),
            }
        }
        Ok(doc)
    }

    fn register_import(
        &mut self,
        url: &Url,
        ty: &types::ComponentInstanceType,
    ) -> Result<InterfaceId> {
        let interface = self.extract_url_interface(url)?;

        for (name, export_url, ty) in ty.exports(self.info.types.as_ref()) {
            if export_url.is_some() {
                bail!("instance type export `{name}` should not have a url")
            }

            match ty {
                types::ComponentEntityType::Type {
                    referenced,
                    created,
                } => {
                    let def = match self.info.types.type_from_id(referenced) {
                        Some(types::Type::Defined(ty)) => ty,
                        _ => unreachable!(),
                    };

                    let id = match self.resolve.interfaces[interface].types.get(name.as_str()) {
                        // 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.
                        //
                        // TODO: ideally this would verify that `def` matches
                        // the structure of `id`.
                        Some(id) => *id,

                        // 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 url.scheme() == "pkg" {
                                bail!("instance type export `{name}` not defined in interface");
                            }
                            let kind = match self.type_map.get(&referenced).copied() {
                                Some(id) => TypeDefKind::Type(Type::Id(id)),
                                None => self.convert_defined(def)?,
                            };
                            let id = self.resolve.types.alloc(TypeDef {
                                name: Some(name.to_string()),
                                kind,
                                docs: Default::default(),
                                owner: TypeOwner::Interface(interface),
                            });
                            let prev = self.resolve.interfaces[interface]
                                .types
                                .insert(name.to_string(), id);
                            assert!(prev.is_none());
                            id
                        }
                    };

                    // Register the `types::TypeId` with our resolve `TypeId`
                    // for ensuring type information remains correct throughout
                    // decoding.
                    let prev = self.type_map.insert(created, id);
                    assert!(prev.is_none());
                    self.type_src_map.entry(PtrHash(def)).or_insert(id);
                }

                // 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 = match self.info.types.type_from_id(ty) {
                        Some(types::Type::ComponentFunc(ty)) => ty,
                        _ => unreachable!(),
                    };
                    if self.resolve.interfaces[interface]
                        .functions
                        .contains_key(name.as_str())
                    {
                        // TODO: should ideally verify that function signatures
                        // match.
                        continue;
                    }
                    if url.scheme() == "pkg" {
                        bail!("instance function export `{name}` not defined in interface");
                    }
                    let func = self.convert_function(name, def)?;
                    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 extract_url_interface(&mut self, url: &Url) -> Result<InterfaceId> {
        Ok(if url.scheme() == "pkg" {
            self.url_to_interface
                .get(url)
                .copied()
                .ok_or_else(|| anyhow!("no previously defined interface with url: {url}"))?
        } else {
            self.extract_dep_interface(url)
                .with_context(|| format!("failed to parse url: {url}"))?
        })
    }

    /// TODO: Ideally this function should not need to exist.
    ///
    /// This function parses the `url` provided and requires it to have a
    /// particular structure. That's not really great, however, since otherwise
    /// there's no need to impose structure on the url field of imports/exports.
    ///
    /// Note that this is only used for foreign dependencies of which the binary
    /// encoding does not currently reflect the package/document/interface
    /// organization. Instead foreign dependencies simply have their interfaces
    /// imported, and from this interface import we need to somehow translate
    /// back into a package/document structure as well.
    ///
    /// Resolving this may require changing the binary format for components, or
    /// otherwise encoding more pieces into the binary encoding of a WIT
    /// document. In any case this is "good enough" for now hopefully.
    fn extract_dep_interface(&mut self, url: &Url) -> Result<InterfaceId> {
        // Extract the interface and the document from the url
        let mut segments = url.path_segments().ok_or_else(|| anyhow!("invalid url"))?;
        let interface = segments.next_back().ok_or_else(|| anyhow!("invalid url"))?;
        let document = segments.next_back().ok_or_else(|| anyhow!("invalid url"))?;
        let package_name = segments.next_back().ok_or_else(|| anyhow!("invalid url"))?;

        // Then drop the two path segments from the url as a key to lookup the
        // dependency package by url.
        let mut url = url.clone();
        url.path_segments_mut().unwrap().pop().pop();

        // Lazily create a `Package` as necessary, along with the document and
        // interface.
        let package = *self.url_to_package.entry(url.clone()).or_insert_with(|| {
            self.resolve.packages.alloc(Package {
                name: package_name.to_string(),
                documents: Default::default(),
                url: Some(url.to_string()),
            })
        });
        let doc = *self.resolve.packages[package]
            .documents
            .entry(document.to_string())
            .or_insert_with(|| {
                self.resolve.documents.alloc(Document {
                    name: document.to_string(),
                    interfaces: IndexMap::new(),
                    worlds: IndexMap::new(),
                    default_interface: None,
                    default_world: None,
                    package: Some(package),
                })
            });
        let interface = *self.resolve.documents[doc]
            .interfaces
            .entry(interface.to_string())
            .or_insert_with(|| {
                self.resolve.interfaces.alloc(Interface {
                    name: Some(interface.to_string()),
                    docs: Default::default(),
                    types: IndexMap::default(),
                    functions: IndexMap::new(),
                    document: doc,
                })
            });
        Ok(interface)
    }

    fn register_interface(
        &mut self,
        doc: DocumentId,
        name: Option<&str>,
        ty: &types::ComponentInstanceType,
    ) -> Result<InterfaceId> {
        let mut interface = Interface {
            name: name.map(|n| n.to_string()),
            docs: Default::default(),
            types: IndexMap::default(),
            functions: IndexMap::new(),
            document: doc,
        };

        for (name, export_url, ty) in ty.exports(self.info.types.as_ref()) {
            if export_url.is_some() {
                bail!("instance type export `{name}` should not have a url")
            }

            match ty {
                types::ComponentEntityType::Type {
                    referenced,
                    created,
                } => {
                    let ty = match self.info.types.type_from_id(referenced) {
                        Some(types::Type::Defined(ty)) => ty,
                        _ => unreachable!(),
                    };
                    let key = PtrHash(ty);

                    // Note that first the `type_map` is consulted for the
                    // referenced type id here, meaning if this is a reexport of
                    // another type in this interface then we're guaranteed to
                    // get that precise link.
                    //
                    // Failing that, though, the `type_src_map` is consulted to
                    // find the item, if present, from an alias of an import or
                    // other export, representing a cross-interface `use`.
                    let (kind, insert_src) = match self
                        .type_map
                        .get(&referenced)
                        .or_else(|| self.type_src_map.get(&key))
                    {
                        // If this `TypeId` points to a type which has
                        // previously been defined, meaning we're aliasing a
                        // prior definition.
                        Some(prev) => (TypeDefKind::Type(Type::Id(*prev)), false),

                        // ... or this `TypeId`'s source definition has never
                        // been seen before, so declare the full type.
                        None => {
                            let ty = self
                                .convert_defined(ty)
                                .with_context(|| format!("failed to decode type `{name}`"))?;
                            (ty, true)
                        }
                    };
                    let ty = self.resolve.types.alloc(TypeDef {
                        docs: Default::default(),
                        kind,
                        name: Some(name.to_string()),
                        owner: TypeOwner::Interface(self.resolve.interfaces.next_id()),
                    });

                    if insert_src {
                        let prev = self.type_src_map.insert(key, ty);
                        assert!(prev.is_none());
                    }
                    let prev = self.type_map.insert(created, ty);
                    assert!(prev.is_none());
                    let prev = interface.types.insert(name.to_string(), ty);
                    assert!(prev.is_none());
                }

                types::ComponentEntityType::Func(ty) => {
                    let ty = match self.info.types.type_from_id(ty) {
                        Some(types::Type::ComponentFunc(ty)) => ty,
                        _ => unreachable!(),
                    };
                    let func = self.convert_function(&name, ty)?;
                    let prev = interface.functions.insert(name.to_string(), func);
                    assert!(prev.is_none());
                }
                _ => bail!("instance type export `{name}` is not a type or function"),
            };
        }
        Ok(self.resolve.interfaces.alloc(interface))
    }

    fn register_world(
        &mut self,
        document: DocumentId,
        name: &str,
        ty: &types::ComponentType,
    ) -> Result<WorldId> {
        let mut world = World {
            name: name.to_string(),
            docs: Default::default(),
            imports: Default::default(),
            exports: Default::default(),
            document,
        };

        // Imports in this component type represent all of the imported items
        // into the world itself, so all imports get registered.
        for (name, (url, ty)) in ty.imports.iter() {
            let item = match ty {
                types::ComponentEntityType::Instance(idx) => {
                    let ty = match self.info.types.type_from_id(*idx) {
                        Some(types::Type::ComponentInstance(ty)) => ty,
                        _ => unreachable!(),
                    };
                    let id = match url {
                        // If a URL is specified then the import is either to a
                        // package-local or foreign interface, and both
                        // situations are handled in `register_import`.
                        Some(url) => self.register_import(url, ty)?,

                        // Without a URL this indicates an inline interface that
                        // wasn't declared explicitly elsewhere with a name, and
                        // `register_interface` will create a new `Interface`
                        // with no name.
                        None => self.register_interface(document, None, ty)?,
                    };
                    WorldItem::Interface(id)
                }

                types::ComponentEntityType::Func(idx) => {
                    let ty = match self.info.types.type_from_id(*idx) {
                        Some(types::Type::ComponentFunc(ty)) => ty,
                        _ => unreachable!(),
                    };
                    let func = self.convert_function(name, ty)?;
                    WorldItem::Function(func)
                }

                _ => bail!("component import `{name}` is not an instance or function"),
            };
            world.imports.insert(name.to_string(), item);
        }

        for (name, (url, ty)) in ty.exports.iter() {
            let item = match ty {
                types::ComponentEntityType::Instance(idx) => {
                    let ty = match self.info.types.type_from_id(*idx) {
                        Some(types::Type::ComponentInstance(ty)) => ty,
                        _ => unreachable!(),
                    };
                    let id = match url {
                        // 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.
                        Some(url) => self.register_import(url, ty)?,
                        None => self.register_interface(document, None, ty)?,
                    };
                    WorldItem::Interface(id)
                }

                types::ComponentEntityType::Func(idx) => {
                    let ty = match self.info.types.type_from_id(*idx) {
                        Some(types::Type::ComponentFunc(ty)) => ty,
                        _ => unreachable!(),
                    };
                    let func = self.convert_function(name, ty)?;
                    WorldItem::Function(func)
                }

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

    fn convert_function(&mut self, name: &str, ty: &types::ComponentFuncType) -> Result<Function> {
        let params = ty
            .params
            .iter()
            .map(|(name, ty)| Ok((name.to_string(), self.convert_valtype(ty)?)))
            .collect::<Result<Vec<_>>>()?;
        let results = if ty.results.len() == 1 && ty.results[0].0.is_none() {
            Results::Anon(self.convert_valtype(&ty.results[0].1)?)
        } else {
            Results::Named(
                ty.results
                    .iter()
                    .map(|(name, ty)| {
                        Ok((
                            name.as_ref().unwrap().to_string(),
                            self.convert_valtype(ty)?,
                        ))
                    })
                    .collect::<Result<Vec<_>>>()?,
            )
        };
        Ok(Function {
            docs: Default::default(),
            kind: FunctionKind::Freestanding,
            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) {
            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 ty = match self.info.types.type_from_id(id) {
            Some(types::Type::Defined(ty)) => ty,
            _ => unreachable!(),
        };
        let kind = self.convert_defined(ty)?;
        match &kind {
            TypeDefKind::Type(_)
            | TypeDefKind::List(_)
            | TypeDefKind::Tuple(_)
            | TypeDefKind::Option(_)
            | TypeDefKind::Result(_) => {}

            TypeDefKind::Record(_)
            | TypeDefKind::Enum(_)
            | TypeDefKind::Variant(_)
            | TypeDefKind::Union(_)
            | TypeDefKind::Flags(_)
            | TypeDefKind::Future(_)
            | TypeDefKind::Stream(_) => {
                bail!("unexpected unnamed type");
            }
            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, 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)?,
                            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::Union(u) => {
                let cases = u
                    .types
                    .iter()
                    .map(|ty| {
                        Ok(UnionCase {
                            ty: self.convert_valtype(ty)?,
                            docs: Default::default(),
                        })
                    })
                    .collect::<Result<_>>()?;
                Ok(TypeDefKind::Union(Union { cases }))
            }

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

    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,
        }
    }
}

struct PtrHash<'a, T>(&'a T);

impl<T> PartialEq for PtrHash<'_, T> {
    fn eq(&self, other: &Self) -> bool {
        std::ptr::eq(self.0, other.0)
    }
}

impl<T> Eq for PtrHash<'_, T> {}

impl<T> Hash for PtrHash<'_, T> {
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        std::ptr::hash(self.0, hasher)
    }
}