forked from tanishiking/scala-wasm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLoaderContent.scala
325 lines (302 loc) · 10.8 KB
/
LoaderContent.scala
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
package wasm.ir2wasm
import java.nio.charset.StandardCharsets
import EmbeddedConstants._
/** Contents of the `__loader.js` file that we emit in every output. */
object LoaderContent {
val bytesContent: Array[Byte] =
stringContent.getBytes(StandardCharsets.UTF_8)
private def stringContent: String = {
raw"""
// This implementation follows no particular specification, but is the same as the JS backend.
// It happens to coincide with java.lang.Long.hashCode() for common values.
function bigintHashCode(x) {
var res = 0;
if (x < 0n)
x = ~x;
while (x !== 0n) {
res ^= Number(BigInt.asIntN(32, x));
x >>= 32n;
}
return res;
}
// JSSuperSelect support -- directly copied from the output of the JS backend
function resolveSuperRef(superClass, propName) {
var getPrototypeOf = Object.getPrototyeOf;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var superProto = superClass.prototype;
while (superProto !== null) {
var desc = getOwnPropertyDescriptor(superProto, propName);
if (desc !== (void 0)) {
return desc;
}
superProto = getPrototypeOf(superProto);
}
}
function superGet(superClass, self, propName) {
var desc = resolveSuperRef(superClass, propName);
if (desc !== (void 0)) {
var getter = desc.get;
return getter !== (void 0) ? getter.call(self) : getter.value;
}
}
function superSet(superClass, self, propName, value) {
var desc = resolveSuperRef(superClass, propName);
if (desc !== (void 0)) {
var setter = desc.set;
if (setter !== (void 0)) {
setter.call(self, value);
return;
}
}
throw new TypeError("super has no setter '" + propName + "'.");
}
const linkingInfo = Object.freeze({
"esVersion": 6,
"assumingES6": true,
"productionMode": false,
"linkerVersion": "1.15.0",
"fileLevelThis": this
});
const scalaJSHelpers = {
// JSTag
JSTag: WebAssembly.JSTag,
// BinaryOp.===
is: Object.is,
// undefined
undef: () => void 0,
isUndef: (x) => x === (void 0),
// Boxes (upcast) -- most are identity at the JS level but with different types in Wasm
bZ: (x) => x !== 0,
bB: (x) => x,
bS: (x) => x,
bI: (x) => x,
bF: (x) => x,
bD: (x) => x,
// Unboxes (downcast, null is converted to the zero of the type)
uZ: (x) => x | 0,
uB: (x) => (x << 24) >> 24,
uS: (x) => (x << 16) >> 16,
uI: (x) => x | 0,
uF: (x) => Math.fround(x),
uD: (x) => +x,
// Unboxes to primitive or null (downcast to the boxed classes)
uNZ: (x) => (x !== null) ? (x | 0) : null,
uNB: (x) => (x !== null) ? ((x << 24) >> 24) : null,
uNS: (x) => (x !== null) ? ((x << 16) >> 16) : null,
uNI: (x) => (x !== null) ? (x | 0) : null,
uNF: (x) => (x !== null) ? Math.fround(x) : null,
uND: (x) => (x !== null) ? +x : null,
// Type tests
tZ: (x) => typeof x === 'boolean',
tB: (x) => typeof x === 'number' && Object.is((x << 24) >> 24, x),
tS: (x) => typeof x === 'number' && Object.is((x << 16) >> 16, x),
tI: (x) => typeof x === 'number' && Object.is(x | 0, x),
tF: (x) => typeof x === 'number' && (Math.fround(x) === x || x !== x),
tD: (x) => typeof x === 'number',
// fmod, to implement Float_% and Double_% (it is apparently quite hard to implement fmod otherwise)
fmod: (x, y) => x % y,
// Closure
closure: (f, data) => f.bind(void 0, data),
closureThis: (f, data) => function(...args) { return f(data, this, ...args); },
closureRest: (f, data, n) => ((...args) => f(data, ...args.slice(0, n), args.slice(n))),
closureThisRest: (f, data, n) => function(...args) { return f(data, this, ...args.slice(0, n), args.slice(n)); },
closureRestNoData: (f, n) => ((...args) => f(...args.slice(0, n), args.slice(n))),
// Strings
emptyString: () => "",
stringLength: (s) => s.length,
stringCharAt: (s, i) => s.charCodeAt(i),
jsValueToString: (x) => (x === void 0) ? "undefined" : x.toString(),
jsValueToStringForConcat: (x) => "" + x,
booleanToString: (b) => b ? "true" : "false",
charToString: (c) => String.fromCharCode(c),
intToString: (i) => "" + i,
longToString: (l) => "" + l, // l must be a bigint here
doubleToString: (d) => "" + d,
stringConcat: (x, y) => ("" + x) + y, // the added "" is for the case where x === y === null
isString: (x) => typeof x === 'string',
// Get the type of JS value of `x` in a single JS helper call, for the purpose of dispatch.
jsValueType: (x) => {
if (typeof x === 'number')
return $JSValueTypeNumber;
if (typeof x === 'string')
return $JSValueTypeString;
if (typeof x === 'boolean')
return x | 0; // JSValueTypeFalse or JSValueTypeTrue
if (typeof x === 'undefined')
return $JSValueTypeUndefined;
if (typeof x === 'bigint')
return $JSValueTypeBigInt;
if (typeof x === 'symbol')
return $JSValueTypeSymbol;
return $JSValueTypeOther;
},
// Identity hash code
bigintHashCode: bigintHashCode,
symbolDescription: (x) => {
var desc = x.description;
return (desc === void 0) ? null : desc;
},
idHashCodeGet: (map, obj) => map.get(obj) | 0, // undefined becomes 0
idHashCodeSet: (map, obj, value) => map.set(obj, value),
// JS interop
jsGlobalRefGet: (globalRefName) => (new Function("return " + globalRefName))(),
jsGlobalRefSet: (globalRefName, v) => {
var argName = globalRefName === 'v' ? 'w' : 'v';
(new Function(argName, globalRefName + " = " + argName))(v);
},
jsGlobalRefTypeof: (globalRefName) => (new Function("return typeof " + globalRefName))(),
jsNewArray: () => [],
jsArrayPush: (a, v) => (a.push(v), a),
jsArraySpreadPush: (a, vs) => (a.push(...vs), a),
jsNewObject: () => ({}),
jsObjectPush: (o, p, v) => (o[p] = v, o),
jsSelect: (o, p) => o[p],
jsSelectSet: (o, p, v) => o[p] = v,
jsNew: (constr, args) => new constr(...args),
jsFunctionApply: (f, args) => f(...args),
jsMethodApply: (o, m, args) => o[m](...args),
jsImportCall: (s) => import(s),
jsImportMeta: () => import.meta,
jsDelete: (o, p) => { delete o[p]; },
jsForInSimple: (o, f) => { for (var k in o) f(k); },
jsIsTruthy: (x) => !!x,
jsLinkingInfo: () => linkingInfo,
// Excruciating list of all the JS operators
jsUnaryPlus: (a) => +a,
jsUnaryMinus: (a) => -a,
jsUnaryTilde: (a) => ~a,
jsUnaryBang: (a) => !a,
jsUnaryTypeof: (a) => typeof a,
jsStrictEquals: (a, b) => a === b,
jsNotStrictEquals: (a, b) => a !== b,
jsPlus: (a, b) => a + b,
jsMinus: (a, b) => a - b,
jsTimes: (a, b) => a * b,
jsDivide: (a, b) => a / b,
jsModulus: (a, b) => a % b,
jsBinaryOr: (a, b) => a | b,
jsBinaryAnd: (a, b) => a & b,
jsBinaryXor: (a, b) => a ^ b,
jsShiftLeft: (a, b) => a << b,
jsArithmeticShiftRight: (a, b) => a >> b,
jsLogicalShiftRight: (a, b) => a >>> b,
jsLessThan: (a, b) => a < b,
jsLessEqual: (a, b) => a <= b,
jsGreaterThan: (a, b) => a > b,
jsGreaterEqual: (a, b) => a >= b,
jsIn: (a, b) => a in b,
jsInstanceof: (a, b) => a instanceof b,
jsExponent: (a, b) => a ** b,
// Non-native JS class support
newSymbol: Symbol,
createJSClass: (data, superClass, preSuperStats, superArgs, postSuperStats) => {
return class extends superClass {
constructor(...args) {
var preSuperEnv = preSuperStats(data, new.target, ...args);
super(...superArgs(data, preSuperEnv, new.target, ...args));
postSuperStats(data, preSuperEnv, new.target, this, ...args);
}
};
},
createJSClassRest: (data, superClass, preSuperStats, superArgs, postSuperStats, n) => {
return class extends superClass {
constructor(...args) {
var fixedArgs = args.slice(0, n);
var restArg = args.slice(n);
var preSuperEnv = preSuperStats(data, new.target, ...fixedArgs, restArg);
super(...superArgs(data, preSuperEnv, new.target, ...fixedArgs, restArg));
postSuperStats(data, preSuperEnv, new.target, this, ...fixedArgs, restArg);
}
};
},
installJSField: (instance, name, value) => {
Object.defineProperty(instance, name, {
value: value,
configurable: true,
enumerable: true,
writable: true,
});
},
installJSMethod: (data, jsClass, name, func, fixedArgCount) => {
var closure = fixedArgCount < 0
? (function(...args) { return func(data, this, ...args); })
: (function(...args) { return func(data, this, ...args.slice(0, fixedArgCount), args.slice(fixedArgCount))});
jsClass.prototype[name] = closure;
},
installJSStaticMethod: (data, jsClass, name, func, fixedArgCount) => {
var closure = fixedArgCount < 0
? (function(...args) { return func(data, ...args); })
: (function(...args) { return func(data, ...args.slice(0, fixedArgCount), args.slice(fixedArgCount))});
jsClass[name] = closure;
},
installJSProperty: (data, jsClass, name, getter, setter) => {
var getterClosure = getter
? (function() { return getter(data, this) })
: (void 0);
var setterClosure = setter
? (function(arg) { setter(data, this, arg) })
: (void 0);
Object.defineProperty(jsClass.prototype, name, {
get: getterClosure,
set: setterClosure,
configurable: true,
});
},
installJSStaticProperty: (data, jsClass, name, getter, setter) => {
var getterClosure = getter
? (function() { return getter(data) })
: (void 0);
var setterClosure = setter
? (function(arg) { setter(data, arg) })
: (void 0);
Object.defineProperty(jsClass, name, {
get: getterClosure,
set: setterClosure,
configurable: true,
});
},
jsSuperGet: superGet,
jsSuperSet: superSet,
jsSuperCall: (superClass, receiver, method, args) => {
return superClass.prototype[method].apply(receiver, args);
},
}
export async function load(wasmFileURL, importedModules) {
const myScalaJSHelpers = { ...scalaJSHelpers, idHashCodeMap: new WeakMap() };
const importsObj = {
"__scalaJSHelpers": myScalaJSHelpers,
"__scalaJSImports": importedModules,
};
const resolvedURL = new URL(wasmFileURL, import.meta.url);
var wasmModulePromise;
if (resolvedURL.protocol === 'file:') {
const wasmPath = import("node:url").then((url) => url.fileURLToPath(resolvedURL))
wasmModulePromise = import("node:fs").then((fs) => {
return wasmPath.then((path) => {
return WebAssembly.instantiate(fs.readFileSync(path), importsObj);
});
});
} else {
wasmModulePromise = WebAssembly.instantiateStreaming(fetch(resolvedURL), importsObj);
}
const wasmModule = await wasmModulePromise;
const exports = wasmModule.instance.exports;
const userExports = Object.create(null);
for (const exportName of Object.getOwnPropertyNames(exports)) {
const exportValue = exports[exportName];
if (exportValue instanceof WebAssembly.Global) {
Object.defineProperty(userExports, exportName, {
configurable: true,
enumerable: true,
get: () => exportValue.value,
});
} else {
userExports[exportName] = exportValue;
}
}
Object.freeze(userExports);
return userExports;
}
"""
}
}