-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathmod.rs
3350 lines (3094 loc) · 120 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
mod closures;
mod js2rust;
mod rust2js;
use self::{
js2rust::{ExportedShim, Js2Rust},
rust2js::Rust2Js,
};
use crate::{
decode,
descriptor::{Descriptor, VectorKind},
Bindgen, EncodeInto, OutputMode,
};
use failure::{bail, Error, ResultExt};
use std::{
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
env, fs,
};
use walrus::{MemoryId, Module};
use wasm_bindgen_shared::struct_function_export_name;
use wasm_bindgen_wasm_interpreter::Interpreter;
pub struct Context<'a> {
pub globals: String,
pub imports: String,
pub imports_post: String,
pub footer: String,
pub typescript: String,
pub exposed_globals: Option<HashSet<&'static str>>,
pub required_internal_exports: HashSet<&'static str>,
pub imported_functions: HashSet<&'a str>,
pub imported_statics: HashSet<&'a str>,
pub config: &'a Bindgen,
pub module: &'a mut Module,
pub start: Option<String>,
/// A map which maintains a list of what identifiers we've imported and what
/// they're named locally.
///
/// The `Option<String>` key is the module that identifiers were imported
/// from, `None` being the global module. The second key is a map of
/// identifiers we've already imported from the module to what they're
/// called locally.
pub imported_names: HashMap<ImportModule<'a>, HashMap<&'a str, 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.
pub defined_identifiers: HashMap<String, usize>,
/// A map of all imported shim functions which can actually be directly
/// imported from the containing module. The mapping here maps to a tuple,
/// where the first element is the module to import from and the second
/// element is the name to import from the module.
///
/// Note that for `direct_imports` no shims are generated in JS that
/// wasm-bindgen emits.
pub direct_imports: HashMap<&'a str, (&'a str, &'a str)>,
pub exported_classes: Option<BTreeMap<String, ExportedClass>>,
pub function_table_needed: bool,
pub interpreter: &'a mut Interpreter,
pub memory: MemoryId,
/// A map of all local modules we've found, from the identifier they're
/// known as to their actual JS contents.
pub local_modules: HashMap<&'a str, &'a str>,
/// A map of how many snippets we've seen from each unique crate identifier,
/// used to number snippets correctly when writing them to the filesystem
/// when there's multiple snippets within one crate that aren't all part of
/// the same `Program`.
pub snippet_offsets: HashMap<&'a str, usize>,
/// All package.json dependencies we've learned about so far
pub package_json_read: HashSet<&'a str>,
/// 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, (&'a str, String)>,
pub anyref: wasm_bindgen_anyref_xform::Context,
}
#[derive(Default)]
pub struct ExportedClass {
comments: String,
contents: String,
typescript: String,
has_constructor: bool,
wrap_needed: bool,
}
pub struct SubContext<'a, 'b: 'a> {
pub program: &'b decode::Program<'b>,
pub cx: &'a mut Context<'b>,
pub vendor_prefixes: HashMap<&'b str, Vec<&'b str>>,
}
pub enum ImportTarget {
Function(String),
Method(String),
Constructor(String),
StructuralMethod(String),
StructuralGetter(Option<String>, String),
StructuralSetter(Option<String>, String),
StructuralIndexingGetter(Option<String>),
StructuralIndexingSetter(Option<String>),
StructuralIndexingDeleter(Option<String>),
}
/// Return value of `determine_import` which is where we look at an imported
/// function AST and figure out where it's actually being imported from
/// (performing some validation checks and whatnot).
enum Import<'a> {
/// An item is imported from the global scope. The `name` is what's imported
/// and the optional `field` is the field on that item we're importing.
Global {
name: &'a str,
field: Option<&'a str>,
},
/// Same as `Global`, except the `name` is imported via an ESM import from
/// the specified `module` path.
Module {
module: &'a str,
name: &'a str,
field: Option<&'a str>,
},
/// Same as `Module`, except we're importing from a local module defined in
/// a local JS snippet.
LocalModule {
module: &'a str,
name: &'a str,
field: Option<&'a str>,
},
/// Same as `Module`, except we're importing from an `inline_js` attribute
InlineJs {
unique_crate_identifier: &'a str,
snippet_idx_in_crate: usize,
name: &'a str,
field: Option<&'a str>,
},
/// A global import which may have a number of vendor prefixes associated
/// with it, like `webkitAudioPrefix`. The `name` is the name to test
/// whether it's prefixed.
VendorPrefixed {
name: &'a str,
prefixes: Vec<&'a str>,
},
}
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> {
fn should_write_global(&mut self, name: &'static str) -> bool {
self.exposed_globals.as_mut().unwrap().insert(name)
}
fn export(
&mut self,
export_name: &str,
contents: &str,
comments: Option<String>,
) -> Result<(), Error> {
let definition_name = generate_identifier(export_name, &mut self.defined_identifiers);
if contents.starts_with("class") && definition_name != export_name {
bail!("cannot shadow already defined class `{}`", export_name);
}
let contents = contents.trim();
if let Some(ref c) = comments {
self.globals.push_str(c);
self.typescript.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,
} => {
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)
}
}
OutputMode::Web => {
// In web mode there's no need to export the internals of
// wasm-bindgen as we're not using the module itself as the
// import object but rather the `__exports` map we'll be
// initializing below.
let export = if export_name.starts_with("__wbindgen")
|| export_name.starts_with("__wbg_")
|| export_name.starts_with("__widl_")
{
""
} else {
"export "
};
if contents.starts_with("function") {
let body = &contents[8..];
if export_name == definition_name {
format!(
"{}function {name}{}\n__exports.{name} = {name}",
export,
body,
name = export_name,
)
} else {
format!(
"{}function {defname}{}\n__exports.{name} = {defname}",
export,
body,
name = export_name,
defname = definition_name,
)
}
} else if contents.starts_with("class") {
assert_eq!(export_name, definition_name);
format!("{}{}\n", export, contents)
} else {
assert_eq!(export_name, definition_name);
format!("{}const {} = {};\n", export, export_name, contents)
}
}
};
self.global(&global);
Ok(())
}
fn require_internal_export(&mut self, name: &'static str) -> Result<(), Error> {
if !self.required_internal_exports.insert(name) {
return Ok(());
}
if self.module.exports.iter().any(|e| e.name == name) {
return Ok(());
}
bail!(
"the exported function `{}` is required to generate bindings \
but it was not found in the wasm file, perhaps the `std` feature \
of the `wasm-bindgen` crate needs to be enabled?",
name
);
}
pub fn finalize(&mut self, module_name: &str) -> Result<(String, String), Error> {
// Wire up all default intrinsics, those which don't have any sort of
// dependency on the clsoure/anyref/etc passes. This is where almost all
// intrinsics are wired up.
self.wire_up_initial_intrinsics()?;
// Next up, perform our closure rewriting pass. This is where we'll
// update invocations of the closure intrinsics we have to instead call
// appropriate JS functions which actually create closures.
closures::rewrite(self).with_context(|_| "failed to generate internal closure shims")?;
// 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()?;
// And now that we're almost ready, run the final "anyref" pass. This is
// where we transform a wasm module which doesn't actually use `anyref`
// anywhere to using the type internally. The transformation here is
// based off all the previous data we've collected so far for each
// import/export listed.
self.anyref.run(self.module)?;
// With our transforms finished, we can now wire up the final list of
// intrinsics which may depend on the passes run above.
self.wire_up_late_intrinsics()?;
// We're almost done here, so we can delete any internal exports (like
// `__wbindgen_malloc`) if none of our JS glue actually needed it.
self.unexport_unused_internal_exports();
// Handle the `start` function, if one was specified. If we're in a
// --test mode (such as wasm-bindgen-test-runner) then we skip this
// entirely. Otherwise we want to first add a start function to the
// `start` section if one is specified.
//
// Note that once a start function is added, if any, we immediately
// un-start it. This is done because we require that the JS glue
// initializes first, so we execute wasm startup manually once the JS
// glue is all in place.
let mut needs_manual_start = false;
if self.config.emit_start {
self.add_start_function()?;
needs_manual_start = self.unstart_start_function();
}
// If our JS glue needs to access the function table, then do so here.
// JS closure shim generation may access the function table as an
// example, but if there's no closures in the module there's no need to
// export it!
self.export_table()?;
// After all we've done, especially
// `unexport_unused_internal_exports()`, we probably have a bunch of
// garbage in the module that's no longer necessary, so delete
// everything that we don't actually need.
walrus::passes::gc::run(self.module);
// Almost there, but before we're done make sure to rewrite the `module`
// field of all imports in the wasm module. The field is currently
// always `__wbindgen_placeholder__` coming out of rustc, but we need to
// update that here to the shim file or an actual ES module.
self.rewrite_imports(module_name)?;
// We likely made a ton of modifications, so add ourselves to the
// producers section!
self.update_producers_section();
// 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());
Ok(self.finalize_js(module_name, needs_manual_start))
}
/// 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) -> (String, String) {
let mut ts = self.typescript.clone();
let mut js = String::new();
if self.config.mode.no_modules() {
js.push_str("(function() {\n");
}
// 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());
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(&module_name, needs_manual_start);
self.footer.push_str(&format!(
"self.{} = 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,
} => {
self.footer
.push_str(&format!("wasm = require('./{}_bg');\n", module_name));
if needs_manual_start {
self.footer.push_str("wasm.__wbindgen_start();\n");
}
js.push_str("var wasm;\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,
} => {
self.imports
.push_str(&format!("import * as wasm from './{}_bg';\n", module_name));
if needs_manual_start {
self.footer.push_str("wasm.__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("const __exports = {};\n");
self.imports_post.push_str("let wasm;\n");
init = self.gen_init(&module_name, needs_manual_start);
self.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(&self.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(&self.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");
}
(js, ts)
}
fn wire_up_initial_intrinsics(&mut self) -> Result<(), Error> {
self.bind("__wbindgen_string_new", &|me| {
me.anyref.import_xform(
"__wbindgen_placeholder__",
"__wbindgen_string_new",
&[],
true,
);
me.expose_get_string_from_wasm();
Ok(format!(
"function(p, l) {{ return {}; }}",
me.add_heap_object("getStringFromWasm(p, l)")
))
})?;
self.bind("__wbindgen_number_new", &|me| {
me.anyref.import_xform(
"__wbindgen_placeholder__",
"__wbindgen_number_new",
&[],
true,
);
Ok(format!(
"function(i) {{ return {}; }}",
me.add_heap_object("i")
))
})?;
self.bind("__wbindgen_number_get", &|me| {
me.anyref.import_xform(
"__wbindgen_placeholder__",
"__wbindgen_number_get",
&[(0, false)],
false,
);
me.expose_uint8_memory();
Ok(format!(
"
function(n, invalid) {{
let obj = {};
if (typeof(obj) === 'number') return obj;
getUint8Memory()[invalid] = 1;
return 0;
}}
",
me.get_object("n"),
))
})?;
self.bind("__wbindgen_is_null", &|me| {
me.anyref.import_xform(
"__wbindgen_placeholder__",
"__wbindgen_is_null",
&[(0, false)],
false,
);
Ok(format!(
"function(i) {{ return {} === null ? 1 : 0; }}",
me.get_object("i")
))
})?;
self.bind("__wbindgen_is_undefined", &|me| {
me.anyref.import_xform(
"__wbindgen_placeholder__",
"__wbindgen_is_undefined",
&[(0, false)],
false,
);
Ok(format!(
"function(i) {{ return {} === undefined ? 1 : 0; }}",
me.get_object("i")
))
})?;
self.bind("__wbindgen_boolean_get", &|me| {
me.anyref.import_xform(
"__wbindgen_placeholder__",
"__wbindgen_boolean_get",
&[(0, false)],
false,
);
Ok(format!(
"
function(i) {{
let v = {};
return typeof(v) === 'boolean' ? (v ? 1 : 0) : 2;
}}
",
me.get_object("i"),
))
})?;
self.bind("__wbindgen_symbol_new", &|me| {
me.anyref.import_xform(
"__wbindgen_placeholder__",
"__wbindgen_symbol_new",
&[],
true,
);
me.expose_get_string_from_wasm();
let expr = "ptr === 0 ? Symbol() : Symbol(getStringFromWasm(ptr, len))";
Ok(format!(
"function(ptr, len) {{ return {}; }}",
me.add_heap_object(expr)
))
})?;
self.bind("__wbindgen_is_symbol", &|me| {
me.anyref.import_xform(
"__wbindgen_placeholder__",
"__wbindgen_is_symbol",
&[(0, false)],
false,
);
Ok(format!(
"function(i) {{ return typeof({}) === 'symbol' ? 1 : 0; }}",
me.get_object("i")
))
})?;
self.bind("__wbindgen_is_object", &|me| {
me.anyref.import_xform(
"__wbindgen_placeholder__",
"__wbindgen_is_object",
&[(0, false)],
false,
);
Ok(format!(
"
function(i) {{
const val = {};
return typeof(val) === 'object' && val !== null ? 1 : 0;
}}",
me.get_object("i"),
))
})?;
self.bind("__wbindgen_is_function", &|me| {
me.anyref.import_xform(
"__wbindgen_placeholder__",
"__wbindgen_is_function",
&[(0, false)],
false,
);
Ok(format!(
"function(i) {{ return typeof({}) === 'function' ? 1 : 0; }}",
me.get_object("i")
))
})?;
self.bind("__wbindgen_is_string", &|me| {
me.anyref.import_xform(
"__wbindgen_placeholder__",
"__wbindgen_is_string",
&[(0, false)],
false,
);
Ok(format!(
"function(i) {{ return typeof({}) === 'string' ? 1 : 0; }}",
me.get_object("i")
))
})?;
self.bind("__wbindgen_string_get", &|me| {
me.expose_pass_string_to_wasm()?;
me.expose_uint32_memory();
me.anyref.import_xform(
"__wbindgen_placeholder__",
"__wbindgen_string_get",
&[(0, false)],
false,
);
Ok(format!(
"
function(i, len_ptr) {{
let obj = {};
if (typeof(obj) !== 'string') return 0;
const ptr = passStringToWasm(obj);
getUint32Memory()[len_ptr / 4] = WASM_VECTOR_LEN;
return ptr;
}}
",
me.get_object("i"),
))
})?;
self.bind("__wbindgen_anyref_heap_live_count", &|me| {
if me.config.anyref {
// Eventually we should add support to the anyref-xform to
// re-write calls to the imported
// `__wbindgen_anyref_heap_live_count` function into calls to
// the exported `__wbindgen_anyref_heap_live_count_impl`
// function, and to un-export that function.
//
// But for now, we just bounce wasm -> js -> wasm because it is
// easy.
Ok("function() {{ return wasm.__wbindgen_anyref_heap_live_count_impl(); }}".into())
} else {
me.expose_global_heap();
Ok(format!(
"
function() {{
let free_count = 0;
let next = heap_next;
while (next < heap.length) {{
free_count += 1;
next = heap[next];
}}
return heap.length - free_count - {} - {};
}}
",
INITIAL_HEAP_OFFSET,
INITIAL_HEAP_VALUES.len(),
))
}
})?;
self.bind("__wbindgen_debug_string", &|me| {
me.expose_pass_string_to_wasm()?;
me.expose_uint32_memory();
let debug_str = "
val => {
// primitive types
const type = typeof val;
if (type == 'number' || type == 'boolean' || val == null) {
return `${val}`;
}
if (type == 'string') {
return `\"${val}\"`;
}
if (type == 'symbol') {
const description = val.description;
if (description == null) {
return 'Symbol';
} else {
return `Symbol(${description})`;
}
}
if (type == 'function') {
const name = val.name;
if (typeof name == 'string' && name.length > 0) {
return `Function(${name})`;
} else {
return 'Function';
}
}
// objects
if (Array.isArray(val)) {
const length = val.length;
let debug = '[';
if (length > 0) {
debug += debug_str(val[0]);
}
for(let i = 1; i < length; i++) {
debug += ', ' + debug_str(val[i]);
}
debug += ']';
return debug;
}
// Test for built-in
const builtInMatches = /\\[object ([^\\]]+)\\]/.exec(toString.call(val));
let className;
if (builtInMatches.length > 1) {
className = builtInMatches[1];
} else {
// Failed to match the standard '[object ClassName]'
return toString.call(val);
}
if (className == 'Object') {
// we're a user defined class or Object
// JSON.stringify avoids problems with cycles, and is generally much
// easier than looping through ownProperties of `val`.
try {
return 'Object(' + JSON.stringify(val) + ')';
} catch (_) {
return 'Object';
}
}
// errors
if (val instanceof Error) {
return `${val.name}: ${val.message}\n${val.stack}`;
}
// TODO we could test for more things here, like `Set`s and `Map`s.
return className;
}
";
Ok(format!(
"
function(i, len_ptr) {{
const debug_str = {};
const toString = Object.prototype.toString;
const val = {};
const debug = debug_str(val);
const ptr = passStringToWasm(debug);
getUint32Memory()[len_ptr / 4] = WASM_VECTOR_LEN;
return ptr;
}}
",
debug_str,
me.get_object("i"),
))
})?;
self.bind("__wbindgen_cb_drop", &|me| {
me.anyref.import_xform(
"__wbindgen_placeholder__",
"__wbindgen_cb_drop",
&[(0, true)],
false,
);
Ok(format!(
"
function(i) {{
const obj = {}.original;
if (obj.cnt-- == 1) {{
obj.a = 0;
return 1;
}}
return 0;
}}
",
me.take_object("i"),
))
})?;
self.bind("__wbindgen_cb_forget", &|me| {
Ok(if me.config.anyref {
// TODO: we should rewrite this in the anyref xform to not even
// call into JS
me.anyref.import_xform(
"__wbindgen_placeholder__",
"__wbindgen_cb_drop",
&[(0, true)],
false,
);
String::from("function(obj) {}")
} else {
me.expose_drop_ref();
"dropObject".to_string()
})
})?;
self.bind("__wbindgen_json_parse", &|me| {
me.expose_get_string_from_wasm();
me.anyref.import_xform(
"__wbindgen_placeholder__",
"__wbindgen_json_parse",
&[],
true,
);
let expr = "JSON.parse(getStringFromWasm(ptr, len))";
let expr = me.add_heap_object(expr);
Ok(format!("function(ptr, len) {{ return {}; }}", expr))
})?;
self.bind("__wbindgen_json_serialize", &|me| {
me.anyref.import_xform(
"__wbindgen_placeholder__",
"__wbindgen_json_serialize",
&[(0, false)],
false,
);
me.expose_pass_string_to_wasm()?;
me.expose_uint32_memory();
Ok(format!(
"
function(idx, ptrptr) {{
const ptr = passStringToWasm(JSON.stringify({}));
getUint32Memory()[ptrptr / 4] = ptr;
return WASM_VECTOR_LEN;
}}
",
me.get_object("idx"),
))
})?;
self.bind("__wbindgen_jsval_eq", &|me| {
Ok(format!(
"function(a, b) {{ return {} === {} ? 1 : 0; }}",
me.get_object("a"),
me.get_object("b")
))
})?;
self.bind("__wbindgen_memory", &|me| {
let mem = me.memory();
Ok(format!(
"function() {{ return {}; }}",
me.add_heap_object(mem)
))
})?;
self.bind("__wbindgen_module", &|me| {
if !me.config.mode.no_modules() && !me.config.mode.web() {
bail!(
"`wasm_bindgen::module` is currently only supported with \
`--target no-modules` and `--target web`"
);
}
Ok(format!(
"function() {{ return {}; }}",
me.add_heap_object("init.__wbindgen_wasm_module")
))
})?;
self.bind("__wbindgen_function_table", &|me| {
me.function_table_needed = true;
Ok(format!(
"function() {{ return {}; }}",
me.add_heap_object("wasm.__wbg_function_table")
))
})?;
self.bind("__wbindgen_rethrow", &|me| {
Ok(format!(
"function(idx) {{ throw {}; }}",
me.take_object("idx")
))
})?;
self.bind("__wbindgen_throw", &|me| {
me.expose_get_string_from_wasm();
Ok(String::from(
"
function(ptr, len) {
throw new Error(getStringFromWasm(ptr, len));
}
",
))
})?;
Ok(())
}
/// Provide implementations of remaining intrinsics after initial passes
/// have been run on the wasm module.
///
/// The intrinsics implemented here are added very late in the process or
/// otherwise may be overwritten by passes (such as the anyref pass). As a
/// result they don't go into the initial list of intrinsics but go just at
/// the end.
fn wire_up_late_intrinsics(&mut self) -> Result<(), Error> {
// After the anyref pass has executed, if this intrinsic is needed then
// we expose a function which initializes it
self.bind("__wbindgen_init_anyref_table", &|me| {
me.expose_anyref_table();
Ok(String::from(
"function() {
const table = wasm.__wbg_anyref_table;
const offset = table.grow(4);
table.set(offset + 0, undefined);
table.set(offset + 1, null);
table.set(offset + 2, true);
table.set(offset + 3, false);
}",
))
})?;
// make sure that the anyref pass runs before binding this as anyref may
// remove calls to this import and then gc would remove it
self.bind("__wbindgen_object_clone_ref", &|me| {
me.expose_get_object();
me.expose_add_heap_object();
Ok(String::from(
"
function(idx) {
return addHeapObject(getObject(idx));
}
",
))
})?;
// like above, make sure anyref runs first and the anyref pass may
// remove usages of this.
self.bind("__wbindgen_object_drop_ref", &|me| {
me.expose_drop_ref();
Ok(String::from("function(i) { dropObject(i); }"))
})?;
Ok(())
}
fn ts_for_init_fn(has_memory: bool) -> String {
let (memory_doc, memory_param) = if has_memory {
(
"* @param {WebAssembly.Memory} maybe_memory\n",
", maybe_memory: WebAssembly.Memory",
)
} else {
("", "")
};
format!(
"\n\
/**\n\
* If `module_or_path` is {{RequestInfo}}, makes a request and\n\
* for everything else, calls `WebAssembly.instantiate` directly.\n\
*\n\
* @param {{RequestInfo | BufferSource | WebAssembly.Module}} module_or_path\n\
{}\
*\n\
* @returns {{Promise<any>}}\n\
*/\n\
export default function init \
(module_or_path: RequestInfo | BufferSource | WebAssembly.Module{}): Promise<any>;
",
memory_doc, memory_param
)
}
fn gen_init(&mut self, module_name: &str, needs_manual_start: bool) -> (String, String) {
let mem = self.module.memories.get(self.memory);
let (init_memory1, init_memory2) = if mem.import.is_some() {
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");
(
format!("memory = __exports.memory = maybe_memory;"),
format!("memory = __exports.memory = {};", memory),
)
} else {
(String::new(), String::new())
};
let init_memory_arg = if mem.import.is_some() {
", maybe_memory"
} else {
""
};
let ts = Self::ts_for_init_fn(mem.import.is_some());
// Generate extra initialization for the `imports` object if necessary
// based on the values in `direct_imports` we find. These functions are
// intended to be imported directly to the wasm module and we need to
// ensure that the modules are actually imported from and inserted into
// the object correctly.
let mut map = BTreeMap::new();
for &(module, name) in self.direct_imports.values() {
map.entry(module).or_insert(BTreeSet::new()).insert(name);
}
let mut imports_init = String::new();
for (module, names) in map {