-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
mod.rs
4600 lines (4140 loc) · 168 KB
/
mod.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::descriptor::VectorKind;
use crate::intrinsic::Intrinsic;
use crate::wit::{
Adapter, AdapterId, AdapterJsImportKind, AdapterType, AuxExportedMethodKind, AuxReceiverKind,
AuxStringEnum, AuxValue,
};
use crate::wit::{AdapterKind, Instruction, InstructionData};
use crate::wit::{AuxEnum, AuxExport, AuxExportKind, AuxImport, AuxStruct};
use crate::wit::{JsImport, JsImportName, NonstandardWitSection, WasmBindgenAux};
use crate::{reset_indentation, Bindgen, EncodeInto, OutputMode, PLACEHOLDER_MODULE};
use anyhow::{anyhow, bail, Context as _, Error};
use binding::TsReference;
use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fmt;
use std::fmt::Write;
use std::fs;
use std::path::{Path, PathBuf};
use walrus::{FunctionId, ImportId, MemoryId, Module, TableId, ValType};
mod binding;
pub struct Context<'a> {
globals: String,
imports_post: String,
typescript: String,
exposed_globals: Option<HashSet<Cow<'static, str>>>,
next_export_idx: usize,
config: &'a Bindgen,
pub module: &'a mut Module,
aux: &'a WasmBindgenAux,
wit: &'a NonstandardWitSection,
/// A map representing the `import` statements we'll be generating in the JS
/// glue. The key is the module we're importing from and the value is the
/// list of identifier we're importing from the module, with optional
/// renames for each identifier.
js_imports: HashMap<String, Vec<(String, Option<String>)>>,
/// A map of each Wasm import and what JS to hook up to it.
wasm_import_definitions: HashMap<ImportId, String>,
/// A map from an import to the name we've locally imported it as.
imported_names: HashMap<JsImportName, String>,
/// A set of all defined identifiers through either exports or imports to
/// the number of times they've been used, used to generate new
/// identifiers.
defined_identifiers: HashMap<String, usize>,
/// A set of all (tracked) symbols referenced from within type definitions,
/// function signatures, etc.
typescript_refs: HashSet<TsReference>,
/// String enums that are used internally by the generated bindings.
///
/// This tracks which string enums are used independently from whether their
/// type is used, because users may only use them in a way that doesn't
/// require the type or requires only the type.
used_string_enums: HashSet<String>,
exported_classes: Option<BTreeMap<String, ExportedClass>>,
/// A map of the name of npm dependencies we've loaded so far to the path
/// they're defined in as well as their version specification.
pub npm_dependencies: HashMap<String, (PathBuf, String)>,
/// A mapping from the memory IDs as we see them to an index for that memory,
/// used in function names, as well as all the kinds of views we've created
/// of that memory.
///
/// `BTreeMap` and `BTreeSet` are used to make the ordering deterministic.
memories: BTreeMap<MemoryId, (usize, BTreeSet<&'static str>)>,
table_indices: HashMap<TableId, usize>,
/// A flag to track if the stack pointer setter shim has been injected.
stack_pointer_shim_injected: bool,
/// If threading is enabled.
threads_enabled: bool,
}
#[derive(Default)]
struct ExportedClass {
comments: String,
contents: String,
/// The TypeScript for the class's methods.
typescript: String,
/// Whether TypeScript for this class should be emitted (i.e., `skip_typescript` wasn't specified).
generate_typescript: bool,
has_constructor: bool,
wrap_needed: bool,
unwrap_needed: bool,
/// Whether to generate helper methods for inspecting the class
is_inspectable: bool,
/// All readable properties of the class
readable_properties: Vec<String>,
/// Map from field to information about those fields
typescript_fields: HashMap<FieldLocation, FieldInfo>,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct FieldLocation {
name: String,
is_static: bool,
}
#[derive(Debug)]
struct FieldInfo {
name: String,
is_static: bool,
order: usize,
getter: Option<FieldAccessor>,
setter: Option<FieldAccessor>,
}
/// A getter or setter for a field.
#[derive(Debug)]
struct FieldAccessor {
ty: String,
docs: String,
is_optional: bool,
}
const INITIAL_HEAP_VALUES: &[&str] = &["undefined", "null", "true", "false"];
// Must be kept in sync with `src/lib.rs` of the `wasm-bindgen` crate
const INITIAL_HEAP_OFFSET: usize = 128;
impl<'a> Context<'a> {
pub fn new(
module: &'a mut Module,
config: &'a Bindgen,
wit: &'a NonstandardWitSection,
aux: &'a WasmBindgenAux,
) -> Result<Context<'a>, Error> {
Ok(Context {
globals: String::new(),
imports_post: String::new(),
typescript: "/* tslint:disable */\n/* eslint-disable */\n".to_string(),
exposed_globals: Some(Default::default()),
imported_names: Default::default(),
js_imports: Default::default(),
defined_identifiers: Default::default(),
wasm_import_definitions: Default::default(),
typescript_refs: Default::default(),
used_string_enums: Default::default(),
exported_classes: Some(Default::default()),
config,
threads_enabled: config.threads.is_enabled(module),
module,
npm_dependencies: Default::default(),
next_export_idx: 0,
wit,
aux,
memories: Default::default(),
table_indices: Default::default(),
stack_pointer_shim_injected: false,
})
}
fn should_write_global(&mut self, name: impl Into<Cow<'static, str>>) -> bool {
self.exposed_globals.as_mut().unwrap().insert(name.into())
}
fn export(
&mut self,
export_name: &str,
contents: &str,
comments: Option<&str>,
) -> Result<(), Error> {
let definition_name = self.generate_identifier(export_name);
if contents.starts_with("class") && definition_name != export_name {
bail!("cannot shadow already defined class `{}`", export_name);
}
let contents = contents.trim();
if let Some(c) = comments {
self.globals.push_str(c);
}
let global = match self.config.mode {
OutputMode::Node { module: false } => {
if contents.starts_with("class") {
format!("{}\nmodule.exports.{1} = {1};\n", contents, export_name)
} else {
format!("module.exports.{} = {};\n", export_name, contents)
}
}
OutputMode::NoModules { .. } => {
if contents.starts_with("class") {
format!("{}\n__exports.{1} = {1};\n", contents, export_name)
} else {
format!("__exports.{} = {};\n", export_name, contents)
}
}
OutputMode::Bundler { .. }
| OutputMode::Node { module: true }
| OutputMode::Web
| OutputMode::Deno => {
if let Some(body) = contents.strip_prefix("function") {
if export_name == definition_name {
format!("export function {}{}\n", export_name, body)
} else {
format!(
"function {}{}\nexport {{ {} as {} }};\n",
definition_name, body, definition_name, export_name,
)
}
} else if contents.starts_with("class") {
assert_eq!(export_name, definition_name);
format!("export {}\n", contents)
} else {
assert_eq!(export_name, definition_name);
format!("export const {} = {};\n", export_name, contents)
}
}
};
self.global(&global);
Ok(())
}
pub fn finalize(
&mut self,
module_name: &str,
) -> Result<(String, String, Option<String>), Error> {
// Finalize all bindings for JS classes. This is where we'll generate JS
// glue for all classes as well as finish up a few final imports like
// `__wrap` and such.
self.write_classes()?;
// Initialization is just flat out tricky and not something we
// understand super well. To try to handle various issues that have come
// up we always remove the `start` function if one is present. The JS
// bindings glue then manually calls the start function (if it was
// previously present).
let needs_manual_start = self.unstart_start_function();
// Cause any future calls to `should_write_global` to panic, making sure
// we don't ask for items which we can no longer emit.
drop(self.exposed_globals.take().unwrap());
self.finalize_js(module_name, needs_manual_start)
}
fn generate_node_imports(&self) -> String {
let mut imports = BTreeSet::new();
for import in self.module.imports.iter() {
imports.insert(&import.module);
}
let mut shim = String::new();
shim.push_str("\nlet imports = {};\n");
if self.config.mode.uses_es_modules() {
for (i, module) in imports.iter().enumerate() {
if module.as_str() != PLACEHOLDER_MODULE {
shim.push_str(&format!("import * as import{} from '{}';\n", i, module));
}
}
for (i, module) in imports.iter().enumerate() {
if module.as_str() != PLACEHOLDER_MODULE {
shim.push_str(&format!("imports['{}'] = import{};\n", module, i));
}
}
} else {
for module in imports.iter() {
if module.as_str() == PLACEHOLDER_MODULE {
shim.push_str(&format!(
"imports['{0}'] = module.exports;\n",
PLACEHOLDER_MODULE
));
} else {
shim.push_str(&format!("imports['{0}'] = require('{0}');\n", module));
}
}
}
reset_indentation(&shim)
}
fn generate_node_wasm_loading(&self, path: &Path) -> String {
let mut shim = String::new();
if self.config.mode.uses_es_modules() {
// On windows skip the leading `/` which comes out when we parse a
// url to use `C:\...` instead of `\C:\...`
shim.push_str(&format!(
"
import * as path from 'node:path';
import * as fs from 'node:fs';
import * as process from 'node:process';
let file = path.dirname(new URL(import.meta.url).pathname);
if (process.platform === 'win32') {{
file = file.substring(1);
}}
const bytes = fs.readFileSync(path.join(file, '{}'));
",
path.file_name().unwrap().to_str().unwrap()
));
shim.push_str(
"
const wasmModule = new WebAssembly.Module(bytes);
const wasmInstance = new WebAssembly.Instance(wasmModule, imports);
const wasm = wasmInstance.exports;
export const __wasm = wasm;
",
);
} else {
shim.push_str(&format!(
"
const path = require('path').join(__dirname, '{}');
const bytes = require('fs').readFileSync(path);
",
path.file_name().unwrap().to_str().unwrap()
));
shim.push_str(
"
const wasmModule = new WebAssembly.Module(bytes);
const wasmInstance = new WebAssembly.Instance(wasmModule, imports);
wasm = wasmInstance.exports;
module.exports.__wasm = wasm;
",
);
}
reset_indentation(&shim)
}
// generates something like
// ```js
// import * as import0 from './snippets/.../inline1.js';
// ```,
//
// ```js
// const imports = {
// __wbindgen_placeholder__: {
// __wbindgen_throw: function(..) { .. },
// ..
// },
// './snippets/deno-65e2634a84cc3c14/inline1.js': import0,
// }
// ```
fn generate_deno_imports(&self) -> (String, String) {
let mut imports = String::new();
let mut wasm_import_object = "const imports = {\n".to_string();
wasm_import_object.push_str(&format!(" {}: {{\n", crate::PLACEHOLDER_MODULE));
for (id, js) in iter_by_import(&self.wasm_import_definitions, self.module) {
let import = self.module.imports.get(*id);
wasm_import_object.push_str(&format!("{}: {},\n", &import.name, js.trim()));
}
wasm_import_object.push_str("\t},\n");
// e.g. snippets without parameters
let import_modules = self
.module
.imports
.iter()
.map(|import| &import.module)
.filter(|module| module.as_str() != PLACEHOLDER_MODULE);
for (i, module) in import_modules.enumerate() {
imports.push_str(&format!("import * as import{} from '{}'\n", i, module));
wasm_import_object.push_str(&format!(" '{}': import{},", module, i))
}
wasm_import_object.push_str("\n};\n\n");
(imports, wasm_import_object)
}
fn generate_deno_wasm_loading(&self, module_name: &str) -> String {
// Deno removed support for .wasm imports in https://github.com/denoland/deno/pull/5135
// the issue for bringing it back is https://github.com/denoland/deno/issues/5609.
format!(
"const wasm_url = new URL('{module_name}_bg.wasm', import.meta.url);
let wasmCode = '';
switch (wasm_url.protocol) {{
case 'file:':
wasmCode = await Deno.readFile(wasm_url);
break
case 'https:':
case 'http:':
wasmCode = await (await fetch(wasm_url)).arrayBuffer();
break
default:
throw new Error(`Unsupported protocol: ${{wasm_url.protocol}}`);
}}
const wasmInstance = (await WebAssembly.instantiate(wasmCode, imports)).instance;
const wasm = wasmInstance.exports;
export const __wasm = wasm;",
module_name = module_name
)
}
/// Performs the task of actually generating the final JS module, be it
/// `--target no-modules`, `--target web`, or for bundlers. This is the very
/// last step performed in `finalize`.
fn finalize_js(
&mut self,
module_name: &str,
needs_manual_start: bool,
) -> Result<(String, String, Option<String>), Error> {
let mut ts;
let mut js = String::new();
let mut start = None;
if let OutputMode::NoModules { global } = &self.config.mode {
js.push_str(&format!("let {};\n(function() {{\n", global));
}
// Depending on the output mode, generate necessary glue to actually
// import the Wasm file in one way or another.
let mut init = (String::new(), String::new());
let mut footer = String::new();
let mut imports = self.js_import_header()?;
match &self.config.mode {
// In `--target no-modules` mode we need to both expose a name on
// the global object as well as generate our own custom start
// function.
// `document.currentScript` property can be null in browser extensions
OutputMode::NoModules { global } => {
js.push_str("const __exports = {};\n");
js.push_str("let script_src;\n");
js.push_str(
"\
if (typeof document !== 'undefined' && document.currentScript !== null) {
script_src = new URL(document.currentScript.src, location.href).toString();
}\n",
);
js.push_str("let wasm = undefined;\n");
init = self.gen_init(needs_manual_start, None)?;
footer.push_str(&format!(
"{} = Object.assign(__wbg_init, {{ initSync }}, __exports);\n",
global
));
}
// With normal CommonJS node we need to defer requiring the wasm
// until the end so most of our own exports are hooked up
OutputMode::Node { module: false } => {
js.push_str(&self.generate_node_imports());
js.push_str("let wasm;\n");
for (id, js) in iter_by_import(&self.wasm_import_definitions, self.module) {
let import = self.module.imports.get(*id);
footer.push_str("\nmodule.exports.");
footer.push_str(&import.name);
footer.push_str(" = ");
footer.push_str(js.trim());
footer.push_str(";\n");
}
footer.push_str(
&self.generate_node_wasm_loading(Path::new(&format!(
"./{}_bg.wasm",
module_name
))),
);
if needs_manual_start {
footer.push_str("\nwasm.__wbindgen_start();\n");
}
}
OutputMode::Deno => {
let (js_imports, wasm_import_object) = self.generate_deno_imports();
imports.push_str(&js_imports);
footer.push_str(&wasm_import_object);
footer.push_str(&self.generate_deno_wasm_loading(module_name));
footer.push_str("\n\n");
if needs_manual_start {
footer.push_str("\nwasm.__wbindgen_start();\n");
}
}
// With Bundlers we can simply import the Wasm file as if it were an ES module
// and let the bundler/runtime take care of it.
// With Node we manually read the Wasm file from the filesystem and instantiate it.
OutputMode::Bundler { .. } | OutputMode::Node { module: true } => {
for (id, js) in iter_by_import(&self.wasm_import_definitions, self.module) {
let import = self.module.imports.get_mut(*id);
import.module = format!("./{}_bg.js", module_name);
if let Some(body) = js.strip_prefix("function") {
footer.push_str("\nexport function ");
footer.push_str(&import.name);
footer.push_str(body.trim());
footer.push_str(";\n");
} else {
footer.push_str("\nexport const ");
footer.push_str(&import.name);
footer.push_str(" = ");
footer.push_str(js.trim());
footer.push_str(";\n");
}
}
self.imports_post.push_str(
"\
let wasm;
export function __wbg_set_wasm(val) {
wasm = val;
}
",
);
if matches!(self.config.mode, OutputMode::Node { module: true }) {
let start = start.get_or_insert_with(String::new);
start.push_str(&self.generate_node_imports());
start.push_str(&self.generate_node_wasm_loading(Path::new(&format!(
"./{}_bg.wasm",
module_name
))));
}
match self.config.mode {
OutputMode::Bundler { .. } => {
start.get_or_insert_with(String::new).push_str(&format!(
"\
import {{ __wbg_set_wasm }} from \"./{module_name}_bg.js\";
__wbg_set_wasm(wasm);"
));
}
OutputMode::Node { module: true } => {
start.get_or_insert_with(String::new).push_str(&format!(
"imports[\"./{module_name}_bg.js\"].__wbg_set_wasm(wasm);"
));
}
_ => {}
}
if needs_manual_start {
start
.get_or_insert_with(String::new)
.push_str("\nwasm.__wbindgen_start();\n");
}
}
// With a browser-native output we're generating an ES module, but
// browsers don't support natively importing Wasm right now so we
// expose the same initialization function as `--target no-modules`
// as the default export of the module.
OutputMode::Web => {
self.imports_post.push_str("let wasm;\n");
init = self.gen_init(needs_manual_start, Some(&mut imports))?;
footer.push_str("export { initSync };\n");
footer.push_str("export default __wbg_init;");
}
}
// Before putting the static init code declaration info, put all existing typescript into a `wasm_bindgen` namespace declaration.
// Not sure if this should happen in all cases, so just adding it to NoModules for now...
if self.config.mode.no_modules() {
ts = String::from("declare namespace wasm_bindgen {\n\t");
ts.push_str(&self.typescript.replace('\n', "\n\t"));
ts.push_str("\n}\n");
} else {
ts = self.typescript.clone();
}
let (init_js, init_ts) = init;
ts.push_str(&init_ts);
// Emit all the JS for importing all our functionality
assert!(
!self.config.mode.uses_es_modules() || js.is_empty(),
"ES modules require imports to be at the start of the file, but we \
generated some JS before the imports: {}",
js
);
let mut push_with_newline = |s| {
js.push_str(s);
if !s.is_empty() {
js.push('\n');
}
};
push_with_newline(&imports);
push_with_newline(&self.imports_post);
// Emit all our exports from this module
push_with_newline(&self.globals);
// Generate the initialization glue, if there was any
push_with_newline(&init_js);
push_with_newline(&footer);
if self.config.mode.no_modules() {
js.push_str("})();\n");
}
while js.contains("\n\n\n") {
js = js.replace("\n\n\n", "\n\n");
}
Ok((js, ts, start))
}
fn js_import_header(&self) -> Result<String, Error> {
let mut imports = String::new();
if self.config.omit_imports {
return Ok(imports);
}
match &self.config.mode {
OutputMode::NoModules { .. } => {
if let Some((module, _items)) = self.js_imports.iter().next() {
bail!(
"importing from `{}` isn't supported with `--target no-modules`",
module
);
}
}
OutputMode::Node { module: false } => {
for (module, items) in crate::sorted_iter(&self.js_imports) {
imports.push_str("const { ");
for (i, (item, rename)) in items.iter().enumerate() {
if i > 0 {
imports.push_str(", ");
}
imports.push_str(item);
if let Some(other) = rename {
imports.push_str(": ");
imports.push_str(other)
}
}
if module.starts_with('.') || PathBuf::from(module).is_absolute() {
imports.push_str(" } = require(String.raw`");
} else {
imports.push_str(" } = require(`");
}
imports.push_str(module);
imports.push_str("`);\n");
}
}
OutputMode::Bundler { .. }
| OutputMode::Node { module: true }
| OutputMode::Web
| OutputMode::Deno => {
for (module, items) in crate::sorted_iter(&self.js_imports) {
imports.push_str("import { ");
for (i, (item, rename)) in items.iter().enumerate() {
if i > 0 {
imports.push_str(", ");
}
imports.push_str(item);
if let Some(other) = rename {
imports.push_str(" as ");
imports.push_str(other)
}
}
imports.push_str(" } from '");
imports.push_str(module);
imports.push_str("';\n");
}
}
}
Ok(imports)
}
fn ts_for_init_fn(
&self,
has_memory: bool,
has_module_or_path_optional: bool,
) -> Result<String, Error> {
let output = crate::wasm2es6js::interface(self.module)?;
let (memory_doc, memory_param) = if has_memory {
(
"* @param {WebAssembly.Memory} memory - Deprecated.\n",
", memory?: WebAssembly.Memory",
)
} else {
("", "")
};
let stack_size = if self.threads_enabled {
", thread_stack_size?: number"
} else {
""
};
let arg_optional = if has_module_or_path_optional { "?" } else { "" };
// With TypeScript 3.8.3, I'm seeing that any "export"s at the root level cause TypeScript to ignore all "declare" statements.
// So using "declare" everywhere for at least the NoModules option.
// Also in (at least) the NoModules, the `init()` method is renamed to `wasm_bindgen()`.
let setup_function_declaration;
let mut sync_init_function = String::new();
let declare_or_export;
if self.config.mode.no_modules() {
declare_or_export = "declare";
setup_function_declaration = "declare function wasm_bindgen";
} else {
declare_or_export = "export";
sync_init_function.push_str(&format!(
"\
{declare_or_export} type SyncInitInput = BufferSource | WebAssembly.Module;\n\
/**\n\
* Instantiates the given `module`, which can either be bytes or\n\
* a precompiled `WebAssembly.Module`.\n\
*\n\
* @param {{{{ module: SyncInitInput{memory_param}{stack_size} }}}} module - Passing `SyncInitInput` directly is deprecated.\n\
{memory_doc}\
*\n\
* @returns {{InitOutput}}\n\
*/\n\
export function initSync(module: {{ module: SyncInitInput{memory_param}{stack_size} }} | SyncInitInput{memory_param}): InitOutput;\n\n\
",
memory_doc = memory_doc,
memory_param = memory_param
));
setup_function_declaration = "export default function __wbg_init";
}
Ok(format!(
"\n\
{declare_or_export} type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;\n\
\n\
{declare_or_export} interface InitOutput {{\n\
{output}}}\n\
\n\
{sync_init_function}\
/**\n\
* If `module_or_path` is {{RequestInfo}} or {{URL}}, makes a request and\n\
* for everything else, calls `WebAssembly.instantiate` directly.\n\
*\n\
* @param {{{{ module_or_path: InitInput | Promise<InitInput>{memory_param}{stack_size} }}}} module_or_path - Passing `InitInput` directly is deprecated.\n\
{}\
*\n\
* @returns {{Promise<InitOutput>}}\n\
*/\n\
{setup_function_declaration} \
(module_or_path{}: {{ module_or_path: InitInput | Promise<InitInput>{memory_param}{stack_size} }} | InitInput | Promise<InitInput>{}): Promise<InitOutput>;\n",
memory_doc, arg_optional, memory_param,
output = output,
sync_init_function = sync_init_function,
declare_or_export = declare_or_export,
setup_function_declaration = setup_function_declaration,
))
}
fn gen_init(
&mut self,
needs_manual_start: bool,
mut imports: Option<&mut String>,
) -> Result<(String, String), Error> {
let module_name = "wbg";
let mut init_memory_arg = "";
let mut init_memory = String::new();
let mut has_memory = false;
if let Some(mem) = self.module.memories.iter().next() {
if let Some(id) = mem.import {
self.module.imports.get_mut(id).module = module_name.to_string();
init_memory = format!(
"imports.{}.memory = memory || new WebAssembly.Memory({{",
module_name
);
init_memory.push_str(&format!("initial:{}", mem.initial));
if let Some(max) = mem.maximum {
init_memory.push_str(&format!(",maximum:{}", max));
}
if mem.shared {
init_memory.push_str(",shared:true");
}
init_memory.push_str("});");
init_memory_arg = ", memory";
has_memory = true;
}
}
let default_module_path = if !self.config.omit_default_module_path {
match self.config.mode {
OutputMode::Web => format!(
"\
if (typeof module_or_path === 'undefined') {{
module_or_path = new URL('{stem}_bg.wasm', import.meta.url);
}}",
stem = self.config.stem()?
),
OutputMode::NoModules { .. } => "\
if (typeof module_or_path === 'undefined' && typeof script_src !== 'undefined') {
module_or_path = script_src.replace(/\\.js$/, '_bg.wasm');
}"
.to_string(),
_ => "".to_string(),
}
} else {
String::from("")
};
let ts = self.ts_for_init_fn(
has_memory,
!self.config.omit_default_module_path && !default_module_path.is_empty(),
)?;
// Initialize the `imports` object for all import definitions that we're
// directed to wire up.
let mut imports_init = String::new();
imports_init.push_str("imports.");
imports_init.push_str(module_name);
imports_init.push_str(" = {};\n");
for (id, js) in iter_by_import(&self.wasm_import_definitions, self.module) {
let import = self.module.imports.get_mut(*id);
import.module = module_name.to_string();
imports_init.push_str("imports.");
imports_init.push_str(module_name);
imports_init.push('.');
imports_init.push_str(&import.name);
imports_init.push_str(" = ");
imports_init.push_str(js.trim());
imports_init.push_str(";\n");
}
let extra_modules = self
.module
.imports
.iter()
.filter(|i| !self.wasm_import_definitions.contains_key(&i.id()))
.filter(|i| {
// Importing memory is handled specially in this area, so don't
// consider this a candidate for importing from extra modules.
!(matches!(i.kind, walrus::ImportKind::Memory(_)))
})
.map(|i| &i.module)
.collect::<BTreeSet<_>>();
for (i, extra) in extra_modules.iter().enumerate() {
let imports = match &mut imports {
Some(list) => list,
None => bail!(
"cannot import from modules (`{}`) with `--no-modules`",
extra
),
};
imports.push_str(&format!("import * as __wbg_star{} from '{}';\n", i, extra));
imports_init.push_str(&format!("imports['{}'] = __wbg_star{};\n", extra, i));
}
let mut init_memviews = String::new();
for &(num, ref views) in self.memories.values() {
for kind in views {
writeln!(
init_memviews,
// Reset the memory views to null in case `init` gets called multiple times.
// Without this, the `length = 0` check would never detect that the view was
// outdated.
"cached{kind}Memory{num} = null;",
kind = kind,
num = num,
)
.unwrap()
}
}
let js = format!(
"\
async function __wbg_load(module, imports) {{
if (typeof Response === 'function' && module instanceof Response) {{
if (typeof WebAssembly.instantiateStreaming === 'function') {{
try {{
return await WebAssembly.instantiateStreaming(module, imports);
}} catch (e) {{
if (module.headers.get('Content-Type') != 'application/wasm') {{
console.warn(\"`WebAssembly.instantiateStreaming` failed \
because your server does not serve Wasm with \
`application/wasm` MIME type. Falling back to \
`WebAssembly.instantiate` which is slower. Original \
error:\\n\", e);
}} else {{
throw e;
}}
}}
}}
const bytes = await module.arrayBuffer();
return await WebAssembly.instantiate(bytes, imports);
}} else {{
const instance = await WebAssembly.instantiate(module, imports);
if (instance instanceof WebAssembly.Instance) {{
return {{ instance, module }};
}} else {{
return instance;
}}
}}
}}
function __wbg_get_imports() {{
const imports = {{}};
{imports_init}
return imports;
}}
function __wbg_init_memory(imports, memory) {{
{init_memory}
}}
function __wbg_finalize_init(instance, module{init_stack_size_arg}) {{
wasm = instance.exports;
__wbg_init.__wbindgen_wasm_module = module;
{init_memviews}
{init_stack_size_check}
{start}
return wasm;
}}
function initSync(module{init_memory_arg}) {{
if (wasm !== undefined) return wasm;
{init_stack_size}
if (typeof module !== 'undefined') {{
if (Object.getPrototypeOf(module) === Object.prototype) {{
({{module{init_memory_arg}{init_stack_size_arg}}} = module)
}} else {{
console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
}}
}}
const imports = __wbg_get_imports();
__wbg_init_memory(imports{init_memory_arg});
if (!(module instanceof WebAssembly.Module)) {{
module = new WebAssembly.Module(module);
}}
const instance = new WebAssembly.Instance(module, imports);
return __wbg_finalize_init(instance, module{init_stack_size_arg});
}}
async function __wbg_init(module_or_path{init_memory_arg}) {{
if (wasm !== undefined) return wasm;
{init_stack_size}
if (typeof module_or_path !== 'undefined') {{
if (Object.getPrototypeOf(module_or_path) === Object.prototype) {{
({{module_or_path{init_memory_arg}{init_stack_size_arg}}} = module_or_path)
}} else {{
console.warn('using deprecated parameters for the initialization function; pass a single object instead')
}}
}}
{default_module_path}
const imports = __wbg_get_imports();
if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {{
module_or_path = fetch(module_or_path);
}}
__wbg_init_memory(imports{init_memory_arg});
const {{ instance, module }} = await __wbg_load(await module_or_path, imports);
return __wbg_finalize_init(instance, module{init_stack_size_arg});
}}
",
init_memory_arg = init_memory_arg,
default_module_path = default_module_path,
init_memory = init_memory,
init_memviews = init_memviews,
start = if needs_manual_start && self.threads_enabled {
"wasm.__wbindgen_start(thread_stack_size);"
} else if needs_manual_start {
"wasm.__wbindgen_start();"
} else {
""
},
imports_init = imports_init,
init_stack_size = if self.threads_enabled {
"let thread_stack_size"
} else {
""
},
init_stack_size_arg = if self.threads_enabled {
", thread_stack_size"
} else {
""
},
init_stack_size_check = if self.threads_enabled {
format!(
"if (typeof thread_stack_size !== 'undefined' && (typeof thread_stack_size !== 'number' || thread_stack_size === 0 || thread_stack_size % {} !== 0)) {{ throw 'invalid stack size' }}",
wasm_bindgen_threads_xform::PAGE_SIZE,
)
} else {