Skip to content

Instantly share code, notes, and snippets.

@xeioex
Created July 10, 2025 17:28
Show Gist options
  • Save xeioex/1540861feca6655b07b4fedee1db74a8 to your computer and use it in GitHub Desktop.
Save xeioex/1540861feca6655b07b4fedee1db74a8 to your computer and use it in GitHub Desktop.
// Copyright (C) 2017 Ecma International. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
description: |
Collection of assertion functions used throughout test262
defines: [assert]
---*/
function assert(mustBeTrue, message) {
if (mustBeTrue === true) {
return;
}
if (message === undefined) {
message = 'Expected true but got ' + assert._toString(mustBeTrue);
}
throw new Test262Error(message);
}
assert._isSameValue = function (a, b) {
if (a === b) {
// Handle +/-0 vs. -/+0
return a !== 0 || 1 / a === 1 / b;
}
// Handle NaN vs. NaN
return a !== a && b !== b;
};
assert.sameValue = function (actual, expected, message) {
try {
if (assert._isSameValue(actual, expected)) {
return;
}
} catch (error) {
throw new Test262Error(message + ' (_isSameValue operation threw) ' + error);
return;
}
if (message === undefined) {
message = '';
} else {
message += ' ';
}
message += 'Expected SameValue(«' + assert._toString(actual) + '», «' + assert._toString(expected) + '») to be true';
throw new Test262Error(message);
};
assert.notSameValue = function (actual, unexpected, message) {
if (!assert._isSameValue(actual, unexpected)) {
return;
}
if (message === undefined) {
message = '';
} else {
message += ' ';
}
message += 'Expected SameValue(«' + assert._toString(actual) + '», «' + assert._toString(unexpected) + '») to be false';
throw new Test262Error(message);
};
assert.throws = function (expectedErrorConstructor, func, message) {
var expectedName, actualName;
if (typeof func !== "function") {
throw new Test262Error('assert.throws requires two arguments: the error constructor ' +
'and a function to run');
return;
}
if (message === undefined) {
message = '';
} else {
message += ' ';
}
try {
func();
} catch (thrown) {
if (typeof thrown !== 'object' || thrown === null) {
message += 'Thrown value was not an object!';
throw new Test262Error(message);
} else if (thrown.constructor !== expectedErrorConstructor) {
expectedName = expectedErrorConstructor.name;
actualName = thrown.constructor.name;
if (expectedName === actualName) {
message += 'Expected a ' + expectedName + ' but got a different error constructor with the same name';
} else {
message += 'Expected a ' + expectedName + ' but got a ' + actualName;
}
throw new Test262Error(message);
}
return;
}
message += 'Expected a ' + expectedErrorConstructor.name + ' to be thrown but no exception was thrown at all';
throw new Test262Error(message);
};
assert._formatIdentityFreeValue = function formatIdentityFreeValue(value) {
switch (value === null ? 'null' : typeof value) {
case 'string':
return typeof JSON !== "undefined" ? JSON.stringify(value) : `"${value}"`;
case 'bigint':
return `${value}n`;
case 'number':
if (value === 0 && 1 / value === -Infinity) return '-0';
// falls through
case 'boolean':
case 'undefined':
case 'null':
return String(value);
}
};
assert._toString = function (value) {
var basic = assert._formatIdentityFreeValue(value);
if (basic) return basic;
try {
return String(value);
} catch (err) {
if (err.name === 'TypeError') {
return Object.prototype.toString.call(value);
}
throw err;
}
};
// Copyright (c) 2012 Ecma International. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
description: |
Provides both:
- An error class to avoid false positives when testing for thrown exceptions
- A function to explicitly throw an exception using the Test262Error class
defines: [Test262Error, $DONOTEVALUATE]
---*/
function Test262Error(message) {
this.message = message || "";
}
Test262Error.prototype.toString = function () {
return "Test262Error: " + this.message;
};
Test262Error.thrower = function (message) {
throw new Test262Error(message);
};
function $DONOTEVALUATE() {
throw "Test262: This statement should not be evaluated.";
}
// Copyright (C) 2017 Ecma International. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
description: |
Collection of functions used to safely verify the correctness of
property descriptors.
defines:
- verifyProperty
- verifyCallableProperty
- verifyEqualTo # deprecated
- verifyWritable # deprecated
- verifyNotWritable # deprecated
- verifyEnumerable # deprecated
- verifyNotEnumerable # deprecated
- verifyConfigurable # deprecated
- verifyNotConfigurable # deprecated
- verifyPrimordialProperty
- verifyPrimordialCallableProperty
---*/
// @ts-check
// Capture primordial functions and receiver-uncurried primordial methods that
// are used in verification but might be destroyed *by* that process itself.
var __isArray = Array.isArray;
var __defineProperty = Object.defineProperty;
var __getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var __getOwnPropertyNames = Object.getOwnPropertyNames;
var __join = Function.prototype.call.bind(Array.prototype.join);
var __push = Function.prototype.call.bind(Array.prototype.push);
var __hasOwnProperty = Function.prototype.call.bind(Object.prototype.hasOwnProperty);
var __propertyIsEnumerable = Function.prototype.call.bind(Object.prototype.propertyIsEnumerable);
var nonIndexNumericPropertyName = Math.pow(2, 32) - 1;
/**
* @param {object} obj
* @param {string|symbol} name
* @param {PropertyDescriptor|undefined} desc
* @param {object} [options]
* @param {boolean} [options.restore] revert mutations from verifying writable/configurable
*/
function verifyProperty(obj, name, desc, options) {
assert(
arguments.length > 2,
'verifyProperty should receive at least 3 arguments: obj, name, and descriptor'
);
var originalDesc = __getOwnPropertyDescriptor(obj, name);
var nameStr = String(name);
// Allows checking for undefined descriptor if it's explicitly given.
if (desc === undefined) {
assert.sameValue(
originalDesc,
undefined,
"obj['" + nameStr + "'] descriptor should be undefined"
);
// desc and originalDesc are both undefined, problem solved;
return true;
}
assert(
__hasOwnProperty(obj, name),
"obj should have an own property " + nameStr
);
assert.notSameValue(
desc,
null,
"The desc argument should be an object or undefined, null"
);
assert.sameValue(
typeof desc,
"object",
"The desc argument should be an object or undefined, " + String(desc)
);
var names = __getOwnPropertyNames(desc);
for (var i = 0; i < names.length; i++) {
assert(
names[i] === "value" ||
names[i] === "writable" ||
names[i] === "enumerable" ||
names[i] === "configurable" ||
names[i] === "get" ||
names[i] === "set",
"Invalid descriptor field: " + names[i],
);
}
var failures = [];
if (__hasOwnProperty(desc, 'value')) {
if (!isSameValue(desc.value, originalDesc.value)) {
__push(failures, "obj['" + nameStr + "'] descriptor value should be " + desc.value);
}
if (!isSameValue(desc.value, obj[name])) {
__push(failures, "obj['" + nameStr + "'] value should be " + desc.value);
}
}
if (__hasOwnProperty(desc, 'enumerable') && desc.enumerable !== undefined) {
if (desc.enumerable !== originalDesc.enumerable ||
desc.enumerable !== isEnumerable(obj, name)) {
__push(failures, "obj['" + nameStr + "'] descriptor should " + (desc.enumerable ? '' : 'not ') + "be enumerable");
}
}
// Operations past this point are potentially destructive!
if (__hasOwnProperty(desc, 'writable') && desc.writable !== undefined) {
if (desc.writable !== originalDesc.writable ||
desc.writable !== isWritable(obj, name)) {
__push(failures, "obj['" + nameStr + "'] descriptor should " + (desc.writable ? '' : 'not ') + "be writable");
}
}
if (__hasOwnProperty(desc, 'configurable') && desc.configurable !== undefined) {
if (desc.configurable !== originalDesc.configurable ||
desc.configurable !== isConfigurable(obj, name)) {
__push(failures, "obj['" + nameStr + "'] descriptor should " + (desc.configurable ? '' : 'not ') + "be configurable");
}
}
if (failures.length) {
assert(false, __join(failures, '; '));
}
if (options && options.restore) {
__defineProperty(obj, name, originalDesc);
}
return true;
}
function isConfigurable(obj, name) {
try {
delete obj[name];
} catch (e) {
if (!(e instanceof TypeError)) {
throw new Test262Error("Expected TypeError, got " + e);
}
}
return !__hasOwnProperty(obj, name);
}
function isEnumerable(obj, name) {
var stringCheck = false;
if (typeof name === "string") {
for (var x in obj) {
if (x === name) {
stringCheck = true;
break;
}
}
} else {
// skip it if name is not string, works for Symbol names.
stringCheck = true;
}
return stringCheck && __hasOwnProperty(obj, name) && __propertyIsEnumerable(obj, name);
}
function isSameValue(a, b) {
if (a === 0 && b === 0) return 1 / a === 1 / b;
if (a !== a && b !== b) return true;
return a === b;
}
function isWritable(obj, name, verifyProp, value) {
var unlikelyValue = __isArray(obj) && name === "length" ?
nonIndexNumericPropertyName :
"unlikelyValue";
var newValue = value || unlikelyValue;
var hadValue = __hasOwnProperty(obj, name);
var oldValue = obj[name];
var writeSucceeded;
if (arguments.length < 4 && newValue === oldValue) {
newValue = newValue + "2";
}
try {
obj[name] = newValue;
} catch (e) {
if (!(e instanceof TypeError)) {
throw new Test262Error("Expected TypeError, got " + e);
}
}
writeSucceeded = isSameValue(obj[verifyProp || name], newValue);
// Revert the change only if it was successful (in other cases, reverting
// is unnecessary and may trigger exceptions for certain property
// configurations)
if (writeSucceeded) {
if (hadValue) {
obj[name] = oldValue;
} else {
delete obj[name];
}
}
return writeSucceeded;
}
/**
* Verify that there is a function of specified name, length, and containing
* descriptor associated with `obj[name]` and following the conventions for
* built-in objects.
*
* @param {object} obj
* @param {string|symbol} name
* @param {string} [functionName] defaults to name for strings, `[${name.description}]` for symbols
* @param {number} functionLength
* @param {PropertyDescriptor} [desc] defaults to data property conventions (writable, non-enumerable, configurable)
* @param {object} [options]
* @param {boolean} [options.restore] revert mutations from verifying writable/configurable
*/
function verifyCallableProperty(obj, name, functionName, functionLength, desc, options) {
var value = obj[name];
assert.sameValue(typeof value, "function",
"obj['" + String(name) + "'] descriptor should be a function");
// Every other data property described in clauses 19 through 28 and in
// Annex B.2 has the attributes { [[Writable]]: true, [[Enumerable]]: false,
// [[Configurable]]: true } unless otherwise specified.
// https://tc39.es/ecma262/multipage/ecmascript-standard-built-in-objects.html
if (desc === undefined) {
desc = {
writable: true,
enumerable: false,
configurable: true,
value: value
};
} else if (!__hasOwnProperty(desc, "value") && !__hasOwnProperty(desc, "get")) {
desc.value = value;
}
verifyProperty(obj, name, desc, options);
if (functionName === undefined) {
if (typeof name === "symbol") {
functionName = "[" + name.description + "]";
} else {
functionName = name;
}
}
// Unless otherwise specified, the "name" property of a built-in function
// object has the attributes { [[Writable]]: false, [[Enumerable]]: false,
// [[Configurable]]: true }.
// https://tc39.es/ecma262/multipage/ecmascript-standard-built-in-objects.html#sec-ecmascript-standard-built-in-objects
// https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-setfunctionname
verifyProperty(value, "name", {
value: functionName,
writable: false,
enumerable: false,
configurable: desc.configurable
}, options);
// Unless otherwise specified, the "length" property of a built-in function
// object has the attributes { [[Writable]]: false, [[Enumerable]]: false,
// [[Configurable]]: true }.
// https://tc39.es/ecma262/multipage/ecmascript-standard-built-in-objects.html#sec-ecmascript-standard-built-in-objects
// https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-setfunctionlength
verifyProperty(value, "length", {
value: functionLength,
writable: false,
enumerable: false,
configurable: desc.configurable
}, options);
}
/**
* Deprecated; please use `verifyProperty` in new tests.
*/
function verifyEqualTo(obj, name, value) {
if (!isSameValue(obj[name], value)) {
throw new Test262Error("Expected obj[" + String(name) + "] to equal " + value +
", actually " + obj[name]);
}
}
/**
* Deprecated; please use `verifyProperty` in new tests.
*/
function verifyWritable(obj, name, verifyProp, value) {
if (!verifyProp) {
assert(__getOwnPropertyDescriptor(obj, name).writable,
"Expected obj[" + String(name) + "] to have writable:true.");
}
if (!isWritable(obj, name, verifyProp, value)) {
throw new Test262Error("Expected obj[" + String(name) + "] to be writable, but was not.");
}
}
/**
* Deprecated; please use `verifyProperty` in new tests.
*/
function verifyNotWritable(obj, name, verifyProp, value) {
if (!verifyProp) {
assert(!__getOwnPropertyDescriptor(obj, name).writable,
"Expected obj[" + String(name) + "] to have writable:false.");
}
if (isWritable(obj, name, verifyProp)) {
throw new Test262Error("Expected obj[" + String(name) + "] NOT to be writable, but was.");
}
}
/**
* Deprecated; please use `verifyProperty` in new tests.
*/
function verifyEnumerable(obj, name) {
assert(__getOwnPropertyDescriptor(obj, name).enumerable,
"Expected obj[" + String(name) + "] to have enumerable:true.");
if (!isEnumerable(obj, name)) {
throw new Test262Error("Expected obj[" + String(name) + "] to be enumerable, but was not.");
}
}
/**
* Deprecated; please use `verifyProperty` in new tests.
*/
function verifyNotEnumerable(obj, name) {
assert(!__getOwnPropertyDescriptor(obj, name).enumerable,
"Expected obj[" + String(name) + "] to have enumerable:false.");
if (isEnumerable(obj, name)) {
throw new Test262Error("Expected obj[" + String(name) + "] NOT to be enumerable, but was.");
}
}
/**
* Deprecated; please use `verifyProperty` in new tests.
*/
function verifyConfigurable(obj, name) {
assert(__getOwnPropertyDescriptor(obj, name).configurable,
"Expected obj[" + String(name) + "] to have configurable:true.");
if (!isConfigurable(obj, name)) {
throw new Test262Error("Expected obj[" + String(name) + "] to be configurable, but was not.");
}
}
/**
* Deprecated; please use `verifyProperty` in new tests.
*/
function verifyNotConfigurable(obj, name) {
assert(!__getOwnPropertyDescriptor(obj, name).configurable,
"Expected obj[" + String(name) + "] to have configurable:false.");
if (isConfigurable(obj, name)) {
throw new Test262Error("Expected obj[" + String(name) + "] NOT to be configurable, but was.");
}
}
/**
* Use this function to verify the properties of a primordial object.
* For non-primordial objects, use verifyProperty.
* See: https://github.com/tc39/how-we-work/blob/main/terminology.md#primordial
*/
var verifyPrimordialProperty = verifyProperty;
/**
* Use this function to verify the primordial function-valued properties.
* For non-primordial functions, use verifyCallableProperty.
* See: https://github.com/tc39/how-we-work/blob/main/terminology.md#primordial
*/
var verifyPrimordialCallableProperty = verifyCallableProperty;
// Copyright (C) 2015 André Bargull. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
description: |
Collection of functions used to assert the correctness of TypedArray objects.
defines:
- floatArrayConstructors
- nonClampedIntArrayConstructors
- intArrayConstructors
- typedArrayConstructors
- TypedArray
- testWithTypedArrayConstructors
- nonAtomicsFriendlyTypedArrayConstructors
- testWithAtomicsFriendlyTypedArrayConstructors
- testWithNonAtomicsFriendlyTypedArrayConstructors
- testTypedArrayConversions
---*/
var floatArrayConstructors = [
Float64Array,
Float32Array
];
var nonClampedIntArrayConstructors = [
Int32Array,
Int16Array,
Int8Array,
Uint32Array,
Uint16Array,
Uint8Array
];
var intArrayConstructors = nonClampedIntArrayConstructors.concat([Uint8ClampedArray]);
// Float16Array is a newer feature
// adding it to this list unconditionally would cause implementations lacking it to fail every test which uses it
if (typeof Float16Array !== 'undefined') {
floatArrayConstructors.push(Float16Array);
}
/**
* Array containing every non-bigint typed array constructor.
*/
var typedArrayConstructors = floatArrayConstructors.concat(intArrayConstructors);
/**
* The %TypedArray% intrinsic constructor function.
*/
var TypedArray = Object.getPrototypeOf(Int8Array);
/**
* Callback for testing a typed array constructor.
*
* @callback typedArrayConstructorCallback
* @param {Function} Constructor the constructor object to test with.
*/
/**
* Calls the provided function for every typed array constructor.
*
* @param {typedArrayConstructorCallback} f - the function to call for each typed array constructor.
* @param {Array} selected - An optional Array with filtered typed arrays
*/
function testWithTypedArrayConstructors(f, selected) {
var constructors = selected || typedArrayConstructors;
for (var i = 0; i < constructors.length; ++i) {
var constructor = constructors[i];
try {
f(constructor);
} catch (e) {
e.message += " (Testing with " + constructor.name + ".)";
throw e;
}
}
}
var nonAtomicsFriendlyTypedArrayConstructors = floatArrayConstructors.concat([Uint8ClampedArray]);
/**
* Calls the provided function for every non-"Atomics Friendly" typed array constructor.
*
* @param {typedArrayConstructorCallback} f - the function to call for each typed array constructor.
* @param {Array} selected - An optional Array with filtered typed arrays
*/
function testWithNonAtomicsFriendlyTypedArrayConstructors(f) {
testWithTypedArrayConstructors(f, nonAtomicsFriendlyTypedArrayConstructors);
}
/**
* Calls the provided function for every "Atomics Friendly" typed array constructor.
*
* @param {typedArrayConstructorCallback} f - the function to call for each typed array constructor.
* @param {Array} selected - An optional Array with filtered typed arrays
*/
function testWithAtomicsFriendlyTypedArrayConstructors(f) {
testWithTypedArrayConstructors(f, [
Int32Array,
Int16Array,
Int8Array,
Uint32Array,
Uint16Array,
Uint8Array,
]);
}
/**
* Helper for conversion operations on TypedArrays, the expected values
* properties are indexed in order to match the respective value for each
* TypedArray constructor
* @param {Function} fn - the function to call for each constructor and value.
* will be called with the constructor, value, expected
* value, and a initial value that can be used to avoid
* a false positive with an equivalent expected value.
*/
function testTypedArrayConversions(byteConversionValues, fn) {
var values = byteConversionValues.values;
var expected = byteConversionValues.expected;
testWithTypedArrayConstructors(function(TA) {
var name = TA.name.slice(0, -5);
return values.forEach(function(value, index) {
var exp = expected[name][index];
var initial = 0;
if (exp === 0) {
initial = 1;
}
fn(TA, value, exp, initial);
});
});
}
/**
* Checks if the given argument is one of the float-based TypedArray constructors.
*
* @param {constructor} ctor - the value to check
* @returns {boolean}
*/
function isFloatTypedArrayConstructor(arg) {
return floatArrayConstructors.indexOf(arg) !== -1;
}
/**
* Determines the precision of the given float-based TypedArray constructor.
*
* @param {constructor} ctor - the value to check
* @returns {string} "half", "single", or "double" for Float16Array, Float32Array, and Float64Array respectively.
*/
function floatTypedArrayConstructorPrecision(FA) {
if (typeof Float16Array !== "undefined" && FA === Float16Array) {
return "half";
} else if (FA === Float32Array) {
return "single";
} else if (FA === Float64Array) {
return "double";
} else {
throw new Error("Malformed test - floatTypedArrayConstructorPrecision called with non-float TypedArray");
}
}
// Copyright (C) 2021 Alexey Shvayka. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
esid: sec-integer-indexed-exotic-objects-set-p-v-receiver
description: >
If receiver is altered, OrdinarySet result is returned for valid indices.
Value is not coerced.
info: |
[[Set]] ( P, V, Receiver )
[...]
2. If Type(P) is String, then
a. Let numericIndex be ! CanonicalNumericIndexString(P).
b. If numericIndex is not undefined, then
[...]
3. Return ? OrdinarySet(O, P, V, Receiver).
includes: [testTypedArray.js]
features: [TypedArray, Proxy]
---*/
testWithTypedArrayConstructors(function(TA) {
var target, receiver;
Object.defineProperty(TA.prototype, 0, {
set: function(_v) { throw new Test262Error("0 setter should be unreachable!"); },
configurable: true,
});
target = new TA([0]);
receiver = Object.create(target);
receiver[0] = 1;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment