-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathmod.rs
2085 lines (1916 loc) · 68.2 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::fmt::Write;
use std::mem;
use failure::{Error, ResultExt};
use parity_wasm;
use parity_wasm::elements::*;
use shared;
use wasm_gc;
use super::Bindgen;
use descriptor::{Descriptor, VectorKind};
mod js2rust;
use self::js2rust::Js2Rust;
mod rust2js;
use self::rust2js::Rust2Js;
pub struct Context<'a> {
pub globals: String,
pub imports: String,
pub footer: String,
pub typescript: String,
pub exposed_globals: HashSet<&'static str>,
pub required_internal_exports: HashSet<&'static str>,
pub config: &'a Bindgen,
pub module: &'a mut Module,
/// 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<String>, HashMap<String, 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>,
pub exported_classes: HashMap<String, ExportedClass>,
pub function_table_needed: bool,
pub run_descriptor: &'a Fn(&str) -> Option<Vec<u32>>,
}
#[derive(Default)]
pub struct ExportedClass {
comments: String,
contents: String,
typescript: String,
constructor: Option<String>,
fields: Vec<ClassField>,
}
struct ClassField {
comments: Vec<String>,
name: String,
readonly: bool,
}
pub struct SubContext<'a, 'b: 'a> {
pub program: &'a shared::Program,
pub cx: &'a mut Context<'b>,
}
const INITIAL_SLAB_VALUES: &[&str] = &["undefined", "null", "true", "false"];
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_add_heap_object();
me.expose_get_object();
let bump_cnt = if me.config.debug {
String::from(
"
if (typeof(val) === 'number') throw new Error('corrupt slab');
val.cnt += 1;
",
)
} else {
String::from("val.cnt += 1;")
};
Ok(format!(
"
function(idx) {{
// If this object is on the stack promote it to the heap.
if ((idx & 1) === 1) return addHeapObject(getObject(idx));
// Otherwise if the object is on the heap just bump the
// refcount and move on
const val = slab[idx >> 1];
{}
return idx;
}}
",
bump_cnt
))
})?;
self.bind("__wbindgen_object_drop_ref", &|me| {
me.expose_drop_ref();
Ok(String::from(
"
function(i) {
dropRef(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, len] = passStringToWasm(obj);
getUint32Memory()[len_ptr / 4] = len;
return ptr;
}
",
))
})?;
self.bind("__wbindgen_cb_drop", &|me| {
me.expose_drop_ref();
Ok(String::from(
"
function(i) {
let obj = getObject(i).original;
obj.a = obj.b = 0;
dropRef(i);
}
",
))
})?;
self.bind("__wbindgen_cb_forget", &|me| {
me.expose_drop_ref();
Ok(String::from(
"
function(i) {
dropRef(i);
}
",
))
})?;
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, len] = passStringToWasm(JSON.stringify(getObject(idx)));
getUint32Memory()[ptrptr / 4] = ptr;
return 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.unexport_unused_internal_exports();
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);
let mut js = if self.config.no_modules {
format!(
"
(function() {{
var wasm;
const __exports = {{}};
{globals}
function init(wasm_path) {{
const fetchPromise = fetch(wasm_path);
let resultPromise;
if (typeof WebAssembly.instantiateStreaming === 'function') {{
resultPromise = WebAssembly.instantiateStreaming(fetchPromise, {{ './{module}': __exports }});
}} else {{
resultPromise = fetchPromise
.then(response => response.arrayBuffer())
.then(buffer => WebAssembly.instantiate(buffer, {{ './{module}': __exports }}));
}}
return resultPromise.then(({{instance}}) => {{
wasm = init.wasm = instance.exports;
return;
}});
}};
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"),
)
} 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\
{globals}\n\
{footer}",
import_wasm = import_wasm,
globals = self.globals,
imports = self.imports,
footer = self.footer,
)
};
self.export_table();
self.gc()?;
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);
if self.config.debug || class.constructor.is_some() {
self.expose_constructor_token();
dst.push_str(&format!(
"
static __construct(ptr) {{
return new {}(new ConstructorToken(ptr));
}}
constructor(...args) {{
if (args.length === 1 && args[0] instanceof ConstructorToken) {{
this.ptr = args[0].ptr;
return;
}}
",
name
));
if let Some(ref constructor) = class.constructor {
ts_dst.push_str(&format!("constructor(...args: any[]);\n"));
dst.push_str(&format!(
"
// This invocation of new will call this constructor with a ConstructorToken
let instance = {class}.{constructor}(...args);
this.ptr = instance.ptr;
",
class = name,
constructor = constructor
));
} else {
dst.push_str(
"throw new Error('you cannot invoke `new` directly without having a \
method annotated a constructor');\n",
);
}
dst.push_str("}");
} else {
dst.push_str(&format!(
"
static __construct(ptr) {{
return new {}(ptr);
}}
constructor(ptr) {{
this.ptr = ptr;
}}
",
name
));
}
let new_name = shared::new_function(&name);
if self.wasm_import_needed(&new_name) {
self.expose_add_heap_object();
self.export(
&new_name,
&format!(
"
function(ptr) {{
return addHeapObject({}.__construct(ptr));
}}
",
name
),
None,
);
}
for field in class.fields.iter() {
let wasm_getter = shared::struct_field_get(name, &field.name);
let wasm_setter = shared::struct_field_set(name, &field.name);
let descriptor = match self.describe(&wasm_getter) {
None => continue,
Some(d) => d,
};
let set = {
let mut cx = Js2Rust::new(&field.name, self);
cx.method(true, false).argument(&descriptor)?.ret(&None)?;
ts_dst.push_str(&format!(
"{}{}: {}\n",
if field.readonly { "readonly " } else { "" },
field.name,
&cx.js_arguments[0].1
));
cx.finish("", &format!("wasm.{}", wasm_setter)).0
};
let (get, _ts, js_doc) = Js2Rust::new(&field.name, self)
.method(true, false)
.ret(&Some(descriptor))?
.finish("", &format!("wasm.{}", wasm_getter));
if !dst.ends_with("\n") {
dst.push_str("\n");
}
dst.push_str(&format_doc_comments(&field.comments, Some(js_doc)));
dst.push_str("get ");
dst.push_str(&field.name);
dst.push_str(&get);
dst.push_str("\n");
if !field.readonly {
dst.push_str("set ");
dst.push_str(&field.name);
dst.push_str(&set);
}
}
dst.push_str(&format!(
"
free() {{
const ptr = this.ptr;
this.ptr = 0;
wasm.{}(ptr);
}}
",
shared::free_function(&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);
import.module_mut().push_str("./");
import.module_mut().push_str(module_name);
continue;
}
if import.module() != "env" {
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); }"),
"cos" => bind_math("(x) { return Math.cos(x); }"),
"cosf" => bind_math("(x) { return Math.cos(x); }"),
"exp" => bind_math("(x) { return Math.exp(x); }"),
"expf" => bind_math("(x) { return Math.exp(x); }"),
"log2" => bind_math("(x) { return Math.log2(x); }"),
"log2f" => bind_math("(x) { return Math.log2(x); }"),
"log10" => bind_math("(x) { return Math.log10(x); }"),
"log10f" => bind_math("(x) { return Math.log10(x); }"),
"log" => bind_math("(x) { return Math.log(x); }"),
"logf" => bind_math("(x) { return Math.log(x); }"),
"round" => bind_math("(x) { return Math.round(x); }"),
"roundf" => bind_math("(x) { return Math.round(x); }"),
"sin" => bind_math("(x) { return Math.sin(x); }"),
"sinf" => bind_math("(x) { return Math.sin(x); }"),
"pow" => bind_math("(x, y) { return Math.pow(x, y); }"),
"powf" => bind_math("(x, y) { return Math.pow(x, y); }"),
"exp2" => bind_math("(a) { return Math.pow(2, a); }"),
"exp2f" => bind_math("(a) { return Math.pow(2, a); }"),
"fmod" => bind_math("(a, b) { return a % b; }"),
"fmodf" => bind_math("(a, b) { return a % b; }"),
"fma" => bind_math("(a, b, c) { return (a * b) + c; }"),
"fmaf" => bind_math("(a, b, c) { return (a * b) + c; }"),
_ => 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_slab();
self.expose_global_slab_next();
let validate_owned = if self.config.debug {
String::from(
"
if ((idx & 1) === 1) throw new Error('cannot drop ref of stack objects');
",
)
} else {
String::new()
};
let dec_ref = if self.config.debug {
String::from(
"
if (typeof(obj) === 'number') throw new Error('corrupt slab');
obj.cnt -= 1;
if (obj.cnt > 0) return;
",
)
} else {
String::from(
"
obj.cnt -= 1;
if (obj.cnt > 0) return;
",
)
};
self.global(&format!(
"
function dropRef(idx) {{
{}
idx = idx >> 1;
if (idx < {}) return;
let obj = slab[idx];
{}
// If we hit 0 then free up our space in the slab
slab[idx] = slab_next;
slab_next = idx;
}}
",
validate_owned, INITIAL_SLAB_VALUES.len(), dec_ref
));
}
fn expose_global_stack(&mut self) {
if !self.exposed_globals.insert("stack") {
return;
}
self.global(&format!(
"
const stack = [];
"
));
if self.config.debug {
self.export(
"assertStackEmpty",
"
function() {
if (stack.length === 0) return;
throw new Error('stack is not currently empty');
}
",
None,
);
}
}
fn expose_global_slab(&mut self) {
if !self.exposed_globals.insert("slab") {
return;
}
let initial_values = INITIAL_SLAB_VALUES.iter()
.map(|s| format!("{{ obj: {} }}", s))
.collect::<Vec<_>>();
self.global(&format!("const slab = [{}];", initial_values.join(", ")));
if self.config.debug {
self.export(
"assertSlabEmpty",
&format!(
"
function() {{
for (let i = {}; i < slab.length; i++) {{
if (typeof(slab[i]) === 'number') continue;
throw new Error('slab is not currently empty');
}}
}}
",
initial_values.len()
),
None,
);
}
}
fn expose_global_slab_next(&mut self) {
if !self.exposed_globals.insert("slab_next") {
return;
}
self.expose_global_slab();
self.global(
"
let slab_next = slab.length;
",
);
}
fn expose_get_object(&mut self) {
if !self.exposed_globals.insert("get_object") {
return;
}
self.expose_global_stack();
self.expose_global_slab();
let get_obj = if self.config.debug {
String::from(
"
if (typeof(val) === 'number') throw new Error('corrupt slab');
return val.obj;
",
)
} else {
String::from(
"
return val.obj;
",
)
};
self.global(&format!(
"
function getObject(idx) {{
if ((idx & 1) === 1) {{
return stack[idx >> 1];
}} else {{
const val = slab[idx >> 1];
{}
}}
}}
",
get_obj
));
}
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_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();
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 = cachedEncoder.encode(arg);
const ptr = wasm.__wbindgen_malloc(buf.length);
getUint8Memory().set(buf, ptr);
return [ptr, buf.length];
}}
",
debug
));
Ok(())
}
fn expose_pass_array8_to_wasm(&mut self) -> Result<(), Error> {
self.expose_uint8_memory();
self.pass_array_to_wasm("passArray8ToWasm", "getUint8Memory", 1)
}
fn expose_pass_array16_to_wasm(&mut self) -> Result<(), Error> {
self.expose_uint16_memory();
self.pass_array_to_wasm("passArray16ToWasm", "getUint16Memory", 2)
}
fn expose_pass_array32_to_wasm(&mut self) -> Result<(), Error> {
self.expose_uint32_memory();
self.pass_array_to_wasm("passArray32ToWasm", "getUint32Memory", 4)
}
fn expose_pass_array64_to_wasm(&mut self) -> Result<(), Error> {
self.expose_uint64_memory();
self.pass_array_to_wasm("passArray64ToWasm", "getUint64Memory", 8)
}
fn expose_pass_array_f32_to_wasm(&mut self) -> Result<(), Error> {
self.expose_f32_memory();
self.pass_array_to_wasm("passArrayF32ToWasm", "getFloat32Memory", 4)
}
fn expose_pass_array_f64_to_wasm(&mut self) -> Result<(), Error> {
self.expose_f64_memory();
self.pass_array_to_wasm("passArrayF64ToWasm", "getFloat64Memory", 8)
}
fn expose_pass_array_jsvalue_to_wasm(&mut self) -> Result<(), Error> {
if !self.exposed_globals.insert("pass_array_jsvalue") {
return Ok(());
}
self.require_internal_export("__wbindgen_malloc")?;
self.expose_uint32_memory();
self.expose_add_heap_object();
self.global("
function passArrayJsValueToWasm(array) {
const ptr = wasm.__wbindgen_malloc(array.length * 4);
const mem = getUint32Memory();
for (let i = 0; i < array.length; i++) {
mem[ptr / 4 + i] = addHeapObject(array[i]);
}
return [ptr, array.length];
}
");
Ok(())
}
fn pass_array_to_wasm(
&mut self,
name: &'static str,
delegate: &str,
size: usize,
) -> Result<(), Error> {
if !self.exposed_globals.insert(name) {
return Ok(());
}
self.require_internal_export("__wbindgen_malloc")?;
self.global(&format!(
"