forked from bytecodealliance/wasm-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencoding.rs
More file actions
1706 lines (1524 loc) · 62.5 KB
/
encoding.rs
File metadata and controls
1706 lines (1524 loc) · 62.5 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
use crate::graph::{
CompositionGraph, EncodeOptions, ExportIndex, ImportIndex, InstanceId, type_desc,
};
use anyhow::{Result, anyhow, bail};
use indexmap::{IndexMap, IndexSet};
use petgraph::EdgeDirection;
use smallvec::SmallVec;
use std::collections::{HashMap, hash_map::Entry};
use std::mem;
use wasm_encoder::*;
use wasmparser::{
ComponentExternalKind,
component_types::{
self as ct, AnyTypeId, ComponentAnyTypeId, ComponentCoreModuleTypeId, ComponentCoreTypeId,
ComponentDefinedType, ComponentDefinedTypeId, ComponentEntityType, ComponentFuncTypeId,
ComponentInstanceTypeId, ComponentTypeId, RecordType, Remap, Remapping, ResourceId,
SubtypeCx, TupleType, VariantType,
},
names::KebabString,
types,
};
fn type_ref_to_export_kind(ty: wasmparser::ComponentTypeRef) -> ComponentExportKind {
match ty {
wasmparser::ComponentTypeRef::Module(_) => ComponentExportKind::Module,
wasmparser::ComponentTypeRef::Func(_) => ComponentExportKind::Func,
wasmparser::ComponentTypeRef::Value(_) => ComponentExportKind::Value,
wasmparser::ComponentTypeRef::Type { .. } => ComponentExportKind::Type,
wasmparser::ComponentTypeRef::Instance(_) => ComponentExportKind::Instance,
wasmparser::ComponentTypeRef::Component(_) => ComponentExportKind::Component,
}
}
enum Encodable {
Component(ComponentType),
Instance(InstanceType),
Builder(ComponentBuilder),
}
impl Encodable {
fn type_count(&self) -> u32 {
match self {
Encodable::Component(t) => t.type_count(),
Encodable::Instance(t) => t.type_count(),
Encodable::Builder(t) => t.type_count(),
}
}
fn instance_count(&self) -> u32 {
match self {
Encodable::Component(t) => t.instance_count(),
Encodable::Instance(t) => t.instance_count(),
Encodable::Builder(t) => t.instance_count(),
}
}
fn core_type_count(&self) -> u32 {
match self {
Encodable::Component(t) => t.core_type_count(),
Encodable::Instance(t) => t.core_type_count(),
Encodable::Builder(t) => t.core_type_count(),
}
}
fn ty(&mut self) -> ComponentTypeEncoder<'_> {
match self {
Encodable::Component(t) => t.ty(),
Encodable::Instance(t) => t.ty(),
Encodable::Builder(t) => t.ty(None).1,
}
}
fn core_type(&mut self) -> ComponentCoreTypeEncoder<'_> {
match self {
Encodable::Component(t) => t.core_type(),
Encodable::Instance(t) => t.core_type(),
Encodable::Builder(t) => t.core_type(None).1,
}
}
fn alias(&mut self, alias: Alias<'_>) {
match self {
Encodable::Component(t) => {
t.alias(alias);
}
Encodable::Instance(t) => {
t.alias(alias);
}
Encodable::Builder(t) => {
t.alias(None, alias);
}
}
}
}
/// Metadata necessary to track type definitions across both instances and also
/// across unioning components.
///
/// This state is used when assembling the imports into a composed component.
/// The imported instances will have types that are intended to mirror the
/// original source components which means that the type structure, such as
/// aliases, additionally needs to be mirrored. This structure keeps track of
/// type scopes and is used throughout type translation to facilitate this.
pub(crate) struct TypeState<'a> {
// Current outer scopes of this state which can be referred to with
// `alias outer`
scopes: Vec<TypeScope<'a>>,
// Current type scope that's being translated into.
cur: TypeScope<'a>,
remapping: HashMap<ResourceId, (&'a crate::graph::Component<'a>, ResourceId)>,
}
/// A unique key identifying a type.
///
/// Note that this has two components: the first is the component that a type
/// comes from and the second is the wasmparser-unique id for within that
/// component.
type TypeKey<'a> = (PtrKey<'a, crate::graph::Component<'a>>, AnyTypeId);
/// A scope that types can be defined into.
///
/// This is stored within `TypeState` and contains all the relevant information
/// for mirroring a preexisting wasmparser-defined structure of types into a
/// new component type (such as an instance for an instance import).
struct TypeScope<'a> {
/// Types defined in this current scope.
///
/// Contains the type index that the type is defined at.
type_defs: HashMap<TypeKey<'a>, u32>,
/// Types exported in the current scope.
///
/// This is filled out during `export` and indicates that a particular type
/// is exported with the specified name.
type_exports: HashMap<TypeKey<'a>, &'a str>,
/// Reverse of the `type_exports` map, indicating which name exports which
/// types.
///
/// Note that this can export a "list" of types which represents that
/// multiple components may be "unioned" together to create a single
/// instance import, so exporting a type can have different names as each
/// original component may have ID for the same export name.
///
/// This enables translating type-use situations where one component
/// translates the base type and then a second component refers to that.
type_exports_rev: HashMap<&'a str, Vec<TypeKey<'a>>>,
/// Instances that are available to alias from in this scope.
///
/// This map is keyed by the types that are available to be referred to.
/// The value here is the instance index that the type is defined in along
/// with its export name. This is used to generate `alias export` items.
instance_exports: HashMap<TypeKey<'a>, (u32, &'a str)>,
/// Encoded representation of this type scope, a `wasm-encoder` structure.
encodable: Encodable,
}
impl<'a> TypeState<'a> {
fn new() -> TypeState<'a> {
Self::new_with_remapping(HashMap::new())
}
fn new_with_remapping(
remapping: HashMap<ResourceId, (&'a crate::graph::Component<'a>, ResourceId)>,
) -> TypeState<'a> {
TypeState {
scopes: Vec::new(),
cur: TypeScope {
type_exports: HashMap::new(),
type_exports_rev: HashMap::new(),
instance_exports: HashMap::new(),
type_defs: HashMap::new(),
encodable: Encodable::Builder(Default::default()),
},
remapping,
}
}
/// Pushes a new scope which will be written to the `encodable` provided.
fn push(&mut self, encodable: Encodable) {
let prev = mem::replace(
&mut self.cur,
TypeScope {
type_exports: HashMap::new(),
type_exports_rev: HashMap::new(),
instance_exports: HashMap::new(),
type_defs: HashMap::new(),
encodable,
},
);
self.scopes.push(prev);
}
/// Pops a previously pushed scope and returns the encoding.
fn pop(&mut self) -> Encodable {
let prev = mem::replace(&mut self.cur, self.scopes.pop().unwrap());
// If the previous scope was an instance then assume that the instance
// type is about to be used as an import or export which defines a new
// instance that this previously-outer-now-current scope has access to.
//
// This scope then takes all of the type exports of the created instance
// and registers them as available at this next instance index.
if let Encodable::Instance(_) = &prev.encodable {
let idx = self.cur.encodable.instance_count();
for (id, name) in prev.type_exports {
let prev = self.cur.instance_exports.insert(id, (idx, name));
assert!(prev.is_none());
}
}
prev.encodable
}
}
impl Default for TypeState<'_> {
fn default() -> Self {
Self::new()
}
}
impl<'a> TypeScope<'a> {
/// Registers that `ty` is exported as `name`, filling in both type export
/// maps at the same time.
fn add_type_export(&mut self, ty: TypeKey<'a>, name: &'a str) {
let prev = self.type_exports.insert(ty, name);
assert!(prev.is_none());
self.type_exports_rev.entry(name).or_default().push(ty);
}
}
pub struct PtrKey<'a, T>(&'a T);
impl<T> PartialEq for PtrKey<'_, T> {
fn eq(&self, other: &Self) -> bool {
std::ptr::eq(self.0, other.0)
}
}
impl<T> Eq for PtrKey<'_, T> {}
impl<T> Copy for PtrKey<'_, T> {}
impl<T> Clone for PtrKey<'_, T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> std::hash::Hash for PtrKey<'_, T> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::ptr::hash(self.0, state);
}
}
pub(crate) struct TypeEncoder<'a>(&'a crate::graph::Component<'a>);
impl<'a> TypeEncoder<'a> {
pub fn new(component: &'a crate::graph::Component) -> Self {
Self(component)
}
pub fn component<I, E>(
&self,
state: &mut TypeState<'a>,
imports: I,
exports: E,
) -> ComponentType
where
I: IntoIterator<Item = (&'a str, ComponentEntityType)>,
E: IntoIterator<Item = (&'a str, ComponentEntityType)>,
{
state.push(Encodable::Component(ComponentType::new()));
for (name, ty) in imports {
let ty = self.component_entity_type(state, ty);
let c = match &mut state.cur.encodable {
Encodable::Component(c) => c,
_ => unreachable!(),
};
c.import(name, ty);
}
for (name, ty) in exports {
let export = self.export(name, ty, state);
let c = match &mut state.cur.encodable {
Encodable::Component(c) => c,
_ => unreachable!(),
};
c.export(name, export);
}
match state.pop() {
Encodable::Component(c) => c,
_ => unreachable!(),
}
}
pub fn instance<E>(&self, state: &mut TypeState<'a>, exports: E) -> InstanceType
where
E: IntoIterator<Item = (&'a str, ComponentEntityType)>,
{
state.push(Encodable::Instance(InstanceType::new()));
for (name, ty) in exports {
let export = self.export(name, ty, state);
let c = match &mut state.cur.encodable {
Encodable::Instance(c) => c,
_ => unreachable!(),
};
c.export(name, export);
}
match state.pop() {
Encodable::Instance(c) => c,
_ => unreachable!(),
}
}
pub fn module<I, E>(&self, imports: I, exports: E) -> ModuleType
where
I: IntoIterator<Item = (&'a str, &'a str, wasmparser::types::EntityType)>,
E: IntoIterator<Item = (&'a str, wasmparser::types::EntityType)>,
{
let mut encoded = ModuleType::new();
let mut types = HashMap::default();
for (module, name, ty) in imports {
let ty = self.entity_type(&mut encoded, &mut types, ty);
encoded.import(module, name, ty);
}
for (name, ty) in exports {
let ty = self.entity_type(&mut encoded, &mut types, ty);
encoded.export(name, ty);
}
encoded
}
fn entity_type(
&self,
encodable: &mut ModuleType,
types: &mut HashMap<AnyTypeId, u32>,
ty: wasmparser::types::EntityType,
) -> EntityType {
match ty {
wasmparser::types::EntityType::Func(id)
| wasmparser::types::EntityType::FuncExact(id) => {
let exact = matches!(ty, wasmparser::types::EntityType::FuncExact(_));
let ty = &self.0.types[id].unwrap_func();
let idx = match types.entry(ComponentCoreTypeId::Sub(id).into()) {
Entry::Occupied(e) => *e.get(),
Entry::Vacant(e) => {
let index = encodable.type_count();
encodable.ty().function(
ty.params().iter().copied().map(Self::val_type),
ty.results().iter().copied().map(Self::val_type),
);
*e.insert(index)
}
};
if exact {
EntityType::FunctionExact(idx)
} else {
EntityType::Function(idx)
}
}
wasmparser::types::EntityType::Table(ty) => EntityType::Table(ty.try_into().unwrap()),
wasmparser::types::EntityType::Memory(ty) => EntityType::Memory(ty.into()),
wasmparser::types::EntityType::Global(ty) => EntityType::Global(ty.try_into().unwrap()),
wasmparser::types::EntityType::Tag(id) => {
let ty = &self.0.types[id];
let idx = match types.entry(ComponentCoreTypeId::Sub(id).into()) {
Entry::Occupied(e) => *e.get(),
Entry::Vacant(e) => {
let ty = ty.unwrap_func();
let index = encodable.type_count();
encodable.ty().function(
ty.params().iter().copied().map(Self::val_type),
ty.results().iter().copied().map(Self::val_type),
);
*e.insert(index)
}
};
EntityType::Tag(TagType {
kind: TagKind::Exception,
func_type_idx: idx,
})
}
}
}
fn component_entity_type(
&self,
state: &mut TypeState<'a>,
ty: ComponentEntityType,
) -> ComponentTypeRef {
match ty {
ComponentEntityType::Module(id) => ComponentTypeRef::Module(self.ty(state, id.into())),
ComponentEntityType::Func(id) => ComponentTypeRef::Func(self.ty(state, id.into())),
ComponentEntityType::Value(ty) => {
ComponentTypeRef::Value(self.component_val_type(state, ty))
}
ComponentEntityType::Type {
created: created @ ComponentAnyTypeId::Resource(_),
referenced,
} => {
if created == referenced {
log::trace!("creation of a new resource");
ComponentTypeRef::Type(TypeBounds::SubResource)
} else {
log::trace!("alias of an existing resource");
ComponentTypeRef::Type(TypeBounds::Eq(self.ty(state, referenced.into())))
}
}
ComponentEntityType::Type { referenced, .. } => {
ComponentTypeRef::Type(TypeBounds::Eq(self.ty(state, referenced.into())))
}
ComponentEntityType::Instance(id) => {
ComponentTypeRef::Instance(self.ty(state, id.into()))
}
ComponentEntityType::Component(id) => {
ComponentTypeRef::Component(self.ty(state, id.into()))
}
}
}
fn val_type(ty: wasmparser::ValType) -> ValType {
ty.try_into().unwrap()
}
fn module_type(&self, state: &mut TypeState<'a>, id: ComponentCoreModuleTypeId) -> u32 {
let ty = &self.0.types[id];
let module = self.module(
ty.imports
.iter()
.map(|((m, n), t)| (m.as_str(), n.as_str(), *t)),
ty.exports.iter().map(|(n, t)| (n.as_str(), *t)),
);
let index = state.cur.encodable.core_type_count();
state.cur.encodable.core_type().module(&module);
index
}
fn component_instance_type(
&self,
state: &mut TypeState<'a>,
id: ComponentInstanceTypeId,
) -> u32 {
let ty = &self.0.types[id];
let instance = self.instance(state, ty.exports.iter().map(|(n, t)| (n.as_str(), *t)));
let index = state.cur.encodable.type_count();
state.cur.encodable.ty().instance(&instance);
index
}
fn component_type(&self, state: &mut TypeState<'a>, id: ComponentTypeId) -> u32 {
let ty = &self.0.types[id];
let component = self.component(
state,
ty.imports.iter().map(|(n, t)| (n.as_str(), *t)),
ty.exports.iter().map(|(n, t)| (n.as_str(), *t)),
);
let index = state.cur.encodable.type_count();
state.cur.encodable.ty().component(&component);
index
}
fn component_func_type(&self, state: &mut TypeState<'a>, id: ComponentFuncTypeId) -> u32 {
let ty = &self.0.types[id];
let params = ty
.params
.iter()
.map(|(name, ty)| (name.as_str(), self.component_val_type(state, *ty)))
.collect::<Vec<_>>();
let result = ty.result.map(|ty| self.component_val_type(state, ty));
let index = state.cur.encodable.type_count();
let mut f = state.cur.encodable.ty().function();
f.async_(ty.async_).params(params).result(result);
index
}
/// Translates a type `id` provided, returning the index that it is defined
/// at.
///
/// This is the main point at which type translation flows through. This
/// performs everything necessary such as:
///
/// * Each type is translated only once
/// * If `id` comes from a different instance it's aliased
/// * Dispatching to the correct translation internally.
fn ty(&self, state: &mut TypeState<'a>, id: AnyTypeId) -> u32 {
// Consult our scope's `type_defs` map, and if it's not present then
// generate the type and fill it in.
let key = (PtrKey(self.0), id);
if let Some(ret) = state.cur.type_defs.get(&key) {
return *ret;
}
// If it's a resource that has been remapped, check one more time using
// the remapped version.
if let AnyTypeId::Component(ComponentAnyTypeId::Resource(resource)) = id {
if let Some((component, id)) = state.remapping.get(&resource.resource()) {
let key = (
PtrKey(*component),
AnyTypeId::Component(ComponentAnyTypeId::Resource(
resource.with_resource_id(*id),
)),
);
if let Some(ret) = state.cur.type_defs.get(&key) {
return *ret;
}
}
}
let idx = self._ty(state, id);
let prev = state.cur.type_defs.insert(key, idx);
assert!(prev.is_none());
idx
}
// Inner version of `ty` above which is a separate method to make it easier
// to use `return` and not thwart the caching above.
fn _ty(&self, state: &mut TypeState<'a>, mut id: AnyTypeId) -> u32 {
// This loop will walk the "alias chain" starting at `id` which will
// eventually reach the definition of `id`.
loop {
let key = (PtrKey(self.0), id);
// First see if this `id` has already been defined under a different
// name. This can happen where one component's view of an imported
// instance may be partial and then unioned with another component's
// view of an imported instance. The second instance should reuse
// all the types defined/exported by the first.
//
// Here the reverse-export map is consulted where if `key` as an
// exported type from this instance (which is registered in
// "parallel" when one of those is encountered for all components)
// then search with the exported name if any other component has a
// type definition for their own version of our `id`.
if let Some(name) = state.cur.type_exports.get(&key) {
for key in state.cur.type_exports_rev[name].iter() {
if let Some(ret) = state.cur.type_defs.get(key) {
log::trace!("id already defined through a different component");
return *ret;
}
}
}
// Otherwise see if this type is defined elsewhere and if an alias
// hasn't previously been created then one is done so here. This
// will search all outer scopes for an instance that exports `id`.
for (i, scope) in state.scopes.iter_mut().rev().enumerate() {
let (instance, name) = match scope.instance_exports.get(&key) {
Some(pair) => *pair,
None => continue,
};
let scope_idx = scope.encodable.type_count();
scope.encodable.alias(Alias::InstanceExport {
instance,
name,
kind: ComponentExportKind::Type,
});
match &scope.encodable {
Encodable::Instance(_) => log::trace!("instance"),
Encodable::Component(_) => log::trace!("component"),
Encodable::Builder(_) => log::trace!("builder"),
}
let ret = state.cur.encodable.type_count();
state.cur.encodable.alias(Alias::Outer {
count: i as u32 + 1,
index: scope_idx,
kind: ComponentOuterAliasKind::Type,
});
log::trace!("id defined in a different instance");
return ret;
}
if let Some((instance, name)) = state.cur.instance_exports.get(&key) {
let ret = state.cur.encodable.type_count();
state.cur.encodable.alias(Alias::InstanceExport {
instance: *instance,
name,
kind: ComponentExportKind::Type,
});
log::trace!("id defined in current instance");
return ret;
}
match id.peel_alias(&self.0.types) {
Some(next) => id = next,
// If there's no more aliases then fall through to the
// definition of the type below.
None => break,
}
}
// This type wasn't previously defined, so define it here.
return match id {
AnyTypeId::Core(ComponentCoreTypeId::Sub(_)) => unreachable!(),
AnyTypeId::Core(ComponentCoreTypeId::Module(id)) => self.module_type(state, id),
AnyTypeId::Component(id) => match id {
ComponentAnyTypeId::Resource(r) => {
unreachable!(
"should have been handled in `TypeEncoder::component_entity_type`: {r:?}"
)
}
ComponentAnyTypeId::Defined(id) => self.defined_type(state, id),
ComponentAnyTypeId::Func(id) => self.component_func_type(state, id),
ComponentAnyTypeId::Instance(id) => self.component_instance_type(state, id),
ComponentAnyTypeId::Component(id) => self.component_type(state, id),
},
};
}
fn component_val_type(
&self,
state: &mut TypeState<'a>,
ty: ct::ComponentValType,
) -> ComponentValType {
match ty {
ct::ComponentValType::Primitive(ty) => ComponentValType::Primitive(ty.into()),
ct::ComponentValType::Type(id) => {
ComponentValType::Type(self.ty(state, ComponentAnyTypeId::from(id).into()))
}
}
}
fn defined_type(&self, state: &mut TypeState<'a>, id: ComponentDefinedTypeId) -> u32 {
let ty = &self.0.types[id];
match ty {
ComponentDefinedType::Primitive(ty) => {
let index = state.cur.encodable.type_count();
state
.cur
.encodable
.ty()
.defined_type()
.primitive((*ty).into());
index
}
ComponentDefinedType::Record(r) => self.record(state, r),
ComponentDefinedType::Variant(v) => self.variant(state, v),
ComponentDefinedType::List(ty) => self.list(state, *ty),
ComponentDefinedType::Map(key, value) => self.map(state, *key, *value),
ComponentDefinedType::FixedSizeList(ty, elements) => {
self.fixed_size_list(state, *ty, *elements)
}
ComponentDefinedType::Tuple(t) => self.tuple(state, t),
ComponentDefinedType::Flags(names) => Self::flags(&mut state.cur.encodable, names),
ComponentDefinedType::Enum(cases) => Self::enum_type(&mut state.cur.encodable, cases),
ComponentDefinedType::Option(ty) => self.option(state, *ty),
ComponentDefinedType::Result { ok, err } => self.result(state, *ok, *err),
ComponentDefinedType::Own(r) => {
let ty = self.ty(state, (*r).into());
let index = state.cur.encodable.type_count();
state.cur.encodable.ty().defined_type().own(ty);
index
}
ComponentDefinedType::Borrow(r) => {
let ty = self.ty(state, (*r).into());
let index = state.cur.encodable.type_count();
state.cur.encodable.ty().defined_type().borrow(ty);
index
}
ComponentDefinedType::Future(ty) => self.future(state, *ty),
ComponentDefinedType::Stream(ty) => self.stream(state, *ty),
}
}
fn record(&self, state: &mut TypeState<'a>, record: &RecordType) -> u32 {
let fields = record
.fields
.iter()
.map(|(n, ty)| (n.as_str(), self.component_val_type(state, *ty)))
.collect::<Vec<_>>();
let index = state.cur.encodable.type_count();
state.cur.encodable.ty().defined_type().record(fields);
index
}
fn variant(&self, state: &mut TypeState<'a>, variant: &VariantType) -> u32 {
let cases = variant
.cases
.iter()
.map(|(n, c)| {
(
n.as_str(),
c.ty.map(|ty| self.component_val_type(state, ty)),
c.refines
.as_deref()
.map(|r| variant.cases.iter().position(|(n, _)| n == r).unwrap() as u32),
)
})
.collect::<Vec<_>>();
let index = state.cur.encodable.type_count();
state.cur.encodable.ty().defined_type().variant(cases);
index
}
fn list(&self, state: &mut TypeState<'a>, ty: ct::ComponentValType) -> u32 {
let ty = self.component_val_type(state, ty);
let index = state.cur.encodable.type_count();
state.cur.encodable.ty().defined_type().list(ty);
index
}
fn map(
&self,
state: &mut TypeState<'a>,
key: ct::ComponentValType,
value: ct::ComponentValType,
) -> u32 {
let key = self.component_val_type(state, key);
let value = self.component_val_type(state, value);
let index = state.cur.encodable.type_count();
state.cur.encodable.ty().defined_type().map(key, value);
index
}
fn fixed_size_list(
&self,
state: &mut TypeState<'a>,
ty: ct::ComponentValType,
elements: u32,
) -> u32 {
let ty = self.component_val_type(state, ty);
let index = state.cur.encodable.type_count();
state
.cur
.encodable
.ty()
.defined_type()
.fixed_size_list(ty, elements);
index
}
fn tuple(&self, state: &mut TypeState<'a>, tuple: &TupleType) -> u32 {
let types = tuple
.types
.iter()
.map(|ty| self.component_val_type(state, *ty))
.collect::<Vec<_>>();
let index = state.cur.encodable.type_count();
state.cur.encodable.ty().defined_type().tuple(types);
index
}
fn flags(
encodable: &mut Encodable,
names: &wasmparser::collections::IndexSet<KebabString>,
) -> u32 {
let index = encodable.type_count();
encodable
.ty()
.defined_type()
.flags(names.iter().map(|n| n.as_str()));
index
}
fn enum_type(
encodable: &mut Encodable,
cases: &wasmparser::collections::IndexSet<KebabString>,
) -> u32 {
let index = encodable.type_count();
encodable
.ty()
.defined_type()
.enum_type(cases.iter().map(|c| c.as_str()));
index
}
fn option(&self, state: &mut TypeState<'a>, ty: ct::ComponentValType) -> u32 {
let ty = self.component_val_type(state, ty);
let index = state.cur.encodable.type_count();
state.cur.encodable.ty().defined_type().option(ty);
index
}
fn result(
&self,
state: &mut TypeState<'a>,
ok: Option<ct::ComponentValType>,
err: Option<ct::ComponentValType>,
) -> u32 {
let ok = ok.map(|ty| self.component_val_type(state, ty));
let err = err.map(|ty| self.component_val_type(state, ty));
let index = state.cur.encodable.type_count();
state.cur.encodable.ty().defined_type().result(ok, err);
index
}
fn export(
&self,
name: &'a str,
export: ComponentEntityType,
state: &mut TypeState<'a>,
) -> ComponentTypeRef {
// Check if the export is a type; if so, we need to update the index of the
// type to point to the export instead of the original definition
let id = match export {
ComponentEntityType::Type { created: id, .. } => Some(id),
_ => None,
};
let export = self.component_entity_type(state, export);
if let Some(id) = id {
// Update the index in the type map to point to this export
let key = (PtrKey(self.0), id.into());
let value = state.cur.encodable.type_count();
let prev = state.cur.type_defs.insert(key, value);
assert!(prev.is_none());
state.cur.add_type_export(key, name);
}
export
}
fn future(&self, state: &mut TypeState<'a>, ty: Option<ct::ComponentValType>) -> u32 {
let ty = ty.map(|ty| self.component_val_type(state, ty));
let index = state.cur.encodable.type_count();
state.cur.encodable.ty().defined_type().future(ty);
index
}
fn stream(&self, state: &mut TypeState<'a>, ty: Option<ct::ComponentValType>) -> u32 {
let ty = ty.map(|ty| self.component_val_type(state, ty));
let index = state.cur.encodable.type_count();
state.cur.encodable.ty().defined_type().stream(ty);
index
}
}
/// Represents an instance index in a composition graph.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
struct InstanceIndex(usize);
enum ArgumentImportKind<'a> {
/// An item is being imported.
///
/// The item may be an instance that does not need to be merged.
Item(&'a crate::graph::Component<'a>, ComponentEntityType),
/// A merged instance is being imported.
///
/// Instances are unioned together to form a single instance to
/// import that will satisfy all instantiation arguments that
/// reference the import.
Instance(IndexMap<&'a str, Vec<(&'a crate::graph::Component<'a>, ComponentEntityType)>>),
}
/// Represents an import for an instantiation argument.
struct ArgumentImport<'a> {
// The name of the import.
name: &'a str,
/// The kind of import.
kind: ArgumentImportKind<'a>,
/// The instances that will use the import for an argument.
instances: SmallVec<[(InstanceIndex, ImportIndex); 1]>,
}
impl ArgumentImport<'_> {
fn merge(&mut self, arg: Self, remapping: &mut Remapping) -> Result<()> {
assert_eq!(self.name, arg.name);
self.instances.extend(arg.instances);
// If the existing import is an instance, convert this argument import to
// a merged instance import.
if let ArgumentImportKind::Item(component, ComponentEntityType::Instance(id)) = &self.kind {
let exports = component.types[*id].exports.iter();
let mut map = IndexMap::with_capacity(exports.len());
for (name, ty) in exports {
map.insert(name.as_str(), vec![(*component, *ty)]);
}
self.kind = ArgumentImportKind::Instance(map);
}
match (&mut self.kind, arg.kind) {
// The new item should never be a merged instance
(_, ArgumentImportKind::Instance(..)) => {
unreachable!("expected an item import to merge with")
}
// If the existing import is a merged instance, merge with an instance item import
(
ArgumentImportKind::Instance(exports),
ArgumentImportKind::Item(new_component, ComponentEntityType::Instance(id)),
) => {
for (name, new_type) in new_component.types[id].exports.iter() {
let dst = exports.entry(name.as_str()).or_default();
for (existing_component, existing_type) in dst.iter_mut() {
if Self::types_compatible(
existing_component,
*existing_type,
new_component,
*new_type,
remapping,
) {
continue;
}
bail!(
"cannot import instance with name `{name}` for \
an instantiation argument of component \
`{cname}` because it conflicts with an \
imported instantiation argument of component \
`{ecname}`",
name = self.name,
cname = new_component.name,
ecname = existing_component.name,
)
}
dst.push((new_component, *new_type));
}
}
// Otherwise, an attempt to merge an instance with a non-instance is an error
(ArgumentImportKind::Instance(_), ArgumentImportKind::Item(component, ty)) => {
bail!(
"cannot import {ty} with name `{name}` for an instantiation \
argument of component `{cname}` because it conflicts with \
an instance imported with the same name",
name = self.name,
ty = type_desc(ty),
cname = component.name,
);
}
// Finally, merge two item imports together by finding the most-compatible type
(
ArgumentImportKind::Item(existing_component, existing_type),
ArgumentImportKind::Item(new_component, new_type),
) => {
if !Self::types_compatible(
existing_component,
*existing_type,
new_component,
new_type,
remapping,
) {
bail!(
"cannot import {ty} with name `{name}` for an \
instantiation argument of component `{cname}` \
because it conflicts with an imported instantiation \
argument of component `{ecname}`",
ty = type_desc(new_type),
name = self.name,
cname = new_component.name,
ecname = existing_component.name,
)
}
}
}
Ok(())
}
/// Tests whether two types from different components are compatible with
/// one another.
///
/// For now this performs a subtype check in both directions, only
/// considering them compatible if both checks are "true". This means
/// that it effectively requires the types to be structured the same way.
fn types_compatible<'a>(
existing_component: &'a crate::graph::Component<'a>,
existing_type: ComponentEntityType,
new_component: &'a crate::graph::Component<'a>,
new_type: ComponentEntityType,
remapping: &mut Remapping,
) -> bool {
let mut context =
SubtypeCx::new_with_refs(existing_component.types(), new_component.types());
let mut a_ty = existing_type;
context.a.remap_component_entity(&mut a_ty, remapping);
remapping.reset_type_cache();
let mut b_ty = new_type;
context.b.remap_component_entity(&mut b_ty, remapping);
remapping.reset_type_cache();
if context.component_entity_type(&a_ty, &b_ty, 0).is_err() {
return false;
}
context.swap();