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
use crate::{
    CoreExtern, CoreFuncType, DefinedType, Enum, Flags, FuncResult, FuncType, FuncTypeId,
    Interface, InterfaceId, ItemKind, ModuleType, ModuleTypeId, Record, Resource, ResourceAlias,
    ResourceId, Type, Types, UsedType, ValueType, Variant, World, WorldId,
};
use anyhow::{bail, Context, Result};
use indexmap::IndexMap;
use semver::Version;
use std::borrow::Borrow;
use std::fmt;
use std::{collections::HashMap, path::Path, rc::Rc};
use wasmparser::{
    names::{ComponentName, ComponentNameKind},
    types::{self as wasm, ComponentAnyTypeId},
    Chunk, Encoding, Parser, Payload, ValidPayload, Validator, WasmFeatures,
};

/// Represents a package key that can be used in associative containers.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct PackageKey {
    /// The name of the package,
    name: String,
    /// The version of the package.
    version: Option<Version>,
}

impl PackageKey {
    /// Constructs a new package key from the given package reference.
    pub fn new(package: &Package) -> Self {
        Self {
            name: package.name.clone(),
            version: package.version.clone(),
        }
    }

    /// Gets the name of the package.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Gets the version of the package.
    pub fn version(&self) -> Option<&Version> {
        self.version.as_ref()
    }
}

impl fmt::Display for PackageKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{name}", name = self.name)?;
        if let Some(version) = &self.version {
            write!(f, "@{version}")?;
        }

        Ok(())
    }
}

/// A borrowed package key.
#[derive(Copy, Clone, Hash, PartialEq, Eq)]
pub struct BorrowedPackageKey<'a> {
    /// The package name.
    pub name: &'a str,
    /// The optional package version.
    pub version: Option<&'a Version>,
}

impl<'a> BorrowedPackageKey<'a> {
    /// Constructs a new borrowed package key from the given package reference.
    pub fn new(package: &'a Package) -> Self {
        Self {
            name: &package.name,
            version: package.version.as_ref(),
        }
    }

    /// Constructs a new borrowed package key from the given name and version.
    pub fn from_name_and_version(name: &'a str, version: Option<&'a Version>) -> Self {
        Self { name, version }
    }

    /// Converts the borrowed package key into an owned package key.
    pub fn into_owned(self) -> PackageKey {
        PackageKey {
            name: self.name.to_owned(),
            version: self.version.cloned(),
        }
    }
}

impl fmt::Display for BorrowedPackageKey<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{name}", name = self.name)?;
        if let Some(version) = self.version {
            write!(f, "@{version}")?;
        }

        Ok(())
    }
}

/// A trait implemented by types that can be borrowed as a package key.
pub trait BorrowedKey {
    /// Borrows the key as a borrowed package key.
    fn borrowed_key(&self) -> BorrowedPackageKey;
}

impl BorrowedKey for PackageKey {
    fn borrowed_key(&self) -> BorrowedPackageKey {
        BorrowedPackageKey {
            name: &self.name,
            version: self.version.as_ref(),
        }
    }
}

impl BorrowedKey for BorrowedPackageKey<'_> {
    fn borrowed_key(&self) -> BorrowedPackageKey {
        *self
    }
}

impl<'a> Borrow<dyn BorrowedKey + 'a> for PackageKey {
    fn borrow(&self) -> &(dyn BorrowedKey + 'a) {
        self
    }
}

impl Eq for (dyn BorrowedKey + '_) {}

impl PartialEq for (dyn BorrowedKey + '_) {
    fn eq(&self, other: &dyn BorrowedKey) -> bool {
        self.borrowed_key().eq(&other.borrowed_key())
    }
}

impl<'a> std::hash::Hash for (dyn BorrowedKey + 'a) {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.borrowed_key().hash(state)
    }
}

/// Represents a WebAssembly component model package.
///
/// A package is a binary-encoded WebAssembly component.
#[derive(Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct Package {
    /// The package name.
    name: String,
    /// The package version.
    version: Option<Version>,
    /// The bytes of the package.
    ///
    /// The bytes are a binary-encoded WebAssembly component.
    #[cfg_attr(feature = "serde", serde(skip))]
    bytes: Vec<u8>,
    /// The type of the represented component.
    ty: WorldId,
    /// The type resulting from instantiating the component.
    instance_type: InterfaceId,
    /// Defined interfaces and worlds (from a WIT package).
    definitions: IndexMap<String, ItemKind>,
}

impl Package {
    /// Gets the package key for the package.
    pub fn key(&self) -> BorrowedPackageKey {
        BorrowedPackageKey::new(self)
    }

    /// Creates a new package from the given file path.
    ///
    /// The package will populate its types into the provided type collection.
    pub fn from_file(
        name: &str,
        version: Option<&Version>,
        path: impl AsRef<Path>,
        types: &mut Types,
    ) -> Result<Self> {
        let path = path.as_ref();
        let bytes = std::fs::read(path)
            .with_context(|| format!("failed to read `{path}`", path = path.display()))?;
        Self::from_bytes(name, version, bytes, types)
    }

    /// Creates a new package from the given bytes.
    ///
    /// The package will populate its types into the provided type collection.
    pub fn from_bytes(
        name: &str,
        version: Option<&Version>,
        bytes: impl Into<Vec<u8>>,
        types: &mut Types,
    ) -> Result<Self> {
        let bytes = bytes.into();
        if !Parser::is_component(&bytes) {
            bail!("package `{name}` is not a binary-encoded WebAssembly component");
        }

        let mut parser = Parser::new(0);
        let mut parsers = Vec::new();
        let mut validator = Validator::new_with_features(WasmFeatures {
            component_model: true,
            ..Default::default()
        });
        let mut imports = Vec::new();
        let mut exports = Vec::new();

        let mut cur = bytes.as_ref();
        loop {
            match parser.parse(cur, true)? {
                Chunk::Parsed { payload, consumed } => {
                    cur = &cur[consumed..];

                    match validator.payload(&payload)? {
                        ValidPayload::Ok => {
                            // Don't parse any sub-components or sub-modules
                            if !parsers.is_empty() {
                                continue;
                            }

                            match payload {
                                Payload::Version { encoding, .. } => {
                                    assert_eq!(encoding, Encoding::Component);
                                }
                                Payload::ComponentImportSection(s) => {
                                    imports.reserve(s.count() as usize);
                                    for import in s {
                                        imports.push(import?.name.0);
                                    }
                                }
                                Payload::ComponentExportSection(s) => {
                                    exports.reserve(s.count() as usize);
                                    for export in s {
                                        exports.push(export?.name.0);
                                    }
                                }
                                _ => {}
                            }
                        }
                        ValidPayload::Func(_, _) => {}
                        ValidPayload::Parser(next) => {
                            parsers.push(parser);
                            parser = next;
                        }
                        ValidPayload::End(wasm_types) => match parsers.pop() {
                            Some(parent) => parser = parent,
                            None => {
                                let mut converter = TypeConverter::new(types, wasm_types);

                                let imports = imports
                                    .into_iter()
                                    .map(|i| Ok((i.to_string(), converter.import(i)?)))
                                    .collect::<Result<_>>()?;

                                let exports: IndexMap<String, ItemKind> = exports
                                    .into_iter()
                                    .map(|i| Ok((i.to_string(), converter.export(i)?)))
                                    .collect::<Result<_>>()?;

                                let ty = types.add_world(World {
                                    id: None,
                                    uses: Default::default(),
                                    imports,
                                    exports: exports.clone(),
                                });

                                let instance_type = types.add_interface(Interface {
                                    id: None,
                                    uses: Default::default(),
                                    exports,
                                });

                                let definitions = Self::find_definitions(types, ty);

                                return Ok(Self {
                                    name: name.to_owned(),
                                    version: version.map(ToOwned::to_owned),
                                    bytes,
                                    ty,
                                    instance_type,
                                    definitions,
                                });
                            }
                        },
                    }
                }
                Chunk::NeedMoreData(_) => panic!("all data should be present"),
            }
        }
    }

    /// Gets the name of the package.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Gets the version of the package.
    pub fn version(&self) -> Option<&Version> {
        self.version.as_ref()
    }

    /// Gets the bytes of the package.
    ///
    /// The bytes are a binary-encoded WebAssembly component.
    pub fn bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Gets the id of the world (i.e. component type) of the package.
    pub fn ty(&self) -> WorldId {
        self.ty
    }

    /// Gets the id of the interface (i.e. instance type) that would
    /// result from instantiating the package.
    pub fn instance_type(&self) -> InterfaceId {
        self.instance_type
    }

    /// Gets the interfaces and worlds defined in this package.
    pub fn definitions(&self) -> &IndexMap<String, ItemKind> {
        &self.definitions
    }

    fn find_definitions(types: &Types, world: WorldId) -> IndexMap<String, ItemKind> {
        // Look for any component type exports that export a component type or instance type
        let exports = &types[world].exports;
        let mut defs = IndexMap::new();
        for (name, kind) in exports {
            if let ItemKind::Type(Type::World(id)) = kind {
                let world = &types[*id];
                if world.exports.len() != 1 {
                    continue;
                }

                // Check if the export name is an interface name
                let (export_name, kind) = world.exports.get_index(0).unwrap();
                match ComponentName::new(export_name, 0).unwrap().kind() {
                    ComponentNameKind::Interface(_) => {}
                    _ => continue,
                }

                match kind {
                    ItemKind::Instance(id) => {
                        defs.insert(name.clone(), ItemKind::Type(Type::Interface(*id)));
                    }
                    ItemKind::Component(id) => {
                        defs.insert(name.clone(), ItemKind::Type(Type::World(*id)));
                    }
                    _ => continue,
                }
            }
        }

        defs
    }
}

impl fmt::Debug for Package {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Package")
            .field("name", &self.name)
            .field("version", &self.version)
            .field("bytes", &"...")
            .field("ty", &self.ty)
            .field("instance_type", &self.instance_type)
            .field("definitions", &self.definitions)
            .finish()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Owner {
    /// The owner is an interface.
    Interface(InterfaceId),
    /// The owner is a world.
    World(WorldId),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum Entity {
    /// The entity is a type.
    Type(Type),
    /// The entity is a resource.
    Resource(ResourceId),
}

/// Responsible for converting between wasmparser and wac-parser type
/// representations.
struct TypeConverter<'a> {
    types: &'a mut Types,
    wasm_types: Rc<wasm::Types>,
    cache: HashMap<wasm::AnyTypeId, Entity>,
    resource_map: HashMap<wasm::ResourceId, ResourceId>,
    owners: HashMap<wasm::ComponentAnyTypeId, (Owner, String)>,
}

impl<'a> TypeConverter<'a> {
    fn new(types: &'a mut Types, wasm_types: wasm::Types) -> Self {
        Self {
            types,
            wasm_types: Rc::new(wasm_types),
            cache: Default::default(),
            resource_map: Default::default(),
            owners: Default::default(),
        }
    }

    fn import(&mut self, name: &str) -> Result<ItemKind> {
        let import = self
            .wasm_types
            .component_entity_type_of_import(name)
            .unwrap();
        self.entity(name, import)
    }

    fn export(&mut self, name: &str) -> Result<ItemKind> {
        let export = self
            .wasm_types
            .component_entity_type_of_export(name)
            .unwrap();
        self.entity(name, export)
    }

    fn component_func_type(&mut self, id: wasm::ComponentFuncTypeId) -> Result<FuncTypeId> {
        let key = wasm::AnyTypeId::Component(wasm::ComponentAnyTypeId::Func(id));
        if let Some(ty) = self.cache.get(&key) {
            match ty {
                Entity::Type(Type::Func(id)) => return Ok(*id),
                _ => panic!("invalid cached type"),
            }
        }

        let wasm_types = self.wasm_types.clone();
        let func_ty = &wasm_types[id];
        let params = func_ty
            .params
            .iter()
            .map(|(name, ty)| Ok((name.to_string(), self.component_val_type(*ty)?)))
            .collect::<Result<_>>()?;

        let results = if func_ty.results.len() == 0 {
            None
        } else if func_ty.results.len() == 1 && func_ty.results[0].0.is_none() {
            Some(FuncResult::Scalar(
                self.component_val_type(func_ty.results[0].1)?,
            ))
        } else {
            Some(FuncResult::List(
                func_ty
                    .results
                    .iter()
                    .map(|(name, ty)| {
                        Ok((
                            name.as_ref().unwrap().to_string(),
                            self.component_val_type(*ty)?,
                        ))
                    })
                    .collect::<Result<_>>()?,
            ))
        };

        let id = self.types.add_func_type(FuncType { params, results });
        self.cache.insert(key, Entity::Type(Type::Func(id)));
        Ok(id)
    }

    fn module_type(&mut self, id: wasm::ComponentCoreModuleTypeId) -> Result<ModuleTypeId> {
        let key = wasm::AnyTypeId::Core(wasm::ComponentCoreTypeId::Module(id));
        if let Some(ty) = self.cache.get(&key) {
            match ty {
                Entity::Type(Type::Module(id)) => return Ok(*id),
                _ => panic!("invalid cached type"),
            }
        }

        let module_ty = &self.wasm_types[id];

        let imports = module_ty
            .imports
            .iter()
            .map(|((module, name), ty)| ((module.clone(), name.clone()), self.entity_type(*ty)))
            .collect();

        let exports = module_ty
            .exports
            .iter()
            .map(|(name, ty)| (name.clone(), self.entity_type(*ty)))
            .collect();

        let module_id = self.types.add_module_type(ModuleType { imports, exports });
        self.cache
            .insert(key, Entity::Type(Type::Module(module_id)));
        Ok(module_id)
    }

    fn ty(&mut self, name: &str, id: wasm::ComponentAnyTypeId) -> Result<Type> {
        match id {
            wasm::ComponentAnyTypeId::Defined(id) => {
                Ok(Type::Value(self.component_defined_type(id)?))
            }
            wasm::ComponentAnyTypeId::Func(id) => Ok(Type::Func(self.component_func_type(id)?)),
            wasm::ComponentAnyTypeId::Component(id) => {
                Ok(Type::World(self.component_type(None, id)?))
            }
            wasm::ComponentAnyTypeId::Instance(id) => {
                Ok(Type::Interface(self.component_instance_type(None, id)?))
            }
            wasm::ComponentAnyTypeId::Resource(id) => Ok(Type::Resource(self.resource(name, id))),
        }
    }

    fn component_val_type(&mut self, ty: wasm::ComponentValType) -> Result<ValueType> {
        match ty {
            wasm::ComponentValType::Primitive(ty) => Ok(ValueType::Primitive(ty.into())),
            wasm::ComponentValType::Type(id) => Ok(self.component_defined_type(id)?),
        }
    }

    fn component_instance_type(
        &mut self,
        name: Option<&str>,
        id: wasm::ComponentInstanceTypeId,
    ) -> Result<InterfaceId> {
        let key = wasm::AnyTypeId::Component(wasm::ComponentAnyTypeId::Instance(id));
        if let Some(ty) = self.cache.get(&key) {
            match ty {
                Entity::Type(Type::Interface(id)) => {
                    return Ok(*id);
                }
                _ => panic!("invalid cached type"),
            }
        }

        let wasm_types = self.wasm_types.clone();
        let instance_ty = &wasm_types[id];
        let id = self.types.add_interface(Interface {
            id: name.and_then(|n| n.contains(':').then(|| n.to_owned())),
            uses: Default::default(),
            exports: IndexMap::with_capacity(instance_ty.exports.len()),
        });

        for (name, ty) in &instance_ty.exports {
            let export = self.entity(name, *ty)?;

            if let wasm::ComponentEntityType::Type {
                referenced,
                created,
            } = ty
            {
                self.use_or_own(Owner::Interface(id), name, *referenced, *created);

                // Prevent self-referential ownership of any aliased resources in this interface
                if let ItemKind::Type(Type::Resource(res)) = export {
                    if let Some(ResourceAlias { owner, .. }) = &mut self.types[res].alias {
                        if let Some(owner_id) = owner {
                            if *owner_id == id {
                                *owner = None;
                            }
                        }
                    }
                }
            }

            let prev = self.types[id].exports.insert(name.clone(), export);
            assert!(prev.is_none());
        }

        self.cache.insert(key, Entity::Type(Type::Interface(id)));
        Ok(id)
    }

    fn entity(&mut self, name: &str, ty: wasm::ComponentEntityType) -> Result<ItemKind> {
        match ty {
            wasm::ComponentEntityType::Module(id) => Ok(ItemKind::Module(self.module_type(id)?)),
            wasm::ComponentEntityType::Value(ty) => {
                Ok(ItemKind::Value(self.component_val_type(ty)?))
            }
            wasm::ComponentEntityType::Type { created, .. } => {
                Ok(ItemKind::Type(self.ty(name, created)?))
            }
            wasm::ComponentEntityType::Func(id) => {
                Ok(ItemKind::Func(self.component_func_type(id)?))
            }
            wasm::ComponentEntityType::Instance(id) => Ok(ItemKind::Instance(
                self.component_instance_type(Some(name), id)?,
            )),
            wasm::ComponentEntityType::Component(id) => {
                Ok(ItemKind::Component(self.component_type(Some(name), id)?))
            }
        }
    }

    fn use_or_own(
        &mut self,
        owner: Owner,
        name: &str,
        referenced: ComponentAnyTypeId,
        created: ComponentAnyTypeId,
    ) {
        if let Some((other, orig)) = self.find_owner(referenced) {
            match *other {
                Owner::Interface(interface) if owner != *other => {
                    let used = UsedType {
                        interface,
                        name: if name != orig {
                            Some(orig.to_string())
                        } else {
                            None
                        },
                    };

                    // Owner is a different interface, so add a using reference
                    let uses = match owner {
                        Owner::Interface(id) => &mut self.types[id].uses,
                        Owner::World(id) => &mut self.types[id].uses,
                    };

                    uses.insert(name.to_string(), used);
                }
                _ => {}
            }
            return;
        }

        // Take ownership of the entity
        let prev = self.owners.insert(created, (owner, name.to_string()));
        assert!(prev.is_none());
    }

    fn component_type(&mut self, name: Option<&str>, id: wasm::ComponentTypeId) -> Result<WorldId> {
        let key = wasm::AnyTypeId::Component(wasm::ComponentAnyTypeId::Component(id));
        if let Some(ty) = self.cache.get(&key) {
            match ty {
                Entity::Type(Type::World(id)) => return Ok(*id),
                _ => panic!("invalid cached type"),
            }
        }

        let wasm_types = self.wasm_types.clone();
        let component_ty = &wasm_types[id];
        let id = self.types.add_world(World {
            id: name.and_then(|n| n.contains(':').then(|| n.to_owned())),
            uses: Default::default(),
            imports: IndexMap::with_capacity(component_ty.imports.len()),
            exports: IndexMap::with_capacity(component_ty.exports.len()),
        });

        for (name, ty) in &component_ty.imports {
            let import = self.entity(name, *ty)?;

            if let wasm::ComponentEntityType::Type {
                referenced,
                created,
            } = ty
            {
                self.use_or_own(Owner::World(id), name, *referenced, *created);
            }

            let prev = self.types[id].imports.insert(name.clone(), import);
            assert!(prev.is_none());
        }

        for (name, ty) in &component_ty.exports {
            let ty = self.entity(name, *ty)?;
            let prev = self.types[id].exports.insert(name.clone(), ty);
            assert!(prev.is_none());
        }

        self.cache.insert(key, Entity::Type(Type::World(id)));
        Ok(id)
    }

    fn component_defined_type(&mut self, id: wasm::ComponentDefinedTypeId) -> Result<ValueType> {
        let key = wasm::AnyTypeId::Component(wasm::ComponentAnyTypeId::Defined(id));
        if let Some(ty) = self.cache.get(&key) {
            match ty {
                Entity::Type(Type::Value(ty)) => return Ok(*ty),
                _ => panic!("invalid cached type"),
            }
        }

        let wasm_types = self.wasm_types.clone();
        let ty = match &wasm_types[id] {
            wasm::ComponentDefinedType::Primitive(ty) => ValueType::Defined(
                self.types
                    .add_defined_type(DefinedType::Alias(ValueType::Primitive((*ty).into()))),
            ),
            wasm::ComponentDefinedType::Record(ty) => {
                let fields = ty
                    .fields
                    .iter()
                    .map(|(name, ty)| Ok((name.as_str().to_owned(), self.component_val_type(*ty)?)))
                    .collect::<Result<_>>()?;

                ValueType::Defined(
                    self.types
                        .add_defined_type(DefinedType::Record(Record { fields })),
                )
            }
            wasm::ComponentDefinedType::Variant(ty) => {
                let cases = ty
                    .cases
                    .iter()
                    .map(|(name, case)| {
                        Ok((
                            name.as_str().to_owned(),
                            case.ty.map(|ty| self.component_val_type(ty)).transpose()?,
                        ))
                    })
                    .collect::<Result<_>>()?;

                ValueType::Defined(
                    self.types
                        .add_defined_type(DefinedType::Variant(Variant { cases })),
                )
            }
            wasm::ComponentDefinedType::List(ty) => {
                let ty = self.component_val_type(*ty)?;
                ValueType::Defined(self.types.add_defined_type(DefinedType::List(ty)))
            }
            wasm::ComponentDefinedType::Tuple(ty) => {
                let types = ty
                    .types
                    .iter()
                    .map(|ty| self.component_val_type(*ty))
                    .collect::<Result<_>>()?;
                ValueType::Defined(self.types.add_defined_type(DefinedType::Tuple(types)))
            }
            wasm::ComponentDefinedType::Flags(flags) => {
                let flags = flags.iter().map(|flag| flag.as_str().to_owned()).collect();
                ValueType::Defined(
                    self.types
                        .add_defined_type(DefinedType::Flags(Flags(flags))),
                )
            }
            wasm::ComponentDefinedType::Enum(cases) => {
                let cases = cases.iter().map(|case| case.as_str().to_owned()).collect();
                ValueType::Defined(self.types.add_defined_type(DefinedType::Enum(Enum(cases))))
            }
            wasm::ComponentDefinedType::Option(ty) => {
                let ty = self.component_val_type(*ty)?;
                ValueType::Defined(self.types.add_defined_type(DefinedType::Option(ty)))
            }
            wasm::ComponentDefinedType::Result { ok, err } => {
                let ok = ok.map(|ty| self.component_val_type(ty)).transpose()?;
                let err = err.map(|ty| self.component_val_type(ty)).transpose()?;
                ValueType::Defined(self.types.add_defined_type(DefinedType::Result { ok, err }))
            }
            wasm::ComponentDefinedType::Borrow(id) => ValueType::Borrow(
                match self.cache.get(&wasm::AnyTypeId::Component(
                    wasm::ComponentAnyTypeId::Resource(*id),
                )) {
                    Some(Entity::Resource(id)) => *id,
                    _ => panic!("expected a resource"),
                },
            ),
            wasm::ComponentDefinedType::Own(id) => ValueType::Own(
                match self.cache.get(&wasm::AnyTypeId::Component(
                    wasm::ComponentAnyTypeId::Resource(*id),
                )) {
                    Some(Entity::Resource(id)) => *id,
                    _ => panic!("expected a resource"),
                },
            ),
        };

        self.cache.insert(key, Entity::Type(Type::Value(ty)));
        Ok(ty)
    }

    fn resource(&mut self, name: &str, id: wasm::AliasableResourceId) -> ResourceId {
        let key = wasm::AnyTypeId::Component(wasm::ComponentAnyTypeId::Resource(id));
        if let Some(ty) = self.cache.get(&key) {
            match ty {
                Entity::Resource(id) => return *id,
                _ => panic!("invalid cached type"),
            }
        }

        // Check if this is an alias of another resource
        if let Some(resource_id) = self.resource_map.get(&id.resource()) {
            let alias_id = self.types.add_resource(Resource {
                name: name.to_owned(),
                alias: Some(ResourceAlias {
                    owner: match self.find_owner(ComponentAnyTypeId::Resource(id)) {
                        Some((Owner::Interface(id), _)) => Some(*id),
                        _ => None,
                    },
                    source: *resource_id,
                }),
            });
            self.cache.insert(key, Entity::Resource(alias_id));
            return alias_id;
        }

        // Otherwise, this is a new resource
        let resource_id = self.types.add_resource(Resource {
            name: name.to_owned(),
            alias: None,
        });

        self.resource_map.insert(id.resource(), resource_id);
        self.cache.insert(key, Entity::Resource(resource_id));
        resource_id
    }

    fn entity_type(&self, ty: wasm::EntityType) -> CoreExtern {
        match ty {
            wasm::EntityType::Func(ty) => CoreExtern::Func(self.func_type(ty)),
            wasm::EntityType::Table(ty) => ty.into(),
            wasm::EntityType::Memory(ty) => ty.into(),
            wasm::EntityType::Global(ty) => ty.into(),
            wasm::EntityType::Tag(ty) => CoreExtern::Tag(self.func_type(ty)),
        }
    }

    fn func_type(&self, ty: wasm::CoreTypeId) -> CoreFuncType {
        let func_ty = self.wasm_types[ty].unwrap_func();
        CoreFuncType {
            params: func_ty.params().iter().copied().map(Into::into).collect(),
            results: func_ty.results().iter().copied().map(Into::into).collect(),
        }
    }

    fn find_owner(&self, mut id: wasm::ComponentAnyTypeId) -> Option<&(Owner, String)> {
        let mut prev = None;
        while prev.is_none() {
            prev = self.owners.get(&id);
            id = match self.wasm_types.peel_alias(id) {
                Some(next) => next,
                None => break,
            };
        }
        prev
    }
}