-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathmod.rs
2691 lines (2468 loc) · 90 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 std::collections::{HashMap, HashSet};
use std::mem;
use decode;
use failure::{Error, ResultExt};
use gc;
use parity_wasm::elements::Error as ParityError;
use parity_wasm::elements::*;
use shared;
use super::Bindgen;
use descriptor::{Descriptor, VectorKind};
use wasm_interpreter::Interpreter;
use wasm_utils::Remap;
mod js2rust;
use self::js2rust::Js2Rust;
mod rust2js;
use self::rust2js::Rust2Js;
mod closures;
pub struct Context<'a> {
pub globals: String,
pub imports: String,
pub imports_post: String,
pub footer: String,
pub typescript: String,
pub exposed_globals: 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<Option<&'a str>, HashMap<&'a str, String>>,
/// A set of all imported identifiers to the number of times they've been
/// imported, used to generate new identifiers.
pub imported_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: HashMap<String, ExportedClass>,
pub function_table_needed: bool,
pub interpreter: &'a mut Interpreter,
pub memory_init: Option<ResizableLimits>,
}
#[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>,
},
/// 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 export(&mut self, name: &str, contents: &str, comments: Option<String>) {
let contents = contents.trim();
if let Some(ref c) = comments {
self.globals.push_str(c);
}
let global = if self.use_node_require() {
if contents.starts_with("class") {
format!("{1}\nmodule.exports.{0} = {0};\n", name, contents)
} else {
format!("module.exports.{} = {};\n", name, contents)
}
} else if self.config.no_modules {
if contents.starts_with("class") {
format!("{1}\n__exports.{0} = {0};\n", name, contents)
} else {
format!("__exports.{} = {};\n", name, contents)
}
} else {
if contents.starts_with("function") {
format!("export function {}{}\n", name, &contents[8..])
} else if contents.starts_with("class") {
format!("export {}\n", contents)
} else {
format!("export const {} = {};\n", name, contents)
}
};
self.global(&global);
}
fn require_internal_export(&mut self, name: &'static str) -> Result<(), Error> {
if !self.required_internal_exports.insert(name) {
return Ok(());
}
if let Some(s) = self.module.export_section() {
if s.entries().iter().any(|e| e.field() == 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> {
self.write_classes()?;
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));
}
",
))
})?;
self.bind("__wbindgen_object_drop_ref", &|me| {
me.expose_drop_ref();
Ok(String::from("function(i) { dropObject(i); }"))
})?;
self.bind("__wbindgen_string_new", &|me| {
me.expose_add_heap_object();
me.expose_get_string_from_wasm();
Ok(String::from(
"
function(p, l) {
return addHeapObject(getStringFromWasm(p, l));
}
",
))
})?;
self.bind("__wbindgen_number_new", &|me| {
me.expose_add_heap_object();
Ok(String::from("function(i) { return addHeapObject(i); }"))
})?;
self.bind("__wbindgen_number_get", &|me| {
me.expose_get_object();
me.expose_uint8_memory();
Ok(String::from(
"
function(n, invalid) {
let obj = getObject(n);
if (typeof(obj) === 'number') return obj;
getUint8Memory()[invalid] = 1;
return 0;
}
",
))
})?;
self.bind("__wbindgen_is_null", &|me| {
me.expose_get_object();
Ok(String::from(
"
function(idx) {
return getObject(idx) === null ? 1 : 0;
}
",
))
})?;
self.bind("__wbindgen_is_undefined", &|me| {
me.expose_get_object();
Ok(String::from(
"
function(idx) {
return getObject(idx) === undefined ? 1 : 0;
}
",
))
})?;
self.bind("__wbindgen_boolean_get", &|me| {
me.expose_get_object();
Ok(String::from(
"
function(i) {
let v = getObject(i);
if (typeof(v) === 'boolean') {
return v ? 1 : 0;
} else {
return 2;
}
}
",
))
})?;
self.bind("__wbindgen_symbol_new", &|me| {
me.expose_get_string_from_wasm();
me.expose_add_heap_object();
Ok(String::from(
"
function(ptr, len) {
let a;
if (ptr === 0) {
a = Symbol();
} else {
a = Symbol(getStringFromWasm(ptr, len));
}
return addHeapObject(a);
}
",
))
})?;
self.bind("__wbindgen_is_symbol", &|me| {
me.expose_get_object();
Ok(String::from(
"
function(i) {
return typeof(getObject(i)) === 'symbol' ? 1 : 0;
}
",
))
})?;
self.bind("__wbindgen_is_object", &|me| {
me.expose_get_object();
Ok(String::from(
"
function(i) {
const val = getObject(i);
return typeof(val) === 'object' && val !== null ? 1 : 0;
}
",
))
})?;
self.bind("__wbindgen_is_function", &|me| {
me.expose_get_object();
Ok(String::from(
"
function(i) {
return typeof(getObject(i)) === 'function' ? 1 : 0;
}
",
))
})?;
self.bind("__wbindgen_is_string", &|me| {
me.expose_get_object();
Ok(String::from(
"
function(i) {
return typeof(getObject(i)) === 'string' ? 1 : 0;
}
",
))
})?;
self.bind("__wbindgen_string_get", &|me| {
me.expose_pass_string_to_wasm()?;
me.expose_get_object();
me.expose_uint32_memory();
Ok(String::from(
"
function(i, len_ptr) {
let obj = getObject(i);
if (typeof(obj) !== 'string') return 0;
const ptr = passStringToWasm(obj);
getUint32Memory()[len_ptr / 4] = WASM_VECTOR_LEN;
return ptr;
}
",
))
})?;
self.bind("__wbindgen_cb_drop", &|me| {
me.expose_drop_ref();
Ok(String::from(
"
function(i) {
const obj = getObject(i).original;
dropObject(i);
if (obj.cnt-- == 1) {
obj.a = 0;
return 1;
}
return 0;
}
",
))
})?;
self.bind("__wbindgen_cb_forget", &|me| {
me.expose_drop_ref();
Ok("dropObject".to_string())
})?;
self.bind("__wbindgen_json_parse", &|me| {
me.expose_add_heap_object();
me.expose_get_string_from_wasm();
Ok(String::from(
"
function(ptr, len) {
return addHeapObject(JSON.parse(getStringFromWasm(ptr, len)));
}
",
))
})?;
self.bind("__wbindgen_json_serialize", &|me| {
me.expose_get_object();
me.expose_pass_string_to_wasm()?;
me.expose_uint32_memory();
Ok(String::from(
"
function(idx, ptrptr) {
const ptr = passStringToWasm(JSON.stringify(getObject(idx)));
getUint32Memory()[ptrptr / 4] = ptr;
return WASM_VECTOR_LEN;
}
",
))
})?;
self.bind("__wbindgen_jsval_eq", &|me| {
me.expose_get_object();
Ok(String::from(
"
function(a, b) {
return getObject(a) === getObject(b) ? 1 : 0;
}
",
))
})?;
self.bind("__wbindgen_memory", &|me| {
me.expose_add_heap_object();
let mem = me.memory();
Ok(format!("function() {{ return addHeapObject({}); }}", mem))
})?;
self.bind("__wbindgen_module", &|me| {
if !me.config.no_modules {
bail!(
"`wasm_bindgen::module` is currently only supported with \
--no-modules"
);
}
me.expose_add_heap_object();
Ok(format!(
"
function() {{
return addHeapObject(init.__wbindgen_wasm_module);
}}
",
))
})?;
self.bind("__wbindgen_rethrow", &|me| {
me.expose_take_object();
Ok(String::from("function(idx) { throw takeObject(idx); }"))
})?;
closures::rewrite(self).with_context(|_| "failed to generate internal closure shims")?;
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.
//
// Afterwards, we need to perform what's a bit of a hack. Right after we
// added the start function, we remove it again because no current
// strategy for bundlers and deployment works well enough with it. For
// `--no-modules` output we need to be sure to call the start function
// after our exports are wired up (or most imported functions won't
// work).
//
// For ESM outputs bundlers like webpack also don't work because
// currently they run the wasm initialization before the JS glue
// initialization, meaning that if the wasm start function calls
// imported functions the JS glue isn't ready to go just yet.
//
// To handle `--no-modules` we just unstart the start function and call
// it manually. To handle the ESM use case we switch the start function
// to calling an imported function which defers the start function via
// `Promise.resolve().then(...)` to execute on the next microtask tick.
let mut has_start_function = false;
if self.config.emit_start {
self.add_start_function()?;
has_start_function = self.unstart_start_function();
if has_start_function && !self.config.no_modules {
self.inject_start_shim();
}
}
self.export_table();
self.gc();
// Note that it's important `throw` comes last *after* we gc. The
// `__wbindgen_malloc` function may call this but we only want to
// generate code for this if it's actually live (and __wbindgen_malloc
// isn't gc'd).
self.bind("__wbindgen_throw", &|me| {
me.expose_get_string_from_wasm();
Ok(String::from(
"
function(ptr, len) {
throw new Error(getStringFromWasm(ptr, len));
}
",
))
})?;
self.rewrite_imports(module_name);
self.update_producers_section();
let mut js = if self.config.threads.is_some() {
// TODO: It's not clear right now how to best use threads with
// bundlers like webpack. We need a way to get the existing
// module/memory into web workers for now and we don't quite know
// idiomatically how to do that! In the meantime, always require
// `--no-modules`
if !self.config.no_modules {
bail!("most use `--no-modules` with threads for now")
}
self.memory(); // set `memory_limit` if it's not already set
let limits = match &self.memory_init {
Some(l) if l.shared() => l.clone(),
_ => bail!("must impot a shared memory with threads"),
};
let mut memory = String::from("new WebAssembly.Memory({");
memory.push_str(&format!("initial:{}", limits.initial()));
if let Some(max) = limits.maximum() {
memory.push_str(&format!(",maximum:{}", max));
}
if limits.shared() {
memory.push_str(",shared:true");
}
memory.push_str("})");
format!(
"\
(function() {{
var wasm;
var memory;
const __exports = {{}};
{globals}
function init(module_or_path, maybe_memory) {{
let result;
const imports = {{ './{module}': __exports }};
if (module_or_path instanceof WebAssembly.Module) {{
memory = __exports.memory = maybe_memory;
result = WebAssembly.instantiate(module_or_path, imports)
.then(instance => {{
return {{ instance, module: module_or_path }}
}});
}} else {{
memory = __exports.memory = {init_memory};
const response = fetch(module_or_path);
if (typeof WebAssembly.instantiateStreaming === 'function') {{
result = WebAssembly.instantiateStreaming(response, imports);
}} else {{
result = response
.then(r => r.arrayBuffer())
.then(bytes => WebAssembly.instantiate(bytes, imports));
}}
}}
return result.then(({{instance, module}}) => {{
wasm = init.wasm = instance.exports;
init.__wbindgen_wasm_instance = instance;
init.__wbindgen_wasm_module = module;
init.__wbindgen_wasm_memory = __exports.memory;
{start}
}});
}};
self.{global_name} = Object.assign(init, __exports);
}})();",
globals = self.globals,
module = module_name,
global_name = self
.config
.no_modules_global
.as_ref()
.map(|s| &**s)
.unwrap_or("wasm_bindgen"),
init_memory = memory,
start = if has_start_function {
"wasm.__wbindgen_start();"
} else {
""
},
)
} else if self.config.no_modules {
format!(
"\
(function() {{
var wasm;
const __exports = {{}};
{globals}
function init(path_or_module) {{
let instantiation;
const imports = {{ './{module}': __exports }};
if (path_or_module instanceof WebAssembly.Module) {{
instantiation = WebAssembly.instantiate(path_or_module, imports)
.then(instance => {{
return {{ instance, module: path_or_module }}
}});
}} else {{
const data = fetch(path_or_module);
if (typeof WebAssembly.instantiateStreaming === 'function') {{
instantiation = WebAssembly.instantiateStreaming(data, imports);
}} else {{
instantiation = data
.then(response => response.arrayBuffer())
.then(buffer => WebAssembly.instantiate(buffer, imports));
}}
}}
return instantiation.then(({{instance}}) => {{
wasm = init.wasm = instance.exports;
{start}
}});
}};
self.{global_name} = Object.assign(init, __exports);
}})();",
globals = self.globals,
module = module_name,
global_name = self
.config
.no_modules_global
.as_ref()
.map(|s| &**s)
.unwrap_or("wasm_bindgen"),
start = if has_start_function {
"wasm.__wbindgen_start();"
} else {
""
},
)
} else {
let import_wasm = if self.globals.len() == 0 {
String::new()
} else if self.use_node_require() {
self.footer
.push_str(&format!("wasm = require('./{}_bg');", module_name));
format!("var wasm;")
} else {
format!("import * as wasm from './{}_bg';", module_name)
};
format!(
"\
/* tslint:disable */\n\
{import_wasm}\n\
{imports}\n\
{imports_post}\n\
{globals}\n\
{footer}",
import_wasm = import_wasm,
globals = self.globals,
imports = self.imports,
imports_post = self.imports_post,
footer = self.footer,
)
};
while js.contains("\n\n\n") {
js = js.replace("\n\n\n", "\n\n");
}
Ok((js, self.typescript.clone()))
}
fn bind(
&mut self,
name: &str,
f: &Fn(&mut Self) -> Result<String, Error>,
) -> Result<(), Error> {
if !self.wasm_import_needed(name) {
return Ok(());
}
let contents = f(self)
.with_context(|_| format!("failed to generate internal JS function `{}`", name))?;
self.export(name, &contents, None);
Ok(())
}
fn write_classes(&mut self) -> Result<(), Error> {
let classes = mem::replace(&mut self.exported_classes, Default::default());
for (class, exports) in classes {
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);
let (mkweakref, freeref) = if self.config.weak_refs {
// When weak refs are enabled we use them to automatically free the
// contents of an exported rust class when it's gc'd. Note that a
// manual `free` function still exists for deterministic
// destruction.
//
// This is implemented by using a `WeakRefGroup` to run finalizers
// for all `WeakRef` objects that it creates. Upon construction of
// a new wasm object we use `makeRef` with "holdings" of a thunk to
// free the wasm instance. Once the `this` (the instance we're
// creating) is gc'd then the finalizer will run with the
// `WeakRef`, and we'll pull out the `holdings`, our pointer.
//
// Note, though, that if manual finalization happens we want to
// cancel the `WeakRef`-generated finalization, so we retain the
// `WeakRef` in a global map. This global map is then used to
// `drop()` the `WeakRef` (cancel finalization) whenever it is
// finalized.
self.expose_cleanup_groups();
let mk = format!("addCleanup(this, this.ptr, free{});", name);
let free = "
CLEANUPS_MAP.get(ptr).drop();
CLEANUPS_MAP.delete(ptr);
";
(mk, free)
} else {
(String::new(), "")
};
if self.config.debug && !class.has_constructor {
dst.push_str(
"
constructor() {
throw new Error('cannot invoke `new` directly');
}
",
);
}
let mut wrap_needed = class.wrap_needed;
let new_name = shared::new_function(&name);
if self.wasm_import_needed(&new_name) {
self.expose_add_heap_object();
wrap_needed = true;
self.export(
&new_name,
&format!(
"
function(ptr) {{
return addHeapObject({}.__wrap(ptr));
}}
",
name
),
None,
);
}
if wrap_needed {
dst.push_str(&format!(
"
static __wrap(ptr) {{
const obj = Object.create({}.prototype);
obj.ptr = ptr;
{}
return obj;
}}
",
name,
mkweakref.replace("this", "obj"),
));
}
self.global(&format!(
"
function free{}(ptr) {{
{}
wasm.{}(ptr);
}}
",
name,
freeref,
shared::free_function(&name)
));
dst.push_str(&format!(
"
free() {{
const ptr = this.ptr;
this.ptr = 0;
free{}(ptr);
}}
",
name,
));
ts_dst.push_str("free(): void;\n");
dst.push_str(&class.contents);
ts_dst.push_str(&class.typescript);
dst.push_str("}\n");
ts_dst.push_str("}\n");
self.export(&name, &dst, Some(class.comments.clone()));
self.typescript.push_str(&ts_dst);
Ok(())
}
fn export_table(&mut self) {
if !self.function_table_needed {
return;
}
for section in self.module.sections_mut() {
let exports = match *section {
Section::Export(ref mut s) => s,
_ => continue,
};
let entry = ExportEntry::new("__wbg_function_table".to_string(), Internal::Table(0));
exports.entries_mut().push(entry);
break;
}
}
fn rewrite_imports(&mut self, module_name: &str) {
for (name, contents) in self._rewrite_imports(module_name) {
self.export(&name, &contents, None);
}
}
fn _rewrite_imports(&mut self, module_name: &str) -> Vec<(String, String)> {
let mut math_imports = Vec::new();
let imports = self
.module
.sections_mut()
.iter_mut()
.filter_map(|s| match *s {
Section::Import(ref mut s) => Some(s),
_ => None,
})
.flat_map(|s| s.entries_mut());
for import in imports {
if import.module() == "__wbindgen_placeholder__" {
import.module_mut().truncate(0);
if let Some((module, name)) = self.direct_imports.get(import.field()) {
import.field_mut().truncate(0);
import.module_mut().push_str(module);
import.field_mut().push_str(name);
} else {
import.module_mut().push_str("./");
import.module_mut().push_str(module_name);
}
continue;
}
if import.module() != "env" {
continue;
}
// If memory is imported we'll have exported it from the shim module
// so let's import it from there.
if import.field() == "memory" {
import.module_mut().truncate(0);
import.module_mut().push_str("./");
import.module_mut().push_str(module_name);
continue;
}
let renamed_import = format!("__wbindgen_{}", import.field());
let mut bind_math = |expr: &str| {
math_imports.push((renamed_import.clone(), format!("function{}", expr)));
};
// FIXME(#32): try to not use function shims
match import.field() {
"Math_acos" => bind_math("(x) { return Math.acos(x); }"),
"Math_asin" => bind_math("(x) { return Math.asin(x); }"),
"Math_atan" => bind_math("(x) { return Math.atan(x); }"),
"Math_atan2" => bind_math("(x, y) { return Math.atan2(x, y); }"),
"Math_cbrt" => bind_math("(x) { return Math.cbrt(x); }"),
"Math_cosh" => bind_math("(x) { return Math.cosh(x); }"),
"Math_expm1" => bind_math("(x) { return Math.expm1(x); }"),
"Math_hypot" => bind_math("(x, y) { return Math.hypot(x, y); }"),
"Math_log1p" => bind_math("(x) { return Math.log1p(x); }"),
"Math_sinh" => bind_math("(x) { return Math.sinh(x); }"),
"Math_tan" => bind_math("(x) { return Math.tan(x); }"),
"Math_tanh" => bind_math("(x) { return Math.tanh(x); }"),
_ => continue,
}
import.module_mut().truncate(0);
import.module_mut().push_str("./");
import.module_mut().push_str(module_name);
*import.field_mut() = renamed_import.clone();
}
math_imports
}
fn unexport_unused_internal_exports(&mut self) {
let required = &self.required_internal_exports;
for section in self.module.sections_mut() {
let exports = match *section {
Section::Export(ref mut s) => s,
_ => continue,
};
exports.entries_mut().retain(|export| {
!export.field().starts_with("__wbindgen") || required.contains(export.field())
});
}
}
fn expose_drop_ref(&mut self) {
if !self.exposed_globals.insert("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.exposed_globals.insert("heap") {
return;
}
self.global(&format!("const heap = new Array({});", INITIAL_HEAP_OFFSET));
self.global("heap.fill(undefined);");
self.global(&format!("heap.push({});", INITIAL_HEAP_VALUES.join(", ")));
}
fn expose_global_heap_next(&mut self) {
if !self.exposed_globals.insert("heap_next") {
return;
}
self.expose_global_heap();
self.global("let heap_next = heap.length;");
}
fn expose_get_object(&mut self) {
if !self.exposed_globals.insert("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_assert_num(&mut self) {
if !self.exposed_globals.insert("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.exposed_globals.insert("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.exposed_globals.insert("wasm_vector_len") {
return;
}
self.global("let WASM_VECTOR_LEN = 0;");
}
fn expose_pass_string_to_wasm(&mut self) -> Result<(), Error> {
if !self.exposed_globals.insert("pass_string_to_wasm") {
return Ok(());
}
self.require_internal_export("__wbindgen_malloc")?;
self.expose_text_encoder();
self.expose_uint8_memory();
self.expose_wasm_vector_len();
let debug = if self.config.debug {
"
if (typeof(arg) !== 'string') throw new Error('expected a string argument');
"
} else {
""
};
self.global(&format!(
"
function passStringToWasm(arg) {{
{}
const buf = cachedTextEncoder.encode(arg);
const ptr = wasm.__wbindgen_malloc(buf.length);
getUint8Memory().set(buf, ptr);
WASM_VECTOR_LEN = buf.length;
return ptr;
}}
",
debug
));
Ok(())
}
fn expose_pass_array8_to_wasm(&mut self) -> Result<(), Error> {
self.expose_uint8_memory();
self.pass_array_to_wasm("passArray8ToWasm", "getUint8Memory", 1)
}