forked from bytecodealliance/wasm-tools
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgraph.rs
More file actions
1578 lines (1389 loc) · 52.4 KB
/
graph.rs
File metadata and controls
1578 lines (1389 loc) · 52.4 KB
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
//! 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::{
component_types::{
ComponentAnyTypeId, ComponentEntityType, ComponentInstanceTypeId, Remap, Remapping,
ResourceId, SubtypeCx,
},
names::ComponentName,
types::{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::all());
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.as_ref().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.as_ref().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.as_ref().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, Copy, Clone, 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 non-empty, 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 {
// 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 ensures that each set of identical imports in the composed
/// components can be merged into a single import in the output component.
//
// TODO: How do we balance the need to call this early (so we can match up
// imports with exports which mutually import the same resources) with the
// need to delay decisions about where resources are coming from (so that we
// can match up imported resources with exported resources)? Right now I
// think we're erring on the side if the former at the expense of the
// latter.
pub(crate) fn unify_imported_resources(&self) {
let mut resource_mapping = self.resource_mapping.borrow_mut();
let mut resource_imports = IndexMap::<_, IndexSet<_>>::new();
for (component_id, component) in &self.components {
let component = &component.component;
for import_name in component.imports.keys() {
let ty = component
.types
.as_ref()
.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
{
let set = resource_imports
.entry(vec![import_name.to_string(), export_name.to_string()])
.or_default();
if let Some(pair) = resource_mapping.map.get(&resource_id.resource()) {
set.insert(*pair);
}
set.insert((*component_id, resource_id.resource()));
}
}
}
}
}
for resources in resource_imports.values() {
match &resources.iter().copied().collect::<Vec<_>>()[..] {
[] => 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();
let v = context.component_entity_type(&export_type, &import_type, 0);
if v.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());
if self.components.len() > 1 {
self.unify_imported_resources();
}
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.swap_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.swap_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.swap_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.swap_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.swap_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.swap_remove(&target_import);
let remove_edge = if let Some(set) = self.graph.edge_weight_mut(source, target) {
set.swap_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(())