Four short programs, each with breakpoints set where the specification's algorithms do the work. The debugger's guided script for them, stop by stop, is docs/debugger/DEMO.md.
GetValue calls the object's [[Get]], which is OrdinaryGet; for a property the object lacks, OrdinaryGet calls its prototype's [[Get]] with the same receiver.
Open in the debugger: The specification
Opened with breakpoints at sec-ordinaryget 1.
- The specification: pauses at
OrdinaryGet 1, then OrdinaryGet 1, then OrdinaryGet 1; ends normal: 8.
Source tools/dbg/demo/get.js
let proto = { z: 5 };
let point = { x: 3, __proto__: proto };
let a = point.x;
let b = point.z;
a + b;
EvaluateCall evaluates the arguments and calls Call, the function's [[Call]] makes a new execution context, and OrdinaryCallEvaluateBody runs the body.
Open in the debugger: The specification
Opened with breakpoints at sec-evaluatecall 7, sec-ordinarycallevaluatebody 1.
- The specification: pauses at
EvaluateCall 7, then OrdinaryCallEvaluateBody 1; ends normal: 5.
Source tools/dbg/demo/call.js
function add(a, b) {
var s = a + b;
return s;
}
var r = add(2, 3);
r;
ForIn/OfBodyEvaluation asks the iterator for its next result at step 8.a once per round, and once more to find that it is done.
Open in the debugger: The specification
Opened with breakpoints at ForIn/OfBodyEvaluation 8.a.
- The specification: pauses at
ForIn/OfBodyEvaluation 8.a, then ForIn/OfBodyEvaluation 8.a, then ForIn/OfBodyEvaluation 8.a; ends normal: 30.
Source tools/dbg/demo/forof.js
let sum = 0;
for (const v of [10, 20]) {
sum = sum + v;
}
sum;
The throw statement's Evaluation makes a throw completion inside the called function; it returns through [[Call]] to the try statement, and CatchClauseEvaluation binds it.
Open in the debugger: The specification
Opened with breakpoints at sec-runtime-semantics-catchclauseevaluation 1; pauses on throw completions.
- The specification: pauses at
sec-throw-statement-runtime-semantics-evaluation 3, then CatchClauseEvaluation 1; ends normal: "negative".
Source tools/dbg/demo/throw.js
function check(n) {
if (n < 0) throw new RangeError("negative");
return n;
}
let msg;
try {
check(-1);
} catch (e) {
msg = e.message;
}
msg;
Ordinary JavaScript, paused in the algorithms that give it its meaning: environments, calls into built-ins, eval, generators, modules.
The worked example of How it works. EvaluateCall asks IsCallable of each callee that is an Object: a function has a [[Call]] internal method, and step 2 returns true; an ordinary object has none, step 3 returns false, and the call throws a TypeError.
Open in the debugger: The specification
Opened with breakpoints at sec-iscallable 2, sec-iscallable 3.
- The specification: pauses at
IsCallable 2, then IsCallable 2, then IsCallable 2, then IsCallable 2, then IsCallable 3; ends normal: "function|TypeError".
Source tests/run/iscallable.js
// expect: normal: "function|TypeError"
// IsCallable (§7.2.3), asked by EvaluateCall of a callee that is an Object: a function
// has a [[Call]] internal method (step 2 returns true); an ordinary object has none,
// step 3 returns false, and the call throws a TypeError.
function f() { return "function"; }
var o = {};
var r = f();
try { o(); } catch (e) { r += "|" + e.constructor.name; }
r;
The declarative Environment Record's GetBindingValue finds the binding uninitialized and throws a ReferenceError, which the catch clause receives.
Open in the debugger: The specification
Opened with breakpoints at sec-declarative-environment-records-getbindingvalue-n-s.
- The specification: pauses at
sec-declarative-environment-records-getbindingvalue-n-s 1; ends normal: "ReferenceError".
Source tests/run/s2_let_tdz.js
// S2 end to end: reading a let binding before its declaration throws a ReferenceError.
// expect: normal: "ReferenceError"
try { t; let t = 1; } catch (e) { e.name }
ForBodyEvaluation calls CreatePerIterationEnvironment before the first round and after each, so each round has its own binding of i.
Open in the debugger: The specification
Opened with breakpoints at sec-createperiterationenvironment.
- The specification: pauses at
CreatePerIterationEnvironment 1, then CreatePerIterationEnvironment 1; ends normal: 1.
Source tests/dbg/loop.js
var s = 0;
for (let i = 0; i < 3; i++) {
s = s + i;
}
while (s > 1) s = s - 2;
OrdinaryGet finds an accessor descriptor and, at step 7, calls its getter with the receiver as this; the getter's body runs in OrdinaryCallEvaluateBody.
Open in the debugger: The specification
Opened with breakpoints at sec-ordinaryget 7, sec-ordinarycallevaluatebody 1.
- The specification: pauses at
OrdinaryGet 7, then OrdinaryCallEvaluateBody 1; ends normal: [object #N].
Source tests/dbg/getter.js
var o = {};
Object.defineProperty(o, "v", { get: function () {
var k = 41;
return k + 1;
} });
var w = o.v;
Array.prototype.map runs as a built-in function's steps under BuiltinCallOrConstruct, and calls the callback for each element; the JS stack shows the built-in between the two functions.
Open in the debugger: The specification
Opened with breakpoints at sec-array.prototype.map, sec-ordinarycallevaluatebody 1.
- The specification: pauses at
Array.prototype.map 1, then OrdinaryCallEvaluateBody 1; ends normal: undefined.
Source tests/dbg/map.js
var a = [1, 2].map(function (x) {
var y = x * 10;
return y;
});
var b = a.map(function (x) { return x + 1; });
A direct eval goes through PerformEval and new Function through CreateDynamicFunction; each parses its own source text, which the debugger opens as a source of its own.
Open in the debugger: The specification
Opened with breakpoints at sec-performeval, sec-createdynamicfunction.
- The specification: pauses at
PerformEval 1, then CreateDynamicFunction 1; ends normal: undefined; prints 10.
Source tests/dbg/eval.js
var a = 1;
var b = eval("var c = a + 1;\nc * 2");
var f = new Function("x", "var y = x + 1;\nreturn y * 2;");
var r = f(b);
print(r);
Each yield is GeneratorYield, which suspends the generator's execution context; next() resumes it through GeneratorResume.
Open in the debugger: The specification
Opened with breakpoints at sec-generatoryield.
- The specification: pauses at
GeneratorYield 1, then GeneratorYield 1; ends normal: 3.
Source tests/dbg/generator.js
function* g() {
var a = 1;
yield a;
a = a + 1;
yield a;
}
var it = g();
var x = it.next().value;
x = x + it.next().value;
"use strict" followed by .length on the next line is one expression statement, not a Use Strict Directive: IsStrict finds the script non-strict.
Open in the debugger: The specification
Opened with breakpoints at sec-isstrict.
- The specification: pauses at
IsStrict 1; ends normal: 10.
Source tests/dbg/strict.js
"use strict"
.length;
debugger;
Each debugger statement pauses; the Heap tab shows the object's cell, and after the assignment the cell that changed.
Open in the debugger: The specification
Opened with pauses on debugger statements.
- The specification: pauses at
sec-debugger-statement-runtime-semantics-evaluation 1, then sec-debugger-statement-runtime-semantics-evaluation 1, then sec-debugger-statement-runtime-semantics-evaluation 1; ends normal: 2.
Source tests/dbg/heap.js
debugger;
var o = {a: 1};
debugger;
o.a = 2;
debugger;
The entry module's LoadRequestedModules, then Link, then Evaluate; each module of the bundle opens as a source of its own.
Open in the debugger: The specification
Opened with breakpoints at sec-LoadRequestedModules, sec-moduledeclarationlinking, sec-moduleevaluation.
- The specification: pauses at
LoadRequestedModules 1, then Link 1, then Evaluate 1; ends normal: undefined; prints 42.
Source tests/dbg/bundle.js
// Flags: --bundle
// JS_BUNDLE_MODULE:lib/math.mjs
export function double(x) {
return x * 2;
}
// JS_BUNDLE_MODULE:lib/show.mjs
import { double } from "./math.mjs";
export function show(x) {
print(double(x));
}
// JS_BUNDLE_MODULE_ENTRYPOINT:main.mjs
import { show } from "./lib/show.mjs";
show(21);
Programs that go where fewer readers go: Proxy traps, the job queue, using declarations, with, Annex B, regular expressions, top-level await, timeouts, iterator helpers.
A get on a Proxy is the Proxy's own [[Get]], which calls the handler's get trap; every other trap is called the same way, and a missing one forwards to the target.
Open in the debugger: The specification
Opened with breakpoints at sec-proxy-object-internal-methods-and-internal-slots-get-p-receiver.
- The specification: pauses at
sec-proxy-object-internal-methods-and-internal-slots-get-p-receiver 1; ends normal: "get:a,has:a,set:b,getOwnPropertyDescriptor:b,defineProperty:b,delete:b,ownKeys,getOwnPropertyDescriptor:a,defineProperty:c,getPrototypeOf,setPrototypeOf,isExtensible,preventExtensions|1|true|2|a,c|true".
Source tests/run/proxy_traps.js
// Proxy exotic objects (§10.5): every trap is called with the target, and a
// missing trap forwards to the target. Reflect.set with the Proxy as receiver
// defines the property through the Proxy (OrdinarySetWithOwnDescriptor, §10.1.9.2).
// expect: normal: "get:a,has:a,set:b,getOwnPropertyDescriptor:b,defineProperty:b,delete:b,ownKeys,getOwnPropertyDescriptor:a,defineProperty:c,getPrototypeOf,setPrototypeOf,isExtensible,preventExtensions|1|true|2|a,c|true"
var log = [];
var target = { a: 1 };
var handler = {
get: function (t, k, r) { log.push("get:" + String(k)); return Reflect.get(t, k, r); },
has: function (t, k) { log.push("has:" + String(k)); return k in t; },
set: function (t, k, v, r) { log.push("set:" + String(k)); return Reflect.set(t, k, v, r); },
deleteProperty: function (t, k) { log.push("delete:" + String(k)); return delete t[k]; },
ownKeys: function (t) { log.push("ownKeys"); return Reflect.ownKeys(t); },
getOwnPropertyDescriptor: function (t, k) {
log.push("getOwnPropertyDescriptor:" + String(k));
return Object.getOwnPropertyDescriptor(t, k);
},
defineProperty: function (t, k, d) { log.push("defineProperty:" + String(k)); return Reflect.defineProperty(t, k, d); },
getPrototypeOf: function (t) { log.push("getPrototypeOf"); return Object.getPrototypeOf(t); },
setPrototypeOf: function (t, p) { log.push("setPrototypeOf"); return Reflect.setPrototypeOf(t, p); },
isExtensible: function (t) { log.push("isExtensible"); return Object.isExtensible(t); },
preventExtensions: function (t) { log.push("preventExtensions"); return Reflect.preventExtensions(t); }
};
var p = new Proxy(target, handler);
var a = p.a;
var has = "a" in p;
p.b = 2;
var b = target.b;
delete p.b;
Reflect.ownKeys(p);
Object.getOwnPropertyDescriptor(p, "a");
Object.defineProperty(p, "c", { value: 3, configurable: true, enumerable: true });
Object.getPrototypeOf(p);
Object.setPrototypeOf(p, Object.prototype);
Object.isExtensible(p);
Object.preventExtensions(p);
log.join(",") + "|" + a + "|" + has + "|" + b + "|" + Object.keys(target).join(",") + "|" +
(Object.isExtensible(target) === false)
then calls PerformPromiseThen, which makes a job with NewPromiseReactionJob; the jobs run after the script in the order they were queued, and resolving with a promise takes two more.
Open in the debugger: The specification
Opened with breakpoints at sec-newpromisereactionjob.
- The specification: pauses at
NewPromiseReactionJob 1; ends normal: "0"; prints 0,1,2,3,4, b,c,a,d.
Source tests/run/promise_job_order.js
// expect: normal: "0"
// print: 0,1,2,3,4
// print: b,c,a,d
// Promise jobs run in FIFO order after the Script (§9.5, §27.5.2); resolving
// with a promise takes two more jobs (NewPromiseResolveThenableJob, then the
// reaction that resolves).
var log = [];
Promise.resolve().then(function () { log.push(1); }).then(function () { log.push(3); });
Promise.resolve().then(function () { log.push(2); }).then(function () { log.push(4); print(log.join(",")); });
var order = [];
var p = Promise.resolve(1);
new Promise(function (r) { r(p); }).then(function () { order.push("a"); });
p.then(function () { order.push("b"); }).then(function () { order.push("c"); })
.then(function () { order.push("d"); print(order.join(",")); });
log.push(0);
log.join(",")
At the end of the block, DisposeResources calls each resource's dispose method in the reverse order of the declarations; DisposableStack.prototype.dispose does the same.
Open in the debugger: The specification
Opened with breakpoints at sec-disposeresources.
- The specification: pauses at
DisposeResources 1; ends normal: "b,a,s".
Source tests/run/using_dispose.js
// `using` declarations (§14.3.1) dispose their resources in reverse order when
// the Block ends (DisposeResources, §7.5.5); DisposableStack.prototype.use too.
// expect: normal: "b,a,s"
var log = [];
function res(n) { return { [Symbol.dispose]() { log.push(n); } }; }
{
using a = res("a"), b = res("b");
}
var stack = new DisposableStack();
stack.use(res("s"));
stack.dispose();
log.join()
Inside with, ResolveBinding goes through GetIdentifierReference to the object Environment Record's HasBinding, which reads @@unscopables.
Open in the debugger: The specification
Opened with breakpoints at sec-object-environment-records-hasbinding-n.
- The specification: pauses at
sec-object-environment-records-hasbinding-n 1; ends normal: "1,5,outer,undefined,2".
Source tests/run/s2_with.js
// The with statement (§14.11): names resolve in the object first, assignments
// go to its properties, @@unscopables hides names, and the scope ends after.
// expect: normal: "1,5,outer,undefined,2"
var v = "outer", a = 0, o = { a: 1, v: 2 };
var r = [];
with (o) { r.push(a); v = 5; }
r.push(o.v, v);
o[Symbol.unscopables] = { a: true };
with (o) { r.push(typeof b); a = 2; }
r.push(a);
r.join()
With the host a web browser, FunctionDeclarationInstantiation also gives the enclosing function a var binding of the block's function (B.3.2.1): typeof f is undefined before the block and function after it.
Open in the debugger: The specification
Opened with breakpoints at sec-functiondeclarationinstantiation.
Run with --web-browser.
- The specification: pauses at
FunctionDeclarationInstantiation 1; ends normal: "undefined,function,2".
Source tests/run/annexb_block_function.js
// On a web-browser host, a FunctionDeclaration in a Block is also a var of the
// enclosing function (§B.3.2.1), set when the declaration is evaluated.
// args: --web-browser
// expect: normal: "undefined,function,2"
function g() {
var before = typeof f;
{ function f() { return 2; } }
return [before, typeof f, f()].join();
}
g()
Two groups of one name are an early error unless MightBothParticipate finds them in different alternatives; the check runs while the pattern is parsed.
Open in the debugger: The specification
Opened with breakpoints at sec-mightbothparticipate.
- The specification: pauses at
MightBothParticipate 1; ends normal: undefined; prints SyntaxError SyntaxError SyntaxError ok ok, SyntaxError, y.
Source tests/run/regexp_duplicate_named_groups.js
// Two GroupSpecifiers with one CapturingGroupName are a SyntaxError unless
// some Disjunction has them in different Alternatives (§22.2.1.1, Pattern ::
// Disjunction; MightBothParticipate, §22.2.1.4), in nested Disjunctions too,
// for new RegExp and for a RegularExpressionLiteral (§13.2.7.2).
// expect: normal: undefined
// print: SyntaxError SyntaxError SyntaxError ok ok
// print: SyntaxError
// print: y
function t(s) { try { new RegExp(s); return "ok"; } catch (e) { return e.name; } }
print(t("(?:(?<a>x)|y)(?:z|(?<a>w))") + " " + t("(?<a>x)(?:|(?<a>z))") + " " + t("(?<a>(?<a>x))") + " " +
t("(?<a>x)|(?<a>y)") + " " + t("((?<a>x)|y|(?:z|(?<a>w)))"));
try { eval("/(?:(?<a>x)|y)(?:z|(?<a>w))\\k<a>/"); print("parsed"); } catch (e) { print(e.name); }
print(/(?:(?<a>x)|(?<a>y))\k<a>/.exec("yy").groups.a);
A module whose body awaits is evaluated by ExecuteAsyncModule, which runs the body with AsyncBlockStart, so the rest of the body runs from the promise jobs. Read literally, AsyncBlockStart's step 4 has no answer (erratum AsyncBlockStartAwaitResult) and the run stops there.
Open in the debugger: The specification Open in the debugger: The literal text
Opened with breakpoints at sec-asyncblockstart; pauses on the machine's stops.
Run with --module.
- The specification: pauses at
AsyncBlockStart 1; ends normal: undefined; prints before, 3 after. - The literal text: pauses at
AsyncBlockStart 1, then AsyncBlockStart 4; ends stop: erratum AsyncBlockStartAwaitResult sec-asyncblockstart#0 4.
Source tests/run/module_top_level_await.js
// module: yes
// expect: normal: undefined
// print: before
// print: 3 after
// A Module whose body contains `await` has [[HasTLA]] true: ExecuteModule
// runs it with AsyncBlockStart (§16.2.1.7.3.2 step 4.b), so the body suspends
// at each Await and the rest of it runs from the promise jobs.
print("before");
var a = await Promise.resolve(1);
var b = await 2;
print((a + b) + " after");
The test host's setTimeout performs HostEnqueueTimeoutJob: the promise jobs run first, then each timeout job once its delay has passed on the host's clock.
Open in the debugger: The specification
- The specification: ends
normal: undefined; prints function,2,undefined, sync, promise, t0, t5, t10,true.
Source tests/run/settimeout_order.js
// expect: normal: undefined
// print: function,2,undefined
// print: sync
// print: promise
// print: t0
// print: t5
// print: t10,true
// setTimeout (the test host's global) performs HostEnqueueTimeoutJob of a Job that calls its callback:
// the promise Jobs run first, then each timeout Job once its delay has passed; a negative delay is 0.
var before = Date.now();
print([typeof setTimeout, setTimeout.length, typeof setTimeout(function () { print("t0"); }, -3)].join(","));
setTimeout(function () { print("t5"); }, 5);
setTimeout(function () { print(["t10", Date.now() - before >= 10].join(",")); }, 10);
Promise.resolve().then(function () { print("promise"); });
print("sync");
Iterator.prototype.map and the other helpers make iterator objects whose next runs the helper's steps; Iterator.from, concat and zip build on the same protocol.
Open in the debugger: The specification
Opened with breakpoints at sec-iterator.prototype.map.
- The specification: pauses at
Iterator.prototype.map 1; ends normal: "10,30,50|2,3|3,4,5|1,1,2,2|15|true,false,3|1+2|a,b,c|1:x,2:y|u,v,w".
Source tests/run/iterator_helpers.js
// expect: normal: "10,30,50|2,3|3,4,5|1,1,2,2|15|true,false,3|1+2|a,b,c|1:x,2:y|u,v,w"
// Iterator helpers (§27.1.3.3), Iterator.from, Iterator.concat and Iterator.zip (§27.1.3.2).
var parts = [];
parts.push([1, 2, 3, 4, 5].values().filter(function (x) { return x % 2; })
.map(function (x) { return x * 10; }).toArray().join(","));
parts.push([1, 2, 3, 4].values().drop(1).take(2).toArray().join(","));
parts.push([1, 2, 3, 4, 5].values().drop(2).toArray().join(","));
parts.push([1, 2].values().flatMap(function (x) { return [x, x]; }).toArray().join(","));
parts.push([1, 2, 3, 4, 5].values().reduce(function (a, b) { return a + b; }));
parts.push([[1, 2].values().some(function (x) { return x > 1; }),
[1, 2].values().every(function (x) { return x > 1; }),
[1, 2, 3].values().find(function (x) { return x > 2; })].join(","));
var seen = [];
[1, 2].values().forEach(function (x) { seen.push(x); });
parts.push(seen.join("+"));
var n = 0;
var plain = { next: function () { n++; return n <= 3 ? { value: "abc"[n - 1], done: false } : { done: true }; } };
parts.push(Iterator.from(plain).toArray().join(","));
parts.push(Iterator.zip([[1, 2], ["x", "y", "z"]]).map(function (p) { return p.join(":"); }).toArray().join(","));
parts.push(Iterator.concat(["u"], ["v", "w"]).toArray().join(","));
parts.join("|")
Each of these programs reaches a sentence the formalisation reads in more than one way (an erratum). Under the specification's build it runs with the default reading; under the literal text's build it shows what the sentence says as written. Where the default reading is itself the literal one, the run stops in both builds, at the step where the text gives no answer.
Number::multiply step 6 gives 𝔽(0), which is +0, where IEEE 754 and every engine give −0. The default reading gives −0, so 1 / (0 * -5) is -Infinity; the literal text gives +0 and Infinity.
Open in the debugger: The specification Open in the debugger: The literal text
Opened with breakpoints at sec-numeric-types-number-multiply 6.
- The specification: pauses at
Number::multiply 6; ends normal: undefined; prints -Infinity,-Infinity,Infinity,-Infinity,Infinity,Infinity,-Infinity. - The literal text: pauses at
Number::multiply 6; ends normal: undefined; prints Infinity,Infinity,Infinity,-Infinity,Infinity,Infinity,-Infinity.
Source tests/run/number_multiply_zero_sign.js
// expect: normal: undefined
// print: -Infinity,-Infinity,Infinity,-Infinity,Infinity,Infinity,-Infinity
// Number::multiply step 6 gives 𝔽(0) = +0 for +0 × -5; the clause's
// description (IEEE 754-2019) and every engine give -0 (Erratum
// NumberMultiplyZeroSign, read by default as proposed: no test262 assertion
// covers the case). A product that underflows keeps
// its sign by 𝔽 itself.
print(String([1 / (0 * -5), 1 / (-5 * 0), 1 / (0 * 5), 1 / (-0 * 5), 1 / (-0 * -5), 1 / (0 * 0),
1 / (1e-300 * -1e-300)]));
SortIndexedProperties takes ℝ of the comparator's result, which ±∞ does not have. The default reading orders by the result's sign; the literal text stops in SortIndexedProperties.
Open in the debugger: The specification Open in the debugger: The literal text
Opened with breakpoints at sec-sortindexedproperties; pauses on the machine's stops.
- The specification: pauses at
SortIndexedProperties 1; ends normal: "1,2,3|3,2,1". - The literal text: pauses at
SortIndexedProperties 1; ends stop: sortError sec-sortindexedproperties#0 ?.
Source tests/run/errata_sort_infinite_comparator.js
// expect: normal: "1,2,3|3,2,1"
// A comparator that returns ±Infinity (Erratum SortInfiniteComparator): under
// the test262 reading the order is the host's, and the test host's goes by the
// result's sign.
var r = [];
r.push([3, 1, 2].sort(function (a, b) { return a < b ? -Infinity : a > b ? Infinity : 0; }).join());
r.push([1, 3, 2].sort(function (a, b) { return a < b ? Infinity : a > b ? -Infinity : 0; }).join());
r.join("|");
IsLabelledFunction takes "the LabelledItem of" a Statement that has one only through its chain of single children. The default reading follows the chain and the early error makes it a SyntaxError; the literal text stops at IsLabelledFunction step 2.
Open in the debugger: The specification Open in the debugger: The literal text
Opened with breakpoints at sec-islabelledfunction; pauses on the machine's stops.
Run with --web-browser.
- The specification: pauses at
IsLabelledFunction 1; ends throw: SyntaxError. - The literal text: pauses at
IsLabelledFunction 1; ends stop: sortError sec-islabelledfunction#0 2.
Source tests/run/erratum_unit_chain_child.js
// IsLabelledFunction takes "the |LabelledItem| of" a |Statement| node through
// its unit chain (Erratum UnitChainChild, test262's reading): the labelled
// function in an if body is the Early Error of sec-if-statement-static-semantics-early-errors.
// args: --web-browser
// expect: throw: SyntaxError
if (1) l: function f() {}
An async function's body runs under AsyncBlockStart and suspends at each await. Its step 4, read literally, has no answer for the result of the body's last await, and the run stops there; the default reading goes on, and the function's promise resolves to 2.
Open in the debugger: The specification Open in the debugger: The literal text
Opened with breakpoints at sec-asyncblockstart; pauses on the machine's stops.
- The specification: pauses at
AsyncBlockStart 1; ends normal: [object #N]; prints 2. - The literal text: pauses at
AsyncBlockStart 1, then AsyncBlockStart 4; ends stop: erratum AsyncBlockStartAwaitResult sec-asyncblockstart#0 4.
Source tests/dbg/async.js
async function h() {
var a = 1;
await a;
a = a + 1;
return a;
}
var p = h();
p.then(function (v) { print(v); });
var z = 3;
On a host whose agent can block, DoWait waits until its timeout. The default reading gives the woken waiter the result "timed-out" and removes it from the WaiterList; as the text is written it returns "ok" and leaves the waiter in the WaiterList, so the second Atomics.wait fails AddWaiter step 2's Assert.
Open in the debugger: The specification Open in the debugger: The literal text
Opened with breakpoints at sec-dowait; pauses on the machine's stops.
Run with --can-block.
- The specification: pauses at
DoWait 1; ends normal: undefined; prints timed-out,timed-out,true,true,0 ; not-equal. - The literal text: pauses at
DoWait 1, then DoWait 1, then AddWaiter 2; ends stop: erratum DoWaitSyncTimeout sec-addwaiter#0 2.
Source tests/run/atomics_wait_sync_timeout.js
// Atomics.wait on an agent that can block (§25.4.3.14, SuspendThisAgent
// §25.4.3.11): with one agent nothing notifies the waiter, so it wakes when
// the host's clock reaches its timeout time. Erratum DoWaitSyncTimeout: the
// woken waiter's [[Result]] is "timed-out" and it leaves the WaiterList, so a
// second wait on the same location does not fail AddWaiter step 2's Assert
// and a later Atomics.notify finds no waiter.
// args: --can-block
// expect: normal: undefined
// print: timed-out,timed-out,true,true,0 ; not-equal
var i32 = new Int32Array(new SharedArrayBuffer(8));
var t0 = Date.now();
var first = Atomics.wait(i32, 0, 0, 10);
var t1 = Date.now();
var second = Atomics.wait(i32, 0, 0, 5);
var t2 = Date.now();
var notified = Atomics.notify(i32, 0);
Atomics.store(i32, 1, 3);
print([first, second, t1 - t0 >= 10, t2 - t1 >= 5, notified].join() + " ; " + Atomics.wait(i32, 1, 0, 10));
void 0;
CreateDynamicFunction parses the parameters and the body on their own, where a private name refers to no class. The default reading makes that a SyntaxError for both (test262 requires it of the body); the literal text has no such check and makes the function.
Open in the debugger: The specification Open in the debugger: The literal text
Opened with breakpoints at sec-createdynamicfunction.
- The specification: pauses at
CreateDynamicFunction 1; ends normal: undefined; prints body: SyntaxError, params: SyntaxError, generator body: SyntaxError. - The literal text: pauses at
CreateDynamicFunction 1; ends normal: undefined; prints body: no error, params: no error, generator body: no error.
Source tests/run/dynamic_function_private_identifiers.js
// expect: normal: undefined
// print: body: SyntaxError
// print: params: SyntaxError
// print: generator body: SyntaxError
// CreateDynamicFunction steps 18-29: no goal it parses with applies
// AllPrivateIdentifiersValid (Erratum CreateDynamicFunctionPrivateIdentifiers).
// The default reading, the proposed one, adds after step 25
// "If AllPrivateIdentifiersValid of _body_ with argument « » is false, throw a
// SyntaxError exception" and the same of _params_ (spec/formal/readings.emu):
// engines parse the parameters and the body as one source text and throw for
// both. The test262 reading checks the body only, which is all test262's
// built-ins/Function/private-identifiers-not-empty.js asserts
// (dynamic_function_private_identifiers_test262.js); the literal text checks
// neither (dynamic_function_private_identifiers_literal.js).
try { new Function("o", "return o.#f"); print("body: no error"); }
catch (e) { print("body: " + e.constructor.name); }
try { new Function("a = {}.#g", ""); print("params: no error"); }
catch (e) { print("params: " + e.constructor.name); }
var GeneratorFunction = Object.getPrototypeOf(function* () {}).constructor;
try { GeneratorFunction("o", "yield o.#h"); print("generator body: no error"); }
catch (e) { print("generator body: " + e.constructor.name); }
FinalizationRegistry.prototype.unregister removes cells from the list it iterates. The default reading removes both cells with the token, so a second unregister returns false; as written it skips the second cell, and the second call returns true.
Open in the debugger: The specification Open in the debugger: The literal text
Opened with breakpoints at sec-finalization-registry.prototype.unregister.
- The specification: pauses at
FinalizationRegistry.prototype.unregister 1; ends normal: "true|false". - The literal text: pauses at
FinalizationRegistry.prototype.unregister 1; ends normal: "true|true".
Source tests/run/errata_unregister_two_cells.js
// expect: normal: "true|false"
// Two cells with one unregister token, in a row (Erratum
// UnregisterIteratesCopy): the test262 reading removes both.
var fr = new FinalizationRegistry(function () {});
var token = {};
fr.register({}, 1, token);
fr.register({}, 2, token);
[fr.unregister(token), fr.unregister(token)].join("|");
Read literally, CreateIntrinsics passes an argument SetFunctionName does not accept for one async built-in, and the run stops at SetFunctionName step 5.a while the realm is set up, before the program. This is why the literal text's build keeps this erratum at its default reading; this example reads it literally on its own.
Open in the debugger: The specification
Run with --erratum CreateIntrinsicsAsyncArgument=literal.
- The specification: ends
stop: erratum CreateIntrinsicsAsyncArgument sec-setfunctionname#0 5.a.
Source tests/run/errata_createintrinsics_async_argument_literal.js
// expect: stop: erratum CreateIntrinsicsAsyncArgument sec-setfunctionname#0 5.a
// args: --erratum CreateIntrinsicsAsyncArgument=literal
// CreateIntrinsics step 2 (Erratum CreateIntrinsicsAsyncArgument): the literal
// reading passes [[Async]] as CreateBuiltinFunction's prefix, SetFunctionName
// concatenates a Boolean, and realm creation stops as the erratum.
var r = [];
r.push(Object.getOwnPropertyDescriptor(Map.prototype, "size").get.name);
r.push(Array.fromAsync([1]) instanceof Promise);
r.join("|");
setHours(1e21) asks UTC for a local time far out of range: GetUTCEpochNanoseconds finds no time value, and the Assert of its step 4 fails. No reading is chosen for this one, so the run stops in both builds.
Open in the debugger: The specification Open in the debugger: The literal text
Opened with breakpoints at sec-getutcepochnanoseconds; pauses on the machine's stops.
- The specification: pauses at
GetUTCEpochNanoseconds 1, then GetUTCEpochNanoseconds 4; ends stop: erratum GetUTCEpochNanosecondsNaN sec-getutcepochnanoseconds#0 4; prints NaN. - The literal text: pauses at
GetUTCEpochNanoseconds 1, then GetUTCEpochNanoseconds 4; ends stop: erratum GetUTCEpochNanosecondsNaN sec-getutcepochnanoseconds#0 4; prints NaN.
Source tests/run/date_utc_large_local_time.js
// expect: stop: erratum GetUTCEpochNanosecondsNaN sec-getutcepochnanoseconds#0 4
// UTC ( t ) of a large finite local time: setHours(1e21) gives t = 3.6e24,
// GetUTCEpochNanoseconds step 1's MakeDay finds no time value on the month's
// first day (NaN), and the Assert of its step 4 fails. No test262 test
// reaches it, and the default reading is the text as written (Erratum
// GetUTCEpochNanosecondsNaN), so the run stops.
// Engines give NaN. The UTC setter does not call UTC ( t ): NaN.
print(String(new Date(0).setUTCHours(1e21)));
print(String(new Date(0).setHours(1e21)));
With /u and lastIndex on the second half of a surrogate pair, RegExpBuiltinExec starts the empty match at the pair's start, and GetMatchString's Assert (start before end) fails at step 1. No reading is chosen, so the run stops in both builds.
Open in the debugger: The specification Open in the debugger: The literal text
Opened with breakpoints at sec-regexpbuiltinexec; pauses on the machine's stops.
- The specification: pauses at
RegExpBuiltinExec 1, then GetMatchString 1; ends stop: erratum GetMatchStringStartAfterEnd sec-getmatchstring#0 1. - The literal text: pauses at
RegExpBuiltinExec 1, then GetMatchString 1; ends stop: erratum GetMatchStringStartAfterEnd sec-getmatchstring#0 1.
Source tests/run/regexp_lastindex_inside_pair.js
// expect: stop: erratum GetMatchStringStartAfterEnd sec-getmatchstring#0 1
// RegExpBuiltinExec with /u and lastIndex on the trailing surrogate of a pair:
// step 13.b starts at the code point that contains it, the empty pattern
// matches there with [[EndIndex]] 0, and step 24's Match Record { 1, 0 } fails
// GetMatchString step 1's Assert. No test262 test sets lastIndex inside a
// pair before an empty match; the default reading is the text as written
// (Erratum GetMatchStringStartAfterEnd), so the run stops.
// V8 and SpiderMonkey report index 0; JavaScriptCore reports index 1.
// (The non-empty case, which does not stop, is
// regexp_lastindex_inside_pair_nonempty.js.)
var r = /(?:)/gu;
r.lastIndex = 1;
r.exec("\u{1F600}");
A promise reaction job, made by NewPromiseReactionJob, returns a throw completion when the species constructor's resolve function throws, which a job must not do. No reading is chosen, so the run stops in both builds when the job returns.
Open in the debugger: The specification Open in the debugger: The literal text
Opened with breakpoints at sec-newpromisereactionjob; pauses on the machine's stops.
- The specification: pauses at
NewPromiseReactionJob 1; ends stop: erratum PromiseJobAbruptCompletion sec-jobs -. - The literal text: pauses at
NewPromiseReactionJob 1; ends stop: erratum PromiseJobAbruptCompletion sec-jobs -.
Source tests/run/promise_job_abrupt.js
// expect: stop: erratum PromiseJobAbruptCompletion sec-jobs -
// NewPromiseReactionJob 1.i returns `? Call(promiseCapability.[[Resolve]], …)`;
// with a species constructor whose resolve throws, the Job returns a throw
// completion, which §9.5 says a Job must not. No test262 test makes a
// reaction Job's resolving function throw; the default reading is the text
// as written (Erratum PromiseJobAbruptCompletion), so the run
// stops. (Engine hosts differ: node goes on silently; the SpiderMonkey shell
// and Bun, with JavaScriptCore, report the throw and go on.)
function Bad(executor) {
executor(function () { throw new Error("boom"); }, function () {});
}
Bad[Symbol.species] = Bad;
var p = Promise.resolve(1);
p.constructor = Bad;
p.then(function (v) { print("handler " + v); return v; });
Promise.resolve(3).then(function () { print("a later Job"); });
Three programs that use the syntax of tc39/proposal-defer-import-eval. Under the specification's build each is a SyntaxError, since ECMA-262 has no such syntax. Under the build "Proposal: import defer", made from a branch where the proposal's text is merged into the specification's, each runs, and the breakpoints stop in the proposal's own algorithms.
What it took to apply the proposal: Applying a proposal.
With proposal-defer-import-eval, `import defer * as heavy` links heavy.mjs with the graph but leaves it unevaluated: InitializeEnvironment asks GetModuleNamespace for its ~defer~ namespace, and the first read of an export goes through the namespace's [[Get]] and GetModuleExportsList to EvaluateModuleSync. Reading %Symbol.toStringTag% does not evaluate it.
Open in the debugger: Proposal (Stage 3): import defer Open in the debugger: The specification
Opened with breakpoints at sec-getmodulenamespace 1, sec-EvaluateModuleSync 1.
Run with --bundle.
- Proposal (Stage 3): import defer: pauses at
GetModuleNamespace 1, then EvaluateModuleSync 1, then EvaluateModuleSync 1; ends normal: undefined; prints [object Deferred Module], main starts; heavy evaluates; read 42; read again 42. - The specification: ends
throw: SyntaxError.
Source tests/run/import_defer_basic.js
// args: --bundle
// expect: throw: SyntaxError
// ECMA-262 as it stands has no `import defer` and no `import.defer()`: this is a SyntaxError.
// With proposal-defer-import-eval applied (branch proposal-defer-import-eval; the debugger's build
// "Proposal: import defer") it completes normally and prints:
// [object Deferred Module]
// main starts; heavy evaluates; read 42; read again 42
// proposal-defer-import-eval: `import defer * as heavy` loads and links heavy.mjs with the graph but evaluates it at the
// first read of an export (the namespace's [[Get]]: GetModuleExportsList, EvaluateModuleSync); %Symbol.toStringTag%
// is read without evaluating it (IsSymbolLikeNamespaceKey), and is "Deferred Module" (ModuleNamespaceCreate).
// JS_BUNDLE_MODULE:log.mjs
export const log = [];
// JS_BUNDLE_MODULE:heavy.mjs
import { log } from "./log.mjs";
log.push("heavy evaluates");
export const answer = 42;
// JS_BUNDLE_MODULE_ENTRYPOINT:main.mjs
import { log } from "./log.mjs";
import defer * as heavy from "./heavy.mjs";
log.push("main starts");
print(Object.prototype.toString.call(heavy));
log.push("read " + heavy.answer);
log.push("read again " + heavy.answer);
print(log.join("; "));
`import.defer()` loads and links the module, and ContinueDynamicImport's ~defer~ branch asks GatherAsynchronousTransitiveDependencies what must be evaluated first (nothing here) before it settles the promise. The module exports `then`, but a deferred namespace has no `then` (IsSymbolLikeNamespaceKey), so settling the promise does not evaluate it; reading `x` does.
Open in the debugger: Proposal (Stage 3): import defer Open in the debugger: The specification
Opened with breakpoints at sec-ContinueDynamicImport 1, sec-GatherAsynchronousTransitiveDependencies 1, sec-IsSymbolLikeNamespaceKey 1.
Run with --bundle.
- Proposal (Stage 3): import defer: pauses at
ContinueDynamicImport 1, then GatherAsynchronousTransitiveDependencies 1, then IsSymbolLikeNamespaceKey 1, then IsSymbolLikeNamespaceKey 1, then IsSymbolLikeNamespaceKey 1, then IsSymbolLikeNamespaceKey 1, then IsSymbolLikeNamespaceKey 1; ends normal: undefined; prints promise settled; then in ns: false; dep evaluates; x is 1. - The specification: ends
throw: SyntaxError.
Source tests/run/import_defer_dynamic.js
// args: --bundle
// expect: throw: SyntaxError
// ECMA-262 as it stands has no `import defer` and no `import.defer()`: this is a SyntaxError.
// With proposal-defer-import-eval applied (branch proposal-defer-import-eval; the debugger's build
// "Proposal: import defer") it completes normally and prints:
// promise settled; then in ns: false; dep evaluates; x is 1
// proposal-defer-import-eval: `import.defer()` settles with a deferred namespace without evaluating the module
// (ContinueDynamicImport, GatherAsynchronousTransitiveDependencies finds nothing); "then" is not an export of a
// deferred namespace (GetModuleNamespace), so the promise's resolution does not evaluate it either
// (IsSymbolLikeNamespaceKey); reading `x` does.
// JS_BUNDLE_MODULE:dep.mjs
globalThis.order.push("dep evaluates");
export function then(resolve) { globalThis.order.push("then called"); resolve("oops"); }
export const x = 1;
// JS_BUNDLE_MODULE_ENTRYPOINT:main.mjs
globalThis.order = [];
const ns = await import.defer("./dep.mjs");
order.push("promise settled");
order.push("then in ns: " + ("then" in ns));
order.push("x is " + ns.x);
print(order.join("; "));
The proposal's README graph: c is deferred, but its dependency d awaits at top level, so InnerModuleEvaluation asks GatherAsynchronousTransitiveDependencies for c's asynchronous dependencies and evaluates d (and e) with the graph; f and c wait for the first read of c's namespace, which EvaluateModuleSync evaluates synchronously.
Open in the debugger: Proposal (Stage 3): import defer Open in the debugger: The specification
Opened with breakpoints at sec-GatherAsynchronousTransitiveDependencies 1, sec-EvaluateModuleSync 1.
Run with --bundle.
- Proposal (Stage 3): import defer: pauses at
GatherAsynchronousTransitiveDependencies 1, then GatherAsynchronousTransitiveDependencies 1, then GatherAsynchronousTransitiveDependencies 1, then GatherAsynchronousTransitiveDependencies 1, then GatherAsynchronousTransitiveDependencies 1, then EvaluateModuleSync 1; ends normal: undefined; prints before access: b, e, d, a, after access: b, e, d, a, f, c. - The specification: ends
throw: SyntaxError.
Source tests/run/import_defer_tla.js
// args: --bundle
// expect: throw: SyntaxError
// ECMA-262 as it stands has no `import defer` and no `import.defer()`: this is a SyntaxError.
// With proposal-defer-import-eval applied (branch proposal-defer-import-eval; the debugger's build
// "Proposal: import defer") it completes normally and prints:
// before access: b, e, d, a
// after access: b, e, d, a, f, c
// proposal-defer-import-eval, the README's graph: c is deferred, but its dependency d has top-level await, so d and
// its dependency e evaluate with the graph (InnerModuleEvaluation, GatherAsynchronousTransitiveDependencies); f and
// c wait for the first read of c's namespace.
// JS_BUNDLE_MODULE:order.mjs
export const order = [];
// JS_BUNDLE_MODULE:b.mjs
import { order } from "./order.mjs";
order.push("b");
// JS_BUNDLE_MODULE:e.mjs
import { order } from "./order.mjs";
order.push("e");
// JS_BUNDLE_MODULE:d.mjs
import { order } from "./order.mjs";
import "./e.mjs";
await 0;
order.push("d");
// JS_BUNDLE_MODULE:f.mjs
import { order } from "./order.mjs";
order.push("f");
// JS_BUNDLE_MODULE:c.mjs
import { order } from "./order.mjs";
import "./d.mjs";
import "./f.mjs";
order.push("c");
export let value = 2;
// JS_BUNDLE_MODULE_ENTRYPOINT:a.mjs
import { order } from "./order.mjs";
import "./b.mjs";
import defer * as c from "./c.mjs";
order.push("a");
print("before access: " + order.join(", "));
c.value;
print("after access: " + order.join(", "));
Thirteen more ECMA-262 proposals from the 117th TC39 plenary agenda (Stages 0–3, alongside import defer above). Each runs under its own lazy-loaded WebAssembly build and pauses inside the proposal's specification algorithm; under the baseline specification build each shows how ECMA-262 behaves today.
HostLoadImportedModule dispatches on the type: "text" import attribute to CreateTextModule, wrapping the UTF-8 decoded text in a Synthetic Module Record shared between static and dynamic imports.
Open in the debugger: Proposal (Stage 3): Import Text Open in the debugger: The specification
Opened with breakpoints at sec-create-text-module 1.
Run with --bundle.
- Proposal (Stage 3): Import Text: pauses at
CreateTextModule 1; ends normal: undefined; prints Hello from ECMA-262 Import Text! | cached=true. - The specification: ends
throw: TypeError.
Source tests/dbg/proposal_import_text.js
// JS_BUNDLE_MODULE:greeting.txt
Hello from ECMA-262 Import Text!
// JS_BUNDLE_MODULE_ENTRYPOINT:main.mjs
import greeting from "./greeting.txt" with { type: "text" };
const dyn = await import("./greeting.txt", { with: { type: "text" } });
print(greeting.trim() + " | cached=" + (greeting === dyn.default));
Promise.resolve inspects whether looking up "then" could run user code via RequiresDeferredPromiseResolution, then dispatches user-defined thenables through PerformPromiseResolveThenable.
Open in the debugger: Proposal (Stage 3): Thenable Curtailment Open in the debugger: The specification
Opened with breakpoints at sec-perform-promise-resolve-thenable 1.
- Proposal (Stage 3): Thenable Curtailment: pauses at
PerformPromiseResolveThenable 1; ends normal: undefined; prints then-called -> microtask -> resolved:42. - The specification: ends
normal: undefined; prints then-called -> microtask -> resolved:42.
Source tests/dbg/proposal_thenable_curtailment.js
const events = [];
const thenable = {
then(resolve) {
events.push("then-called");
resolve(42);
}
};
const p = Promise.resolve(thenable);
Promise.resolve().then(() => events.push("microtask"));
p.then((v) => {
events.push("resolved:" + v);
print(events.join(" -> "));
});
void 0;
Importing barrel.mjs links export defer { x } from "./heavy.mjs" without evaluating heavy.mjs; reading barrel.x triggers EnsureDeferredExportEvaluated on the module namespace.
Open in the debugger: Proposal (Stage 2.7): Deferred Re-exports Open in the debugger: The specification
Opened with breakpoints at sec-EnsureDeferredExportEvaluated 1.
Run with --bundle.
- Proposal (Stage 2.7): Deferred Re-exports: pauses at
EnsureDeferredExportEvaluated 1; ends normal: undefined; prints after barrel import: barrel, after reading barrel.x=99: barrel,heavy. - The specification: ends
throw: SyntaxError.
Source tests/dbg/proposal_deferred_reexports.js
// JS_BUNDLE_MODULE:log.mjs
export const events = [];
// JS_BUNDLE_MODULE:heavy.mjs
import { events } from "./log.mjs";
events.push("heavy");
export const x = 99;
// JS_BUNDLE_MODULE:barrel.mjs
import { events } from "./log.mjs";
export defer { x } from "./heavy.mjs";
events.push("barrel");
// JS_BUNDLE_MODULE_ENTRYPOINT:main.mjs
import { events } from "./log.mjs";
import * as barrel from "./barrel.mjs";
print("after barrel import: " + events.join(","));
const v = barrel.x;
print("after reading barrel.x=" + v + ": " + events.join(","));
CreateJSONParseOptions validates the options bag for { freeze: true } and { nullPrototypeObjects: true }, producing frozen null-prototype graphs or mutable null-prototype objects.
Open in the debugger: Proposal (Stage 2.7): JSON.parse Options Open in the debugger: The specification
Opened with breakpoints at sec-createjsonparseoptions 1.
- Proposal (Stage 2.7): JSON.parse Options: pauses at
CreateJSONParseOptions 1, then CreateJSONParseOptions 1; ends normal: undefined; prints frozen=true, proto=null, ownProto=true, nullMutable=2. - The specification: ends
normal: undefined; prints frozen=false, proto=[object Object], ownProto=true, nullMutable=2.
Source tests/dbg/proposal_json_parseimmutable.js
const imm = JSON.parse('{"x":[1,{"y":2}],"__proto__":{"safe":true}}', { freeze: true });
const nullOnly = JSON.parse('{"mutable":1}', { nullPrototypeObjects: true });
nullOnly.mutable = 2;
print([
"frozen=" + Object.isFrozen(imm.x[1]),
"proto=" + Object.getPrototypeOf(imm),
"ownProto=" + imm.__proto__.safe,
"nullMutable=" + nullOnly.mutable
].join(", "));
import source and import.source() bind a ModuleSource object inheriting from %AbstractModuleSource%; dynamic import(depSrc) unwraps its Module Source Record via GetModuleSourceRecord and coalesces evaluation.
Open in the debugger: Proposal (Stage 2.7): ESM Phase Imports Open in the debugger: The specification
Opened with breakpoints at sec-getmodulesourcerecord 1.
Run with --bundle.
- Proposal (Stage 2.7): ESM Phase Imports: pauses at
GetModuleSourceRecord 1, then GetModuleSourceRecord 1; ends normal: undefined; prints ModuleSource, sameSource=true, sameNs=true, runs=1, answer=42. - The specification: ends
throw: SyntaxError.
Source tests/dbg/proposal_esm_phase_imports.js
// JS_BUNDLE_MODULE:dep.js
export let runs = 0;
runs++;
export const answer = 42;
// JS_BUNDLE_MODULE_ENTRYPOINT:main.js
import source depSrc from "./dep.js";
const dynSrc = await import.source("./dep.js");
const ns1 = await import(depSrc);
const ns2 = await import("./dep.js");
print([
depSrc[Symbol.toStringTag],
"sameSource=" + (depSrc === dynSrc),
"sameNs=" + (ns1 === ns2),
"runs=" + ns1.runs,
"answer=" + ns1.answer
].join(", "));
sliceToImmutable copies a subrange and transferToImmutable detaches the source buffer into a new buffer with [[ArrayBufferDetachKey]] ~immutable~, causing TypedArray writes to throw a TypeError.
Open in the debugger: Proposal (Stage 2.7): Immutable ArrayBuffers Open in the debugger: The specification
Opened with breakpoints at sec-arraybuffer.prototype.transfertoimmutable 1.
- Proposal (Stage 2.7): Immutable ArrayBuffers: pauses at
ArrayBuffer.prototype.transferToImmutable 1; ends normal: undefined; prints slice=20,30, detached=true, immutable=true, writeThrew=true. - The specification: ends
throw: TypeError.
Source tests/dbg/proposal_immutable_arraybuffer.js
"use strict";
const ab = new ArrayBuffer(4);
new Uint8Array(ab).set([10, 20, 30, 40]);
const sliced = ab.sliceToImmutable(1, 3);
const moved = ab.transferToImmutable(6);
const view = new Uint8Array(moved);
let writeThrew = false;
try { view[0] = 99; } catch (e) { writeThrew = e instanceof TypeError; }
print([
"slice=" + Array.from(new Uint8Array(sliced)).join(","),
"detached=" + ab.detached,
"immutable=" + moved.immutable,
"writeThrew=" + writeThrew
].join(", "));
Error, NativeError, and SuppressedError constructors delegate to InstallErrorOwnProperties, installing non-enumerable code alongside cause from the options object.
Open in the debugger: Proposal (Stage 2): Error.code Open in the debugger: The specification
Opened with breakpoints at sec-installerrorownproperties 1.
- Proposal (Stage 2): Error.code: pauses at
InstallErrorOwnProperties 1, then InstallErrorOwnProperties 1, then InstallErrorOwnProperties 1; ends normal: undefined; prints code=ECONNREFUSED, enumerable=false, suppressedCode=EDISPOSE. - The specification: ends
throw: TypeError.
Source tests/dbg/proposal_error_code_property.js
const err = new Error("connect failed", { code: "ECONNREFUSED", cause: "timeout" });
const sup = new SuppressedError(err, new TypeError("close failed"), "disposal failed", { code: "EDISPOSE" });
const desc = Object.getOwnPropertyDescriptor(err, "code");
print([
"code=" + err.code,
"enumerable=" + desc.enumerable,
"suppressedCode=" + sup.code
].join(", "));
For a = 1 + 2^-52 and b = 1 - 2^-52, naive a * b + (-1) rounds a * b to 1 first and yields 0; Math.fusedMultiplyAdd computes a * b + c in R with a single rounding, preserving -2^-104.
Open in the debugger: Proposal (Stage 2): Math.fusedMultiplyAdd Open in the debugger: The specification
Opened with breakpoints at sec-math.fusedMultiplyAdd 1.
- Proposal (Stage 2): Math.fusedMultiplyAdd: pauses at
Math.fusedMultiplyAdd 1; ends normal: undefined; prints naive=0, fma=-4.930380657631324e-32, exactMatch=true. - The specification: ends
throw: TypeError.
Source tests/dbg/proposal_fma.js
// (1 + 2^-52) * (1 - 2^-52) = 1 - 2^-104 in R.
// Naive a * b + (-1) rounds a * b to 1 first and loses the -2^-104 residual!
const a = 1 + 2 ** -52;
const b = 1 - 2 ** -52;
const naive = a * b + (-1);
const exact = Math.fusedMultiplyAdd(a, b, -1);
print("naive=" + naive + ", fma=" + exact + ", exactMatch=" + (exact === -(2 ** -104)));
Composite(...) canonicalizes integer-index keys before lexicographic string keys, freezes the object with null prototype, and interns structural duplicates in the Realm's [[CompositeRegistry]].
Open in the debugger: Proposal (Stage 2): Composites Open in the debugger: The specification
Opened with breakpoints at sec-composite-function-arg 1.
- Proposal (Stage 2): Composites: pauses at
Composite 1, then Composite 1, then Composite 1; ends normal: undefined; prints interned=true | keys=2,10,x,y | inSet=true. - The specification: ends
throw: ReferenceError.
Source tests/dbg/proposal_composites.js
const c1 = Composite({ y: 4, x: 1, 10: "ten", 2: "two" });
const c2 = Composite({ 2: "two", x: 1, 10: "ten", y: 4 });
const visited = new Set([c1]);
print([
"interned=" + (c1 === c2),
"keys=" + Object.keys(c1).join(","),
"inSet=" + visited.has(Composite({ x: 1, y: 4, 2: "two", 10: "ten" }))
].join(" | "));
new AbortController() allocates an AbortSignal via CreateAbortSignal; a block-scoped using registration disposes cleanly before ac.abort("timeout") runs SignalAbort and rejects Atomics.waitAsync.
Open in the debugger: Proposal (Stage 1): Cancellation (AbortController) Open in the debugger: The specification
Opened with breakpoints at sec-createabortsignal 1, sec-signalabort 1.
- Proposal (Stage 1): Cancellation (AbortController): pauses at
CreateAbortSignal 1, then SignalAbort 1; ends normal: undefined; prints aborted:timeout, waitAsync:timeout. - The specification: ends
throw: ReferenceError.
Source tests/dbg/proposal_cancellation.js
const ac = new AbortController();
const events = [];
{
using _scoped = ac.signal.addAbortCallback(() => events.push("disposed-listener"));
}
ac.signal.addAbortCallback(() => events.push("aborted:" + ac.signal.reason));
const sab = new SharedArrayBuffer(4);
const wait = Atomics.waitAsync(new Int32Array(sab), 0, 0, { signal: ac.signal });
ac.abort("timeout");
wait.value.catch((reason) => {
events.push("waitAsync:" + reason);
print(events.join(", "));
});
void 0;
Iterator.prototype.transfer moves a suspended generator's state and execution context onto a fresh Generator instance while marking the source generator ~completed~.
Open in the debugger: Proposal (Stage 0): Iterator.prototype.transfer Open in the debugger: The specification
Opened with breakpoints at sec-iterator.prototype.transfer 1.
- Proposal (Stage 0): Iterator.prototype.transfer: pauses at
Iterator.prototype.transfer 1; ends normal: undefined; prints a=first, origDone=true, b=second, finallyRuns=1. - The specification: ends
throw: TypeError.
Source tests/dbg/proposal_iterator_transfer.js
let cleanedUp = 0;
function* items() {
try {
yield "first";
yield "second";
} finally {
cleanedUp++;
}
}
const orig = items();
const a = orig.next().value;
const moved = orig.transfer();
const origDone = orig.next().done;
const b = moved.next().value;
moved.return();
print("a=" + a + ", origDone=" + origDone + ", b=" + b + ", finallyRuns=" + cleanedUp);
String.prototype.trim accepts an optional characters string and forwards it to TrimString, which trims matching Unicode code points via StringToCodePoints rather than UTF-16 code units.
Open in the debugger: Proposal (Stage 0): Trim Specific Characters Open in the debugger: The specification
Opened with breakpoints at sec-string.prototype.trim 2.
- Proposal (Stage 0): Trim Specific Characters: pauses at
String.prototype.trim 2, then String.prototype.trim 2; ends normal: undefined; prints path=ecma-262, astralPreserved=true. - The specification: pauses at
String.prototype.trim 2, then String.prototype.trim 2; ends normal: undefined; prints path=/__ecma-262__/, astralPreserved=true.
Source tests/dbg/proposal_trim_chars.js
const path = "/__ecma-262__/".trim("/_");
// U+1F601 (\uD83D\uDE01) shares high surrogate \uD83D with U+1F600 (\uD83D\uDE00)
const astral = "\u{1F601}ok\u{1F601}".trim("\u{1F600}");
print("path=" + path + ", astralPreserved=" + (astral === "\u{1F601}ok\u{1F601}"));
Math.popcount32 counts 1 bits and Math.ctz32 counts trailing 0 bits of ToUint32(n), returning 32 when the 32-bit unsigned value is 0.
Open in the debugger: Proposal (Stage 0): Math.popcount32 / ctz32 Open in the debugger: The specification
Opened with breakpoints at sec-math.popcount32 1, sec-math.ctz32 1.
- Proposal (Stage 0): Math.popcount32 / ctz32: pauses at
Math.popcount32 1, then Math.ctz32 1, then Math.ctz32 1; ends normal: undefined; prints popcount32(0xaaaaaaaa)=16, ctz32(0)=32, ctz32(12)=2. - The specification: ends
throw: TypeError.
Source tests/dbg/proposal_popcount.js
const pop = Math.popcount32(0xaaaaaaaa);
const ctzZero = Math.ctz32(0);
const ctz12 = Math.ctz32(12);
print("popcount32(0xaaaaaaaa)=" + pop + ", ctz32(0)=" + ctzZero + ", ctz32(12)=" + ctz12);
The programs the errata page runs that show an erratum and are not above, with no breakpoints set: each opens under the specification's build. The errata page links each also with its erratum's other reading.
var \u0069f spells the reserved word if with an escape; the default reading makes it a SyntaxError.
Open in the debugger: The specification
- The specification: ends
throw: SyntaxError.
Source tests/run/erratum_stringvalue_reserved_word.js
// An |IdentifierName| spelling `if` with an escape is the String value of a
// terminal of |ReservedWord| (Erratum StringValueReservedWord, test262's reading).
// expect: throw: SyntaxError
var \u0069f;
After if (0) let and a line break, ExpressionStatement's lookahead reads the source's tokens past the inserted semicolon; the default reading gives no parse, a SyntaxError.
Open in the debugger: The specification
- The specification: ends
throw: SyntaxError.
Source tests/run/erratum_lookahead_source_tokens.js
// The inserted `;` after `let` is no source token: ExpressionStatement's lookahead
// reads `let [` and the program has no parse (Erratum LookaheadSourceTokens,
// test262's reading).
// expect: throw: SyntaxError
if (0) let
[a] = 0;
Under B.1.2's grammar the alternatives commit in order: \b is an Assertion, which no quantifier follows, so the pattern is a SyntaxError.
Open in the debugger: The specification
Run with --annex-b sec-regular-expressions-patterns.
- The specification: ends
throw: SyntaxError.
Source tests/run/erratum_annexb_regexp_order.js
// B.1.2's alternatives commit in order: `\b*` is an Assertion, which no
// quantifier follows, and the literal has no parse (Erratum AnnexBRegExpOrder,
// test262's reading).
// args: --annex-b sec-regular-expressions-patterns
// expect: throw: SyntaxError
/\b*/;
Under B.1.2's grammar \1 with one capturing group is a backreference: the group count comes from a committed parse.
Open in the debugger: The specification
Run with --annex-b sec-regular-expressions-patterns.
- The specification: ends
normal: true.
Source tests/run/erratum_annexb_group_count.js
// `\1` with one capturing group is a backreference: the group count is read
// from a committed parse (Erratum AnnexBGroupCount, test262's reading).
// args: --annex-b sec-regular-expressions-patterns
// expect: normal: true
/(a)\1/.test("aa");
§22.2.1.1's modifier rules apply to B.1.2's ExtendedAtom under the default reading: a repeated modifier is a SyntaxError.
Open in the debugger: The specification
Run with --annex-b sec-regular-expressions-patterns.
- The specification: ends
throw: SyntaxError.
Source tests/run/erratum_annexb_modifier_early_errors.js
// §22.2.1.1's modifier rules hold on B.1.2's ExtendedAtom: `(?ii:a)` repeats a
// modifier (Erratum AnnexBModifierEarlyErrors, test262's reading).
// args: --annex-b sec-regular-expressions-patterns
// expect: throw: SyntaxError
/(?ii:a)/;
The covered ParenthesizedExpression takes its cover's place in the tree, so return (f(n - 1)) is in tail position.
Open in the debugger: The specification
- The specification: ends
normal: 0.
Source tests/run/erratum_covered_node_parent.js
// Erratum CoveredNodeParent at its test262 reading: the covered
// |ParenthesizedExpression| takes its cover's place, so `return (f(n - 1))` is
// in tail position (test262 tco-pos.js).
// expect: normal: 0
"use strict";
function f(n) {
if (n === 0) return 0;
return (f(n - 1));
}
f(3);
Array.fromAsync's promise is fulfilled with the array under the default reading of BuiltinCallOrConstruct step 10.b.iii.
Open in the debugger: The specification
- The specification: ends
normal: undefined; prints undefined, 1,2.
Source tests/run/builtin_async_return.js
// expect: normal: undefined
// print: undefined
// print: 1,2
// BuiltinCallOrConstruct step 10.b.iii under Erratum BuiltinReturnCompletion
// (its test262 reading): "Return array" of Array.fromAsync is a normal
// completion, which the resultsClosure gives to AsyncBlockStart as a return
// completion, so the promise is fulfilled with the array; disposeAsync's
// "Return ? DisposeResources(…)" fulfils it with undefined.
Array.fromAsync([1, 2]).then(function (a) { print(a.join(",")); });
new AsyncDisposableStack().disposeAsync().then(function (v) { print(String(v)); });
void 0;
A module with top-level await disposes its await using resources after its body under the default reading; read literally, never.
Open in the debugger: The specification
Run with --module.
- The specification: ends
normal: undefined; prints end, disposed.
Source tests/run/errata_execute_module_dispose.js
// module: yes
// expect: normal: undefined
// print: end
// print: disposed
// A module with top-level await and `await using` (Erratum ExecuteModuleAsyncDisposeResources):
// the test262 reading disposes the module's resources after its body.
await using x = { [Symbol.asyncDispose]() { print("disposed"); } };
await 0;
print("end");
Without the u or v flag, a backslash before U+200C or U+200D is an IdentityEscape under the default reading.
Open in the debugger: The specification
- The specification: ends
normal: undefined; prints U+200C: literal true, class true, a-literal true, RegExp true, u SyntaxError, v SyntaxError, U+200D: literal true, class true, a-literal true, RegExp true, u SyntaxError, v SyntaxError, U+200B: literal true, class true, a-literal true, RegExp true, u SyntaxError, v SyntaxError, U+200E: literal true, class true, a-literal true, RegExp true, u SyntaxError, v SyntaxError, U+61: literal SyntaxError, class SyntaxError, a-literal SyntaxError, RegExp SyntaxError, u SyntaxError, v SyntaxError, U+B7: literal SyntaxError, class SyntaxError, a-literal SyntaxError, RegExp SyntaxError, u SyntaxError, v SyntaxError.
Source tests/run/regexp_identity_escape_join_controls.js
// Erratum IdentityEscapeJoinControls, at its test262 reading: without the
// u or v flag, `\` U+200C (ZWNJ) and `\` U+200D (ZWJ) are IdentityEscapes,
// as test262's language/literals/regexp/S7.8.5_A1.4_T2.js and
// S7.8.5_A2.4_T2.js require, although Unicode 15.1 made both UnicodeIDContinue.
// ecma-run's default host does not support §B.1.2, so this is the main grammar:
// the other UnicodeIDContinue code points (`a`, U+00B7) stay SyntaxErrors, and
// U+200B and U+200E (not ID_Continue) are IdentityEscapes. The u and v flags
// allow neither. The characters are invisible: the patterns are built with
// fromCharCode.
// expect: normal: undefined
// print: U+200C: literal true, class true, a-literal true, RegExp true, u SyntaxError, v SyntaxError
// print: U+200D: literal true, class true, a-literal true, RegExp true, u SyntaxError, v SyntaxError
// print: U+200B: literal true, class true, a-literal true, RegExp true, u SyntaxError, v SyntaxError
// print: U+200E: literal true, class true, a-literal true, RegExp true, u SyntaxError, v SyntaxError
// print: U+61: literal SyntaxError, class SyntaxError, a-literal SyntaxError, RegExp SyntaxError, u SyntaxError, v SyntaxError
// print: U+B7: literal SyntaxError, class SyntaxError, a-literal SyntaxError, RegExp SyntaxError, u SyntaxError, v SyntaxError
function t(f) { try { return f(); } catch (e) { return e.name; } }
for (var cu of [0x200C, 0x200D, 0x200B, 0x200E, 0x61, 0xB7]) {
var ch = String.fromCharCode(cu), src = "\\" + ch;
print("U+" + cu.toString(16).toUpperCase() + ": " + [
"literal " + t(() => { var re = eval("/" + src + "/"); return re.source === src && re.test(ch) && !re.test("x"); }),
"class " + t(() => eval("/[" + src + "]/").test(ch)),
"a-literal " + t(() => eval("/a" + src + "/").test("a" + ch)),
"RegExp " + t(() => new RegExp(src).exec("x" + ch)[0] === ch),
"u " + t(() => new RegExp(src, "u")),
"v " + t(() => new RegExp(src, "v")),
].join(", "));
}
A lone \p{ASCII} is a binary property; under the default reading CompileToCharSet asks UnicodeMatchProperty for it.
Open in the debugger: The specification
Run with --erratum LonePropertyGeneralCategoryAssert=literal.
- The specification: ends
stop: erratum LonePropertyGeneralCategoryAssert sec-runtime-semantics-unicodematchpropertyvalue-p-v#0 2.
Source tests/run/errata_lone_property_gc_assert_literal.js
// expect: stop: erratum LonePropertyGeneralCategoryAssert sec-runtime-semantics-unicodematchpropertyvalue-p-v#0 2
// args: --erratum LonePropertyGeneralCategoryAssert=literal
// CompileToCharSet's lone \p{X} (Erratum LonePropertyGeneralCategoryAssert): the
// literal reading passes the String "General_Category" to UnicodeMatchPropertyValue
// and asks it for a binary property's name, and the run stops as the erratum.
/\p{ASCII}/u.test("a");
grow reads the byte length that AllocateSharedArrayBuffer stored in a Shared Data Block.
Open in the debugger: The specification
- The specification: ends
normal: 2.
Source tests/run/errata_allocate_sab_byte_length.js
// expect: normal: 2
// A growable SharedArrayBuffer (Erratum AllocateSharedArrayBufferByteLengthStore): the
// test262 reading stores the byte length in its Shared Data Block, which grow reads.
var b = new SharedArrayBuffer(1, { maxByteLength: 4 });
b.grow(2);
b.byteLength;
The early errors "X Contains AwaitExpression" see an await expression, which parses as a cover.
Open in the debugger: The specification
- The specification: ends
normal: undefined; prints async function: SyntaxError, async function expression: SyntaxError, async generator: SyntaxError, async generator expression: SyntaxError, async method: SyntaxError, async generator method: SyntaxError, arrow in async body: SyntaxError, async arrow in async body: SyntaxError, AsyncFunction: SyntaxError, AsyncGeneratorFunction: SyntaxError, await in async body: no error, static block in async function: no error, var await in nested function: no error, async arrow parameters: no error, await in static block: SyntaxError, var await in static block function: no error.
Source tests/run/await_in_params_early_errors.js
// expect: normal: undefined
// print: async function: SyntaxError
// print: async function expression: SyntaxError
// print: async generator: SyntaxError
// print: async generator expression: SyntaxError
// print: async method: SyntaxError
// print: async generator method: SyntaxError
// print: arrow in async body: SyntaxError
// print: async arrow in async body: SyntaxError
// print: AsyncFunction: SyntaxError
// print: AsyncGeneratorFunction: SyntaxError
// print: await in async body: no error
// print: static block in async function: no error
// print: var await in nested function: no error
// print: async arrow parameters: no error
// print: await in static block: SyntaxError
// print: var await in static block function: no error
// The early errors "X Contains |AwaitExpression|" (§15.3.1, §15.6.1, §15.8.1,
// §15.9.1): an `await` expression is the cover of UnaryExpression :
// CoverAwaitExpressionAndAwaitUsingDeclarationHead, which Contains counts as an
// AwaitExpression (Erratum ContainsAwaitCover, its test262 reading).
// Contains does not look into nested functions, and a static block's rule is
// on the terminal `await`.
var AsyncFunction = (async function () {}).constructor;
var AsyncGeneratorFunction = (async function* () {}).constructor;
function check(name, run) {
try { run(); print(name + ": no error"); }
catch (e) { print(name + ": " + e.constructor.name); }
}
function script(src) { return function () { (0, eval)(src); }; }
check("async function", script("async function f(x = await 1) {}"));
check("async function expression", script("(async function (x = await 1) {})"));
check("async generator", script("async function* f(x = await 1) {}"));
check("async generator expression", script("(async function* (x = await 1) {})"));
check("async method", script("({ async m(x = await 1) {} })"));
check("async generator method", script("({ async *m(x = await 1) {} })"));
check("arrow in async body", script("async function g() { (x = await 1) => 0; }"));
check("async arrow in async body", script("async function g() { async (x = await 1) => 0; }"));
check("AsyncFunction", function () { AsyncFunction("x = await 1", ""); });
check("AsyncGeneratorFunction", function () { AsyncGeneratorFunction("x = await 1", ""); });
check("await in async body", script("async function h() { await 1; }"));
check("static block in async function", script("(async function () { class C { static { } } })"));
check("var await in nested function", script("async function k(x = function () { var await; }) {}"));
check("async arrow parameters", script("async (x = 1) => await x;"));
check("await in static block", script("class C { static { await 0; } }"));
check("var await in static block function", script("class C { static { (function () { var await; }); } }"));
Each element is a String of one code unit under the default reading; read literally, the Array holds code units.
Open in the debugger: The specification
- The specification: ends
normal: "string".
Source tests/run/errata_split_code_units.js
// expect: normal: "string"
// String.prototype.split with the empty String as separator (Erratum SplitCodeUnitStrings):
// the test262 reading makes each element a String of one code unit.
typeof "ab".split("")[1];
Under the default reading a getter gets its prefix and Array.fromAsync is async.
Open in the debugger: The specification
- The specification: ends
normal: "get size|true".
Source tests/run/errata_createintrinsics_async_argument.js
// expect: normal: "get size|true"
// CreateIntrinsics step 2 (Erratum CreateIntrinsicsAsyncArgument): the
// test262 reading passes a getter its prefix and Array.fromAsync its [[Async]].
var r = [];
r.push(Object.getOwnPropertyDescriptor(Map.prototype, "size").get.name);
r.push(Array.fromAsync([1]) instanceof Promise);
r.join("|");
On a host with B.1.2, a class range between two \c escapes asks IsCharacterClass of each; the default reading gives that production a row.
Open in the debugger: The specification
Run with --annex-b sec-regular-expressions-patterns.
- The specification: ends
normal: true.
Source tests/run/errata_ischaracterclass_control_letter.js
// expect: normal: true
// args: --annex-b sec-regular-expressions-patterns
// A class range between two \c escapes of B.1.2 (Erratum IsCharacterClassControlLetter):
// the test262 reading gives IsCharacterClass a row for ClassEscape :: `c` ClassControlLetter.
/[\c1-\c5]/.test("\x11");
The proposed text throws a RangeError past the implementation's maximum BigInt size; read as written, the engine stops at its own limit.
Open in the debugger: The specification
- The specification: ends
throw: RangeError.
Source tests/run/bigint_huge_left_shift.js
// expect: throw: RangeError
// BigInt::leftShift whose result has more than 2^30 bits throws a RangeError
// (erratum BigIntMaximumSize, proposed reading), not a runtime abort
// (BigInt.shiftLeft).
2n << (1n << 64n);