forked from swiftwasm/JavaScriptKit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
426 lines (393 loc) · 15.3 KB
/
index.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
interface ExportedMemory {
buffer: any
}
type ref = number;
type pointer = number;
interface GlobalVariable { }
declare const window: GlobalVariable;
declare const global: GlobalVariable;
let globalVariable: any;
if (typeof globalThis !== "undefined") {
globalVariable = globalThis
} else if (typeof window !== "undefined") {
globalVariable = window
} else if (typeof global !== "undefined") {
globalVariable = global
} else if (typeof self !== "undefined") {
globalVariable = self
}
interface SwiftRuntimeExportedFunctions {
swjs_library_version(): number;
swjs_prepare_host_function_call(size: number): pointer;
swjs_cleanup_host_function_call(argv: pointer): void;
swjs_call_host_function(
host_func_id: number,
argv: pointer, argc: number,
callback_func_ref: ref
): void;
}
enum JavaScriptValueKind {
Invalid = -1,
Boolean = 0,
String = 1,
Number = 2,
Object = 3,
Null = 4,
Undefined = 5,
Function = 6,
}
enum JavaScriptTypedArrayKind {
Int8 = 0,
Uint8 = 1,
Int16 = 2,
Uint16 = 3,
Int32 = 4,
Uint32 = 5,
BigInt64 = 6,
BigUint64 = 7,
Float32 = 8,
Float64 = 9,
}
type TypedArray =
| Int8ArrayConstructor
| Uint8ArrayConstructor
| Int16ArrayConstructor
| Uint16ArrayConstructor
| Int32ArrayConstructor
| Uint32ArrayConstructor
// | BigInt64ArrayConstructor
// | BigUint64ArrayConstructor
| Float32ArrayConstructor
| Float64ArrayConstructor
type SwiftRuntimeHeapEntry = {
id: number,
rc: number,
}
class SwiftRuntimeHeap {
private _heapValueById: Map<number, any>;
private _heapEntryByValue: Map<any, SwiftRuntimeHeapEntry>;
private _heapNextKey: number;
constructor() {
this._heapValueById = new Map();
this._heapValueById.set(0, globalVariable);
this._heapEntryByValue = new Map();
this._heapEntryByValue.set(globalVariable, { id: 0, rc: 1 });
// Note: 0 is preserved for global
this._heapNextKey = 1;
}
retain(value: any) {
const isObject = typeof value == "object";
const entry = this._heapEntryByValue.get(value);
if (isObject && entry) {
entry.rc++
return entry.id
}
const id = this._heapNextKey++;
this._heapValueById.set(id, value)
if (isObject) {
this._heapEntryByValue.set(value, { id: id, rc: 1 })
}
return id
}
release(ref: ref) {
const value = this._heapValueById.get(ref);
const isObject = typeof value == "object"
if (isObject) {
const entry = this._heapEntryByValue.get(value)!;
entry.rc--;
if (entry.rc != 0) return;
this._heapEntryByValue.delete(value);
this._heapValueById.delete(ref)
} else {
this._heapValueById.delete(ref)
}
}
referenceHeap(ref: ref) {
const value = this._heapValueById.get(ref)
if (value === undefined) {
throw new ReferenceError("Attempted to read invalid reference " + ref)
}
return value
}
}
export class SwiftRuntime {
private instance: WebAssembly.Instance | null;
private heap: SwiftRuntimeHeap
private version: number = 400
constructor() {
this.instance = null;
this.heap = new SwiftRuntimeHeap();
}
setInstance(instance: WebAssembly.Instance) {
this.instance = instance
const exports = this.instance.exports as any as SwiftRuntimeExportedFunctions;
if (exports.swjs_library_version() != this.version) {
throw new Error("The versions of JavaScriptKit are incompatible.")
}
}
importObjects() {
const memory = () => {
if (this.instance)
return this.instance.exports.memory as ExportedMemory;
throw new Error("WebAssembly instance is not set yet");
}
const callHostFunction = (host_func_id: number, args: any[]) => {
if (!this.instance)
throw new Error("WebAssembly instance is not set yet");
const exports = this.instance.exports as any as SwiftRuntimeExportedFunctions;
const argc = args.length
const argv = exports.swjs_prepare_host_function_call(argc)
for (let index = 0; index < args.length; index++) {
const argument = args[index]
const base = argv + 24 * index
writeValue(argument, base, base + 4, base + 8, base + 16)
}
let output: any;
const callback_func_ref = this.heap.retain(function (result: any) {
output = result
})
exports.swjs_call_host_function(host_func_id, argv, argc, callback_func_ref)
exports.swjs_cleanup_host_function_call(argv)
return output
}
const textDecoder = new TextDecoder('utf-8');
const textEncoder = new TextEncoder(); // Only support utf-8
const readString = (ptr: pointer, len: number) => {
const uint8Memory = new Uint8Array(memory().buffer);
return textDecoder.decode(uint8Memory.subarray(ptr, ptr + len));
}
const writeString = (ptr: pointer, bytes: Uint8Array) => {
const uint8Memory = new Uint8Array(memory().buffer);
for (const [index, byte] of bytes.entries()) {
uint8Memory[ptr + index] = byte
}
uint8Memory[ptr]
}
const readUInt32 = (ptr: pointer) => {
const uint8Memory = new Uint8Array(memory().buffer);
return uint8Memory[ptr + 0]
+ (uint8Memory[ptr + 1] << 8)
+ (uint8Memory[ptr + 2] << 16)
+ (uint8Memory[ptr + 3] << 24)
}
const readFloat64 = (ptr: pointer) => {
const dataView = new DataView(memory().buffer);
return dataView.getFloat64(ptr, true);
}
const writeUint32 = (ptr: pointer, value: number) => {
const uint8Memory = new Uint8Array(memory().buffer);
uint8Memory[ptr + 0] = (value & 0x000000ff) >> 0
uint8Memory[ptr + 1] = (value & 0x0000ff00) >> 8
uint8Memory[ptr + 2] = (value & 0x00ff0000) >> 16
uint8Memory[ptr + 3] = (value & 0xff000000) >> 24
}
const writeFloat64 = (ptr: pointer, value: number) => {
const dataView = new DataView(memory().buffer);
dataView.setFloat64(ptr, value, true);
}
const decodeValue = (
kind: JavaScriptValueKind,
payload1: number, payload2: number, payload3: number
) => {
switch (kind) {
case JavaScriptValueKind.Boolean: {
switch (payload1) {
case 0: return false
case 1: return true
}
}
case JavaScriptValueKind.Number: {
return payload3;
}
case JavaScriptValueKind.String: {
return readString(payload1, payload2)
}
case JavaScriptValueKind.Object: {
return this.heap.referenceHeap(payload1)
}
case JavaScriptValueKind.Null: {
return null
}
case JavaScriptValueKind.Undefined: {
return undefined
}
case JavaScriptValueKind.Function: {
return this.heap.referenceHeap(payload1)
}
default:
throw new Error(`Type kind "${kind}" is not supported`)
}
}
const writeValue = (
value: any, kind_ptr: pointer,
payload1_ptr: pointer, payload2_ptr: pointer, payload3_ptr: pointer
) => {
if (value === null) {
writeUint32(kind_ptr, JavaScriptValueKind.Null);
writeUint32(payload1_ptr, 0);
writeUint32(payload2_ptr, 0);
return;
}
switch (typeof value) {
case "boolean": {
writeUint32(kind_ptr, JavaScriptValueKind.Boolean);
writeUint32(payload1_ptr, value ? 1 : 0);
writeUint32(payload2_ptr, 0);
break;
}
case "number": {
writeUint32(kind_ptr, JavaScriptValueKind.Number);
writeUint32(payload1_ptr, 0);
writeUint32(payload2_ptr, 0);
writeFloat64(payload3_ptr, value);
break;
}
case "string": {
const bytes = textEncoder.encode(value);
writeUint32(kind_ptr, JavaScriptValueKind.String);
writeUint32(payload1_ptr, this.heap.retain(bytes));
writeUint32(payload2_ptr, bytes.length);
break;
}
case "undefined": {
writeUint32(kind_ptr, JavaScriptValueKind.Undefined);
writeUint32(payload1_ptr, 0);
writeUint32(payload2_ptr, 0);
break;
}
case "object": {
writeUint32(kind_ptr, JavaScriptValueKind.Object);
writeUint32(payload1_ptr, this.heap.retain(value));
writeUint32(payload2_ptr, 0);
break;
}
case "function": {
writeUint32(kind_ptr, JavaScriptValueKind.Function);
writeUint32(payload1_ptr, this.heap.retain(value));
writeUint32(payload2_ptr, 0);
break;
}
default:
throw new Error(`Type "${typeof value}" is not supported yet`)
}
}
// Note:
// `decodeValues` assumes that the size of RawJSValue is 24
// and the alignment of it is 8
const decodeValues = (ptr: pointer, length: number) => {
let result = []
for (let index = 0; index < length; index++) {
const base = ptr + 24 * index
const kind = readUInt32(base)
const payload1 = readUInt32(base + 4)
const payload2 = readUInt32(base + 8)
const payload3 = readFloat64(base + 16)
result.push(decodeValue(kind, payload1, payload2, payload3))
}
return result
}
return {
swjs_set_prop: (
ref: ref, name: pointer, length: number,
kind: JavaScriptValueKind,
payload1: number, payload2: number, payload3: number
) => {
const obj = this.heap.referenceHeap(ref);
Reflect.set(obj, readString(name, length), decodeValue(kind, payload1, payload2, payload3))
},
swjs_get_prop: (
ref: ref, name: pointer, length: number,
kind_ptr: pointer,
payload1_ptr: pointer, payload2_ptr: pointer, payload3_ptr: number
) => {
const obj = this.heap.referenceHeap(ref);
const result = Reflect.get(obj, readString(name, length));
writeValue(result, kind_ptr, payload1_ptr, payload2_ptr, payload3_ptr);
},
swjs_set_subscript: (
ref: ref, index: number,
kind: JavaScriptValueKind,
payload1: number, payload2: number, payload3: number
) => {
const obj = this.heap.referenceHeap(ref);
Reflect.set(obj, index, decodeValue(kind, payload1, payload2, payload3))
},
swjs_get_subscript: (
ref: ref, index: number,
kind_ptr: pointer,
payload1_ptr: pointer, payload2_ptr: pointer, payload3_ptr: pointer
) => {
const obj = this.heap.referenceHeap(ref);
const result = Reflect.get(obj, index);
writeValue(result, kind_ptr, payload1_ptr, payload2_ptr, payload3_ptr);
},
swjs_load_string: (ref: ref, buffer: pointer) => {
const bytes = this.heap.referenceHeap(ref);
writeString(buffer, bytes);
},
swjs_call_function: (
ref: ref, argv: pointer, argc: number,
kind_ptr: pointer,
payload1_ptr: pointer, payload2_ptr: pointer, payload3_ptr: pointer
) => {
const func = this.heap.referenceHeap(ref)
const result = Reflect.apply(func, undefined, decodeValues(argv, argc))
writeValue(result, kind_ptr, payload1_ptr, payload2_ptr, payload3_ptr);
},
swjs_call_function_with_this: (
obj_ref: ref, func_ref: ref,
argv: pointer, argc: number,
kind_ptr: pointer,
payload1_ptr: pointer, payload2_ptr: pointer, payload3_ptr: pointer
) => {
const obj = this.heap.referenceHeap(obj_ref)
const func = this.heap.referenceHeap(func_ref)
const result = Reflect.apply(func, obj, decodeValues(argv, argc))
writeValue(result, kind_ptr, payload1_ptr, payload2_ptr, payload3_ptr);
},
swjs_create_function: (
host_func_id: number,
func_ref_ptr: pointer,
) => {
const func_ref = this.heap.retain(function () {
return callHostFunction(host_func_id, Array.prototype.slice.call(arguments))
})
writeUint32(func_ref_ptr, func_ref)
},
swjs_call_new: (
ref: ref, argv: pointer, argc: number,
result_obj: pointer
) => {
const obj = this.heap.referenceHeap(ref)
const result = Reflect.construct(obj, decodeValues(argv, argc))
if (typeof result != "object")
throw Error(`Invalid result type of object constructor of "${obj}": "${result}"`)
writeUint32(result_obj, this.heap.retain(result));
},
swjs_instanceof: (
obj_ref: ref, constructor_ref: ref,
result_ptr: pointer
) => {
const obj = this.heap.referenceHeap(obj_ref)
const constructor = this.heap.referenceHeap(constructor_ref)
return obj instanceof constructor
},
swjs_create_typed_array: (
kind: JavaScriptTypedArrayKind,
elementsPtr: pointer, length: number,
result_obj: pointer
) => {
const ArrayType: TypedArray = globalVariable[JavaScriptTypedArrayKind[kind] + 'Array']
const array = new ArrayType(memory().buffer, elementsPtr, length);
// Call `.slice()` to copy the memory
writeUint32(result_obj, this.heap.retain(array.slice()));
},
swjs_retain: (ref: ref) => {
this.heap.retain(this.heap.referenceHeap(ref))
},
swjs_release: (ref: ref) => {
this.heap.release(ref)
}
}
}
}