@ruby/head-wasm-wasi 2.3.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js DELETED
@@ -1,1195 +0,0 @@
1
- console.warn(`DEPRECATED(ruby-head-wasm-wasi): "index.cjs.js" will be moved to "@ruby/wasm-wasi" in the next major release.
2
- Please replace your \`require('ruby-head-wasm-wasi/dist/index.cjs.js');\` with \`require('@ruby/wasm-wasi/dist/index.cjs.js');\``);
3
-
4
- 'use strict';
5
-
6
- let DATA_VIEW = new DataView(new ArrayBuffer());
7
-
8
- function data_view(mem) {
9
- if (DATA_VIEW.buffer !== mem.buffer) DATA_VIEW = new DataView(mem.buffer);
10
- return DATA_VIEW;
11
- }
12
-
13
- function to_uint32(val) {
14
- return val >>> 0;
15
- }
16
- const UTF8_DECODER = new TextDecoder('utf-8');
17
-
18
- const UTF8_ENCODER = new TextEncoder('utf-8');
19
-
20
- function utf8_encode(s, realloc, memory) {
21
- if (typeof s !== 'string') throw new TypeError('expected a string');
22
-
23
- if (s.length === 0) {
24
- UTF8_ENCODED_LEN = 0;
25
- return 1;
26
- }
27
-
28
- let alloc_len = 0;
29
- let ptr = 0;
30
- let writtenTotal = 0;
31
- while (s.length > 0) {
32
- ptr = realloc(ptr, alloc_len, 1, alloc_len + s.length);
33
- alloc_len += s.length;
34
- const { read, written } = UTF8_ENCODER.encodeInto(
35
- s,
36
- new Uint8Array(memory.buffer, ptr + writtenTotal, alloc_len - writtenTotal),
37
- );
38
- writtenTotal += written;
39
- s = s.slice(read);
40
- }
41
- if (alloc_len > writtenTotal)
42
- ptr = realloc(ptr, alloc_len, 1, writtenTotal);
43
- UTF8_ENCODED_LEN = writtenTotal;
44
- return ptr;
45
- }
46
- let UTF8_ENCODED_LEN = 0;
47
-
48
- class Slab {
49
- constructor() {
50
- this.list = [];
51
- this.head = 0;
52
- }
53
-
54
- insert(val) {
55
- if (this.head >= this.list.length) {
56
- this.list.push({
57
- next: this.list.length + 1,
58
- val: undefined,
59
- });
60
- }
61
- const ret = this.head;
62
- const slot = this.list[ret];
63
- this.head = slot.next;
64
- slot.next = -1;
65
- slot.val = val;
66
- return ret;
67
- }
68
-
69
- get(idx) {
70
- if (idx >= this.list.length)
71
- throw new RangeError('handle index not valid');
72
- const slot = this.list[idx];
73
- if (slot.next === -1)
74
- return slot.val;
75
- throw new RangeError('handle index not valid');
76
- }
77
-
78
- remove(idx) {
79
- const ret = this.get(idx); // validate the slot
80
- const slot = this.list[idx];
81
- slot.val = undefined;
82
- slot.next = this.head;
83
- this.head = idx;
84
- return ret;
85
- }
86
- }
87
-
88
- function throw_invalid_bool() {
89
- throw new RangeError("invalid variant discriminant for bool");
90
- }
91
-
92
- class RbAbiGuest {
93
- constructor() {
94
- this._resource0_slab = new Slab();
95
- this._resource1_slab = new Slab();
96
- }
97
- addToImports(imports) {
98
- if (!("canonical_abi" in imports)) imports["canonical_abi"] = {};
99
-
100
- imports.canonical_abi['resource_drop_rb-iseq'] = i => {
101
- this._resource0_slab.remove(i).drop();
102
- };
103
- imports.canonical_abi['resource_clone_rb-iseq'] = i => {
104
- const obj = this._resource0_slab.get(i);
105
- return this._resource0_slab.insert(obj.clone())
106
- };
107
- imports.canonical_abi['resource_get_rb-iseq'] = i => {
108
- return this._resource0_slab.get(i)._wasm_val;
109
- };
110
- imports.canonical_abi['resource_new_rb-iseq'] = i => {
111
- this._registry0;
112
- return this._resource0_slab.insert(new RbIseq(i, this));
113
- };
114
-
115
- imports.canonical_abi['resource_drop_rb-abi-value'] = i => {
116
- this._resource1_slab.remove(i).drop();
117
- };
118
- imports.canonical_abi['resource_clone_rb-abi-value'] = i => {
119
- const obj = this._resource1_slab.get(i);
120
- return this._resource1_slab.insert(obj.clone())
121
- };
122
- imports.canonical_abi['resource_get_rb-abi-value'] = i => {
123
- return this._resource1_slab.get(i)._wasm_val;
124
- };
125
- imports.canonical_abi['resource_new_rb-abi-value'] = i => {
126
- this._registry1;
127
- return this._resource1_slab.insert(new RbAbiValue(i, this));
128
- };
129
- }
130
-
131
- async instantiate(module, imports) {
132
- imports = imports || {};
133
- this.addToImports(imports);
134
-
135
- if (module instanceof WebAssembly.Instance) {
136
- this.instance = module;
137
- } else if (module instanceof WebAssembly.Module) {
138
- this.instance = await WebAssembly.instantiate(module, imports);
139
- } else if (module instanceof ArrayBuffer || module instanceof Uint8Array) {
140
- const { instance } = await WebAssembly.instantiate(module, imports);
141
- this.instance = instance;
142
- } else {
143
- const { instance } = await WebAssembly.instantiateStreaming(module, imports);
144
- this.instance = instance;
145
- }
146
- this._exports = this.instance.exports;
147
- this._registry0 = new FinalizationRegistry(this._exports['canonical_abi_drop_rb-iseq']);
148
- this._registry1 = new FinalizationRegistry(this._exports['canonical_abi_drop_rb-abi-value']);
149
- }
150
- rubyShowVersion() {
151
- this._exports['ruby-show-version: func() -> ()']();
152
- }
153
- rubyInit() {
154
- this._exports['ruby-init: func() -> ()']();
155
- }
156
- rubySysinit(arg0) {
157
- const memory = this._exports.memory;
158
- const realloc = this._exports["cabi_realloc"];
159
- const vec1 = arg0;
160
- const len1 = vec1.length;
161
- const result1 = realloc(0, 0, 4, len1 * 8);
162
- for (let i = 0; i < vec1.length; i++) {
163
- const e = vec1[i];
164
- const base = result1 + i * 8;
165
- const ptr0 = utf8_encode(e, realloc, memory);
166
- const len0 = UTF8_ENCODED_LEN;
167
- data_view(memory).setInt32(base + 4, len0, true);
168
- data_view(memory).setInt32(base + 0, ptr0, true);
169
- }
170
- this._exports['ruby-sysinit: func(args: list<string>) -> ()'](result1, len1);
171
- }
172
- rubyOptions(arg0) {
173
- const memory = this._exports.memory;
174
- const realloc = this._exports["cabi_realloc"];
175
- const vec1 = arg0;
176
- const len1 = vec1.length;
177
- const result1 = realloc(0, 0, 4, len1 * 8);
178
- for (let i = 0; i < vec1.length; i++) {
179
- const e = vec1[i];
180
- const base = result1 + i * 8;
181
- const ptr0 = utf8_encode(e, realloc, memory);
182
- const len0 = UTF8_ENCODED_LEN;
183
- data_view(memory).setInt32(base + 4, len0, true);
184
- data_view(memory).setInt32(base + 0, ptr0, true);
185
- }
186
- const ret = this._exports['ruby-options: func(args: list<string>) -> handle<rb-iseq>'](result1, len1);
187
- return this._resource0_slab.remove(ret);
188
- }
189
- rubyScript(arg0) {
190
- const memory = this._exports.memory;
191
- const realloc = this._exports["cabi_realloc"];
192
- const ptr0 = utf8_encode(arg0, realloc, memory);
193
- const len0 = UTF8_ENCODED_LEN;
194
- this._exports['ruby-script: func(name: string) -> ()'](ptr0, len0);
195
- }
196
- rubyInitLoadpath() {
197
- this._exports['ruby-init-loadpath: func() -> ()']();
198
- }
199
- rbEvalStringProtect(arg0) {
200
- const memory = this._exports.memory;
201
- const realloc = this._exports["cabi_realloc"];
202
- const ptr0 = utf8_encode(arg0, realloc, memory);
203
- const len0 = UTF8_ENCODED_LEN;
204
- const ret = this._exports['rb-eval-string-protect: func(str: string) -> tuple<handle<rb-abi-value>, s32>'](ptr0, len0);
205
- return [this._resource1_slab.remove(data_view(memory).getInt32(ret + 0, true)), data_view(memory).getInt32(ret + 4, true)];
206
- }
207
- rbFuncallvProtect(arg0, arg1, arg2) {
208
- const memory = this._exports.memory;
209
- const realloc = this._exports["cabi_realloc"];
210
- const obj0 = arg0;
211
- if (!(obj0 instanceof RbAbiValue)) throw new TypeError('expected instance of RbAbiValue');
212
- const vec2 = arg2;
213
- const len2 = vec2.length;
214
- const result2 = realloc(0, 0, 4, len2 * 4);
215
- for (let i = 0; i < vec2.length; i++) {
216
- const e = vec2[i];
217
- const base = result2 + i * 4;
218
- const obj1 = e;
219
- if (!(obj1 instanceof RbAbiValue)) throw new TypeError('expected instance of RbAbiValue');
220
- data_view(memory).setInt32(base + 0, this._resource1_slab.insert(obj1.clone()), true);
221
- }
222
- const ret = this._exports['rb-funcallv-protect: func(recv: handle<rb-abi-value>, mid: u32, args: list<handle<rb-abi-value>>) -> tuple<handle<rb-abi-value>, s32>'](this._resource1_slab.insert(obj0.clone()), to_uint32(arg1), result2, len2);
223
- return [this._resource1_slab.remove(data_view(memory).getInt32(ret + 0, true)), data_view(memory).getInt32(ret + 4, true)];
224
- }
225
- rbIntern(arg0) {
226
- const memory = this._exports.memory;
227
- const realloc = this._exports["cabi_realloc"];
228
- const ptr0 = utf8_encode(arg0, realloc, memory);
229
- const len0 = UTF8_ENCODED_LEN;
230
- const ret = this._exports['rb-intern: func(name: string) -> u32'](ptr0, len0);
231
- return ret >>> 0;
232
- }
233
- rbErrinfo() {
234
- const ret = this._exports['rb-errinfo: func() -> handle<rb-abi-value>']();
235
- return this._resource1_slab.remove(ret);
236
- }
237
- rbClearErrinfo() {
238
- this._exports['rb-clear-errinfo: func() -> ()']();
239
- }
240
- rstringPtr(arg0) {
241
- const memory = this._exports.memory;
242
- const obj0 = arg0;
243
- if (!(obj0 instanceof RbAbiValue)) throw new TypeError('expected instance of RbAbiValue');
244
- const ret = this._exports['rstring-ptr: func(value: handle<rb-abi-value>) -> string'](this._resource1_slab.insert(obj0.clone()));
245
- const ptr1 = data_view(memory).getInt32(ret + 0, true);
246
- const len1 = data_view(memory).getInt32(ret + 4, true);
247
- const result1 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr1, len1));
248
- this._exports["cabi_post_rstring-ptr"](ret);
249
- return result1;
250
- }
251
- rbVmBugreport() {
252
- this._exports['rb-vm-bugreport: func() -> ()']();
253
- }
254
- rbGcEnable() {
255
- const ret = this._exports['rb-gc-enable: func() -> bool']();
256
- const bool0 = ret;
257
- return bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool());
258
- }
259
- rbGcDisable() {
260
- const ret = this._exports['rb-gc-disable: func() -> bool']();
261
- const bool0 = ret;
262
- return bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool());
263
- }
264
- rbSetShouldProhibitRewind(arg0) {
265
- const ret = this._exports['rb-set-should-prohibit-rewind: func(new-value: bool) -> bool'](arg0 ? 1 : 0);
266
- const bool0 = ret;
267
- return bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool());
268
- }
269
- }
270
-
271
- class RbIseq {
272
- constructor(wasm_val, obj) {
273
- this._wasm_val = wasm_val;
274
- this._obj = obj;
275
- this._refcnt = 1;
276
- obj._registry0.register(this, wasm_val, this);
277
- }
278
-
279
- clone() {
280
- this._refcnt += 1;
281
- return this;
282
- }
283
-
284
- drop() {
285
- this._refcnt -= 1;
286
- if (this._refcnt !== 0)
287
- return;
288
- this._obj._registry0.unregister(this);
289
- const dtor = this._obj._exports['canonical_abi_drop_rb-iseq'];
290
- const wasm_val = this._wasm_val;
291
- delete this._obj;
292
- delete this._refcnt;
293
- delete this._wasm_val;
294
- dtor(wasm_val);
295
- }
296
- }
297
-
298
- class RbAbiValue {
299
- constructor(wasm_val, obj) {
300
- this._wasm_val = wasm_val;
301
- this._obj = obj;
302
- this._refcnt = 1;
303
- obj._registry1.register(this, wasm_val, this);
304
- }
305
-
306
- clone() {
307
- this._refcnt += 1;
308
- return this;
309
- }
310
-
311
- drop() {
312
- this._refcnt -= 1;
313
- if (this._refcnt !== 0)
314
- return;
315
- this._obj._registry1.unregister(this);
316
- const dtor = this._obj._exports['canonical_abi_drop_rb-abi-value'];
317
- const wasm_val = this._wasm_val;
318
- delete this._obj;
319
- delete this._refcnt;
320
- delete this._wasm_val;
321
- dtor(wasm_val);
322
- }
323
- }
324
-
325
- function addRbJsAbiHostToImports(imports, obj, get_export) {
326
- if (!("rb-js-abi-host" in imports)) imports["rb-js-abi-host"] = {};
327
- imports["rb-js-abi-host"]["eval-js: func(code: string) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2) {
328
- const memory = get_export("memory");
329
- const ptr0 = arg0;
330
- const len0 = arg1;
331
- const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
332
- const ret0 = obj.evalJs(result0);
333
- const variant1 = ret0;
334
- switch (variant1.tag) {
335
- case "success": {
336
- const e = variant1.val;
337
- data_view(memory).setInt8(arg2 + 0, 0, true);
338
- data_view(memory).setInt32(arg2 + 4, resources0.insert(e), true);
339
- break;
340
- }
341
- case "failure": {
342
- const e = variant1.val;
343
- data_view(memory).setInt8(arg2 + 0, 1, true);
344
- data_view(memory).setInt32(arg2 + 4, resources0.insert(e), true);
345
- break;
346
- }
347
- default:
348
- throw new RangeError("invalid variant specified for JsAbiResult");
349
- }
350
- };
351
- imports["rb-js-abi-host"]["is-js: func(value: handle<js-abi-value>) -> bool"] = function(arg0) {
352
- const ret0 = obj.isJs(resources0.get(arg0));
353
- return ret0 ? 1 : 0;
354
- };
355
- imports["rb-js-abi-host"]["instance-of: func(value: handle<js-abi-value>, klass: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
356
- const ret0 = obj.instanceOf(resources0.get(arg0), resources0.get(arg1));
357
- return ret0 ? 1 : 0;
358
- };
359
- imports["rb-js-abi-host"]["global-this: func() -> handle<js-abi-value>"] = function() {
360
- const ret0 = obj.globalThis();
361
- return resources0.insert(ret0);
362
- };
363
- imports["rb-js-abi-host"]["int-to-js-number: func(value: s32) -> handle<js-abi-value>"] = function(arg0) {
364
- const ret0 = obj.intToJsNumber(arg0);
365
- return resources0.insert(ret0);
366
- };
367
- imports["rb-js-abi-host"]["float-to-js-number: func(value: float64) -> handle<js-abi-value>"] = function(arg0) {
368
- const ret0 = obj.floatToJsNumber(arg0);
369
- return resources0.insert(ret0);
370
- };
371
- imports["rb-js-abi-host"]["string-to-js-string: func(value: string) -> handle<js-abi-value>"] = function(arg0, arg1) {
372
- const memory = get_export("memory");
373
- const ptr0 = arg0;
374
- const len0 = arg1;
375
- const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
376
- const ret0 = obj.stringToJsString(result0);
377
- return resources0.insert(ret0);
378
- };
379
- imports["rb-js-abi-host"]["bool-to-js-bool: func(value: bool) -> handle<js-abi-value>"] = function(arg0) {
380
- const bool0 = arg0;
381
- const ret0 = obj.boolToJsBool(bool0 == 0 ? false : (bool0 == 1 ? true : throw_invalid_bool()));
382
- return resources0.insert(ret0);
383
- };
384
- imports["rb-js-abi-host"]["proc-to-js-function: func(value: u32) -> handle<js-abi-value>"] = function(arg0) {
385
- const ret0 = obj.procToJsFunction(arg0 >>> 0);
386
- return resources0.insert(ret0);
387
- };
388
- imports["rb-js-abi-host"]["rb-object-to-js-rb-value: func(raw-rb-abi-value: u32) -> handle<js-abi-value>"] = function(arg0) {
389
- const ret0 = obj.rbObjectToJsRbValue(arg0 >>> 0);
390
- return resources0.insert(ret0);
391
- };
392
- imports["rb-js-abi-host"]["js-value-to-string: func(value: handle<js-abi-value>) -> string"] = function(arg0, arg1) {
393
- const memory = get_export("memory");
394
- const realloc = get_export("cabi_realloc");
395
- const ret0 = obj.jsValueToString(resources0.get(arg0));
396
- const ptr0 = utf8_encode(ret0, realloc, memory);
397
- const len0 = UTF8_ENCODED_LEN;
398
- data_view(memory).setInt32(arg1 + 4, len0, true);
399
- data_view(memory).setInt32(arg1 + 0, ptr0, true);
400
- };
401
- imports["rb-js-abi-host"]["js-value-to-integer: func(value: handle<js-abi-value>) -> variant { f64(float64), bignum(string) }"] = function(arg0, arg1) {
402
- const memory = get_export("memory");
403
- const realloc = get_export("cabi_realloc");
404
- const ret0 = obj.jsValueToInteger(resources0.get(arg0));
405
- const variant1 = ret0;
406
- switch (variant1.tag) {
407
- case "f64": {
408
- const e = variant1.val;
409
- data_view(memory).setInt8(arg1 + 0, 0, true);
410
- data_view(memory).setFloat64(arg1 + 8, +e, true);
411
- break;
412
- }
413
- case "bignum": {
414
- const e = variant1.val;
415
- data_view(memory).setInt8(arg1 + 0, 1, true);
416
- const ptr0 = utf8_encode(e, realloc, memory);
417
- const len0 = UTF8_ENCODED_LEN;
418
- data_view(memory).setInt32(arg1 + 12, len0, true);
419
- data_view(memory).setInt32(arg1 + 8, ptr0, true);
420
- break;
421
- }
422
- default:
423
- throw new RangeError("invalid variant specified for RawInteger");
424
- }
425
- };
426
- imports["rb-js-abi-host"]["export-js-value-to-host: func(value: handle<js-abi-value>) -> ()"] = function(arg0) {
427
- obj.exportJsValueToHost(resources0.get(arg0));
428
- };
429
- imports["rb-js-abi-host"]["import-js-value-from-host: func() -> handle<js-abi-value>"] = function() {
430
- const ret0 = obj.importJsValueFromHost();
431
- return resources0.insert(ret0);
432
- };
433
- imports["rb-js-abi-host"]["js-value-typeof: func(value: handle<js-abi-value>) -> string"] = function(arg0, arg1) {
434
- const memory = get_export("memory");
435
- const realloc = get_export("cabi_realloc");
436
- const ret0 = obj.jsValueTypeof(resources0.get(arg0));
437
- const ptr0 = utf8_encode(ret0, realloc, memory);
438
- const len0 = UTF8_ENCODED_LEN;
439
- data_view(memory).setInt32(arg1 + 4, len0, true);
440
- data_view(memory).setInt32(arg1 + 0, ptr0, true);
441
- };
442
- imports["rb-js-abi-host"]["js-value-equal: func(lhs: handle<js-abi-value>, rhs: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
443
- const ret0 = obj.jsValueEqual(resources0.get(arg0), resources0.get(arg1));
444
- return ret0 ? 1 : 0;
445
- };
446
- imports["rb-js-abi-host"]["js-value-strictly-equal: func(lhs: handle<js-abi-value>, rhs: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
447
- const ret0 = obj.jsValueStrictlyEqual(resources0.get(arg0), resources0.get(arg1));
448
- return ret0 ? 1 : 0;
449
- };
450
- imports["rb-js-abi-host"]["reflect-apply: func(target: handle<js-abi-value>, this-argument: handle<js-abi-value>, arguments: list<handle<js-abi-value>>) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2, arg3, arg4) {
451
- const memory = get_export("memory");
452
- const len0 = arg3;
453
- const base0 = arg2;
454
- const result0 = [];
455
- for (let i = 0; i < len0; i++) {
456
- const base = base0 + i * 4;
457
- result0.push(resources0.get(data_view(memory).getInt32(base + 0, true)));
458
- }
459
- const ret0 = obj.reflectApply(resources0.get(arg0), resources0.get(arg1), result0);
460
- const variant1 = ret0;
461
- switch (variant1.tag) {
462
- case "success": {
463
- const e = variant1.val;
464
- data_view(memory).setInt8(arg4 + 0, 0, true);
465
- data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
466
- break;
467
- }
468
- case "failure": {
469
- const e = variant1.val;
470
- data_view(memory).setInt8(arg4 + 0, 1, true);
471
- data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
472
- break;
473
- }
474
- default:
475
- throw new RangeError("invalid variant specified for JsAbiResult");
476
- }
477
- };
478
- imports["rb-js-abi-host"]["reflect-construct: func(target: handle<js-abi-value>, arguments: list<handle<js-abi-value>>) -> handle<js-abi-value>"] = function(arg0, arg1, arg2) {
479
- const memory = get_export("memory");
480
- const len0 = arg2;
481
- const base0 = arg1;
482
- const result0 = [];
483
- for (let i = 0; i < len0; i++) {
484
- const base = base0 + i * 4;
485
- result0.push(resources0.get(data_view(memory).getInt32(base + 0, true)));
486
- }
487
- const ret0 = obj.reflectConstruct(resources0.get(arg0), result0);
488
- return resources0.insert(ret0);
489
- };
490
- imports["rb-js-abi-host"]["reflect-delete-property: func(target: handle<js-abi-value>, property-key: string) -> bool"] = function(arg0, arg1, arg2) {
491
- const memory = get_export("memory");
492
- const ptr0 = arg1;
493
- const len0 = arg2;
494
- const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
495
- const ret0 = obj.reflectDeleteProperty(resources0.get(arg0), result0);
496
- return ret0 ? 1 : 0;
497
- };
498
- imports["rb-js-abi-host"]["reflect-get: func(target: handle<js-abi-value>, property-key: string) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2, arg3) {
499
- const memory = get_export("memory");
500
- const ptr0 = arg1;
501
- const len0 = arg2;
502
- const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
503
- const ret0 = obj.reflectGet(resources0.get(arg0), result0);
504
- const variant1 = ret0;
505
- switch (variant1.tag) {
506
- case "success": {
507
- const e = variant1.val;
508
- data_view(memory).setInt8(arg3 + 0, 0, true);
509
- data_view(memory).setInt32(arg3 + 4, resources0.insert(e), true);
510
- break;
511
- }
512
- case "failure": {
513
- const e = variant1.val;
514
- data_view(memory).setInt8(arg3 + 0, 1, true);
515
- data_view(memory).setInt32(arg3 + 4, resources0.insert(e), true);
516
- break;
517
- }
518
- default:
519
- throw new RangeError("invalid variant specified for JsAbiResult");
520
- }
521
- };
522
- imports["rb-js-abi-host"]["reflect-get-own-property-descriptor: func(target: handle<js-abi-value>, property-key: string) -> handle<js-abi-value>"] = function(arg0, arg1, arg2) {
523
- const memory = get_export("memory");
524
- const ptr0 = arg1;
525
- const len0 = arg2;
526
- const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
527
- const ret0 = obj.reflectGetOwnPropertyDescriptor(resources0.get(arg0), result0);
528
- return resources0.insert(ret0);
529
- };
530
- imports["rb-js-abi-host"]["reflect-get-prototype-of: func(target: handle<js-abi-value>) -> handle<js-abi-value>"] = function(arg0) {
531
- const ret0 = obj.reflectGetPrototypeOf(resources0.get(arg0));
532
- return resources0.insert(ret0);
533
- };
534
- imports["rb-js-abi-host"]["reflect-has: func(target: handle<js-abi-value>, property-key: string) -> bool"] = function(arg0, arg1, arg2) {
535
- const memory = get_export("memory");
536
- const ptr0 = arg1;
537
- const len0 = arg2;
538
- const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
539
- const ret0 = obj.reflectHas(resources0.get(arg0), result0);
540
- return ret0 ? 1 : 0;
541
- };
542
- imports["rb-js-abi-host"]["reflect-is-extensible: func(target: handle<js-abi-value>) -> bool"] = function(arg0) {
543
- const ret0 = obj.reflectIsExtensible(resources0.get(arg0));
544
- return ret0 ? 1 : 0;
545
- };
546
- imports["rb-js-abi-host"]["reflect-own-keys: func(target: handle<js-abi-value>) -> list<handle<js-abi-value>>"] = function(arg0, arg1) {
547
- const memory = get_export("memory");
548
- const realloc = get_export("cabi_realloc");
549
- const ret0 = obj.reflectOwnKeys(resources0.get(arg0));
550
- const vec0 = ret0;
551
- const len0 = vec0.length;
552
- const result0 = realloc(0, 0, 4, len0 * 4);
553
- for (let i = 0; i < vec0.length; i++) {
554
- const e = vec0[i];
555
- const base = result0 + i * 4;
556
- data_view(memory).setInt32(base + 0, resources0.insert(e), true);
557
- }
558
- data_view(memory).setInt32(arg1 + 4, len0, true);
559
- data_view(memory).setInt32(arg1 + 0, result0, true);
560
- };
561
- imports["rb-js-abi-host"]["reflect-prevent-extensions: func(target: handle<js-abi-value>) -> bool"] = function(arg0) {
562
- const ret0 = obj.reflectPreventExtensions(resources0.get(arg0));
563
- return ret0 ? 1 : 0;
564
- };
565
- imports["rb-js-abi-host"]["reflect-set: func(target: handle<js-abi-value>, property-key: string, value: handle<js-abi-value>) -> variant { success(handle<js-abi-value>), failure(handle<js-abi-value>) }"] = function(arg0, arg1, arg2, arg3, arg4) {
566
- const memory = get_export("memory");
567
- const ptr0 = arg1;
568
- const len0 = arg2;
569
- const result0 = UTF8_DECODER.decode(new Uint8Array(memory.buffer, ptr0, len0));
570
- const ret0 = obj.reflectSet(resources0.get(arg0), result0, resources0.get(arg3));
571
- const variant1 = ret0;
572
- switch (variant1.tag) {
573
- case "success": {
574
- const e = variant1.val;
575
- data_view(memory).setInt8(arg4 + 0, 0, true);
576
- data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
577
- break;
578
- }
579
- case "failure": {
580
- const e = variant1.val;
581
- data_view(memory).setInt8(arg4 + 0, 1, true);
582
- data_view(memory).setInt32(arg4 + 4, resources0.insert(e), true);
583
- break;
584
- }
585
- default:
586
- throw new RangeError("invalid variant specified for JsAbiResult");
587
- }
588
- };
589
- imports["rb-js-abi-host"]["reflect-set-prototype-of: func(target: handle<js-abi-value>, prototype: handle<js-abi-value>) -> bool"] = function(arg0, arg1) {
590
- const ret0 = obj.reflectSetPrototypeOf(resources0.get(arg0), resources0.get(arg1));
591
- return ret0 ? 1 : 0;
592
- };
593
- if (!("canonical_abi" in imports)) imports["canonical_abi"] = {};
594
-
595
- const resources0 = new Slab();
596
- imports.canonical_abi["resource_drop_js-abi-value"] = (i) => {
597
- const val = resources0.remove(i);
598
- if (obj.dropJsAbiValue)
599
- obj.dropJsAbiValue(val);
600
- };
601
- }
602
-
603
- /**
604
- * A Ruby VM instance
605
- *
606
- * @example
607
- *
608
- * const wasi = new WASI();
609
- * const vm = new RubyVM();
610
- * const imports = {
611
- * wasi_snapshot_preview1: wasi.wasiImport,
612
- * };
613
- *
614
- * vm.addToImports(imports);
615
- *
616
- * const instance = await WebAssembly.instantiate(rubyModule, imports);
617
- * await vm.setInstance(instance);
618
- * wasi.initialize(instance);
619
- * vm.initialize();
620
- *
621
- */
622
- class RubyVM {
623
- constructor() {
624
- this.instance = null;
625
- this.interfaceState = {
626
- hasJSFrameAfterRbFrame: false,
627
- };
628
- // Wrap exported functions from Ruby VM to prohibit nested VM operation
629
- // if the call stack has sandwitched JS frames like JS -> Ruby -> JS -> Ruby.
630
- const proxyExports = (exports) => {
631
- const excludedMethods = [
632
- "addToImports",
633
- "instantiate",
634
- "rbSetShouldProhibitRewind",
635
- "rbGcDisable",
636
- "rbGcEnable",
637
- ];
638
- const excluded = ["constructor"].concat(excludedMethods);
639
- // wrap all methods in RbAbi.RbAbiGuest class
640
- for (const key of Object.getOwnPropertyNames(RbAbiGuest.prototype)) {
641
- if (excluded.includes(key)) {
642
- continue;
643
- }
644
- const value = exports[key];
645
- if (typeof value === "function") {
646
- exports[key] = (...args) => {
647
- const isNestedVMCall = this.interfaceState.hasJSFrameAfterRbFrame;
648
- if (isNestedVMCall) {
649
- const oldShouldProhibitRewind = this.guest.rbSetShouldProhibitRewind(true);
650
- const oldIsDisabledGc = this.guest.rbGcDisable();
651
- const result = Reflect.apply(value, exports, args);
652
- this.guest.rbSetShouldProhibitRewind(oldShouldProhibitRewind);
653
- if (!oldIsDisabledGc) {
654
- this.guest.rbGcEnable();
655
- }
656
- return result;
657
- }
658
- else {
659
- return Reflect.apply(value, exports, args);
660
- }
661
- };
662
- }
663
- }
664
- return exports;
665
- };
666
- this.guest = proxyExports(new RbAbiGuest());
667
- this.transport = new JsValueTransport();
668
- this.exceptionFormatter = new RbExceptionFormatter();
669
- }
670
- /**
671
- * Initialize the Ruby VM with the given command line arguments
672
- * @param args The command line arguments to pass to Ruby. Must be
673
- * an array of strings starting with the Ruby program name.
674
- */
675
- initialize(args = ["ruby.wasm", "--disable-gems", "-EUTF-8", "-e_=0"]) {
676
- const c_args = args.map((arg) => arg + "\0");
677
- this.guest.rubyInit();
678
- this.guest.rubySysinit(c_args);
679
- this.guest.rubyOptions(c_args);
680
- }
681
- /**
682
- * Set a given instance to interact JavaScript and Ruby's
683
- * WebAssembly instance. This method must be called before calling
684
- * Ruby API.
685
- *
686
- * @param instance The WebAssembly instance to interact with. Must
687
- * be instantiated from a Ruby built with JS extension, and built
688
- * with Reactor ABI instead of command line.
689
- */
690
- async setInstance(instance) {
691
- this.instance = instance;
692
- await this.guest.instantiate(instance);
693
- }
694
- /**
695
- * Add intrinsic import entries, which is necessary to interact JavaScript
696
- * and Ruby's WebAssembly instance.
697
- * @param imports The import object to add to the WebAssembly instance
698
- */
699
- addToImports(imports) {
700
- this.guest.addToImports(imports);
701
- function wrapTry(f) {
702
- return (...args) => {
703
- try {
704
- return { tag: "success", val: f(...args) };
705
- }
706
- catch (e) {
707
- if (e instanceof RbFatalError) {
708
- // RbFatalError should not be caught by Ruby because it Ruby VM
709
- // can be already in an inconsistent state.
710
- throw e;
711
- }
712
- return { tag: "failure", val: e };
713
- }
714
- };
715
- }
716
- imports["rb-js-abi-host"] = {
717
- rb_wasm_throw_prohibit_rewind_exception: (messagePtr, messageLen) => {
718
- const memory = this.instance.exports.memory;
719
- const str = new TextDecoder().decode(new Uint8Array(memory.buffer, messagePtr, messageLen));
720
- throw new RbFatalError("Ruby APIs that may rewind the VM stack are prohibited under nested VM operation " +
721
- `(${str})\n` +
722
- "Nested VM operation means that the call stack has sandwitched JS frames like JS -> Ruby -> JS -> Ruby " +
723
- "caused by something like `window.rubyVM.eval(\"JS.global[:rubyVM].eval('Fiber.yield')\")`\n" +
724
- "\n" +
725
- "Please check your call stack and make sure that you are **not** doing any of the following inside the nested Ruby frame:\n" +
726
- " 1. Switching fibers (e.g. Fiber#resume, Fiber.yield, and Fiber#transfer)\n" +
727
- " Note that `evalAsync` JS API switches fibers internally\n" +
728
- " 2. Raising uncaught exceptions\n" +
729
- " Please catch all exceptions inside the nested operation\n" +
730
- " 3. Calling Continuation APIs\n");
731
- },
732
- };
733
- // NOTE: The GC may collect objects that are still referenced by Wasm
734
- // locals because Asyncify cannot scan the Wasm stack above the JS frame.
735
- // So we need to keep track whether the JS frame is sandwitched by Ruby
736
- // frames or not, and prohibit nested VM operation if it is.
737
- const proxyImports = (imports) => {
738
- for (const [key, value] of Object.entries(imports)) {
739
- if (typeof value === "function") {
740
- imports[key] = (...args) => {
741
- const oldValue = this.interfaceState.hasJSFrameAfterRbFrame;
742
- this.interfaceState.hasJSFrameAfterRbFrame = true;
743
- const result = Reflect.apply(value, imports, args);
744
- this.interfaceState.hasJSFrameAfterRbFrame = oldValue;
745
- return result;
746
- };
747
- }
748
- }
749
- return imports;
750
- };
751
- addRbJsAbiHostToImports(imports, proxyImports({
752
- evalJs: wrapTry((code) => {
753
- return Function(code)();
754
- }),
755
- isJs: (value) => {
756
- // Just for compatibility with the old JS API
757
- return true;
758
- },
759
- globalThis: () => {
760
- if (typeof globalThis !== "undefined") {
761
- return globalThis;
762
- }
763
- else if (typeof global !== "undefined") {
764
- return global;
765
- }
766
- else if (typeof window !== "undefined") {
767
- return window;
768
- }
769
- throw new Error("unable to locate global object");
770
- },
771
- intToJsNumber: (value) => {
772
- return value;
773
- },
774
- floatToJsNumber: (value) => {
775
- return value;
776
- },
777
- stringToJsString: (value) => {
778
- return value;
779
- },
780
- boolToJsBool: (value) => {
781
- return value;
782
- },
783
- procToJsFunction: (rawRbAbiValue) => {
784
- const rbValue = this.rbValueOfPointer(rawRbAbiValue);
785
- return (...args) => {
786
- rbValue.call("call", ...args.map((arg) => this.wrap(arg)));
787
- };
788
- },
789
- rbObjectToJsRbValue: (rawRbAbiValue) => {
790
- return this.rbValueOfPointer(rawRbAbiValue);
791
- },
792
- jsValueToString: (value) => {
793
- // According to the [spec](https://tc39.es/ecma262/multipage/text-processing.html#sec-string-constructor-string-value)
794
- // `String(value)` always returns a string.
795
- return String(value);
796
- },
797
- jsValueToInteger(value) {
798
- if (typeof value === "number") {
799
- return { tag: "f64", val: value };
800
- }
801
- else if (typeof value === "bigint") {
802
- return { tag: "bignum", val: BigInt(value).toString(10) + "\0" };
803
- }
804
- else if (typeof value === "string") {
805
- return { tag: "bignum", val: value + "\0" };
806
- }
807
- else if (typeof value === "undefined") {
808
- return { tag: "f64", val: 0 };
809
- }
810
- else {
811
- return { tag: "f64", val: Number(value) };
812
- }
813
- },
814
- exportJsValueToHost: (value) => {
815
- // See `JsValueExporter` for the reason why we need to do this
816
- this.transport.takeJsValue(value);
817
- },
818
- importJsValueFromHost: () => {
819
- return this.transport.consumeJsValue();
820
- },
821
- instanceOf: (value, klass) => {
822
- if (typeof klass === "function") {
823
- return value instanceof klass;
824
- }
825
- else {
826
- return false;
827
- }
828
- },
829
- jsValueTypeof(value) {
830
- return typeof value;
831
- },
832
- jsValueEqual(lhs, rhs) {
833
- return lhs == rhs;
834
- },
835
- jsValueStrictlyEqual(lhs, rhs) {
836
- return lhs === rhs;
837
- },
838
- reflectApply: wrapTry((target, thisArgument, args) => {
839
- return Reflect.apply(target, thisArgument, args);
840
- }),
841
- reflectConstruct: function (target, args) {
842
- throw new Error("Function not implemented.");
843
- },
844
- reflectDeleteProperty: function (target, propertyKey) {
845
- throw new Error("Function not implemented.");
846
- },
847
- reflectGet: wrapTry((target, propertyKey) => {
848
- return target[propertyKey];
849
- }),
850
- reflectGetOwnPropertyDescriptor: function (target, propertyKey) {
851
- throw new Error("Function not implemented.");
852
- },
853
- reflectGetPrototypeOf: function (target) {
854
- throw new Error("Function not implemented.");
855
- },
856
- reflectHas: function (target, propertyKey) {
857
- throw new Error("Function not implemented.");
858
- },
859
- reflectIsExtensible: function (target) {
860
- throw new Error("Function not implemented.");
861
- },
862
- reflectOwnKeys: function (target) {
863
- throw new Error("Function not implemented.");
864
- },
865
- reflectPreventExtensions: function (target) {
866
- throw new Error("Function not implemented.");
867
- },
868
- reflectSet: wrapTry((target, propertyKey, value) => {
869
- return Reflect.set(target, propertyKey, value);
870
- }),
871
- reflectSetPrototypeOf: function (target, prototype) {
872
- throw new Error("Function not implemented.");
873
- },
874
- }), (name) => {
875
- return this.instance.exports[name];
876
- });
877
- }
878
- /**
879
- * Print the Ruby version to stdout
880
- */
881
- printVersion() {
882
- this.guest.rubyShowVersion();
883
- }
884
- /**
885
- * Runs a string of Ruby code from JavaScript
886
- * @param code The Ruby code to run
887
- * @returns the result of the last expression
888
- *
889
- * @example
890
- * vm.eval("puts 'hello world'");
891
- * const result = vm.eval("1 + 2");
892
- * console.log(result.toString()); // 3
893
- *
894
- */
895
- eval(code) {
896
- return evalRbCode(this, this.privateObject(), code);
897
- }
898
- /**
899
- * Runs a string of Ruby code with top-level `JS::Object#await`
900
- * Returns a promise that resolves when execution completes.
901
- * @param code The Ruby code to run
902
- * @returns a promise that resolves to the result of the last expression
903
- *
904
- * @example
905
- * const text = await vm.evalAsync(`
906
- * require 'js'
907
- * response = JS.global.fetch('https://example.com').await
908
- * response.text.await
909
- * `);
910
- * console.log(text.toString()); // <html>...</html>
911
- */
912
- evalAsync(code) {
913
- const JS = this.eval("require 'js'; JS");
914
- return new Promise((resolve, reject) => {
915
- JS.call("__eval_async_rb", this.wrap(code), this.wrap({
916
- resolve,
917
- reject: (error) => {
918
- reject(new RbError(this.exceptionFormatter.format(error, this, this.privateObject())));
919
- },
920
- }));
921
- });
922
- }
923
- /**
924
- * Wrap a JavaScript value into a Ruby JS::Object
925
- * @param value The value to convert to RbValue
926
- * @returns the RbValue object representing the given JS value
927
- *
928
- * @example
929
- * const hash = vm.eval(`Hash.new`)
930
- * hash.call("store", vm.eval(`"key1"`), vm.wrap(new Object()));
931
- */
932
- wrap(value) {
933
- return this.transport.importJsValue(value, this);
934
- }
935
- privateObject() {
936
- return {
937
- transport: this.transport,
938
- exceptionFormatter: this.exceptionFormatter,
939
- };
940
- }
941
- rbValueOfPointer(pointer) {
942
- const abiValue = new RbAbiValue(pointer, this.guest);
943
- return new RbValue(abiValue, this, this.privateObject());
944
- }
945
- }
946
- /**
947
- * Export a JS value held by the Ruby VM to the JS environment.
948
- * This is implemented in a dirty way since wit cannot reference resources
949
- * defined in other interfaces.
950
- * In our case, we can't express `function(v: rb-abi-value) -> js-abi-value`
951
- * because `rb-js-abi-host.wit`, that defines `js-abi-value`, is implemented
952
- * by embedder side (JS) but `rb-abi-guest.wit`, that defines `rb-abi-value`
953
- * is implemented by guest side (Wasm).
954
- *
955
- * This class is a helper to export by:
956
- * 1. Call `function __export_to_js(v: rb-abi-value)` defined in guest from embedder side.
957
- * 2. Call `function takeJsValue(v: js-abi-value)` defined in embedder from guest side with
958
- * underlying JS value of given `rb-abi-value`.
959
- * 3. Then `takeJsValue` implementation escapes the given JS value to the `_takenJsValues`
960
- * stored in embedder side.
961
- * 4. Finally, embedder side can take `_takenJsValues`.
962
- *
963
- * Note that `exportJsValue` is not reentrant.
964
- *
965
- * @private
966
- */
967
- class JsValueTransport {
968
- constructor() {
969
- this._takenJsValue = null;
970
- }
971
- takeJsValue(value) {
972
- this._takenJsValue = value;
973
- }
974
- consumeJsValue() {
975
- return this._takenJsValue;
976
- }
977
- exportJsValue(value) {
978
- value.call("__export_to_js");
979
- return this._takenJsValue;
980
- }
981
- importJsValue(value, vm) {
982
- this._takenJsValue = value;
983
- return vm.eval('require "js"; JS::Object').call("__import_from_js");
984
- }
985
- }
986
- /**
987
- * A RbValue is an object that represents a value in Ruby
988
- */
989
- class RbValue {
990
- /**
991
- * @hideconstructor
992
- */
993
- constructor(inner, vm, privateObject) {
994
- this.inner = inner;
995
- this.vm = vm;
996
- this.privateObject = privateObject;
997
- }
998
- /**
999
- * Call a given method with given arguments
1000
- *
1001
- * @param callee name of the Ruby method to call
1002
- * @param args arguments to pass to the method. Must be an array of RbValue
1003
- *
1004
- * @example
1005
- * const ary = vm.eval("[1, 2, 3]");
1006
- * ary.call("push", 4);
1007
- * console.log(ary.call("sample").toString());
1008
- *
1009
- */
1010
- call(callee, ...args) {
1011
- const innerArgs = args.map((arg) => arg.inner);
1012
- return new RbValue(callRbMethod(this.vm, this.privateObject, this.inner, callee, innerArgs), this.vm, this.privateObject);
1013
- }
1014
- /**
1015
- * @see {@link https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive}
1016
- * @param hint Preferred type of the result primitive value. `"number"`, `"string"`, or `"default"`.
1017
- */
1018
- [Symbol.toPrimitive](hint) {
1019
- if (hint === "string" || hint === "default") {
1020
- return this.toString();
1021
- }
1022
- else if (hint === "number") {
1023
- return null;
1024
- }
1025
- return null;
1026
- }
1027
- /**
1028
- * Returns a string representation of the value by calling `to_s`
1029
- */
1030
- toString() {
1031
- const rbString = callRbMethod(this.vm, this.privateObject, this.inner, "to_s", []);
1032
- return this.vm.guest.rstringPtr(rbString);
1033
- }
1034
- /**
1035
- * Returns a JavaScript object representation of the value
1036
- * by calling `to_js`.
1037
- *
1038
- * Returns null if the value is not convertible to a JavaScript object.
1039
- */
1040
- toJS() {
1041
- const JS = this.vm.eval("JS");
1042
- const jsValue = JS.call("try_convert", this);
1043
- if (jsValue.call("nil?").toString() === "true") {
1044
- return null;
1045
- }
1046
- return this.privateObject.transport.exportJsValue(jsValue);
1047
- }
1048
- }
1049
- var ruby_tag_type;
1050
- (function (ruby_tag_type) {
1051
- ruby_tag_type[ruby_tag_type["None"] = 0] = "None";
1052
- ruby_tag_type[ruby_tag_type["Return"] = 1] = "Return";
1053
- ruby_tag_type[ruby_tag_type["Break"] = 2] = "Break";
1054
- ruby_tag_type[ruby_tag_type["Next"] = 3] = "Next";
1055
- ruby_tag_type[ruby_tag_type["Retry"] = 4] = "Retry";
1056
- ruby_tag_type[ruby_tag_type["Redo"] = 5] = "Redo";
1057
- ruby_tag_type[ruby_tag_type["Raise"] = 6] = "Raise";
1058
- ruby_tag_type[ruby_tag_type["Throw"] = 7] = "Throw";
1059
- ruby_tag_type[ruby_tag_type["Fatal"] = 8] = "Fatal";
1060
- ruby_tag_type[ruby_tag_type["Mask"] = 15] = "Mask";
1061
- })(ruby_tag_type || (ruby_tag_type = {}));
1062
- class RbExceptionFormatter {
1063
- constructor() {
1064
- this.literalsCache = null;
1065
- }
1066
- format(error, vm, privateObject) {
1067
- const [zeroLiteral, oneLiteral, newLineLiteral] = (() => {
1068
- if (this.literalsCache == null) {
1069
- const zeroOneNewLine = [
1070
- evalRbCode(vm, privateObject, "0"),
1071
- evalRbCode(vm, privateObject, "1"),
1072
- evalRbCode(vm, privateObject, `"\n"`),
1073
- ];
1074
- this.literalsCache = zeroOneNewLine;
1075
- return zeroOneNewLine;
1076
- }
1077
- else {
1078
- return this.literalsCache;
1079
- }
1080
- })();
1081
- const backtrace = error.call("backtrace");
1082
- if (backtrace.call("nil?").toString() === "true") {
1083
- return this.formatString(error.call("class").toString(), error.toString());
1084
- }
1085
- const firstLine = backtrace.call("at", zeroLiteral);
1086
- const restLines = backtrace
1087
- .call("drop", oneLiteral)
1088
- .call("join", newLineLiteral);
1089
- return this.formatString(error.call("class").toString(), error.toString(), [
1090
- firstLine.toString(),
1091
- restLines.toString(),
1092
- ]);
1093
- }
1094
- formatString(klass, message, backtrace) {
1095
- if (backtrace) {
1096
- return `${backtrace[0]}: ${message} (${klass})\n${backtrace[1]}`;
1097
- }
1098
- else {
1099
- return `${klass}: ${message}`;
1100
- }
1101
- }
1102
- }
1103
- const checkStatusTag = (rawTag, vm, privateObject) => {
1104
- switch (rawTag & ruby_tag_type.Mask) {
1105
- case ruby_tag_type.None:
1106
- break;
1107
- case ruby_tag_type.Return:
1108
- throw new RbError("unexpected return");
1109
- case ruby_tag_type.Next:
1110
- throw new RbError("unexpected next");
1111
- case ruby_tag_type.Break:
1112
- throw new RbError("unexpected break");
1113
- case ruby_tag_type.Redo:
1114
- throw new RbError("unexpected redo");
1115
- case ruby_tag_type.Retry:
1116
- throw new RbError("retry outside of rescue clause");
1117
- case ruby_tag_type.Throw:
1118
- throw new RbError("unexpected throw");
1119
- case ruby_tag_type.Raise:
1120
- case ruby_tag_type.Fatal:
1121
- const error = new RbValue(vm.guest.rbErrinfo(), vm, privateObject);
1122
- if (error.call("nil?").toString() === "true") {
1123
- throw new RbError("no exception object");
1124
- }
1125
- // clear errinfo if got exception due to no rb_jump_tag
1126
- vm.guest.rbClearErrinfo();
1127
- throw new RbError(privateObject.exceptionFormatter.format(error, vm, privateObject));
1128
- default:
1129
- throw new RbError(`unknown error tag: ${rawTag}`);
1130
- }
1131
- };
1132
- function wrapRbOperation(vm, body) {
1133
- try {
1134
- return body();
1135
- }
1136
- catch (e) {
1137
- if (e instanceof RbError) {
1138
- throw e;
1139
- }
1140
- // All JS exceptions triggered by Ruby code are translated to Ruby exceptions,
1141
- // so non-RbError exceptions are unexpected.
1142
- vm.guest.rbVmBugreport();
1143
- if (e instanceof WebAssembly.RuntimeError && e.message === "unreachable") {
1144
- const error = new RbError(`Something went wrong in Ruby VM: ${e}`);
1145
- error.stack = e.stack;
1146
- throw error;
1147
- }
1148
- else {
1149
- throw e;
1150
- }
1151
- }
1152
- }
1153
- const callRbMethod = (vm, privateObject, recv, callee, args) => {
1154
- const mid = vm.guest.rbIntern(callee + "\0");
1155
- return wrapRbOperation(vm, () => {
1156
- const [value, status] = vm.guest.rbFuncallvProtect(recv, mid, args);
1157
- checkStatusTag(status, vm, privateObject);
1158
- return value;
1159
- });
1160
- };
1161
- const evalRbCode = (vm, privateObject, code) => {
1162
- return wrapRbOperation(vm, () => {
1163
- const [value, status] = vm.guest.rbEvalStringProtect(code + "\0");
1164
- checkStatusTag(status, vm, privateObject);
1165
- return new RbValue(value, vm, privateObject);
1166
- });
1167
- };
1168
- /**
1169
- * Error class thrown by Ruby execution
1170
- */
1171
- class RbError extends Error {
1172
- /**
1173
- * @hideconstructor
1174
- */
1175
- constructor(message) {
1176
- super(message);
1177
- }
1178
- }
1179
- /**
1180
- * Error class thrown by Ruby execution when it is not possible to recover.
1181
- * This is usually caused when Ruby VM is in an inconsistent state.
1182
- */
1183
- class RbFatalError extends RbError {
1184
- /**
1185
- * @hideconstructor
1186
- */
1187
- constructor(message) {
1188
- super("Ruby Fatal Error: " + message);
1189
- }
1190
- }
1191
-
1192
- exports.RbError = RbError;
1193
- exports.RbFatalError = RbFatalError;
1194
- exports.RbValue = RbValue;
1195
- exports.RubyVM = RubyVM;