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
//! Module for WebAssembly composition graphs.
use crate::encoding::{CompositionGraphEncoder, TypeEncoder};
use anyhow::{anyhow, bail, Context, Result};
use indexmap::{IndexMap, IndexSet};
use petgraph::{algo::toposort, graphmap::DiGraphMap, EdgeDirection};
use std::{
    borrow::Cow,
    cell::RefCell,
    collections::{hash_map::Entry, HashMap, HashSet},
    path::{Path, PathBuf},
    sync::atomic::{AtomicUsize, Ordering},
};
use wasmparser::{
    names::ComponentName,
    types::{
        ComponentAnyTypeId, ComponentEntityType, ComponentInstanceTypeId, Remap, Remapping,
        ResourceId, SubtypeCx, Types, TypesRef,
    },
    Chunk, ComponentExternalKind, ComponentTypeRef, Encoding, Parser, Payload, ValidPayload,
    Validator, WasmFeatures,
};

pub(crate) fn type_desc(item: ComponentEntityType) -> &'static str {
    match item {
        ComponentEntityType::Instance(_) => "instance",
        ComponentEntityType::Module(_) => "module",
        ComponentEntityType::Func(_) => "function",
        ComponentEntityType::Value(_) => "value",
        ComponentEntityType::Type { .. } => "type",
        ComponentEntityType::Component(_) => "component",
    }
}

/// Represents a component in a composition graph.
pub struct Component<'a> {
    /// The name of the component.
    pub(crate) name: String,
    /// The path to the component file if parsed via `Component::from_file`.
    pub(crate) path: Option<PathBuf>,
    /// The raw bytes of the component.
    pub(crate) bytes: Cow<'a, [u8]>,
    /// The type information of the component.
    pub(crate) types: Types,
    /// The import map of the component.
    pub(crate) imports: IndexMap<String, ComponentTypeRef>,
    /// The export map of the component.
    pub(crate) exports: IndexMap<String, (ComponentExternalKind, u32)>,
}

impl<'a> Component<'a> {
    /// Constructs a new component from reading the given file.
    pub fn from_file(name: &str, path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref();
        log::info!("parsing WebAssembly component file `{}`", path.display());
        let component = Self::parse(
            ComponentName::new(name, 0)?.to_string(),
            Some(path.to_owned()),
            wat::parse_file(path)
                .with_context(|| {
                    format!("failed to parse component `{path}`", path = path.display())
                })?
                .into(),
        )
        .with_context(|| format!("failed to parse component `{path}`", path = path.display()))?;

        log::debug!(
            "WebAssembly component `{path}` parsed:\n{component:#?}",
            path = path.display()
        );

        Ok(component)
    }

    /// Constructs a new component from the given bytes.
    pub fn from_bytes(name: impl Into<String>, bytes: impl Into<Cow<'a, [u8]>>) -> Result<Self> {
        let mut bytes = bytes.into();

        match wat::parse_bytes(bytes.as_ref()).context("failed to parse component")? {
            Cow::Borrowed(_) => {
                // Original bytes were not modified
            }
            Cow::Owned(v) => bytes = v.into(),
        }

        log::info!("parsing WebAssembly component from bytes");
        let component = Self::parse(
            ComponentName::new(&name.into(), 0)?.to_string(),
            None,
            bytes,
        )
        .context("failed to parse component")?;

        log::debug!("WebAssembly component parsed:\n{component:#?}",);

        Ok(component)
    }

    fn parse(name: String, path: Option<PathBuf>, bytes: Cow<'a, [u8]>) -> Result<Self> {
        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 = IndexMap::new();
        let mut exports = IndexMap::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, .. } => {
                                    if encoding != Encoding::Component {
                                        bail!(
                                            "the {} is not a WebAssembly component",
                                            if path.is_none() { "given data" } else { "file" }
                                        );
                                    }
                                }
                                Payload::ComponentImportSection(s) => {
                                    for import in s {
                                        let import = import?;
                                        let name = import.name.0.to_string();
                                        imports.insert(name, import.ty);
                                    }
                                }
                                Payload::ComponentExportSection(s) => {
                                    for export in s {
                                        let export = export?;
                                        let name = export.name.0.to_string();
                                        exports.insert(name, (export.kind, export.index));
                                    }
                                }
                                _ => {}
                            }
                        }
                        ValidPayload::Func(_, _) => {}
                        ValidPayload::Parser(next) => {
                            parsers.push(parser);
                            parser = next;
                        }
                        ValidPayload::End(types) => match parsers.pop() {
                            Some(parent) => parser = parent,
                            None => {
                                return Ok(Component {
                                    name,
                                    path,
                                    bytes,
                                    types,
                                    imports,
                                    exports,
                                });
                            }
                        },
                    }
                }
                Chunk::NeedMoreData(_) => unreachable!(),
            }
        }
    }

    /// Gets the name of the component.
    ///
    /// Names must be unique within a composition graph.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Gets the path of the component.
    ///
    /// Returns `None` if the component was not loaded from a file.
    pub fn path(&self) -> Option<&Path> {
        self.path.as_deref()
    }

    /// Gets the bytes of the component.
    pub fn bytes(&self) -> &[u8] {
        self.bytes.as_ref()
    }

    /// Gets the type information of the component.
    pub fn types(&self) -> TypesRef {
        self.types.as_ref()
    }

    /// Gets an export from the component for the given export index.
    pub fn export(
        &self,
        index: impl Into<ExportIndex>,
    ) -> Option<(&str, ComponentExternalKind, u32)> {
        let index = index.into();
        self.exports
            .get_index(index.0)
            .map(|(name, (kind, index))| (name.as_str(), *kind, *index))
    }

    /// Gets an export from the component for the given export name.
    pub fn export_by_name(&self, name: &str) -> Option<(ExportIndex, ComponentExternalKind, u32)> {
        self.exports
            .get_full(name)
            .map(|(i, _, (kind, index))| (ExportIndex(i), *kind, *index))
    }

    /// Gets an iterator over the component's exports.
    pub fn exports(
        &self,
    ) -> impl ExactSizeIterator<Item = (ExportIndex, &str, ComponentExternalKind, u32)> {
        self.exports
            .iter()
            .enumerate()
            .map(|(i, (name, (kind, index)))| (ExportIndex(i), name.as_str(), *kind, *index))
    }

    /// Gets an import from the component for the given import index.
    pub fn import(&self, index: impl Into<ImportIndex>) -> Option<(&str, ComponentTypeRef)> {
        let index = index.into();
        self.imports
            .get_index(index.0)
            .map(|(name, ty)| (name.as_str(), *ty))
    }

    /// Gets an import from the component for the given import name.
    pub fn import_by_name(&self, name: &str) -> Option<(ImportIndex, ComponentTypeRef)> {
        self.imports
            .get_full(name)
            .map(|(i, _, ty)| (ImportIndex(i), *ty))
    }

    /// Gets an iterator over the component's imports.
    pub fn imports(&self) -> impl ExactSizeIterator<Item = (ImportIndex, &str, ComponentTypeRef)> {
        self.imports
            .iter()
            .enumerate()
            .map(|(i, (name, ty))| (ImportIndex(i), name.as_str(), *ty))
    }

    pub(crate) fn ty(&self) -> wasm_encoder::ComponentType {
        let encoder = TypeEncoder::new(self);

        encoder.component(
            &mut Default::default(),
            self.imports()
                .map(|(i, ..)| self.import_entity_type(i).unwrap()),
            self.exports()
                .map(|(i, ..)| self.export_entity_type(i).unwrap()),
        )
    }

    pub(crate) fn export_entity_type(
        &self,
        index: ExportIndex,
    ) -> Option<(&str, ComponentEntityType)> {
        let (name, _kind, _index) = self.export(index)?;
        Some((name, self.types.component_entity_type_of_export(name)?))
    }

    pub(crate) fn import_entity_type(
        &self,
        index: ImportIndex,
    ) -> Option<(&str, ComponentEntityType)> {
        let (name, _ty) = self.import(index)?;
        Some((name, self.types.component_entity_type_of_import(name)?))
    }

    /// Finds a compatible instance export on the component for the given instance type.
    pub(crate) fn find_compatible_export(
        &self,
        ty: ComponentInstanceTypeId,
        types: TypesRef,
        export_component_id: ComponentId,
        graph: &CompositionGraph,
    ) -> Option<ExportIndex> {
        self.exports
            .iter()
            .position(|(_, (kind, index))| {
                if *kind != ComponentExternalKind::Instance {
                    return false;
                }

                graph.try_connection(
                    export_component_id,
                    ComponentEntityType::Instance(self.types.component_instance_at(*index)),
                    self.types(),
                    ComponentEntityType::Instance(ty),
                    types,
                )
            })
            .map(ExportIndex)
    }

    /// Checks to see if an instance of this component would be a
    /// subtype of the given instance type.
    pub(crate) fn is_instance_subtype_of(
        &self,
        ty: ComponentInstanceTypeId,
        types: TypesRef,
    ) -> bool {
        let exports = types[ty].exports.iter();

        for (k, b) in exports {
            match self.exports.get_full(k.as_str()) {
                Some((ai, _, _)) => {
                    let (_, a) = self.export_entity_type(ExportIndex(ai)).unwrap();
                    if !ComponentEntityType::is_subtype_of(&a, self.types(), b, types) {
                        return false;
                    }
                }
                None => return false,
            }
        }

        true
    }
}

impl std::fmt::Debug for Component<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.debug_struct("Component")
            .field("imports", &self.imports)
            .field("exports", &self.exports)
            .finish_non_exhaustive()
    }
}

static NEXT_COMPONENT_ID: AtomicUsize = AtomicUsize::new(0);

/// Represents an identifier of a component in a composition graph.
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub struct ComponentId(pub usize);

impl ComponentId {
    fn next() -> Result<Self> {
        let next = NEXT_COMPONENT_ID.fetch_add(1, Ordering::SeqCst);
        if next == usize::MAX {
            bail!("component limit reached");
        }
        Ok(Self(next))
    }
}

impl std::fmt::Display for ComponentId {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<usize> for ComponentId {
    fn from(id: usize) -> Self {
        Self(id)
    }
}

static NEXT_INSTANCE_ID: AtomicUsize = AtomicUsize::new(0);

/// Represents an identifier of an instance in a composition graph.
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub struct InstanceId(pub usize);

impl std::fmt::Display for InstanceId {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl InstanceId {
    fn next() -> Result<Self> {
        let next = NEXT_INSTANCE_ID.fetch_add(1, Ordering::SeqCst);
        if next == usize::MAX {
            bail!("instance limit reached");
        }
        Ok(Self(next))
    }
}

impl From<usize> for InstanceId {
    fn from(id: usize) -> Self {
        Self(id)
    }
}

/// Represents an index into a component's import list.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct ImportIndex(pub usize);

impl std::fmt::Display for ImportIndex {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<usize> for ImportIndex {
    fn from(id: usize) -> Self {
        Self(id)
    }
}

/// Represents an index into a component's export list.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct ExportIndex(pub usize);

impl std::fmt::Display for ExportIndex {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<usize> for ExportIndex {
    fn from(id: usize) -> Self {
        Self(id)
    }
}

#[derive(Debug)]
pub(crate) struct ComponentEntry<'a> {
    pub(crate) component: Component<'a>,
    pub(crate) instances: HashSet<InstanceId>,
}

#[derive(Debug)]
pub(crate) struct Instance {
    pub(crate) component: ComponentId,
    pub(crate) connected: IndexSet<ImportIndex>,
}

/// The options for encoding a composition graph.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Default)]
pub struct EncodeOptions {
    /// Whether or not to define instantiated components.
    ///
    /// If `false`, components will be imported instead.
    pub define_components: bool,

    /// The instance in the graph to export.
    ///
    /// If `Some`, the instance's exports will be aliased and
    /// exported from the resulting component.
    pub export: Option<InstanceId>,

    /// Whether or not to validate the encoded output.
    pub validate: bool,
}

#[derive(Clone, Debug, Default)]
pub(crate) struct ResourceMapping {
    map: im_rc::HashMap<ResourceId, (ComponentId, ResourceId)>,
}

impl ResourceMapping {
    fn add_pairs(
        mut self,
        export_component: ComponentId,
        export_type: ComponentEntityType,
        export_types: TypesRef,
        import_type: ComponentEntityType,
        import_types: TypesRef,
    ) -> Option<Self> {
        if let (
            ComponentEntityType::Instance(export_type),
            ComponentEntityType::Instance(import_type),
        ) = (export_type, import_type)
        {
            let mut exports = HashMap::new();
            for (export_name, ty) in &export_types[export_type].exports {
                // TODO: support nested instances
                if let ComponentEntityType::Type {
                    referenced: ComponentAnyTypeId::Resource(resource_id),
                    ..
                } = ty
                {
                    exports.insert(export_name, (export_component, resource_id.resource()));
                }
            }

            for (export_name, ty) in &import_types[import_type].exports {
                // TODO: support nested instances
                if let ComponentEntityType::Type {
                    referenced: ComponentAnyTypeId::Resource(resource_id),
                    ..
                } = ty
                {
                    let import_resource = resource_id.resource();
                    if let Some((export_component, export_resource)) =
                        exports.get(&export_name).copied()
                    {
                        let value = self
                            .map
                            .get(&export_resource)
                            .copied()
                            .or_else(|| self.map.get(&import_resource).copied())
                            .unwrap_or((export_component, export_resource));

                        if value.1 == export_resource {
                            self.map.insert(export_resource, value);
                            self.map.insert(import_resource, value);
                        } else {
                            // Can't set two different exports equal to each other -- give up.
                            return None;
                        }
                    } else {
                        // Couldn't find an export with a name that matches this
                        // import -- give up.
                        return None;
                    }
                }
            }
        }

        Some(self)
    }

    pub(crate) fn remapping(&self) -> Remapping {
        let mut remapping = Remapping::default();
        for (old, (_, new)) in &self.map {
            if old != new {
                remapping.add(*old, *new)
            }
        }
        remapping
    }
}

/// Represents a composition graph used to compose a new component
/// from other components.
#[derive(Debug, Default)]
pub struct CompositionGraph<'a> {
    names: HashMap<String, ComponentId>,
    pub(crate) components: IndexMap<ComponentId, ComponentEntry<'a>>,
    pub(crate) instances: IndexMap<InstanceId, Instance>,
    // Map where each node is an instance in the graph.
    // An edge between nodes stores a map of target import index to source export index.
    // A source export index of `None` means that the source instance itself is being used.
    pub(crate) graph: DiGraphMap<InstanceId, IndexMap<ImportIndex, Option<ExportIndex>>>,
    pub(crate) resource_mapping: RefCell<ResourceMapping>,
}

impl<'a> CompositionGraph<'a> {
    /// Constructs a new composition graph.
    pub fn new() -> Self {
        Self::default()
    }

    /// Gather any remaining resource imports which have not already been
    /// connected to exports, group them by name, and update the resource
    /// mapping to make all resources within each group equivalent.
    ///
    /// This should be the last step prior to encoding, after all
    /// inter-component connections have been made.  It ensures that each set of
    /// identical imports composed component can be merged into a single import
    /// in the output component.
    pub(crate) fn unify_imported_resources(&self) {
        let mut resource_mapping = self.resource_mapping.borrow_mut();

        let mut resource_imports = HashMap::<_, Vec<_>>::new();
        for (component_id, component) in &self.components {
            let component = &component.component;
            for import_name in component.imports.keys() {
                let ty = component
                    .types
                    .component_entity_type_of_import(import_name)
                    .unwrap();

                if let ComponentEntityType::Instance(instance_id) = ty {
                    for (export_name, ty) in &component.types[instance_id].exports {
                        // TODO: support nested instances
                        if let ComponentEntityType::Type {
                            referenced: ComponentAnyTypeId::Resource(resource_id),
                            ..
                        } = ty
                        {
                            if !resource_mapping.map.contains_key(&resource_id.resource()) {
                                resource_imports
                                    .entry(vec![import_name.to_string(), export_name.to_string()])
                                    .or_default()
                                    .push((*component_id, resource_id.resource()))
                            }
                        }
                    }
                }
            }
        }

        for resources in resource_imports.values() {
            match &resources[..] {
                [] => unreachable!(),
                [_] => {}
                [first, rest @ ..] => {
                    resource_mapping.map.insert(first.1, *first);
                    for resource in rest {
                        resource_mapping.map.insert(resource.1, *first);
                    }
                }
            }
        }
    }

    /// Attempt to connect the specified import to the specified export.
    ///
    /// This will attempt to match up any resource types by name by name and
    /// optimistically produce a remapping that sets identically-named pairs
    /// equal to each other, provided that remapping does not contradict any
    /// previous remappings.  If the import is not a subtype of the export
    /// (either because a consistent remapping could not be created or because
    /// the instances were incompatible for other reasons), we discard the
    /// remapping changes and return `false`.  Otherwise, we store the remapping
    /// changes and return `true`.
    ///
    /// Note that although this method takes a shared reference, it uses
    /// internal mutability to update the remapping.
    pub(crate) fn try_connection(
        &self,
        export_component: ComponentId,
        mut export_type: ComponentEntityType,
        export_types: TypesRef,
        mut import_type: ComponentEntityType,
        import_types: TypesRef,
    ) -> bool {
        let resource_mapping = self.resource_mapping.borrow().clone();

        if let Some(resource_mapping) = resource_mapping.add_pairs(
            export_component,
            export_type,
            export_types,
            import_type,
            import_types,
        ) {
            let remapping = &mut resource_mapping.remapping();
            let mut context = SubtypeCx::new_with_refs(export_types, import_types);

            context
                .a
                .remap_component_entity(&mut export_type, remapping);
            remapping.reset_type_cache();

            context
                .b
                .remap_component_entity(&mut import_type, remapping);
            remapping.reset_type_cache();

            if context
                .component_entity_type(&export_type, &import_type, 0)
                .is_ok()
            {
                *self.resource_mapping.borrow_mut() = resource_mapping;
                true
            } else {
                false
            }
        } else {
            false
        }
    }

    pub(crate) fn remapping_map<'b>(
        &'b self,
    ) -> HashMap<ResourceId, (&'b Component<'a>, ResourceId)> {
        let mut map = HashMap::new();
        for (old, (component, new)) in &self.resource_mapping.borrow().map {
            if old != new {
                let component = &self.components.get(component).unwrap().component;
                map.insert(*old, (component, *new));
            }
        }
        map
    }

    /// Adds a new component to the graph.
    ///
    /// The component name must be unique.
    pub fn add_component(&mut self, component: Component<'a>) -> Result<ComponentId> {
        let id = match self.names.entry(component.name.clone()) {
            Entry::Occupied(e) => {
                bail!(
                    "a component with name `{name}` already exists",
                    name = e.key()
                )
            }
            Entry::Vacant(e) => *e.insert(ComponentId::next()?),
        };

        log::info!(
            "adding WebAssembly component `{name}` ({id}) to the graph",
            name = component.name(),
        );

        let entry = ComponentEntry {
            component,
            instances: HashSet::new(),
        };

        assert!(self.components.insert(id, entry).is_none());

        Ok(id)
    }

    /// Gets a component from the graph.
    pub fn get_component(&self, id: impl Into<ComponentId>) -> Option<&Component<'a>> {
        self.components.get(&id.into()).map(|e| &e.component)
    }

    /// Gets a component from the graph by name.
    pub fn get_component_by_name(&self, name: &str) -> Option<(ComponentId, &Component<'a>)> {
        let id = self.names.get(name)?;
        let entry = &self.components[id];
        Some((*id, &entry.component))
    }

    /// Removes a component from the graph.
    ///
    /// All instances and connections relating to the component
    /// will also be removed.
    pub fn remove_component(&mut self, id: impl Into<ComponentId>) {
        let id = id.into();
        if let Some(entry) = self.components.remove(&id) {
            log::info!(
                "removing WebAssembly component `{name}` ({id}) from the graph",
                name = entry.component.name(),
            );

            assert!(self.names.remove(&entry.component.name).is_some());

            for instance_id in entry.instances.iter().copied() {
                self.instances.remove(&instance_id);

                // Remove any connected indexes from outward edges from the instance being removed
                for (_, target_id, map) in self
                    .graph
                    .edges_directed(instance_id, EdgeDirection::Outgoing)
                {
                    let target = self.instances.get_mut(&target_id).unwrap();
                    for index in map.keys() {
                        target.connected.remove(index);
                    }
                }

                self.graph.remove_node(instance_id);
            }
        }
    }

    /// Creates a new instance of a component in the composition graph.
    pub fn instantiate(&mut self, id: impl Into<ComponentId>) -> Result<InstanceId> {
        let id = id.into();
        let entry = self
            .components
            .get_mut(&id)
            .ok_or_else(|| anyhow!("component does not exist in the graph"))?;

        let instance_id = InstanceId::next()?;

        log::info!(
            "instantiating WebAssembly component `{name}` ({id}) with instance identifier {instance_id}",
            name = entry.component.name(),
        );

        self.instances.insert(
            instance_id,
            Instance {
                component: id,
                connected: Default::default(),
            },
        );

        entry.instances.insert(instance_id);

        Ok(instance_id)
    }

    /// Gets the component of the given instance.
    pub fn get_component_of_instance(
        &self,
        id: impl Into<InstanceId>,
    ) -> Option<(ComponentId, &Component)> {
        let id = id.into();
        let instance = self.instances.get(&id)?;

        Some((
            instance.component,
            self.get_component(instance.component).unwrap(),
        ))
    }

    /// Removes an instance from the graph.
    ///
    /// All connections relating to the instance will also be removed.
    pub fn remove_instance(&mut self, id: impl Into<InstanceId>) {
        let id = id.into();
        if let Some(instance) = self.instances.remove(&id) {
            let entry = self.components.get_mut(&instance.component).unwrap();

            log::info!(
                "removing instance ({id}) of component `{name}` ({cid}) from the graph",
                name = entry.component.name(),
                cid = instance.component.0,
            );

            entry.instances.remove(&id);

            // Remove any connected indexes from outward edges from this instance
            for (_, target, map) in self.graph.edges_directed(id, EdgeDirection::Outgoing) {
                let target = self.instances.get_mut(&target).unwrap();
                for index in map.keys() {
                    target.connected.remove(index);
                }
            }

            self.graph.remove_node(id);
        }
    }

    /// Creates a connection (edge) between instances in the composition graph.
    ///
    /// A connection represents an instantiation argument.
    ///
    /// If `source_export` is `None`, the source instance itself
    /// is used as the instantiation argument.
    pub fn connect(
        &mut self,
        source: impl Into<InstanceId> + Copy,
        source_export: Option<impl Into<ExportIndex> + Copy>,
        target: impl Into<InstanceId> + Copy,
        target_import: impl Into<ImportIndex> + Copy,
    ) -> Result<()> {
        self.validate_connection(source, source_export, target, target_import)?;

        let source = source.into();
        let source_export = source_export.map(Into::into);
        let target = target.into();
        let target_import = target_import.into();

        match source_export {
            Some(export) => log::info!("connecting export {export} of instance {source} to import `{target_import}` of instance {target}"),
            None => log::info!("connecting instance {source} to import {target_import} of instance {target}"),
        }

        self.instances
            .get_mut(&target)
            .unwrap()
            .connected
            .insert(target_import);

        if let Some(map) = self.graph.edge_weight_mut(source, target) {
            assert!(map.insert(target_import, source_export).is_none());
        } else {
            let mut map = IndexMap::new();
            map.insert(target_import, source_export);
            self.graph.add_edge(source, target, map);
        }

        Ok(())
    }

    /// Disconnects a previous connection between instances.
    ///
    /// Requires that the source and target instances are valid.
    ///
    /// If the source and target are not connected via the target's import,
    /// then this is a no-op.
    pub fn disconnect(
        &mut self,
        source: impl Into<InstanceId>,
        target: impl Into<InstanceId>,
        target_import: impl Into<ImportIndex>,
    ) -> Result<()> {
        let source = source.into();
        let target = target.into();
        let target_import = target_import.into();

        log::info!("disconnecting import {target_import} of instance {target}");

        if !self.instances.contains_key(&source) {
            bail!("the source instance does not exist in the graph");
        }

        let target_instance = self
            .instances
            .get_mut(&target)
            .ok_or_else(|| anyhow!("the target instance does not exist in the graph"))?;

        target_instance.connected.remove(&target_import);

        let remove_edge = if let Some(set) = self.graph.edge_weight_mut(source, target) {
            set.remove(&target_import);
            set.is_empty()
        } else {
            false
        };

        if remove_edge {
            self.graph.remove_edge(source, target);
        }

        Ok(())
    }

    /// Validates a connection between two instances in the graph.
    ///
    /// Use `None` for `source_export` to signify that the instance
    /// itself should be the source for the connection.
    ///
    /// Returns `Err(_)` if the connection would not be valid.
    pub fn validate_connection(
        &self,
        source: impl Into<InstanceId>,
        source_export: Option<impl Into<ExportIndex>>,
        target: impl Into<InstanceId>,
        target_import: impl Into<ImportIndex>,
    ) -> Result<()> {
        let source = source.into();
        let source_export = source_export.map(Into::into);
        let target = target.into();
        let target_import = target_import.into();

        if source == target {
            bail!("an instance cannot be connected to itself");
        }

        let source_instance = self
            .instances
            .get(&source)
            .ok_or_else(|| anyhow!("the source instance does not exist in the graph"))?;

        let source_component = &self.components[&source_instance.component].component;

        let target_instance = self
            .instances
            .get(&target)
            .ok_or_else(|| anyhow!("the target instance does not exist in the graph"))?;

        let target_component = &self.components[&target_instance.component].component;
        let (import_name, import_ty) = target_component
            .import_entity_type(target_import)
            .ok_or_else(|| anyhow!("the target import index is invalid"))?;

        if target_instance.connected.contains(&target_import) {
            bail!(
                "{import_ty} import `{import_name}` is already connected",
                import_ty = type_desc(import_ty)
            );
        }

        if let Some(export_index) = source_export {
            let (export_name, export_ty) = source_component
                .export_entity_type(export_index)
                .ok_or_else(|| anyhow!("the source export index is invalid"))?;

            if !self.try_connection(
                source_instance.component,
                export_ty,
                source_component.types(),
                import_ty,
                target_component.types(),
            ) {
                bail!(
                    "source {export_ty} export `{export_name}` is not compatible with target \
                         {import_ty} import `{import_name}`",
                    export_ty = type_desc(export_ty),
                    import_ty = type_desc(import_ty),
                );
            }
        } else {
            let ty = match import_ty {
                ComponentEntityType::Instance(id) => id,
                _ => bail!(
                    "source instance is not compatible with target {import_ty} import `{import_name}`",
                    import_ty = type_desc(import_ty)
                ),
            };

            if !source_component.is_instance_subtype_of(ty, target_component.types()) {
                bail!(
                    "source instance is not compatible with target {import_ty} import `{import_name}`",
                    import_ty = type_desc(import_ty)
                );
            }
        };

        Ok(())
    }

    /// Encodes the current composition graph as a WebAssembly component.
    pub fn encode(&self, options: EncodeOptions) -> Result<Vec<u8>> {
        let bytes = CompositionGraphEncoder::new(options, self).encode()?;

        if options.validate {
            Validator::new_with_features(WasmFeatures {
                component_model: true,
                ..Default::default()
            })
            .validate_all(&bytes)
            .context("failed to validate encoded graph bytes")?;
        }

        Ok(bytes)
    }

    /// Gets the topological instantiation order based on the composition graph.
    ///
    /// If an instance is not in the returned set, it is considered to be
    /// "independent" (i.e it has no dependencies on other instances).
    pub(crate) fn instantiation_order(&self) -> Result<Vec<InstanceId>> {
        toposort(&self.graph, None).map_err(|e| {
            let id = e.node_id();
            let instance = &self.instances[&id];
            anyhow!(
                "an instantiation of component `{name}` and its dependencies form a cycle in the instantiation graph",
                name = self.components[&instance.component].component.name,
            )
        })
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use pretty_assertions::assert_eq;

    #[test]
    fn it_rejects_modules() -> Result<()> {
        match Component::from_bytes("a", b"(module)".as_ref()) {
            Ok(_) => panic!("expected a failure to parse"),
            Err(e) => assert_eq!(
                format!("{e:#}"),
                "failed to parse component: the given data is not a WebAssembly component"
            ),
        }

        Ok(())
    }

    #[test]
    fn it_rejects_invalid_components() -> Result<()> {
        match Component::from_bytes("a", b"(component (export \"x\" (func 0)))".as_ref()) {
            Ok(_) => panic!("expected a failure to parse"),
            Err(e) => assert_eq!(format!("{e:#}"), "failed to parse component: unknown function 0: function index out of bounds (at offset 0xb)"),
        }

        Ok(())
    }

    #[test]
    fn it_ensures_unique_component_names() -> Result<()> {
        let mut graph = CompositionGraph::new();
        graph.add_component(Component::from_bytes("a", b"(component)".as_ref())?)?;

        match graph.add_component(Component::from_bytes("a", b"(component)".as_ref())?) {
            Ok(_) => panic!("expected a failure to add component"),
            Err(e) => assert_eq!(format!("{e:#}"), "a component with name `a` already exists"),
        }

        Ok(())
    }

    #[test]
    fn it_fails_to_instantiate_a_missing_component() -> Result<()> {
        let mut graph = CompositionGraph::new();
        match graph.instantiate(ComponentId(0)) {
            Ok(_) => panic!("expected a failure to instantiate"),
            Err(e) => assert_eq!(format!("{e:#}"), "component does not exist in the graph"),
        }

        Ok(())
    }

    #[test]
    fn it_instantiates_a_component() -> Result<()> {
        let mut graph = CompositionGraph::new();
        let id = graph.add_component(Component::from_bytes("a", b"(component)".as_ref())?)?;
        let id = graph.instantiate(id)?;
        assert_eq!(graph.get_component_of_instance(id).unwrap().1.name(), "a");
        Ok(())
    }

    #[test]
    fn it_cannot_get_a_component_of_missing_instance() -> Result<()> {
        let graph = CompositionGraph::new();
        assert!(graph.get_component_of_instance(InstanceId(0)).is_none());
        Ok(())
    }

    #[test]
    fn it_gets_a_component() -> Result<()> {
        let mut graph = CompositionGraph::new();
        let id = graph.add_component(Component::from_bytes("a", b"(component)".as_ref())?)?;
        assert_eq!(graph.get_component(id).unwrap().name(), "a");
        assert_eq!(graph.get_component_by_name("a").unwrap().1.name(), "a");
        Ok(())
    }

    #[test]
    fn it_removes_a_component() -> Result<()> {
        let mut graph = CompositionGraph::new();
        let a = graph.add_component(Component::from_bytes(
            "a",
            b"(component (import \"x\" (func)))".as_ref(),
        )?)?;
        let b = graph.add_component(Component::from_bytes(
            "b",
            b"(component (import \"x\" (func)) (export \"y\" (func 0)))".as_ref(),
        )?)?;
        let ai = graph.instantiate(a)?;
        let bi = graph.instantiate(b)?;
        graph.connect(bi, Some(0), ai, 0)?;

        assert!(graph.get_component(a).is_some());
        assert!(graph.get_component(b).is_some());
        assert_eq!(graph.components.len(), 2);
        assert_eq!(graph.instances.len(), 2);
        assert_eq!(graph.graph.node_count(), 2);
        assert_eq!(graph.graph.edge_count(), 1);

        graph.remove_component(b);

        assert!(graph.get_component(a).is_some());
        assert!(graph.get_component(b).is_none());
        assert_eq!(graph.components.len(), 1);
        assert_eq!(graph.instances.len(), 1);
        assert_eq!(graph.graph.node_count(), 1);
        assert_eq!(graph.graph.edge_count(), 0);
        Ok(())
    }

    #[test]
    fn it_removes_a_connection() -> Result<()> {
        let mut graph = CompositionGraph::new();
        let a = graph.add_component(Component::from_bytes(
            "a",
            b"(component (import \"x\" (func)))".as_ref(),
        )?)?;
        let b = graph.add_component(Component::from_bytes(
            "b",
            b"(component (import \"x\" (func)) (export \"y\" (func 0)))".as_ref(),
        )?)?;
        let ai = graph.instantiate(a)?;
        let bi = graph.instantiate(b)?;
        graph.connect(bi, Some(0), ai, 0)?;

        assert_eq!(graph.graph.node_count(), 2);
        assert_eq!(graph.graph.edge_count(), 1);

        graph.disconnect(bi, ai, 0)?;

        assert_eq!(graph.graph.node_count(), 2);
        assert_eq!(graph.graph.edge_count(), 0);
        Ok(())
    }

    #[test]
    fn it_requires_source_to_disconnect() -> Result<()> {
        let mut graph = CompositionGraph::new();
        let a = graph.add_component(Component::from_bytes(
            "a",
            b"(component (import \"x\" (func)))".as_ref(),
        )?)?;
        let b = graph.add_component(Component::from_bytes(
            "b",
            b"(component (import \"x\" (func)) (export \"y\" (func 0)))".as_ref(),
        )?)?;
        let ai = graph.instantiate(a)?;
        let bi = graph.instantiate(b)?;
        graph.connect(bi, Some(0), ai, 0)?;

        match graph.disconnect(101, ai, 0) {
            Ok(_) => panic!("expected a failure to disconnect"),
            Err(e) => assert_eq!(
                format!("{e:#}"),
                "the source instance does not exist in the graph"
            ),
        }

        Ok(())
    }

    #[test]
    fn it_requires_a_target_to_disconnect() -> Result<()> {
        let mut graph = CompositionGraph::new();
        let a = graph.add_component(Component::from_bytes(
            "a",
            b"(component (import \"x\" (func)))".as_ref(),
        )?)?;
        let b = graph.add_component(Component::from_bytes(
            "b",
            b"(component (import \"x\" (func)) (export \"y\" (func 0)))".as_ref(),
        )?)?;
        let ai = graph.instantiate(a)?;
        let bi = graph.instantiate(b)?;
        graph.connect(bi, Some(0), ai, 0)?;

        match graph.disconnect(bi, 101, 0) {
            Ok(_) => panic!("expected a failure to disconnect"),
            Err(e) => assert_eq!(
                format!("{e:#}"),
                "the target instance does not exist in the graph"
            ),
        }

        Ok(())
    }

    #[test]
    fn it_validates_connections() -> Result<()> {
        let mut graph = CompositionGraph::new();
        let a = graph.add_component(Component::from_bytes(
            "a",
            b"(component (import \"i1\" (func)) (import \"i2\" (instance (export \"no\" (func)))))"
                .as_ref(),
        )?)?;
        let b = graph.add_component(Component::from_bytes(
            "b",
            b"(component (import \"i1\" (func)) (import \"i2\" (core module)) (export \"e1\" (func 0)) (export \"e2\" (core module 0)))".as_ref(),
        )?)?;
        let ai = graph.instantiate(a)?;
        let bi = graph.instantiate(b)?;

        match graph.connect(ai, None::<ExportIndex>, ai, 0) {
            Ok(_) => panic!("expected a failure to connect"),
            Err(e) => assert_eq!(
                format!("{e:#}"),
                "an instance cannot be connected to itself"
            ),
        }

        match graph.connect(ai, Some(0), bi, 0) {
            Ok(_) => panic!("expected a failure to connect"),
            Err(e) => assert_eq!(format!("{e:#}"), "the source export index is invalid"),
        }

        match graph.connect(101, Some(0), ai, 0) {
            Ok(_) => panic!("expected a failure to connect"),
            Err(e) => assert_eq!(
                format!("{e:#}"),
                "the source instance does not exist in the graph"
            ),
        }

        match graph.connect(bi, Some(0), 101, 0) {
            Ok(_) => panic!("expected a failure to connect"),
            Err(e) => assert_eq!(
                format!("{e:#}"),
                "the target instance does not exist in the graph"
            ),
        }

        match graph.connect(bi, Some(101), ai, 0) {
            Ok(_) => panic!("expected a failure to connect"),
            Err(e) => assert_eq!(format!("{e:#}"), "the source export index is invalid"),
        }

        match graph.connect(bi, Some(0), ai, 101) {
            Ok(_) => panic!("expected a failure to connect"),
            Err(e) => assert_eq!(format!("{e:#}"), "the target import index is invalid"),
        }

        match graph.connect(bi, Some(1), ai, 0) {
            Ok(_) => panic!("expected a failure to connect"),
            Err(e) => assert_eq!(
                format!("{e:#}"),
                "source module export `e2` is not compatible with target function import `i1`"
            ),
        }

        match graph.connect(bi, None::<ExportIndex>, ai, 0) {
            Ok(_) => panic!("expected a failure to connect"),
            Err(e) => assert_eq!(
                format!("{e:#}"),
                "source instance is not compatible with target function import `i1`"
            ),
        }

        match graph.connect(bi, None::<ExportIndex>, ai, 1) {
            Ok(_) => panic!("expected a failure to connect"),
            Err(e) => assert_eq!(
                format!("{e:#}"),
                "source instance is not compatible with target instance import `i2`"
            ),
        }

        Ok(())
    }

    #[test]
    fn it_cannot_encode_a_cycle() -> Result<()> {
        let mut graph = CompositionGraph::new();
        let a = graph.add_component(Component::from_bytes(
            "a",
            b"(component (import \"i1\" (func)) (export \"e1\" (func 0)))".as_ref(),
        )?)?;
        let b = graph.add_component(Component::from_bytes(
            "b",
            b"(component (import \"i1\" (func)) (export \"e1\" (func 0)))".as_ref(),
        )?)?;
        let ai = graph.instantiate(a)?;
        let bi = graph.instantiate(b)?;

        graph.connect(ai, Some(0), bi, 0)?;
        graph.connect(bi, Some(0), ai, 0)?;

        match graph.encode(EncodeOptions {
            define_components: false,
            export: None,
            validate: true,
        }) {
            Ok(_) => panic!("graph should not encode"),
            Err(e) => assert_eq!(format!("{e:#}"), "an instantiation of component `b` and its dependencies form a cycle in the instantiation graph"),
        }

        Ok(())
    }

    #[test]
    fn it_encodes_an_empty_component() -> Result<()> {
        let mut graph = CompositionGraph::new();
        graph.add_component(Component::from_bytes("a", b"(component)".as_ref())?)?;
        graph.add_component(Component::from_bytes("b", b"(component)".as_ref())?)?;

        let encoded = graph.encode(EncodeOptions {
            define_components: false,
            export: None,
            validate: true,
        })?;

        let wat = wasmprinter::print_bytes(encoded)?;
        assert_eq!(r#"(component)"#, wat);

        Ok(())
    }

    #[test]
    fn it_encodes_component_imports() -> Result<()> {
        let mut graph = CompositionGraph::new();
        // Add a component that doesn't get instantiated (shouldn't be imported)
        graph.add_component(Component::from_bytes("a", b"(component)".as_ref())?)?;
        let b = graph.add_component(Component::from_bytes("b", b"(component)".as_ref())?)?;
        graph.instantiate(b)?;

        let encoded = graph.encode(EncodeOptions {
            define_components: false,
            export: None,
            validate: true,
        })?;

        let wat = wasmprinter::print_bytes(encoded)?.replace("\r\n", "\n");
        assert_eq!(
            r#"(component
  (type (;0;)
    (component)
  )
  (import "b" (component (;0;) (type 0)))
  (instance (;0;) (instantiate 0))
)"#,
            wat
        );

        Ok(())
    }

    #[test]
    fn it_encodes_defined_components() -> Result<()> {
        let mut graph = CompositionGraph::new();
        // Add a component that doesn't get instantiated (shouldn't be imported)
        graph.add_component(Component::from_bytes("a", b"(component)".as_ref())?)?;
        let b = graph.add_component(Component::from_bytes("b", b"(component)".as_ref())?)?;
        graph.instantiate(b)?;

        let encoded = graph.encode(EncodeOptions {
            define_components: true,
            export: None,
            validate: true,
        })?;

        let wat = wasmprinter::print_bytes(encoded)?.replace("\r\n", "\n");
        assert_eq!(
            r#"(component
  (component (;0;))
  (instance (;0;) (instantiate 0))
)"#,
            wat
        );

        Ok(())
    }

    #[test]
    fn it_encodes_a_simple_composition() -> Result<()> {
        let mut graph = CompositionGraph::new();
        let a = graph.add_component(Component::from_bytes(
            "a",
            b"(component
  (type (tuple u32 u32))
  (import \"i1\" (instance (export \"e1\" (func)) (export \"e3\" (func (param \"a\" u32)))))
  (import \"i2\" (func))
  (import \"i3\" (component))
  (import \"i4\" (core module))
  (import \"i5\" (type (eq 0)))
  (export \"e1\" (instance 0))
  (export \"e2\" (func 0))
  (export \"e3\" (component 0))
  (export \"e4\" (core module 0))
  (export \"e5\" (type 1))
)"
            .as_ref(),
        )?)?;
        let b = graph.add_component(Component::from_bytes(
            "b",
            b"(component
  (type (tuple u32 u32))
  (import \"i1\" (instance (export \"e2\" (func)) (export \"e3\" (func (param \"a\" u32)))))
  (import \"i2\" (func))
  (import \"i3\" (component))
  (import \"i4\" (core module))
  (import \"i5\" (type (eq 0)))
)"
            .as_ref(),
        )?)?;

        let ai = graph.instantiate(a)?;
        let bi1 = graph.instantiate(b)?;
        let bi2 = graph.instantiate(b)?;
        let bi3 = graph.instantiate(b)?;

        // Skip the instance arguments so a merged instance is imported
        for i in 1..=3 {
            graph.connect(ai, Some(i), bi1, i)?;
            graph.connect(ai, Some(i), bi2, i)?;
            graph.connect(ai, Some(i), bi3, i)?;
        }

        let encoded = graph.encode(EncodeOptions {
            define_components: true,
            export: None,
            validate: true,
        })?;

        let wat = wasmprinter::print_bytes(encoded)?.replace("\r\n", "\n");
        assert_eq!(
            r#"(component
  (type (;0;)
    (instance
      (type (;0;) (func))
      (export (;0;) "e1" (func (type 0)))
      (type (;1;) (func (param "a" u32)))
      (export (;1;) "e3" (func (type 1)))
      (type (;2;) (func))
      (export (;2;) "e2" (func (type 2)))
    )
  )
  (import "i1" (instance (;0;) (type 0)))
  (type (;1;) (func))
  (import "i2" (func (;0;) (type 1)))
  (type (;2;)
    (component)
  )
  (import "i3" (component (;0;) (type 2)))
  (core type (;0;)
    (module)
  )
  (import "i4" (core module (;0;) (type 0)))
  (type (;3;) (tuple u32 u32))
  (import "i5" (type (;4;) (eq 3)))
  (component (;1;)
    (type (;0;) (tuple u32 u32))
    (type (;1;)
      (instance
        (type (;0;) (func))
        (export (;0;) "e1" (func (type 0)))
        (type (;1;) (func (param "a" u32)))
        (export (;1;) "e3" (func (type 1)))
      )
    )
    (import "i1" (instance (;0;) (type 1)))
    (type (;2;) (func))
    (import "i2" (func (;0;) (type 2)))
    (type (;3;)
      (component)
    )
    (import "i3" (component (;0;) (type 3)))
    (core type (;0;)
      (module)
    )
    (import "i4" (core module (;0;) (type 0)))
    (import "i5" (type (;4;) (eq 0)))
    (export (;1;) "e1" (instance 0))
    (export (;1;) "e2" (func 0))
    (export (;1;) "e3" (component 0))
    (export (;1;) "e4" (core module 0))
    (export (;5;) "e5" (type 1))
  )
  (component (;2;)
    (type (;0;) (tuple u32 u32))
    (type (;1;)
      (instance
        (type (;0;) (func))
        (export (;0;) "e2" (func (type 0)))
        (type (;1;) (func (param "a" u32)))
        (export (;1;) "e3" (func (type 1)))
      )
    )
    (import "i1" (instance (;0;) (type 1)))
    (type (;2;) (func))
    (import "i2" (func (;0;) (type 2)))
    (type (;3;)
      (component)
    )
    (import "i3" (component (;0;) (type 3)))
    (core type (;0;)
      (module)
    )
    (import "i4" (core module (;0;) (type 0)))
    (import "i5" (type (;4;) (eq 0)))
  )
  (instance (;1;) (instantiate 1
      (with "i1" (instance 0))
      (with "i2" (func 0))
      (with "i3" (component 0))
      (with "i4" (core module 0))
      (with "i5" (type 4))
    )
  )
  (alias export 1 "e2" (func (;1;)))
  (alias export 1 "e3" (component (;3;)))
  (alias export 1 "e4" (core module (;1;)))
  (instance (;2;) (instantiate 2
      (with "i2" (func 1))
      (with "i3" (component 3))
      (with "i4" (core module 1))
      (with "i1" (instance 0))
      (with "i5" (type 4))
    )
  )
  (instance (;3;) (instantiate 2
      (with "i2" (func 1))
      (with "i3" (component 3))
      (with "i4" (core module 1))
      (with "i1" (instance 0))
      (with "i5" (type 4))
    )
  )
  (instance (;4;) (instantiate 2
      (with "i2" (func 1))
      (with "i3" (component 3))
      (with "i4" (core module 1))
      (with "i1" (instance 0))
      (with "i5" (type 4))
    )
  )
)"#,
            wat
        );

        Ok(())
    }
}