-
-
Notifications
You must be signed in to change notification settings - Fork 670
/
Copy pathjs.ts
1605 lines (1547 loc) · 54.5 KB
/
js.ts
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
import {
NodeKind,
DecoratorKind,
LiteralKind,
LiteralExpression,
StringLiteralExpression,
TemplateLiteralExpression,
findDecorator,
Source
} from "../ast";
import {
CommonFlags
} from "../common";
import {
runtimeFunctions,
runtimeGlobals
} from "../compiler";
import {
ElementKind,
Element,
Program,
Function,
Global,
Class,
Interface,
Enum,
EnumValue,
PropertyPrototype
} from "../program";
import {
Type,
TypeFlags,
Signature
} from "../types";
import {
CharCode,
escapeString,
indent,
isIdentifier
} from "../util";
import {
ExportsWalker
} from "./util";
// Limitations
//
// - Instrumented globals are no longer WebAssembly.Global, hence cannot be
// imported the same way as non-instrumented globals would allow. Affects both
// globals imported here and globals imported elsewhere.
//
// - Since little is known about how class imports and exports will behave,
// there is currently no glue generated for them. In IT there appears to be
// a concept of protocols that may or may not map in the future. In GC there
// doesn't appear to be a connection between classes and their methods so far.
//
// Instead, generated bindings are limited to lifting and lowering of plain
// objects when the class has no constructor and no non-public elements. In
// any other sitation an internal or external reference is passed.
//
// - Linking two instrumented modules with separate bindings produces
// intermediate garbage (i.e. goes through a temporary JS object). Any native
// mechanism enabling communication between modules directly would help here.
//
// - Cycles between the internal and the external GC cannot be resolved. Using
// a common GC as envisioned by the GC proposal can help here, but so far it
// seems that the same limitations as for IT will remain.
//
// - Duplicate Wasm imports don't yet work when instrumentation is required as
// provided argument types cannot be told apart when these only come in as
// numbers. It might be possible to modify the binary post compilation, but
// this has not been attempted yet.
//
// Oddities
//
// - Interface Types `string` will be incompatible with JavaScript `String` and
// it remains unclear how to proceed on this front. We could either use the IT
// mechanism and accept potential hazards or keep using unfortunate glue code.
//
// - Functions with a variable number of arguments need some special glue to
// inform the binary how many arguments have been provided so it can fill in
// defaults for the omitted arguments. No native mechanism in sight, yet.
//
// - Optional BigInt arguments must be coerced to 0n since JS does not
// implicitly coerce from `null` or `undefined`. Numbers do, however.
//
// - Generated bindings assume little endian architecture with typed arrays as
// it appears to be more efficient than using a DataView and BE use cases
// haven't been seen in the wild so far.
//
// - It is assumed that generated import bindings call JavaScript and that the
// callee expects a properly coerced integer value, leading to more `>>> 0`
// coercions than necessary when the import is actually another Wasm module.
/** Maps special imports to their actual modules. */
function importToModule(moduleName: string): string {
// Map rtrace via `imports` in package.json
if (moduleName == "rtrace") return "#rtrace";
return moduleName;
}
/** Determines whether a module's imports should be instrumented. */
function shouldInstrument(moduleName: string): bool {
return moduleName != "rtrace";
}
/** A JavaScript bindings builder. */
export class JSBuilder extends ExportsWalker {
/** Builds JavaScript bindings for the specified program. */
static build(program: Program, esm: bool = true): string {
return new JSBuilder(program, esm).build();
}
private esm: bool;
private sb: string[] = [];
private indentLevel: i32 = 0;
private needsLiftBuffer: bool = false;
private needsLowerBuffer: bool = false;
private needsLiftString: bool = false;
private needsLowerString: bool = false;
private needsLiftArray: bool = false;
private needsLowerArray: bool = false;
private needsLiftTypedArray: bool = false;
private needsLowerTypedArray: bool = false;
private needsLiftStaticArray: bool = false;
private needsLowerStaticArray: bool = false;
private needsLiftInternref: bool = false;
private needsLowerInternref: bool = false;
private needsRetain: bool = false;
private needsRelease: bool = false;
private needsNotNull: bool = false;
private needsSetU8: bool = false;
private needsSetU16: bool = false;
private needsSetU32: bool = false;
private needsSetU64: bool = false;
private needsSetF32: bool = false;
private needsSetF64: bool = false;
private needsGetI8: bool = false;
private needsGetU8: bool = false;
private needsGetI16: bool = false;
private needsGetU16: bool = false;
private needsGetI32: bool = false;
private needsGetU32: bool = false;
private needsGetI64: bool = false;
private needsGetU64: bool = false;
private needsGetF32: bool = false;
private needsGetF64: bool = false;
private deferredLifts: Set<Element> = new Set();
private deferredLowers: Set<Element> = new Set();
private deferredCode: string[] = new Array<string>();
private exports: string[] = new Array();
private importMappings: Map<string,i32> = new Map();
/** Constructs a new JavaScript bindings builder. */
constructor(program: Program, esm: bool, includePrivate: bool = false) {
super(program, includePrivate);
this.esm = esm;
}
visitGlobal(name: string, element: Global): void {
let sb = this.sb;
let type = element.type;
this.exports.push(name);
if (!isPlainValue(type, Mode.Export)) {
indent(sb, this.indentLevel);
sb.push(name);
sb.push(": {\n");
indent(sb, ++this.indentLevel);
sb.push("// ");
sb.push(element.internalName);
sb.push(": ");
sb.push(type.toString());
sb.push("\n");
indent(sb, this.indentLevel);
sb.push("valueOf() { return this.value; },\n");
indent(sb, this.indentLevel);
sb.push("get value() {\n");
indent(sb, ++this.indentLevel);
sb.push("return ");
this.makeLiftFromValue("exports." + name + ".value", type, sb);
sb.push(";\n");
indent(sb, --this.indentLevel);
sb.push("}");
if (!element.is(CommonFlags.Const)) {
sb.push(",\n");
indent(sb, this.indentLevel);
sb.push("set value(value) {\n");
indent(sb, ++this.indentLevel);
sb.push("exports.");
sb.push(name);
sb.push(".value = ");
this.makeLowerToValue("value", type, sb);
sb.push(";\n");
indent(sb, --this.indentLevel);
sb.push("}");
}
sb.push("\n");
indent(sb, --this.indentLevel);
sb.push("},\n");
}
this.visitNamespace(name, element);
}
visitEnum(name: string, element: Enum): void {
let sb = this.sb;
this.exports.push(name);
indent(sb, this.indentLevel);
sb.push(name);
sb.push(": (values => (\n");
indent(sb, ++this.indentLevel);
sb.push("// ");
sb.push(element.internalName);
sb.push("\n");
let members = element.members;
if (members) {
for (let _values = Map_values(members), i = 0, k = _values.length; i < k; ++i) {
let value = _values[i];
if (value.kind != ElementKind.EnumValue) continue;
indent(sb, this.indentLevel);
sb.push("values[values.");
sb.push(value.name);
if (value.is(CommonFlags.Inlined)) {
sb.push(" = ");
sb.push(i64_low((<EnumValue>value).constantIntegerValue).toString());
} else {
sb.push(" = exports[\"");
sb.push(escapeString(name + "." + value.name, CharCode.DoubleQuote));
sb.push("\"].valueOf()");
}
sb.push("] = \"");
sb.push(escapeString(value.name, CharCode.DoubleQuote));
sb.push("\",\n");
}
}
indent(sb, this.indentLevel);
sb.push("values\n");
indent(sb, --this.indentLevel);
sb.push("))({}),\n");
this.visitNamespace(name, element);
}
makeGlobalImport(moduleName: string, name: string, element: Global): void {
let sb = this.sb;
let type = element.type;
indent(sb, this.indentLevel);
if (isIdentifier(name)) {
sb.push(name);
} else {
sb.push("\"");
sb.push(escapeString(name, CharCode.DoubleQuote));
sb.push("\": ");
}
let moduleId = this.ensureModuleId(moduleName);
if (isPlainValue(type, Mode.Import)) {
sb.push("(\n");
indent(sb, this.indentLevel + 1);
sb.push("// ");
sb.push(element.internalName);
sb.push(": ");
sb.push(element.type.toString());
sb.push("\n");
indent(sb, this.indentLevel + 1);
if (moduleName != "env") {
sb.push("__module");
sb.push(moduleId.toString());
sb.push(".");
}
sb.push(name);
sb.push("\n");
indent(sb, this.indentLevel);
sb.push(")");
} else {
sb.push("{\n");
indent(sb, ++this.indentLevel);
sb.push("// ");
sb.push(element.internalName);
sb.push(": ");
sb.push(element.type.toString());
sb.push("\n");
indent(sb, this.indentLevel);
sb.push("// not supported: cannot lower before instantiate completes\n");
indent(sb, --this.indentLevel);
sb.push("}");
}
sb.push(",\n");
}
makeFunctionImport(moduleName: string, name: string, element: Function, code: string | null = null): void {
let sb = this.sb;
let signature = element.signature;
indent(sb, this.indentLevel);
if (isIdentifier(name)) {
sb.push(name);
} else {
sb.push("\"");
sb.push(escapeString(name, CharCode.DoubleQuote));
sb.push("\"");
}
if (isPlainFunction(signature, Mode.Import) && !code && isIdentifier(name)) {
sb.push(": (\n");
indent(sb, this.indentLevel + 1);
sb.push("// ");
sb.push(element.internalName);
sb.push(element.signature.toString());
sb.push("\n");
indent(sb, this.indentLevel + 1);
if (moduleName != "env") {
sb.push(moduleName);
sb.push(".");
}
sb.push(name);
sb.push("\n");
indent(sb, this.indentLevel);
sb.push(")");
} else {
sb.push("(");
let parameterTypes = signature.parameterTypes;
let parameterNames = new Array<string>();
for (let i = 0, k = parameterTypes.length; i < k; ++i) {
parameterNames.push(element.getParameterName(i));
}
sb.push(parameterNames.join(", "));
sb.push(") {\n");
indent(sb, ++this.indentLevel);
sb.push("// ");
sb.push(element.internalName);
sb.push(element.signature.toString());
sb.push("\n");
for (let i = 0, k = parameterTypes.length; i < k; ++i) {
let type = parameterTypes[i];
if (!isPlainValue(type, Mode.Export)) {
let name = element.getParameterName(i);
indent(sb, this.indentLevel);
sb.push(name);
sb.push(" = ");
this.makeLiftFromValue(name, type, sb);
sb.push(";\n");
}
}
let expr = new Array<string>();
let moduleId = this.ensureModuleId(moduleName);
if (code) {
expr.push("(() => {\n");
indent(expr, 1);
expr.push("// @external.js\n");
indentText(code, 1, expr);
expr.push("\n})()");
} else {
if (moduleName != "env") {
expr.push("__module");
expr.push(moduleId.toString());
expr.push(".");
}
expr.push(name);
expr.push("(");
expr.push(parameterNames.join(", "));
expr.push(")");
}
code = expr.join("");
expr.length = 0;
indentText(code, this.indentLevel, expr, true);
code = expr.join("");
indent(sb, this.indentLevel);
if (signature.returnType != Type.void) {
sb.push("return ");
this.makeLowerToValue(code, signature.returnType, sb);
sb.push(";\n");
} else {
sb.push(code);
sb.push(";\n");
}
indent(sb, --this.indentLevel);
sb.push("}");
}
sb.push(",\n");
}
visitFunction(name: string, element: Function): void {
if (element.is(CommonFlags.Private)) return;
let sb = this.sb;
let signature = element.signature;
this.exports.push(name);
if (!isPlainFunction(signature, Mode.Export)) {
indent(sb, this.indentLevel);
sb.push(name);
sb.push("(");
let parameterTypes = signature.parameterTypes;
let numReferences = 0;
for (let i = 0, k = parameterTypes.length; i < k; ++i) {
if (parameterTypes[i].isInternalReference) numReferences++;
if (i > 0) sb.push(", ");
sb.push(element.getParameterName(i));
}
sb.push(") {\n");
indent(sb, ++this.indentLevel);
sb.push("// ");
sb.push(element.internalName);
sb.push(signature.toString());
sb.push("\n");
let releases = new Array<string>();
for (let i = 0, k = parameterTypes.length; i < k; ++i) {
let type = parameterTypes[i];
if (!isPlainValue(type, Mode.Import)) {
let name = element.getParameterName(i);
indent(sb, this.indentLevel);
sb.push(name);
sb.push(" = ");
let needsRetainRelease = type.isInternalReference && --numReferences > 0;
if (needsRetainRelease) {
this.needsRetain = true;
this.needsRelease = true;
sb.push("__retain(");
releases.push(name);
}
this.makeLowerToValue(name, type, sb);
if (needsRetainRelease) {
sb.push(")");
}
sb.push(";\n");
}
}
if (releases.length) {
indent(sb, this.indentLevel++);
sb.push("try {\n");
}
if (signature.requiredParameters < parameterTypes.length) {
indent(sb, this.indentLevel);
sb.push("exports.__setArgumentsLength(arguments.length);\n");
}
const expr = new Array<string>();
expr.push("exports.");
expr.push(name);
expr.push("(");
for (let i = 0, k = parameterTypes.length; i < k; ++i) {
if (i > 0) expr.push(", ");
expr.push(element.getParameterName(i));
}
expr.push(")");
if (signature.returnType != Type.void) {
indent(sb, this.indentLevel);
sb.push("return ");
this.makeLiftFromValue(expr.join(""), signature.returnType, sb);
} else {
indent(sb, this.indentLevel);
sb.push(expr.join(""));
}
sb.push(";\n");
if (releases.length) {
indent(sb, this.indentLevel - 1);
sb.push("} finally {\n");
for (let i = 0, k = releases.length; i < k; ++i) {
indent(sb, this.indentLevel);
sb.push("__release(");
sb.push(releases[i]);
sb.push(");\n");
}
indent(sb, --this.indentLevel);
sb.push("}\n");
}
indent(sb, --this.indentLevel);
sb.push("},\n");
}
this.visitNamespace(name, element);
}
visitClass(name: string, element: Class): void {
// not implemented
}
visitInterface(name: string, element: Interface): void {
this.visitClass(name, element);
}
visitNamespace(name: string, element: Element): void {
// not implemented
}
visitAlias(name: string, element: Element, originalName: string): void {
// not implemented
// let sb = this.sb;
// sb.push("export const ");
// sb.push(name);
// sb.push(" = ");
// sb.push(originalName);
// sb.push(";\n");
}
getExternalCode(element: Function): string | null {
let decorator = findDecorator(DecoratorKind.ExternalJs, element.decoratorNodes);
if (decorator) {
let args = decorator.args;
if (args && args.length == 1) {
let codeArg = args[0];
if (codeArg.kind == NodeKind.Literal) {
let literal = <LiteralExpression>codeArg;
if (literal.literalKind == LiteralKind.String) {
return (<StringLiteralExpression>literal).value;
}
if (literal.literalKind == LiteralKind.Template) {
let parts = (<TemplateLiteralExpression>literal).parts;
if (parts.length == 1) {
return parts[0];
}
}
}
}
}
return null;
}
build(): string {
let exports = this.exports;
let moduleImports = this.program.moduleImports;
let program = this.program;
let options = program.options;
let sb = this.sb;
sb.push(""); // placeholder
indent(sb, this.indentLevel++);
if (!this.esm) sb.push("export ");
sb.push("async function instantiate(module, imports = {}) {\n");
const insertPos = sb.push("") - 1;
// Instrument module imports. Keeps raw (JS) imports on the respective
// prototypes and overrides selectively where instrumentation is required.
indent(sb, this.indentLevel++);
sb.push("const adaptedImports = {\n");
let sbLengthBefore = sb.length;
for (let _keys = Map_keys(moduleImports), i = 0, k = _keys.length; i < k; ++i) {
let moduleName = _keys[i];
let moduleId = this.ensureModuleId(moduleName);
let module = <Map<string,Element>>moduleImports.get(moduleName);
indent(sb, this.indentLevel);
if (isIdentifier(moduleName)) {
sb.push(moduleName);
} else {
sb.push("\"");
sb.push(escapeString(moduleName, CharCode.DoubleQuote));
sb.push("\"");
}
if (!shouldInstrument(moduleName)) {
sb.push(": __module");
sb.push(moduleId.toString());
sb.push(",\n");
continue;
}
let resetPos = sb.length;
sb.push(": Object.assign(Object.create(");
if (moduleName == "env") {
sb.push("globalThis");
} else {
sb.push("__module");
sb.push(moduleId.toString());
}
sb.push("), ");
if (moduleName == "env") {
sb.push("imports.env || {}, ");
}
sb.push("{\n");
++this.indentLevel;
let numInstrumented = 0;
for (let _keys2 = Map_keys(module), j = 0, l = _keys2.length; j < l; ++j) {
let name = _keys2[j];
let elem = assert(module.get(name));
if (elem.kind == ElementKind.Function) {
let func = <Function>elem;
let code = this.getExternalCode(func);
if (!isPlainFunction(func.signature, Mode.Import) || !isIdentifier(name) || code) {
this.makeFunctionImport(moduleName, name, <Function>elem, code);
++numInstrumented;
}
} else if (elem.kind == ElementKind.Global) {
let global = <Global>elem;
if (!isPlainValue(global.type, Mode.Import) || !isIdentifier(name)) {
this.makeGlobalImport(moduleName, name, global);
++numInstrumented;
}
}
}
--this.indentLevel;
if (!numInstrumented) {
sb.length = resetPos;
if (moduleName == "env") {
sb.push(": Object.assign(Object.create(globalThis), imports.env || {})");
} else {
sb.push(": __module");
sb.push(moduleId.toString());
}
sb.push(",\n");
} else {
indent(sb, this.indentLevel);
sb.push("}),\n");
}
}
--this.indentLevel;
let hasAdaptedImports = sb.length > sbLengthBefore;
if (hasAdaptedImports) {
indent(sb, this.indentLevel);
sb.push("};\n");
} else {
sb.length = sbLengthBefore - 2; // incl. indent
}
let mappings = this.importMappings;
let map = new Array<string>();
for (let _keys = Map_keys(mappings), i = 0, k = _keys.length; i < k; ++i) {
let moduleName = _keys[i];
if (moduleName == "env") {
map.push(" const env = imports.env;\n");
} else {
let moduleId = <i32>mappings.get(moduleName);
if (moduleName == "rtrace") {
// Rtrace is special in that it needs to be installed on the imports
// object. Use sensible defaults and substitute the original import.
map.push(" ((rtrace) => {\n");
map.push(" delete imports.rtrace;\n");
map.push(" new rtrace.Rtrace({ getMemory() { return memory; }, onerror(err) { console.log(`RTRACE: ${err.stack}`); } }).install(imports);\n");
map.push(" })(imports.rtrace);\n");
}
map.push(" const __module");
map.push(moduleId.toString());
map.push(" = imports");
if (isIdentifier(moduleName)) {
map.push(".");
map.push(moduleName);
} else {
map.push("[\"");
map.push(escapeString(moduleName, CharCode.DoubleQuote));
map.push("\"]");
}
map.push(";\n");
}
}
sb[insertPos] = map.join("");
indent(sb, this.indentLevel);
sb.push("const { exports } = await WebAssembly.instantiate(module");
if (hasAdaptedImports) {
sb.push(", adaptedImports);\n");
} else {
sb.push(", imports);\n");
}
indent(sb, this.indentLevel);
sb.push("const memory = exports.memory || imports.env.memory;\n");
indent(sb, this.indentLevel++);
sb.push("const adaptedExports = Object.setPrototypeOf({\n");
sbLengthBefore = sb.length;
// Instrument module exports. Keeps raw (Wasm) exports on the prototype and
// overrides selectively where instrumentation is required.
this.walk();
--this.indentLevel;
let hasAdaptedExports = sb.length > sbLengthBefore;
if (hasAdaptedExports) {
indent(sb, this.indentLevel);
sb.push("}, exports);\n");
} else {
if (
this.needsLiftBuffer || this.needsLowerBuffer ||
this.needsLiftString || this.needsLowerString ||
this.needsLiftArray || this.needsLowerArray ||
this.needsLiftTypedArray || this.needsLowerTypedArray ||
this.needsLiftStaticArray
) {
sb.length = sbLengthBefore - 2; // skip adaptedExports + 1x indent
} else {
sb.length = sbLengthBefore - 4; // skip memory and adaptedExports + 2x indent
}
}
// Add external JS code fragments
let deferredCode = this.deferredCode;
if (deferredCode.length) {
for (let i = 0, k = deferredCode.length; i < k; ++i) {
sb.push(deferredCode[i]);
}
}
// Add the respective lifting and lowering adapters
if (this.needsLiftBuffer) {
let objectInstance = program.OBJECTInstance;
let rtSizeOffset = objectInstance.offsetof("rtSize") - objectInstance.nextMemoryOffset;
sb.push(` function __liftBuffer(pointer) {
if (!pointer) return null;
return memory.buffer.slice(pointer, pointer + new Uint32Array(memory.buffer)[pointer - ${-rtSizeOffset} >>> 2]);
}
`);
}
if (this.needsLowerBuffer) {
let arrayBufferId = program.arrayBufferInstance.id;
sb.push(` function __lowerBuffer(value) {
if (value == null) return 0;
const pointer = exports.__new(value.byteLength, ${arrayBufferId}) >>> 0;
new Uint8Array(memory.buffer).set(new Uint8Array(value), pointer);
return pointer;
}
`);
}
if (this.needsLiftString) {
let objectInstance = program.OBJECTInstance;
let rtSizeOffset = objectInstance.offsetof("rtSize") - objectInstance.nextMemoryOffset;
let chunkSize = 1024;
sb.push(` function __liftString(pointer) {
if (!pointer) return null;
const
end = pointer + new Uint32Array(memory.buffer)[pointer - ${-rtSizeOffset} >>> 2] >>> 1,
memoryU16 = new Uint16Array(memory.buffer);
let
start = pointer >>> 1,
string = "";
while (end - start > ${chunkSize}) string += String.fromCharCode(...memoryU16.subarray(start, start += ${chunkSize}));
return string + String.fromCharCode(...memoryU16.subarray(start, end));
}
`);
}
if (this.needsLowerString) {
let stringId = program.stringInstance.id;
sb.push(` function __lowerString(value) {
if (value == null) return 0;
const
length = value.length,
pointer = exports.__new(length << 1, ${stringId}) >>> 0,
memoryU16 = new Uint16Array(memory.buffer);
for (let i = 0; i < length; ++i) memoryU16[(pointer >>> 1) + i] = value.charCodeAt(i);
return pointer;
}
`);
}
if (this.needsLiftArray) {
let dataStartOffset = program.arrayBufferViewInstance.offsetof("dataStart");
let lengthOffset = program.arrayBufferViewInstance.nextMemoryOffset;
this.needsGetU32 = true;
sb.push(` function __liftArray(liftElement, align, pointer) {
if (!pointer) return null;
const
dataStart = __getU32(pointer + ${dataStartOffset}),
length = __dataview.getUint32(pointer + ${lengthOffset}, true),
values = new Array(length);
for (let i = 0; i < length; ++i) values[i] = liftElement(dataStart + (i << align >>> 0));
return values;
}
`);
}
if (this.needsLowerArray) {
let arrayBufferId = program.arrayBufferInstance.id;
let arrayBufferViewInstance = program.arrayBufferViewInstance;
let arraySize = arrayBufferViewInstance.nextMemoryOffset + 4; // + length
let bufferOffset = arrayBufferViewInstance.offsetof("buffer");
let dataStartOffset = arrayBufferViewInstance.offsetof("dataStart");
let byteLengthOffset = arrayBufferViewInstance.offsetof("byteLength");
let lengthOffset = byteLengthOffset + 4;
this.needsSetU32 = true;
sb.push(` function __lowerArray(lowerElement, id, align, values) {
if (values == null) return 0;
const
length = values.length,
buffer = exports.__pin(exports.__new(length << align, ${arrayBufferId})) >>> 0,
header = exports.__pin(exports.__new(${arraySize}, id)) >>> 0;
__setU32(header + ${bufferOffset}, buffer);
__dataview.setUint32(header + ${dataStartOffset}, buffer, true);
__dataview.setUint32(header + ${byteLengthOffset}, length << align, true);
__dataview.setUint32(header + ${lengthOffset}, length, true);
for (let i = 0; i < length; ++i) lowerElement(buffer + (i << align >>> 0), values[i]);
exports.__unpin(buffer);
exports.__unpin(header);
return header;
}
`);
}
if (this.needsLiftTypedArray) {
let arrayBufferViewInstance = program.arrayBufferViewInstance;
let dataStartOffset = arrayBufferViewInstance.offsetof("dataStart");
let byteLengthOffset = arrayBufferViewInstance.offsetof("byteLength");
this.needsGetU32 = true;
sb.push(` function __liftTypedArray(constructor, pointer) {
if (!pointer) return null;
return new constructor(
memory.buffer,
__getU32(pointer + ${dataStartOffset}),
__dataview.getUint32(pointer + ${byteLengthOffset}, true) / constructor.BYTES_PER_ELEMENT
).slice();
}
`);
}
if (this.needsLowerTypedArray) {
let arrayBufferId = program.arrayBufferInstance.id;
let arrayBufferViewInstance = program.arrayBufferViewInstance;
let size = arrayBufferViewInstance.nextMemoryOffset;
let bufferOffset = arrayBufferViewInstance.offsetof("buffer");
let dataStartOffset = arrayBufferViewInstance.offsetof("dataStart");
let byteLengthOffset = arrayBufferViewInstance.offsetof("byteLength");
this.needsSetU32 = true;
sb.push(` function __lowerTypedArray(constructor, id, align, values) {
if (values == null) return 0;
const
length = values.length,
buffer = exports.__pin(exports.__new(length << align, ${arrayBufferId})) >>> 0,
header = exports.__new(${size}, id) >>> 0;
__setU32(header + ${bufferOffset}, buffer);
__dataview.setUint32(header + ${dataStartOffset}, buffer, true);
__dataview.setUint32(header + ${byteLengthOffset}, length << align, true);
new constructor(memory.buffer, buffer, length).set(values);
exports.__unpin(buffer);
return header;
}
`);
}
if (this.needsLiftStaticArray) {
let objectInstance = program.OBJECTInstance;
let rtSizeOffset = objectInstance.offsetof("rtSize") - objectInstance.nextMemoryOffset;
this.needsGetU32 = true;
sb.push(` function __liftStaticArray(liftElement, align, pointer) {
if (!pointer) return null;
const
length = __getU32(pointer - ${-rtSizeOffset}) >>> align,
values = new Array(length);
for (let i = 0; i < length; ++i) values[i] = liftElement(pointer + (i << align >>> 0));
return values;
}
`);
}
if (this.needsLowerStaticArray) {
sb.push(` function __lowerStaticArray(lowerElement, id, align, values, typedConstructor) {
if (values == null) return 0;
const
length = values.length,
buffer = exports.__pin(exports.__new(length << align, id)) >>> 0;
if (typedConstructor) {
new typedConstructor(memory.buffer, buffer, length).set(values);
} else {
for (let i = 0; i < length; i++) lowerElement(buffer + (i << align >>> 0), values[i]);
}
exports.__unpin(buffer);
return buffer;
}
`);
}
if (this.needsLiftInternref || this.needsLowerInternref) {
sb.push(" class Internref extends Number {}\n");
}
if (this.needsLiftInternref) {
this.needsRetain = true;
this.needsRelease = true;
sb.push(` const registry = new FinalizationRegistry(__release);
function __liftInternref(pointer) {
if (!pointer) return null;
const sentinel = new Internref(__retain(pointer));
registry.register(sentinel, pointer);
return sentinel;
}
`);
}
if (this.needsLowerInternref) {
sb.push(` function __lowerInternref(value) {
if (value == null) return 0;
if (value instanceof Internref) return value.valueOf();
throw TypeError("internref expected");
}
`);
}
if (this.needsRetain || this.needsRelease) {
sb.push(` const refcounts = new Map();
`);
}
if (this.needsRetain) {
sb.push(` function __retain(pointer) {
if (pointer) {
const refcount = refcounts.get(pointer);
if (refcount) refcounts.set(pointer, refcount + 1);
else refcounts.set(exports.__pin(pointer), 1);
}
return pointer;
}
`);
}
if (this.needsRelease) {
sb.push(` function __release(pointer) {
if (pointer) {
const refcount = refcounts.get(pointer);
if (refcount === 1) exports.__unpin(pointer), refcounts.delete(pointer);
else if (refcount) refcounts.set(pointer, refcount - 1);
else throw Error(\`invalid refcount '\${refcount}' for reference '\${pointer}'\`);
}
}
`);
}
if (this.needsNotNull) {
sb.push(` function __notnull() {
throw TypeError("value must not be null");
}
`);
}
if (
this.needsSetU8 ||
this.needsSetU16 ||
this.needsSetU32 ||
this.needsSetU64 ||
this.needsSetF32 ||
this.needsSetF64 ||
this.needsGetI8 ||
this.needsGetU8 ||
this.needsGetI16 ||
this.needsGetU16 ||
this.needsGetI32 ||
this.needsGetU32 ||
this.needsGetI64 ||
this.needsGetU64 ||
this.needsGetF32 ||
this.needsGetF64
) {
sb.push(" let __dataview = new DataView(memory.buffer);\n");
}
if (this.needsSetU8) sb.push(makeCheckedSetter("U8", "setUint8"));
if (this.needsSetU16) sb.push(makeCheckedSetter("U16", "setUint16"));
if (this.needsSetU32) sb.push(makeCheckedSetter("U32", "setUint32"));
if (this.needsSetU64) sb.push(makeCheckedSetter("U64", "setBigUint64"));
if (this.needsSetF32) sb.push(makeCheckedSetter("F32", "setFloat32"));
if (this.needsSetF64) sb.push(makeCheckedSetter("F64", "setFloat64"));
if (this.needsGetI8) sb.push(makeCheckedGetter("I8", "getInt8"));
if (this.needsGetU8) sb.push(makeCheckedGetter("U8", "getUint8"));
if (this.needsGetI16) sb.push(makeCheckedGetter("I16", "getInt16"));
if (this.needsGetU16) sb.push(makeCheckedGetter("U16", "getUint16"));
if (this.needsGetI32) sb.push(makeCheckedGetter("I32", "getInt32"));
if (this.needsGetU32) sb.push(makeCheckedGetter("U32", "getUint32"));
if (this.needsGetI64) sb.push(makeCheckedGetter("I64", "getBigInt64"));
if (this.needsGetU64) sb.push(makeCheckedGetter("U64", "getBigUint64"));
if (this.needsGetF32) sb.push(makeCheckedGetter("F32", "getFloat32"));
if (this.needsGetF64) sb.push(makeCheckedGetter("F64", "getFloat64"));
let exportStart = options.exportStart;
if (exportStart) {
sb.push(` exports.${exportStart}();\n`);
}
if (hasAdaptedExports) {
sb.push(" return adaptedExports;\n}\n");
} else {
sb.push(" return exports;\n}\n");
}
--this.indentLevel;
assert(this.indentLevel == 0);
if (this.esm) {
sb.push("export const {\n");
if (this.program.options.exportMemory) {
sb.push(" memory,\n");
}
if (this.program.options.exportTable) {
sb.push(" table,\n");
}
if (this.program.options.exportRuntime) {
for (let i = 0, k = runtimeFunctions.length; i < k; ++i) {
sb.push(" ");
sb.push(runtimeFunctions[i]);
sb.push(",\n");
}
for (let i = 0, k = runtimeGlobals.length; i < k; ++i) {
sb.push(" ");
sb.push(runtimeGlobals[i]);
sb.push(",\n");
}
}
for (let i = 0, k = exports.length; i < k; ++i) {
sb.push(" ");
sb.push(exports[i]);
sb.push(",\n");
}
sb.push(`} = await (async url => instantiate(
await (async () => {
try { return await globalThis.WebAssembly.compileStreaming(globalThis.fetch(url)); }
catch { return globalThis.WebAssembly.compile(await (await import("node:fs/promises")).readFile(url)); }
})(), {
`);
let needsMaybeDefault = false;
let importExpr = new Array<string>();
for (let _keys = Map_keys(mappings), i = 0, k = _keys.length; i < k; ++i) {
let moduleName = _keys[i];
if (moduleName == "env") {
indent(sb, 2);
sb.push("env: globalThis,\n");
} else {
let moduleId = this.ensureModuleId(moduleName);
indent(sb, 2);
if (isIdentifier(moduleName)) {
sb.push(moduleName);
} else {
sb.push("\"");
sb.push(escapeString(moduleName, CharCode.DoubleQuote));
sb.push("\"");
}
sb.push(": __maybeDefault(__import");