-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
mod.rs
3443 lines (3117 loc) · 125 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, 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 std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};
use walrus::{FunctionId, ImportId, MemoryId, Module, TableId};
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>,
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 of a index for memories as we see them. Used in function
/// names.
memory_indices: HashMap<MemoryId, usize>,
table_indices: HashMap<TableId, usize>,
}
#[derive(Default)]
pub struct ExportedClass {
comments: String,
contents: String,
typescript: String,
has_constructor: bool,
wrap_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 name to type as a string, docs plus whether it has a setter
/// and it is optional
typescript_fields: HashMap<String, (String, String, bool, 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 = 32;
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(),
exported_classes: Some(Default::default()),
config,
module,
npm_dependencies: Default::default(),
next_export_idx: 0,
wit,
aux,
memory_indices: Default::default(),
table_indices: Default::default(),
})
}
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 {
experimental_modules: 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 {
experimental_modules: true,
}
| OutputMode::Web
| OutputMode::Deno => {
if contents.starts_with("function") {
let body = &contents[8..];
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("let imports = {};\n");
if self.config.mode.nodejs_experimental_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['{0}'] = module.exports;\n",
PLACEHOLDER_MODULE
));
} else {
if self.config.mode.nodejs_experimental_modules() {
shim.push_str(&format!("imports['{}'] = import{};\n", module, i));
} 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.nodejs_experimental_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 'path';
import * as fs from 'fs';
import * as url from 'url';
import * as process from 'process';
let file = path.dirname(url.parse(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()
));
} 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 somthing like
// ```js
// const imports = {
// __wbindgen_placeholder__: {
// __wbindgen_throw: function(..) { .. },
// ..
// }
// }
// ```
fn generate_deno_imports(&self) -> String {
let mut imports = "const imports = {\n".to_string();
imports.push_str(&format!(" {}: {{\n", crate::PLACEHOLDER_MODULE));
for (id, js) in crate::sorted_iter(&self.wasm_import_definitions) {
let import = self.module.imports.get(*id);
imports.push_str(&format!("{}: {},\n", &import.name, js.trim()));
}
imports.push_str("\t}\n};\n\n");
imports
}
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 file = new URL(import.meta.url).pathname;
const wasmFile = file.substring(0, file.lastIndexOf(Deno.build.os === 'windows' ? '\\\\' : '/') + 1) + '{}_bg.wasm';
const wasmModule = new WebAssembly.Module(Deno.readFileSync(wasmFile));
const wasmInstance = new WebAssembly.Instance(wasmModule, imports);
const wasm = wasmInstance.exports;",
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 = self.typescript.clone();
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.
OutputMode::NoModules { global } => {
js.push_str("const __exports = {};\n");
js.push_str("let wasm;\n");
init = self.gen_init(needs_manual_start, None)?;
footer.push_str(&format!("{} = Object.assign(init, __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 {
experimental_modules: false,
} => {
js.push_str(&self.generate_node_imports());
js.push_str("let wasm;\n");
for (id, js) in crate::sorted_iter(&self.wasm_import_definitions) {
let import = self.module.imports.get_mut(*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("wasm.__wbindgen_start();\n");
}
}
OutputMode::Deno => {
footer.push_str(&self.generate_deno_imports());
footer.push_str(&self.generate_deno_wasm_loading(module_name));
if needs_manual_start {
footer.push_str("wasm.__wbindgen_start();\n");
}
}
// With Bundlers and modern ES6 support in Node we can simply import
// the wasm file as if it were an ES module and let the
// bundler/runtime take care of it.
OutputMode::Bundler { .. }
| OutputMode::Node {
experimental_modules: true,
} => {
imports.push_str(&format!(
"import * as wasm from './{}_bg.wasm';\n",
module_name
));
for (id, js) in crate::sorted_iter(&self.wasm_import_definitions) {
let import = self.module.imports.get_mut(*id);
import.module = format!("./{}_bg.js", module_name);
footer.push_str("\nexport const ");
footer.push_str(&import.name);
footer.push_str(" = ");
footer.push_str(js.trim());
footer.push_str(";\n");
}
if needs_manual_start {
start = Some("\nwasm.__wbindgen_start();\n".to_string());
}
}
// 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 default init;\n");
}
}
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"
);
js.push_str(&imports);
js.push_str("\n");
js.push_str(&self.imports_post);
js.push_str("\n");
// Emit all our exports from this module
js.push_str(&self.globals);
js.push_str("\n");
// Generate the initialization glue, if there was any
js.push_str(&init_js);
js.push_str("\n");
js.push_str(&footer);
js.push_str("\n");
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 { .. } => {
for (module, _items) in self.js_imports.iter() {
bail!(
"importing from `{}` isn't supported with `--target no-modules`",
module
);
}
}
OutputMode::Node {
experimental_modules: 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)
}
}
imports.push_str(" } = require(String.raw`");
imports.push_str(module);
imports.push_str("`);\n");
}
}
OutputMode::Bundler { .. }
| OutputMode::Node {
experimental_modules: 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} maybe_memory\n",
", maybe_memory: WebAssembly.Memory",
)
} else {
("", "")
};
let arg_optional = if has_module_or_path_optional { "?" } else { "" };
Ok(format!(
"\n\
export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;\n\
\n\
export interface InitOutput {{\n\
{output}}}\n\
\n\
/**\n\
* If `module_or_path` is {{RequestInfo}} or {{URL}}, makes a request and\n\
* for everything else, calls `WebAssembly.instantiate` directly.\n\
*\n\
* @param {{InitInput | Promise<InitInput>}} module_or_path\n\
{}\
*\n\
* @returns {{Promise<InitOutput>}}\n\
*/\n\
export default function init \
(module_or_path{}: InitInput | Promise<InitInput>{}): Promise<InitOutput>;
",
memory_doc, arg_optional, memory_param,
output = output,
))
}
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_memory1 = String::new();
let mut init_memory2 = 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();
let mut memory = String::from("new WebAssembly.Memory({");
memory.push_str(&format!("initial:{}", mem.initial));
if let Some(max) = mem.maximum {
memory.push_str(&format!(",maximum:{}", max));
}
if mem.shared {
memory.push_str(",shared:true");
}
memory.push_str("})");
self.imports_post.push_str("let memory;\n");
init_memory1 = format!("memory = imports.{}.memory = maybe_memory;", module_name);
init_memory2 = format!("memory = imports.{}.memory = {};", module_name, memory);
init_memory_arg = ", maybe_memory";
has_memory = true;
}
}
let default_module_path = match self.config.mode {
OutputMode::Web => {
"\
if (typeof input === 'undefined') {
input = import.meta.url.replace(/\\.js$/, '_bg.wasm');
}"
}
OutputMode::NoModules { .. } => {
"\
if (typeof input === 'undefined') {
let src;
if (typeof document === 'undefined') {
src = location.href;
} else {
src = document.currentScript.src;
}
input = src.replace(/\\.js$/, '_bg.wasm');
}"
}
_ => "",
};
let ts = self.ts_for_init_fn(has_memory, !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();
if self.wasm_import_definitions.len() > 0 {
imports_init.push_str("imports.");
imports_init.push_str(module_name);
imports_init.push_str(" = {};\n");
}
for (id, js) in crate::sorted_iter(&self.wasm_import_definitions) {
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_str(".");
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.
match i.kind {
walrus::ImportKind::Memory(_) => false,
_ => true,
}
})
.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 js = format!(
"\
async function load(module, imports{init_memory_arg}) {{
if (typeof Response === 'function' && module instanceof Response) {{
{init_memory2}
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 {{
{init_memory1}
const instance = await WebAssembly.instantiate(module, imports);
if (instance instanceof WebAssembly.Instance) {{
return {{ instance, module }};
}} else {{
return instance;
}}
}}
}}
async function init(input{init_memory_arg}) {{
{default_module_path}
const imports = {{}};
{imports_init}
if (typeof input === 'string' || (typeof Request === 'function' && input instanceof Request) || (typeof URL === 'function' && input instanceof URL)) {{
input = fetch(input);
}}
const {{ instance, module }} = await load(await input, imports{init_memory_arg});
wasm = instance.exports;
init.__wbindgen_wasm_module = module;
{start}
return wasm;
}}
",
init_memory_arg = init_memory_arg,
default_module_path = default_module_path,
init_memory1 = init_memory1,
init_memory2 = init_memory2,
start = if needs_manual_start {
"wasm.__wbindgen_start();"
} else {
""
},
imports_init = imports_init,
);
Ok((js, ts))
}
fn write_classes(&mut self) -> Result<(), Error> {
for (class, exports) in self.exported_classes.take().unwrap() {
self.write_class(&class, &exports)?;
}
Ok(())
}
fn write_class(&mut self, name: &str, class: &ExportedClass) -> Result<(), Error> {
let mut dst = format!("class {} {{\n", name);
let mut ts_dst = format!("export {}", dst);
if self.config.debug && !class.has_constructor {
dst.push_str(
"
constructor() {
throw new Error('cannot invoke `new` directly');
}
",
);
}
if class.wrap_needed {
dst.push_str(&format!(
"
static __wrap(ptr) {{
const obj = Object.create({}.prototype);
obj.ptr = ptr;
{}
return obj;
}}
",
name,
if self.config.weak_refs {
format!("{}FinalizationGroup.register(obj, obj.ptr, obj.ptr);", name)
} else {
String::new()
},
));
}
if self.config.weak_refs {
self.global(&format!(
"
const {}FinalizationGroup = new FinalizationGroup((items) => {{
for (const ptr of items) {{
wasm.{}(ptr);
}}
}});
",
name,
wasm_bindgen_shared::free_function(&name),
));
}
// If the class is inspectable, generate `toJSON` and `toString`
// to expose all readable properties of the class. Otherwise,
// the class shows only the "ptr" property when logged or serialized
if class.is_inspectable {
// Creates a `toJSON` method which returns an object of all readable properties
// This object looks like { a: this.a, b: this.b }
dst.push_str(&format!(
"
toJSON() {{
return {{{}}};
}}
toString() {{
return JSON.stringify(this);
}}
",
class
.readable_properties
.iter()
.fold(String::from("\n"), |fields, field_name| {
format!("{}{name}: this.{name},\n", fields, name = field_name)
})
));
if self.config.mode.nodejs() {
// `util.inspect` must be imported in Node.js to define [inspect.custom]
let module_name = self.import_name(&JsImport {
name: JsImportName::Module {
module: "util".to_string(),
name: "inspect".to_string(),
},
fields: Vec::new(),
})?;
// Node.js supports a custom inspect function to control the
// output of `console.log` and friends. The constructor is set
// to display the class name as a typical JavaScript class would
dst.push_str(&format!(
"
[{}.custom]() {{
return Object.assign(Object.create({{constructor: this.constructor}}), this.toJSON());
}}
",
module_name
));
}
}
dst.push_str(&format!(
"
free() {{
const ptr = this.ptr;
this.ptr = 0;
{}
wasm.{}(ptr);
}}
",
if self.config.weak_refs {
format!("{}FinalizationGroup.unregister(ptr);", name)
} else {
String::new()
},
wasm_bindgen_shared::free_function(&name),
));
ts_dst.push_str(" free(): void;\n");
dst.push_str(&class.contents);
ts_dst.push_str(&class.typescript);
let mut fields = class.typescript_fields.keys().collect::<Vec<_>>();
fields.sort(); // make sure we have deterministic output
for name in fields {
let (ty, docs, has_setter, is_optional) = &class.typescript_fields[name];
ts_dst.push_str(docs);
ts_dst.push_str(" ");
if !has_setter {
ts_dst.push_str("readonly ");
}
ts_dst.push_str(name);
if *is_optional {
ts_dst.push_str("?: ");
} else {
ts_dst.push_str(": ");
}
ts_dst.push_str(&ty);
ts_dst.push_str(";\n");
}
dst.push_str("}\n");
ts_dst.push_str("}\n");
self.export(&name, &dst, Some(&class.comments))?;
self.typescript.push_str(&class.comments);
self.typescript.push_str(&ts_dst);
Ok(())
}
fn expose_drop_ref(&mut self) {
if !self.should_write_global("drop_ref") {
return;
}
self.expose_global_heap();
self.expose_global_heap_next();
// Note that here we check if `idx` shouldn't actually be dropped. This
// is due to the fact that `JsValue::null()` and friends can be passed
// by value to JS where we'll automatically call this method. Those
// constants, however, cannot be dropped. See #1054 for removing this
// branch.
//
// Otherwise the free operation here is pretty simple, just appending to
// the linked list of heap slots that are free.
self.global(&format!(
"
function dropObject(idx) {{
if (idx < {}) return;
heap[idx] = heap_next;
heap_next = idx;
}}
",
INITIAL_HEAP_OFFSET + INITIAL_HEAP_VALUES.len(),
));
}
fn expose_global_heap(&mut self) {
if !self.should_write_global("heap") {
return;
}
assert!(!self.config.externref);
self.global(&format!(
"const heap = new Array({}).fill(undefined);",
INITIAL_HEAP_OFFSET
));
self.global(&format!("heap.push({});", INITIAL_HEAP_VALUES.join(", ")));
}
fn expose_global_heap_next(&mut self) {
if !self.should_write_global("heap_next") {
return;
}
self.expose_global_heap();
self.global("let heap_next = heap.length;");
}
fn expose_get_object(&mut self) {
if !self.should_write_global("get_object") {
return;
}
self.expose_global_heap();
// Accessing a heap object is just a simple index operation due to how
// the stack/heap are laid out.
self.global("function getObject(idx) { return heap[idx]; }");
}
fn expose_not_defined(&mut self) {
if !self.should_write_global("not_defined") {
return;
}
self.global("function notDefined(what) { return () => { throw new Error(`${what} is not defined`); }; }");
}
fn expose_assert_num(&mut self) {
if !self.should_write_global("assert_num") {
return;
}
self.global(&format!(
"
function _assertNum(n) {{
if (typeof(n) !== 'number') throw new Error('expected a number argument');
}}
"
));
}
fn expose_assert_bool(&mut self) {
if !self.should_write_global("assert_bool") {
return;
}
self.global(&format!(
"
function _assertBoolean(n) {{
if (typeof(n) !== 'boolean') {{
throw new Error('expected a boolean argument');
}}
}}
"
));
}
fn expose_wasm_vector_len(&mut self) {
if !self.should_write_global("wasm_vector_len") {
return;
}
self.global("let WASM_VECTOR_LEN = 0;");
}
fn expose_pass_string_to_wasm(&mut self, memory: MemoryId) -> Result<MemView, Error> {
self.expose_wasm_vector_len();
let debug = if self.config.debug {
"
if (typeof(arg) !== 'string') throw new Error('expected a string argument');
"
} else {
""
};
// If we are targeting Node.js, it doesn't have `encodeInto` yet
// but it does have `Buffer::write` which has similar semantics but
// doesn't require creating intermediate view using `subarray`
// and also has `Buffer::byteLength` to calculate size upfront.
if self.config.mode.nodejs() {
let get_buf = self.expose_node_buffer_memory(memory);
let ret = MemView {
name: "passStringToWasm",
num: get_buf.num,
};
if !self.should_write_global(ret.to_string()) {
return Ok(ret);
}