summaryrefslogtreecommitdiffstats
path: root/js/src/jit-test/tests/wasm/spec/gc/harness/harness.js
blob: a96781e8ed48f97d55f194bd9b668ca317d174f0 (plain)
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
"use strict";

/* Copyright 2021 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

if (!wasmIsSupported()) {
  quit();
}

function bytes(type, bytes) {
  var typedBuffer = new Uint8Array(bytes);
  return wasmGlobalFromArrayBuffer(type, typedBuffer.buffer);
}
function value(type, value) {
  return new WebAssembly.Global({
    value: type,
    mutable: false,
  }, value);
}

function i8x16(elements) {
  let typedBuffer = new Uint8Array(elements);
  return wasmGlobalFromArrayBuffer("v128", typedBuffer.buffer);
}
function i16x8(elements) {
  let typedBuffer = new Uint16Array(elements);
  return wasmGlobalFromArrayBuffer("v128", typedBuffer.buffer);
}
function i32x4(elements) {
  let typedBuffer = new Uint32Array(elements);
  return wasmGlobalFromArrayBuffer("v128", typedBuffer.buffer);
}
function i64x2(elements) {
  let typedBuffer = new BigUint64Array(elements);
  return wasmGlobalFromArrayBuffer("v128", typedBuffer.buffer);
}
function f32x4(elements) {
  let typedBuffer = new Float32Array(elements);
  return wasmGlobalFromArrayBuffer("v128", typedBuffer.buffer);
}
function f64x2(elements) {
  let typedBuffer = new Float64Array(elements);
  return wasmGlobalFromArrayBuffer("v128", typedBuffer.buffer);
}

function either(...arr) {
  return new EitherVariants(arr);
}

class F32x4Pattern {
  constructor(x, y, z, w) {
    this.x = x;
    this.y = y;
    this.z = z;
    this.w = w;
  }
}

class F64x2Pattern {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

class RefWithType {
  constructor(type) {
    this.type = type;
  }

  formatExpected() {
    return `RefWithType(${this.type})`;
  }

  test(refGlobal) {
    try {
      new WebAssembly.Global({value: this.type}, refGlobal.value);
      return true;
    } catch (err) {
      assertEq(err instanceof TypeError, true, `wrong type of error when creating global: ${err}`);
      assertEq(!!err.message.match(/can only pass/), true, `wrong type of error when creating global: ${err}`);
      return false;
    }
  }
}

// ref.extern values created by spec tests will be JS objects of the form
// { [externsym]: <number> }. Other externref values are possible to observe
// if extern.convert_any is used.
let externsym = Symbol("externref");
function externref(s) {
  return { [externsym]: s };
}
function is_externref(x) {
  return (x !== null && externsym in x) ? 1 : 0;
}
function is_funcref(x) {
  return typeof x === "function" ? 1 : 0;
}
function eq_externref(x, y) {
  return x === y ? 1 : 0;
}
function eq_funcref(x, y) {
  return x === y ? 1 : 0;
}

class ExternRefResult {
  constructor(n) {
    this.n = n;
  }

  formatExpected() {
    return `ref.extern ${this.n}`;
  }

  test(global) {
    // the global's value can either be an externref or just a plain old JS number
    let result = global.value;
    if (typeof global.value === "object" && externsym in global.value) {
      result = global.value[externsym];
    }
    return result === this.n;
  }
}

// ref.host values created by spectests will be whatever the JS API does to
// convert the given value to anyref. It should implicitly be like any.convert_extern.
function hostref(v) {
  if (!wasmGcEnabled()) {
    throw new Error("ref.host only works when wasm GC is enabled");
  }

  const { internalizeNum } = new WebAssembly.Instance(
    new WebAssembly.Module(wasmTextToBinary(`(module
      (func (import "test" "coerce") (param i32) (result anyref))
      (func (export "internalizeNum") (param i32) (result anyref)
        (call 0 (local.get 0))
      )
    )`)),
    { "test": { "coerce": x => x } },
  ).exports;
  return internalizeNum(v);
}

class HostRefResult {
  constructor(n) {
    this.n = n;
  }

  formatExpected() {
    return `ref.host ${this.n}`;
  }

  test(externrefGlobal) {
    assertEq(externsym in externrefGlobal.value, true, `HostRefResult only works with externref inputs`);
    return externrefGlobal.value[externsym] === this.n;
  }
}

let spectest = {
  externref: externref,
  is_externref: is_externref,
  is_funcref: is_funcref,
  eq_externref: eq_externref,
  eq_funcref: eq_funcref,
  print: console.log.bind(console),
  print_i32: console.log.bind(console),
  print_i32_f32: console.log.bind(console),
  print_f64_f64: console.log.bind(console),
  print_f32: console.log.bind(console),
  print_f64: console.log.bind(console),
  global_i32: 666,
  global_i64: 666n,
  global_f32: 666,
  global_f64: 666,
  table: new WebAssembly.Table({
    initial: 10,
    maximum: 20,
    element: "anyfunc",
  }),
  memory: new WebAssembly.Memory({ initial: 1, maximum: 2 }),
};

let linkage = {
  spectest,
};

function getInstance(instanceish) {
  if (typeof instanceish === "string") {
    assertEq(
      instanceish in linkage,
      true,
      `'${instanceish}'' must be registered`,
    );
    return linkage[instanceish];
  }
  return instanceish;
}

function instantiate(source) {
  let bytecode = wasmTextToBinary(source);
  let module = new WebAssembly.Module(bytecode);
  let instance = new WebAssembly.Instance(module, linkage);
  return instance.exports;
}

function register(instanceish, name) {
  linkage[name] = getInstance(instanceish);
}

function invoke(instanceish, field, params) {
  let func = getInstance(instanceish)[field];
  assertEq(func instanceof Function, true, "expected a function");
  return wasmLosslessInvoke(func, ...params);
}

function get(instanceish, field) {
  let global = getInstance(instanceish)[field];
  assertEq(
    global instanceof WebAssembly.Global,
    true,
    "expected a WebAssembly.Global",
  );
  return global;
}

function assert_trap(thunk, message) {
  try {
    thunk();
    throw new Error("expected trap");
  } catch (err) {
    if (err instanceof WebAssembly.RuntimeError) {
      return;
    }
    throw err;
  }
}

let StackOverflow;
try {
  (function f() {
    1 + f();
  })();
} catch (e) {
  StackOverflow = e.constructor;
}
function assert_exhaustion(thunk, message) {
  try {
    thunk();
    assertEq("normal return", "exhaustion");
  } catch (err) {
    assertEq(
      err instanceof StackOverflow,
      true,
      "expected exhaustion",
    );
  }
}

function assert_invalid(thunk, message) {
  try {
    thunk();
    assertEq("valid module", "invalid module");
  } catch (err) {
    assertEq(
      err instanceof WebAssembly.LinkError ||
        err instanceof WebAssembly.CompileError,
      true,
      "expected an invalid module",
    );
  }
}

function assert_unlinkable(thunk, message) {
  try {
    thunk();
    assertEq(true, false, "expected an unlinkable module");
  } catch (err) {
    assertEq(
      err instanceof WebAssembly.LinkError ||
        err instanceof WebAssembly.CompileError,
      true,
      "expected an unlinkable module",
    );
  }
}

function assert_malformed(thunk, message) {
  try {
    thunk();
    assertEq("valid module", "malformed module");
  } catch (err) {
    assertEq(
      err instanceof TypeError ||
        err instanceof SyntaxError ||
        err instanceof WebAssembly.CompileError ||
        err instanceof WebAssembly.LinkError,
      true,
      `expected a malformed module`,
    );
  }
}

function assert_exception(thunk) {
  let thrown = false;
  try {
    thunk();
  } catch (err) {
    thrown = true;
  }
  assertEq(thrown, true, "expected an exception to be thrown");
}

function assert_return(thunk, expected) {
  let results = thunk();

  if (results === undefined) {
    results = [];
  } else if (!Array.isArray(results)) {
    results = [results];
  }
  if (!Array.isArray(expected)) {
    expected = [expected];
  }

  if (!compareResults(results, expected)) {
    let got = results.map((x) => formatResult(x)).join(", ");
    let wanted = expected.map((x) => formatExpected(x)).join(", ");
    assertEq(
      `[${got}]`,
      `[${wanted}]`,
    );
    assertEq(true, false, `${got} !== ${wanted}`);
  }
}

function formatResult(result) {
  if (typeof (result) === "object") {
    return wasmGlobalToString(result);
  } else {
    return `${result}`;
  }
}

function formatExpected(expected) {
  if (
    expected === `f32_canonical_nan` ||
    expected === `f32_arithmetic_nan` ||
    expected === `f64_canonical_nan` ||
    expected === `f64_arithmetic_nan`
  ) {
    return expected;
  } else if (expected instanceof F32x4Pattern) {
    return `f32x4(${formatExpected(expected.x)}, ${
      formatExpected(expected.y)
    }, ${formatExpected(expected.z)}, ${formatExpected(expected.w)})`;
  } else if (expected instanceof F64x2Pattern) {
    return `f64x2(${formatExpected(expected.x)}, ${
      formatExpected(expected.y)
    })`;
  } else if (expected instanceof EitherVariants) {
    return expected.formatExpected();
  } else if (expected instanceof RefWithType) {
    return expected.formatExpected();
  } else if (expected instanceof ExternRefResult) {
    return expected.formatExpected();
  } else if (expected instanceof HostRefResult) {
    return expected.formatExpected();
  } else if (typeof (expected) === "object") {
    return wasmGlobalToString(expected);
  } else {
    throw new Error("unknown expected result");
  }
}

class EitherVariants {
  constructor(arr) {
    this.arr = arr;
  }
  matches(v) {
    return this.arr.some((e) => compareResult(v, e));
  }
  formatExpected() {
    return `either(${this.arr.map(formatExpected).join(", ")})`;
  }
}

function compareResults(results, expected) {
  if (results.length !== expected.length) {
    return false;
  }
  for (let i in results) {
    if (expected[i] instanceof EitherVariants) {
      return expected[i].matches(results[i]);
    }
    if (!compareResult(results[i], expected[i])) {
      return false;
    }
  }
  return true;
}

function compareResult(result, expected) {
  if (
    expected === `canonical_nan` ||
    expected === `arithmetic_nan`
  ) {
    return wasmGlobalIsNaN(result, expected);
  } else if (expected === null) {
    return result.value === null;
  } else if (expected instanceof F32x4Pattern) {
    return compareResult(
      wasmGlobalExtractLane(result, "f32x4", 0),
      expected.x,
    ) &&
      compareResult(wasmGlobalExtractLane(result, "f32x4", 1), expected.y) &&
      compareResult(wasmGlobalExtractLane(result, "f32x4", 2), expected.z) &&
      compareResult(wasmGlobalExtractLane(result, "f32x4", 3), expected.w);
  } else if (expected instanceof F64x2Pattern) {
    return compareResult(
      wasmGlobalExtractLane(result, "f64x2", 0),
      expected.x,
    ) &&
      compareResult(wasmGlobalExtractLane(result, "f64x2", 1), expected.y);
  } else if (expected instanceof RefWithType) {
    return expected.test(result);
  } else if (expected instanceof ExternRefResult) {
    return expected.test(result);
  } else if (expected instanceof HostRefResult) {
    return expected.test(result);
  } else if (typeof (expected) === "object") {
    return wasmGlobalsEqual(result, expected);
  } else {
    throw new Error("unknown expected result");
  }
}