-
Notifications
You must be signed in to change notification settings - Fork 197
/
lib.rs
1405 lines (1277 loc) · 46.7 KB
/
lib.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::interface::InterfaceGenerator;
use anyhow::{bail, Result};
use heck::*;
use indexmap::IndexSet;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt::{self, Write as _};
use std::io::{Read, Write};
use std::mem;
use std::process::{Command, Stdio};
use std::str::FromStr;
use wit_bindgen_core::abi::{Bitcast, WasmType};
use wit_bindgen_core::{
uwrite, uwriteln, wit_parser::*, Files, InterfaceGenerator as _, Source, Types, WorldGenerator,
};
mod bindgen;
mod interface;
struct InterfaceName {
/// True when this interface name has been remapped through the use of `with` in the `bindgen!`
/// macro invocation.
remapped: bool,
/// The string name for this interface.
path: String,
}
#[derive(Default)]
struct RustWasm {
types: Types,
src: Source,
opts: Opts,
import_modules: Vec<(String, Vec<String>)>,
export_modules: Vec<(String, Vec<String>)>,
skip: HashSet<String>,
interface_names: HashMap<InterfaceId, InterfaceName>,
/// Each imported and exported interface is stored in this map. Value indicates if last use was import.
interface_last_seen_as_import: HashMap<InterfaceId, bool>,
import_funcs_called: bool,
with_name_counter: usize,
// Track the with options that were used. Remapped interfaces provided via `with`
// are required to be used.
used_with_opts: HashSet<String>,
world: Option<WorldId>,
rt_module: IndexSet<RuntimeItem>,
export_macros: Vec<(String, String)>,
with: HashMap<String, String>,
}
#[derive(PartialEq, Eq, Clone, Copy, Hash, Debug)]
enum RuntimeItem {
AllocCrate,
StringType,
StdAllocModule,
VecType,
StringLift,
InvalidEnumDiscriminant,
CharLift,
BoolLift,
CabiDealloc,
RunCtorsOnce,
AsI32,
AsI64,
AsF32,
AsF64,
ResourceType,
BoxType,
}
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum ExportKey {
World,
Name(String),
}
#[cfg(feature = "clap")]
fn parse_with(s: &str) -> Result<(String, String), String> {
let (k, v) = s.split_once('=').ok_or_else(|| {
format!("expected string of form `<key>=<value>[,<key>=<value>...]`; got `{s}`")
})?;
Ok((k.to_string(), v.to_string()))
}
#[derive(Default, Debug, Clone)]
#[cfg_attr(feature = "clap", derive(clap::Args))]
pub struct Opts {
/// Whether or not `rustfmt` is executed to format generated code.
#[cfg_attr(feature = "clap", arg(long))]
pub rustfmt: bool,
/// If true, code generation should qualify any features that depend on
/// `std` with `cfg(feature = "std")`.
#[cfg_attr(feature = "clap", arg(long))]
pub std_feature: bool,
/// If true, code generation should pass borrowed string arguments as
/// `&[u8]` instead of `&str`. Strings are still required to be valid
/// UTF-8, but this avoids the need for Rust code to do its own UTF-8
/// validation if it doesn't already have a `&str`.
#[cfg_attr(feature = "clap", arg(long))]
pub raw_strings: bool,
/// Names of functions to skip generating bindings for.
#[cfg_attr(feature = "clap", arg(long))]
pub skip: Vec<String>,
/// If true, generate stub implementations for any exported functions,
/// interfaces, and/or resources.
#[cfg_attr(feature = "clap", arg(long))]
pub stubs: bool,
/// Optionally prefix any export names with the specified value.
///
/// This is useful to avoid name conflicts when testing.
#[cfg_attr(feature = "clap", arg(long))]
pub export_prefix: Option<String>,
/// Whether to generate owning or borrowing type definitions.
///
/// Valid values include:
///
/// - `owning`: Generated types will be composed entirely of owning fields,
/// regardless of whether they are used as parameters to imports or not.
///
/// - `borrowing`: Generated types used as parameters to imports will be
/// "deeply borrowing", i.e. contain references rather than owned values
/// when applicable.
///
/// - `borrowing-duplicate-if-necessary`: As above, but generating distinct
/// types for borrowing and owning, if necessary.
#[cfg_attr(feature = "clap", arg(long, default_value_t = Ownership::Owning))]
pub ownership: Ownership,
/// The optional path to the wit-bindgen runtime module to use.
///
/// This defaults to `wit_bindgen::rt`.
#[cfg_attr(feature = "clap", arg(long))]
pub runtime_path: Option<String>,
/// The optional path to the bitflags crate to use.
///
/// This defaults to `wit_bindgen::bitflags`.
#[cfg_attr(feature = "clap", arg(long))]
pub bitflags_path: Option<String>,
/// Additional derive attributes to add to generated types. If using in a CLI, this flag can be
/// specified multiple times to add multiple attributes.
///
/// These derive attributes will be added to any generated structs or enums
#[cfg_attr(feature = "clap", arg(long = "additional_derive_attribute", short = 'd', default_values_t = Vec::<String>::new()))]
pub additional_derive_attributes: Vec<String>,
/// Remapping of interface names to rust module names.
///
/// Argument must be of the form `k=v` and this option can be passed
/// multiple times or one option can be comma separated, for example
/// `k1=v1,k2=v2`.
#[cfg_attr(feature = "clap", arg(long, value_parser = parse_with, value_delimiter = ','))]
pub with: Vec<(String, String)>,
/// Add the specified suffix to the name of the custome section containing
/// the component type.
#[cfg_attr(feature = "clap", arg(long))]
pub type_section_suffix: Option<String>,
/// Disable a workaround used to prevent libc ctors/dtors from being invoked
/// too much.
#[cfg_attr(feature = "clap", arg(long))]
pub disable_run_ctors_once_workaround: bool,
/// Changes the default module used in the generated `export!` macro to
/// something other than `self`.
#[cfg_attr(feature = "clap", arg(long))]
pub default_bindings_module: Option<String>,
/// Alternative name to use for the `export!` macro if one is generated.
#[cfg_attr(feature = "clap", arg(long))]
pub export_macro_name: Option<String>,
/// Ensures that the `export!` macro will be defined as `pub` so it is a
/// candidate for being exported outside of the crate.
#[cfg_attr(feature = "clap", arg(long))]
pub pub_export_macro: bool,
/// Whether to generate unused structures, not generated by default (false)
#[cfg_attr(feature = "clap", arg(long))]
pub generate_unused_types: bool,
}
impl Opts {
pub fn build(self) -> Box<dyn WorldGenerator> {
let mut r = RustWasm::new();
r.skip = self.skip.iter().cloned().collect();
r.opts = self;
Box::new(r)
}
}
impl RustWasm {
fn new() -> RustWasm {
RustWasm::default()
}
fn interface<'a>(
&'a mut self,
identifier: Identifier<'a>,
wasm_import_module: Option<&'a str>,
resolve: &'a Resolve,
in_import: bool,
) -> InterfaceGenerator<'a> {
let mut sizes = SizeAlign::default();
sizes.fill(resolve);
InterfaceGenerator {
identifier,
wasm_import_module,
src: Source::default(),
in_import,
gen: self,
sizes,
resolve,
return_pointer_area_size: 0,
return_pointer_area_align: 0,
needs_runtime_module: false,
}
}
fn emit_modules(&mut self, modules: Vec<(String, Vec<String>)>) {
#[derive(Default)]
struct Module {
submodules: BTreeMap<String, Module>,
contents: Vec<String>,
}
let mut map = Module::default();
for (module, path) in modules {
let mut cur = &mut map;
for name in path[..path.len() - 1].iter() {
cur = cur
.submodules
.entry(name.clone())
.or_insert(Module::default());
}
cur.contents.push(module);
}
emit(&mut self.src, map);
fn emit(me: &mut Source, module: Module) {
for (name, submodule) in module.submodules {
// Ignore dead-code warnings. If the bindings are only used
// within a crate, and not exported to a different crate, some
// parts may be unused, and that's ok.
uwriteln!(me, "#[allow(dead_code)]");
uwriteln!(me, "pub mod {name} {{");
emit(me, submodule);
uwriteln!(me, "}}");
}
for submodule in module.contents {
uwriteln!(me, "{submodule}");
}
}
}
fn runtime_path(&self) -> &str {
self.opts
.runtime_path
.as_deref()
.unwrap_or("wit_bindgen::rt")
}
fn bitflags_path(&self) -> String {
self.opts
.bitflags_path
.to_owned()
.unwrap_or(format!("{}::bitflags", self.runtime_path()))
}
fn name_interface(
&mut self,
resolve: &Resolve,
id: InterfaceId,
name: &WorldKey,
is_export: bool,
) -> bool {
let with_name = resolve.name_world_key(name);
let entry = if let Some(remapped_path) = self.with.get(&with_name) {
let name = format!("__with_name{}", self.with_name_counter);
self.used_with_opts.insert(with_name);
self.with_name_counter += 1;
uwriteln!(self.src, "use {remapped_path} as {name};");
InterfaceName {
remapped: true,
path: name,
}
} else {
let path = compute_module_path(name, resolve, is_export).join("::");
InterfaceName {
remapped: false,
path,
}
};
let remapped = entry.remapped;
self.interface_names.insert(id, entry);
remapped
}
fn finish_runtime_module(&mut self) {
if self.rt_module.is_empty() {
return;
}
self.src.push_str("mod _rt {\n");
let mut emitted = IndexSet::new();
while !self.rt_module.is_empty() {
for item in mem::take(&mut self.rt_module) {
if emitted.insert(item) {
self.emit_runtime_item(item);
}
}
}
self.src.push_str("}\n");
}
fn emit_runtime_item(&mut self, item: RuntimeItem) {
match item {
RuntimeItem::AllocCrate => {
uwriteln!(self.src, "extern crate alloc as alloc_crate;");
}
RuntimeItem::StdAllocModule => {
self.rt_module.insert(RuntimeItem::AllocCrate);
uwriteln!(self.src, "pub use alloc_crate::alloc;");
}
RuntimeItem::StringType => {
self.rt_module.insert(RuntimeItem::AllocCrate);
uwriteln!(self.src, "pub use alloc_crate::string::String;");
}
RuntimeItem::BoxType => {
self.rt_module.insert(RuntimeItem::AllocCrate);
uwriteln!(self.src, "pub use alloc_crate::boxed::Box;");
}
RuntimeItem::VecType => {
self.rt_module.insert(RuntimeItem::AllocCrate);
uwriteln!(self.src, "pub use alloc_crate::vec::Vec;");
}
RuntimeItem::CabiDealloc => {
self.rt_module.insert(RuntimeItem::StdAllocModule);
self.src.push_str(
"\
pub unsafe fn cabi_dealloc(ptr: *mut u8, size: usize, align: usize) {
if size == 0 {
return;
}
let layout = alloc::Layout::from_size_align_unchecked(size, align);
alloc::dealloc(ptr as *mut u8, layout);
}
",
);
}
RuntimeItem::StringLift => {
self.rt_module.insert(RuntimeItem::StringType);
self.src.push_str(
"\
pub unsafe fn string_lift(bytes: Vec<u8>) -> String {
if cfg!(debug_assertions) {
String::from_utf8(bytes).unwrap()
} else {
String::from_utf8_unchecked(bytes)
}
}
",
);
}
RuntimeItem::InvalidEnumDiscriminant => {
self.src.push_str(
"\
pub unsafe fn invalid_enum_discriminant<T>() -> T {
if cfg!(debug_assertions) {
panic!(\"invalid enum discriminant\")
} else {
core::hint::unreachable_unchecked()
}
}
",
);
}
RuntimeItem::CharLift => {
self.src.push_str(
"\
pub unsafe fn char_lift(val: u32) -> char {
if cfg!(debug_assertions) {
core::char::from_u32(val).unwrap()
} else {
core::char::from_u32_unchecked(val)
}
}
",
);
}
RuntimeItem::BoolLift => {
self.src.push_str(
"\
pub unsafe fn bool_lift(val: u8) -> bool {
if cfg!(debug_assertions) {
match val {
0 => false,
1 => true,
_ => panic!(\"invalid bool discriminant\"),
}
} else {
val != 0
}
}
",
);
}
RuntimeItem::RunCtorsOnce => {
let rt = self.runtime_path();
self.src.push_str(&format!(
r#"
#[cfg(target_arch = "wasm32")]
pub fn run_ctors_once() {{
{rt}::run_ctors_once();
}}
"#,
));
}
RuntimeItem::AsI32 => {
self.emit_runtime_as_trait(
"i32",
&["i32", "u32", "i16", "u16", "i8", "u8", "char", "usize"],
);
}
RuntimeItem::AsI64 => {
self.emit_runtime_as_trait("i64", &["i64", "u64"]);
}
RuntimeItem::AsF32 => {
self.emit_runtime_as_trait("f32", &["f32"]);
}
RuntimeItem::AsF64 => {
self.emit_runtime_as_trait("f64", &["f64"]);
}
RuntimeItem::ResourceType => {
self.src.push_str(
r#"
use core::fmt;
use core::marker;
use core::sync::atomic::{AtomicU32, Ordering::Relaxed};
/// A type which represents a component model resource, either imported or
/// exported into this component.
///
/// This is a low-level wrapper which handles the lifetime of the resource
/// (namely this has a destructor). The `T` provided defines the component model
/// intrinsics that this wrapper uses.
///
/// One of the chief purposes of this type is to provide `Deref` implementations
/// to access the underlying data when it is owned.
///
/// This type is primarily used in generated code for exported and imported
/// resources.
#[repr(transparent)]
pub struct Resource<T: WasmResource> {
// NB: This would ideally be `u32` but it is not. The fact that this has
// interior mutability is not exposed in the API of this type except for the
// `take_handle` method which is supposed to in theory be private.
//
// This represents, almost all the time, a valid handle value. When it's
// invalid it's stored as `u32::MAX`.
handle: AtomicU32,
_marker: marker::PhantomData<T>,
}
/// A trait which all wasm resources implement, namely providing the ability to
/// drop a resource.
///
/// This generally is implemented by generated code, not user-facing code.
#[allow(clippy::missing_safety_doc)]
pub unsafe trait WasmResource {
/// Invokes the `[resource-drop]...` intrinsic.
unsafe fn drop(handle: u32);
}
impl<T: WasmResource> Resource<T> {
#[doc(hidden)]
pub unsafe fn from_handle(handle: u32) -> Self {
debug_assert!(handle != u32::MAX);
Self {
handle: AtomicU32::new(handle),
_marker: marker::PhantomData,
}
}
/// Takes ownership of the handle owned by `resource`.
///
/// Note that this ideally would be `into_handle` taking `Resource<T>` by
/// ownership. The code generator does not enable that in all situations,
/// unfortunately, so this is provided instead.
///
/// Also note that `take_handle` is in theory only ever called on values
/// owned by a generated function. For example a generated function might
/// take `Resource<T>` as an argument but then call `take_handle` on a
/// reference to that argument. In that sense the dynamic nature of
/// `take_handle` should only be exposed internally to generated code, not
/// to user code.
#[doc(hidden)]
pub fn take_handle(resource: &Resource<T>) -> u32 {
resource.handle.swap(u32::MAX, Relaxed)
}
#[doc(hidden)]
pub fn handle(resource: &Resource<T>) -> u32 {
resource.handle.load(Relaxed)
}
}
impl<T: WasmResource> fmt::Debug for Resource<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Resource")
.field("handle", &self.handle)
.finish()
}
}
impl<T: WasmResource> Drop for Resource<T> {
fn drop(&mut self) {
unsafe {
match self.handle.load(Relaxed) {
// If this handle was "taken" then don't do anything in the
// destructor.
u32::MAX => {}
// ... but otherwise do actually destroy it with the imported
// component model intrinsic as defined through `T`.
other => T::drop(other),
}
}
}
}
"#,
);
}
}
}
// This is a workaround for in the bindings sometimes we've got `&i32` and
// sometimes we've got `i32` but that should all be able to be worked with
// as `i32`, so these helper functions are used to boil away the
// indirection.
fn emit_runtime_as_trait(&mut self, ty: &str, to_convert: &[&str]) {
let upcase = ty.to_uppercase();
self.src.push_str(&format!(
r#"
pub fn as_{ty}<T: As{upcase}>(t: T) -> {ty} {{
t.as_{ty}()
}}
pub trait As{upcase} {{
fn as_{ty}(self) -> {ty};
}}
impl<'a, T: Copy + As{upcase}> As{upcase} for &'a T {{
fn as_{ty}(self) -> {ty} {{
(*self).as_{ty}()
}}
}}
"#
));
for to_convert in to_convert {
self.src.push_str(&format!(
r#"
impl As{upcase} for {to_convert} {{
#[inline]
fn as_{ty}(self) -> {ty} {{
self as {ty}
}}
}}
"#
));
}
}
/// Generates an `export!` macro for the `world_id` specified.
///
/// This will generate a macro which will then itself invoke all the
/// other macros collected in `self.export_macros` prior. All these macros
/// are woven together in this single invocation.
fn finish_export_macro(&mut self, resolve: &Resolve, world_id: WorldId) {
if self.export_macros.is_empty() {
return;
}
let world = &resolve.worlds[world_id];
let world_name = world.name.to_snake_case();
let default_bindings_module = self
.opts
.default_bindings_module
.clone()
.unwrap_or("self".to_string());
let (macro_export, use_vis) = if self.opts.pub_export_macro {
("#[macro_export]", "pub")
} else {
("", "pub(crate)")
};
let export_macro_name = self
.opts
.export_macro_name
.as_deref()
.unwrap_or("export")
.to_string();
uwriteln!(
self.src,
r#"
/// Generates `#[no_mangle]` functions to export the specified type as the
/// root implementation of all generated traits.
///
/// For more information see the documentation of `wit_bindgen::generate!`.
///
/// ```rust
/// # macro_rules! {export_macro_name} {{ ($($t:tt)*) => (); }}
/// # trait Guest {{}}
/// struct MyType;
///
/// impl Guest for MyType {{
/// // ...
/// }}
///
/// {export_macro_name}!(MyType);
/// ```
#[allow(unused_macros)]
#[doc(hidden)]
{macro_export}
macro_rules! __export_{world_name}_impl {{
($ty:ident) => ({default_bindings_module}::{export_macro_name}!($ty with_types_in {default_bindings_module}););
($ty:ident with_types_in $($path_to_types_root:tt)*) => ("#
);
for (name, path_to_types) in self.export_macros.iter() {
let mut path = "$($path_to_types_root)*".to_string();
if !path_to_types.is_empty() {
path.push_str("::");
path.push_str(path_to_types)
}
uwriteln!(self.src, "{path}::{name}!($ty with_types_in {path});");
}
// See comments in `finish` for why this conditionally happens here.
if self.opts.pub_export_macro {
uwriteln!(self.src, "const _: () = {{");
self.emit_custom_section(resolve, world_id, "imports and exports", None);
uwriteln!(self.src, "}};");
}
uwriteln!(self.src, ")\n}}");
uwriteln!(
self.src,
"#[doc(inline)]\n\
{use_vis} use __export_{world_name}_impl as {export_macro_name};"
);
if self.opts.stubs {
uwriteln!(self.src, "export!(Stub);");
}
}
/// Generates a `#[link_section]` custom section to get smuggled through
/// `wasm-ld`.
///
/// This custom section is an encoding of the component metadata and will be
/// used as part of the `wit-component`-based componentization process.
///
/// The `section_suffix` here is used to distinguish the multiple sections
/// that this generator emits, and `func_name` is an optional function to
/// generate next to this which is used to force rustc to at least visit
/// this `static` and codegen it.
fn emit_custom_section(
&mut self,
resolve: &Resolve,
world: WorldId,
section_suffix: &str,
func_name: Option<&str>,
) {
self.src.push_str("\n#[cfg(target_arch = \"wasm32\")]\n");
// The custom section name here must start with "component-type" but
// otherwise is attempted to be unique here to ensure that this doesn't get
// concatenated to other custom sections by LLD by accident since LLD will
// concatenate custom sections of the same name.
let opts_suffix = self.opts.type_section_suffix.as_deref().unwrap_or("");
let world_name = &resolve.worlds[world].name;
let version = env!("CARGO_PKG_VERSION");
self.src.push_str(&format!(
"#[link_section = \"component-type:wit-bindgen:{version}:\
{world_name}:{section_suffix}{opts_suffix}\"]\n"
));
let mut producers = wasm_metadata::Producers::empty();
producers.add(
"processed-by",
env!("CARGO_PKG_NAME"),
env!("CARGO_PKG_VERSION"),
);
let component_type = wit_component::metadata::encode(
resolve,
world,
wit_component::StringEncoding::UTF8,
Some(&producers),
)
.unwrap();
self.src.push_str("#[doc(hidden)]\n");
self.src.push_str(&format!(
"pub static __WIT_BINDGEN_COMPONENT_TYPE: [u8; {}] = *b\"\\\n",
component_type.len()
));
let old_indent = self.src.set_indent(0);
let mut line_length = 0;
let s = self.src.as_mut_string();
for byte in component_type.iter() {
if line_length >= 80 {
s.push_str("\\\n");
line_length = 0;
}
match byte {
b'\\' => {
s.push_str("\\\\");
line_length += 2;
}
b'"' => {
s.push_str("\\\"");
line_length += 2;
}
b if b.is_ascii_alphanumeric() || b.is_ascii_punctuation() => {
s.push(char::from(*byte));
line_length += 1;
}
0 => {
s.push_str("\\0");
line_length += 2;
}
_ => {
uwrite!(s, "\\x{:02x}", byte);
line_length += 4;
}
}
}
self.src.push_str("\";\n");
self.src.set_indent(old_indent);
if let Some(func_name) = func_name {
let rt = self.runtime_path().to_string();
uwriteln!(
self.src,
"
#[inline(never)]
#[doc(hidden)]
#[cfg(target_arch = \"wasm32\")]
pub fn {func_name}() {{
{rt}::maybe_link_cabi_realloc();
}}
",
);
}
}
}
/// If the package `id` is the only package with its namespace/name combo
/// then pass through the name unmodified. If, however, there are multiple
/// versions of this package then the package module is going to get version
/// information.
fn name_package_module(resolve: &Resolve, id: PackageId) -> String {
let pkg = &resolve.packages[id];
let versions_with_same_name = resolve
.packages
.iter()
.filter_map(|(_, p)| {
if p.name.namespace == pkg.name.namespace && p.name.name == pkg.name.name {
Some(&p.name.version)
} else {
None
}
})
.collect::<Vec<_>>();
let base = pkg.name.name.to_snake_case();
if versions_with_same_name.len() == 1 {
return base;
}
let version = match &pkg.name.version {
Some(version) => version,
// If this package didn't have a version then don't mangle its name
// and other packages with the same name but with versions present
// will have their names mangled.
None => return base,
};
// Here there's multiple packages with the same name that differ only in
// version, so the version needs to be mangled into the Rust module name
// that we're generating. This in theory could look at all of
// `versions_with_same_name` and produce a minimal diff, e.g. for 0.1.0
// and 0.2.0 this could generate "foo1" and "foo2", but for now
// a simpler path is chosen to generate "foo0_1_0" and "foo0_2_0".
let version = version
.to_string()
.replace('.', "_")
.replace('-', "_")
.replace('+', "_")
.to_snake_case();
format!("{base}{version}")
}
impl WorldGenerator for RustWasm {
fn preprocess(&mut self, resolve: &Resolve, world: WorldId) {
wit_bindgen_core::generated_preamble(&mut self.src, env!("CARGO_PKG_VERSION"));
// Render some generator options to assist with debugging and/or to help
// recreate it if the original generation command is lost.
uwriteln!(self.src, "// Options used:");
if self.opts.std_feature {
uwriteln!(self.src, "// * std_feature");
}
if self.opts.raw_strings {
uwriteln!(self.src, "// * raw_strings");
}
if !self.opts.skip.is_empty() {
uwriteln!(self.src, "// * skip: {:?}", self.opts.skip);
}
if !matches!(self.opts.ownership, Ownership::Owning) {
uwriteln!(self.src, "// * ownership: {:?}", self.opts.ownership);
}
if !self.opts.additional_derive_attributes.is_empty() {
uwriteln!(
self.src,
"// * additional derives {:?}",
self.opts.additional_derive_attributes
);
}
for (k, v) in self.opts.with.iter() {
uwriteln!(self.src, "// * with {k:?} = {v:?}");
}
if let Some(default) = &self.opts.default_bindings_module {
uwriteln!(self.src, "// * default-bindings-module: {default:?}");
}
if self.opts.disable_run_ctors_once_workaround {
uwriteln!(self.src, "// * disable-run-ctors-once-workaround");
}
if let Some(s) = &self.opts.export_macro_name {
uwriteln!(self.src, "// * export-macro-name: {s}");
}
if self.opts.pub_export_macro {
uwriteln!(self.src, "// * pub-export-macro");
}
self.types.analyze(resolve);
self.world = Some(world);
for (k, v) in self.opts.with.iter() {
self.with.insert(k.clone(), v.clone());
}
}
fn import_interface(
&mut self,
resolve: &Resolve,
name: &WorldKey,
id: InterfaceId,
_files: &mut Files,
) {
self.interface_last_seen_as_import.insert(id, true);
let wasm_import_module = resolve.name_world_key(name);
let mut gen = self.interface(
Identifier::Interface(id, name),
Some(&wasm_import_module),
resolve,
true,
);
let (snake, module_path) = gen.start_append_submodule(name);
if gen.gen.name_interface(resolve, id, name, false) {
return;
}
gen.types(id);
gen.generate_imports(resolve.interfaces[id].functions.values());
gen.finish_append_submodule(&snake, module_path);
}
fn import_funcs(
&mut self,
resolve: &Resolve,
world: WorldId,
funcs: &[(&str, &Function)],
_files: &mut Files,
) {
self.import_funcs_called = true;
let mut gen = self.interface(Identifier::World(world), Some("$root"), resolve, true);
gen.generate_imports(funcs.iter().map(|(_, func)| *func));
let src = gen.finish();
self.src.push_str(&src);
}
fn export_interface(
&mut self,
resolve: &Resolve,
name: &WorldKey,
id: InterfaceId,
_files: &mut Files,
) -> Result<()> {
self.interface_last_seen_as_import.insert(id, false);
let mut gen = self.interface(Identifier::Interface(id, name), None, resolve, false);
let (snake, module_path) = gen.start_append_submodule(name);
if gen.gen.name_interface(resolve, id, name, true) {
return Ok(());
}
gen.types(id);
let macro_name =
gen.generate_exports(Some((id, name)), resolve.interfaces[id].functions.values())?;
gen.finish_append_submodule(&snake, module_path);
self.export_macros
.push((macro_name, self.interface_names[&id].path.clone()));
if self.opts.stubs {
let world_id = self.world.unwrap();
let mut gen = self.interface(Identifier::World(world_id), None, resolve, false);
gen.generate_stub(Some((id, name)), resolve.interfaces[id].functions.values());
let stub = gen.finish();
self.src.push_str(&stub);
}
Ok(())
}
fn export_funcs(
&mut self,
resolve: &Resolve,
world: WorldId,
funcs: &[(&str, &Function)],
_files: &mut Files,
) -> Result<()> {
let mut gen = self.interface(Identifier::World(world), None, resolve, false);
let macro_name = gen.generate_exports(None, funcs.iter().map(|f| f.1))?;
let src = gen.finish();
self.src.push_str(&src);
self.export_macros.push((macro_name, String::new()));
if self.opts.stubs {
let mut gen = self.interface(Identifier::World(world), None, resolve, false);
gen.generate_stub(None, funcs.iter().map(|f| f.1));
let stub = gen.finish();
self.src.push_str(&stub);
}
Ok(())
}
fn import_types(
&mut self,
resolve: &Resolve,
world: WorldId,
types: &[(&str, TypeId)],
_files: &mut Files,
) {
let mut gen = self.interface(Identifier::World(world), Some("$root"), resolve, true);
for (name, ty) in types {
gen.define_type(name, *ty);
}
let src = gen.finish();
self.src.push_str(&src);
}
fn finish_imports(&mut self, resolve: &Resolve, world: WorldId, files: &mut Files) {
if !self.import_funcs_called {
// We call `import_funcs` even if the world doesn't import any
// functions since one of the side effects of that method is to
// generate `struct`s for any imported resources.
self.import_funcs(resolve, world, &[], files);
}
}
fn finish(&mut self, resolve: &Resolve, world: WorldId, files: &mut Files) -> Result<()> {
let name = &resolve.worlds[world].name;
let imports = mem::take(&mut self.import_modules);
self.emit_modules(imports);