-
Notifications
You must be signed in to change notification settings - Fork 261
/
Copy pathdecoding.rs
1820 lines (1679 loc) · 70.2 KB
/
decoding.rs
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::*;
use anyhow::{anyhow, bail};
use indexmap::IndexSet;
use std::mem;
use std::{collections::HashMap, io::Read};
use wasmparser::Chunk;
use wasmparser::{
component_types::{
ComponentAnyTypeId, ComponentDefinedType, ComponentEntityType, ComponentFuncType,
ComponentInstanceType, ComponentType, ComponentValType,
},
names::{ComponentName, ComponentNameKind},
types,
types::Types,
ComponentExternalKind, Parser, Payload, PrimitiveValType, ValidPayload, Validator,
WasmFeatures,
};
/// Represents information about a decoded WebAssembly component.
struct ComponentInfo {
/// Wasmparser-defined type information learned after a component is fully
/// validated.
types: types::Types,
/// List of all imports and exports from this component.
externs: Vec<(String, Extern)>,
/// Decoded package metadata
package_metadata: Option<PackageMetadata>,
}
struct DecodingExport {
name: String,
kind: ComponentExternalKind,
index: u32,
}
enum Extern {
Import(String),
Export(DecodingExport),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WitEncodingVersion {
V1,
V2,
}
impl ComponentInfo {
/// Creates a new component info by parsing the given WebAssembly component bytes.
fn from_reader(mut reader: impl Read) -> Result<Self> {
let mut validator = Validator::new_with_features(WasmFeatures::all());
let mut externs = Vec::new();
let mut depth = 1;
let mut types = None;
let mut _package_metadata = None;
let mut cur = Parser::new(0);
let mut eof = false;
let mut stack = Vec::new();
let mut buffer = Vec::new();
loop {
let chunk = cur.parse(&buffer, eof)?;
let (payload, consumed) = match chunk {
Chunk::NeedMoreData(hint) => {
assert!(!eof); // otherwise an error would be returned
// Use the hint to preallocate more space, then read
// some more data into our buffer.
//
// Note that the buffer management here is not ideal,
// but it's compact enough to fit in an example!
let len = buffer.len();
buffer.extend((0..hint).map(|_| 0u8));
let n = reader.read(&mut buffer[len..])?;
buffer.truncate(len + n);
eof = n == 0;
continue;
}
Chunk::Parsed { consumed, payload } => (payload, consumed),
};
match validator.payload(&payload)? {
ValidPayload::Ok => {}
ValidPayload::Parser(_) => depth += 1,
ValidPayload::End(t) => {
depth -= 1;
if depth == 0 {
types = Some(t);
}
}
ValidPayload::Func(..) => {}
}
match payload {
Payload::ComponentImportSection(s) if depth == 1 => {
for import in s {
let import = import?;
externs.push((
import.name.0.to_string(),
Extern::Import(import.name.0.to_string()),
));
}
}
Payload::ComponentExportSection(s) if depth == 1 => {
for export in s {
let export = export?;
externs.push((
export.name.0.to_string(),
Extern::Export(DecodingExport {
name: export.name.0.to_string(),
kind: export.kind,
index: export.index,
}),
));
}
}
#[cfg(feature = "serde")]
Payload::CustomSection(s) if s.name() == PackageMetadata::SECTION_NAME => {
if _package_metadata.is_some() {
bail!("multiple {:?} sections", PackageMetadata::SECTION_NAME);
}
_package_metadata = Some(PackageMetadata::decode(s.data())?);
}
Payload::ModuleSection { parser, .. }
| Payload::ComponentSection { parser, .. } => {
stack.push(cur.clone());
cur = parser.clone();
}
Payload::End(_) => {
if let Some(parent_parser) = stack.pop() {
cur = parent_parser.clone();
} else {
break;
}
}
_ => {}
}
// once we're done processing the payload we can forget the
// original.
buffer.drain(..consumed);
}
Ok(Self {
types: types.unwrap(),
externs,
package_metadata: _package_metadata,
})
}
fn is_wit_package(&self) -> Option<WitEncodingVersion> {
// all wit package exports must be component types, and there must be at
// least one
if self.externs.is_empty() {
return None;
}
if !self.externs.iter().all(|(_, item)| {
let export = match item {
Extern::Export(e) => e,
_ => return false,
};
match export.kind {
ComponentExternalKind::Type => matches!(
self.types.as_ref().component_any_type_at(export.index),
ComponentAnyTypeId::Component(_)
),
_ => false,
}
}) {
return None;
}
// The distinction between v1 and v2 encoding formats is the structure of the export
// strings for each component. The v1 format uses "<namespace>:<package>/wit" as the name
// for the top-level exports, while the v2 format uses the unqualified name of the encoded
// entity.
match ComponentName::new(&self.externs[0].0, 0).ok()?.kind() {
ComponentNameKind::Interface(name) if name.interface().as_str() == "wit" => {
Some(WitEncodingVersion::V1)
}
ComponentNameKind::Label(_) => Some(WitEncodingVersion::V2),
_ => None,
}
}
fn decode_wit_v1_package(&self) -> Result<(Resolve, PackageId)> {
let mut decoder = WitPackageDecoder::new(&self.types);
let mut pkg = None;
for (name, item) in self.externs.iter() {
let export = match item {
Extern::Export(e) => e,
_ => unreachable!(),
};
let id = self.types.as_ref().component_type_at(export.index);
let ty = &self.types[id];
if pkg.is_some() {
bail!("more than one top-level exported component type found");
}
let name = ComponentName::new(name, 0).unwrap();
pkg = Some(
decoder
.decode_v1_package(&name, ty)
.with_context(|| format!("failed to decode document `{name}`"))?,
);
}
let pkg = pkg.ok_or_else(|| anyhow!("no exported component type found"))?;
let (mut resolve, package) = decoder.finish(pkg);
if let Some(package_metadata) = &self.package_metadata {
package_metadata.inject(&mut resolve, package)?;
}
Ok((resolve, package))
}
fn decode_wit_v2_package(&self) -> Result<(Resolve, PackageId)> {
let mut decoder = WitPackageDecoder::new(&self.types);
let mut pkg_name = None;
let mut interfaces = IndexMap::new();
let mut worlds = IndexMap::new();
let mut fields = PackageFields {
interfaces: &mut interfaces,
worlds: &mut worlds,
};
for (_, item) in self.externs.iter() {
let export = match item {
Extern::Export(e) => e,
_ => unreachable!(),
};
let index = export.index;
let id = self.types.as_ref().component_type_at(index);
let component = &self.types[id];
// The single export of this component will determine if it's a world or an interface:
// worlds export a component, while interfaces export an instance.
if component.exports.len() != 1 {
bail!(
"Expected a single export, but found {} instead",
component.exports.len()
);
}
let name = component.exports.keys().nth(0).unwrap();
let name = match component.exports[name] {
ComponentEntityType::Component(ty) => {
let package_name =
decoder.decode_world(name.as_str(), &self.types[ty], &mut fields)?;
package_name
}
ComponentEntityType::Instance(ty) => {
let package_name = decoder.decode_interface(
name.as_str(),
&component.imports,
&self.types[ty],
&mut fields,
)?;
package_name
}
_ => unreachable!(),
};
if let Some(pkg_name) = pkg_name.as_ref() {
// TODO: when we have fully switched to the v2 format, we should switch to parsing
// multiple wit documents instead of bailing.
if pkg_name != &name {
bail!("item defined with mismatched package name")
}
} else {
pkg_name.replace(name);
}
}
let pkg = if let Some(name) = pkg_name {
Package {
name,
docs: Docs::default(),
interfaces,
worlds,
}
} else {
bail!("no exported component type found");
};
let (mut resolve, package) = decoder.finish(pkg);
if let Some(package_metadata) = &self.package_metadata {
package_metadata.inject(&mut resolve, package)?;
}
Ok((resolve, package))
}
fn decode_component(&self) -> Result<(Resolve, WorldId)> {
assert!(self.is_wit_package().is_none());
let mut decoder = WitPackageDecoder::new(&self.types);
// Note that this name is arbitrarily chosen. We may one day perhaps
// want to encode this in the component binary format itself, but for
// now it shouldn't be an issue to have a defaulted name here.
let world_name = "root";
let world = decoder.resolve.worlds.alloc(World {
name: world_name.to_string(),
docs: Default::default(),
imports: Default::default(),
exports: Default::default(),
package: None,
includes: Default::default(),
include_names: Default::default(),
stability: Default::default(),
});
let mut package = Package {
// Similar to `world_name` above this is arbitrarily chosen as it's
// not otherwise encoded in a binary component. This theoretically
// shouldn't cause issues, however.
name: PackageName {
namespace: "root".to_string(),
version: None,
name: "component".to_string(),
},
docs: Default::default(),
worlds: [(world_name.to_string(), world)].into_iter().collect(),
interfaces: Default::default(),
};
let mut fields = PackageFields {
worlds: &mut package.worlds,
interfaces: &mut package.interfaces,
};
for (_name, item) in self.externs.iter() {
match item {
Extern::Import(import) => {
decoder.decode_component_import(import, world, &mut fields)?
}
Extern::Export(export) => {
decoder.decode_component_export(export, world, &mut fields)?
}
}
}
let (resolve, _) = decoder.finish(package);
Ok((resolve, world))
}
}
/// Result of the [`decode`] function.
pub enum DecodedWasm {
/// The input to [`decode`] was one or more binary-encoded WIT package(s).
///
/// The full resolve graph is here plus the identifier of the packages that
/// were encoded. Note that other packages may be within the resolve if any
/// of the main packages refer to other, foreign packages.
WitPackage(Resolve, PackageId),
/// The input to [`decode`] was a component and its interface is specified
/// by the world here.
Component(Resolve, WorldId),
}
impl DecodedWasm {
/// Returns the [`Resolve`] for WIT types contained.
pub fn resolve(&self) -> &Resolve {
match self {
DecodedWasm::WitPackage(resolve, _) => resolve,
DecodedWasm::Component(resolve, _) => resolve,
}
}
/// Returns the main packages of what was decoded.
pub fn package(&self) -> PackageId {
match self {
DecodedWasm::WitPackage(_, id) => *id,
DecodedWasm::Component(resolve, world) => resolve.worlds[*world].package.unwrap(),
}
}
}
/// Decode for incremental reading
pub fn decode_reader(reader: impl Read) -> Result<DecodedWasm> {
let info = ComponentInfo::from_reader(reader)?;
if let Some(version) = info.is_wit_package() {
match version {
WitEncodingVersion::V1 => {
log::debug!("decoding a v1 WIT package encoded as wasm");
let (resolve, pkg) = info.decode_wit_v1_package()?;
Ok(DecodedWasm::WitPackage(resolve, pkg))
}
WitEncodingVersion::V2 => {
log::debug!("decoding a v2 WIT package encoded as wasm");
let (resolve, pkg) = info.decode_wit_v2_package()?;
Ok(DecodedWasm::WitPackage(resolve, pkg))
}
}
} else {
log::debug!("inferring the WIT of a concrete component");
let (resolve, world) = info.decode_component()?;
Ok(DecodedWasm::Component(resolve, world))
}
}
/// Decodes an in-memory WebAssembly binary into a WIT [`Resolve`] and
/// associated metadata.
///
/// The WebAssembly binary provided here can either be a
/// WIT-package-encoded-as-binary or an actual component itself. A [`Resolve`]
/// is always created and the return value indicates which was detected.
pub fn decode(bytes: &[u8]) -> Result<DecodedWasm> {
decode_reader(bytes)
}
/// Decodes the single component type `world` specified as a WIT world.
///
/// The `world` should be an exported component type. The `world` must have been
/// previously created via `encode_world` meaning that it is a component that
/// itself imports nothing and exports a single component, and the single
/// component export represents the world. The name of the export is also the
/// name of the package/world/etc.
pub fn decode_world(wasm: &[u8]) -> Result<(Resolve, WorldId)> {
let mut validator = Validator::new();
let mut exports = Vec::new();
let mut depth = 1;
let mut types = None;
for payload in Parser::new(0).parse_all(wasm) {
let payload = payload?;
match validator.payload(&payload)? {
ValidPayload::Ok => {}
ValidPayload::Parser(_) => depth += 1,
ValidPayload::End(t) => {
depth -= 1;
if depth == 0 {
types = Some(t);
}
}
ValidPayload::Func(..) => {}
}
match payload {
Payload::ComponentExportSection(s) if depth == 1 => {
for export in s {
exports.push(export?);
}
}
_ => {}
}
}
if exports.len() != 1 {
bail!("expected one export in component");
}
if exports[0].kind != ComponentExternalKind::Type {
bail!("expected an export of a type");
}
if exports[0].ty.is_some() {
bail!("expected an un-ascribed exported type");
}
let types = types.as_ref().unwrap();
let world = match types.as_ref().component_any_type_at(exports[0].index) {
ComponentAnyTypeId::Component(c) => c,
_ => bail!("expected an exported component type"),
};
let mut decoder = WitPackageDecoder::new(types);
let mut interfaces = IndexMap::new();
let mut worlds = IndexMap::new();
let ty = &types[world];
assert_eq!(ty.imports.len(), 0);
assert_eq!(ty.exports.len(), 1);
let name = ty.exports.keys().nth(0).unwrap();
let ty = match ty.exports[0] {
ComponentEntityType::Component(ty) => ty,
_ => unreachable!(),
};
let name = decoder.decode_world(
name,
&types[ty],
&mut PackageFields {
interfaces: &mut interfaces,
worlds: &mut worlds,
},
)?;
let (resolve, pkg) = decoder.finish(Package {
name,
interfaces,
worlds,
docs: Default::default(),
});
// The package decoded here should only have a single world so extract that
// here to return.
let world = *resolve.packages[pkg].worlds.iter().next().unwrap().1;
Ok((resolve, world))
}
struct PackageFields<'a> {
interfaces: &'a mut IndexMap<String, InterfaceId>,
worlds: &'a mut IndexMap<String, WorldId>,
}
struct WitPackageDecoder<'a> {
resolve: Resolve,
types: &'a Types,
foreign_packages: IndexMap<String, Package>,
iface_to_package_index: HashMap<InterfaceId, usize>,
named_interfaces: HashMap<String, InterfaceId>,
/// A map which tracks named resources to what their corresponding `TypeId`
/// is. This first layer of key in this map is the owner scope of a
/// resource, more-or-less the `world` or `interface` that it's defined
/// within. The second layer of this map is keyed by name of the resource
/// and points to the actual ID of the resource.
///
/// This map is populated in `register_type_export`.
resources: HashMap<TypeOwner, HashMap<String, TypeId>>,
/// A map from a type id to what it's been translated to.
type_map: HashMap<ComponentAnyTypeId, TypeId>,
}
impl WitPackageDecoder<'_> {
fn new<'a>(types: &'a Types) -> WitPackageDecoder<'a> {
WitPackageDecoder {
resolve: Resolve::default(),
types,
type_map: HashMap::new(),
foreign_packages: Default::default(),
iface_to_package_index: Default::default(),
named_interfaces: Default::default(),
resources: Default::default(),
}
}
fn decode_v1_package(&mut self, name: &ComponentName, ty: &ComponentType) -> Result<Package> {
// Process all imports for this package first, where imports are
// importing from remote packages.
for (name, ty) in ty.imports.iter() {
let ty = match ty {
ComponentEntityType::Instance(idx) => &self.types[*idx],
_ => bail!("import `{name}` is not an instance"),
};
self.register_import(name, ty)
.with_context(|| format!("failed to process import `{name}`"))?;
}
let mut package = Package {
// The name encoded for packages must be of the form `foo:bar/wit`
// where "wit" is just a placeholder for now. The package name in
// this case would be `foo:bar`.
name: match name.kind() {
ComponentNameKind::Interface(name) if name.interface().as_str() == "wit" => {
name.to_package_name()
}
_ => bail!("package name is not a valid id: {name}"),
},
docs: Default::default(),
interfaces: Default::default(),
worlds: Default::default(),
};
let mut fields = PackageFields {
interfaces: &mut package.interfaces,
worlds: &mut package.worlds,
};
for (name, ty) in ty.exports.iter() {
match ty {
ComponentEntityType::Instance(idx) => {
let ty = &self.types[*idx];
self.register_interface(name.as_str(), ty, &mut fields)
.with_context(|| format!("failed to process export `{name}`"))?;
}
ComponentEntityType::Component(idx) => {
let ty = &self.types[*idx];
self.register_world(name.as_str(), ty, &mut fields)
.with_context(|| format!("failed to process export `{name}`"))?;
}
_ => bail!("component export `{name}` is not an instance or component"),
}
}
Ok(package)
}
fn decode_interface<'a>(
&mut self,
name: &str,
imports: &wasmparser::collections::IndexMap<String, ComponentEntityType>,
ty: &ComponentInstanceType,
fields: &mut PackageFields<'a>,
) -> Result<PackageName> {
let component_name = self
.parse_component_name(name)
.context("expected world name to have an ID form")?;
let package = match component_name.kind() {
ComponentNameKind::Interface(name) => name.to_package_name(),
_ => bail!("expected world name to be fully qualified"),
};
for (name, ty) in imports.iter() {
let ty = match ty {
ComponentEntityType::Instance(idx) => &self.types[*idx],
_ => bail!("import `{name}` is not an instance"),
};
self.register_import(name, ty)
.with_context(|| format!("failed to process import `{name}`"))?;
}
let _ = self.register_interface(name, ty, fields)?;
Ok(package)
}
fn decode_world<'a>(
&mut self,
name: &str,
ty: &ComponentType,
fields: &mut PackageFields<'a>,
) -> Result<PackageName> {
let kebab_name = self
.parse_component_name(name)
.context("expected world name to have an ID form")?;
let package = match kebab_name.kind() {
ComponentNameKind::Interface(name) => name.to_package_name(),
_ => bail!("expected world name to be fully qualified"),
};
let _ = self.register_world(name, ty, fields)?;
Ok(package)
}
fn decode_component_import<'a>(
&mut self,
name: &str,
world: WorldId,
package: &mut PackageFields<'a>,
) -> Result<()> {
log::debug!("decoding component import `{name}`");
let ty = self
.types
.as_ref()
.component_entity_type_of_import(name)
.unwrap();
let owner = TypeOwner::World(world);
let (name, item) = match ty {
ComponentEntityType::Instance(i) => {
let ty = &self.types[i];
let (name, id) = if name.contains('/') {
let id = self.register_import(name, ty)?;
(WorldKey::Interface(id), id)
} else {
self.register_interface(name, ty, package)
.with_context(|| format!("failed to decode WIT from import `{name}`"))?
};
(
name,
WorldItem::Interface {
id,
stability: Default::default(),
},
)
}
ComponentEntityType::Func(i) => {
let ty = &self.types[i];
let func = self
.convert_function(name, ty, owner)
.with_context(|| format!("failed to decode function from import `{name}`"))?;
(WorldKey::Name(name.to_string()), WorldItem::Function(func))
}
ComponentEntityType::Type {
referenced,
created,
} => {
let id = self
.register_type_export(name, owner, referenced, created)
.with_context(|| format!("failed to decode type from export `{name}`"))?;
(WorldKey::Name(name.to_string()), WorldItem::Type(id))
}
// All other imports do not form part of the component's world
_ => return Ok(()),
};
self.resolve.worlds[world].imports.insert(name, item);
Ok(())
}
fn decode_component_export<'a>(
&mut self,
export: &DecodingExport,
world: WorldId,
package: &mut PackageFields<'a>,
) -> Result<()> {
let name = &export.name;
log::debug!("decoding component export `{name}`");
let types = self.types.as_ref();
let ty = types.component_entity_type_of_export(name).unwrap();
let (name, item) = match ty {
ComponentEntityType::Func(i) => {
let ty = &types[i];
let func = self
.convert_function(name, ty, TypeOwner::World(world))
.with_context(|| format!("failed to decode function from export `{name}`"))?;
(WorldKey::Name(name.to_string()), WorldItem::Function(func))
}
ComponentEntityType::Instance(i) => {
let ty = &types[i];
let (name, id) = if name.contains('/') {
let id = self.register_import(name, ty)?;
(WorldKey::Interface(id), id)
} else {
self.register_interface(name, ty, package)
.with_context(|| format!("failed to decode WIT from export `{name}`"))?
};
(
name,
WorldItem::Interface {
id,
stability: Default::default(),
},
)
}
_ => {
bail!("component export `{name}` was not a function or instance")
}
};
self.resolve.worlds[world].exports.insert(name, item);
Ok(())
}
/// Registers that the `name` provided is either imported interface from a
/// foreign package or referencing a previously defined interface in this
/// package.
///
/// This function will internally ensure that `name` is well-structured and
/// will fill in any information as necessary. For example with a foreign
/// dependency the foreign package structure, types, etc, all need to be
/// created. For a local dependency it's instead ensured that all the types
/// line up with the previous definitions.
fn register_import(&mut self, name: &str, ty: &ComponentInstanceType) -> Result<InterfaceId> {
let (is_local, interface) = match self.named_interfaces.get(name) {
Some(id) => (true, *id),
None => (false, self.extract_dep_interface(name)?),
};
let owner = TypeOwner::Interface(interface);
for (name, ty) in ty.exports.iter() {
log::debug!("decoding import instance export `{name}`");
match *ty {
ComponentEntityType::Type {
referenced,
created,
} => {
match self.resolve.interfaces[interface]
.types
.get(name.as_str())
.copied()
{
// If this name is already defined as a type in the
// specified interface then that's ok. For package-local
// interfaces that's expected since the interface was
// fully defined. For remote interfaces it means we're
// using something that was already used elsewhere. In
// both cases continue along.
//
// Notably for the remotely defined case this will also
// walk over the structure of the type and register
// internal wasmparser ids with wit-parser ids. This is
// necessary to ensure that anonymous types like
// `list<u8>` defined in original definitions are
// unified with anonymous types when duplicated inside
// of worlds. Overall this prevents, for example, extra
// `list<u8>` types from popping up when decoding. This
// is not strictly necessary but assists with
// roundtripping assertions during fuzzing.
Some(id) => {
log::debug!("type already exist");
match referenced {
ComponentAnyTypeId::Defined(ty) => {
self.register_defined(id, &self.types[ty])?;
}
ComponentAnyTypeId::Resource(_) => {}
_ => unreachable!(),
}
let prev = self.type_map.insert(created, id);
assert!(prev.is_none());
}
// If the name is not defined, however, then there's two
// possibilities:
//
// * For package-local interfaces this is an error
// because the package-local interface defined
// everything already and this is referencing
// something that isn't defined.
//
// * For remote interfaces they're never fully declared
// so it's lazily filled in here. This means that the
// view of remote interfaces ends up being the minimal
// slice needed for this resolve, which is what's
// intended.
None => {
if is_local {
bail!("instance type export `{name}` not defined in interface");
}
let id = self.register_type_export(
name.as_str(),
owner,
referenced,
created,
)?;
let prev = self.resolve.interfaces[interface]
.types
.insert(name.to_string(), id);
assert!(prev.is_none());
}
}
}
// This has similar logic to types above where we lazily fill in
// functions for remote dependencies and otherwise assert
// they're already defined for local dependencies.
ComponentEntityType::Func(ty) => {
let def = &self.types[ty];
if self.resolve.interfaces[interface]
.functions
.contains_key(name.as_str())
{
// TODO: should ideally verify that function signatures
// match.
continue;
}
if is_local {
bail!("instance function export `{name}` not defined in interface");
}
let func = self.convert_function(name.as_str(), def, owner)?;
let prev = self.resolve.interfaces[interface]
.functions
.insert(name.to_string(), func);
assert!(prev.is_none());
}
_ => bail!("instance type export `{name}` is not a type"),
}
}
Ok(interface)
}
fn find_alias(&self, id: ComponentAnyTypeId) -> Option<TypeId> {
// Consult `type_map` for `referenced` or anything in its
// chain of aliases to determine what it maps to. This may
// bottom out in `None` in the case that this type is
// just now being defined, but this should otherwise follow
// chains of aliases to determine what exactly this was a
// `use` of if it exists.
let mut prev = None;
let mut cur = id;
while prev.is_none() {
prev = self.type_map.get(&cur).copied();
cur = match self.types.as_ref().peel_alias(cur) {
Some(next) => next,
None => break,
};
}
prev
}
/// This will parse the `name_string` as a component model ID string and
/// ensure that there's an `InterfaceId` corresponding to its components.
fn extract_dep_interface(&mut self, name_string: &str) -> Result<InterfaceId> {
let name = ComponentName::new(name_string, 0).unwrap();
let name = match name.kind() {
ComponentNameKind::Interface(name) => name,
_ => bail!("package name is not a valid id: {name_string}"),
};
let package_name = name.to_package_name();
// Lazily create a `Package` as necessary, along with the interface.
let package = self
.foreign_packages
.entry(package_name.to_string())
.or_insert_with(|| Package {
name: package_name.clone(),
docs: Default::default(),
interfaces: Default::default(),
worlds: Default::default(),
});
let interface = *package
.interfaces
.entry(name.interface().to_string())
.or_insert_with(|| {
self.resolve.interfaces.alloc(Interface {
name: Some(name.interface().to_string()),
docs: Default::default(),
types: IndexMap::default(),
functions: IndexMap::new(),
package: None,
stability: Default::default(),
})
});
// Record a mapping of which foreign package this interface belongs to
self.iface_to_package_index.insert(
interface,
self.foreign_packages
.get_full(&package_name.to_string())
.unwrap()
.0,
);
Ok(interface)
}
/// A general-purpose helper function to translate a component instance
/// into a WIT interface.
///
/// This is one of the main workhorses of this module. This handles
/// interfaces both at the type level, for concrete components, and
/// internally within worlds as well.
///
/// The `name` provided is the contextual ID or name of the interface. This
/// could be a kebab-name in the case of a world import or export or it can
/// also be an ID. This is used to guide insertion into various maps.
///
/// The `ty` provided is the actual component type being decoded.
///
/// The `package` is where to insert the final interface if `name` is an ID
/// meaning it's registered as a named standalone item within the package.
fn register_interface<'a>(
&mut self,
name: &str,
ty: &ComponentInstanceType,
package: &mut PackageFields<'a>,
) -> Result<(WorldKey, InterfaceId)> {
// If this interface's name is already known then that means this is an
// interface that's both imported and exported. Use `register_import`
// to draw connections between types and this interface's types.
if self.named_interfaces.contains_key(name) {
let id = self.register_import(name, ty)?;
return Ok((WorldKey::Interface(id), id));
}
// If this is a bare kebab-name for an interface then the interface's
// listed name is `None` and the name goes out through the key.
// Otherwise this name is extracted from `name` interpreted as an ID.
let interface_name = self.extract_interface_name_from_component_name(name)?;
let mut interface = Interface {
name: interface_name.clone(),
docs: Default::default(),
types: IndexMap::default(),
functions: IndexMap::new(),
package: None,
stability: Default::default(),
};
let owner = TypeOwner::Interface(self.resolve.interfaces.next_id());
for (name, ty) in ty.exports.iter() {
match *ty {
ComponentEntityType::Type {
referenced,
created,
} => {
let ty = self
.register_type_export(name.as_str(), owner, referenced, created)
.with_context(|| format!("failed to register type export '{name}'"))?;
let prev = interface.types.insert(name.to_string(), ty);
assert!(prev.is_none());
}
ComponentEntityType::Func(ty) => {
let ty = &self.types[ty];
let func = self
.convert_function(name.as_str(), ty, owner)
.with_context(|| format!("failed to convert function '{name}'"))?;
let prev = interface.functions.insert(name.to_string(), func);
assert!(prev.is_none());
}
_ => bail!("instance type export `{name}` is not a type or function"),
};
}
let id = self.resolve.interfaces.alloc(interface);
let key = match interface_name {
// If this interface is named then it's part of the package, so
// insert it. Additionally register it in `named_interfaces` so
// further use comes back to this original definition.
Some(interface_name) => {
let prev = package.interfaces.insert(interface_name, id);
assert!(prev.is_none(), "duplicate interface added for {name:?}");
let prev = self.named_interfaces.insert(name.to_string(), id);
assert!(prev.is_none());
WorldKey::Interface(id)
}
// If this interface isn't named then its key is always a
// kebab-name.
None => WorldKey::Name(name.to_string()),
};