-
Notifications
You must be signed in to change notification settings - Fork 260
/
Copy pathencoding.rs
2231 lines (2023 loc) · 90.5 KB
/
encoding.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
//! Support for encoding a core wasm module into a component.
//!
//! This module, at a high level, is tasked with transforming a core wasm
//! module into a component. This will process the imports/exports of the core
//! wasm module and translate between the `wit-parser` AST and the component
//! model binary format, producing a final component which will import
//! `*.wit` defined interfaces and export `*.wit` defined interfaces as well
//! with everything wired up internally according to the canonical ABI and such.
//!
//! This doc block here is not currently 100% complete and doesn't cover the
//! full functionality of this module.
//!
//! # Adapter Modules
//!
//! One feature of this encoding process which is non-obvious is the support for
//! "adapter modules". The general idea here is that historical host API
//! definitions have been around for quite some time, such as
//! `wasi_snapshot_preview1`, but these host API definitions are not compatible
//! with the canonical ABI or component model exactly. These APIs, however, can
//! in most situations be roughly adapted to component-model equivalents. This
//! is where adapter modules come into play, they're converting from some
//! arbitrary API/ABI into a component-model using API.
//!
//! An adapter module is a separately compiled `*.wasm` blob which will export
//! functions matching the desired ABI (e.g. exporting functions matching the
//! `wasi_snapshot_preview1` ABI). The `*.wasm` blob will then import functions
//! in the canonical ABI and internally adapt the exported functions to the
//! imported functions. The encoding support in this module is what wires
//! everything up and makes sure that everything is imported and exported to the
//! right place. Adapter modules currently always use "indirect lowerings"
//! meaning that a shim module is created and provided as the imports to the
//! main core wasm module, and the shim module is "filled in" at a later time
//! during the instantiation process.
//!
//! Adapter modules are not intended to be general purpose and are currently
//! very restrictive, namely:
//!
//! * They must import a linear memory and not define their own linear memory
//! otherwise. In other words they import memory and cannot use multi-memory.
//! * They cannot define any `elem` or `data` segments since otherwise there's
//! no knowledge ahead-of-time of where their data or element segments could
//! go. This means things like no panics, no indirect calls, etc.
//! * If the adapter uses a shadow stack, the global that points to it must be a
//! mutable `i32` named `__stack_pointer`. This stack is automatically
//! allocated with an injected `allocate_stack` function that will either use
//! the main module's `cabi_realloc` export (if present) or `memory.grow`. It
//! allocates only 64KB of stack space, and there is no protection if that
//! overflows.
//! * If the adapter has a global, mutable `i32` named `allocation_state`, it
//! will be used to keep track of stack allocation status and avoid infinite
//! recursion if the main module's `cabi_realloc` function calls back into the
//! adapter. `allocate_stack` will check this global on entry; if it is zero,
//! it will set it to one, then allocate the stack, and finally set it to two.
//! If it is non-zero, `allocate_stack` will do nothing and return immediately
//! (because either the stack has already been allocated or is in the process
//! of being allocated). If the adapter does not have an `allocation_state`,
//! `allocate_stack` will use `memory.grow` to allocate the stack; it will
//! _not_ use the main module's `cabi_realloc` even if it's available.
//! * If the adapter imports a `cabi_realloc` function, and the main module
//! exports one, they'll be linked together via an alias. If the adapter
//! imports such a function but the main module does _not_ export one, we'll
//! synthesize one based on `memory.grow` (which will trap for any size other
//! than 64KB). Note that the main module's `cabi_realloc` function may call
//! back into the adapter before the shadow stack has been allocated. In this
//! case (when `allocation_state` is zero or one), the adapter should return
//! whatever dummy value(s) it can immediately without touching the stack.
//!
//! This means that adapter modules are not meant to be written by everyone.
//! It's assumed that these will be relatively few and far between yet still a
//! crucial part of the transition process from to the component model since
//! otherwise there's no way to run a `wasi_snapshot_preview1` module within the
//! component model.
use crate::metadata::{self, Bindgen, ModuleMetadata};
use crate::validation::{Export, ExportMap, Import, ImportInstance, ImportMap};
use crate::StringEncoding;
use anyhow::{anyhow, bail, Context, Result};
use indexmap::{IndexMap, IndexSet};
use std::borrow::Cow;
use std::collections::HashMap;
use std::hash::Hash;
use std::mem;
use wasm_encoder::*;
use wasmparser::Validator;
use wit_parser::{
abi::{AbiVariant, WasmSignature, WasmType},
Function, FunctionKind, InterfaceId, LiveTypes, Resolve, Type, TypeDefKind, TypeId, TypeOwner,
WorldItem, WorldKey,
};
const INDIRECT_TABLE_NAME: &str = "$imports";
mod wit;
pub use wit::{encode, encode_world};
mod types;
use types::{InstanceTypeEncoder, RootTypeEncoder, ValtypeEncoder};
mod world;
use world::{ComponentWorld, ImportedInterface, Lowering};
fn to_val_type(ty: &WasmType) -> ValType {
match ty {
WasmType::I32 => ValType::I32,
WasmType::I64 => ValType::I64,
WasmType::F32 => ValType::F32,
WasmType::F64 => ValType::F64,
WasmType::Pointer => ValType::I32,
WasmType::PointerOrI64 => ValType::I64,
WasmType::Length => ValType::I32,
}
}
bitflags::bitflags! {
/// Options in the `canon lower` or `canon lift` required for a particular
/// function.
#[derive(Copy, Clone, Debug)]
pub struct RequiredOptions: u8 {
/// A memory must be specified, typically the "main module"'s memory
/// export.
const MEMORY = 1 << 0;
/// A `realloc` function must be specified, typically named
/// `cabi_realloc`.
const REALLOC = 1 << 1;
/// A string encoding must be specified, which is always utf-8 for now
/// today.
const STRING_ENCODING = 1 << 2;
}
}
impl RequiredOptions {
fn for_import(resolve: &Resolve, func: &Function) -> RequiredOptions {
let sig = resolve.wasm_signature(AbiVariant::GuestImport, func);
let mut ret = RequiredOptions::empty();
// Lift the params and lower the results for imports
ret.add_lift(TypeContents::for_types(
resolve,
func.params.iter().map(|(_, t)| t),
));
ret.add_lower(TypeContents::for_types(resolve, func.results.iter_types()));
// If anything is indirect then `memory` will be required to read the
// indirect values.
if sig.retptr || sig.indirect_params {
ret |= RequiredOptions::MEMORY;
}
ret
}
fn for_export(resolve: &Resolve, func: &Function) -> RequiredOptions {
let sig = resolve.wasm_signature(AbiVariant::GuestExport, func);
let mut ret = RequiredOptions::empty();
// Lower the params and lift the results for exports
ret.add_lower(TypeContents::for_types(
resolve,
func.params.iter().map(|(_, t)| t),
));
ret.add_lift(TypeContents::for_types(resolve, func.results.iter_types()));
// If anything is indirect then `memory` will be required to read the
// indirect values, but if the arguments are indirect then `realloc` is
// additionally required to allocate space for the parameters.
if sig.retptr || sig.indirect_params {
ret |= RequiredOptions::MEMORY;
if sig.indirect_params {
ret |= RequiredOptions::REALLOC;
}
}
ret
}
fn add_lower(&mut self, types: TypeContents) {
// If lists/strings are lowered into wasm then memory is required as
// usual but `realloc` is also required to allow the external caller to
// allocate space in the destination for the list/string.
if types.contains(TypeContents::LIST) {
*self |= RequiredOptions::MEMORY | RequiredOptions::REALLOC;
}
if types.contains(TypeContents::STRING) {
*self |= RequiredOptions::MEMORY
| RequiredOptions::STRING_ENCODING
| RequiredOptions::REALLOC;
}
}
fn add_lift(&mut self, types: TypeContents) {
// Unlike for `lower` when lifting a string/list all that's needed is
// memory, since the string/list already resides in memory `realloc`
// isn't needed.
if types.contains(TypeContents::LIST) {
*self |= RequiredOptions::MEMORY;
}
if types.contains(TypeContents::STRING) {
*self |= RequiredOptions::MEMORY | RequiredOptions::STRING_ENCODING;
}
}
fn into_iter(
self,
encoding: StringEncoding,
memory_index: Option<u32>,
realloc_index: Option<u32>,
) -> Result<impl ExactSizeIterator<Item = CanonicalOption>> {
#[derive(Default)]
struct Iter {
options: [Option<CanonicalOption>; 3],
current: usize,
count: usize,
}
impl Iter {
fn push(&mut self, option: CanonicalOption) {
assert!(self.count < self.options.len());
self.options[self.count] = Some(option);
self.count += 1;
}
}
impl Iterator for Iter {
type Item = CanonicalOption;
fn next(&mut self) -> Option<Self::Item> {
if self.current == self.count {
return None;
}
let option = self.options[self.current];
self.current += 1;
option
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.count - self.current, Some(self.count - self.current))
}
}
impl ExactSizeIterator for Iter {}
let mut iter = Iter::default();
if self.contains(RequiredOptions::MEMORY) {
iter.push(CanonicalOption::Memory(memory_index.ok_or_else(|| {
anyhow!("module does not export a memory named `memory`")
})?));
}
if self.contains(RequiredOptions::REALLOC) {
iter.push(CanonicalOption::Realloc(realloc_index.ok_or_else(
|| anyhow!("module does not export a function named `cabi_realloc`"),
)?));
}
if self.contains(RequiredOptions::STRING_ENCODING) {
iter.push(encoding.into());
}
Ok(iter)
}
}
bitflags::bitflags! {
/// Flags about what kinds of types are present within the recursive
/// structure of a type.
struct TypeContents: u8 {
const STRING = 1 << 0;
const LIST = 1 << 1;
}
}
impl TypeContents {
fn for_types<'a>(resolve: &Resolve, types: impl Iterator<Item = &'a Type>) -> Self {
let mut cur = TypeContents::empty();
for ty in types {
cur |= Self::for_type(resolve, ty);
}
cur
}
fn for_optional_types<'a>(
resolve: &Resolve,
types: impl Iterator<Item = Option<&'a Type>>,
) -> Self {
Self::for_types(resolve, types.flatten())
}
fn for_optional_type(resolve: &Resolve, ty: Option<&Type>) -> Self {
match ty {
Some(ty) => Self::for_type(resolve, ty),
None => Self::empty(),
}
}
fn for_type(resolve: &Resolve, ty: &Type) -> Self {
match ty {
Type::Id(id) => match &resolve.types[*id].kind {
TypeDefKind::Handle(h) => match h {
wit_parser::Handle::Own(_) => Self::empty(),
wit_parser::Handle::Borrow(_) => Self::empty(),
},
TypeDefKind::Resource => Self::empty(),
TypeDefKind::Record(r) => Self::for_types(resolve, r.fields.iter().map(|f| &f.ty)),
TypeDefKind::Tuple(t) => Self::for_types(resolve, t.types.iter()),
TypeDefKind::Flags(_) => Self::empty(),
TypeDefKind::Option(t) => Self::for_type(resolve, t),
TypeDefKind::Result(r) => {
Self::for_optional_type(resolve, r.ok.as_ref())
| Self::for_optional_type(resolve, r.err.as_ref())
}
TypeDefKind::Variant(v) => {
Self::for_optional_types(resolve, v.cases.iter().map(|c| c.ty.as_ref()))
}
TypeDefKind::Enum(_) => Self::empty(),
TypeDefKind::List(t) => Self::for_type(resolve, t) | Self::LIST,
TypeDefKind::Type(t) => Self::for_type(resolve, t),
TypeDefKind::Future(_) => todo!("encoding for future"),
TypeDefKind::Stream(_) => todo!("encoding for stream"),
TypeDefKind::Unknown => unreachable!(),
},
Type::String => Self::STRING,
_ => Self::empty(),
}
}
}
/// State relating to encoding a component.
pub struct EncodingState<'a> {
/// The component being encoded.
component: ComponentBuilder,
/// The index into the core module index space for the inner core module.
///
/// If `None`, the core module has not been encoded.
module_index: Option<u32>,
/// The index into the core instance index space for the inner core module.
///
/// If `None`, the core module has not been instantiated.
instance_index: Option<u32>,
/// The index in the core memory index space for the exported memory.
///
/// If `None`, then the memory has not yet been aliased.
memory_index: Option<u32>,
/// The index of the shim instance used for lowering imports into the core instance.
///
/// If `None`, then the shim instance how not yet been encoded.
shim_instance_index: Option<u32>,
/// The index of the fixups module to instantiate to fill in the lowered imports.
///
/// If `None`, then a fixup module has not yet been encoded.
fixups_module_index: Option<u32>,
/// A map of named adapter modules and the index that the module was defined
/// at.
adapter_modules: IndexMap<&'a str, u32>,
/// A map of adapter module instances and the index of their instance.
adapter_instances: IndexMap<&'a str, u32>,
/// Imported instances and what index they were imported as.
imported_instances: IndexMap<InterfaceId, u32>,
imported_funcs: IndexMap<String, u32>,
exported_instances: IndexMap<InterfaceId, u32>,
/// Maps used when translating types to the component model binary format.
/// Note that imports and exports are stored in separate maps since they
/// need fresh hierarchies of types in case the same interface is both
/// imported and exported.
import_type_map: HashMap<TypeId, u32>,
import_func_type_map: HashMap<types::FunctionKey<'a>, u32>,
export_type_map: HashMap<TypeId, u32>,
export_func_type_map: HashMap<types::FunctionKey<'a>, u32>,
/// Cache of items that have been aliased from core instances.
///
/// This is a helper to reduce the number of aliases created by ensuring
/// that repeated requests for the same item return the same index of an
/// original `core alias` item.
aliased_core_items: HashMap<(u32, String), u32>,
/// Metadata about the world inferred from the input to `ComponentEncoder`.
info: &'a ComponentWorld<'a>,
}
impl<'a> EncodingState<'a> {
fn encode_core_modules(&mut self) {
assert!(self.module_index.is_none());
let idx = self.component.core_module_raw(&self.info.encoder.module);
self.module_index = Some(idx);
for (name, adapter) in self.info.adapters.iter() {
let add_meta = wasm_metadata::AddMetadata {
name: Some(if adapter.library_info.is_some() {
name.to_string()
} else {
format!("wit-component:adapter:{name}")
}),
..Default::default()
};
let wasm = add_meta
.to_wasm(&adapter.wasm)
.expect("core wasm can get name added");
let idx = self.component.core_module_raw(&wasm);
let prev = self.adapter_modules.insert(name, idx);
assert!(prev.is_none());
}
}
fn root_import_type_encoder(
&mut self,
interface: Option<InterfaceId>,
) -> RootTypeEncoder<'_, 'a> {
RootTypeEncoder {
state: self,
interface,
import_types: true,
}
}
fn root_export_type_encoder(
&mut self,
interface: Option<InterfaceId>,
) -> RootTypeEncoder<'_, 'a> {
RootTypeEncoder {
state: self,
interface,
import_types: false,
}
}
fn instance_type_encoder(&mut self, interface: InterfaceId) -> InstanceTypeEncoder<'_, 'a> {
InstanceTypeEncoder {
state: self,
interface,
type_map: Default::default(),
func_type_map: Default::default(),
ty: Default::default(),
}
}
fn encode_imports(&mut self, name_map: &HashMap<String, String>) -> Result<()> {
let mut has_funcs = false;
for (name, info) in self.info.import_map.iter() {
match name {
Some(name) => {
self.encode_interface_import(name_map.get(name).unwrap_or(name), info)?
}
None => has_funcs = true,
}
}
let resolve = &self.info.encoder.metadata.resolve;
let world = &resolve.worlds[self.info.encoder.metadata.world];
for (_name, item) in world.imports.iter() {
if let WorldItem::Type(ty) = item {
self.root_import_type_encoder(None)
.encode_valtype(resolve, &Type::Id(*ty))?;
}
}
if has_funcs {
let info = &self.info.import_map[&None];
self.encode_root_import_funcs(info)?;
}
Ok(())
}
fn encode_interface_import(&mut self, name: &str, info: &ImportedInterface) -> Result<()> {
let resolve = &self.info.encoder.metadata.resolve;
let interface_id = info.interface.as_ref().unwrap();
let interface_id = *interface_id;
let interface = &resolve.interfaces[interface_id];
log::trace!("encoding imports for `{name}` as {:?}", interface_id);
let mut encoder = self.instance_type_encoder(interface_id);
// First encode all type information
if let Some(live) = encoder.state.info.live_type_imports.get(&interface_id) {
for ty in live {
log::trace!(
"encoding extra type {ty:?} name={:?}",
resolve.types[*ty].name
);
encoder.encode_valtype(resolve, &Type::Id(*ty))?;
}
}
// Next encode all required functions from this imported interface
// into the instance type.
for (_, func) in interface.functions.iter() {
if !info.lowerings.contains_key(&func.name) {
continue;
}
log::trace!("encoding function type for `{}`", func.name);
let idx = encoder.encode_func_type(resolve, func)?;
encoder.ty.export(&func.name, ComponentTypeRef::Func(idx));
}
let ty = encoder.ty;
// Don't encode empty instance types since they're not
// meaningful to the runtime of the component anyway.
if ty.is_empty() {
return Ok(());
}
let instance_type_idx = self.component.type_instance(&ty);
let instance_idx = self
.component
.import(name, ComponentTypeRef::Instance(instance_type_idx));
let prev = self.imported_instances.insert(interface_id, instance_idx);
assert!(prev.is_none());
Ok(())
}
fn encode_root_import_funcs(&mut self, info: &ImportedInterface) -> Result<()> {
let resolve = &self.info.encoder.metadata.resolve;
let world = self.info.encoder.metadata.world;
for (name, item) in resolve.worlds[world].imports.iter() {
let func = match item {
WorldItem::Function(f) => f,
WorldItem::Interface { .. } | WorldItem::Type(_) => continue,
};
let name = resolve.name_world_key(name);
if !info.lowerings.contains_key(&name) {
continue;
}
log::trace!("encoding function type for `{}`", func.name);
let idx = self
.root_import_type_encoder(None)
.encode_func_type(resolve, func)?;
let func_idx = self.component.import(&name, ComponentTypeRef::Func(idx));
let prev = self.imported_funcs.insert(name, func_idx);
assert!(prev.is_none());
}
Ok(())
}
fn alias_imported_type(&mut self, interface: InterfaceId, id: TypeId) -> u32 {
let ty = &self.info.encoder.metadata.resolve.types[id];
let name = ty.name.as_ref().expect("type must have a name");
let instance = self.imported_instances[&interface];
self.component
.alias_export(instance, name, ComponentExportKind::Type)
}
fn alias_exported_type(&mut self, interface: InterfaceId, id: TypeId) -> u32 {
let ty = &self.info.encoder.metadata.resolve.types[id];
let name = ty.name.as_ref().expect("type must have a name");
let instance = self.exported_instances[&interface];
self.component
.alias_export(instance, name, ComponentExportKind::Type)
}
fn encode_core_instantiation(&mut self) -> Result<()> {
// Encode a shim instantiation if needed
let shims = self.encode_shim_instantiation()?;
// Next declare all exported resource types. This populates
// `export_type_map` and will additionally be used for imports to
// modules instantiated below.
self.declare_exported_resources(&shims);
// Next instantiate the main module. This provides the linear memory to
// use for all future adapters and enables creating indirect lowerings
// at the end.
self.instantiate_main_module(&shims)?;
// Separate the adapters according which should be instantiated before
// and after indirect lowerings are encoded.
let (before, after) = self
.info
.adapters
.iter()
.partition::<Vec<_>, _>(|(_, adapter)| {
!matches!(
adapter.library_info,
Some(LibraryInfo {
instantiate_after_shims: true,
..
})
)
});
for (name, _adapter) in before {
self.instantiate_adapter_module(&shims, name)?;
}
// With all the relevant core wasm instances in play now the original shim
// module, if present, can be filled in with lowerings/adapters/etc.
self.encode_indirect_lowerings(&shims)?;
for (name, _adapter) in after {
self.instantiate_adapter_module(&shims, name)?;
}
self.encode_initialize_with_start()?;
Ok(())
}
fn lookup_resource_index(&mut self, id: TypeId) -> u32 {
let resolve = &self.info.encoder.metadata.resolve;
let ty = &resolve.types[id];
match ty.owner {
// If this resource is owned by a world then it's a top-level
// resource which means it must have already been translated so
// it's available for lookup in `import_type_map`.
TypeOwner::World(_) => self.import_type_map[&id],
TypeOwner::Interface(i) => {
let instance = self.imported_instances[&i];
let name = ty.name.as_ref().expect("resources must be named");
self.component
.alias_export(instance, name, ComponentExportKind::Type)
}
TypeOwner::None => panic!("resources must have an owner"),
}
}
fn encode_exports(&mut self, module: CustomModule) -> Result<()> {
let resolve = &self.info.encoder.metadata.resolve;
let exports = match module {
CustomModule::Main => &self.info.encoder.main_module_exports,
CustomModule::Adapter(name) => &self.info.encoder.adapters[name].required_exports,
};
if exports.is_empty() {
return Ok(());
}
let mut interface_func_core_names = IndexMap::new();
let mut world_func_core_names = IndexMap::new();
for (core_name, export) in self.info.exports_for(module).iter() {
match export {
Export::WorldFunc(name) => {
let prev = world_func_core_names.insert(name, core_name);
assert!(prev.is_none());
}
Export::InterfaceFunc(id, name) => {
let prev = interface_func_core_names
.entry(id)
.or_insert(IndexMap::new())
.insert(name.as_str(), core_name);
assert!(prev.is_none());
}
Export::WorldFuncPostReturn(..)
| Export::InterfaceFuncPostReturn(..)
| Export::ResourceDtor(..)
| Export::Memory
| Export::GeneralPurposeRealloc
| Export::GeneralPurposeExportRealloc
| Export::GeneralPurposeImportRealloc
| Export::Initialize
| Export::ReallocForAdapter => continue,
}
}
let world = &resolve.worlds[self.info.encoder.metadata.world];
for export_name in exports {
let export_string = resolve.name_world_key(export_name);
match &world.exports[export_name] {
WorldItem::Function(func) => {
let ty = self
.root_import_type_encoder(None)
.encode_func_type(resolve, func)?;
let core_name = world_func_core_names[&func.name];
let idx = self.encode_lift(module, &core_name, export_name, func, ty)?;
self.component
.export(&export_string, ComponentExportKind::Func, idx, None);
}
WorldItem::Interface { id, .. } => {
let core_names = interface_func_core_names.get(id);
self.encode_interface_export(
&export_string,
module,
export_name,
*id,
core_names,
)?;
}
WorldItem::Type(_) => unreachable!(),
}
}
Ok(())
}
fn encode_interface_export(
&mut self,
export_name: &str,
module: CustomModule<'_>,
key: &WorldKey,
export: InterfaceId,
interface_func_core_names: Option<&IndexMap<&str, &str>>,
) -> Result<()> {
log::trace!("encode interface export `{export_name}`");
let resolve = &self.info.encoder.metadata.resolve;
// First execute a `canon lift` for all the functions in this interface
// from the core wasm export. This requires type information but notably
// not exported type information since we don't want to export this
// interface's types from the root of the component. Each lifted
// function is saved off into an `imports` array to get imported into
// the nested component synthesized below.
let mut imports = Vec::new();
let mut root = self.root_export_type_encoder(Some(export));
for (_, func) in &resolve.interfaces[export].functions {
let core_name = interface_func_core_names.unwrap()[func.name.as_str()];
let ty = root.encode_func_type(resolve, func)?;
let func_index = root.state.encode_lift(module, &core_name, key, func, ty)?;
imports.push((
import_func_name(func),
ComponentExportKind::Func,
func_index,
));
}
// Next a nested component is created which will import the functions
// above and then reexport them. The purpose of them is to "re-type" the
// functions through type ascription on each `func` item.
let mut nested = NestedComponentTypeEncoder {
component: ComponentBuilder::default(),
type_map: Default::default(),
func_type_map: Default::default(),
export_types: false,
interface: export,
state: self,
imports: IndexMap::new(),
};
// Import all transitively-referenced types from other interfaces into
// this component. This temporarily switches the `interface` listed to
// the interface of the referred-to-type to generate the import. After
// this loop `interface` is rewritten to `export`.
//
// Each component is a standalone "island" so the necessary type
// information needs to be rebuilt within this component. This ensures
// that we're able to build a valid component and additionally connect
// all the type information to the outer context.
let mut types_to_import = LiveTypes::default();
types_to_import.add_interface(resolve, export);
let exports_used = &nested.state.info.exports_used[&export];
for ty in types_to_import.iter() {
if let TypeOwner::Interface(owner) = resolve.types[ty].owner {
if owner == export {
// Here this deals with the current exported interface which
// is handled below.
continue;
}
// Ensure that `self` has encoded this type before. If so this
// is a noop but otherwise it generates the type here.
let mut encoder = if exports_used.contains(&owner) {
nested.state.root_export_type_encoder(Some(export))
} else {
nested.state.root_import_type_encoder(Some(export))
};
encoder.encode_valtype(resolve, &Type::Id(ty))?;
// Next generate the same type but this time within the
// component itself. The type generated above (or prior) will be
// used to satisfy this type import.
nested.interface = owner;
nested.encode_valtype(resolve, &Type::Id(ty))?;
}
}
nested.interface = export;
// Record the map of types imported to their index at where they were
// imported. This is used after imports are encoded as exported types
// will refer to these.
let imported_types = nested.type_map.clone();
// Handle resource types for this instance specially, namely importing
// them into the nested component. This models how the resource is
// imported from its definition in the outer component to get reexported
// internally. This chiefly avoids creating a second resource which is
// not desired in this situation.
let mut resources = HashMap::new();
for (_name, ty) in resolve.interfaces[export].types.iter() {
if !matches!(resolve.types[*ty].kind, TypeDefKind::Resource) {
continue;
}
let idx = match nested.encode_valtype(resolve, &Type::Id(*ty))? {
ComponentValType::Type(idx) => idx,
_ => unreachable!(),
};
resources.insert(*ty, idx);
}
// Next import each function of this interface. This will end up
// defining local types as necessary or using the types as imported
// above.
for (_, func) in resolve.interfaces[export].functions.iter() {
let ty = nested.encode_func_type(resolve, func)?;
nested
.component
.import(&import_func_name(func), ComponentTypeRef::Func(ty));
}
// Swap the `nested.type_map` which was previously from `TypeId` to
// `u32` to instead being from `u32` to `TypeId`. This reverse map is
// then used in conjunction with `self.type_map` to satisfy all type
// imports of the nested component generated. The type import's index in
// the inner component is translated to a `TypeId` via `reverse_map`
// which is then translated back to our own index space via `type_map`.
let reverse_map = nested
.type_map
.drain()
.map(|p| (p.1, p.0))
.collect::<HashMap<_, _>>();
for (name, idx) in nested.imports.drain(..) {
let id = reverse_map[&idx];
let owner = match resolve.types[id].owner {
TypeOwner::Interface(id) => id,
_ => unreachable!(),
};
let idx = if owner == export || exports_used.contains(&owner) {
log::trace!("consulting exports for {id:?}");
nested.state.export_type_map[&id]
} else {
log::trace!("consulting imports for {id:?}");
nested.state.import_type_map[&id]
};
imports.push((name, ComponentExportKind::Type, idx))
}
// Before encoding exports reset the type map to what all was imported
// from foreign interfaces. This will enable any encoded types below to
// refer to imports which, after type substitution, will point to the
// correct type in the outer component context.
nested.type_map = imported_types;
// Next the component reexports all of its imports, but notably uses the
// type ascription feature to change the type of the function. Note that
// no structural change is happening to the types here but instead types
// are getting proper names and such now that this nested component is a
// new type index space. Hence the `export_types = true` flag here which
// flows through the type encoding and when types are emitted.
nested.export_types = true;
nested.func_type_map.clear();
// To start off all type information is encoded. This will be used by
// functions below but notably this also has special handling for
// resources. Resources reexport their imported resource type under
// the final name which achieves the desired goal of threading through
// the original resource without creating a new one.
for (_, id) in resolve.interfaces[export].types.iter() {
let ty = &resolve.types[*id];
match ty.kind {
TypeDefKind::Resource => {
let idx = nested.component.export(
ty.name.as_ref().expect("resources must be named"),
ComponentExportKind::Type,
resources[id],
None,
);
nested.type_map.insert(*id, idx);
}
_ => {
nested.encode_valtype(resolve, &Type::Id(*id))?;
}
}
}
for (i, (_, func)) in resolve.interfaces[export].functions.iter().enumerate() {
let ty = nested.encode_func_type(resolve, func)?;
nested.component.export(
&func.name,
ComponentExportKind::Func,
i as u32,
Some(ComponentTypeRef::Func(ty)),
);
}
// Embed the component within our component and then instantiate it with
// the lifted functions. That final instance is then exported under the
// appropriate name as the final typed export of this component.
let component = nested.component;
let component_index = self.component.component(component);
let instance_index = self.component.instantiate(component_index, imports);
let idx = self.component.export(
export_name,
ComponentExportKind::Instance,
instance_index,
None,
);
let prev = self.exported_instances.insert(export, idx);
assert!(prev.is_none());
// After everything is all said and done remove all the type information
// about type exports of this interface. Any entries in the map
// currently were used to create the instance above but aren't the
// actual copy of the exported type since that comes from the exported
// instance itself. Entries will be re-inserted into this map as
// necessary via aliases from the exported instance which is the new
// source of truth for all these types.
for (_name, id) in resolve.interfaces[export].types.iter() {
self.export_type_map.remove(id);
}
return Ok(());
struct NestedComponentTypeEncoder<'state, 'a> {
component: ComponentBuilder,
type_map: HashMap<TypeId, u32>,
func_type_map: HashMap<types::FunctionKey<'a>, u32>,
export_types: bool,
interface: InterfaceId,
state: &'state mut EncodingState<'a>,
imports: IndexMap<String, u32>,
}
impl<'a> ValtypeEncoder<'a> for NestedComponentTypeEncoder<'_, 'a> {
fn defined_type(&mut self) -> (u32, ComponentDefinedTypeEncoder<'_>) {
self.component.type_defined()
}
fn define_function_type(&mut self) -> (u32, ComponentFuncTypeEncoder<'_>) {
self.component.type_function()
}
fn export_type(&mut self, idx: u32, name: &'a str) -> Option<u32> {
if self.export_types {
Some(
self.component
.export(name, ComponentExportKind::Type, idx, None),
)
} else {
let name = self.unique_import_name(name);
let ret = self
.component
.import(&name, ComponentTypeRef::Type(TypeBounds::Eq(idx)));
self.imports.insert(name, ret);
Some(ret)
}
}
fn export_resource(&mut self, name: &'a str) -> u32 {
if self.export_types {
panic!("resources should already be exported")
} else {
let name = self.unique_import_name(name);
let ret = self
.component
.import(&name, ComponentTypeRef::Type(TypeBounds::SubResource));
self.imports.insert(name, ret);
ret
}
}
fn import_type(&mut self, _: InterfaceId, _id: TypeId) -> u32 {
unreachable!()
}
fn type_map(&mut self) -> &mut HashMap<TypeId, u32> {
&mut self.type_map
}
fn func_type_map(&mut self) -> &mut HashMap<types::FunctionKey<'a>, u32> {
&mut self.func_type_map
}
fn interface(&self) -> Option<InterfaceId> {
Some(self.interface)
}
}
impl NestedComponentTypeEncoder<'_, '_> {
fn unique_import_name(&mut self, name: &str) -> String {
let mut name = format!("import-type-{name}");
let mut n = 0;
while self.imports.contains_key(&name) {
name = format!("{name}{n}");
n += 1;
}
name
}
}
fn import_func_name(f: &Function) -> String {
match f.kind {
FunctionKind::Freestanding => {
format!("import-func-{}", f.name)
}
// transform `[method]foo.bar` into `import-method-foo-bar` to
// have it be a valid kebab-name which can't conflict with
// anything else.
//
// There's probably a better and more "formal" way to do this
// but quick-and-dirty string manipulation should work well
// enough for now hopefully.
FunctionKind::Method(_)
| FunctionKind::Static(_)
| FunctionKind::Constructor(_) => {
format!(
"import-{}",
f.name.replace('[', "").replace([']', '.'], "-")
)
}
}
}
}
fn encode_lift(
&mut self,
module: CustomModule<'_>,
core_name: &str,
key: &WorldKey,
func: &Function,
ty: u32,
) -> Result<u32> {
let resolve = &self.info.encoder.metadata.resolve;
let metadata = self.info.module_metadata_for(module);