-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathbinding.rs
1311 lines (1194 loc) · 44.5 KB
/
binding.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
//! Support for actually generating a JS function shim.
//!
//! This `Builder` type is used to generate JS function shims which sit between
//! exported functions, table elements, imports, etc. All function shims
//! generated by `wasm-bindgen` run through this type.
use crate::js::Context;
use crate::wit::InstructionData;
use crate::wit::{Adapter, AdapterId, AdapterKind, AdapterType, Instruction};
use anyhow::{anyhow, bail, Error};
use walrus::Module;
/// A one-size-fits-all builder for processing WebIDL bindings and generating
/// JS.
pub struct Builder<'a, 'b> {
/// Parent context used to expose helper functions and such.
pub cx: &'a mut Context<'b>,
/// Whether or not this is building a constructor for a Rust class, and if
/// so what class it's constructing.
constructor: Option<String>,
/// Whether or not this is building a method of a Rust class instance, and
/// whether or not the method consumes `self` or not.
method: Option<bool>,
/// Whether or not we're catching exceptions from the main function
/// invocation. Currently only used for imports.
catch: bool,
/// Whether or not we're logging the error coming out of this intrinsic
log_error: bool,
}
/// Helper struct used to create JS to process all instructions in an adapter
/// function.
pub struct JsBuilder<'a, 'b> {
/// General context for building JS, used to manage intrinsic names, exposed
/// JS functions, etc.
cx: &'a mut Context<'b>,
/// The "prelude" of the function, or largely just the JS function we've
/// built so far.
prelude: String,
/// JS code to execute in a `finally` block in case any exceptions happen.
finally: String,
/// An index used to manage allocation of temporary indices, used to name
/// variables to ensure nothing clashes with anything else.
tmp: usize,
/// Names or expressions representing the arguments to the adapter. This is
/// use to translate the `arg.get` instruction.
args: Vec<String>,
/// The wasm interface types "stack". The expressions pushed onto this stack
/// are intended to be *pure*, and if they're not, they should be pushed
/// into the `prelude`, assigned to a variable, and the variable should be
/// pushed to the stack. We're not super principled about this though, so
/// improvements will likely happen here over time.
stack: Vec<String>,
}
pub struct JsFunction {
pub code: String,
pub ts_sig: String,
pub js_doc: String,
pub ts_arg_tys: Vec<String>,
pub ts_ret_ty: Option<String>,
pub might_be_optional_field: bool,
pub catch: bool,
pub log_error: bool,
}
impl<'a, 'b> Builder<'a, 'b> {
pub fn new(cx: &'a mut Context<'b>) -> Builder<'a, 'b> {
Builder {
log_error: false,
cx,
constructor: None,
method: None,
catch: false,
}
}
pub fn method(&mut self, consumed: bool) {
self.method = Some(consumed);
}
pub fn constructor(&mut self, class: &str) {
self.constructor = Some(class.to_string());
}
pub fn catch(&mut self, catch: bool) {
self.catch = catch;
}
pub fn log_error(&mut self, log: bool) {
self.log_error = log;
}
pub fn process(
&mut self,
adapter: &Adapter,
instructions: &[InstructionData],
explicit_arg_names: &Option<Vec<String>>,
asyncness: bool,
) -> Result<JsFunction, Error> {
if self
.cx
.aux
.imports_with_assert_no_shim
.contains(&adapter.id)
{
bail!("generating a shim for something asserted to have no shim");
}
let mut params = adapter.params.iter();
let mut function_args = Vec::new();
let mut arg_tys = Vec::new();
// If this is a method then we're generating this as part of a class
// method, so the leading parameter is the this pointer stored on
// the JS object, so synthesize that here.
let mut js = JsBuilder::new(self.cx);
match self.method {
Some(consumes_self) => {
drop(params.next());
if js.cx.config.debug {
js.prelude(
"if (this.ptr == 0) throw new Error('Attempt to use a moved value');",
);
}
if consumes_self {
js.prelude("const ptr = this.__destroy_into_raw();");
js.args.push("ptr".into());
} else {
js.args.push("this.ptr".into());
}
}
None => {}
}
for (i, param) in params.enumerate() {
let arg = match explicit_arg_names {
Some(list) => list[i].clone(),
None => format!("arg{}", i),
};
js.args.push(arg.clone());
function_args.push(arg);
arg_tys.push(param);
}
// Translate all instructions, the fun loop!
//
// This loop will process all instructions for this adapter function.
// Each instruction will push/pop from the `js.stack` variable, and will
// eventually build up the entire `js.prelude` variable with all the JS
// code that we're going to be adding. Note that the stack at the end
// represents all returned values.
//
// We don't actually manage a literal stack at runtime, but instead we
// act as more of a compiler to generate straight-line code to make it
// more JIT-friendly. The generated code should be equivalent to the
// wasm interface types stack machine, however.
for instr in instructions {
instruction(&mut js, &instr.instr, &mut self.log_error)?;
}
assert_eq!(js.stack.len(), adapter.results.len());
match js.stack.len() {
0 => {}
1 => {
let val = js.pop();
js.prelude(&format!("return {};", val));
}
// TODO: this should be pretty trivial to support (commented out
// code below), but we should be sure to have a test for this
// somewhere. Currently I don't think it's possible to actually
// exercise this with just Rust code, so let's wait until we get
// some tests to enable this path.
_ => bail!("multi-value returns from adapters not supported yet"),
// _ => {
// let expr = js.stack.join(", ");
// js.stack.truncate(0);
// js.prelude(&format!("return [{}];", expr));
// }
}
assert!(js.stack.is_empty());
// // Remove extraneous typescript args which were synthesized and aren't
// // part of our function shim.
// while self.ts_args.len() > function_args.len() {
// self.ts_args.remove(0);
// }
let mut code = String::new();
code.push_str("(");
code.push_str(&function_args.join(", "));
code.push_str(") {\n");
let mut call = js.prelude;
if js.finally.len() != 0 {
call = format!("try {{\n{}}} finally {{\n{}}}\n", call, js.finally);
}
if self.catch {
js.cx.expose_handle_error()?;
}
// Generate a try/catch block in debug mode which handles unexpected and
// unhandled exceptions, typically used on imports. This currently just
// logs what happened, but keeps the exception being thrown to propagate
// elsewhere.
if self.log_error {
js.cx.expose_log_error();
}
code.push_str(&call);
code.push_str("}");
// Rust Structs' fields converted into Getter and Setter functions before
// we decode them from webassembly, finding if a function is a field
// should start from here. Struct fields(Getter) only have one arg, and
// this is the clue we can infer if a function might be a field.
let mut might_be_optional_field = false;
let (ts_sig, ts_arg_tys, ts_ret_ty) = self.typescript_signature(
&function_args,
&arg_tys,
&adapter.inner_results,
&mut might_be_optional_field,
asyncness,
);
let js_doc = self.js_doc_comments(&function_args, &arg_tys, &ts_ret_ty);
Ok(JsFunction {
code,
ts_sig,
js_doc,
ts_arg_tys,
ts_ret_ty,
might_be_optional_field,
catch: self.catch,
log_error: self.log_error,
})
}
/// Returns the typescript signature of the binding that this has described.
/// This is used to generate all the TypeScript definitions later on.
///
/// Note that the TypeScript returned here is just the argument list and the
/// return value, it doesn't include the function name in any way.
fn typescript_signature(
&self,
arg_names: &[String],
arg_tys: &[&AdapterType],
result_tys: &[AdapterType],
might_be_optional_field: &mut bool,
asyncness: bool,
) -> (String, Vec<String>, Option<String>) {
// Build up the typescript signature as well
let mut omittable = true;
let mut ts_args = Vec::new();
let mut ts_arg_tys = Vec::new();
for (name, ty) in arg_names.iter().zip(arg_tys).rev() {
// In TypeScript, we can mark optional parameters as omittable
// using the `?` suffix, but only if they're not followed by
// non-omittable parameters. Therefore iterate the parameter list
// in reverse and stop using the `?` suffix for optional params as
// soon as a non-optional parameter is encountered.
let mut arg = name.to_string();
let mut ts = String::new();
match ty {
AdapterType::Option(ty) if omittable => {
arg.push_str("?: ");
adapter2ts(ty, &mut ts);
}
ty => {
omittable = false;
arg.push_str(": ");
adapter2ts(ty, &mut ts);
}
}
arg.push_str(&ts);
ts_arg_tys.push(ts);
ts_args.push(arg);
}
ts_args.reverse();
ts_arg_tys.reverse();
let mut ts = format!("({})", ts_args.join(", "));
// If this function is an optional field's setter, it should have only
// one arg, and omittable should be `true`.
if ts_args.len() == 1 && omittable {
*might_be_optional_field = true;
}
// Constructors have no listed return type in typescript
let mut ts_ret = None;
if self.constructor.is_none() {
ts.push_str(": ");
let mut ret = String::new();
match result_tys.len() {
0 => ret.push_str("void"),
1 => adapter2ts(&result_tys[0], &mut ret),
_ => ret.push_str("[any]"),
}
if asyncness {
ret = format!("Promise<{}>", ret);
}
ts.push_str(&ret);
ts_ret = Some(ret);
}
return (ts, ts_arg_tys, ts_ret);
}
/// Returns a helpful JS doc comment which lists types for all parameters
/// and the return value.
fn js_doc_comments(
&self,
arg_names: &[String],
arg_tys: &[&AdapterType],
ts_ret: &Option<String>,
) -> String {
let mut ret = String::new();
for (name, ty) in arg_names.iter().zip(arg_tys) {
ret.push_str("@param {");
adapter2ts(ty, &mut ret);
ret.push_str("} ");
ret.push_str(name);
ret.push_str("\n");
}
if let Some(ts) = ts_ret {
if ts != "void" {
ret.push_str(&format!("@returns {{{}}}", ts));
}
}
ret
}
}
impl<'a, 'b> JsBuilder<'a, 'b> {
pub fn new(cx: &'a mut Context<'b>) -> JsBuilder<'a, 'b> {
JsBuilder {
cx,
args: Vec::new(),
tmp: 0,
finally: String::new(),
prelude: String::new(),
stack: Vec::new(),
}
}
pub fn arg(&self, idx: u32) -> &str {
&self.args[idx as usize]
}
pub fn prelude(&mut self, prelude: &str) {
for line in prelude.trim().lines().map(|l| l.trim()) {
if !line.is_empty() {
self.prelude.push_str(line);
self.prelude.push_str("\n");
}
}
}
pub fn finally(&mut self, finally: &str) {
for line in finally.trim().lines().map(|l| l.trim()) {
if !line.is_empty() {
self.finally.push_str(line);
self.finally.push_str("\n");
}
}
}
pub fn tmp(&mut self) -> usize {
let ret = self.tmp;
self.tmp += 1;
return ret;
}
fn pop(&mut self) -> String {
self.stack.pop().unwrap()
}
fn push(&mut self, arg: String) {
self.stack.push(arg);
}
fn assert_class(&mut self, arg: &str, class: &str) {
self.cx.expose_assert_class();
self.prelude(&format!("_assertClass({}, {});", arg, class));
}
fn assert_number(&mut self, arg: &str) {
if !self.cx.config.debug {
return;
}
self.cx.expose_assert_num();
self.prelude(&format!("_assertNum({});", arg));
}
fn assert_bool(&mut self, arg: &str) {
if !self.cx.config.debug {
return;
}
self.cx.expose_assert_bool();
self.prelude(&format!("_assertBoolean({});", arg));
}
fn assert_optional_number(&mut self, arg: &str) {
if !self.cx.config.debug {
return;
}
self.cx.expose_is_like_none();
self.prelude(&format!("if (!isLikeNone({})) {{", arg));
self.assert_number(arg);
self.prelude("}");
}
fn assert_optional_bool(&mut self, arg: &str) {
if !self.cx.config.debug {
return;
}
self.cx.expose_is_like_none();
self.prelude(&format!("if (!isLikeNone({})) {{", arg));
self.assert_bool(arg);
self.prelude("}");
}
fn assert_not_moved(&mut self, arg: &str) {
if !self.cx.config.debug {
return;
}
self.prelude(&format!(
"\
if ({0}.ptr === 0) {{
throw new Error('Attempt to use a moved value');
}}
",
arg,
));
}
fn string_to_memory(
&mut self,
mem: walrus::MemoryId,
malloc: walrus::FunctionId,
realloc: Option<walrus::FunctionId>,
) -> Result<(), Error> {
let pass = self.cx.expose_pass_string_to_wasm(mem)?;
let val = self.pop();
let malloc = self.cx.export_name_of(malloc);
let i = self.tmp();
let realloc = match realloc {
Some(f) => format!(", wasm.{}", self.cx.export_name_of(f)),
None => String::new(),
};
self.prelude(&format!(
"var ptr{i} = {f}({0}, wasm.{malloc}{realloc});",
val,
i = i,
f = pass,
malloc = malloc,
realloc = realloc,
));
self.prelude(&format!("var len{} = WASM_VECTOR_LEN;", i));
self.push(format!("ptr{}", i));
self.push(format!("len{}", i));
Ok(())
}
}
fn instruction(js: &mut JsBuilder, instr: &Instruction, log_error: &mut bool) -> Result<(), Error> {
match instr {
Instruction::Standard(wit_walrus::Instruction::ArgGet(n)) => {
let arg = js.arg(*n).to_string();
js.push(arg);
}
Instruction::Standard(wit_walrus::Instruction::CallAdapter(_)) => {
panic!("standard call adapter functions should be mapped to our adapters");
}
Instruction::Standard(wit_walrus::Instruction::CallCore(_))
| Instruction::CallExport(_)
| Instruction::CallAdapter(_)
| Instruction::CallTableElement(_)
| Instruction::Standard(wit_walrus::Instruction::DeferCallCore(_)) => {
let invoc = Invocation::from(instr, js.cx.module)?;
let (params, results) = invoc.params_results(js.cx);
// Pop off the number of parameters for the function we're calling
let mut args = Vec::new();
for _ in 0..params {
args.push(js.pop());
}
args.reverse();
// Call the function through an export of the underlying module.
let call = invoc.invoke(js.cx, &args, &mut js.prelude, log_error)?;
// And then figure out how to actually handle where the call
// happens. This is pretty conditional depending on the number of
// return values of the function.
match (invoc.defer(), results) {
(true, 0) => {
js.finally(&format!("{};", call));
js.stack.extend(args);
}
(true, _) => panic!("deferred calls must have no results"),
(false, 0) => js.prelude(&format!("{};", call)),
(false, n) => {
js.prelude(&format!("var ret = {};", call));
if n == 1 {
js.push("ret".to_string());
} else {
for i in 0..n {
js.push(format!("ret[{}]", i));
}
}
}
}
}
Instruction::Standard(wit_walrus::Instruction::IntToWasm { trap: false, .. }) => {
let val = js.pop();
js.assert_number(&val);
js.push(val);
}
// When converting to a JS number we need to specially handle the `u32`
// case because if the high bit is set then it comes out as a negative
// number, but we want to switch that to an unsigned representation.
Instruction::Standard(wit_walrus::Instruction::WasmToInt {
trap: false,
output,
..
}) => {
let val = js.pop();
match output {
wit_walrus::ValType::U32 => js.push(format!("{} >>> 0", val)),
_ => js.push(val),
}
}
Instruction::Standard(wit_walrus::Instruction::WasmToInt { trap: true, .. })
| Instruction::Standard(wit_walrus::Instruction::IntToWasm { trap: true, .. }) => {
bail!("trapping wasm-to-int and int-to-wasm instructions not supported")
}
Instruction::Standard(wit_walrus::Instruction::MemoryToString(mem)) => {
let len = js.pop();
let ptr = js.pop();
let get = js.cx.expose_get_string_from_wasm(*mem)?;
js.push(format!("{}({}, {})", get, ptr, len));
}
Instruction::Standard(wit_walrus::Instruction::StringToMemory { mem, malloc }) => {
js.string_to_memory(*mem, *malloc, None)?;
}
Instruction::StringToMemory {
mem,
malloc,
realloc,
} => {
js.string_to_memory(*mem, *malloc, *realloc)?;
}
Instruction::Retptr { size } => {
js.cx.inject_stack_pointer_shim()?;
js.prelude(&format!(
"const retptr = wasm.__wbindgen_add_to_stack_pointer(-{});",
size
));
js.finally(&format!("wasm.__wbindgen_add_to_stack_pointer({});", size));
js.stack.push("retptr".to_string());
}
Instruction::StoreRetptr { ty, offset, mem } => {
let (mem, size) = match ty {
AdapterType::I32 => (js.cx.expose_int32_memory(*mem), 4),
AdapterType::F32 => (js.cx.expose_f32_memory(*mem), 4),
AdapterType::F64 => (js.cx.expose_f64_memory(*mem), 8),
other => bail!("invalid aggregate return type {:?}", other),
};
// Note that we always assume the return pointer is argument 0,
// which is currently the case for LLVM.
let val = js.pop();
let expr = format!(
"{}()[{} / {} + {}] = {};",
mem,
js.arg(0),
size,
offset,
val,
);
js.prelude(&expr);
}
Instruction::LoadRetptr { ty, offset, mem } => {
let (mem, quads) = match ty {
AdapterType::I32 => (js.cx.expose_int32_memory(*mem), 1),
AdapterType::F32 => (js.cx.expose_f32_memory(*mem), 1),
AdapterType::F64 => (js.cx.expose_f64_memory(*mem), 2),
other => bail!("invalid aggregate return type {:?}", other),
};
let size = quads * 4;
// Separate the offset and the scaled offset, because otherwise you don't guarantee
// that the variable names will be unique.
let scaled_offset = offset / quads;
// If we're loading from the return pointer then we must have pushed
// it earlier, and we always push the same value, so load that value
// here
let expr = format!("{}()[retptr / {} + {}]", mem, size, scaled_offset);
js.prelude(&format!("var r{} = {};", offset, expr));
js.push(format!("r{}", offset));
}
Instruction::I32FromBool => {
let val = js.pop();
js.assert_bool(&val);
// JS will already coerce booleans into numbers for us
js.push(val);
}
Instruction::I32FromStringFirstChar => {
let val = js.pop();
js.push(format!("{}.codePointAt(0)", val));
}
Instruction::I32FromExternrefOwned => {
js.cx.expose_add_heap_object();
let val = js.pop();
js.push(format!("addHeapObject({})", val));
}
Instruction::I32FromExternrefBorrow => {
js.cx.expose_borrowed_objects();
js.cx.expose_global_stack_pointer();
let val = js.pop();
js.push(format!("addBorrowedObject({})", val));
js.finally("heap[stack_pointer++] = undefined;");
}
Instruction::I32FromExternrefRustOwned { class } => {
let val = js.pop();
js.assert_class(&val, &class);
js.assert_not_moved(&val);
let i = js.tmp();
js.prelude(&format!("var ptr{} = {}.ptr;", i, val));
js.prelude(&format!("{}.ptr = 0;", val));
js.push(format!("ptr{}", i));
}
Instruction::I32FromExternrefRustBorrow { class } => {
let val = js.pop();
js.assert_class(&val, &class);
js.assert_not_moved(&val);
js.push(format!("{}.ptr", val));
}
Instruction::I32FromOptionRust { class } => {
let val = js.pop();
js.cx.expose_is_like_none();
let i = js.tmp();
js.prelude(&format!("let ptr{} = 0;", i));
js.prelude(&format!("if (!isLikeNone({0})) {{", val));
js.assert_class(&val, class);
js.assert_not_moved(&val);
js.prelude(&format!("ptr{} = {}.ptr;", i, val));
js.prelude(&format!("{}.ptr = 0;", val));
js.prelude("}");
js.push(format!("ptr{}", i));
}
Instruction::I32Split64 { signed } => {
let val = js.pop();
let f = if *signed {
js.cx.expose_int64_cvt_shim()
} else {
js.cx.expose_uint64_cvt_shim()
};
let i = js.tmp();
js.prelude(&format!(
"
{f}[0] = {val};
const low{i} = u32CvtShim[0];
const high{i} = u32CvtShim[1];
",
i = i,
f = f,
val = val,
));
js.push(format!("low{}", i));
js.push(format!("high{}", i));
}
Instruction::I32SplitOption64 { signed } => {
let val = js.pop();
js.cx.expose_is_like_none();
let f = if *signed {
js.cx.expose_int64_cvt_shim()
} else {
js.cx.expose_uint64_cvt_shim()
};
let i = js.tmp();
js.prelude(&format!(
"\
{f}[0] = isLikeNone({val}) ? BigInt(0) : {val};
const low{i} = u32CvtShim[0];
const high{i} = u32CvtShim[1];
",
i = i,
f = f,
val = val,
));
js.push(format!("!isLikeNone({0})", val));
js.push(format!("low{}", i));
js.push(format!("high{}", i));
}
Instruction::I32FromOptionExternref { table_and_alloc } => {
let val = js.pop();
js.cx.expose_is_like_none();
match table_and_alloc {
Some((table, alloc)) => {
let alloc = js.cx.expose_add_to_externref_table(*table, *alloc)?;
js.push(format!("isLikeNone({0}) ? 0 : {1}({0})", val, alloc));
}
None => {
js.cx.expose_add_heap_object();
js.push(format!("isLikeNone({0}) ? 0 : addHeapObject({0})", val));
}
}
}
Instruction::I32FromOptionU32Sentinel => {
let val = js.pop();
js.cx.expose_is_like_none();
js.assert_optional_number(&val);
js.push(format!("isLikeNone({0}) ? 0xFFFFFF : {0}", val));
}
Instruction::I32FromOptionBool => {
let val = js.pop();
js.cx.expose_is_like_none();
js.assert_optional_bool(&val);
js.push(format!("isLikeNone({0}) ? 0xFFFFFF : {0} ? 1 : 0", val));
}
Instruction::I32FromOptionChar => {
let val = js.pop();
js.cx.expose_is_like_none();
js.push(format!(
"isLikeNone({0}) ? 0xFFFFFF : {0}.codePointAt(0)",
val
));
}
Instruction::I32FromOptionEnum { hole } => {
let val = js.pop();
js.cx.expose_is_like_none();
js.assert_optional_number(&val);
js.push(format!("isLikeNone({0}) ? {1} : {0}", val, hole));
}
Instruction::FromOptionNative { .. } => {
let val = js.pop();
js.cx.expose_is_like_none();
js.assert_optional_number(&val);
js.push(format!("!isLikeNone({0})", val));
js.push(format!("isLikeNone({0}) ? 0 : {0}", val));
}
Instruction::VectorToMemory { kind, malloc, mem } => {
let val = js.pop();
let func = js.cx.pass_to_wasm_function(kind.clone(), *mem)?;
let malloc = js.cx.export_name_of(*malloc);
let i = js.tmp();
js.prelude(&format!(
"var ptr{i} = {f}({0}, wasm.{malloc});",
val,
i = i,
f = func,
malloc = malloc,
));
js.prelude(&format!("var len{} = WASM_VECTOR_LEN;", i));
js.push(format!("ptr{}", i));
js.push(format!("len{}", i));
}
Instruction::UnwrapResult { table_and_drop } => {
let take_object = if let Some((table, drop)) = *table_and_drop {
js.cx
.expose_take_from_externref_table(table, drop)?
.to_string()
} else {
js.cx.expose_take_object();
"takeObject".to_string()
};
// is_err is popped first. The original layout was: ResultAbi {
// abi: ResultAbiUnion<T>,
// err: u32,
// is_err: u32,
// }
// So is_err is last to be added to the stack.
let is_err = js.pop();
let err = js.pop();
js.prelude(&format!(
"
if ({is_err}) {{
throw {take_object}({err});
}}
",
take_object = take_object,
is_err = is_err,
err = err,
));
}
Instruction::UnwrapResultString { table_and_drop } => {
let take_object = if let Some((table, drop)) = *table_and_drop {
js.cx
.expose_take_from_externref_table(table, drop)?
.to_string()
} else {
js.cx.expose_take_object();
"takeObject".to_string()
};
let is_err = js.pop();
let err = js.pop();
let len = js.pop();
let ptr = js.pop();
let i = js.tmp();
js.prelude(&format!(
"
var ptr{i} = {ptr};
var len{i} = {len};
if ({is_err}) {{
ptr{i} = 0; len{i} = 0;
throw {take_object}({err});
}}
",
take_object = take_object,
is_err = is_err,
err = err,
i = i,
ptr = ptr,
len = len,
));
js.push(format!("ptr{}", i));
js.push(format!("len{}", i));
}
Instruction::OptionString {
mem,
malloc,
realloc,
} => {
let func = js.cx.expose_pass_string_to_wasm(*mem)?;
js.cx.expose_is_like_none();
let i = js.tmp();
let malloc = js.cx.export_name_of(*malloc);
let val = js.pop();
let realloc = match realloc {
Some(f) => format!(", wasm.{}", js.cx.export_name_of(*f)),
None => String::new(),
};
js.prelude(&format!(
"var ptr{i} = isLikeNone({0}) ? 0 : {f}({0}, wasm.{malloc}{realloc});",
val,
i = i,
f = func,
malloc = malloc,
realloc = realloc,
));
js.prelude(&format!("var len{} = WASM_VECTOR_LEN;", i));
js.push(format!("ptr{}", i));
js.push(format!("len{}", i));
}
Instruction::OptionVector { kind, mem, malloc } => {
let func = js.cx.pass_to_wasm_function(kind.clone(), *mem)?;
js.cx.expose_is_like_none();
let i = js.tmp();
let malloc = js.cx.export_name_of(*malloc);
let val = js.pop();
js.prelude(&format!(
"var ptr{i} = isLikeNone({0}) ? 0 : {f}({0}, wasm.{malloc});",
val,
i = i,
f = func,
malloc = malloc,
));
js.prelude(&format!("var len{} = WASM_VECTOR_LEN;", i));
js.push(format!("ptr{}", i));
js.push(format!("len{}", i));
}
Instruction::MutableSliceToMemory {
kind,
malloc,
mem,
free,
} => {
// First up, pass the JS value into wasm, getting out a pointer and
// a length. These two pointer/length values get pushed onto the
// value stack.
let val = js.pop();
let func = js.cx.pass_to_wasm_function(kind.clone(), *mem)?;
let malloc = js.cx.export_name_of(*malloc);
let i = js.tmp();
js.prelude(&format!(
"var ptr{i} = {f}({val}, wasm.{malloc});",
val = val,
i = i,
f = func,
malloc = malloc,
));
js.prelude(&format!("var len{} = WASM_VECTOR_LEN;", i));
js.push(format!("ptr{}", i));
js.push(format!("len{}", i));
// Next we set up a `finally` clause which will both update the
// original mutable slice with any modifications, and then free the
// Rust-backed memory.
let free = js.cx.export_name_of(*free);
let get = js.cx.memview_function(kind.clone(), *mem);
js.finally(&format!(
"
{val}.set({get}().subarray(ptr{i} / {size}, ptr{i} / {size} + len{i}));
wasm.{free}(ptr{i}, len{i} * {size});
",
val = val,
get = get,
free = free,
size = kind.size(),
i = i,
));
}
Instruction::BoolFromI32 => {
let val = js.pop();
js.push(format!("{} !== 0", val));
}
Instruction::ExternrefLoadOwned => {
js.cx.expose_take_object();
let val = js.pop();
js.push(format!("takeObject({})", val));
}
Instruction::StringFromChar => {
let val = js.pop();
js.push(format!("String.fromCodePoint({})", val));
}
Instruction::I64FromLoHi { signed } => {
let f = if *signed {
js.cx.expose_int64_cvt_shim()
} else {
js.cx.expose_uint64_cvt_shim()
};
let i = js.tmp();
let high = js.pop();
let low = js.pop();
js.prelude(&format!(
"\
u32CvtShim[0] = {low};
u32CvtShim[1] = {high};
const n{i} = {f}[0];
",
low = low,
high = high,
f = f,
i = i,
));
js.push(format!("n{}", i))
}
Instruction::RustFromI32 { class } => {
js.cx.require_class_wrap(class);
let val = js.pop();
js.push(format!("{}.__wrap({})", class, val));
}
Instruction::OptionRustFromI32 { class } => {
js.cx.require_class_wrap(class);
let val = js.pop();
js.push(format!(
"{0} === 0 ? undefined : {1}.__wrap({0})",
val, class,
))
}
Instruction::CachedStringLoad {
owned,
optional: _,
mem,
free,
} => {
let len = js.pop();