forked from bytecodealliance/wasm-tools
-
Notifications
You must be signed in to change notification settings - Fork 1
/
encoding.rs
2387 lines (2158 loc) · 86.3 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 sill 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.
//! * Only one mutable global is allowed and it's assumed to be the stack
//! pointer. This stack pointer is automatically configured with an injected
//! `start` function that is allocated with `memory.grow (i32.const 1)`,
//! meaning that the shim module has 64k of stack space and no protection if
//! that overflows.
//!
//! 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, BindgenMetadata};
use crate::{
validation::{
validate_adapter_module, validate_module, ValidatedAdapter, ValidatedModule,
MAIN_MODULE_IMPORT_NAME,
},
ComponentInterfaces, StringEncoding,
};
use anyhow::{anyhow, bail, Context, Result};
use indexmap::{map::Entry, IndexMap, IndexSet};
use std::hash::{Hash, Hasher};
use std::mem;
use wasm_encoder::*;
use wasmparser::{FuncType, Validator, WasmFeatures};
use wit_parser::{
abi::{AbiVariant, WasmSignature, WasmType},
Enum, Flags, Function, FunctionKind, Interface, Params, Record, Result_, Results, Tuple, Type,
TypeDef, TypeDefKind, Union, Variant,
};
const INDIRECT_TABLE_NAME: &str = "$imports";
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,
}
}
struct TypeKey<'a> {
interface: &'a Interface,
ty: Type,
}
impl Hash for TypeKey<'_> {
fn hash<H: Hasher>(&self, state: &mut H) {
match self.ty {
Type::Id(id) => TypeDefKey::new(self.interface, &self.interface.types[id]).hash(state),
_ => self.ty.hash(state),
}
}
}
impl PartialEq for TypeKey<'_> {
fn eq(&self, other: &Self) -> bool {
match (self.ty, other.ty) {
(Type::Id(id), Type::Id(other_id)) => {
TypeDefKey::new(self.interface, &self.interface.types[id])
== TypeDefKey::new(other.interface, &other.interface.types[other_id])
}
_ => self.ty.eq(&other.ty),
}
}
}
impl Eq for TypeKey<'_> {}
/// Represents a key type for interface type definitions.
pub struct TypeDefKey<'a> {
interface: &'a Interface,
def: &'a TypeDef,
}
impl<'a> TypeDefKey<'a> {
fn new(interface: &'a Interface, def: &'a TypeDef) -> Self {
Self { interface, def }
}
}
impl PartialEq for TypeDefKey<'_> {
fn eq(&self, other: &Self) -> bool {
let def = self.def;
let other_def = other.def;
def.name == other_def.name
&& match (&def.kind, &other_def.kind) {
(TypeDefKind::Record(r1), TypeDefKind::Record(r2)) => {
if r1.fields.len() != r2.fields.len() {
return false;
}
r1.fields.iter().zip(r2.fields.iter()).all(|(f1, f2)| {
f1.name == f2.name
&& TypeKey {
interface: self.interface,
ty: f1.ty,
}
.eq(&TypeKey {
interface: other.interface,
ty: f2.ty,
})
})
}
(TypeDefKind::Tuple(t1), TypeDefKind::Tuple(t2)) => {
if t1.types.len() != t2.types.len() {
return false;
}
t1.types.iter().zip(t2.types.iter()).all(|(t1, t2)| {
TypeKey {
interface: self.interface,
ty: *t1,
}
.eq(&TypeKey {
interface: other.interface,
ty: *t2,
})
})
}
(TypeDefKind::Flags(f1), TypeDefKind::Flags(f2)) => {
if f1.flags.len() != f2.flags.len() {
return false;
}
f1.flags
.iter()
.zip(f2.flags.iter())
.all(|(f1, f2)| f1.name == f2.name)
}
(TypeDefKind::Variant(v1), TypeDefKind::Variant(v2)) => {
if v1.cases.len() != v2.cases.len() {
return false;
}
v1.cases.iter().zip(v2.cases.iter()).all(|(c1, c2)| {
c1.name == c2.name
&& match (c1.ty, c2.ty) {
(Some(ty1), Some(ty2)) => {
TypeKey {
interface: self.interface,
ty: ty1,
} == TypeKey {
interface: other.interface,
ty: ty2,
}
}
(None, None) => true,
_ => false,
}
})
}
(TypeDefKind::Union(v1), TypeDefKind::Union(v2)) => {
if v1.cases.len() != v2.cases.len() {
return false;
}
v1.cases.iter().zip(v2.cases.iter()).all(|(c1, c2)| {
TypeKey {
interface: self.interface,
ty: c1.ty,
} == TypeKey {
interface: other.interface,
ty: c2.ty,
}
})
}
(TypeDefKind::Enum(e1), TypeDefKind::Enum(e2)) => {
if e1.cases.len() != e2.cases.len() {
return false;
}
e1.cases
.iter()
.zip(e2.cases.iter())
.all(|(c1, c2)| c1.name == c2.name)
}
(TypeDefKind::List(t1), TypeDefKind::List(t2))
| (TypeDefKind::Type(t1), TypeDefKind::Type(t2))
| (TypeDefKind::Option(t1), TypeDefKind::Option(t2)) => TypeKey {
interface: self.interface,
ty: *t1,
}
.eq(&TypeKey {
interface: other.interface,
ty: *t2,
}),
(TypeDefKind::Result(r1), TypeDefKind::Result(r2)) => {
let ok_eq = match (r1.ok, r2.ok) {
(Some(ok1), Some(ok2)) => {
TypeKey {
interface: self.interface,
ty: ok1,
} == TypeKey {
interface: other.interface,
ty: ok2,
}
}
(None, None) => true,
_ => false,
};
let err_eq = match (r1.err, r2.err) {
(Some(err1), Some(err2)) => {
TypeKey {
interface: self.interface,
ty: err1,
} == TypeKey {
interface: other.interface,
ty: err2,
}
}
(None, None) => true,
_ => false,
};
ok_eq && err_eq
}
_ => false,
}
}
}
impl Eq for TypeDefKey<'_> {}
impl Hash for TypeDefKey<'_> {
fn hash<H: Hasher>(&self, state: &mut H) {
let def = self.def;
def.name.hash(state);
match &def.kind {
TypeDefKind::Record(r) => {
state.write_u8(0);
r.fields.len().hash(state);
for f in &r.fields {
f.name.hash(state);
TypeKey {
interface: self.interface,
ty: f.ty,
}
.hash(state);
}
}
TypeDefKind::Tuple(t) => {
state.write_u8(1);
t.types.len().hash(state);
for ty in &t.types {
TypeKey {
interface: self.interface,
ty: *ty,
}
.hash(state);
}
}
TypeDefKind::Flags(r) => {
state.write_u8(2);
r.flags.len().hash(state);
for f in &r.flags {
f.name.hash(state);
}
}
TypeDefKind::Variant(v) => {
state.write_u8(3);
v.cases.len().hash(state);
for c in &v.cases {
c.name.hash(state);
c.ty.map(|ty| TypeKey {
interface: self.interface,
ty,
})
.hash(state);
}
}
TypeDefKind::Enum(e) => {
state.write_u8(4);
e.cases.len().hash(state);
for c in &e.cases {
c.name.hash(state);
}
}
TypeDefKind::List(ty) => {
state.write_u8(5);
TypeKey {
interface: self.interface,
ty: *ty,
}
.hash(state);
}
TypeDefKind::Type(ty) => {
state.write_u8(6);
TypeKey {
interface: self.interface,
ty: *ty,
}
.hash(state);
}
TypeDefKind::Option(ty) => {
state.write_u8(7);
TypeKey {
interface: self.interface,
ty: *ty,
}
.hash(state);
}
TypeDefKind::Result(r) => {
state.write_u8(8);
r.ok.map(|ty| TypeKey {
interface: self.interface,
ty,
})
.hash(state);
r.err
.map(|ty| TypeKey {
interface: self.interface,
ty,
})
.hash(state);
}
TypeDefKind::Union(u) => {
state.write_u8(9);
u.cases.len().hash(state);
for case in u.cases.iter() {
TypeKey {
interface: self.interface,
ty: case.ty,
}
.hash(state);
}
}
TypeDefKind::Future(_) => todo!("hash for future"),
TypeDefKind::Stream(_) => todo!("hash for stream"),
}
}
}
/// Represents a key type for interface function definitions.
pub struct FunctionKey<'a> {
interface: &'a Interface,
func: &'a Function,
}
impl PartialEq for FunctionKey<'_> {
fn eq(&self, other: &Self) -> bool {
if self.func.params.len() != other.func.params.len() {
return false;
}
let key_equal = |t1, t2| {
TypeKey {
interface: self.interface,
ty: t1,
}
.eq(&TypeKey {
interface: other.interface,
ty: t2,
})
};
let params_equal = |ps: &Params, ops: &Params| {
ps.len() == ops.len()
&& ps
.iter()
.zip(ops.iter())
.all(|((n1, t1), (n2, t2))| n1 == n2 && key_equal(*t1, *t2))
};
let results_equal = |rs: &Results, ors: &Results| match (rs, ors) {
(Results::Named(rs), Results::Named(ors)) => params_equal(rs, ors),
(Results::Anon(ty), Results::Anon(oty)) => key_equal(*ty, *oty),
_ => false,
};
params_equal(&self.func.params, &other.func.params)
&& results_equal(&self.func.results, &other.func.results)
}
}
impl Eq for FunctionKey<'_> {}
impl Hash for FunctionKey<'_> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.func.params.len().hash(state);
for (name, ty) in self.func.params.iter() {
name.hash(state);
TypeKey {
interface: self.interface,
ty: *ty,
}
.hash(state);
}
match &self.func.results {
Results::Named(rs) => {
state.write_u8(0);
rs.len().hash(state);
for (name, ty) in rs.iter() {
name.hash(state);
TypeKey {
interface: self.interface,
ty: *ty,
}
.hash(state);
}
}
Results::Anon(ty) => {
state.write_u8(1);
TypeKey {
interface: self.interface,
ty: *ty,
}
.hash(state);
}
}
}
}
#[derive(Default)]
struct InstanceTypeEncoder<'a> {
ty: InstanceType,
aliased_types: IndexMap<ComponentTypeRef, ComponentTypeRef>,
exported_types: IndexMap<&'a str, ComponentTypeRef>,
}
impl<'a> InstanceTypeEncoder<'a> {
fn export(&mut self, name: &'a str, type_ref: ComponentTypeRef) -> Result<()> {
match self.exported_types.entry(name) {
Entry::Occupied(e) => {
if *e.get() != type_ref {
bail!("duplicate export `{}`", name)
}
}
Entry::Vacant(entry) => {
entry.insert(type_ref);
let alias = self.alias_type(type_ref);
self.ty.export(name, alias);
}
}
Ok(())
}
fn alias_type(&mut self, type_ref: ComponentTypeRef) -> ComponentTypeRef {
match self.aliased_types.entry(type_ref) {
Entry::Occupied(e) => *e.get(),
Entry::Vacant(e) => {
let index = self.ty.type_count();
let (alias, outer_index) = match type_ref {
ComponentTypeRef::Module(outer) => (ComponentTypeRef::Module(index), outer),
ComponentTypeRef::Func(outer) => (ComponentTypeRef::Func(index), outer),
ComponentTypeRef::Value(ComponentValType::Primitive(_)) => unreachable!(),
ComponentTypeRef::Value(ComponentValType::Type(outer)) => (
ComponentTypeRef::Value(ComponentValType::Type(index)),
outer,
),
ComponentTypeRef::Type(bounds, outer) => {
(ComponentTypeRef::Type(bounds, index), outer)
}
ComponentTypeRef::Instance(outer) => (ComponentTypeRef::Instance(index), outer),
ComponentTypeRef::Component(outer) => {
(ComponentTypeRef::Component(index), outer)
}
};
self.ty.alias_outer_type(1, outer_index);
e.insert(alias);
alias
}
}
}
}
#[derive(Default)]
struct TypeEncoder<'a> {
types: ComponentTypeSection,
type_map: IndexMap<TypeDefKey<'a>, u32>,
func_type_map: IndexMap<FunctionKey<'a>, u32>,
exports: ComponentExportSection,
}
impl<'a> TypeEncoder<'a> {
fn finish(&self, component: &mut ComponentEncoding) {
if !self.types.is_empty() {
component.flush();
component.component.section(&self.types);
}
if !self.exports.is_empty() {
component.flush();
component.component.section(&self.exports);
}
}
fn encode_instance_imports(
&mut self,
interfaces: &'a IndexMap<String, Interface>,
info: Option<&ValidatedModule<'a>>,
imports: &mut ImportEncoder<'a>,
) -> Result<()> {
for (name, import) in interfaces {
let required_funcs = match info {
Some(info) => match info.required_imports.get(name.as_str()) {
Some(required) => Some(required),
None => continue,
},
None => None,
};
self.encode_instance_import(name, import, required_funcs, imports)?;
}
Ok(())
}
/// Encodes an import of the `import` interface specified which will be
/// slimmed down to the `required_funcs` set, if specified.
///
/// The imported instance, if any, is placed within `imports`.
fn encode_instance_import(
&mut self,
name: &'a str,
import: &'a Interface,
required_funcs: Option<&IndexSet<&'a str>>,
imports: &mut ImportEncoder<'a>,
) -> Result<()> {
if let Some(index) = self.encode_interface_as_instance_type(import, required_funcs)? {
imports.import(
name,
import,
ComponentTypeRef::Instance(index),
required_funcs,
)?;
}
Ok(())
}
/// Generates an instance type index representing `import` slimmed down to
/// `required_funcs`, if specified.
fn encode_interface_as_instance_type(
&mut self,
import: &'a Interface,
required_funcs: Option<&IndexSet<&'a str>>,
) -> Result<Option<u32>> {
let exports =
match self.encode_interface_as_instance_type_exports(import, required_funcs)? {
Some(exports) => exports,
None => return Ok(None),
};
let mut instance = InstanceTypeEncoder::default();
for (name, ty) in exports {
instance.export(name, ty)?;
}
Ok(Some(self.encode_instance_type(&instance.ty)))
}
/// Generates a list of items that make up `import`.
fn encode_interface_as_instance_type_exports(
&mut self,
import: &'a Interface,
required_funcs: Option<&IndexSet<&'a str>>,
) -> Result<Option<Vec<(&'a str, ComponentTypeRef)>>> {
// Don't import empty instances if no functions are actually required
// from this interface.
match required_funcs {
Some(funcs) if funcs.is_empty() => return Ok(None),
_ => {}
}
let mut exports = self.encode_interface_named_types(import)?;
for func in &import.functions {
if let Some(required_funcs) = required_funcs {
if !required_funcs.contains(func.name.as_str()) {
continue;
}
}
Self::validate_function(func)?;
let index = self.encode_func_type(import, func)?;
exports.push((func.name.as_str(), ComponentTypeRef::Func(index)));
}
Ok(Some(exports))
}
fn encode_interface_named_types(
&mut self,
interface: &'a Interface,
) -> Result<Vec<(&'a str, ComponentTypeRef)>> {
let mut exports = Vec::new();
for (id, def) in &interface.types {
let name = match &def.name {
Some(name) => name,
None => continue,
};
let idx = match self.encode_valtype(interface, &Type::Id(id))? {
ComponentValType::Type(idx) => idx,
// With a name this type should be converted to an indexed type
// automatically and this shouldn't be possible.
ComponentValType::Primitive(_) => unreachable!(),
};
exports.push((name.as_str(), ComponentTypeRef::Type(TypeBounds::Eq, idx)));
}
Ok(exports)
}
fn encode_func_types(&mut self, interfaces: impl Iterator<Item = &'a Interface>) -> Result<()> {
for export in interfaces {
// TODO: stick interface documentation in a custom section?
for func in &export.functions {
Self::validate_function(func)?;
self.encode_func_type(export, func)?;
}
}
Ok(())
}
fn encode_instance_type(&mut self, ty: &InstanceType) -> u32 {
let index = self.types.len();
self.types.instance(ty);
index
}
fn encode_params(
&mut self,
interface: &'a Interface,
params: &'a Params,
) -> Result<Vec<(&'a str, ComponentValType)>> {
params
.iter()
.map(|(name, ty)| Ok((name.as_str(), self.encode_valtype(interface, ty)?)))
.collect::<Result<_>>()
}
fn encode_func_type(&mut self, interface: &'a Interface, func: &'a Function) -> Result<u32> {
let key = FunctionKey { interface, func };
if let Some(index) = self.func_type_map.get(&key) {
return Ok(*index);
}
// Encode all referenced parameter types from this function.
let params: Vec<_> = self.encode_params(interface, &func.params)?;
enum EncodedResults<'a> {
Named(Vec<(&'a str, ComponentValType)>),
Anon(ComponentValType),
}
let results = match &func.results {
Results::Named(rs) => EncodedResults::Named(self.encode_params(interface, rs)?),
Results::Anon(ty) => EncodedResults::Anon(self.encode_valtype(interface, ty)?),
};
// Encode the function type
let index = self.types.len();
let mut f = self.types.function();
f.params(params);
match results {
EncodedResults::Named(rs) => f.results(rs),
EncodedResults::Anon(ty) => f.result(ty),
};
self.func_type_map.insert(key, index);
Ok(index)
}
fn encode_valtype(&mut self, interface: &'a Interface, ty: &Type) -> Result<ComponentValType> {
Ok(match ty {
Type::Bool => ComponentValType::Primitive(PrimitiveValType::Bool),
Type::U8 => ComponentValType::Primitive(PrimitiveValType::U8),
Type::U16 => ComponentValType::Primitive(PrimitiveValType::U16),
Type::U32 => ComponentValType::Primitive(PrimitiveValType::U32),
Type::U64 => ComponentValType::Primitive(PrimitiveValType::U64),
Type::S8 => ComponentValType::Primitive(PrimitiveValType::S8),
Type::S16 => ComponentValType::Primitive(PrimitiveValType::S16),
Type::S32 => ComponentValType::Primitive(PrimitiveValType::S32),
Type::S64 => ComponentValType::Primitive(PrimitiveValType::S64),
Type::Float32 => ComponentValType::Primitive(PrimitiveValType::Float32),
Type::Float64 => ComponentValType::Primitive(PrimitiveValType::Float64),
Type::Char => ComponentValType::Primitive(PrimitiveValType::Char),
Type::String => ComponentValType::Primitive(PrimitiveValType::String),
Type::Id(id) => {
let ty = &interface.types[*id];
let key = TypeDefKey::new(interface, &interface.types[*id]);
let encoded = if let Some(index) = self.type_map.get(&key) {
ComponentValType::Type(*index)
} else {
let mut encoded = match &ty.kind {
TypeDefKind::Record(r) => self.encode_record(interface, r)?,
TypeDefKind::Tuple(t) => self.encode_tuple(interface, t)?,
TypeDefKind::Flags(r) => self.encode_flags(r)?,
TypeDefKind::Variant(v) => self.encode_variant(interface, v)?,
TypeDefKind::Union(u) => self.encode_union(interface, u)?,
TypeDefKind::Option(t) => self.encode_option(interface, t)?,
TypeDefKind::Result(r) => self.encode_result(interface, r)?,
TypeDefKind::Enum(e) => self.encode_enum(e)?,
TypeDefKind::List(ty) => {
let ty = self.encode_valtype(interface, ty)?;
let index = self.types.len();
let encoder = self.types.defined_type();
encoder.list(ty);
ComponentValType::Type(index)
}
TypeDefKind::Type(ty) => self.encode_valtype(interface, ty)?,
TypeDefKind::Future(_) => todo!("encoding for future type"),
TypeDefKind::Stream(_) => todo!("encoding for stream type"),
};
if ty.name.is_some() {
if let ComponentValType::Primitive(ty) = encoded {
// Named primitive types need entries in the type
// section, so convert this to a type reference
let index = self.types.len();
self.types.defined_type().primitive(ty);
encoded = ComponentValType::Type(index);
}
}
if let ComponentValType::Type(index) = encoded {
self.type_map.insert(key, index);
}
encoded
};
encoded
}
})
}
fn encode_optional_valtype(
&mut self,
interface: &'a Interface,
ty: Option<&Type>,
) -> Result<Option<ComponentValType>> {
match ty {
Some(ty) => self.encode_valtype(interface, ty).map(Some),
None => Ok(None),
}
}
fn encode_record(
&mut self,
interface: &'a Interface,
record: &Record,
) -> Result<ComponentValType> {
let fields = record
.fields
.iter()
.map(|f| Ok((f.name.as_str(), self.encode_valtype(interface, &f.ty)?)))
.collect::<Result<Vec<_>>>()?;
let index = self.types.len();
let encoder = self.types.defined_type();
encoder.record(fields);
Ok(ComponentValType::Type(index))
}
fn encode_tuple(
&mut self,
interface: &'a Interface,
tuple: &Tuple,
) -> Result<ComponentValType> {
let tys = tuple
.types
.iter()
.map(|ty| self.encode_valtype(interface, ty))
.collect::<Result<Vec<_>>>()?;
let index = self.types.len();
let encoder = self.types.defined_type();
encoder.tuple(tys);
Ok(ComponentValType::Type(index))
}
fn encode_flags(&mut self, flags: &Flags) -> Result<ComponentValType> {
let index = self.types.len();
let encoder = self.types.defined_type();
encoder.flags(flags.flags.iter().map(|f| f.name.as_str()));
Ok(ComponentValType::Type(index))
}
fn encode_variant(
&mut self,
interface: &'a Interface,
variant: &Variant,
) -> Result<ComponentValType> {
let cases = variant
.cases
.iter()
.map(|c| {
Ok((
c.name.as_str(),
self.encode_optional_valtype(interface, c.ty.as_ref())?,
None, // TODO: support defaulting case values in the future
))
})
.collect::<Result<Vec<_>>>()?;
let index = self.types.len();
let encoder = self.types.defined_type();
encoder.variant(cases);
Ok(ComponentValType::Type(index))
}
fn encode_union(
&mut self,
interface: &'a Interface,
union: &Union,
) -> Result<ComponentValType> {
let tys = union
.cases
.iter()
.map(|c| self.encode_valtype(interface, &c.ty))
.collect::<Result<Vec<_>>>()?;
let index = self.types.len();
let encoder = self.types.defined_type();
encoder.union(tys);
Ok(ComponentValType::Type(index))
}
fn encode_option(
&mut self,
interface: &'a Interface,
payload: &Type,
) -> Result<ComponentValType> {
let ty = self.encode_valtype(interface, payload)?;
let index = self.types.len();
let encoder = self.types.defined_type();
encoder.option(ty);
Ok(ComponentValType::Type(index))
}
fn encode_result(
&mut self,
interface: &'a Interface,
result: &Result_,
) -> Result<ComponentValType> {
let ok = self.encode_optional_valtype(interface, result.ok.as_ref())?;
let error = self.encode_optional_valtype(interface, result.err.as_ref())?;
let index = self.types.len();
let encoder = self.types.defined_type();
encoder.result(ok, error);
Ok(ComponentValType::Type(index))
}
fn encode_enum(&mut self, enum_: &Enum) -> Result<ComponentValType> {
let index = self.types.len();
let encoder = self.types.defined_type();
encoder.enum_type(enum_.cases.iter().map(|c| c.name.as_str()));
Ok(ComponentValType::Type(index))
}
fn validate_function(function: &Function) -> Result<()> {
if function.name.is_empty() {
bail!("interface has an unnamed function");
}
if !matches!(function.kind, FunctionKind::Freestanding) {
bail!(
"unsupported function `{}`: only free-standing functions are currently supported",
function.name
);
}
Ok(())
}
}
bitflags::bitflags! {
/// Options in the `canon lower` or `canon lift` required for a particular
/// function.
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(interface: &Interface, func: &Function) -> RequiredOptions {
let sig = interface.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(
interface,
func.params.iter().map(|(_, t)| t),
));
ret.add_lower(TypeContents::for_types(
interface,
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(interface: &Interface, func: &Function) -> RequiredOptions {
let sig = interface.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(
interface,
func.params.iter().map(|(_, t)| t),
));
ret.add_lift(TypeContents::for_types(
interface,
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;
}