From eb2dfb2638c8d4d37af804880d89eb70440681a9 Mon Sep 17 00:00:00 2001 From: James Long Date: Thu, 19 Nov 2026 23:10:54 -0500 Subject: [PATCH] refactor(codemode): use the psychoscript package for the language (#65011) --- .oxlintrc.json | 27 - bun.lock | 3 + bunfig.toml | 2 +- packages/codemode/AGENTS.md | 6 +- packages/codemode/README.md | 76 +- packages/codemode/bunfig.toml | 2 - packages/codemode/interpreter-support.md | 731 ---- packages/codemode/package.json | 6 +- packages/codemode/script/bench.ts | 174 - packages/codemode/script/build.ts | 1 - packages/codemode/script/disasm.ts | 263 -- packages/codemode/script/prelude.ts | 30 - packages/codemode/script/setup.ts | 32 - packages/codemode/script/sync-test262.ts | 62 - packages/codemode/script/test262-report.ts | 55 - packages/codemode/src/codemode/codemode.ts | 33 +- packages/codemode/src/codemode/extension.ts | 2 +- packages/codemode/src/codemode/scan.ts | 4 +- .../codemode/src/codemode/tool-runtime.ts | 8 +- packages/codemode/src/language/async.ts | 474 --- packages/codemode/src/language/code.ts | 435 -- .../codemode/src/language/compiler/compile.ts | 1863 --------- .../codemode/src/language/compiler/scope.ts | 736 ---- packages/codemode/src/language/data.ts | 18 - packages/codemode/src/language/generators.ts | 498 --- .../codemode/src/language/host-function.ts | 154 - packages/codemode/src/language/host.ts | 299 -- packages/codemode/src/language/index.ts | 12 - .../codemode/src/language/internal-prelude.ts | 625 --- packages/codemode/src/language/opcodes.ts | 325 -- .../src/language/prelude/bytecode.json | 1 - .../codemode/src/language/prelude/bytecode.ts | 37 - .../codemode/src/language/prelude/helpers.ts | 331 -- .../codemode/src/language/prelude/prelude.ts | 57 - .../codemode/src/language/prelude/source.ts | 693 --- packages/codemode/src/language/runtime.ts | 179 - .../codemode/src/language/runtime/callback.ts | 86 - .../codemode/src/language/runtime/driver.ts | 265 -- .../codemode/src/language/runtime/errors.ts | 233 -- .../codemode/src/language/runtime/execute.ts | 550 --- .../src/language/runtime/extensions.ts | 540 --- .../src/language/runtime/generators.ts | 56 - .../codemode/src/language/runtime/globals.ts | 167 - .../src/language/runtime/interpreter.ts | 141 - .../src/language/runtime/intrinsic-names.ts | 198 - .../src/language/runtime/intrinsics.ts | 127 - .../codemode/src/language/runtime/limits.ts | 21 - .../codemode/src/language/runtime/model.ts | 105 - .../codemode/src/language/runtime/modules.ts | 55 - .../codemode/src/language/runtime/native.ts | 74 - .../codemode/src/language/runtime/objects.ts | 1399 ------- .../src/language/runtime/operations.ts | 396 -- .../codemode/src/language/runtime/promises.ts | 326 -- .../src/language/runtime/references.ts | 78 - .../codemode/src/language/runtime/signals.ts | 90 - .../codemode/src/language/runtime/source.ts | 74 - .../codemode/src/language/runtime/table.ts | 143 - packages/codemode/src/language/scheduler.ts | 165 - packages/codemode/src/language/snapshot.ts | 384 -- .../codemode/src/language/snapshot/codec.ts | 1112 ----- .../src/language/snapshot/snapshot.ts | 143 - .../codemode/src/language/stdlib/array.ts | 362 -- .../codemode/src/language/stdlib/buffer.ts | 312 -- .../codemode/src/language/stdlib/bytes.ts | 380 -- .../src/language/stdlib/collections.ts | 210 - .../codemode/src/language/stdlib/console.ts | 114 - packages/codemode/src/language/stdlib/date.ts | 216 - .../codemode/src/language/stdlib/headers.ts | 92 - .../codemode/src/language/stdlib/iterator.ts | 31 - packages/codemode/src/language/stdlib/json.ts | 51 - packages/codemode/src/language/stdlib/math.ts | 75 - .../codemode/src/language/stdlib/number.ts | 76 - .../codemode/src/language/stdlib/object.ts | 412 -- .../codemode/src/language/stdlib/regexp.ts | 152 - .../codemode/src/language/stdlib/string.ts | 427 -- packages/codemode/src/language/stdlib/url.ts | 310 -- .../codemode/src/language/stdlib/value.ts | 33 - packages/codemode/src/language/stdlib/web.ts | 122 - .../src/language/streaming-response.ts | 11 - packages/codemode/src/language/vm.ts | 3706 ----------------- packages/codemode/test/LICENSE.test262 | 28 - packages/codemode/test/LICENSE.wpt | 11 - .../codemode/test/accessors-suspend.test.ts | 407 -- packages/codemode/test/accessors.test.ts | 453 -- .../test/array-callbacks-test262.test.ts | 394 -- .../codemode/test/array-core-test262.test.ts | 352 -- packages/codemode/test/buffer.test.ts | 85 - packages/codemode/test/build-id.test.ts | 33 - .../codemode/test/bytecode-limits.test.ts | 601 --- packages/codemode/test/callbacks.test.ts | 305 -- .../codemode/test/classes-suspend.test.ts | 236 -- packages/codemode/test/classes.test.ts | 517 --- .../codemode/test/constructor-test262.test.ts | 66 - packages/codemode/test/date-test262.test.ts | 266 -- packages/codemode/test/descriptors.test.ts | 265 -- packages/codemode/test/enumeration.test.ts | 151 - packages/codemode/test/errors.test.ts | 310 -- packages/codemode/test/fixtures/build-id.ts | 8 - .../test/fixtures/prelude-roundtrip.ts | 27 - .../test/fixtures/resume-getters-process.ts | 17 - .../codemode/test/fixtures/resume-process.ts | 16 - .../codemode/test/fixtures/wpt-base64.json | 82 - .../codemode/test/for-await-test262.test.ts | 534 --- .../codemode/test/generator-test262.test.ts | 1311 ------ .../codemode/test/groupby-test262.test.ts | 184 - packages/codemode/test/host-accessors.test.ts | 213 - .../test/json-callbacks-test262.test.ts | 238 -- .../test/labeled-control-test262.test.ts | 249 -- .../codemode/test/language-boundary.test.ts | 33 +- packages/codemode/test/language.test.ts | 365 -- .../codemode/test/lexical-test262.test.ts | 188 - packages/codemode/test/limits.test.ts | 130 - packages/codemode/test/new-expression.test.ts | 80 - .../test/object-coercion-test262.test.ts | 214 - packages/codemode/test/parity.test.ts | 2016 --------- packages/codemode/test/preload.ts | 11 - .../codemode/test/prelude-bytecode.test.ts | 41 - .../codemode/test/promise-test262.test.ts | 1510 ------- packages/codemode/test/promise.test.ts | 1441 +------ .../codemode/test/regexp-math-test262.test.ts | 283 -- packages/codemode/test/resumable.test.ts | 360 -- packages/codemode/test/run-program.ts | 153 - .../codemode/test/set-methods-test262.test.ts | 463 -- packages/codemode/test/snapshot.test.ts | 311 -- packages/codemode/test/state.test.ts | 501 --- packages/codemode/test/stdlib.test.ts | 2246 +--------- .../codemode/test/string-core-test262.test.ts | 758 ---- .../test/string-date-methods-test262.test.ts | 179 - .../test/string-regexp-test262.test.ts | 731 ---- .../test/string-search-test262.test.ts | 811 ---- packages/codemode/test/suspend.test.ts | 298 +- packages/codemode/test/test262.test.ts | 20 - packages/codemode/test/test262/.gitignore | 4 - packages/codemode/test/test262/README.md | 43 - packages/codemode/test/test262/manifest.json | 101 - packages/codemode/test/test262/run.ts | 185 - packages/codemode/test/test262/skipped.txt | 2845 ------------- .../test/var-hoisting-test262.test.ts | 280 -- packages/codemode/test/verify-bytecode.ts | 388 -- packages/codemode/test/vm.test.ts | 584 --- packages/codemode/test/web-wpt.test.ts | 424 -- 141 files changed, 62 insertions(+), 47568 deletions(-) delete mode 100644 packages/codemode/bunfig.toml delete mode 100644 packages/codemode/interpreter-support.md delete mode 100644 packages/codemode/script/bench.ts delete mode 100644 packages/codemode/script/disasm.ts delete mode 100644 packages/codemode/script/prelude.ts delete mode 100644 packages/codemode/script/setup.ts delete mode 100644 packages/codemode/script/sync-test262.ts delete mode 100644 packages/codemode/script/test262-report.ts delete mode 100644 packages/codemode/src/language/async.ts delete mode 100644 packages/codemode/src/language/code.ts delete mode 100644 packages/codemode/src/language/compiler/compile.ts delete mode 100644 packages/codemode/src/language/compiler/scope.ts delete mode 100644 packages/codemode/src/language/data.ts delete mode 100644 packages/codemode/src/language/generators.ts delete mode 100644 packages/codemode/src/language/host-function.ts delete mode 100644 packages/codemode/src/language/host.ts delete mode 100644 packages/codemode/src/language/index.ts delete mode 100644 packages/codemode/src/language/internal-prelude.ts delete mode 100644 packages/codemode/src/language/opcodes.ts delete mode 100644 packages/codemode/src/language/prelude/bytecode.json delete mode 100644 packages/codemode/src/language/prelude/bytecode.ts delete mode 100644 packages/codemode/src/language/prelude/helpers.ts delete mode 100644 packages/codemode/src/language/prelude/prelude.ts delete mode 100644 packages/codemode/src/language/prelude/source.ts delete mode 100644 packages/codemode/src/language/runtime.ts delete mode 100644 packages/codemode/src/language/runtime/callback.ts delete mode 100644 packages/codemode/src/language/runtime/driver.ts delete mode 100644 packages/codemode/src/language/runtime/errors.ts delete mode 100644 packages/codemode/src/language/runtime/execute.ts delete mode 100644 packages/codemode/src/language/runtime/extensions.ts delete mode 100644 packages/codemode/src/language/runtime/generators.ts delete mode 100644 packages/codemode/src/language/runtime/globals.ts delete mode 100644 packages/codemode/src/language/runtime/interpreter.ts delete mode 100644 packages/codemode/src/language/runtime/intrinsic-names.ts delete mode 100644 packages/codemode/src/language/runtime/intrinsics.ts delete mode 100644 packages/codemode/src/language/runtime/limits.ts delete mode 100644 packages/codemode/src/language/runtime/model.ts delete mode 100644 packages/codemode/src/language/runtime/modules.ts delete mode 100644 packages/codemode/src/language/runtime/native.ts delete mode 100644 packages/codemode/src/language/runtime/objects.ts delete mode 100644 packages/codemode/src/language/runtime/operations.ts delete mode 100644 packages/codemode/src/language/runtime/promises.ts delete mode 100644 packages/codemode/src/language/runtime/references.ts delete mode 100644 packages/codemode/src/language/runtime/signals.ts delete mode 100644 packages/codemode/src/language/runtime/source.ts delete mode 100644 packages/codemode/src/language/runtime/table.ts delete mode 100644 packages/codemode/src/language/scheduler.ts delete mode 100644 packages/codemode/src/language/snapshot.ts delete mode 100644 packages/codemode/src/language/snapshot/codec.ts delete mode 100644 packages/codemode/src/language/snapshot/snapshot.ts delete mode 100644 packages/codemode/src/language/stdlib/array.ts delete mode 100644 packages/codemode/src/language/stdlib/buffer.ts delete mode 100644 packages/codemode/src/language/stdlib/bytes.ts delete mode 100644 packages/codemode/src/language/stdlib/collections.ts delete mode 100644 packages/codemode/src/language/stdlib/console.ts delete mode 100644 packages/codemode/src/language/stdlib/date.ts delete mode 100644 packages/codemode/src/language/stdlib/headers.ts delete mode 100644 packages/codemode/src/language/stdlib/iterator.ts delete mode 100644 packages/codemode/src/language/stdlib/json.ts delete mode 100644 packages/codemode/src/language/stdlib/math.ts delete mode 100644 packages/codemode/src/language/stdlib/number.ts delete mode 100644 packages/codemode/src/language/stdlib/object.ts delete mode 100644 packages/codemode/src/language/stdlib/regexp.ts delete mode 100644 packages/codemode/src/language/stdlib/string.ts delete mode 100644 packages/codemode/src/language/stdlib/url.ts delete mode 100644 packages/codemode/src/language/stdlib/value.ts delete mode 100644 packages/codemode/src/language/stdlib/web.ts delete mode 100644 packages/codemode/src/language/streaming-response.ts delete mode 100644 packages/codemode/src/language/vm.ts delete mode 100644 packages/codemode/test/LICENSE.test262 delete mode 100644 packages/codemode/test/LICENSE.wpt delete mode 100644 packages/codemode/test/accessors-suspend.test.ts delete mode 100644 packages/codemode/test/accessors.test.ts delete mode 100644 packages/codemode/test/array-callbacks-test262.test.ts delete mode 100644 packages/codemode/test/array-core-test262.test.ts delete mode 100644 packages/codemode/test/buffer.test.ts delete mode 100644 packages/codemode/test/build-id.test.ts delete mode 100644 packages/codemode/test/bytecode-limits.test.ts delete mode 100644 packages/codemode/test/callbacks.test.ts delete mode 100644 packages/codemode/test/classes-suspend.test.ts delete mode 100644 packages/codemode/test/classes.test.ts delete mode 100644 packages/codemode/test/constructor-test262.test.ts delete mode 100644 packages/codemode/test/date-test262.test.ts delete mode 100644 packages/codemode/test/descriptors.test.ts delete mode 100644 packages/codemode/test/errors.test.ts delete mode 100644 packages/codemode/test/fixtures/build-id.ts delete mode 100644 packages/codemode/test/fixtures/prelude-roundtrip.ts delete mode 100644 packages/codemode/test/fixtures/resume-getters-process.ts delete mode 100644 packages/codemode/test/fixtures/resume-process.ts delete mode 100644 packages/codemode/test/fixtures/wpt-base64.json delete mode 100644 packages/codemode/test/for-await-test262.test.ts delete mode 100644 packages/codemode/test/generator-test262.test.ts delete mode 100644 packages/codemode/test/groupby-test262.test.ts delete mode 100644 packages/codemode/test/host-accessors.test.ts delete mode 100644 packages/codemode/test/json-callbacks-test262.test.ts delete mode 100644 packages/codemode/test/labeled-control-test262.test.ts delete mode 100644 packages/codemode/test/language.test.ts delete mode 100644 packages/codemode/test/lexical-test262.test.ts delete mode 100644 packages/codemode/test/limits.test.ts delete mode 100644 packages/codemode/test/new-expression.test.ts delete mode 100644 packages/codemode/test/object-coercion-test262.test.ts delete mode 100644 packages/codemode/test/parity.test.ts delete mode 100644 packages/codemode/test/preload.ts delete mode 100644 packages/codemode/test/prelude-bytecode.test.ts delete mode 100644 packages/codemode/test/promise-test262.test.ts delete mode 100644 packages/codemode/test/regexp-math-test262.test.ts delete mode 100644 packages/codemode/test/resumable.test.ts delete mode 100644 packages/codemode/test/run-program.ts delete mode 100644 packages/codemode/test/set-methods-test262.test.ts delete mode 100644 packages/codemode/test/snapshot.test.ts delete mode 100644 packages/codemode/test/state.test.ts delete mode 100644 packages/codemode/test/string-core-test262.test.ts delete mode 100644 packages/codemode/test/string-date-methods-test262.test.ts delete mode 100644 packages/codemode/test/string-regexp-test262.test.ts delete mode 100644 packages/codemode/test/string-search-test262.test.ts delete mode 100644 packages/codemode/test/test262.test.ts delete mode 100644 packages/codemode/test/test262/.gitignore delete mode 100644 packages/codemode/test/test262/README.md delete mode 100644 packages/codemode/test/test262/manifest.json delete mode 100644 packages/codemode/test/test262/run.ts delete mode 100644 packages/codemode/test/test262/skipped.txt delete mode 100644 packages/codemode/test/var-hoisting-test262.test.ts delete mode 100644 packages/codemode/test/verify-bytecode.ts delete mode 100644 packages/codemode/test/vm.test.ts delete mode 100644 packages/codemode/test/web-wpt.test.ts diff --git a/.oxlintrc.json b/.oxlintrc.json index 0ad3ae0a5cc..08499c44323 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -179,33 +179,6 @@ } ] } - }, - { - "files": ["packages/codemode/src/interpreter/**", "packages/codemode/src/stdlib/**"], - "rules": { - "no-restricted-imports": [ - "error", - { - "paths": [ - { - "name": "effect", - "allowTypeImports": true, - "message": "The evaluator and built-ins are plain generators driven by the job queue in runner.ts. Start host work with runner.host or block on it with runner.blocking; only runner.ts, execute.ts, and extensions.ts run Effects." - } - ] - } - ] - } - }, - { - "files": [ - "packages/codemode/src/interpreter/runner.ts", - "packages/codemode/src/interpreter/execute.ts", - "packages/codemode/src/interpreter/extensions.ts" - ], - "rules": { - "no-restricted-imports": "off" - } } ], "ignorePatterns": [ diff --git a/bun.lock b/bun.lock index 0223d09fcbe..b2feb884fdb 100644 --- a/bun.lock +++ b/bun.lock @@ -202,6 +202,7 @@ "dependencies": { "acorn": "8.15.0", "effect": "catalog:", + "psychoscript": "0.1.2", }, "devDependencies": { "@tsconfig/bun": "catalog:", @@ -3872,6 +3873,8 @@ "proxy-from-env": ["proxy-from-env@1.1.0", "", {}, "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="], + "psychoscript": ["psychoscript@0.1.2", "", { "dependencies": { "acorn": "8.15.0" }, "peerDependencies": { "effect": "^4.1.0" } }, "sha512-eEuVbhaQ+3MEfi+LTNatMFY0OWcrmZjiUDd/4KVmWOCBTVYY87QoIc/DPNTDu+GVKHDeAPCsIqDq6wVyLMODXA=="], + "pump": ["pump@3.0.4", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA=="], "pupa": ["pupa@3.3.0", "", { "dependencies": { "escape-goat": "^4.0.0" } }, "sha512-LjgDO2zPtoXP2wJpDjZrGdojii1uqO0cnwKoIoUzkfS98HDmbeiGmYiXo3lXeFlq2xvne1QFQhwYXSUCLKtEuA=="], diff --git a/bunfig.toml b/bunfig.toml index 670dc7555a0..812e312a12e 100644 --- a/bunfig.toml +++ b/bunfig.toml @@ -2,7 +2,7 @@ exact = true # Only install newly resolved package versions published at least 3 days ago. minimumReleaseAge = 259200 -minimumReleaseAgeExcludes = ["@ai-sdk/amazon-bedrock", "@ai-sdk/anthropic", "@brendonovich/vite-plugin-opencode", "@hona/strobe", "@hona/strobe-darwin-arm64", "@hona/strobe-darwin-x64", "@hona/strobe-linux-arm64", "@hona/strobe-linux-x64", "@hona/strobe-win32-arm64", "@hona/strobe-win32-x64", "@kitlangton/knobs", "@kitlangton/solid-motion", "@opencode/sdk", "@opencode/pty", "@opencode/pty-darwin-arm64", "@opencode/pty-darwin-x64", "@opencode/pty-linux-arm64-gnu", "@opencode/pty-linux-arm64-musl", "@opencode/pty-linux-x64-gnu", "@opencode/pty-linux-x64-musl", "@opencode/pty-win32-arm64", "@opencode/pty-win32-x64", "@opentui/core", "@opentui/core-darwin-arm64", "@opentui/core-darwin-x64", "@opentui/core-linux-arm64", "@opentui/core-linux-arm64-musl", "@opentui/core-linux-x64", "@opentui/core-linux-x64-musl", "@opentui/core-win32-arm64", "@opentui/core-win32-x64", "@opentui/keymap", "@opentui/solid", "@opentunnel/client", "@opentunnel/protocol", "gitlab-ai-provider", "opencode-gitlab-auth", "@ff-labs/fff-node", "@ff-labs/fff-bun", "@ff-labs/fff-bin-darwin-arm64", "@ff-labs/fff-bin-darwin-x64", "@ff-labs/fff-bin-linux-arm64-gnu", "@ff-labs/fff-bin-linux-arm64-musl", "@ff-labs/fff-bin-linux-x64-gnu", "@ff-labs/fff-bin-linux-x64-musl", "@ff-labs/fff-bin-win32-arm64", "@ff-labs/fff-bin-win32-x64", "@pierre/diffs", "@pierre/highlights", "@pierre/theming", "app-builder-lib", "dmg-builder", "electron", "electron-builder", "electron-publish", "blume", "pele", "bun-types", "typescript@7.1.0-beta", "@textjs/app", "@textjs/core", "@textjs/opencode", "@textjs/react"] +minimumReleaseAgeExcludes = ["@ai-sdk/amazon-bedrock", "@ai-sdk/anthropic", "@brendonovich/vite-plugin-opencode", "@hona/strobe", "@hona/strobe-darwin-arm64", "@hona/strobe-darwin-x64", "@hona/strobe-linux-arm64", "@hona/strobe-linux-x64", "@hona/strobe-win32-arm64", "@hona/strobe-win32-x64", "@kitlangton/knobs", "@kitlangton/solid-motion", "@opencode/sdk", "@opencode/pty", "@opencode/pty-darwin-arm64", "@opencode/pty-darwin-x64", "@opencode/pty-linux-arm64-gnu", "@opencode/pty-linux-arm64-musl", "@opencode/pty-linux-x64-gnu", "@opencode/pty-linux-x64-musl", "@opencode/pty-win32-arm64", "@opencode/pty-win32-x64", "@opentui/core", "@opentui/core-darwin-arm64", "@opentui/core-darwin-x64", "@opentui/core-linux-arm64", "@opentui/core-linux-arm64-musl", "@opentui/core-linux-x64", "@opentui/core-linux-x64-musl", "@opentui/core-win32-arm64", "@opentui/core-win32-x64", "@opentui/keymap", "@opentui/solid", "@opentunnel/client", "@opentunnel/protocol", "gitlab-ai-provider", "opencode-gitlab-auth", "@ff-labs/fff-node", "@ff-labs/fff-bun", "@ff-labs/fff-bin-darwin-arm64", "@ff-labs/fff-bin-darwin-x64", "@ff-labs/fff-bin-linux-arm64-gnu", "@ff-labs/fff-bin-linux-arm64-musl", "@ff-labs/fff-bin-linux-x64-gnu", "@ff-labs/fff-bin-linux-x64-musl", "@ff-labs/fff-bin-win32-arm64", "@ff-labs/fff-bin-win32-x64", "@pierre/diffs", "@pierre/highlights", "@pierre/theming", "app-builder-lib", "dmg-builder", "electron", "electron-builder", "electron-publish", "blume", "pele", "bun-types", "typescript@7.1.0-beta", "@textjs/app", "@textjs/core", "@textjs/opencode", "@textjs/react", "psychoscript"] [test] root = "./do-not-run-tests-from-root" diff --git a/packages/codemode/AGENTS.md b/packages/codemode/AGENTS.md index 75f76b24bf9..db2775fc392 100644 --- a/packages/codemode/AGENTS.md +++ b/packages/codemode/AGENTS.md @@ -1,7 +1,3 @@ # @opencode/codemode -- `src/language/` is the language layer (compiler, VM, runtime, stdlib, prelude, scheduler, snapshots, and the Effect driver); `src/codemode/` is Code Mode, built on it (tools, schemas, catalog, `search`, `scanTools`, OpenAPI, hooks, `maxToolCalls`). Nothing in `src/language/` imports from the rest of `src` (`test/language-boundary.test.ts`), and the language never knows what a tool is: Code Mode gives programs its functions through `Host` and `Runtime.make`. -- `interpreter-support.md` is a checklist, not a changelog: check off newly added support and add unchecked items for significant gaps. Leave it alone for fixes and refactors. -- Program values are `Value` (`src/language/runtime/objects.ts`). Host values are `unknown` and enter only through `fromHost` and `fromJson`; do not widen program-facing signatures to `unknown`. -- Each built-in object kind is one `Obj` subclass (`Wrapper` or `Opaque`) that overrides the hooks it needs. Ask the object instead of adding `instanceof` ladders. -- The core VM, compiler, prelude, snapshot, and stdlib modules must not import `effect`; in `src/language/`, Effect lives only in the host boundary and driver (`runtime.ts`, `host-function.ts`, `runtime/driver.ts`, `runtime/execute.ts`, `runtime/extensions.ts`). `src/codemode/` uses Effect freely. +- The language (compiler, VM, runtime, stdlib, snapshots, Effect driver) is the `psychoscript` package (https://github.com/anomalyco/psychoscript). Language changes go there, get published, and are then bumped here. `src/codemode/` is Code Mode, built on it (tools, schemas, catalog, `search`, `scanTools`, OpenAPI, hooks, `maxToolCalls`): it gives programs its functions through `Host` and `Runtime.make`, and imports only `psychoscript`'s package entry (`test/language-boundary.test.ts`). diff --git a/packages/codemode/README.md b/packages/codemode/README.md index f70609bad5d..6e3a48663bc 100644 --- a/packages/codemode/README.md +++ b/packages/codemode/README.md @@ -1,8 +1,8 @@ # @opencode/codemode This is our take on code mode: a lightweight, pure interpreter for a JavaScript-like language built around calling -tools. It supports familiar JavaScript syntax with a few key differences and limitations. See the -[interpreter support checklist](./interpreter-support.md) for more details. +tools. The language itself is [psychoscript](https://github.com/anomalyco/psychoscript); see its interpreter support +checklist for what is supported. Rather than trying to sandbox arbitrary JavaScript, CodeMode only runs the language features we implement. Programs cannot directly access the network, filesystem, processes, or application APIs. They can interact with the outside @@ -21,20 +21,15 @@ The idea of code mode was originally introduced by Cloudflare. See - **REPL-style results.** Without an explicit `return`, the final top-level expression becomes the result. `undefined` becomes `null`. -Unsupported syntax returns an `UnsupportedSyntax` diagnostic with a source location. Current gaps are tracked in the -[interpreter support checklist](./interpreter-support.md). +Unsupported syntax returns an `UnsupportedSyntax` diagnostic with a source location. Current gaps are tracked in +psychoscript's interpreter support checklist. ## Layout -The package is two layers, as folders under `src/`: - -- `src/language/` is the language: the compiler, VM, runtime, standard library, prelude, scheduler, snapshots, and the - Effect driver. It knows nothing about tools. A host gives programs its functions with `Host` and runs them with - `Runtime.make` (see [The language layer](#the-language-layer)). -- `src/codemode/` is Code Mode, built on the language: tools and their schemas, the catalog and namespaces, `search`, - `scanTools`, OpenAPI, hooks, `maxToolCalls`, `CodeMode.make`, and `Extension.make`. - -Nothing in `src/language/` imports from `src/codemode/`; a test checks it. The package's public API is Code Mode's. +The language (compiler, VM, runtime, standard library, snapshots, and the Effect driver) is the +[`psychoscript`](https://www.npmjs.com/package/psychoscript) package. `src/codemode/` is Code Mode, built on it: tools +and their schemas, the catalog and namespaces, search, scanTools, OpenAPI, hooks, maxToolCalls, CodeMode.make, +and Extension.make. ## Quick Start @@ -218,14 +213,11 @@ can't be saved or is too large fails the suspend the same way. A resumed run keeps the limits it was saved with: `timeoutMs` counts active time across every resume, and `maxToolCalls` counts every admitted call of the run (Code Mode keeps them in the run's `metadata`, saved with the state). A state -resumes only on the same build of this package and with the same host globals (the same extension globals, with the +resumes only on the same build of psychoscript and with the same host globals (the same extension globals, with the same `snapshot` hooks). The state is checked when the resumed program runs: its `run()` fails with a `CodeMode.SnapshotError` when it can't be resumed here or is malformed. Built-ins are saved by name and only their changes are copied. -Set `CODEMODE_ROUNDTRIP=1` (`bun run test:roundtrip`) to run the tests with every run saved to bytes and -restored into a brand-new runtime at every host call and every few steps. - ### `Extension.make` Extensions are host functions a program calls directly as globals, such as `fetch`. Unlike tools they are not in the @@ -342,54 +334,8 @@ responses pass through unchanged. See `src/codemode/openapi/types.ts` for option ## The language layer -Code Mode is built on the language layer in `src/language/`, which runs programs over any host globals. It is not part -of the package's public API yet. - -```ts -import { Host, Runtime } from "./src/language/index.js" - -const runtime = Runtime.make({ - // Called when a run starts, and again when it resumes, so globals can keep the run's own state. - globals: (run) => ({ - hash: Host.fn(([text]) => sha256(text as string)), // "sync" (the default): the program waits for it - sleep: Host.fn(([ms]) => Effect.sleep(ms as number), { type: "async" }), // the program gets a promise - find: Host.fn(([query]) => searchIndex(query), { type: "sync-thenable" }), // the object now, also awaitable - lookup: Host.fn(([id], { key }) => Db.get(id, key), { type: "async", idempotent: true }), // rerun on resume - review: Host.durableFn({ start, wait, cancel }), // keeps running across a suspend - api: Host.namespace({ - keys: (path) => childrenOf(path), // Object.keys and for...in - resolve: (path) => fnAt(path) ?? Host.missing(`No api.${path.join(".")}`, suggestionsFor(path)), - }), - fs: { readFile: Host.fn(([file]) => read(file), { type: "async" }) }, // plain objects of functions work too - }), - limits: { timeoutMs: 30_000, maxOutputBytes: 1_000_000 }, -}) - -const program = runtime.program(code, { bindings: { repo: "…" }, runId }) -yield* program.run() // Result | Suspended -yield* program.suspend({ maxBytes }) -yield* runtime.resume(bytes).run() -``` - -- **`Host.fn(f, { type, idempotent })`.** `f` gets the program's arguments, as they crossed, and the call, `{ key }` - (`:`). `sync` (the default) blocks the program: an Effect runs until it ends, and a returned Promise - is a promise. `async` hands the program a promise. `sync-thenable` returns the result at once, with hidden - `then`/`catch`/`finally`. `idempotent: true`, only with `async`, lets a suspend interrupt a call in progress, which - runs again on resume under the same key; any other call in progress refuses a suspend. `constructible: true` lets - the program call it with `new`. `takesFunctions: true` lets the program pass back a function that was inside a - result, which arrives as the host function itself, and a call holding one refuses a suspend until it completes; - without it, such a function is treated like any other function in an argument: refused, or left out when the - runtime's `translate.functions` is `"drop"`. -- **`Host.durableFn({ start, wait, cancel })`.** `start` gives JSON data, saved with the run; `wait(data)` runs right - after, and again after a resume; `cancel(data)` only when the run is interrupted or ends with the work still running. -- **`Host.namespace({ keys, resolve })`.** A lazy object of functions addressed by path, for catalogs too large to - build as objects. Any path can be read; calling one asks `resolve` for its function, or a failure it throws. -- **`Host.fail(kind, message, suggestions?)`.** A failure with its own diagnostic kind, to throw or fail with. -- **`run.metadata`.** The host's own JSON state for the run: saved with a suspended run, given back on resume, and in - the run's result. Code Mode keeps `toolCalls` and `maxToolCalls` there. - -Every host function gets the same structured translation: arguments and results cross as copies (plain data, `Date`, -`Map`, `Set`, `Uint8Array`, `URL`, `Headers`, errors), and a function inside a result is callable. +Code Mode is built on [psychoscript](https://github.com/anomalyco/psychoscript), which runs programs over any host +globals given through Host and Runtime.make. See its README for that API. ## Results diff --git a/packages/codemode/bunfig.toml b/packages/codemode/bunfig.toml deleted file mode 100644 index 786a3774447..00000000000 --- a/packages/codemode/bunfig.toml +++ /dev/null @@ -1,2 +0,0 @@ -[test] -preload = ["./test/preload.ts"] diff --git a/packages/codemode/interpreter-support.md b/packages/codemode/interpreter-support.md deleted file mode 100644 index 5cfe1681d1d..00000000000 --- a/packages/codemode/interpreter-support.md +++ /dev/null @@ -1,731 +0,0 @@ -# CodeMode Interpreter Support - -This is the checkable support matrix for CodeMode's confined JavaScript interpreter. It tracks the language and -standard-library surface that programs can use today, plus concrete gaps that may be implemented later. - -- `[x]` means the feature is implemented at the scope described here. -- `[ ]` means a concrete compatibility gap remains. -- Checked items do not promise complete ECMAScript edge-case parity; known differences are stated explicitly. -- Intentional boundaries are not listed as compatibility work. - -Check off items as support lands and add unchecked items for significant gaps. The implementation and tests remain -the ultimate source of truth. Upstream test262 files run verbatim from `test/test262`; a failing file is listed in -`test/test262/skipped.txt` and its gap is an unchecked item here (see `test/test262/README.md`). - -## Source and execution model - -- [x] JavaScript parsed with the latest syntax accepted by Acorn, then restricted by the interpreter allowlist. - TypeScript-only syntax is rejected rather than stripped before execution. -- [x] Top-level `await` and `return` through the program's implicit async-function scope. -- [x] Explicit `return`, final top-level expression as a REPL-style result, and `null` when no value is produced. -- [x] The result boundary is `JSON.stringify` plus a short table. The program result crosses as - what `JSON.stringify` would serialize: `toJSON` is honored, functions and `undefined` properties vanish, - `undefined` array elements and non-finite numbers become `null`, a cyclic value throws the same `TypeError`, - and Map, RegExp, and generators serialize as `{}`. A bare `undefined` result is `null`. - Tool results come back the way `JSON.parse(JSON.stringify(result))` would. The table, where a value cannot - be JSON but what the program meant is clear: a promise is awaited (a rejection fails the program), a Set - crosses as an array, a URLSearchParams as its query string, an Error as `{ name, message, ...own enumerable }`, - and own `__proto__` keys are dropped so merging results cannot replace a prototype. Tool arguments cross as - copies, like extension arguments, and the tool layer turns them into JSON with the same table (a Uint8Array is - rejected with a hint to encode as text); a program's own `toJSON` is not called there, and a promise or function - inside an argument fails the call. In-program `JSON.stringify` keeps JS behavior except for the Error form and a - promise, which is a `TypeError` with an await hint rather than a silent `{}`. -- [x] Live Date, RegExp, Map, Set, URL, URLSearchParams, Headers, and Uint8Array values inside CodeMode. -- [x] Tool calls through the host-provided `tools` tree only. -- [x] Imports of globals by Node module name: `import x from "m"`, `import { a, b as c } from "m"`, - `import * as m from "m"`, `import "m"`, `require("m")`, and `await import("m")`, with `node:fs` naming the - same module as `fs` and `fs/promises`, `url`, `util`, and `buffer` mapped to their globals. Imports load before - the program runs; a default import binds the module itself and the namespace adds it as `default`, the way - Node presents a CommonJS module. Anything else throws, and `import()` of it rejects. `export` is a parse error, - and an import below the top level throws. -- [x] The global `search(...)` built-in: synchronous tool discovery that counts as an admitted tool call and is - shadowable by program declarations like other globals. Its result can also be awaited or chained with - `then`, `catch`, and `finally`. -- [x] Cooperative timeout, an optional total tool-call limit, output bounding, and unrestricted tool-call concurrency. -- [x] The timeout fires between interpreter steps, so one built-in is bounded in what it may build: strings up to - 2^24 characters (`repeat`, `pad*`, `concat`, `join`, `+`, template literals, `JSON.stringify`), arrays up to - 10,000,000 elements (`Array(n)`, `length =`, `Array.from`, `split`, `matchAll`, `concat`, `flat`; below the JS - maximum of 2^32 - 1), and 10,000 pending promises at once. Exceeding one throws a `RangeError`. A single regular - expression match can still run long on a pathological pattern; the host regex engine has no interrupt hook. -- [x] A trailing comma after a rest parameter is a syntax error, with or without `"use strict"`. -- [x] A program that begins with `"use strict"` rejects `yield` as an identifier and duplicate parameter names at - parse time. Without it, `yield` is an ordinary binding. -- [x] Duplicate parameter names in non-strict code bind the last parameter, as in JS (`function f(a, a)` called - with `(1, 2)` sees `a === 2`). - -## Values and literals - -- [x] `null`, `undefined`, booleans, finite and non-finite numbers, and strings. -- [x] Array literals, including holes and spread from arrays, strings, Maps, Sets, URLSearchParams, Headers, custom - synchronous iterators, and synchronous generators. -- [x] Object literals with shorthand, computed string/number keys, and spread following ToObject: data objects and - arrays copy own enumerable keys, strings copy index keys, and other values contribute nothing. -- [x] Template literals with interpolation. -- [x] Tagged templates: a tag applied to a template literal is called as `tag(strings, ...values)`, with the tag read - like a callee so a member tag keeps its receiver. `strings` is an array of the cooked text with a read-only `raw` - array of the source text; an invalid escape such as `\unicode` cooks to `undefined`. One template object per - site, as in JS, but it is not frozen: `strings[0] = "x"` succeeds here where JS throws. -- [x] Regular-expression literals. -- [x] `NaN` and `Infinity` globals. -- [ ] BigInt literals and in-interpreter BigInt arithmetic; BigInt remains invalid at JSON-like host boundaries. -- [ ] Arbitrary Symbol primitive values and symbol-keyed properties. The confined `Symbol.iterator` and - `Symbol.asyncIterator` keys are available only for the iterator protocols. -- [x] Getter and setter definitions in object literals (`get x() {}`, `set x(v) {}`, computed and symbol keys), named - `get x` / `set x`. Every read and write honours program accessors: member and computed reads, method calls, - destructuring, `=`, compound and logical assignment, `++`/`--`, inherited setters (with a primitive as `this` - through a wrapper prototype), and `instanceof`'s `prototype`. Spread, rest, `Object.assign`, `entries` and - `values` call getters in key order (and `assign` runs the target's setters); `JSON.stringify`, `structuredClone` - and the program's result call getters and leave setter-only properties out; the iterator protocol's `next`, - `done`, `value`, `return` and `[Symbol.iterator]` may be getters. `console.log` and `console.table` never call - them and show `[Getter]`, `[Setter]` or `[Getter/Setter]`; `Object.keys`, `for...in`, `in` and - `hasOwnProperty` never call them either. A suspended run resumes inside a getter or setter. -- [ ] Getters and setters in classes (classes are unsupported), `__defineGetter__` and friends. -- [ ] Built-ins that read program getters ahead (`Array.from` on an array-like, `apply`, `structuredClone`, - `String.raw`, `Buffer.from`, `TextDecoder` options, `Headers`/`URLSearchParams` records, `new Error`'s - `cause`, `defineProperties`, host arguments) call each getter once per receiver and key per call, in rounds: - a value reached twice in one call reuses the first read, and the order across rounds can differ from JS's - interleaving. `Array.from` on an iterable reads a `[Symbol.iterator]` getter twice. - -## Bindings and destructuring - -- [x] `const`, `let`, and `var` declarations. -- [x] Object and array destructuring in declarations, parameters, assignment expressions, and `for...of` bindings. -- [x] Nested patterns, defaults, elisions, and rest elements. -- [x] Assignment to identifiers, plain-object fields, non-negative integer array indexes, and writable URL - fields. -- [x] Direct function declarations are hoisted in program and block statement lists. -- [x] Parameter defaults observe a temporal dead zone for later parameters. -- [x] `var` is function-scoped and hoisted: names declared anywhere in a function or program body, including loop - heads, blocks, `switch` cases, and `try`/`catch`, read as `undefined` before their statement runs; redeclaration - assigns the one binding; a same-named parameter keeps its argument; closures in parameter defaults see outer - names rather than body `var`s. -- [x] Predeclare `let` and `const` bindings in every lexical scope, including program/block bodies, switch bodies, and - loop headers, so reads before initialization and self- or cross-referential initializers observe the JavaScript - temporal dead zone. -- [x] Function declarations are hoisted across all cases of a `switch`, like any other statement list. -- [x] Computed object destructuring keys such as `const { [field]: value } = record`. -- [x] Object destructuring from arrays, such as `const { length } = values`. -- [x] Array binding and assignment destructuring from strings, Maps, Sets, URLSearchParams, custom synchronous - iterators, and synchronous generators, including stepwise elisions/rest and `IteratorClose` on early completion - or binding/default failure. -- [x] Object destructuring from primitives follows ToObject: `const { length } = "abc"` is `3`, `const { toFixed } = 1` - finds the built-in, `const {} = 1` is a no-op, and a rest element copies a string's indexes (`{ 1: "y", 2: "z" }`). - Only `null` and `undefined` sources throw (`Cannot destructure null as it is null.`). -- [x] Destructuring reads through the prototype chain like member access: `const { constructor } = error` and - `const { slice } = values` find the inherited built-in. -- [x] Any assignment target as a `for...in` head, like `for...of`: `for (x.y in obj)`, `for (a[i++] in obj)`, and - destructuring patterns. - -## Statements and control flow - -- [x] Blocks and empty statements. -- [x] `if`/`else` and conditional expressions. -- [x] `switch`, including default clauses and fallthrough. -- [x] `for`, `while`, and `do...while`. -- [x] `for...of` over arrays, strings, Maps, Sets, URLSearchParams, Headers, Uint8Arrays, built-in iterators, custom - synchronous iterators, and confined synchronous generators. Abrupt completion invokes the iterator's optional `return()`. -- [x] `for...in` over own keys of plain objects, arrays, strings, and tool references. `null`, `undefined`, and other - non-objects iterate nothing. An un-awaited promise throws rather than iterating. -- [x] `for...in` over inherited enumerable keys (`Object.create(proto)`): own keys first, then each prototype's, skipping - keys a nearer level already has, even as a non-enumerable property. -- [ ] `for...in` skipping keys deleted during the loop. -- [x] Unlabeled `break` and `continue`. -- [x] `try`, `catch`, optional catch bindings, and `finally`. -- [x] `throw` with arbitrary values. -- [x] Labeled statements, labeled `break`, and labeled `continue`. -- [x] `for await...of` over the supported synchronous collections and custom iterator objects using - `Symbol.asyncIterator` or the `Symbol.iterator` fallback. Each iterator step is sequential, yielded promises and - plain values from synchronous collections and sync iterators are awaited before binding, and abrupt loop - completion invokes the iterator's optional `return()`. Custom async iterators control their yielded values, as in - JavaScript; only their `next()` results are awaited. Confined sync and async generators are iterable here. - -## Functions and callbacks - -- [x] Function declarations, function expressions, and arrow functions. -- [x] Synchronous and `async` functions. A line break between `function` and the name is allowed, as in JavaScript; - a line break between `async` and `function` is not an async function. -- [x] Closures, recursion, default parameters, rest parameters, and destructured parameters. -- [x] A call depth limit of 10000: deeper nesting throws a catchable `RangeError: Maximum call stack size exceeded` - at the overflowing call instead of running until the timeout. Callbacks invoked by built-ins count below the - call that invoked the built-in, and a resumed `await` starts from depth 0 as in JS, so long async chains such - as recursive pagination are unaffected. -- [x] Expression and block function bodies. -- [x] User callbacks for the supported Array, Map, Set, URLSearchParams, sort, string-replacement, and `Array.from` - mapper APIs, with one shared acceptance rule everywhere including promise reactions. -- [x] `Boolean`, `Number`, `String`, `parseInt`, `parseFloat`, `isFinite`, `isNaN`, and URI helpers as callbacks. -- [x] Built-in method references as callbacks, such as `values.map(Math.abs)`, `records.map(JSON.stringify)`, - `items.forEach(console.log)`, and `Promise.resolve(-1).then(Math.abs)`. Extra callback arguments a built-in - does not consume are ignored, like JS, and consumed arguments coerce, like JS (`"3.7".replace(/\d\.\d/, -Math.floor)` is `"3"`). A detached method loses its receiver, as in JS: `values.filter("abc".includes)` is a `TypeError` - because `includes` is called without a string `this`. -- [x] Constructors work as callbacks with JS call semantics: `Error` types construct (`messages.map(Error)`), - and new-requiring constructors (`Map`, `Set`, `URL`, `URLSearchParams`, `Headers`, `Promise`) throw a `TypeError`, - like JS. -- [x] Tool references and detached `Promise` statics are rejected as callbacks with a hint to wrap them in an - arrow function. -- [x] Promise-returning string replacers are coerced synchronously to `"[object Promise]"`, like JavaScript; they are - not automatically awaited. -- [x] `this` in non-arrow functions is the call's receiver: `obj.m()` and `obj["m"]()` see `obj`, a bare or detached - call (`f()`, `const m = obj.m; m()`, `(0, obj.m)()`) sees `undefined`, as in strict JS. Arrows read the enclosing - function's `this`. Program code has no receiver, so top-level `this` is `undefined`, as in a module. -- [x] `arguments` in non-arrow functions: an unmapped ordinary object with the call's arguments as indexed - properties and a hidden `length`; iterable, so spread, `for...of`, and `Array.from` work. It is not an Array - (`JSON.stringify` gives `{"0":1}`, `String` gives `[object Arguments]`). A parameter named `arguments` shadows - it; arrows read the enclosing function's; it is only created for functions whose body mentions it. `callee` - and `caller` are absent rather than poisoned. -- [ ] Array methods on `arguments` and other array-likes (`Array.prototype.slice.call(arguments, 1)`); use - `[...arguments]` or a rest parameter meanwhile. -- [x] `Function.prototype.call`, `apply`, and `bind` on program functions and built-ins: - `Array.prototype.push.call(arr, 1)`, `Math.max.apply(null, values)`, `fn.bind(obj, first)`. `apply` accepts an - array, an array-like object (its `length` clamped and capped like `Array.from`), or `null`/`undefined`. A - bound function is named `bound f`, has its remaining `length`, and is not constructible. -- [x] `JSON.parse` revivers and `JSON.stringify` function replacers see the holder object as `this`. -- [x] The optional `thisArg` of the Array, Uint8Array, and `Array.from` callback methods and of Map, Set, - URLSearchParams, and Headers `forEach` is the callback's `this`: `[1, 2].forEach(function () { this.n++ }, c)` - increments `c.n` twice. Arrows ignore it, as in JS; `reduce`/`reduceRight` take an initial value instead. -- [ ] User-defined constructor calls. -- [ ] Classes and private fields. -- [x] Functions are objects: they hold own properties (`fn.count = 1`), enumerate them, and expose read-only `name` - and `length`. Names follow JavaScript's NamedEvaluation: declarations, named expressions, bindings, - assignments, object literal keys, and destructuring or parameter defaults. -- [x] Built-in functions are objects too, with `name` and `length` (`Math.max.length === 2`, - `Array.prototype.push.name === "push"`). -- [x] A named function expression's name is bound read-only inside its own body; assigning to it throws a - `TypeError`, as in strict mode. -- [x] Redeclaring a function in the same scope, or alongside a `var`, is allowed: the last declaration wins. -- [x] Generator functions have their own `prototype` (inheriting the shared generator prototype), so - `g() instanceof g` holds. Plain functions have none, since they cannot construct. -- [ ] `GeneratorFunction.prototype`: every function, generator or not, inherits directly from `Function.prototype`, - and a generator whose `prototype` was replaced by a non-object still creates from the shared generator prototype. -- [x] Generator and async generator functions bind parameters (defaults, destructuring) at the call and defer only the - body to the first `next()`, so a bad argument throws synchronously from the call site, as in JS. -- [x] Synchronous and async generator declarations/expressions, `yield`, and `yield*`, including lazy bodies, - `next(value)`, `return(value)`, `throw(value)`, exhaustion, promise adoption, async request ordering, - `try`/`catch`/`finally`, and sync/async iterator symbols. Async `yield*` awaits values while adapting a sync - iterator but preserves values supplied by a manually implemented async iterator. Generator values are opaque - runtime references. -- [x] Synchronous generators and custom synchronous iterators are consumed stepwise by array/argument spread, array - destructuring, `Array.from`, Map/Set/URLSearchParams construction, `Object.fromEntries`, Object/Map `groupBy`, - Promise combinators, `AggregateError`, and `Math.sumPrecise`. Mapper/grouping callbacks interleave with iterator - steps; synchronous consumers preserve yielded promise objects rather than awaiting them. Async generators are - rejected by every synchronous consumer. -- [x] Synchronous iterator acquisition and result validation follow `IteratorClose` boundaries: consumer errors and - intentional early stops invoke `return()`, acquisition/`next()` failures do not, and an original consumer error - wins over a cleanup failure. A generator's `return()` is an intentional stop, so a `return()` that throws or - yields a non-object surfaces from it as a `TypeError`. Async iterator consumption remains limited to `for await...of` and async `yield*`. -- [x] Portable generator protocol coverage is adapted from pinned Test262 cases for suspended-start, suspended-yield, - and completed states; sync and async `next`/`return`/`throw`; finally yields and completion overrides; rejected - yielded promises; mixed async request queues; sync and async `yield*` forwarding; malformed methods/results; - and declaration, expression, and object-method forms with closure and parameter behavior. The adapted suite - deliberately skips Test262 variants whose observation mechanism requires unsupported getter definitions, - proxies, prototype inspection or mutation, classes, or arbitrary symbols. It also skips tests - asserting exact promise reaction-turn counts beyond the observable ordering guarantee documented below. These - are interpreter-surface boundaries, not claims that the corresponding full Test262 families pass unchanged. - -## Expressions and operators - -- [x] Property access with dot or computed bracket syntax. -- [x] Optional property access and optional calls. -- [x] Function/tool calls and spread arguments. -- [x] Sequence expressions (the comma operator). -- [x] `await` for CodeMode promises and callable thenables; a plain value passes through unchanged, though every - `await` still defers its continuation one reaction turn. -- [x] `new` for Array, Object, Error types, Date, RegExp, Map, Set, URL, URLSearchParams, Headers, and Promise. `new` - on any other value throws a catchable `TypeError` naming the callee: other built-in functions such as `Number` - say `new` is unsupported and point at the plain call, user-defined functions report the constructor gap below, - and non-callable values are not constructors. Error constructors take the ES2022 options object, so - `new Error(message, { cause })` installs a non-enumerable `cause` when the option is present. `Error.isError` - is true for every Error value. -- [x] Arithmetic operators: `+`, `-`, `*`, `/`, `%`, and `**`. -- [x] Equality and ordering: `==`, `!=`, `===`, `!==`, `<`, `<=`, `>`, and `>=`. -- [x] Bitwise operators: `&`, `|`, `^`, `~`, `<<`, `>>`, and `>>>`. -- [x] Logical operators: `&&`, `||`, `??`, and `!`, with short-circuiting. -- [x] Unary `+`, unary `-`, `void`, `typeof`, `instanceof` (through the constructor's `prototype`, so - `[] instanceof Object` holds), and `in` across the prototype chain. -- [x] Prefix and postfix `++` and `--`. -- [x] Plain, arithmetic, bitwise, and logical assignment operators. -- [x] Property deletion on plain data objects and arrays, including computed and optional forms; deleting an array index - creates a hole without changing its length. Deleting a non-configurable property (`length`) or - assigning a read-only one (`Math.PI`, `fn.name`) throws a `TypeError`, as in strict mode. `delete` of a - non-reference (`delete 0`, `delete f()`) evaluates the operand and is `true`; `delete x` on a variable throws. -- [x] Coercion helpers and template interpolation accept functions and namespaces: `String(fn)` and `${fn}` give - `"[object Function]"` rather than the source text, `isNaN(fn)` is `true`. -- [x] `==` and `!=` follow IsLooselyEqual: objects (including functions and tool references) compare by identity, a - nullish operand never coerces the other side, and a data object facing a primitive converts through its own - `valueOf`/`toString` (default hint) (`fn == null` is `false`, `fn == fn` is `true`, `[1] == 1` and `[1, 2] == "1,2"` are `true`). - `switch` matches cases with `===`, so `switch (fn) { case fn: }` selects, and `Object.is` compares any two - values. Operators inspect only their direct operands, so `rows == null` on a large array costs the same as - `rows === null`, and an object merely holding a function inside (`[fn] + ""`, `-[fn]`) coerces like any other - data object (`"[object Function]"`, `NaN`). -- [ ] Coercing a function, promise, generator, or tool reference itself: `fn + ""`, `-fn`, `fn++`, and `fn == 1` - throw `TypeError: Binary operators require data values.` (or the unary/update form) where JavaScript would use - the source text or `NaN`. -- [x] ToPrimitive on program objects: `+ - * / % **`, the relational and bitwise operators, unary `+ - ~`, `++`/`--`, - compound assignment, `${x}`, `Number`/`String`/`isNaN`/`isFinite`, `parseInt`/`parseFloat` (text and radix), - `Math.*` arguments, `Error(message)`, and `Array.prototype.join`/`toString` elements call the object's own - `valueOf`/`toString` in spec order (both operands left then right, `+` with the default hint) and surface their - throws: `{ valueOf() { return 7 } } * 2` is `14`, `` `${{ toString() { return "x" } }}` `` is `"x"`, and - `[1, 2]` with `arr.toString = () => "x"` makes `arr + ""` `"x"`. Dates keep their `Symbol.toPrimitive` - behavior (`date + 1` concatenates, `date - date` subtracts). -- [x] String and Number method arguments convert through ToPrimitive in spec order, receiver first: search strings, - separators, fills, and replacements with the string hint, indexes, counts, digits, and radixes with the number - hint (`"abc".indexOf({ toString() { return "b" } })` is `1`, `(255).toString({ valueOf() { return 16 } })` is - `"ff"`, `String.prototype.trim.call({ toString() { return " a " } })` is `"a"`). Only consumed positions - convert; a RegExp pattern is used as is, and `includes`/`startsWith`/`endsWith` reject one before converting. -- [ ] ToPrimitive elsewhere: `Error.prototype.toString` on an object `message` and numeric arguments of the Array and - Uint8Array methods (`at`, `indexOf` start, `slice`) still use the built-in form (`NaN`, `"[object Object]"`) and - ignore own methods. -- [x] Property keys follow ToPropertyKey: `x[null]` and `x[true]` become string keys, and a data object key - converts through its own `toString`/`valueOf` (string hint) exactly once per access, in reads, writes, - compound assignment, `++`, `delete`, `in`, object literals, and destructuring: - `o[{ toString() { return "id" } }] += 1` updates `o.id`. A nullish base throws before the key converts, as - in JS. Opaque values (functions, promises, tool references) keep their built-in string form. - -## Promises and tools - -- [x] Tool calls start eagerly and return supervised, run-once CodeMode promises. -- [x] Direct `await`, repeated awaits, and recursive thenable assimilation when a promise or thenable is returned from - a function/program. -- [x] `Promise.resolve` and `Promise.reject`. -- [x] `Promise.all`, `Promise.allSettled`, `Promise.race`, and `Promise.any` over finite collections, custom synchronous - iterators, and synchronous generators containing promises and plain values. -- [x] `Promise.all` preserves result order and rejects on the first observed failure without cancelling siblings. -- [x] `Promise.allSettled` returns plain fulfilled/rejected outcome records. -- [x] `Promise.race` settles from the first result without cancelling losers at settlement time. -- [x] Real promise values from `Promise.all`, `Promise.allSettled`, and `Promise.race`; separately constructed - combinator batches overlap as in normal JavaScript. -- [x] Promise chaining with `.then`, `.catch`, and `.finally`: handlers run deferred in attach order, returned - promises are adopted, handler throws reject the derived promise, `.finally` preserves the original settlement - unless its cleanup fails, and direct self-resolution rejects with a `TypeError`. -- [x] Every `await` (including of plain values and already-settled promises) defers its continuation one reaction - turn, so concurrent async functions interleave at await points as in JavaScript. -- [x] Each job runs to completion: code between two awaits, and an async function's body up to its first await, - finishes before another job runs, even when the scheduler preempts a long job. Tool calls still run - concurrently. -- [x] Combinators settle one reaction turn after their deciding member (V8-observable ordering): reactions already - attached to members run first, and an aggregate cannot beat a plain value settling in the same turn into a - `Promise.race`. Exact microtask-count parity beyond this observable ordering is not a documented guarantee. -- [x] All still-pending work (race losers, fail-fast `Promise.all` stragglers, and un-awaited calls alike) is - interrupted when the program returns; rejections that settled un-awaited become `Success.warnings` - diagnostics. A combinator abandoned inside its final settlement turn counts as pending and is interrupted - without a warning. -- [x] `try`/`catch` can handle awaited tool and promise failures. -- [x] `Promise.any`: first fulfillment wins; all-rejected rejects with an `AggregateError` whose `errors` array holds - the catch-normalized reasons in input order, and empty input rejects with an empty `AggregateError`. -- [x] `new Promise((resolve, reject) => ...)`: the executor runs synchronously and receives first-class resolve/reject - callables that settle the promise exactly once (they may escape the executor and settle later); an executor - throw rejects unless the promise already settled, resolving with a promise or callable thenable adopts it, and - resolving with the promise itself rejects with a `TypeError`. Resolver callables work anywhere callbacks are - accepted, including `.then`/`.catch` handlers and collection callbacks, and vanish at the data boundary like - any function. -- [x] `Promise.withResolvers()`: the same promise and resolver callables as the constructor, as a `{ promise, resolve, -reject }` object. -- [x] `Promise.try(fn, ...args)`: calls `fn` synchronously; a throw rejects, a return fulfils, and a returned promise or - thenable is adopted. -- [x] Recursive assimilation of objects with an own callable `then` field across `Promise.resolve`, combinators, - constructors, reactions, `finally`, `await`, and async returns. Thenable methods run deferred, receive - first-call-wins resolve/reject functions, and ignore throws after settlement. Inherited and accessor `then` - fields are supported; an accessor `then` is read in a job of its own, one microtask after JS would read it. -- [x] Dotted tool names are canonicalized into namespace paths; a path can be both callable and a namespace, and the - last tool supplied for a canonical path wins. -- [x] Tool path segments may be named `constructor`, `prototype`, or `__proto__` because paths use inert Map keys. -- [x] Outbound tool arguments are what `JSON.stringify` would serialize (see the boundary rule above). Tools never - receive `undefined` inside their input object, though a bare `tools.t(undefined)` argument still reaches schema - decoding as `undefined`. -- [ ] Tokenize and case-fold non-ASCII tool paths, descriptions, and queries for tool search. - -## Objects and properties - -- [x] Own-field reads and writes on plain data objects. -- [x] `new` dispatches on the evaluated constructor value, so aliases (`const D = Date; new D()`), constructors held in - objects, and constructors passed as arguments work, while a shadowed name (`const Date = 5; new Date()`) does - not construct. -- [x] `Object()` and `new Object()` return `{}` for nullish arguments and pass objects through unchanged; - primitive wrapper objects (`Object(1)`) are rejected explicitly. -- [x] Computed property names and object spread. Any value works as a key (ToPropertyKey): strings, numbers, and the - two confined symbols as themselves, data objects through their own `toString` (`o[[1, 2]]` is `o["1,2"]`), and - everything else as its string form (`o[null]` is `o["null"]`), in reads, writes, literals, `in`, and - destructuring. -- [x] `Object.keys`, `Object.values`, `Object.entries`, `Object.hasOwn`, `Object.assign`, and `Object.fromEntries`, with - synchronous iterator support for `fromEntries`. Sources follow ToObject: strings enumerate by index, other - primitives and wrappers contribute nothing, and `null`/`undefined` throw. `Object.assign` accepts array - targets for index keys only; a primitive target is a `TypeError` rather than a boxed object. -- [x] `Object.keys` over arrays and tool references. -- [x] Object identity is preserved by in-CodeMode Object helpers. -- [x] Every value has a real prototype chain built fresh for each run: `Object.prototype`, `Array.prototype`, - `String.prototype`, `Error.prototype` → `TypeError.prototype`, and so on hold the built-in methods as - non-enumerable properties, and each constructor's `prototype` points at it (`[].constructor === Array`, - `Object.getPrototypeOf([]) === Array.prototype`). Programs may read and even overwrite these prototypes; the - change is confined to that run. `__proto__` is an ordinary own data key, so `o.__proto__ = x` never changes the - chain, and `Object.groupBy` results have no prototype at all, as in JS. -- [x] `Object.getPrototypeOf`: the prototype of an object, or the built-in prototype for a string, number, or boolean - (`Object.getPrototypeOf("a") === String.prototype`); `null`, `undefined`, and the two confined symbols throw a - `TypeError`. -- [x] `Object.create(proto)` with an object or `null` prototype; any other prototype is a `TypeError` - (`Object prototype may only be an Object or null`). Inherited reads, `in`, `hasOwnProperty`, own-only - `Object.keys`, and `for...in` follow the chain as in JS. A second `properties` - argument defines properties from descriptors, as `Object.defineProperties` does. -- [x] `Object.defineProperty`, `defineProperties`, `getOwnPropertyDescriptor(s)` and `getOwnPropertyNames`, with the - spec's validation (non-configurable and non-writable rules, `SameValue`, extensibility) and descriptor objects - read through getters and the prototype chain. Built-in accessors (`Map.prototype.size`, `URL.prototype.href`, …) - show as callable functions and can be redefined, one half at a time. -- [ ] Array elements share one set of attributes, so `defineProperty` on an index takes only the array's own - attributes (new elements must say `writable`, `enumerable` and `configurable` true), never an accessor, and an - array's `length` can't be made read-only on its own (use `Object.freeze`). -- [x] `Object.freeze`, `Object.seal`, and `Object.preventExtensions`, with `isFrozen`, `isSealed`, and `isExtensible`. - Each returns its argument and passes primitives through (`Object.freeze(1) === 1`, `Object.isFrozen(1)`). - Programs run as strict code, so violations throw `TypeError`: `Cannot assign to read only property 'a'`, - `Cannot add property b, object is not extensible`, and `Cannot delete property 'a'`. Arrays enforce the same - rules for index writes, `length`, and the mutating methods (`Object.freeze([1]).push(2)` throws; a sealed array's - `pop()` throws; a non-extensible array's `pop()`, `sort()`, and `splice(0, 1, x)` work). The mutating methods are - checked once up front, so a `fill` or `sort` that would land on a hole of a non-extensible array succeeds here - where JS throws. Maps, Sets, and Dates freeze their properties only, not their contents, as in JS. - `Object.freeze(new Uint8Array(1))` and `seal` throw `TypeError` like JS (`preventExtensions` and empty typed - arrays are fine). Functions are objects and freeze like any other value. -- [x] Circular references are rejected when created (`o.self = o`, `array.push(array)`), not at serialization as in JS. -- [x] `Object.is` for supported data values. -- [x] `Object.groupBy` over finite collections and custom synchronous iterators/generators, with string-key coercion - and plain-object results. -- [x] `Object.prototype` methods on values: `toString` (`"[object Array]"`, `"[object Map]"`, `"[object Promise]"`, and so - on for every built-in kind, as JS reports through `Symbol.toStringTag`), `toLocaleString` (calls the value's - `toString`, as in JS), `valueOf`, `hasOwnProperty`, `isPrototypeOf`, and `propertyIsEnumerable`. - -## Arrays - -- [x] The `Array` constructor with or without `new`: `Array(a, b)` collects arguments and `Array(n)` creates a sparse - array of that length; invalid lengths throw `RangeError`. Iteration, spread, join, `flatMap`, and JSON handle - holes like JavaScript, and host results normalize holes to `null`. -- [x] Static methods: `Array.isArray`, `Array.of`, and `Array.from`, including the `Array.from` mapper form with - `(value, index)` arguments and stepwise synchronous iterator consumption. -- [x] Iteration/transformation: `map`, `filter`, `flatMap`, and `forEach`. -- [x] Searching/tests: `find`, `findIndex`, `findLast`, `findLastIndex`, `some`, `every`, `includes`, `indexOf`, and - `lastIndexOf`. An explicit `undefined` fromIndex counts as present: `[1, 2, 1].lastIndexOf(1, undefined)` is `0` - while `lastIndexOf(1)` is `2`. -- [x] Aggregation: `reduce` and `reduceRight`. -- [x] Ordering: `sort`, `toSorted`, `reverse`, and `toReversed`. -- [x] Access/copying: `at`, `slice`, `concat`, `flat`, `with`, `join`, and `toLocaleString` (each element's - `toLocaleString`, holes and nullish elements as empty strings). -- [x] Mutation: `push`, `pop`, `shift`, `unshift`, `splice`, `fill`, and `copyWithin`. -- [x] `keys`, `values`, `entries`, and `[Symbol.iterator]` (the same function as `values`) return live iterator objects - with `next()` and `[Symbol.iterator]`, as in JS. Iterator objects are opaque references: they print as - `[opaque reference]`, serialize to `{}`, and cannot be passed to extensions. Every built-in collection iterator - shares one prototype, where JavaScript gives each collection its own; `Object.getPrototypeOf` shows the - difference. -- [x] `length`, numeric indexing, index assignment, spread, and `for...of`. -- [x] `Array.prototype.toSpliced`. -- [x] Canonical array/string index parsing: keys such as `"01"` are ordinary properties rather than aliases of index - `1`. -- [x] `Array.prototype.sort` preserves trailing holes, while `toSorted` densifies holes into `undefined` elements, - like JavaScript. -- [x] Assigning `length` to truncate or extend an array; invalid lengths throw `RangeError`. -- [x] Non-index own properties on arrays (`arr.foo = 1`, `arr.constructor = null`). They are excluded from the JSON - form, like `JSON.stringify`. -- [x] Numeric arguments coerce as in JS (ToIntegerOrInfinity): `indexOf(x, "1")`, `slice("1", "3")`, `at(null)`, - `flat(1.9)`, `with(1.5, v)`, `Math.max("3", "2")`, `parseInt("11", "2")`, `(1.5).toFixed("2")`, - `String.fromCharCode("65")`, and the Uint8Array equivalents. `join(sep)` and `JSON.parse(text)` apply ToString - (`join(null)` is `"1null2"`, `JSON.parse(123)` is `123`). `Array.from({ length: "2" })` applies ToLength; a - promise source still throws with an `await` hint rather than JS's silent `[]`. `join`, `Math.*`, `parseInt`, - and the String and Number methods consult a program object's own `valueOf`/`toString`; the array methods do not - yet (see ToPrimitive above). - -## Strings - -- [x] Case/normalization: `toLowerCase`, `toUpperCase`, `normalize`, and the `toLocaleLowerCase`/`toLocaleUpperCase` - aliases, which ignore their locale argument and apply the default Unicode casing. -- [x] Trimming: `trim`, `trimStart`, and `trimEnd`, plus the Annex B `trimLeft` and `trimRight` aliases. -- [x] Searching/tests: `includes`, `startsWith`, `endsWith`, `indexOf`, `lastIndexOf`, and `search`. -- [x] Slicing/access: `slice`, `substring`, Annex B `substr`, `at`, `charAt`, `charCodeAt`, and `codePointAt`. -- [x] Construction/transformation: `split`, `concat`, `repeat`, `padStart`, `padEnd`, `replace`, and `replaceAll`. -- [x] Regular-expression integration: `match`, materialized `matchAll`, `replace`, `replaceAll`, `split`, and `search`. -- [x] `localeCompare`, with its locales and collator options (`numeric`, `sensitivity`, `caseFirst`, - `ignorePunctuation`, and the rest) passed to the host collator; there is still no global `Intl`. -- [x] `isWellFormed` and `toWellFormed`. -- [x] `toString`, `length`, numeric indexing, spread, `for...of`, and `[Symbol.iterator]` by Unicode code point. -- [x] Static `String.fromCharCode` and `String.fromCodePoint`. -- [x] Native argument coercion for supported String methods; for example, `includes(1)` and `slice("1")` coerce like - native JS, `split(undefined)` returns the whole string, and `includes`/`startsWith`/`endsWith` reject regular - expressions with a native-style `TypeError`. Data objects convert through their own `toString`/`valueOf` (see - ToPrimitive above). Opaque runtime references still reject as data errors, and `repeat` still requires a finite - non-negative count. -- [x] Native no-argument parity for `match()`, `matchAll()`, and `search()`; all behave as an empty pattern. -- [x] `String.raw`, on a template object or any `{ raw }` object; raw strings and substitutions coerce through their own - `toString`. -- [x] `match`, `matchAll`, `search`, and `split` read any non-RegExp argument as a pattern string, as `new RegExp(arg)` - would: `"a1b".match(1)` matches `/1/`, `search(null)` looks for `"null"`, `undefined` is the empty pattern, and - an object supplies its own `toString`. - -## Numbers and Math - -- [x] Coercion functions: `Number`, `parseInt`, and `parseFloat`. -- [x] Number predicates/parsers: `Number.isInteger`, `Number.isFinite`, `Number.isNaN`, `Number.isSafeInteger`, - `Number.parseInt`, and `Number.parseFloat`. -- [x] Number formatting: `toFixed`, `toPrecision`, `toExponential`, `toString`, `valueOf`, and `toLocaleString`, which - always formats as `en-US` (`"1,234.5"`) so output does not depend on the host. -- [x] `Number.prototype.toString` truncates a fractional radix before validating the 2–36 range; invalid radixes - throw a catchable `RangeError`. -- [x] Number constants: `MAX_SAFE_INTEGER`, `MIN_SAFE_INTEGER`, `MAX_VALUE`, `MIN_VALUE`, `EPSILON`, `NaN`, - `POSITIVE_INFINITY`, and `NEGATIVE_INFINITY`. -- [x] Math constants: `PI`, `E`, `LN2`, `LN10`, `LOG2E`, `LOG10E`, `SQRT2`, and `SQRT1_2`. -- [x] Math methods: `random`, `max`, `min`, `abs`, `acos`, `acosh`, `asin`, `asinh`, `atan`, `atan2`, `atanh`, - `floor`, `ceil`, `round`, `trunc`, `sign`, `sqrt`, `cbrt`, `pow`, `hypot`, `cos`, `cosh`, `sin`, `sinh`, - `tan`, `tanh`, `log`, `log2`, `log10`, `log1p`, `exp`, `expm1`, `f16round`, `fround`, `clz32`, and `imul`. -- [x] Native zero-argument behavior for `Number()` and `String()`: they produce `0` and `""`, while - `Number(undefined)` stays `NaN` and `String(undefined)` stays `"undefined"`. -- [x] `++` and `--` use CodeMode numeric coercion (numeric strings increment, plain data objects become `NaN`, Dates - use their epoch time) and reject opaque runtime references as data errors. -- [x] Unknown static members on global namespaces and on `Number`/`String`/the coercion functions read as `undefined` - for feature detection. Calling any undefined value reports a native-style `TypeError` naming the callee, for - example `Math.sum is not a function.` or `search(...).catch is not a function.` Unknown `Promise` statics keep - their descriptive error. -- [x] `Math.sumPrecise` over finite collections and custom synchronous iterators/generators, rejecting non-number - elements without coercion. -- [x] Global coercing `isFinite` and `isNaN`; opaque runtime references reject as data errors, like `Number(...)`. - -## JSON and console - -- [x] `JSON.parse` and `JSON.stringify` for supported data objects. -- [x] Numeric/string indentation for `JSON.stringify`. -- [x] `JSON.parse` reviver callbacks, including postorder traversal, deletion through `undefined`, and root replacement. - Revivers receive `(key, value)` with the holder as `this`. -- [x] `JSON.stringify` function and array replacers. Function replacers receive `(key, value)` in preorder, including - the root, with the holder as `this`. Array replacers preserve requested property order, deduplicate names, coerce - number primitives, and ignore non-string/non-number entries. Primitive wrapper entries remain unsupported. -- [x] Captured `console.log`, `console.info`, `console.debug`, `console.warn`, and `console.error`. An Error prints as - `Error.prototype.toString` would show it (`Error: boom`), wherever it appears in the logged value. -- [x] Captured `console.dir` and `console.table`. - -## Date - -- [x] `Date.now`, `Date.parse`, and `Date.UTC`. -- [x] `new Date()` from the current time, epoch milliseconds, a date string, another Date, or local components. -- [x] `Date()` without `new` returns the current time as a string, like JS, but in deterministic ISO format - rather than the host's locale/timezone string. -- [x] `getTime`, `valueOf`, `toISOString`, `toJSON`, and deterministic ISO `toString`. -- [x] Local getters: `getFullYear`, `getMonth`, `getDate`, `getDay`, `getHours`, `getMinutes`, `getSeconds`, and - `getMilliseconds`. -- [x] UTC getters: `getUTCFullYear`, `getUTCMonth`, `getUTCDate`, `getUTCDay`, `getUTCHours`, `getUTCMinutes`, - `getUTCSeconds`, and `getUTCMilliseconds`. -- [x] `getTimezoneOffset`, arithmetic, relational comparison, and `instanceof Date`. -- [x] Date values serialize to ISO strings; invalid dates serialize to `null`. -- [x] Local and UTC Date setters, including native argument coercion, mutation, rollover, invalid-Date recovery, and - `TimeClip` behavior. On an invalid Date every setter but `setTime` and `set(UTC)FullYear` answers `NaN` without - writing, so a time set inside an argument's `valueOf` survives. -- [x] `Date.prototype.toUTCString` and its `toGMTString` alias. -- [x] `toDateString` and `toTimeString` in the host's local timezone. -- [x] `toLocaleString`, `toLocaleDateString`, and `toLocaleTimeString` format through the host's - `Intl.DateTimeFormat`, honoring the locale and options (`timeZone`, `dateStyle`, `weekday`, `hour12`, ...). Without - a locale they format as `en-US`, Bun's default; without a `timeZone`, in the host's local timezone, like `getHours` - and `toDateString`. -- [x] Native one-argument Date coercion for supported values, including booleans, null, arrays, and plain objects. -- [x] Date setters, construction, and `Date.UTC` coerce object arguments through their own `valueOf`/`toString` in - argument order and surface their throws; only the first seven components are converted. -- [x] Native Date loose-equality and default primitive-coercion semantics, using CodeMode's deterministic ISO string - representation for the string primitive. -- [x] Native `RangeError` branding for invalid `toISOString()` calls. - -## Regular expressions - -- [x] Literal and `RegExp(pattern, flags)` construction, with or without `new`. -- [x] `test`, `exec`, and `toString`. -- [x] Readable `source`, `flags`, `lastIndex`, `hasIndices`, `global`, `ignoreCase`, `multiline`, `sticky`, `unicode`, - `unicodeSets`, and `dotAll`. -- [x] Captures, named groups, match `.index` and `.input`, and stateful global matching. -- [x] Integration with supported String methods, including function replacers. -- [x] Writable `lastIndex`, shared by `exec`, `test`, and the String methods. It is a prototype accessor that stores - a number, so `re.lastIndex = "12"` reads back `12`, `delete` is a no-op, and `hasOwnProperty("lastIndex")` is - `false`. -- [x] Match `indices` metadata for the `d` flag, including named groups on `exec`, `match`, and `matchAll` results. -- [x] `RegExp.escape`. - -## Iterator - -- [x] `Iterator.prototype.map`, `filter`, `take`, `drop`, and `flatMap` on any iterator or generator: lazy, one source - step per result, closing the source when a callback throws, on early `return()`, or when `for...of` or - destructuring finishes with it early. Once done or closed a helper stays done, and a callback that re-enters its - own helper is a `TypeError`. `take`/`drop` coerce their count and reject `NaN` or negative counts with a - `RangeError`; `flatMap` callbacks must return an iterable or iterator, not a string. -- [x] `Iterator.prototype.reduce`, `toArray`, `forEach`, `some`, `every`, and `find`, closing the source on early exit. -- [x] `Iterator.from(value)` returns iterators and generators as they are, and wraps strings, iterables, and objects - with a `next` method. `Iterator` itself is abstract: calling or constructing it is a `TypeError`. -- [x] Helpers and `Iterator.from` wrappers have `return()`; collection iterators (`array.values()`) do not, as in JS, - so an early exit from them leaves them where they were. -- [ ] `Iterator.concat`, `Iterator.zip`, and `Iterator.zipKeyed` (stage 3 proposals). - -## Map and Set - -- [x] Static `Map.groupBy` over finite collections and custom synchronous iterators/generators, preserving key identity. -- [x] `new Map()` from synchronous iterables of entries. -- [x] Map `get`, `set`, `has`, `delete`, `clear`, `size`, `forEach`, `getOrInsert`, and `getOrInsertComputed`. - `forEach` is live: entries deleted during the walk are skipped and entries added are visited, as in JS. -- [x] `new Set()` from synchronous iterables. -- [x] Set `add`, `has`, `delete`, `clear`, `size`, and `forEach`. -- [x] Live `keys`, `values`, `entries`, and `[Symbol.iterator]` iterators for Map and Set; a Set-like operand's `keys()` - may return any iterator or an array. -- [x] Spread, `for...of`, `Array.from`, and `Object.fromEntries` integration. -- [x] Map and Set values serialize to `{}` at host/JSON boundaries. -- [x] Set composition and relation methods: `union`, `intersection`, `difference`, `symmetricDifference`, `isSubsetOf`, - `isSupersetOf`, and `isDisjointFrom`, including supported Set-like operands. -- [x] `WeakMap` (`get`, `set`, `has`, `delete`, `getOrInsert`, `getOrInsertComputed`) and `WeakSet` (`add`, `has`, - `delete`), constructed from iterables. Keys must be program objects: a primitive or tool reference throws - `Invalid value used as weak map key`, while `has`/`delete`/`get` with one answer `false`/`undefined`. Entries are - held by a host weak collection, so nothing is retained past the key's own lifetime. As in JS they have no `size`, - iteration, or `clear`, `structuredClone` rejects them, and they serialize to `{}` at host boundaries. - -## URL and URI helpers - -- [x] `encodeURI`, `encodeURIComponent`, `decodeURI`, and `decodeURIComponent`. -- [x] `new URL(input, base)`, `URL.canParse`, and `URL.parse`. -- [x] URL `toString`, `toJSON`, and linked `searchParams`. -- [x] Readable URL fields: `href`, `origin`, `protocol`, `username`, `password`, `host`, `hostname`, `port`, - `pathname`, `search`, and `hash`. -- [x] Writable URL fields except `origin`. -- [x] `new URLSearchParams()` from query strings, data objects, synchronous iterables of pairs, and URLSearchParams. -- [x] URLSearchParams `append`, `delete`, `get`, `getAll`, `has`, `set`, `sort`, `forEach`, `keys`, `values`, - `entries`, `[Symbol.iterator]`, `toString`, and `size`. -- [x] URL values are their href in `JSON.stringify` and at the host boundary. URLSearchParams are `{}` in - `JSON.stringify` and their query string at the host boundary. - -## Uint8Array - -The only binary type. Bytes stay inside the program or cross to extensions as copies; the tool boundary rejects them -with a hint to encode as text first (`TextDecoder`, `toBase64`, `toHex`). - -- [x] `new Uint8Array(length | array | iterable | Uint8Array)`, `Uint8Array.from`, `Uint8Array.of`, `fromBase64` - (with the `alphabet` and `lastChunkHandling` options), and `fromHex`. Lengths are capped like arrays. The - `Uint8Array.from` mapper and `thisArg` see the original values, so - `Uint8Array.from(atob(b64), (c) => c.charCodeAt(0))` decodes base64. `BYTES_PER_ELEMENT` is 1 on the - constructor, its instances, and `Buffer`. -- [x] Index reads and writes with JS byte semantics: values wrap modulo 256, out-of-range writes are ignored, indexes - cannot be deleted. `length` is a prototype accessor, so `Object.keys` lists only indexes. -- [x] `at`, `slice`, `subarray` (a view on the same bytes), `set`, `fill`, `reverse`, `indexOf`, `lastIndexOf`, - `includes`, `join`, `toString`, `toBase64` (with `alphabet` and `omitPadding`), `toHex`, and live `keys`, `values`, `entries`, and `[Symbol.iterator]` - iterators. Start indexes coerce as for arrays, search values do not (`bytes.includes("1")` is `false`), and - `lastIndexOf(x, undefined)` searches from index 0 while `lastIndexOf(x)` searches from the end, as in JS. -- [x] Spread, destructuring, `for...of`, `yield*`, `Array.from`, and `new Set(bytes)`. `Array.isArray` is false. -- [x] String coercion joins with commas; `JSON.stringify` gives `{"0":1,...}`; `console.log` prints - `Uint8Array(n) [...]`. -- [x] Callback methods `forEach`, `map`, `filter`, `find`, `findIndex`, `findLast`, `findLastIndex`, `some`, `every`, - `reduce`, and `reduceRight`, sharing the Array implementations; the callback receives `(byte, index, bytes)`. - `map` and `filter` return new Uint8Arrays with results clamped like index writes (`map((b) => b * 100)` on - `[1, 2, 3]` is `[100, 200, 44]`); `reduce` on an empty Uint8Array without an initial value is a `TypeError`. -- [x] `sort` in place, numeric ascending by default (`[10, 9, 1]` sorts to `[1, 9, 10]`) or by comparator. -- [ ] `ArrayBuffer`, `DataView`, and other typed arrays. - -## Buffer - -Node's `Buffer`, where the host has one (Node and Bun; not browsers). It is a `Uint8Array`, so every `Uint8Array` -method works on it, and its text conversions default to UTF-8. - -- [x] `Buffer.from(string, encoding)`, `Buffer.from(bytes | array | array-like | { type: "Buffer", data })`, - `alloc`, `allocUnsafe`, `concat`, `byteLength`, `compare`, `isBuffer`, and `isEncoding`, with the encodings - utf8, hex, base64, base64url, latin1/binary, ascii, and utf16le/ucs2. An unknown encoding is a `TypeError` with - code `ERR_UNKNOWN_ENCODING`. -- [x] `toString(encoding, start, end)` (so string coercion and templates give UTF-8 text), `toJSON` as - `{ type: "Buffer", data }`, `slice` and `subarray` as Buffer views on the same bytes, `equals`, `compare`, - `indexOf`, `lastIndexOf`, `includes`, `write`, `fill`, `copy`, and the `read`/`write` integer and float methods. - `console.log` prints ``. -- [x] The inherited `Uint8Array` methods that make new bytes (`map`, `filter`, `slice`, `subarray`, also called - through `Uint8Array.prototype`) make a Buffer from a Buffer, as JS's species does. -- [x] A host Buffer crosses into the program as a Buffer, and a program Buffer crosses out as one; snapshots keep it. -- [ ] The 64-bit `readBigInt64*`/`writeBigInt64*` methods, since programs have no BigInt. - -## Web platform helpers - -- [x] `atob` and `btoa` with forgiving-base64 decoding and WebIDL string conversion; invalid input throws a - `TypeError`, since there is no `DOMException`. -- [x] `crypto.randomUUID()` and `crypto.getRandomValues(uint8Array)`. -- [x] `structuredClone(value)` deep-copies primitives, plain objects (own enumerable string keys onto a plain object; - the prototype is not kept), arrays (holes and extra keys kept), Map, Set, Date, RegExp (`lastIndex` reset to 0), - Uint8Array, and errors (standard `name`, `message`, `cause`, and `stack`; other names become `Error`, extra - fields drop). Shared references stay shared in the copy, and the copy is extensible even when the source was - frozen. Functions, symbols, promises, iterators, URL, Headers, and tool references cannot be cloned; without a - `DOMException`, the failure is a `TypeError` whose message starts with `DataCloneError:`. -- [x] `TextEncoder` and `TextDecoder` for UTF-8 only: any other label is a `RangeError`. `TextDecoder` accepts the - `fatal` and `ignoreBOM` options. `decode(chunk, { stream: true })` accepts incremental Uint8Array input; - `decode()` flushes the stream. -- [x] `new Headers()` from records, synchronous iterables of pairs, and Headers, wrapping the host's `Headers`: names - fold to lowercase, values are normalized and combined, and invalid names or values throw a `TypeError`. -- [x] Headers `append`, `delete`, `get`, `getSetCookie`, `has`, `set`, `forEach`, `keys`, `values`, `entries`, and - `[Symbol.iterator]`; iteration is live and sorted by name, with `set-cookie` values kept apart. -- [x] Headers serialize to a `{ name: value }` object in JSON, in results, and in tool arguments. -- [ ] `Request`, `Response`, and `Blob`. -- [x] A host-provided streaming fetch response exposes `bodyUsed`, whole-body readers, a default stream reader and `for await` iteration. `arrayBuffer()` crosses as a `Uint8Array`. -- [ ] `crypto.subtle` and non-UTF-8 `TextDecoder` encodings. - -## Extensions - -Host functions a host opts in through `Extension.make({ name, globals })` and `CodeMode.make({ extensions })`. -Nothing is exposed unless a host provides it; extension calls are not tool calls. - -- [x] Each global is a function, callable but not constructible, run with `this` undefined. A global that shadows - a built-in or another extension throws at `make`. -- [x] Every value crossing in either direction is converted, never shared: plain objects and arrays are copied, - `Date`, `RegExp`, `URL`, `URLSearchParams`, `Headers`, `Map`, `Set`, and `Uint8Array` become fresh copies with - their contents converted (a host `ArrayBuffer` comes in as a `Uint8Array`; other typed arrays cannot come out), - errors cross as errors with their name, message, `cause`, and own enumerable data, and a `__proto__` key is - dropped. Functions, generators, - un-awaited promises, and symbols cannot be passed in; a class instance, a symbol, or a BigInt cannot come out. -- [x] A host function inside a result becomes a program function whose calls cross the same way, so a result can - carry methods (`res.json()`) whose host closures keep the host state. Diagnostics name it by its path - (`fetch.json`). Like any program function it vanishes at the data boundary. -- [x] Each call to an extension global runs inside the host's `extension.before`/`extension.after` hooks as - `{ extension, name, args }`, with the host's own error on failure; calls to functions inside results do not. -- [x] A host `Promise` becomes a program promise. Whatever host code returns, resolves, throws, or rejects with - crosses the same way, so `catch (e)` receives a copy of the thrown value (an `Error` of the matching type, or - plain data). -- [x] An Error crosses, in either direction, as its name, message, `cause`, and own enumerable data, so Node's - `code`, `errno`, `syscall`, and `path` reach the program and `err.code === "ENOENT"` works. `stack` stays on its - own side, no field may shadow an Error method, and a field that cannot cross (a class instance, a function) is - left behind rather than replacing the error. -- [x] A synchronous global that returns an Effect blocks the program until the Effect completes and returns its - value or throws its error, as `fs.readFileSync` does. An `async` global (or one marked `Extension.async`) hands - the program a promise instead. -- [ ] Program functions as arguments to extension code (callbacks such as `forEach`). -- [ ] Host classes. Stateful host objects are expressed as closures; a declared method table would be the next - step if `new X()` in a program is ever needed. - -## Errors and diagnostics - -- [x] `Error`, `TypeError`, `RangeError`, `SyntaxError`, `ReferenceError`, `EvalError`, and `URIError`, callable with - or without `new`. -- [x] `AggregateError` with the `(errors, message?)` signature and an own `errors` array, constructed directly or by - an all-rejected `Promise.any`; direct construction accepts custom synchronous iterators and generators. -- [x] Error `name`/`message`, error inheritance through `instanceof`, and plain-data serialization. `message` is an own - non-enumerable property and `name` is inherited, as in JS, so `Object.keys(err)` is `[]` for a plain error. The - result boundary still emits `{ name, message, ...own enumerable }`, so a field such as `code` crosses. `cause` is - non-enumerable: an extension Error carries it, and this JSON form does not. An uncaught error's diagnostic - carries a 1-based line and column in the submitted source. -- [x] Every Error has an own non-enumerable string `stack` in V8's format: `name: message`, then - ` at fn (:line:col)` lines. As in V8, the frames are taken when the error is made and the header when - `stack` is first read, so a subclass constructor that sets `this.name` shows in it; the value is then fixed until - assigned. The header reads `name` and `message` as data: a program getter there is not run and reads as - `undefined`, as in Bun (Node runs it). `stack` is a data property, as in Bun (Node's is an accessor). - `new Error()` lists up to 10 program frames, innermost first (built-in frames are skipped, and top-level code is - a bare `at :line:col`); a built-in or tool failure has at most one line at the expression that raised - it or the `await` that observed it. A host Error's own `stack` never crosses, so no host path appears. -- [ ] `Error.captureStackTrace`, `Error.stackTraceLimit`, and `at async` frames across an `await`. -- [x] `instanceof` against any constructor with a `prototype`, including every built-in and `Function`. -- [x] Derived error constructors extend `Error` itself: `Object.getPrototypeOf(TypeError) === Error`, so - `TypeError.isError` is inherited, and `TypeError.prototype` inherits from `Error.prototype`. -- [x] Catchable user throws, runtime failures raised during interpreted evaluation, awaited tool failures, and awaited - tool-call-limit failures; parse/compile failures, cooperative timeout, and output bounding remain outside program - `catch`. -- [x] Source locations on unsupported-syntax diagnostics. The diagnostic names the rejected node type and attaches a - short orientation to the supported subset; this matrix is the full reference. -- [x] Model-visible host failure messages and underlying causes, including output-validation errors. -- [x] Caught errors do not distinguish user throws, interpreter failures, and tool failures; a program sees one - Error-shaped value in `catch`, rejection handlers, and `Promise.allSettled` reasons. It always has `name` and - `message`, plus `cause` and own data when the failure carried them. This is deliberate: the program should - handle a failure the same way regardless of where it originated. -- [x] Failures raised by the interpreter are `TypeError`s unless JavaScript names them otherwise (`RangeError`, - `ReferenceError`, `SyntaxError`, `URIError`), so `e instanceof TypeError` and `e.constructor === TypeError` - hold. Unsupported syntax reached at runtime is a `SyntaxError`; awaited tool failures stay plain `Error`. - Host errors escaping a built-in (`(1).toFixed(200)`) become the same-named program error at the call. - A failure raised inside a promise a built-in created (`Promise.all(1)`, `Promise.race([])`, a resolution cycle) - is located at the call that created the promise. -- [x] One failure is one error object: every `catch`, rejection handler, and `allSettled` reason for the same - failure sees the identical value, so `a === b` holds after awaiting the same rejected promise twice. -- [x] Rethrowing an interpreter failure keeps its diagnostic: `catch (e) { throw e }` still reports the original - kind and source location. Uncaught errors report as `name: message` whoever raised them, as - `Error.prototype.toString` would (`TypeError: Cannot read properties of null (reading 'foo').`, - `TypeError: bad input`); other thrown values report as `Uncaught: `. diff --git a/packages/codemode/package.json b/packages/codemode/package.json index 7f256b2a3ae..9fac95019ab 100644 --- a/packages/codemode/package.json +++ b/packages/codemode/package.json @@ -24,12 +24,12 @@ "pack": "bun run script/pack.ts", "typecheck": "bun check --no-script", "typecheck:tsc": "tsc --noEmit", - "test": "bun test", - "test:roundtrip": "CODEMODE_ROUNDTRIP=1 bun test" + "test": "bun test" }, "dependencies": { "acorn": "8.15.0", - "effect": "catalog:" + "effect": "catalog:", + "psychoscript": "0.1.2" }, "devDependencies": { "@tsconfig/bun": "catalog:", diff --git a/packages/codemode/script/bench.ts b/packages/codemode/script/bench.ts deleted file mode 100644 index 4ce3500f628..00000000000 --- a/packages/codemode/script/bench.ts +++ /dev/null @@ -1,174 +0,0 @@ -#!/usr/bin/env bun - -// Interpreter benchmarks: median and fastest wall-clock milliseconds per program over several runs. -// Usage: bun run script/bench.ts [--iterations N] [--filter name] [--mixed] [--jsc] - -import { numberOfDFGCompiles, reoptimizationRetryCount } from "bun:jsc" -import { Effect, Schema } from "effect" -import { CodeMode, Tool } from "../src/index.js" -import { Vm } from "../src/language/vm.js" - -const cases: ReadonlyArray = [ - [ - "numeric loop", - `let sum = 0 -for (let i = 0; i < 300000; i++) sum = (sum + i * 3) % 1000003 -return sum`, - ], - [ - "closure recursion (fib 22)", - `const fib = (n) => (n < 2 ? n : fib(n - 1) + fib(n - 2)) -return fib(22)`, - ], - [ - "array callbacks (50k)", - `const items = Array.from({ length: 50000 }, (_, i) => (i * 7919) % 50000) -const mapped = items.map((x) => x * 2).filter((x) => x % 3 !== 0) -const total = mapped.reduce((a, b) => a + b, 0) -const sorted = mapped.slice(0, 20000).sort((a, b) => a - b) -return [total, sorted[0], sorted[sorted.length - 1]]`, - ], - [ - "promise fan-out (5k)", - `const work = async (i) => { await null; return i * 2 } -const results = await Promise.all(Array.from({ length: 5000 }, (_, i) => work(i))) -return results.length`, - ], - [ - "tool fan-out (1k)", - `const results = await Promise.all(Array.from({ length: 1000 }, (_, i) => tools.echo({ id: i }))) -return results.length`, - ], - [ - "JSON round-trip", - `const make = (depth) => depth === 0 ? { a: 1, b: "two", c: [1, 2, 3], d: null } : { left: make(depth - 1), right: make(depth - 1), list: [depth, String(depth)] } -let size = 0 -for (let i = 0; i < 20; i++) size += JSON.stringify(JSON.parse(JSON.stringify(make(9)))).length -return size`, - ], - [ - "generator iteration", - `function* range(n) { for (let i = 0; i < n; i++) yield i } -let sum = 0 -for (const x of range(50000)) sum += x -return sum`, - ], - [ - "string building", - `let out = "" -for (let i = 0; i < 50000; i++) out += String.fromCharCode(97 + (i % 26)) -const parts = [] -for (let i = 0; i < 20000; i++) parts.push(\`item-\${i}\`) -return out.length + parts.join(",").length`, - ], - [ - "Map/Set ops", - `const map = new Map() -const set = new Set() -for (let i = 0; i < 30000; i++) { map.set("k" + (i % 5000), i); set.add(i % 7000) } -let sum = 0 -for (const [k, v] of map) sum += v -for (const v of set) sum += v -for (let i = 0; i < 5000; i++) { map.delete("k" + i); set.delete(i) } -return sum + map.size + set.size`, - ], - [ - "property-heavy (plain data)", - `const rows = Array.from({ length: 20000 }, (_, i) => ({ id: i, name: "n" + i, score: i % 97, tags: ["a", "b"] })) -let sum = 0 -for (const r of rows) { - const c = { ...r, extra: 1 } - const { id, ...rest } = r - Object.assign(c, rest) - sum += c.score + Object.keys(c).length + Object.entries(r).length + Object.values(r).length + rest.score -} -return sum + JSON.stringify(rows.slice(0, 3000)).length`, - ], - [ - "accessors", - `const o = { _v: 1, get v() { return this._v }, set v(x) { this._v = x } } -const p = Object.create(o) -let sum = 0 -for (let i = 0; i < 100000; i++) { p.v = i; sum += p.v + o.v } -return sum + JSON.stringify(Array.from({ length: 2000 }, () => o)).length`, - ], - [ - "classes", - `class Shape { kind = "shape"; constructor(size) { this.size = size } area() { return this.size } } -class Square extends Shape { sides = 4; constructor(size) { super(size) } area() { return super.area() * this.size } } -let sum = 0 -for (let i = 0; i < 20000; i++) { const s = new Square(i % 10); sum += s.area() + s.sides + s.kind.length } -return sum`, - ], -] - -const argument = (flag: string) => { - const index = process.argv.indexOf(flag) - return index === -1 ? undefined : process.argv[index + 1] -} -const iterations = Number(argument("--iterations") ?? 7) -const filter = argument("--filter") -const mixed = process.argv.includes("--mixed") -const jsc = mixed || process.argv.includes("--jsc") -const exec = Vm.prototype["exec"] - -const runtime = CodeMode.make({ - tools: { - echo: Tool.make({ - description: "Echo an id", - input: Schema.Struct({ id: Schema.Number }), - output: Schema.Number, - execute: ({ id }) => Effect.succeed(id), - }), - }, -}) - -const median = (values: Array) => { - const sorted = [...values].sort((a, b) => a - b) - return sorted[Math.floor(sorted.length / 2)]! -} - -const run = (code: string) => runtime.execute(code) - -const selected = cases.filter(([name]) => filter === undefined || name.includes(filter)) - -const formatRow = (name: string, times: Array) => { - const base = `${name.padEnd(28)} ${median(times).toFixed(1).padStart(8)} ms (min ${Math.min(...times).toFixed(1)} ms)` - if (!jsc) return base - return `${base} [dfg=${numberOfDFGCompiles(exec)} retries=${reoptimizationRetryCount(exec)}]` -} - -if (mixed) { - // Pollute profiles in reverse order first, then interleave cases with a stride across rounds. - for (let i = selected.length - 1; i >= 0; i--) { - const [name, code] = selected[i]! - const warm = await Effect.runPromise(run(code)) - if (warm.ok !== true) throw new Error(`${name} failed: ${JSON.stringify(warm)}`) - } - const recorded = selected.map((): Array => []) - for (let round = 0; round < iterations; round++) { - for (let step = 0; step < selected.length; step++) { - const idx = (step * 5 + round * 3) % selected.length - const [, code] = selected[idx]! - const start = performance.now() - await Effect.runPromise(run(code)) - recorded[idx]!.push(performance.now() - start) - } - } - for (let i = 0; i < selected.length; i++) { - console.log(formatRow(selected[i]![0], recorded[i]!)) - } -} else { - for (const [name, code] of selected) { - // One warm-up run, which also checks the program succeeds. - const warm = await Effect.runPromise(run(code)) - if (warm.ok !== true) throw new Error(`${name} failed: ${JSON.stringify(warm)}`) - const times = Array.from({ length: iterations }, () => 0) - for (const index of times.keys()) { - const start = performance.now() - await Effect.runPromise(run(code)) - times[index] = performance.now() - start - } - console.log(formatRow(name, times)) - } -} diff --git a/packages/codemode/script/build.ts b/packages/codemode/script/build.ts index ac0348e7e42..323a63ddf96 100644 --- a/packages/codemode/script/build.ts +++ b/packages/codemode/script/build.ts @@ -6,5 +6,4 @@ import { fileURLToPath } from "node:url" process.chdir(fileURLToPath(new URL("..", import.meta.url))) await $`rm -rf dist` -await $`bun run script/prelude.ts` await $`bun tsc -p tsconfig.build.json` diff --git a/packages/codemode/script/disasm.ts b/packages/codemode/script/disasm.ts deleted file mode 100644 index f61c1b7b7ba..00000000000 --- a/packages/codemode/script/disasm.ts +++ /dev/null @@ -1,263 +0,0 @@ -#!/usr/bin/env bun - -// The bytecode disassembler: pcs, ops, constants, handler and finally tables, local names, source lines. -import { sourceLocation } from "../src/language/runtime/model.js" -import type { Code } from "../src/language/code.js" -import { compileSource } from "../src/language/compiler/compile.js" -import { - BinOpSymbols, - CheckBaseKind, - CodeFlags, - CondKind, - Op, - OpNames, - PutKind, - UnaryOpSymbols, -} from "../src/language/opcodes.js" -import { parseProgram } from "../src/language/runtime/execute.js" - -const formatFlags = (flags: number): string => { - const names: Array = [] - if (flags & CodeFlags.PROGRAM) names.push("PROGRAM") - if (flags & CodeFlags.ARROW) names.push("ARROW") - if (flags & CodeFlags.ASYNC) names.push("ASYNC") - if (flags & CodeFlags.GENERATOR) names.push("GENERATOR") - if (flags & CodeFlags.SIMPLE_PARAMS) names.push("SIMPLE_PARAMS") - if (flags & CodeFlags.USES_THIS) names.push("USES_THIS") - if (flags & CodeFlags.USES_ARGUMENTS) names.push("USES_ARGUMENTS") - if (flags & CodeFlags.INTERNAL) names.push("INTERNAL") - if (flags & CodeFlags.NEEDS_ARGS) names.push("NEEDS_ARGS") - return names.join("|") || "NONE" -} - -export const disassembleCode = (c: Code): string => { - const lines: Array = [] - const header = `=== fn#${c.index} ${c.name || ""} (params=${c.params}, locals=${c.locals}, maxStack=${c.maxStack}, flags=${formatFlags(c.flags)}) ===` - lines.push(header) - if (c.localNames.length > 0) { - lines.push(`locals: ${c.localNames.map((n, i) => `${i}:${n}`).join(", ")}`) - } - if (c.captures.length > 0) { - const caps: Array = [] - for (let i = 0, j = 0; i < c.captures.length; i += 2, j++) { - const from = c.captures[i] === 0 ? "local" : "upval" - const idx = c.captures[i + 1]! - caps.push(`${j}:${c.upvalNames[j] ?? "?"}(${from}[${idx}])`) - } - lines.push(`upvals: ${caps.join(", ")}`) - } - - const words = c.code - for (let pc = 0; pc < words.length; pc++) { - const w = words[pc]! - const op = w & 0xff - let a = (w >>> 8) & 0xff - let bx = w >>> 16 - if (op !== Op.EXTRA && pc > 0 && (words[pc - 1]! & 0xff) === Op.EXTRA) { - const w1 = words[pc - 1]! - const w0 = pc > 1 ? words[pc - 2]! : 0 - a = (w0 & 0xff) === Op.EXTRA ? ((w0 >>> 16) << 16) | (w1 & 0xff00) | a : (w1 & 0xff00) | a - bx = ((w1 >>> 16) << 16) | bx - } - const sbx = w >> 16 - const opName = OpNames[op] ?? `OP_${op}` - const operand = formatOperand(c, op, a, bx, sbx) - const siteNode = c.siteAt(pc) - const loc = siteNode?.loc ? sourceLocation(siteNode) : undefined - const locText = loc ? ` ; L${loc.line}:${loc.column}` : "" - lines.push(`${String(pc).padStart(4)} ${opName.padEnd(18)} ${operand.padEnd(28)}${locText}`.trimEnd()) - } - - if (c.handlers.length > 0) { - const hList: Array = [] - for (let i = 0; i < c.handlers.length; i += 4) { - hList.push(`[${c.handlers[i]}, ${c.handlers[i + 1]}) -> ${c.handlers[i + 2]} (depth ${c.handlers[i + 3]})`) - } - lines.push(`handlers: ${hList.join(", ")}`) - } - - if (c.finallies.length > 0) { - const fList: Array = [] - for (let level = 0; level < c.finallyOffsets.length; level++) { - const off = c.finallyOffsets[level]! - const tag = c.finallies[off]! - const val = c.finallies[off + 1]! - const depth = c.finallies[off + 2]! - const n = c.finallies[off + 3]! - const targets: Array = [] - for (let k = 0; k < n; k++) targets.push(c.finallies[off + 4 + k]!) - fList.push(`#${level}{tag=${tag}, val=${val}, depth=${depth}, targets=[${targets.join(", ")}]}`) - } - lines.push(`finallies: ${fList.join(", ")}`) - } - - return lines.join("\n") -} - -const formatOperand = (c: Code, op: number, a: number, bx: number, sbx: number): string => { - switch (op) { - case Op.PUSH_UNDEF: - case Op.PUSH_NULL: - case Op.POP: - case Op.DUP: - case Op.NEW_OBJECT: - case Op.COPY_DATA_PROPS: - case Op.PUT_ELEM: - case Op.DELETE_ELEM: - case Op.TO_KEY: - case Op.IN: - case Op.INSTANCEOF: - case Op.ADD: - case Op.SUB: - case Op.MUL: - case Op.LT: - case Op.LE: - case Op.GT: - case Op.GE: - case Op.SEQ: - case Op.SNE: - case Op.NOT: - case Op.THROW: - case Op.RETURN: - case Op.END_PROGRAM: - case Op.NOP: - case Op.CALL_SPREAD: - case Op.NEW_SPREAD: - case Op.FOR_IN: - case Op.GENERATOR_START: - return "" - case Op.PUSH_BOOL: - return a === 1 ? "true" : "false" - case Op.PUSH_INT: - return String(sbx) - case Op.PUSH_CONST: - return `${bx} (${JSON.stringify(c.consts[bx])})` - case Op.POPN: - case Op.NEW_ARRAY: - case Op.CONCAT: - case Op.COPY_REST: - case Op.END_FINALLY: - case Op.EXTRA: - return a === 0 ? String(bx) : `a=${a} bx=${bx}` - case Op.PICK: - case Op.ROT: - case Op.CALL: - return String(a) - case Op.NEW: - return a === 255 ? "check" : String(a) - case Op.GET_LOCAL: - case Op.HOLE_LOCAL: - case Op.COPY_CELL: - case Op.GET_CELL: - return `${bx} (${c.localNames[bx] ?? "?"})` - case Op.NEW_CELL: - return `${a === 1 ? "wrap " : ""}${bx} (${c.localNames[bx] ?? "?"})` - case Op.PUT_LOCAL: - case Op.PUT_CELL: { - const prefix = a === PutKind.INIT ? ".init " : a === PutKind.CONST ? ".const " : "" - return `${prefix}${bx} (${c.localNames[bx] ?? "?"})` - } - case Op.GET_UPVAL: - return `${bx} (${c.upvalNames[bx] ?? "?"})` - case Op.PUT_UPVAL: { - const prefix = a === PutKind.INIT ? ".init " : a === PutKind.CONST ? ".const " : "" - return `${prefix}${bx} (${c.upvalNames[bx] ?? "?"})` - } - case Op.GET_GLOBAL: { - const prefix = a === 1 ? ".typeof " : a === 2 ? ".put " : "" - return `${prefix}${JSON.stringify(c.consts[bx])}` - } - case Op.GET_INTRINSIC: - return `${JSON.stringify(c.consts[bx])}` - case Op.ARGS: - return a === 0 ? "arguments" : a === 1 ? `rest(${bx})` : a === 2 ? "self" : a === 3 ? "this" : `arg[${bx}]` - case Op.CLOSURE: - return `fn#${bx}` - case Op.SET_NAME: - return a === 0 ? JSON.stringify(c.consts[bx]) : "(computed)" - case Op.GET_PROP: { - const prefix = a === 1 ? ".keep " : a === 2 ? ".destr " : "" - return `${prefix}${JSON.stringify(c.consts[bx])}` - } - case Op.GET_ELEM: - return a === 1 ? ".keep" : a === 2 ? ".destr" : "" - case Op.PUT_PROP: - case Op.DELETE_PROP: - return JSON.stringify(c.consts[bx]) - case Op.DEFINE_FIELD: - return a === 0 ? JSON.stringify(c.consts[bx]) : "(computed)" - case Op.DEFINE_ACCESSOR: - return `${(a & 2) === 0 ? "get" : "set"} ${(a & 1) === 0 ? JSON.stringify(c.consts[bx]) : "(computed)"}` - case Op.CHECK_BASE: - return a === CheckBaseKind.READ - ? ".read" - : a === CheckBaseKind.WRITE_PROP - ? `.writeProp ${JSON.stringify(c.consts[bx])}` - : a === CheckBaseKind.WRITE_ELEM - ? ".writeElem" - : ".destructure" - case Op.BINOP: - return BinOpSymbols[a] ?? String(a) - case Op.UNARY: - return UnaryOpSymbols[a] ?? String(a) - case Op.INC: - return a === 0 ? "+1" : "-1" - case Op.JUMP: - case Op.LOOP: - case Op.JUMP_IF_FALSE: - case Op.JUMP_IF_TRUE: - return `-> ${bx}` - case Op.JUMP_COND: { - const kind = - a === CondKind.TRUTHY_KEEP - ? ".truthyKeep" - : a === CondKind.FALSY_KEEP - ? ".falsyKeep" - : a === CondKind.NOT_NULLISH_KEEP - ? ".notNullishKeep" - : a === CondKind.DEFINED - ? ".defined" - : a === CondKind.NULLISH - ? ".nullish" - : ".nullishMethod" - return `${kind} -> ${bx}` - } - case Op.ITER_STEP: - case Op.ITER_RESULT: - case Op.ITER_CLOSE: - case Op.ITER_APPEND_ALL: - case Op.YSTAR: - case Op.YSTAR_RESULT: - return `slot=${a} -> ${bx}` - case Op.AWAIT: - return a === 1 ? ".unlocated" : "" - case Op.YIELD: - return "" - case Op.RESUME: - return `-> ${bx}` - default: - return `a=${a} bx=${bx}` - } -} - -export const disassemble = (codes: ReadonlyArray | Code): string => { - const list = Array.isArray(codes) ? codes : [codes] - return list.map(disassembleCode).join("\n\n") -} - -export const disassembleSource = (sourceText: string): string => { - const parsed = parseProgram(sourceText) - if (!parsed.ok) throw new Error(parsed.error.message) - return disassemble(compileSource(parsed.source)) -} - -if (import.meta.main) { - const arg = process.argv[2] - if (!arg) { - console.error("Usage: bun run script/disasm.ts ") - process.exit(1) - } - const file = Bun.file(arg) - const source = (await file.exists()) ? await file.text() : arg - console.log(disassembleSource(source)) -} diff --git a/packages/codemode/script/prelude.ts b/packages/codemode/script/prelude.ts deleted file mode 100644 index ec2ebd61610..00000000000 --- a/packages/codemode/script/prelude.ts +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env bun - -// Compiles the built-in sources (the prelude, the VM's internal helpers) ahead of time into src/language/prelude/bytecode.json, -// which a process loads instead of parsing and compiling them (see src/language/prelude/bytecode.ts). Run it after changing -// either source or the compiler; test/prelude-bytecode.test.ts fails until then. - -import { parse } from "acorn" -import { Source } from "../src/language/runtime/source.js" -import { saveCodes } from "../src/language/prelude/bytecode.js" -import { code } from "../src/language/prelude/source.js" -import { compileSource } from "../src/language/compiler/compile.js" -import { INTERNAL_SOURCE } from "../src/language/internal-prelude.js" - -export const compileBuiltins = () => - Object.fromEntries( - [ - ["@prelude", code], - ["@vm-internal", INTERNAL_SOURCE], - ].map(([id, text]) => { - const source = new Source(id!, text!, parse(text!, { ecmaVersion: "latest", sourceType: "script" })) - return [id, saveCodes(text!, compileSource(source, { internal: true }))] - }), - ) - -if (import.meta.main) { - await Bun.write( - new URL("../src/language/prelude/bytecode.json", import.meta.url), - `${JSON.stringify(compileBuiltins())}\n`, - ) -} diff --git a/packages/codemode/script/setup.ts b/packages/codemode/script/setup.ts deleted file mode 100644 index 8743326bd46..00000000000 --- a/packages/codemode/script/setup.ts +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env bun - -// Per-run setup cost: making a runtime, and running a trivial program end to end, in microseconds. -// Usage: bun run script/setup.ts [--iterations N] - -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" -import { Interpreter } from "../src/language/runtime/interpreter.js" -import { createBuiltins } from "../src/language/runtime/intrinsics.js" - -const index = process.argv.indexOf("--iterations") -const iterations = index === -1 ? 2000 : Number(process.argv[index + 1]) - -const runtime = CodeMode.make({ tools: {} }) - -const measure = async (name: string, work: () => unknown) => { - for (let at = 0; at < 200; at++) await work() - const times: Array = [] - for (let at = 0; at < iterations; at++) { - const start = performance.now() - await work() - times.push(performance.now() - start) - } - times.sort((a, b) => a - b) - const micros = (ms: number) => `${(ms * 1000).toFixed(0).padStart(5)} µs` - console.log( - `${name.padEnd(24)} median ${micros(times[times.length >> 1]!)} p10 ${micros(times[Math.floor(times.length / 10)]!)}`, - ) -} - -await measure("runtime", () => new Interpreter({ builtins: createBuiltins() })) -await measure("trivial program", () => Effect.runPromise(runtime.execute("return 1"))) diff --git a/packages/codemode/script/sync-test262.ts b/packages/codemode/script/sync-test262.ts deleted file mode 100644 index 2b2e8319f36..00000000000 --- a/packages/codemode/script/sync-test262.ts +++ /dev/null @@ -1,62 +0,0 @@ -// Copies the manifest's test262 directories from a local checkout into test/test262, verbatim. -// Files needing unsupported flags, features, or harness includes, or whose code crosses one of the -// interpreter's intentional boundaries, are not copied, so the vendored tree is exactly what -// test/test262.test.ts runs. -// -// Usage: bun run script/sync-test262.ts /path/to/test262 -import path from "node:path" -import { rm } from "node:fs/promises" - -type Frontmatter = { flags?: Array; features?: Array; includes?: Array } - -const root = path.resolve(import.meta.dir, "../test/test262") -const manifest = (await Bun.file(path.join(root, "manifest.json")).json()) as { - revision: string - directories: Array - harness: Array - flags: Array - features: Array - boundaries: Record -} -const boundaries = Object.entries(manifest.boundaries).map(([name, pattern]) => [name, new RegExp(pattern)] as const) -const checkout = process.argv[2] -if (checkout === undefined) { - console.error("usage: bun run script/sync-test262.ts /path/to/test262") - process.exit(1) -} -const head = (await Bun.$`git -C ${checkout} rev-parse HEAD`.text()).trim() -if (head !== manifest.revision) { - console.error(`checkout is at ${head}; manifest pins ${manifest.revision}`) - process.exit(1) -} - -const excluded = new Map() -let copied = 0 -for (const dir of manifest.directories) { - await rm(path.join(root, dir), { recursive: true, force: true }) - const from = path.join(checkout, "test", dir) - for await (const file of new Bun.Glob("**/*.js").scan({ cwd: from })) { - if (file.endsWith("_FIXTURE.js")) continue - const source = await Bun.file(path.join(from, file)).text() - const start = source.indexOf("/*---") - const end = source.indexOf("---*/", start) - const meta = start === -1 ? {} : (Bun.YAML.parse(source.slice(start + 5, end)) as Frontmatter) - const code = start === -1 ? source : source.slice(end + 5) - const reason = - meta.flags?.find((flag) => manifest.flags.includes(flag)) ?? - meta.features?.find((feature) => manifest.features.includes(feature)) ?? - meta.includes?.find((include) => !manifest.harness.includes(include)) ?? - boundaries.find(([, pattern]) => pattern.test(code))?.[0] - if (reason !== undefined) { - excluded.set(reason, (excluded.get(reason) ?? 0) + 1) - continue - } - await Bun.write(path.join(root, dir, file), Bun.file(path.join(from, file))) - copied++ - } -} - -console.log(`copied ${copied} files`) -for (const [reason, count] of [...excluded].sort((a, b) => b[1] - a[1])) { - console.log(` excluded ${String(count).padStart(5)} ${reason}`) -} diff --git a/packages/codemode/script/test262-report.ts b/packages/codemode/script/test262-report.ts deleted file mode 100644 index fd2f2307fd2..00000000000 --- a/packages/codemode/script/test262-report.ts +++ /dev/null @@ -1,55 +0,0 @@ -// Runs every vendored test262 file, including skipped ones, and groups failures by cause. Pass -// --write to regenerate test/test262/skipped.txt from the current failures. -// -// Usage: bun run script/test262-report.ts [--write] [path-prefix] -import path from "node:path" -import { root, run, skipped } from "../test/test262/run.js" - -const write = process.argv.includes("--write") -const prefix = process.argv.slice(2).find((arg) => !arg.startsWith("--")) ?? "" -const files = [...new Bun.Glob("**/*.js").scanSync({ cwd: root })].filter((file) => file.startsWith(prefix)).sort() - -const failures: Array<{ file: string; reason: string }> = [] -const recovered: Array = [] -for (const file of files) { - const outcome = await run(file) - if (outcome.status === "fail") failures.push({ file, reason: outcome.reason }) - if (outcome.status === "pass" && skipped.has(file)) recovered.push(file) -} - -// Collapse a reason to the part that identifies the cause rather than the test. -const bucket = (reason: string) => { - const syntax = reason.match(/Syntax '([A-Za-z]+)' is not supported/) - if (syntax) return `unsupported syntax ${syntax[1]}` - if (reason.startsWith("expected ")) return reason.replace(/ but got .*/, " but the program ran") - return reason - .replace(/^(\$DONE: |ExecutionFailure: |InvalidDataValue: |ParseError: |Uncaught: |Test262Error: |Error: )+/, "") - .replace(/ \(line \d+, col \d+\)/, "") - .replace(/^[\w$]+\.(\w+) is not a function/, ".$1 is not a function") - .replace(/^[\w$]+ cannot be constructed/, "… cannot be constructed") - .replace(/'[^']*'/g, "'…'") - .slice(0, 100) -} - -const buckets = new Map>() -for (const failure of failures) { - const key = bucket(failure.reason) - buckets.set(key, [...(buckets.get(key) ?? []), failure.file]) -} - -console.log(`${files.length - failures.length} pass, ${failures.length} fail of ${files.length}\n`) -for (const [key, list] of [...buckets].sort((a, b) => b[1].length - a[1].length)) { - console.log(`${String(list.length).padStart(5)} ${key}`) - for (const file of list.slice(0, 3)) console.log(` ${file}`) - if (list.length > 3) console.log(` … ${list.length - 3} more`) -} -if (recovered.length > 0) { - console.log(`\n${recovered.length} skipped files pass now; remove them from skipped.txt:`) - for (const file of recovered) console.log(` ${file}`) -} - -if (write) { - const lines = failures.map((failure) => `${failure.file} # ${bucket(failure.reason)}`) - await Bun.write(path.join(root, "skipped.txt"), `${lines.join("\n")}\n`) - console.log(`\nwrote ${lines.length} entries to skipped.txt`) -} diff --git a/packages/codemode/src/codemode/codemode.ts b/packages/codemode/src/codemode/codemode.ts index d5d393ecf40..76812c26281 100644 --- a/packages/codemode/src/codemode/codemode.ts +++ b/packages/codemode/src/codemode/codemode.ts @@ -7,15 +7,17 @@ import { fromBytes, globalNames, Host, - Language, + // Code Mode exports its own Runtime type. + Runtime as Language, type Snapshot, SnapshotError, type SnapshotHeader, - SuspendError, toBytes, -} from "../language/index.js" +} from "psychoscript" -export { fromBytes, scanTools, SnapshotError, SuspendError, toBytes } +export const SuspendError = Language.SuspendError +export type SuspendError = Language.SuspendError +export { fromBytes, scanTools, SnapshotError, toBytes } export type { Snapshot, SnapshotHeader } /** A tool call admitted during an execution. */ @@ -208,11 +210,18 @@ export type Program = { } const resolveExecutionLimits = (limits?: ExecutionLimits): ResolvedExecutionLimits => ({ - timeoutMs: Language.Runtime.validateLimit("timeoutMs", limits?.timeoutMs, 1), - maxToolCalls: Language.Runtime.validateLimit("maxToolCalls", limits?.maxToolCalls, 0), - maxOutputBytes: Language.Runtime.validateLimit("maxOutputBytes", limits?.maxOutputBytes, 0), + timeoutMs: validateLimit("timeoutMs", limits?.timeoutMs, 1), + maxToolCalls: validateLimit("maxToolCalls", limits?.maxToolCalls, 0), + maxOutputBytes: validateLimit("maxOutputBytes", limits?.maxOutputBytes, 0), }) +const validateLimit = (name: string, value: number | undefined, minimum: number) => { + if (value !== undefined && (!Number.isSafeInteger(value) || value < minimum)) { + throw new RangeError(`${name} must be a safe integer greater than or equal to ${minimum}.`) + } + return value +} + /** Executes one Effect-native CodeMode program without constructing a reusable runtime. */ export const execute = < const Provided extends Record, @@ -240,7 +249,7 @@ export function make< } } // One language runtime for each set of the runtime's extensions a run picks, made when first picked. - const runtimes = new Map>() + const runtimes = new Map>() const runtimeFor = (selected: ReadonlyArray = extensions) => { for (const extension of selected) { if (!extensions.includes(extension)) { @@ -253,7 +262,7 @@ export function make< const known = runtimes.get(key) if (known !== undefined) return known // The tools' and extensions' environment, which the language runtime can't infer through them. - const made = Language.Runtime.make({ + const made = Language.make({ globals: (run) => ({ ...ToolRuntime.globals(prepared, hooks, run, limits.maxToolCalls), ...Object.fromEntries( @@ -270,7 +279,7 @@ export function make< limits: { timeoutMs: limits.timeoutMs, maxOutputBytes: limits.maxOutputBytes }, // Arguments cross as JSON would carry them: functions are left out and promises are awaited. translate: { functions: "drop", promises: "await" }, - }) as unknown as Language.Runtime.Runtime + }) as unknown as Language.Runtime runtimes.set(key, made) return made } @@ -365,13 +374,13 @@ const extensionFunction = ( } // A language program whose outcomes report the run's tool calls in place of its metadata. -const reported = (program: Language.Runtime.Program): Program => ({ +const reported = (program: Language.Program): Program => ({ run: () => Effect.map(program.run(), outcome), suspend: (options) => Effect.map(program.suspend(options), outcome), }) // A run's outcome as Code Mode reports it: the tool calls in place of the run's metadata. -const outcome = (ended: Language.Runtime.Outcome): Outcome => { +const outcome = (ended: Language.Outcome): Outcome => { if (ended.ok === "suspended") return ended const { metadata, ...result } = ended return { ...result, toolCalls: ToolRuntime.toolCalls(metadata) } as Result diff --git a/packages/codemode/src/codemode/extension.ts b/packages/codemode/src/codemode/extension.ts index 245f6c45554..c6e78d31902 100644 --- a/packages/codemode/src/codemode/extension.ts +++ b/packages/codemode/src/codemode/extension.ts @@ -69,7 +69,7 @@ export const make = >>( const asyncGlobals = new WeakSet() -export { StreamingResponse } from "../language/streaming-response.js" +export { StreamingResponse } from "psychoscript" const AsyncFunction = (async () => {}).constructor /** Marks a global that returns a Promise or an Effect, so a denied call rejects its promise instead of throwing. */ diff --git a/packages/codemode/src/codemode/scan.ts b/packages/codemode/src/codemode/scan.ts index 6610f7fa1ac..96834cf439f 100644 --- a/packages/codemode/src/codemode/scan.ts +++ b/packages/codemode/src/codemode/scan.ts @@ -1,9 +1,7 @@ import type { AnyNode, BlockStatement, ModuleDeclaration, Pattern, Program, Statement } from "acorn" import { Result } from "effect" import type { Diagnostic } from "./codemode.js" -import { parseProgram } from "../language/runtime/execute.js" -import { formatLocation } from "../language/runtime/model.js" -import { moduleName } from "../language/runtime/modules.js" +import { formatLocation, moduleName, parseProgram } from "psychoscript" /** * Extracts every `tools.` referenced by a Code Mode program, in first-seen order. Fails on syntax errors, diff --git a/packages/codemode/src/codemode/tool-runtime.ts b/packages/codemode/src/codemode/tool-runtime.ts index eabe07d080c..6c37e06d784 100644 --- a/packages/codemode/src/codemode/tool-runtime.ts +++ b/packages/codemode/src/codemode/tool-runtime.ts @@ -1,11 +1,7 @@ import { Cause, Effect, Exit, Formatter, Schema } from "effect" -import type { Json } from "../language/data.js" -import { compareText } from "../language/runtime/operations.js" import type { DiagnosticKind } from "./codemode.js" import { ToolError, toolError } from "./tool-error.js" -import { Host } from "../language/host-function.js" -import { HostFailure } from "../language/runtime/model.js" -import type { Run } from "../language/runtime/execute.js" +import { Host, HostFailure, type Json, type Run } from "psychoscript" import { decodeInput as decodeToolInput, decodeOutput as decodeToolOutput, @@ -858,3 +854,5 @@ const toJson = (value: unknown): Json | undefined => { } export * as ToolRuntime from "./tool-runtime.js" + +const compareText = (left: string, right: string) => (left < right ? -1 : left > right ? 1 : 0) diff --git a/packages/codemode/src/language/async.ts b/packages/codemode/src/language/async.ts deleted file mode 100644 index 8b9051eee3e..00000000000 --- a/packages/codemode/src/language/async.ts +++ /dev/null @@ -1,474 +0,0 @@ -import type { Diagnostic } from "./runtime/model.js" -import { normalizeError, locate } from "./runtime/errors.js" -import { MAX_PENDING_PROMISES } from "./runtime/limits.js" -import { type AstNode, IteratorSymbol, rangeError, typeError } from "./runtime/model.js" -import { - access, - Arr, - BoundFn, - type Callable, - Fn, - GetterCall, - isProgramAccessor, - lookup, - peek, - iteratorResult, - Obj, - Position, - PromiseObj, - Resolver, - type Value, -} from "./runtime/objects.js" -import { builtinCursor, isThenable } from "./runtime/operations.js" -import { adoptThenable, capability, finishCombination, react } from "./runtime/promises.js" -import { describeValue, typeofValue } from "./runtime/references.js" -import { abrupt, type Completion, Interruption, Invoke, MAX_CALL_DEPTH, normal } from "./runtime/signals.js" -import { type Combination, type Job, type Reaction, Resolving } from "./scheduler.js" -import { internalCode, VmIntrinsic } from "./internal-prelude.js" -import { CodeFlags } from "./opcodes.js" -import { type Frame, type FrameMode, Mode, type Vm } from "./vm.js" - -export type SettlingTarget = { - resolve(value: Value): void - reject(reason: unknown): void -} - -/** - * Target for a `Promise.prototype.finally` cleanup frame running in `Mode.SETTLE`. - * When the cleanup completes with `result`, chains `finallyCleaned` and `finallyOutcome` reactions. - */ -export class FinallyTarget implements SettlingTarget { - constructor( - readonly vm: Vm, - readonly made: Resolving, - readonly site: AstNode | undefined, - readonly outcome: Completion, - ) {} - - resolve(result: Value): void { - const after = this.vm.scheduler.promiseResolve(result) - const derived = capability(this.vm.ctx, this.site) - this.vm.scheduler.then(after, { kind: "finallyCleaned", target: derived }) - this.vm.scheduler.then(derived.promise, { - kind: "finallyOutcome", - target: this.made, - outcome: this.outcome, - }) - } - - reject(reason: unknown): void { - this.made.reject(reason) - } -} - -/** - * Target for `$vmAsyncFromSyncClose`: regardless of whether `iterator.return()` succeeds or throws, - * the original rejection reason wins. - */ -export class AsyncFromSyncCloseTarget implements SettlingTarget { - constructor( - readonly made: Resolving, - readonly reason: unknown, - ) {} - - resolve(_value: Value): void { - this.made.reject(this.reason) - } - - reject(_error: unknown): void { - this.made.reject(this.reason) - } -} - -type Parked = { - readonly promise: PromiseObj - readonly node: AstNode | undefined - readonly result: Value -} - -export class VmScheduler { - intrinsicThen: Callable | undefined - readonly parked = new Map() - readonly queue: Array = [] - head = 0 - pending = 0 - nextID = 0 - readonly unhandled = new Map() - - constructor(readonly vm: Vm) {} - - get hasJobs(): boolean { - return this.head < this.queue.length - } - - newPromise(): PromiseObj { - if (this.pending >= MAX_PENDING_PROMISES) { - throw rangeError( - `Too many pending promises (limit ${MAX_PENDING_PROMISES}); await promises before creating more.`, - ) - } - this.pending++ - return new PromiseObj(this.vm.ctx.builtins.Promise, this.nextID++) - } - - resolving(promise: PromiseObj, site?: AstNode): Resolving { - return new Resolving(this, promise, site) - } - - then(promise: PromiseObj, reaction: Reaction): void { - if (promise.state === "pending") { - promise.reactions.push(reaction) - } else { - if (promise.state === "rejected") this.unhandled.delete(promise) - const settled = promise.state === "fulfilled" ? normal(promise.result) : abrupt(promise.result) - this.enqueue({ kind: "reaction", reaction, settled }) - } - promise.handled = true - } - - detach(promise: PromiseObj, reaction: Reaction): void { - const index = promise.reactions.indexOf(reaction) - if (index >= 0) promise.reactions.splice(index, 1) - } - - promiseResolve(value: Value): PromiseObj { - if (value instanceof PromiseObj) return value - const promise = this.newPromise() - this.resolveWith(promise, value) - return promise - } - - reject(promise: PromiseObj, reason: unknown): void { - this.settle(promise, abrupt(reason)) - } - - resolveWith(promise: PromiseObj, resolution: Value, site?: AstNode): void { - if (resolution === promise) { - const cycle = typeError("Chaining cycle detected: a promise cannot resolve with itself.", site) - this.settle(promise, abrupt(cycle)) - return - } - if (!(resolution instanceof Obj)) { - this.settle(promise, normal(resolution)) - return - } - const then = access(resolution, "then") - // A program `then` getter is program code, so it runs in a job of its own (`$vmThenableGet`). - if (then instanceof GetterCall) { - this.enqueue({ kind: "thenable-get", promise, thenable: resolution }) - return - } - if (typeofValue(then) !== "function") { - this.settle(promise, normal(resolution)) - return - } - this.enqueue({ kind: "thenable", promise, thenable: resolution, then }) - } - - settle(promise: PromiseObj, completion: Completion): void { - if (promise.state !== "pending") return - this.pending-- - promise.state = completion.ok ? "fulfilled" : "rejected" - promise.result = completion.ok ? completion.value : completion.error - const reactions = promise.reactions - promise.reactions = [] - if (!completion.ok && !promise.handled && !(completion.error instanceof Interruption)) { - const failure = normalizeError(completion.error) - this.unhandled.set(promise, { - ...failure, - message: `Unhandled rejection from an un-awaited promise: ${failure.message}`, - }) - } - for (const reaction of reactions) { - this.enqueue({ kind: "reaction", reaction, settled: completion }) - } - } - - enqueue(job: Job): void { - this.queue.push(job) - } - - dequeue(): Job | undefined { - if (this.head === this.queue.length) { - if (this.head > 0) { - this.queue.length = 0 - this.head = 0 - } - return undefined - } - const job = this.queue[this.head++] - if (this.head > 4096 && this.head * 2 > this.queue.length) { - this.queue.splice(0, this.head) - this.head = 0 - } - return job - } - - compact(): void { - this.queue.splice(0, this.head) - this.head = 0 - } - - park(frames: Array, promise: PromiseObj, node: AstNode | undefined, result: Value): void { - this.parked.set(frames[0]!, { promise, node, result }) - this.then(promise, { kind: "await", frames }) - } - - stuckAwait(): AstNode | undefined { - const results = new Set() - for (const parked of this.parked.values()) { - if (parked.result instanceof PromiseObj) results.add(parked.result) - } - const located = [...this.parked.values()].filter((parked) => parked.node !== undefined) - return (located.find((parked) => !results.has(parked.promise)) ?? located[0])?.node - } - - diagnostics(): Array { - return [...this.unhandled].sort(([left], [right]) => left.id - right.id).map(([, diagnostic]) => diagnostic) - } - - beginJob(job: Job): void { - const vm = this.vm - if (job.kind === "thenable-get") { - const resolving = this.resolving(job.promise) - const proto = vm.ctx.builtins.Function - vm.pushInternal( - internalCode("$vmThenableGet"), - [job.thenable, new Resolver(proto, "", resolving, "resolve"), new Resolver(proto, "", resolving, "reject")], - undefined, - Mode.REJECT_ONLY, - resolving, - ) - return - } - if (job.kind === "thenable") { - const call = adoptThenable(vm.ctx, job.promise, job.thenable, job.then) - if (call === undefined || call.kind !== "thenable") return - this.enterSettlingCall( - undefined, - call.then, - call.thenable, - call.functions, - Mode.REJECT_ONLY, - call.resolving, - undefined, - undefined, - ) - return - } - - const reaction = job.reaction - if (reaction.kind === "await") { - const frames = reaction.frames - this.parked.delete(frames[0]!) - for (const f of frames) { - if (f.counted) vm.depth++ - vm.frames.push(f) - } - const top = frames[frames.length - 1]! - if (job.settled.ok) { - top.regs[top.sp++] = job.settled.value - return - } - top.pc-- - vm.unwind(job.settled.error) - return - } - - if (reaction.kind === "asyncFromSync") { - if (job.settled.ok) { - reaction.made.resolve(iteratorResult(vm.ctx.builtins.Object, job.settled.value as Value, reaction.done)) - return - } - if ( - reaction.done || - reaction.close === undefined || - job.settled.error instanceof Interruption || - reaction.close instanceof Position - ) { - reaction.made.reject(job.settled.error) - return - } - vm.pushInternal( - internalCode("$vmAsyncFromSyncClose"), - [reaction.close.iterator], - reaction.site, - Mode.SETTLE, - new AsyncFromSyncCloseTarget(reaction.made, job.settled.error), - ) - return - } - - const call = react(vm.ctx, reaction, job.settled) - if (call === undefined) return - if (call.kind === "handler") { - this.enterSettlingCall( - undefined, - call.handler, - undefined, - [call.argument], - Mode.SETTLE, - call.derived, - undefined, - undefined, - ) - return - } - if (call.kind === "finally") { - this.enterSettlingCall( - undefined, - call.cleanup, - undefined, - [], - Mode.SETTLE, - new FinallyTarget(vm, call.made, call.site, call.outcome), - undefined, - call.site, - ) - } - } - - enterSettlingCall( - callerFrame: Frame | undefined, - callable: Value, - thisVal: Value, - args: Array, - mode: FrameMode, - target: SettlingTarget, - answer: Value, - site: AstNode | undefined, - ): number { - const vm = this.vm - while (callable instanceof BoundFn) { - thisVal = callable.boundThis - args = [...callable.boundArgs, ...args] - callable = callable.target - } - - if (callable instanceof Resolver) { - try { - const res = callable.invoke(thisVal, args) as Value - if (mode === Mode.SETTLE) target.resolve(res) - } catch (err) { - target.reject(locate(err, site ?? vm.currentSite())) - } - if (answer !== undefined && callerFrame !== undefined) { - callerFrame.regs[callerFrame.sp++] = answer - } - return 0 - } - - if (callable instanceof Fn) { - const code = callable.code - if ((code.flags & (CodeFlags.ASYNC | CodeFlags.GENERATOR | CodeFlags.CLASS_CONSTRUCTOR)) === 0) { - const counted = (code.flags & CodeFlags.INTERNAL) === 0 - if (counted && vm.depth > MAX_CALL_DEPTH) { - target.reject(rangeError("Maximum call stack size exceeded", site ?? vm.currentSite())) - if (answer !== undefined && callerFrame !== undefined) { - callerFrame.regs[callerFrame.sp++] = answer - } - return 0 - } - vm.pushFn(callable, thisVal, args, site ?? callerFrame?.origin, mode, target, answer) - return 1 - } - } - - vm.pushInternal( - internalCode("$vmSettleCall"), - [callable, thisVal, new Arr(vm.ctx.builtins.Array, args)], - site ?? callerFrame?.origin, - mode, - target, - answer, - ) - return 1 - } - - handlePromisePush( - callerFrame: Frame, - kindName: string, - slots: Array, - site: AstNode | undefined, - ): number | undefined { - // An executor's result is ignored and only its failure rejects; `Promise.try` settles with its callback's outcome. - if (kindName === "Promise executor" || kindName === "Promise.try") { - const made = slots[0] as Resolving - const mode = kindName === "Promise.try" ? Mode.SETTLE : Mode.REJECT_ONLY - return this.enterSettlingCall( - callerFrame, - slots[1] as Value, - undefined, - slots[2] as Array, - mode, - made, - made.promise, - site, - ) - } - if (kindName === "Promise combinator") { - const made = slots[0] as Resolving - this.vm.pushInternal( - internalCode("$vmCombine"), - [slots[1], slots[2]], - site ?? callerFrame.origin, - Mode.REJECT_ONLY, - made, - made.promise, - ) - return 1 - } - return undefined - } -} - -export const registerAsyncIntrinsics = (map: Map, vm: Vm): void => { - const ctx = vm.ctx - const builtins = ctx.builtins - const add = (name: string, fn: (args: Array) => Value | Invoke) => { - map.set(name, new VmIntrinsic(name, fn)) - } - - add("$Apply", ([callable, thisVal, args]) => { - const argItems = args instanceof Arr ? [...args.items] : [] - return new Invoke(callable, thisVal, argItems, vm.currentSite()) - }) - - add("$CombineStart", ([nameVal, items]) => { - const name = nameVal as Combination["name"] - // Only whether there is a method: `$vmCombine`'s for...of reads it (a getter too) in program code. - const slot = items instanceof Obj ? lookup(items, IteratorSymbol) : undefined - const method = slot === undefined || isProgramAccessor(slot) ? slot : peek(items as Obj, IteratorSymbol) - const isIter = builtinCursor(builtins, items) !== undefined || (method !== undefined && method !== null) - if (!isIter) { - throw typeError(`Promise.${name} expects a synchronous iterable, received ${describeValue(items)}.`) - } - const top = vm.frames[vm.frames.length - 1]! - const made = top.target as Resolving - const comb: Combination = { name, made, values: [], reasons: [], remaining: 1, attached: [] } - return comb as unknown as Value - }) - - add("$CombineAdd", ([combVal, item]) => { - const c = combVal as unknown as Combination - const p = vm.scheduler.promiseResolve(item) - const reaction: Reaction = { kind: "combinator", combination: c, index: c.values.length, called: false } - c.values.push(undefined) - c.reasons.push(undefined) - c.remaining++ - c.attached.push([p, reaction]) - vm.scheduler.then(p, reaction) - return undefined - }) - - add("$CombineEnd", ([combVal]) => { - const c = combVal as unknown as Combination - if (c.name === "race" && c.attached.length === 0) { - throw typeError("Promise.race([]) would never settle; provide at least one promise or value.") - } - finishCombination(ctx, c) - return undefined - }) - - add("$IsThenable", ([val]) => isThenable(val)) -} diff --git a/packages/codemode/src/language/code.ts b/packages/codemode/src/language/code.ts deleted file mode 100644 index 8f406707be0..00000000000 --- a/packages/codemode/src/language/code.ts +++ /dev/null @@ -1,435 +0,0 @@ -import type { AstNode } from "./runtime/model.js" -import type { Source } from "./runtime/source.js" -import { type ConstValue, Op, type OpCode, packWord } from "./opcodes.js" - -type SourceRef = { - readonly id: string - readonly hash: string -} - -export type Label = { - pc: number - readonly patches: Array - depth: number | undefined -} - -/** - * Immutable compiled function or program body. Holds no per-run mutable state. - */ -export class Code { - readonly source: SourceRef - readonly index: number - readonly name: string - readonly flags: number - readonly length: number - readonly params: number - readonly locals: number - readonly maxStack: number - readonly code: Int32Array - readonly consts: ReadonlyArray - /** Per upvalue: `[from (0 = parent cell slot, 1 = parent upvalue), index]`. */ - readonly captures: Int32Array - /** Exception handlers `[start, end, target, depth]*`, innermost first (`end` exclusive). */ - readonly handlers: Int32Array - /** Per finally level: `[tagSlot, valSlot, entryDepth, n, target_0 … target_{n-1}]`. */ - readonly finallies: Int32Array - /** Offsets into `finallies` indexed by finally level. */ - readonly finallyOffsets: Int32Array - /** Run-length encoded `[pc, nodeIndex]*` sorted by `pc`. */ - readonly sites: Int32Array - readonly localNames: ReadonlyArray - readonly upvalNames: ReadonlyArray - readonly sourceObj: Source | undefined - - constructor(init: { - readonly source: SourceRef - readonly index: number - readonly name: string - readonly flags: number - readonly length: number - readonly params: number - readonly locals: number - readonly maxStack: number - readonly code: Int32Array - readonly consts: ReadonlyArray - readonly captures: Int32Array - readonly handlers: Int32Array - readonly finallies: Int32Array - readonly finallyOffsets: Int32Array - readonly sites: Int32Array - readonly localNames: ReadonlyArray - readonly upvalNames?: ReadonlyArray | undefined - readonly sourceObj?: Source | undefined - }) { - this.source = init.source - this.index = init.index - this.name = init.name - this.flags = init.flags - this.length = init.length - this.params = init.params - this.locals = init.locals - this.maxStack = init.maxStack - this.code = init.code - const consts: Array = [""] - consts.pop() - for (let i = 0; i < init.consts.length; i++) consts.push(init.consts[i]!) - this.consts = consts - this.captures = init.captures - this.handlers = init.handlers - this.finallies = init.finallies - this.finallyOffsets = init.finallyOffsets - this.sites = init.sites - this.localNames = init.localNames - this.upvalNames = init.upvalNames ?? [] - this.sourceObj = init.sourceObj - } - - /** Resolves the AST node index recorded for `pc`, or `-1` when none was recorded. */ - nodeIndexAt(pc: number): number { - const sites = this.sites - const count = sites.length >>> 1 - if (count === 0) return -1 - let low = 0 - let high = count - 1 - let best = -1 - while (low <= high) { - const mid = (low + high) >>> 1 - const entryPc = sites[mid << 1]! - if (entryPc <= pc) { - best = sites[(mid << 1) + 1]! - low = mid + 1 - } else { - high = mid - 1 - } - } - return best - } - - /** Resolves the AST node recorded for `pc`. */ - siteAt(pc: number): AstNode | undefined { - const index = this.nodeIndexAt(pc) - return index >= 0 ? this.sourceObj?.nodes[index] : undefined - } - - /** The same code over another parse of its source, so its sites resolve to that tree's nodes. */ - withSource(sourceObj: Source): Code { - return new Code({ ...this, sourceObj }) - } -} - -// The fields of a `Code` that are packed words. -const words = ["code", "captures", "handlers", "finallies", "finallyOffsets", "sites"] as const - -export type CodeJson = { readonly [field: string]: unknown } - -/** Code as JSON, for bytecode compiled ahead of time: every field but the source tree, which `codeFromJson` is given. */ -export const codeToJson = (code: Code): CodeJson => { - const { sourceObj: _, ...fields } = code - return { ...fields, ...Object.fromEntries(words.map((field) => [field, [...code[field]]])) } -} - -export const codeFromJson = (data: CodeJson, sourceObj: Source): Code => - new Code({ - ...(data as unknown as ConstructorParameters[0]), - ...Object.fromEntries(words.map((field) => [field, Int32Array.from(data[field] as Array)])), - sourceObj, - }) - -/** Raised when a narrow-jump function exceeds 16-bit jump range (`65,535` words) and must recompile in wide mode. */ -export class CodeSizeOverflow extends RangeError { - constructor(message = "Function bytecode exceeds 16-bit jump range") { - super(message) - this.name = "CodeSizeOverflow" - } -} - -const checkUint31 = (value: number, name: string): void => { - if (!Number.isInteger(value) || value < 0 || value > 0x7fffffff) { - throw new RangeError(`${name} out of range: ${value}`) - } -} - -export class CodeBuilder { - private readonly words: Array = [] - private readonly sitePairs: Array = [] - private lastNodeIndex = -2 - private readonly constList: Array = [] - // Strings and numbers (but -0) are pooled; other constants are each their own. - private readonly pooled = new Map() - private readonly handlerWords: Array = [] - private readonly finallyWords: Array = [] - private readonly finallyLevelOffsets: Array = [] - - depth = 0 - maxStack = 0 - wideJumps = false - forceExtra = false - - constructor( - readonly source: SourceRef, - readonly sourceObj: Source | undefined, - readonly index: number, - readonly name: string, - public flags: number, - readonly length: number, - readonly params: number, - public locals: number, - readonly localNames: Array, - readonly captures: Int32Array, - readonly upvalNames: ReadonlyArray = [], - ) {} - - get pc(): number { - return this.words.length - } - - adjustDepth(delta: number): void { - if (this.depth < 0) return - this.depth += delta - if (this.depth > this.maxStack) this.maxStack = this.depth - } - - setDepth(depth: number): void { - this.depth = depth - if (this.depth > this.maxStack) this.maxStack = this.depth - } - - unreachable(): void { - this.depth = -1 - } - - constant(value: ConstValue): number { - const poolable = typeof value === "string" || (typeof value === "number" && !Object.is(value, -0)) - const existing = poolable ? this.pooled.get(value) : undefined - if (existing !== undefined) return existing - const k = this.constList.length - checkUint31(k, "Constant index") - if (poolable) this.pooled.set(value, k) - this.constList.push(value) - return k - } - - private recordSite(pc: number, nodeIndex: number): void { - if (nodeIndex < 0 || nodeIndex === this.lastNodeIndex) return - this.sitePairs.push(pc, nodeIndex) - this.lastNodeIndex = nodeIndex - } - - private pushOp(op: OpCode, a: number, bx: number, nodeIndex: number, forceWide: boolean): number { - if ((op & 0xff) !== op || op === Op.EXTRA) { - throw new RangeError(`Invalid opcode: ${op}`) - } - checkUint31(a, "Operand a") - if (op === Op.NEW && a > 0xff) { - throw new RangeError(`Op.NEW operand a out of range: ${a}`) - } - if (op === Op.PUSH_INT) { - if (a !== 0 || (bx & 0xffff) !== bx) { - throw new RangeError(`Op.PUSH_INT operand out of range: a=${a} bx=${bx}`) - } - } else { - checkUint31(bx, "Operand bx") - } - if (a > 0xffff) { - this.recordSite(this.words.length, nodeIndex) - this.words.push(packWord(Op.EXTRA, 0, a >>> 16)) - this.words.push(packWord(Op.EXTRA, (a >>> 8) & 0xff, bx >>> 16)) - } else if (forceWide || a > 0xff || (op !== Op.PUSH_INT && bx > 0xffff)) { - this.recordSite(this.words.length, nodeIndex) - this.words.push(packWord(Op.EXTRA, a >>> 8, bx >>> 16)) - } - const pc = this.words.length - this.recordSite(pc, nodeIndex) - this.words.push(packWord(op, a & 0xff, bx & 0xffff)) - if (this.words.length > 0x7fffffff) { - throw new RangeError(`Bytecode length ${this.words.length} exceeds 31-bit limit`) - } - if (!this.wideJumps && !this.forceExtra && this.words.length > 0xffff) { - throw new CodeSizeOverflow() - } - return pc - } - - emit(op: OpCode, a = 0, bx = 0, nodeIndex = -1, stackDelta = 0): number { - if (this.depth < 0) return this.words.length - const pc = this.pushOp(op, a, bx, nodeIndex, this.forceExtra) - this.adjustDepth(stackDelta) - return pc - } - - emitNumber(value: number, nodeIndex = -1): void { - if (this.depth < 0) return - if (Number.isInteger(value) && !Object.is(value, -0) && value >= -32768 && value <= 32767 && !this.forceExtra) { - this.emit(Op.PUSH_INT, 0, value & 0xffff, nodeIndex, 1) - return - } - const k = this.constant(value) - this.emit(Op.PUSH_CONST, 0, k, nodeIndex, 1) - } - - emitString(value: string, nodeIndex = -1): void { - if (this.depth < 0) return - const k = this.constant(value) - this.emit(Op.PUSH_CONST, 0, k, nodeIndex, 1) - } - - newLabel(depth?: number): Label { - return { pc: -1, patches: [], depth } - } - - mark(label: Label): void { - const target = this.words.length - checkUint31(target, "Jump target") - label.pc = target - if (label.depth !== undefined) this.setDepth(label.depth) - else if (this.depth >= 0) label.depth = this.depth - for (const patchPc of label.patches) { - const hasExtra = patchPc > 0 && (this.words[patchPc - 1]! & 0xff) === Op.EXTRA - if (!hasExtra) { - if (target > 0xffff) throw new CodeSizeOverflow() - this.words[patchPc] = (this.words[patchPc]! & 0xffff) | (target << 16) - } else { - this.words[patchPc - 1] = (this.words[patchPc - 1]! & 0xffff) | ((target >>> 16) << 16) - this.words[patchPc] = (this.words[patchPc]! & 0xffff) | ((target & 0xffff) << 16) - } - } - label.patches.length = 0 - } - - emitJump(op: OpCode, a: number, label: Label, nodeIndex = -1, jumpDelta = 0, fallDelta: number | null = 0): void { - if (this.depth < 0) return - const targetDepth = this.depth + jumpDelta - if (label.depth === undefined) label.depth = targetDepth - const known = label.pc >= 0 - if (known && !this.wideJumps && !this.forceExtra && label.pc > 0xffff) { - throw new CodeSizeOverflow() - } - const pc = this.pushOp(op, a, known ? label.pc : 0, nodeIndex, this.wideJumps || this.forceExtra) - if (!known) label.patches.push(pc) - if (fallDelta === null) this.depth = -1 - else this.adjustDepth(fallDelta) - } - - addHandler(start: number, end: number, target: number, depth: number): void { - if (start >= end || target < 0) return - checkUint31(start, "Handler start") - checkUint31(end, "Handler end") - checkUint31(target, "Handler target") - checkUint31(depth, "Handler depth") - this.handlerWords.push(start, end, target, depth) - } - - reserveFinally(): number { - const level = this.finallyLevelOffsets.length - checkUint31(level, "Finally level") - this.finallyLevelOffsets.push(-1) - return level - } - - setFinally( - level: number, - tagSlot: number, - valSlot: number, - entryDepth: number, - targets: ReadonlyArray, - ): void { - checkUint31(level, "Finally level") - checkUint31(tagSlot, "Finally tagSlot") - checkUint31(valSlot, "Finally valSlot") - checkUint31(entryDepth, "Finally entryDepth") - checkUint31(targets.length, "Finally target count") - this.finallyLevelOffsets[level] = this.finallyWords.length - this.finallyWords.push(tagSlot, valSlot, entryDepth, targets.length) - for (const t of targets) { - if (!Number.isInteger(t) || t < -1 || t > 0x7fffffff) { - throw new RangeError(`Finally target out of range: ${t}`) - } - this.finallyWords.push(t) - } - } - - finish(): Code { - return new Code({ - source: this.source, - index: this.index, - name: this.name, - flags: this.flags, - length: this.length, - params: this.params, - locals: this.locals, - maxStack: this.maxStack, - code: new Int32Array(this.words), - consts: this.constList, - captures: this.captures, - handlers: new Int32Array(this.handlerWords), - finallies: new Int32Array(this.finallyWords), - finallyOffsets: new Int32Array(this.finallyLevelOffsets), - sites: new Int32Array(this.sitePairs), - localNames: this.localNames, - upvalNames: this.upvalNames, - sourceObj: this.sourceObj, - }) - } -} - -/** Deterministic FNV-1a 64-bit hash over a compiled `Code[]` array. */ -export const hashOf = (codes: ReadonlyArray): string => { - let h1 = 0x811c9dc5 - let h2 = 0xcbf29ce4 - const mix = (v: number) => { - h1 = Math.imul(h1 ^ (v & 0xff), 0x01000193) - h1 = Math.imul(h1 ^ ((v >>> 8) & 0xff), 0x01000193) - h2 = Math.imul(h2 ^ ((v >>> 16) & 0xff), 0x01000193) - h2 = Math.imul(h2 ^ ((v >>> 24) & 0xff), 0xff000193) - } - const mixStr = (s: string) => { - mix(s.length) - for (let i = 0; i < s.length; i++) mix(s.charCodeAt(i)) - } - const mixArr = (arr: Int32Array) => { - mix(arr.length) - for (let i = 0; i < arr.length; i++) mix(arr[i]!) - } - mix(codes.length) - for (const c of codes) { - mix(c.index) - mixStr(c.name) - mix(c.flags) - mix(c.length) - mix(c.params) - mix(c.locals) - mix(c.maxStack) - mixArr(c.code) - mixArr(c.captures) - mixArr(c.handlers) - mixArr(c.finallies) - mixArr(c.sites) - mix(c.consts.length) - for (const k of c.consts) { - if (typeof k === "string") { - mix(1) - mixStr(k) - } else if (typeof k === "number") { - mix(2) - mixStr(Object.is(k, -0) ? "-0" : String(k)) - } else if ("pattern" in k) { - mix(3) - mixStr(k.pattern) - mixStr(k.flags) - } else if ("cooked" in k) { - mix(4) - mix(k.nodeIndex) - for (const s of k.raw) mixStr(s) - } else if ("specifier" in k) { - mix(5) - mixStr(k.specifier) - if (k.imported !== undefined) mixStr(k.imported) - } else { - mix(6) - mixStr(k.type) - mixStr(k.message) - } - } - } - return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0") -} diff --git a/packages/codemode/src/language/compiler/compile.ts b/packages/codemode/src/language/compiler/compile.ts deleted file mode 100644 index 570f08bbb35..00000000000 --- a/packages/codemode/src/language/compiler/compile.ts +++ /dev/null @@ -1,1863 +0,0 @@ -import type { - ArrayExpression, - ArrayPattern, - ArrowFunctionExpression, - AssignmentExpression, - AwaitExpression, - BinaryExpression, - BlockStatement, - CallExpression, - CatchClause, - ClassExpression, - ConditionalExpression, - DoWhileStatement, - Expression, - ExpressionStatement, - ForInStatement, - ForOfStatement, - ForStatement, - FunctionExpression, - IfStatement, - ImportExpression, - LabeledStatement, - Literal, - LogicalExpression, - MemberExpression, - ModuleDeclaration, - NewExpression, - ObjectExpression, - ObjectPattern, - Pattern, - Program, - SpreadElement, - Statement, - SwitchStatement, - TaggedTemplateExpression, - TemplateLiteral, - TryStatement, - UnaryExpression, - UpdateExpression, - VariableDeclaration, - WhileStatement, - YieldExpression, -} from "acorn" -import { type AstNode, supportedSyntaxMessage } from "../runtime/model.js" -import { nodeId, type Source } from "../runtime/source.js" -import { Code, CodeBuilder, CodeSizeOverflow, hashOf, type Label } from "../code.js" -import { - BinOp, - CheckBaseKind, - CodeFlags, - CondKind, - type ErrorSite, - ImportKind, - IterContext, - Op, - type OpCode, - PutKind, - UnaryOp, -} from "../opcodes.js" -import { - analyzeScopes, - type Decl, - type ClassNode, - type FunctionInfo, - type ResolvedRef, - type Scope, - type ScopeAnalysis, - supportedClassMember, -} from "./scope.js" - -/** Each binary operator as the op and `a` operand that apply it. */ -const BinaryOps: Readonly> = { - "+": [Op.ADD, 0], - "-": [Op.SUB, 0], - "*": [Op.MUL, 0], - "<": [Op.LT, 0], - "<=": [Op.LE, 0], - ">": [Op.GT, 0], - ">=": [Op.GE, 0], - "===": [Op.SEQ, 0], - "!==": [Op.SNE, 0], - in: [Op.IN, 0], - instanceof: [Op.INSTANCEOF, 0], - "/": [Op.BINOP, BinOp.DIV], - "%": [Op.BINOP, BinOp.MOD], - "**": [Op.BINOP, BinOp.EXP], - "&": [Op.BINOP, BinOp.BAND], - "|": [Op.BINOP, BinOp.BOR], - "^": [Op.BINOP, BinOp.BXOR], - "<<": [Op.BINOP, BinOp.SHL], - ">>": [Op.BINOP, BinOp.SAR], - ">>>": [Op.BINOP, BinOp.SHR], - "==": [Op.BINOP, BinOp.EQ], - "!=": [Op.BINOP, BinOp.NE], -} - -const UnaryOps: Readonly> = { - "-": UnaryOp.NEG, - "+": UnaryOp.PLUS, - "~": UnaryOp.BNOT, - typeof: UnaryOp.TYPEOF, - void: UnaryOp.VOID, -} - -/** The jump that skips the right operand of `||`, `&&`, `??` and their assignments. */ -const logicalCond = (operator: string) => - operator.startsWith("||") - ? CondKind.TRUTHY_KEEP - : operator.startsWith("&&") - ? CondKind.FALSY_KEEP - : CondKind.NOT_NULLISH_KEEP - -/** NamedEvaluation: whether `node` is an anonymous function definition, which takes the name it is assigned to. */ -const isAnonymousFunction = ( - node: Expression, -): node is FunctionExpression | ArrowFunctionExpression | ClassExpression => - node.type === "ArrowFunctionExpression" || - ((node.type === "FunctionExpression" || node.type === "ClassExpression") && !node.id) - -type LoopEntry = { - readonly kind: "loop" - readonly labels: ReadonlySet - readonly breakLabel: Label - readonly continueLabel: Label - readonly entryDepth: number - readonly iterSlot: number - readonly iterAsync: boolean -} - -type ControlEntry = - | LoopEntry - | { - readonly kind: "switch" | "label" - readonly labels: ReadonlySet - readonly breakLabel: Label - readonly entryDepth: number - } - | { readonly kind: "iterator"; readonly itSlot: number; readonly entryDepth: number } - | { - readonly kind: "finally" - readonly tagSlot: number - readonly valSlot: number - readonly finallyLabel: Label - readonly entryDepth: number - readonly exits: Map< - string, - { readonly tag: number; readonly kind: "return" | "break" | "continue"; readonly target: ControlEntry | null } - > - } - -const idx = (node: AstNode | undefined | null): number => (node ? (nodeId(node)?.index ?? -1) : -1) - -/** Bump when the compiler emits different bytecode for the same source; it is part of the snapshot build id. */ -export const COMPILER_VERSION = 2 - -const compileCache = new Map>() -const MAX_CACHE_SIZE = 64 - -export type CompileOptions = { - readonly internal?: boolean - readonly forceExtra?: boolean - readonly noCache?: boolean -} - -/** - * Compiles a `Source` into an immutable `Code[]` array indexed by pre-order function index (`0` = program). - */ -export const compileSource = (source: Source, options?: CompileOptions): ReadonlyArray => { - const internal = options?.internal ?? false - const forceExtra = options?.forceExtra ?? false - const cacheable = !internal && !forceExtra && !options?.noCache && source.id === "main" - const cached = cacheable ? compileCache.get(source.code) : undefined - // Sites resolve against this Source's nodes. - if (cached !== undefined) return cached.map((code) => code.withSource(source)) - - const analysis = analyzeScopes(source, internal) - const preliminary = analysis.functions.map((fnInfo) => - compileFunction(source, { id: source.id, hash: "" }, analysis, fnInfo, forceExtra), - ) - const finalRef = { id: source.id, hash: hashOf(preliminary) } - const codes = preliminary.map((code) => new Code({ ...code, source: finalRef })) - - if (cacheable) { - if (compileCache.size >= MAX_CACHE_SIZE) compileCache.delete(compileCache.keys().next().value!) - compileCache.set(source.code, codes) - } - return codes -} - -const compileFunction = ( - source: Source, - sourceRef: Code["source"], - analysis: ScopeAnalysis, - fnInfo: FunctionInfo, - forceExtra: boolean, -): Code => { - try { - return compileFunctionBody(source, sourceRef, analysis, fnInfo, forceExtra, false) - } catch (err) { - if (err instanceof CodeSizeOverflow) { - return compileFunctionBody(source, sourceRef, analysis, fnInfo, forceExtra, true) - } - throw err - } -} - -const compileFunctionBody = ( - source: Source, - sourceRef: Code["source"], - analysis: ScopeAnalysis, - fnInfo: FunctionInfo, - forceExtra: boolean, - wideJumps: boolean, -): Code => { - const isProgram = fnInfo.index === 0 - const internal = (fnInfo.flags & CodeFlags.INTERNAL) !== 0 - const builder = new CodeBuilder( - sourceRef, - source, - fnInfo.index, - fnInfo.name, - fnInfo.flags, - fnInfo.length, - fnInfo.params.length, - fnInfo.locals, - [...fnInfo.localNames], - Int32Array.from(fnInfo.upvalues.flatMap((u) => [u.from, u.index])), - fnInfo.upvalues.map((u) => u.decl.name), - ) - builder.forceExtra = forceExtra - builder.wideJumps = wideJumps - - const controlStack: Array = [] - let pendingLabels: Set | undefined - let retSlot = -1 - - const allocSlot = (name: string): number => { - builder.localNames.push(name) - return builder.locals++ - } - - const emitThrowError = (site: ErrorSite, node: AstNode): void => { - builder.emit(Op.THROW_ERROR, 0, builder.constant(site), idx(node), 0) - builder.unreachable() - } - - const emitUnsupported = (kindName: string, node: AstNode): void => - emitThrowError( - { - type: "SyntaxError", - message: unsupportedFeatureMessages[kindName] ?? `Syntax '${kindName}' is not supported. ${supportedSyntaxMessage}`, - kind: "UnsupportedSyntax", - suggestions: [supportedSyntaxMessage], - }, - node, - ) - - // `super.x` in a class method: pushes its home object and `this`. False (after the error) outside class methods. - const emitSuperBase = (node: MemberExpression): boolean => { - const refs = analysis.superRefs.get(node.object) - if (!refs) return !unsupportedSuper(node) - emitLoadRef(refs.home, node.object) - emitLoadRef(refs.self, node.object) - return true - } - - // Pushes [home, this(, key)] and reads super.x above them; returns how many base values stay for emitPutSuper. - const emitSuperRead = (node: MemberExpression): number => { - emitSuperBase(node) - if (node.computed) { - compileExpression(node.property as Expression) - builder.emit(Op.TO_KEY, 0, 0, idx(node.property), 0) - } - const n = node.computed ? 3 : 2 - for (let i = 0; i < n; i++) builder.emit(Op.PICK, n - 1, 0, idx(node), 1) - const k = node.computed ? 0 : builder.constant(propertyName(node)) - builder.emit(Op.GET_SUPER, node.computed ? 2 : 0, k, idx(node), node.computed ? -2 : -1) - return n - } - - const emitPutSuper = (node: MemberExpression): void => { - const k = node.computed ? 0 : builder.constant(propertyName(node)) - builder.emit(Op.PUT_SUPER, node.computed ? 2 : 0, k, idx(node), node.computed ? -3 : -2) - } - - // A derived constructor's `this` binding: SUPER_BIND writes it in place. - const thisOperand = (): [number, number] => [fnInfo.thisDecl!.captured ? 1 : 0, fnInfo.thisDecl!.slot] - - // `super.x` parses inside object methods but is not supported. Code after the error is unreachable, so it emits nothing. - // `construct` names the unsupported use when `super` itself is in a class method. - const unsupportedSuper = (node: MemberExpression, construct?: string): boolean => { - if (node.object.type !== "Super") return false - if (construct && analysis.superRefs.has(node.object)) emitUnsupportedSuper(`${construct} is not supported.`, node.object) - else emitUnsupported("Super", node.object) - return true - } - - const emitUnsupportedSuper = (message: string, node: AstNode): void => - emitThrowError({ type: "SyntaxError", message, kind: "UnsupportedSyntax", suggestions: [supportedSyntaxMessage] }, node) - - const putKind = (decl: Decl, isInit: boolean) => - isInit ? PutKind.INIT : decl.mutable ? PutKind.ASSIGN : PutKind.CONST - - const emitLoadDecl = (decl: Decl, node?: AstNode) => - builder.emit(decl.captured ? Op.GET_CELL : Op.GET_LOCAL, 0, decl.slot, idx(node), 1) - - const emitStoreDecl = (decl: Decl, isInit: boolean, node?: AstNode) => - builder.emit(decl.captured ? Op.PUT_CELL : Op.PUT_LOCAL, putKind(decl, isInit), decl.slot, idx(node), -1) - - const emitLoadRef = (ref: ResolvedRef, node: AstNode, isTypeof = false): void => { - if (ref.kind === "local") emitLoadDecl(ref.decl, node) - else if (ref.kind === "upval") builder.emit(Op.GET_UPVAL, 0, ref.upvalIndex, idx(node), 1) - else if (internal && !isTypeof) { - // Internal code can't shadow `undefined`. - if (ref.name === "undefined") builder.emit(Op.PUSH_UNDEF, 0, 0, idx(node), 1) - else builder.emit(Op.GET_INTRINSIC, 0, builder.constant(ref.name), idx(node), 1) - } else builder.emit(Op.GET_GLOBAL, isTypeof ? 1 : 0, builder.constant(ref.name), idx(node), 1) - } - - const emitStoreRef = (ref: ResolvedRef, isInit: boolean, node: AstNode): void => { - if (ref.kind === "local") emitStoreDecl(ref.decl, isInit, node) - else if (ref.kind === "upval") builder.emit(Op.PUT_UPVAL, putKind(ref.decl, isInit), ref.upvalIndex, idx(node), -1) - // Global assignment: checks if global exists (`Cannot assign to constant`) or unknown (`Unknown identifier`) - else builder.emit(Op.GET_GLOBAL, 2, builder.constant(ref.name), idx(node), -1) - } - - const emitScopePrologue = (scope: Scope, resetUncapturedLexicals: boolean): void => { - for (const decl of scope.decls.values()) { - if (["this", "arguments", "param", "self", "home", "newTarget"].includes(decl.kind)) continue - if (decl.captured) builder.emit(Op.NEW_CELL, 0, decl.slot) - else if (resetUncapturedLexicals && (decl.kind === "let" || decl.kind === "const")) { - builder.emit(Op.HOLE_LOCAL, 0, decl.slot) - } - } - for (const decl of scope.decls.values()) { - if (decl.kind !== "var") continue - if (decl.copyFromParam !== undefined) emitLoadDecl(decl.copyFromParam) - else builder.emit(Op.PUSH_UNDEF, 0, 0, -1, 1) - emitStoreDecl(decl, true) - } - emitHoistedFunctions(scope) - } - - const emitHoistedFunctions = (scope: Scope): void => { - for (const hoisted of scope.hoistedFunctions) { - if (hoisted.fnIndex < 0) continue - builder.emit(Op.CLOSURE, 0, hoisted.fnIndex, idx(hoisted.node), 1) - emitStoreDecl(hoisted.decl, true, hoisted.node) - } - } - - const emitImports = (stmts: ReadonlyArray): void => { - for (const stmt of stmts) { - if (stmt.type !== "ImportDeclaration") continue - const specifier = String(stmt.source.value) - if (stmt.specifiers.length === 0) { - builder.emit(Op.IMPORT, ImportKind.SIDE_EFFECT, builder.constant({ specifier }), idx(stmt), 0) - } - for (const spec of stmt.specifiers) { - if (spec.type === "ImportSpecifier") { - const imported = spec.imported.type === "Identifier" ? spec.imported.name : String(spec.imported.value) - builder.emit(Op.IMPORT, ImportKind.NAMED, builder.constant({ specifier, imported }), idx(spec), 1) - } else { - const kind = spec.type === "ImportDefaultSpecifier" ? ImportKind.DEFAULT : ImportKind.NAMESPACE - builder.emit(Op.IMPORT, kind, builder.constant({ specifier }), idx(spec), 1) - } - emitStoreDecl(fnInfo.bodyScope.decls.get(spec.local.name)!, true, spec) - } - } - } - - // --- Iteration (fast paths inline, a custom iterator's calls out of line) --- - - // Opens an iterator over the value on top into `itSlot`. The returned function emits the out-of-line path that - // calls a custom `[Symbol.iterator]` method. - const emitIterOpen = (context: number, itSlot: number, base: number, node: AstNode) => { - const slow = builder.newLabel(base + 2) - const join = builder.newLabel(base + 1) - builder.emitJump(Op.ITER_OPEN, context, slow, idx(node), 0, 1) - builder.emitJump(Op.JUMP, 0, slow, idx(node), 0, null) - builder.mark(join) - builder.emit(Op.PUT_LOCAL, PutKind.INIT, itSlot, idx(node), -1) - return () => { - builder.mark(slow) - builder.emit(Op.CALL, 0, 0, idx(node), -1) - builder.emit(Op.ITER_INIT, context, 0, idx(node), 0) - builder.emitJump(Op.JUMP, 0, join, idx(node), 0, null) - } - } - - // Pushes the next value, or jumps to `done`. The returned function emits the out-of-line path that calls a custom - // `next` method. - const emitIterStep = (itSlot: number, base: number, done: Label, node: AstNode, isAwait = false) => { - const got = builder.newLabel(base + 1) - const slow = builder.newLabel(base + 2) - builder.emitJump(Op.ITER_STEP, itSlot, done, idx(node), 0, 2) - builder.emitJump(Op.JUMP, 0, slow, idx(node), 0, null) - builder.mark(got) - return () => { - builder.mark(slow) - builder.emit(Op.CALL, 0, 0, idx(node), -1) - if (isAwait) builder.emit(Op.AWAIT, 0, 0, idx(node), 0) - builder.emitJump(Op.ITER_RESULT, itSlot, done, idx(node), -1, 0) - builder.emitJump(Op.JUMP, 0, got, idx(node), 0, null) - } - } - - // Appends what is left of the iterator to the array on top (at `base`). `beforeSlow` emits other out-of-line code. - const emitAppendRest = (itSlot: number, base: number, node: AstNode, beforeSlow?: () => void): void => { - const loop = builder.newLabel(base) - const done = builder.newLabel(base) - builder.emitJump(Op.ITER_APPEND_ALL, itSlot, loop, idx(node), 0, 0) - builder.emitJump(Op.JUMP, 0, done, idx(node), 0, 0) - builder.mark(loop) - const slow = emitIterStep(itSlot, base, done, node) - builder.emit(Op.ARRAY_APPEND, 0, 0, idx(node), -1) - builder.emitJump(Op.JUMP, 0, loop, idx(node), 0, 0) - beforeSlow?.() - slow() - builder.mark(done) - } - - const emitIteratorCloseNormal = (itSlot: number, iterAsync: boolean, node: AstNode): void => { - const skipLabel = builder.newLabel(builder.depth) - builder.emitJump(Op.ITER_CLOSE, itSlot, skipLabel, idx(node), 0, 2) - builder.emit(Op.CALL, 0, 0, idx(node), -1) - if (iterAsync) builder.emit(Op.AWAIT, 0, 0, idx(node), 0) - builder.emit(Op.ITER_INIT, IterContext.CHECK_OBJECT, 0, idx(node), 0) - builder.emit(Op.POP, 0, 0, idx(node), -1) - builder.mark(skipLabel) - } - - // The handler for a throw out of `ranges`: closes the iterator, ignoring an error from closing it, and rethrows. - const emitCloseOnThrow = ( - ranges: ReadonlyArray, - itSlot: number, - errSlot: number, - entryDepth: number, - node: AstNode, - isAwait = false, - ): void => { - const catchLabel = builder.newLabel(entryDepth + 1) - builder.mark(catchLabel) - for (const [start, end] of ranges) builder.addHandler(start, end, catchLabel.pc, entryDepth) - builder.emit(Op.PUT_LOCAL, PutKind.INIT, errSlot, idx(node), -1) - const rethrowLabel = builder.newLabel(entryDepth) - const swallowLabel = builder.newLabel(entryDepth + 1) - const closeStart = builder.pc - builder.emitJump(Op.ITER_CLOSE, itSlot, rethrowLabel, idx(node), 0, 2) - builder.emit(Op.CALL, 0, 0, idx(node), -1) - if (isAwait) builder.emit(Op.AWAIT, 0, 0, idx(node), 0) - builder.emit(Op.POP, 0, 0, idx(node), -1) - const closeEnd = builder.pc - builder.mark(rethrowLabel) - builder.emit(Op.GET_LOCAL, 0, errSlot, idx(node), 1) - builder.emit(Op.THROW, 0, 0, idx(node), -1) - builder.mark(swallowLabel) - builder.emit(Op.POP, 0, 0, idx(node), -1) - builder.emitJump(Op.JUMP, 0, rethrowLabel, idx(node), 0, null) - builder.addHandler(closeStart, closeEnd, swallowLabel.pc, entryDepth) - } - - // --- Exit Plan (return, break, continue across iterators and finally blocks; C1, C3, C4) --- - const findExitTarget = (kind: "break" | "continue", label: string | undefined): ControlEntry | null => { - for (let i = controlStack.length - 1; i >= 0; i--) { - const e = controlStack[i]! - if (e.kind === "finally" || e.kind === "iterator") continue - if (kind === "break" && (label !== undefined ? e.labels.has(label) : e.kind === "loop" || e.kind === "switch")) - return e - if (kind === "continue" && e.kind === "loop" && (label === undefined || e.labels.has(label))) return e - } - return null - } - - const exitPlan = (kind: "return" | "break" | "continue", target: ControlEntry | null, node: AstNode): void => { - if (builder.depth < 0) return - const stop = target ? controlStack.indexOf(target) : -1 - const crossing = controlStack.slice(stop + 1).reverse() - const needsRet = - kind === "return" && - crossing.some((e) => e.kind === "finally" || e.kind === "iterator" || (e.kind === "loop" && e.iterSlot >= 0)) - - if (kind === "return" && !needsRet) { - // C1: RETURN discards the frame directly when nothing needs closing or routing - builder.emit(Op.RETURN, 0, 0, idx(node), -1) - builder.unreachable() - return - } - - if (needsRet) { - if (retSlot === -1) retSlot = allocSlot("%ret") - builder.emit(Op.PUT_LOCAL, PutKind.INIT, retSlot, idx(node), -1) - } - - const popTo = (d: number) => { - const drop = builder.depth - d - if (drop > 0) builder.emit(Op.POPN, 0, drop, idx(node), -drop) - } - - for (const e of crossing) { - popTo(e.entryDepth) - if (e.kind === "iterator") emitIteratorCloseNormal(e.itSlot, false, node) - else if (e.kind === "loop" && e.iterSlot >= 0) emitIteratorCloseNormal(e.iterSlot, e.iterAsync, node) - else if (e.kind === "finally") { - const key = `${kind}:${target ? stop : ""}` - let exit = e.exits.get(key) - if (!exit) { - exit = { tag: e.exits.size + 2, kind, target } - e.exits.set(key, exit) - } - if (kind === "return") { - builder.emit(Op.GET_LOCAL, 0, retSlot, idx(node), 1) - builder.emit(Op.PUT_LOCAL, PutKind.INIT, e.valSlot, idx(node), -1) - } - builder.emitNumber(exit.tag, idx(node)) - builder.emit(Op.PUT_LOCAL, PutKind.INIT, e.tagSlot, idx(node), -1) - builder.emitJump(Op.JUMP, 0, e.finallyLabel, idx(node), 0, null) - return - } - } - - if (kind === "return") { - popTo(0) - builder.emit(Op.GET_LOCAL, 0, retSlot, idx(node), 1) - builder.emit(Op.RETURN, 0, 0, idx(node), -1) - builder.unreachable() - return - } - - if (target && target.kind !== "iterator" && target.kind !== "finally") { - popTo(target.entryDepth) - if (kind === "break" && target.kind === "loop" && target.iterSlot >= 0) { - emitIteratorCloseNormal(target.iterSlot, target.iterAsync, node) - } - const dst = kind === "break" ? target.breakLabel : (target as LoopEntry).continueLabel - builder.emitJump(Op.JUMP, 0, dst, idx(node), 0, null) - return - } - - emitThrowError({ type: "TypeError", message: `Unexpected '${kind}' outside of a loop.` }, node) - } - - // --- Pattern Compilation (value to bind is on top of stack: depth -> depth - 1) --- - const compilePattern = (pattern: Pattern, isDecl: boolean, isInit: boolean, contextNode: AstNode): void => { - switch (pattern.type) { - case "Identifier": - emitStoreRef(analysis.refs.get(pattern)!, isInit, isDecl ? contextNode : pattern) - return - case "MemberExpression": { - // Stack has [value]. Evaluate target object and key, then write [value]. - const valSlot = allocSlot("%mval") - builder.emit(Op.PUT_LOCAL, PutKind.INIT, valSlot, idx(pattern), -1) - if (unsupportedSuper(pattern, "Destructuring into super.x")) return - compileExpression(pattern.object as Expression) - if (pattern.computed) { - compileExpression(pattern.property as Expression) - emitWritableKey(pattern) - builder.emit(Op.GET_LOCAL, 0, valSlot, idx(pattern), 1) - builder.emit(Op.PUT_ELEM, 0, 0, idx(pattern), -2) - } else { - const k = builder.constant(propertyName(pattern)) - builder.emit(Op.CHECK_BASE, CheckBaseKind.WRITE_PROP, k, idx(pattern), 0) - builder.emit(Op.GET_LOCAL, 0, valSlot, idx(pattern), 1) - builder.emit(Op.PUT_PROP, 0, k, idx(pattern), -1) - } - builder.emit(Op.POP, 0, 0, idx(pattern), -1) - return - } - case "AssignmentPattern": { - const definedLabel = builder.newLabel(builder.depth) - builder.emitJump(Op.JUMP_COND, CondKind.DEFINED, definedLabel, idx(pattern), 0, -1) - if (pattern.left.type === "Identifier") compileNamedExpression(pattern.right, pattern.left.name) - else compileExpression(pattern.right) - builder.mark(definedLabel) - compilePattern(pattern.left, isDecl, isInit, contextNode) - return - } - case "ObjectPattern": - return compileObjectPattern(pattern, isDecl, isInit) - case "ArrayPattern": - return compileArrayPattern(pattern, isDecl, isInit) - default: - emitThrowError({ type: "TypeError", message: `Unsupported binding pattern '${pattern.type}'.` }, pattern) - } - } - - // A computed member's key as a write target: `[o, k] -> [o, key]`. - const emitWritableKey = (node: MemberExpression): void => { - builder.emit(Op.CHECK_BASE, CheckBaseKind.READ, 0, idx(node), 0) - builder.emit(Op.TO_KEY, 0, 0, idx(node.property), 0) - builder.emit(Op.CHECK_BASE, CheckBaseKind.WRITE_ELEM, 0, idx(node), 0) - } - - const compileObjectPattern = (pattern: ObjectPattern, isDecl: boolean, isInit: boolean): void => { - builder.emit(Op.CHECK_BASE, CheckBaseKind.DESTRUCTURE, 0, idx(pattern), 0) - const props = pattern.properties - const lastProp = props.at(-1) - if (lastProp === undefined) { - builder.emit(Op.POP, 0, 0, idx(pattern), -1) - return - } - if (lastProp.type !== "RestElement") { - props.forEach((prop, i) => { - if (prop.type === "RestElement") return - if (i < props.length - 1) builder.emit(Op.DUP, 0, 0, idx(prop), 1) - if (prop.computed) { - compileExpression(prop.key as Expression) - builder.emit(Op.TO_KEY, 0, 0, idx(prop.key), 0) - builder.emit(Op.GET_ELEM, 2, 0, idx(prop), -1) - } else builder.emit(Op.GET_PROP, 2, builder.constant(keyName(prop.key)), idx(prop), 0) - compilePattern(prop.value, isDecl, isInit, prop) - }) - return - } - - // ObjectPattern with RestElement at the end: keep `[src, k1, ..., kn]` on the stack for `COPY_REST n` - const count = props.length - 1 - props.slice(0, count).forEach((prop, i) => { - if (prop.type === "RestElement") return - if (prop.computed) { - compileExpression(prop.key as Expression) - builder.emit(Op.TO_KEY, 0, 0, idx(prop.key), 0) - } else builder.emitString(keyName(prop.key), idx(prop.key)) - // Stack is `[src, k1, ..., k_{i+1}]`. Pick `src` (at offset i + 1) and `k_{i+1}` (at offset 1 after picking src). - builder.emit(Op.PICK, i + 1, 0, idx(prop), 1) - builder.emit(Op.PICK, 1, 0, idx(prop), 1) - builder.emit(Op.GET_ELEM, 2, 0, idx(prop), -1) - compilePattern(prop.value, isDecl, isInit, prop) - }) - builder.emit(Op.COPY_REST, 0, count, idx(lastProp), -count) - compilePattern(lastProp.argument, isDecl, isInit, lastProp) - } - - const compileArrayPattern = (pattern: ArrayPattern, isDecl: boolean, isInit: boolean): void => { - const itSlot = allocSlot("%it") - const errSlot = allocSlot("%e") - const entryDepth = builder.depth - 1 - const openSlow = emitIterOpen(IterContext.DESTRUCTURE, itSlot, entryDepth, pattern) - controlStack.push({ kind: "iterator", itSlot, entryDepth }) - const protectedRanges: Array = [] - const bind = (target: Pattern, node: AstNode) => { - const start = builder.pc - compilePattern(target, isDecl, isInit, node) - protectedRanges.push([start, builder.pc]) - } - - for (const el of pattern.elements) { - if (el?.type === "RestElement") { - // Drain remaining elements into a new array, then bind - builder.emit(Op.NEW_ARRAY, 0, 0, idx(el), 1) - emitAppendRest(itSlot, entryDepth + 1, el) - bind(el.argument, el) - break - } - const node = el ?? pattern - const doneLabel = builder.newLabel(entryDepth) - const afterLabel = builder.newLabel(entryDepth) - const slow = emitIterStep(itSlot, entryDepth, doneLabel, node) - // Elision: step iterator and discard value - if (el === null) builder.emit(Op.POP, 0, 0, idx(pattern), -1) - else bind(el, el) - builder.emitJump(Op.JUMP, 0, afterLabel, idx(node), 0, 0) - slow() - builder.mark(doneLabel) - if (el !== null) { - builder.emit(Op.PUSH_UNDEF, 0, 0, idx(el), 1) - bind(el, el) - } - builder.mark(afterLabel) - } - - controlStack.pop() - emitIteratorCloseNormal(itSlot, false, pattern) - const endLabel = builder.newLabel(entryDepth) - builder.emitJump(Op.JUMP, 0, endLabel, idx(pattern), 0, 0) - openSlow() - emitCloseOnThrow(protectedRanges, itSlot, errSlot, entryDepth, pattern) - builder.mark(endLabel) - } - - // --- Statements --- - const compileStatement = (stmt: Statement | ModuleDeclaration): void => { - const labels = pendingLabels - pendingLabels = undefined - if (builder.depth < 0) return - const compile = statements[stmt.type] as ((node: typeof stmt, labels?: Set) => void) | undefined - if (compile) compile(stmt, labels) - else emitUnsupported(stmt.type, stmt) - } - - const withStatementLabels = (labels: Set | undefined, body: () => void): void => { - if (!labels || labels.size === 0) return body() - const breakLabel = builder.newLabel(builder.depth) - controlStack.push({ kind: "label", labels, breakLabel, entryDepth: builder.depth }) - body() - controlStack.pop() - builder.mark(breakLabel) - } - - const pushLoop = ( - labels: Set | undefined, - breakLabel: Label, - continueLabel: Label, - entryDepth: number, - iterSlot = -1, - iterAsync = false, - ) => - controlStack.push({ - kind: "loop", - labels: labels ?? new Set(), - breakLabel, - continueLabel, - entryDepth, - iterSlot, - iterAsync, - }) - - const compileVariableDeclaration = (node: VariableDeclaration): void => { - const isVar = node.kind === "var" - for (const decl of node.declarations) { - if (isVar && !decl.init && decl.id.type === "Identifier") continue - if (!decl.init) builder.emit(Op.PUSH_UNDEF, 0, 0, idx(decl), 1) - else if (decl.id.type === "Identifier") compileNamedExpression(decl.init, decl.id.name) - else compileExpression(decl.init) - compilePattern(decl.id, !isVar, !isVar, decl) - } - } - - // Leaves the class constructor on the stack. - // `name` is an anonymous class's NamedEvaluation name, set before its static fields run. - const compileClass = (node: ClassNode, name?: string): void => { - const unsupported = node.body.body.find((member) => !supportedClassMember(member)) - if (unsupported) return emitUnsupported(classSyntaxName(unsupported), unsupported) - const scope = analysis.scopeOfNode.get(node)! - emitScopePrologue(scope, true) - if (node.superClass) compileExpression(node.superClass) - const ctor = analysis.classConstructors.get(node)! - builder.emit(Op.CLOSURE, 0, analysis.nodeToFunction.get(ctor)!.index, idx(node), 1) - builder.emit(Op.CLASS, node.superClass ? 1 : 0, 0, idx(node.superClass ?? node), node.superClass ? 0 : 1) - // Member keys are evaluated once, in order; a computed field's key is kept in its hidden binding. - for (const member of node.body.body) { - if (member.type === "PropertyDefinition") { - const key = analysis.fieldKeys.get(member) - if (!key) continue - compileExpression(member.key as Expression) - builder.emit(Op.TO_KEY, 0, 0, idx(member.key), 0) - emitStoreDecl(scope.decls.get(key.name)!, true, member) - continue - } - if (member.type !== "MethodDefinition" || member.kind === "constructor") continue - if (member.computed) { - compileExpression(member.key as Expression) - builder.emit(Op.TO_KEY, 0, 0, idx(member.key), 0) - } - const kind = member.kind === "get" ? 4 : member.kind === "set" ? 8 : 0 - const flags = (member.static ? 1 : 0) | (member.computed ? 2 : 0) | kind - builder.emit(Op.CLOSURE, 0, analysis.nodeToFunction.get(member.value)!.index, idx(member), 1) - builder.emit( - Op.DEFINE_METHOD, - flags, - member.computed ? 0 : builder.constant(keyName(member.key)), - idx(member), - member.computed ? -2 : -1, - ) - } - const fieldInits = analysis.classFieldInits.get(node) - if (fieldInits?.instance) { - builder.emit(Op.CLOSURE, 0, analysis.nodeToFunction.get(fieldInits.instance)!.index, idx(node), 1) - builder.emit(Op.SET_FIELDS, 0, 0, idx(node), -1) - } - builder.emit(Op.POP, 0, 0, idx(node), -1) - if (name !== undefined) builder.emit(Op.SET_NAME, 0, builder.constant(name), idx(node), 0) - if (node.id) { - builder.emit(Op.DUP, 0, 0, idx(node), 1) - emitStoreDecl(scope.decls.get(node.id.name)!, true, node) - } - if (!fieldInits?.static) return - builder.emit(Op.DUP, 0, 0, idx(node), 1) - builder.emit(Op.CLOSURE, 0, analysis.nodeToFunction.get(fieldInits.static)!.index, idx(node), 1) - builder.emit(Op.INIT_FIELDS, 1, 0, idx(node), -1) - builder.emit(Op.POP, 0, 0, idx(node), -1) - } - - const compileBlockStatement = (node: BlockStatement, labels?: Set): void => - withStatementLabels(labels, () => { - const scope = analysis.scopeOfNode.get(node) - if (scope && (scope.decls.size > 0 || scope.hoistedFunctions.length > 0)) emitScopePrologue(scope, true) - for (const s of node.body) compileStatement(s) - }) - - const compileIfStatement = (node: IfStatement, labels?: Set): void => - withStatementLabels(labels, () => { - const elseLabel = builder.newLabel(builder.depth) - const endLabel = builder.newLabel(builder.depth) - compileExpression(node.test) - builder.emitJump(Op.JUMP_IF_FALSE, 0, node.alternate ? elseLabel : endLabel, idx(node), -1, -1) - compileStatement(node.consequent) - if (node.alternate) { - builder.emitJump(Op.JUMP, 0, endLabel, idx(node), 0, null) - builder.mark(elseLabel) - compileStatement(node.alternate) - } - builder.mark(endLabel) - }) - - const compileWhileStatement = (node: WhileStatement, labels?: Set): void => { - const entryDepth = builder.depth - const testLabel = builder.newLabel(entryDepth) - const continueLabel = builder.newLabel(entryDepth) - const breakLabel = builder.newLabel(entryDepth) - builder.mark(testLabel) - compileExpression(node.test) - builder.emitJump(Op.JUMP_IF_FALSE, 0, breakLabel, idx(node), -1, -1) - pushLoop(labels, breakLabel, continueLabel, entryDepth) - compileStatement(node.body) - controlStack.pop() - builder.mark(continueLabel) - builder.emitJump(Op.LOOP, 0, testLabel, idx(node), 0, null) - builder.mark(breakLabel) - } - - const compileDoWhileStatement = (node: DoWhileStatement, labels?: Set): void => { - const entryDepth = builder.depth - const bodyLabel = builder.newLabel(entryDepth) - const continueLabel = builder.newLabel(entryDepth) - const breakLabel = builder.newLabel(entryDepth) - builder.mark(bodyLabel) - pushLoop(labels, breakLabel, continueLabel, entryDepth) - compileStatement(node.body) - controlStack.pop() - builder.mark(continueLabel) - compileExpression(node.test) - builder.emitJump(Op.JUMP_IF_FALSE, 0, breakLabel, idx(node), -1, -1) - builder.emitJump(Op.LOOP, 0, bodyLabel, idx(node), 0, null) - builder.mark(breakLabel) - } - - const compileForStatement = (node: ForStatement, labels?: Set): void => { - const entryDepth = builder.depth - const forScope = analysis.scopeOfNode.get(node)! - emitScopePrologue(forScope, true) - if (node.init?.type === "VariableDeclaration") compileVariableDeclaration(node.init) - else if (node.init) compileEffect(node.init) - // Each iteration gets fresh cells for the bindings its closures capture. - const copyCells = () => { - for (const d of forScope.decls.values()) if (d.captured) builder.emit(Op.COPY_CELL, 0, d.slot, idx(node), 0) - } - copyCells() - const testLabel = builder.newLabel(entryDepth) - const continueLabel = builder.newLabel(entryDepth) - const breakLabel = builder.newLabel(entryDepth) - builder.mark(testLabel) - if (node.test) { - compileExpression(node.test) - builder.emitJump(Op.JUMP_IF_FALSE, 0, breakLabel, idx(node), -1, -1) - } - pushLoop(labels, breakLabel, continueLabel, entryDepth) - compileStatement(node.body) - controlStack.pop() - builder.mark(continueLabel) - copyCells() - if (node.update) compileEffect(node.update) - builder.emitJump(Op.LOOP, 0, testLabel, idx(node), 0, null) - builder.mark(breakLabel) - } - - // The binding a for...in or for...of assigns each value to, inside the loop's own scope when it is lexical. - const compileLoopBinding = (node: ForInStatement | ForOfStatement): void => { - if (node.left.type !== "VariableDeclaration") return compilePattern(node.left, false, false, node.left) - const lexical = node.left.kind !== "var" - if (lexical) emitScopePrologue(analysis.scopeOfNode.get(node)!, true) - compilePattern(node.left.declarations[0]!.id, lexical, lexical, node.left) - } - - const loopScopePrologue = (node: ForInStatement | ForOfStatement): void => { - if (node.left.type === "VariableDeclaration" && node.left.kind !== "var") { - emitScopePrologue(analysis.scopeOfNode.get(node)!, true) - } - } - - const compileForInStatement = (node: ForInStatement, labels?: Set): void => { - const entryDepth = builder.depth - loopScopePrologue(node) - compileExpression(node.right) - const itSlot = allocSlot("%it") - builder.emit(Op.FOR_IN, 0, 0, idx(node.right), 0) - builder.emit(Op.PUT_LOCAL, PutKind.INIT, itSlot, idx(node), -1) - const stepLabel = builder.newLabel(entryDepth) - const continueLabel = builder.newLabel(entryDepth) - const breakLabel = builder.newLabel(entryDepth) - builder.mark(stepLabel) - const stepSlow = emitIterStep(itSlot, entryDepth, breakLabel, node) - compileLoopBinding(node) - pushLoop(labels, breakLabel, continueLabel, entryDepth) - compileStatement(node.body) - controlStack.pop() - builder.mark(continueLabel) - builder.emitJump(Op.LOOP, 0, stepLabel, idx(node), 0, null) - stepSlow() - builder.mark(breakLabel) - } - - const compileForOfStatement = (node: ForOfStatement, labels?: Set): void => { - const isAwait = node.await - const entryDepth = builder.depth - loopScopePrologue(node) - compileExpression(node.right) - const itSlot = allocSlot("%it") - const errSlot = allocSlot("%e") - const openSlow = emitIterOpen(isAwait ? IterContext.FOR_AWAIT : IterContext.FOR_OF, itSlot, entryDepth, node) - const stepLabel = builder.newLabel(entryDepth) - const continueLabel = builder.newLabel(entryDepth) - const breakLabel = builder.newLabel(entryDepth) - builder.mark(stepLabel) - const stepSlow = emitIterStep(itSlot, entryDepth, breakLabel, node, isAwait) - // C4: iterSlot belongs to the loop entry itself (`break` and `return` close it, `continue` does not) - pushLoop(labels, breakLabel, continueLabel, entryDepth, itSlot, isAwait) - const bodyStart = builder.pc - compileLoopBinding(node) - compileStatement(node.body) - controlStack.pop() - builder.mark(continueLabel) - builder.emitJump(Op.LOOP, 0, stepLabel, idx(node), 0, null) - const bodyEnd = builder.pc - openSlow() - stepSlow() - emitCloseOnThrow([[bodyStart, bodyEnd]], itSlot, errSlot, entryDepth, node, isAwait) - builder.mark(breakLabel) - } - - const compileSwitchStatement = (node: SwitchStatement, labels?: Set): void => { - const entryDepth = builder.depth - compileExpression(node.discriminant) - const discSlot = allocSlot("%disc") - builder.emit(Op.PUT_LOCAL, PutKind.INIT, discSlot, idx(node), -1) - emitScopePrologue(analysis.scopeOfNode.get(node)!, true) - const breakLabel = builder.newLabel(entryDepth) - const caseLabels = node.cases.map(() => builder.newLabel(entryDepth)) - let defaultLabel: Label | undefined - node.cases.forEach((clause, i) => { - if (!clause.test) { - defaultLabel = caseLabels[i] - return - } - builder.emit(Op.GET_LOCAL, 0, discSlot, idx(clause), 1) - compileExpression(clause.test) - builder.emit(Op.SEQ, 0, 0, idx(clause), -1) - builder.emitJump(Op.JUMP_IF_TRUE, 0, caseLabels[i]!, idx(clause), -1, -1) - }) - builder.emitJump(Op.JUMP, 0, defaultLabel ?? breakLabel, idx(node), 0, 0) - controlStack.push({ kind: "switch", labels: labels ?? new Set(), breakLabel, entryDepth }) - node.cases.forEach((clause, i) => { - builder.mark(caseLabels[i]!) - for (const s of clause.consequent) compileStatement(s) - }) - controlStack.pop() - builder.mark(breakLabel) - } - - const compileLabeledStatement = (node: LabeledStatement, existingLabels?: Set): void => { - const labels = existingLabels ?? new Set() - let cur: Statement = node - for (; cur.type === "LabeledStatement"; cur = cur.body) labels.add(cur.label.name) - pendingLabels = labels - compileStatement(cur) - } - - const compileTryCatch = (block: BlockStatement, handler: CatchClause, parentNode: AstNode): void => { - const entryDepth = builder.depth - const catchLabel = builder.newLabel(entryDepth + 1) - const endLabel = builder.newLabel(entryDepth) - const tryStart = builder.pc - compileBlockStatement(block) - const tryEnd = builder.pc - builder.emitJump(Op.JUMP, 0, endLabel, idx(parentNode), 0, null) - builder.mark(catchLabel) - builder.addHandler(tryStart, tryEnd, catchLabel.pc, entryDepth) - emitScopePrologue(analysis.scopeOfNode.get(handler)!, true) - if (handler.param) compilePattern(handler.param, true, true, handler) - else builder.emit(Op.POP, 0, 0, idx(handler), -1) - compileBlockStatement(handler.body) - builder.mark(endLabel) - } - - const compileTryStatement = (node: TryStatement, labels?: Set): void => - withStatementLabels(labels, () => { - if (!node.finalizer) return compileTryCatch(node.block, node.handler!, node) - - // try/[catch]/finally with static tag routing (§3.5, C3) - const entryDepth = builder.depth - const level = builder.reserveFinally() - const tagSlot = allocSlot(`%ftag${level}`) - const valSlot = allocSlot(`%fval${level}`) - const finallyLabel = builder.newLabel(entryDepth) - const afterFinallyLabel = builder.newLabel(entryDepth) - const finallyThrowLabel = builder.newLabel(entryDepth + 1) - const finallyEntry = { kind: "finally", tagSlot, valSlot, finallyLabel, entryDepth, exits: new Map() } as const - - controlStack.push(finallyEntry) - const tryStart = builder.pc - if (node.handler) compileTryCatch(node.block, node.handler, node) - else compileBlockStatement(node.block) - const tryEnd = builder.pc - builder.emitNumber(0, idx(node)) - builder.emit(Op.PUT_LOCAL, PutKind.INIT, tagSlot, idx(node), -1) - builder.emitJump(Op.JUMP, 0, finallyLabel, idx(node), 0, null) - - // Throw out of try/catch -> tag = 1, val = e, fall into finally - builder.mark(finallyThrowLabel) - builder.addHandler(tryStart, tryEnd, finallyThrowLabel.pc, entryDepth) - builder.emit(Op.PUT_LOCAL, PutKind.INIT, valSlot, idx(node), -1) - builder.emitNumber(1, idx(node)) - builder.emit(Op.PUT_LOCAL, PutKind.INIT, tagSlot, idx(node), -1) - controlStack.pop() - - // Finally body at `entryDepth` - builder.mark(finallyLabel) - compileBlockStatement(node.finalizer) - - const targets = new Array(finallyEntry.exits.size + 2).fill(-1) - if (builder.depth >= 0) { - builder.emit(Op.END_FINALLY, 0, level, idx(node), 0) - builder.unreachable() - for (const exit of finallyEntry.exits.values()) { - targets[exit.tag] = builder.pc - builder.setDepth(entryDepth) - if (exit.kind === "return") builder.emit(Op.GET_LOCAL, 0, valSlot, idx(node), 1) - exitPlan(exit.kind, exit.target, node) - } - } - - builder.mark(afterFinallyLabel) - targets[0] = afterFinallyLabel.pc - builder.setFinally(level, tagSlot, valSlot, entryDepth, targets) - }) - - // --- Expressions (depth -> depth + 1, or `compileEffect` depth -> depth) --- - const compileEffect = (expr: Expression): void => { - if (expr.type === "AssignmentExpression" && expr.left.type === "Identifier" && !isLogicalAssignment(expr)) { - return compileAssignmentExpression(expr, true) - } - if (expr.type === "UpdateExpression" && expr.argument.type === "Identifier") { - const ref = analysis.refs.get(expr.argument)! - emitLoadRef(ref, expr.argument) - builder.emit(Op.INC, expr.operator === "++" ? 0 : 1, 0, idx(expr), 0) - emitStoreRef(ref, false, expr.argument) - return - } - compileExpression(expr) - builder.emit(Op.POP, 0, 0, idx(expr), -1) - } - - const compileNamedExpression = (expr: Expression, targetName: string): void => { - if (expr.type === "ClassExpression" && !expr.id) return compileClass(expr, targetName) - compileExpression(expr) - if (isAnonymousFunction(expr)) builder.emit(Op.SET_NAME, 0, builder.constant(targetName), idx(expr), 0) - } - - const compileExpression = (expr: Expression, chainShortCircuit?: Label): void => { - const compile = expressions[expr.type] as ((node: Expression, short?: Label) => void) | undefined - if (compile) compile(expr, chainShortCircuit) - else emitUnsupported(expr.type, expr) - } - - const compileLiteral = (node: Literal): void => { - const v = node.value - if (node.regex) { - const k = builder.constant({ pattern: node.regex.pattern, flags: node.regex.flags }) - builder.emit(Op.REGEXP, 0, k, idx(node), 1) - } else if (typeof v === "bigint") - emitThrowError({ type: "TypeError", message: "BigInt literals are not supported." }, node) - else if (v === null) builder.emit(Op.PUSH_NULL, 0, 0, idx(node), 1) - else if (typeof v === "boolean") builder.emit(Op.PUSH_BOOL, v ? 1 : 0, 0, idx(node), 1) - else if (typeof v === "number") builder.emitNumber(v, idx(node)) - else builder.emitString(v as string, idx(node)) - } - - // Stack has `[arr]`: appends every value the spread argument iterates to it. - const compileSpreadAppend = (spreadNode: SpreadElement): void => { - const baseDepth = builder.depth - const itSlot = allocSlot("%it") - compileExpression(spreadNode.argument) - const openSlow = emitIterOpen(IterContext.SPREAD, itSlot, baseDepth, spreadNode) - emitAppendRest(itSlot, baseDepth, spreadNode, openSlow) - } - - const compileArrayExpression = (node: ArrayExpression): void => { - const elements = node.elements - if (!elements.some((el) => el === null || el.type === "SpreadElement")) { - for (const el of elements) compileExpression(el as Expression) - builder.emit(Op.NEW_ARRAY, 0, elements.length, idx(node), 1 - elements.length) - return - } - builder.emit(Op.NEW_ARRAY, 0, 0, idx(node), 1) - for (const el of elements) { - if (el === null) builder.emit(Op.ARRAY_APPEND, 1, 0, idx(node), 0) - else if (el.type === "SpreadElement") compileSpreadAppend(el) - else { - compileExpression(el) - builder.emit(Op.ARRAY_APPEND, 0, 0, idx(node), -1) - } - } - } - - // Pushes call arguments, or one array of them when one is spread (or there are too many for an operand): true then. - const emitArguments = (args: ReadonlyArray, node: AstNode): boolean => { - if (!args.some((a) => a.type === "SpreadElement") && args.length <= 254) { - for (const arg of args) compileExpression(arg as Expression) - return false - } - builder.emit(Op.NEW_ARRAY, 0, 0, idx(node), 1) - for (const arg of args) { - if (arg.type === "SpreadElement") compileSpreadAppend(arg) - else { - compileExpression(arg) - builder.emit(Op.ARRAY_APPEND, 0, 0, idx(arg), -1) - } - } - return true - } - - // Only methods that use `super` need their home object. - const emitSetHome = (fn: Expression, depth: number): void => { - if (analysis.nodeToFunction.get(fn as FunctionExpression)?.homeDecl === undefined) return - builder.emit(Op.SET_HOME, depth, 0, idx(fn), 0) - } - - const compileObjectExpression = (node: ObjectExpression): void => { - builder.emit(Op.NEW_OBJECT, 0, 0, idx(node), 1) - for (const prop of node.properties) { - if (prop.type === "SpreadElement") { - compileExpression(prop.argument) - builder.emit(Op.COPY_DATA_PROPS, 0, 0, idx(prop), -1) - } else if (prop.kind !== "init") { - const setter = prop.kind === "set" ? 2 : 0 - if (prop.computed) { - compileExpression(prop.key as Expression) - builder.emit(Op.TO_KEY, 0, 0, idx(prop.key), 0) - compileExpression(prop.value as Expression) - builder.emit(Op.SET_NAME, setter === 0 ? 2 : 3, 0, idx(prop.value), 0) - emitSetHome(prop.value as Expression, 2) - builder.emit(Op.DEFINE_ACCESSOR, 1 | setter, 0, idx(prop), -2) - } else { - const bigint = prop.key.type === "Literal" && typeof prop.key.value === "bigint" - if (bigint) emitThrowError({ type: "TypeError", message: "BigInt literals are not supported." }, prop.key) - const name = bigint ? "" : keyName(prop.key) - compileNamedExpression(prop.value as Expression, `${prop.kind} ${name}`) - emitSetHome(prop.value as Expression, 1) - builder.emit(Op.DEFINE_ACCESSOR, setter, builder.constant(name), idx(prop), -1) - } - } else if (prop.computed) { - compileExpression(prop.key as Expression) - builder.emit(Op.TO_KEY, 0, 0, idx(prop.key), 0) - compileExpression(prop.value as Expression) - if (isAnonymousFunction(prop.value as Expression)) builder.emit(Op.SET_NAME, 1, 0, idx(prop.value), 0) - if (prop.method) emitSetHome(prop.value as Expression, 2) - builder.emit(Op.DEFINE_FIELD, 1, 0, idx(prop), -2) - } else { - const bigint = prop.key.type === "Literal" && typeof prop.key.value === "bigint" - if (bigint) emitThrowError({ type: "TypeError", message: "BigInt literals are not supported." }, prop.key) - const name = bigint ? "" : keyName(prop.key) - compileNamedExpression(prop.value as Expression, name) - if (prop.method) emitSetHome(prop.value as Expression, 1) - builder.emit(Op.DEFINE_FIELD, 0, builder.constant(name), idx(prop), -1) - } - } - } - - const compileTemplateLiteral = (node: TemplateLiteral): void => { - const quasis = node.quasis - const exprs = node.expressions - // Untagged templates always have cooked strings: an invalid escape is a syntax error. - if (exprs.length === 0) return builder.emitString(quasis[0]!.value.cooked!, idx(node)) - let parts = 0 - quasis.forEach((q, i) => { - if (q.value.cooked!.length > 0 || parts === 0) { - builder.emitString(q.value.cooked!, idx(q)) - parts++ - } - if (i >= exprs.length) return - compileExpression(exprs[i]!) - builder.emit(Op.TO_STRING, 0, 0, idx(exprs[i]), 0) - parts++ - }) - if (parts > 1) builder.emit(Op.CONCAT, 0, parts, idx(node), 1 - parts) - } - - const compileTaggedTemplate = (node: TaggedTemplateExpression): void => { - if (node.tag.type === "MemberExpression") compileMemberExpression(node.tag, true) - else { - builder.emit(Op.PUSH_UNDEF, 0, 0, idx(node), 1) - compileExpression(node.tag) - } - const siteConst = builder.constant({ - cooked: node.quasi.quasis.map((q) => q.value.cooked ?? undefined), - raw: node.quasi.quasis.map((q) => q.value.raw), - nodeIndex: idx(node), - }) - const argc = 1 + node.quasi.expressions.length - if (argc <= 254) { - builder.emit(Op.TEMPLATE, 0, siteConst, idx(node), 1) - for (const expr of node.quasi.expressions) compileExpression(expr) - builder.emit(Op.CALL, argc, 0, idx(node), -(argc + 1)) - return - } - builder.emit(Op.NEW_ARRAY, 0, 0, idx(node), 1) - builder.emit(Op.TEMPLATE, 0, siteConst, idx(node), 1) - builder.emit(Op.ARRAY_APPEND, 0, 0, idx(node), -1) - for (const expr of node.quasi.expressions) { - compileExpression(expr) - builder.emit(Op.ARRAY_APPEND, 0, 0, idx(expr), -1) - } - builder.emit(Op.CALL_SPREAD, 0, 0, idx(node), -2) - } - - const compileUnaryExpression = (node: UnaryExpression): void => { - const op = node.operator - if (op === "delete") return compileDeleteExpression(node) - const ref = node.argument.type === "Identifier" ? analysis.refs.get(node.argument)! : undefined - if (op === "typeof" && ref?.kind === "global") return emitLoadRef(ref, node.argument, true) - compileExpression(node.argument) - if (op === "!") builder.emit(Op.NOT, 0, 0, idx(node), 0) - else builder.emit(Op.UNARY, UnaryOps[op]!, 0, idx(node), 0) - } - - const compileDeleteExpression = (node: UnaryExpression): void => { - const arg = node.argument - const isChain = arg.type === "ChainExpression" - const target = isChain ? arg.expression : arg - if (target.type === "Identifier") { - return emitThrowError({ type: "TypeError", message: "Only data fields may be deleted." }, target) - } - if (target.type !== "MemberExpression") { - compileExpression(arg) - builder.emit(Op.POP, 0, 0, idx(node), -1) - builder.emit(Op.PUSH_BOOL, 1, 0, idx(node), 1) - return - } - if (target.object.type === "Super" && analysis.superRefs.has(target.object)) { - // `delete super.x` evaluates the reference (`this` first, then the key) and always throws. - emitSuperBase(target) - if (target.computed) { - compileExpression(target.property as Expression) - builder.emit(Op.TO_KEY, 0, 0, idx(target.property), 0) - } - return emitThrowError({ type: "ReferenceError", message: "Unsupported reference to 'super'." }, target) - } - if (unsupportedSuper(target)) return - const shortLabel = isChain || target.optional ? builder.newLabel(builder.depth + 1) : undefined - compileExpression(target.object as Expression, shortLabel) - if (target.optional && shortLabel) { - builder.emitJump(Op.JUMP_COND, CondKind.NULLISH, shortLabel, idx(target), 0, 0) - } - if (target.computed) { - compileExpression(target.property as Expression) - builder.emit(Op.DELETE_ELEM, 0, 0, idx(target), -1) - } else builder.emit(Op.DELETE_PROP, 0, builder.constant(propertyName(target)), idx(target), 0) - if (shortLabel && shortLabel.patches.length > 0) { - const endLabel = builder.newLabel(builder.depth) - builder.emitJump(Op.JUMP, 0, endLabel, idx(node), 0, 0) - builder.mark(shortLabel) - builder.emit(Op.POP, 0, 0, idx(node), -1) - builder.emit(Op.PUSH_BOOL, 1, 0, idx(node), 1) - builder.mark(endLabel) - } - } - - const compileUpdateExpression = (node: UpdateExpression): void => { - const incFlag = node.operator === "++" ? 0 : 1 - const arg = node.argument - if (arg.type === "Identifier") { - const ref = analysis.refs.get(arg)! - emitLoadRef(ref, arg) - if (node.prefix) builder.emit(Op.INC, incFlag, 0, idx(node), 0) - else builder.emit(Op.TO_NUMERIC, incFlag, 0, idx(arg), 0) - builder.emit(Op.DUP, 0, 0, idx(node), 1) - if (!node.prefix) builder.emit(Op.INC, incFlag, 0, idx(node), 0) - emitStoreRef(ref, false, arg) - return - } - if (arg.type !== "MemberExpression") { - return emitThrowError( - { type: "TypeError", message: "Update target must be an Identifier or MemberExpression." }, - arg, - ) - } - if (arg.object.type === "Super" && analysis.superRefs.has(arg.object)) { - const n = emitSuperRead(arg) - builder.emit(Op.TO_NUMERIC, incFlag, 0, idx(arg), 0) - if (!node.prefix) { - builder.emit(Op.DUP, 0, 0, idx(node), 1) - builder.emit(Op.ROT, n + 1, 0, idx(node), 0) - } - builder.emit(Op.INC, incFlag, 0, idx(node), 0) - emitPutSuper(arg) - if (!node.prefix) builder.emit(Op.POP, 0, 0, idx(node), -1) - return - } - if (unsupportedSuper(arg)) return - compileExpression(arg.object as Expression) - const k = arg.computed ? 0 : builder.constant(propertyName(arg)) - if (arg.computed) { - compileExpression(arg.property as Expression) - emitWritableKey(arg) - builder.emit(Op.PICK, 1, 0, idx(arg), 1) - builder.emit(Op.PICK, 1, 0, idx(arg), 1) - builder.emit(Op.GET_ELEM, 0, 0, idx(arg), -1) - } else { - builder.emit(Op.CHECK_BASE, CheckBaseKind.WRITE_PROP, k, idx(arg), 0) - builder.emit(Op.DUP, 0, 0, idx(arg), 1) - builder.emit(Op.GET_PROP, 0, k, idx(arg), 0) - } - builder.emit(Op.TO_NUMERIC, incFlag, 0, idx(arg), 0) - if (!node.prefix) { - builder.emit(Op.DUP, 0, 0, idx(node), 1) - builder.emit(Op.ROT, arg.computed ? 3 : 2, 0, idx(node), 0) - } - builder.emit(Op.INC, incFlag, 0, idx(node), 0) - if (arg.computed) builder.emit(Op.PUT_ELEM, 0, 0, idx(arg), -2) - else builder.emit(Op.PUT_PROP, 0, k, idx(arg), -1) - if (!node.prefix) builder.emit(Op.POP, 0, 0, idx(node), -1) - } - - const emitBinaryOp = (op: string, node: AstNode): void => { - const [code, a] = BinaryOps[op]! - builder.emit(code, a, 0, idx(node), -1) - } - - const compileBinaryExpression = (node: BinaryExpression): void => { - compileExpression(node.left as Expression) - compileExpression(node.right) - emitBinaryOp(node.operator, node) - } - - const compileLogicalExpression = (node: LogicalExpression): void => { - const endLabel = builder.newLabel(builder.depth + 1) - compileExpression(node.left) - builder.emitJump(Op.JUMP_COND, logicalCond(node.operator), endLabel, idx(node), 0, -1) - compileExpression(node.right) - builder.mark(endLabel) - } - - const compileConditionalExpression = (node: ConditionalExpression): void => { - const elseLabel = builder.newLabel(builder.depth) - const endLabel = builder.newLabel(builder.depth + 1) - compileExpression(node.test) - builder.emitJump(Op.JUMP_IF_FALSE, 0, elseLabel, idx(node), -1, -1) - compileExpression(node.consequent) - builder.emitJump(Op.JUMP, 0, endLabel, idx(node), 0, -1) - builder.mark(elseLabel) - compileExpression(node.alternate) - builder.mark(endLabel) - } - - const isLogicalAssignment = (node: AssignmentExpression) => - node.operator === "&&=" || node.operator === "||=" || node.operator === "??=" - - // `discard` skips keeping the assigned value, for an assignment to an identifier used as a statement. - const compileAssignmentExpression = (node: AssignmentExpression, discard = false): void => { - const left = node.left - const op = node.operator - const isLogical = isLogicalAssignment(node) - - if (left.type === "Identifier") { - const ref = analysis.refs.get(left)! - const endLabel = builder.newLabel(builder.depth + 1) - if (op !== "=") emitLoadRef(ref, left) - if (isLogical) builder.emitJump(Op.JUMP_COND, logicalCond(op), endLabel, idx(node), 0, -1) - if (op === "=" || isLogical) compileNamedExpression(node.right, left.name) - else { - compileExpression(node.right) - emitBinaryOp(op.slice(0, -1), node) - } - if (!discard) builder.emit(Op.DUP, 0, 0, idx(node), 1) - emitStoreRef(ref, false, left) - if (isLogical) builder.mark(endLabel) - return - } - - if (left.type === "ObjectPattern" || left.type === "ArrayPattern") { - compileExpression(node.right) - builder.emit(Op.DUP, 0, 0, idx(node), 1) - compilePattern(left, false, false, node) - return - } - - if (left.type !== "MemberExpression") { - return emitThrowError( - { type: "TypeError", message: "Assignment target must be an Identifier or MemberExpression." }, - left, - ) - } - if (left.object.type === "Super" && op === "=" && analysis.superRefs.has(left.object)) { - emitSuperBase(left) - if (left.computed) { - compileExpression(left.property as Expression) - builder.emit(Op.TO_KEY, 0, 0, idx(left.property), 0) - } - compileExpression(node.right) - emitPutSuper(left) - return - } - if (left.object.type === "Super" && analysis.superRefs.has(left.object)) { - // [home, this(, key)] stays below the value for PUT_SUPER. - const n = emitSuperRead(left) - if (!isLogical) { - compileExpression(node.right) - emitBinaryOp(op.slice(0, -1), node) - emitPutSuper(left) - return - } - const shortLabel = builder.newLabel(builder.depth) - const endLabel = builder.newLabel(builder.depth - n) - builder.emitJump(Op.JUMP_COND, logicalCond(op), shortLabel, idx(node), 0, -1) - compileExpression(node.right) - emitPutSuper(left) - builder.emitJump(Op.JUMP, 0, endLabel, idx(node), 0, -1) - builder.mark(shortLabel) - builder.emit(Op.ROT, n, 0, idx(node), 0) - builder.emit(Op.POPN, 0, n, idx(node), -n) - builder.mark(endLabel) - return - } - if (unsupportedSuper(left)) return - - const baseDepth = builder.depth - compileExpression(left.object as Expression) - const k = left.computed ? 0 : builder.constant(propertyName(left)) - const put = () => - left.computed ? builder.emit(Op.PUT_ELEM, 0, 0, idx(left), -2) : builder.emit(Op.PUT_PROP, 0, k, idx(left), -1) - if (left.computed) { - compileExpression(left.property as Expression) - emitWritableKey(left) - } else builder.emit(Op.CHECK_BASE, CheckBaseKind.WRITE_PROP, k, idx(left), 0) - if (op === "=") { - compileExpression(node.right) - put() - return - } - if (left.computed) { - builder.emit(Op.PICK, 1, 0, idx(left), 1) - builder.emit(Op.PICK, 1, 0, idx(left), 1) - builder.emit(Op.GET_ELEM, 0, 0, idx(left), -1) - } else { - builder.emit(Op.DUP, 0, 0, idx(left), 1) - builder.emit(Op.GET_PROP, 0, k, idx(left), 0) - } - if (!isLogical) { - compileExpression(node.right) - emitBinaryOp(op.slice(0, -1), node) - put() - return - } - // Short-circuits with `[o, key, current]` (or `[o, current]`) on the stack, and keeps `current`. - const shortLabel = builder.newLabel(baseDepth + (left.computed ? 3 : 2)) - const endLabel = builder.newLabel(baseDepth + 1) - builder.emitJump(Op.JUMP_COND, logicalCond(op), shortLabel, idx(node), 0, -1) - compileExpression(node.right) - put() - builder.emitJump(Op.JUMP, 0, endLabel, idx(node), 0, -1) - builder.mark(shortLabel) - builder.emit(Op.ROT, left.computed ? 2 : 1, 0, idx(node), 0) - builder.emit(Op.POP, 0, 0, idx(node), -1) - if (left.computed) builder.emit(Op.POP, 0, 0, idx(node), -1) - builder.mark(endLabel) - } - - const compileMemberExpression = (node: MemberExpression, keepReceiver: boolean, chainShortCircuit?: Label): void => { - if (node.object.type === "Super") { - if (!emitSuperBase(node)) return - if (node.computed) { - compileExpression(node.property as Expression) - builder.emit(Op.TO_KEY, 0, 0, idx(node.property), 0) - } - const a = (keepReceiver ? 1 : 0) | (node.computed ? 2 : 0) - const k = node.computed ? 0 : builder.constant(propertyName(node)) - builder.emit(Op.GET_SUPER, a, k, idx(node), (keepReceiver ? 0 : -1) - (node.computed ? 1 : 0)) - return - } - if (unsupportedSuper(node)) return - compileExpression(node.object as Expression, chainShortCircuit) - if (node.optional && chainShortCircuit) { - builder.emitJump(Op.JUMP_COND, CondKind.NULLISH, chainShortCircuit, idx(node), 0, 0) - } - const keepFlag = keepReceiver ? 1 : 0 - if (node.computed) { - compileExpression(node.property as Expression) - if (keepReceiver) { - builder.emit(Op.CHECK_BASE, CheckBaseKind.READ, 0, idx(node), 0) - builder.emit(Op.TO_KEY, 0, 0, idx(node.property), 0) - } - builder.emit(Op.GET_ELEM, keepFlag, 0, idx(node), keepReceiver ? 0 : -1) - } else { - builder.emit(Op.GET_PROP, keepFlag, builder.constant(propertyName(node)), idx(node), keepReceiver ? 1 : 0) - } - } - - const compileCallExpression = (node: CallExpression, chainShortCircuit?: Label): void => { - if (node.callee.type === "Super") return compileSuperCall(node) - const args = node.arguments - // Lower `$Call(fn, thisArg, ...args)` in internal/prelude code directly to `Op.CALL` (§5.1) - if ( - internal && - !node.optional && - node.callee.type === "Identifier" && - node.callee.name === "$Call" && - args.length >= 2 && - args.length - 2 <= 254 && - !args.some((a) => a.type === "SpreadElement") - ) { - for (const arg of [args[1]!, args[0]!, ...args.slice(2)]) compileExpression(arg as Expression) - builder.emit(Op.CALL, args.length - 2, 0, idx(node), -(args.length - 1)) - return - } - const shortLabel = chainShortCircuit ?? (node.optional ? builder.newLabel(builder.depth + 1) : undefined) - if (node.callee.type === "MemberExpression") { - compileMemberExpression(node.callee, true, shortLabel) - if (node.optional && shortLabel) { - builder.emitJump(Op.JUMP_COND, CondKind.NULLISH_METHOD, shortLabel, idx(node), -1, 0) - } - } else if (shortLabel) { - compileExpression(node.callee, shortLabel) - if (node.optional) builder.emitJump(Op.JUMP_COND, CondKind.NULLISH, shortLabel, idx(node), 0, 0) - builder.emit(Op.PUSH_UNDEF, 0, 0, idx(node), 1) - builder.emit(Op.ROT, 1, 0, idx(node), 0) - } else { - builder.emit(Op.PUSH_UNDEF, 0, 0, idx(node), 1) - compileExpression(node.callee) - } - if (emitArguments(args, node)) builder.emit(Op.CALL_SPREAD, 0, 0, idx(node), -2) - else builder.emit(Op.CALL, args.length, 0, idx(node), -(args.length + 1)) - if (!chainShortCircuit && shortLabel) builder.mark(shortLabel) - } - - // `super(...)` in a derived constructor: constructs the parent for the new target, binds `this`, then the fields. - const compileSuperCall = (node: CallExpression): void => { - if ((fnInfo.flags & CodeFlags.DERIVED) === 0) - return fnInfo.node.type === "ArrowFunctionExpression" - ? emitUnsupportedSuper("super() inside an arrow function is not supported. Call super() directly in the constructor.", node.callee) - : emitUnsupported("Super", node.callee) - const spread = emitArguments(node.arguments, node) - const n = node.arguments.length - builder.emit(Op.SUPER_CALL, spread ? 255 : n, fnInfo.newTargetDecl!.slot, idx(node), spread ? 0 : 1 - n) - const [captured, slot] = thisOperand() - builder.emit(Op.SUPER_BIND, captured, slot, idx(node), 0) - if (!hasInstanceFields(fnInfo.node)) return - builder.emit(Op.INIT_FIELDS, 0, 0, idx(node), 1) - builder.emit(Op.POP, 0, 0, idx(node), -1) - } - - const hasInstanceFields = (ctor: AstNode): boolean => - [...analysis.classConstructors].some(([c, fn]) => fn === ctor && analysis.classFieldInits.get(c)?.instance) - - const compileNewExpression = (node: NewExpression): void => { - compileExpression(node.callee as Expression) - // Check constructibility before evaluating arguments - builder.emit(Op.NEW, 255, 0, idx(node), 0) - const args = node.arguments - if (emitArguments(args, node)) builder.emit(Op.NEW_SPREAD, 0, 0, idx(node), -1) - else builder.emit(Op.NEW, args.length, 0, idx(node), -args.length) - } - - const compileImportExpression = (node: ImportExpression): void => { - compileExpression(node.source) - builder.emit(Op.TO_STRING, 1, 0, idx(node.source), 0) - if (node.options) { - compileExpression(node.options) - builder.emit(Op.POP, 0, 0, idx(node.options), -1) - } - builder.emit(Op.IMPORT, ImportKind.DYNAMIC, 0, idx(node), 0) - } - - const compileAwaitExpression = (node: AwaitExpression): void => { - compileExpression(node.argument) - builder.emit(Op.AWAIT, internal ? 1 : 0, 0, idx(node), 0) - } - - const isAsync = (fnInfo.flags & CodeFlags.ASYNC) !== 0 - - const compileYieldExpression = (node: YieldExpression): void => { - if (node.delegate) return compileYieldDelegate(node) - const targetDepth = builder.depth + 1 - if (node.argument) compileExpression(node.argument) - else builder.emit(Op.PUSH_UNDEF, 0, 0, idx(node), 1) - if (isAsync) builder.emit(Op.AWAIT, 0, 0, idx(node), 0) - builder.emit(Op.YIELD, 0, 0, idx(node), 1) - // C2: RESUME jumps to `normalLabel` on next (`[recv]`), throws on throw, and falls through on return (`[recv]`). - const normalLabel = builder.newLabel(targetDepth) - builder.emitJump(Op.RESUME, 0, normalLabel, idx(node), -1, -1) - if (isAsync) builder.emit(Op.AWAIT, 1, 0, idx(node), 0) - exitPlan("return", null, node) - builder.mark(normalLabel) - } - - // Pushes whether the resume kind in `kindSlot` (or on top, when `kindSlot` is -1) is `return`. - const emitIsReturn = (kindSlot: number, node: AstNode): void => { - if (kindSlot < 0) builder.emit(Op.DUP, 0, 0, idx(node), 1) - else builder.emit(Op.GET_LOCAL, 0, kindSlot, idx(node), 1) - builder.emitNumber(2, idx(node)) - builder.emit(Op.SEQ, 0, 0, idx(node), -1) - } - - const compileYieldDelegate = (node: YieldExpression): void => { - const baseDepth = builder.depth - const itSlot = allocSlot("%it") - const kindSlot = allocSlot("%kind") - compileExpression(node.argument!) - const openSlow = emitIterOpen(isAsync ? IterContext.ASYNC_DELEGATE : IterContext.DELEGATE, itSlot, baseDepth, node) - builder.emit(Op.PUSH_UNDEF, 0, 0, idx(node), 1) - builder.emitNumber(0, idx(node)) - - const loopLabel = builder.newLabel(baseDepth + 2) - const callLabel = builder.newLabel(baseDepth + 3) - const noThrowLabel = builder.newLabel(baseDepth + 1) - const doneLabel = builder.newLabel(baseDepth + 1) - const exprDoneLabel = builder.newLabel(baseDepth + 1) - - builder.mark(loopLabel) - builder.emit(Op.DUP, 0, 0, idx(node), 1) - builder.emit(Op.PUT_LOCAL, PutKind.INIT, kindSlot, idx(node), -1) - // YSTAR jumps to `callLabel` (`[iterator, method, recv]`) when the method exists, and falls through (`[recv]`) when missing. - builder.emitJump(Op.YSTAR, itSlot, callLabel, idx(node), 1, -1) - emitIsReturn(kindSlot, node) - builder.emitJump(Op.JUMP_IF_FALSE, 0, noThrowLabel, idx(node), -1, -1) - // Missing `return` method: await received value in async generators, then return - if (isAsync) builder.emit(Op.AWAIT, 0, 0, idx(node), 0) - exitPlan("return", null, node) - - // Missing `throw` method: close iterator, then throw TypeError - builder.mark(noThrowLabel) - builder.emit(Op.POP, 0, 0, idx(node), -1) - emitIteratorCloseNormal(itSlot, isAsync, node) - emitThrowError({ type: "TypeError", message: "The delegated iterator does not provide a throw() method." }, node) - - builder.mark(callLabel) - builder.emit(Op.CALL, 1, 0, idx(node), -2) - if (isAsync) builder.emit(Op.AWAIT, 0, 0, idx(node), 0) - builder.emitJump(Op.YSTAR_RESULT, kindSlot, doneLabel, idx(node), 0, 0) - builder.emit(Op.YIELD, 0, 0, idx(node), 1) - if (isAsync) { - const notReturnLabel = builder.newLabel(baseDepth + 2) - emitIsReturn(-1, node) - builder.emitJump(Op.JUMP_IF_FALSE, 0, notReturnLabel, idx(node), -1, -1) - builder.emit(Op.ROT, 1, 0, idx(node), 0) - builder.emit(Op.AWAIT, 1, 0, idx(node), 0) - builder.emit(Op.ROT, 1, 0, idx(node), 0) - builder.mark(notReturnLabel) - } - builder.emitJump(Op.LOOP, 0, loopLabel, idx(node), 0, null) - openSlow() - - builder.mark(doneLabel) - emitIsReturn(kindSlot, node) - builder.emitJump(Op.JUMP_IF_FALSE, 0, exprDoneLabel, idx(node), -1, -1) - exitPlan("return", null, node) - builder.mark(exprDoneLabel) - } - - type Compilers = { - readonly [K in N["type"]]?: (node: Extract, arg?: A) => void - } - - const statements: Compilers> = { - EmptyStatement: () => {}, - FunctionDeclaration: () => {}, - ClassDeclaration: (stmt) => { - compileClass(stmt) - if (builder.depth < 0 || !stmt.id) return - emitStoreDecl(analysis.scopeOfNode.get(stmt)!.parent!.decls.get(stmt.id.name)!, true, stmt) - }, - ImportDeclaration: (stmt) => { - if (isProgram) return - const message = "An import declaration may only appear at the top level of the program." - emitThrowError({ type: "SyntaxError", message }, stmt) - }, - ExpressionStatement: (stmt) => compileEffect(stmt.expression), - VariableDeclaration: compileVariableDeclaration, - BlockStatement: compileBlockStatement, - IfStatement: compileIfStatement, - WhileStatement: compileWhileStatement, - DoWhileStatement: compileDoWhileStatement, - ForStatement: compileForStatement, - ForInStatement: compileForInStatement, - ForOfStatement: compileForOfStatement, - SwitchStatement: compileSwitchStatement, - LabeledStatement: compileLabeledStatement, - BreakStatement: (stmt) => exitPlan("break", findExitTarget("break", stmt.label?.name), stmt), - ContinueStatement: (stmt) => exitPlan("continue", findExitTarget("continue", stmt.label?.name), stmt), - ReturnStatement: (stmt) => { - if (stmt.argument) { - compileExpression(stmt.argument) - if (isAsync && (fnInfo.flags & CodeFlags.GENERATOR) !== 0) builder.emit(Op.AWAIT, 0, 0, idx(stmt), 0) - } else builder.emit(Op.PUSH_UNDEF, 0, 0, idx(stmt), 1) - exitPlan("return", null, stmt) - }, - ThrowStatement: (stmt) => { - compileExpression(stmt.argument) - builder.emit(Op.THROW, 0, 0, idx(stmt), -1) - builder.unreachable() - }, - TryStatement: compileTryStatement, - } - - const expressions: Compilers = { - Literal: compileLiteral, - Identifier: (expr) => emitLoadRef(analysis.refs.get(expr)!, expr), - ThisExpression: (expr) => emitLoadRef(analysis.thisRefs.get(expr)!, expr), - FunctionExpression: (expr) => builder.emit(Op.CLOSURE, 0, analysis.nodeToFunction.get(expr)!.index, idx(expr), 1), - ArrowFunctionExpression: (expr) => - builder.emit(Op.CLOSURE, 0, analysis.nodeToFunction.get(expr)!.index, idx(expr), 1), - ClassExpression: (expr) => compileClass(expr), - ArrayExpression: compileArrayExpression, - ObjectExpression: compileObjectExpression, - TemplateLiteral: compileTemplateLiteral, - TaggedTemplateExpression: compileTaggedTemplate, - UnaryExpression: compileUnaryExpression, - UpdateExpression: compileUpdateExpression, - BinaryExpression: compileBinaryExpression, - LogicalExpression: compileLogicalExpression, - ConditionalExpression: compileConditionalExpression, - SequenceExpression: (expr) => - expr.expressions.forEach((e, i) => { - compileExpression(e) - if (i < expr.expressions.length - 1) builder.emit(Op.POP, 0, 0, idx(e), -1) - }), - AssignmentExpression: (expr) => compileAssignmentExpression(expr), - MemberExpression: (expr, short) => compileMemberExpression(expr, false, short), - CallExpression: compileCallExpression, - NewExpression: compileNewExpression, - ChainExpression: (expr) => { - const shortLabel = builder.newLabel(builder.depth + 1) - compileExpression(expr.expression, shortLabel) - builder.mark(shortLabel) - }, - ImportExpression: compileImportExpression, - AwaitExpression: compileAwaitExpression, - YieldExpression: compileYieldExpression, - } - - // --- Emit Function / Program Body --- - // `this`, `arguments`, and a named function expression's own name, when the body uses them. - const emitImplicit = (decl: Decl | undefined, argsKind: number): void => { - if (!decl?.used) return - if (decl.captured) builder.emit(Op.NEW_CELL, 0, decl.slot) - if (isProgram) builder.emit(Op.PUSH_UNDEF, 0, 0, -1, 1) - else builder.emit(Op.ARGS, argsKind, 0, idx(fnInfo.node), 1) - emitStoreDecl(decl, true, isProgram ? undefined : fnInfo.node) - } - - if (isProgram) { - const prog = fnInfo.node as Program - emitImplicit(fnInfo.thisDecl, 3) - for (const decl of fnInfo.bodyScope.decls.values()) { - if (decl.kind !== "this" && decl.captured) builder.emit(Op.NEW_CELL, 0, decl.slot) - } - emitImports(prog.body) - for (const decl of fnInfo.bodyScope.decls.values()) { - if (decl.kind !== "var") continue - builder.emit(Op.PUSH_UNDEF, 0, 0, -1, 1) - emitStoreDecl(decl, true) - } - emitHoistedFunctions(fnInfo.bodyScope) - const last = prog.body.at(-1) - for (const s of prog.body) if (s !== last || s.type !== "ExpressionStatement") compileStatement(s) - if (last?.type === "ExpressionStatement") { - compileExpression(last.expression) - builder.emit(Op.END_PROGRAM, 0, 0, idx(last), -1) - } else { - builder.emit(Op.PUSH_UNDEF, 0, 0, idx(prog), 1) - builder.emit(Op.END_PROGRAM, 0, 0, idx(prog), -1) - } - } else { - emitImplicit(fnInfo.selfScope?.decls.values().next().value, 2) - if ((fnInfo.flags & CodeFlags.DERIVED) === 0) emitImplicit(fnInfo.thisDecl, 3) - else { - const decl = fnInfo.thisDecl! - builder.emit(decl.captured ? Op.NEW_CELL : Op.HOLE_LOCAL, 0, decl.slot) - emitImplicit(fnInfo.newTargetDecl, 3) - } - emitImplicit(fnInfo.homeDecl, 5) - const simple = (fnInfo.flags & CodeFlags.SIMPLE_PARAMS) !== 0 - for (const decl of fnInfo.paramScope.decls.values()) { - // A simple parameter's argument is already in its slot: it moves into the new cell. - if (decl.kind === "param" && decl.captured) - builder.emit(Op.NEW_CELL, simple ? 1 : 0, decl.slot, idx(fnInfo.node), 0) - } - emitImplicit(fnInfo.argumentsDecl, 0) - if (!simple) { - fnInfo.params.forEach((param, i) => { - if (param.type === "RestElement") { - builder.emit(Op.ARGS, 1, i, idx(param), 1) - return compilePattern(param.argument, true, true, param) - } - // Duplicate plain identifier parameter: only the last occurrence initializes the binding - const name = param.type === "Identifier" ? param.name : undefined - if (name !== undefined && fnInfo.params.findLastIndex((p) => p.type === "Identifier" && p.name === name) !== i) - return - builder.emit(Op.ARGS, 4, i, idx(param), 1) - compilePattern(param, true, true, param) - }) - } - emitScopePrologue(fnInfo.bodyScope, false) - if ((fnInfo.flags & CodeFlags.GENERATOR) !== 0) builder.emit(Op.GENERATOR_START, 0, 0, idx(fnInfo.node), 0) - - const body = fnInfo.node.body as BlockStatement | Expression - const fields = analysis.fieldInitMembers.get(fnInfo.node) - if ((fnInfo.flags & (CodeFlags.CLASS_CONSTRUCTOR | CodeFlags.DERIVED)) === CodeFlags.CLASS_CONSTRUCTOR && hasInstanceFields(fnInfo.node)) { - builder.emit(Op.INIT_FIELDS, 0, 0, idx(fnInfo.node), 1) - builder.emit(Op.POP, 0, 0, idx(fnInfo.node), -1) - } - if (fields) { - // The body is `this` and then each initializer: define the fields on `this` in order. - compileExpression(((body as BlockStatement).body[0] as ExpressionStatement).expression) - for (const field of fields) { - const key = analysis.fieldKeys.get(field) - if (key) { - compileExpression(key) - if (field.value) compileExpression(field.value) - else builder.emit(Op.PUSH_UNDEF, 0, 0, idx(field), 1) - if (field.value && isAnonymousFunction(field.value)) builder.emit(Op.SET_NAME, 1, 0, idx(field.value), 0) - builder.emit(Op.DEFINE_FIELD, 3, 0, idx(field), -2) - continue - } - const name = keyName(field.key) - if (field.value) compileNamedExpression(field.value, name) - else builder.emit(Op.PUSH_UNDEF, 0, 0, idx(field), 1) - builder.emit(Op.DEFINE_FIELD, 2, builder.constant(name), idx(field), -1) - } - builder.emit(Op.POP, 0, 0, idx(body), -1) - builder.emit(Op.PUSH_UNDEF, 0, 0, idx(body), 1) - } else if (body.type === "BlockStatement") { - for (const s of body.body) compileStatement(s) - builder.emit(Op.PUSH_UNDEF, 0, 0, idx(body), 1) - } else compileExpression(body) - builder.emit(Op.RETURN, 0, 0, idx(body), -1) - } - - return builder.finish() -} - -const unsupportedFeatureMessages: Record = { - PrivateIdentifier: "Private class members (#name) are not supported. Use a regular property instead.", - StaticBlock: "Class static blocks are not supported. Assign static fields instead.", - MetaProperty: "new.target is not supported.", - Super: "'super' is only supported in class methods.", -} - -// What an unsupported class element or `extends` is called in the error. -const classSyntaxName = (node: AstNode): string => { - const member = node as ClassNode["body"]["body"][number] - if (member.type === "StaticBlock") return "StaticBlock" - if (member.type !== "MethodDefinition" && member.type !== "PropertyDefinition") return "ClassHeritage" - if (member.key.type === "PrivateIdentifier") return "PrivateIdentifier" - if (member.type === "PropertyDefinition") return member.computed ? "ComputedClassMember" : "PropertyDefinition" - if (member.kind === "get" || member.kind === "set") return `${member.kind === "get" ? "Getter" : "Setter"}` - if (member.computed) return "ComputedClassMember" - return member.value.async ? "AsyncMethod" : "GeneratorMethod" -} - -const propertyName = (node: MemberExpression): string => (node.property as { name: string }).name - -const keyName = (key: Expression | { type: "PrivateIdentifier" }): string => - key.type === "Identifier" ? key.name : String((key as Literal).value) diff --git a/packages/codemode/src/language/compiler/scope.ts b/packages/codemode/src/language/compiler/scope.ts deleted file mode 100644 index bfc75cb720d..00000000000 --- a/packages/codemode/src/language/compiler/scope.ts +++ /dev/null @@ -1,736 +0,0 @@ -import type { - AnyNode, - ArrowFunctionExpression, - BlockStatement, - CatchClause, - ClassDeclaration, - ClassExpression, - Expression, - FunctionDeclaration, - FunctionExpression, - Identifier, - ModuleDeclaration, - Pattern, - PrivateIdentifier, - Program, - PropertyDefinition, - Statement, - VariableDeclaration, -} from "acorn" -import type { Source } from "../runtime/source.js" -import { CodeFlags } from "../opcodes.js" - -type FunctionNode = Program | FunctionDeclaration | FunctionExpression | ArrowFunctionExpression - -type DeclKind = "var" | "let" | "const" | "function" | "param" | "catch" | "import" | "self" | "this" | "arguments" | "home" | "newTarget" - -export type Decl = { - readonly name: string - readonly kind: DeclKind - readonly fnIndex: number - mutable: boolean - captured: boolean - used: boolean - slot: number - /** When a body `var` shares a name with a parameter or `arguments` in a separate `paramScope`. */ - copyFromParam?: Decl | undefined -} - -export class Scope { - readonly decls = new Map() - readonly hoistedFunctions: Array<{ readonly node: FunctionDeclaration; fnIndex: number; readonly decl: Decl }> = [] - - constructor(readonly parent: Scope | undefined) {} -} - -type UpvalueInfo = { - /** `0` = parent's local cell slot, `1` = parent's upvalue index. */ - readonly from: 0 | 1 - index: number - readonly decl: Decl -} - -export type FunctionInfo = { - readonly index: number - readonly node: FunctionNode - readonly parentIndex: number - readonly name: string - flags: number - readonly length: number - readonly params: ReadonlyArray - readonly selfScope: Scope | undefined - readonly paramScope: Scope - readonly bodyScope: Scope - readonly allDecls: Array - readonly upvalues: Array - readonly upvalueMap: Map - thisDecl: Decl | undefined - /** A method's home object (`super`), when it or an arrow in it uses `super`. */ - homeDecl: Decl | undefined - /** A derived constructor's new target, which `super()` passes on. */ - newTargetDecl: Decl | undefined - argumentsDecl: Decl | undefined - locals: number - readonly localNames: Array -} - -export type ResolvedRef = - | { readonly kind: "local"; readonly decl: Decl } - | { readonly kind: "upval"; readonly upvalIndex: number; readonly decl: Decl } - | { readonly kind: "global"; readonly name: string } - -export type ScopeAnalysis = { - readonly functions: ReadonlyArray - readonly nodeToFunction: ReadonlyMap - readonly scopeOfNode: ReadonlyMap - readonly refs: ReadonlyMap - readonly thisRefs: ReadonlyMap - /** Each `super` of a `super.x`: its home object and `this`. Missing when it is outside a class method. */ - readonly superRefs: ReadonlyMap - /** Each class's constructor: its own, or a synthetic empty one when it has none. */ - readonly classConstructors: ReadonlyMap - /** Each class's synthetic field-initializer functions, when it has instance or static fields. */ - readonly classFieldInits: ReadonlyMap - /** The fields a synthetic field-initializer function defines, in order. */ - readonly fieldInitMembers: ReadonlyMap> - /** A computed field's key, evaluated once at class definition into a hidden class-scope binding read by this name. */ - readonly fieldKeys: ReadonlyMap -} - -export type ClassNode = ClassDeclaration | ClassExpression - -/** The class elements compiled so far: methods, accessors and fields with plain or computed names. Anything else is refused. */ -export const supportedClassMember = (member: ClassNode["body"]["body"][number]): boolean => - (member.type === "PropertyDefinition" || member.type === "MethodDefinition") && - (member.computed || plainKey(member.key)) - -const plainKey = (key: Expression | PrivateIdentifier): boolean => - key.type === "Identifier" || - (key.type === "Literal" && (typeof key.value === "string" || typeof key.value === "number")) - -/** - * Pass 1: walks the AST to build lexical/var scopes, assign pre-order function indices, - * resolve all identifier and `this` references, mark captured bindings, and assign local/upvalue slots. - */ -export const analyzeScopes = (source: Source, internal = false): ScopeAnalysis => { - const functions: Array = [] - const nodeToFunction = new Map() - const scopeOfNode = new Map() - const classConstructors = new Map() - const classFieldInits = new Map() - const fieldInitMembers = new Map>() - const fieldKeys = new Map() - const supers: Array<{ readonly node: AnyNode; readonly scope: Scope; readonly fnIndex: number }> = [] - const unresolved: Array<{ readonly node: AnyNode; readonly name: string; readonly scope: Scope; fnIndex: number }> = - [] - - const addDecl = (scope: Scope, fnInfo: FunctionInfo, name: string, kind: DeclKind, mutable: boolean): Decl => { - const existing = scope.decls.get(name) - if (existing !== undefined) { - if (mutable) existing.mutable = true - return existing - } - const decl: Decl = { name, kind, fnIndex: fnInfo.index, mutable, captured: false, used: false, slot: -1 } - scope.decls.set(name, decl) - fnInfo.allDecls.push(decl) - return decl - } - - const declareLexical = (node: VariableDeclaration, scope: Scope, fnInfo: FunctionInfo): void => { - if (node.kind === "var") return - for (const d of node.declarations) { - for (const name of collectPatternNames(d.id)) - addDecl(scope, fnInfo, name, node.kind === "let" ? "let" : "const", node.kind === "let") - } - } - - const visitFunction = ( - node: FunctionNode, - parentScope: Scope | undefined, - parentFnIndex: number, - className?: string, - ): FunctionInfo => { - const index = functions.length - const isProgram = node.type === "Program" - const isArrow = node.type === "ArrowFunctionExpression" - const params: ReadonlyArray = isProgram ? [] : node.params - const simple = params.every((p) => p.type === "Identifier") - - let flags = 0 - if (isArrow) flags |= CodeFlags.ARROW - if (isProgram || node.async) flags |= CodeFlags.ASYNC - if (!isProgram && node.generator) flags |= CodeFlags.GENERATOR - if (simple) flags |= CodeFlags.SIMPLE_PARAMS - if (internal) flags |= CodeFlags.INTERNAL - if (isProgram) flags |= CodeFlags.PROGRAM - - const selfScope = node.type === "FunctionExpression" && node.id ? new Scope(parentScope) : undefined - const paramScope = new Scope(selfScope ?? parentScope) - const bodyScope = simple ? paramScope : new Scope(paramScope) - const lengthEnd = params.findIndex((p) => p.type === "AssignmentPattern" || p.type === "RestElement") - - const fnInfo: FunctionInfo = { - index, - node, - parentIndex: parentFnIndex, - name: isProgram ? "" : isArrow ? "" : (className ?? node.id?.name ?? ""), - flags, - length: lengthEnd === -1 ? params.length : lengthEnd, - params, - selfScope, - paramScope, - bodyScope, - allDecls: [], - upvalues: [], - upvalueMap: new Map(), - thisDecl: undefined, - homeDecl: undefined, - newTargetDecl: undefined, - argumentsDecl: undefined, - locals: 0, - localNames: [], - } - functions.push(fnInfo) - nodeToFunction.set(node, fnInfo) - scopeOfNode.set(node, bodyScope) - - if (selfScope && node.type === "FunctionExpression") addDecl(selfScope, fnInfo, node.id!.name, "self", false) - if (!isArrow) fnInfo.thisDecl = addDecl(paramScope, fnInfo, "this", "this", false) - const paramNames = params.flatMap((param) => collectPatternNames(param)) - if (!isProgram && !isArrow && !paramNames.includes("arguments")) { - fnInfo.argumentsDecl = addDecl(paramScope, fnInfo, "arguments", "arguments", true) - } - for (const name of paramNames) addDecl(paramScope, fnInfo, name, "param", true) - for (const param of params) visitPattern(param, paramScope, fnInfo) - - if (node.type !== "Program" && node.body.type !== "BlockStatement") visitExpression(node.body, bodyScope, fnInfo) - else { - if (node.type !== "Program") scopeOfNode.set(node.body, bodyScope) - const stmts = node.type === "Program" ? node.body : (node.body as BlockStatement).body - hoistStatementList(stmts, bodyScope, bodyScope, fnInfo, isProgram) - for (const stmt of stmts) visitStatement(stmt, bodyScope, bodyScope, fnInfo) - } - - if (!simple) { - for (const [varName, decl] of bodyScope.decls) { - const paramDecl = decl.kind === "var" ? paramScope.decls.get(varName) : undefined - if (paramDecl?.kind !== "param" && paramDecl?.kind !== "arguments") continue - decl.copyFromParam = paramDecl - paramDecl.used = true - if (paramDecl.kind === "arguments") fnInfo.flags |= CodeFlags.USES_ARGUMENTS | CodeFlags.NEEDS_ARGS - } - } - return fnInfo - } - - const hoistStatementList = ( - stmts: ReadonlyArray, - lexicalScope: Scope, - varScope: Scope, - fnInfo: FunctionInfo, - isProgram: boolean, - ): void => { - if (isProgram) { - for (const stmt of stmts) { - if (stmt.type !== "ImportDeclaration") continue - for (const spec of stmt.specifiers) addDecl(lexicalScope, fnInfo, spec.local.name, "import", false) - } - } - for (const stmt of stmts) if (stmt.type === "VariableDeclaration") declareLexical(stmt, lexicalScope, fnInfo) - for (const stmt of stmts) - if (stmt.type === "ClassDeclaration" && stmt.id) addDecl(lexicalScope, fnInfo, stmt.id.name, "let", true) - for (const stmt of stmts) { - if (stmt.type !== "FunctionDeclaration" || !stmt.id || (internal && isProgram)) continue - const decl = addDecl(lexicalScope, fnInfo, stmt.id.name, "function", true) - lexicalScope.hoistedFunctions.push({ node: stmt, fnIndex: -1, decl }) - } - if (lexicalScope === varScope) for (const stmt of stmts) collectVars(stmt, varScope, fnInfo) - } - - const collectVars = ( - stmt: Statement | ModuleDeclaration | null | undefined, - varScope: Scope, - fnInfo: FunctionInfo, - ) => { - switch (stmt?.type) { - case "VariableDeclaration": - if (stmt.kind !== "var") break - for (const d of stmt.declarations) { - for (const name of collectPatternNames(d.id)) { - if (!varScope.decls.has(name)) addDecl(varScope, fnInfo, name, "var", true) - } - } - break - case "BlockStatement": - for (const s of stmt.body) collectVars(s, varScope, fnInfo) - break - case "IfStatement": - collectVars(stmt.consequent, varScope, fnInfo) - collectVars(stmt.alternate, varScope, fnInfo) - break - case "WhileStatement": - case "DoWhileStatement": - case "LabeledStatement": - collectVars(stmt.body, varScope, fnInfo) - break - case "ForStatement": - if (stmt.init?.type === "VariableDeclaration") collectVars(stmt.init, varScope, fnInfo) - collectVars(stmt.body, varScope, fnInfo) - break - case "ForInStatement": - case "ForOfStatement": - if (stmt.left.type === "VariableDeclaration") collectVars(stmt.left, varScope, fnInfo) - collectVars(stmt.body, varScope, fnInfo) - break - case "SwitchStatement": - for (const c of stmt.cases) for (const s of c.consequent) collectVars(s, varScope, fnInfo) - break - case "TryStatement": - collectVars(stmt.block, varScope, fnInfo) - collectVars(stmt.handler?.body, varScope, fnInfo) - collectVars(stmt.finalizer, varScope, fnInfo) - break - } - } - - const visitStatement = ( - stmt: Statement | ModuleDeclaration, - scope: Scope, - varScope: Scope, - fnInfo: FunctionInfo, - ): void => { - switch (stmt.type) { - case "ExpressionStatement": - visitExpression(stmt.expression, scope, fnInfo) - break - case "VariableDeclaration": - for (const d of stmt.declarations) { - visitPattern(d.id, scope, fnInfo) - if (d.init) visitExpression(d.init, scope, fnInfo) - } - break - case "ReturnStatement": - case "ThrowStatement": - if (stmt.argument) visitExpression(stmt.argument, scope, fnInfo) - break - case "BlockStatement": - visitBlock(stmt, new Scope(scope), varScope, fnInfo) - break - case "IfStatement": - visitExpression(stmt.test, scope, fnInfo) - visitStatement(stmt.consequent, scope, varScope, fnInfo) - if (stmt.alternate) visitStatement(stmt.alternate, scope, varScope, fnInfo) - break - case "WhileStatement": - case "DoWhileStatement": - visitExpression(stmt.test, scope, fnInfo) - visitStatement(stmt.body, scope, varScope, fnInfo) - break - case "ForStatement": { - const forScope = new Scope(scope) - scopeOfNode.set(stmt, forScope) - if (stmt.init?.type === "VariableDeclaration") { - declareLexical(stmt.init, forScope, fnInfo) - visitStatement(stmt.init, forScope, varScope, fnInfo) - } else if (stmt.init) visitExpression(stmt.init, forScope, fnInfo) - if (stmt.test) visitExpression(stmt.test, forScope, fnInfo) - if (stmt.update) visitExpression(stmt.update, forScope, fnInfo) - visitStatement(stmt.body, forScope, varScope, fnInfo) - break - } - case "ForInStatement": - case "ForOfStatement": { - const forScope = new Scope(scope) - scopeOfNode.set(stmt, forScope) - if (stmt.left.type === "VariableDeclaration") { - declareLexical(stmt.left, forScope, fnInfo) - for (const d of stmt.left.declarations) visitPattern(d.id, forScope, fnInfo) - } else visitPattern(stmt.left, forScope, fnInfo) - visitExpression(stmt.right, forScope, fnInfo) - visitStatement(stmt.body, forScope, varScope, fnInfo) - break - } - case "SwitchStatement": { - visitExpression(stmt.discriminant, scope, fnInfo) - const switchScope = new Scope(scope) - scopeOfNode.set(stmt, switchScope) - hoistStatementList( - stmt.cases.flatMap((c) => c.consequent), - switchScope, - varScope, - fnInfo, - false, - ) - for (const c of stmt.cases) { - if (c.test) visitExpression(c.test, switchScope, fnInfo) - for (const s of c.consequent) visitStatement(s, switchScope, varScope, fnInfo) - } - break - } - case "LabeledStatement": - visitStatement(stmt.body, scope, varScope, fnInfo) - break - case "TryStatement": - visitBlock(stmt.block, new Scope(scope), varScope, fnInfo) - if (stmt.handler) visitCatchClause(stmt.handler, scope, varScope, fnInfo) - if (stmt.finalizer) visitBlock(stmt.finalizer, new Scope(scope), varScope, fnInfo) - break - case "ClassDeclaration": - visitClass(stmt, scope, fnInfo) - break - case "FunctionDeclaration": { - const childFn = visitFunction(stmt, scope, fnInfo.index) - const hoisted = scope.hoistedFunctions.find((h) => h.node === stmt) - if (hoisted) hoisted.fnIndex = childFn.index - break - } - } - } - - const visitBlock = (block: BlockStatement, blockScope: Scope, varScope: Scope, fnInfo: FunctionInfo): void => { - scopeOfNode.set(block, blockScope) - hoistStatementList(block.body, blockScope, varScope, fnInfo, false) - for (const s of block.body) visitStatement(s, blockScope, varScope, fnInfo) - } - - const visitCatchClause = (handler: CatchClause, scope: Scope, varScope: Scope, fnInfo: FunctionInfo): void => { - const catchScope = new Scope(scope) - scopeOfNode.set(handler, catchScope) - if (handler.param) { - for (const name of collectPatternNames(handler.param)) addDecl(catchScope, fnInfo, name, "catch", true) - visitPattern(handler.param, catchScope, fnInfo) - } - visitBlock(handler.body, new Scope(catchScope), varScope, fnInfo) - } - - const visitPattern = (pattern: Pattern, scope: Scope, fnInfo: FunctionInfo): void => { - switch (pattern.type) { - case "Identifier": - unresolved.push({ node: pattern, name: pattern.name, scope, fnIndex: fnInfo.index }) - break - case "AssignmentPattern": - visitPattern(pattern.left, scope, fnInfo) - visitExpression(pattern.right, scope, fnInfo) - break - case "RestElement": - visitPattern(pattern.argument, scope, fnInfo) - break - case "ArrayPattern": - for (const el of pattern.elements) if (el) visitPattern(el, scope, fnInfo) - break - case "ObjectPattern": - for (const prop of pattern.properties) { - if (prop.type === "RestElement") visitPattern(prop.argument, scope, fnInfo) - else { - if (prop.computed) visitExpression(prop.key as Expression, scope, fnInfo) - visitPattern(prop.value, scope, fnInfo) - } - } - break - case "MemberExpression": - visitExpression(pattern, scope, fnInfo) - break - } - } - - const visitExpression = (expr: Expression | AnyNode, scope: Scope, fnInfo: FunctionInfo): void => { - const visit = (child: Expression | AnyNode) => visitExpression(child, scope, fnInfo) - switch (expr.type) { - case "Identifier": - unresolved.push({ node: expr, name: expr.name, scope, fnIndex: fnInfo.index }) - break - case "ThisExpression": - unresolved.push({ node: expr, name: "this", scope, fnIndex: fnInfo.index }) - break - case "FunctionExpression": - case "ArrowFunctionExpression": - visitFunction(expr, scope, fnInfo.index) - break - case "ClassExpression": - visitClass(expr, scope, fnInfo) - break - case "BinaryExpression": - case "LogicalExpression": - visit(expr.left) - visit(expr.right) - break - case "UnaryExpression": - case "UpdateExpression": - case "AwaitExpression": - case "SpreadElement": - visit(expr.argument) - break - case "YieldExpression": - if (expr.argument) visit(expr.argument) - break - case "AssignmentExpression": - visitPattern(expr.left, scope, fnInfo) - visit(expr.right) - break - case "SequenceExpression": - case "TemplateLiteral": - for (const e of expr.expressions) visit(e) - break - case "ConditionalExpression": - visit(expr.test) - visit(expr.consequent) - visit(expr.alternate) - break - case "CallExpression": - case "NewExpression": - if (expr.callee.type !== "Super") visit(expr.callee) - for (const arg of expr.arguments) visit(arg) - break - case "MemberExpression": - if (expr.object.type !== "Super") visit(expr.object) - else supers.push({ node: expr.object, scope, fnIndex: fnInfo.index }) - if (expr.computed) visit(expr.property) - break - case "ChainExpression": - visit(expr.expression) - break - case "ArrayExpression": - for (const el of expr.elements) if (el) visit(el) - break - case "ObjectExpression": - for (const prop of expr.properties) { - if (prop.type === "SpreadElement") visit(prop.argument) - else { - if (prop.computed) visit(prop.key) - visit(prop.value) - // Object literal methods and accessors have the object as their home, for `super`. - if (prop.method || prop.kind !== "init") nodeToFunction.get(prop.value as FunctionExpression)!.flags |= CodeFlags.METHOD - } - } - break - case "TaggedTemplateExpression": - visit(expr.tag) - for (const e of expr.quasi.expressions) visit(e) - break - case "ImportExpression": - visit(expr.source) - if (expr.options) visit(expr.options) - break - } - } - - // The class body sees its own name as an immutable binding; the constructor and methods are functions in it. - function visitClass(node: ClassNode, scope: Scope, fnInfo: FunctionInfo): void { - if (!node.body.body.every(supportedClassMember)) return - const classScope = new Scope(scope) - scopeOfNode.set(node, classScope) - if (node.id) addDecl(classScope, fnInfo, node.id.name, "const", false) - if (node.superClass) visitExpression(node.superClass, classScope, fnInfo) - const methods = node.body.body.filter((m) => m.type === "MethodDefinition") - const ctor = methods.find((m) => m.kind === "constructor")?.value ?? defaultConstructor(node) - classConstructors.set(node, ctor) - const ctorInfo = visitFunction(ctor, classScope, fnInfo.index, node.id?.name ?? "") - ctorInfo.flags |= CodeFlags.CLASS_CONSTRUCTOR | CodeFlags.METHOD - if (node.superClass) { - // `this` starts uninitialized: `super()` binds it, and the return rules read it. - ctorInfo.flags |= CodeFlags.DERIVED - ctorInfo.thisDecl!.used = true - ctorInfo.newTargetDecl = addDecl(ctorInfo.paramScope, ctorInfo, "%newTarget", "newTarget", false) - ctorInfo.newTargetDecl.used = true - } - for (const m of node.body.body) { - if ((m.type !== "MethodDefinition" && m.type !== "PropertyDefinition") || !m.computed) continue - visitExpression(m.key as Expression, classScope, fnInfo) - if (m.type !== "PropertyDefinition") continue - const name = `%key${fieldKeys.size}` - addDecl(classScope, fnInfo, name, "const", false) - fieldKeys.set(m, { type: "Identifier", name, start: m.key.start, end: m.key.end } as Identifier) - } - for (const m of methods) { - if (m.kind === "constructor") continue - visitFunction(m.value, classScope, fnInfo.index).flags |= CodeFlags.METHOD - } - const fields = node.body.body.filter((m) => m.type === "PropertyDefinition") - const instance = fieldInit( - node, - classScope, - fnInfo, - "", - fields.filter((f) => !f.static), - ) - const statics = fieldInit( - node, - classScope, - fnInfo, - "", - fields.filter((f) => f.static), - ) - if (instance || statics) classFieldInits.set(node, { instance, static: statics }) - } - - // `constructor() {}`, or `constructor(...args) { super(...args) }` for a derived class. - function defaultConstructor(node: ClassNode): FunctionExpression { - const at = { start: node.start, end: node.end } - const args = { type: "Identifier", name: "args", ...at } - const superCall = { - type: "ExpressionStatement", - expression: { - type: "CallExpression", - callee: { type: "Super", ...at }, - arguments: [{ type: "SpreadElement", argument: args, ...at }], - optional: false, - ...at, - }, - ...at, - } - return { - type: "FunctionExpression", - id: null, - params: node.superClass ? [{ type: "RestElement", argument: { ...args }, ...at }] : [], - body: { type: "BlockStatement", body: node.superClass ? [superCall] : [], ...at }, - generator: false, - expression: false, - async: false, - ...at, - } as FunctionExpression - } - - // A synthetic method whose body is `this` and the field initializers: the compiler defines each field on `this`. - function fieldInit( - node: ClassNode, - classScope: Scope, - fnInfo: FunctionInfo, - name: string, - fields: Array, - ): FunctionExpression | undefined { - if (fields.length === 0) return undefined - const at = { start: node.start, end: node.end } - const statement = (expression: Expression) => ({ type: "ExpressionStatement", expression, ...at }) - const fn = { - type: "FunctionExpression", - id: null, - params: [], - body: { - type: "BlockStatement", - body: [ - statement({ type: "ThisExpression", ...at } as Expression), - ...fields.flatMap((f) => [ - ...(fieldKeys.has(f) ? [statement(fieldKeys.get(f)!)] : []), - ...(f.value ? [statement(f.value)] : []), - ]), - ], - ...at, - }, - generator: false, - expression: false, - async: false, - ...at, - } as FunctionExpression - fieldInitMembers.set(fn, fields) - visitFunction(fn, classScope, fnInfo.index, name).flags |= CodeFlags.METHOD | CodeFlags.FIELD_INIT - return fn - } - - visitFunction(source.program, undefined, -1) - - const ensureUpvalue = (fnIndex: number, decl: Decl): number => { - const fnInfo = functions[fnIndex]! - const existing = fnInfo.upvalueMap.get(decl) - if (existing !== undefined) return existing - const upvalIndex = fnInfo.upvalues.length - if (fnInfo.parentIndex === decl.fnIndex) fnInfo.upvalues.push({ from: 0, index: -1, decl }) - else fnInfo.upvalues.push({ from: 1, index: ensureUpvalue(fnInfo.parentIndex, decl), decl }) - fnInfo.upvalueMap.set(decl, upvalIndex) - return upvalIndex - } - - const lookupDecl = (scope: Scope | undefined, name: string): Decl | undefined => - scope === undefined ? undefined : (scope.decls.get(name) ?? lookupDecl(scope.parent, name)) - - const refs = new Map() - const thisRefs = new Map() - // Identifiers resolve first, then `this`, so upvalues keep their order. - const resolve = (item: (typeof unresolved)[number]): ResolvedRef => { - const decl = lookupDecl(item.scope, item.name) - if (decl === undefined) return { kind: "global", name: item.name } - decl.used = true - const owner = functions[decl.fnIndex]! - if (decl.kind === "arguments") owner.flags |= CodeFlags.USES_ARGUMENTS | CodeFlags.NEEDS_ARGS - if (decl.kind === "this") owner.flags |= CodeFlags.USES_THIS - if (decl.fnIndex === item.fnIndex) return { kind: "local", decl } - decl.captured = true - return { kind: "upval", upvalIndex: ensureUpvalue(item.fnIndex, decl), decl } - } - for (const item of unresolved) - if (item.node.type !== "ThisExpression") refs.set(item.node as Identifier, resolve(item)) - for (const item of unresolved) if (item.node.type === "ThisExpression") thisRefs.set(item.node, resolve(item)) - // `super` reads the home object of the method it is in, through arrows. - const superRefs = new Map() - for (const item of supers) { - let owner = functions[item.fnIndex]! - while (owner.node.type === "ArrowFunctionExpression") owner = functions[owner.parentIndex]! - if ((owner.flags & CodeFlags.METHOD) === 0) continue - owner.homeDecl ??= addDecl(owner.paramScope, owner, "%home", "home", false) - superRefs.set(item.node, { - home: resolve({ ...item, name: "%home" }), - self: resolve({ ...item, name: "this" }), - }) - } - - // Assign dense local slots per function. A call copies its arguments into the leading slots, so with simple - // parameters each position gets a slot; an earlier duplicate name (`function f(a, a)`) gets a dummy one. - for (const fnInfo of functions) { - const assignSlot = (decl: Decl) => { - if (decl.slot >= 0) return - decl.slot = fnInfo.localNames.length - fnInfo.localNames.push(decl.name) - } - if ((fnInfo.flags & CodeFlags.SIMPLE_PARAMS) !== 0) { - fnInfo.params.forEach((p, i) => { - const name = (p as Identifier).name - const last = fnInfo.params.findLastIndex((q) => (q as Identifier).name === name) - if (last === i) assignSlot(fnInfo.paramScope.decls.get(name)!) - else fnInfo.localNames.push(name) - }) - } else fnInfo.flags |= CodeFlags.NEEDS_ARGS - for (const decl of fnInfo.allDecls) { - if ((decl.kind === "this" || decl.kind === "arguments") && !decl.used) continue - assignSlot(decl) - } - fnInfo.locals = fnInfo.localNames.length - } - - // Patch `from === 0` upvalue indices now that parent local slots are assigned - for (const fnInfo of functions) for (const u of fnInfo.upvalues) if (u.from === 0) u.index = u.decl.slot - - return { - functions, - nodeToFunction, - scopeOfNode, - refs, - thisRefs, - superRefs, - classConstructors, - classFieldInits, - fieldInitMembers, - fieldKeys, - } -} - -const collectPatternNames = (pattern: Pattern, out: Array = []): Array => { - switch (pattern.type) { - case "Identifier": - out.push(pattern.name) - break - case "AssignmentPattern": - collectPatternNames(pattern.left, out) - break - case "RestElement": - collectPatternNames(pattern.argument, out) - break - case "ArrayPattern": - for (const element of pattern.elements) if (element !== null) collectPatternNames(element, out) - break - case "ObjectPattern": - for (const prop of pattern.properties) { - collectPatternNames(prop.type === "RestElement" ? prop.argument : prop.value, out) - } - break - } - return out -} diff --git a/packages/codemode/src/language/data.ts b/packages/codemode/src/language/data.ts deleted file mode 100644 index 8a3dd2f1d32..00000000000 --- a/packages/codemode/src/language/data.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type { Json } from "./snapshot/codec.js" -import type { Interpreter } from "./runtime/interpreter.js" -import { Arr, define, Obj, type Value } from "./runtime/objects.js" - -export type { Json } - -/** Host JSON as program values: objects and arrays are copied, primitives pass through. */ -export const fromJson = (ctx: Interpreter, value: Json | undefined): Value => { - if (value === null || typeof value !== "object") return value - if (Array.isArray(value)) - return new Arr( - ctx.builtins.Array, - value.map((item) => fromJson(ctx, item)), - ) - const copied = new Obj(ctx.builtins.Object) - for (const [key, item] of Object.entries(value)) define(copied, key, fromJson(ctx, item)) - return copied -} diff --git a/packages/codemode/src/language/generators.ts b/packages/codemode/src/language/generators.ts deleted file mode 100644 index d621f8a8e91..00000000000 --- a/packages/codemode/src/language/generators.ts +++ /dev/null @@ -1,498 +0,0 @@ -import { type AstNode, type GeneratorRequestKind, Throw, typeError } from "./runtime/model.js" -import { - type Cursor, - type CustomIterator, - GeneratorObj, - get, - iteratorResult, - Obj, - Opaque, - Position, - type PromiseObj, - type Value, -} from "./runtime/objects.js" -import { requireIteratorMethod, requireIteratorObject } from "./runtime/operations.js" -import { capability } from "./runtime/promises.js" -import { abrupt, type Completion, type GeneratorRequest, Interruption, normal, Resume } from "./runtime/signals.js" -import type { Reaction, Resolving } from "./scheduler.js" -import { internalCode, VmIntrinsic } from "./internal-prelude.js" -import { CodeFlags, Op } from "./opcodes.js" -import { CustomIter, type Frame, Mode, REDO, REDO_ENTERED, type Vm } from "./vm.js" - -/** - * CreateAsyncFromSyncIterator's object: an async iterator over a synchronous one, for `for await` and an async - * generator's `yield*`. Its methods are the `%AsyncFromSyncIterator%` intrinsics, so it is plain data. - */ -export class AsyncFromSyncIterator extends Opaque { - override readonly tag = "AsyncFromSyncIterator" - constructor( - proto: Obj, - /** The synchronous iterator it drives. */ - readonly sync: Cursor, - /** Where it was made, so a failure that rejects one of its promises is located there. */ - readonly site: AstNode, - ) { - super(proto) - } - override get describe() { - return "an iterator" - } -} - -const result = (vm: Vm, value: Value, done: boolean) => iteratorResult(vm.ctx.builtins.Object, value, done) - -// A request reaches a resumed body as a number on its stack (see `RESUME`): its index here. -const REQUEST_KINDS: ReadonlyArray = ["next", "throw", "return"] - -const NO_THROW_METHOD = "The delegated iterator does not provide a throw() method." - -// Hands a resumed body its request: the value, then the kind's number. -const pushRequest = (frame: Frame, request: GeneratorRequest) => { - frame.regs[frame.sp++] = request.value - frame.regs[frame.sp++] = request.kind === "next" ? 0 : request.kind === "throw" ? 1 : 2 -} - -// Takes the generator's body off the job stack, to continue after the instruction at `pc`. -const suspend = (vm: Vm, generator: GeneratorObj, frame: Frame, pc: number, sp: number) => { - generator.frame = frame - frame.pc = pc + 1 - frame.sp = sp - vm.frames.pop() - if (frame.counted) vm.depth-- -} - -// A synchronous generator's step answers the caller now on the stack: a `for...of` waiting at `ITER_STEP` takes the -// value or leaves the loop; any other caller receives an iterator result. -const answerCallerWide = ( - caller: Frame, - code: Int32Array, - pc: number, - prevW: number, - w: number, - value: Value, - done: boolean, -) => { - if (done) { - caller.pc = ((prevW >>> 16) << 16) | (w >>> 16) - return - } - const prev2W = pc > 1 ? code[pc - 2]! : 0 - const slot = - (prev2W & 0xff) === Op.EXTRA - ? ((prev2W >>> 16) << 16) | (prevW & 0xff00) | ((w >>> 8) & 0xff) - : (prevW & 0xff00) | ((w >>> 8) & 0xff) - ;(caller.regs[slot] as CustomIter).done = false - caller.regs[caller.sp++] = value - caller.pc = pc + ((code[pc + 1]! & 0xff) === Op.EXTRA ? 3 : 2) -} - -const answerCaller = (vm: Vm, value: Value, done: boolean) => { - const caller = vm.frames[vm.frames.length - 1]! - const pc = caller.pc - const code = caller.code.code - const w = code[pc]! - if ((w & 0xff) !== Op.ITER_STEP) { - caller.regs[caller.sp++] = result(vm, value, done) - caller.pc = pc + 1 - return - } - const prevW = pc > 0 ? code[pc - 1]! : 0 - if ((prevW & 0xff) === Op.EXTRA) return answerCallerWide(caller, code, pc, prevW, w, value, done) - if (done) { - caller.pc = w >>> 16 - return - } - ;(caller.regs[(w >>> 8) & 0xff] as CustomIter).done = false - caller.regs[caller.sp++] = value - caller.pc = pc + 2 -} - -/** Generator.prototype.next/return/throw: the body runs on the caller's job stack until it yields, returns, or throws. */ -export const generatorStep = ( - vm: Vm, - generator: GeneratorObj, - kind: GeneratorRequestKind, - value: Value, -): Value | Resume => { - if (generator.state === "executing") { - throw typeError( - generator.proto === vm.ctx.builtins.IteratorHelper - ? "Iterator helper is already running." - : "Generator is already running.", - ) - } - if (generator.state === "suspendedStart" && kind !== "next") generator.state = "completed" - if (generator.state === "completed") { - if (kind === "throw") throw new Throw(value) - return result(vm, kind === "return" ? value : undefined, true) - } - generator.state = "executing" - return new Resume(generator, { kind, value }) -} - -/** - * AsyncGenerator.prototype.next/return/throw: queue the request with its promise, and run the body now if it is - * waiting for one. A request that arrives while the body runs is answered when the body reaches it. - */ -export const generatorRequest = ( - vm: Vm, - thisValue: Value, - kind: GeneratorRequestKind, - value: Value, -): Value | Resume => { - const resolving = vm.scheduler.resolving(vm.scheduler.newPromise()) - const promise = resolving.promise - if (!(thisValue instanceof GeneratorObj) || !thisValue.asynchronous) { - resolving.reject(typeError(`AsyncGenerator.prototype.${kind} called on incompatible receiver.`)) - return promise - } - const generator = thisValue - const state = generator.state - if (kind === "next" && state === "completed") { - resolving.resolve(result(vm, undefined, true)) - return promise - } - if (kind === "throw") { - if (state === "suspendedStart") generator.state = "completed" - if (generator.state === "completed") { - resolving.reject(new Throw(value)) - return promise - } - } - const queued = { kind, value } - generator.queue.push({ request: queued, resolving }) - if (kind === "return" && (state === "suspendedStart" || state === "completed")) { - generator.state = "awaiting-return" - awaitReturn(vm, generator) - return promise - } - if (state !== "suspendedStart" && state !== "suspendedYield") return promise - generator.state = "executing" - return new Resume(generator, queued) -} - -// AsyncGeneratorCompleteStep: answer the oldest request. -const completeStep = (vm: Vm, generator: GeneratorObj, completion: Completion, done: boolean) => { - const next = generator.queue.shift()! - if (completion.ok) next.resolving.resolve(result(vm, completion.value as Value, done)) - else next.resolving.reject(completion.error) -} - -// AsyncGeneratorDrainQueue: once the body has ended, answer the remaining requests in order. -const drainQueue = (vm: Vm, generator: GeneratorObj) => { - generator.state = "draining" - while (true) { - const next = generator.queue[0] - if (next === undefined) { - generator.state = "completed" - return - } - if (next.request.kind === "return") { - generator.state = "awaiting-return" - return awaitReturn(vm, generator) - } - completeStep( - vm, - generator, - next.request.kind === "throw" ? abrupt(new Throw(next.request.value)) : normal(undefined), - true, - ) - } -} - -// AsyncGeneratorAwaitReturn: a `return(value)` on an ended or unstarted generator settles once `value` does. -const awaitReturn = (vm: Vm, generator: GeneratorObj) => { - try { - vm.scheduler.then(vm.scheduler.promiseResolve(generator.queue[0]!.request.value), { - kind: "awaitReturn", - generator, - }) - } catch (error) { - finishAwaitReturn(vm, generator, abrupt(error)) - } -} - -/** The `awaitReturn` reaction: answers the `return` request with how its value settled, then drains the queue. */ -export const finishAwaitReturn = (vm: Vm, generator: GeneratorObj, completion: Completion) => { - completeStep(vm, generator, completion, true) - drainQueue(vm, generator) -} - -export const execGeneratorStart = (vm: Vm, frame: Frame, pc: number, sp: number): void => { - const fn = frame.fn! - const isAsync = (frame.code.flags & CodeFlags.ASYNC) !== 0 - const proto = get(fn, "prototype") - const builtins = vm.ctx.builtins - const gen = new GeneratorObj( - proto instanceof Obj ? proto : isAsync ? builtins.AsyncGenerator : builtins.Generator, - isAsync, - ) - gen.state = "suspendedStart" - frame.mode = Mode.GENERATOR - frame.target = gen - suspend(vm, gen, frame, pc, sp) - const caller = vm.frames[vm.frames.length - 1]! - caller.regs[caller.sp++] = gen - caller.pc++ -} - -export const execYield = (vm: Vm, frame: Frame, pc: number, sp: number): boolean => { - const v = frame.regs[--sp] as Value - const gen = frame.target as GeneratorObj - if (!gen.asynchronous) { - gen.state = "suspendedYield" - suspend(vm, gen, frame, pc, sp) - answerCaller(vm, v, false) - return true - } - completeStep(vm, gen, normal(v), false) - const next = gen.queue[0] - if (next !== undefined) { - frame.sp = sp - frame.pc = pc + 1 - pushRequest(frame, next.request) - return false - } - gen.state = "suspendedYield" - suspend(vm, gen, frame, pc, sp) - vm.deliverAnswer(frame) - return true -} - -export const execResume = (frame: Frame, bx: number, pc: number, sp: number): number => { - const kind = frame.regs[--sp] as number - if (kind === 0) { - frame.sp = sp - return bx - } - if (kind === 1) { - const errVal = frame.regs[--sp] as Value - frame.pc = pc - frame.sp = sp - throw new Throw(errVal) - } - frame.sp = sp - return pc + 1 -} - -const synchronous = (frame: Frame): boolean => - frame.mode === Mode.CALLER || - frame.mode === Mode.REDO || - frame.mode === Mode.CONSTRUCT || - (frame.mode === Mode.GENERATOR && !(frame.target as GeneratorObj).asynchronous) - -export const execAwait = (vm: Vm, frame: Frame, a: number, pc: number, sp: number): void => { - const v = frame.regs[--sp] as Value - frame.pc = pc - frame.sp = sp - const promise = vm.scheduler.promiseResolve(v) - const site = a === 1 ? undefined : frame.code.siteAt(pc) - frame.pc = pc + 1 - let bIdx = vm.frames.length - 1 - // Only `$vmHostWait` awaits under synchronous code (a host call waiting on its arguments): a getter an iterator op - // runs (`Mode.REDO`) and a synchronous generator's body run inside their caller's job, so the await parks it all. - while (bIdx > 0 && synchronous(vm.frames[bIdx]!)) bIdx-- - const cut = vm.frames.splice(bIdx) - for (const f of cut) { - if (f.counted) vm.depth-- - } - const root = cut[0]! - const result: Value = - root.mode === Mode.ASYNC || root.mode === Mode.REJECT_ONLY - ? (root.target as Resolving).promise - : root.mode === Mode.GENERATOR - ? (root.target as GeneratorObj).queue[0]?.resolving.promise - : undefined - vm.deliverAnswer(root) - vm.scheduler.park(cut, promise, site, result) -} - -export const execYstar = (vm: Vm, frame: Frame, itSlot: number, bx: number, pc: number, sp: number): number => { - const kind = frame.regs[sp - 1] as number - const recv = frame.regs[sp - 2] as Value - const rec = frame.regs[itSlot] as CustomIter - const site = frame.code.siteAt(pc) ?? frame.origin - if (kind === 0) { - frame.regs[sp - 2] = rec.iterator - frame.regs[sp - 1] = rec.next - frame.regs[sp] = recv - frame.sp = sp + 1 - return bx - } - const methodName = REQUEST_KINDS[kind]! - const method = vm.redoRead(frame, rec.iterator, methodName, rec.iterator, pc, sp, []) - if (method === REDO) return REDO_ENTERED - if (method === undefined || method === null) { - frame.sp = sp - 1 - return pc + 1 - } - const callable = requireIteratorMethod(method, `Iterator ${methodName}`, site) - frame.regs[sp - 2] = rec.iterator - frame.regs[sp - 1] = callable - frame.regs[sp] = recv - frame.sp = sp + 1 - return bx -} - -export const execYstarResult = (vm: Vm, frame: Frame, kindSlot: number, bx: number, pc: number, sp: number): number => { - const res = frame.regs[sp - 1] as Value - const kind = frame.regs[kindSlot] as number - const site = frame.code.siteAt(pc) ?? frame.origin - const obj = requireIteratorObject(res, `Iterator ${REQUEST_KINDS[kind]}() result`, site) - const reads: Array = [] - const done = vm.redoRead(frame, obj, "done", obj, pc, sp, reads) - if (done === REDO) return REDO_ENTERED - const value = vm.redoRead(frame, obj, "value", obj, pc, sp, reads) - if (value === REDO) return REDO_ENTERED - frame.regs[sp - 1] = value - return done ? bx : pc + 1 -} - -/** Puts a suspended generator's body back on the job stack, handing it `request` unless it has not started yet. */ -export const resumeVmGenerator = (vm: Vm, gen: GeneratorObj, request: GeneratorRequest): void => { - const f = gen.frame! - gen.frame = undefined - if (gen.asynchronous) f.answer = gen.queue[0]!.resolving.promise - if ((f.code.code[f.pc - 1]! & 0xff) !== Op.GENERATOR_START) pushRequest(f, request) - if (f.counted) vm.depth++ - vm.frames.push(f) -} - -export const completeGeneratorReturn = (vm: Vm, frame: Frame, v: Value): void => { - const gen = frame.target as GeneratorObj - vm.frames.pop() - gen.frame = undefined - if (!gen.asynchronous) { - gen.state = "completed" - vm.release(frame) - answerCaller(vm, v, true) - return - } - vm.deliverAnswer(frame) - vm.release(frame) - completeStep(vm, gen, normal(v), true) - drainQueue(vm, gen) -} - -export const unwindGenerator = (vm: Vm, frame: Frame, error: unknown): boolean => { - const gen = frame.target as GeneratorObj - gen.frame = undefined - if (!gen.asynchronous) { - gen.state = "completed" - vm.release(frame) - return false - } - vm.deliverAnswer(frame) - vm.release(frame) - completeStep(vm, gen, abrupt(error), true) - drainQueue(vm, gen) - return true -} - -const settleAdapterStep = ( - vm: Vm, - adapter: AsyncFromSyncIterator, - value: Value, - done: boolean, - closeOnRejection: boolean, - made: Resolving, -): void => { - const reaction: Reaction = { - kind: "asyncFromSync", - made, - done, - close: closeOnRejection ? adapter.sync : undefined, - site: adapter.site, - } - let wrapper: PromiseObj - try { - wrapper = vm.scheduler.promiseResolve(value) - } catch (error) { - if (!done && closeOnRejection && adapter.sync !== undefined && !(error instanceof Interruption)) { - vm.scheduler.enqueue({ kind: "reaction", reaction, settled: abrupt(error) }) - } else { - made.reject(error) - } - return - } - vm.scheduler.then(wrapper, reaction) -} - -export const handleAdapterPush = (vm: Vm, callerFrame: Frame, slots: Array): number => { - const adapter = slots[0] as AsyncFromSyncIterator - const kind = slots[1] as GeneratorRequestKind - const args = slots[2] as Array - const site = adapter.site - const made = capability(vm.ctx, site) - const sync = adapter.sync - if (sync instanceof Position) { - if (kind === "next") { - const step = sync.step() - settleAdapterStep(vm, adapter, step.value, step.done, true, made) - } else if (kind === "return") made.resolve(result(vm, args[0], true)) - else made.reject(typeError(NO_THROW_METHOD, site)) - callerFrame.regs[callerFrame.sp++] = made.promise - return 0 - } - vm.pushInternal( - internalCode("$vmAsyncFromSync"), - [adapter, kind, args.length > 0, args[0]], - site, - Mode.REJECT_ONLY, - made, - made.promise, - ) - return 1 -} - -export const registerGeneratorIntrinsics = (map: Map, vm: Vm): void => { - const ctx = vm.ctx - const builtins = ctx.builtins - const add = (name: string, fn: (args: Array) => Value) => { - map.set(name, new VmIntrinsic(name, fn)) - } - // The `$vmAsyncFromSync` frame running now settles this. - const made = () => vm.frames[vm.frames.length - 1]!.target as Resolving - - add("$AfsRequireObj", ([syncVal]) => requireIteratorObject(syncVal, "Iterator method result", vm.currentSite())) - - add("$WrapAsyncFromSync", ([obj, nextVal]) => { - const site = vm.currentSite() - const next = requireIteratorMethod(nextVal, "Iterator next", site) - return new AsyncFromSyncIterator( - builtins.AsyncFromSyncIterator, - { iterator: obj as Obj, next, asynchronous: false }, - site!, - ) - }) - - add("$AfsGetIter", ([adapter]) => ((adapter as AsyncFromSyncIterator).sync as CustomIterator).iterator) - - add("$AfsGetNext", ([adapter]) => ((adapter as AsyncFromSyncIterator).sync as CustomIterator).next) - - // An iterator method the prelude read: undefined when absent, else it must be a function. - add("$AfsMethod", ([adapter, method, kind]) => { - const site = (adapter as AsyncFromSyncIterator).site - if (method === undefined || method === null) return undefined - return requireIteratorMethod(method, `Iterator ${kind as string}`, site) - }) - - add("$AfsCheckObj", ([adapter, res, kind]) => - requireIteratorObject(res, `Iterator ${kind as string}() result`, (adapter as AsyncFromSyncIterator).site), - ) - - add("$AfsResolveDone", ([value]) => { - made().resolve(result(vm, value, true)) - return undefined - }) - - add("$AfsRejectNoThrow", ([adapter]) => { - made().reject(typeError(NO_THROW_METHOD, (adapter as AsyncFromSyncIterator).site)) - return undefined - }) - - add("$AfsSettle", ([adapter, value, done, close]) => { - settleAdapterStep(vm, adapter as AsyncFromSyncIterator, value, Boolean(done), Boolean(close), made()) - return undefined - }) -} diff --git a/packages/codemode/src/language/host-function.ts b/packages/codemode/src/language/host-function.ts deleted file mode 100644 index 78547ac8368..00000000000 --- a/packages/codemode/src/language/host-function.ts +++ /dev/null @@ -1,154 +0,0 @@ -export * as Host from "./host-function.js" - -import type { Effect } from "effect" -import type { Json } from "./data.js" -import { HostFailure } from "./runtime/model.js" - -// Host functions a program calls as globals. Arguments cross into the host as copies (`Date`, `Map`, `Set`, -// `Uint8Array`, `URL`, `Headers`, errors, plain data), and results cross back the same way; a function inside a -// result is callable too. A host function may return a value, a Promise, or an Effect, and an Effect's requirements -// join the runtime's environment. - -/** What every call of a host function gets. */ -export type Call = { - /** The call's key, `:`: the same across a suspended run's resumes. */ - readonly key: string - /** Whether the run is being suspended: an interruption now detaches the call instead of ending it. */ - readonly suspending: () => boolean -} - -/** What every call of a durable function gets: also the arguments it was called with, as they crossed. */ -export type DurableCall = Call & { readonly args: ReadonlyArray } - -/** - * Lets a saved run keep the functions inside values a host function returned: `encode` gets such a value and gives - * plain data (JSON values and `Uint8Array`s); `decode` gets that data back on resume and gives a value of the same - * shape, whose functions the program's copies call from then on. Without it, those functions are lost on resume. - */ -export type Snapshot = { - readonly encode: (value: unknown) => unknown - readonly decode: (data: unknown) => unknown -} - -/** - * How a call reaches the program: - * - `sync`: the program waits for the function. An Effect runs until it ends; whatever is still pending then (a - * returned Promise, or a Promise or Effect the Effect produced) reaches the program as a promise. - * - `async`: the program gets a promise at once, and the function runs once the program's current step ends. - * - `sync-thenable`: as `sync`, and an object result also has hidden `then`, `catch` and `finally`, so the program can - * use it directly or await it. - */ -export type Type = "sync" | "async" | "sync-thenable" - -export type Options = - | { - readonly type?: "sync" | "sync-thenable" - readonly idempotent?: false - readonly snapshot?: Snapshot | undefined - /** - * Lets a program call the function with `new`, as it would a class. `new` calls it the same way a plain call - * does, and the program gets what it returns. - */ - readonly constructible?: boolean - /** - * Lets the program pass back a function that was inside a result, on its own or inside an argument: it arrives - * as the host function itself, and the run can't be suspended until the call completes. Without it, such a - * function is treated like any other function in an argument (see `Runtime.Translate`). - */ - readonly takesFunctions?: boolean - } - | { - readonly type: "async" - /** - * Safe to run twice: a suspend interrupts a call in progress, and the resumed run calls it again with the same - * key. Without it, a suspend fails while a call is in progress. - */ - readonly idempotent?: boolean - readonly snapshot?: Snapshot | undefined - readonly constructible?: boolean - readonly takesFunctions?: boolean - } - -/** A host function; see `fn`. */ -export class Fn { - declare readonly requirements?: (_: never) => R - constructor( - readonly run: (args: ReadonlyArray, call: Call) => unknown, - readonly type: Type, - readonly idempotent: boolean, - readonly snapshot: Snapshot | undefined, - readonly constructible = false, - readonly takesFunctions = false, - ) {} -} - -/** A host function whose work keeps running across a suspend; see `durableFn`. */ -export class DurableFn { - declare readonly requirements?: (_: never) => R - constructor( - readonly start: (args: ReadonlyArray, call: Call) => Effect.Effect, - readonly wait: (data: Json, call: DurableCall) => Effect.Effect, - readonly cancel: (data: Json, call: DurableCall) => Effect.Effect, - ) {} -} - -/** A lazy object of host functions, addressed by path; see `namespace`. */ -export class Namespace { - declare readonly requirements?: (_: never) => R - constructor( - readonly keys: (path: ReadonlyArray) => ReadonlyArray, - readonly resolve: (path: ReadonlyArray) => Fn | DurableFn | HostFailure, - ) {} -} - -export { HostFailure as Failure } - -type Requirements = A extends Effect.Effect ? R : never - -/** A host function: `f` gets the program's arguments, as they crossed, and the call. */ -export const fn = , call: Call) => unknown>( - f: F, - options: Options = {}, -): Fn>> => - new Fn( - f, - options.type ?? "sync", - options.type === "async" && options.idempotent === true, - options.snapshot, - options.constructible === true, - options.takesFunctions === true, - ) - -/** - * A host function whose work keeps running across a suspend. `start` begins it and gives JSON data, kept in a saved - * run; `wait(data)` runs right after, and again after a resume, for the result. `cancel(data)` runs only when the run - * is interrupted, or ends with the work still running. The program always gets a promise. - */ -export const durableFn = (options: { - readonly start: (args: ReadonlyArray, call: Call) => Effect.Effect - readonly wait: (data: Data, call: DurableCall) => Effect.Effect - readonly cancel: (data: Data, call: DurableCall) => Effect.Effect -}): DurableFn => - new DurableFn( - options.start, - options.wait as (data: Json, call: DurableCall) => Effect.Effect, - options.cancel as (data: Json, call: DurableCall) => Effect.Effect, - ) - -/** - * A lazy object of host functions, for catalogs too large to build as objects. `keys(path)` lists the names under a - * path, for `Object.keys` and `for...in`; `resolve(path)` gives the function a call reaches, or a failure (see - * `missing`) the call throws. Any path can be read, so `ns.a.b` is a path whether or not anything is there. - */ -export const namespace = (options: { - readonly keys: (path: ReadonlyArray) => ReadonlyArray - readonly resolve: (path: ReadonlyArray) => Fn | DurableFn | HostFailure -}): Namespace => new Namespace(options.keys, options.resolve) - -/** A failure with its own diagnostic `kind` and `suggestions`, to throw or fail with from a host function. */ -export const fail = (kind: string, message: string, suggestions?: ReadonlyArray): HostFailure => - new HostFailure(kind, message, suggestions) - -/** What `resolve` gives for a path with no function: calling it throws this failure. */ -export const missing = (message: string, suggestions?: ReadonlyArray, kind = "ExecutionFailure"): HostFailure => - new HostFailure(kind, message, suggestions) diff --git a/packages/codemode/src/language/host.ts b/packages/codemode/src/language/host.ts deleted file mode 100644 index ac3dae824bf..00000000000 --- a/packages/codemode/src/language/host.ts +++ /dev/null @@ -1,299 +0,0 @@ -import type { Code } from "./code.js" -import { DurableFn, Fn } from "./host-function.js" -import type { Interpreter } from "./runtime/interpreter.js" -import type { AstNode, Diagnostic } from "./runtime/model.js" -import { internalCode } from "./internal-prelude.js" -import { Arr, type PromiseObj, reads, type Value } from "./runtime/objects.js" -import { promiseLike } from "./runtime/promises.js" -import { type Completion, Prefetch } from "./runtime/signals.js" -import { HostCall, type HostPolicy, Resolving } from "./scheduler.js" -import { type FrameMode, Mode } from "./vm.js" - -// The VM's side of host work (plan §4.10): calls to host functions, the host calls they queue, and the blocking call -// a job may wait on. - -/** What host calls need from the promise scheduler. */ -export type Promises = { - newPromise(): PromiseObj - resolving(promise: PromiseObj, site?: AstNode): Resolving - /** Unhandled rejections, in promise creation order. */ - diagnostics(): Array -} - -/** A native's answer asking the VM to stop the job until the blocking host call it queued completes. */ -export const BLOCK: unique symbol = Symbol("vm.block") -/** A host operation pushed an internal frame that produces its result. */ -export const ENTERED: unique symbol = Symbol("vm.entered") - -/** A `Prefetch`: the arguments hold program getters to run first, and then the call is made again (`$vmReplay`). */ -export type HostResult = Value | typeof BLOCK | typeof ENTERED | Prefetch - -/** What the VM gives host operations: its runtime, and a way to run an internal prelude function at the call. */ -export type HostVm = { - readonly ctx: Interpreter - /** - * Runs an internal prelude function at the call `origin`; its result is the call's. In another `mode` than `CALLER`, - * it settles `target`, and the call's result is `answer`: in `REJECT_ONLY` mode, a failure in it rejects `target`. - */ - pushInternal( - code: Code, - args: ReadonlyArray, - origin: AstNode | undefined, - mode?: FrameMode, - target?: unknown, - answer?: Value, - ): unknown -} - -/** Where a host function is, and how its calls are named and saved. */ -export type HostTarget = { - /** How the program names it in errors: `fetch`, `fs.readFile`, `api.issues.list`. */ - readonly label: string - /** Where it is among the run's host globals, so a resumed run can find it again; none inside a result. */ - readonly path: ReadonlyArray | undefined - /** The host function whose `snapshot` hooks save the values this call returns, by label; see `Host.Snapshot`. */ - readonly owner: string | undefined -} - -type Delivery = { readonly call: HostCall; readonly completion: Completion } - -/** Visited nodes a native fast path may spend before it hands the work to the prelude walk, which slices. */ -export const VISIT_BUDGET = 2048 - -/** - * The host calls of one run: queued (written ahead, for the driver to start at the next stop), running, completed and - * waiting in the inbox, and the blocking call the current job waits on. Ids count up in program order, and every call - * of a host function takes one, so its key is `:`. - */ -export class HostCalls { - /** Names this run's host calls (`:`). */ - runId = "" - queued: Array = [] - readonly running = new Map() - readonly inbox: Array = [] - nextID = 0 - /** The blocking call the job on the stack waits on. */ - blocked: HostCall | undefined = undefined - /** A completed blocking call's outcome, which continues the job on the stack before anything else runs. */ - input: { readonly call: HostCall; readonly completion: Completion } | undefined = undefined - - constructor( - private readonly ctx: Interpreter, - readonly promises: Promises, - ) {} - - /** - * Calls a host function from the program, which reached it as `callee`. Its arguments cross to the host now. An - * `async` or durable function's call is queued and the program gets its promise; a failure crossing rejects it. Any - * other is called now: its value crosses back at once, a Promise it returned is a promise, and an Effect blocks the - * job until it completes. When the runtime awaits promises in arguments and one hasn't fulfilled, the call waits for - * them (see `wait`) first. - */ - call( - fn: Fn | DurableFn, - values: Array, - site: AstNode | undefined, - target: HostTarget, - callee: Value, - ): HostResult { - const hosts = this.ctx.hosts! - const waiting: Array = [] - // The host functions that cross back among the arguments, when the function takes them. - const back: Array | undefined = fn instanceof Fn && fn.takesFunctions ? [] : undefined - // Program getters in the arguments run first, as program code, before anything else happens for the call: no - // promise, no call id. - const crossed = this.cross(values, target.label, waiting, back) - const async = fn instanceof DurableFn || fn.type === "async" - // An async call reads its getters in a frame that settles its promise, so a getter that throws rejects it. - if (crossed instanceof Prefetch && async && reads.list === undefined) return this.read(crossed, callee, values, site) - if (crossed instanceof Prefetch) return crossed - if (async) { - const resolving = this.promises.resolving(this.promises.newPromise(), site) - if (!crossed.ok) { - resolving.reject(crossed.error) - return resolving.promise - } - if (waiting.length > 0) return this.wait(waiting, callee, values, site, resolving) - const policy = fn instanceof DurableFn ? "durable" : fn.idempotent ? "idempotent" : "async" - const call = this.queue(target, policy, crossed.args, false, resolving, site) - call.fn = fn - call.holdsFunctions = back !== undefined && back.length > 0 - return resolving.promise - } - if (!crossed.ok) throw crossed.error - const args = crossed.args - if (waiting.length > 0) return this.wait(waiting, callee, values, site) - const id = this.nextID++ - const result = hosts.invoke(fn, args, `${this.runId}:${id}`, target.label) - if (result.kind === "value") { - const value = hosts.fromHost(result.value, target.label, target.owner) - return fn.type === "sync-thenable" ? promiseLike(this.ctx, value) : value - } - if (result.kind === "pending") return this.pending(target, result.work, site, id) - const call = new HostCall(id, `${this.runId}:${id}`, target, fn.type, [], true, undefined, site) - call.work = result.work - this.queued.push(call) - this.blocked = call - return BLOCK - } - - // Copies the arguments to the host, reading program getters ahead (see `withReads`): a Prefetch while some are - // still to run, else the copy or why it failed. - private cross( - values: Array, - label: string, - waiting: Array, - back: Array | undefined, - ): - | { readonly ok: true; readonly args: ReadonlyArray } - | { readonly ok: false; readonly error: unknown } - | Prefetch { - const outer = reads.missing - reads.missing = undefined - reads.depth++ - try { - const args = this.ctx.hosts!.toHost(values, label, waiting, back) - return reads.missing !== undefined ? new Prefetch(reads.missing) : { ok: true, args } - } catch (error) { - return reads.missing !== undefined ? new Prefetch(reads.missing) : { ok: false, error } - } finally { - reads.depth-- - reads.missing = outer - } - } - - // Waits in the program for the promises, then calls `callee` again with the same arguments, which cross with their - // values now, and the getter values read so far. A sync function's call waits where it is, as an `await` would; an - // async one's settles `resolving`. - private wait( - promises: Array, - callee: Value, - values: Array, - site: AstNode | undefined, - resolving?: Resolving, - ): HostResult { - const builtins = this.ctx.builtins - this.ctx.vm.pushInternal( - internalCode("$vmHostWait"), - [ - new Arr(builtins.Array, promises), - callee, - new Arr(builtins.Array, values), - reads.list ?? new Arr(builtins.Array, []), - ], - site, - resolving === undefined ? Mode.CALLER : Mode.ASYNC, - resolving, - resolving?.promise, - ) - return ENTERED - } - - // Runs an async call's program getters, then the call again (`$vmReplay`), in a frame that settles the call's promise. - private read(prefetch: Prefetch, callee: Value, values: Array, site: AstNode | undefined): HostResult { - const builtins = this.ctx.builtins - const resolving = this.promises.resolving(this.promises.newPromise(), site) - this.ctx.vm.pushInternal( - internalCode("$vmReplay"), - [ - callee, - undefined, - new Arr(builtins.Array, values), - false, - new Arr(builtins.Array, []), - new Arr(builtins.Array, []), - prefetch as unknown as Value, - ], - site, - Mode.ASYNC, - resolving, - resolving.promise, - ) - return ENTERED - } - - // What a host function left pending (a Promise, or an Effect): the program holds a promise for it. - private pending(target: HostTarget, work: unknown, site: AstNode | undefined, id = this.nextID++): PromiseObj { - const resolving = this.promises.resolving(this.promises.newPromise(), site) - const call = new HostCall(id, `${this.runId}:${id}`, target, "sync", [], false, resolving, site) - call.work = work - this.queued.push(call) - return resolving.promise - } - - private queue( - target: HostTarget, - policy: HostPolicy, - args: ReadonlyArray, - blocking: boolean, - resolving: Resolving | undefined, - site: AstNode | undefined, - ): HostCall { - const id = this.nextID++ - const call = new HostCall(id, `${this.runId}:${id}`, target, policy, args, blocking, resolving, site) - this.queued.push(call) - return call - } - - /** Continues the job stopped at a blocking call with its outcome. */ - resume(input: { readonly call: HostCall; readonly completion: Completion }): HostResult { - const call = input.call - const completion = input.completion - const hosts = this.ctx.hosts! - if (!completion.ok) throw hosts.failure(completion.error, call.label) - if (hosts.isPending(completion.value)) return this.pending(call, completion.value, call.site) - const value = hosts.fromHost(completion.value, call.label, call.owner) - return call.policy === "sync-thenable" ? promiseLike(this.ctx, value) : value - } - - /** Hands the queued calls to the driver: they are running from now on. */ - handOver(): Array { - const calls = this.queued - this.queued = [] - for (const call of calls) this.running.set(call.id, call) - return calls - } - - complete(id: number, completion: Completion): void { - const call = this.running.get(id) - if (call === undefined) return - this.running.delete(id) - // Its outcome is all that is left: the host function, its arguments, and what it returned are dropped. - call.data = undefined - call.fn = undefined - call.work = undefined - call.args = [] - if (call.blocking) { - call.status = "completed" - if (this.blocked !== call) return - this.blocked = undefined - this.input = { call, completion } - return - } - this.inbox.push({ call, completion }) - } - - /** Settles the oldest completed concurrent call's promise; false when the inbox is empty. */ - deliver(): boolean { - const delivery = this.inbox.shift() - if (delivery === undefined) return false - const call = delivery.call - const completion = delivery.completion - call.status = "completed" - const resolving = call.resolving! - const hosts = this.ctx.hosts! - if (!completion.ok) { - resolving.reject(hosts.failure(completion.error, call.label)) - return true - } - let value: Value - try { - value = hosts.fromHost(completion.value, call.label, call.owner) - } catch (error) { - resolving.reject(error) - return true - } - resolving.resolve(value) - return true - } -} diff --git a/packages/codemode/src/language/index.ts b/packages/codemode/src/language/index.ts deleted file mode 100644 index 45336a00dca..00000000000 --- a/packages/codemode/src/language/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -export * as Language from "./index.js" - -// The language layer: the compiler, VM, runtime, standard library, snapshots, and the Effect driver. It knows nothing -// about tools; a host gives programs its functions through `Host` and runs them with `Runtime.make`. -export { Host } from "./host-function.js" -export { Runtime } from "./runtime.js" -export { StreamingResponse } from "./streaming-response.js" -export { fromBytes, SnapshotError, toBytes, type Snapshot, type SnapshotHeader } from "./snapshot/snapshot.js" -export { SuspendError } from "./runtime/execute.js" -export { globalNames } from "./runtime/globals.js" -export type { Diagnostic, DiagnosticKind } from "./runtime/model.js" -export type { Json } from "./data.js" diff --git a/packages/codemode/src/language/internal-prelude.ts b/packages/codemode/src/language/internal-prelude.ts deleted file mode 100644 index 970d7aec840..00000000000 --- a/packages/codemode/src/language/internal-prelude.ts +++ /dev/null @@ -1,625 +0,0 @@ -import { fromJson, type Json } from "./data.js" -import { conversions } from "./runtime/callback.js" -import type { Builtins } from "./runtime/intrinsics.js" -import { checkStringLength, MAX_VALUE_DEPTH } from "./runtime/limits.js" -import { invalidData, rangeError, typeError } from "./runtime/model.js" -import { - Arr, - Builtin, - Bytes, - Callable, - coerceToNumber, - coerceToString, - DateObj, - ErrorObj, - get, - type Getter, - HeadersObj, - HostNamespace, - isProgramAccessor, - reads, - lookup, - keys, - type NativeResult, - Obj, - PromiseObj, - SetObj, - URLSearchParamsObj, - type Value, -} from "./runtime/objects.js" -import { applyBinaryOperator, hasInstance, operatorConversion, propertyKey } from "./runtime/operations.js" -import { isOpaque, typeofValue } from "./runtime/references.js" -import { Convert, normal, Prefetch } from "./runtime/signals.js" -import type { Resolving } from "./scheduler.js" -import type { Code } from "./code.js" -import { builtinCodes } from "./prelude/bytecode.js" -import { UnaryOp } from "./opcodes.js" -import { type Vm, VmInternalFn } from "./vm.js" - -/** - * Lightweight internal callable for VM-only `$` intrinsics. Does not extend `Obj` or `Native`, - * so it never touches `builtins.Function`, `nativeRule.sealed`, or static intrinsic numbering. - */ -export class VmIntrinsic { - constructor( - readonly name: string, - readonly call: (args: Array) => NativeResult, - ) {} -} - -export const INTERNAL_SOURCE = String.raw` -function $vmToPrimitive(v, hint) { - if (!$IsDataObj(v)) return v - const first = hint === "string" || (hint === "default" && $IsDate(v)) ? "toString" : "valueOf" - const second = first === "toString" ? "valueOf" : "toString" - const m1 = v[first] - if ($IsCallableAny(m1)) { - const r1 = $Call(m1, v) - if (!$IsObj(r1)) return r1 - } - const m2 = v[second] - if ($IsCallableAny(m2)) { - const r2 = $Call(m2, v) - if (!$IsObj(r2)) return r2 - } - $Throw("TypeError", "Cannot convert object to primitive value.") -} - -function $vmToKey(v) { - return $PropKey($vmToPrimitive(v, "string")) -} - -function $vmToString(v) { - return $CoerceToString($vmToPrimitive(v, "string")) -} - -function $vmToNumeric(incFlag, v) { - return $ApplyToNumeric(incFlag, $vmToPrimitive(v, "number")) -} - -function $vmInc(incFlag, v) { - const n = $ApplyToNumeric(incFlag, $vmToPrimitive(v, "number")) - return incFlag === 0 ? n + 1 : n - 1 -} - -function $vmUnary(sub, v) { - return $ApplyUnary(sub, $vmToPrimitive(v, "number")) -} - -function $vmBinary(op, lhs, rhs) { - const kind = $OpConvKind(op, lhs, rhs) - if (kind === 0) return $ApplyBinary(op, lhs, rhs) - if (kind === 1) { - const key = $vmToPrimitive(lhs, "string") - return $ApplyBinary(op, key, rhs) - } - const hint = kind === 2 ? "default" : "number" - const l = $vmToPrimitive(lhs, hint) - const r = $vmToPrimitive(rhs, hint) - return $ApplyBinary(op, l, r) -} - -// A write that reached a program setter: the assignment's value is what was assigned, not what the setter returns. -function $vmSet(setter, receiver, value) { - $Call(setter, receiver, value) - return value -} - -function $vmInstanceof(lhs, rhs) { - return $HasInstance(lhs, rhs.prototype) -} - -// A getter an iterator op met; the op runs again with its value (see Mode.REDO). -function $vmRedo(getter, receiver) { - return $Call(getter, receiver) -} - -// A promise resolved with an object whose then is a program getter: the getter runs in this job. -function $vmThenableGet(thenable, resolve, reject) { - const then = thenable.then - if ($IsFunction(then)) $Call(then, thenable, resolve, reject) - else $FulfillWith(thenable) -} - -// Spread and rest from a source with program getters: each getter runs once, in key order, and the copy is data. -function $vmCopyDataProps(target, source, excluded) { - const keys = $OwnKeys(source, false, excluded) - let index = 0 - while (index < keys.length) { - const key = keys[index] - if ($IsEnumerableOwn(source, key)) $Define(target, key, source[key], true) - index++ - } - return target -} - -function $vmGetElem(o, k) { - return o[$vmToKey(k)] -} - -function $vmDeleteElem(o, k) { - return delete o[$vmToKey(k)] -} - -// A built-in that asked for conversions (a Convert) or program getters (a Prefetch) before it can go on: runs them in -// program code, then the built-in again with what they gave (replay by ordinal, read as receiver, key, value), until -// it asks for nothing more. With no request, it runs again straight away. -function $vmReplay(callable, target, args, constructing, replay, read, req) { - while (true) { - if ($IsPrefetch(req)) { - const pairs = $PrefetchReads(req) - let at = 0 - while (at < pairs.length) { - const receiver = pairs[at] - const key = pairs[at + 1] - $ArraySet(read, read.length, receiver) - $ArraySet(read, read.length, key) - $ArraySet(read, read.length, receiver[key]) - at += 2 - } - } else if (req !== undefined) { - const values = $ConvValues(req) - const coerce = $ConvFlag(req, 0) - const ordinal = $ConvFlag(req, 1) - const len = values.length - const converted = [] - let i = 0 - while (i < len) { - const val = values[i] - const hint = $ConvHint(req, i) - const prim = $IsObj(val) ? $vmToPrimitive(val, hint) : val - $ArraySet(converted, i, coerce ? $ConvCoerce(hint, prim) : prim) - i++ - } - $ArraySet(replay, ordinal, converted) - } - const res = $Replay(callable, target, args, constructing, replay, read) - if (!$IsConvert(res) && !$IsPrefetch(res)) return res - req = res - } -} - -// A JSON walk's step for one value, holder[key]: its JSON as program data, or undefined when it is left out. A promise -// is yielded at the host boundary, which resumes the walk with its value. -function $vmJsonVisitor(boundary, replacer, properties) { - const ancestors = [] - function* visit(holder, key, depth) { - if (depth > 100) $Throw("RangeError", "Value exceeds the maximum depth of 100.") - let val = holder[key] - if ($IsPromise(val)) { - if (!boundary) { - $Throw("InvalidData", "JSON.stringify received an un-awaited Promise; await it first - e.g. \x60const result = await load(...)\x60.") - } - val = yield val - } - if ($IsObj(val)) { - const toJSON = val.toJSON - if ($IsCallableAny(toJSON)) val = $Call(toJSON, val, key) - } - if (replacer !== undefined) val = $Call(replacer, holder, key, val) - const kind = $JsonClassify(val, boundary, ancestors) - if (kind === 0) return undefined - if (kind === 1) return val - if (kind === 2) return null - if (kind === 3) return $JsonSpecial(val, boundary) - const target = kind === 4 ? $SetToArray(val) : val - $ArraySet(ancestors, ancestors.length, target) - let out - if ($IsArray(target)) { - out = [] - const len = target.length - let i = 0 - while (i < len) { - const elem = yield* visit(target, String(i), depth + 1) - $ArraySet(out, i, elem === undefined ? null : elem) - i++ - } - } else { - out = $NewNullProtoObj() - const names = $JsonNames(target, boundary, properties) - let i = 0 - while (i < names.length) { - const k = names[i] - const propVal = yield* visit(target, k, depth + 1) - if (propVal !== undefined) $Define(out, k, propVal, true) - i++ - } - } - $ArrayPop(ancestors) - return out - } - return visit -} - -function $vmJsonWalk(replacer, value, properties, indent) { - const json = $vmJsonVisitor(false, replacer, properties)({ "": value }, "", 0).next().value - return $JsonFinish(false, json, properties, indent) -} - -function $vmSettleCall(callable, thisVal, args) { - return $Apply(callable, thisVal, args) -} - -function $vmCombine(name, items) { - const c = $CombineStart(name, items) - for (const item of items) { - $CombineAdd(c, item) - } - $CombineEnd(c) -} - -function $vmOpenSyncForAsync(v, method) { - const it = $AfsRequireObj($Call(method, v)) - return $WrapAsyncFromSync(it, it.next) -} - -function $vmAsyncFromSync(adapter, kind, hasArg, val) { - const iter = $AfsGetIter(adapter) - const method = kind === "next" ? $AfsGetNext(adapter) : $AfsMethod(adapter, iter[kind], kind) - if (method === undefined || method === null) { - if (kind === "return") { - $AfsResolveDone(val) - return - } - const ret = $AfsMethod(adapter, iter.return, "return") - if (ret !== undefined && ret !== null) { - $AfsCheckObj(adapter, $Call(ret, iter), "return") - } - $AfsRejectNoThrow(adapter) - return - } - const res = hasArg ? $Call(method, iter, val) : $Call(method, iter) - $AfsCheckObj(adapter, res, kind) - const done = !!res.done - const value = res.value - $AfsSettle(adapter, value, done, kind !== "return") -} - -function $vmAsyncFromSyncClose(iter) { - const ret = iter.return - if (ret !== undefined && ret !== null) $Call(ret, iter) -} - -// A host call whose arguments hold promises that haven't fulfilled: waits for each, then calls again with the getter -// values read so far (read, as $vmReplay keeps them), so no getter runs twice; getters inside the values are read then. -async function $vmHostWait(promises, callee, args, read) { - let i = 0 - while (i < promises.length) { - await promises[i] - i++ - } - return $vmReplay(callee, undefined, args, false, [], read, undefined) -} - -async function $vmResult(value) { - const root = $IsThenable(value) ? await value : value - const walk = $vmJsonVisitor(true, undefined, null)({ "": root }, "", 0) - let step = walk.next() - while (!step.done) step = walk.next(await step.value) - return $JsonFinish(true, step.value, null, undefined) -} -` - -let compiledInternal: ReturnType | undefined - -/** The VM's internal helpers' bytecode, and their functions' code by name. */ -export const getInternalPrelude = () => (compiledInternal ??= builtinCodes("@vm-internal", INTERNAL_SOURCE)) - -/** The code of the internal helper `name`. */ -export const internalCode = (name: string): Code => getInternalPrelude().byName.get(name)! - -/** - * Adds the intrinsics available to `CodeFlags.INTERNAL` functions (both `@prelude` and `@vm-internal`) to `map`: the - * internal helpers, and the `$` natives. Uses `VmIntrinsic` rather than `Native` so it never touches - * `builtins.Function` or `nativeRule.sealed`. - */ -export const registerVmIntrinsics = (map: Map, vm: Vm): void => { - const ctx = vm.ctx - const builtins = ctx.builtins - const currentSite = () => vm.currentSite() - for (const [name, code] of getInternalPrelude().byName) map.set(name, new VmInternalFn(code)) - - const add = (name: string, fn: (args: Array) => NativeResult) => { - map.set(name, new VmIntrinsic(name, fn)) - } - - add("$IsObj", ([v]) => v instanceof Obj) - add("$IsDataObj", ([v]) => v instanceof Obj && !isOpaque(v)) - add("$IsDate", ([v]) => v instanceof DateObj) - add("$IsPromise", ([v]) => v instanceof PromiseObj) - add("$IsArray", ([v]) => v instanceof Arr) - add("$IsCallableAny", ([v]) => v instanceof Callable) - add("$IsFunction", ([v]) => typeofValue(v) === "function") - // Fulfills the promise the running `$vmThenableGet` settles, without adopting the value again. - add("$FulfillWith", ([value]) => { - const resolving = vm.frames[vm.frames.length - 1]!.target as Resolving - if (resolving.done) return undefined - resolving.done = true - vm.scheduler.settle(resolving.promise, normal(value)) - return undefined - }) - add("$PropKey", ([v]) => propertyKey(v) as Value) - add("$HasInstance", ([lhs, prototype]) => hasInstance(lhs, prototype, currentSite())) - add("$CoerceToString", ([v]) => coerceToString(v)) - add("$ApplyToNumeric", ([incFlag, v]) => { - if (isOpaque(v)) { - const op = incFlag === 0 ? "++" : "--" - throw invalidData(`'${op}' requires a data value.`, currentSite()) - } - return coerceToNumber(v) - }) - add("$ApplyUnary", ([sub, v]) => { - if (isOpaque(v)) throw invalidData("Unary operators require data values.", currentSite()) - const n = coerceToNumber(v) - return sub === UnaryOp.NEG ? -n : sub === UnaryOp.PLUS ? +n : ~n - }) - add("$OpConvKind", ([op, lhs, rhs]) => { - const conv = operatorConversion(op as string, lhs, rhs) - if (conv === undefined) return 0 - if (conv.kind === "key") return 1 - return conv.hint === "default" ? 2 : 3 - }) - add("$ApplyBinary", ([op, lhs, rhs]) => applyBinaryOperator(op as string, lhs, rhs, currentSite()!)) - - // Convert helpers - add("$ConvValues", ([req]) => new Arr(builtins.Array, [...(req as unknown as Convert).values])) - add("$ConvFlag", ([req, which]) => { - const c = req as unknown as Convert - return which === 0 ? c.coerce : c.ordinal - }) - add("$ConvHint", ([req, idx]) => { - const hints = (req as unknown as Convert).hints - return typeof hints === "string" ? hints : hints[idx as number]! - }) - add("$ConvCoerce", ([hint, val]) => (hint === "string" ? coerceToString(val) : coerceToNumber(val))) - add("$IsConvert", ([res]) => res instanceof Convert) - add("$IsPrefetch", ([res]) => res instanceof Prefetch) - add("$PrefetchReads", ([req]) => new Arr(builtins.Array, [...(req as unknown as Prefetch).reads])) - add("$Replay", ([callable, target, args, constructing, replay, read]) => { - const rep = (replay as Arr).items.map((item) => (item instanceof Arr ? item.items : undefined)) - const table = new Map>() - const items = (read as Arr).items - for (let at = 0; at < items.length; at += 3) { - const receiver = items[at] - const key = items[at + 1] as string | symbol - const known = table.get(receiver) ?? new Map() - known.set(key, items[at + 2]) - table.set(receiver, known) - } - const outer = [reads.table, reads.list] as const - conversions.count = 0 - conversions.replay = rep - reads.table = table - reads.list = read as Arr - try { - const argList = (args as Arr).items - if (callable instanceof HostNamespace) return ctx.callNamespace(callable, argList, currentSite()) as NativeResult - const fnObj = callable as Builtin - return constructing - ? fnObj.construct!(argList, target as Builtin, currentSite()) - : fnObj.invoke(target, argList, currentSite()) - } finally { - conversions.replay = undefined - reads.table = outer[0] - reads.list = outer[1] - } - }) - - // JSON walk helpers - add("$JsonClassify", ([val, boundary, ancestors]) => { - if (val === undefined || typeofValue(val) === "function") return 0 - if (typeof val === "number") return Number.isFinite(val) ? 1 : 2 - if (val === null || typeof val === "string" || typeof val === "boolean") return 1 - if (!(val instanceof Obj)) return 3 - if (boundary && val instanceof Bytes) { - throw invalidData( - "A Uint8Array cannot cross to the host; pass text instead, e.g. `new TextDecoder().decode(bytes)` or `bytes.toBase64()`.", - ) - } - if ((boundary && val instanceof URLSearchParamsObj) || val instanceof HeadersObj) return 3 - if ((ancestors as Arr).items.includes(val)) throw typeError("Converting circular structure to JSON.") - if (boundary && val instanceof SetObj) return 4 - return 5 - }) - add("$JsonSpecial", ([val, boundary]) => { - if (!(val instanceof Obj)) return new Obj(builtins.Object) - if (boundary && val instanceof URLSearchParamsObj) return val.params.toString() - if (val instanceof HeadersObj) return fromJson(ctx, Object.fromEntries(val.headers)) - return new Obj(builtins.Object) - }) - add("$SetToArray", ([val]) => new Arr(builtins.Array, [...(val as SetObj).set.liveKeys()])) - add("$NewNullProtoObj", () => new Obj(null)) - // The keys a JSON walk writes, in order: an error's name and message come first, then its other own keys. - add("$JsonNames", ([target, boundary, properties]) => { - const error = target instanceof ErrorObj - const propFilter = properties instanceof Arr ? new Set(properties.items as Array) : undefined - const list = keys(target as Obj).filter( - (k) => - !(error && (k === "name" || k === "message")) && - !(boundary && k === "__proto__") && - (propFilter === undefined || propFilter.has(k)), - ) - return new Arr(builtins.Array, error ? ["name", "message", ...list] : list) - }) - add("$ArrayPop", ([arr]) => (arr as Arr).items.pop()) - // Writes an element of an internal array without going through the prototype chain, where a program accessor could catch it. - add("$ArraySet", ([arr, index, value]) => ((arr as Arr).items[index as number] = value)) - add("$JsonFinish", ([boundary, root, properties, indent]) => { - const plain = toPlainJson(root) - if (boundary) return plain as Value - const props = properties instanceof Arr ? (properties.items as Array) : null - const text = JSON.stringify(plain, props, indent as string | number | undefined) - if (text !== undefined) checkStringLength(text.length) - return text - }) -} - -const toPlainJson = (val: Value): Json | undefined => { - if (val === undefined) return undefined - if (val === null || typeof val === "string" || typeof val === "number" || typeof val === "boolean") return val - if (val instanceof Arr) return val.items.map((item) => toPlainJson(item) ?? null) - if (val instanceof Obj) { - const out: Record = {} - for (const [k, slot] of val.props) { - if (typeof k !== "string" || !slot.enumerable || !("value" in slot)) continue - const v = toPlainJson(slot.value) - if (v !== undefined) { - if (k === "__proto__") { - Object.defineProperty(out, k, { value: v, enumerable: true, writable: true, configurable: true }) - } else { - out[k] = v - } - } - } - return out - } - return {} -} - -/** - * Budgeted native fast path for copying plain data at the host boundary (`boundary`) or for `JSON.stringify`. Returns - * `{ ok: true, json }` if the tree has no custom `toJSON`, promises, or shared references revisited more than `budget` - * times; otherwise the prelude walk (`$vmJsonWalk`) does the work, ticking fuel. - * - * Both give the text `JSON.stringify` would: `toJSON` is honored, functions and `undefined` vanish, non-finite numbers - * become null, and everything else is copied. Two departures from JS so a mistake is not a silent `{}`: an Error - * serializes as `{ name, message, ...own }`, and a promise throws. At the host boundary a promise is awaited, a Set - * crosses as an array, a URLSearchParams as its query string, a Uint8Array asks to be encoded as text first, and a - * `__proto__` key is dropped so host code can never receive one. - */ -export const tryFastBoundaryOrJson = ( - builtins: Builtins, - value: Value, - boundary: boolean, - revisitBudget = 2048, -): { readonly ok: true; readonly json: Json | undefined } | { readonly ok: false } => { - if (value === undefined) return { ok: true, json: undefined } - if (value === null || typeof value === "string" || typeof value === "boolean") return { ok: true, json: value } - if (typeof value === "number") return { ok: true, json: Number.isFinite(value) ? value : null } - if ( - value instanceof Obj && - value.constructor === Obj && - value.proto === builtins.Object && - value.proto.intrinsic > 0 && - value.props.size <= 4 && - !value.props.has("toJSON") - ) { - const flatOut: Record = {} - let flatOk = true - for (const [k, slot] of value.props) { - if (typeof k !== "string" || !slot.enumerable) continue - if (k === "__proto__") { - if (!boundary) flatOk = false - continue - } - if (!("value" in slot)) { - flatOk = false - break - } - const pv = slot.value - if (pv === undefined) continue - if (pv === null || typeof pv === "string" || typeof pv === "boolean") { - flatOut[k] = pv - } else if (typeof pv === "number") { - flatOut[k] = Number.isFinite(pv) ? pv : null - } else { - flatOk = false - break - } - } - if (flatOk) return { ok: true, json: flatOut } - } - let remainingRevisits = revisitBudget - const ancestors = new Set() - const seen = new Set() - const objectProto = builtins.Object - let dateProtoToJSON: Value | undefined - let urlProtoToJSON: Value | undefined - - const visit = ( - cur: Value, - depth: number, - ): { readonly ok: true; readonly json: Json | undefined } | { readonly ok: false } => { - if (depth > MAX_VALUE_DEPTH) throw rangeError(`Value exceeds the maximum depth of ${MAX_VALUE_DEPTH}.`) - if (cur === undefined || typeofValue(cur) === "function") return { ok: true, json: undefined } - if (typeof cur === "number") return { ok: true, json: Number.isFinite(cur) ? cur : null } - if (cur === null || typeof cur === "string" || typeof cur === "boolean") return { ok: true, json: cur } - if (cur instanceof PromiseObj) return { ok: false } - if (!(cur instanceof Obj)) return { ok: true, json: {} } - // Program getters run in the prelude walk. - if (cur.hasProgramAccessors) return { ok: false } - if (seen.has(cur)) { - if (--remainingRevisits <= 0) return { ok: false } - } else { - seen.add(cur) - } - const plain = cur.constructor === Obj - const toJSONSlot = - plain && cur.proto === objectProto && objectProto.intrinsic > 0 && !cur.props.has("toJSON") - ? undefined - : lookup(cur, "toJSON") - if (toJSONSlot !== undefined && isProgramAccessor(toJSONSlot)) return { ok: false } - const toJSON = toJSONSlot === undefined ? undefined : get(cur, "toJSON") - if (toJSON instanceof Callable) { - if (cur instanceof DateObj && toJSON === (dateProtoToJSON ??= get(builtins.Date, "toJSON"))) { - return { ok: true, json: Number.isFinite(cur.time) ? new Date(cur.time).toISOString() : null } - } - if (cur.tag === "URL" && toJSON === (urlProtoToJSON ??= get(builtins.URL, "toJSON"))) { - return { ok: true, json: cur.toString() } - } - return { ok: false } - } - if (boundary && cur instanceof Bytes) { - throw invalidData( - "A Uint8Array cannot cross to the host; pass text instead, e.g. `new TextDecoder().decode(bytes)` or `bytes.toBase64()`.", - ) - } - if (boundary && cur instanceof URLSearchParamsObj) return { ok: true, json: cur.params.toString() } - if (cur instanceof HeadersObj) return { ok: true, json: Object.fromEntries(cur.headers) } - if (ancestors.has(cur)) throw typeError("Converting circular structure to JSON.") - ancestors.add(cur) - try { - if (cur instanceof Arr || (boundary && cur instanceof SetObj)) { - const items = cur instanceof Arr ? cur.items : [...cur.set.liveKeys()] - const out: Array = new Array(items.length) - for (let i = 0; i < items.length; i++) { - const r = visit(items[i], depth + 1) - if (!r.ok) return r - out[i] = r.json ?? null - } - return { ok: true, json: out } - } - const out: Record = {} - if (cur instanceof ErrorObj) { - for (const k of ["name", "message"]) { - const slot = lookup(cur, k) - if (slot !== undefined && isProgramAccessor(slot)) return { ok: false } - const r = visit(get(cur, k), depth + 1) - if (!r.ok) return r - if (r.json !== undefined) out[k] = r.json - } - } - // A plain object's own data is its property table; a wrapper (bytes, say) presents its own keys. - for (const [k, slot] of plain ? cur.props : keys(cur).map((key) => [key, undefined] as const)) { - if (typeof k !== "string" || (slot !== undefined && !slot.enumerable)) continue - if (boundary && k === "__proto__") continue - const propVal = - slot === undefined ? get(cur, k) : "value" in slot ? slot.value : (slot.get as Getter | undefined)?.(cur) - const r = visit(propVal, depth + 1) - if (!r.ok) return r - if (r.json !== undefined) { - if (k === "__proto__") { - Object.defineProperty(out, k, { value: r.json, enumerable: true, writable: true, configurable: true }) - } else { - out[k] = r.json - } - } - } - return { ok: true, json: out } - } finally { - ancestors.delete(cur) - } - } - - return visit(value, 0) -} diff --git a/packages/codemode/src/language/opcodes.ts b/packages/codemode/src/language/opcodes.ts deleted file mode 100644 index bdecb1987f3..00000000000 --- a/packages/codemode/src/language/opcodes.ts +++ /dev/null @@ -1,325 +0,0 @@ -import type { DiagnosticKind } from "./runtime/model.js" -import type { ErrorType } from "./runtime/intrinsics.js" - -/** Uninitialized lexical binding sentinel (temporal dead zone). */ -export const HOLE: unique symbol = Symbol("codemode.hole") - -/** Mutable box for a binding captured by a closure. */ -export class Cell { - constructor(public v: unknown) {} -} - -const initCell = new Cell(0) -initCell.v = 1.5 -initCell.v = "" -initCell.v = true -initCell.v = null -initCell.v = undefined -initCell.v = HOLE - -const makeEmptyCells = (): ReadonlyArray => { - const arr: Array = [] - arr.push(initCell) - arr.length = 0 - return arr as Array -} - -export const EMPTY_CELLS: ReadonlyArray = makeEmptyCells() - -/** Raised when the VM compiler or runtime encounters a feature scheduled for a later phase. */ -export class NotYetImplemented extends Error { - constructor(readonly feature: string) { - super(`Not yet implemented in VM: ${feature}`) - this.name = "NotYetImplemented" - } -} - -/** - * Bytecode opcodes (1 word per instruction: `op:8 | a:8 | bx:16`, widened by `EXTRA` prefixes for `a > 0xff` or `bx > 0xffff`). - */ -export const Op = { - // Stack and constants (10) - PUSH_UNDEF: 0, - PUSH_NULL: 1, - PUSH_BOOL: 2, - PUSH_INT: 3, - PUSH_CONST: 4, - POP: 5, - POPN: 6, - DUP: 7, - PICK: 8, - ROT: 9, - - // Variables (15) - GET_LOCAL: 10, - PUT_LOCAL: 11, - HOLE_LOCAL: 12, - NEW_CELL: 13, - COPY_CELL: 14, - GET_CELL: 15, - PUT_CELL: 16, - GET_UPVAL: 17, - PUT_UPVAL: 18, - GET_GLOBAL: 19, - GET_INTRINSIC: 20, - ARGS: 21, - CLOSURE: 22, - SET_NAME: 23, - IMPORT: 24, - - // Properties (10) - GET_PROP: 25, - GET_ELEM: 26, - PUT_PROP: 27, - PUT_ELEM: 28, - DELETE_PROP: 29, - DELETE_ELEM: 30, - CHECK_BASE: 31, - TO_KEY: 32, - IN: 33, - INSTANCEOF: 34, - - // Literals (8) - NEW_OBJECT: 35, - NEW_ARRAY: 36, - ARRAY_APPEND: 37, - // a bit 0: computed key on the stack; bit 1: a class field, which throws when it cannot be defined. - DEFINE_FIELD: 38, - COPY_DATA_PROPS: 39, - COPY_REST: 40, - TEMPLATE: 41, - REGEXP: 42, - - // Operators (16) - ADD: 43, - SUB: 44, - MUL: 45, - LT: 46, - LE: 47, - GT: 48, - GE: 49, - SEQ: 50, - SNE: 51, - BINOP: 52, - UNARY: 53, - NOT: 54, - TO_NUMERIC: 55, - INC: 56, - TO_STRING: 57, - CONCAT: 58, - - // Control (11) - JUMP: 59, - LOOP: 60, - JUMP_IF_FALSE: 61, - JUMP_IF_TRUE: 62, - JUMP_COND: 63, - THROW: 64, - THROW_ERROR: 65, - END_FINALLY: 66, - RETURN: 67, - NOP: 68, - EXTRA: 69, - - // Calls (4) - CALL: 70, - CALL_SPREAD: 71, - NEW: 72, - NEW_SPREAD: 73, - - // Iteration (7) - ITER_OPEN: 74, - ITER_INIT: 75, - ITER_STEP: 76, - ITER_RESULT: 77, - ITER_CLOSE: 78, - ITER_APPEND_ALL: 79, - FOR_IN: 80, - - // Generators and async (6) - GENERATOR_START: 81, - YIELD: 82, - RESUME: 83, - AWAIT: 84, - YSTAR: 85, - YSTAR_RESULT: 86, - - // Program (1) - END_PROGRAM: 87, - - // Literals, added later: `get x() {}` / `set x(v) {}` (a bit 0: computed key; bit 1: setter) - DEFINE_ACCESSOR: 88, - - // Classes: `CLASS` turns the constructor on top into a class, `[ctor] -> [ctor, proto]`; `DEFINE_METHOD` defines the - // method on top as a hidden property of the prototype, or of the constructor when a bit 0 is set: `[ctor, proto, fn] - // -> [ctor, proto]`, keyed by constant `bx`. - CLASS: 89, - // DEFINE_METHOD's `a`: 1 static, 2 computed (`[.., key, fn]`), 4 getter, 8 setter (non-enumerable accessors). - DEFINE_METHOD: 90, - // `SET_FIELDS` makes the field-initializer function on top the class's: `[ctor, proto, fn] -> [ctor, proto]`. - // `INIT_FIELDS` runs field initializers: a 0 calls the running constructor's with its `this`, `[] -> [result]`; - // a 1 calls a static initializer with the constructor as `this`, `[ctor, fn] -> [result]`. - SET_FIELDS: 91, - INIT_FIELDS: 92, - // Inheritance. `SUPER_CALL` constructs the parent of the running constructor for its new target (local `bx`): - // `[...args] -> [instance]` with `a` args, or `[argsArr] -> [instance]` when `a` is 255. - SUPER_CALL: 93, - // `SUPER_BIND` makes the instance on top the derived constructor's `this` (local `bx`, a cell when `a` is 1): - // `[instance] -> [instance]`. Once only. - SUPER_BIND: 94, - // `super.x`: `[home, this] -> [value]` (`[this, value]` when bit 0 keeps the receiver), keyed by constant `bx`, or - // by a key on top when bit 1 is set (`[home, this, key]`). - GET_SUPER: 96, - // `super.x = v`: `[home, this, v] -> [v]`, or `[home, this, key, v] -> [v]` when bit 1 is set. - PUT_SUPER: 97, - // An object literal method that uses `super` gets the object at depth `a` as its home: `[o, .., fn]` unchanged. - SET_HOME: 98, -} as const - -export type OpCode = (typeof Op)[keyof typeof Op] - -export const OpNames: ReadonlyArray = Object.entries(Op).reduce>((acc, [name, code]) => { - acc[code] = name - return acc -}, []) - -/** Sub-ops for `Op.BINOP` (`a` operand). */ -export const BinOp = { - DIV: 0, - MOD: 1, - EXP: 2, - BAND: 3, - BOR: 4, - BXOR: 5, - SHL: 6, - SAR: 7, - SHR: 8, - EQ: 9, - NE: 10, -} as const - -export const BinOpSymbols: ReadonlyArray = ["/", "%", "**", "&", "|", "^", "<<", ">>", ">>>", "==", "!="] - -/** Sub-ops for `Op.UNARY` (`a` operand). */ -export const UnaryOp = { - NEG: 0, - PLUS: 1, - BNOT: 2, - TYPEOF: 3, - VOID: 4, -} as const - -export const UnaryOpSymbols: ReadonlyArray = ["-", "+", "~", "typeof", "void"] - -/** Sub-ops for `Op.JUMP_COND` (`a` operand). */ -export const CondKind = { - /** If top is truthy, keep it and jump; else pop and fall through (`||`, `||=`). */ - TRUTHY_KEEP: 0, - /** If top is falsy, keep it and jump; else pop and fall through (`&&`, `&&=`). */ - FALSY_KEEP: 1, - /** If top is not null/undefined, keep it and jump; else pop and fall through (`??`, `??=`). */ - NOT_NULLISH_KEEP: 2, - /** If top !== undefined, keep it and jump; else pop and fall through (defaults). */ - DEFINED: 3, - /** If top == null, replace top with undefined and jump; else keep top and fall through (`?.`). */ - NULLISH: 4, - /** For `[thisValue, callable]`: if callable == null, pop callable, set top to undefined, and jump (`o.m?.()`). */ - NULLISH_METHOD: 5, -} as const - -/** Sub-ops for `Op.PUT_LOCAL`, `Op.PUT_CELL`, `Op.PUT_UPVAL` (`a` operand). */ -export const PutKind = { - /** Normal assignment: checks TDZ (`HOLE`). */ - ASSIGN: 0, - /** Declaration initialization or internal slot write: skips TDZ check. */ - INIT: 1, - /** Assignment to a `const` or read-only binding: checks TDZ first, then throws `TypeError`. */ - CONST: 2, -} as const - -/** Sub-ops for `Op.CHECK_BASE` (`a` operand). */ -export const CheckBaseKind = { - /** `o[k]`: checks `o` is not null/undefined before converting `k` (`[o, k] -> [o, k]`). */ - READ: 0, - /** `o.x = ...`: checks `o.x` is a writable reference (`[o] -> [o]`, `bx = k`). */ - WRITE_PROP: 1, - /** `o[k] = ...`: checks `o[k]` is a writable reference after `TO_KEY` (`[o, key] -> [o, key]`). */ - WRITE_ELEM: 2, - /** Destructuring target check: throws if top is null or undefined (`[v] -> [v]`). */ - DESTRUCTURE: 3, -} as const - -/** Sub-ops for `Op.ITER_OPEN` and `Op.ITER_INIT` (`a` operand). */ -export const IterContext = { - FOR_OF: 0, - DESTRUCTURE: 1, - SPREAD: 2, - DELEGATE: 3, - FOR_AWAIT: 4, - ASYNC_DELEGATE: 5, - CHECK_OBJECT: 6, -} as const - -/** Sub-ops for `Op.IMPORT` (`a` operand). */ -export const ImportKind = { - DEFAULT: 0, - NAMESPACE: 1, - NAMED: 2, - SIDE_EFFECT: 3, - DYNAMIC: 4, -} as const - -/** Bit flags on `Code.flags`. */ -export const CodeFlags = { - ARROW: 1 << 0, - ASYNC: 1 << 1, - GENERATOR: 1 << 2, - SIMPLE_PARAMS: 1 << 3, - USES_THIS: 1 << 4, - USES_ARGUMENTS: 1 << 5, - INTERNAL: 1 << 6, - PROGRAM: 1 << 7, - /** A class constructor: `new` only, calling it throws. */ - CLASS_CONSTRUCTOR: 1 << 8, - NEEDS_ARGS: 1 << 9, - /** The constructor of a class with `extends`. */ - DERIVED: 1 << 10, - /** A class method, with a home object. */ - METHOD: 1 << 11, - /** A class's hidden field-initializer function. */ - FIELD_INIT: 1 << 12, -} as const - -/** Constant pool descriptors. */ -export type TemplateSite = { - readonly cooked: ReadonlyArray - readonly raw: ReadonlyArray - readonly nodeIndex: number -} - -export type RegExpSite = { - readonly pattern: string - readonly flags: string -} - -export type ErrorSite = { - readonly type: ErrorType - readonly message: string - readonly kind?: DiagnosticKind - readonly suggestions?: ReadonlyArray -} - -export type ImportSite = { - readonly specifier: string - readonly imported?: string -} - -export type ConstValue = string | number | TemplateSite | RegExpSite | ErrorSite | ImportSite - -/** Packs one instruction word: `op:8 | a:8 | bx:16`. Throws if any field does not fit its width. */ -export const packWord = (op: OpCode, a = 0, bx = 0): number => { - if ((op & 0xff) !== op || (a & 0xff) !== a || (bx & 0xffff) !== bx) { - throw new RangeError(`Instruction operand out of single-word range: op=${op} a=${a} bx=${bx}`) - } - return op | (a << 8) | (bx << 16) -} diff --git a/packages/codemode/src/language/prelude/bytecode.json b/packages/codemode/src/language/prelude/bytecode.json deleted file mode 100644 index 70cc26acd99..00000000000 --- a/packages/codemode/src/language/prelude/bytecode.json +++ /dev/null @@ -1 +0,0 @@ -{"@prelude":{"text":"da8b0aa558dd4aa2","codes":[{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":0,"name":"","flags":202,"length":0,"params":0,"locals":0,"maxStack":1,"code":[0,87],"consts":[],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,0],"localNames":[],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":1,"name":"arrayFromIterable","flags":72,"length":3,"params":3,"locals":8,"maxStack":8,"code":[36,196875,3,262411,327692,10,2228298,2228283,393483,3147340,2424891,327692,327947,0,20,196618,262154,65546,0,50,1507389,327690,1835067,131082,65546,327690,262154,582,838,5,262154,56,262155,589884,70,75,524347,70,3147341,720955,459019,2885198,70,5,458762,64,5,2883643,196618,67],"consts":["$ArraySet"],"captures":[],"handlers":[11,34,40,0,41,44,46,0],"finallies":[],"finallyOffsets":[],"sites":[0,10,1,8,2,14,3,12,5,19,6,15,12,16,13,22,14,23,15,24,16,25,17,28,18,29,19,27,20,26,21,30,22,26,23,34,24,33,25,35,26,36,27,31,28,22,30,39,31,38,32,39,33,15,48,41,49,40],"localNames":["items","mapper","thisArg","result","index","item","%it","%e"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":2,"name":"arrayFromLike","flags":72,"length":4,"params":4,"locals":6,"maxStack":8,"code":[20,65352,65546,328,262411,3,327947,327690,65546,46,1835069,0,65556,262154,327690,196618,131082,10,327690,26,327690,582,838,5,327690,56,327691,458812,262154,67],"consts":["Array","$ArraySet"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,53,1,52,2,54,3,52,4,50,5,58,6,56,7,61,8,62,9,60,10,59,11,65,12,66,13,67,14,68,15,72,16,71,17,74,18,75,19,73,20,76,21,69,22,65,24,79,25,78,26,79,27,59,28,81,29,80],"localNames":["source","length","mapper","thisArg","result","index"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":3,"name":"Array$prototype$map","flags":592,"length":1,"params":2,"locals":3,"maxStack":7,"code":[789,267,1045,65803,66581,459583,0,131339,0,20,0,65556,10,131076,196612,838,65546,131082,262148,1094,67],"consts":["mapItems","$Receiver","Array","Array.prototype.map","Array.map"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,82,2,84,4,85,6,87,7,85,8,90,9,91,10,92,11,93,12,94,13,95,14,96,15,92,16,97,17,98,18,99,19,90,20,89],"localNames":["this","callback","thisArg"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":4,"name":"Uint8Array$prototype$map","flags":592,"length":1,"params":2,"locals":4,"maxStack":8,"code":[789,267,1045,65803,66581,459583,0,131339,0,20,10,65540,131076,838,196875,0,196628,0,262164,196618,65546,131082,327684,1094,196618,582,67],"consts":["$Receiver","Uint8Array","Uint8Array.prototype.map","$DerivedBytes","mapItems","Uint8Array.map"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,100,2,102,4,103,6,105,7,103,8,110,9,111,10,112,11,113,12,114,13,110,14,108,15,116,16,117,17,118,18,119,19,120,20,121,21,122,22,123,23,118,24,124,25,116,26,115],"localNames":["this","callback","thisArg","bytes"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":5,"name":"mapItems","flags":72,"length":4,"params":4,"locals":7,"maxStack":9,"code":[0,20,65546,196618,582,5,10,65561,262411,131092,65352,262154,328,327947,3,393483,393226,262154,46,2752573,393226,10,33,2490429,0,196628,327690,393226,131082,65546,10,393226,26,393226,10,838,838,5,393226,56,393227,1048636,327690,67],"consts":["$Callback","length","Array","$ArraySet"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,133,1,134,2,135,3,136,4,133,6,141,7,140,8,138,9,147,10,146,11,148,12,146,13,144,14,152,15,150,16,155,17,156,18,154,19,153,20,160,21,161,22,159,23,158,24,163,25,164,26,165,27,166,28,170,29,169,30,172,31,173,32,171,33,174,34,175,35,167,36,163,38,178,39,177,40,178,41,153,42,180,43,179],"localNames":["array","callback","thisArg","label","length","result","index"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":6,"name":"Array$prototype$filter","flags":592,"length":1,"params":2,"locals":3,"maxStack":7,"code":[789,267,1045,65803,66581,459583,0,131339,0,20,0,65556,10,131076,196612,838,65546,131082,262148,1094,67],"consts":["filterItems","$Receiver","Array","Array.prototype.filter","Array.filter"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,181,2,183,4,184,6,186,7,184,8,189,9,190,10,191,11,192,12,193,13,194,14,195,15,191,16,196,17,197,18,198,19,189,20,188],"localNames":["this","callback","thisArg"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":7,"name":"Uint8Array$prototype$filter","flags":592,"length":1,"params":2,"locals":4,"maxStack":8,"code":[789,267,1045,65803,66581,459583,0,131339,0,20,10,65540,131076,838,196875,0,196628,0,262164,196618,65546,131082,327684,1094,196618,582,67],"consts":["$Receiver","Uint8Array","Uint8Array.prototype.filter","$DerivedBytes","filterItems","Uint8Array.filter"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,199,2,201,4,202,6,204,7,202,8,209,9,210,10,211,11,212,12,213,13,209,14,207,15,215,16,216,17,217,18,218,19,219,20,220,21,221,22,222,23,217,24,223,25,215,26,214],"localNames":["this","callback","thisArg","bytes"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":8,"name":"filterItems","flags":72,"length":4,"params":4,"locals":9,"maxStack":5,"code":[0,20,65546,196618,582,5,10,65561,262411,36,327947,3,393483,3,459019,0,524555,458762,262154,46,3407933,458762,10,33,3145789,10,458762,26,524299,131082,65546,524298,458762,10,838,3145789,327690,393226,55,7,56,393227,31,32,543,524298,28,5,458762,56,458763,1114172,327690,67],"consts":["$Callback","length"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,232,1,233,2,234,3,235,4,232,6,240,7,239,8,237,9,245,10,243,11,249,12,247,13,253,14,251,15,255,17,259,18,260,19,258,20,257,21,264,22,265,23,263,24,262,25,271,26,272,27,270,28,269,29,277,30,276,31,278,32,279,33,280,34,274,35,273,36,284,37,286,39,285,41,286,42,283,43,285,44,283,45,287,46,283,47,282,48,290,49,289,50,290,51,257,52,292,53,291],"localNames":["array","callback","thisArg","label","length","result","count","index","item"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":9,"name":"Array$prototype$forEach","flags":592,"length":1,"params":2,"locals":3,"maxStack":7,"code":[789,267,1045,65803,66581,459583,0,131339,0,20,0,65556,10,131076,196612,838,65546,131082,262148,1094,5,0,67],"consts":["forEachItem","$Receiver","Array","Array.prototype.forEach","Array.forEach"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,293,2,295,4,296,6,298,7,296,8,301,9,302,10,303,11,304,12,305,13,306,14,307,15,303,16,308,17,309,18,310,19,301,21,299],"localNames":["this","callback","thisArg"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":10,"name":"Uint8Array$prototype$forEach","flags":592,"length":1,"params":2,"locals":3,"maxStack":7,"code":[789,267,1045,65803,66581,459583,0,131339,0,20,0,65556,10,131076,196612,838,65546,131082,262148,1094,5,0,67],"consts":["forEachItem","$Receiver","Uint8Array","Uint8Array.prototype.forEach","Uint8Array.forEach"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,311,2,313,4,314,6,316,7,314,8,319,9,320,10,321,11,322,12,323,13,324,14,325,15,321,16,326,17,327,18,328,19,319,21,317],"localNames":["this","callback","thisArg"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":11,"name":"forEachItem","flags":72,"length":4,"params":4,"locals":6,"maxStack":5,"code":[0,20,65546,196618,582,5,10,65561,262411,3,327947,327690,262154,46,2097213,327690,10,33,1835069,131082,65546,10,327690,26,327690,10,838,5,327690,56,327691,720956,0,67],"consts":["$Callback","length"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,337,1,338,2,339,3,340,4,337,6,345,7,344,8,342,9,350,10,348,11,353,12,354,13,352,14,351,15,358,16,359,17,357,18,356,19,364,20,363,21,366,22,367,23,365,24,368,25,369,26,361,28,372,29,371,30,372,31,351,32,335],"localNames":["array","callback","thisArg","label","length","index"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":12,"name":"Array$prototype$some","flags":592,"length":1,"params":2,"locals":3,"maxStack":7,"code":[789,267,1045,65803,66581,459583,0,131339,0,20,0,65556,10,131076,196612,838,65546,131082,262148,2,1350,67],"consts":["testItems","$Receiver","Array","Array.prototype.some","Array.some"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,373,2,375,4,376,6,378,7,376,8,381,9,382,10,383,11,384,12,385,13,386,14,387,15,383,16,388,17,389,18,390,19,391,20,381,21,380],"localNames":["this","callback","thisArg"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":13,"name":"Uint8Array$prototype$some","flags":592,"length":1,"params":2,"locals":3,"maxStack":7,"code":[789,267,1045,65803,66581,459583,0,131339,0,20,0,65556,10,131076,196612,838,65546,131082,262148,2,1350,67],"consts":["testItems","$Receiver","Uint8Array","Uint8Array.prototype.some","Uint8Array.some"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,392,2,394,4,395,6,397,7,395,8,400,9,401,10,402,11,403,12,404,13,405,14,406,15,402,16,407,17,408,18,409,19,410,20,400,21,399],"localNames":["this","callback","thisArg"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":14,"name":"Array$prototype$every","flags":592,"length":1,"params":2,"locals":3,"maxStack":7,"code":[789,267,1045,65803,66581,459583,0,131339,0,20,0,65556,10,131076,196612,838,65546,131082,262148,258,1350,67],"consts":["testItems","$Receiver","Array","Array.prototype.every","Array.every"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,411,2,413,4,414,6,416,7,414,8,419,9,420,10,421,11,422,12,423,13,424,14,425,15,421,16,426,17,427,18,428,19,429,20,419,21,418],"localNames":["this","callback","thisArg"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":15,"name":"Uint8Array$prototype$every","flags":592,"length":1,"params":2,"locals":3,"maxStack":7,"code":[789,267,1045,65803,66581,459583,0,131339,0,20,0,65556,10,131076,196612,838,65546,131082,262148,258,1350,67],"consts":["testItems","$Receiver","Uint8Array","Uint8Array.prototype.every","Uint8Array.every"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,430,2,432,4,433,6,435,7,433,8,438,9,439,10,440,11,441,12,442,13,443,14,444,15,440,16,445,17,446,18,447,19,448,20,438,21,437],"localNames":["this","callback","thisArg"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":16,"name":"testItems","flags":72,"length":5,"params":5,"locals":7,"maxStack":5,"code":[0,20,65546,196618,582,5,10,65561,327947,3,393483,393226,327690,46,2490429,393226,10,33,1966399,131082,65546,10,393226,26,393226,10,838,54,262154,50,2228285,262154,54,67,393226,56,393227,720956,262154,67],"consts":["$Callback","length"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,458,1,459,2,460,3,461,4,458,6,466,7,465,8,463,9,471,10,469,11,474,12,475,13,473,14,472,15,480,16,481,17,479,18,478,19,487,20,486,21,489,22,490,23,488,24,491,25,492,26,484,27,483,28,493,29,482,30,477,31,496,32,495,33,494,34,499,35,498,36,499,37,472,38,501,39,500],"localNames":["array","callback","thisArg","label","every","length","index"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":17,"name":"Array$prototype$find","flags":592,"length":1,"params":2,"locals":3,"maxStack":8,"code":[789,267,1045,65803,66581,459583,0,131339,0,20,0,65556,10,131076,196612,838,65546,131082,262148,2,2,1606,67],"consts":["findItem","$Receiver","Array","Array.prototype.find","Array.find"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,502,2,504,4,505,6,507,7,505,8,510,9,511,10,512,11,513,12,514,13,515,14,516,15,512,16,517,17,518,18,519,19,520,20,521,21,510,22,509],"localNames":["this","callback","thisArg"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":18,"name":"Uint8Array$prototype$find","flags":592,"length":1,"params":2,"locals":3,"maxStack":8,"code":[789,267,1045,65803,66581,459583,0,131339,0,20,0,65556,10,131076,196612,838,65546,131082,262148,2,2,1606,67],"consts":["findItem","$Receiver","Uint8Array","Uint8Array.prototype.find","Uint8Array.find"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,522,2,524,4,525,6,527,7,525,8,530,9,531,10,532,11,533,12,534,13,535,14,536,15,532,16,537,17,538,18,539,19,540,20,541,21,530,22,529],"localNames":["this","callback","thisArg"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":19,"name":"Array$prototype$findIndex","flags":592,"length":1,"params":2,"locals":3,"maxStack":8,"code":[789,267,1045,65803,66581,459583,0,131339,0,20,0,65556,10,131076,196612,838,65546,131082,262148,2,258,1606,67],"consts":["findItem","$Receiver","Array","Array.prototype.findIndex","Array.findIndex"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,542,2,544,4,545,6,547,7,545,8,550,9,551,10,552,11,553,12,554,13,555,14,556,15,552,16,557,17,558,18,559,19,560,20,561,21,550,22,549],"localNames":["this","callback","thisArg"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":20,"name":"Uint8Array$prototype$findIndex","flags":592,"length":1,"params":2,"locals":3,"maxStack":8,"code":[789,267,1045,65803,66581,459583,0,131339,0,20,0,65556,10,131076,196612,838,65546,131082,262148,2,258,1606,67],"consts":["findItem","$Receiver","Uint8Array","Uint8Array.prototype.findIndex","Uint8Array.findIndex"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,562,2,564,4,565,6,567,7,565,8,570,9,571,10,572,11,573,12,574,13,575,14,576,15,572,16,577,17,578,18,579,19,580,20,581,21,570,22,569],"localNames":["this","callback","thisArg"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":21,"name":"Array$prototype$findLast","flags":592,"length":1,"params":2,"locals":3,"maxStack":8,"code":[789,267,1045,65803,66581,459583,0,131339,0,20,0,65556,10,131076,196612,838,65546,131082,262148,258,2,1606,67],"consts":["findItem","$Receiver","Array","Array.prototype.findLast","Array.findLast"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,582,2,584,4,585,6,587,7,585,8,590,9,591,10,592,11,593,12,594,13,595,14,596,15,592,16,597,17,598,18,599,19,600,20,601,21,590,22,589],"localNames":["this","callback","thisArg"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":22,"name":"Uint8Array$prototype$findLast","flags":592,"length":1,"params":2,"locals":3,"maxStack":8,"code":[789,267,1045,65803,66581,459583,0,131339,0,20,0,65556,10,131076,196612,838,65546,131082,262148,258,2,1606,67],"consts":["findItem","$Receiver","Uint8Array","Uint8Array.prototype.findLast","Uint8Array.findLast"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,602,2,604,4,605,6,607,7,605,8,610,9,611,10,612,11,613,12,614,13,615,14,616,15,612,16,617,17,618,18,619,19,620,20,621,21,610,22,609],"localNames":["this","callback","thisArg"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":23,"name":"Array$prototype$findLastIndex","flags":592,"length":1,"params":2,"locals":3,"maxStack":8,"code":[789,267,1045,65803,66581,459583,0,131339,0,20,0,65556,10,131076,196612,838,65546,131082,262148,258,258,1606,67],"consts":["findItem","$Receiver","Array","Array.prototype.findLastIndex","Array.findLastIndex"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,622,2,624,4,625,6,627,7,625,8,630,9,631,10,632,11,633,12,634,13,635,14,636,15,632,16,637,17,638,18,639,19,640,20,641,21,630,22,629],"localNames":["this","callback","thisArg"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":24,"name":"Uint8Array$prototype$findLastIndex","flags":592,"length":1,"params":2,"locals":3,"maxStack":8,"code":[789,267,1045,65803,66581,459583,0,131339,0,20,0,65556,10,131076,196612,838,65546,131082,262148,258,258,1606,67],"consts":["findItem","$Receiver","Uint8Array","Uint8Array.prototype.findLastIndex","Uint8Array.findLastIndex"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,642,2,644,4,645,6,647,7,645,8,650,9,651,10,652,11,653,12,654,13,655,14,656,15,652,16,657,17,658,18,659,19,660,20,661,21,650,22,649],"localNames":["this","callback","thisArg"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":25,"name":"findItem","flags":72,"length":6,"params":6,"locals":10,"maxStack":5,"code":[0,20,65546,196618,582,5,10,65561,393483,262154,917565,65539,53,983099,65539,459019,262154,1441853,393226,65539,44,1507387,3,524555,0,590091,524298,3,49,2163007,524298,393226,46,3670077,10,524298,26,589835,131082,65546,589834,524298,10,838,3342397,327690,3211325,524298,3276859,589834,67,524298,458762,43,524299,1703996,327690,3997757,65539,53,4063291,0,67],"consts":["$Callback","length"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,672,1,673,2,674,3,675,4,672,6,680,7,679,8,677,9,686,10,685,11,688,12,687,13,685,14,689,15,683,16,694,17,693,18,696,19,697,20,695,21,693,22,698,23,691,24,700,26,705,27,706,28,704,29,703,30,708,31,709,32,707,33,702,34,715,35,716,36,714,37,713,38,721,39,720,40,722,41,723,42,724,43,718,44,717,45,727,46,726,47,728,48,726,49,729,50,725,51,732,52,733,53,731,54,732,55,702,56,736,57,735,58,738,59,737,60,735,61,739,62,734],"localNames":["array","callback","thisArg","label","last","wantIndex","length","step","index","item"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":26,"name":"Array$prototype$reduce","flags":592,"length":1,"params":2,"locals":3,"maxStack":7,"code":[789,267,1045,65803,65813,131339,0,20,0,65556,10,131076,196612,838,65546,131082,262148,2,1350,67],"consts":["reduceItems","$Receiver","Array","Array.prototype.reduce","Array.reduce"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,740,2,742,4,743,6,747,7,748,8,749,9,750,10,751,11,752,12,753,13,749,14,754,15,755,16,756,17,757,18,747,19,746],"localNames":["this","callback","initial"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":27,"name":"Uint8Array$prototype$reduce","flags":592,"length":1,"params":2,"locals":3,"maxStack":7,"code":[789,267,1045,65803,65813,131339,0,20,0,65556,10,131076,196612,838,65546,131082,262148,2,1350,67],"consts":["reduceItems","$Receiver","Uint8Array","Uint8Array.prototype.reduce","Uint8Array.reduce"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,758,2,760,4,761,6,765,7,766,8,767,9,768,10,769,11,770,12,771,13,767,14,772,15,773,16,774,17,775,18,765,19,764],"localNames":["this","callback","initial"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":28,"name":"Array$prototype$reduceRight","flags":592,"length":1,"params":2,"locals":3,"maxStack":7,"code":[789,267,1045,65803,65813,131339,0,20,0,65556,10,131076,196612,838,65546,131082,262148,258,1350,67],"consts":["reduceItems","$Receiver","Array","Array.prototype.reduceRight","Array.reduceRight"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,776,2,778,4,779,6,783,7,784,8,785,9,786,10,787,11,788,12,789,13,785,14,790,15,791,16,792,17,793,18,783,19,782],"localNames":["this","callback","initial"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":29,"name":"Uint8Array$prototype$reduceRight","flags":592,"length":1,"params":2,"locals":3,"maxStack":7,"code":[789,267,1045,65803,65813,131339,0,20,0,65556,10,131076,196612,838,65546,131082,262148,258,1350,67],"consts":["reduceItems","$Receiver","Uint8Array","Uint8Array.prototype.reduceRight","Uint8Array.reduceRight"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,794,2,796,4,797,6,801,7,802,8,803,9,804,10,805,11,806,12,807,13,803,14,808,15,809,16,810,17,811,18,801,19,800],"localNames":["this","callback","initial"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":30,"name":"reduceItems","flags":72,"length":5,"params":5,"locals":9,"maxStack":6,"code":[0,20,65546,196618,582,5,10,65561,327947,262154,917565,65539,53,983099,65539,393483,262154,1441853,327690,65539,44,1507387,3,459019,0,524555,131082,65561,3,48,2359357,131082,3,26,524299,5111867,458762,3,49,2818367,458762,327690,46,3146047,458762,10,33,54,3539005,458762,393226,43,458763,2359356,458762,3,46,3997759,458762,327690,49,4587581,0,131092,196612,196618,262148,43,582,5,10,458762,26,524299,458762,393226,43,458763,458762,3,49,5570879,458762,327690,46,6881341,458762,10,33,6553661,0,65546,524298,10,458762,26,458762,10,1094,524299,458762,393226,43,458763,5111868,524298,67],"consts":["$Callback","length","$Throw","TypeError"," of an empty array with no initial value."],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,821,1,822,2,823,3,824,4,821,6,829,7,828,8,826,9,835,10,834,11,837,12,836,13,834,14,838,15,832,16,843,17,842,18,845,19,846,20,844,21,842,22,847,23,840,24,849,26,854,27,853,28,856,29,852,30,851,31,861,32,862,33,860,34,859,35,851,36,868,37,869,38,867,39,866,40,871,41,872,42,870,43,865,44,875,45,876,46,874,47,873,48,864,49,879,50,880,51,878,52,879,53,864,54,884,55,885,56,883,57,882,58,887,59,888,60,886,61,881,62,890,63,891,64,892,65,894,66,895,67,893,68,890,70,900,71,901,72,899,73,898,74,904,75,905,76,903,77,904,78,909,79,910,80,908,81,907,82,912,83,913,84,911,85,906,86,917,87,918,88,916,89,915,90,925,91,924,92,926,93,928,94,929,95,927,96,930,97,931,98,922,99,921,100,934,101,935,102,933,103,934,104,906,105,937,106,936],"localNames":["array","callback","initial","label","right","length","step","index","accumulator"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":31,"name":"Array$prototype$flatMap","flags":592,"length":1,"params":2,"locals":10,"maxStack":5,"code":[789,267,1045,65803,66581,459583,0,131339,0,20,10,65540,131076,838,196875,0,196628,65546,262148,582,5,196618,327705,262411,36,327947,3,393483,3,459019,0,524555,0,590091,458762,262154,46,6684733,458762,196618,33,6422589,131082,65546,196618,458762,26,458762,196618,838,524299,0,393236,524298,326,5636157,3,589835,589834,524298,327705,46,5570621,589834,524298,33,5308477,327690,393226,55,7,56,393227,31,32,543,524298,589834,26,28,5,589834,56,589835,3801148,6422587,327690,393226,55,7,56,393227,31,32,543,524298,28,5,458762,56,458763,2228284,327690,67],"consts":["$Receiver","Array","Array.prototype.flatMap","$Callback","Array.flatMap","length","$IsArray"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,938,2,940,4,941,6,943,7,941,8,948,9,949,10,950,11,951,12,952,13,948,14,946,15,954,16,955,17,956,18,957,19,954,21,962,22,961,23,959,24,967,25,965,26,971,27,969,28,975,29,973,30,977,32,980,34,984,35,985,36,983,37,982,38,989,39,990,40,988,41,987,42,998,43,997,44,1000,45,1001,46,999,47,1002,48,1003,49,995,50,994,51,1005,52,1006,53,1007,54,1005,55,1004,56,1012,57,1011,58,1015,59,1017,60,1016,61,1014,62,1013,63,1022,64,1023,65,1021,66,1020,67,1027,68,1029,70,1028,72,1029,73,1026,74,1028,75,1026,76,1031,77,1032,78,1030,79,1026,80,1025,81,1035,82,1034,83,1035,84,1013,85,1004,86,1039,87,1041,89,1040,91,1041,92,1038,93,1040,94,1038,95,1042,96,1038,97,1037,98,1045,99,1044,100,1045,101,982,102,1047,103,1046],"localNames":["this","callback","thisArg","array","length","result","count","index","inner","at"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":32,"name":"sortWith","flags":72,"length":7,"params":7,"locals":15,"maxStack":11,"code":[36,459019,3,524555,0,590091,0,655627,0,721163,0,786699,0,852235,0,917771,524298,393226,25,46,7602237,393226,524298,26,720907,393226,524298,65539,43,26,589835,393226,524298,131075,43,26,655371,589834,786443,3,851979,720906,589834,46,3146047,786442,655370,46,6357053,0,196618,262154,720906,26,262154,786442,26,582,309,917515,917514,3,47,4390975,917514,917514,51,5308477,0,65556,458762,851978,262154,720906,26,838,5,720906,56,720907,6094907,0,65556,458762,851978,262154,786442,26,838,5,786442,56,786443,851978,56,851979,2687036,0,131092,262154,458762,851978,720906,589834,786442,655370,393226,524298,26,2118,5,524298,196611,43,524299,1048636,0,196628,10,65546,131082,262154,327690,1350,67],"consts":["length","$ArraySet","$MergeRest","$Sorted"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,1061,1,1059,2,1065,3,1063,4,1067,6,1070,8,1073,10,1076,12,1079,14,1082,16,1086,17,1088,18,1087,19,1085,20,1084,21,1095,22,1096,23,1094,24,1093,25,1101,26,1103,27,1104,28,1102,29,1100,30,1099,31,1109,32,1111,33,1112,34,1110,35,1108,36,1107,37,1116,38,1115,39,1120,40,1119,41,1124,42,1125,43,1123,44,1122,45,1127,46,1128,47,1126,48,1121,49,1137,50,1136,51,1139,52,1140,53,1138,54,1142,55,1143,56,1141,57,1134,58,1133,59,1132,60,1147,61,1148,62,1146,63,1145,64,1150,65,1151,66,1149,67,1144,68,1154,69,1155,70,1156,71,1157,72,1159,73,1160,74,1158,75,1154,77,1163,78,1162,79,1163,80,1144,81,1166,82,1167,83,1168,84,1169,85,1171,86,1172,87,1170,88,1166,90,1175,91,1174,92,1175,93,1178,94,1177,95,1178,96,1121,97,1180,98,1181,99,1182,100,1183,101,1184,102,1185,103,1186,104,1187,105,1188,106,1190,107,1191,108,1189,109,1180,111,1194,112,1195,113,1193,114,1194,115,1084,116,1197,117,1198,118,1199,119,1200,120,1201,121,1202,122,1203,123,1197,124,1196],"localNames":["target","into","holes","comparator","work","undefs","merges","merged","merge","middle","high","left","right","count","order"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":33,"name":"sortDefault","flags":72,"length":5,"params":5,"locals":6,"maxStack":9,"code":[0,20,196618,326,327947,0,65556,327690,326,720957,327740,0,131092,10,65546,131082,0,196628,327690,196618,582,262154,1350,67],"consts":["$SortState","$SortStep","$Sorted","$SortResult"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,1215,1,1216,2,1217,3,1215,4,1213,5,1219,6,1220,7,1221,8,1219,9,1218,11,1224,12,1225,13,1226,14,1227,15,1228,16,1229,17,1230,18,1231,19,1232,20,1229,21,1233,22,1224,23,1223],"localNames":["target","into","holes","values","undefs","state"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":34,"name":"Array$prototype$toLocaleString","flags":88,"length":0,"params":0,"locals":5,"maxStack":5,"code":[789,267,0,20,10,65540,131076,838,65803,196612,131339,3,196875,0,262411,196618,65546,262169,46,3473469,196618,3,48,1835069,131082,327684,43,131083,65546,196618,26,262155,262154,1,51,2556223,262154,0,51,3211325,131082,0,393236,262154,459033,70,326,43,131083,196618,56,196619,983100,131082,67],"consts":["$Receiver","Array","Array.prototype.toLocaleString","","length",",","String","toLocaleString"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,1234,2,1240,3,1241,4,1242,5,1243,6,1244,7,1240,8,1238,9,1248,10,1246,11,1252,12,1250,13,1254,15,1258,16,1260,17,1259,18,1257,19,1256,20,1265,21,1266,22,1264,23,1263,24,1269,25,1270,26,1268,27,1269,28,1275,29,1276,30,1274,31,1273,32,1280,33,1281,34,1279,35,1278,36,1283,37,1284,38,1282,39,1277,40,1287,41,1288,42,1289,43,1292,44,1291,45,1290,46,1288,47,1286,48,1287,49,1296,50,1295,51,1296,52,1256,53,1298,54,1297],"localNames":["this","array","result","index","item"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":35,"name":"fillCollection","flags":72,"length":3,"params":3,"locals":7,"maxStack":7,"code":[131082,4,50,458815,131082,65540,50,196875,262156,65546,3801162,3801147,327947,4719948,3997755,262156,262411,196618,54,1835069,0,131092,196612,10,262154,838,5,3735611,0,262164,262154,326,54,2949181,0,327700,393220,458756,131082,43,524292,43,582,5,3735611,0,131092,196612,10,262154,3,26,262154,65539,26,1094,5,852028,70,75,786491,70,4719949,983099,393483,4457806,70,5,393226,64,5,4456507,10,67],"consts":["Map","WeakMap","$Table","add","$IsObject","$Throw","TypeError","new ","(...) expects [key, value] pairs as entry objects."],"captures":[],"handlers":[15,58,64,0,65,68,70,0],"finallies":[],"finallyOffsets":[],"sites":[0,1310,1,1311,2,1309,3,1308,4,1313,5,1314,6,1312,7,1306,9,1319,10,1315,16,1316,17,1323,18,1322,19,1321,20,1325,21,1326,22,1327,23,1328,24,1329,25,1325,27,1321,28,1332,29,1333,30,1334,31,1332,32,1331,33,1330,34,1336,35,1337,36,1338,37,1341,38,1342,39,1340,40,1343,41,1339,42,1336,44,1330,45,1345,46,1346,47,1347,48,1348,49,1350,50,1351,51,1349,52,1353,53,1354,54,1352,55,1345,57,1315,72,1356,73,1355],"localNames":["target","items","kind","pairs","item","%it","%e"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":36,"name":"Map$groupBy","flags":72,"length":2,"params":2,"locals":2,"maxStack":5,"code":[0,20,10,65546,65540,838,67],"consts":["groupBy","Map"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,1363,1,1364,2,1365,3,1366,4,1367,5,1363,6,1362],"localNames":["items","callback"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":37,"name":"Object$groupBy","flags":72,"length":2,"params":2,"locals":2,"maxStack":5,"code":[0,20,10,65546,65540,838,67],"consts":["groupBy","Object"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,1374,1,1375,2,1376,3,1377,4,1378,5,1374,6,1373],"localNames":["items","callback"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":38,"name":"groupBy","flags":72,"length":3,"params":3,"locals":9,"maxStack":6,"code":[10,1,50,458815,10,0,50,1048637,0,20,65540,131082,131076,43,582,5,0,196628,65546,131082,262148,43,582,5,0,327700,393220,131082,582,196875,3,262411,0,327947,393228,10,4915274,4915259,459019,5834572,5111867,393228,393483,0,65546,393226,262154,55,7,56,262155,582,327691,131082,458756,50,4325437,0,524308,0,327700,589828,327690,582,326,327691,0,327700,655364,196618,327690,393226,1094,5,2555964,70,75,2490427,70,5834573,2687035,524555,5572430,70,5,524298,64,5,5570619,196618,67],"consts":["$Throw","TypeError",".groupBy expects an iterable collection.","$Callback",".groupBy","$Table","groups","Object","String","groupKey","group"],"captures":[],"handlers":[41,75,81,0,82,85,87,0],"finallies":[],"finallyOffsets":[],"sites":[0,1388,1,1389,2,1387,3,1386,4,1391,5,1392,6,1390,7,1385,8,1394,9,1395,10,1396,11,1398,12,1399,13,1397,14,1394,16,1401,17,1402,18,1403,19,1405,20,1406,21,1404,22,1401,24,1410,25,1411,26,1412,27,1413,28,1410,29,1408,30,1417,31,1415,32,1419,35,1425,36,1421,42,1422,43,1430,44,1431,45,1432,46,1434,48,1433,50,1434,51,1430,52,1429,53,1437,54,1438,55,1436,56,1435,57,1442,58,1443,59,1444,60,1445,61,1446,62,1447,63,1444,64,1442,65,1441,66,1449,67,1450,68,1451,69,1452,70,1453,71,1454,72,1449,74,1421,89,1456,90,1455],"localNames":["items","callback","kind","groups","index","key","item","%it","%e"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":39,"name":"insertComputed","flags":72,"length":3,"params":3,"locals":4,"maxStack":6,"code":[0,131082,65546,326,196875,0,20,65540,10,65546,196618,1094,5,196618,67],"consts":["$Table","add"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,1466,1,1467,2,1468,3,1466,4,1464,5,1470,6,1471,7,1472,8,1473,9,1474,10,1475,11,1470,13,1477,14,1476],"localNames":["target","key","callback","value"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":40,"name":"Map$prototype$forEach","flags":592,"length":1,"params":2,"locals":3,"maxStack":7,"code":[789,267,1045,65803,66581,459583,0,131339,0,20,0,65556,10,131076,196612,838,65546,131082,262148,1094,5,0,67],"consts":["collectionForEach","$Receiver","Map","Map.prototype.forEach","Map.forEach"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,1478,2,1480,4,1481,6,1483,7,1481,8,1486,9,1487,10,1488,11,1489,12,1490,13,1491,14,1492,15,1488,16,1493,17,1494,18,1495,19,1486,21,1484],"localNames":["this","callback","thisArg"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":41,"name":"Set$prototype$forEach","flags":592,"length":1,"params":2,"locals":3,"maxStack":7,"code":[789,267,1045,65803,66581,459583,0,131339,0,20,0,65556,10,131076,196612,838,65546,131082,262148,1094,5,0,67],"consts":["collectionForEach","$Receiver","Set","Set.prototype.forEach","Set.forEach"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,1496,2,1498,4,1499,6,1501,7,1499,8,1504,9,1505,10,1506,11,1507,12,1508,13,1509,14,1510,15,1506,16,1511,17,1512,18,1513,19,1504,21,1502],"localNames":["this","callback","thisArg"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":42,"name":"collectionForEach","flags":72,"length":4,"params":4,"locals":7,"maxStack":5,"code":[0,20,65546,196618,582,5,262156,0,65556,131076,10,582,2031690,2031675,327947,2950476,2228283,262156,262411,131082,65546,262154,65539,26,262154,3,26,10,838,5,983100,70,75,917563,70,2950477,1114171,393483,2688334,70,5,393226,64,5,2687035,0,67],"consts":["$Callback","$Table","entries"],"captures":[],"handlers":[17,31,37,0,38,41,43,0],"finallies":[],"finallyOffsets":[],"sites":[0,1522,1,1523,2,1524,3,1525,4,1522,7,1530,8,1531,9,1532,10,1533,11,1530,12,1526,18,1527,19,1538,20,1537,21,1540,22,1541,23,1539,24,1543,25,1544,26,1542,27,1545,28,1535,30,1526,45,1520],"localNames":["target","callback","thisArg","label","entry","%it","%e"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":43,"name":"Set$prototype$union","flags":88,"length":1,"params":1,"locals":2,"maxStack":7,"code":[789,65803,0,20,0,65556,65546,131076,196612,838,10,262148,838,67],"consts":["setMethod","$Receiver","Set","Set.prototype.union","union"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,1546,2,1551,3,1552,4,1553,5,1554,6,1555,7,1556,8,1557,9,1553,10,1558,11,1559,12,1551,13,1550],"localNames":["other","this"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":44,"name":"Set$prototype$intersection","flags":88,"length":1,"params":1,"locals":2,"maxStack":7,"code":[789,65803,0,20,0,65556,65546,131076,196612,838,10,262148,838,67],"consts":["setMethod","$Receiver","Set","Set.prototype.intersection","intersection"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,1560,2,1565,3,1566,4,1567,5,1568,6,1569,7,1570,8,1571,9,1567,10,1572,11,1573,12,1565,13,1564],"localNames":["other","this"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":45,"name":"Set$prototype$difference","flags":88,"length":1,"params":1,"locals":2,"maxStack":7,"code":[789,65803,0,20,0,65556,65546,131076,196612,838,10,262148,838,67],"consts":["setMethod","$Receiver","Set","Set.prototype.difference","difference"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,1574,2,1579,3,1580,4,1581,5,1582,6,1583,7,1584,8,1585,9,1581,10,1586,11,1587,12,1579,13,1578],"localNames":["other","this"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":46,"name":"Set$prototype$symmetricDifference","flags":88,"length":1,"params":1,"locals":2,"maxStack":7,"code":[789,65803,0,20,0,65556,65546,131076,196612,838,10,262148,838,67],"consts":["setMethod","$Receiver","Set","Set.prototype.symmetricDifference","symmetricDifference"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,1588,2,1593,3,1594,4,1595,5,1596,6,1597,7,1598,8,1599,9,1595,10,1600,11,1601,12,1593,13,1592],"localNames":["other","this"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":47,"name":"Set$prototype$isSubsetOf","flags":88,"length":1,"params":1,"locals":2,"maxStack":7,"code":[789,65803,0,20,0,65556,65546,131076,196612,838,10,262148,838,67],"consts":["setMethod","$Receiver","Set","Set.prototype.isSubsetOf","isSubsetOf"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,1602,2,1607,3,1608,4,1609,5,1610,6,1611,7,1612,8,1613,9,1609,10,1614,11,1615,12,1607,13,1606],"localNames":["other","this"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":48,"name":"Set$prototype$isSupersetOf","flags":88,"length":1,"params":1,"locals":2,"maxStack":7,"code":[789,65803,0,20,0,65556,65546,131076,196612,838,10,262148,838,67],"consts":["setMethod","$Receiver","Set","Set.prototype.isSupersetOf","isSupersetOf"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,1616,2,1621,3,1622,4,1623,5,1624,6,1625,7,1626,8,1627,9,1623,10,1628,11,1629,12,1621,13,1620],"localNames":["other","this"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":49,"name":"Set$prototype$isDisjointFrom","flags":88,"length":1,"params":1,"locals":2,"maxStack":7,"code":[789,65803,0,20,0,65556,65546,131076,196612,838,10,262148,838,67],"consts":["setMethod","$Receiver","Set","Set.prototype.isDisjointFrom","isDisjointFrom"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,1630,2,1635,3,1636,4,1637,5,1638,6,1639,7,1640,8,1641,9,1637,10,1642,11,1643,12,1635,13,1634],"localNames":["other","this"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":50,"name":"setMethod","flags":72,"length":3,"params":3,"locals":18,"maxStack":5,"code":[0,20,65546,326,54,1048637,0,65556,131076,196612,131082,43,262148,43,582,5,65546,327705,309,196875,196618,196618,51,2228285,0,65556,131076,196612,131082,43,393220,43,582,5,196618,3,46,3145789,0,65556,458756,196612,131082,43,524292,43,582,5,65546,589849,262411,65546,655385,327947,0,720916,262154,326,54,4259903,0,720916,327690,326,54,4980797,0,65556,131076,196612,131082,43,786436,43,582,5,0,851988,327684,10,582,393483,131082,917508,50,5833023,393226,196618,48,6029373,2,67,131082,983044,50,6488383,393226,196618,46,6684733,2,67,131082,1048580,50,7209021,1114132,65352,72,8454203,131082,1179652,50,7667775,131082,1245188,50,7929919,131082,1310724,50,8388669,0,851988,1376260,10,582,8454203,0,459019,131082,917508,50,9764927,131082,1048580,50,9240639,131082,1245188,50,9502783,131082,1441796,50,9765183,393226,196618,47,524555,0,590091,524298,16056381,720908,0,851988,1507332,131082,1245188,50,10747965,458762,10813499,10,582,14614602,14614587,852235,15535436,14811195,720908,721163,65546,262154,720906,326,54,54,589835,131082,1048580,50,12714045,589834,12648509,0,851988,1572868,458762,720906,838,5,14549051,131082,1245188,50,13631549,589834,13566013,0,851988,1638404,458762,720906,838,5,14549051,589834,131082,1441796,50,50,14549053,2,983307,14421326,70,1611,5,983050,67,11075644,70,75,11010107,70,15535437,11206715,917771,15273294,70,5,917514,64,5,15269947,458762,0,50,15925309,258,15990843,458762,67,65546,327690,70,655627,0,20,655370,326,54,17367101,0,65556,131076,196612,131082,43,1703940,43,582,5,786444,0,1769492,655370,258,582,23199818,23199803,1048843,24121420,23396411,786444,786699,0,851988,589828,10,786442,838,589835,131082,1179652,50,19464253,0,851988,1572868,458762,786442,838,5,23134267,131082,1048580,50,20381757,589834,20316221,0,851988,1572868,458762,786442,838,5,23134267,131082,1245188,50,21168189,0,851988,1638404,458762,786442,838,5,23134267,131082,1310724,50,22216765,0,851988,589834,21823549,1638404,21889083,1572868,458762,786442,838,5,23134267,589834,131082,1441796,50,50,23134269,2,983307,23007310,70,1611,5,983050,67,17956924,70,75,17891387,70,24121421,18087995,1114379,23859278,70,5,1114122,64,5,23855163,458762,0,50,24510525,258,24576059,458762,67],"consts":["$IsObject","$Throw","TypeError","Set."," expects a Set-like object.","size"," received a Set-like object with an invalid size.","RangeError"," received a Set-like object with a negative size.","has","keys","$IsCallable"," expects callable 'has' and 'keys' methods.","$Table","isSubsetOf","isSupersetOf","intersection","Set","union","difference","symmetricDifference","copy","isDisjointFrom","values","add","delete"," expects 'keys' to return an iterator object.","$Direct"],"captures":[],"handlers":[171,223,229,0,230,233,235,0,276,354,360,0,361,364,366,0],"finallies":[],"finallyOffsets":[],"sites":[0,1652,1,1653,2,1654,3,1652,4,1651,5,1650,6,1656,7,1657,8,1658,9,1661,10,1662,11,1660,12,1663,13,1659,14,1656,16,1669,17,1668,18,1667,19,1665,20,1673,21,1674,22,1672,23,1671,24,1676,25,1677,26,1678,27,1681,28,1682,29,1680,30,1683,31,1679,32,1676,34,1686,35,1687,36,1685,37,1684,38,1689,39,1690,40,1691,41,1694,42,1695,43,1693,44,1696,45,1692,46,1689,48,1701,49,1700,50,1698,51,1707,52,1706,53,1704,54,1712,55,1713,56,1714,57,1712,58,1711,59,1710,60,1716,61,1717,62,1718,63,1716,64,1715,65,1709,66,1720,67,1721,68,1722,69,1725,70,1726,71,1724,72,1727,73,1723,74,1720,76,1731,77,1732,78,1733,79,1734,80,1731,81,1729,82,1738,83,1739,84,1737,85,1736,86,1741,87,1742,88,1740,89,1735,90,1744,91,1743,92,1748,93,1749,94,1747,95,1746,96,1751,97,1752,98,1750,99,1745,100,1754,101,1753,102,1760,103,1761,104,1759,105,1758,106,1763,107,1762,109,1758,110,1768,111,1769,112,1767,113,1766,114,1771,115,1772,116,1770,117,1765,118,1774,119,1775,120,1773,121,1764,122,1776,123,1777,124,1778,125,1779,126,1776,127,1764,128,1780,129,1756,130,1786,131,1787,132,1785,133,1784,134,1792,135,1793,136,1791,137,1790,138,1795,139,1796,140,1794,141,1789,142,1798,143,1799,144,1797,145,1788,146,1801,147,1802,148,1800,149,1782,150,1804,152,1807,153,1806,155,1813,156,1814,157,1815,158,1818,159,1819,160,1817,161,1816,162,1820,163,1816,164,1821,165,1813,166,1809,172,1810,173,1831,174,1830,175,1832,176,1828,177,1827,178,1826,179,1825,180,1835,181,1836,182,1834,183,1833,184,1839,185,1838,186,1841,187,1842,188,1843,189,1844,190,1845,191,1841,193,1833,194,1848,195,1849,196,1847,197,1846,198,1852,199,1851,200,1854,201,1855,202,1856,203,1857,204,1858,205,1854,207,1846,208,1861,209,1863,210,1864,211,1862,212,1860,213,1859,214,1866,215,1865,222,1809,237,1870,238,1871,239,1869,240,1868,241,1872,242,1868,243,1873,244,1867,245,1880,246,1879,247,1877,248,1875,249,1883,250,1884,251,1885,252,1883,253,1882,254,1881,255,1887,256,1888,257,1889,258,1892,259,1893,260,1891,261,1894,262,1890,263,1887,266,1899,267,1900,268,1901,269,1902,270,1899,271,1895,277,1896,278,1907,279,1908,280,1909,281,1910,282,1911,283,1907,284,1906,285,1914,286,1915,287,1913,288,1912,289,1917,290,1918,291,1919,292,1920,293,1921,294,1917,296,1912,297,1924,298,1925,299,1923,300,1922,301,1928,302,1927,303,1930,304,1931,305,1932,306,1933,307,1934,308,1930,310,1922,311,1937,312,1938,313,1936,314,1935,315,1940,316,1941,317,1942,318,1943,319,1944,320,1940,322,1935,323,1947,324,1948,325,1946,326,1945,327,1950,328,1951,329,1953,330,1952,331,1954,332,1952,333,1955,334,1956,335,1957,336,1950,338,1945,339,1960,340,1962,341,1963,342,1961,343,1959,344,1958,345,1965,346,1964,353,1895,368,1969,369,1970,370,1968,371,1967,372,1971,373,1967,374,1972,375,1966],"localNames":["target","other","name","size","has","keys","own","result","asks","found","iterator","item","item","%it","%e","%ret","%it","%e"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":51,"name":"Object$fromEntries","flags":72,"length":1,"params":1,"locals":5,"maxStack":7,"code":[35,65803,131084,10,2621514,2621499,196875,3539788,2818107,131084,131339,0,20,131082,258,582,54,1572925,0,65556,131076,196612,582,5,0,262164,65546,0,327700,131082,3,26,326,131082,65539,26,258,1094,5,458812,70,75,393275,70,3539789,589883,262411,3277646,70,5,262154,64,5,3276859,65546,67],"consts":["$IsObject","$Throw","TypeError","Object.fromEntries expects [key, value] entry objects.","$Define","String"],"captures":[],"handlers":[9,40,46,0,47,50,52,0],"finallies":[],"finallyOffsets":[],"sites":[0,1980,1,1978,3,1985,4,1981,10,1982,11,1989,12,1990,13,1991,14,1992,15,1989,16,1988,17,1987,18,1994,19,1995,20,1996,21,1997,22,1994,24,1999,25,2000,26,2001,27,2002,28,2003,29,2005,30,2006,31,2004,32,2002,33,2008,34,2009,35,2007,36,2010,37,1999,39,1981,54,2012,55,2011],"localNames":["entries","result","entry","%it","%e"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":52,"name":"Math$sumPrecise","flags":72,"length":1,"params":1,"locals":5,"maxStack":5,"code":[36,65803,131084,10,2031690,2031675,196875,2949964,2228283,131084,131339,131082,821,4,51,1441853,0,65556,131076,196612,582,5,0,262164,65546,65546,327705,131082,838,5,458812,70,75,393275,70,2949965,589883,262411,2687822,70,5,262154,64,5,2687035,0,393236,65546,326,67],"consts":["number","$Throw","TypeError","Math.sumPrecise expects an iterable of numbers.","$ArraySet","length","$SumPrecise"],"captures":[],"handlers":[9,31,37,0,38,41,43,0],"finallies":[],"finallyOffsets":[],"sites":[0,2020,1,2018,3,2025,4,2021,10,2022,11,2030,12,2029,13,2031,14,2028,15,2027,16,2033,17,2034,18,2035,19,2036,20,2033,22,2038,23,2039,24,2040,25,2042,26,2041,27,2044,28,2038,30,2021,45,2046,46,2047,47,2048,48,2046,49,2045],"localNames":["items","numbers","item","%it","%e"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":53,"name":"aggregateError","flags":72,"length":2,"params":2,"locals":6,"maxStack":6,"code":[36,131339,196620,65546,1310794,1310779,262411,2229324,1507387,196620,196875,0,20,131082,131082,65561,196618,838,5,458812,70,75,393275,70,2229325,589883,327947,1967182,70,5,327690,64,5,1966139,0,131092,10,196612,131082,2,1094,67],"consts":["$ArraySet","length","$Define","errors"],"captures":[],"handlers":[9,20,26,0,27,30,32,0],"finallies":[],"finallyOffsets":[],"sites":[0,2057,1,2055,3,2062,4,2058,10,2059,11,2064,12,2065,13,2066,14,2068,15,2067,16,2070,17,2064,19,2058,34,2072,35,2073,36,2074,37,2075,38,2076,39,2077,40,2072,41,2071],"localNames":["error","errors","list","item","%it","%e"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":54,"name":"collectBytes","flags":72,"length":6,"params":6,"locals":11,"maxStack":7,"code":[0,20,10,326,54,1376317,0,65556,131076,65546,196612,43,0,262164,10,326,43,327684,43,582,5,36,393483,524300,10,2687050,2687035,590091,3606860,2883643,524300,524555,0,393236,393226,393226,458777,524298,838,5,1835068,70,75,1769531,70,3606861,1966139,655627,3344718,70,5,655370,64,5,3342395,3,459019,131082,0,51,5505085,458762,393226,458777,46,5505085,393226,458762,31,32,543,196618,131082,393226,458762,26,458762,582,28,5,458762,56,458763,3997756,0,524308,393226,262154,327690,838,67],"consts":["$IsIterable","$Throw","TypeError"," expects a Uint8Array, an array, or an iterable of numbers, received ","$Describe",".","$ArraySet","length","$Bytes"],"captures":[],"handlers":[30,41,47,0,48,51,53,0],"finallies":[],"finallyOffsets":[],"sites":[0,2089,1,2090,2,2091,3,2089,4,2088,5,2087,6,2093,7,2094,8,2095,9,2099,10,2100,11,2098,12,2101,13,2102,14,2103,15,2101,16,2097,17,2104,18,2096,19,2093,21,2108,22,2106,24,2113,25,2109,31,2110,32,2115,33,2116,34,2117,35,2119,36,2118,37,2121,38,2115,40,2109,55,2125,56,2123,57,2128,58,2129,59,2127,60,2126,61,2133,62,2135,63,2134,64,2132,65,2131,66,2141,67,2142,68,2140,69,2142,70,2140,71,2146,72,2145,73,2148,74,2149,75,2147,76,2150,77,2143,78,2140,79,2139,80,2153,81,2152,82,2153,83,2131,84,2155,85,2156,86,2157,87,2158,88,2159,89,2155,90,2154],"localNames":["source","name","mapper","thisArg","into","offset","values","index","item","%it","%e"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":55,"name":"argumentsValues","flags":92,"length":0,"params":0,"locals":2,"maxStack":2,"code":[789,267,81,3,65803,65546,10,25,46,1376317,10,65546,26,82,1048659,67,5,65546,56,65547,327740,0,67],"consts":["length"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,2160,3,2166,4,2164,5,2169,6,2171,7,2170,8,2168,9,2167,10,2177,11,2178,12,2176,13,2175,17,2181,18,2180,19,2181,20,2167,21,2162],"localNames":["this","index"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":56,"name":"objectEntries","flags":72,"length":2,"params":2,"locals":6,"maxStack":7,"code":[0,20,10,258,0,838,131339,36,196875,3,262411,262154,131082,65561,46,3211325,327692,131082,262154,26,327947,0,131092,10,327690,582,2949181,0,196628,196618,196618,65561,65546,2490429,10,327690,26,2818107,327690,10,327690,26,131108,838,5,262154,56,262155,720956,196618,67],"consts":["$OwnKeys","length","$IsEnumerableOwn","$ArraySet"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,2190,1,2191,2,2192,3,2193,4,2194,5,2190,6,2188,7,2198,8,2196,9,2202,10,2200,11,2205,12,2207,13,2206,14,2204,15,2203,17,2214,18,2215,19,2213,20,2211,21,2217,22,2218,23,2219,24,2220,25,2217,26,2216,27,2222,28,2223,29,2224,30,2226,31,2225,32,2229,33,2228,34,2231,35,2232,36,2230,37,2228,38,2234,39,2236,40,2237,41,2235,42,2233,43,2222,45,2240,46,2239,47,2240,48,2203,49,2242,50,2241],"localNames":["source","values","keys","result","index","key"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":57,"name":"objectAssign","flags":72,"length":2,"params":2,"locals":7,"maxStack":5,"code":[3,131339,131082,65546,25,46,3735613,196620,262156,327692,65546,131082,26,196875,0,65556,196618,2,0,838,262411,3,327947,327690,262154,25,46,3473469,393228,262154,327690,26,393483,0,131092,196618,393226,582,3211325,10,393226,31,32,543,196618,393226,26,28,5,327690,56,327691,1507388,131082,56,131083,131132,10,67],"consts":["length","$OwnKeys","$IsEnumerableOwn"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,2251,1,2249,2,2254,3,2256,4,2255,5,2253,6,2252,10,2263,11,2264,12,2262,13,2260,14,2268,15,2269,16,2270,17,2271,18,2272,19,2268,20,2266,21,2276,22,2274,23,2279,24,2281,25,2280,26,2278,27,2277,29,2288,30,2289,31,2287,32,2285,33,2291,34,2292,35,2293,36,2294,37,2291,38,2290,39,2298,40,2299,41,2297,42,2299,43,2297,44,2301,45,2302,46,2300,47,2297,48,2296,49,2305,50,2304,51,2305,52,2277,53,2308,54,2307,55,2308,56,2252,57,2310,58,2309],"localNames":["target","sources","at","source","keys","index","key"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":58,"name":"readPairs","flags":72,"length":4,"params":4,"locals":12,"maxStack":7,"code":[0,20,10,326,54,917565,0,65556,131082,196618,10,65546,1094,67,36,262411,0,327947,393228,10,5701706,5701691,524555,6621260,5898299,393228,393483,0,20,393226,326,54,2687037,0,131092,196612,65546,262148,43,582,5,36,327691,458764,393226,4194378,4194363,655627,5114444,4390971,458764,459019,0,327700,327690,327690,393241,0,458772,458762,326,838,5,3145788,70,75,3080251,70,5114445,3276859,721163,4852302,70,5,720906,64,5,4849723,0,327700,262154,262154,393241,327690,838,5,1507388,70,75,1441851,70,6621261,1638459,590091,6359118,70,5,589834,64,5,6357051,0,65556,131082,196618,262154,65546,1094,67],"consts":["$IsIterable","$Pairs","$Throw","TypeError"," expects iterable [name, value] pairs.","$ArraySet","length","String"],"captures":[],"handlers":[50,64,70,0,71,74,76,0,25,87,93,0,94,97,99,0],"finallies":[],"finallyOffsets":[],"sites":[0,2320,1,2321,2,2322,3,2320,4,2319,5,2318,6,2324,7,2325,8,2326,9,2327,10,2328,11,2329,12,2324,13,2323,14,2333,15,2331,16,2335,19,2341,20,2337,26,2338,27,2345,28,2346,29,2347,30,2345,31,2344,32,2343,33,2349,34,2350,35,2351,36,2353,37,2354,38,2352,39,2349,41,2358,42,2357,44,2363,45,2359,51,2360,52,2365,53,2366,54,2367,55,2369,56,2368,57,2371,58,2372,59,2373,60,2371,61,2365,63,2359,78,2375,79,2376,80,2377,81,2379,82,2378,83,2381,84,2375,86,2337,101,2383,102,2384,103,2385,104,2386,105,2387,106,2388,107,2383,108,2382],"localNames":["init","label","kind","proto","pairs","strings","pair","item","%it","%e","%it","%e"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":59,"name":"pairsForEach","flags":72,"length":4,"params":4,"locals":5,"maxStack":5,"code":[3,262411,262154,65546,25,46,1703997,196618,131082,65546,262154,26,65539,26,65546,262154,26,3,26,10,838,5,262154,56,262155,131132,0,67],"consts":["length"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,2399,1,2397,2,2402,3,2404,4,2403,5,2401,6,2400,7,2411,8,2410,9,2414,10,2415,11,2413,12,2416,13,2412,14,2419,15,2420,16,2418,17,2421,18,2417,19,2422,20,2408,22,2425,23,2424,24,2425,25,2400,26,2395],"localNames":["target","pairs","callback","thisArg","index"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":60,"name":"Iterator$from","flags":72,"length":1,"params":1,"locals":1,"maxStack":10,"code":[0,20,10,326,721215,0,65556,10,131092,196633,582,917565,10,67,0,262164,0,327700,10,0,393236,10,258,458756,838,582,326,67],"consts":["$IsObject","$Inherits","Iterator","prototype","prime","wrapHelper","flattenable","Iterator.from"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,2432,1,2433,2,2434,3,2432,4,2431,5,2435,6,2436,7,2437,8,2439,9,2438,10,2435,11,2430,12,2442,13,2441,14,2444,15,2445,16,2446,17,2447,18,2448,19,2449,20,2450,21,2451,22,2452,23,2453,24,2449,25,2446,26,2444,27,2443],"localNames":["value"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":61,"name":"wrapHelper","flags":76,"length":2,"params":2,"locals":9,"maxStack":3,"code":[81,2,131339,0,82,786515,393483,393226,327947,131075,262411,3866683,5,258,131083,196620,65546,2555978,2555963,459019,3475276,2752571,196620,196875,196618,82,2424915,393483,2099022,70,1611,5,393226,327947,131075,262411,3866683,5,1310780,70,75,1245243,70,3475277,1441851,524555,3213134,70,5,524298,64,5,3211323,3,262411,3866683,327947,65539,262411,131082,54,4390973,0,20,10,326,5,66,327690,67,0,67],"consts":["closeIterator"],"captures":[],"handlers":[22,39,45,0,46,49,51,0,3,53,56,0],"finallies":[4,5,0,3,70,-1,68],"finallyOffsets":[0],"sites":[0,2454,1,2462,2,2460,3,2466,13,2470,14,2469,16,2475,17,2471,23,2472,24,2478,25,2477,38,2471,53,2463,59,2482,60,2481,61,2480,62,2484,63,2485,64,2486,65,2484,67,2463,70,2458],"localNames":["source","iterator","started","item","%ftag0","%fval0","%ret","%it","%e"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":62,"name":"Iterator$prototype$map","flags":88,"length":1,"params":1,"locals":3,"maxStack":7,"code":[789,65803,0,20,65546,2,582,131339,0,65556,10,131076,582,5,0,196628,0,262164,65546,131082,10,838,326,67],"consts":["$Direct","$Callback","Iterator.prototype.map","prime","mapHelper"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,2487,2,2494,3,2495,4,2496,5,2497,6,2494,7,2492,8,2499,9,2500,10,2501,11,2502,12,2499,14,2504,15,2505,16,2506,17,2507,18,2508,19,2509,20,2510,21,2506,22,2504,23,2503],"localNames":["mapper","this","iterator"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":63,"name":"mapHelper","flags":76,"length":3,"params":3,"locals":11,"maxStack":5,"code":[81,2,196875,262156,0,82,852051,524555,524298,459019,131075,393483,4587579,5,258,196619,3,262411,327692,65546,3276874,3276859,590091,4196684,3473467,327692,327947,0,131082,327690,262154,55,7,56,262155,582,82,3145811,524555,2820430,70,1611,5,524298,459019,131075,393483,4587579,5,1507388,70,75,1441851,70,4196685,1638459,655627,3934542,70,5,655370,64,5,3932219,3,393483,4587579,459019,65539,393483,196618,54,5111869,0,20,10,326,5,66,458762,67,0,67],"consts":["closeIterator"],"captures":[],"handlers":[25,50,56,0,57,60,62,0,3,64,67,0],"finallies":[6,7,0,3,81,-1,79],"finallyOffsets":[0],"sites":[0,2511,1,2520,2,2518,4,2524,14,2528,15,2527,16,2532,17,2530,19,2537,20,2533,26,2534,27,2540,28,2541,29,2542,30,2544,32,2543,34,2544,35,2540,36,2539,49,2533,64,2521,70,2548,71,2547,72,2546,73,2550,74,2551,75,2552,76,2550,78,2521,81,2516],"localNames":["source","iterator","mapper","started","counter","item","%ftag0","%fval0","%ret","%it","%e"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":64,"name":"Iterator$prototype$filter","flags":88,"length":1,"params":1,"locals":3,"maxStack":7,"code":[789,65803,0,20,65546,2,582,131339,0,65556,10,131076,582,5,0,196628,0,262164,65546,131082,10,838,326,67],"consts":["$Direct","$Callback","Iterator.prototype.filter","prime","filterHelper"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,2553,2,2560,3,2561,4,2562,5,2563,6,2560,7,2558,8,2565,9,2566,10,2567,11,2568,12,2565,14,2570,15,2571,16,2572,17,2573,18,2574,19,2575,20,2576,21,2572,22,2570,23,2569],"localNames":["predicate","this","iterator"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":65,"name":"filterHelper","flags":76,"length":3,"params":3,"locals":11,"maxStack":5,"code":[81,2,196875,262156,0,82,852051,524555,524298,459019,131075,393483,4718651,5,258,196619,3,262411,327692,65546,3407946,3407931,590091,4327756,3604539,327692,327947,0,131082,327690,262154,55,7,56,262155,582,3342397,327690,82,3276883,524555,2951502,70,1611,5,524298,459019,131075,393483,4718651,5,1507388,70,75,1441851,70,4327757,1638459,655627,4065614,70,5,655370,64,5,4063291,3,393483,4718651,459019,65539,393483,196618,54,5242941,0,20,10,326,5,66,458762,67,0,67],"consts":["closeIterator"],"captures":[],"handlers":[25,52,58,0,59,62,64,0,3,66,69,0],"finallies":[6,7,0,3,83,-1,81],"finallyOffsets":[0],"sites":[0,2577,1,2586,2,2584,4,2590,14,2594,15,2593,16,2598,17,2596,19,2603,20,2599,26,2600,27,2605,28,2606,29,2607,30,2609,32,2608,34,2609,35,2605,36,2604,37,2612,38,2611,51,2599,66,2587,72,2616,73,2615,74,2614,75,2618,76,2619,77,2620,78,2618,80,2587,83,2582],"localNames":["source","iterator","predicate","started","counter","item","%ftag0","%fval0","%ret","%it","%e"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":66,"name":"Iterator$prototype$take","flags":88,"length":1,"params":1,"locals":3,"maxStack":10,"code":[789,65803,0,20,65546,2,582,131339,0,65556,0,131092,65546,131082,0,196628,10,262148,582,838,326,67],"consts":["$Direct","prime","takeHelper","count","take"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,2621,2,2628,3,2629,4,2630,5,2631,6,2628,7,2626,8,2633,9,2634,10,2635,11,2636,12,2637,13,2638,14,2639,15,2640,16,2641,17,2642,18,2639,19,2635,20,2633,21,2632],"localNames":["limit","this","iterator"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":67,"name":"takeHelper","flags":76,"length":3,"params":3,"locals":10,"maxStack":3,"code":[81,2,196875,0,82,786515,459019,458762,393483,131075,327947,5570619,5,258,196619,131082,3,50,1900605,0,20,10,326,459019,458762,393483,131075,327947,5570619,262156,65546,4259914,4259899,524555,5179468,4456507,262156,262411,131082,312,131083,262154,82,3539027,459019,3213390,70,1611,5,458762,393483,131075,327947,5570619,5,131082,3,50,4194365,4130894,70,1611,5,5177403,2228284,70,75,2162747,70,5179469,2359355,590091,4917326,70,5,589834,64,5,4915259,3,327947,5570619,393483,65539,327947,196618,54,6094909,0,20,10,326,5,66,393226,67,0,67],"consts":["closeIterator"],"captures":[],"handlers":[36,65,71,0,72,75,77,0,3,79,82,0],"finallies":[5,6,0,3,96,-1,94],"finallyOffsets":[0],"sites":[0,2643,1,2652,2,2650,3,2656,13,2660,14,2659,15,2663,16,2664,17,2662,18,2661,19,2666,20,2667,21,2668,22,2666,23,2665,30,2673,31,2669,37,2670,38,2677,39,2676,40,2677,41,2680,42,2679,55,2683,56,2684,57,2682,58,2681,59,2685,64,2669,79,2653,85,2689,86,2688,87,2687,88,2691,89,2692,90,2693,91,2691,93,2653,96,2648],"localNames":["source","iterator","remaining","started","item","%ftag0","%fval0","%ret","%it","%e"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":68,"name":"Iterator$prototype$drop","flags":88,"length":1,"params":1,"locals":3,"maxStack":10,"code":[789,65803,0,20,65546,2,582,131339,0,65556,0,131092,65546,131082,0,196628,10,262148,582,838,326,67],"consts":["$Direct","prime","dropHelper","count","drop"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,2694,2,2701,3,2702,4,2703,5,2704,6,2701,7,2699,8,2706,9,2707,10,2708,11,2709,12,2710,13,2711,14,2712,15,2713,16,2714,17,2715,18,2712,19,2708,20,2706,21,2705],"localNames":["limit","this","iterator"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":69,"name":"dropHelper","flags":76,"length":3,"params":3,"locals":10,"maxStack":3,"code":[81,2,196875,0,82,786515,459019,458762,393483,131075,327947,4390971,5,258,196619,262156,65546,3080266,3080251,524555,3999820,3276859,262156,262411,131082,3,48,2097213,131082,312,131083,3014715,262154,82,2949203,459019,2623566,70,1611,5,458762,393483,131075,327947,4390971,5,1310780,70,75,1245243,70,3999821,1441851,590091,3737678,70,5,589834,64,5,3735611,3,327947,4390971,393483,65539,327947,196618,54,4915261,0,20,10,326,5,66,393226,67,0,67],"consts":["closeIterator"],"captures":[],"handlers":[22,47,53,0,54,57,59,0,3,61,64,0],"finallies":[5,6,0,3,78,-1,76],"finallyOffsets":[0],"sites":[0,2716,1,2725,2,2723,3,2729,13,2733,14,2732,16,2738,17,2734,23,2735,24,2742,25,2743,26,2741,27,2740,28,2746,29,2745,30,2746,31,2740,32,2749,33,2748,46,2734,61,2726,67,2753,68,2752,69,2751,70,2755,71,2756,72,2757,73,2755,75,2726,78,2721],"localNames":["source","iterator","remaining","started","item","%ftag0","%fval0","%ret","%it","%e"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":70,"name":"Iterator$prototype$flatMap","flags":88,"length":1,"params":1,"locals":3,"maxStack":7,"code":[789,65803,0,20,65546,2,582,131339,0,65556,10,131076,582,5,0,196628,0,262164,65546,131082,10,838,326,67],"consts":["$Direct","$Callback","Iterator.prototype.flatMap","prime","flatMapHelper"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,2758,2,2765,3,2766,4,2767,5,2768,6,2765,7,2763,8,2770,9,2771,10,2772,11,2773,12,2770,14,2775,15,2776,16,2777,17,2778,18,2779,19,2780,20,2781,21,2777,22,2775,23,2774],"localNames":["mapper","this","iterator"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":71,"name":"flatMapHelper","flags":76,"length":3,"params":3,"locals":14,"maxStack":7,"code":[81,2,196875,262156,0,82,852051,590091,589834,524555,131075,459019,6750267,5,258,196619,3,262411,327692,65546,5439562,5439547,655627,6359628,5636155,327692,327947,393228,0,20,0,131082,327690,262154,55,7,56,262155,582,2,65540,838,4456522,4456507,786699,5377100,4653115,393228,393483,393226,82,4325459,590091,3738702,70,1611,5,4000334,70,1611,5,589834,524555,131075,459019,6750267,5,2949180,70,75,2883643,70,5377101,3080251,852235,5114958,70,5,851978,64,5,5111867,1507388,70,75,1441851,70,6359629,1638459,721163,6097486,70,5,720906,64,5,6094907,3,459019,6750267,524555,65539,459019,196618,54,7274557,0,131092,10,326,5,66,524298,67,0,67],"consts":["flattenable","Iterator.prototype.flatMap","closeIterator"],"captures":[],"handlers":[47,68,74,0,75,78,80,0,25,83,89,0,90,93,95,0,3,97,100,0],"finallies":[7,8,0,3,114,-1,112],"finallyOffsets":[0],"sites":[0,2782,1,2791,2,2789,4,2795,14,2799,15,2798,16,2803,17,2801,19,2808,20,2804,26,2805,28,2814,29,2815,30,2816,31,2817,32,2818,33,2820,35,2819,37,2820,38,2816,39,2821,40,2822,41,2814,42,2810,48,2811,49,2825,50,2824,67,2810,82,2804,97,2792,103,2829,104,2828,105,2827,106,2831,107,2832,108,2833,109,2831,111,2792,114,2787],"localNames":["source","iterator","mapper","started","counter","item","inner","%ftag0","%fval0","%ret","%it","%e","%it","%e"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":72,"name":"prime","flags":72,"length":1,"params":1,"locals":1,"maxStack":2,"code":[10,281,70,5,10,67],"consts":["next"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,2841,1,2840,2,2839,4,2844,5,2843],"localNames":["helper"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":73,"name":"count","flags":72,"length":2,"params":2,"locals":4,"maxStack":5,"code":[10,309,131339,131082,20,50,720959,131082,20,53,50,917565,131082,1245243,131082,131082,65539,308,44,196875,131082,131082,51,1769535,196618,3,46,2752573,0,65556,131076,196612,65546,43,262148,43,131082,43,327684,43,582,5,196618,67],"consts":["Infinity","$Throw","RangeError","Iterator.prototype."," expects a non-negative count, received ","."],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,2854,1,2853,2,2851,3,2861,4,2862,5,2860,6,2859,7,2864,8,2866,9,2865,10,2863,11,2858,12,2867,13,2858,14,2869,15,2871,16,2872,17,2870,18,2868,19,2856,20,2876,21,2877,22,2875,23,2874,24,2879,25,2880,26,2878,27,2873,28,2882,29,2883,30,2884,31,2889,32,2890,33,2888,34,2891,35,2887,36,2892,37,2886,38,2893,39,2885,40,2882,42,2895,43,2894],"localNames":["limit","name","number","integer"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":74,"name":"flattenable","flags":72,"length":3,"params":3,"locals":4,"maxStack":7,"code":[10,821,4,50,524349,65546,54,852027,0,65556,10,326,54,1900605,0,131092,196612,131082,262148,43,0,327700,10,326,43,393220,43,582,5,10,458772,524313,26,196875,0,589844,196618,0,50,2818111,196618,1,50,3014717,10,3211323,10,196618,70,2,582,67],"consts":["string","$IsObject","$Throw","TypeError"," expects an iterable or iterator, received ","$Describe",".","Symbol","iterator","$Direct"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,2906,1,2905,2,2907,3,2904,4,2903,5,2909,6,2908,7,2903,8,2911,9,2912,10,2913,11,2911,12,2910,13,2902,14,2915,15,2916,16,2917,17,2921,18,2922,19,2920,20,2923,21,2924,22,2925,23,2923,24,2919,25,2926,26,2918,27,2915,29,2931,30,2933,31,2932,32,2930,33,2928,34,2936,35,2937,36,2941,37,2942,38,2940,39,2939,40,2944,41,2945,42,2943,43,2938,44,2946,45,2938,46,2950,47,2949,48,2947,49,2951,50,2936,51,2935],"localNames":["value","strings","name","method"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":75,"name":"closeIterator","flags":72,"length":1,"params":1,"locals":2,"maxStack":4,"code":[10,25,65803,65546,0,51,655679,65546,1,51,1179967,0,65556,10,65546,70,326,54,1638461,0,131092,196612,262148,582,5,0,67],"consts":["return","$IsObject","$Throw","TypeError","Iterator return() must return an object."],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,2960,1,2959,2,2957,3,2966,4,2967,5,2965,6,2964,7,2969,8,2970,9,2968,10,2963,11,2972,12,2973,13,2977,14,2976,15,2974,16,2972,17,2971,18,2962,19,2979,20,2980,21,2981,22,2982,23,2979,25,2955],"localNames":["iterator","method"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":76,"name":"Iterator$prototype$toArray","flags":88,"length":0,"params":0,"locals":5,"maxStack":5,"code":[789,267,36,65803,131084,0,20,10,2,582,1704010,1703995,196875,2622284,1900603,131084,131339,0,65556,65546,65546,131097,131082,838,5,852028,70,75,786491,70,2622285,983099,262411,2360142,70,5,262154,64,5,2359355,65546,67],"consts":["$Direct","$ArraySet","length"],"captures":[],"handlers":[15,26,32,0,33,36,38,0],"finallies":[],"finallyOffsets":[],"sites":[0,2983,2,2989,3,2987,5,2994,6,2995,7,2996,8,2997,9,2994,10,2990,16,2991,17,2999,18,3000,19,3001,20,3003,21,3002,22,3005,23,2999,25,2990,40,3007,41,3006],"localNames":["this","result","item","%it","%e"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":77,"name":"Iterator$prototype$reduce","flags":592,"length":1,"params":2,"locals":10,"maxStack":5,"code":[789,267,1045,65803,65813,131339,0,20,10,2,582,196875,0,65556,65546,131076,582,5,131082,3,26,262411,131082,196633,3,48,327947,3,393483,458764,196618,3670090,3670075,524555,4589644,3866683,458764,459019,327690,3145789,0,65546,262154,458762,393226,838,262155,3276859,458762,262155,258,327691,393226,56,393227,2228284,70,75,2162747,70,4589645,2359355,590091,4327502,70,5,589834,64,5,4325435,327690,54,5177405,0,262164,327684,393220,582,5,262154,67],"consts":["$Direct","$Callback","Iterator.prototype.reduce","length","$Throw","TypeError","Iterator.prototype.reduce of an empty iterator with no initial value."],"captures":[],"handlers":[36,56,62,0,63,66,68,0],"finallies":[],"finallyOffsets":[],"sites":[0,3008,2,3010,4,3011,6,3017,7,3018,8,3019,9,3020,10,3017,11,3015,12,3022,13,3023,14,3024,15,3025,16,3022,18,3030,19,3031,20,3029,21,3027,22,3037,23,3036,24,3039,25,3035,26,3033,27,3043,28,3041,30,3048,31,3044,37,3045,38,3051,39,3050,40,3055,41,3056,42,3057,43,3058,44,3059,45,3055,46,3054,47,3050,48,3063,49,3062,50,3067,51,3066,52,3070,53,3069,54,3070,55,3044,70,3073,71,3072,72,3071,73,3075,74,3076,75,3077,76,3078,77,3075,79,3080,80,3079],"localNames":["this","callback","initial","iterator","accumulator","started","index","item","%it","%e"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":78,"name":"Iterator$prototype$forEach","flags":88,"length":1,"params":1,"locals":2,"maxStack":5,"code":[789,65803,0,20,65546,10,65540,838,5,0,67],"consts":["iteratorTest","forEach"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,3081,2,3086,3,3087,4,3088,5,3089,6,3090,7,3086,9,3084],"localNames":["callback","this"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":79,"name":"Iterator$prototype$some","flags":88,"length":1,"params":1,"locals":2,"maxStack":5,"code":[789,65803,0,20,65546,10,65540,838,67],"consts":["iteratorTest","some"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,3091,2,3096,3,3097,4,3098,5,3099,6,3100,7,3096,8,3095],"localNames":["callback","this"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":80,"name":"Iterator$prototype$every","flags":88,"length":1,"params":1,"locals":2,"maxStack":5,"code":[789,65803,0,20,65546,10,65540,838,67],"consts":["iteratorTest","every"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,3101,2,3106,3,3107,4,3108,5,3109,6,3110,7,3106,8,3105],"localNames":["callback","this"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":81,"name":"Iterator$prototype$find","flags":88,"length":1,"params":1,"locals":2,"maxStack":5,"code":[789,65803,0,20,65546,10,65540,838,67],"consts":["iteratorTest","find"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,3111,2,3116,3,3117,4,3118,5,3119,6,3120,7,3116,8,3115],"localNames":["callback","this"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":82,"name":"iteratorTest","flags":72,"length":3,"params":3,"locals":10,"maxStack":5,"code":[0,20,10,2,582,196875,0,65556,65546,131076,131082,43,582,5,3,262411,0,327947,393228,196618,5308490,5308475,459019,6227788,5505083,393228,393483,0,65546,393226,262154,55,7,56,262155,582,327691,131082,196612,50,2752831,327690,3342397,258,590091,3213134,70,1611,5,589834,67,131082,262148,50,3735871,327690,54,4325437,2,590091,4196174,70,1611,5,589834,67,131082,327684,50,4653375,327690,5242941,393226,590091,5113678,70,1611,5,589834,67,1507388,70,75,1441851,70,6227789,1638459,524555,5965646,70,5,524298,64,5,5963835,131082,262148,50,6619197,258,7077947,131082,196612,50,7012413,2,7077947,0,67],"consts":["$Direct","$Callback","Iterator.prototype.","some","every","find"],"captures":[],"handlers":[25,81,87,0,88,91,93,0],"finallies":[],"finallyOffsets":[],"sites":[0,3130,1,3131,2,3132,3,3133,4,3130,5,3128,6,3135,7,3136,8,3137,9,3139,10,3140,11,3138,12,3135,14,3144,15,3142,16,3146,19,3152,20,3148,26,3149,27,3157,28,3158,29,3159,30,3161,32,3160,34,3161,35,3157,36,3156,37,3165,38,3166,39,3164,40,3163,41,3167,42,3162,43,3169,44,3168,51,3173,52,3174,53,3172,54,3171,55,3176,56,3175,57,3170,58,3178,59,3177,66,3182,67,3183,68,3181,69,3180,70,3184,71,3179,72,3186,73,3185,80,3148,95,3190,96,3191,97,3189,98,3188,99,3192,100,3188,101,3195,102,3196,103,3194,104,3193,105,3197,106,3193,107,3198,108,3187],"localNames":["self","callback","name","iterator","index","result","item","%it","%e","%ret"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":83,"name":"revive","flags":72,"length":3,"params":3,"locals":7,"maxStack":5,"code":[10,65546,26,196875,0,20,196618,326,3932221,262156,327692,393228,0,65556,196618,326,262411,3,327947,0,393483,327690,262154,131097,46,3932221,0,196628,196618,262154,327690,26,131082,838,393227,393226,0,50,3014717,196618,262154,327690,26,30,5,3670075,196618,262154,327690,26,31,32,543,393226,28,5,327690,56,327691,1376316,10,131082,65546,196618,582,67],"consts":["$IsObject","$Keys","length","revive"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,3209,1,3210,2,3208,3,3206,4,3212,5,3213,6,3214,7,3212,8,3211,12,3219,13,3220,14,3221,15,3219,16,3217,17,3225,18,3223,19,3227,21,3231,22,3233,23,3232,24,3230,25,3229,26,3239,27,3240,28,3241,29,3243,30,3244,31,3242,32,3245,33,3239,34,3238,35,3248,36,3249,37,3247,38,3246,39,3253,40,3255,41,3256,42,3254,43,3252,44,3251,45,3246,46,3260,47,3262,48,3263,49,3261,50,3259,51,3261,52,3259,53,3264,54,3259,55,3258,56,3267,57,3266,58,3267,59,3229,60,3272,61,3271,62,3273,63,3274,64,3269,65,3268],"localNames":["holder","key","reviver","value","names","index","revived"],"upvalNames":[]},{"source":{"id":"@prelude","hash":"b3c48e112834eb16"},"index":84,"name":"replaceWith","flags":72,"length":3,"params":3,"locals":6,"maxStack":9,"code":[4,196875,3,262411,262154,10,65561,46,3211325,196618,10,262154,26,3,26,0,131092,0,131082,36,10,262154,26,65539,26,2228810,2228283,327947,1967439,2621499,2622796,2424891,37,1966139,70,587,1769531,70,2622797,2097211,71,326,43,43,196619,262154,56,262155,262204,196618,65546,43,67],"consts":["","length","String"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,3284,1,3282,2,3288,3,3286,4,3291,5,3293,6,3292,7,3290,8,3289,9,3298,10,3302,11,3303,12,3301,13,3304,14,3300,15,3305,16,3306,17,3307,18,3308,19,3307,20,3312,21,3313,22,3311,23,3314,24,3310,25,3309,40,3307,41,3305,42,3299,43,3297,44,3298,45,3317,46,3316,47,3317,48,3289,49,3320,50,3321,51,3319,52,3318],"localNames":["matches","rest","callback","result","index","%it"],"upvalNames":[]}]},"@vm-internal":{"text":"44830039edee7f3c","codes":[{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":0,"name":"","flags":202,"length":0,"params":0,"locals":0,"maxStack":1,"code":[0,87],"consts":[],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,0],"localNames":[],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":1,"name":"$vmToPrimitive","flags":72,"length":2,"params":2,"locals":8,"maxStack":4,"code":[0,20,10,326,54,524349,10,67,65546,65540,50,1310783,65546,131076,50,1311039,0,196628,10,326,1507389,262148,1572923,327684,131339,131082,262148,50,2031677,327684,2097211,262148,196875,10,131082,26,262411,0,393236,262154,326,3604541,393228,10,262154,70,393483,0,458772,393226,326,54,3604541,393226,67,10,196618,26,327947,0,393236,327690,326,5046333,458764,10,327690,70,459019,0,458772,458762,326,54,5046333,458762,67,0,524308,589828,655364,582,5,0,67],"consts":["$IsDataObj","string","default","$IsDate","toString","valueOf","$IsCallableAny","$IsObj","$Throw","TypeError","Cannot convert object to primitive value."],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,8,1,9,2,10,3,8,4,7,5,6,6,12,7,11,8,19,9,20,10,18,11,17,12,23,13,24,14,22,15,21,16,25,17,26,18,27,19,25,20,16,21,28,22,16,23,29,24,14,25,35,26,36,27,34,28,33,29,37,30,33,31,38,32,31,33,43,34,44,35,42,36,40,37,46,38,47,39,48,40,46,41,45,43,56,44,55,45,53,46,51,47,59,48,60,49,61,50,59,51,58,52,57,53,63,54,62,55,68,56,69,57,67,58,65,59,71,60,72,61,73,62,71,63,70,65,81,66,80,67,78,68,76,69,84,70,85,71,86,72,84,73,83,74,82,75,88,76,87,77,90,78,91,79,92,80,93,81,90,83,5],"localNames":["v","hint","first","second","m1","m2","r1","r2"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":2,"name":"$vmToKey","flags":72,"length":1,"params":1,"locals":1,"maxStack":6,"code":[0,20,0,65556,10,131076,582,326,67],"consts":["$PropKey","$vmToPrimitive","string"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,99,1,100,2,101,3,102,4,103,5,104,6,101,7,99,8,98],"localNames":["v"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":3,"name":"$vmToString","flags":72,"length":1,"params":1,"locals":1,"maxStack":6,"code":[0,20,0,65556,10,131076,582,326,67],"consts":["$CoerceToString","$vmToPrimitive","string"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,110,1,111,2,112,3,113,4,114,5,115,6,112,7,110,8,109],"localNames":["v"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":4,"name":"$vmToNumeric","flags":72,"length":2,"params":2,"locals":2,"maxStack":7,"code":[0,20,10,0,65556,65546,131076,582,582,67],"consts":["$ApplyToNumeric","$vmToPrimitive","number"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,122,1,123,2,124,3,125,4,126,5,127,6,128,7,125,8,122,9,121],"localNames":["incFlag","v"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":5,"name":"$vmInc","flags":72,"length":2,"params":2,"locals":3,"maxStack":7,"code":[0,20,10,0,65556,65546,131076,582,582,131339,10,3,50,1179709,131082,65539,43,1376315,131082,65539,44,67],"consts":["$ApplyToNumeric","$vmToPrimitive","number"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,137,1,138,2,139,3,140,4,141,5,142,6,143,7,140,8,137,9,135,10,147,11,148,12,146,13,145,14,150,15,151,16,149,17,145,18,153,19,154,20,152,21,144],"localNames":["incFlag","v","n"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":6,"name":"$vmUnary","flags":72,"length":2,"params":2,"locals":2,"maxStack":7,"code":[0,20,10,0,65556,65546,131076,582,582,67],"consts":["$ApplyUnary","$vmToPrimitive","number"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,161,1,162,2,163,3,164,4,165,5,166,6,167,7,164,8,161,9,160],"localNames":["sub","v"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":7,"name":"$vmBinary","flags":72,"length":3,"params":3,"locals":8,"maxStack":5,"code":[0,20,10,65546,131082,838,196875,196618,3,50,1179709,0,65556,10,65546,131082,838,67,196618,65539,50,2359357,458764,0,131092,65546,196612,582,459019,0,65556,10,458762,131082,838,67,196618,131075,50,2752573,262148,2818107,327684,262411,0,131092,65546,262154,582,327947,0,131092,131082,262154,582,393483,0,65556,10,327690,393226,838,67],"consts":["$OpConvKind","$ApplyBinary","$vmToPrimitive","string","default","number"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,177,1,178,2,179,3,180,4,181,5,177,6,175,7,184,8,185,9,183,10,182,11,187,12,188,13,189,14,190,15,191,16,187,17,186,18,194,19,195,20,193,21,192,23,200,24,201,25,202,26,203,27,200,28,198,29,205,30,206,31,207,32,208,33,209,34,205,35,204,36,215,37,216,38,214,39,213,40,217,41,213,42,218,43,211,44,222,45,223,46,224,47,225,48,222,49,220,50,229,51,230,52,231,53,232,54,229,55,227,56,234,57,235,58,236,59,237,60,238,61,234,62,233],"localNames":["op","lhs","rhs","kind","hint","l","r","key"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":8,"name":"$vmSet","flags":72,"length":3,"params":3,"locals":3,"maxStack":3,"code":[65546,10,131082,326,5,131082,67],"consts":[],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,249,1,248,2,250,3,246,5,252,6,251],"localNames":["setter","receiver","value"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":9,"name":"$vmInstanceof","flags":72,"length":2,"params":2,"locals":2,"maxStack":4,"code":[0,20,10,65546,65561,582,67],"consts":["$HasInstance","prototype"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,259,1,260,2,261,3,263,4,262,5,259,6,258],"localNames":["lhs","rhs"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":10,"name":"$vmRedo","flags":72,"length":2,"params":2,"locals":2,"maxStack":2,"code":[65546,10,70,67],"consts":[],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,274,1,273,2,271,3,270],"localNames":["getter","receiver"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":11,"name":"$vmThenableGet","flags":72,"length":3,"params":3,"locals":4,"maxStack":4,"code":[10,25,196875,0,65556,196618,326,983101,10,196618,65546,131082,582,5,1310779,0,131092,10,326,5,0,67],"consts":["then","$IsFunction","$FulfillWith"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,285,1,284,2,282,3,288,4,289,5,290,6,288,7,287,8,295,9,294,10,296,11,297,12,292,14,287,15,299,16,300,17,301,18,299,20,280],"localNames":["thenable","resolve","reject","then"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":12,"name":"$vmCopyDataProps","flags":72,"length":3,"params":3,"locals":6,"maxStack":6,"code":[0,20,65546,2,131082,838,196875,3,262411,262154,196618,65561,46,2555965,327692,196618,262154,26,327947,0,131092,65546,327690,582,2293821,0,196628,10,327690,65546,327690,26,258,1094,5,262154,56,262155,589884,10,67],"consts":["$OwnKeys","length","$IsEnumerableOwn","$Define"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,311,1,312,2,313,3,314,4,315,5,311,6,309,7,319,8,317,9,322,10,324,11,323,12,321,13,320,15,331,16,332,17,330,18,328,19,334,20,335,21,336,22,337,23,334,24,333,25,339,26,340,27,341,28,342,29,344,30,345,31,343,32,346,33,339,35,349,36,348,37,349,38,320,39,351,40,350],"localNames":["target","source","excluded","keys","index","key"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":13,"name":"$vmGetElem","flags":72,"length":2,"params":2,"locals":2,"maxStack":4,"code":[10,0,20,65546,326,26,67],"consts":["$vmToKey"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,359,1,360,2,361,3,362,4,360,5,358,6,357],"localNames":["o","k"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":14,"name":"$vmDeleteElem","flags":72,"length":2,"params":2,"locals":2,"maxStack":4,"code":[10,0,20,65546,326,30,67],"consts":["$vmToKey"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,371,1,372,2,373,3,374,4,372,5,370,6,368],"localNames":["o","k"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":15,"name":"$vmReplay","flags":72,"length":7,"params":7,"locals":21,"maxStack":8,"code":[258,11993149,458764,0,20,393226,326,4325437,524300,589836,0,65556,393226,326,524555,3,590091,589834,524298,131097,46,4259901,655372,720908,524298,589834,26,655627,524298,589834,65539,43,26,721163,0,196628,327690,327690,131097,655370,838,5,0,196628,327690,327690,131097,720906,838,5,0,196628,327690,327690,131097,655370,720906,26,838,5,589834,131075,43,589835,1114172,10223675,393226,0,51,10223677,786444,851980,917516,983052,1048588,1114124,0,262164,393226,326,786699,0,327700,393226,3,582,852235,0,327700,393226,65539,582,917771,786442,131097,983307,36,1048843,3,1114379,1114122,983050,46,9764925,1179660,1245196,1310732,786442,1114122,26,1179915,0,393236,393226,1114122,582,1245451,0,458772,1179658,326,8388669,0,524308,1179658,1245194,582,8454203,1179658,1310987,0,196628,1048586,1114122,851978,9306173,0,589844,1245194,1310730,582,9371707,1310730,838,5,1114122,56,1114123,6553660,0,196628,262154,917514,1048586,838,5,0,655380,10,65546,131082,196618,262154,327690,1606,459019,0,720916,458762,326,54,11600191,0,20,458762,326,54,11796541,458762,67,458762,393227,60,0,67],"consts":["$IsPrefetch","$PrefetchReads","length","$ArraySet","$ConvValues","$ConvFlag","$ConvHint","$IsObj","$vmToPrimitive","$ConvCoerce","$Replay","$IsConvert"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,386,1,385,3,389,4,390,5,391,6,389,7,388,10,396,11,397,12,398,13,396,14,394,15,402,16,400,17,405,18,407,19,406,20,404,21,403,24,414,25,415,26,413,27,411,28,420,29,422,30,423,31,421,32,419,33,417,34,425,35,426,36,427,37,429,38,428,39,431,40,425,42,433,43,434,44,435,45,437,46,436,47,439,48,433,50,441,51,442,52,443,53,445,54,444,55,448,56,449,57,447,58,441,60,452,61,453,62,451,63,452,64,403,65,388,66,456,67,457,68,455,69,454,76,462,77,463,78,464,79,462,80,460,81,468,82,469,83,470,84,471,85,468,86,466,87,475,88,476,89,477,90,478,91,475,92,473,93,483,94,482,95,480,96,488,97,486,98,492,99,490,100,495,101,496,102,494,103,493,107,502,108,503,109,501,110,499,111,507,112,508,113,509,114,510,115,507,116,505,117,515,118,516,119,517,120,515,121,514,122,518,123,519,124,520,125,521,126,518,127,514,128,522,129,512,130,524,131,525,132,526,133,527,134,529,135,528,136,530,137,531,138,532,139,533,140,530,141,528,142,534,143,524,145,537,146,536,147,537,148,493,149,539,150,540,151,541,152,542,153,543,154,539,156,547,157,548,158,549,159,550,160,551,161,552,162,553,163,554,164,547,165,545,166,558,167,559,168,560,169,558,170,557,171,556,172,562,173,563,174,564,175,562,176,561,177,555,178,566,179,565,180,570,181,569,182,385,183,384],"localNames":["callable","target","args","constructing","replay","read","req","res","pairs","at","receiver","key","values","coerce","ordinal","len","converted","i","val","hint","prim"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":16,"name":"$vmJsonVisitor","flags":72,"length":3,"params":3,"locals":5,"maxStack":1,"code":[269,65805,131341,196621,262157,1114134,262416,36,196880,262159,67],"consts":[],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,571,5,581,7,580,8,578,9,828,10,827],"localNames":["boundary","replacer","properties","ancestors","visit"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":17,"name":"visit","flags":76,"length":3,"params":3,"locals":19,"maxStack":6,"code":[81,131082,6553603,48,720957,0,20,65540,131076,582,5,10,65546,26,196875,0,196628,196618,326,2228285,17,54,1900605,0,20,262148,327684,582,5,196618,82,2162771,67,196619,0,393236,196618,326,3473469,458764,196618,458777,459019,0,524308,458762,326,3473469,196618,458762,65546,326,196619,65553,0,51,4128829,10,65553,65546,196618,582,196619,0,589844,196618,17,131089,838,262411,262154,3,50,4980797,0,67,262154,65539,50,5374013,196618,67,262154,131075,50,5767229,1,67,262154,196611,50,6422589,0,655380,196618,17,582,67,262154,262147,50,7012413,0,720916,196618,326,7077947,196618,327947,0,786452,131089,131089,851993,327690,838,5,0,393483,0,917524,327690,326,13041725,524300,589836,36,393227,327690,851993,524555,3,590091,589834,524298,46,12976189,655372,0,196625,327690,0,983060,589834,326,131082,65539,43,838,11273034,11272251,983307,0,3,7,1048843,11013973,1048586,131075,50,10616893,67,5,10948430,70,1611,5,1048641,326,11472982,82,10092604,70,843,9895995,1048586,131075,50,11796541,67,655627,0,786452,393226,589834,655370,0,50,12517437,1,12582971,655370,838,5,589834,56,589835,8716348,18415675,720908,786444,0,1114132,70,393227,0,1179668,327690,17,262161,838,721163,3,786699,786442,720906,851993,46,18415677,851980,917516,720906,786442,26,852235,0,196625,327690,851978,131082,65539,43,838,16778058,16777275,1114379,0,3,7,1179915,16519509,1179658,131075,50,16121917,67,5,16453966,70,1611,5,1245249,326,16978518,82,15597628,70,843,15401019,1179658,131075,50,17301565,67,917771,917514,0,51,18153533,0,1310740,393226,851978,917514,258,1094,5,786442,56,786443,14024764,0,1376276,131089,326,5,393226,67],"consts":["$Throw","RangeError","Value exceeds the maximum depth of 100.","$IsPromise","InvalidData","JSON.stringify received an un-awaited Promise; await it first - e.g. `const result = await load(...)`.","$IsObj","toJSON","$IsCallableAny","$JsonClassify","$JsonSpecial","$SetToArray","$ArraySet","length","$IsArray","String",{"type":"TypeError","message":"The delegated iterator does not provide a throw() method."},"$NewNullProtoObj","$JsonNames",{"type":"TypeError","message":"The delegated iterator does not provide a throw() method."},"$Define","$ArrayPop"],"captures":[0,0,0,1,0,3,0,4,0,2],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,581,1,589,2,590,3,588,4,587,5,592,6,593,7,594,8,595,9,592,11,600,12,601,13,599,14,597,15,603,16,604,17,605,18,603,19,602,20,609,21,608,22,607,23,612,24,613,25,614,26,615,27,612,29,620,30,619,33,618,34,622,35,623,36,624,37,622,38,621,40,630,41,629,42,627,43,633,44,634,45,635,46,633,47,632,48,642,49,641,50,643,51,639,52,638,53,646,54,647,55,645,56,644,57,654,58,653,59,655,60,656,61,651,62,650,63,660,64,661,65,662,66,663,67,664,68,660,69,658,70,667,71,668,72,666,73,665,74,670,75,669,76,673,77,674,78,672,79,671,80,676,81,675,82,679,83,680,84,678,85,677,86,682,87,681,88,685,89,686,90,684,91,683,92,688,93,689,94,690,95,691,96,688,97,687,98,697,99,698,100,696,101,695,102,699,103,700,104,701,105,699,106,695,107,702,108,693,109,704,110,705,111,706,112,708,113,707,114,710,115,704,117,712,119,715,120,716,121,717,122,715,123,714,126,722,127,721,128,727,129,726,130,724,131,732,132,730,133,735,134,736,135,734,136,733,138,742,139,743,140,744,141,745,142,746,143,747,144,745,145,749,146,750,147,748,148,742,149,741,180,739,181,752,182,753,183,754,184,755,185,758,186,759,187,757,188,756,189,760,190,756,191,761,192,752,194,764,195,763,196,764,197,733,198,714,201,769,202,770,203,769,204,768,205,774,206,775,207,776,208,777,209,778,210,774,211,772,212,782,213,780,214,785,215,787,216,786,217,784,218,783,221,794,222,795,223,793,224,791,225,800,226,801,227,802,228,803,229,805,230,806,231,804,232,800,233,799,264,797,265,809,266,810,267,808,268,807,269,812,270,813,271,814,272,815,273,816,274,817,275,812,277,820,278,819,279,820,280,783,281,822,282,823,283,824,284,822,286,826,287,825],"localNames":["holder","key","depth","val","kind","target","out","toJSON","len","i","elem","names","i","k","propVal","%it","%kind","%it","%kind"],"upvalNames":["boundary","replacer","ancestors","visit","properties"]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":18,"name":"$vmJsonWalk","flags":72,"length":4,"params":4,"locals":5,"maxStack":6,"code":[0,0,20,2,10,131082,838,35,65546,65574,65540,3,838,131353,70,196633,262411,0,262164,2,262154,131082,196618,1094,67],"consts":["$vmJsonVisitor","","next","value","$JsonFinish"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,842,1,843,2,844,3,845,4,846,5,847,6,843,7,848,8,851,9,849,10,852,11,853,12,842,13,841,14,840,15,839,16,837,17,857,18,858,19,859,20,860,21,861,22,862,23,857,24,856],"localNames":["replacer","value","properties","indent","json"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":19,"name":"$vmSettleCall","flags":72,"length":3,"params":3,"locals":3,"maxStack":5,"code":[0,20,10,65546,131082,838,67],"consts":["$Apply"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,870,1,871,2,872,3,873,4,874,5,870,6,869],"localNames":["callable","thisVal","args"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":20,"name":"$vmCombine","flags":72,"length":2,"params":2,"locals":6,"maxStack":4,"code":[0,20,10,65546,582,131339,196620,65546,1441866,1441851,262411,2360396,1638459,196620,196875,0,65556,131082,196618,582,5,720956,70,75,655419,70,2360397,852027,327947,2098254,70,5,327690,64,5,2097211,0,131092,131082,326,5,0,67],"consts":["$CombineStart","$CombineAdd","$CombineEnd"],"captures":[],"handlers":[13,22,28,0,29,32,34,0],"finallies":[],"finallyOffsets":[],"sites":[0,883,1,884,2,885,3,886,4,883,5,881,7,891,8,887,14,888,15,894,16,895,17,896,18,897,19,894,21,887,36,899,37,900,38,901,39,899,41,879],"localNames":["name","items","c","item","%it","%e"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":21,"name":"$vmOpenSyncForAsync","flags":72,"length":2,"params":2,"locals":3,"maxStack":4,"code":[0,20,10,65546,70,326,131339,0,65556,131082,131082,131097,582,67],"consts":["$AfsRequireObj","$WrapAsyncFromSync","next"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,910,1,911,2,915,3,914,4,912,5,910,6,908,7,917,8,918,9,919,10,921,11,920,12,917,13,916],"localNames":["v","method","it"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":22,"name":"$vmAsyncFromSync","flags":72,"length":4,"params":4,"locals":10,"maxStack":7,"code":[0,20,10,326,262411,65546,65540,50,917565,0,131092,10,326,1441851,0,196628,10,262154,65546,26,65546,838,327947,327690,0,50,1966143,327690,1,50,4915261,589836,65546,262148,50,2818109,0,327700,196618,326,5,0,67,0,196628,10,262154,262169,262148,838,590091,589834,0,51,3801407,589834,1,51,4456509,0,393236,10,262154,589834,70,262148,838,5,0,458772,10,326,5,0,67,131082,5374013,262154,327690,196618,326,5570619,262154,327690,70,393483,0,393236,10,393226,65546,838,5,393226,524313,54,54,459019,393226,589849,524555,0,655380,10,524298,458762,65546,262148,51,1094,5,0,67],"consts":["$AfsGetIter","next","$AfsGetNext","$AfsMethod","return","$AfsResolveDone","$AfsCheckObj","$AfsRejectNoThrow","done","value","$AfsSettle"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,933,1,934,2,935,3,933,4,931,5,941,6,942,7,940,8,939,9,943,10,944,11,945,12,943,13,939,14,946,15,947,16,948,17,950,18,951,19,949,20,952,21,946,22,937,23,956,24,957,25,955,26,954,27,959,28,960,29,958,30,953,32,964,33,965,34,963,35,962,36,968,37,969,38,970,39,968,41,971,43,975,44,976,45,977,46,979,47,978,48,981,49,975,50,973,51,985,52,986,53,984,54,983,55,988,56,989,57,987,58,982,59,992,60,993,61,994,62,998,63,997,64,995,65,999,66,992,68,1001,69,1002,70,1003,71,1001,73,1004,75,1009,76,1008,77,1013,78,1012,79,1014,80,1010,81,1008,82,1018,83,1017,84,1015,85,1006,86,1020,87,1021,88,1022,89,1023,90,1024,91,1020,93,1031,94,1030,95,1029,96,1028,97,1026,98,1037,99,1036,100,1034,101,1040,102,1041,103,1042,104,1043,105,1044,106,1046,107,1047,108,1045,109,1040,111,929],"localNames":["adapter","kind","hasArg","val","iter","method","res","done","value","ret"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":23,"name":"$vmAsyncFromSyncClose","flags":72,"length":1,"params":1,"locals":2,"maxStack":2,"code":[10,25,65803,65546,0,51,655679,65546,1,51,983101,10,65546,70,5,0,67],"consts":["return"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,1056,1,1055,2,1053,3,1061,4,1062,5,1060,6,1059,7,1064,8,1065,9,1063,10,1058,11,1070,12,1069,13,1067,15,1051],"localNames":["iter","ret"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":24,"name":"$vmHostWait","flags":74,"length":4,"params":4,"locals":5,"maxStack":9,"code":[3,262411,262154,10,25,46,1048637,10,262154,26,340,5,262154,56,262155,131132,0,65556,65546,0,131082,2,36,196618,0,1862,67],"consts":["length","$vmReplay"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,1081,1,1079,2,1084,3,1086,4,1085,5,1083,6,1082,7,1092,8,1093,9,1091,10,1090,12,1096,13,1095,14,1096,15,1082,16,1098,17,1099,18,1100,19,1101,20,1102,21,1103,22,1104,23,1105,24,1106,25,1098,26,1097],"localNames":["promises","callee","args","read","i"],"upvalNames":[]},{"source":{"id":"@vm-internal","hash":"2fa81019ca46a87e"},"index":25,"name":"$vmResult","flags":74,"length":1,"params":1,"locals":4,"maxStack":6,"code":[0,20,10,326,524349,10,340,589883,10,65803,0,0,65556,258,0,1,838,35,65546,131110,131076,3,838,131339,131082,196889,70,196875,196618,262169,54,2621501,131082,196889,196618,327705,340,326,196619,1835068,0,393236,258,196618,327705,1,0,1094,67],"consts":["$IsThenable","$vmJsonVisitor","","next","done","value","$JsonFinish"],"captures":[],"handlers":[],"finallies":[],"finallyOffsets":[],"sites":[0,1115,1,1116,2,1117,3,1115,4,1114,5,1119,6,1118,7,1114,8,1120,9,1112,10,1124,11,1125,12,1126,13,1127,14,1128,15,1129,16,1125,17,1130,18,1133,19,1131,20,1134,21,1135,22,1124,23,1122,24,1141,25,1140,26,1139,27,1137,28,1146,29,1145,30,1144,31,1143,32,1153,33,1152,34,1157,35,1156,36,1155,37,1151,38,1150,39,1143,40,1160,41,1161,42,1162,43,1164,44,1163,45,1166,46,1167,47,1160,48,1159],"localNames":["value","root","walk","step"],"upvalNames":[]}]}} diff --git a/packages/codemode/src/language/prelude/bytecode.ts b/packages/codemode/src/language/prelude/bytecode.ts deleted file mode 100644 index 91d395d876f..00000000000 --- a/packages/codemode/src/language/prelude/bytecode.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { parse } from "acorn" -import { Source } from "../runtime/source.js" -import { hash } from "../snapshot/snapshot.js" -import { type Code, codeFromJson, type CodeJson, codeToJson } from "../code.js" -import { compileSource } from "../compiler/compile.js" -import saved from "./bytecode.json" with { type: "json" } - -/** A built-in source's bytecode as `script/prelude.ts` saves it, with a hash of the text it was compiled from. */ -export type SavedCodes = { readonly text: string; readonly codes: ReadonlyArray } - -/** - * A built-in source's bytecode (the prelude's, the VM's internal helpers'), made once per process: from the bytecode - * compiled ahead of time when it was compiled from this text, so the process neither parses nor compiles it until - * something asks for its nodes (an error's site, a saved state's); compiled now otherwise. A test checks the saved - * bytecode is what the compiler makes. Its top-level functions start at a line's start; they are found by name. - */ -export const builtinCodes = (id: string, text: string) => { - const tree = () => parse(text, { ecmaVersion: "latest", sourceType: "script" }) - const ahead = (saved as { readonly [id: string]: SavedCodes | undefined })[id] - const lazy = new Source(id, text, tree) - const codes = - ahead?.text === hash(text) - ? ahead.codes.map((code) => codeFromJson(code, lazy)) - : compileSource(new Source(id, text, tree()), { internal: true }) - const byName = new Map() - // A top-level function comes before the functions nested in it, in pre-order. - for (const [, name] of text.matchAll(/^(?:async )?function\*? ?([\w$]+)/gm)) { - byName.set(name!, codes.find((made) => made.index > 0 && made.name === name)!) - } - return { codes, byName } -} - -/** What `script/prelude.ts` saves for a built-in source. */ -export const saveCodes = (text: string, codes: ReadonlyArray): SavedCodes => ({ - text: hash(text), - codes: codes.map(codeToJson), -}) diff --git a/packages/codemode/src/language/prelude/helpers.ts b/packages/codemode/src/language/prelude/helpers.ts deleted file mode 100644 index f6c58b6ff70..00000000000 --- a/packages/codemode/src/language/prelude/helpers.ts +++ /dev/null @@ -1,331 +0,0 @@ -import { isSupportedCallback, requireCallback, withReads } from "../runtime/callback.js" -import type { Builtins } from "../runtime/intrinsics.js" -import { SORT_RUN, sorted, type SortInto } from "../stdlib/array.js" -import { finishBytes } from "../stdlib/bytes.js" -import { weakKey } from "../stdlib/collections.js" -import { buildPairs } from "../stdlib/url.js" -import type { Interpreter } from "../runtime/interpreter.js" -import { checkArrayLength } from "../runtime/limits.js" -import { AsyncIteratorSymbol, invalidData, IteratorSymbol, PendingThrow } from "../runtime/model.js" -import { native, receiver } from "../runtime/native.js" -import { - Arr, - Bytes, - coerceToString, - data, - define, - hidden, - hasPrototype, - keys, - getOwn, - own, - ownKeys, - IteratorObj, - positionIterator, - coerceToNumber, - get, - MapObj, - type NativeResult, - Obj, - PromiseObj, - SetObj, - type Value, - WeakMapObj, - WeakSetObj, -} from "../runtime/objects.js" -import { builtinCursor, requireIteratorObject } from "../runtime/operations.js" -import { containsOpaqueReference, describeValue, isOpaque } from "../runtime/references.js" -import { compareText } from "../runtime/operations.js" -import { Invoke } from "../runtime/signals.js" - -// The prelude's privileged helpers: leaf built-ins (they never call program code) bound only in the prelude's scope. - -type Helper = readonly [length: number, call: (args: Array) => NativeResult] - -const classes = { Array: Arr, Uint8Array: Bytes, Map: MapObj, Set: SetObj } as const - -// Bun exposes ES2026 Math.sumPrecise before TypeScript's standard library types. -declare global { - interface Math { - sumPrecise(values: Iterable): number - } -} - -export const helpers = (ctx: Interpreter): Array => { - const builtins = ctx.builtins - const helpers: Record = { - /** Throws a program error of `type` ("TypeError", "RangeError", or "InvalidData") with `message`. */ - $Throw: [ - 2, - ([type, message]) => { - if (type === "InvalidData") throw invalidData(String(message)) - throw new PendingThrow(type as "TypeError", String(message)) - }, - ], - /** The callback itself, or the TypeError for one a callback site doesn't admit. */ - $Callback: [2, ([value, label]) => requireCallback(value, String(label))], - /** Calls `fn` with a receiver and arguments, as `Function.prototype.call` would, without reading `call`. */ - $Call: [2, ([fn, thisArg, ...args]) => new Invoke(fn, thisArg, args, undefined)], - /** The receiver, when it is the built-in kind `kind` names, or the TypeError for any other. */ - $Receiver: [ - 3, - ([value, kind, method]) => receiver(classes[kind as keyof typeof classes], value, String(method)), - ], - /** Whether `value` is an object; with `data`, one holding no opaque reference. */ - $IsObject: [2, ([value, data]) => value instanceof Obj && !(data === true && containsOpaqueReference(value))], - /** Whether `for...of` can iterate `value`. */ - $IsIterable: [ - 1, - ([value]) => - withReads(() => { - if (builtinCursor(builtins, value) !== undefined) return true - if (!(value instanceof Obj)) return false - const method = get(value, IteratorSymbol) - return method !== undefined && method !== null - }), - ], - $Describe: [1, ([value]) => describeValue(value)], - $Inherits: [2, ([value, proto]) => hasPrototype(value, proto as Obj)], - /** An object's own enumerable string keys. */ - $Keys: [1, ([value]) => new Arr(builtins.Array, keys(value as Obj))], - /** - * An object's own keys as the copying built-ins visit them: strings and the iterator symbols, or only strings, less - * `excluded` (canonical keys). Each is checked for enumerability when it is visited (`$IsEnumerableOwn`). - */ - $OwnKeys: [ - 3, - ([value, strings, excluded]) => { - const skip = excluded instanceof Arr ? new Set(excluded.items) : undefined - return new Arr( - builtins.Array, - ownKeys(value as Obj).filter( - (key) => - (typeof key === "string" || - (strings !== true && (key === IteratorSymbol || key === AsyncIteratorSymbol))) && - skip?.has(key) !== true, - ), - ) - }, - ], - $IsEnumerableOwn: [2, ([value, key]) => own(value as Obj, key as string)?.enumerable === true], - /** Defines an own data property, enumerable or hidden, and returns the object. */ - $Define: [ - 4, - ([target, key, value, enumerable]) => { - define(target as Obj, key as string, value, enumerable === true ? data : hidden) - return target - }, - ], - /** Writes an element of a prelude-made array without going through the prototype chain. */ - $ArraySet: [ - 3, - ([array, index, value]) => { - ;(array as Arr).items[index as number] = value - return value - }, - ], - $SumPrecise: [1, ([numbers]) => Math.sumPrecise((numbers as Arr).items as Array)], - /** A Uint8Array of the values (see `collectBytes`). */ - $Bytes: [ - 3, - ([values, into, offset]) => { - const items = (values as Arr).items - checkArrayLength(items.length) - return finishBytes(Uint8Array.from(items, coerceToNumber), into as Obj, offset as number) - }, - ], - /** A Uint8Array of the values, of the same kind as the Uint8Array `source`: a Buffer's map makes a Buffer. */ - $DerivedBytes: [ - 2, - ([values, source]) => { - const items = (values as Arr).items - checkArrayLength(items.length) - return (source as Bytes).derive(builtins, Uint8Array.from(items, coerceToNumber)) - }, - ], - /** Headers or URLSearchParams from the pairs `readPairs` read, or from a record. */ - $Pairs: [ - 4, - ([kind, proto, value, label]) => - withReads(() => buildPairs({ kind: kind as "Headers", proto: proto as Obj }, value, String(label))), - ], - $IsCallable: [1, ([value]) => isSupportedCallback(value)], - /** - * An iterator object as `for...of` steps it, reading `next` once and calling it only then (GetIteratorDirect); - * with `arrays`, an array's values. - */ - $Direct: [ - 2, - ([value, arrays]) => - arrays === true && value instanceof Arr - ? positionIterator(builtins, value, "values") - : value instanceof IteratorObj - ? value - : withReads( - () => - new IteratorObj(builtins.Iterator, { - iterator: requireIteratorObject(value, "An iterator"), - next: get(value as Obj, "next"), - asynchronous: false, - }), - ), - ], - /** A sort's result written where it goes (see `sortWith`): the defined values in order, then `undefs` undefined. */ - $Sorted: [ - 5, - ([target, into, holes, values, undefs]) => - sorted(builtins, target as Arr | Bytes, into as SortInto, holes as number, [ - ...(values as Arr).items, - ...Array(undefs as number).fill(undefined), - ]), - ], - /** Ends one merge of `sortWith`: the runs' remaining values after the merged ones, then all of them back in `work`. */ - $MergeRest: [ - 8, - ([work, merged, count, left, middle, right, high, low]) => { - const items = (work as Arr).items - const out = (merged as Arr).items - out.length = count as number - for (let at = left as number; at < (middle as number); at++) out.push(items[at]) - for (let at = right as number; at < (high as number); at++) out.push(items[at]) - for (let at = 0; at < out.length; at++) items[(low as number) + at] = out[at] - return undefined - }, - ], - $SortState: [1, ([values]) => sortState(builtins, values as Arr)], - $SortStep: [1, ([state]) => sortStep(state as Arr)], - $SortResult: [ - 2, - ([state, values]) => { - const items = (values as Arr).items - return new Arr( - builtins.Array, - ((state as Arr).items[1] as Arr).items.map((at) => items[at as number]), - ) - }, - ], - /** What the collection built-ins need from a Map, Set, WeakMap, or WeakSet's table; see `table`. */ - $Table: [4, ([op, target, key, value]) => table(builtins, String(op), target, key, value)], - } - return Object.entries(helpers).map(([name, [length, call]]) => [ - name, - native(builtins, { name, length, call: (_, args) => call(args), callback: false }), - ]) -} - -const table = (builtins: Builtins, op: string, target: Value, key: Value, value: Value): Value => { - switch (op) { - case "add": - if (target instanceof MapObj) target.map.set(key, value) - else if (target instanceof SetObj) target.set.add(key) - else if (target instanceof WeakMapObj) target.map.set(weakKey(key, "as weak map key"), value) - else (target as WeakSetObj).set.add(weakKey(key, "in weak set")) - return undefined - case "delete": - return (target as SetObj).set.delete(key) - case "has": - return (target as SetObj).set.has(key) - case "size": - return (target as SetObj).set.size - case "copy": { - const copy = new SetObj(builtins.Set) - for (const item of (target as SetObj).set.liveKeys()) copy.set.add(item) - return copy - } - case "values": - return positionIterator(builtins, target as SetObj, "values") - case "entries": - return positionIterator(builtins, target as MapObj | SetObj, "entries") - case "groups": - return target === "Map" ? new MapObj(builtins.Map) : new Obj(null) - case "groupKey": - if (target instanceof PromiseObj) return coerceToString(target) - if (isOpaque(target)) { - throw invalidData(`Object.groupBy callback must return a data value, received ${describeValue(target)}.`) - } - return target - case "group": { - if (target instanceof MapObj) { - const group = target.map.get(key) - if (group === undefined) target.map.set(key, new Arr(builtins.Array, [value])) - else (group as Arr).items.push(value) - return undefined - } - const group = getOwn(target as Obj, key as string) - if (group === undefined) define(target as Obj, key as string, new Arr(builtins.Array, [value])) - else (group as Arr).items.push(value) - return undefined - } - } - throw new Error(`Unknown table operation ${op}.`) -} - -// The most values one merge step writes. -const MERGE_STEP = 65_536 - -/** - * A default sort's state, as data: the values' string keys, the order so far and a buffer (indices into the values), - * the next run to sort, and the merge pass's run width, output position, and positions in its two runs. Runs of - * SORT_RUN are sorted first, then merged in passes of doubling width from the order into the buffer, which swap. - */ -const sortState = (builtins: Builtins, values: Arr): Arr => { - const keys = values.items.map(coerceToString) - const order = keys.map((_, at) => at) - return new Arr(builtins.Array, [ - new Arr(builtins.Array, keys), - new Arr(builtins.Array, order), - new Arr(builtins.Array, [...order]), - 0, - SORT_RUN, - 0, - 0, - 0, - ]) -} - -// One bounded step of a default sort: one run sorted, or up to MERGE_STEP values merged. Whether work remains. -const sortStep = (state: Arr): boolean => { - const slots = state.items - const keys = (slots[0] as Arr).items as Array - const from = (slots[1] as Arr).items as Array - const length = keys.length - const run = slots[3] as number - const width = slots[4] as number - const compare = (left: number, right: number) => compareText(keys[left]!, keys[right]!) - if (run < length) { - const end = Math.min(run + SORT_RUN, length) - const part = from.slice(run, end).sort(compare) - for (let at = 0; at < part.length; at++) from[run + at] = part[at]! - slots[3] = end - return end < length || width < length - } - const to = (slots[2] as Arr).items as Array - let out = slots[5] as number - let left = slots[6] as number - let right = slots[7] as number - const stop = Math.min(out + MERGE_STEP, length) - while (out < stop) { - const low = out - (out % (2 * width)) - const middle = Math.min(low + width, length) - const high = Math.min(low + 2 * width, length) - if (out === low) { - left = low - right = middle - } - while (out < high && out < stop) { - to[out++] = - left < middle && (right >= high || compare(from[left]!, from[right]!) <= 0) ? from[left++]! : from[right++]! - } - } - if (out === length) { - const merged = slots[2] - slots[2] = slots[1] - slots[1] = merged - slots[4] = width * 2 - out = 0 - } - slots[5] = out - slots[6] = left - slots[7] = right - return (slots[4] as number) < length -} diff --git a/packages/codemode/src/language/prelude/prelude.ts b/packages/codemode/src/language/prelude/prelude.ts deleted file mode 100644 index aa06268b2a8..00000000000 --- a/packages/codemode/src/language/prelude/prelude.ts +++ /dev/null @@ -1,57 +0,0 @@ -import type { Interpreter } from "../runtime/interpreter.js" -import { define, Fn, get, hidden, Obj, type Value } from "../runtime/objects.js" -import { builtinCodes } from "./bytecode.js" -import { helpers } from "./helpers.js" -import { code } from "./source.js" - -// The prelude: built-ins that call program code, written in Code Mode itself and compiled to bytecode ahead of time -// (see bytecode.ts). Each runtime makes its top-level functions as `Fn`s; their free names are the intrinsic globals, the `$` -// helpers, and the prelude's own functions (`GET_INTRINSIC`), so programs can't reach the helpers, and replacing a -// global can't change what a built-in does. A function named `Array$prototype$map` is installed as -// `Array.prototype.map`; one without a `$` is internal, and a generator makes iterator helpers. Snapshots name prelude -// functions as intrinsics and never copy them; the prelude's bytecode hash is part of the build id. Natives reach a -// prelude function with `fn` and hand their work on to it (`new Invoke(...)`). - -let compiled: ReturnType | undefined - -/** - * The prelude's bytecode, and its top-level functions' code by name. It is parsed without locations: a failure raised - * inside it has none, so it is located at the program's call instead (see `locate`). - */ -export const compiledPrelude = () => (compiled ??= builtinCodes("@prelude", code)) - -/** One runtime's prelude: what its functions' free names see, and its functions and helpers, by name. */ -export class Prelude { - readonly scope = new Map() - /** Every prelude function (installed or internal), as an object the intrinsic names reach. */ - readonly functions: Obj - /** The `$` helpers, as an object the intrinsic names reach. */ - readonly helpers: Obj - - constructor(ctx: Interpreter, globals: ReadonlyArray) { - const builtins = ctx.builtins - this.functions = new Obj(null) - this.helpers = new Obj(null) - for (const [name, value] of globals) this.scope.set(name, value) - for (const [name, value] of helpers(ctx)) { - define(this.helpers, name, value, hidden) - this.scope.set(name, value) - } - for (const [name, made] of compiledPrelude().byName) { - const path = name.split("$") - const fn = new Fn(builtins.Function, made, [], path.at(-1)) - // The prelude's generators are iterator helpers. - if (fn.generator) define(fn, "prototype", builtins.IteratorHelper, hidden) - this.scope.set(name, fn) - define(this.functions, name, fn, hidden) - if (path.length === 1) continue - const owner = path.slice(1, -1).reduce((value, key) => get(value as Obj, key), this.scope.get(path[0]!)) - define(owner as Obj, path.at(-1)!, fn, hidden) - } - } - - /** A prelude function, for a native that hands its work on to it. */ - fn(name: string): Fn { - return get(this.functions, name) as Fn - } -} diff --git a/packages/codemode/src/language/prelude/source.ts b/packages/codemode/src/language/prelude/source.ts deleted file mode 100644 index 676809e905d..00000000000 --- a/packages/codemode/src/language/prelude/source.ts +++ /dev/null @@ -1,693 +0,0 @@ -// The prelude's source (see prelude.ts): Code Mode JavaScript, parsed once per process. Only top-level function -// declarations; `$` names are the privileged helpers (helpers.ts). Keep `${` and backticks out of it. -export const code = String.raw` -function arrayFromIterable(items, mapper, thisArg) { - const result = [] - let index = 0 - for (const item of items) { - $ArraySet(result, index, mapper === undefined ? item : $Call(mapper, thisArg, item, index)) - index++ - } - return result -} - -// Array.from over an array-like with a mapper: every index is read, holes included. -function arrayFromLike(source, length, mapper, thisArg) { - const result = new Array(length) - let index = 0 - while (index < length) { - $ArraySet(result, index, $Call(mapper, thisArg, source[index], index)) - index++ - } - return result -} - -// The callback methods Array and Uint8Array share. They fix the iteration length when they start and read elements -// live; they skip holes, but the find methods visit them as undefined. map and filter return the receiver's kind of -// collection. -function Array$prototype$map(callback, thisArg = undefined) { - return mapItems($Receiver(this, "Array", "Array.prototype.map"), callback, thisArg, "Array.map") -} -function Uint8Array$prototype$map(callback, thisArg = undefined) { - const bytes = $Receiver(this, "Uint8Array", "Uint8Array.prototype.map") - return $DerivedBytes(mapItems(bytes, callback, thisArg, "Uint8Array.map"), bytes) -} -function mapItems(array, callback, thisArg, label) { - $Callback(callback, label) - const length = array.length - const result = new Array(length) - let index = 0 - while (index < length) { - if (index in array) $ArraySet(result, index, $Call(callback, thisArg, array[index], index, array)) - index++ - } - return result -} - -function Array$prototype$filter(callback, thisArg = undefined) { - return filterItems($Receiver(this, "Array", "Array.prototype.filter"), callback, thisArg, "Array.filter") -} -function Uint8Array$prototype$filter(callback, thisArg = undefined) { - const bytes = $Receiver(this, "Uint8Array", "Uint8Array.prototype.filter") - return $DerivedBytes(filterItems(bytes, callback, thisArg, "Uint8Array.filter"), bytes) -} -function filterItems(array, callback, thisArg, label) { - $Callback(callback, label) - const length = array.length - const result = [] - let count = 0 - let index = 0 - let item - while (index < length) { - if (index in array) { - item = array[index] - if ($Call(callback, thisArg, item, index, array)) result[count++] = item - } - index++ - } - return result -} - -function Array$prototype$forEach(callback, thisArg = undefined) { - forEachItem($Receiver(this, "Array", "Array.prototype.forEach"), callback, thisArg, "Array.forEach") -} -function Uint8Array$prototype$forEach(callback, thisArg = undefined) { - forEachItem($Receiver(this, "Uint8Array", "Uint8Array.prototype.forEach"), callback, thisArg, "Uint8Array.forEach") -} -function forEachItem(array, callback, thisArg, label) { - $Callback(callback, label) - const length = array.length - let index = 0 - while (index < length) { - if (index in array) $Call(callback, thisArg, array[index], index, array) - index++ - } -} - -function Array$prototype$some(callback, thisArg = undefined) { - return testItems($Receiver(this, "Array", "Array.prototype.some"), callback, thisArg, "Array.some", false) -} -function Uint8Array$prototype$some(callback, thisArg = undefined) { - return testItems($Receiver(this, "Uint8Array", "Uint8Array.prototype.some"), callback, thisArg, "Uint8Array.some", false) -} -function Array$prototype$every(callback, thisArg = undefined) { - return testItems($Receiver(this, "Array", "Array.prototype.every"), callback, thisArg, "Array.every", true) -} -function Uint8Array$prototype$every(callback, thisArg = undefined) { - return testItems($Receiver(this, "Uint8Array", "Uint8Array.prototype.every"), callback, thisArg, "Uint8Array.every", true) -} -// some stops at the first truthy result, every at the first falsy one. -function testItems(array, callback, thisArg, label, every) { - $Callback(callback, label) - const length = array.length - let index = 0 - while (index < length) { - if (index in array && !$Call(callback, thisArg, array[index], index, array) === every) return !every - index++ - } - return every -} - -function Array$prototype$find(callback, thisArg = undefined) { - return findItem($Receiver(this, "Array", "Array.prototype.find"), callback, thisArg, "Array.find", false, false) -} -function Uint8Array$prototype$find(callback, thisArg = undefined) { - return findItem($Receiver(this, "Uint8Array", "Uint8Array.prototype.find"), callback, thisArg, "Uint8Array.find", false, false) -} -function Array$prototype$findIndex(callback, thisArg = undefined) { - return findItem($Receiver(this, "Array", "Array.prototype.findIndex"), callback, thisArg, "Array.findIndex", false, true) -} -function Uint8Array$prototype$findIndex(callback, thisArg = undefined) { - return findItem($Receiver(this, "Uint8Array", "Uint8Array.prototype.findIndex"), callback, thisArg, "Uint8Array.findIndex", false, true) -} -function Array$prototype$findLast(callback, thisArg = undefined) { - return findItem($Receiver(this, "Array", "Array.prototype.findLast"), callback, thisArg, "Array.findLast", true, false) -} -function Uint8Array$prototype$findLast(callback, thisArg = undefined) { - return findItem($Receiver(this, "Uint8Array", "Uint8Array.prototype.findLast"), callback, thisArg, "Uint8Array.findLast", true, false) -} -function Array$prototype$findLastIndex(callback, thisArg = undefined) { - return findItem($Receiver(this, "Array", "Array.prototype.findLastIndex"), callback, thisArg, "Array.findLastIndex", true, true) -} -function Uint8Array$prototype$findLastIndex(callback, thisArg = undefined) { - return findItem($Receiver(this, "Uint8Array", "Uint8Array.prototype.findLastIndex"), callback, thisArg, "Uint8Array.findLastIndex", true, true) -} -function findItem(array, callback, thisArg, label, last, wantIndex) { - $Callback(callback, label) - const length = array.length - const step = last ? -1 : 1 - let index = last ? length - 1 : 0 - let item - while (index >= 0 && index < length) { - item = array[index] - if ($Call(callback, thisArg, item, index, array)) return wantIndex ? index : item - index += step - } - return wantIndex ? -1 : undefined -} - -// reduce and reduceRight take an initial value where the others take a thisArg. -function Array$prototype$reduce(callback, ...initial) { - return reduceItems($Receiver(this, "Array", "Array.prototype.reduce"), callback, initial, "Array.reduce", false) -} -function Uint8Array$prototype$reduce(callback, ...initial) { - return reduceItems($Receiver(this, "Uint8Array", "Uint8Array.prototype.reduce"), callback, initial, "Uint8Array.reduce", false) -} -function Array$prototype$reduceRight(callback, ...initial) { - return reduceItems($Receiver(this, "Array", "Array.prototype.reduceRight"), callback, initial, "Array.reduceRight", true) -} -function Uint8Array$prototype$reduceRight(callback, ...initial) { - return reduceItems($Receiver(this, "Uint8Array", "Uint8Array.prototype.reduceRight"), callback, initial, "Uint8Array.reduceRight", true) -} -function reduceItems(array, callback, initial, label, right) { - $Callback(callback, label) - const length = array.length - const step = right ? -1 : 1 - let index = right ? length - 1 : 0 - let accumulator - if (initial.length > 0) accumulator = initial[0] - else { - while (index >= 0 && index < length && !(index in array)) index += step - if (index < 0 || index >= length) $Throw("TypeError", label + " of an empty array with no initial value.") - accumulator = array[index] - index += step - } - while (index >= 0 && index < length) { - if (index in array) accumulator = $Call(callback, undefined, accumulator, array[index], index, array) - index += step - } - return accumulator -} - -// forEach semantics: a returned array's holes are skipped, as flattening does. -function Array$prototype$flatMap(callback, thisArg = undefined) { - const array = $Receiver(this, "Array", "Array.prototype.flatMap") - $Callback(callback, "Array.flatMap") - const length = array.length - const result = [] - let count = 0 - let index = 0 - let inner - let at - while (index < length) { - if (index in array) { - inner = $Call(callback, thisArg, array[index], index, array) - if ($IsArray(inner)) { - at = 0 - while (at < inner.length) { - if (at in inner) result[count++] = inner[at] - at++ - } - } else result[count++] = inner - } - index++ - } - return result -} - -// A sort with a comparator (see sortArray): a stable top-down merge sort that compares in the same order as the -// recursive one, running the merges (low, middle, high) the native planned in post-order over one working copy. -// Holes and undefined values sort last without being compared. -function sortWith(target, into, holes, comparator, work, undefs, merges) { - const merged = [] - let merge = 0 - let middle - let high - let left - let right - let count - let order - while (merge < merges.length) { - left = merges[merge] - middle = merges[merge + 1] - high = merges[merge + 2] - right = middle - count = 0 - while (left < middle && right < high) { - order = +$Call(comparator, undefined, work[left], work[right]) - // A NaN result counts as equal, which keeps the order stable. - if (order <= 0 || order !== order) { - $ArraySet(merged, count, work[left]) - left++ - } else { - $ArraySet(merged, count, work[right]) - right++ - } - count++ - } - $MergeRest(work, merged, count, left, middle, right, high, merges[merge]) - merge += 3 - } - return $Sorted(target, into, holes, work, undefs) -} - -// The default sort over more values than one native sort may take at once: native steps of bounded size (see -// $SortStep), so the run can pause between them like any loop. -function sortDefault(target, into, holes, values, undefs) { - const state = $SortState(values) - while ($SortStep(state)) {} - return $Sorted(target, into, holes, $SortResult(state, values), undefs) -} - -function Array$prototype$toLocaleString() { - const array = $Receiver(this, "Array", "Array.prototype.toLocaleString") - let result = "" - let index = 0 - let item - while (index < array.length) { - if (index > 0) result += "," - item = array[index] - if (item !== null && item !== undefined) result += String(item.toLocaleString()) - index++ - } - return result -} -// new Map, Set, WeakMap, and WeakSet from an iterable. -function fillCollection(target, items, kind) { - const pairs = kind === "Map" || kind === "WeakMap" - for (const item of items) { - if (!pairs) $Table("add", target, item) - else if (!$IsObject(item)) $Throw("TypeError", "new " + kind + "(...) expects [key, value] pairs as entry objects.") - else $Table("add", target, item[0], item[1]) - } - return target -} - -function Map$groupBy(items, callback) { - return groupBy(items, callback, "Map") -} -function Object$groupBy(items, callback) { - return groupBy(items, callback, "Object") -} -// Object.groupBy's groups have a null prototype, so group names never collide with inherited methods. -function groupBy(items, callback, kind) { - if (items === null || items === undefined) $Throw("TypeError", kind + ".groupBy expects an iterable collection.") - $Callback(callback, kind + ".groupBy") - const groups = $Table("groups", kind) - let index = 0 - let key - for (const item of items) { - key = callback(item, index++) - if (kind === "Object") key = String($Table("groupKey", key)) - $Table("group", groups, key, item) - } - return groups -} - -// getOrInsertComputed when the key is missing: the callback's result wins over anything it inserted itself. -function insertComputed(target, key, callback) { - const value = callback(key) - $Table("add", target, key, value) - return value -} - -function Map$prototype$forEach(callback, thisArg = undefined) { - collectionForEach($Receiver(this, "Map", "Map.prototype.forEach"), callback, thisArg, "Map.forEach") -} -function Set$prototype$forEach(callback, thisArg = undefined) { - collectionForEach($Receiver(this, "Set", "Set.prototype.forEach"), callback, thisArg, "Set.forEach") -} -// Visits entries live, as in JS. -function collectionForEach(target, callback, thisArg, label) { - $Callback(callback, label) - for (const entry of $Table("entries", target)) $Call(callback, thisArg, entry[1], entry[0], target) -} - -function Set$prototype$union(other) { - return setMethod($Receiver(this, "Set", "Set.prototype.union"), other, "union") -} -function Set$prototype$intersection(other) { - return setMethod($Receiver(this, "Set", "Set.prototype.intersection"), other, "intersection") -} -function Set$prototype$difference(other) { - return setMethod($Receiver(this, "Set", "Set.prototype.difference"), other, "difference") -} -function Set$prototype$symmetricDifference(other) { - return setMethod($Receiver(this, "Set", "Set.prototype.symmetricDifference"), other, "symmetricDifference") -} -function Set$prototype$isSubsetOf(other) { - return setMethod($Receiver(this, "Set", "Set.prototype.isSubsetOf"), other, "isSubsetOf") -} -function Set$prototype$isSupersetOf(other) { - return setMethod($Receiver(this, "Set", "Set.prototype.isSupersetOf"), other, "isSupersetOf") -} -function Set$prototype$isDisjointFrom(other) { - return setMethod($Receiver(this, "Set", "Set.prototype.isDisjointFrom"), other, "isDisjointFrom") -} -// A Set method over the other set's size, has, and keys (GetSetRecord): it either asks the other set whether it has -// each of this set's values, or takes all of the other set's values, whichever is smaller. -function setMethod(target, other, name) { - if (!$IsObject(other)) $Throw("TypeError", "Set." + name + " expects a Set-like object.") - const size = +other.size - if (size !== size) $Throw("TypeError", "Set." + name + " received a Set-like object with an invalid size.") - if (size < 0) $Throw("RangeError", "Set." + name + " received a Set-like object with a negative size.") - const has = other.has - const keys = other.keys - if (!$IsCallable(has) || !$IsCallable(keys)) $Throw("TypeError", "Set." + name + " expects callable 'has' and 'keys' methods.") - const own = $Table("size", target) - if (name === "isSubsetOf" && own > size) return false - if (name === "isSupersetOf" && own < size) return false - const result = name === "intersection" ? new Set() : name === "union" || name === "difference" || name === "symmetricDifference" ? $Table("copy", target) : undefined - const asks = name === "isSubsetOf" || ((name === "intersection" || name === "difference" || name === "isDisjointFrom") && own <= size) - let found - if (asks) { - for (const item of $Table("values", name === "difference" ? result : target)) { - found = !!$Call(has, other, item) - if (name === "intersection") { - if (found) $Table("add", result, item) - } else if (name === "difference") { - if (found) $Table("delete", result, item) - } else if (found === (name === "isDisjointFrom")) return false - } - return result === undefined ? true : result - } - const iterator = $Call(keys, other) - if (!$IsObject(iterator)) $Throw("TypeError", "Set." + name + " expects 'keys' to return an iterator object.") - for (const item of $Direct(iterator, true)) { - found = $Table("has", target, item) - if (name === "union") $Table("add", result, item) - else if (name === "intersection") { - if (found) $Table("add", result, item) - } else if (name === "difference") $Table("delete", result, item) - else if (name === "symmetricDifference") $Table(found ? "delete" : "add", result, item) - else if (found === (name === "isDisjointFrom")) return false - } - return result === undefined ? true : result -} -function Object$fromEntries(entries) { - const result = {} - for (const entry of entries) { - if (!$IsObject(entry, true)) $Throw("TypeError", "Object.fromEntries expects [key, value] entry objects.") - $Define(result, String(entry[0]), entry[1], true) - } - return result -} - -function Math$sumPrecise(items) { - const numbers = [] - for (const item of items) { - if (typeof item !== "number") $Throw("TypeError", "Math.sumPrecise expects an iterable of numbers.") - $ArraySet(numbers, numbers.length, item) - } - return $SumPrecise(numbers) -} - -// new AggregateError: the error is made (message and cause) before its errors are read. -function aggregateError(error, errors) { - const list = [] - for (const item of errors) $ArraySet(list, list.length, item) - return $Define(error, "errors", list, false) -} - -// A Uint8Array's bytes from an iterable: a new one with prototype into, or set into the Uint8Array into at -// offset. As in TypedArray.from, a mapper sees the original values, after the source is consumed in full. -function collectBytes(source, name, mapper, thisArg, into, offset) { - if (!$IsIterable(source)) $Throw("TypeError", name + " expects a Uint8Array, an array, or an iterable of numbers, received " + $Describe(source) + ".") - const values = [] - for (const item of source) $ArraySet(values, values.length, item) - let index = 0 - if (mapper !== undefined) { - while (index < values.length) { - values[index] = $Call(mapper, thisArg, values[index], index) - index++ - } - } - return $Bytes(values, into, offset) -} - -// An arguments object's [Symbol.iterator], as Array.prototype.values reads it: the length and each index, live. -function* argumentsValues() { - let index = 0 - while (index < this.length) { - yield this[index] - index++ - } -} - -// Object.entries and Object.values over an object with program getters: each key's enumerability is checked as it is -// visited, so a getter that deletes or hides a later key is seen. -function objectEntries(source, values) { - const keys = $OwnKeys(source, true, undefined) - const result = [] - let index = 0 - while (index < keys.length) { - const key = keys[index] - if ($IsEnumerableOwn(source, key)) $ArraySet(result, result.length, values ? source[key] : [key, source[key]]) - index++ - } - return result -} - -// Object.assign when a source has program getters or the target's chain has program setters: Get from each source, -// then Set on the target, key by key. -function objectAssign(target, sources) { - let at = 0 - while (at < sources.length) { - const source = sources[at] - const keys = $OwnKeys(source, false, undefined) - let index = 0 - while (index < keys.length) { - const key = keys[index] - if ($IsEnumerableOwn(source, key)) target[key] = source[key] - index++ - } - at++ - } - return target -} - -// Headers and URLSearchParams from iterable [name, value] pairs, read in full as strings before any is checked; from a -// record of names to values when init is not iterable. -function readPairs(init, label, kind, proto) { - if (!$IsIterable(init)) return $Pairs(kind, proto, init, label) - const pairs = [] - let strings - for (const pair of init) { - if (!$IsIterable(pair)) $Throw("TypeError", label + " expects iterable [name, value] pairs.") - strings = [] - for (const item of pair) $ArraySet(strings, strings.length, String(item)) - $ArraySet(pairs, pairs.length, strings) - } - return $Pairs(kind, proto, pairs, label) -} - -// Headers and URLSearchParams forEach: the callback sees each pair as listed when it started. -function pairsForEach(target, pairs, callback, thisArg) { - let index = 0 - while (index < pairs.length) { - $Call(callback, thisArg, pairs[index][1], pairs[index][0], target) - index++ - } -} -// Iterator helpers are prelude generators, made with %IteratorHelper% as their prototype. Each is primed to its first -// yield, so a return() before the first next() still closes the source, from its finally. -function Iterator$from(value) { - if ($IsObject(value) && $Inherits(value, Iterator.prototype)) return value - return prime(wrapHelper(value, flattenable(value, true, "Iterator.from"))) -} -function* wrapHelper(source, iterator) { - let started = false - try { - yield - started = true - for (const item of iterator) yield item - } finally { - if (!started) closeIterator(source) - } -} - -function Iterator$prototype$map(mapper) { - const iterator = $Direct(this, false) - $Callback(mapper, "Iterator.prototype.map") - return prime(mapHelper(this, iterator, mapper)) -} -function* mapHelper(source, iterator, mapper) { - let started = false - try { - yield - started = true - let counter = 0 - for (const item of iterator) yield mapper(item, counter++) - } finally { - if (!started) closeIterator(source) - } -} - -function Iterator$prototype$filter(predicate) { - const iterator = $Direct(this, false) - $Callback(predicate, "Iterator.prototype.filter") - return prime(filterHelper(this, iterator, predicate)) -} -function* filterHelper(source, iterator, predicate) { - let started = false - try { - yield - started = true - let counter = 0 - for (const item of iterator) if (predicate(item, counter++)) yield item - } finally { - if (!started) closeIterator(source) - } -} - -function Iterator$prototype$take(limit) { - const iterator = $Direct(this, false) - return prime(takeHelper(this, iterator, count(limit, "take"))) -} -function* takeHelper(source, iterator, remaining) { - let started = false - try { - yield - started = true - if (remaining === 0) return closeIterator(source) - for (const item of iterator) { - remaining-- - yield item - if (remaining === 0) break - } - } finally { - if (!started) closeIterator(source) - } -} - -function Iterator$prototype$drop(limit) { - const iterator = $Direct(this, false) - return prime(dropHelper(this, iterator, count(limit, "drop"))) -} -function* dropHelper(source, iterator, remaining) { - let started = false - try { - yield - started = true - for (const item of iterator) { - if (remaining > 0) remaining-- - else yield item - } - } finally { - if (!started) closeIterator(source) - } -} - -function Iterator$prototype$flatMap(mapper) { - const iterator = $Direct(this, false) - $Callback(mapper, "Iterator.prototype.flatMap") - return prime(flatMapHelper(this, iterator, mapper)) -} -function* flatMapHelper(source, iterator, mapper) { - let started = false - try { - yield - started = true - let counter = 0 - for (const item of iterator) { - for (const inner of flattenable(mapper(item, counter++), false, "Iterator.prototype.flatMap")) yield inner - } - } finally { - if (!started) closeIterator(source) - } -} - -function prime(helper) { - helper.next() - return helper -} - -// A take or drop count: a number that is not NaN or negative. -function count(limit, name) { - const number = +limit - const integer = number === Infinity || number === -Infinity ? number : number - (number % 1) - if (number !== number || integer < 0) $Throw("RangeError", "Iterator.prototype." + name + " expects a non-negative count, received " + number + ".") - return integer -} - -// GetIteratorFlattenable: an iterable by its [Symbol.iterator], otherwise the object itself as an iterator. -function flattenable(value, strings, name) { - if (typeof value === "string" ? !strings : !$IsObject(value)) $Throw("TypeError", name + " expects an iterable or iterator, received " + $Describe(value) + ".") - const method = value[Symbol.iterator] - return $Direct(method === undefined || method === null ? value : $Call(method, value), false) -} - -function closeIterator(iterator) { - const method = iterator.return - if (method !== undefined && method !== null && !$IsObject($Call(method, iterator))) $Throw("TypeError", "Iterator return() must return an object.") -} - -function Iterator$prototype$toArray() { - const result = [] - for (const item of $Direct(this, false)) $ArraySet(result, result.length, item) - return result -} - -function Iterator$prototype$reduce(callback, ...initial) { - const iterator = $Direct(this, false) - $Callback(callback, "Iterator.prototype.reduce") - let accumulator = initial[0] - let started = initial.length > 0 - let index = 0 - for (const item of iterator) { - if (started) accumulator = callback(accumulator, item, index) - else accumulator = item - started = true - index++ - } - if (!started) $Throw("TypeError", "Iterator.prototype.reduce of an empty iterator with no initial value.") - return accumulator -} - -function Iterator$prototype$forEach(callback) { - iteratorTest(this, callback, "forEach") -} -function Iterator$prototype$some(callback) { - return iteratorTest(this, callback, "some") -} -function Iterator$prototype$every(callback) { - return iteratorTest(this, callback, "every") -} -function Iterator$prototype$find(callback) { - return iteratorTest(this, callback, "find") -} -// Calls the callback with each value and its index until its result decides; leaving early closes the iterator. -function iteratorTest(self, callback, name) { - const iterator = $Direct(self, false) - $Callback(callback, "Iterator.prototype." + name) - let index = 0 - let result - for (const item of iterator) { - result = callback(item, index++) - if (name === "some" && result) return true - if (name === "every" && !result) return false - if (name === "find" && result) return item - } - return name === "every" ? true : name === "some" ? false : undefined -} - -// JSON.parse's reviver: children are revived first, each replacing (or, when the reviver gives undefined, removing) -// its property; then the reviver sees the value itself. -function revive(holder, key, reviver) { - const value = holder[key] - if ($IsObject(value)) { - const names = $Keys(value) - let index = 0 - let revived - while (index < names.length) { - revived = revive(value, names[index], reviver) - if (revived === undefined) delete value[names[index]] - else value[names[index]] = revived - index++ - } - } - return $Call(reviver, holder, key, value) -} - -// String replace with a callback, once the matches are found: each is the text before it and the callback's -// arguments; the text after the last one follows. -function replaceWith(matches, rest, callback) { - let result = "" - let index = 0 - while (index < matches.length) { - result += matches[index][0] + String(callback(...matches[index][1])) - index++ - } - return result + rest -} -` diff --git a/packages/codemode/src/language/runtime.ts b/packages/codemode/src/language/runtime.ts deleted file mode 100644 index 4320d5e83a7..00000000000 --- a/packages/codemode/src/language/runtime.ts +++ /dev/null @@ -1,179 +0,0 @@ -export * as Runtime from "./runtime.js" - -import { Deferred, Effect, Exit } from "effect" -import type { Json } from "./data.js" -import type { DurableFn, Fn, Namespace } from "./host-function.js" -import { - finishExecution, - type Outcome, - type Result, - resumeProgram, - type Run, - type Running, - type Setup, - startProgram, - SuspendError, - type Suspended, -} from "./runtime/execute.js" -import type { SnapshotError } from "./snapshot/snapshot.js" - -export { SuspendError } -export type { Outcome, Result, Run, Suspended } - -/** Budgets enforced on each run. Time counts active time only, across every resume of a run. */ -export type Limits = { - /** Wall-clock milliseconds before interruption. No default: absent means no timeout. */ - readonly timeoutMs?: number - /** - * Maximum UTF-8 bytes retained from the result and logs. Warnings have a separate equal budget; truncation notices - * are additional. - */ - readonly maxOutputBytes?: number -} - -/** - * How a host call's arguments carry program values the host can't hold. Every host function in the runtime gets its - * arguments this way; results are not affected. - */ -export type Translate = { - /** - * A program function inside an argument: `"error"` (the default) fails the call; `"drop"` leaves it out, as - * `JSON.stringify` does: an object's key is left out, an array's item is `null`, and an argument is `undefined`. - */ - readonly functions?: "error" | "drop" | undefined - /** - * A program promise inside an argument: `"error"` (the default) fails the call; `"await"` makes the call wait for it - * to settle and use its value. A rejection fails the call with its reason. - */ - readonly promises?: "error" | "await" | undefined -} - -/** A runtime's host globals for one run: `Host.fn`, `Host.durableFn`, `Host.namespace`, and plain values of them. */ -export type Globals = Readonly> - -export type Options = { - /** - * The globals a program reaches, made for each run when it starts and again when it resumes, so they can keep the - * run's own state in `run.metadata`. - */ - readonly globals?: ((run: Run) => G) | undefined - /** Module names that load a global, beyond its own name: `{ bun: "Bun" }` makes `import "bun"` load `Bun`. */ - readonly modules?: Readonly> | undefined - readonly limits?: Limits | undefined - readonly translate?: Translate | undefined -} - -/** Options for `Runtime.program`. */ -export type ProgramOptions = { - /** Read-only JSON values bound in the program's outer scope (shadowable by top-level declarations). */ - readonly bindings?: Readonly> | undefined - /** Names this run's host calls (`:`); a random UUID by default. */ - readonly runId?: string | undefined -} - -/** How `program.suspend` saves a run's state. */ -export type SuspendOptions = { - /** The most bytes a saved state may take; a larger one fails the suspend, and the run goes on. */ - readonly maxBytes?: number -} - -/** A reusable confined runtime over host globals. */ -export type Runtime = { - /** Runs a program to its end. */ - readonly execute: (code: string, options?: ProgramOptions) => Effect.Effect - /** A program ready to run once; nothing runs until `program.run()`. */ - readonly program: (code: string, options?: ProgramOptions) => Program - /** - * A suspended run (its `state`, or that state as bytes) as a program to continue in this runtime, which must be the - * same build with the same host globals. The state is checked when it runs: `run()` fails with a `SnapshotError` - * when it can't be resumed here. - */ - readonly resume: (state: Suspended["state"] | Uint8Array) => Program -} - -/** - * One run of a program. `run()` runs it in the current fiber until it ends or is suspended, and owns its host calls: - * interrupting `run()` interrupts them. A program runs once: running it again is a defect. - */ -export type Program = { - readonly run: () => Effect.Effect - /** - * Saves the run's state and stops it, at once, from another fiber: `run()` then returns the same `Suspended`, and so - * does this. It fails with a `SuspendError`, leaving the run running, while a host call that can't be suspended is - * in progress, or when the state can't be saved or is over `options.maxBytes`. A run that already ended gives its - * result. Before `run()` starts, this waits for it to start. - */ - readonly suspend: (options?: SuspendOptions) => Effect.Effect -} - -/** The Effect environment the host functions among `G` need, at any depth. */ -export type Services = ServicesOf - -type ServicesOf> = Depth["length"] extends 8 - ? never - : T extends Fn | DurableFn | Namespace - ? R - : T extends object - ? ServicesOf - : never - -/** Creates a runtime whose programs reach `globals`. */ -export const make = (options: Options = {}): Runtime> => { - type R = Services - const setup: Setup = { - limits: { - timeoutMs: validateLimit("timeoutMs", options.limits?.timeoutMs, 1), - maxOutputBytes: validateLimit("maxOutputBytes", options.limits?.maxOutputBytes, 0), - }, - globals: options.globals, - modules: options.modules, - translate: { - functions: options.translate?.functions ?? "error", - promises: options.translate?.promises ?? "error", - }, - } - const program = (code: string, programOptions?: ProgramOptions) => - makeProgram(() => Effect.succeed(startProgram(setup, code, programOptions?.bindings, programOptions?.runId))) - return { - execute: (code, programOptions) => Effect.suspend(() => finishExecution(program(code, programOptions).run())), - program, - resume: (state) => makeProgram(() => resumeProgram(setup, state)), - } -} - -export const validateLimit = (name: string, value: number | undefined, minimum: number): number | undefined => { - if (value !== undefined && (!Number.isSafeInteger(value) || value < minimum)) { - throw new RangeError(`${name} must be a safe integer greater than or equal to ${minimum}.`) - } - return value -} - -// A program's one run: `start` makes it when `run()` is called, and a suspend waits for it. -const makeProgram = (start: () => Effect.Effect, E>): Program => { - let claimed = false - const started = Deferred.makeUnsafe, SuspendError>() - return { - run: () => - Effect.suspend(() => { - if (claimed) { - return Effect.die(new Error("A program runs once; make another with runtime.program or runtime.resume.")) - } - claimed = true - return start().pipe( - Effect.onExit((exit) => - Exit.isSuccess(exit) - ? Deferred.succeed(started, exit.value) - : Deferred.fail(started, new SuspendError({ message: "The program didn't start.", running: [] })), - ), - Effect.flatMap((running) => running.run()), - ) - }), - suspend: (options) => { - const maxBytes = options?.maxBytes - if (maxBytes !== undefined && (!Number.isSafeInteger(maxBytes) || maxBytes < 0)) { - throw new RangeError("maxBytes must be a safe integer greater than or equal to 0.") - } - return Effect.flatMap(Deferred.await(started), (running) => running.suspend(maxBytes)) - }, - } -} diff --git a/packages/codemode/src/language/runtime/callback.ts b/packages/codemode/src/language/runtime/callback.ts deleted file mode 100644 index e8911f5d5b3..00000000000 --- a/packages/codemode/src/language/runtime/callback.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { type Builtins, primitivePrototype } from "./intrinsics.js" -import { typeError } from "./model.js" -import { Callable, get, Builtin, Obj, type NativeResult, reads, type Value } from "./objects.js" -import { typeofValue } from "./references.js" -import { Convert, type Hints, Invoke, Prefetch } from "./signals.js" - -/** Invoke(value, name), as the call to make: the method the value would find through its prototype. */ -export const invokeMethod = (builtins: Builtins, value: Value, name: string, label: string): Invoke => { - const target = value instanceof Obj ? value : primitivePrototype(builtins, value) - if (target === undefined) throw typeError(`${label} called on null or undefined.`) - return new Invoke(get(target, name), value, [], undefined) -} - -/** - * The conversions a built-in received, while it runs again after them: by ordinal, the order its `withPrimitives` - * calls run in. The VM resets `count` before every built-in call. - */ -export const conversions: { count: number; replay: Array | undefined> | undefined } = { - count: 0, - replay: undefined, -} - -/** - * Runs a native body on values after ToPrimitive, in order, with one hint for all positions or one per position. - * Primitive values skip the conversion entirely. Otherwise the built-in asks the VM for the conversions (they - * call program code, so they run as prelude code) and runs again from the start once they are done; this call then - * receives them. So everything a built-in does before its last conversion must be repeatable: it reads, checks, and - * throws, but changes nothing. State the body needs as it was before the conversions (a Date's time) goes in `values`. - * With `coerce`, each value is also converted to a number or string (by its hint) before the next one is. - */ -export const withPrimitives = ( - hints: Hints, - values: Array, - body: (primitives: Array) => NativeResult, - coerce = false, -): NativeResult => { - const ordinal = conversions.count++ - const replayed = conversions.replay?.[ordinal] - if (replayed !== undefined) return body(replayed) - if (!values.some((value) => value instanceof Obj)) return body(values) - return new Convert(hints, values, ordinal, coerce) -} - -/** - * Runs a native body whose [[Get]]s may meet program getters. A getter not read yet gives `undefined` and is - * recorded; if any were, the body's result (or failure, which a placeholder may have caused) is dropped for a - * `Prefetch`: the VM runs those getters in program code, then the built-in again from the start, and the getters' - * values are read from the table this time. So the body must be repeatable until it returns: it reads, checks and - * allocates, but changes nothing it does not own. A body whose path depends on a read stops at `readsPending()`. - */ -export const withReads = (body: () => NativeResult): NativeResult => { - const outer = reads.missing - reads.missing = undefined - reads.depth++ - try { - const result = body() - return reads.missing === undefined ? result : new Prefetch(reads.missing) - } catch (error) { - if (reads.missing !== undefined) return new Prefetch(reads.missing) - throw error - } finally { - reads.depth-- - reads.missing = outer - } -} - -/** Whether a read in this `withReads` round met a getter not read yet, so what it gave is only a placeholder. */ -export const readsPending = (): boolean => reads.missing !== undefined - -/** Checks a callback argument: the callable it is, or the TypeError for one a callback site does not admit. */ -export const requireCallback = (callback: Value, name: string): Callable => { - if (isSupportedCallback(callback)) return callback - if (typeofValue(callback) === "function") { - throw typeError( - `${name} cannot use this callable as a callback; wrap it in an arrow function, e.g. (value) => fn(value).`, - ) - } - throw typeError(`${name} expects a function callback.`) -} - -// The single acceptance list for callbacks: collections, sort, string replacers, -// Array.from mappers, and promise reactions all admit exactly these callables. -// Admission means dispatchable, not necessarily invocable: new-requiring -// constructors pass the gate and throw a TypeError on call, like JS. -export const isSupportedCallback = (value: Value): value is Callable => - value instanceof Callable && !(value instanceof Builtin && !value.callback) diff --git a/packages/codemode/src/language/runtime/driver.ts b/packages/codemode/src/language/runtime/driver.ts deleted file mode 100644 index 586cbd78ba9..00000000000 --- a/packages/codemode/src/language/runtime/driver.ts +++ /dev/null @@ -1,265 +0,0 @@ -import { Cause, type Context, Effect, Exit, Fiber } from "effect" -import type { Json } from "../data.js" -import { DurableFn, type Fn } from "../host-function.js" -import type { HostCall } from "../scheduler.js" -import { locate } from "./errors.js" -import { HostFailure, PendingThrow } from "./model.js" -import type { Vm } from "../vm.js" -import { abrupt, type Completion, Interruption, normal } from "./signals.js" - -/** What `Driver.run` returns once the run was suspended: its state is saved, and the VM stopped. */ -export const SUSPENDED: unique symbol = Symbol("codemode.suspended") - -/** For tests: `onPark` is called each time a run has nothing to do but wait on host calls in flight. */ -export const parking: { onPark?: () => void } = {} - -/** - * Runs the VM (see `Vm`) in Effect: the only place program execution meets the host. It calls `vm.run` - * until the program ends, and does what each stop asks: yields to the Effect scheduler for a slice, and starts the host - * calls the VM queued, as fibers with the caller's services, reporting each outcome back with `vm.complete`. - * Fibers live only here, by host call id, and never become part of the VM's state. - * - * A durable call runs as two fibers, `start` then `wait`, so suspending can detach the second and keep the JSON data - * `start` gave. An idempotent call's running fiber is detached and interrupted on suspend, and the call is saved as - * queued to run again on resume. The VM can be swapped for a restored one between stops (the round-trip test mode - * does); a fiber's outcome goes to whichever VM is current, by host call id. - */ -export class Driver { - private readonly fibers = new Map>() - // Calls whose fibers were interrupted to suspend or end the run: their outcomes are not reported. - private readonly detached = new Set() - private wake: (() => void) | undefined - private stopping = false - private suspending = false - // Blocking host work interrupted on its own, which interrupts the execution. - private interrupted: Cause.Cause | undefined - /** Called at every slice and host stop, before queued calls start: the round-trip test mode swaps the VM. */ - checkpoint: Effect.Effect | undefined - - constructor( - public vm: Vm, - /** The services host work runs with: the caller's, so host functions see its context, tracing, and clock. */ - private readonly services: Context.Context, - ) {} - - /** - * Runs the VM until the program's body completes, then returns how it ended, or `SUSPENDED` once the run was - * suspended (see `detach`). Host work it started may still be running; `interrupt` stops it. Host work interrupted - * on its own that reaches the program's body, or blocking host work that is interrupted, interrupts the execution. - */ - run(): Effect.Effect { - const self = this - return Effect.gen(function* () { - while (true) { - if (self.interrupted !== undefined) return yield* Effect.failCause(self.interrupted) - if (self.suspending) return SUSPENDED - const stop = self.vm.run() - if (stop.kind === "slice") { - if (self.checkpoint !== undefined) yield* self.checkpoint - yield* Effect.yieldNow - continue - } - if (stop.kind === "host") { - if (stop.calls.length === 0) { - parking.onPark?.() - yield* self.settled - continue - } - if (self.checkpoint !== undefined) yield* self.checkpoint - // Suspended now: the calls stay queued, and start on resume. - if (self.suspending) continue - for (const handed of stop.calls) self.launch(self.vm.call(handed.id) ?? handed) - continue - } - if (stop.kind === "stuck") { - return abrupt( - new PendingThrow( - "Error", - "The program is waiting on a promise that can never settle: nothing else is running, so nothing can resolve it. There are no timers or sleep, so don't wait or poll inside a program.", - stop.node, - ), - ) - } - const outcome = stop.completion - if (!outcome.ok && outcome.error instanceof Interruption) return yield* Effect.failCause(outcome.error.cause) - return outcome - } - }) - } - - /** - * The host calls that block a suspend now: every call in progress except an idempotent call, or a durable call in - * `started`. A call queued but not started starts on resume, unless its arguments hold host functions, which - * can't be saved. - */ - blocking(): Array<{ readonly key: string; readonly path: string }> { - return this.vm - .calls() - .filter( - (call) => - call.holdsFunctions || - (call.status !== "queued" && call.status !== "started" && call.policy !== "idempotent"), - ) - .map((call) => ({ key: call.key, path: call.label })) - } - - /** - * Whether the run holds live host values: a call whose function can't be found again, that waits on its result, or - * whose arguments hold host functions. - */ - get holdsHostValues(): boolean { - return this.vm.calls().some((call) => call.work !== undefined || call.path === undefined || call.holdsFunctions) - } - - /** - * Stops the run to suspend it, once its state is saved: `run` returns `SUSPENDED` at its next step, and running - * idempotent or durable calls' fibers are detached, so ending them reports nothing. - */ - detach(): void { - this.suspending = true - for (const id of this.fibers.keys()) this.detached.add(id) - this.wake?.() - } - - /** Stops host work still running, waiting for its cleanup; a durable call's work is cancelled unless detached. */ - interrupt(): Effect.Effect { - const self = this - return Effect.uninterruptible( - Effect.gen(function* () { - self.stopping = true - while (self.fibers.size > 0) yield* Fiber.interruptAll([...self.fibers.values()]) - // A suspended run's durable work keeps running, to be waited on at resume. - if (self.suspending) return - for (const call of self.vm.calls()) { - if (call.status !== "started") continue - call.status = "completed" - const fn = self.function(call) - if (!(fn instanceof DurableFn)) continue - const cancel = Effect.suspend(() => fn.cancel(call.data as Json, self.context(call))) - yield* Effect.ignore(cancel as Effect.Effect).pipe(Effect.provideContext(self.services)) - } - }), - ) - } - - /** Starts calls that were queued (including idempotent ones) and waits on durable calls in `started`. */ - resume(): void { - if (this.suspending) return - for (const call of this.vm.calls()) { - if (call.status === "queued") this.launch(call) - else if (call.status === "started") this.wait(call) - } - } - - // Starts host work now; its outcome goes back to the VM: a blocking call's continues the job that made it, a - // concurrent call's waits in the inbox and settles its promise in a later job, in completion order. - private launch(call: HostCall): void { - call.status = "running" - if (call.work !== undefined) return this.fork(call.id, outcome(call.work)) - const fn = this.function(call) - if (fn === undefined) { - return this.fork( - call.id, - Effect.fail(new HostFailure("ExecutionFailure", `${call.label} is not available in this runtime.`)), - ) - } - if (fn instanceof DurableFn) { - return this.fork( - call.id, - Effect.suspend(() => fn.start(call.args, this.context(call))), - (data) => { - const current = this.vm.call(call.id) - if (current === undefined) return - current.status = "started" - current.data = data as Json - if (this.stopping || this.detached.has(call.id)) return - this.wait(current) - }, - ) - } - this.fork( - call.id, - Effect.suspend(() => { - try { - return outcome(fn.run(call.args, this.context(call))) - } catch (reason) { - return Effect.fail(reason) - } - }), - ) - } - - private wait(call: HostCall): void { - const fn = this.function(call) - if (!(fn instanceof DurableFn)) return - this.fork( - call.id, - Effect.suspend(() => fn.wait(call.data as Json, this.context(call))), - ) - } - - // The call's host function: the one it was made with, or, in a restored run, the one at its path now. - private function(call: HostCall): Fn | DurableFn | undefined { - if (call.fn !== undefined) return call.fn - if (call.path === undefined) return undefined - return (call.fn = this.vm.ctx.hosts?.resolve(call.path)) - } - - private context(call: HostCall) { - return { key: call.key, args: call.args, suspending: () => this.suspending } - } - - // Forks `work` with the caller's services; it starts synchronously, so host functions run before the VM runs - // another job. A success goes to `next` when given, otherwise to the VM. - private fork(id: number, work: Effect.Effect, next?: (value: unknown) => void): void { - const fiber = Effect.runForkWith(this.services)(work as Effect.Effect) - this.fibers.set(id, fiber) - fiber.addObserver((exit) => { - if (this.fibers.get(id) === fiber) this.fibers.delete(id) - if (next !== undefined && Exit.isSuccess(exit)) return next(exit.value) - // Interrupted to end or suspend the run: nothing is left to settle. - if (this.stopping || this.detached.has(id)) return - const call = this.vm.call(id) - if (call === undefined) return - if (call.blocking && Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)) { - // Blocking work interrupted on its own interrupts the execution. - this.interrupted = exit.cause - this.wake?.() - return - } - this.vm.complete( - id, - Exit.isSuccess(exit) - ? normal(exit.value) - : abrupt( - Cause.hasInterruptsOnly(exit.cause) - ? new Interruption(exit.cause) - : Cause.hasDies(exit.cause) - ? locate(Cause.squash(exit.cause), call.site) - : Cause.squash(exit.cause), - ), - ) - this.wake?.() - }) - } - - private get settled(): Effect.Effect { - return Effect.callback((resume) => { - if (this.vm.ready || this.suspending || this.interrupted !== undefined) return resume(Effect.void) - this.wake = () => { - this.wake = undefined - resume(Effect.void) - } - return Effect.sync(() => { - this.wake = undefined - }) - }) - } -} - -// What a host function returned, as the Effect its call waits on: an Effect runs, a Promise settles. -const outcome = (result: unknown): Effect.Effect => { - if (Effect.isEffect(result)) return result as Effect.Effect - if (result instanceof Promise) return Effect.tryPromise({ try: () => result, catch: (reason) => reason }) - return Effect.succeed(result) -} diff --git a/packages/codemode/src/language/runtime/errors.ts b/packages/codemode/src/language/runtime/errors.ts deleted file mode 100644 index 6c22f6cdb13..00000000000 --- a/packages/codemode/src/language/runtime/errors.ts +++ /dev/null @@ -1,233 +0,0 @@ -import { - type AstNode, - type Diagnostic, - formatLocation, - HostFailure, - PendingThrow, - Throw, - sourceLocation, -} from "./model.js" -import { containsRuntimeReference } from "./references.js" -import { createErrorValue, type ErrorType, isErrorType } from "./intrinsics.js" -import { constructor, methods, prototypeFrom, receiver } from "./native.js" -import { - type Callable, - define, - get, - has, - hidden, - type Native, - Arr, - ErrorObj, - errorToString, - Obj, - coerceToString, - type Value, -} from "./objects.js" -import type { Interpreter } from "./interpreter.js" -import { Invoke } from "./signals.js" -import { withPrimitives, withReads } from "./callback.js" -import { formatValue } from "../stdlib/console.js" -import { inPrelude } from "./source.js" - -/** - * A host error's message as text. A host can store anything there; an object must not cross as itself, and turning it - * into text would run its own methods. - */ -export const errorMessage = (error: Error): string => { - const message: unknown = error.message - if (typeof message === "string") return message - if (message === undefined || typeof message === "function" || (typeof message === "object" && message !== null)) { - return "" - } - return String(message) -} - -/** A host error's name as a program error type, read once so a getter cannot pass the check and then change. */ -export const errorType = (error: Error): ErrorType => { - const name: unknown = error.name - return typeof name === "string" && isErrorType(name) ? name : "Error" -} - -export const normalizeError = (error: unknown): Diagnostic => { - if (error instanceof PendingThrow) { - const location = error.node?.loc ? sourceLocation(error.node) : undefined - return { - kind: error.kind, - message: `${error.type}: ${error.message}${formatLocation(location)}`, - ...(location ? { location } : {}), - ...(error.suggestions ? { suggestions: error.suggestions } : {}), - } - } - - if (error instanceof HostFailure) { - return { - kind: error.kind, - message: error.message, - ...(error.suggestions.length > 0 ? { suggestions: error.suggestions } : {}), - } - } - - if (error instanceof Throw) { - const value = error.value - if (value instanceof ErrorObj) { - return value.failure ? normalizeError(value.failure) : { kind: "ExecutionFailure", message: errorToString(value) } - } - let message: string - if (containsRuntimeReference(value)) { - // Never expose runtime reference internals through thrown values. - message = "a non-data value" - } else if (typeof value === "string") { - message = value - } else { - message = formatValue(value) - } - return { kind: "ExecutionFailure", message: `Uncaught: ${message}` } - } - - if (error instanceof RangeError && /call stack|recursion/i.test(errorMessage(error))) { - return { - kind: "ExecutionFailure", - message: "Execution exceeded the maximum nesting depth.", - } - } - - if (error instanceof Error) { - return { - kind: error.name === "SyntaxError" ? "ParseError" : "ExecutionFailure", - message: errorMessage(error), - } - } - - return { - kind: "ExecutionFailure", - message: String(error), - } -} - -/** - * Gives a failure the source location of the expression that raised it, keeping the first one attached. Host errors - * that escape a built-in become the equivalent program error here. - */ -export const locate = (error: unknown, node?: AstNode): unknown => { - if (error instanceof PendingThrow) { - if ((error.node === undefined || inPrelude(error.node)) && node) error.node = node - return error - } - if (error instanceof Error && !(error instanceof HostFailure)) { - return new PendingThrow(errorType(error), errorMessage(error), node) - } - return error -} - -/** - * The program value a handler receives for a failure; one failure always yields the same value. A host failure has no - * site of its own, so its `stack` names `site`, where the handler observed it, when there is one. - */ -export const materialize = (ctx: Interpreter, thrown: unknown, site?: AstNode): Value => { - if (thrown instanceof Throw) return thrown.value - const builtins = ctx.builtins - if (thrown instanceof PendingThrow) { - if (thrown.value === undefined) { - const node = thrown.node - thrown.value = createErrorValue( - builtins[thrown.type], - thrown.message, - node?.loc && !inPrelude(node) ? stackFrame(node) : "", - ) - thrown.value.failure = thrown - } - return thrown.value - } - return createErrorValue( - builtins[thrown instanceof Error ? errorType(thrown) : "Error"], - normalizeError(thrown).message, - site?.loc ? stackFrame(site) : "", - ) -} - -/** - * One V8-style `stack` line for a program site: `at name (:line:col)`, or `at :line:col` at top - * level. The location is in the submitted source and never names a host file. - */ -export const stackFrame = (node: AstNode, name?: string): string => { - const location = sourceLocation(node) - const at = `:${location.line}:${location.column}` - return `\n at ${name === undefined ? at : `${name} (${at})`}` -} - -export const createAggregateErrorValue = ( - ctx: Interpreter, - errors: Array, - message: string, - proto: Obj = ctx.builtins.AggregateError, -) => { - const value = createErrorValue(proto, message) - define(value, "errors", new Arr(ctx.builtins.Array, errors), { ...hidden }) - return value -} - -// ES2022 `new Error(message, { cause })`: installed only when the options object has the property at all. -const withCause = (created: ErrorObj, options: Value) => { - if (options instanceof Obj && has(options, "cause")) define(created, "cause", get(options, "cause"), hidden) - return created -} - -/** An error constructor such as `Error` or `TypeError`; callable with or without `new`, like JS. */ -export const errorGlobal = (type: ErrorType, ctx: Interpreter) => { - const builtins = ctx.builtins - const prototype = builtins[type] - const construct = (args: Array, newTarget: Callable) => { - const proto = prototypeFrom(newTarget, prototype) - if (type === "AggregateError") { - const message = args[1] - return withPrimitives( - "string", - message === undefined ? [] : [message], - ([text]) => { - return withReads(() => { - const created = withCause( - createErrorValue(proto, message === undefined ? "" : coerceToString(text), ctx.vm.stackTrace()), - args[2], - ) - return new Invoke(ctx.prelude.fn("aggregateError"), undefined, [created, args[0]], undefined) - }) - }, - true, - ) - } - const message = args[0] - return withPrimitives( - "string", - message === undefined ? [] : [message], - ([text]) => - withReads(() => - withCause( - createErrorValue(proto, message === undefined ? undefined : coerceToString(text), ctx.vm.stackTrace()), - args[1], - ), - ), - true, - ) - } - const ctor: Native = constructor(builtins, prototype, { - name: type, - length: type === "AggregateError" ? 2 : 1, - call: (_, args) => construct(args, ctor), - construct, - }) - if (type === "Error") { - methods(builtins, prototype, [ - [ - "toString", - 0, - (thisValue) => withReads(() => errorToString(receiver(Obj, thisValue, "Error.prototype.toString"), get)), - ], - ]) - methods(builtins, ctor, [["isError", 1, (_, args) => args[0] instanceof ErrorObj]]) - return ctor - } - // Derived constructors extend Error itself, so its statics are inherited. The globals table creates Error first. - ctor.proto = get(builtins.Error, "constructor") as Obj - return ctor -} diff --git a/packages/codemode/src/language/runtime/execute.ts b/packages/codemode/src/language/runtime/execute.ts deleted file mode 100644 index 1f151cfd8ff..00000000000 --- a/packages/codemode/src/language/runtime/execute.ts +++ /dev/null @@ -1,550 +0,0 @@ -import { parse, type Program } from "acorn" -import { Cause, Deferred, Effect, Option, Schema } from "effect" -import { fromJson, type Json } from "../data.js" -import { DurableFn } from "../host-function.js" -import { fromBytes, header, type Snapshot, SnapshotError, toBytes } from "../snapshot/snapshot.js" -import { normalizeError } from "./errors.js" -import { hostGlobals } from "./extensions.js" -import { createBuiltins } from "./intrinsics.js" -import { Interpreter } from "./interpreter.js" -import type { Value } from "./objects.js" -import { type Diagnostic, formatLocation, sourceLocation } from "./model.js" -import { Driver, SUSPENDED } from "./driver.js" -import { Interruption } from "./signals.js" -import { Source } from "./source.js" -import type { Vm } from "../vm.js" -import type { Translate } from "../runtime.js" - -/** - * A suspend that failed, leaving the run running: `running` names each host call that blocked it by its key and its - * path (`fetch`, `fs.readFile`, `api.issues.list`). Empty when the state couldn't be saved or was too large. - */ -export class SuspendError extends Schema.TaggedError()("SuspendError", { - message: Schema.String, - running: Schema.Array(Schema.Struct({ key: Schema.String, path: Schema.String })), -}) {} - -/** A run that ended: its value, or the diagnostic it failed with, plus its logs and its `run.metadata` at the end. */ -export type Result = - | { - readonly ok: true - readonly value: Json - readonly warnings?: ReadonlyArray - readonly logs?: ReadonlyArray - readonly truncated?: boolean - readonly metadata: Json - } - | { - readonly ok: false - readonly error: Diagnostic - readonly logs?: ReadonlyArray - readonly truncated?: boolean - readonly metadata: Json - } - -/** A run stopped by `program.suspend`: its whole state, to resume with `Runtime.resume`. */ -export type Suspended = { - readonly ok: "suspended" - readonly state: Snapshot -} - -/** How a run of a program ended: its result, or its saved state once suspended. */ -export type Outcome = Result | Suspended - -/** - * One run of a program, as its host globals see it. `metadata` is the host's own state for the run, as JSON: saved - * with a suspended run and given back on resume, and in the run's result. - */ -export type Run = { - readonly id: string - metadata: Json -} - -/** The budgets every run of a runtime gets. Time counts active time only, across every resume of a run. */ -export type Limits = { - readonly timeoutMs: number | undefined - readonly maxOutputBytes: number | undefined -} - -type Globals = (ctx: Interpreter) => ReadonlyArray - -/** How a runtime runs programs: its limits and host globals, shared by every run it starts. */ -export type Setup = { - readonly limits: Limits - readonly translate?: Required | undefined - /** Each run's host globals (see `Host`): made when it starts, and again for a restored run. */ - readonly globals?: ((run: Run) => Readonly>) | undefined - /** Module names that load a global, beyond its own name; see `Runtime.Options`. */ - readonly modules?: Readonly> | undefined - /** Globals made as program values (a test harness), made again the same way for a restored run. */ - readonly programGlobals?: Globals | undefined -} - -/** Turns a suspended outcome into a failure, for callers that only run programs to their end. */ -export const finishExecution = (outcome: Effect.Effect): Effect.Effect => - Effect.map(outcome, (outcome): Result => { - if (outcome.ok !== "suspended") return outcome - return { - ok: false, - error: { kind: "ExecutionFailure", message: "The program suspended, which isn't supported here." }, - metadata: outcome.state.header.metadata, - } - }) - -/** A program ready to run on the VM: nothing runs until `run`. */ -export const startProgram = ( - setup: Setup, - code: string, - bindings?: Readonly>, - runId: string = crypto.randomUUID(), -): Running => - new Running(setup, 0, () => { - if (code.trim().length === 0) { - return { ok: false, error: { kind: "ParseError", message: "Code cannot be empty." }, metadata: null } - } - const parsed = parseProgram(code) - if (!parsed.ok) return { ok: false, error: parsed.error, metadata: null } - const run: Run = { id: runId, metadata: null } - const runtime = instantiate(setup, run, bindings) - runtime.vm.hosts.runId = runId - runtime.vm.start(parsed.source) - return [runtime, run] as const - }) - -/** - * Restores a saved run into this runtime, under the limits it was saved with, ready to run as `startProgram`'s. - * Fails with a `SnapshotError` when the state can't be read or belongs to another build, other host globals, or other - * sources, or when a durable call it waits on has no durable function at its path any more. - */ -export const resumeProgram = ( - setup: Setup, - saved: Snapshot | Uint8Array | unknown, -): Effect.Effect, SnapshotError> => - Effect.try({ - try: () => { - const state = saved instanceof Uint8Array ? fromBytes(saved) : saved - const saw = header(state) - const resumed: Setup = { - ...setup, - limits: { - timeoutMs: saw.limits.timeoutMs ?? undefined, - maxOutputBytes: saw.limits.maxOutputBytes ?? undefined, - }, - } - const run: Run = { id: saw.runId, metadata: saw.metadata } - const fresh = instantiate(resumed, run) - const snapshot = restoreInto(state, fresh.vm) - for (const call of fresh.vm.calls()) { - if (call.status !== "started") continue - if (call.path === undefined || !(fresh.hosts?.resolve(call.path) instanceof DurableFn)) { - throw new SnapshotError( - `The pending durable call ${call.key} (${call.label}) cannot resume because that function is no longer a durable function in this runtime.`, - ) - } - } - return new Running(resumed, snapshot.header.budget.activeMs, () => [fresh, run] as const, true) - }, - catch: (error) => (error instanceof SnapshotError ? error : new SnapshotError(String(error))), - }) - -// Sources restored recently, by text: the AST is never changed, so runs restored from the same program share it. -const restoredSources = new Map() - -const restoreInto = (saved: unknown, vm: Vm): Snapshot => - vm.restore(saved, { - parse: (code) => { - const known = restoredSources.get(code) - if (known !== undefined) return known - const parsed = parseProgram(code) - if (!parsed.ok) throw new SnapshotError(`A saved source no longer parses: ${parsed.error.message}`) - if (restoredSources.size >= 16) restoredSources.delete(restoredSources.keys().next().value!) - restoredSources.set(code, parsed.source) - return parsed.source - }, - interruption: () => new Interruption(Cause.interrupt()), - }) - -// A new runtime for a run: intrinsics, the host globals, the program's bindings, and its VM. -const instantiate = (setup: Setup, run: Run, bindings?: Readonly>): Interpreter => { - const ctx = new Interpreter({ - builtins: createBuiltins(), - logs: [], - modules: setup.modules, - globals: (ctx) => [ - ...(setup.programGlobals?.(ctx) ?? []), - ...(setup.globals === undefined ? [] : hostGlobals(ctx, setup.globals(run), setup.translate)), - ], - bindings: - bindings === undefined - ? undefined - : (ctx) => Object.entries(bindings).map(([name, value]) => [name, fromJson(ctx, value)] as const), - }) - if (roundTrip) ctx.vm.tripEvery = ROUND_TRIP_TICKS - return ctx -} - -/** - * The round-trip test mode: at every host stop and every slice, which come every few loop back-edges and calls, a run's - * state is saved to bytes and restored into a brand-new runtime, which continues the run. It proves the VM's state is - * plain data at every step. Internal: only the test suite turns it on (`bun run test:roundtrip`). - */ -let roundTrip = false -export const setRoundTrip = (enabled: boolean) => { - roundTrip = enabled -} -const ROUND_TRIP_TICKS = 2 -const ROUND_TRIP_MAX = 200 - -/** One run's state: the runtime it is in now (restoring swaps it), its driver, and how much active time it used. */ -export class Running { - private ctx!: Interpreter - private run_!: Run - private driver!: Driver - private startedAt = 0 - // Set once the program's body ends, and once a suspend saved the run: either way, `done` gets the outcome next. - private finished = false - private suspended: Suspended | undefined - private trips = 0 - // Checkpoints to let pass before the next round trip, so a large state is not saved at every one. - private skip = 0 - private readonly started = Deferred.makeUnsafe() - private readonly done = Deferred.makeUnsafe() - - constructor( - private readonly setup: Setup, - /** Active milliseconds used before this run, by earlier ones of the same execution. */ - private readonly activeBefore: number, - private readonly prepare: () => readonly [Interpreter, Run] | Result, - private readonly resuming = false, - ) {} - - /** Makes the run's runtime and driver, then runs the program in the current fiber until it ends or is suspended. */ - run(): Effect.Effect { - const self = this - return Effect.gen(function* () { - const prepared = self.prepare() - if (!Array.isArray(prepared)) { - self.finished = true - return prepared as Result - } - const [ctx, run] = prepared as readonly [Interpreter, Run] - self.ctx = ctx - self.run_ = run - self.driver = new Driver(ctx.vm, yield* Effect.context()) - if (roundTrip) self.driver.checkpoint = Effect.sync(() => self.trip()) - self.startedAt = Date.now() - return yield* self.execute() - }).pipe( - Effect.onExit((exit) => - Effect.andThen(Deferred.succeed(self.started, undefined), Deferred.done(self.done, exit)), - ), - ) - } - - /** - * Saves the run's state and stops it, at once: `run` then returns the same `Suspended`. It fails with a - * `SuspendError`, leaving the run running, while a host call is in progress. A run that already ended gives its result. - * Before the run has started, it waits for it. - */ - suspend(maxBytes: number | undefined): Effect.Effect { - return Effect.andThen( - Deferred.await(this.started), - Effect.suspend(() => { - if (this.finished) return Deferred.await(this.done) - const saved = this.save(maxBytes) - if (saved instanceof SuspendError) return Effect.fail(saved) - this.stop(saved) - return Deferred.await(this.done) - }), - ) - } - - private execute(): Effect.Effect { - const self = this - const limits = this.setup.limits - const logged = () => { - const logs = self.ctx.logs - return logs.length > 0 ? { logs: [...logs] } : {} - } - const metadata = () => self.run_.metadata - const failed = (error: Diagnostic): Result => ({ ok: false, error, ...logged(), metadata: metadata() }) - // Set only after copy-out so timeouts cannot report invalid values as completed. - let returned: { value: Json; warnings: () => Array } | undefined - - const base = Effect.gen(function* () { - const driver = self.driver - if (self.resuming) driver.resume() - yield* Deferred.succeed(self.started, undefined) - const outcome = yield* driver.run() - if (outcome === SUSPENDED) return self.suspended! - self.finished = true - if (!outcome.ok) return failed(normalizeError(outcome.error)) - const result = (outcome.value as Json | undefined) ?? null - const vm = self.ctx.vm - returned = { value: result, warnings: () => vm.diagnostics() } - // Host work the program left running is interrupted, not awaited. - yield* driver.interrupt() - const warnings = vm.diagnostics() - return { - ok: true, - value: result, - ...(warnings.length > 0 ? { warnings } : {}), - ...logged(), - metadata: metadata(), - } satisfies Result - }).pipe(Effect.ensuring(Effect.suspend(() => self.driver.interrupt()))) - const timeoutMs = limits.timeoutMs - const operation = - timeoutMs === undefined - ? base - : base.pipe( - Effect.timeoutOrElse({ - duration: Math.max(0, timeoutMs - this.activeBefore), - orElse: () => - Effect.sync((): Outcome => { - self.finished = true - if (self.suspended !== undefined) return self.suspended - if (returned === undefined) { - return failed({ kind: "TimeoutExceeded", message: `Execution timed out after ${timeoutMs}ms.` }) - } - // Keep the timeout warning first so truncation preserves it. - return { - ok: true, - value: returned.value, - warnings: [ - { - kind: "TimeoutExceeded", - message: `The program returned, but background work was still running at the ${timeoutMs}ms timeout and was interrupted. Await all started promises.`, - }, - ...returned.warnings(), - ], - ...logged(), - metadata: metadata(), - } satisfies Result - }), - }), - ) - - return operation.pipe( - Effect.catchCause((cause) => - Cause.hasInterruptsOnly(cause) ? Effect.interrupt : Effect.succeed(failed(normalizeError(Cause.squash(cause)))), - ), - Effect.map((result) => - result.ok === "suspended" || limits.maxOutputBytes === undefined - ? result - : boundOutput(result, limits.maxOutputBytes), - ), - ) - } - - // Suspends the run once its state is saved: the driver stops. - private stop(saved: Suspended): void { - this.finished = true - this.suspended = saved - this.driver.detach() - } - - /** - * Saves the run's state, with no effect on the run: the calls that block a suspend, or the state as it is now. The - * program shares this thread with the caller, so it is at a step boundary. - */ - private save(maxBytes: number | undefined): Suspended | SuspendError { - const vm = this.ctx.vm - const running = this.driver.blocking() - if (running.length > 0) { - return new SuspendError({ - message: `The run can't be suspended while ${running.map((call) => call.path).join(", ")} ${running.length === 1 ? "is" : "are"} running.`, - running, - }) - } - // Idempotent calls in flight are saved as queued so they run again on resume under the same key. - const idempotent = vm.calls().filter((call) => call.status === "running") - for (const call of idempotent) call.status = "queued" - const restoreRunning = () => { - for (const call of idempotent) call.status = "running" - } - const limits = this.setup.limits - const saved = attempt(() => - vm.capture({ - limits: { timeoutMs: limits.timeoutMs ?? null, maxOutputBytes: limits.maxOutputBytes ?? null }, - activeMs: this.activeBefore + Date.now() - this.startedAt, - metadata: this.run_.metadata, - strict: false, - }), - ) - if (!saved.ok) { - restoreRunning() - const error = saved.error - return new SuspendError({ - message: `The run's state couldn't be saved: ${error instanceof Error ? error.message : String(error)}`, - running: [], - }) - } - const snapshot = saved.value.snapshot - if (maxBytes !== undefined) { - const size = toBytes(snapshot).byteLength - if (size > maxBytes) { - restoreRunning() - return new SuspendError({ - message: `The run's state takes ${size} bytes, more than the ${maxBytes}-byte limit, so it couldn't be suspended.`, - running: [], - }) - } - } - return { ok: "suspended", state: snapshot } - } - - // The round-trip test mode's checkpoint: saves the state to bytes and continues in a brand-new runtime, made with - // the run's metadata as it would be on resume. States that hold live host values (a call waiting on what its host - // function returned, a function a host function without `snapshot` hooks returned) can't round-trip, so they are - // skipped; a value with no data form anywhere else is a codec gap and fails the run. - private trip(): void { - const driver = this.driver - if (this.trips >= ROUND_TRIP_MAX) { - this.ctx.vm.tripEvery = 0 - return - } - if (this.skip > 0) { - this.skip-- - return - } - if (driver.holdsHostValues) return - this.trips++ - const attempted = attempt(() => this.ctx.vm.capture({ metadata: this.run_.metadata, strict: true })) - // A host function's `snapshot` hooks may refuse to save a value, which fails a suspend, not the run. - if (!attempted.ok) { - const error = attempted.error - if (error instanceof SnapshotError && error.message.startsWith("The host function ")) return - throw error - } - const saved = attempted.value - const bytes = toBytes(saved.snapshot) - this.skip = Math.floor(saved.snapshot.records.length / 200 + bytes.byteLength / 100_000) - if (saved.lost.length > 0) return - const restored = fromBytes(bytes) - const run = { id: this.run_.id, metadata: header(restored).metadata } - const fresh = instantiate(this.setup, run) - restoreInto(restored, fresh.vm) - this.ctx = fresh - this.run_ = run - driver.vm = fresh.vm - } -} - -const attempt = (run: () => A): { ok: true; value: A } | { ok: false; error: unknown } => { - try { - return { ok: true, value: run() } - } catch (error) { - return { ok: false, error } - } -} - -export const parseProgram = ( - code: string, -): { ok: true; program: Program; source: Source } | { ok: false; error: Diagnostic } => { - try { - const program = parse(code, { - ecmaVersion: "latest", - sourceType: "script", - allowReturnOutsideFunction: true, - allowAwaitOutsideFunction: true, - // Imports bind globals by module name; scripts keep sloppy-mode semantics, which module source would make strict. - allowImportExportEverywhere: true, - locations: true, - }) - const exported = program.body.find((statement) => statement.type.startsWith("Export")) - if (exported) { - const location = sourceLocation(exported) - return { - ok: false, - error: { - kind: "ParseError", - message: `SyntaxError: Exports aren't available. Return the result instead.${formatLocation(location)}`, - location, - }, - } - } - return { ok: true, program, source: new Source("main", code, program) } - } catch (error) { - // Only acorn's own syntax errors become a located ParseError; anything else keeps the generic failure path. - const acorn = error instanceof SyntaxError ? decodeAcornError(error) : Option.none() - if (Option.isNone(acorn)) throw error - return { ok: false, error: parseDiagnostic(acorn.value) } - } -} - -// Acorn appends ` (line:column)` to its messages; its lines are 1-based and its columns 0-based. -const AcornError = Schema.Struct({ - message: Schema.String, - loc: Schema.Struct({ line: Schema.Number, column: Schema.Number }), -}) -const decodeAcornError = Schema.decodeUnknownOption(AcornError) - -const parseDiagnostic = (error: typeof AcornError.Type): Diagnostic => { - const location = { line: error.loc.line, column: error.loc.column + 1 } - const reason = error.message.replace(/ \(\d+:\d+\)$/, "") - const feature = reason === "Unexpected character '@'" - ? "Decorators are not supported." - : /^Private field '#/.test(reason) - ? "Private class members (#name) are not supported. Use a regular property instead." - : undefined - const text = feature ?? `${reason.endsWith(".") ? reason : `${reason}.`} Code must be plain JavaScript written as a program body.` - return { kind: "ParseError", message: `SyntaxError: ${text}${formatLocation(location)}`, location } -} - -const utf8ByteLength = (value: string): number => new TextEncoder().encode(value).byteLength - -// Drop a replacement character produced by truncating inside a UTF-8 sequence. -const utf8Truncate = (value: string, maxBytes: number): string => { - const bytes = new TextEncoder().encode(value) - if (bytes.byteLength <= maxBytes) return value - const text = new TextDecoder("utf-8").decode(bytes.slice(0, Math.max(0, maxBytes))) - return text.endsWith("\uFFFD") ? text.slice(0, -1) : text -} - -// The longest prefix of `items` whose sizes add up to at most `budget` bytes. -const fitting = (items: ReadonlyArray, budget: number, size: (item: T) => number): Array => { - const kept: Array = [] - let used = 0 - for (const item of items) { - used += size(item) - if (used > budget) break - kept.push(item) - } - return kept -} - -// Warnings have a separate budget so result data cannot starve diagnostics. -const boundOutput = (result: Result, maxOutputBytes: number): Result => { - const serialized = result.ok ? (JSON.stringify(result.value) ?? "null") : "" - const valueBytes = result.ok ? utf8ByteLength(serialized) : 0 - const valueTruncated = valueBytes > maxOutputBytes - const value: Json = !result.ok - ? null - : valueTruncated - ? `${utf8Truncate(serialized, maxOutputBytes)} [result truncated: ${valueBytes} bytes exceeds the ${maxOutputBytes}-byte output limit; return a smaller value]` - : result.value - - const warnings = result.ok ? (result.warnings ?? []) : [] - const keptWarnings = fitting(warnings, maxOutputBytes, (warning) => utf8ByteLength(JSON.stringify(warning)) + 1) - const warningsCut = keptWarnings.length < warnings.length - if (warningsCut) { - keptWarnings.push({ - kind: "Truncated", - message: `${warnings.length - keptWarnings.length} additional warnings omitted by the output limit.`, - }) - } - - const logs = result.logs ?? [] - const logBudget = Math.max(0, maxOutputBytes - Math.min(valueBytes, maxOutputBytes)) - const kept = fitting(logs, logBudget, (line) => utf8ByteLength(line) + 1) - const logsCut = kept.length < logs.length - if (logsCut) kept.push(`[logs truncated: showing ${kept.length} of ${logs.length} lines]`) - - if (!valueTruncated && !warningsCut && !logsCut) return result - const warningsPart = keptWarnings.length > 0 ? { warnings: keptWarnings } : {} - const logsPart = kept.length > 0 ? { logs: kept } : {} - return result.ok - ? { ok: true, value, ...warningsPart, ...logsPart, truncated: true, metadata: result.metadata } - : { ok: false, error: result.error, ...logsPart, truncated: true, metadata: result.metadata } -} diff --git a/packages/codemode/src/language/runtime/extensions.ts b/packages/codemode/src/language/runtime/extensions.ts deleted file mode 100644 index 0182b8e7501..00000000000 --- a/packages/codemode/src/language/runtime/extensions.ts +++ /dev/null @@ -1,540 +0,0 @@ -import { Effect } from "effect" -import { DurableFn, Fn, Namespace, type Snapshot } from "../host-function.js" -import type { HostTarget } from "../host.js" -import { BufferObj } from "../stdlib/buffer.js" -import { StreamingResponse } from "../streaming-response.js" -import { errorMessage, errorType } from "./errors.js" -import type { Interpreter } from "./interpreter.js" -import { createErrorValue } from "./intrinsics.js" -import { member } from "./intrinsic-names.js" -import { MAX_ARRAY_LENGTH, MAX_VALUE_DEPTH } from "./limits.js" -import { AsyncIteratorSymbol, HostFailure, PendingThrow, rangeError, Throw, typeError } from "./model.js" -import { native } from "./native.js" -import { - define, - defineAccessorHalf, - get, - has, - hidden, - keys, - Arr, - Bytes, - DateObj, - ErrorObj, - HeadersObj, - HostNamespace, - MapObj, - Obj, - OMITTED, - PromiseObj, - RegExpObj, - SetObj, - URLObj, - URLSearchParamsObj, - coerceToString, - type Value, - lookup, - type Slot, -} from "./objects.js" -import { describeValue, isOpaque, typeofValue } from "./references.js" -import type { Translate } from "../runtime.js" -import { Interruption } from "./signals.js" -import { type HostOrigin, SnapshotError } from "../snapshot/codec.js" - -/** - * Where a value crossing from the host is: among the run's host globals, at `global` (so a function there can be found - * again on resume), or inside a value a host function with `snapshot` hooks returned (`within`), at `path` - * (undefined inside a Map or a Set, where no path leads). - */ -type Place = { - readonly global?: ReadonlyArray | undefined - readonly within?: Within | undefined - /** Whether it is among the globals at all, even where no path of names leads: inside an array, a Map or a Set. */ - readonly installed?: boolean | undefined -} - -type Within = { - readonly owner: string - readonly root: object - readonly path: ReadonlyArray | undefined -} - -/** - * The global bindings of one run's host globals (see `Host`), and the bridge its calls cross (`ctx.hosts`). - * Everything crossing the boundary is converted: plain data and built-in wrappers are copied, a host function becomes - * a program function whose calls cross the same way, a namespace becomes a path the program reads into, and a host - * Promise or Effect becomes a program promise. - */ -const setterOnly = (slot: Slot): boolean => !("value" in slot) && slot.get === undefined - -export const hostGlobals = ( - ctx: Interpreter, - globals: Readonly>, - translate: Required = { functions: "error", promises: "error" }, -): ReadonlyArray => { - const builtins = ctx.builtins - // The `snapshot` hooks of the host functions among the globals that have them, by label. - const owners = new Map() - const shape: Array = [] - // The program functions wrapping functions inside values a hooked host function returned, by where they came from. - const origins = new WeakMap() - // The host function behind each function inside a result, so passing it back to a host function that takes - // functions hands the host its own function. The functions among the globals are left out: whatever the host runs - // around their calls (permission checks, say) runs when the program calls them, and the host could call one - // without it. - const hosted = new WeakMap() - - // With `waiting`, a promise that hasn't fulfilled goes there instead, and the copy is to be made again once it settles. - // `back` collects the host functions that cross back; without it they are treated like any function. - const toHost = ( - value: Value, - label: string, - depth: number, - seen: Set, - waiting: Array | undefined, - back: Array | undefined, - ): unknown => { - if (depth > MAX_VALUE_DEPTH) throw typeError(`${label} exceeds the maximum value depth of ${MAX_VALUE_DEPTH}.`) - if (isPrimitive(value)) return value - const host = value instanceof Obj ? hosted.get(value) : undefined - if (back !== undefined && host !== undefined) { - back.push(host) - return host - } - if (translate.functions === "drop" && typeofValue(value) === "function") return OMITTED - if (seen.has(value as object)) throw typeError(`${label} contains a circular value.`) - if (waiting !== undefined && value instanceof PromiseObj) { - if (value.state !== "fulfilled") { - waiting.push(value) - return undefined - } - seen.add(value) - const copied = toHost(value.result as Value, label, depth + 1, seen, waiting, back) - seen.delete(value) - return copied - } - if (!(value instanceof Obj) || isOpaque(value)) { - throw typeError(`${label} contains ${describeValue(value)}, which cannot be passed to the host.`) - } - seen.add(value) - const next = (item: Value) => { - const copied = toHost(item, label, depth + 1, seen, waiting, back) - return copied === OMITTED && (value instanceof MapObj || value instanceof SetObj) ? undefined : copied - } - if (value instanceof ErrorObj) { - const name = coerceToString(get(value, "name")) - const message = get(value, "message") - const text = message === undefined ? "" : coerceToString(message) - const copied = - name === "AggregateError" ? new AggregateError([], text) : new (hostErrors.get(name) ?? Error)(text) - for (const key of new Set(["cause", ...keys(value)])) { - if (uncrossed.has(key) || !has(value, key) || setterOnly(lookup(value, key)!)) continue - const item = crossing(() => next(get(value, key))) - if (item === left || item === OMITTED) continue - Object.defineProperty(copied, key, { - value: item, - writable: true, - configurable: true, - enumerable: key !== "cause", - }) - } - seen.delete(value) - return copied - } - const copied = value.toHost(next) - seen.delete(value) - return copied - } - - // A live response's state, read through a host function: the one kind of accessor made after the intrinsics. - const hostGetter = (name: string, read: () => boolean) => - native(builtins, { runtime: "host", name: `get ${name}`, call: () => read() }) - - const fromHost = (value: unknown, label: string, depth = 0, seen = new Set(), place: Place = {}): Value => { - if (depth > MAX_VALUE_DEPTH) throw typeError(`${label} exceeds the maximum value depth of ${MAX_VALUE_DEPTH}.`) - if (isPrimitive(value)) return value - if (place.global !== undefined) { - if (value instanceof Namespace) return namespace(value, label, place.global) - if (value instanceof Fn && value.snapshot !== undefined) { - owners.set(label, value.snapshot) - shape.push(`${label} (snapshot hooks)`) - } - } - if (value instanceof Fn || value instanceof DurableFn) { - const owner = - value instanceof Fn && value.snapshot !== undefined && place.global !== undefined ? label : undefined - return wrap(value, label, { label, path: place.global, owner }) - } - if (typeof value === "function") { - const within = place.within - const made = wrap(plain(value), label, { label, path: place.global, owner: within?.owner }, value) - if (place.installed !== true) hosted.set(made, value) - if (within !== undefined && within.path !== undefined) { - origins.set(made, { owner: within.owner, root: within.root, path: within.path, label }) - } - return made - } - if (value !== null && typeof value === "object") { - const next = (item: unknown, path: string, key?: string | number) => - fromHost(item, path, depth + 1, seen, { - global: place.global !== undefined && typeof key === "string" ? [...place.global, key] : undefined, - within: place.within && { - ...place.within, - path: key === undefined || place.within.path === undefined ? undefined : [...place.within.path, key], - }, - installed: place.installed, - }) - // Nothing a host value hands back is kept: results are read as primitives or copied. Where the value's own - // method could hand back host storage or an object (`getTime`, `slice`, `map`), its internal data is read. - if (value instanceof Date) return new DateObj(builtins.Date, Date.prototype.getTime.call(value)) - if (value instanceof StreamingResponse) { - const response = value.response - const body = response.body - const stream = new Obj(builtins.Object) - if (body) { - defineAccessorHalf( - stream, - "locked", - "get", - hostGetter("locked", () => body.locked), - false, - ) - define( - stream, - "cancel", - next(async (reason?: unknown) => body.cancel(reason), `${label}.body.cancel`), - ) - define( - stream, - "getReader", - next((options?: { mode?: string }) => { - if (options?.mode !== undefined) throw new TypeError("Only the default stream reader is supported.") - const reader = body.getReader() - return { - read: async () => reader.read(), - cancel: async (reason?: unknown) => reader.cancel(reason), - releaseLock: () => reader.releaseLock(), - } - }, `${label}.body.getReader`), - ) - define( - stream, - AsyncIteratorSymbol, - next(() => { - const iterator = body.values() - return { - next: async () => iterator.next(), - return: async () => iterator.return!(), - } - }, `${label}.body[Symbol.asyncIterator]`), - ) - } - const result = new Obj(builtins.Object) - for (const key of ["url", "status", "statusText", "ok", "headers"] as const) - define(result, key, next(response[key], `${label}.${key}`)) - define(result, "redirected", value.redirected) - define(result, "body", body ? stream : null) - defineAccessorHalf( - result, - "bodyUsed", - "get", - hostGetter("bodyUsed", () => response.bodyUsed), - false, - ) - for (const key of ["text", "json", "bytes", "arrayBuffer"] as const) - define( - result, - key, - next(async () => response[key](), `${label}.${key}`), - ) - return result - } - if (value instanceof RegExp) return new RegExpObj(builtins.RegExp, value.source, value.flags) - if (typeof Buffer !== "undefined" && Buffer.isBuffer(value)) - return new BufferObj(builtins.Buffer, new Uint8Array(value)) - if (value instanceof Uint8Array) return new Bytes(builtins.Uint8Array, new Uint8Array(value)) - if (value instanceof ArrayBuffer) { - const view = new Uint8Array(value) - // Only a real buffer has bytes to view; anything else would be read as array-like and lose them silently. - if (view.buffer !== value) - throw typeError(`${label} produced ${describeHost(value)}, which the program cannot hold.`) - return new Bytes(builtins.Uint8Array, new Uint8Array(view)) - } - if (value instanceof Error) { - if (seen.has(value)) throw typeError(`${label} produced a circular value.`) - seen.add(value) - const copied = createErrorValue(builtins[errorType(value)], errorMessage(value)) - const fields = value as unknown as Record - for (const key of new Set(["cause", ...Object.keys(value)])) { - if (uncrossed.has(key) || !(key in value)) continue - // Read once: a getter could pass the check and then hand back a function. - const field = fields[key] - if (typeof field === "function") continue - const item = crossing(() => next(field, `${label}.${key}`, key)) - if (item === left) continue - define(copied, key, item, key === "cause" ? hidden : undefined) - } - seen.delete(value) - return copied - } - if (value instanceof URL) return new URLObj(builtins.URL, builtins.URLSearchParams, new URL(value.href)) - if (value instanceof URLSearchParams) { - return new URLSearchParamsObj(builtins.URLSearchParams, new URLSearchParams(value)) - } - if (value instanceof Headers) return new HeadersObj(builtins.Headers, new Headers(value)) - if (value instanceof Map) { - const wrapped = new MapObj(builtins.Map) - for (const [key, item] of value) wrapped.map.set(next(key, label), next(item, label)) - return wrapped - } - if (value instanceof Set) { - const wrapped = new SetObj(builtins.Set) - for (const item of value) wrapped.set.add(next(item, label)) - return wrapped - } - if (seen.has(value)) throw typeError(`${label} produced a circular value.`) - seen.add(value) - if (Array.isArray(value)) { - const length = value.length - if (length > MAX_ARRAY_LENGTH) { - throw rangeError(`${label} produced an array of ${length} items; at most ${MAX_ARRAY_LENGTH} can cross.`) - } - // Filled in order so the copy stays a dense array; holes stay holes, as a copy made with `map` would leave them. - const items: Array = [] - for (let index = 0; index < length; index += 1) { - if (index in value) items[index] = next(value[index], `${label}[${index}]`, index) - } - items.length = length - seen.delete(value) - return new Arr(builtins.Array, items) - } - const prototype = Object.getPrototypeOf(value) - if (prototype === Object.prototype || prototype === null) { - const copied = new Obj(builtins.Object) - for (const [key, item] of Object.entries(value)) define(copied, key, next(item, `${label}.${key}`, key)) - seen.delete(value) - return copied - } - } - throw typeError(`${label} produced ${describeHost(value)}, which the program cannot hold.`) - } - - // A host function as a program function: its calls go through the run's host calls (see `HostCalls.call`). The - // name and length come from the host function, read once, and only as text and a count. - // `callee` is the program function calling it, when that is not the one made here (see `rewrap`). - const wrap = ( - fn: Fn | DurableFn, - label: string, - target: HostTarget, - source?: Function, - callee?: Obj, - ) => { - const named = source ?? (fn instanceof Fn ? fn.run : undefined) - const own: unknown = named?.name - // A host function made inline has no name of its own: it is named by where it is. - const name = - source === undefined && (typeof own !== "string" || own === "") ? label.slice(label.lastIndexOf(".") + 1) : own - const length: unknown = named?.length ?? 0 - const made = native(builtins, { - runtime: "host", - name: typeof name === "string" ? name : "", - length: typeof length === "number" && Number.isSafeInteger(length) && length >= 0 ? length : 0, - call: (_, values, site) => ctx.vm.hosts.call(fn, values, site, target, callee ?? made), - ...(fn instanceof Fn && fn.constructible - ? { construct: (values, _, site) => ctx.vm.hosts.call(fn, values, site, target, callee ?? made) } - : {}), - }) - return made - } - - // A namespace among the globals: a path the program reads into, whose calls ask `resolve` for the function. - const namespace = (value: Namespace, label: string, global: ReadonlyArray) => { - ctx.hostNamespaces.set(label, { - keys: (path) => value.keys(path), - call: (path, values, site) => { - const found = value.resolve(path) - if (found instanceof HostFailure) throw found - return ctx.vm.hosts.call( - found, - values, - site, - { - label: path.reduce((at, key) => member(at, key), label), - path: [...global, ...path], - owner: undefined, - }, - new HostNamespace(label, path), - ) - }, - }) - shape.push(`${label} (namespace)`) - return new HostNamespace(label, []) - } - - const failure = (reason: unknown, label: string): unknown => { - if ( - reason instanceof HostFailure || - reason instanceof PendingThrow || - reason instanceof Interruption || - reason instanceof Throw - ) { - return reason - } - try { - return new Throw(fromHost(reason, label)) - } catch (error) { - return error - } - } - - const hooks = (owner: string) => { - const snapshot = owners.get(owner) - if (snapshot === undefined) throw new SnapshotError(`The host function ${owner} has no snapshot hooks.`) - return snapshot - } - - ctx.hosts = { - shape, - toHost: (values, label, waiting, back) => - values.map((item, index) => { - const copied = toHost( - item, - `Argument ${index + 1} to ${label}`, - 0, - new Set(), - translate.promises === "await" ? waiting : undefined, - back, - ) - return copied === OMITTED ? undefined : copied - }), - fromHost: (value, label, owner) => - fromHost(value, label, 0, new Set(), { - within: - owner !== undefined && ((typeof value === "object" && value !== null) || typeof value === "function") - ? { owner, root: value, path: [] } - : undefined, - }), - failure, - isPending: (value) => value instanceof Promise || Effect.isEffect(value), - invoke: (fn, args, key, label) => { - let result: unknown - try { - result = fn.run(args, { key, suspending: () => false }) - } catch (reason) { - throw failure(reason, label) - } - if (Effect.isEffect(result)) return { kind: "block", work: result } - if (result instanceof Promise) return { kind: "pending", work: result } - return { kind: "value", value: result } - }, - resolve: (path) => { - let at: unknown = globals - for (let index = 0; index < path.length; index++) { - if (at instanceof Namespace) { - const found = at.resolve(path.slice(index)) - return found instanceof HostFailure ? undefined : found - } - if (typeof at !== "object" || at === null || !Object.hasOwn(at, path[index]!)) return undefined - at = (at as { readonly [key: string]: unknown })[path[index]!] - } - return at instanceof Fn || at instanceof DurableFn ? at : undefined - }, - origin: (value) => origins.get(value), - encode: (owner, root) => hostStep(owner, "save", () => hooks(owner).encode(root)), - decode: (owner, data) => { - const root = hostStep(owner, "restore", () => hooks(owner).decode(data)) - if ((typeof root !== "object" && typeof root !== "function") || root === null) { - throw new SnapshotError( - `The host function ${owner} restored a value it returned as ${typeof root}, not an object.`, - ) - } - return root - }, - rewrap: (target, origin) => { - const host = origin.path.reduce( - (at, key) => - (typeof at === "object" && at !== null) || typeof at === "function" - ? (at as { readonly [key: string | number]: unknown })[key] - : undefined, - origin.root, - ) - if (typeof host !== "function") { - throw new SnapshotError( - `The host function ${origin.owner} restored a value with no function at ${origin.label}, so this state can't resume.`, - ) - } - const made = wrap( - plain(host), - origin.label, - { label: origin.label, path: undefined, owner: origin.owner }, - host, - target, - ) - // The restored function keeps its own properties; only what calling it does comes from the new one. - Object.assign(target, { tag: made.tag, call: made.call, construct: made.construct, callback: made.callback }) - origins.set(target, origin) - hosted.set(target, host) - }, - } - - return Object.entries(globals).map( - ([name, value]) => [name, fromHost(value, name, 0, new Set(), { global: [name], installed: true })] as const, - ) -} - -// A plain host function (one inside a result, or among the globals) is called like a `sync` host function that takes -// functions. -const plain = (value: Function) => new Fn((args) => value(...args), "sync", false, undefined, false, true) - -// Runs a host function's `snapshot` hook; what goes wrong is the state's problem, said as such. -const hostStep = (owner: string, what: "save" | "restore", step: () => A): A => { - try { - return step() - } catch (error) { - if (error instanceof SnapshotError) throw error - throw new SnapshotError( - `The host function ${owner} couldn't ${what} a value it returned: ${error instanceof Error ? error.message : String(error)}`, - ) - } -} - -/** - * An error crosses as its name, message, `cause`, and own enumerable fields, such as Node's `code`, `errno`, - * `syscall`, and `path`. `stack` stays on its own side, `message` crosses once as text, and no field may shadow an - * Error method. A field that cannot cross (a socket, a handle, a function) is left behind so the error itself always - * arrives. - */ -const uncrossed = new Set(["stack", "message", "constructor", "toString", "__proto__"]) -const left = Symbol("left behind") -const crossing = (convert: () => T): T | typeof left => { - try { - return convert() - } catch (reason) { - if (reason instanceof PendingThrow) return left - throw reason - } -} - -const hostErrors = new Map([ - ["TypeError", TypeError], - ["RangeError", RangeError], - ["SyntaxError", SyntaxError], - ["ReferenceError", ReferenceError], - ["EvalError", EvalError], - ["URIError", URIError], -]) - -// The primitives the interpreter operates on; symbols and BigInts are not among them. -const isPrimitive = (value: unknown): value is string | number | boolean | null | undefined => - value === null || - value === undefined || - typeof value === "string" || - typeof value === "number" || - typeof value === "boolean" - -const describeHost = (value: unknown): string => { - if (typeof value !== "object" || value === null) return `a ${typeof value}` - const name = (value as { constructor?: { name?: string } }).constructor?.name - if (name === undefined || name === "") return "an object" - return `${/^[AEIO]/.test(name) ? "an" : "a"} ${name}` -} diff --git a/packages/codemode/src/language/runtime/generators.ts b/packages/codemode/src/language/runtime/generators.ts deleted file mode 100644 index 4031adc2616..00000000000 --- a/packages/codemode/src/language/runtime/generators.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { fn, type Method, methods, receiver } from "./native.js" -import { AsyncIteratorSymbol, type GeneratorRequestKind, IteratorSymbol, typeError } from "./model.js" -import { define, hidden, GeneratorObj } from "./objects.js" -import type { Interpreter } from "./interpreter.js" -import { Push } from "./signals.js" -import { AsyncFromSyncIterator, generatorRequest, generatorStep } from "../generators.js" - -/** - * `next`/`return`/`throw` on the generator prototypes (async generators answer with promises), on iterator helpers, - * and on the async-from-sync iterator. A generator's suspended body runs on the caller's job stack. - */ -export const generatorGlobals = (ctx: Interpreter): void => { - const builtins = ctx.builtins - const sync = (kind: GeneratorRequestKind, owner = "Generator.prototype"): Method => [ - kind, - 1, - (thisValue, args) => { - const method = `${owner}.${kind}` - const generator = receiver(GeneratorObj, thisValue, method) - if (generator.asynchronous) throw typeError(`${method} called on incompatible receiver an async generator.`) - return generatorStep(ctx.vm, generator, kind, args[0]) - }, - ] - const async = (kind: GeneratorRequestKind): Method => [ - kind, - 1, - (thisValue, args) => generatorRequest(ctx.vm, thisValue, kind, args[0]), - ] - const adapter = (kind: GeneratorRequestKind): Method => [ - kind, - 1, - (thisValue, args) => - new Push("AsyncFromSyncIterator", [ - receiver(AsyncFromSyncIterator, thisValue, `AsyncFromSyncIterator.${kind}`), - kind, - args, - ]), - ] - methods(builtins, builtins.Generator, [sync("next"), sync("return"), sync("throw")]) - // Iterator helpers are the prelude's generators (see prelude.ts). - methods(builtins, builtins.IteratorHelper, [sync("next", "%IteratorHelper%"), sync("return", "%IteratorHelper%")]) - methods(builtins, builtins.AsyncGenerator, [async("next"), async("return"), async("throw")]) - methods(builtins, builtins.AsyncFromSyncIterator, [adapter("next"), adapter("return"), adapter("throw")]) - define( - builtins.Iterator, - IteratorSymbol, - fn(builtins, "[Symbol.iterator]", 0, (thisValue) => thisValue), - hidden, - ) - define( - builtins.AsyncIterator, - AsyncIteratorSymbol, - fn(builtins, "[Symbol.asyncIterator]", 0, (thisValue) => thisValue), - hidden, - ) -} diff --git a/packages/codemode/src/language/runtime/globals.ts b/packages/codemode/src/language/runtime/globals.ts deleted file mode 100644 index 675f0d9dd4e..00000000000 --- a/packages/codemode/src/language/runtime/globals.ts +++ /dev/null @@ -1,167 +0,0 @@ -import { Arr, BoundFn, Callable, coerceToInteger, defineAccessor, get, Obj, type Value } from "./objects.js" -import { withReads } from "./callback.js" -import { arrayGlobal } from "../stdlib/array.js" -import { textDecoderGlobal, textEncoderGlobal, uint8ArrayGlobal } from "../stdlib/bytes.js" -import { bufferGlobal } from "../stdlib/buffer.js" -import { mapGlobal, setGlobal, weakMapGlobal, weakSetGlobal } from "../stdlib/collections.js" -import { consoleGlobal } from "../stdlib/console.js" -import { dateGlobal } from "../stdlib/date.js" -import { jsonGlobal } from "../stdlib/json.js" -import { mathGlobal } from "../stdlib/math.js" -import { booleanGlobal, numberGlobal } from "../stdlib/number.js" -import { objectGlobal } from "../stdlib/object.js" -import { regexpGlobal } from "../stdlib/regexp.js" -import { stringGlobal } from "../stdlib/string.js" -import { uriGlobal, urlGlobal, urlSearchParamsGlobal } from "../stdlib/url.js" -import { headersGlobal } from "../stdlib/headers.js" -import { iteratorGlobals } from "../stdlib/iterator.js" -import { coercion } from "../stdlib/value.js" -import { base64Global, cryptoGlobal, structuredCloneGlobal } from "../stdlib/web.js" -import { errorGlobal } from "./errors.js" -import { errorTypes } from "./intrinsics.js" -import { constants, constructor, methods, native, receiver } from "./native.js" -import { AsyncIteratorSymbol, IteratorSymbol, typeError } from "./model.js" -import { checkArrayLength } from "./limits.js" -import { generatorGlobals } from "./generators.js" -import { promiseGlobal } from "./promises.js" -import type { Interpreter } from "./interpreter.js" -import { Invoke } from "./signals.js" - -// Function.prototype.constructor exists so `fn.constructor === Function` holds; dynamic code is unsupported. -const functionGlobal = (ctx: Interpreter) => { - const reject = () => { - throw typeError("The Function constructor is not supported; write the function inline.") - } - const target = (thisValue: Value, method: string) => receiver(Callable, thisValue, `Function.prototype.${method}`) - methods(ctx.builtins, ctx.builtins.Function, [ - ["call", 1, (thisValue, args, site) => new Invoke(target(thisValue, "call"), args[0], args.slice(1), site)], - [ - "apply", - 2, - (thisValue, args, site) => - withReads(() => new Invoke(target(thisValue, "apply"), args[0], listFromArrayLike(args[1]), site)), - ], - [ - "bind", - 1, - (thisValue, args) => - withReads(() => { - const fn = target(thisValue, "bind") - const name = get(fn, "name") - const length = get(fn, "length") - return new BoundFn( - ctx.builtins.Function, - fn, - args[0], - args.slice(1), - typeof name === "string" ? name : "", - typeof length === "number" && !Number.isNaN(length) - ? Math.max(0, Math.trunc(length) - Math.max(0, args.length - 1)) - : 0, - ) - }), - ], - ]) - // AddRestrictedFunctionProperties: strict functions have no caller or arguments of their own. - // Each half gets its own function: the intrinsics name a native accessor half by the function it wraps. - const restricted = (): never => { - throw typeError("'caller' and 'arguments' are restricted function properties and cannot be accessed in this context.") - } - for (const key of ["caller", "arguments"]) - defineAccessor(ctx.builtins.Function, key, () => restricted(), () => restricted()) - return constructor(ctx.builtins, ctx.builtins.Function, { - name: "Function", - length: 1, - call: reject, - construct: reject, - }) -} - -// CreateListFromArrayLike: `apply` reads `length` and the indexed properties of any object. -const listFromArrayLike = (value: Value): Array => { - if (value === undefined || value === null) return [] - if (value instanceof Arr) return [...value.items] - if (!(value instanceof Obj)) throw typeError("Function.prototype.apply expects an array-like argument list.") - const length = Math.max(0, coerceToInteger(get(value, "length"))) - checkArrayLength(length) - return Array.from({ length }, (_, index) => get(value, String(index))) -} - -const symbolGlobal = (ctx: Interpreter) => { - const symbol = native(ctx.builtins, { - name: "Symbol", - call: () => { - throw typeError("Symbol is not callable; only Symbol.asyncIterator and Symbol.iterator are available.") - }, - callback: false, - }) - constants(symbol, { asyncIterator: AsyncIteratorSymbol, iterator: IteratorSymbol }) - return symbol -} - -type Factory = (ctx: Interpreter) => Value - -// A table rather than a list so the names are known before any runtime exists. -const table: Record = { - require: (ctx) => - native(ctx.builtins, { - name: "require", - length: 1, - call: (_, args, site) => { - const specifier = args[0] - if (typeof specifier !== "string") throw typeError("require expects a module name string.") - return ctx.module(specifier, site) - }, - }), - undefined: () => undefined, - NaN: () => NaN, - Infinity: () => Infinity, - Object: (ctx) => objectGlobal(ctx), - Function: (ctx) => functionGlobal(ctx), - Array: (ctx) => arrayGlobal(ctx), - Math: (ctx) => mathGlobal(ctx), - JSON: (ctx) => jsonGlobal(ctx), - console: (ctx) => consoleGlobal(ctx), - Promise: (ctx) => promiseGlobal(ctx), - Symbol: (ctx) => symbolGlobal(ctx), - Iterator: (ctx) => iteratorGlobals(ctx), - Number: (ctx) => numberGlobal(ctx), - String: (ctx) => stringGlobal(ctx), - Boolean: (ctx) => booleanGlobal(ctx), - parseInt: (ctx) => coercion(ctx, "parseInt", 2), - parseFloat: (ctx) => coercion(ctx, "parseFloat"), - isFinite: (ctx) => coercion(ctx, "isFinite"), - isNaN: (ctx) => coercion(ctx, "isNaN"), - Date: (ctx) => dateGlobal(ctx), - RegExp: (ctx) => regexpGlobal(ctx), - Map: (ctx) => mapGlobal(ctx), - Set: (ctx) => setGlobal(ctx), - WeakMap: (ctx) => weakMapGlobal(ctx), - WeakSet: (ctx) => weakSetGlobal(ctx), - URL: (ctx) => urlGlobal(ctx), - URLSearchParams: (ctx) => urlSearchParamsGlobal(ctx), - Headers: (ctx) => headersGlobal(ctx), - Uint8Array: (ctx) => uint8ArrayGlobal(ctx), - // Built on the host's Buffer, so only where there is one (Node and Bun, not browsers). - ...(typeof Buffer === "undefined" ? {} : { Buffer: (ctx: Interpreter) => bufferGlobal(ctx) }), - TextEncoder: (ctx) => textEncoderGlobal(ctx), - TextDecoder: (ctx) => textDecoderGlobal(ctx), - encodeURI: (ctx) => uriGlobal(ctx, "encodeURI"), - encodeURIComponent: (ctx) => uriGlobal(ctx, "encodeURIComponent"), - decodeURI: (ctx) => uriGlobal(ctx, "decodeURI"), - decodeURIComponent: (ctx) => uriGlobal(ctx, "decodeURIComponent"), - atob: (ctx) => base64Global(ctx, "atob"), - btoa: (ctx) => base64Global(ctx, "btoa"), - crypto: (ctx) => cryptoGlobal(ctx), - structuredClone: (ctx) => structuredCloneGlobal(ctx), - ...Object.fromEntries(errorTypes.map((type) => [type, (ctx: Interpreter) => errorGlobal(type, ctx)])), -} - -/** Names bound in every program before extensions apply. */ -export const globalNames: ReadonlySet = new Set(Object.keys(table)) - -/** The immutable global bindings of every program, in declaration order. */ -export const globals = (ctx: Interpreter): ReadonlyArray => { - generatorGlobals(ctx) - return Object.entries(table).map(([name, factory]) => [name, factory(ctx)] as const) -} diff --git a/packages/codemode/src/language/runtime/interpreter.ts b/packages/codemode/src/language/runtime/interpreter.ts deleted file mode 100644 index bd7d9ec8531..00000000000 --- a/packages/codemode/src/language/runtime/interpreter.ts +++ /dev/null @@ -1,141 +0,0 @@ -import type { HostBridge } from "../snapshot/codec.js" -import { Vm } from "../vm.js" -import { globals } from "./globals.js" -import type { Builtins } from "./intrinsics.js" -import { IntrinsicNames } from "./intrinsic-names.js" -import { type AstNode, type Binding, PendingThrow } from "./model.js" -import { isRuntimeModule, moduleName, resolveModule } from "./modules.js" -import { define, type HostNamespace, keys, peek, makingIntrinsics, nativeRule, Obj, type Value } from "./objects.js" -import type { HostResult } from "../host.js" -import { Prelude } from "../prelude/prelude.js" -import type { NodeId, Source } from "./source.js" - -/** What a host namespace does, by the global it is under; see `HostNamespace`. */ -export type NamespaceHandler = { - /** The names directly under `path`, for `Object.keys` and `for...in`. */ - readonly keys: (path: ReadonlyArray) => ReadonlyArray - /** Calls the function at `path`. */ - readonly call: (path: ReadonlyArray, args: Array, site: AstNode | undefined) => HostResult -} - -/** One program execution: the VM that runs it, captured logs, and the global scope built once. */ -export class Interpreter { - readonly builtins: Builtins - readonly logs: Array - /** Runs program code, and keeps the job queue, promises, and host calls the program waits on. */ - readonly vm: Vm - /** Names for this runtime's intrinsics, taken before any program code can change a built-in. */ - readonly intrinsics: IntrinsicNames - /** The built-ins written in Code Mode, and the scope they close over. */ - readonly prelude: Prelude - /** How the program meets its host globals: calls, values crossing, and saving what they return; see `hostGlobals`. */ - hosts: HostBridge | undefined - /** The host namespaces among the globals, by the global they are under. */ - readonly hostNamespaces = new Map() - /** The parsed sources this execution runs, by id, so a `NodeId` resolves to its node. */ - readonly sources = new Map() - /** The global bindings: the intrinsics, the host's globals, and the program's bindings. */ - readonly globalScope: Map - private readonly modules = new Map() - private readonly moduleGlobals: Readonly> - private readonly namespaces = new Map() - - constructor(options: { - readonly builtins: Builtins - readonly logs?: Array - /** Module names that load a global, beyond its own name; see `Runtime.Options`. */ - readonly modules?: Readonly> | undefined - /** The host's globals (extensions, a test harness): made again, the same way, when a saved run is restored. */ - readonly globals?: (ctx: Interpreter) => ReadonlyArray - /** Data bound for this program, part of its saved state; host globals of the same name win. */ - readonly bindings?: (ctx: Interpreter) => ReadonlyArray - }) { - this.builtins = options.builtins - this.logs = options.logs ?? [] - this.moduleGlobals = options.modules ?? {} - // Program code has no receiver: top-level `this` is undefined, as in a module. - this.globalScope = new Map([["this", { value: undefined }]]) - // Everything made from here to the host globals is an intrinsic, with a static id (see `IntrinsicNames`). - const [[intrinsics, prelude], made] = makingIntrinsics(Object.values(this.builtins), this.builtins.Function, () => { - const intrinsics = globals(this) - return [intrinsics, new Prelude(this as Interpreter, intrinsics)] as const - }) - this.prelude = prelude - const hosts = options.globals?.(this) ?? [] - this.intrinsics = new IntrinsicNames( - made, - { - globals: intrinsics, - builtins: this.builtins, - internals: [ - ["Prelude", this.prelude.functions], - ["PreludeHelpers", this.prelude.helpers], - ], - }, - hosts, - ) - for (const [name, value] of [...intrinsics, ...(options.bindings?.(this) ?? []), ...hosts]) { - this.globalScope.set(name, { value }) - } - nativeRule.sealed.add(this.builtins.Function) - // The VM never runs host work itself, so it does not need the services that work runs with. - this.vm = new Vm(this as Interpreter) - } - - /** A module, as `require` returns it and a default import binds it: a global, by its Node module name. */ - module(specifier: string, site?: AstNode): Value { - const name = moduleName(specifier) - const cached = this.modules.get(name) - if (cached !== undefined) return cached - const module = resolveModule(name, (global) => this.globalScope.get(global)?.value, this.moduleGlobals) - if (module === undefined) throw new PendingThrow("Error", cannotImport(specifier), site) - this.modules.set(name, module) - return module - } - - /** - * What `import * as` and `import()` see: the module's own properties, and the module itself as `default`, the way - * Node presents a CommonJS module. - */ - namespace(specifier: string, site?: AstNode): Obj { - const module = this.module(specifier, site) - const name = moduleName(specifier) - const cached = this.namespaces.get(name) - if (cached) return cached - const namespace = new Obj(null) - // Data only: making a namespace runs no program getter. - if (module instanceof Obj) for (const key of keys(module)) define(namespace, key, peek(module, key)) - define(namespace, "default", module) - this.namespaces.set(name, namespace) - return namespace - } - - /** The names directly under a namespace path. */ - namespaceKeys(value: HostNamespace): ReadonlyArray { - return this.namespaceHandler(value).keys(value.path) - } - - /** Calls the function a namespace path names. */ - callNamespace(value: HostNamespace, args: Array, site: AstNode | undefined): HostResult { - return this.namespaceHandler(value).call(value.path, args, site) - } - - private namespaceHandler(value: HostNamespace): NamespaceHandler { - const handler = this.hostNamespaces.get(value.root) - if (handler === undefined) throw new PendingThrow("TypeError", `The namespace ${value.root} is not available.`) - return handler - } - - /** The node a `NodeId` names, in one of this execution's sources. */ - node(id: NodeId): AstNode | undefined { - return this.sources.get(id.source)?.node(id) - } -} - -/** Why `specifier` can't be loaded, split so the error names the kind of import that failed. */ -function cannotImport(specifier: string): string { - if (specifier.startsWith(".") || specifier.startsWith("/") || specifier.startsWith("file:")) - return `Cannot import "${specifier}": local files can't be imported.` - if (isRuntimeModule(specifier)) return `Cannot import "${specifier}": this runtime doesn't provide it.` - return `Cannot import "${specifier}": packages can't be installed here.` -} diff --git a/packages/codemode/src/language/runtime/intrinsic-names.ts b/packages/codemode/src/language/runtime/intrinsic-names.ts deleted file mode 100644 index ed1cfcd35f8..00000000000 --- a/packages/codemode/src/language/runtime/intrinsic-names.ts +++ /dev/null @@ -1,198 +0,0 @@ -import type { Builtins } from "./intrinsics.js" -import { AsyncIteratorSymbol, IteratorSymbol } from "./model.js" -import { accessorFunction, Arr, Fn, Native, Obj, type Value } from "./objects.js" - -/** - * Deterministic names for one runtime's intrinsic objects, so saved state can refer to a built-in by name instead of - * copying it, and whether each one changed since the runtime was made. - * - * - **Static ids.** Every object made with the intrinsics (`createBuiltins`, the globals, the prelude) has an id: its - * creation index, which is the same in every runtime because making them is deterministic (see `makingIntrinsics`). - * The ids are named once per process, by a breadth-first walk of the first runtime made, before any program runs: - * from the global names (`Array.prototype.map`), then `%Name%` for built-in prototypes the walk cannot reach - * (`%Generator%`) and the prelude's internals, and what is reachable from them. The first path found names a value. - * No later runtime walks anything. - * - **`@host` names.** The host's globals (extensions, a test harness) differ between runtimes, so each runtime names - * them itself, `@name`, by a walk over only the objects they reach that have no static id. Host lists are small. - * - **Dirty bits.** `Obj.intrinsic` is the id plus one while the object is as made, negated once it changes. Every - * write to an object's properties, prototype, extensibility or elements marks it (`changed` in objects.ts), and so - * does restoring it from a saved record, so a run suspended twice keeps what changed before the first suspend. - */ -export class IntrinsicNames { - private readonly hostValues: Array = [] - private readonly hostNames: Array = [] - private readonly hostIndex = new Map() - private named: Array | undefined - - constructor( - /** The objects made with the intrinsics, by id. */ - private readonly made: ReadonlyArray, - roots: Roots, - hosts: ReadonlyArray = [], - ) { - made.forEach((value, id) => { - value.intrinsic = id + 1 - }) - table ??= walk(made, roots) - if (made.length !== table.count) { - throw new Error(`This runtime made ${made.length} intrinsics, and the first one made ${table.count}.`) - } - const visit = (value: Value, name: () => string) => { - if (!(value instanceof Obj) || this.hostIndex.has(value) || this.isStatic(value)) return - this.hostIndex.set(value, this.hostValues.length) - this.hostValues.push(value) - this.hostNames.push(name()) - value.intrinsic = table!.count + this.hostValues.length - } - let next = 0 - for (const [name, value] of hosts) { - visit(value, () => `@${name}`) - for (; next < this.hostValues.length; next++) { - const item = this.hostValues[next]! - const base = this.hostNames[next]! - for (const [key, slot] of item.props) if ("value" in slot) visit(slot.value, () => member(base, key)) - if (item.proto !== null) visit(item.proto, () => member(base, prototypeKey)) - } - } - } - - /** The named intrinsics, in name order (see `all`). */ - get values(): ReadonlyArray { - return (this.named ??= [...table!.order.map((id) => this.made[id]!), ...this.hostValues]) - } - - /** The name of an intrinsic, or undefined for any other object. */ - nameOf(value: Obj): string | undefined { - if (this.isStatic(value)) { - const at = table!.position[Math.abs(value.intrinsic) - 1]! - return at < 0 ? undefined : table!.names[at] - } - const host = this.hostIndex.get(value) - return host === undefined ? undefined : this.hostNames[host] - } - - /** The intrinsic a name refers to. */ - valueOf(name: string): Obj | undefined { - const id = staticIds().get(name) - if (id !== undefined) return this.made[id] - const host = this.hostNames.indexOf(name) - return host < 0 ? undefined : this.hostValues[host] - } - - /** Every name: the static ones in walk order, then the host globals'. */ - all(): ReadonlyArray { - return [...table!.names, ...this.hostNames] - } - - /** The host globals' names, `@name`, in walk order. */ - hosts(): ReadonlyArray { - return this.hostNames - } - - /** - * The named intrinsics a saved state has to record: those changed since the runtime was made, and host values of - * classes whose state is not their properties (an extension's Map), which count as changed. - */ - changed(): Array { - return this.values.filter((value) => !unchanged(value)) - } - - private isStatic(value: Obj): boolean { - const id = Math.abs(value.intrinsic) - 1 - return id >= 0 && id < this.made.length && this.made[id] === value - } -} - -/** Whether a named object is still as the runtime made it, so its name alone restores it. */ -export const unchanged = (value: Obj): boolean => { - if (value.intrinsic <= 0) return false - const ctor = value.constructor - return ctor === Obj || ctor === Arr || ctor === Native || ctor === Fn -} - -/** The static names, in walk order, once a runtime has been made in this process. */ -export const staticNames = (): ReadonlyArray => { - if (table === undefined) throw new Error("No runtime has been made yet, so the intrinsics have no names.") - return table.names -} - -/** Where the walk that names the static intrinsics starts. */ -export type Roots = { - readonly globals: ReadonlyArray - readonly builtins: Builtins - /** Internal objects no global reaches (the prelude's functions and helpers), named like the builtins. */ - readonly internals: ReadonlyArray -} - -type Table = { - readonly count: number - /** Static ids in walk order, and their names. */ - readonly order: ReadonlyArray - readonly names: ReadonlyArray - /** By id: the position in `order`, or -1 for an object the walk does not reach. */ - readonly position: ReadonlyArray -} - -let table: Table | undefined -let ids: Map | undefined - -const staticIds = () => (ids ??= new Map(table!.names.map((name, at) => [name, table!.order[at]!]))) - -const walk = (made: ReadonlyArray, roots: Roots): Table => { - type Path = string | readonly [parent: number, key: string | symbol, half?: "get" | "set"] - const order: Array = [] - const paths: Array = [] - const position = made.map(() => -1) - const visit = (value: Value, path: Path) => { - if (!(value instanceof Obj)) return - const id = value.intrinsic - 1 - if (id < 0 || made[id] !== value) { - throw new Error(`The intrinsic at ${describe(path)} was not made with this runtime's intrinsics.`) - } - if (position[id] !== -1) return - position[id] = order.length - order.push(id) - paths.push(path) - } - const name = (base: string, path: Exclude) => - `${member(base, path[1])}${path[2] === undefined ? "" : path[2] === "get" ? "[[Get]]" : "[[Set]]"}` - const describe = (path: Path): string => (typeof path === "string" ? path : name(describe(paths[path[0]]!), path)) - let next = 0 - const drain = () => { - for (; next < order.length; next++) { - const item = made[order[next]!]! - for (const [key, slot] of item.props) { - if ("value" in slot) visit(slot.value, [next, key]) - else { - // A built-in accessor's halves are named by their companions: `Map.prototype.size[[Get]]`. - visit(accessorFunction(slot.get), [next, key, "get"]) - visit(accessorFunction(slot.set), [next, key, "set"]) - } - } - if (item.proto !== null) visit(item.proto, [next, prototypeKey]) - } - } - for (const [name, value] of roots.globals) visit(value, name) - drain() - for (const [name, value] of [...Object.entries(roots.builtins), ...roots.internals]) { - visit(value, `%${name}%`) - drain() - } - const names: Array = [] - for (const path of paths) names.push(typeof path === "string" ? path : name(names[path[0]]!, path)) - return { count: made.length, order, names, position } -} - -const prototypeKey: unique symbol = Symbol("[[Prototype]]") - -const symbolNames = new Map([ - [IteratorSymbol, "[Symbol.iterator]"], - [AsyncIteratorSymbol, "[Symbol.asyncIterator]"], - [prototypeKey, ".[[Prototype]]"], -]) - -/** How a program reads `key` from `base`: `base.key`, or `base["key"]` for a key that isn't a name. */ -export const member = (base: string, key: string | symbol): string => { - if (typeof key === "symbol") return `${base}${symbolNames.get(key) ?? `[${String(key)}]`}` - return /^[A-Za-z_$][\w$]*$/.test(key) ? `${base}.${key}` : `${base}[${JSON.stringify(key)}]` -} diff --git a/packages/codemode/src/language/runtime/intrinsics.ts b/packages/codemode/src/language/runtime/intrinsics.ts deleted file mode 100644 index 23f9b65024f..00000000000 --- a/packages/codemode/src/language/runtime/intrinsics.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { define, hidden, Native, Arr, ErrorObj, Obj, StackSlot, type Value } from "./objects.js" - -export const errorTypes = [ - "Error", - "TypeError", - "RangeError", - "SyntaxError", - "ReferenceError", - "EvalError", - "URIError", - "AggregateError", -] as const - -export type ErrorType = (typeof errorTypes)[number] - -export const isErrorType = (name: string): name is ErrorType => (errorTypes as ReadonlyArray).includes(name) - -const builtins = [ - "Object", - "Function", - "Array", - "String", - "Number", - "Boolean", - "Date", - "RegExp", - "Map", - "Set", - "WeakMap", - "WeakSet", - "URL", - "URLSearchParams", - "Headers", - "Uint8Array", - "Buffer", - "TextEncoder", - "TextDecoder", - "Promise", - "PromiseLike", - "Iterator", - "IteratorHelper", - "AsyncIterator", - "Generator", - "AsyncGenerator", - "AsyncFromSyncIterator", -] as const - -/** - * The built-in prototype objects of one runtime, allocated empty in dependency order. The globals populate them - * and attach their constructors when the runtime is built. - */ -export type Builtins = Readonly> - -/** A new error; its `stack` is `name: message` as of its first read, then `trace`, the ` at` lines where it was made. */ -export const createErrorValue = (prototype: Obj, message: string | undefined, trace = ""): ErrorObj => { - const value = new ErrorObj(prototype) - if (message !== undefined) define(value, "message", message, hidden) - value.props.set("stack", new StackSlot(value, trace)) - return value -} - -/** The prototype a primitive reads its methods from without being boxed; none for null, undefined, and symbols. */ -export const primitivePrototype = (builtins: Builtins, value: Value): Obj | undefined => { - if (typeof value === "string") return builtins.String - if (typeof value === "number") return builtins.Number - if (typeof value === "boolean") return builtins.Boolean - return undefined -} - -export const createBuiltins = (): Builtins => { - const object = new Obj(null) - // Function.prototype is itself callable and returns undefined. - const fn = new Native(object, { name: "", call: () => undefined }) - const plain = () => new Obj(object) - const error = plain() - define(error, "name", "Error", hidden) - define(error, "message", "", hidden) - const derived = (type: ErrorType) => { - const proto = new Obj(error) - define(proto, "name", type, hidden) - define(proto, "message", "", hidden) - return proto - } - const iterator = plain() - const asyncIterator = plain() - const uint8Array = plain() - return { - Object: object, - Function: fn, - Array: new Arr(object), - String: plain(), - Number: plain(), - Boolean: plain(), - Date: plain(), - RegExp: plain(), - Map: plain(), - Set: plain(), - WeakMap: plain(), - WeakSet: plain(), - URL: plain(), - URLSearchParams: plain(), - Headers: plain(), - Uint8Array: uint8Array, - /** Node's Buffer: a Uint8Array whose text conversions default to UTF-8. */ - Buffer: new Obj(uint8Array), - TextEncoder: plain(), - TextDecoder: plain(), - Promise: plain(), - /** What a synchronous result that can also be awaited inherits: then/catch/finally over a plain copy. */ - PromiseLike: plain(), - Iterator: iterator, - IteratorHelper: new Obj(iterator), - AsyncIterator: asyncIterator, - Generator: new Obj(iterator), - AsyncGenerator: new Obj(asyncIterator), - /** CreateAsyncFromSyncIterator's objects; programs never see them. */ - AsyncFromSyncIterator: new Obj(asyncIterator), - Error: error, - TypeError: derived("TypeError"), - RangeError: derived("RangeError"), - SyntaxError: derived("SyntaxError"), - ReferenceError: derived("ReferenceError"), - EvalError: derived("EvalError"), - URIError: derived("URIError"), - AggregateError: derived("AggregateError"), - } -} diff --git a/packages/codemode/src/language/runtime/limits.ts b/packages/codemode/src/language/runtime/limits.ts deleted file mode 100644 index 18bada5f301..00000000000 --- a/packages/codemode/src/language/runtime/limits.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { rangeError } from "./model.js" - -// The timeout only fires between interpreter steps, so a single built-in must not be able to materialize an -// unbounded value. These bound what one call may build; programs cannot reach such sizes any other way. - -/** Longest string a built-in or operator may produce. */ -export const MAX_STRING_LENGTH = 1 << 24 -/** Longest array a built-in may create or grow to. */ -export const MAX_ARRAY_LENGTH = 10_000_000 -/** Most promises that may be pending at once. */ -export const MAX_PENDING_PROMISES = 10_000 -/** Deepest nesting a value may have when it crosses to or from the host. */ -export const MAX_VALUE_DEPTH = 32 - -export const checkStringLength = (length: number): void => { - if (length > MAX_STRING_LENGTH) throw rangeError("Invalid string length") -} - -export const checkArrayLength = (length: number): void => { - if (length > MAX_ARRAY_LENGTH) throw rangeError("Invalid array length") -} diff --git a/packages/codemode/src/language/runtime/model.ts b/packages/codemode/src/language/runtime/model.ts deleted file mode 100644 index aeb8069801e..00000000000 --- a/packages/codemode/src/language/runtime/model.ts +++ /dev/null @@ -1,105 +0,0 @@ -import type { Node } from "acorn" -import type { ErrorType } from "./intrinsics.js" -import type { ErrorObj, Value } from "./objects.js" - -/** - * A diagnostic's category: one of the language's (`ParseError`, `UnsupportedSyntax`, `InvalidDataValue`, - * `TimeoutExceeded`, `ExecutionFailure`, `Truncated`), or one a host function gives with `Host.fail`. - */ -export type DiagnosticKind = string - -/** A program's failure or warning, as plain data. */ -export type Diagnostic = { - readonly kind: DiagnosticKind - readonly message: string - readonly location?: { readonly line: number; readonly column: number } - readonly suggestions?: ReadonlyArray -} - -/** Any parsed node; the compiler narrows on `type`, and diagnostics read `loc`. */ -export type AstNode = Node - -/** A global binding: globals are immutable per run, and top-level declarations are the program's own locals. */ -export type Binding = { readonly value: Value } - -export type GeneratorRequestKind = "next" | "return" | "throw" - -export const AsyncIteratorSymbol: unique symbol = Symbol("codemode.async-iterator") -export const IteratorSymbol: unique symbol = Symbol("codemode.iterator") - -export class Throw { - constructor(readonly value: Value) {} -} - -/** - * A failure raised by the interpreter or a built-in. It travels as a defect and becomes one program Error object - * the first time a handler observes it, so every observer of the same failure sees the same value. - */ -export class PendingThrow { - node?: AstNode - value?: ErrorObj - - constructor( - /** The JS error class a program sees when it catches this failure. */ - readonly type: ErrorType, - readonly message: string, - node?: AstNode, - readonly kind: DiagnosticKind = "ExecutionFailure", - readonly suggestions?: ReadonlyArray, - ) { - if (node) this.node = node - } -} - -/** - * A failure a host function raises with its own diagnostic `kind` and `suggestions` (see `Host.fail`). It reaches the - * program as an Error with its message, and a result as a diagnostic of its kind. - */ -export class HostFailure extends Error { - constructor( - readonly kind: DiagnosticKind, - message: string, - readonly suggestions: ReadonlyArray = [], - ) { - super(message) - } -} - -/** - * A host value a restored run cannot have back: a function an extension returned, or what a host function returned, - * which have no data form. Using it fails with `lostError`. - */ -export class Lost { - constructor(readonly description: string) {} -} - -/** What using a value lost to a suspend throws. */ -export const lostError = (description: string, node?: AstNode): PendingThrow => - new PendingThrow( - "TypeError", - `${description} came from the host and was lost when the run was suspended; get it again after resuming.`, - node, - ) - -const failure = (type: ErrorType, kind?: DiagnosticKind) => (message: string, node?: AstNode) => - new PendingThrow(type, message, node, kind) - -export const typeError = failure("TypeError") -export const invalidData = failure("TypeError", "InvalidDataValue") -export const rangeError = failure("RangeError") -export const referenceError = failure("ReferenceError") -export const syntaxError = failure("SyntaxError") -export const uriError = failure("URIError") - -// Orient the agent rather than enumerate JavaScript; interpreter-support.md is the full matrix. -export const supportedSyntaxMessage = - "This is a restricted JavaScript-like language. Supported: plain and async functions, data literals, destructuring, standard control flow, await and Promise, and built-ins such as Array, Object, Math, JSON, Date, RegExp, Map, Set, and URL. Unsupported: classes, BigInt, and custom Symbols. Use plain functions and data objects instead." - -// Acorn lines are 1-based and its columns are 0-based. Diagnostics use 1-based columns of the submitted source. -export const sourceLocation = (node: AstNode): { readonly line: number; readonly column: number } => ({ - line: node.loc?.start.line ?? 1, - column: (node.loc?.start.column ?? 0) + 1, -}) - -export const formatLocation = (location?: { readonly line: number; readonly column: number }): string => - location ? ` (line ${location.line}, col ${location.column})` : "" diff --git a/packages/codemode/src/language/runtime/modules.ts b/packages/codemode/src/language/runtime/modules.ts deleted file mode 100644 index a89fc75e774..00000000000 --- a/packages/codemode/src/language/runtime/modules.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { define, get, Obj, type Value } from "./objects.js" - -/** - * What `import` and `require` load: a global, by the Node module name that provides it. `fs` loads the `fs` global - * and `crypto` the `crypto` global; the names below come from globals with different names. A module that would be - * empty isn't available. - */ -const aliases: Record Value) => Value> = { - "fs/promises": (global) => { - const fs = global("fs") - return fs instanceof Obj ? get(fs, "promises") : undefined - }, - url: (global) => pick(global, ["URL", "URLSearchParams"]), - util: (global) => pick(global, ["TextEncoder", "TextDecoder"]), - buffer: (global) => pick(global, ["Buffer", "atob", "btoa"]), -} - -/** `node:fs` names the same module as `fs`. */ -export const moduleName = (specifier: string) => (specifier.startsWith("node:") ? specifier.slice(5) : specifier) - -// Node's core modules, fixed here so every host gives the same answer (Bun's `isBuiltin` also claims `ws` and `undici`). -const core = new Set( - "assert async_hooks buffer child_process cluster console constants crypto dgram diagnostics_channel dns domain events fs http http2 https inspector module net os path perf_hooks process punycode querystring readline repl stream string_decoder sys timers tls trace_events tty url util v8 vm wasi worker_threads zlib".split( - " ", - ), -) - -/** Whether a specifier names a module a runtime provides, as Node's and Bun's own modules are, rather than a package. */ -export const isRuntimeModule = (specifier: string) => - specifier.startsWith("node:") || - specifier === "bun" || - specifier.startsWith("bun:") || - core.has(specifier.split("/")[0]!) - -/** `hosted` names the global a host's own module names load (`{ bun: "Bun" }`). */ -export const resolveModule = ( - specifier: string, - global: (name: string) => Value, - hosted: Readonly> = {}, -): Value => { - const name = moduleName(specifier) - const named = Object.hasOwn(hosted, name) ? hosted[name] : undefined - return global(name) ?? (named === undefined ? undefined : global(named)) ?? aliases[name]?.(global) -} - -function pick(global: (name: string) => Value, names: ReadonlyArray): Value { - const found = names.flatMap((name) => { - const value = global(name) - return value === undefined ? [] : [[name, value] as const] - }) - if (found.length === 0) return undefined - const module = new Obj(null) - for (const [name, value] of found) define(module, name, value) - return module -} diff --git a/packages/codemode/src/language/runtime/native.ts b/packages/codemode/src/language/runtime/native.ts deleted file mode 100644 index 421405c10c1..00000000000 --- a/packages/codemode/src/language/runtime/native.ts +++ /dev/null @@ -1,74 +0,0 @@ -import type { Builtins } from "./intrinsics.js" -import { typeError } from "./model.js" -import { - type Callable, - define, - frozen, - hidden, - Native, - type NativeCall, - type NativeOptions, - Obj, - positionIterator, - type PositionSource, - type Value, -} from "./objects.js" -import { describeValue } from "./references.js" - -/** A native function body: a value, a thrown `PendingThrow`, or what the VM carries out as the call. */ -export type Impl = NativeCall - -export const native = (builtins: Builtins, options: NativeOptions): Native => new Native(builtins.Function, options) - -export const fn = (builtins: Builtins, name: string, length: number, impl: Impl): Native => - native(builtins, { name, length, call: impl }) - -export type Method = readonly [name: string, length: number, impl: Impl] - -export const methods = (builtins: Builtins, target: Obj, table: ReadonlyArray): void => { - for (const [name, length, impl] of table) define(target, name, fn(builtins, name, length, impl), hidden) -} - -/** `keys`, `values`, and `entries`: built-in iterators over the receiver `self` checks. */ -export const iteratorMethods = ( - builtins: Builtins, - self: (thisValue: Value, name: string) => PositionSource, -): Array => - (["keys", "values", "entries"] as const).map((kind) => [ - kind, - 0, - (thisValue) => positionIterator(builtins, self(thisValue, kind), kind), - ]) - -export const constants = (target: Obj, table: Record): void => { - for (const [name, value] of Object.entries(table)) define(target, name, value, frozen) -} - -/** A constructor wired to its prototype: `C.prototype === proto` and `proto.constructor === C`. */ -export const constructor = (builtins: Builtins, proto: Obj, options: NativeOptions): Native => { - const ctor = native(builtins, options) - define(ctor, "prototype", proto, frozen) - define(proto, "constructor", ctor, hidden) - return ctor -} - -/** The `call` of a constructor that JS requires to be invoked with `new`. */ -export const requiresNew = (name: string) => (): never => { - throw typeError(`Constructor ${name} requires 'new'.`) -} - -/** The instance prototype for `new` via `newTarget.prototype`, falling back to the built-in's own. */ -export const prototypeFrom = (newTarget: Callable, fallback: Obj): Obj => { - const proto = newTarget.props.get("prototype") - return proto !== undefined && "value" in proto && proto.value instanceof Obj ? proto.value : fallback -} - -/** Narrows a method receiver to the built-in it belongs to, or throws the TypeError JS would. */ -export const receiver = ( - cls: abstract new (...args: never) => T, - thisValue: Value, - method: string, -): T => { - if (thisValue instanceof cls) return thisValue - throw typeError(`${method} called on incompatible receiver ${describeValue(thisValue)}.`) -} diff --git a/packages/codemode/src/language/runtime/objects.ts b/packages/codemode/src/language/runtime/objects.ts deleted file mode 100644 index 57b3f683808..00000000000 --- a/packages/codemode/src/language/runtime/objects.ts +++ /dev/null @@ -1,1399 +0,0 @@ -import type { Builtins } from "./intrinsics.js" -import { checkArrayLength } from "./limits.js" -import { - type AstNode, - AsyncIteratorSymbol, - IteratorSymbol, - type PendingThrow, - rangeError, - Throw, - typeError, -} from "./model.js" -import { type Convert, type GeneratorRequest, Invoke, type Prefetch, type Push, type Resume } from "./signals.js" -import type { Code } from "../code.js" -import { type Cell, CodeFlags } from "../opcodes.js" -import type { Reaction, Resolving } from "../scheduler.js" -import type { Frame } from "../vm.js" -import { OrderedTable, type TableCursor } from "./table.js" - -/** Property attributes, as in a JS property descriptor. */ -export type Attributes = { - readonly writable: boolean - readonly enumerable: boolean - readonly configurable: boolean -} - -export type Getter = (receiver: Value) => Value -export type Setter = (receiver: Value, value: Value) => void - -/** - * One own property: a data slot, or an accessor whose halves are each a native closure (`typeof half === "function"`) - * or a program function (a `Callable`, which is never a JS function). - */ -export type Slot = - | { value: Value; writable: boolean; enumerable: boolean; configurable: boolean } - | { - get: Getter | Callable | undefined - set: Setter | Callable | undefined - enumerable: boolean - configurable: boolean - } -export type AccessorSlot = Extract - -/** Whether an accessor half is a program function, which only program code can call. */ -export const isProgramHalf = (half: unknown): half is Callable => half !== undefined && typeof half !== "function" - -/** Whether a slot is an accessor with at least one program half. */ -export const isProgramAccessor = (slot: Slot): slot is AccessorSlot => - !("value" in slot) && (isProgramHalf(slot.get) || isProgramHalf(slot.set)) - -/** Whether a slot is an accessor with no getter, which reads as undefined and never crosses to the host. */ -const isSetterOnly = (slot: Slot): boolean => !("value" in slot) && slot.get === undefined - -// The objects made while a runtime's intrinsics are being made, in creation order; see `makingIntrinsics`. -let making: Array | undefined -// The `Function.prototype` of the intrinsics being made, for the companions of native accessors. -let makingFunctions: Obj | undefined - -/** - * The program function that stands for each native accessor half (`Object.getOwnPropertyDescriptor(Map.prototype, - * "size").get`), made with the intrinsics so it is named like one, and the half each one stands for. - */ -const companions = new WeakMap() -const companionHalves = new WeakMap() - -/** The function a program sees for an accessor half: the program function, or a native half's companion. */ -export const accessorFunction = (half: Getter | Setter | Callable | undefined): Callable | undefined => - half === undefined || isProgramHalf(half) ? half : companions.get(half) - -/** The half to store for a function a program gives: a companion's native closure, so reads stay on the native path. */ -export const accessorHalf = (fn: Callable | undefined): Getter | Setter | Callable | undefined => - fn instanceof Native ? (companionHalves.get(fn) ?? fn) : fn - -/** - * Runs `make`, which makes a runtime's intrinsics, and returns every object made meanwhile, in creation order, after - * `first` (the built-in prototypes, made before). An object's index in the list is its static intrinsic id. - */ -export const makingIntrinsics = ( - first: ReadonlyArray, - functions: Obj, - make: () => A, -): readonly [A, Array] => { - const made = [...first] - making = made - makingFunctions = functions - try { - return [make(), made] - } finally { - making = undefined - makingFunctions = undefined - } -} - -/** Marks an intrinsic as changed by the program, so saving a run records it; any other object is left alone. */ -export const changed = (target: Obj): void => { - if (target.intrinsic > 0) target.intrinsic = -target.intrinsic -} - -/** Ordinary assignment: writable, enumerable, configurable. */ -export const data: Attributes = { writable: true, enumerable: true, configurable: true } -/** Built-in methods and `constructor`: writable and configurable but hidden from enumeration. */ -export const hidden: Attributes = { writable: true, enumerable: false, configurable: true } -/** Function `name` and `length`: read-only but deletable. */ -export const readonly: Attributes = { writable: false, enumerable: false, configurable: true } -/** Constants such as `Math.PI` and a constructor's `prototype`. */ -export const frozen: Attributes = { writable: false, enumerable: false, configurable: false } - -/** What a child converted by `toHost` gives to be left out: an object's key is skipped, an array's item is `null`. */ -export const OMITTED: unique symbol = Symbol("omitted") - -/** - * An object owned by the program: own properties plus a prototype link. Subclasses answer, in one place, how a - * built-in kind of object prints, coerces, iterates, and crosses to the host. - */ -export class Obj { - readonly props = new Map() - /** [[Extensible]]: cleared by `Object.preventExtensions`, `seal`, and `freeze`. */ - extensible = true - /** - * 0 for an object the program made. For an intrinsic, its id plus one while it is as the runtime made it, negated - * once it changes (see `changed` and `IntrinsicNames`). - */ - intrinsic = 0 - /** Whether a program accessor was ever defined here: the bulk readers' cue to take their slow paths. */ - hasProgramAccessors = false - constructor(public proto: Obj | null) { - if (making !== undefined) making.push(this) - } - - /** The class name `Object.prototype.toString` reports: `[object Map]`. */ - readonly tag: string = "Object" - - /** How diagnostics refer to a value of this kind. */ - get describe(): string { - if (this.tag === "Object") return "a data object" - return `${/^[AEIO]/.test(this.tag) ? "an" : "a"} ${this.tag}` - } - - /** ToString without consulting program-defined methods. */ - toString(): string { - return `[object ${this.tag}]` - } - - /** ToPrimitive without consulting program-defined methods: only a Date answers a number hint differently. */ - toPrimitive(hint: "default" | "number" | "string"): string | number { - return this.toString() - } - - /** ToNumber without consulting program-defined methods. */ - toNumber(): number { - return Number(this.toPrimitive("number")) - } - - /** How `console.log` shows the value; `item` formats a child with cycle and depth tracking. */ - inspect(item: (value: Value) => string): string { - const shown = this.inspectBody(item) - const name = instanceClassName(this) - return name === undefined ? shown : `${name} ${shown}` - } - - private inspectBody(item: (value: Value) => string): string { - if (!this.hasProgramAccessors) { - return `{${entries(this) - .map(([key, value]) => `${JSON.stringify(key)}:${item(value)}`) - .join(",")}}` - } - // Showing a value never runs program code, so a program accessor shows what it is, as Node does. - return `{${keys(this) - .map((key) => { - const slot = own(this, key)! - return `${JSON.stringify(key)}:${isProgramAccessor(slot) ? accessorLabel(slot) : item(getOwn(this, key))}` - }) - .join(",")}}` - } - - /** A copy the host can hold; `item` converts a child. A `__proto__` key never reaches host code. */ - toHost(item: (value: Value) => unknown): unknown { - if (!this.hasProgramAccessors) { - return Object.fromEntries( - entries(this).flatMap(([key, value]) => { - if (key === "__proto__") return [] - // A setter-only native accessor reads as undefined; it is left out like a program one. - if (value === undefined && isSetterOnly(own(this, key)!)) return [] - const copied = item(value) - return copied === OMITTED ? [] : [[key, copied]] - }), - ) - } - // A getter's value crosses as data (read ahead by the call; see `HostCalls`), and a setter-only property is left out. - return Object.fromEntries( - keys(this).flatMap((key) => { - const slot = own(this, key)! - if (key === "__proto__" || isSetterOnly(slot)) return [] - const copied = item(getOwn(this, key)) - return copied === OMITTED ? [] : [[key, copied]] - }), - ) - } - - /** The built-in iteration `for...of` and spread use, when this kind of object has one. */ - iterator(builtins: Builtins): Cursor | undefined { - return undefined - } -} - -export class Arr extends Obj { - override readonly tag = "Array" - /** The attributes every live element shares; `seal` and `freeze` narrow them since elements have no slots. */ - elements: Attributes = data - constructor( - proto: Obj, - readonly items: Array = [], - ) { - super(proto) - } - override get describe() { - return "an array" - } - override toString() { - return this.items.map((item) => (item === null || item === undefined ? "" : coerceToString(item))).join(",") - } - override inspect(item: (value: Value) => string) { - return `[${this.items.map(item).join(",")}]` - } - override toHost(item: (value: Value) => unknown) { - return this.items.map((value) => { - const copied = item(value) - return copied === OMITTED ? null : copied - }) - } - override iterator(builtins: Builtins) { - return new Position(this, "values", builtins.Array) - } -} - -/** An object with the [[ErrorData]] slot: what `Error.prototype.toString` and the host boundary recognize as an error. */ -export class ErrorObj extends Obj { - override readonly tag = "Error" - /** - * The interpreter failure this error materialized from, so rethrowing it keeps the diagnostic kind and location. It - * is plain data (type, message, kind, suggestions, and the node it is located at), shared with the failure so a - * location attached later is seen here too. - */ - failure?: PendingThrow - /** Error.prototype.toString: "name: message", or just one when the other is empty. */ - override toString() { - const name = peek(this, "name") - const message = peek(this, "message") - const shownName = typeof name === "string" ? name : "Error" - const shownMessage = typeof message === "string" ? message : "" - if (shownMessage === "") return shownName - if (shownName === "") return shownMessage - return `${shownName}: ${shownMessage}` - } - override inspect() { - return this.toString() - } -} - -/** Error.prototype.toString: `name: message`, omitting whichever side is empty. */ -export const errorToString = (self: Obj, read: (target: Obj, key: string) => Value = peek): string => { - const name = read(self, "name") - const message = read(self, "message") - const shownName = name === undefined ? "Error" : coerceToString(name) - const shownMessage = message === undefined ? "" : coerceToString(message) - if (shownMessage === "") return shownName - if (shownName === "") return shownMessage - return `${shownName}: ${shownMessage}` -} - -/** - * An error's own `stack` slot, a data property to every reader. Its ` at` lines are fixed when the error is made, - * and its `name: message` header when `value` is first read (a copy of the slot reads it too), as V8 formats on first - * access: a subclass constructor that sets `this.name` is in the header. The header reads `name` and `message` as - * display does, so a program getter there runs no code and reads as undefined. - */ -export class StackSlot { - writable = true - enumerable = false - configurable = true - declare value: Value - #trace: string | undefined - constructor(error: ErrorObj, trace: string) { - this.#trace = trace - let text: Value - // An own enumerable accessor, so a copy of the slot (`{ ...slot }`) reads it. - Object.defineProperty(this, "value", { - get: () => { - if (this.#trace !== undefined) { - text = errorToString(error) + this.#trace - this.#trace = undefined - } - return text - }, - set: (value: Value) => { - this.#trace = undefined - text = value - }, - enumerable: true, - }) - } - /** The ` at` lines while the header is not formatted yet; `undefined` once `value` is fixed. */ - get trace(): string | undefined { - return this.#trace - } -} - -/** Interpreter machinery a program can hold but never inspect, serialize, or hand to the host. */ -export abstract class Opaque extends Obj { - override inspect() { - return "[opaque reference]" - } -} - -export abstract class Callable extends Opaque { - override readonly tag = "Function" - constructor( - proto: Obj, - name: string, - readonly length: number, - ) { - super(proto) - define(this, "length", length, readonly) - define(this, "name", name, readonly) - } - override get describe() { - return "a function" - } -} - -/** A program or prelude function: its bytecode, and the cells of the bindings it captured. */ -export class Fn extends Callable { - constructor( - proto: Obj, - readonly code: Code, - readonly cells: ReadonlyArray, - name = code.name, - ) { - super(proto, name, code.length) - } - /** [[HomeObject]]: the prototype or constructor a class method was defined on. */ - home: Obj | undefined = undefined - /** Set on class constructors only. */ - klass: ClassInfo | undefined = undefined - get generator(): boolean { - return (this.code.flags & CodeFlags.GENERATOR) !== 0 - } - override inspect() { - if (this.klass === undefined) return super.inspect() - const name = ownName(this) || "(anonymous)" - const parent = this.klass.derived && this.proto instanceof Callable ? ownName(this.proto) : "" - return parent === "" ? `[class ${name}]` : `[class ${name} extends ${parent}]` - } -} - -const ownName = (target: Obj): string => { - const slot = own(target, "name") - return slot !== undefined && "value" in slot && typeof slot.value === "string" ? slot.value : "" -} - -/** The class an instance was made by, read from its prototype's own `constructor` without running program code. */ -const instanceClassName = (target: Obj): string | undefined => { - if (target.proto === null) return undefined - const slot = own(target.proto, "constructor") - if (slot === undefined || !("value" in slot) || !(slot.value instanceof Fn) || slot.value.klass === undefined) return undefined - return ownName(slot.value) || undefined -} - -/** What a class constructor knows about its class. */ -export class ClassInfo { - constructor( - readonly derived: boolean, - public fields: Fn | undefined = undefined, - readonly errorBase: Callable | undefined = undefined, - ) {} -} - -/** The strict `arguments` object: an ordinary object with indexed own properties and a hidden `length`. */ -export class Arguments extends Obj { - override readonly tag = "Arguments" - constructor(proto: Obj, args: Array) { - super(proto) - args.forEach((arg, index) => define(this, String(index), arg)) - define(this, "length", args.length, hidden) - } - override iterator(builtins: Builtins) { - // With program accessors, its own `[Symbol.iterator]` (the prelude's `argumentsValues`) reads it in program code. - if (this.hasProgramAccessors) return undefined - return new Position( - keys(this).map((key) => get(this, key)), - "values", - builtins.Array, - ) - } -} - -/** - * A native function body: a value, or what the VM carries out as the call: work it hands over by name (`Push`), a - * suspended generator to continue (`Resume`), a call it hands on (`Invoke`), or conversions to run before it runs again - * (`Convert`). A native never runs program code itself. - */ -export type NativeResult = Value | Push | Resume | Invoke | Convert | Prefetch -/** `site` is the call running the built-in, where a failure it reports later (a rejection) is located. */ -export type NativeCall = (thisValue: Value, args: Array, site: AstNode | undefined) => NativeResult -export type NativeConstruct = (args: Array, newTarget: Callable, site: AstNode | undefined) => NativeResult - -export type NativeOptions = { - /** - * Why this native may be made while the program runs, for the few kinds that still capture state in a host closure. - * Every other native is made with the intrinsics; see `nativeRule`. - */ - readonly runtime?: RuntimeNative - readonly name: string - readonly length?: number - readonly call: NativeCall - /** `new name(...)`; without it the function is not a constructor. */ - readonly construct?: NativeConstruct - /** Whether callback sites (array methods, replacers, promise reactions) admit this function. Defaults to true. */ - readonly callback?: boolean -} - -/** The natives still made at run time, each holding state in a host closure that cannot be saved yet. */ -export type RuntimeNative = "host" - -/** - * Natives are made only with the intrinsics, so each one has an intrinsic name and run state never holds a host - * closure. When `check` is on (tests turn it on), making a native for a runtime whose intrinsics are `sealed` (keyed by - * its `Function.prototype`) throws, unless it declares one of the `RuntimeNative` exceptions. - */ -export const nativeRule: { check: boolean; sealed: WeakSet; observe?: (native: Native) => void } = { - check: false, - sealed: new WeakSet(), -} - -/** - * A built-in function: a `Native` made with the intrinsics, or a data kind such as `BoundFn` or `Resolver` whose state - * is plain fields and whose behaviour lives on its class. - */ -export abstract class Builtin extends Callable { - /** `new name(...)`; without it the function is not a constructor. */ - abstract readonly construct: NativeConstruct | undefined - /** Whether callback sites (array methods, replacers, promise reactions) admit this function. */ - abstract readonly callback: boolean - abstract invoke(thisValue: Value, args: Array, site: AstNode | undefined): NativeResult -} - -export class Native extends Builtin { - readonly call: NativeCall - readonly construct: NativeConstruct | undefined - readonly callback: boolean - - constructor(proto: Obj, options: NativeOptions) { - if (nativeRule.check && options.runtime === undefined && nativeRule.sealed.has(proto)) { - throw new Error(`Native "${options.name}" was made after the intrinsics; make it a data kind instead.`) - } - super(proto, options.name, options.length ?? 0) - nativeRule.observe?.(this) - this.call = options.call - this.construct = options.construct - this.callback = options.callback ?? true - } - - invoke(thisValue: Value, args: Array, site: AstNode | undefined): NativeResult { - return this.call(thisValue, args, site) - } -} - -/** `Function.prototype.bind`'s result: calls `target` with the bound receiver and leading arguments. */ -export class BoundFn extends Builtin { - readonly construct = undefined - readonly callback = true - constructor( - proto: Obj, - readonly target: Callable, - readonly boundThis: Value, - readonly boundArgs: ReadonlyArray, - name: string, - length: number, - ) { - super(proto, `bound ${name}`, length) - } - - invoke(_: Value, args: Array, site: AstNode | undefined): NativeResult { - return new Invoke(this.target, this.boundThis, [...this.boundArgs, ...args], site) - } -} - -/** A `resolve` or `reject` function handed to an executor or thenable: settles its shared `Resolving` once. */ -export class Resolver extends Builtin { - readonly construct = undefined - readonly callback = true - constructor( - proto: Obj, - name: string, - readonly resolving: Resolving, - readonly kind: "resolve" | "reject", - ) { - super(proto, name, 1) - } - - invoke(_: Value, args: Array): NativeResult { - if (this.kind === "resolve") this.resolving.resolve(args[0]) - else this.resolving.reject(new Throw(args[0])) - return undefined - } -} - -export class PromiseObj extends Opaque { - override readonly tag = "Promise" - state: "pending" | "fulfilled" | "rejected" = "pending" - /** The value, or the failure as thrown; a handler receives it materialized. */ - result: unknown = undefined - reactions: Array = [] - /** [[PromiseIsHandled]]: a reaction was attached, so a rejection is not reported as unhandled. */ - handled = false - constructor( - proto: Obj, - /** Creation order, for reporting unhandled rejections in the order their promises were made. */ - readonly id: number, - ) { - super(proto) - } - override get describe() { - return "an un-awaited Promise" - } - override inspect() { - return "[Promise (await it to get its value)]" - } -} - -export type GeneratorState = - | "suspendedStart" - | "suspendedYield" - | "executing" - | "awaiting-return" - | "draining" - | "completed" - -export class GeneratorObj extends Opaque { - override readonly tag = "Generator" - state: GeneratorState = "suspendedStart" - /** The suspended body's frame, kept while it waits for the next request, which puts it back on the job stack. */ - frame: Frame | undefined = undefined - /** An async generator's requests, oldest first, each with what settles its promise. */ - readonly queue: Array<{ readonly request: GeneratorRequest; readonly resolving: Resolving }> = [] - constructor( - proto: Obj, - readonly asynchronous: boolean, - ) { - super(proto) - } - override get describe() { - return "a generator" - } -} - -/** One pull from an iterator, as `for...of` sees it. */ -export type Step = { readonly done: boolean; readonly value: Value } - -/** - * An iterator the interpreter drives, as data: a built-in cursor over a collection (`Position`), or a program - * iterator driven by its own `next` method (`CustomIterator`). - */ -export type Cursor = Position | CustomIterator - -/** A program iterator record: the iterator, its `next` method, and whether its results are awaited. */ -export type CustomIterator = { - readonly iterator: Obj - readonly next: Value - readonly asynchronous: boolean -} - -const finished: Step = { done: true, value: undefined } - -/** What a built-in iterator yields for each entry: `keys()`, `values()`, or `entries()`. */ -export type IterationKind = "keys" | "values" | "entries" - -/** What a built-in iterator walks: a collection, a string, or a fixed list of values. */ -export type PositionSource = - | Arr - | Bytes - | MapObj - | SetObj - | HeadersObj - | URLSearchParamsObj - | string - | ReadonlyArray - -/** - * A built-in iterator's place in its source, as data: what it walks, what it yields, and the next index. Iteration is - * live, as in JS: an array iterator reads the length on every step, and a Map or Set iterator is kept in place by its - * table. Once done it stays done. There is nothing to close. - */ -export class Position implements TableCursor { - index = 0 - done = false - constructor( - readonly source: PositionSource, - readonly kind: IterationKind, - /** The prototype of the `[key, value]` arrays `entries()` yields. */ - readonly arrays: Obj, - ) { - if (source instanceof MapObj) source.map.track(this) - if (source instanceof SetObj) source.set.track(this) - } - - step(): Step { - if (this.done) return finished - const source = this.source - if (typeof source === "string") { - if (this.index >= source.length) return this.finish() - const point = source.codePointAt(this.index)! - const value = source.slice(this.index, this.index + (point > 0xffff ? 2 : 1)) - this.index += value.length - return { done: false, value } - } - if (source instanceof MapObj || source instanceof SetObj) { - const table = source instanceof MapObj ? source.map : source.set - const at = table.advance(this) - if (at < 0) return finished - const key = table.keys[at] as Value - return this.yield(key, source instanceof MapObj ? table.values[at] : key) - } - if (source instanceof HeadersObj || source instanceof URLSearchParamsObj) { - // The host recomputes the sorted list on every step, as the spec's pair iterators do. - const list = Array.from(source instanceof HeadersObj ? source.headers.entries() : source.params.entries()) - const entry = list[this.index] - if (entry === undefined) return this.finish() - this.index++ - return this.yield(entry[0], entry[1]) - } - const items = source instanceof Arr ? source.items : source instanceof Bytes ? source.bytes : source - if (this.index >= items.length) return this.finish() - const at = this.index++ - return this.yield(at, items[at]) - } - - private yield(key: Value, value: Value): Step { - if (this.kind === "keys") return { done: false, value: key } - if (this.kind === "values") return { done: false, value } - return { done: false, value: new Arr(this.arrays, [key, value]) } - } - - private finish(): Step { - this.done = true - return finished - } -} - -/** A built-in iterator: a live cursor over a host collection or an iterator helper, yielding program values. */ -export class IteratorObj extends Opaque { - override readonly tag = "Iterator" - constructor( - proto: Obj, - readonly cursor: Cursor, - ) { - super(proto) - } - override get describe() { - return "an iterator" - } -} - -/** A built-in iterator over a collection, e.g. `array.values()`. */ -export const positionIterator = (builtins: Builtins, source: PositionSource, kind: IterationKind): IteratorObj => - new IteratorObj(builtins.Iterator, new Position(source, kind, builtins.Array)) - -/** A built-in object around a host value: data-like, so it prints as itself and crosses to extensions as a copy. */ -export abstract class Wrapper extends Obj { - override inspect(item: (value: Value) => string) { - return this.toString() - } -} - -export class DateObj extends Wrapper { - override readonly tag = "Date" - constructor( - proto: Obj, - public time: number, - ) { - super(proto) - } - override toString() { - return Number.isFinite(this.time) ? new Date(this.time).toISOString() : "Invalid Date" - } - override toPrimitive(hint: "default" | "number" | "string") { - return hint === "number" ? this.time : this.toString() - } - override toHost() { - return new Date(this.time) - } -} - -/** A RegExp as data: its source, flags, and `lastIndex`; the host regex is only a compiled cache of the first two. */ -export class RegExpObj extends Wrapper { - override readonly tag = "RegExp" - readonly source: string - readonly flags: string - /** Shared by `exec`/`test` and the String methods, as the host regex's own `lastIndex` would be. */ - lastIndex = 0 - private compiled: RegExp | undefined - constructor(proto: Obj, pattern: string, flags: string) { - super(proto) - // Compiling validates the pattern and flags, and normalizes both as the host spells them. - this.compiled = new RegExp(pattern, flags) - this.source = this.compiled.source - this.flags = this.compiled.flags - } - /** The compiled regex, for reading what it is; anything that matches goes through `use`. */ - get regex(): RegExp { - this.compiled ??= new RegExp(this.source, this.flags) - return this.compiled - } - /** Runs host regex work starting from this object's `lastIndex`, and keeps the `lastIndex` the work leaves. */ - use(work: (regex: RegExp) => T): T { - const regex = this.regex - regex.lastIndex = this.lastIndex - try { - return work(regex) - } finally { - this.lastIndex = regex.lastIndex - } - } - override toString() { - return `/${this.source}/${this.flags}` - } - override toHost() { - return new RegExp(this.source, this.flags) - } -} - -export class MapObj extends Wrapper { - override readonly tag = "Map" - readonly map = new OrderedTable() - override inspect(item: (value: Value) => string) { - return `Map(${this.map.size}) [${[...this.map].map(([key, value]) => `[${item(key)},${item(value)}]`).join(",")}]` - } - override toHost(item: (value: Value) => unknown) { - return new Map([...this.map].map(([key, value]) => [item(key), item(value)])) - } - override iterator(builtins: Builtins) { - return new Position(this, "entries", builtins.Array) - } -} - -export class SetObj extends Wrapper { - override readonly tag = "Set" - readonly set = new OrderedTable() - override inspect(item: (value: Value) => string) { - return `Set(${this.set.size}) [${[...this.set.liveKeys()].map(item).join(",")}]` - } - override toHost(item: (value: Value) => unknown) { - return new Set([...this.set.liveKeys()].map(item)) - } - override iterator(builtins: Builtins) { - return new Position(this, "values", builtins.Array) - } -} - -/** - * Keys are held strongly for the run, which is short-lived; garbage collection is not observable in Code Mode, and a - * plain table keeps the state as data. - */ -export class WeakMapObj extends Wrapper { - override readonly tag = "WeakMap" - readonly map = new Map() - override inspect() { - return "WeakMap { }" - } -} - -export class WeakSetObj extends Wrapper { - override readonly tag = "WeakSet" - readonly set = new Set() - override inspect() { - return "WeakSet { }" - } -} - -export class URLSearchParamsObj extends Wrapper { - override readonly tag = "URLSearchParams" - constructor( - proto: Obj, - readonly params: URLSearchParams, - ) { - super(proto) - } - override toString() { - return this.params.toString() - } - override toHost() { - return new URLSearchParams(this.params) - } - override iterator(builtins: Builtins) { - return new Position(this, "entries", builtins.Array) - } -} - -export class HeadersObj extends Wrapper { - override readonly tag = "Headers" - constructor( - proto: Obj, - readonly headers: Headers, - ) { - super(proto) - } - override inspect() { - return `Headers ${JSON.stringify(Object.fromEntries(this.headers))}` - } - override toHost() { - return new Headers(this.headers) - } - override iterator(builtins: Builtins) { - return new Position(this, "entries", builtins.Array) - } -} - -export class URLObj extends Wrapper { - override readonly tag = "URL" - readonly searchParams: URLSearchParamsObj - constructor( - proto: Obj, - searchParamsProto: Obj, - readonly url: URL, - ) { - super(proto) - this.searchParams = new URLSearchParamsObj(searchParamsProto, url.searchParams) - } - override toString() { - return this.url.href - } - override toHost() { - return new URL(this.url.href) - } -} - -/** A `Uint8Array`: the host array does the byte clamping and ignores out-of-range writes, as JS does. */ -export class Bytes extends Wrapper { - override readonly tag = "Uint8Array" - constructor( - proto: Obj, - readonly bytes: Uint8Array, - ) { - super(proto) - } - override toString() { - return this.bytes.join(",") - } - override inspect() { - return `Uint8Array(${this.bytes.length}) [${this.bytes.join(",")}]` - } - override toHost() { - return new Uint8Array(this.bytes) - } - override iterator(builtins: Builtins) { - return new Position(this, "values", builtins.Array) - } - /** New bytes of this one's kind, as `slice`, `subarray`, `map` and `filter` make them (a Buffer's are a Buffer). */ - derive(builtins: Builtins, bytes: Uint8Array): Bytes { - return new Bytes(builtins.Uint8Array, bytes) - } -} - -/** - * A path into a host namespace (see `Host.namespace`): the global it is under, `root`, and the property names read - * from it. Reading a property makes a longer path, and calling one asks the namespace for the function there. It is not - * an `Obj`, so no object operation reaches it by accident; the few that apply ask it explicitly. - */ -export class HostNamespace { - constructor( - readonly root: string, - readonly path: ReadonlyArray, - ) {} -} - -/** Every value a program can hold. Host values never appear here; they are copied in at the boundaries. */ -export type Value = string | number | boolean | null | undefined | symbol | Obj | HostNamespace - -/** ToString without consulting program-defined methods. */ -export const coerceToString = (value: Value): string => (value instanceof Obj ? value.toString() : String(value)) - -/** ToNumber without consulting program-defined methods; namespace paths are not numbers. */ -export const coerceToNumber = (value: Value): number => { - if (value instanceof Obj) return value.toNumber() - return value instanceof HostNamespace ? Number.NaN : Number(value) -} - -/** ToIntegerOrInfinity: NaN is 0, fractions truncate. */ -export const coerceToInteger = (value: Value): number => { - const number = coerceToNumber(value) - return Number.isNaN(number) ? 0 : Math.trunc(number) -} - -/** Values that cannot cross the data boundary: opaque machinery and host-backed wrappers. */ -export const isRuntimeReference = (value: Value): boolean => - value instanceof Opaque || value instanceof Wrapper || value instanceof HostNamespace - -const MAX_ARRAY_INDEX = 4_294_967_295 - -export const parseArrayIndex = (key: string | number): number | undefined => { - if (typeof key === "number") return Number.isInteger(key) && key >= 0 && key < MAX_ARRAY_INDEX ? key : undefined - const property = String(key) - if (!/^(0|[1-9]\d*)$/.test(property)) return undefined - const index = Number(property) - return index < MAX_ARRAY_INDEX ? index : undefined -} - -const canonical = (key: PropertyKey): string | symbol => (typeof key === "symbol" ? key : String(key)) - -/** Objects whose integer keys are live elements rather than own property slots. */ -type Indexed = Arr | Bytes - -const isIndexed = (target: Obj): target is Indexed => target instanceof Arr || target instanceof Bytes - -const elements = (target: Indexed): Array | Uint8Array => (target instanceof Arr ? target.items : target.bytes) - -const index = (target: Obj, key: string | number | symbol): number | undefined => - isIndexed(target) && typeof key !== "symbol" ? parseArrayIndex(key) : undefined - -/** The own property under `key`, including an array's live indexes and `length`. */ -export const own = (target: Obj, key: PropertyKey): Slot | undefined => { - // Most lookups are a name on a plain object or a prototype. - if (typeof key === "string" && !isIndexed(target)) return target.props.get(key) - const name = typeof key === "number" && isIndexed(target) ? key : canonical(key) - if (isIndexed(target)) { - const at = index(target, name) - if (at !== undefined) { - const items = elements(target) - if (!(at in items)) return undefined - return { value: items[at], ...(target instanceof Arr ? target.elements : data) } - } - if (target instanceof Arr && name === "length") { - return { value: target.items.length, writable: target.elements.writable, enumerable: false, configurable: false } - } - } - return target.props.get(typeof name === "number" ? String(name) : name) -} - -// A slot's value for `receiver`. A program getter can only run as program code: inside `withReads` its value comes from -// the read-ahead table (or is recorded as missing); anywhere else reaching one is an error. -const read = (slot: Slot, receiver: Value, key: PropertyKey): Value => { - if ("value" in slot) return slot.value - const getter = slot.get - if (getter === undefined) return undefined - if (typeof getter === "function") return getter(receiver) - return programRead(receiver, key) -} - -export const hasOwn = (target: Obj, key: PropertyKey): boolean => own(target, key) !== undefined - -export const getOwn = (target: Obj, key: PropertyKey): Value => { - const slot = own(target, key) - return slot === undefined ? undefined : read(slot, target, key) -} - -/** [[Get]]'s lookup: the slot `key` names on `target` or its prototype chain. */ -export const lookup = (target: Obj, key: PropertyKey): Slot | undefined => { - for (let current: Obj | null = target; current !== null; current = current.proto) { - const slot = own(current, key) - if (slot !== undefined) return slot - } - return undefined -} - -/** [[Get]]: walks the prototype chain; accessors see `receiver`, which is the primitive for wrapper prototypes. */ -export const get = (target: Obj, key: PropertyKey, receiver: Value = target): Value => { - // An array's present element, without making its property slot. - if (typeof key === "number" && target instanceof Arr && key in target.items && parseArrayIndex(key) !== undefined) - return target.items[key] - for (let current: Obj | null = target; current !== null; current = current.proto) { - const slot = own(current, key) - if (slot !== undefined) return read(slot, receiver, key) - } - return undefined -} - -/** A program getter a caller that runs program code calls itself, with the read's receiver as `this`. */ -export class GetterCall { - constructor(readonly getter: Callable) {} -} - -/** [[Get]] for callers that can run program code (the VM's ops): the value, or the program getter to call. */ -export const access = (target: Obj, key: PropertyKey, receiver: Value = target): Value | GetterCall => { - if (typeof key === "number" && target instanceof Arr && key in target.items && parseArrayIndex(key) !== undefined) - return target.items[key] - const slot = lookup(target, key) - if (slot === undefined || "value" in slot) return slot?.value - const getter = slot.get - if (getter === undefined) return undefined - if (typeof getter === "function") return getter(receiver) - return new GetterCall(getter) -} - -/** - * [[Get]] for display and diagnostics, which never run program code: a program getter reads as `undefined`. - */ -export const peek = (target: Obj, key: PropertyKey, receiver: Value = target): Value => { - const slot = lookup(target, key) - if (slot === undefined || "value" in slot) return slot?.value - const getter = slot.get - return typeof getter === "function" ? getter(receiver) : undefined -} - -/** How display shows a program accessor in place of its value, in Node's words. */ -export const accessorLabel = (slot: AccessorSlot): string => - slot.get !== undefined && slot.set !== undefined - ? "[Getter/Setter]" - : slot.get !== undefined - ? "[Getter]" - : "[Setter]" - -/** - * The program getters a built-in reads ahead (see `withReads` in callback.ts): while it runs again after the VM read - * them, `table` has their values by receiver and key (canonical), and `list` is the program array they came from - * (receiver, key, value, …). Inside `withReads` (`depth` > 0), a getter not in the table reads as `undefined` and is - * recorded in `missing` (receiver, key, …), once per pair. - */ -export const reads: { - table: Map> | undefined - list: Arr | undefined - depth: number - missing: Array | undefined -} = { table: undefined, list: undefined, depth: 0, missing: undefined } - -/** When `check` is on (tests turn it on), a built-in reaching a program accessor it has no path for is a defect. */ -export const accessorRule = { check: false } - -const programRead = (receiver: Value, key: PropertyKey): Value => { - const name = canonical(key) - const known = reads.table?.get(receiver) - if (known !== undefined && known.has(name)) return known.get(name) - if (reads.depth === 0) return unreachableAccessor(name) - const missing = (reads.missing ??= []) - for (let at = 0; at < missing.length; at += 2) - if (missing[at] === receiver && missing[at + 1] === name) return undefined - missing.push(receiver, name) - return undefined -} - -/** A built-in met a program getter or setter it cannot call: a TypeError, or a defect under `accessorRule.check`. */ -export const unreachableAccessor = (key: PropertyKey): never => { - if (accessorRule.check) throw new Error(`A built-in reached the program accessor ${String(key)} with no path for it.`) - throw typeError( - `A built-in cannot call the getter or setter '${String(key)}' here; read the property into a variable first.`, - ) -} - -export const has = (target: Obj, key: PropertyKey): boolean => { - for (let current: Obj | null = target; current !== null; current = current.proto) { - if (own(current, key) !== undefined) return true - } - return false -} - -export const hasPrototype = (value: Value, proto: Obj): boolean => { - for (let current = value instanceof Obj ? value.proto : null; current !== null; current = current.proto) { - if (current === proto) return true - } - return false -} - -const writeElement = (target: Indexed, name: string | number | symbol, value: Value): boolean | undefined => { - const at = index(target, name) - if (at !== undefined) { - if (target instanceof Bytes) { - target.bytes[at] = typeof value === "number" ? value : Number(value) - return true - } - if (!(at in target.items)) rejectAddition(target, at) - changed(target) - target.items[at] = value - return true - } - if (!(target instanceof Arr) || name !== "length") return undefined - const length = typeof value === "number" ? value : Number(value) - if (!Number.isInteger(length) || length < 0) throw rangeError("Invalid array length") - // Shrinking deletes elements, which a sealed array forbids. - if (length < target.items.length && !target.elements.configurable) return false - checkArrayLength(length) - changed(target) - target.items.length = length - return true -} - -/** - * [[Set]]: an inherited setter or read-only property decides before an own data property is created. A program setter - * is not called here: it is returned, for the caller to call with `target` as `this` and `[value]`. - */ -export const set = (target: Obj, key: PropertyKey, value: Value): boolean | Callable => { - // Overwriting an array's present, writable element: no setter or read-only slot can decide first. - if (typeof key === "number" && target instanceof Arr && target.elements.writable && key in target.items) { - if (parseArrayIndex(key) !== undefined) { - changed(target) - target.items[key] = value - return true - } - } - const name = canonical(key) - for (let current: Obj | null = target; current !== null; current = current.proto) { - const slot = own(current, key) - if (slot === undefined) continue - if (!("value" in slot)) { - const setter = slot.set - if (setter === undefined) return false - if (typeof setter !== "function") return setter - setter(target, value) - return true - } - if (!slot.writable) return false - if (current !== target) break - if (isIndexed(target)) { - const written = writeElement(target, typeof key === "number" ? key : name, value) - if (written !== undefined) return written - } - changed(target) - slot.value = value - return true - } - if (isIndexed(target)) { - const written = writeElement(target, typeof key === "number" ? key : name, value) - if (written !== undefined) return written - } - rejectAddition(target, name) - changed(target) - target.props.set(name, { value, ...data }) - return true -} - -/** Creating a property on a non-extensible object is the one [[Set]] failure with its own message. */ -export const rejectAddition = (target: Obj, key: string | symbol | number): void => { - if (target.extensible) return - throw typeError(`Cannot add property ${String(key)}, object is not extensible.`) -} - -/** [[DefineOwnProperty]] for a data property, ignoring the chain. */ -export const define = (target: Obj, key: PropertyKey, value: Value, attrs: Attributes = data): void => { - const name = canonical(key) - if (isIndexed(target) && writeElement(target, name, value) !== undefined) return - changed(target) - target.props.set(name, { value, ...attrs }) -} - -/** A built-in's native accessor. Made with the intrinsics, each half gets its companion program function. */ -export const defineAccessor = (target: Obj, key: PropertyKey, get: Getter | undefined, set?: Setter): void => { - changed(target) - const name = canonical(key) - target.props.set(name, { get, set, enumerable: false, configurable: true }) - if (making === undefined) return - const label = typeof name === "symbol" ? `[${name.description}]` : name - if (get !== undefined) { - const getter = new Native(makingFunctions!, { name: `get ${label}`, call: (thisValue) => get(thisValue) }) - companions.set(get, getter) - companionHalves.set(getter, get) - } - if (set !== undefined) { - const setter = new Native(makingFunctions!, { - name: `set ${label}`, - length: 1, - call: (thisValue, args) => { - set(thisValue, args[0]) - return undefined - }, - }) - companions.set(set, setter) - companionHalves.set(setter, set) - } -} - -/** - * An object literal's `get x() {}` or `set x(v) {}`: an existing accessor keeps its other half; a data property, or no - * property, becomes an accessor with only this half. - */ -export const defineAccessorHalf = ( - target: Obj, - key: PropertyKey, - half: "get" | "set", - fn: Callable, - enumerable = true, -): void => { - const name = canonical(key) - const current = target.props.get(name) - const slot: AccessorSlot = - current !== undefined && !("value" in current) - ? { get: current.get, set: current.set, enumerable, configurable: true } - : { get: undefined, set: undefined, enumerable, configurable: true } - slot[half] = fn - changed(target) - target.hasProgramAccessors = true - target.props.set(name, slot) -} - -/** A property descriptor a program gave: a field present means the descriptor has it (`"get" in desc`), as in the spec. */ -export type Descriptor = { - value?: Value - writable?: boolean - get?: Callable | undefined - set?: Callable | undefined - enumerable?: boolean - configurable?: boolean -} - -const isAccessorDescriptor = (desc: Descriptor) => "get" in desc || "set" in desc -const isDataDescriptor = (desc: Descriptor) => "value" in desc || "writable" in desc - -/** - * ValidateAndApplyPropertyDescriptor for an own property: false where the spec answers false (the caller throws), and - * a TypeError for what the object model cannot hold (an accessor on an array element, elements whose attributes differ - * from their array's shared ones). Everything is checked before anything changes. - */ -export const defineOwnProperty = (target: Obj, key: PropertyKey, desc: Descriptor): boolean => { - const name = canonical(key) - const current = own(target, key) - if (current === undefined && !target.extensible) return false - if (current !== undefined && !compatible(current, desc)) return false - if (isIndexed(target)) { - const at = index(target, name) - if (at !== undefined) return defineElement(target, at, current, desc) - if (target instanceof Arr && name === "length") return defineLength(target, desc) - } - const slot = current === undefined ? created(desc) : applied(current, desc) - if (isProgramAccessor(slot)) target.hasProgramAccessors = true - changed(target) - target.props.set(name, slot) - return true -} - -// Whether `desc` may change a non-configurable `current` (a configurable one may change in any way). -const compatible = (current: Slot, desc: Descriptor): boolean => { - if (current.configurable) return true - if (desc.configurable === true) return false - if ("enumerable" in desc && desc.enumerable !== current.enumerable) return false - if ("value" in current) { - if (isAccessorDescriptor(desc)) return false - if (current.writable) return true - return desc.writable !== true && !("value" in desc && !Object.is(desc.value, current.value)) - } - if (isDataDescriptor(desc)) return false - return ( - (!("get" in desc) || accessorHalf(desc.get) === current.get) && - (!("set" in desc) || accessorHalf(desc.set) === current.set) - ) -} - -// A new property: what the descriptor gives, and false or undefined for what it leaves out. -const created = (desc: Descriptor): Slot => { - const enumerable = desc.enumerable ?? false - const configurable = desc.configurable ?? false - if (isAccessorDescriptor(desc)) { - return { - get: accessorHalf(desc.get) as Getter | Callable | undefined, - set: accessorHalf(desc.set) as Setter | Callable | undefined, - enumerable, - configurable, - } - } - return { value: desc.value, writable: desc.writable ?? false, enumerable, configurable } -} - -// An existing property with the descriptor's fields applied: a kind change keeps only the attributes. -const applied = (current: Slot, desc: Descriptor): Slot => { - const enumerable = desc.enumerable ?? current.enumerable - const configurable = desc.configurable ?? current.configurable - if ("value" in current && isAccessorDescriptor(desc)) return created({ ...desc, enumerable, configurable }) - if (!("value" in current) && isDataDescriptor(desc)) return created({ ...desc, enumerable, configurable }) - if ("value" in current) { - return { - value: "value" in desc ? desc.value : current.value, - writable: desc.writable ?? current.writable, - enumerable, - configurable, - } - } - return { - get: "get" in desc ? (accessorHalf(desc.get) as Getter | Callable | undefined) : current.get, - set: "set" in desc ? (accessorHalf(desc.set) as Setter | Callable | undefined) : current.set, - enumerable, - configurable, - } -} - -// An array or Uint8Array element: elements have no slots, so only data with the collection's own attributes fits. -const defineElement = (target: Indexed, at: number, current: Slot | undefined, desc: Descriptor): boolean => { - if (isAccessorDescriptor(desc)) { - throw typeError("Accessor properties are not supported on array elements; store the value or use a plain object.") - } - if (target instanceof Bytes && at >= target.bytes.length) return false - const shared = target instanceof Arr ? target.elements : data - // An element's own() slot is always data. - const base = (current as Attributes | undefined) ?? { writable: false, enumerable: false, configurable: false } - const writable = desc.writable ?? base.writable - const enumerable = desc.enumerable ?? base.enumerable - const configurable = desc.configurable ?? base.configurable - if (writable !== shared.writable || enumerable !== shared.enumerable || configurable !== shared.configurable) { - throw typeError( - "Array elements share their attributes; only writable, enumerable and configurable equal to the array's are supported.", - ) - } - if (current === undefined || "value" in desc) { - changed(target) - if (target instanceof Bytes) target.bytes[at] = coerceToNumber(desc.value) - else target.items[at] = desc.value - } - return true -} - -// An array's `length`: its value, or making it read-only, which the shared element attributes can't separate. -const defineLength = (target: Arr, desc: Descriptor): boolean => { - if (isAccessorDescriptor(desc) || desc.configurable === true || desc.enumerable === true) return false - if (desc.writable === false && target.elements.writable) { - throw typeError("Making an array's length read-only is not supported; use Object.freeze.") - } - if ("value" in desc) { - const length = coerceToNumber(desc.value) - if (length !== target.items.length && writeElement(target, "length", length) === false) return false - } - return true -} - -export const remove = (target: Obj, key: PropertyKey): boolean => { - const name = canonical(key) - if (isIndexed(target)) { - const at = index(target, name) - if (at !== undefined) { - if (target instanceof Bytes) return !(at in target.bytes) - if (at in target.items && !target.elements.configurable) return false - changed(target) - return delete target.items[at] - } - if (target instanceof Arr && name === "length") return false - } - const slot = target.props.get(name) - if (slot === undefined) return true - if (!slot.configurable) return false - changed(target) - target.props.delete(name) - return true -} - -// JS order: array indexes, integer-like keys ascending, other strings, then symbols. -export const ownKeys = (target: Obj): Array => { - const strings = [...target.props.keys()].filter((key): key is string => typeof key === "string") - const symbols = [...target.props.keys()].filter((key): key is symbol => typeof key === "symbol") - return [ - ...(isIndexed(target) ? Object.keys(elements(target)) : []), - ...(target instanceof Arr ? ["length"] : []), - ...strings.filter((key) => parseArrayIndex(key) !== undefined).sort((a, b) => Number(a) - Number(b)), - ...strings.filter((key) => parseArrayIndex(key) === undefined), - ...symbols, - ] -} - -const enumerable = (target: Obj, key: string | symbol): boolean => own(target, key)?.enumerable === true - -/** Own enumerable keys, including the iterator symbols; what spread and `Object.assign` copy. */ -export const enumerableKeys = (target: Obj): Array => - ownKeys(target).filter( - (key) => - (typeof key === "string" || key === IteratorSymbol || key === AsyncIteratorSymbol) && enumerable(target, key), - ) - -/** Own enumerable string keys: `Object.keys`. */ -export const keys = (target: Obj): Array => - ownKeys(target).filter((key): key is string => typeof key === "string" && enumerable(target, key)) - -/** Own enumerable string entries: `Object.entries` and serialization. */ -export const entries = (target: Obj): Array<[string, Value]> => keys(target).map((key) => [key, getOwn(target, key)]) - -/** Own enumerable string entries for display, which runs no program code: a program accessor shows as its label. */ -export const shownEntries = (target: Obj): Array<[string, Value]> => { - if (!target.hasProgramAccessors) return entries(target) - return keys(target).map((key) => { - const slot = own(target, key)! - return [key, isProgramAccessor(slot) ? accessorLabel(slot) : getOwn(target, key)] - }) -} - -/** An iterator result `{ value, done }`, built directly since every iteration step makes one. */ -export const iteratorResult = (proto: Obj, value: Value, done: boolean): Obj => { - const target = new Obj(proto) - target.props.set("value", { value, writable: true, enumerable: true, configurable: true }) - target.props.set("done", { value: done, writable: true, enumerable: true, configurable: true }) - return target -} - -export const record = (proto: Obj, fields: Record): Obj => { - const target = new Obj(proto) - for (const [key, value] of Object.entries(fields)) define(target, key, value) - return target -} - -/** - * CopyDataProperties for a source without program accessors (spread and rest): defines data on `target`, so no setter - * on its chain runs. - */ -export const copyDataProperties = (target: Obj, source: Obj, skip?: ReadonlySet): void => { - for (const key of enumerableKeys(source)) { - if (skip?.has(key)) continue - define(target, key, getOwn(source, key)) - } -} diff --git a/packages/codemode/src/language/runtime/operations.ts b/packages/codemode/src/language/runtime/operations.ts deleted file mode 100644 index 8c6ee952337..00000000000 --- a/packages/codemode/src/language/runtime/operations.ts +++ /dev/null @@ -1,396 +0,0 @@ -import type { Expression, MemberExpression, NewExpression, Super } from "acorn" -import { type AstNode, invalidData, typeError } from "./model.js" -import { checkStringLength } from "./limits.js" -import { locate } from "./errors.js" -import { type Builtins, primitivePrototype } from "./intrinsics.js" -import { - access, - Arr, - Builtin, - Callable, - GetterCall, - isProgramAccessor, - lookup, - type Slot, - type Cursor, - Fn, - get, - has, - hasOwn, - hasPrototype, - HostNamespace, - IteratorObj, - keys, - Obj, - parseArrayIndex, - Position, - PromiseObj, - set, - coerceToString, - type Value, -} from "./objects.js" -import { circularValue, describeValue, hasCircularReference, isOpaque, typeofValue } from "./references.js" -import type { Interpreter } from "./interpreter.js" -import { enumerableSource } from "../stdlib/object.js" - -// The synchronous semantics the VM's ops share: operators, property references, and the checks around them. Nothing -// here runs program code. - -/** Orders two strings by UTF-16 code units, as `Array.prototype.sort` does by default. */ -export const compareText = (left: string, right: string) => (left < right ? -1 : left > right ? 1 : 0) - -/** The binary operators that convert object operands through ToPrimitive before acting on primitives. */ -const primitiveOperators = new Set([ - "+", - "-", - "*", - "/", - "%", - "**", - "<", - "<=", - ">", - ">=", - "&", - "|", - "^", - "<<", - ">>", - ">>>", -]) - -/** ToPropertyKey on a primitive (or an opaque value, which keeps its built-in string form). */ -export const propertyKey = (value: Value): PropertyKey => - typeof value === "string" || typeof value === "number" || typeof value === "symbol" ? value : coerceToString(value) - -// Native engines name the callee (`search(...).catch is not a function`), including call chains. Returns -// undefined when a link cannot be named, so a chain is either named completely or not at all. -const calleeDescription = (node: Expression | Super | undefined): string | undefined => { - if (node?.type === "Identifier") return node.name - if (node?.type === "CallExpression") { - const target = calleeDescription(node.callee) - return target === undefined ? undefined : `${target}(...)` - } - if (node?.type !== "MemberExpression") return undefined - const property = node.property - const key = - !node.computed && property.type === "Identifier" - ? property.name - : property.type === "Literal" && typeof property.value === "string" - ? property.value - : undefined - if (key === undefined) return undefined - const object = calleeDescription(node.object) - return object === undefined ? undefined : `${object}.${key}` -} - -/** The TypeError for calling a value that is not a function. */ -export const notAFunction = (callee: Expression | Super | undefined, node: AstNode | undefined) => - typeError(`${calleeDescription(callee) ?? "The called value"} is not a function.`, callee ?? node) - -/** The TypeError for `new` on a callee that cannot be constructed. */ -export const notConstructible = (callee: Value, node: NewExpression) => { - // `new` itself is supported, so a non-constructible callee is a TypeError like JS rather than - // unsupported syntax. Built-ins like Number are real constructors in JS, so do not claim - // otherwise; say `new` is unsupported for them and point at the plain call. - const name = calleeDescription(node.callee) ?? "The called value" - const message = - callee instanceof Fn - ? `${name} is not a constructor: only classes can be constructed with new. Use a class, or call it as a function that returns an object.` - : callee instanceof Builtin - ? `new ${name}(...) is not supported; call ${name}(...) without new instead.` - : `${name} is not a constructor.` - return typeError(message, node) -} - -// OrdinaryHasInstance: walk the left operand's chain looking for the constructor's `prototype`, unless that is a -// program getter, which the VM runs first (`$vmInstanceof`). -export const instanceofValue = (lhs: Value, rhs: Value, node: AstNode): boolean | GetterCall => { - if (!(rhs instanceof Callable)) { - throw typeError("The right-hand side of 'instanceof' is not callable.", node) - } - const prototype = accessProperty(rhs, "prototype", node) - if (prototype instanceof GetterCall) return prototype - return hasInstance(lhs, prototype, node) -} - -/** The rest of OrdinaryHasInstance, once `prototype` is read. */ -export const hasInstance = (lhs: Value, prototype: Value, node: AstNode | undefined): boolean => { - if (!(prototype instanceof Obj)) { - throw typeError("The right-hand side of 'instanceof' has no 'prototype' object.", node) - } - return hasPrototype(lhs, prototype) -} - -export const applyBinaryOperator = (operator: string, lhs: Value, rhs: Value, node: AstNode): Value => { - if (operator === "===") return lhs === rhs - if (operator === "!==") return lhs !== rhs - if (operator === "==") return looselyEqual(lhs, rhs, node) - if (operator === "!=") return !looselyEqual(lhs, rhs, node) - if (operator === "in" && rhs instanceof Obj && !isOpaque(lhs)) return has(rhs, propertyKey(lhs)) - if (isOpaque(lhs) || isOpaque(rhs)) { - throw invalidData("Binary operators require data values.", node) - } - // Object operands were already converted through ToPrimitive; only primitives reach the arithmetic below. - switch (operator) { - case "+": { - const sum = (lhs as string) + (rhs as string) - if (typeof sum === "string") checkStringLength(sum.length) - return sum - } - case "-": - return (lhs as number) - (rhs as number) - case "*": - return (lhs as number) * (rhs as number) - case "/": - return (lhs as number) / (rhs as number) - case "%": - return (lhs as number) % (rhs as number) - case "**": - return (lhs as number) ** (rhs as number) - case "<": - return (lhs as string) < (rhs as string) - case "<=": - return (lhs as string) <= (rhs as string) - case ">": - return (lhs as string) > (rhs as string) - case ">=": - return (lhs as string) >= (rhs as string) - case "&": - return (lhs as number) & (rhs as number) - case "|": - return (lhs as number) | (rhs as number) - case "^": - return (lhs as number) ^ (rhs as number) - case "<<": - return (lhs as number) << (rhs as number) - case ">>": - return (lhs as number) >> (rhs as number) - case ">>>": - return (lhs as number) >>> (rhs as number) - case "in": - throw typeError("The 'in' operator requires a data object on the right-hand side.", node) - default: - throw typeError(`Unsupported binary operator '${operator}'.`, node) - } -} - -// IsLooselyEqual: objects (including functions and namespace paths) compare by identity, and a nullish -// primitive never equals an object. -const looselyEqual = (lhs: Value, rhs: Value, node: AstNode): boolean => { - const lhsObject = lhs !== null && typeof lhs === "object" - const rhsObject = rhs !== null && typeof rhs === "object" - if (lhsObject === rhsObject) return lhsObject ? lhs === rhs : lhs == rhs - const primitive = lhsObject ? rhs : lhs - if (primitive === null || primitive === undefined) return false - // Data objects were converted through ToPrimitive, so only an opaque reference facing a primitive gets here. - throw invalidData("Binary operators require data values.", node) -} - -/** - * How an operator with an object operand converts: `in` with a data object on the left asks ToPropertyKey of it, - * a converting operator asks ToPrimitive of both operands with `hint`, and anything else needs no conversion. - */ -export const operatorConversion = ( - operator: string, - lhs: Value, - rhs: Value, -): { readonly kind: "key" } | { readonly kind: "primitive"; readonly hint: "default" | "number" } | undefined => { - // `in` checks the right operand before ToPropertyKey on the left, so a bad right side wins over a bad key. - if (operator === "in" && lhs instanceof Obj && !isOpaque(lhs) && rhs instanceof Obj) return { kind: "key" } - // IsLooselyEqual converts only an object facing a non-nullish primitive; two objects (including namespace - // references, which are not Obj) compare by identity. - const equality = operator === "==" || operator === "!=" - const other = lhs instanceof Obj ? rhs : lhs - const converts = - primitiveOperators.has(operator) || (equality && other !== null && other !== undefined && typeof other !== "object") - if (!converts) return undefined - return { kind: "primitive", hint: operator === "+" || equality ? "default" : "number" } -} - -export type { CustomIterator } from "./objects.js" - -/** A resolved member: the object to read through and the receiver that inherited accessors see. */ -type MemberReference = { - target: Obj - key: PropertyKey - receiver: Value -} - -// A thenable the program's implicit async body adopts before copy-out. A program `then` getter counts: the adoption -// reads it, in program code. -export const isThenable = (value: Value): boolean => { - if (value instanceof PromiseObj) return true - if (!(value instanceof Obj)) return false - const slot = lookup(value, "then") - if (slot === undefined) return false - if (isProgramAccessor(slot)) return true - return typeofValue(get(value, "then")) === "function" -} - -/** A built-in iterator over `value` that needs no program code to start: an iterator object, a string, a collection. */ -export const builtinCursor = (builtins: Builtins, value: Value): Cursor | undefined => { - if (value instanceof IteratorObj) return value.cursor - if (typeof value === "string") return new Position(value, "values", builtins.Array) - return value instanceof Obj ? value.iterator(builtins) : undefined -} - -export const requireIteratorObject = (value: Value, context: string, node?: AstNode): Obj => { - if (value instanceof Obj) return value - throw typeError(`${context} must be an object.`, node) -} - -export const requireIteratorMethod = (value: Value, context: string, node?: AstNode): Value => { - if (typeofValue(value) === "function") return value - throw typeError(`${context} must be a function.`, node) -} - -// for...in over null/undefined iterates nothing, like JS. After the own keys come each prototype's enumerable -// string keys, skipping any key a nearer level has, even as a non-enumerable property. -export const forInKeys = (ctx: Interpreter, value: Value, node: AstNode): Array => { - if (value instanceof HostNamespace) return [...ctx.namespaceKeys(value)] - if (value === null || value === undefined) return [] - const source = enumerableSource(ctx, "for...in", value, node) - const chain = [source] - // A string's characters stand in an array, but its prototype is String.prototype. - let proto = primitivePrototype(ctx.builtins, value) ?? source.proto - while (proto !== null) { - chain.push(proto) - proto = proto.proto - } - return chain.flatMap((target, depth) => { - const nearer = chain.slice(0, depth) - return keys(target).filter((key) => !nearer.some((level) => hasOwn(level, key))) - }) -} - -// GetValue applies ToObject to the base before ToPropertyKey, so a nullish base throws before the key's own -// toString runs. -export const requireMemberBase = (node: MemberExpression, objectValue: Value, keyValue: Value): void => { - if (objectValue === null || objectValue === undefined) { - throw typeError(`Cannot read properties of ${objectValue} (reading '${coerceToString(keyValue)}').`, node.object) - } -} - -export const resolveProperty = ( - builtins: Builtins, - objectValue: Value, - key: PropertyKey, - objectNode: AstNode, - propertyNode: AstNode, -): MemberReference | HostNamespace | { value: Value } => { - if (objectValue instanceof HostNamespace) { - if (typeof key !== "string") { - throw typeError(`${objectValue.root} paths must use string property names.`, propertyNode) - } - return new HostNamespace(objectValue.root, [...objectValue.path, key]) - } - - if (objectValue instanceof Obj) return { target: objectValue, key, receiver: objectValue } - - // Strings own length and indexes; every other primitive property reads through the wrapper prototype. - if (typeof objectValue === "string") { - if (key === "length") return { value: objectValue.length } - const index = typeof key === "symbol" ? undefined : parseArrayIndex(key) - if (index !== undefined && index < objectValue.length) return { value: objectValue[index] } - } - const proto = primitivePrototype(builtins, objectValue) - if (proto !== undefined) return { target: proto, key, receiver: objectValue } - - if (objectValue === null || objectValue === undefined) { - throw typeError(`Cannot read properties of ${objectValue} (reading '${String(key)}').`, objectNode) - } - throw typeError("Cannot access a property on a non-object value.", objectNode) -} - -/** Rejects reading a property a promise doesn't have, so a missing await cannot hide. */ -export const requirePromiseProperty = (reference: MemberReference, node: AstNode): void => { - if (reference.target instanceof PromiseObj && !has(reference.target, reference.key)) { - throw invalidData( - "This value is an un-awaited Promise; await it first - e.g. `const result = await load(...)`.", - (node as Partial).object ?? node, - ) - } -} - -/** [[Get]] for the VM's ops, located at `node`: the value, or a program getter for the op to enter. */ -export const accessProperty = ( - target: Obj, - key: PropertyKey, - node: AstNode | undefined, - receiver: Value = target, -): Value | GetterCall => { - try { - return access(target, key, receiver) - } catch (error) { - throw locate(error, node) - } -} - -// Accessors throw without a location; the member or pattern that read them supplies it. -export const readProperty = ( - target: Obj, - key: PropertyKey, - node: AstNode | undefined, - receiver: Value = target, -): Value => { - try { - return get(target, key, receiver) - } catch (error) { - throw locate(error, node) - } -} - -/** The reference an assignment or update writes through: only a data field of an object. */ -export const writableReference = ( - reference: MemberReference | HostNamespace | { value: Value } | symbol, - node: MemberExpression, -): MemberReference => { - if (typeof reference === "symbol" || reference instanceof HostNamespace || "value" in reference) { - throw typeError("Only data fields may be assigned.", node) - } - if (reference.receiver !== reference.target) { - throw typeError( - `Cannot create property '${String(reference.key)}' on ${typeof reference.receiver} '${String(reference.receiver)}'.`, - node, - ) - } - return reference -} - -/** Assigns `target[key] = next`: the program setter to call with `target` and `[next]`, if the write reaches one. */ -export const assignToReference = ( - target: Obj, - key: PropertyKey, - next: Value, - node: AstNode | undefined, -): Callable | undefined => { - let written: boolean | Callable - try { - // An accessor decides what a write stores (or refuses it), so only a data write can make a cycle. The cycle check - // goes first: the lookup is only needed in the rare case it fails. - if (next instanceof Obj && hasCircularReference(target, next) && !isAccessor(lookup(target, key))) { - throw circularValue(target instanceof Arr ? "Array assignment result" : "Object assignment result") - } - written = set(target, key, next) - } catch (error) { - throw locate(error, node) - } - if (written === true) return undefined - if (written === false) throw failedAssignment(target, key, node) - return written -} - -const isAccessor = (slot: Slot | undefined): boolean => slot !== undefined && !("value" in slot) - -/** Why `[[Set]]` refused: an accessor with only a getter, or a read-only property. */ -export const failedAssignment = (receiver: Value, key: PropertyKey, node: AstNode | undefined) => { - const slot = receiver instanceof Obj ? lookup(receiver, key) : undefined - if (slot !== undefined && !("value" in slot)) { - return typeError( - `Cannot set property '${String(key)}' of ${describeValue(receiver)} which has only a getter.`, - node, - ) - } - return typeError(`Cannot assign to read only property '${String(key)}'.`, node) -} diff --git a/packages/codemode/src/language/runtime/promises.ts b/packages/codemode/src/language/runtime/promises.ts deleted file mode 100644 index 40bb2942ff0..00000000000 --- a/packages/codemode/src/language/runtime/promises.ts +++ /dev/null @@ -1,326 +0,0 @@ -import { type AstNode, Throw, typeError } from "./model.js" -import { Callable, changed, define, hidden, Arr, Fn, Obj, PromiseObj, record, Resolver, type Value } from "./objects.js" -import { constructor, methods, native, receiver, requiresNew } from "./native.js" -import { createAggregateErrorValue, materialize } from "./errors.js" -import { describeValue, typeofValue } from "./references.js" -import { isSupportedCallback } from "./callback.js" -import type { Interpreter } from "./interpreter.js" -import { type Completion, Interruption, Push } from "./signals.js" -import type { Combination, Reaction, Resolving } from "../scheduler.js" -import { finishAwaitReturn } from "../generators.js" - -// A `resolve`/`reject` handed to an executor or thenable: calling it settles the capability. -const resolvingFunctions = (ctx: Interpreter, resolving: Resolving) => ({ - resolve: new Resolver(ctx.builtins.Function, "resolve", resolving, "resolve"), - reject: new Resolver(ctx.builtins.Function, "reject", resolving, "reject"), -}) - -/** - * NewPromiseCapability(%Promise%): a pending promise with what settles it once. A built-in's own failure that rejects - * it is located at `site`, the call that created it. - */ -export const capability = (ctx: Interpreter, site: AstNode | undefined): Resolving => - ctx.vm.scheduler.resolving(ctx.vm.scheduler.newPromise(), site) - -/** Settles `resolving` with a completion: a fulfillment value is resolved, so a thenable is adopted. */ -const settleWith = (resolving: Resolving, completion: Completion) => - completion.ok ? resolving.resolve(completion.value as Value) : resolving.reject(completion.error) - -/** - * Runs a settled promise's reaction as a job: it finishes at once, or returns the call into program code the VM makes - * for it. - */ -export const react = ( - ctx: Interpreter, - reaction: Exclude, - settled: Completion, -): JobCall | void => { - switch (reaction.kind) { - case "settle": - return settleWith(reaction.target, settled) - case "handler": - return handle(ctx, reaction, settled) - case "combinator": - return combine(ctx, reaction, settled) - case "finally": - return cleanUp(ctx, reaction, settled) - case "finallyCleaned": - return settled.ok ? reaction.target.resolve(undefined) : reaction.target.reject(settled.error) - case "finallyOutcome": - return settleWith(reaction.target, settled.ok ? reaction.outcome : settled) - case "awaitReturn": - return finishAwaitReturn(ctx.vm, reaction.generator, settled) - } -} - -/** - * A job that calls program code once, which the VM runs (`VmScheduler.beginJob`), counted toward the depth limit: - * - `thenable` (PromiseResolveThenableJob): calls the thenable's `then` with the resolving functions; a throw rejects - * `resolving`. - * - `handler` (PromiseReactionJob): a `then`/`catch` handler; its result or failure settles `derived`. - * - `finally` (PromiseFinallyJob): a `finally` cleanup; once its own result settles, the original outcome passes on to - * `made` (the spec chains `then(valueThunk)` onto the cleanup's promise: one more job), and a failing cleanup wins. - */ -export type JobCall = - | { - readonly kind: "thenable" - readonly resolving: Resolving - readonly then: Value - readonly thenable: Obj - readonly functions: Array - } - | { readonly kind: "handler"; readonly derived: Resolving; readonly handler: Callable; readonly argument: Value } - | { - readonly kind: "finally" - readonly made: Resolving - readonly cleanup: Callable - readonly site: AstNode | undefined - readonly outcome: Completion - } - -/** - * NewPromiseResolveThenableJob: the work that calls the thenable's `then`. Adopting a native promise through the - * intrinsic `then` takes the same jobs as calling it, and keeps the rejection as thrown so its diagnostic survives. - */ -export const adoptThenable = ( - ctx: Interpreter, - promise: PromiseObj, - thenable: Obj, - then: Value, -): JobCall | void => { - const vm = ctx.vm - const resolving = vm.scheduler.resolving(promise) - if (then === vm.scheduler.intrinsicThen && thenable instanceof PromiseObj) { - vm.scheduler.then(thenable, { kind: "settle", target: resolving }) - return - } - const proto = ctx.builtins.Function - const resolve = new Resolver(proto, "", resolving, "resolve") - const reject = new Resolver(proto, "", resolving, "reject") - return { kind: "thenable", resolving, then, thenable, functions: [resolve, reject] } -} - -// A `then`/`catch` reaction calls program code: the handler runs as a job, and its result or failure settles the -// derived promise. A missing handler passes the outcome through. -const handle = ( - ctx: Interpreter, - reaction: Extract, - settled: Completion, -): JobCall | void => { - const handler = settled.ok ? reaction.onFulfilled : reaction.onRejected - const derived = reaction.derived - if (handler === undefined || (!settled.ok && settled.error instanceof Interruption)) { - return settleWith(derived, settled) - } - const argument = settled.ok ? (settled.value as Value) : materialize(ctx, settled.error) - return { kind: "handler", derived, handler, argument } -} - -const promiseStatics = ["all", "allSettled", "race", "any", "resolve", "reject", "withResolvers", "try"] as const - -const invokePromiseMethod = ( - ctx: Interpreter, - name: (typeof promiseStatics)[number], - args: Array, - site: AstNode | undefined, -) => { - if (name === "resolve") return ctx.vm.scheduler.promiseResolve(args[0]) - if (name === "reject") { - const made = capability(ctx, site) - made.reject(new Throw(args[0])) - return made.promise - } - if (name === "withResolvers") { - const made = capability(ctx, site) - const functions = resolvingFunctions(ctx, made) - return record(ctx.builtins.Object, { promise: made.promise, resolve: functions.resolve, reject: functions.reject }) - } - if (name === "try") { - if (typeofValue(args[0]) !== "function") { - throw typeError(`Promise.try expects a function, received ${describeValue(args[0])}.`) - } - return new Push("Promise.try", [capability(ctx, site), args[0], args.slice(1)]) - } - return new Push("Promise combinator", [capability(ctx, site), name, args[0]]) -} - -// Promise.all, allSettled, race, and any: the prelude iterates the input (`$vmCombine`), resolving each element to a -// promise observed through a reaction, so the result settles in the job where the deciding element's reaction runs, -// or at once for an empty input. A failure while iterating rejects the result. - -// One member settled. Once the result settles early, the remaining members' reactions can do nothing: they are -// detached so a member that stays pending for the rest of the program does not keep them. -const combine = ( - ctx: Interpreter, - reaction: Extract, - settled: Completion, -) => { - if (reaction.called) return - reaction.called = true - const combination = reaction.combination - const made = combination.made - const name = combination.name - if (name === "race" || (!settled.ok && settled.error instanceof Interruption)) { - settleWith(made, settled) - return detachAll(ctx, combination) - } - if (name === "all") { - if (!settled.ok) { - made.reject(settled.error) - return detachAll(ctx, combination) - } - combination.values[reaction.index] = settled.value as Value - return finishCombination(ctx, combination) - } - if (name === "any") { - if (settled.ok) { - made.resolve(settled.value as Value) - return detachAll(ctx, combination) - } - combination.reasons[reaction.index] = materialize(ctx, settled.error) - return finishCombination(ctx, combination) - } - combination.values[reaction.index] = settled.ok - ? record(ctx.builtins.Object, { status: "fulfilled", value: settled.value as Value }) - : record(ctx.builtins.Object, { status: "rejected", reason: materialize(ctx, settled.error) }) - finishCombination(ctx, combination) -} - -const detachAll = (ctx: Interpreter, combination: Combination) => { - for (const [item, reaction] of combination.attached) ctx.vm.scheduler.detach(item, reaction) -} - -export const finishCombination = (ctx: Interpreter, combination: Combination) => { - if (--combination.remaining > 0) return - if (combination.name === "any") { - combination.made.reject( - new Throw(createAggregateErrorValue(ctx, combination.reasons, "All promises were rejected")), - ) - return - } - combination.made.resolve(new Arr(ctx.builtins.Array, combination.values)) -} - -const instanceMethod = ( - ctx: Interpreter, - name: "then" | "catch" | "finally", - thisValue: Value, - args: Array, - site: AstNode | undefined, -): Value => { - const method = `Promise.prototype.${name}` - const promise = receiver(PromiseObj, thisValue, method) - if (name === "finally") return chainFinally(ctx, promise, reactionHandler(args[0], method), site) - const onFulfilled = name === "then" ? reactionHandler(args[0], method) : undefined - const onRejected = reactionHandler(name === "then" ? args[1] : args[0], method) - const made = capability(ctx, site) - ctx.vm.scheduler.then(promise, { kind: "handler", onFulfilled, onRejected, derived: made }) - return made.promise -} - -// Promise.prototype.finally: the cleanup runs as a reaction, then the original outcome passes through once the -// cleanup's own result settles; a failing cleanup wins. -const chainFinally = ( - ctx: Interpreter, - source: PromiseObj, - cleanup: Callable | undefined, - site: AstNode | undefined, -): PromiseObj => { - const made = capability(ctx, site) - ctx.vm.scheduler.then( - source, - cleanup === undefined ? { kind: "settle", target: made } : { kind: "finally", cleanup, target: made, site }, - ) - return made.promise -} - -const cleanUp = ( - _ctx: Interpreter, - reaction: Extract, - settled: Completion, -): JobCall | void => { - const made = reaction.target - if (!settled.ok && settled.error instanceof Interruption) return made.reject(settled.error) - return { kind: "finally", made, cleanup: reaction.cleanup, site: reaction.site, outcome: settled } -} - -const reactionHandler = (value: Value, method: string): Callable | undefined => { - if (isSupportedCallback(value)) return value - if (typeofValue(value) === "function") { - throw typeError( - `${method} cannot use this callable as a handler; wrap it in an arrow function, e.g. (value) => fn(value).`, - ) - } - return undefined -} - -const constructPromise = (ctx: Interpreter, executor: Value, site: AstNode | undefined) => { - if (!(executor instanceof Fn)) { - throw typeError("new Promise(...) expects an executor function (e.g. new Promise((resolve, reject) => { ... })).") - } - const made = capability(ctx, site) - const functions = resolvingFunctions(ctx, made) - return new Push("Promise executor", [made, executor, [functions.resolve, functions.reject]]) -} - -/** - * Lets a synchronous object result also be awaited or chained like a Promise. It inherits non-enumerable - * then/catch/finally that settle with a plain copy, so data views never show them and awaiting does not recurse. - */ -export const promiseLike = (ctx: Interpreter, value: Value): Value => { - if (!(value instanceof Obj) || value.proto !== ctx.builtins.Object) return value - changed(value) - value.proto = ctx.builtins.PromiseLike - return value -} - -const promiseLikeMethods = (ctx: Interpreter) => { - const settled = (thisValue: Value, name: string) => { - const source = receiver(Obj, thisValue, name) - const copy = new Obj(ctx.builtins.Object) - for (const [key, slot] of source.props) copy.props.set(key, { ...slot }) - copy.hasProgramAccessors = source.hasProgramAccessors - return ctx.vm.scheduler.promiseResolve(copy) - } - methods( - ctx.builtins, - ctx.builtins.PromiseLike, - (["then", "catch", "finally"] as const).map((name) => [ - name, - name === "then" ? 2 : 1, - (thisValue, args, site) => instanceMethod(ctx, name, settled(thisValue, name), args, site), - ]), - ) -} - -export const promiseGlobal = (ctx: Interpreter) => { - const builtins = ctx.builtins - const proto = builtins.Promise - const promise = constructor(builtins, proto, { - name: "Promise", - length: 1, - call: requiresNew("Promise"), - construct: (args, _, site) => constructPromise(ctx, args[0], site), - }) - // Combinators are not callbacks: `[p].map(Promise.resolve)` must ask for an arrow function. - for (const name of promiseStatics) { - define( - promise, - name, - native(builtins, { - name, - length: 1, - call: (_, args, site) => invokePromiseMethod(ctx, name, args, site), - callback: false, - }), - hidden, - ) - } - methods(builtins, proto, [ - ["then", 2, (thisValue, args, site) => instanceMethod(ctx, "then", thisValue, args, site)], - ["catch", 1, (thisValue, args, site) => instanceMethod(ctx, "catch", thisValue, args, site)], - ["finally", 1, (thisValue, args, site) => instanceMethod(ctx, "finally", thisValue, args, site)], - ]) - promiseLikeMethods(ctx) - return promise -} diff --git a/packages/codemode/src/language/runtime/references.ts b/packages/codemode/src/language/runtime/references.ts deleted file mode 100644 index dcc6cebb7c5..00000000000 --- a/packages/codemode/src/language/runtime/references.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { invalidData } from "./model.js" -import { - Callable, - getOwn, - HostNamespace, - isProgramAccessor, - isRuntimeReference, - Obj, - Opaque, - own, - ownKeys, - type Value, -} from "./objects.js" - -/** Interpreter machinery that is never data, unlike a Date or Map, which cross some boundaries as copies. */ -export const isOpaque = (value: Value): boolean => value instanceof Opaque || value instanceof HostNamespace - -// Depth-first search over a value tree. `match` stops the walk; `skip` prunes a subtree without matching it. A -// structural check, so it never runs program code: program accessors are left out. -const find = ( - value: Value, - match: (current: Value) => boolean, - skip: (current: Value) => boolean, - seen: Set, -): boolean => { - const pending: Array> = [[value].values()] - while (pending.length > 0) { - const next = pending.at(-1)!.next() - if (next.done) { - pending.pop() - continue - } - const current = next.value - if (match(current)) return true - if (!(current instanceof Obj) || skip(current) || seen.has(current)) continue - seen.add(current) - const keys = current.hasProgramAccessors - ? ownKeys(current).filter((key) => !isProgramAccessor(own(current, key)!)) - : ownKeys(current) - pending.push(keys.map((key) => getOwn(current, key)).values()) - } - return false -} - -const never = () => false - -export const containsRuntimeReference = (value: Value): boolean => find(value, isRuntimeReference, never, new Set()) - -export const containsOpaqueReference = (value: Value): boolean => - find(value, isOpaque, (current) => isRuntimeReference(current) && !isOpaque(current), new Set()) - -// Reject cycles before mutation so later boundary walks remain safe. -export const rejectCircularInsertion = ( - container: Obj, - value: Value, - label: string, - seen = new Set(), -): void => { - if (hasCircularReference(container, value, seen)) throw circularValue(label) -} - -export const hasCircularReference = (container: Obj, value: Value, seen = new Set()): boolean => - find(value, (current) => current === container, isRuntimeReference, seen) - -export const circularValue = (label: string) => invalidData(`${label} contains a circular value.`) - -export const describeValue = (value: Value): string => { - if (value === null || value === undefined) return String(value) - if (value instanceof Obj) return value.describe - if (value instanceof HostNamespace) return "a namespace reference" - return `a ${typeof value}` -} - -export const typeofValue = (value: Value): string => { - if (value instanceof Callable) return "function" - if (value instanceof HostNamespace) return value.path.length > 0 ? "function" : "object" - return typeof value -} diff --git a/packages/codemode/src/language/runtime/signals.ts b/packages/codemode/src/language/runtime/signals.ts deleted file mode 100644 index a5c318f7294..00000000000 --- a/packages/codemode/src/language/runtime/signals.ts +++ /dev/null @@ -1,90 +0,0 @@ -import type { Cause } from "effect" -import type { AstNode, GeneratorRequestKind } from "./model.js" -import type { GeneratorObj, Value } from "./objects.js" - -// What built-ins return when their result is not a plain value (work for the VM, a generator to resume, a call to -// make, or conversions to run first), and how work completes. All of it is data; nothing here needs Effect at run time. - -export type Completion = - | { readonly ok: true; readonly value: unknown } - | { readonly ok: false; readonly error: unknown } - -export const normal = (value: unknown): Completion => ({ ok: true, value }) -export const abrupt = (error: unknown): Completion => ({ ok: false, error }) - -/** - * Work a built-in hands to the VM, by name, with its arguments: VM-side TS or a prelude function runs it at the call, - * and its result is the call's (see `Vm.settleNativeResult`). - */ -export class Push { - constructor( - readonly kind: PushKind, - readonly slots: Array, - ) {} -} - -export type PushKind = - | "JSON.stringify" - | "AsyncFromSyncIterator" - | "Promise executor" - | "Promise.try" - | "Promise combinator" - -/** Continue a suspended generator's frame with `request`: what `next`/`return`/`throw` return once it can run. */ -export class Resume { - constructor( - readonly generator: GeneratorObj, - readonly request: GeneratorRequest, - ) {} -} - -/** - * A built-in needs `values` converted to primitives (ToPrimitive with `hints`, in order) before it can go on: the - * conversions run as prelude code, then the built-in runs again from the start, and its `ordinal`-th conversion - * receives them. See `withPrimitives`. - */ -export class Convert { - constructor( - readonly hints: Hints, - readonly values: ReadonlyArray, - readonly ordinal: number, - /** Also apply ToNumber or ToString to each one before converting the next. */ - readonly coerce: boolean, - ) {} -} - -/** - * A built-in met program getters it cannot call (see `withReads`): the VM reads `reads` (receiver, key, receiver, key, - * …) in program code, then runs the built-in again from the start, and its reads of them get those values. - */ -export class Prefetch { - constructor(readonly reads: ReadonlyArray) {} -} - -export type Hint = "number" | "string" | "default" -export type Hints = Hint | ReadonlyArray - -/** - * Host work that was interrupted on its own. It settles its promise like a rejection, but program code cannot catch - * it: handlers, `catch`, and `finally` are skipped, an unobserved one is not reported, and one that reaches the - * program's body interrupts the execution. - */ -export class Interruption { - constructor(readonly cause: Cause.Cause) {} -} - -/** A call a built-in hands on (`Function.prototype.call`, say): the VM makes it as the built-in's own result. */ -export class Invoke { - constructor( - readonly callable: Value, - readonly thisValue: Value, - readonly args: Array, - readonly site: AstNode | undefined, - ) {} -} - -/** What a generator body continues with: the `next`, `return`, or `throw` call that resumed it. */ -export type GeneratorRequest = { readonly kind: GeneratorRequestKind; readonly value: Value } - -/** Most activations one stack may hold, as the call-stack limit. */ -export const MAX_CALL_DEPTH = 10_000 diff --git a/packages/codemode/src/language/runtime/source.ts b/packages/codemode/src/language/runtime/source.ts deleted file mode 100644 index 40b31deb323..00000000000 --- a/packages/codemode/src/language/runtime/source.ts +++ /dev/null @@ -1,74 +0,0 @@ -import type { Program } from "acorn" -import type { AstNode } from "./model.js" - -/** A stable reference to one AST node: its source and its index in a pre-order walk of that source's tree. */ -export type NodeId = { readonly source: string; readonly index: number } - -/** - * One parsed program text with every node numbered in pre-order, so a node can be named and found again. A built-in - * source whose bytecode was compiled ahead of time is parsed only once something asks for its nodes. - */ -export class Source { - private tree: Program | (() => Program) - private numbered: ReadonlyArray | undefined - - constructor( - readonly id: string, - readonly code: string, - program: Program | (() => Program), - ) { - this.tree = program - if (typeof program !== "function") this.numbered = numberNodes(program, this) - } - - get program(): Program { - if (typeof this.tree === "function") this.tree = this.tree() - return this.tree - } - - /** Nodes by pre-order index. */ - get nodes(): ReadonlyArray { - return (this.numbered ??= numberNodes(this.program, this)) - } - - /** The node `id` names, when it belongs to this source. */ - node(id: NodeId): AstNode | undefined { - return id.source === this.id ? this.nodes[id.index] : undefined - } -} - -const numbering = new WeakMap() - -/** The id of a node from a numbered source; nodes built outside one (none today) have none. */ -export const nodeId = (node: AstNode): NodeId | undefined => { - const entry = numbering.get(node) - return entry === undefined ? undefined : { source: entry.source.id, index: entry.index } -} - -/** The source a numbered node belongs to. */ -export const sourceOf = (node: AstNode): Source | undefined => numbering.get(node)?.source - -const isNode = (value: unknown): value is AstNode => - typeof value === "object" && value !== null && typeof (value as { readonly type?: unknown }).type === "string" - -// Acorn creates node fields in a fixed order, so walking own keys in order gives the same numbering on every parse. -const numberNodes = (root: AstNode, source: Source): Array => { - const nodes: Array = [] - const pending = [root] - for (let node = pending.pop(); node !== undefined; node = pending.pop()) { - numbering.set(node, { source, index: nodes.length }) - nodes.push(node) - const children: Array = [] - for (const key in node) { - if (key === "loc") continue - const child: unknown = (node as unknown as Record)[key] - if (Array.isArray(child)) children.push(...child.filter(isNode)) - else if (isNode(child)) children.push(child) - } - for (let index = children.length - 1; index >= 0; index--) pending.push(children[index]!) - } - return nodes -} - -/** Whether `node` is the prelude's: it is parsed without locations, so a failure there is located at the program's call. */ -export const inPrelude = (node: AstNode): boolean => node.loc === undefined || node.loc === null diff --git a/packages/codemode/src/language/runtime/table.ts b/packages/codemode/src/language/runtime/table.ts deleted file mode 100644 index b6b21ac455e..00000000000 --- a/packages/codemode/src/language/runtime/table.ts +++ /dev/null @@ -1,143 +0,0 @@ -import type { Value } from "./objects.js" - -/** The key of a deleted entry. */ -export const deleted: unique symbol = Symbol("codemode.deleted") - -/** A position in a table's entries, kept by the table so compaction can move it. */ -export type TableCursor = { index: number; done: boolean } - -/** - * The storage behind Map and Set: entries in insertion order with tombstones, as V8's OrderedHashTable. An entry keeps - * its index until the table compacts, and the table moves every live cursor when it does, so an iterator's position is - * a plain integer. Iteration is live: entries added before a cursor reaches the end are visited, deleted ones skipped, - * and after `clear()` a cursor continues with whatever is added next. Keys compare by SameValueZero. - */ -export class OrderedTable { - readonly keys: Array = [] - readonly values: Array = [] - // Derived from `keys`: where each live key is. - private readonly index = new Map() - private cursors: Array = [] - private tombstones = 0 - private pruneAt = 16 - - get size(): number { - return this.index.size - } - - has(key: Value): boolean { - return this.index.has(key) - } - - get(key: Value): Value { - const at = this.index.get(key) - return at === undefined ? undefined : this.values[at] - } - - set(key: Value, value: Value): void { - const at = this.index.get(key) - if (at !== undefined) { - this.values[at] = value - return - } - // -0 is stored as +0, as Map and Set do. - const stored = key === 0 ? 0 : key - this.index.set(stored, this.keys.length) - this.keys.push(stored) - this.values.push(value) - } - - add(key: Value): void { - if (!this.index.has(key)) this.set(key, undefined) - } - - delete(key: Value): boolean { - const at = this.index.get(key) - if (at === undefined) return false - this.index.delete(key) - this.keys[at] = deleted - this.values[at] = undefined - this.tombstones++ - if (this.tombstones >= 16 && this.tombstones * 2 >= this.keys.length) this.compact() - return true - } - - clear(): void { - this.keys.fill(deleted) - this.values.fill(undefined) - this.index.clear() - this.tombstones = this.keys.length - this.compact() - } - - /** A cursor at the first entry, moved along by `advance`. */ - cursor(): TableCursor { - return this.track({ index: 0, done: false }) - } - - /** Starts keeping `cursor` in place across compaction. */ - track(cursor: C): C { - if (this.cursors.length >= this.pruneAt) { - this.cursors = this.cursors.filter((item) => !item.done) - this.pruneAt = Math.max(16, this.cursors.length * 2) - } - this.cursors.push(cursor) - return cursor - } - - /** The index of the cursor's next live entry, moving past it; -1 once the cursor is done, which is for good. */ - advance(cursor: TableCursor): number { - if (cursor.done) return -1 - for (let at = cursor.index; at < this.keys.length; at++) { - if (this.keys[at] === deleted) continue - cursor.index = at + 1 - return at - } - cursor.done = true - return -1 - } - - /** - * Live entries in order, through a tracked cursor, so host code may change the table (or run program code that does) - * between steps. Stopping early releases the cursor. - */ - *entries(): Generator<[Value, Value]> { - const cursor = this.cursor() - try { - for (let at = this.advance(cursor); at >= 0; at = this.advance(cursor)) { - yield [this.keys[at] as Value, this.values[at]] - } - } finally { - cursor.done = true - } - } - - [Symbol.iterator](): Generator<[Value, Value]> { - return this.entries() - } - - *liveKeys(): Generator { - for (const [key] of this.entries()) yield key - } - - // Drops the tombstones; a cursor moves to the count of live entries before it, which is where it now points. - private compact(): void { - const before: Array = [] - let live = 0 - for (let at = 0; at < this.keys.length; at++) { - before.push(live) - const key = this.keys[at] - if (key === deleted) continue - this.keys[live] = key - this.values[live] = this.values[at] - this.index.set(key, live) - live++ - } - before.push(live) - this.keys.length = live - this.values.length = live - this.tombstones = 0 - this.cursors = this.cursors.filter((cursor) => !cursor.done) - for (const cursor of this.cursors) cursor.index = before[Math.min(cursor.index, before.length - 1)]! - } -} diff --git a/packages/codemode/src/language/scheduler.ts b/packages/codemode/src/language/scheduler.ts deleted file mode 100644 index cbff1908443..00000000000 --- a/packages/codemode/src/language/scheduler.ts +++ /dev/null @@ -1,165 +0,0 @@ -import type { Json } from "./data.js" -import type { DurableFn, Fn } from "./host-function.js" -import type { HostTarget } from "./host.js" -import { locate } from "./runtime/errors.js" -import type { AstNode } from "./runtime/model.js" -import type { Callable, Cursor, GeneratorObj, Obj, PromiseObj, Value } from "./runtime/objects.js" -import type { Completion } from "./runtime/signals.js" -import type { Frame } from "./vm.js" - -// The scheduler's records: jobs, reactions, resolvers, and host calls. All of them are data the VM keeps, so a run's -// queue and the work it waits on can be read (and saved) between `run()`s. - -/** What the member reactions of one `Promise.all`/`allSettled`/`race`/`any` share. */ -export type Combination = { - readonly name: "all" | "allSettled" | "race" | "any" - /** Settles the combinator's result. */ - readonly made: Resolving - readonly values: Array - readonly reasons: Array - /** Members still to settle, plus one until iteration ends. */ - remaining: number - /** Every member's reaction, detached once the result is decided. */ - readonly attached: Array -} - -/** - * A settled promise's reaction, as data. It runs as a job (see `react` in promises.ts) and either finishes at once or - * starts a frame that calls program code. The kinds: - * - `await`: resume the frames parked on the promise, cut off the job stack at an `await`. - * - `settle`: pass the outcome on to `target`. - * - `handler`: `then`/`catch` handlers; the handler's result settles `derived`. - * - `combinator`: one member of a `Promise` combinator. - * - `finally`, `finallyCleaned`, `finallyOutcome`: the steps of `Promise.prototype.finally` with a cleanup. - * - `awaitReturn`: an async generator's `return(value)` once `value` settles. - * - `asyncFromSync`: an async-from-sync iterator method's result value settled: answer `made` with it, closing the - * synchronous iterator `close` first on a rejection when one is given. - */ -export type Reaction = - | { readonly kind: "await"; readonly frames: Array } - | { readonly kind: "settle"; readonly target: Resolving } - | { - readonly kind: "handler" - readonly onFulfilled: Callable | undefined - readonly onRejected: Callable | undefined - readonly derived: Resolving - } - | { readonly kind: "combinator"; readonly combination: Combination; readonly index: number; called: boolean } - | { - readonly kind: "finally" - readonly cleanup: Callable - readonly target: Resolving - readonly site: AstNode | undefined - } - | { readonly kind: "finallyCleaned"; readonly target: Resolving } - | { readonly kind: "finallyOutcome"; readonly target: Resolving; readonly outcome: Completion } - | { readonly kind: "awaitReturn"; readonly generator: GeneratorObj } - | { - readonly kind: "asyncFromSync" - readonly made: Resolving - readonly done: boolean - readonly close: Cursor | undefined - readonly site: AstNode - } - -/** One queued job, as data: run a settled promise's reaction (resuming parked frames, say), or adopt a thenable. */ -export type Job = - | { readonly kind: "reaction"; readonly reaction: Reaction; readonly settled: Completion } - | { readonly kind: "thenable"; readonly promise: PromiseObj; readonly thenable: Obj; readonly then: Value } - | { readonly kind: "thenable-get"; readonly promise: PromiseObj; readonly thenable: Obj } - -/** - * How a host call runs, from its function's options (see `Host.Type`): `sync` and `sync-thenable` calls block the job - * or settle a promise for what the function left pending, `async` calls run concurrently, `idempotent` ones may run - * again after a suspend, and `durable` ones keep running across it. - */ -export type HostPolicy = "sync" | "sync-thenable" | "async" | "idempotent" | "durable" - -/** - * Host work the program waits on. The VM queues it and hands it to the driver at its next stop; the driver runs it and - * reports how it ended with `Vm.complete`. A concurrent call's outcome waits in the inbox and settles its promise in a - * later job; a blocking call stops the VM, and no other job runs until it ends. Its live parts, the host function and - * what it returned, are never saved: a resumed run finds the function again by `path`. - */ -export class HostCall { - /** - * Where the call is: `queued` (written ahead, not started), `running` (or in `start` for a durable call), - * `started` (a durable call whose `start` returned its `data`, now in `wait`), or `completed`. - */ - status: "queued" | "running" | "started" | "completed" = "queued" - /** The JSON data a durable call's `start` returned, saved so a resumed run can call `wait(data)`. */ - data: Json | undefined = undefined - /** The host function, while the call is in progress. */ - fn: Fn | DurableFn | undefined = undefined - /** What a host function returned and left pending (an Effect, or a Promise), which the driver waits on. */ - work: unknown = undefined - /** Whether host functions crossed back among its arguments: they have no data form, so it blocks a suspend. */ - holdsFunctions = false - /** What the program names it by, where it is among the host globals, and whose hooks save what it returns. */ - readonly label: string - readonly path: ReadonlyArray | undefined - readonly owner: string | undefined - constructor( - readonly id: number, - /** The call's stable idempotency key, `:`. */ - readonly key: string, - target: HostTarget, - readonly policy: HostPolicy, - /** The arguments as they crossed to the host. */ - public args: ReadonlyArray, - /** The running job waits for it: its outcome continues the frame that asked, before any other job. */ - readonly blocking: boolean, - /** Settles a concurrent call's promise. */ - readonly resolving: Resolving | undefined, - /** The call that started the work, where a defect it raises is located. */ - readonly site: AstNode | undefined, - ) { - this.label = target.label - this.path = target.path - this.owner = target.owner - } -} - -/** - * CreateResolvingFunctions as data: settles one promise at most once, however many `Resolver`s share it. `reject` takes - * the failure as thrown; one without a location is located at `site`, the call that created the promise. - */ -export class Resolving { - done = false - constructor( - private readonly scheduler: Settles, - readonly promise: PromiseObj, - readonly site: AstNode | undefined, - ) {} - - resolve(resolution: Value): void { - if (this.done) return - this.done = true - this.scheduler.resolveWith(this.promise, resolution, this.site) - } - - reject(reason: unknown): void { - if (this.done) return - this.done = true - this.scheduler.reject(this.promise, locate(reason, this.site)) - } -} - -type Settles = { - resolveWith(promise: PromiseObj, resolution: Value, site?: AstNode): void - reject(promise: PromiseObj, reason: unknown): void -} - -/** - * Why `Vm.run` stopped: - * - `done`: the program's body ended, with its completion. - * - `host`: start `calls`, newly queued host work, in order (a blocking call is last, and the VM continues only once - * it completes). With no calls, the VM waits for host work already running to complete. - * - `slice`: the step budget is used up; let the host run, then continue. - * - `stuck`: nothing can run or settle any more; `node` is the `await` that waits forever, when one is known. - */ -export type Stop = - | { readonly kind: "done"; readonly completion: Completion } - | { readonly kind: "host"; readonly calls: ReadonlyArray } - | { readonly kind: "slice" } - | { readonly kind: "stuck"; readonly node: AstNode | undefined } diff --git a/packages/codemode/src/language/snapshot.ts b/packages/codemode/src/language/snapshot.ts deleted file mode 100644 index bf096a558a1..00000000000 --- a/packages/codemode/src/language/snapshot.ts +++ /dev/null @@ -1,384 +0,0 @@ -import packageJson from "../../package.json" with { type: "json" } -import type { Interruption } from "./runtime/signals.js" -import { staticNames, unchanged } from "./runtime/intrinsic-names.js" -import { Arr, ClassInfo, Fn, Obj } from "./runtime/objects.js" -import { nodeId, type Source } from "./runtime/source.js" -import { type ClassSpec, codecShape, decode, encode, type Json, SnapshotError } from "./snapshot/codec.js" -import { FORMAT, type Header, hash, hostsId, type Snapshot, validate } from "./snapshot/snapshot.js" -import { AsyncFromSyncCloseTarget, FinallyTarget, VmScheduler } from "./async.js" -import { Code, hashOf } from "./code.js" -import { COMPILER_VERSION, compileSource } from "./compiler/compile.js" -import { HostCalls } from "./host.js" -import { getInternalPrelude } from "./internal-prelude.js" -import { compiledPrelude } from "./prelude/prelude.js" -import { Cell, CodeFlags, EMPTY_CELLS, HOLE, Op } from "./opcodes.js" -import { CustomIter, Frame, Mode, Vm, VmInternalFn } from "./vm.js" - -// Snapshots of the bytecode VM (plan §6): the generic graph codec, plus records for the VM's own classes. -// -// - **Code is never saved.** A function's code is `["x", ["code", source, index]]`; restore recompiles every saved -// source eagerly and refuses one whose bytecode hash differs from the saved one, so a pc always means the same -// instruction. The prelude and the VM's internal helpers are named by the build id, which hashes their bytecode. -// - **A frame** saves its registers up to `sp` (locals, then the live operand stack), its function, pc, mode and the -// promise or generator it settles. Restore checks it against its code before anything runs (§6.5). -// - **The VM's internal callables** (`$` intrinsics, internal helpers) are named, never copied. -// - New VM state must be listed in the `Vm` spec: an unknown own field is a codec gap, so nothing is silently dropped. - -export type CaptureOptions = { - readonly limits?: Header["limits"] - /** Active milliseconds used so far, across every resume. */ - readonly activeMs?: number - /** The run's `run.metadata`. */ - readonly metadata?: Json - /** Throw on the first value with no data form, instead of reporting it in `lost`. */ - readonly strict: boolean -} - -export type RestoreOptions = { - /** Parses a saved program source (cached by text). */ - readonly parse: (code: string) => Source - readonly interruption: () => Interruption -} - -let specs: ReadonlyArray | undefined - -// Built on first use: this module and vm.ts import each other, so the classes aren't there at load time. -const vmSpecs = (): ReadonlyArray => - (specs ??= [ - { - name: "Vm", - ctor: Vm, - anchor: "vm", - fields: ["frames", "templates", "scheduler", "hosts", "depth", "sliced", "outcome"], - skip: ["ctx", "pool", "sourceCodes", "intrinsics", "fuel", "sliceStart", "tripEvery", "redo"], - reset: restoreStack, - }, - { - name: "VmScheduler", - ctor: VmScheduler, - anchor: "scheduler", - fields: ["intrinsicThen", "parked", "queue", "head", "pending", "nextID", "unhandled"], - skip: ["vm"], - }, - { - name: "HostCalls", - ctor: HostCalls, - anchor: "hosts", - fields: ["runId", "queued", "running", "inbox", "nextID", "blocked", "input"], - skip: ["ctx", "promises"], - }, - { - name: "Frame", - ctor: Frame, - fields: ["fn", "code", "pc", "sp", "regs", "thisValue", "args", "mode", "target", "answer", "origin", "counted"], - view: (frame: Frame) => [ - frame.fn, - frame.code, - frame.pc, - frame.sp, - frame.regs.slice(0, frame.sp), - frame.thisValue, - frame.args, - frame.mode, - frame.target, - frame.answer, - frame.origin, - frame.counted, - ], - reset: restoreFrame, - }, - { - name: "Fn", - ctor: Fn, - fields: ["code", "cells", "home", "klass"], - skip: ["length"], - obj: true, - constants: { tag: "Function" }, - reset: restoreFn, - }, - { name: "ClassInfo", ctor: ClassInfo, fields: ["derived", "fields", "errorBase"] }, - { name: "VmInternalFn", ctor: VmInternalFn, fields: ["code", "boundArgs"] }, - { name: "FinallyTarget", ctor: FinallyTarget, fields: ["vm", "made", "site", "outcome"] }, - { name: "AsyncFromSyncCloseTarget", ctor: AsyncFromSyncCloseTarget, fields: ["made", "reason"] }, - { name: "Cell", ctor: Cell, fields: ["v"] }, - { name: "CustomIter", ctor: CustomIter, fields: ["done", "rawGen", "iterator", "next"] }, - ]) - -/** - * For tests: the frames a saved state holds (the job stack, parked awaits, suspended generators), each as its - * function's name or the internal helper it runs, with " (redo)" for a getter an iterator op is running (`Mode.REDO`). - * It reads the Frame and Fn records as `vmSpecs` writes them, so it changes with the format. - */ -export const savedFrames = (snapshot: Snapshot): Array => { - const fields = vmSpecs().find((spec) => spec.name === "Frame")!.fields - const records = snapshot.records as ReadonlyArray< - { t?: string; f?: ReadonlyArray; o?: ReadonlyArray } | undefined - > - return records.flatMap((record) => { - if (record?.t !== "Frame") return [] - const fn = record.f![fields.indexOf("fn")] - const redo = record.f![fields.indexOf("mode")] === Mode.REDO ? " (redo)" : "" - if (Array.isArray(fn) && fn[0] === "r") { - const props = records[fn[1] as number]!.o! - return [`${String(props[props.indexOf("name") + 1])}${redo}`] - } - const [, source, index] = (record.f![fields.indexOf("code")] as [string, [string, string, number]])[1] - const codes = source === "@vm-internal" ? getInternalPrelude().codes : compiledPrelude().codes - return [`${codes[index]!.name}${redo}`] - }) -} - -let build: string | undefined - -/** - * The VM build a snapshot belongs to: the package version, and a hash of the format, the opcode table, the frame - * modes, the compiler version, the prelude's and the internal helpers' bytecode, the static intrinsic names, and the - * codec's shape. A runtime must have been made first (the intrinsic names come from it). - */ -export const buildId = (): string => - (build ??= `${packageJson.version}+${hash( - [ - FORMAT, - JSON.stringify(Object.entries(Op)), - JSON.stringify(Object.entries(Mode)), - COMPILER_VERSION, - hashOf(compiledPrelude().codes), - hashOf(getInternalPrelude().codes), - staticNames().join("\n"), - codecShape(vmSpecs()), - ].join("\n"), - )}`) - -/** Saves a VM's state as it is now, with every built-in or host global the run changed. Changes nothing. */ -export const captureVm = ( - vm: Vm, - options: CaptureOptions, -): { readonly snapshot: Snapshot; readonly lost: ReadonlyArray } => { - vm.compact() - const ctx = vm.ctx - const lost: Array = [] - const names = ctx.intrinsics - const programs = [...ctx.sources.values()] - const sources = sourcesOf(vm) - const anchors = new Map(anchorsOf(vm)) - const internals = new Map() - for (const [name, value] of vm.intrinsics) if (!(value instanceof Obj)) internals.set(value, name) - const encoded = encode([vm, ctx, ctx.globalScope, ...names.changed()], { - nameOf: (value) => names.nameOf(value), - unchanged, - anchorOf: (value) => anchors.get(value), - nodeId: (node) => { - const id = nodeId(node) - return id !== undefined && sources.get(id.source)?.nodes[id.index] === node ? [id.source, id.index] : undefined - }, - lost, - strict: options.strict, - hosts: ctx.hosts, - specs: vmSpecs(), - external: (value): Json | undefined => { - if (value === HOLE) return "hole" - if (typeof value === "symbol" || value instanceof Obj) return undefined - const internal = internals.get(value) - if (internal !== undefined) return ["intrinsic", internal] - return codeRef(vm, value) - }, - }) - const snapshot: Snapshot = { - format: FORMAT, - header: { - build: buildId(), - hosts: hostsId(ctx), - runId: vm.hosts.runId, - sources: programs.map((source) => ({ - id: source.id, - code: source.code, - hash: hash(source.code), - bytecode: vm.sourceCodes.get(source.id)![0]!.source.hash, - })), - limits: options.limits ?? { timeoutMs: null, maxOutputBytes: null }, - budget: { activeMs: options.activeMs ?? 0 }, - metadata: options.metadata ?? null, - }, - roots: encoded.roots, - records: encoded.records, - } - return { snapshot, lost } -} - -/** - * Restores a saved state into `vm`, a fresh one made for a new runtime with the same host globals and no bindings, - * after checking the snapshot belongs to this build, these host globals, its own sources and their bytecode. - */ -export const restoreVm = (vm: Vm, saved: unknown, options: RestoreOptions): Snapshot => { - const snapshot = validate(saved) - const header = snapshot.header - const ctx = vm.ctx - const expected = buildId() - if (snapshot.format !== FORMAT || header.build !== expected) { - throw new SnapshotError( - `This state was saved by another Code Mode build (${header.build}); this runtime is ${expected}, so it can't resume it.`, - ) - } - if (header.hosts !== hostsId(ctx)) { - throw new SnapshotError("This state was saved by a runtime with other host globals; resume it with the same ones.") - } - for (const source of header.sources) { - if (hash(source.code) !== source.hash) throw new SnapshotError(`Source ${source.id} does not match its hash.`) - const parsed = options.parse(source.code) - if (parsed.id !== source.id || vm.sourceCodes.has(source.id)) { - throw new SnapshotError(`Source ${source.id} is not a program source.`) - } - const codes = compileSource(parsed) - if (codes[0]!.source.hash !== source.bytecode) { - throw new SnapshotError(`Source ${source.id} compiles to other bytecode in this build, so it can't resume.`) - } - ctx.sources.set(source.id, parsed) - vm.sourceCodes.set(source.id, codes) - } - const sources = sourcesOf(vm) - const anchors = new Map(anchorsOf(vm).map(([object, name]) => [name, object])) - decode(snapshot, { - named: (name) => ctx.intrinsics.valueOf(name), - anchor: (name) => anchors.get(name), - node: (source, index) => sources.get(source)?.nodes[index], - interruption: options.interruption, - hosts: ctx.hosts, - specs: vmSpecs(), - external: (data) => { - if (data === "hole") return HOLE - if (!Array.isArray(data)) return undefined - if (data[0] === "intrinsic" && typeof data[1] === "string") { - const value = vm.intrinsics.get(data[1]) - return value instanceof Obj ? undefined : value - } - if (data[0] === "code" && typeof data[1] === "string" && typeof data[2] === "number") { - return vm.sourceCodes.get(data[1])?.[data[2]] - } - return undefined - }, - }) - return snapshot -} - -// --- Helpers --- - -// The objects a fresh runtime already has, saved by name and filled in place on restore. -const anchorsOf = (vm: Vm): ReadonlyArray => [ - [vm, "vm"], - [vm.scheduler, "scheduler"], - [vm.hosts, "hosts"], - [vm.ctx, "ctx"], - [vm.ctx.globalScope, "globals"], -] - -// Every source a saved node can belong to: the programs, and the prelude's and the internal helpers' sources. -const sourcesOf = (vm: Vm): Map => { - const sources = new Map(vm.ctx.sources) - for (const codes of vm.sourceCodes.values()) { - const source = codes[0]?.sourceObj - if (source !== undefined) sources.set(source.id, source) - } - return sources -} - -const codeRef = (vm: Vm, code: object): Json | undefined => { - if (!(code instanceof Code)) return undefined - if (vm.sourceCodes.get(code.source.id)?.[code.index] !== code) { - throw new SnapshotError(`Codec gap: function ${code.index} of ${code.source.id} is not this run's code.`) - } - return ["code", code.source.id, code.index] -} - -const invalid = (message: string): never => { - throw new SnapshotError(`Invalid snapshot: ${message}`) -} - -// A frame as saved, checked against its code before anything runs (§6.5): pc on an instruction, sp within the -// frame's registers, holes only in locals, finally tags in range, a mode it can complete by. Then its registers are -// padded to the code's size and its cells taken from its function. -function restoreFrame(frame: Frame): void { - const code = frame.code as unknown - if (!(code instanceof Code)) return invalid("a frame has no code.") - const regs = frame.regs as unknown - if (!Array.isArray(regs)) return invalid("a frame's registers are not a list.") - const pc = frame.pc - if (!Number.isSafeInteger(pc) || pc < 0 || pc >= code.code.length) - return invalid(`a frame's pc ${pc} is out of range.`) - const sp = frame.sp - if (!Number.isSafeInteger(sp) || sp < code.locals || sp > code.locals + code.maxStack || regs.length !== sp) { - return invalid(`a frame's stack pointer ${sp} is out of range.`) - } - for (let at = code.locals; at < sp; at++) if (regs[at] === HOLE) invalid("a hole is on a frame's operand stack.") - for (let level = 0; level < code.finallyOffsets.length; level++) { - const offset = code.finallyOffsets[level]! - const tag = regs[code.finallies[offset]!] - const targets = code.finallies[offset + 3]! - if ( - tag !== HOLE && - tag !== undefined && - !(Number.isSafeInteger(tag) && (tag as number) >= 0 && (tag as number) < targets) - ) { - invalid(`a frame's finally tag ${String(tag)} is out of range.`) - } - } - if (!(Object.values(Mode) as Array).includes(frame.mode)) - invalid(`a frame's mode ${String(frame.mode)} is unknown.`) - if (frame.mode === Mode.PROGRAM && (code.flags & CodeFlags.PROGRAM) === 0) - invalid("a frame's mode does not fit its code.") - const settles = - frame.mode !== Mode.CALLER && - frame.mode !== Mode.CONSTRUCT && - frame.mode !== Mode.PROGRAM && - frame.mode !== Mode.BOUNDARY_OUT - // A derived constructor's frame holds its new target until `super()` binds `this`. - const newTarget = - frame.mode === Mode.CONSTRUCT && frame.target instanceof Fn && frame.target.klass !== undefined - if (!settles && frame.target !== undefined && !newTarget) invalid("a frame that settles nothing has a target.") - if (frame.mode === Mode.REDO) { - const target = frame.target - if (!(target instanceof Arr) || !Number.isSafeInteger(target.items[0]) || (target.items[0] as number) < 0) - invalid("a getter frame does not say where its op starts.") - } - const fn = frame.fn as unknown - if (fn !== null && !(fn instanceof Fn)) invalid("a frame's function is not a function.") - if (fn instanceof Fn && fn.code !== code) invalid("a frame's function does not run its code.") - if (typeof frame.counted !== "boolean") invalid("a frame's call depth flag is not a boolean.") - if (frame.args !== undefined && !Array.isArray(frame.args)) invalid("a frame's arguments are not a list.") - for (let at = sp, size = code.locals + code.maxStack; at < size; at++) regs.push(HOLE) - frame.cells = fn instanceof Fn ? fn.cells : EMPTY_CELLS -} - -// The job stack, checked: frames only, the program's frame only at the bottom, and a caller under every `CALLER` one. -function restoreStack(vm: Vm): void { - const frames = vm.frames as unknown - if (!Array.isArray(frames) || frames.some((frame) => !(frame instanceof Frame))) - invalid("the job stack is not frames.") - vm.frames.forEach((frame, at) => { - const bottomOnly = frame.mode === Mode.PROGRAM || frame.mode === Mode.BOUNDARY_OUT - const above = frame.mode === Mode.CALLER || frame.mode === Mode.REDO || frame.mode === Mode.CONSTRUCT - if ((at === 0 && above) || (at > 0 && bottomOnly)) invalid("a frame is out of place on the job stack.") - // A getter frame's op runs again in the frame under it. - if ( - frame.mode === Mode.REDO && - at > 0 && - ((frame.target as Arr).items[0] as number) >= vm.frames[at - 1]!.code.code.length - ) - invalid("a getter frame's op is outside its caller's code.") - }) - if (!Number.isSafeInteger(vm.depth) || vm.depth < 0) invalid("the call depth is not a count.") -} - -// A closure's code and cells, checked; its length comes from its code. -function restoreFn(fn: Fn): void { - const code = fn.code as unknown - if (!(code instanceof Code)) return invalid("a closure has no code.") - const cells = fn.cells as unknown - if ( - !Array.isArray(cells) || - cells.length !== code.captures.length >>> 1 || - cells.some((cell) => !(cell instanceof Cell)) - ) { - invalid("a closure's cells do not match its captures.") - } - Object.assign(fn, { length: code.length }) -} diff --git a/packages/codemode/src/language/snapshot/codec.ts b/packages/codemode/src/language/snapshot/codec.ts deleted file mode 100644 index d0b0bfc5274..00000000000 --- a/packages/codemode/src/language/snapshot/codec.ts +++ /dev/null @@ -1,1112 +0,0 @@ -import type { DurableFn, Fn } from "../host-function.js" -import { Interpreter } from "../runtime/interpreter.js" -import { - type AstNode, - AsyncIteratorSymbol, - HostFailure, - IteratorSymbol, - Lost, - lostError, - PendingThrow, - Throw, -} from "../runtime/model.js" -import { - accessorFunction, - accessorHalf, - Arguments, - Arr, - BoundFn, - Callable, - type Getter, - isProgramAccessor, - type Setter, - Bytes, - changed, - DateObj, - ErrorObj, - StackSlot, - GeneratorObj, - HeadersObj, - HostNamespace, - IteratorObj, - MapObj, - Native, - Obj, - Position, - PromiseObj, - RegExpObj, - Resolver, - SetObj, - type Slot, - URLObj, - type Value, - URLSearchParamsObj, - WeakMapObj, - WeakSetObj, -} from "../runtime/objects.js" -import { Convert, Interruption, Invoke, Prefetch } from "../runtime/signals.js" -import { deleted, OrderedTable } from "../runtime/table.js" -import { AsyncFromSyncIterator } from "../generators.js" -import { HostCall, Resolving } from "../scheduler.js" -import { BufferObj } from "../stdlib/buffer.js" -import { TextDecoderObj } from "../stdlib/bytes.js" - -// A graph codec for a run's state: every object reachable from the roots becomes one record, so identity, sharing, -// and cycles survive, and every value inside a record is tagged JSON. Built-ins, AST nodes, bytecode, and the VM's -// own objects are named rather than copied; a value with no data form (a live host function, say) becomes a `Lost` -// placeholder. Nothing here evaluates anything: decoding only allocates and assigns. - -/** A plain JSON value, as a snapshot holds it. */ -export type Json = null | boolean | number | string | ReadonlyArray | { readonly [key: string]: Json } - -/** - * A value inside a record: a JSON primitive, or a tag (an array whose first item says what it is): - * - `["u"]` undefined, `["n", "NaN" | "Infinity" | "-Infinity" | "-0"]` a number JSON cannot spell, `["-"]` an absent - * field, `["h"]` an array hole; - * - `["s", name]` an interpreter symbol; - * - `["i", name]` a built-in or host global, unchanged since the runtime was made; - * - `["a", source, index]` an AST node (a call site, an error's location); - * - `["x", data]` something the VM names itself (compiled code, by source and function index); - * - `["r", id]` another record. - */ -export type Encoded = string | number | boolean | null | ReadonlyArray - -/** One object of the graph. `t` says how to read the rest. */ -export type Record = { readonly t: string; readonly [field: string]: Json } - -/** A saved state can't be read, or doesn't fit this runtime. */ -export class SnapshotError extends Error { - override readonly name = "SnapshotError" -} - -/** - * Where a function inside a value a host function returned came from, so a saved state can name it instead of losing - * it: the host function whose `snapshot` hooks save that value (`owner`, by label), the value (`root`), and the path - * from there to the function. - */ -export type HostOrigin = { - readonly owner: string - readonly root: object - readonly path: ReadonlyArray - /** What the program calls it, for its errors (`fetch.text`). */ - readonly label: string -} - -/** - * How a run meets its host globals (see `hostGlobals`): values crossing in each direction, calling host functions, and - * saving and restoring the functions inside values they returned. - */ -export type HostBridge = { - /** What a saved state must find again on resume: the host functions with `snapshot` hooks, and the namespaces. */ - readonly shape: ReadonlyArray - /** - * Program values as host values, for a call's arguments. When the runtime awaits promises in arguments, one that - * hasn't fulfilled goes in `waiting` instead, and the arguments are to cross again once it settles. A function - * inside a result crosses back as its host function and is added to `back`; without `back` it is treated like any - * function. - */ - readonly toHost: ( - values: ReadonlyArray, - label: string, - waiting: Array, - back: Array | undefined, - ) => ReadonlyArray - /** A host value as a program value, for what a call returned; `owner`'s `snapshot` hooks can save it. */ - readonly fromHost: (value: unknown, label: string, owner: string | undefined) => Value - /** What a call's failure is to the program. */ - readonly failure: (reason: unknown, label: string) => unknown - /** Whether a call's result is still pending: a Promise or an Effect. */ - readonly isPending: (value: unknown) => boolean - /** Calls a host function now: its value, what it left pending, or the Effect to block on. */ - readonly invoke: ( - fn: Fn, - args: ReadonlyArray, - key: string, - label: string, - ) => - | { readonly kind: "value"; readonly value: unknown } - | { readonly kind: "pending" | "block"; readonly work: unknown } - /** The host function at `path` among the run's host globals, for a resumed call. */ - readonly resolve: (path: ReadonlyArray) => Fn | DurableFn | undefined - /** Where a program function wrapping a host function came from, when its owner can save it. */ - readonly origin: (value: object) => HostOrigin | undefined - /** A returned value as its owner saves it. */ - readonly encode: (owner: string, root: object) => unknown - /** A returned value back from what `encode` gave. */ - readonly decode: (owner: string, data: unknown) => object - /** Makes `target`, a restored program function, call the host function `origin` leads to. */ - readonly rewrap: (target: Native, origin: HostOrigin) => void -} - -/** What the encoder asks of the runtime whose state it saves. */ -export type EncodeEnv = { - /** The name of a built-in or host global object. */ - readonly nameOf: (value: Obj) => string | undefined - /** Whether a named object is still as the runtime made it, so its name alone restores it. */ - readonly unchanged: (value: Obj) => boolean - /** The anchors: objects the restored runtime already has, filled in place (the VM, its scheduler, ...). */ - readonly anchorOf: (value: object) => string | undefined - readonly nodeId: (node: AstNode) => readonly [source: string, index: number] | undefined - /** Values with no data form are reported here; strict encoding throws on the first instead. */ - readonly lost: Array - readonly strict: boolean - readonly hosts?: HostBridge | undefined - /** More classes to save (the VM's frames and closures), after the built-in ones. */ - readonly specs?: ReadonlyArray | undefined - /** The data the VM names an object or symbol by, saved as `["x", data]`, instead of copying it. */ - readonly external?: ((value: object | symbol) => Json | undefined) | undefined -} - -/** What the decoder asks of the fresh runtime it restores into. */ -export type DecodeEnv = { - readonly named: (name: string) => Obj | undefined - readonly anchor: (name: string) => object | undefined - readonly node: (source: string, index: number) => AstNode | undefined - /** An `Interruption` (it holds an Effect cause, which this module does not make). */ - readonly interruption: () => Interruption - readonly hosts?: HostBridge | undefined - readonly specs?: ReadonlyArray | undefined - /** What `EncodeEnv.external` named. */ - readonly external?: ((data: Json) => unknown) | undefined -} - -// --- Registries --- - -const symbols = new Map([ - ["iterator", IteratorSymbol], - ["asyncIterator", AsyncIteratorSymbol], - ["deleted", deleted], -]) -const symbolNames = new Map([...symbols].map(([name, symbol]) => [symbol, name])) - -/** How one class saves: its own fields in order, and how a restored instance is made whole. */ -export type ClassSpec = { - readonly name: string - readonly ctor: Function - /** Saved fields, in the order a constructor makes them. */ - readonly fields: ReadonlyArray - /** Own fields that are not saved: caches and runtime configuration, set to `reset`'s values. */ - readonly skip?: ReadonlyArray - /** Own fields with the same value on every instance. */ - readonly constants?: Readonly<{ [field: string]: unknown }> - /** An `Obj`: its prototype, extensibility, and properties are saved too. */ - readonly obj?: boolean - /** The restored runtime already has this object; it is filled in place. */ - readonly anchor?: string - /** Sets fields that are not saved, once the saved ones are in. */ - readonly reset?: (value: never) => void - /** The saved fields' values, when they are not the own fields as they are (a frame saves its live registers only). */ - readonly view?: (value: never) => ReadonlyArray -} - -// `intrinsic` is not saved: a restored object is the program's, or a named intrinsic that keeps its own. -const objFields = ["props", "extensible", "proto", "intrinsic"] -const callable = { tag: "Function" } - -// Built on first use: the VM's modules and this one import each other, so the classes aren't there at load time. -const builtinSpecs = (): ReadonlyArray => [ - { name: "Obj", ctor: Obj, fields: [], obj: true, constants: { tag: "Object" } }, - { name: "Arr", ctor: Arr, fields: ["items", "elements"], obj: true, constants: { tag: "Array" } }, - { name: "ErrorObj", ctor: ErrorObj, fields: ["failure"], obj: true, constants: { tag: "Error" } }, - { name: "Arguments", ctor: Arguments, fields: [], obj: true, constants: { tag: "Arguments" } }, - // Only named natives are saved (by name); an unnamed one is a host function, saved as `LostNative`. - { name: "Native", ctor: Native, fields: [], skip: ["length", "call", "construct", "callback"], obj: true }, - { - name: "BoundFn", - ctor: BoundFn, - fields: ["length", "target", "boundThis", "boundArgs"], - obj: true, - constants: { ...callable, construct: undefined, callback: true }, - }, - { - name: "Resolver", - ctor: Resolver, - fields: ["length", "resolving", "kind"], - obj: true, - constants: { ...callable, construct: undefined, callback: true }, - }, - { - name: "PromiseObj", - ctor: PromiseObj, - fields: ["state", "result", "reactions", "handled", "id"], - obj: true, - constants: { tag: "Promise" }, - }, - { - name: "GeneratorObj", - ctor: GeneratorObj, - fields: ["state", "frame", "queue", "asynchronous"], - obj: true, - constants: { tag: "Generator" }, - }, - { name: "IteratorObj", ctor: IteratorObj, fields: ["cursor"], obj: true, constants: { tag: "Iterator" } }, - { name: "DateObj", ctor: DateObj, fields: ["time"], obj: true, constants: { tag: "Date" } }, - { - name: "RegExpObj", - ctor: RegExpObj, - fields: ["source", "flags", "lastIndex"], - skip: ["compiled"], - obj: true, - constants: { tag: "RegExp" }, - reset: (value: { compiled: unknown }) => { - value.compiled = undefined - }, - }, - { name: "MapObj", ctor: MapObj, fields: ["map"], obj: true, constants: { tag: "Map" } }, - { name: "SetObj", ctor: SetObj, fields: ["set"], obj: true, constants: { tag: "Set" } }, - { name: "WeakMapObj", ctor: WeakMapObj, fields: ["map"], obj: true, constants: { tag: "WeakMap" } }, - { name: "WeakSetObj", ctor: WeakSetObj, fields: ["set"], obj: true, constants: { tag: "WeakSet" } }, - { - name: "URLSearchParamsObj", - ctor: URLSearchParamsObj, - fields: ["params"], - obj: true, - constants: { tag: "URLSearchParams" }, - }, - { name: "HeadersObj", ctor: HeadersObj, fields: ["headers"], obj: true, constants: { tag: "Headers" } }, - { name: "URLObj", ctor: URLObj, fields: ["searchParams", "url"], obj: true, constants: { tag: "URL" } }, - { name: "Bytes", ctor: Bytes, fields: ["bytes"], obj: true, constants: { tag: "Uint8Array" } }, - { name: "BufferObj", ctor: BufferObj, fields: ["bytes"], obj: true, constants: { tag: "Uint8Array" } }, - { - name: "TextDecoderObj", - ctor: TextDecoderObj, - fields: ["decoder", "ignoreBOM", "queued", "seen"], - obj: true, - constants: { tag: "Object" }, - }, - { - name: "AsyncFromSyncIterator", - ctor: AsyncFromSyncIterator, - fields: ["sync", "site"], - obj: true, - constants: { tag: "AsyncFromSyncIterator" }, - }, - { name: "Position", ctor: Position, fields: ["index", "done", "source", "kind", "arrays"] }, - { - name: "OrderedTable", - ctor: OrderedTable, - fields: ["keys", "values", "cursors", "tombstones", "pruneAt"], - skip: ["index"], - // The index is derived from the keys. - reset: (table: { keys: Array; index: Map }) => { - table.index = new Map() - table.keys.forEach((key, at) => { - if (key !== deleted) table.index.set(key, at) - }) - }, - }, - { - name: "HostCall", - ctor: HostCall, - fields: [ - "status", - "data", - "id", - "key", - "label", - "path", - "owner", - "policy", - "args", - "blocking", - "resolving", - "site", - ], - skip: ["fn", "work", "holdsFunctions"], - // A call holding host functions is never saved. - reset: (call: { holdsFunctions: boolean }) => { - call.holdsFunctions = false - }, - }, - { name: "Resolving", ctor: Resolving, fields: ["done", "scheduler", "promise", "site"] }, - { name: "Throw", ctor: Throw, fields: ["value"] }, - { name: "PendingThrow", ctor: PendingThrow, fields: ["type", "message", "kind", "suggestions", "node", "value"] }, - { name: "Convert", ctor: Convert, fields: ["hints", "values", "ordinal", "coerce"] }, - { name: "Prefetch", ctor: Prefetch, fields: ["reads"] }, - { name: "Invoke", ctor: Invoke, fields: ["callable", "thisValue", "args", "site"] }, - { name: "HostNamespace", ctor: HostNamespace, fields: ["root", "path"] }, - { name: "Lost", ctor: Lost, fields: ["description"] }, - { - name: "Interpreter", - ctor: Interpreter, - anchor: "ctx", - fields: ["logs", "globalScope", "modules", "namespaces"], - skip: ["builtins", "vm", "intrinsics", "hosts", "hostNamespaces", "moduleGlobals", "sources", "prelude"], - }, -] - -let builtins: { readonly byCtor: Map; readonly byName: Map } | undefined - -const builtinRegistry = () => { - if (builtins !== undefined) return builtins - const specs = builtinSpecs() - builtins = { - byCtor: new Map(specs.map((spec) => [spec.ctor, spec])), - byName: new Map(specs.map((spec) => [spec.name, spec])), - } - return builtins -} - -// A function a host function returned while the program ran, which has no data form: saved as `LostNative`. -const hostFunction: ClassSpec = { - name: "LostNative", - ctor: Native, - fields: ["length"], - obj: true, - constants: callable, -} - -/** Host error classes that can travel as a failure, by name. */ -const errorClasses = new Map([ - ["Error", Error], - ["TypeError", TypeError], - ["RangeError", RangeError], - ["SyntaxError", SyntaxError], - ["ReferenceError", ReferenceError], - ["EvalError", EvalError], - ["URIError", URIError], - ["HostFailure", HostFailure], -]) -const errorNames = new Map([...errorClasses].map(([name, ctor]) => [ctor, name])) - -/** The names of every class with a codec: a build that saves a different set cannot read this one's snapshots. */ -export const codecShape = (extra: ReadonlyArray = []): string => - JSON.stringify([[...builtinSpecs(), ...extra].map((spec) => [spec.name, spec.fields]), [...symbols.keys()]]) - -const registry = (extra: ReadonlyArray | undefined) => { - const { byCtor, byName } = builtinRegistry() - return extra === undefined || extra.length === 0 - ? { byCtor, byName } - : { - byCtor: new Map([...byCtor, ...extra.map((spec) => [spec.ctor, spec] as const)]), - byName: new Map([...byName, ...extra.map((spec) => [spec.name, spec] as const)]), - } -} - -// --- Encoding --- - -/** Encodes everything reachable from `roots`: the roots' values and the records they refer to. */ -export const encode = ( - roots: ReadonlyArray, - env: EncodeEnv, -): { readonly roots: Array; readonly records: Array } => { - const encoder = new Encoder(env) - const encoded = roots.map((root) => encoder.value(root)) - encoder.drain() - return { roots: encoded, records: encoder.records as Array } -} - -class Encoder { - readonly records: Array = [] - private readonly ids = new Map() - private readonly work: Array = [] - // A URL's `searchParams` is the same host object its URLSearchParams wraps; it is encoded once every URL is known. - private readonly owners = new Map() - private readonly params: Array = [] - // One `HostValue` record per value a host function returned, however many of its functions the state holds. - private readonly roots = new Map() - private readonly specs: { readonly byCtor: Map; readonly byName: Map } - - constructor(private readonly env: EncodeEnv) { - this.specs = registry(env.specs) - } - - value(value: unknown): Encoded { - switch (typeof value) { - case "string": - case "boolean": - return value - case "undefined": - return ["u"] - case "number": - if (Number.isFinite(value) && !Object.is(value, -0)) return value - return ["n", Object.is(value, -0) ? "-0" : String(value)] - case "symbol": { - const name = symbolNames.get(value) - const external = name === undefined ? this.env.external?.(value) : undefined - if (external !== undefined) return ["x", external] - if (name === undefined) throw new SnapshotError(`Codec gap: the symbol ${String(value)} has no name.`) - return ["s", name] - } - case "bigint": - throw new SnapshotError("Codec gap: a bigint has no data form.") - } - if (value === null) return null - const object = value as object - const external = this.env.external?.(object) - if (external !== undefined) return ["x", external] - if (object instanceof Obj) { - const name = this.env.nameOf(object) - if (name !== undefined && this.env.unchanged(object)) return ["i", name] - } else if (!Array.isArray(object)) { - const node = this.env.nodeId(object as AstNode) - if (node !== undefined) return ["a", node[0], node[1]] - } - return this.ref(object) - } - - drain(): void { - for (let object = this.work.shift(); object !== undefined; object = this.work.shift()) { - const id = this.ids.get(object)! - this.records[id] = this.record(object, id) - } - for (const [id, params] of this.params) { - const owner = this.owners.get(params) - this.records[id] = - owner === undefined - ? { t: "URLSearchParams", s: params.toString() } - : { t: "URLSearchParams", o: this.ref(owner) } - } - } - - private ref(object: object): Encoded { - const known = this.ids.get(object) - if (known !== undefined) return ["r", known] - const id = this.records.length - this.ids.set(object, id) - this.records.push(undefined) - this.work.push(object) - return ["r", id] - } - - private record(object: object, id: number): Record | undefined { - if (object instanceof Obj) { - const name = this.env.nameOf(object) - if (name !== undefined) { - const spec = this.spec(object) - return { t: "@", n: name, c: spec.name, ...this.fields(object, spec) } - } - } - if (Array.isArray(object)) { - // A sparse array (`length` can be ten million with nothing in it) saves only the indexes it has. - if (object.length > 1024) { - const present = Object.keys(object) - if (present.length * 2 < object.length) { - const entries: Array = [] - for (const key of present) entries.push(Number(key), this.value(object[Number(key)])) - return { t: "Array", l: object.length, s: entries } - } - } - const items: Array = [] - for (let at = 0; at < object.length; at++) items.push(at in object ? this.value(object[at]) : ["h"]) - return { t: "Array", v: items } - } - if (object instanceof Map) { - const entries: Array = [] - for (const [key, item] of object) entries.push(this.value(key), this.value(item)) - const anchor = this.env.anchorOf(object) - return anchor === undefined ? { t: "Map", e: entries } : { t: "Map", e: entries, a: anchor } - } - if (object instanceof Set) return { t: "Set", e: [...object].map((item) => this.value(item)) } - const spec = this.specs.byCtor.get(object.constructor) - if (spec !== undefined && spec.name !== "Native") { - if (spec.anchor !== undefined && this.env.anchorOf(object) !== spec.anchor) { - throw new SnapshotError(`Codec gap: a second ${spec.name} is reachable from the state.`) - } - return { t: spec.name, ...this.fields(object, spec) } - } - if (object instanceof Native) { - // A host function made while the program ran: inside a value a host function returned. That function saves the - // value when it has `snapshot` hooks; otherwise its name says what was lost, which never fails a strict save. - const origin = this.env.hosts?.origin(object) - if (origin !== undefined) { - const root = this.hostValue(origin.owner, origin.root) - const fields = this.fields(object, hostFunction, hostFunction.fields) - return { t: "HostFunction", e: origin.owner, h: root, k: [...origin.path], l: origin.label, ...fields } - } - this.env.lost.push(`the function ${functionName(object)}`) - return { t: "LostNative", ...this.fields(object, hostFunction, hostFunction.fields) } - } - const proto = Object.getPrototypeOf(object) - if (proto === Object.prototype || proto === null) { - const entries: Array = [] - for (const key of Object.keys(object)) entries.push(key, this.value((object as { [key: string]: unknown })[key])) - return proto === null ? { t: "Object", e: entries, n: 1 } : { t: "Object", e: entries } - } - if (object instanceof Error) return this.error(object) - if (object instanceof Interruption) return { t: "Interruption" } - if (object instanceof URL) { - this.owners.set(object.searchParams, object) - return { t: "URL", h: object.href } - } - if (object instanceof URLSearchParams) { - this.params.push([id, object]) - return undefined - } - if (object instanceof Date) return { t: "Date", v: this.value(object.getTime()) } - if (object instanceof RegExp) return { t: "RegExp", s: object.source, f: object.flags } - if (object instanceof Headers) return { t: "Headers", e: [...object].map(([key, item]) => [key, item]) } - if (object instanceof Uint8Array) { - return { t: "Uint8Array", b: this.ref(object.buffer), o: object.byteOffset, l: object.length } - } - if (object instanceof ArrayBuffer) return { t: "ArrayBuffer", d: base64(new Uint8Array(object)) } - if (object instanceof TextDecoder) return { t: "TextDecoder", f: object.fatal, i: object.ignoreBOM } - const what = typeof object === "function" ? "a host function" : `a host ${object.constructor?.name ?? "object"}` - this.lose(what) - return { t: "Lost", f: [what] } - } - - // A value a host function returned, as its `snapshot.encode` saves it: plain data, checked before it is copied. - private hostValue(owner: string, root: object): Encoded { - const known = this.roots.get(root) - if (known !== undefined) return known - const data = plainData(this.env.hosts!.encode(owner, root), owner, new Set()) - const id = this.records.length - const ref: Encoded = ["r", id] - this.roots.set(root, ref) - this.records.push(undefined) - this.records[id] = { t: "HostValue", e: owner, d: this.value(data) } - return ref - } - - private lose(what: string): void { - if (this.env.strict) throw new SnapshotError(`Codec gap: ${what} has no data form.`) - this.env.lost.push(what) - } - - private spec(object: object): ClassSpec { - const spec = this.specs.byCtor.get(object.constructor) - if (spec === undefined) throw new SnapshotError(`Codec gap: ${object.constructor.name} has no codec.`) - return spec - } - - // A class instance's saved fields, positional, with its `Obj` header when it is one. Fields the spec does not know - // are a codec gap: they would be silently dropped. - private fields(object: object, spec: ClassSpec, only?: ReadonlyArray): { [field: string]: Json } { - const record = object as { [field: string]: unknown } - const fields = only ?? spec.fields - if (only === undefined && spec.view === undefined) { - for (const key of Object.keys(object)) { - if (fields.includes(key) || spec.skip?.includes(key) || (spec.constants !== undefined && key in spec.constants)) - continue - if (spec.obj && (objFields.includes(key) || key === "tag" || key === "hasProgramAccessors")) continue - throw new SnapshotError(`Codec gap: ${spec.name}.${key} is not saved.`) - } - } - const values = - only === undefined && spec.view !== undefined - ? spec.view(object as never).map((item) => this.value(item)) - : fields.map((field) => (Object.hasOwn(object, field) ? this.value(record[field]) : ["-"])) - if (!(object instanceof Obj)) return { f: values } - const props: Array = [] - for (const [key, slot] of object.props) { - props.push(typeof key === "symbol" ? this.value(key) : key) - // An error's `stack` not read yet stays unformatted: its header is the error's name and message when it is. - if (slot instanceof StackSlot && slot.trace !== undefined) { - props.push(slot.trace, 16 | (slot.writable ? 1 : 0) | (slot.enumerable ? 2 : 0) | (slot.configurable ? 4 : 0)) - } else if ("value" in slot) { - props.push( - this.value(slot.value), - (slot.writable ? 1 : 0) | (slot.enumerable ? 2 : 0) | (slot.configurable ? 4 : 0), - ) - } else { - props.push( - [this.accessorHalf(slot.get, key), this.accessorHalf(slot.set, key)], - 8 | (slot.enumerable ? 2 : 0) | (slot.configurable ? 4 : 0), - ) - } - } - return { f: values, p: object.proto === null ? null : this.value(object.proto), x: object.extensible, o: props } - } - - // An accessor half: a program function as itself, a native one as its companion (a named intrinsic). - private accessorHalf(half: Getter | Setter | Callable | undefined, key: string | symbol): Encoded { - const fn = accessorFunction(half) - if (half !== undefined && fn === undefined) { - this.lose(`the native accessor ${String(key)}`) - return this.value(undefined) - } - return this.value(fn) - } - - private error(error: Error): Record { - const name = errorNames.get(error.constructor) - if (name === undefined) { - // A failure only ever reaches the program when it is thrown, so it is saved as what throwing a lost value does. - this.lose(`a host ${error.constructor.name}`) - return { - t: "PendingThrow", - ...this.fields( - lostError(`An error of class ${error.constructor.name}`), - this.specs.byName.get("PendingThrow")!, - ), - } - } - const fields: Array = [] - for (const key of Object.keys(error)) { - if (key === "message" || key === "stack") continue - fields.push(key, this.value((error as unknown as { [key: string]: unknown })[key])) - } - return { t: "Error", c: name, m: error.message, e: fields } - } -} - -// --- Decoding --- - -/** Rebuilds the graph `encode` saved, filling anchors in place: the decoded roots. */ -export const decode = ( - saved: { readonly roots: ReadonlyArray; readonly records: ReadonlyArray }, - env: DecodeEnv, -): Array => { - const decoder = new Decoder(saved.records, env) - for (let id = 0; id < saved.records.length; id++) decoder.shell(id) - for (let id = 0; id < saved.records.length; id++) decoder.fill(id) - decoder.finish() - return saved.roots.map((root) => decoder.value(root)) -} - -const invalid = (message: string): never => { - throw new SnapshotError(`Invalid snapshot: ${message}`) -} - -const isRecord = (value: unknown): value is { readonly t: string; readonly [field: string]: unknown } => - typeof value === "object" && - value !== null && - !Array.isArray(value) && - typeof (value as { t?: unknown }).t === "string" - -const list = (value: unknown, what: string): ReadonlyArray => - Array.isArray(value) ? value : invalid(`${what} is not a list.`) - -const text = (value: unknown, what: string): string => - typeof value === "string" ? value : invalid(`${what} is not text.`) - -const count = (value: unknown, what: string): number => - Number.isSafeInteger(value) && (value as number) >= 0 ? (value as number) : invalid(`${what} is not a count.`) - -const forbidden = new Set(["__proto__", "constructor", "prototype"]) - -class Decoder { - private readonly shells: Array - private readonly filled: Array - // Derived state is rebuilt once every record is filled in, since it reads other records. - private readonly resets: Array<() => void> = [] - // Functions inside values host functions returned, wrapped again once every record is filled in. - private readonly hostFunctions: Array = [] - // Those values, given back once each by their owner's `snapshot.decode`, by `HostValue` record. - private readonly hostValues = new Map() - private readonly specs: { readonly byCtor: Map; readonly byName: Map } - - constructor( - private readonly records: ReadonlyArray, - private readonly env: DecodeEnv, - ) { - this.specs = registry(env.specs) - this.shells = new Array(records.length) - this.filled = new Array(records.length).fill(false) - } - - private at(id: number): { readonly t: string; readonly [field: string]: unknown } { - const record = this.records[id] - return isRecord(record) ? record : invalid(`record ${id} is malformed.`) - } - - // Allocates the object a record restores, before anything is filled in, so references and cycles resolve. - shell(id: number): object { - const known = this.shells[id] - if (known !== undefined) return known - const record = this.at(id) - const made = this.make(record, id) - this.shells[id] = made - return made - } - - private make(record: { readonly t: string; readonly [field: string]: unknown }, id: number): object { - switch (record.t) { - case "Array": - return [] - case "Object": - return record.n === 1 ? Object.create(null) : {} - case "Map": - return record.a === undefined ? new Map() : this.anchor(text(record.a, "an anchor"), Map) - case "Set": - return new Set() - case "@": { - const name = text(record.n, "a built-in name") - const named = this.env.named(name) - if (named === undefined) return invalid(`this runtime has no built-in or host global named ${name}.`) - const spec = this.classSpec(record.c) - if (named.constructor !== spec.ctor) return invalid(`${name} is not a ${spec.name} in this runtime.`) - return named - } - case "LostNative": - case "HostFunction": - return Object.create(Native.prototype) - case "HostValue": - return {} - case "Interruption": - return this.env.interruption() - case "Error": { - const name = text(record.c, "an error class") - const ctor = errorClasses.get(name) ?? invalid(`unknown error class ${name}.`) - const message = text(record.m, "an error message") - const made = Object.create(ctor.prototype) as Error - Object.defineProperty(made, "message", { - value: message, - writable: true, - configurable: true, - enumerable: false, - }) - return made - } - case "Date": { - const time = this.value(record.v) - return new Date(typeof time === "number" ? time : invalid(`record ${id} is not a time.`)) - } - case "RegExp": - return new RegExp(text(record.s, "a pattern"), text(record.f, "flags")) - case "URL": - return new URL(text(record.h, "a URL")) - case "URLSearchParams": { - if (record.o === undefined) return new URLSearchParams(text(record.s, "search params")) - const owner = this.value(record.o) - return owner instanceof URL ? owner.searchParams : invalid(`record ${id} names no URL.`) - } - case "Headers": { - const entries = list(record.e, "headers").map((entry) => { - const pair = list(entry, "a header") - return [text(pair[0], "a header name"), text(pair[1], "a header value")] as [string, string] - }) - return new Headers(entries) - } - case "ArrayBuffer": - return fromBase64(text(record.d, "bytes")).buffer - case "Uint8Array": { - const buffer = this.value(record.b) - if (!(buffer instanceof ArrayBuffer)) return invalid(`record ${id} names no buffer.`) - const offset = count(record.o, "a byte offset") - const length = count(record.l, "a byte length") - if (offset + length > buffer.byteLength) return invalid(`record ${id} reaches past its buffer.`) - return new Uint8Array(buffer, offset, length) - } - case "TextDecoder": - return new TextDecoder("utf-8", { fatal: record.f === true, ignoreBOM: record.i === true }) - } - const spec = this.classSpec(record.t) - if (spec.name === "Native") return invalid("a native is saved only by name.") - if (spec.anchor !== undefined) return this.anchor(spec.anchor, spec.ctor) - return Object.create(spec.ctor.prototype) - } - - private anchor(name: string, ctor: Function): object { - const anchor = this.env.anchor(name) - if (anchor === undefined || anchor.constructor !== ctor) return invalid(`unknown anchor ${name}.`) - return anchor - } - - private classSpec(name: unknown): ClassSpec { - return this.specs.byName.get(text(name, "a class")) ?? invalid(`unknown record kind ${String(name)}.`) - } - - fill(id: number): void { - if (this.filled[id]) return - this.filled[id] = true - const record = this.at(id) - const target = this.shell(id) as { [field: string]: unknown } - switch (record.t) { - case "Array": { - const array = target as unknown as Array - if (record.v === undefined) { - const length = count(record.l, "an array length") - if (length > 4_294_967_295) invalid("an array is too long.") - array.length = length - const entries = list(record.s, "a sparse array") - for (let at = 0; at < entries.length; at += 2) { - const index = count(entries[at], "an array index") - if (index >= length) invalid("an array index is past its length.") - array[index] = this.value(entries[at + 1]) - } - return - } - const items = list(record.v, "an array") - items.forEach((item, at) => { - if (Array.isArray(item) && item[0] === "h") return - array[at] = this.value(item) - }) - array.length = items.length - return - } - case "Object": - case "Error": { - const entries = list(record.e, record.t === "Error" ? "an error" : "an object") - for (let at = 0; at < entries.length; at += 2) { - const key = text(entries[at], "a key") - if (record.t === "Error" && forbidden.has(key)) invalid(`an error field is named ${key}.`) - Object.defineProperty(target, key, { - value: this.value(entries[at + 1]), - writable: true, - enumerable: true, - configurable: true, - }) - } - return - } - case "Map": { - const map = target as unknown as Map - if (record.a !== undefined) map.clear() - const entries = list(record.e, "a map") - for (let at = 0; at < entries.length; at += 2) map.set(this.value(entries[at]), this.value(entries[at + 1])) - return - } - case "Set": { - const set = target as unknown as Set - for (const item of list(record.e, "a set")) set.add(this.value(item)) - return - } - case "@": - this.fillClass(target, record, this.classSpec(record.c), true) - // Changed before it was saved, so it stays changed: a later save records it again. - return changed(target as unknown as Obj) - case "LostNative": { - this.fillClass(target, record, hostFunction, false) - const native = target as unknown as { tag: string; call: unknown; construct: unknown; callback: boolean } - const name = functionName(target as unknown as Obj) - native.tag = "Function" - native.call = (_: unknown, __: unknown, site: AstNode | undefined) => { - throw lostError(`The function ${name}`, site) - } - native.construct = undefined - native.callback = true - return - } - case "HostFunction": - this.fillClass(target, record, hostFunction, false) - this.hostFunctions.push([target as unknown as Native, record]) - return - case "HostValue": - case "Interruption": - case "Date": - case "RegExp": - case "URL": - case "URLSearchParams": - case "Headers": - case "ArrayBuffer": - case "Uint8Array": - case "TextDecoder": - return - } - const spec = this.classSpec(record.t) - this.fillClass(target, record, spec, false) - } - - private fillClass( - target: { [field: string]: unknown }, - record: { readonly [field: string]: unknown }, - spec: ClassSpec, - named: boolean, - only?: ReadonlyArray, - ): void { - const fields = only ?? spec.fields - const values = list(record.f, `the fields of a ${spec.name}`) - if (values.length !== fields.length) invalid(`a ${spec.name} has ${values.length} fields, not ${fields.length}.`) - if (spec.obj || named) this.fillObj(target as unknown as Obj, record) - if (spec.constants !== undefined) Object.assign(target, spec.constants) - fields.forEach((field, at) => { - const value = values[at] - if (Array.isArray(value) && value[0] === "-") { - delete target[field] - return - } - target[field] = this.value(value) - }) - const reset = spec.reset - if (reset !== undefined) this.resets.push(() => reset(target as never)) - } - - finish(): void { - for (const reset of this.resets) reset() - if (this.hostFunctions.length === 0) return - const hosts = - this.env.hosts ?? invalid("a function a host function returned is saved, and this runtime has no host globals.") - for (const [target, record] of this.hostFunctions) { - const owner = text(record.e, "a host function") - const path = list(record.k, "a path").map((key) => - typeof key === "number" ? count(key, "a path index") : text(key, "a path key"), - ) - hosts.rewrap(target, { - owner, - root: this.hostValue(hosts, record.h, owner), - path, - label: text(record.l, "a label"), - }) - } - } - - // A value a host function returned, given back once by its `snapshot.decode` from the data it saved. - private hostValue(hosts: HostBridge, ref: unknown, owner: string): object { - const id = - Array.isArray(ref) && ref[0] === "r" ? count(ref[1], "a record id") : invalid("a host value is not a record.") - const known = this.hostValues.get(id) - if (known !== undefined) return known - const record = id < this.records.length ? this.at(id) : invalid(`record ${id} does not exist.`) - if (record.t !== "HostValue" || record.e !== owner) invalid(`record ${id} is not a value of ${owner}.`) - const root = hosts.decode(owner, this.value(record.d)) - this.hostValues.set(id, root) - return root - } - - // An object's prototype, extensibility, and properties. A native accessor half comes back as its companion's closure. - private fillObj(target: Obj, record: { readonly [field: string]: unknown }): void { - const proto = record.p === null ? null : this.value(record.p) - if (proto !== null && !(proto instanceof Obj)) invalid("a prototype is not an object.") - if (typeof record.x !== "boolean") invalid("an object's extensibility is not a boolean.") - const entries = list(record.o, "an object's properties") - const props = new Map() - for (let at = 0; at < entries.length; at += 3) { - const raw = entries[at] - const key = typeof raw === "string" ? raw : this.value(raw) - if (typeof key !== "string" && typeof key !== "symbol") invalid("a property key is not a string or symbol.") - const flags = count(entries[at + 2], "property flags") - const enumerable = (flags & 2) !== 0 - const configurable = (flags & 4) !== 0 - if ((flags & 8) !== 0) { - const halves = list(entries[at + 1], "an accessor's halves") - if (halves.length !== 2) invalid(`the accessor ${String(key)} does not have two halves.`) - const half = (data: unknown) => { - const fn = this.value(data) - if (fn !== undefined && !(fn instanceof Callable)) invalid(`the accessor ${String(key)} is not a function.`) - return accessorHalf(fn as Callable | undefined) - } - props.set(key as string | symbol, { - get: half(halves[0]) as Getter | Callable | undefined, - set: half(halves[1]) as Setter | Callable | undefined, - enumerable, - configurable, - }) - continue - } - if ((flags & 16) !== 0) { - const trace = entries[at + 1] - if (!(target instanceof ErrorObj) || typeof trace !== "string") - return invalid(`the stack ${String(key)} is not an error's.`) - const slot = new StackSlot(target, trace) - slot.writable = (flags & 1) !== 0 - slot.enumerable = enumerable - slot.configurable = configurable - props.set(key as string | symbol, slot) - continue - } - props.set(key as string | symbol, { - value: this.value(entries[at + 1]) as Value, - writable: (flags & 1) !== 0, - enumerable, - configurable, - }) - } - const writable = target as unknown as { - props: Map - proto: Obj | null - extensible: boolean - intrinsic: number - hasProgramAccessors: boolean - } - writable.intrinsic ??= 0 - writable.props = props - writable.hasProgramAccessors = [...props.values()].some(isProgramAccessor) - writable.extensible = record.x as boolean - writable.proto = proto as Obj | null - } - - value(value: unknown): unknown { - switch (typeof value) { - case "string": - case "boolean": - return value - case "number": - return Number.isFinite(value) ? value : invalid("a number is not finite.") - } - if (value === null) return null - if (!Array.isArray(value)) return invalid("a value is neither JSON data nor a tag.") - switch (value[0]) { - case "u": - return undefined - case "n": - switch (value[1]) { - case "NaN": - return Number.NaN - case "Infinity": - return Number.POSITIVE_INFINITY - case "-Infinity": - return Number.NEGATIVE_INFINITY - case "-0": - return -0 - } - return invalid(`unknown number ${String(value[1])}.`) - case "s": - return symbols.get(text(value[1], "a symbol")) ?? invalid(`unknown symbol ${String(value[1])}.`) - case "x": - return this.env.external?.(value[1] as Json) ?? invalid(`unknown external value ${JSON.stringify(value[1])}.`) - case "i": { - const name = text(value[1], "a built-in name") - return this.env.named(name) ?? invalid(`this runtime has no built-in or host global named ${name}.`) - } - case "a": - return ( - this.env.node(text(value[1], "a source"), count(value[2], "a node index")) ?? - invalid(`no node ${String(value[2])} in source ${String(value[1])}.`) - ) - case "r": { - const id = count(value[1], "a record id") - if (id >= this.records.length) invalid(`record ${id} does not exist.`) - return this.shell(id) - } - } - return invalid(`unknown tag ${String(value[0])}.`) - } -} - -// What a host function's `snapshot.encode` gives must be plain data the codec copies and hands back to `decode`: JSON -// values and Uint8Arrays. Views (such as a `Buffer` slice on a shared slab) are copied into standalone `Uint8Array`s. -const plainData = (data: unknown, owner: string, seen: Set): unknown => { - if (data === null || typeof data === "string" || typeof data === "boolean") return data - if (typeof data === "number" && Number.isFinite(data)) return data - if (data instanceof Uint8Array) { - return data.constructor === Uint8Array && data.byteOffset === 0 && data.byteLength === data.buffer.byteLength - ? data - : new Uint8Array(data) - } - const fail = (what: string): never => { - throw new SnapshotError( - `The host function ${owner} saved a value it returned as data holding ${what}; snapshot.encode must give plain data (JSON values and Uint8Arrays).`, - ) - } - if (typeof data !== "object") { - return fail(data === undefined ? "undefined" : typeof data === "number" ? String(data) : `a ${typeof data}`) - } - if (seen.has(data)) return fail("a circular reference") - const proto = Object.getPrototypeOf(data) - if (!Array.isArray(data) && proto !== Object.prototype && proto !== null) { - const name = (data as { constructor?: { name?: string } }).constructor?.name ?? "object" - return fail(`${/^[AEIOU]/.test(name) ? "an" : "a"} ${name}`) - } - seen.add(data) - if (Array.isArray(data)) { - const out = data.map((item) => plainData(item, owner, seen)) - seen.delete(data) - return out - } - const out: { [key: string]: unknown } = proto === null ? Object.create(null) : {} - for (const [key, item] of Object.entries(data)) out[key] = plainData(item, owner, seen) - seen.delete(data) - return out -} - -const functionName = (fn: Obj): string => { - const slot = fn.props.get("name") - return slot !== undefined && "value" in slot && typeof slot.value === "string" && slot.value !== "" - ? slot.value - : "(anonymous)" -} - -const base64 = (bytes: Uint8Array): string => { - let binary = "" - for (let at = 0; at < bytes.length; at += 0x8000) binary += String.fromCharCode(...bytes.subarray(at, at + 0x8000)) - return btoa(binary) -} - -const fromBase64 = (encoded: string): Uint8Array => { - const binary = atob(encoded) - const bytes = new Uint8Array(binary.length) - for (let at = 0; at < binary.length; at++) bytes[at] = binary.charCodeAt(at) - return bytes -} diff --git a/packages/codemode/src/language/snapshot/snapshot.ts b/packages/codemode/src/language/snapshot/snapshot.ts deleted file mode 100644 index 00eaf88f824..00000000000 --- a/packages/codemode/src/language/snapshot/snapshot.ts +++ /dev/null @@ -1,143 +0,0 @@ -import type { Interpreter } from "../runtime/interpreter.js" -import { type Encoded, type Json, type Record, SnapshotError } from "./codec.js" - -export { SnapshotError } - -/** A snapshot as bytes: UTF-8 JSON. */ -export const toBytes = (snapshot: Snapshot): Uint8Array => new TextEncoder().encode(JSON.stringify(snapshot)) - -/** Reads bytes `toBytes` wrote; `restore` checks what they hold. */ -export const fromBytes = (bytes: Uint8Array): unknown => { - try { - return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)) - } catch (error) { - throw new SnapshotError(`Invalid snapshot: the bytes are not UTF-8 JSON (${String(error)}).`) - } -} - -/** The snapshot format this build writes and reads (see `src/language/snapshot.ts`). */ -export const FORMAT = 3 - -/** - * A suspended run's whole state as JSON: a header that says which build and sources it belongs to and what budget it - * has used, and the graph of records (see codec.ts) rooted at the VM, the interpreter, and the global scope, then - * every built-in or host global the run changed. - */ -export type Snapshot = { - readonly format: typeof FORMAT - readonly header: Header - readonly roots: ReadonlyArray - readonly records: ReadonlyArray -} - -export type Header = { - /** The build that wrote it: the package version, and a hash of the opcodes, the prelude's bytecode, codecs, and built-ins. */ - readonly build: string - /** - * A hash of the host's globals (their names, the namespaces among them, and the host functions with `snapshot` - * hooks), which the restoring runtime must have too. - */ - readonly hosts: string - readonly runId: string - /** The program texts, re-parsed and recompiled on restore, and checked against their hashes and bytecode hashes. */ - readonly sources: ReadonlyArray<{ - readonly id: string - readonly code: string - readonly hash: string - readonly bytecode: string - }> - readonly limits: { - readonly timeoutMs: number | null - readonly maxOutputBytes: number | null - } - /** What the run has used so far, across every resume: active milliseconds. */ - readonly budget: { readonly activeMs: number } - /** The host's own state for the run (`run.metadata`), given back on resume. */ - readonly metadata: Json -} - -export type SnapshotHeader = Header - -export const hostsId = (ctx: Interpreter): string => - hash([...ctx.intrinsics.hosts(), ...(ctx.hosts?.shape ?? [])].join("\n")) - -// --- Validation --- - -const fail = (message: string): never => { - throw new SnapshotError(`Invalid snapshot: ${message}`) -} - -const object = (value: unknown, what: string): { readonly [key: string]: unknown } => - typeof value === "object" && value !== null && !Array.isArray(value) - ? (value as { readonly [key: string]: unknown }) - : fail(`${what} is not an object.`) - -const array = (value: unknown, what: string): ReadonlyArray => - Array.isArray(value) ? value : fail(`${what} is not a list.`) - -const string = (value: unknown, what: string): string => - typeof value === "string" ? value : fail(`${what} is not text.`) - -const number = (value: unknown, what: string): number => - typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : fail(`${what} is not a number.`) - -const json = (value: unknown, what: string): Json => { - if (value === undefined) fail(`${what} is missing.`) - return value as Json -} - -const limit = (value: unknown, what: string): number | null => (value === null ? null : number(value, what)) - -/** A saved state's header, checked in full, before anything is restored. */ -export const header = (saved: unknown): Header => validate(saved).header - -// The header is checked in full; records are checked as they are decoded. -export const validate = (saved: unknown): Snapshot => { - const root = object(saved, "the snapshot") - if (root.format !== FORMAT) fail(`format ${String(root.format)} is not ${FORMAT}.`) - const header = object(root.header, "the header") - const limits = object(header.limits, "the limits") - const budget = object(header.budget, "the budget") - const checked: Header = { - build: string(header.build, "the build"), - hosts: string(header.hosts, "the host globals"), - runId: string(header.runId, "the run id"), - sources: array(header.sources, "the sources").map((item) => { - const source = object(item, "a source") - return { - id: string(source.id, "a source id"), - code: string(source.code, "a source"), - hash: string(source.hash, "a source hash"), - bytecode: string(source.bytecode, "a bytecode hash"), - } - }), - limits: { - timeoutMs: limit(limits.timeoutMs, "timeoutMs"), - maxOutputBytes: limit(limits.maxOutputBytes, "maxOutputBytes"), - }, - budget: { activeMs: number(budget.activeMs, "the active time") }, - metadata: json(header.metadata, "the metadata"), - } - const roots = array(root.roots, "the roots") - if (roots.length < 3) fail("there are fewer than three roots.") - return { - format: FORMAT, - header: checked, - roots: roots as ReadonlyArray, - records: array(root.records, "the records") as ReadonlyArray, - } -} - -// --- Helpers --- - -// FNV-1a over UTF-16 code units, twice with different offsets: a fingerprint, not a security check. -export const hash = (text: string): string => { - let a = 0x811c9dc5 - let b = 0x01000193 ^ 0x9e3779b9 - for (let at = 0; at < text.length; at++) { - const code = text.charCodeAt(at) - a = Math.imul(a ^ code, 0x01000193) - b = Math.imul(b ^ code, 0x01000193) ^ (b >>> 13) - } - return (a >>> 0).toString(16).padStart(8, "0") + (b >>> 0).toString(16).padStart(8, "0") -} diff --git a/packages/codemode/src/language/stdlib/array.ts b/packages/codemode/src/language/stdlib/array.ts deleted file mode 100644 index a4a0952bc9f..00000000000 --- a/packages/codemode/src/language/stdlib/array.ts +++ /dev/null @@ -1,362 +0,0 @@ -import { Invoke } from "../runtime/signals.js" -import type { Builtins } from "../runtime/intrinsics.js" -import { builtinCursor } from "../runtime/operations.js" -import { constructor, methods, prototypeFrom, receiver, iteratorMethods } from "../runtime/native.js" -import { checkArrayLength, checkStringLength, MAX_ARRAY_LENGTH } from "../runtime/limits.js" -import { invalidData, IteratorSymbol, rangeError, typeError } from "../runtime/model.js" -import { - changed, - define, - get, - hidden, - Arr, - Bytes, - GeneratorObj, - Obj, - PromiseObj, - coerceToInteger, - coerceToNumber, - coerceToString, - rejectAddition, - type Value, -} from "../runtime/objects.js" -import { describeValue, rejectCircularInsertion } from "../runtime/references.js" -import { requireCallback, withPrimitives, readsPending, withReads } from "../runtime/callback.js" -import type { Interpreter } from "../runtime/interpreter.js" -import { compareText } from "../runtime/operations.js" - -const arrayLikeSource = (source: Value): { readonly length: number; readonly source: Obj } => { - // JS would treat a promise as an empty array-like; that would hide a missing `await`. - if (source instanceof Obj && !(source instanceof PromiseObj)) { - const length = Math.max(0, coerceToInteger(get(source, "length"))) - checkArrayLength(length) - return { length, source } - } - throw invalidData(`Array.from expects an iterable or array-like value, received ${describeValue(source)}.`) -} - -const iterable = (builtins: Builtins, value: Value) => { - if (builtinCursor(builtins, value) !== undefined) return true - if (!(value instanceof Obj)) return false - const method = get(value, IteratorSymbol) - return method !== undefined && method !== null -} - -const arrayFrom = (ctx: Interpreter, args: Array) => withReads(() => arrayFromReads(ctx, args)) - -// Under `withReads`: an iterator method that is a getter is read before `length` could be. -const arrayFromReads = (ctx: Interpreter, args: Array): Value | Invoke => { - const source = args[0] - const mapper = args.length < 2 || args[1] === undefined ? undefined : requireCallback(args[1], "Array.from") - if (iterable(ctx.builtins, source)) { - return new Invoke(ctx.prelude.fn("arrayFromIterable"), undefined, [source, mapper, args[2]], undefined) - } - if (readsPending()) return undefined - if (source instanceof GeneratorObj) { - throw typeError(`Array.from expects a synchronous iterable or array-like value, received ${describeValue(source)}.`) - } - const arrayLike = arrayLikeSource(source) - if (mapper === undefined) { - return new Arr( - ctx.builtins.Array, - Array.from({ length: arrayLike.length }, (_, index) => get(arrayLike.source, index)), - ) - } - return new Invoke( - ctx.prelude.fn("arrayFromLike"), - undefined, - [arrayLike.source, arrayLike.length, mapper, args[2]], - undefined, - ) -} - -/** Where a sort puts its result: back into an array or bytes, or into a new array. */ -export type SortInto = "Array.sort" | "Array.toSorted" | "Uint8Array.sort" - -/** The most values the default sort sorts in one native call; more sort in bounded steps (see `sortDefault`). */ -export const SORT_RUN = 4096 - -/** - * Sorts `target`'s values: at once without a comparator, unless there are many, otherwise in the prelude - * (`sortWith`), which calls it. The merges of a top-down merge sort are planned here, in post-order, so the prelude - * compares in the same order as the recursive sort. Holes and undefined values sort last without being compared. - */ -export const sortArray = ( - ctx: Interpreter, - target: Arr | Bytes, - comparator: Value, - into: SortInto, -): Value | Invoke => { - const builtins = ctx.builtins - const items = target instanceof Arr ? [...target.items] : [...target.bytes] - // Counted before any comparator runs; a comparator that changes the array does not change where holes go. - let holes = 0 - if (target instanceof Arr) for (let index = 0; index < items.length; index++) if (!(index in target.items)) holes++ - const callback = comparator === undefined ? undefined : requireCallback(comparator, into) - if (callback === undefined && items.length <= SORT_RUN) { - return sorted( - builtins, - target, - into, - holes, - items.sort((a, b) => compareText(coerceToString(a), coerceToString(b))), - ) - } - const defined = new Arr( - builtins.Array, - items.filter((item) => item !== undefined), - ) - const undefs = items.length - defined.items.length - if (callback === undefined) { - return new Invoke(ctx.prelude.fn("sortDefault"), undefined, [target, into, holes, defined, undefs], undefined) - } - const merges: Array = [] - const plan = (low: number, high: number) => { - if (high - low <= 1) return - const middle = low + Math.floor((high - low) / 2) - plan(low, middle) - plan(middle, high) - merges.push(low, middle, high) - } - plan(0, defined.items.length) - const args = [target, into, holes, callback, defined, undefs, new Arr(builtins.Array, merges)] - return new Invoke(ctx.prelude.fn("sortWith"), undefined, args, undefined) -} - -export const sorted = ( - builtins: Builtins, - target: Arr | Bytes, - into: SortInto, - holes: number, - result: Array, -) => { - if (target instanceof Bytes) { - target.bytes.set(Uint8Array.from(result, coerceToNumber)) - return target - } - if (into === "Array.toSorted") return new Arr(builtins.Array, result) - changed(target) - const items = target.items - const count = result.length - holes - result.slice(0, count).forEach((item, index) => { - items[index] = item - }) - Array.from({ length: holes }, (_, index) => count + index).forEach((index) => { - delete items[index] - }) - return target -} - -// Array constructs identically with or without new, like JS. -export const arrayGlobal = (ctx: Interpreter) => { - const builtins = ctx.builtins - const proto = builtins.Array - const wrap = (items: Array) => new Arr(proto, items) - const construct = (args: Array, into: Obj): Arr => { - if (args.length !== 1) return new Arr(into, [...args]) - const first = args[0] - if (typeof first !== "number") return new Arr(into, [first]) - if (!Number.isInteger(first) || first < 0 || first > MAX_ARRAY_LENGTH) throw rangeError("Invalid array length.") - // Sparse like JS: Array(3) has holes, and combinator loops already skip them. - return new Arr(into, new Array(first)) - } - const array = constructor(builtins, proto, { - name: "Array", - length: 1, - call: (_, args) => construct(args, proto), - construct: (args, newTarget) => construct(args, prototypeFrom(newTarget, proto)), - }) - methods(builtins, array, [ - ["isArray", 1, (_, args) => args[0] instanceof Arr], - ["of", 0, (_, args) => wrap([...args])], - ["from", 1, (_, args) => arrayFrom(ctx, args)], - ]) - - const self = (thisValue: Value, name: string) => receiver(Arr, thisValue, `Array.prototype.${name}`) - // A mutating method fails where its first element write, delete, or `length` write would on a frozen, sealed, or - // non-extensible array. `growth` is given by the methods that always write `length`, even when it is 0; holes a - // method would fill on a non-extensible array are not checked. - const mutable = (target: Arr, growth?: number): Arr => { - const length = target.items.length - if ((growth ?? 0) > 0) rejectAddition(target, length) - if ((growth ?? 0) < 0 && length > 0 && !target.elements.configurable) { - throw typeError(`Cannot delete property '${length - 1}'.`) - } - if (!target.elements.writable && (length > 0 || growth !== undefined)) { - throw typeError(`Cannot assign to read only property '${length > 0 ? 0 : "length"}'.`) - } - changed(target) - return target - } - const optNumber = (value: Value): number | undefined => (value === undefined ? undefined : coerceToInteger(value)) - - methods(builtins, proto, [ - [ - "join", - 1, - (thisValue, args) => { - // .map would keep holes, which the conversion would then hand to the body as undefined. - const parts = Array.from(self(thisValue, "join").items, (item) => item ?? "") - return withPrimitives("string", [args[0] === undefined ? "," : args[0], ...parts], ([separator, ...items]) => { - const joined = items.map(coerceToString).join(coerceToString(separator)) - checkStringLength(joined.length) - return joined - }) - }, - ], - [ - "toString", - 0, - (thisValue) => - withPrimitives( - "string", - Array.from(self(thisValue, "toString").items, (item) => item ?? ""), - (items) => items.map(coerceToString).join(","), - ), - ], - [ - "includes", - 1, - (thisValue, args) => { - return self(thisValue, "includes").items.includes(args[0], optNumber(args[1])) - }, - ], - ["indexOf", 1, (thisValue, args) => self(thisValue, "indexOf").items.indexOf(args[0], optNumber(args[1]))], - [ - "lastIndexOf", - 1, - (thisValue, args) => { - const target = self(thisValue, "lastIndexOf").items - // An explicit undefined is a fromIndex of 0, unlike omitting it. - return args.length < 2 ? target.lastIndexOf(args[0]) : target.lastIndexOf(args[0], optNumber(args[1])) - }, - ], - ["at", 1, (thisValue, args) => self(thisValue, "at").items.at(optNumber(args[0]) ?? 0)], - [ - "slice", - 2, - (thisValue, args) => wrap(self(thisValue, "slice").items.slice(optNumber(args[0]), optNumber(args[1]))), - ], - [ - "concat", - 1, - (thisValue, args) => { - const joined = self(thisValue, "concat").items.concat( - ...args.map((item) => (item instanceof Arr ? item.items : item)), - ) - checkArrayLength(joined.length) - return wrap(joined) - }, - ], - [ - "flat", - 0, - (thisValue, args) => { - const flatten = (items: Array, depth: number): Array => - items.flatMap((item) => (item instanceof Arr && depth > 0 ? flatten(item.items, depth - 1) : [item])) - const flattened = flatten(self(thisValue, "flat").items, optNumber(args[0]) ?? 1) - checkArrayLength(flattened.length) - return wrap(flattened) - }, - ], - [ - "reverse", - 0, - (thisValue) => { - const target = self(thisValue, "reverse") - // Fewer than two elements means no writes at all, so a frozen one-element array reverses fine. - if (target.items.length > 1) mutable(target) - target.items.reverse() - return target - }, - ], - ["sort", 1, (thisValue, args) => sortArray(ctx, mutable(self(thisValue, "sort")), args[0], "Array.sort")], - ["toSorted", 1, (thisValue, args) => sortArray(ctx, self(thisValue, "toSorted"), args[0], "Array.toSorted")], - ["toReversed", 0, (thisValue) => wrap([...self(thisValue, "toReversed").items].reverse())], - [ - "with", - 2, - (thisValue, args) => { - const target = self(thisValue, "with").items - const index = optNumber(args[0]) ?? 0 - const resolved = index < 0 ? target.length + index : index - if (resolved < 0 || resolved >= target.length) throw rangeError("Array.with index is out of range.") - const copied = [...target] - copied[resolved] = args[1] - return wrap(copied) - }, - ], - [ - "push", - 1, - (thisValue, args) => { - const target = mutable(self(thisValue, "push"), args.length) - // Validate all insertions before mutating to avoid partial cyclic updates. - for (const item of args) rejectCircularInsertion(target, item, "Array.push result") - return target.items.push(...args) - }, - ], - [ - "unshift", - 1, - (thisValue, args) => { - const target = mutable(self(thisValue, "unshift"), args.length) - for (const item of args) rejectCircularInsertion(target, item, "Array.unshift result") - return target.items.unshift(...args) - }, - ], - ["pop", 0, (thisValue) => mutable(self(thisValue, "pop"), -1).items.pop()], - ["shift", 0, (thisValue) => mutable(self(thisValue, "shift"), -1).items.shift()], - [ - "splice", - 2, - (thisValue, args) => { - const target = self(thisValue, "splice") - const length = target.items.length - const start = optNumber(args[0]) ?? 0 - const from = start < 0 ? Math.max(length + start, 0) : Math.min(start, length) - const deleteCount = - args.length === 1 ? length - from : Math.min(Math.max(optNumber(args[1]) ?? 0, 0), length - from) - const inserted = args.slice(2) - for (const item of inserted) rejectCircularInsertion(target, item, "Array.splice result") - mutable(target, inserted.length - deleteCount) - return wrap(target.items.splice(from, deleteCount, ...inserted)) - }, - ], - [ - "toSpliced", - 2, - (thisValue, args) => { - const copied = [...self(thisValue, "toSpliced").items] - if (args.length === 0) return wrap(copied) - const start = optNumber(args[0]) ?? 0 - if (args.length === 1) copied.splice(start) - else copied.splice(start, optNumber(args[1]) ?? 0, ...args.slice(2)) - return wrap(copied) - }, - ], - [ - "fill", - 1, - (thisValue, args) => { - const target = mutable(self(thisValue, "fill")) - rejectCircularInsertion(target, args[0], "Array.fill result") - target.items.fill(args[0], optNumber(args[1]), optNumber(args[2])) - return target - }, - ], - [ - "copyWithin", - 2, - (thisValue, args) => { - const target = mutable(self(thisValue, "copyWithin")) - target.items.copyWithin(optNumber(args[0]) ?? 0, optNumber(args[1]) ?? 0, optNumber(args[2])) - return target - }, - ], - ...iteratorMethods(builtins, self), - // The callback methods are the prelude's. - ]) - define(proto, IteratorSymbol, get(proto, "values"), hidden) - return array -} diff --git a/packages/codemode/src/language/stdlib/buffer.ts b/packages/codemode/src/language/stdlib/buffer.ts deleted file mode 100644 index 0e068f0a191..00000000000 --- a/packages/codemode/src/language/stdlib/buffer.ts +++ /dev/null @@ -1,312 +0,0 @@ -import { type Builtins, createErrorValue } from "../runtime/intrinsics.js" -import { readsPending, withReads } from "../runtime/callback.js" -import type { Interpreter } from "../runtime/interpreter.js" -import { Throw, typeError } from "../runtime/model.js" -import { constructor, type Method, methods, prototypeFrom, receiver } from "../runtime/native.js" -import { - Arr, - Bytes, - define, - frozen, - get, - hidden, - Obj, - coerceToNumber, - coerceToString, - record, - type Value, -} from "../runtime/objects.js" -import { describeValue } from "../runtime/references.js" - -/** A Node Buffer: a Uint8Array whose text conversions default to UTF-8. */ -export class BufferObj extends Bytes { - override toString() { - return host(this.bytes).toString("utf8") - } - override toHost() { - return Buffer.from(this.bytes) - } - override derive(builtins: Builtins, bytes: Uint8Array) { - return new BufferObj(builtins.Buffer, bytes) - } - override inspect() { - const shown = Array.from(this.bytes.subarray(0, 50), (byte) => byte.toString(16).padStart(2, "0")).join(" ") - const more = this.bytes.length > 50 ? ` ... ${this.bytes.length - 50} more bytes` : "" - return `` - } -} - -// The host Buffer over the same memory, so reads and writes through it are the program's bytes. -const host = (bytes: Uint8Array) => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength) - -const encodings = new Set([ - "utf8", - "utf-8", - "hex", - "base64", - "base64url", - "latin1", - "binary", - "ascii", - "ucs2", - "ucs-2", - "utf16le", - "utf-16le", -]) - -const isEncoding = (value: Value) => typeof value === "string" && encodings.has(value.toLowerCase()) - -// Read and write methods that take only numbers, delegated to the host Buffer as is. -const numeric = [ - "readUInt8", - "readUint8", - "readInt8", - "readUInt16LE", - "readUint16LE", - "readUInt16BE", - "readUint16BE", - "readInt16LE", - "readInt16BE", - "readUInt32LE", - "readUint32LE", - "readUInt32BE", - "readUint32BE", - "readInt32LE", - "readInt32BE", - "readFloatLE", - "readFloatBE", - "readDoubleLE", - "readDoubleBE", - "readUIntLE", - "readUIntBE", - "readIntLE", - "readIntBE", - "writeUInt8", - "writeUint8", - "writeInt8", - "writeUInt16LE", - "writeUint16LE", - "writeUInt16BE", - "writeUint16BE", - "writeInt16LE", - "writeInt16BE", - "writeUInt32LE", - "writeUint32LE", - "writeUInt32BE", - "writeUint32BE", - "writeInt32LE", - "writeInt32BE", - "writeFloatLE", - "writeFloatBE", - "writeDoubleLE", - "writeDoubleBE", - "writeUIntLE", - "writeUIntBE", - "writeIntLE", - "writeIntBE", - "swap16", - "swap32", - "swap64", -] as const - -export const bufferGlobal = (ctx: Interpreter) => { - const builtins = ctx.builtins - const proto = builtins.Buffer - const wrap = (bytes: Uint8Array) => new BufferObj(proto, bytes) - const self = (thisValue: Value, name: string) => receiver(Bytes, thisValue, `Buffer.prototype.${name}`) - - const fail = (type: "Error" | "TypeError" | "RangeError", message: string, code?: string) => { - const value = createErrorValue(builtins[type], message) - if (code !== undefined) define(value, "code", code) - return new Throw(value) - } - // Host Buffer errors carry Node's `code`; they cross as the program error of the same type. - const attempt = (run: () => A): A => { - try { - return run() - } catch (error) { - if (!(error instanceof Error)) throw error - const code = (error as { code?: unknown }).code - throw fail( - error.name === "RangeError" || error.name === "TypeError" ? error.name : "Error", - error.message, - typeof code === "string" ? code : undefined, - ) - } - } - const encoding = (value: Value): BufferEncoding | undefined => { - if (value === undefined) return undefined - if (isEncoding(value)) return coerceToString(value).toLowerCase() as BufferEncoding - throw fail("TypeError", `Unknown encoding: ${coerceToString(value)}`, "ERR_UNKNOWN_ENCODING") - } - const argument = (value: Value): unknown => { - if (value instanceof Bytes) return host(value.bytes) - if (value === null || value === undefined || typeof value !== "object") return value - return coerceToNumber(value) - } - const bytesFrom = (value: Value, second: Value, third: Value): Uint8Array => { - if (typeof value === "string") return new Uint8Array(Buffer.from(value, encoding(second) ?? "utf8")) - if (value instanceof Bytes) { - const offset = second === undefined ? 0 : coerceToNumber(second) - const length = third === undefined ? undefined : coerceToNumber(third) - return value.bytes.slice(offset, length === undefined ? undefined : offset + length) - } - if (value instanceof Arr) return Uint8Array.from(value.items, coerceToNumber) - if (value instanceof Obj) { - const data = get(value, "data") - const type = get(value, "type") - // `type` and `data` decide the path, so a getter among them is read before `length` could be. - if (readsPending()) return new Uint8Array() - if (type === "Buffer" && data instanceof Arr) return Uint8Array.from(data.items, coerceToNumber) - const length = get(value, "length") - if (typeof length === "number") - return Uint8Array.from({ length }, (_, index) => coerceToNumber(get(value, String(index)))) - } - throw fail( - "TypeError", - `The first argument must be of type string or an instance of Buffer, Uint8Array, or Array or an Array-like Object. Received ${describeValue(value)}`, - "ERR_INVALID_ARG_TYPE", - ) - } - const size = (value: Value) => { - const length = coerceToNumber(value) - if (!Number.isInteger(length) || length < 0) { - throw fail("RangeError", `The argument 'size' is invalid. Received ${coerceToString(value)}`, "ERR_OUT_OF_RANGE") - } - return length - } - - const buffer = constructor(builtins, proto, { - name: "Buffer", - length: 2, - call: (_, args) => withReads(() => wrap(bytesFrom(args[0], args[1], args[2]))), - construct: (args, newTarget) => - withReads(() => new BufferObj(prototypeFrom(newTarget, proto), bytesFrom(args[0], args[1], args[2]))), - }) - // Bun inherits this from Uint8Array; Buffer's constructor here does not. - define(buffer, "BYTES_PER_ELEMENT", 1, frozen) - methods(builtins, buffer, [ - ["from", 3, (_, args) => withReads(() => wrap(bytesFrom(args[0], args[1], args[2])))], - [ - "alloc", - 3, - (_, args) => { - const bytes = new Uint8Array(size(args[0])) - const fill = args[1] === undefined ? undefined : argument(args[1]) - // Node reads an encoding only after a string fill; after a number it would be an offset. - if (typeof fill === "string") attempt(() => host(bytes).fill(fill, encoding(args[2]) ?? "utf8")) - else if (fill !== undefined) attempt(() => host(bytes).fill(fill as number)) - return wrap(bytes) - }, - ], - ["allocUnsafe", 1, (_, args) => wrap(new Uint8Array(size(args[0])))], - ["allocUnsafeSlow", 1, (_, args) => wrap(new Uint8Array(size(args[0])))], - [ - "byteLength", - 2, - (_, args) => - args[0] instanceof Bytes - ? args[0].bytes.byteLength - : Buffer.byteLength(coerceToString(args[0]), encoding(args[1])), - ], - [ - "concat", - 2, - (_, args) => { - const list = args[0] - if (!(list instanceof Arr)) - throw typeError(`Buffer.concat expects an array of Buffers, received ${describeValue(list)}.`) - const parts = list.items.map((item) => { - if (item instanceof Bytes) return item.bytes - throw typeError(`Buffer.concat expects an array of Buffers, received ${describeValue(item)} in it.`) - }) - const total = args[1] === undefined ? parts.reduce((sum, part) => sum + part.length, 0) : size(args[1]) - const joined = new Uint8Array(total) - parts.reduce((offset, part) => { - if (offset < total) joined.set(part.subarray(0, total - offset), offset) - return offset + part.length - }, 0) - return wrap(joined) - }, - ], - ["isBuffer", 1, (_, args) => args[0] instanceof BufferObj], - ["isEncoding", 1, (_, args) => isEncoding(args[0])], - [ - "compare", - 2, - (_, args) => { - if (!(args[0] instanceof Bytes) || !(args[1] instanceof Bytes)) - throw typeError("Buffer.compare expects two Buffers or Uint8Arrays.") - return Buffer.compare(args[0].bytes, args[1].bytes) - }, - ], - ]) - define(buffer, "poolSize", 8192, hidden) - - const view = (thisValue: Value, name: string, args: Array) => { - const bytes = self(thisValue, name).bytes - const length = bytes.length - const clamp = (value: Value, fallback: number) => { - if (value === undefined) return fallback - const index = Math.trunc(coerceToNumber(value)) || 0 - return index < 0 ? Math.max(0, length + index) : Math.min(index, length) - } - return wrap(bytes.subarray(clamp(args[0], 0), clamp(args[1], length))) - } - const delegate = (name: string, length: number): Method => [ - name, - length, - (thisValue, args) => { - const target = host(self(thisValue, name).bytes) - const method = (target as unknown as Record) => unknown>)[name]! - const result = attempt(() => method.apply(target, args.map(argument))) - if (result === target) return thisValue - if (typeof result === "number" || typeof result === "boolean" || typeof result === "string") return result - return undefined - }, - ] - methods(builtins, proto, [ - [ - "toString", - 3, - (thisValue, args) => { - const bytes = self(thisValue, "toString").bytes - const start = args[1] === undefined ? 0 : Math.max(0, coerceToNumber(args[1])) - const end = args[2] === undefined ? bytes.length : Math.min(bytes.length, coerceToNumber(args[2])) - return host(bytes).toString(encoding(args[0]) ?? "utf8", start, end) - }, - ], - [ - "toJSON", - 0, - (thisValue) => - record(builtins.Object, { - type: "Buffer", - data: new Arr(builtins.Array, [...self(thisValue, "toJSON").bytes]), - }), - ], - ["slice", 2, (thisValue, args) => view(thisValue, "slice", args)], - ["subarray", 2, (thisValue, args) => view(thisValue, "subarray", args)], - [ - "equals", - 1, - (thisValue, args) => { - const other = args[0] - if (!(other instanceof Bytes)) - throw typeError( - `The "otherBuffer" argument must be an instance of Buffer or Uint8Array. Received ${describeValue(other)}`, - ) - return Buffer.compare(self(thisValue, "equals").bytes, other.bytes) === 0 - }, - ], - delegate("compare", 5), - delegate("indexOf", 3), - delegate("lastIndexOf", 3), - delegate("includes", 3), - delegate("write", 4), - delegate("fill", 4), - delegate("copy", 4), - ...numeric.map((name) => delegate(name, 2)), - ]) - return buffer -} diff --git a/packages/codemode/src/language/stdlib/bytes.ts b/packages/codemode/src/language/stdlib/bytes.ts deleted file mode 100644 index b18babf3cd8..00000000000 --- a/packages/codemode/src/language/stdlib/bytes.ts +++ /dev/null @@ -1,380 +0,0 @@ -import { Invoke } from "../runtime/signals.js" -import { checkArrayLength, checkStringLength } from "../runtime/limits.js" -import { constructor, methods, prototypeFrom, receiver, requiresNew, iteratorMethods } from "../runtime/native.js" -import { IteratorSymbol, rangeError, syntaxError, typeError } from "../runtime/model.js" -import { - define, - defineAccessor, - frozen, - get, - hidden, - Bytes, - Obj, - coerceToInteger, - coerceToNumber, - coerceToString, - type Value, -} from "../runtime/objects.js" -import { describeValue } from "../runtime/references.js" -import { requireCallback, readsPending, withReads } from "../runtime/callback.js" -import type { Interpreter } from "../runtime/interpreter.js" -import { sortArray } from "./array.js" - -/** - * The bytes a Uint8Array, array, or other iterable of numbers describes, read in the prelude: a new Uint8Array with - * prototype `into`, or set into the Uint8Array `into` at `offset`. The host array clamps each value. - */ -const collectBytes = ( - ctx: Interpreter, - source: Value, - name: string, - into: Obj, - offset: number, - mapper?: Value, - thisArg?: Value, -) => { - const callback = mapper === undefined ? undefined : requireCallback(mapper, name) - if (source instanceof Bytes && callback === undefined) return finishBytes(new Uint8Array(source.bytes), into, offset) - return new Invoke( - ctx.prelude.fn("collectBytes"), - undefined, - [source, name, callback, thisArg, into, offset], - undefined, - ) -} - -export const finishBytes = (bytes: Uint8Array, into: Obj, offset: number): Value => { - if (!(into instanceof Bytes)) return new Bytes(into, bytes) - if (!Number.isInteger(offset) || offset < 0 || bytes.length + offset > into.bytes.length) { - throw rangeError("Uint8Array.set: the source does not fit at that offset.") - } - into.bytes.set(bytes, offset) - return undefined -} - -const constructBytes = (ctx: Interpreter, args: Array, proto: Obj) => { - const source = args[0] - if (source !== null && typeof source === "object") return collectBytes(ctx, source, "new Uint8Array(...)", proto, 0) - const length = source === undefined ? 0 : coerceToNumber(source) - if (!Number.isInteger(length) || length < 0) throw rangeError(`Invalid typed array length: ${coerceToString(source)}`) - checkArrayLength(length) - return new Bytes(proto, new Uint8Array(length)) -} - -const base64Alphabets = ["base64", "base64url"] as const -const lastChunkHandlings = ["loose", "strict", "stop-before-partial"] as const - -const base64Options = (value: Value, name: string) => { - if (value === undefined) return undefined - if (value instanceof Obj) return value - throw typeError(`${name} requires that options be an object.`) -} - -/** A string option of the base64 methods: one of `allowed`, defaulting to the first. */ -const base64Option = ( - options: Obj | undefined, - key: string, - allowed: ReadonlyArray, - name: string, -): T => { - const value = options === undefined ? undefined : get(options, key) - if (value === undefined) return allowed[0] - const match = allowed.find((option) => option === value) - if (match !== undefined) return match - throw typeError(`${name} requires that ${key} be ${allowed.map((option) => `"${option}"`).join(" or ")}.`) -} - -export const uint8ArrayGlobal = (ctx: Interpreter) => { - const builtins = ctx.builtins - const proto = builtins.Uint8Array - const wrap = (bytes: Uint8Array) => new Bytes(proto, bytes) - const uint8Array = constructor(builtins, proto, { - name: "Uint8Array", - length: 3, - call: requiresNew("Uint8Array"), - construct: (args, newTarget) => constructBytes(ctx, args, prototypeFrom(newTarget, proto)), - }) - const decode = (name: string, args: Array, from: (text: string) => Uint8Array) => { - if (typeof args[0] !== "string") throw typeError(`Uint8Array.${name} expects a string.`) - try { - return wrap(from(args[0])) - } catch { - throw syntaxError(`Uint8Array.${name}: the string is not valid ${name === "fromHex" ? "hex" : "base64"}.`) - } - } - methods(builtins, uint8Array, [ - ["from", 1, (_, args) => collectBytes(ctx, args[0], "Uint8Array.from", proto, 0, args[1], args[2])], - ["of", 0, (_, args) => wrap(Uint8Array.from(args, coerceToNumber))], - [ - "fromBase64", - 1, - (_, args) => { - if (typeof args[0] !== "string") throw typeError("Uint8Array.fromBase64 expects a string.") - return withReads(() => { - const options = base64Options(args[1], "Uint8Array.fromBase64") - const alphabet = base64Option(options, "alphabet", base64Alphabets, "Uint8Array.fromBase64") - const lastChunkHandling = base64Option( - options, - "lastChunkHandling", - lastChunkHandlings, - "Uint8Array.fromBase64", - ) - return decode("fromBase64", args, (text) => Uint8Array.fromBase64(text, { alphabet, lastChunkHandling })) - }) - }, - ], - ["fromHex", 1, (_, args) => decode("fromHex", args, (text) => Uint8Array.fromHex(text))], - ]) - define(uint8Array, "BYTES_PER_ELEMENT", 1, frozen) - define(proto, "BYTES_PER_ELEMENT", 1, frozen) - - const self = (thisValue: Value, name: string) => receiver(Bytes, thisValue, `Uint8Array.prototype.${name}`) - const optNumber = (value: Value): number | undefined => (value === undefined ? undefined : coerceToInteger(value)) - // Uint8Array cannot contain NaN, so non-number search values never match a byte. - const search = (value: Value) => (typeof value === "number" ? value : NaN) - defineAccessor(proto, "length", (thisValue) => self(thisValue, "length").bytes.length) - methods(builtins, proto, [ - ["at", 1, (thisValue, args) => self(thisValue, "at").bytes.at(optNumber(args[0]) ?? 0)], - [ - "slice", - 2, - (thisValue, args) => { - const target = self(thisValue, "slice") - return target.derive(builtins, target.bytes.slice(optNumber(args[0]), optNumber(args[1]))) - }, - ], - // A view on the same bytes, as in JS: writes through one are visible through the other. - [ - "subarray", - 2, - (thisValue, args) => { - const target = self(thisValue, "subarray") - return target.derive(builtins, target.bytes.subarray(optNumber(args[0]), optNumber(args[1]))) - }, - ], - [ - "set", - 1, - (thisValue, args) => { - const target = self(thisValue, "set") - return collectBytes(ctx, args[0], "Uint8Array.set", target, optNumber(args[1]) ?? 0) - }, - ], - [ - "fill", - 1, - (thisValue, args) => { - const target = self(thisValue, "fill") - target.bytes.fill(coerceToNumber(args[0]), optNumber(args[1]), optNumber(args[2])) - return target - }, - ], - [ - "reverse", - 0, - (thisValue) => { - const target = self(thisValue, "reverse") - target.bytes.reverse() - return target - }, - ], - [ - "sort", - 1, - (thisValue, args) => { - const target = self(thisValue, "sort") - // Without a comparator, typed arrays sort numerically rather than by string. - if (args[0] === undefined) { - target.bytes.sort() - return target - } - return sortArray(ctx, target, args[0], "Uint8Array.sort") - }, - ], - ["indexOf", 1, (thisValue, args) => self(thisValue, "indexOf").bytes.indexOf(search(args[0]), optNumber(args[1]))], - [ - "lastIndexOf", - 1, - (thisValue, args) => { - const target = self(thisValue, "lastIndexOf").bytes - return args.length < 2 - ? target.lastIndexOf(search(args[0])) - : target.lastIndexOf(search(args[0]), optNumber(args[1])) - }, - ], - [ - "includes", - 1, - (thisValue, args) => self(thisValue, "includes").bytes.includes(search(args[0]), optNumber(args[1])), - ], - [ - "join", - 1, - (thisValue, args) => { - const joined = self(thisValue, "join").bytes.join(args[0] === undefined ? "," : coerceToString(args[0])) - checkStringLength(joined.length) - return joined - }, - ], - ["toString", 0, (thisValue) => self(thisValue, "toString").bytes.join(",")], - [ - "toBase64", - 0, - (thisValue, args) => { - const bytes = self(thisValue, "toBase64").bytes - return withReads(() => { - const options = base64Options(args[0], "Uint8Array.prototype.toBase64") - const alphabet = base64Option(options, "alphabet", base64Alphabets, "Uint8Array.prototype.toBase64") - return bytes.toBase64({ - alphabet, - omitPadding: options !== undefined && Boolean(get(options, "omitPadding")), - }) - }) - }, - ], - ["toHex", 0, (thisValue) => self(thisValue, "toHex").bytes.toHex()], - ...iteratorMethods(builtins, self), - // The callback methods are the prelude's. - ]) - define(proto, IteratorSymbol, get(proto, "values"), hidden) - return uint8Array -} - -export const textEncoderGlobal = (ctx: Interpreter) => { - const builtins = ctx.builtins - const proto = builtins.TextEncoder - const encoder = new TextEncoder() - defineAccessor(proto, "encoding", () => "utf-8") - methods(builtins, proto, [ - [ - "encode", - 0, - (_, args) => new Bytes(builtins.Uint8Array, encoder.encode(coerceToString(args[0] === undefined ? "" : args[0]))), - ], - ]) - return constructor(builtins, proto, { - name: "TextEncoder", - call: requiresNew("TextEncoder"), - construct: (_, newTarget) => new Obj(prototypeFrom(newTarget, proto)), - }) -} - -// Replacement mode only needs to identify an incomplete suffix (at most three bytes). -// Fatal mode also needs the queue position after the first error, which the host doesn't expose. -const streamBoundary = (bytes: Uint8Array, fatal: boolean) => { - let next = fatal ? 0 : Math.max(0, bytes.length - 3) - while (next < bytes.length) { - const start = next - const lead = bytes[next++]! - if (lead < 0x80) continue - if (lead < 0xc2 || lead > 0xf4) { - if (fatal) return { end: next, error: true } - continue - } - const width = lead < 0xe0 ? 2 : lead < 0xf0 ? 3 : 4 - let lower = lead === 0xe0 ? 0xa0 : lead === 0xf0 ? 0x90 : 0x80 - let upper = lead === 0xed ? 0x9f : lead === 0xf4 ? 0x8f : 0xbf - while (next < start + width) { - if (next === bytes.length) return { end: start, error: false } - const byte = bytes[next]! - // A bad continuation is reprocessed as a leading byte, even after a fatal error. - if (byte < lower || byte > upper) { - if (fatal) return { end: next, error: true } - break - } - next++ - lower = 0x80 - upper = 0xbf - } - } - return { end: next, error: false } -} - -const empty = new Uint8Array() - -export class TextDecoderObj extends Obj { - queued: Uint8Array = empty - seen = false - - constructor( - proto: Obj, - readonly decoder: TextDecoder, - readonly ignoreBOM: boolean, - ) { - super(proto) - } - - decode(bytes: Uint8Array, stream: boolean) { - if (this.queued.length && bytes.length) { - checkArrayLength(this.queued.length + bytes.length) - const joined = new Uint8Array(this.queued.length + bytes.length) - joined.set(this.queued) - joined.set(bytes, this.queued.length) - bytes = joined - } - if (!bytes.length) bytes = this.queued - const { end, error } = stream ? streamBoundary(bytes, this.decoder.fatal) : { end: bytes.length, error: false } - this.queued = end < bytes.length ? bytes.slice(end) : empty - if (error) throw typeError("TextDecoder.decode: the input is not valid utf-8.") - const stripBOM = !this.ignoreBOM && !this.seen - if (!stream) this.seen = false - try { - // Keep the host decoder stateless: snapshots own the pending bytes and BOM decision. - const text = this.decoder.decode(end === bytes.length ? bytes : bytes.subarray(0, end)) - if (stream && text.length) this.seen = true - return stripBOM && text.charCodeAt(0) === 0xfeff ? text.slice(1) : text - } catch { - throw typeError("TextDecoder.decode: the input is not valid utf-8.") - } - } -} - -// The WHATWG labels for UTF-8, the only encoding CodeMode decodes. -const utf8Labels = new Set(["unicode-1-1-utf-8", "unicode11utf8", "unicode20utf8", "utf-8", "utf8", "x-unicode20utf8"]) - -export const textDecoderGlobal = (ctx: Interpreter) => { - const builtins = ctx.builtins - const proto = builtins.TextDecoder - const self = (thisValue: Value, name: string) => receiver(TextDecoderObj, thisValue, `TextDecoder.prototype.${name}`) - defineAccessor(proto, "encoding", (thisValue) => self(thisValue, "encoding").decoder.encoding) - defineAccessor(proto, "fatal", (thisValue) => self(thisValue, "fatal").decoder.fatal) - defineAccessor(proto, "ignoreBOM", (thisValue) => self(thisValue, "ignoreBOM").ignoreBOM) - methods(builtins, proto, [ - [ - "decode", - 0, - (thisValue, args) => { - const decoder = self(thisValue, "decode") - if (args[0] !== undefined && !(args[0] instanceof Bytes)) { - throw typeError(`TextDecoder.decode expects a Uint8Array, received ${describeValue(args[0])}.`) - } - const options = args[1] - if (options !== undefined && typeof options !== "object") { - throw typeError("TextDecoder.decode expects an options object.") - } - return withReads(() => { - const stream = options instanceof Obj && Boolean(get(options, "stream")) - return readsPending() ? undefined : decoder.decode((args[0] as Bytes | undefined)?.bytes ?? empty, stream) - }) - }, - ], - ]) - return constructor(builtins, proto, { - name: "TextDecoder", - call: requiresNew("TextDecoder"), - construct: (args, newTarget) => { - const label = args[0] === undefined ? "utf-8" : coerceToString(args[0]).trim().toLowerCase() - if (!utf8Labels.has(label)) throw rangeError(`The "${label}" encoding is not supported; only UTF-8 is.`) - const options = args[1] instanceof Obj ? args[1] : undefined - const flag = (name: string) => options !== undefined && Boolean(get(options, name)) - return withReads( - () => - new TextDecoderObj( - prototypeFrom(newTarget, proto), - new TextDecoder("utf-8", { fatal: flag("fatal"), ignoreBOM: true }), - flag("ignoreBOM"), - ), - ) - }, - }) -} diff --git a/packages/codemode/src/language/stdlib/collections.ts b/packages/codemode/src/language/stdlib/collections.ts deleted file mode 100644 index f9803e6e0e3..00000000000 --- a/packages/codemode/src/language/stdlib/collections.ts +++ /dev/null @@ -1,210 +0,0 @@ -import { Invoke } from "../runtime/signals.js" -import { constructor, methods, prototypeFrom, receiver, requiresNew, iteratorMethods } from "../runtime/native.js" -import { IteratorSymbol, typeError } from "../runtime/model.js" -import { - define, - defineAccessor, - get, - hidden, - type Callable, - MapObj, - Obj, - SetObj, - type Value, - WeakMapObj, - WeakSetObj, -} from "../runtime/objects.js" -import { describeValue } from "../runtime/references.js" -import { requireCallback } from "../runtime/callback.js" -import type { Interpreter } from "../runtime/interpreter.js" - -// A collection from an iterable is filled by the prelude, which iterates it. -const filled = (ctx: Interpreter, target: Obj, init: Value, kind: string) => - init === undefined || init === null - ? target - : new Invoke(ctx.prelude.fn("fillCollection"), undefined, [target, init, kind], undefined) - -// The callback sees the stored key (-0 is +0) and its result wins over anything it inserted itself. -const getOrInsertComputed = ( - ctx: Interpreter, - owner: MapObj | WeakMapObj, - key: Value, - callback: Callable, -): Value | Invoke => { - const table = owner.map as Map - if (table.has(key)) return table.get(key) - return new Invoke(ctx.prelude.fn("insertComputed"), undefined, [owner, key === 0 ? 0 : key, callback], undefined) -} - -export const mapGlobal = (ctx: Interpreter) => { - const builtins = ctx.builtins - const proto = builtins.Map - const map = constructor(builtins, proto, { - name: "Map", - call: requiresNew("Map"), - construct: (args, newTarget) => filled(ctx, new MapObj(prototypeFrom(newTarget, proto)), args[0], "Map"), - }) - const self = (thisValue: Value, name: string) => receiver(MapObj, thisValue, `Map.prototype.${name}`) - defineAccessor(proto, "size", (thisValue) => receiver(MapObj, thisValue, "Map.prototype.size").map.size) - methods(builtins, proto, [ - ["get", 1, (thisValue, args) => self(thisValue, "get").map.get(args[0])], - ["has", 1, (thisValue, args) => self(thisValue, "has").map.has(args[0])], - [ - "set", - 2, - (thisValue, args) => { - const target = self(thisValue, "set") - target.map.set(args[0], args[1]) - return target - }, - ], - [ - "getOrInsert", - 2, - (thisValue, args) => { - const target = self(thisValue, "getOrInsert").map - if (!target.has(args[0])) target.set(args[0], args[1]) - return target.get(args[0]) - }, - ], - [ - "getOrInsertComputed", - 2, - (thisValue, args) => { - const target = self(thisValue, "getOrInsertComputed") - return getOrInsertComputed(ctx, target, args[0], requireCallback(args[1], "Map.getOrInsertComputed")) - }, - ], - ["delete", 1, (thisValue, args) => self(thisValue, "delete").map.delete(args[0])], - [ - "clear", - 0, - (thisValue) => { - self(thisValue, "clear").map.clear() - return undefined - }, - ], - ...iteratorMethods(builtins, self), - ]) - define(proto, IteratorSymbol, get(proto, "entries"), hidden) - return map -} - -export const setGlobal = (ctx: Interpreter) => { - const builtins = ctx.builtins - const proto = builtins.Set - const set = constructor(builtins, proto, { - name: "Set", - call: requiresNew("Set"), - construct: (args, newTarget) => filled(ctx, new SetObj(prototypeFrom(newTarget, proto)), args[0], "Set"), - }) - const self = (thisValue: Value, name: string) => receiver(SetObj, thisValue, `Set.prototype.${name}`) - defineAccessor(proto, "size", (thisValue) => receiver(SetObj, thisValue, "Set.prototype.size").set.size) - methods(builtins, proto, [ - ["has", 1, (thisValue, args) => self(thisValue, "has").set.has(args[0])], - [ - "add", - 1, - (thisValue, args) => { - const target = self(thisValue, "add") - target.set.add(args[0]) - return target - }, - ], - ["delete", 1, (thisValue, args) => self(thisValue, "delete").set.delete(args[0])], - [ - "clear", - 0, - (thisValue) => { - self(thisValue, "clear").set.clear() - return undefined - }, - ], - ...iteratorMethods(builtins, self), - ]) - define(proto, IteratorSymbol, get(proto, "values"), hidden) - return set -} - -// CanBeHeldWeakly: only program objects; namespace paths are rebuilt on every access, so they could never be found again. -export const weakKey = (value: Value, label: string) => { - if (value instanceof Obj) return value - throw typeError(`Invalid value used ${label}: ${describeValue(value)} cannot be held weakly.`) -} - -export const weakMapGlobal = (ctx: Interpreter) => { - const builtins = ctx.builtins - const proto = builtins.WeakMap - const weakMap = constructor(builtins, proto, { - name: "WeakMap", - call: requiresNew("WeakMap"), - construct: (args, newTarget) => filled(ctx, new WeakMapObj(prototypeFrom(newTarget, proto)), args[0], "WeakMap"), - }) - const self = (thisValue: Value, name: string) => receiver(WeakMapObj, thisValue, `WeakMap.prototype.${name}`).map - // Lookups pass any key through: the host collection answers false for a non-object, as the spec requires. - const key = (value: Value) => weakKey(value, "as weak map key") - methods(builtins, proto, [ - [ - "get", - 1, - (thisValue, args) => { - const target = self(thisValue, "get") - return args[0] instanceof Obj ? target.get(args[0]) : undefined - }, - ], - ["has", 1, (thisValue, args) => self(thisValue, "has").has(args[0] as Obj)], - ["delete", 1, (thisValue, args) => self(thisValue, "delete").delete(args[0] as Obj)], - [ - "set", - 2, - (thisValue, args) => { - self(thisValue, "set").set(key(args[0]), args[1]) - return thisValue - }, - ], - [ - "getOrInsert", - 2, - (thisValue, args) => { - const target = self(thisValue, "getOrInsert") - const k = key(args[0]) - if (!target.has(k)) target.set(k, args[1]) - return target.get(k) - }, - ], - [ - "getOrInsertComputed", - 2, - (thisValue, args) => { - const target = receiver(WeakMapObj, thisValue, "WeakMap.prototype.getOrInsertComputed") - const k = key(args[0]) - return getOrInsertComputed(ctx, target, k, requireCallback(args[1], "WeakMap.getOrInsertComputed")) - }, - ], - ]) - return weakMap -} - -export const weakSetGlobal = (ctx: Interpreter) => { - const builtins = ctx.builtins - const proto = builtins.WeakSet - const weakSet = constructor(builtins, proto, { - name: "WeakSet", - call: requiresNew("WeakSet"), - construct: (args, newTarget) => filled(ctx, new WeakSetObj(prototypeFrom(newTarget, proto)), args[0], "WeakSet"), - }) - const self = (thisValue: Value, name: string) => receiver(WeakSetObj, thisValue, `WeakSet.prototype.${name}`).set - methods(builtins, proto, [ - ["has", 1, (thisValue, args) => self(thisValue, "has").has(args[0] as Obj)], - ["delete", 1, (thisValue, args) => self(thisValue, "delete").delete(args[0] as Obj)], - [ - "add", - 1, - (thisValue, args) => { - self(thisValue, "add").add(weakKey(args[0], "in weak set")) - return thisValue - }, - ], - ]) - return weakSet -} diff --git a/packages/codemode/src/language/stdlib/console.ts b/packages/codemode/src/language/stdlib/console.ts deleted file mode 100644 index 92963a6bc39..00000000000 --- a/packages/codemode/src/language/stdlib/console.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { type Method, methods } from "../runtime/native.js" -import { - accessorLabel, - get, - Arr, - HostNamespace, - isProgramAccessor, - lookup, - Obj, - shownEntries, - type Value, -} from "../runtime/objects.js" -import { containsOpaqueReference } from "../runtime/references.js" -import type { Interpreter } from "../runtime/interpreter.js" - -const consoleMethods = ["log", "info", "debug", "warn", "error", "dir", "table"] - -/** Captured console: every method appends one formatted line to `logs`. */ -export const consoleGlobal = (ctx: Interpreter) => { - const builtins = ctx.builtins - const console = new Obj(builtins.Object) - methods( - builtins, - console, - consoleMethods.map( - (name): Method => [ - name, - 0, - (_, args) => { - ctx.logs.push(formatConsoleMessage(name, args)) - return undefined - }, - ], - ), - ) - return console -} - -const MAX_CONSOLE_DEPTH = 32 - -const formatConsoleMessage = (name: string, args: Array): string => { - if (name === "dir") return args.length === 0 ? "undefined" : formatValue(args[0]) - if (name === "table") return formatConsoleTable(args[0], args[1]) - const prefix = name === "warn" ? "[warn] " : name === "error" ? "[error] " : name === "debug" ? "[debug] " : "" - return `${prefix}${args.map((arg) => formatValue(arg)).join(" ")}` -} - -/** One value as `console.log` shows it. */ -export const formatValue = (value: Value): string => { - if (value === undefined) return "undefined" - if (typeof value === "string") return value - return formatConsoleValue(value, new Set(), 0) -} - -const formatConsoleValue = (value: Value, seen: Set, depth: number): string => { - if (value === null || value === undefined) return "null" - if (typeof value === "string") return JSON.stringify(value) - if (!(value instanceof Obj)) return value instanceof HostNamespace ? "[opaque reference]" : String(value) - if (depth > MAX_CONSOLE_DEPTH) return "..." - if (seen.has(value)) return "[Circular]" - seen.add(value) - try { - return value.inspect((item) => formatConsoleValue(item, seen, depth + 1)) - } finally { - seen.delete(value) - } -} - -const formatConsoleTable = (value: Value, columnsArgument: Value): string => { - if (value === undefined) return "undefined" - if (containsOpaqueReference(value)) return "[opaque reference]" - const columns = columnsArgument instanceof Arr ? columnsArgument.items.map(String) : undefined - const rows = consoleTableRows(value, columns) - const keys = columns ?? Array.from(new Set(rows.flatMap((row) => Object.keys(row.values)))) - const header = ["(index)", ...keys].join("\t") - return [ - header, - ...rows.map((row) => [row.index, ...keys.map((key) => formatConsoleTableCell(row.values[key]))].join("\t")), - ].join("\n") -} - -const consoleTableRows = ( - data: Value, - columns: ReadonlyArray | undefined, -): Array<{ readonly index: string; readonly values: Record }> => { - if (data instanceof Arr) { - return data.items.map((item, index) => ({ index: String(index), values: consoleTableValues(item, columns) })) - } - if (data instanceof Obj) { - return shownEntries(data).map(([index, item]) => ({ index, values: consoleTableValues(item, columns) })) - } - return [{ index: "0", values: { Value: data } }] -} - -const consoleTableValues = (value: Value, columns: ReadonlyArray | undefined): Record => { - if (value instanceof Obj && !(value instanceof Arr)) { - if (columns !== undefined) - return Object.fromEntries(columns.map((column) => [column, shownProperty(value, column)])) - return Object.fromEntries(shownEntries(value)) - } - return { Value: value } -} - -// A column of a table row, as display shows it: a program accessor (own or inherited) by its label. -const shownProperty = (value: Obj, column: string): Value => { - const slot = lookup(value, column) - return slot !== undefined && isProgramAccessor(slot) ? accessorLabel(slot) : get(value, column) -} - -const formatConsoleTableCell = (value: Value): string => { - if (value === undefined) return "" - if (typeof value === "string") return value - return formatConsoleValue(value, new Set(), 0) -} diff --git a/packages/codemode/src/language/stdlib/date.ts b/packages/codemode/src/language/stdlib/date.ts deleted file mode 100644 index b225a2d3c1f..00000000000 --- a/packages/codemode/src/language/stdlib/date.ts +++ /dev/null @@ -1,216 +0,0 @@ -import { constructor, type Method, methods, prototypeFrom, receiver } from "../runtime/native.js" -import { rangeError, typeError } from "../runtime/model.js" -import { Arr, DateObj, Obj, coerceToNumber, get, has, coerceToString, type Value } from "../runtime/objects.js" -import { withPrimitives, withReads } from "../runtime/callback.js" -import type { Interpreter } from "../runtime/interpreter.js" -import { checkArrayLength } from "../runtime/limits.js" - -const constructDate = (args: Array, proto: Obj) => { - if (args.length === 0) return new DateObj(proto, Date.now()) - if (args.length === 1) { - const arg = args[0] - if (arg instanceof DateObj) return new DateObj(proto, arg.time) - return withPrimitives("default", [arg], ([value]) => - typeof value === "string" - ? new DateObj(proto, Date.parse(value)) - : new DateObj(proto, new Date(coerceToNumber(value)).getTime()), - ) - } - // The spec converts at most seven components, in order, so extra arguments never run program code. - return toNumbers(args.slice(0, 7), (parts) => new DateObj(proto, new Date(...(parts as [number, number])).getTime())) -} - -// ToNumber on each value in turn, so a symbol throws before any later value's conversion runs program code. -const toNumbers = (values: Array, body: (numbers: Array) => Value) => - withPrimitives("number", values, (primitives) => body(primitives.map(coerceToNumber)), true) - -// The options Intl.DateTimeFormat reads. -const dateTimeOptions = [ - "localeMatcher", - "calendar", - "numberingSystem", - "hour12", - "hourCycle", - "timeZone", - "weekday", - "era", - "year", - "month", - "day", - "dayPeriod", - "hour", - "minute", - "second", - "fractionalSecondDigits", - "timeZoneName", - "formatMatcher", - "dateStyle", - "timeStyle", -] - -const arrayLikeTags = (locales: Obj) => { - const length = get(locales, "length") - const count = length instanceof Obj ? 0 : Math.max(0, Math.floor(coerceToNumber(length)) || 0) - checkArrayLength(count) - return Array.from({ length: count }, (_, index) => index) - .filter((index) => has(locales, String(index))) - .map((index) => get(locales, String(index))) -} - -type Getter = keyof { - [K in keyof Date as Date[K] extends () => number ? K : never]: never -} - -const getters: ReadonlyArray = [ - "getFullYear", - "getMonth", - "getDate", - "getDay", - "getHours", - "getMinutes", - "getSeconds", - "getMilliseconds", - "getUTCFullYear", - "getUTCMonth", - "getUTCDate", - "getUTCDay", - "getUTCHours", - "getUTCMinutes", - "getUTCSeconds", - "getUTCMilliseconds", - "getTimezoneOffset", -] - -type Setter = keyof { - [K in keyof Date as Date[K] extends (value: number, ...rest: Array) => number ? K : never]: never -} - -const setters: ReadonlyArray = [ - ["setTime", 1], - ["setMilliseconds", 1], - ["setUTCMilliseconds", 1], - ["setSeconds", 2], - ["setUTCSeconds", 2], - ["setMinutes", 3], - ["setUTCMinutes", 3], - ["setHours", 4], - ["setUTCHours", 4], - ["setDate", 1], - ["setUTCDate", 1], - ["setMonth", 2], - ["setUTCMonth", 2], - ["setFullYear", 3], - ["setUTCFullYear", 3], -] - -export const dateGlobal = (ctx: Interpreter) => { - const builtins = ctx.builtins - const proto = builtins.Date - const date = constructor(builtins, proto, { - name: "Date", - length: 7, - // ISO instead of the host's locale string: date strings are deterministic and must not leak the host timezone. - call: () => new Date().toISOString(), - construct: (args, newTarget) => constructDate(args, prototypeFrom(newTarget, proto)), - }) - methods(builtins, date, [ - ["now", 0, () => Date.now()], - ["parse", 1, (_, args) => Date.parse(coerceToString(args[0]))], - [ - "UTC", - 7, - (_, args) => toNumbers(args.slice(0, 7), (parts) => Date.UTC(...(parts as Parameters))), - ], - ]) - - const self = (thisValue: Value, name: string) => receiver(DateObj, thisValue, `Date.prototype.${name}`) - const iso = (value: DateObj) => { - if (!Number.isFinite(value.time)) throw rangeError("Invalid time value.") - return new Date(value.time).toISOString() - } - methods(builtins, proto, [ - ["getTime", 0, (thisValue) => self(thisValue, "getTime").time], - ["valueOf", 0, (thisValue) => self(thisValue, "valueOf").time], - ["toISOString", 0, (thisValue) => iso(self(thisValue, "toISOString"))], - [ - "toJSON", - 1, - (thisValue) => { - const value = self(thisValue, "toJSON") - return Number.isFinite(value.time) ? iso(value) : null - }, - ], - ["toString", 0, (thisValue) => coerceToString(self(thisValue, "toString"))], - ["toDateString", 0, (thisValue) => new Date(self(thisValue, "toDateString").time).toDateString()], - ["toTimeString", 0, (thisValue) => new Date(self(thisValue, "toTimeString").time).toTimeString()], - ["toUTCString", 0, (thisValue) => new Date(self(thisValue, "toUTCString").time).toUTCString()], - ["toGMTString", 0, (thisValue) => new Date(self(thisValue, "toGMTString").time).toUTCString()], - ...(["toLocaleString", "toLocaleDateString", "toLocaleTimeString"] as const).map( - (name): Method => [ - name, - 0, - (thisValue, args) => { - const time = self(thisValue, name).time - const [locales, options] = args - if (locales === null || options === null) throw typeError("Cannot convert undefined or null to object.") - return withReads(() => { - // Bun's default locale is en-US whatever the environment says; pinning it keeps output off the host's. - // A non-array object is array-like to Intl, so its elements are the tags. - const tags = - locales === undefined - ? ["en-US"] - : locales instanceof Arr - ? locales.items.filter(() => true) - : locales instanceof Obj - ? arrayLikeTags(locales) - : [locales] - const entries = - options instanceof Obj - ? dateTimeOptions.flatMap((key) => { - const value = get(options, key) - if (value === undefined) return [] - return [[key, key === "hour12" ? Boolean(value) : value] as const] - }) - : [] - // The host's Intl formats; program objects among the arguments are converted first, as Intl's ToString would. - return withPrimitives( - [ - ...tags.map(() => "string" as const), - ...entries.map((entry) => - entry[0] === "fractionalSecondDigits" ? ("number" as const) : ("string" as const), - ), - ], - [...tags, ...entries.map((entry) => entry[1])], - (primitives) => - new Date(time)[name]( - (locales instanceof Obj ? primitives.slice(0, tags.length) : primitives[0]) as Intl.LocalesArgument, - options instanceof Obj - ? Object.fromEntries(entries.map((entry, at) => [entry[0], primitives[tags.length + at]])) - : (options as Intl.DateTimeFormatOptions | undefined), - ), - ) - }) - }, - ], - ), - ...getters.map((name): Method => [name, 0, (thisValue) => new Date(self(thisValue, name).time)[name]()]), - ...setters.map( - ([name, length]): Method => [ - name, - length, - (thisValue, args) => { - const target = self(thisValue, name) - // Native setters read the current time before argument coercion, whose callbacks may mutate the Date. - return toNumbers([target.time, ...args.slice(0, length)], ([time, ...values]) => { - const hosted = new Date(time!) - // Every setter but setTime and setFullYear leaves an invalid Date untouched and answers NaN. - if (Number.isNaN(hosted.getTime()) && name !== "setTime" && !name.endsWith("FullYear")) return NaN - target.time = hosted[name](...(values as [number, number, number, number])) - return target.time - }) - }, - ], - ), - ]) - return date -} diff --git a/packages/codemode/src/language/stdlib/headers.ts b/packages/codemode/src/language/stdlib/headers.ts deleted file mode 100644 index b817946533c..00000000000 --- a/packages/codemode/src/language/stdlib/headers.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { constructor, methods, prototypeFrom, receiver, requiresNew, iteratorMethods } from "../runtime/native.js" -import { IteratorSymbol, typeError } from "../runtime/model.js" -import { define, get, hidden, Arr, HeadersObj, Obj, coerceToString, type Value } from "../runtime/objects.js" -import { requireCallback } from "../runtime/callback.js" -import type { Interpreter } from "../runtime/interpreter.js" -import { attempt, pairsForEach, readPairs } from "./url.js" - -const constructHeaders = (ctx: Interpreter, init: Value, proto: Obj) => { - if (init === undefined) return new HeadersObj(proto, new Headers()) - if (init instanceof Obj) return readPairs(ctx, init, "new Headers(...)", { kind: "Headers", proto }) - throw typeError("new Headers(...) expects a record of names to values, iterable [name, value] pairs, or Headers.") -} - -export const headersGlobal = (ctx: Interpreter) => { - const builtins = ctx.builtins - const proto = builtins.Headers - const headers = constructor(builtins, proto, { - name: "Headers", - call: requiresNew("Headers"), - construct: (args, newTarget) => constructHeaders(ctx, args[0], prototypeFrom(newTarget, proto)), - }) - const self = (thisValue: Value, name: string) => receiver(HeadersObj, thisValue, `Headers.prototype.${name}`) - const wrap = (items: Array) => new Arr(builtins.Array, items) - const arg = (args: Array, index: number): string => coerceToString(args[index]) - const requireArgs = (name: string, args: Array, count: number): void => { - if (args.length < count) throw typeError(`Headers.${name} requires ${count} argument${count === 1 ? "" : "s"}.`) - } - methods(builtins, proto, [ - [ - "append", - 2, - (thisValue, args) => { - requireArgs("append", args, 2) - const target = self(thisValue, "append").headers - attempt(() => target.append(arg(args, 0), arg(args, 1))) - return undefined - }, - ], - [ - "delete", - 1, - (thisValue, args) => { - requireArgs("delete", args, 1) - const target = self(thisValue, "delete").headers - attempt(() => target.delete(arg(args, 0))) - return undefined - }, - ], - [ - "get", - 1, - (thisValue, args) => { - requireArgs("get", args, 1) - const target = self(thisValue, "get").headers - return attempt(() => target.get(arg(args, 0))) - }, - ], - ["getSetCookie", 0, (thisValue) => wrap(self(thisValue, "getSetCookie").headers.getSetCookie())], - [ - "has", - 1, - (thisValue, args) => { - requireArgs("has", args, 1) - const target = self(thisValue, "has").headers - return attempt(() => target.has(arg(args, 0))) - }, - ], - [ - "set", - 2, - (thisValue, args) => { - requireArgs("set", args, 2) - const target = self(thisValue, "set").headers - attempt(() => target.set(arg(args, 0), arg(args, 1))) - return undefined - }, - ], - ...iteratorMethods(builtins, self), - [ - "forEach", - 1, - (thisValue, args) => { - requireArgs("forEach", args, 1) - const target = self(thisValue, "forEach") - const callback = requireCallback(args[0], "Headers.forEach") - return pairsForEach(ctx, target, Array.from(target.headers.entries()), callback, args[1]) - }, - ], - ]) - define(proto, IteratorSymbol, get(proto, "entries"), hidden) - return headers -} diff --git a/packages/codemode/src/language/stdlib/iterator.ts b/packages/codemode/src/language/stdlib/iterator.ts deleted file mode 100644 index 4dd2206b874..00000000000 --- a/packages/codemode/src/language/stdlib/iterator.ts +++ /dev/null @@ -1,31 +0,0 @@ -import type { Interpreter } from "../runtime/interpreter.js" -import { typeError } from "../runtime/model.js" -import { constructor, methods, receiver, requiresNew } from "../runtime/native.js" -import { iteratorResult, IteratorObj, Position } from "../runtime/objects.js" - -// Every built-in iterator and helper shares the Iterator prototype; JS gives each collection its own, which is only -// observable through getPrototypeOf. The helpers (`map`, `take`, `Iterator.from`, ...) are the prelude's. -export const iteratorGlobals = (ctx: Interpreter) => { - const builtins = ctx.builtins - const proto = builtins.Iterator - methods(builtins, proto, [ - [ - "next", - 0, - (thisValue) => { - const cursor = receiver(IteratorObj, thisValue, "Iterator.prototype.next").cursor - if (!(cursor instanceof Position)) throw typeError("Iterator.prototype.next called on an internal iterator.") - const step = cursor.step() - return iteratorResult(builtins.Object, step.value, step.done) - }, - ], - ]) - return constructor(builtins, proto, { - name: "Iterator", - length: 0, - call: requiresNew("Iterator"), - construct: () => { - throw typeError("Iterator is abstract; use Iterator.from(...) or a built-in iterator.") - }, - }) -} diff --git a/packages/codemode/src/language/stdlib/json.ts b/packages/codemode/src/language/stdlib/json.ts deleted file mode 100644 index e6c9c286eb0..00000000000 --- a/packages/codemode/src/language/stdlib/json.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { methods } from "../runtime/native.js" -import { requireCallback } from "../runtime/callback.js" -import type { Interpreter } from "../runtime/interpreter.js" -import { syntaxError } from "../runtime/model.js" -import { typeofValue } from "../runtime/references.js" -import { fromJson } from "../data.js" -import { Arr, Obj, coerceToString, record, type Value } from "../runtime/objects.js" -import { Invoke, Push } from "../runtime/signals.js" - -export const jsonGlobal = (ctx: Interpreter) => { - const json = new Obj(ctx.builtins.Object) - methods(ctx.builtins, json, [ - ["parse", 2, (_, args) => parse(ctx, args)], - ["stringify", 3, (_, args) => stringify(args)], - ]) - return json -} - -const parse = (ctx: Interpreter, args: Array) => { - const text = coerceToString(args[0]) - - const parsed = (() => { - try { - return fromJson(ctx, JSON.parse(text)) - } catch (error) { - throw syntaxError(`JSON.parse received invalid JSON: ${error instanceof Error ? error.message : String(error)}`) - } - })() - if (typeofValue(args[1]) !== "function") return parsed - const reviver = requireCallback(args[1], "JSON.parse") - return new Invoke( - ctx.prelude.fn("revive"), - undefined, - [record(ctx.builtins.Object, { "": parsed }), "", reviver], - undefined, - ) -} - -const stringify = (args: Array) => { - const space = args[2] - const indent = typeof space === "number" || typeof space === "string" ? space : undefined - const replacer = args[1] - const properties = - replacer instanceof Arr - ? replacer.items - .filter((item): item is string | number => typeof item === "string" || typeof item === "number") - .map(String) - : undefined - const callback = typeofValue(replacer) === "function" ? requireCallback(replacer, "JSON.stringify") : undefined - return new Push("JSON.stringify", [args[0], callback, properties, indent]) -} diff --git a/packages/codemode/src/language/stdlib/math.ts b/packages/codemode/src/language/stdlib/math.ts deleted file mode 100644 index e5030dd98ad..00000000000 --- a/packages/codemode/src/language/stdlib/math.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { constants, type Method, methods } from "../runtime/native.js" -import { Obj, coerceToNumber } from "../runtime/objects.js" -import { withPrimitives } from "../runtime/callback.js" -import type { Interpreter } from "../runtime/interpreter.js" - -export const mathGlobal = (ctx: Interpreter) => { - const builtins = ctx.builtins - const math = new Obj(builtins.Object) - // Convert only the arguments a method consumes; like JS, extras are ignored - // (so built-ins work as callbacks receiving (element, index, array)). - const unary = (name: string, op: (a: number) => number): Method => [ - name, - 1, - (_, args) => withPrimitives("number", [args[0]], ([a]) => op(coerceToNumber(a))), - ] - const binary = (name: string, op: (a: number, b: number) => number): Method => [ - name, - 2, - (_, args) => withPrimitives("number", [args[0], args[1]], ([a, b]) => op(coerceToNumber(a), coerceToNumber(b))), - ] - const variadic = (name: string, op: (...values: Array) => number): Method => [ - name, - 2, - (_, args) => withPrimitives("number", args, (values) => op(...values.map(coerceToNumber))), - ] - constants(math, { - PI: Math.PI, - E: Math.E, - LN2: Math.LN2, - LN10: Math.LN10, - LOG2E: Math.LOG2E, - LOG10E: Math.LOG10E, - SQRT2: Math.SQRT2, - SQRT1_2: Math.SQRT1_2, - }) - methods(builtins, math, [ - ["random", 0, () => Math.random()], - variadic("max", Math.max), - variadic("min", Math.min), - variadic("hypot", Math.hypot), - unary("abs", Math.abs), - unary("acos", Math.acos), - unary("acosh", Math.acosh), - unary("asin", Math.asin), - unary("asinh", Math.asinh), - unary("atan", Math.atan), - binary("atan2", Math.atan2), - unary("atanh", Math.atanh), - unary("floor", Math.floor), - unary("ceil", Math.ceil), - unary("round", Math.round), - unary("trunc", Math.trunc), - unary("sign", Math.sign), - unary("sqrt", Math.sqrt), - unary("cbrt", Math.cbrt), - binary("pow", Math.pow), - unary("cos", Math.cos), - unary("cosh", Math.cosh), - unary("sin", Math.sin), - unary("sinh", Math.sinh), - unary("tan", Math.tan), - unary("tanh", Math.tanh), - unary("log", Math.log), - unary("log2", Math.log2), - unary("log10", Math.log10), - unary("log1p", Math.log1p), - unary("exp", Math.exp), - unary("expm1", Math.expm1), - unary("f16round", Math.f16round), - unary("fround", Math.fround), - unary("clz32", Math.clz32), - binary("imul", Math.imul), - ]) - return math -} diff --git a/packages/codemode/src/language/stdlib/number.ts b/packages/codemode/src/language/stdlib/number.ts deleted file mode 100644 index c21ec30990a..00000000000 --- a/packages/codemode/src/language/stdlib/number.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { constructor, constants, type Method, methods } from "../runtime/native.js" -import { coerceToNumber, type Value } from "../runtime/objects.js" -import { typeError } from "../runtime/model.js" -import type { Interpreter } from "../runtime/interpreter.js" -import { withPrimitives } from "../runtime/callback.js" -import { coerce } from "./value.js" - -export const numberGlobal = (ctx: Interpreter) => { - const builtins = ctx.builtins - const number = constructor(builtins, builtins.Number, { - name: "Number", - length: 1, - call: (_, args) => coerce(ctx, "Number", args), - }) - constants(number, { - MAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER, - MIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER, - MAX_VALUE: Number.MAX_VALUE, - MIN_VALUE: Number.MIN_VALUE, - EPSILON: Number.EPSILON, - NaN: Number.NaN, - POSITIVE_INFINITY: Number.POSITIVE_INFINITY, - NEGATIVE_INFINITY: Number.NEGATIVE_INFINITY, - }) - methods(builtins, number, [ - ["isInteger", 1, (_, args) => Number.isInteger(args[0])], - ["isFinite", 1, (_, args) => Number.isFinite(args[0])], - ["isNaN", 1, (_, args) => Number.isNaN(args[0])], - ["isSafeInteger", 1, (_, args) => Number.isSafeInteger(args[0])], - ["parseInt", 2, (_, args) => coerce(ctx, "parseInt", args)], - ["parseFloat", 1, (_, args) => coerce(ctx, "parseFloat", args)], - ]) - - const self = (thisValue: Value, name: string): number => { - if (typeof thisValue === "number") return thisValue - throw typeError(`Number.prototype.${name} requires that 'this' be a Number.`) - } - // The receiver is checked first, then the one argument converts through ToPrimitive with the number hint. - const formatting = (name: string, op: (value: number, digits: number | undefined) => string): Method => [ - name, - 1, - (thisValue, args) => { - const value = self(thisValue, name) - return withPrimitives("number", [args[0]], ([digits]) => - op(value, digits === undefined ? undefined : coerceToNumber(digits)), - ) - }, - ] - methods(builtins, builtins.Number, [ - formatting("toFixed", (value, digits) => value.toFixed(digits)), - ["toLocaleString", 0, (thisValue) => self(thisValue, "toLocaleString").toLocaleString("en-US")], - formatting("toExponential", (value, digits) => value.toExponential(digits)), - formatting("toPrecision", (value, digits) => (digits === undefined ? value.toString() : value.toPrecision(digits))), - formatting("toString", (value, radix) => value.toString(radix)), - ["valueOf", 0, (thisValue) => self(thisValue, "valueOf")], - ]) - return number -} - -export const booleanGlobal = (ctx: Interpreter) => { - const builtins = ctx.builtins - const boolean = constructor(builtins, builtins.Boolean, { - name: "Boolean", - length: 1, - call: (_, args) => coerce(ctx, "Boolean", args), - }) - const self = (thisValue: Value, name: string): boolean => { - if (typeof thisValue === "boolean") return thisValue - throw typeError(`Boolean.prototype.${name} requires that 'this' be a Boolean.`) - } - methods(builtins, builtins.Boolean, [ - ["toString", 0, (thisValue) => String(self(thisValue, "toString"))], - ["valueOf", 0, (thisValue) => self(thisValue, "valueOf")], - ]) - return boolean -} diff --git a/packages/codemode/src/language/stdlib/object.ts b/packages/codemode/src/language/stdlib/object.ts deleted file mode 100644 index a87fa34085d..00000000000 --- a/packages/codemode/src/language/stdlib/object.ts +++ /dev/null @@ -1,412 +0,0 @@ -import { constructor, methods, receiver } from "../runtime/native.js" -import { type AstNode, AsyncIteratorSymbol, invalidData, IteratorSymbol, typeError } from "../runtime/model.js" -import { - changed, - entries, - enumerableKeys, - getOwn, - hasOwn, - hasPrototype, - HostNamespace, - keys, - own, - ownKeys, - Arr, - Bytes, - Obj, - PromiseObj, - set, - coerceToString, - type Value, - accessorFunction, - Callable, - define, - defineOwnProperty, - type Descriptor, - get, - has, - parseArrayIndex, - record, - type Slot, -} from "../runtime/objects.js" -import { type Builtins, primitivePrototype } from "../runtime/intrinsics.js" -import { describeValue, rejectCircularInsertion } from "../runtime/references.js" -import { invokeMethod, readsPending, withPrimitives, withReads } from "../runtime/callback.js" -import { Invoke } from "../runtime/signals.js" -import type { Interpreter } from "../runtime/interpreter.js" - -// ToObject for enumeration. -export const enumerableSource = (ctx: Interpreter, label: string, value: Value, node?: AstNode): Obj => { - if (value === null || value === undefined) { - throw typeError(`${label} cannot convert ${describeValue(value)} to an object.`, node) - } - if (value instanceof PromiseObj) { - throw invalidData(`${label} received an un-awaited Promise; await it before inspecting the result.`, node) - } - if (value instanceof HostNamespace) { - throw invalidData( - `${label} cannot read ${value.root}: it is a namespace of host functions, not plain data. Use Object.keys(${value.root}) for its names.`, - node, - ) - } - if (typeof value === "string") return new Arr(ctx.builtins.Array, [...value]) - if (value instanceof Obj) return value - return new Obj(ctx.builtins.Object) -} - -export const objectAssign = (ctx: Interpreter, args: Array): Value | Invoke => { - const target = args[0] - // JS would box a primitive target; wrappers and primitives cannot hold fields here. - if (!(target instanceof Obj)) { - throw typeError(`Object.assign expects a data object or array target, received ${describeValue(target)}.`) - } - const sources = args - .slice(1) - .filter((source) => source !== null && source !== undefined) - .map((source) => enumerableSource(ctx, "Object.assign(...)", source)) - // Program getters on a source or setters on the target's chain run in the prelude, Get then Set per key. - if (sources.some((from) => from.hasProgramAccessors) || accessorsOnChain(target)) { - return new Invoke( - ctx.prelude.fn("objectAssign"), - undefined, - [target, new Arr(ctx.builtins.Array, sources)], - undefined, - ) - } - const seen = new Set() - for (const from of sources) { - for (const key of enumerableKeys(from)) { - rejectCircularInsertion(target, getOwn(from, key), "Object.assign result", seen) - if (set(target, key, getOwn(from, key)) !== true) { - throw typeError(`Cannot assign to read only property '${String(key)}'.`) - } - } - } - return target -} - -const accessorsOnChain = (target: Obj): boolean => { - for (let current: Obj | null = target; current !== null; current = current.proto) { - if (current.hasProgramAccessors) return true - } - return false -} - -const classTag = (value: Value): string => { - if (value === null) return "Null" - if (value === undefined) return "Undefined" - if (value instanceof Obj) return value.tag - if (typeof value === "string") return "String" - if (typeof value === "number") return "Number" - if (typeof value === "boolean") return "Boolean" - return "Object" -} - -const propertyKey = (value: Value): PropertyKey => - value === AsyncIteratorSymbol || value === IteratorSymbol ? value : coerceToString(value) - -// SetIntegrityLevel: primitives pass through. A typed array's bytes cannot carry attributes, so JS throws after -// already making it non-extensible. -const restrict = (level: "freeze" | "seal" | "preventExtensions", value: Value): Value => { - if (!(value instanceof Obj)) return value - changed(value) - value.extensible = false - if (level === "preventExtensions") return value - if (value instanceof Bytes && value.bytes.length > 0) { - throw typeError(`Cannot ${level} array buffer views with elements.`) - } - for (const slot of value.props.values()) { - slot.configurable = false - if (level === "freeze" && "value" in slot) slot.writable = false - } - if (value instanceof Arr) value.elements = { writable: level === "seal", enumerable: true, configurable: false } - return value -} - -// TestIntegrityLevel: array elements and `length` answer through `own`, so a non-extensible empty array is sealed -// but not frozen, as in JS. -const integrity = (value: Value, frozen: boolean): boolean => { - if (!(value instanceof Obj)) return true - if (value.extensible) return false - return ownKeys(value).every((key) => { - const slot = own(value, key) - return slot !== undefined && !slot.configurable && !(frozen && "value" in slot && slot.writable) - }) -} - -// ToPropertyDescriptor, under `withReads`: each field through the chain, in the spec's order. -const toPropertyDescriptor = (value: Value): Descriptor => { - if (!(value instanceof Obj)) throw typeError(`Property description must be an object: ${describeValue(value)}`) - const desc: Descriptor = {} - if (has(value, "enumerable")) desc.enumerable = Boolean(get(value, "enumerable")) - if (has(value, "configurable")) desc.configurable = Boolean(get(value, "configurable")) - if (has(value, "value")) desc.value = get(value, "value") - if (has(value, "writable")) desc.writable = Boolean(get(value, "writable")) - for (const half of ["get", "set"] as const) { - if (!has(value, half)) continue - const fn = get(value, half) - if (fn !== undefined && !(fn instanceof Callable)) { - throw typeError(`${half === "get" ? "Getter" : "Setter"} must be a function: ${describeValue(fn)}`) - } - desc[half] = fn - } - if (("get" in desc || "set" in desc) && ("value" in desc || "writable" in desc)) { - throw typeError("Invalid property descriptor. Cannot both specify accessors and a value or writable attribute.") - } - return desc -} - -// DefinePropertyOrThrow. -const defineOrThrow = (target: Obj, key: PropertyKey, desc: Descriptor): void => { - if (desc.value instanceof Obj) { - rejectCircularInsertion( - target, - desc.value, - target instanceof Arr ? "Array assignment result" : "Object assignment result", - ) - } - if (defineOwnProperty(target, key, desc)) return - if (!target.extensible && own(target, key) === undefined) { - throw typeError(`Cannot define property ${String(key)}, object is not extensible`) - } - throw typeError(`Cannot redefine property: ${String(key)}`) -} - -const requireTarget = (value: Value, name: string): Obj => { - if (value instanceof Obj) return value - throw typeError(`Object.${name} called on non-object`) -} - -// ObjectDefineProperties: every descriptor is read (getters included) before the first one is defined. -const defineProperties = (target: Obj, props: Value): Obj => { - if (props === null || props === undefined) throw typeError(`Cannot convert ${props} to object`) - // ToObject: a string's indexes are its only own enumerable properties; other primitives have none. - const descriptors = - props instanceof Obj - ? ownKeys(props) - .filter((key) => own(props, key)?.enumerable === true) - .map((key) => [key, toPropertyDescriptor(get(props, key))] as const) - : typeof props === "string" - ? [...props].map((char, index) => [String(index), toPropertyDescriptor(char)] as const) - : [] - if (readsPending()) return target - for (const [key, desc] of descriptors) defineOrThrow(target, key, desc) - return target -} - -// FromPropertyDescriptor: a native accessor half shows as its companion function. -const fromSlot = (builtins: Builtins, slot: Slot | undefined): Value => { - if (slot === undefined) return undefined - const fields: Record = - "value" in slot - ? { value: slot.value, writable: slot.writable } - : { get: accessorFunction(slot.get), set: accessorFunction(slot.set) } - return record(builtins.Object, { ...fields, enumerable: slot.enumerable, configurable: slot.configurable }) -} - -// The own properties a primitive has after ToObject, which only a string's are: its indexes and `length`. -const primitiveSlot = (value: Value, key: PropertyKey): Slot | undefined => { - if (typeof value !== "string") return undefined - if (key === "length") return { value: value.length, writable: false, enumerable: false, configurable: false } - const at = typeof key === "symbol" ? undefined : parseArrayIndex(key) - return at !== undefined && at < value.length - ? { value: value[at], writable: false, enumerable: true, configurable: false } - : undefined -} - -const primitiveKeys = (value: Value): Array => - typeof value === "string" ? [...Object.keys(value), "length"] : [] - -const requireObjectCoercible = (value: Value, name: string): void => { - if (value === null || value === undefined) throw typeError(`Object.${name} cannot convert ${value} to an object.`) - if (value instanceof HostNamespace) { - throw typeError(`Object.${name} cannot read ${value.root}: it is a namespace of host functions, not an object.`) - } -} - -// Object constructs identically with or without new, like JS. Only `keys` copies its result into the -// program; `values`, `entries`, `assign`, and `fromEntries` hand back the program's own values. -export const objectGlobal = (ctx: Interpreter) => { - const builtins = ctx.builtins - const construct = (args: Array): Value => { - const first = args[0] - if (first === null || first === undefined) return new Obj(builtins.Object) - if (first instanceof Obj) return first - throw typeError(`Object(${typeof first}) wrapper objects are not supported; use the primitive value directly.`) - } - const object = constructor(builtins, builtins.Object, { - name: "Object", - length: 1, - call: (_, args) => construct(args), - construct: (args) => construct(args), - }) - methods(builtins, object, [ - [ - "keys", - 1, - (_, args) => - new Arr( - builtins.Array, - args[0] instanceof HostNamespace - ? [...ctx.namespaceKeys(args[0])] - : keys(enumerableSource(ctx, "Object.keys(...)", args[0])), - ), - ], - [ - "values", - 1, - (_, args) => { - const source = enumerableSource(ctx, "Object.values(...)", args[0]) - if (source.hasProgramAccessors) - return new Invoke(ctx.prelude.fn("objectEntries"), undefined, [source, true], undefined) - return new Arr( - builtins.Array, - entries(source).map((entry) => entry[1]), - ) - }, - ], - [ - "entries", - 1, - (_, args) => { - const source = enumerableSource(ctx, "Object.entries(...)", args[0]) - if (source.hasProgramAccessors) - return new Invoke(ctx.prelude.fn("objectEntries"), undefined, [source, false], undefined) - return new Arr( - builtins.Array, - entries(source).map((entry) => new Arr(builtins.Array, entry)), - ) - }, - ], - ["hasOwn", 2, (_, args) => hasOwn(enumerableSource(ctx, "Object.hasOwn(...)", args[0]), propertyKey(args[1]))], - ["is", 2, (_, args) => Object.is(args[0], args[1])], - ["assign", 2, (_, args) => objectAssign(ctx, args)], - ["freeze", 1, (_, args) => restrict("freeze", args[0])], - ["seal", 1, (_, args) => restrict("seal", args[0])], - ["preventExtensions", 1, (_, args) => restrict("preventExtensions", args[0])], - ["isFrozen", 1, (_, args) => integrity(args[0], true)], - ["isSealed", 1, (_, args) => integrity(args[0], false)], - ["isExtensible", 1, (_, args) => args[0] instanceof Obj && args[0].extensible], - [ - "getPrototypeOf", - 1, - (_, args) => { - if (args[0] instanceof Obj) return args[0].proto - const proto = primitivePrototype(builtins, args[0]) - if (proto === undefined) { - throw typeError(`Object.getPrototypeOf cannot convert ${describeValue(args[0])} to an object.`) - } - return proto - }, - ], - [ - "create", - 2, - (_, args) => { - const proto = args[0] - if (proto !== null && !(proto instanceof Obj)) { - throw typeError("Object prototype may only be an Object or null.") - } - if (args[1] === undefined) return new Obj(proto) - return withReads(() => defineProperties(new Obj(proto), args[1])) - }, - ], - [ - "defineProperty", - 3, - (_, args) => { - const target = requireTarget(args[0], "defineProperty") - return withPrimitives("string", [args[1]], ([key]) => - withReads(() => { - const desc = toPropertyDescriptor(args[2]) - if (readsPending()) return target - defineOrThrow(target, propertyKey(key), desc) - return target - }), - ) - }, - ], - [ - "defineProperties", - 2, - (_, args) => { - const target = requireTarget(args[0], "defineProperties") - return withReads(() => defineProperties(target, args[1])) - }, - ], - [ - "getOwnPropertyDescriptor", - 2, - (_, args) => { - const value = args[0] - requireObjectCoercible(value, "getOwnPropertyDescriptor") - return withPrimitives("string", [args[1]], ([raw]) => { - const key = propertyKey(raw) - return fromSlot(builtins, value instanceof Obj ? own(value, key) : primitiveSlot(value, key)) - }) - }, - ], - [ - "getOwnPropertyDescriptors", - 1, - (_, args) => { - const value = args[0] - requireObjectCoercible(value, "getOwnPropertyDescriptors") - const result = new Obj(builtins.Object) - if (value instanceof Obj) - for (const key of ownKeys(value)) define(result, key, fromSlot(builtins, own(value, key))) - else for (const key of primitiveKeys(value)) define(result, key, fromSlot(builtins, primitiveSlot(value, key))) - return result - }, - ], - [ - "getOwnPropertyNames", - 1, - (_, args) => { - const value = args[0] - if (value instanceof HostNamespace) return new Arr(builtins.Array, [...ctx.namespaceKeys(value)]) - requireObjectCoercible(value, "getOwnPropertyNames") - const names = - value instanceof Obj ? ownKeys(value).filter((key) => typeof key === "string") : primitiveKeys(value) - return new Arr(builtins.Array, names) - }, - ], - ]) - methods(builtins, builtins.Object, [ - [ - "hasOwnProperty", - 1, - (thisValue, args) => hasOwn(receiver(Obj, thisValue, "Object.prototype.hasOwnProperty"), propertyKey(args[0])), - ], - [ - "isPrototypeOf", - 1, - (thisValue, args) => hasPrototype(args[0], receiver(Obj, thisValue, "Object.prototype.isPrototypeOf")), - ], - [ - "propertyIsEnumerable", - 1, - (thisValue, args) => - own(receiver(Obj, thisValue, "Object.prototype.propertyIsEnumerable"), propertyKey(args[0]))?.enumerable === - true, - ], - ["toString", 0, (thisValue) => `[object ${classTag(thisValue)}]`], - [ - "toLocaleString", - 0, - (thisValue) => - withReads(() => invokeMethod(ctx.builtins, thisValue, "toString", "Object.prototype.toLocaleString")), - ], - [ - "valueOf", - 0, - (thisValue) => { - if (thisValue === null || thisValue === undefined) { - throw typeError("Object.prototype.valueOf called on null or undefined.") - } - return thisValue - }, - ], - ]) - return object -} diff --git a/packages/codemode/src/language/stdlib/regexp.ts b/packages/codemode/src/language/stdlib/regexp.ts deleted file mode 100644 index 5a8fac99eb4..00000000000 --- a/packages/codemode/src/language/stdlib/regexp.ts +++ /dev/null @@ -1,152 +0,0 @@ -import type { Builtins } from "../runtime/intrinsics.js" -import { constructor, type Method, methods, prototypeFrom, receiver } from "../runtime/native.js" -import { syntaxError, typeError } from "../runtime/model.js" -import { - define, - defineAccessor, - Arr, - Obj, - RegExpObj, - record, - coerceToNumber, - coerceToString, - type Value, -} from "../runtime/objects.js" -import type { Interpreter } from "../runtime/interpreter.js" - -const flagProperties = [ - "hasIndices", - "global", - "ignoreCase", - "multiline", - "sticky", - "unicode", - "unicodeSets", - "dotAll", -] as const - -const regexFailureReason = (error: unknown): string => - (error instanceof Error ? error.message : String(error)).replace(/^Invalid regular expression:\s*/i, "") - -const escapeRegexHint = - 'To match special characters like ( ) [ ] { } + * ? . literally, escape them with a backslash (e.g. "\\\\(") or test for them with String.includes instead.' - -/** Runs host regex work on a RegExp argument, sharing its `lastIndex`, or on a pattern string compiled for the call. */ -export const withHostRegex = (arg: Value, method: string, extraFlags: string, work: (regex: RegExp) => T): T => { - if (arg instanceof RegExpObj) return arg.use(work) - // Anything else is a pattern string, as `new RegExp(arg)` would read it: undefined is the empty pattern. - const source = arg === undefined ? "" : coerceToString(arg) - return work(compilePattern(source, method, extraFlags)) -} - -const compilePattern = (source: string, method: string, extraFlags: string): RegExp => { - try { - return new RegExp(source, extraFlags) - } catch (error) { - throw syntaxError( - `String.${method} received the string ${JSON.stringify(source)}, which is not a valid regular expression pattern (${regexFailureReason(error)}). ${escapeRegexHint}`, - ) - } -} - -export const matchToValue = (builtins: Builtins, match: RegExpMatchArray): Arr => { - const result = new Arr( - builtins.Array, - Array.from(match, (group) => group), - ) - if (match.index !== undefined) define(result, "index", match.index) - if (match.input !== undefined) define(result, "input", match.input) - if (match.groups) define(result, "groups", record(builtins.Object, match.groups)) - if (match.indices) define(result, "indices", indicesToValue(builtins, match.indices)) - return result -} - -export const constructRegExp = (builtins: Builtins, args: Array, proto: Obj = builtins.RegExp): RegExpObj => { - const first = args[0] - const pattern = first instanceof RegExpObj ? first.source : first === undefined ? "" : coerceToString(first) - const flagsArg = args[1] - if (flagsArg !== undefined && typeof flagsArg !== "string") { - throw syntaxError( - `RegExp flags must be a string of flag characters (e.g. "g", "gi"), not ${flagsArg === null ? "null" : typeof flagsArg}.`, - ) - } - const flags = flagsArg ?? (first instanceof RegExpObj ? first.flags : "") - try { - return new RegExpObj(proto, pattern, flags) - } catch (error) { - const reason = regexFailureReason(error) - throw syntaxError( - /flag/i.test(reason) - ? `new RegExp(...) received invalid flags ${JSON.stringify(flags)} (${reason}). Valid flags are d, g, i, m, s, u, v, and y.` - : `new RegExp(...) received ${JSON.stringify(pattern)}, which is not a valid regular expression pattern (${reason}). ${escapeRegexHint}`, - ) - } -} - -// RegExp constructs identically with or without new, like JS. -export const regexpGlobal = (ctx: Interpreter) => { - const builtins = ctx.builtins - const proto = builtins.RegExp - const regexp = constructor(builtins, proto, { - name: "RegExp", - length: 2, - call: (_, args) => constructRegExp(builtins, args), - construct: (args, newTarget) => constructRegExp(builtins, args, prototypeFrom(newTarget, proto)), - }) - methods(builtins, regexp, [ - [ - "escape", - 1, - (_, args) => { - if (typeof args[0] !== "string") throw typeError("RegExp.escape expects a string.") - return RegExp.escape(args[0]) - }, - ], - ]) - - const self = (thisValue: Value, name: string) => receiver(RegExpObj, thisValue, `RegExp.prototype.${name}`) - defineAccessor(proto, "source", (thisValue) => self(thisValue, "source").source) - defineAccessor(proto, "flags", (thisValue) => self(thisValue, "flags").flags) - // One lastIndex per RegExp, so exec/test and the String methods share one counter. - defineAccessor( - proto, - "lastIndex", - (thisValue) => self(thisValue, "lastIndex").lastIndex, - (thisValue, value) => { - self(thisValue, "lastIndex").lastIndex = coerceToNumber(value) - }, - ) - for (const name of flagProperties) defineAccessor(proto, name, (thisValue) => self(thisValue, name).regex[name]) - const run = (name: "exec" | "test"): Method => [ - name, - 1, - (thisValue, args) => { - const value = self(thisValue, name) - const input = coerceToString(args[0]) - const matched = value.use((regex) => regex.exec(input)) - if (name === "test") return matched !== null - return matched === null ? null : matchToValue(builtins, matched) - }, - ] - methods(builtins, proto, [ - run("exec"), - run("test"), - ["toString", 0, (thisValue) => coerceToString(self(thisValue, "toString"))], - ]) - return regexp -} - -const indicesToValue = (builtins: Builtins, indices: RegExpIndicesArray): Arr => { - const range = (pair: [number, number] | undefined) => - pair === undefined ? undefined : new Arr(builtins.Array, [...pair]) - const result = new Arr(builtins.Array, Array.from(indices, range)) - const groups = indices.groups - define( - result, - "groups", - groups === undefined - ? undefined - : record(builtins.Object, Object.fromEntries(Object.entries(groups).map(([key, pair]) => [key, range(pair)]))), - ) - return result -} diff --git a/packages/codemode/src/language/stdlib/string.ts b/packages/codemode/src/language/stdlib/string.ts deleted file mode 100644 index 5faf17f27c5..00000000000 --- a/packages/codemode/src/language/stdlib/string.ts +++ /dev/null @@ -1,427 +0,0 @@ -import { type Hint, Invoke } from "../runtime/signals.js" -import { constructor, fn, type Method, methods } from "../runtime/native.js" -import { checkArrayLength, checkStringLength } from "../runtime/limits.js" -import { invalidData, IteratorSymbol, rangeError, typeError } from "../runtime/model.js" -import { - define, - get, - hidden, - Arr, - positionIterator, - Obj, - RegExpObj, - record, - coerceToInteger, - coerceToNumber, - coerceToString, - type NativeResult, - type Value, -} from "../runtime/objects.js" -import { containsOpaqueReference, typeofValue } from "../runtime/references.js" -import { isSupportedCallback, requireCallback, withPrimitives, withReads } from "../runtime/callback.js" -import type { Interpreter } from "../runtime/interpreter.js" -import { matchToValue, withHostRegex } from "./regexp.js" -import { coerce } from "./value.js" - -// console is intercepted by the interpreter before reaching here. -const requireDataArgument = (name: string, index: number, arg: Value): Value => { - if (containsOpaqueReference(arg)) { - throw invalidData(`String.${name} expects argument ${index + 1} to be a data value.`) - } - return arg -} - -const replaceAllNeedsGlobal = (pattern: RegExp) => { - if (!pattern.global) { - throw typeError( - `String.replaceAll requires a regular expression with the global (g) flag: write /${pattern.source}/${pattern.flags}g, or use String.replace to replace only the first match.`, - ) - } -} - -// The matches are found first, as the host replaces; then the callback runs for each in order. -const replaceWithCallback = ( - ctx: Interpreter, - value: string, - name: "replace" | "replaceAll", - args: Array, -): Invoke => { - const builtins = ctx.builtins - const callback = requireCallback(args[1], `String.${name}`) - const matches: Array = [] - // The host calls back with (match, ...captures, offset, string, groups?); only groups is not already a Value. - const collect = ( - ...callbackArgs: Array> - ): string => { - const match = callbackArgs[0] - const hasGroups = typeof callbackArgs.at(-1) === "object" - const offset = callbackArgs[callbackArgs.length - (hasGroups ? 3 : 2)] - if (typeof match !== "string" || typeof offset !== "number") { - throw typeError(`String.${name} produced an invalid replacement match.`) - } - const args = callbackArgs.map((arg) => (typeof arg === "object" ? record(builtins.Object, arg) : arg)) - matches.push({ match, offset, args }) - return match - } - - const pattern = args[0] - if (pattern instanceof RegExpObj) { - pattern.use((regex) => { - if (name === "replaceAll") replaceAllNeedsGlobal(regex) - if (name === "replace") value.replace(regex, collect) - else value.replaceAll(regex, collect) - }) - } else { - const search = coerceToString(requireDataArgument(name, 0, pattern)) - if (name === "replace") value.replace(search, collect) - else value.replaceAll(search, collect) - } - const pieces = matches.map( - (match, index) => - new Arr(builtins.Array, [ - value.slice(index === 0 ? 0 : matches[index - 1]!.offset + matches[index - 1]!.match.length, match.offset), - new Arr(builtins.Array, match.args), - ]), - ) - const last = matches.at(-1) - const rest = value.slice(last === undefined ? 0 : last.offset + last.match.length) - return new Invoke( - ctx.prelude.fn("replaceWith"), - undefined, - [new Arr(builtins.Array, pieces), rest, callback], - undefined, - ) -} - -type Match = { readonly match: string; readonly offset: number; readonly args: Array } - -// The options Intl.Collator reads; the boolean ones take an object as true instead of converting it. -const collatorOptions = ["usage", "localeMatcher", "collation", "numeric", "caseFirst", "sensitivity", "ignorePunctuation"] -const collatorFlags = new Set(["numeric", "ignorePunctuation"]) - -export const stringGlobal = (ctx: Interpreter) => { - const builtins = ctx.builtins - const string = constructor(builtins, builtins.String, { - name: "String", - length: 1, - call: (_, args) => coerce(ctx, "String", args), - }) - const codeUnits = (name: string, op: (...codes: Array) => string): Method => [ - name, - 1, - (_, args) => op(...args.map(coerceToNumber)), - ] - methods(builtins, string, [ - codeUnits("fromCharCode", String.fromCharCode), - codeUnits("fromCodePoint", String.fromCodePoint), - [ - "raw", - 1, - (_, args) => - withReads(() => { - const template = args[0] - const raw = template instanceof Obj ? get(template, "raw") : undefined - if (!(raw instanceof Obj)) throw typeError("String.raw expects a template object with a raw array.") - const count = Math.max(0, coerceToInteger(get(raw, "length"))) - checkArrayLength(count) - // Each literal is followed by its substitution, except the last literal, or when substitutions run out. - const parts = Array.from({ length: count }, (_, index) => - index + 1 < count && index + 1 < args.length ? [get(raw, index), args[index + 1]] : [get(raw, index)], - ).flat() - return withPrimitives( - "string", - parts, - (strings) => { - const output = strings.map(coerceToString).join("") - checkStringLength(output.length) - return output - }, - true, - ) - }), - ], - ]) - - const self = (thisValue: Value, name: string): string => { - if (typeof thisValue === "string") return thisValue - if (thisValue === null || thisValue === undefined) { - throw typeError(`String.prototype.${name} called on null or undefined.`) - } - return coerceToString(thisValue) - } - // Coerce arguments like native JS; opaque runtime references still reject. - const str = (name: string, args: Array, index: number): string => - coerceToString(requireDataArgument(name, index, args[index])) - const num = (name: string, args: Array, index: number): number => - coerceToNumber(requireDataArgument(name, index, args[index])) - const optNum = (name: string, args: Array, index: number): number | undefined => - args[index] === undefined ? undefined : num(name, args, index) - const optStr = (name: string, args: Array, index: number): string | undefined => - args[index] === undefined ? undefined : str(name, args, index) - // ToPrimitive in spec order: the receiver, then the arguments the method consumes, one hint per position; the - // rest pass through as they are. - const simple = ( - name: string, - length: number, - op: (value: string, args: Array) => NativeResult, - hints: ReadonlyArray = [], - ): Method => [ - name, - length, - (thisValue, args) => { - if (thisValue === null || thisValue === undefined) { - throw typeError(`String.prototype.${name} called on null or undefined.`) - } - return withPrimitives( - ["string", ...hints], - [thisValue, ...args.slice(0, hints.length)], - ([value, ...primitives]) => op(coerceToString(value), [...primitives, ...args.slice(hints.length)]), - ) - }, - ] - // includes, startsWith, and endsWith reject a RegExp before converting their search string and position. - const searching = (name: string, op: (value: string, search: string, position: number | undefined) => boolean) => - simple(name, 1, (value, args) => { - if (args[0] instanceof RegExpObj) { - throw typeError( - `String.${name} cannot take a regular expression; use regex.test(string) or String.search instead.`, - ) - } - return withPrimitives(["string", "number"], args.slice(0, 2), (primitives) => - op(value, str(name, primitives, 0), optNum(name, primitives, 1)), - ) - }) - // match, matchAll, and search read a RegExp as is and convert anything else to its pattern text. - const withPattern = (args: Array, op: (pattern: Value) => Value) => - args[0] instanceof RegExpObj ? op(args[0]) : withPrimitives("string", [args[0]], ([text]) => op(text)) - const replace = (name: "replace" | "replaceAll") => - simple(name, 2, (value, args) => { - const pattern = args[0] - const replacer = args[1] - // A RegExp pattern is used as is; a plain one converts to its search string, then a non-callable replacement. - return withPrimitives( - "string", - [pattern instanceof RegExpObj ? undefined : pattern, isSupportedCallback(replacer) ? undefined : replacer], - ([search, replacement]) => { - if (isSupportedCallback(replacer)) { - return replaceWithCallback(ctx, value, name, [pattern instanceof RegExpObj ? pattern : search, replacer]) - } - if (typeofValue(replacer) === "function") { - throw typeError( - `String.${name} cannot use this callable as a replacer; wrap it in an arrow function, e.g. (match) => fn(match).`, - ) - } - const primitives = [search, replacement] - if (pattern instanceof RegExpObj) { - const text = str(name, primitives, 1) - return pattern.use((regex) => { - if (name === "replaceAll") replaceAllNeedsGlobal(regex) - return name === "replace" ? value.replace(regex, text) : value.replaceAll(regex, text) - }) - } - if (name === "replace") return value.replace(str(name, primitives, 0), str(name, primitives, 1)) - return value.replaceAll(str(name, primitives, 0), str(name, primitives, 1)) - }, - ) - }) - - methods(builtins, builtins.String, [ - simple("toString", 0, (value) => value), - simple("valueOf", 0, (value) => value), - simple("toLowerCase", 0, (value) => value.toLowerCase()), - simple("toUpperCase", 0, (value) => value.toUpperCase()), - simple("toLocaleLowerCase", 0, (value) => value.toLowerCase()), - simple("toLocaleUpperCase", 0, (value) => value.toUpperCase()), - simple("trim", 0, (value) => value.trim()), - simple("trimStart", 0, (value) => value.trimStart()), - simple("trimLeft", 0, (value) => value.trimStart()), - simple("trimEnd", 0, (value) => value.trimEnd()), - simple("trimRight", 0, (value) => value.trimEnd()), - simple("localeCompare", 1, (value, args) => { - const that = str("localeCompare", args, 0) - if (args[1] === undefined && args[2] === undefined) return value.localeCompare(that) - const locales = args[1] - const options = args[2] - if (locales === null || options === null) { - throw typeError("String.localeCompare cannot take null locales or options; pass undefined for the defaults.") - } - return withReads(() => { - // The host collator reads a locale list and these options; objects among them convert to strings first. - const length = locales instanceof Obj ? Math.max(0, coerceToInteger(get(locales, "length"))) : 0 - checkArrayLength(length) - const list = locales instanceof Obj ? Array.from({ length }, (_, index) => get(locales, index)) : undefined - const read = options instanceof Obj ? collatorOptions.map((key) => get(options, key)) : [] - const flags = read.map((option, index) => - collatorFlags.has(collatorOptions[index]!) && option instanceof Obj ? true : option, - ) - return withPrimitives("string", [...(list ?? []), ...flags], (primitives) => { - const hostLocales = list === undefined ? locales : primitives.slice(0, list.length) - const hostOptions = - options instanceof Obj - ? Object.fromEntries(collatorOptions.map((key, index) => [key, primitives[(list?.length ?? 0) + index]])) - : options - try { - return value.localeCompare(that, hostLocales as string | Array, hostOptions as Intl.CollatorOptions) - } catch (error) { - if (error instanceof RangeError) throw rangeError(`String.localeCompare: ${error.message}`) - if (error instanceof TypeError) throw typeError(`String.localeCompare: ${error.message}`) - throw error - } - }) - }) - }, ["string"]), - simple( - "normalize", - 0, - (value, args) => { - const form = optStr("normalize", args, 0) - try { - return value.normalize(form) - } catch { - throw rangeError( - `String.normalize expects the form "NFC", "NFD", "NFKC", or "NFKD" (got ${JSON.stringify(form)}).`, - ) - } - }, - ["string"], - ), - simple("split", 2, (value, args) => { - const separator = args[0] - // A RegExp separator is used as is; the limit converts before a plain separator does, as in the spec. - return withPrimitives( - ["number", "string"], - [args[1], separator instanceof RegExpObj ? undefined : separator], - ([limit, pattern]) => { - const wrap = (parts: Array) => new Arr(builtins.Array, parts) - // Native: an undefined separator returns the whole string, not a split on "undefined", - // unless the limit truncates to zero. - const requestedLimit = args[1] === undefined ? undefined : num("split", [pattern, limit], 1) - if (separator === undefined) { - return wrap(requestedLimit !== undefined && requestedLimit >>> 0 === 0 ? [] : [value]) - } - const parts = - separator instanceof RegExpObj - ? separator.use((regex) => value.split(regex, requestedLimit)) - : value.split(str("split", [pattern], 0), requestedLimit === undefined ? undefined : requestedLimit >>> 0) - checkArrayLength(parts.length) - return wrap(parts) - }, - ) - }), - simple("slice", 2, (value, args) => value.slice(optNum("slice", args, 0), optNum("slice", args, 1)), [ - "number", - "number", - ]), - searching("includes", (value, search, position) => value.includes(search, position)), - searching("startsWith", (value, search, position) => value.startsWith(search, position)), - searching("endsWith", (value, search, position) => value.endsWith(search, position)), - simple("indexOf", 1, (value, args) => value.indexOf(str("indexOf", args, 0), optNum("indexOf", args, 1)), [ - "string", - "number", - ]), - simple( - "lastIndexOf", - 1, - (value, args) => value.lastIndexOf(str("lastIndexOf", args, 0), optNum("lastIndexOf", args, 1)), - ["string", "number"], - ), - replace("replace"), - replace("replaceAll"), - simple("match", 1, (value, args) => - withPattern(args, (arg) => - withHostRegex(arg, "match", "", (regex) => { - const matched = value.match(regex) - if (matched === null) return null - // Preserve the own `index` and `groups` properties on non-global matches. - if (regex.global) return new Arr(builtins.Array, [...matched]) - return matchToValue(builtins, matched) - }), - ), - ), - simple("matchAll", 1, (value, args) => - withPattern(args, (arg) => - withHostRegex(arg, "matchAll", "g", (regex) => { - if (!regex.global) { - throw typeError( - `String.matchAll requires a regular expression with the global (g) flag: write /${regex.source}/${regex.flags}g, or use String.match for a single match.`, - ) - } - const matches: Array = [] - for (const match of value.matchAll(regex)) { - checkArrayLength(matches.length + 1) - matches.push(matchToValue(builtins, match)) - } - return new Arr(builtins.Array, matches) - }), - ), - ), - simple("search", 1, (value, args) => - withPattern(args, (arg) => withHostRegex(arg, "search", "", (regex) => value.search(regex))), - ), - simple( - "repeat", - 1, - (value, args) => { - const count = num("repeat", args, 0) - if (!Number.isFinite(count) || count < 0) { - throw rangeError("String.repeat expects a finite non-negative count.") - } - checkStringLength(value.length * count) - return value.repeat(count) - }, - ["number"], - ), - simple( - "padStart", - 1, - (value, args) => { - const length = num("padStart", args, 0) - checkStringLength(length) - return value.padStart(length, optStr("padStart", args, 1)) - }, - ["number", "string"], - ), - simple( - "padEnd", - 1, - (value, args) => { - const length = num("padEnd", args, 0) - checkStringLength(length) - return value.padEnd(length, optStr("padEnd", args, 1)) - }, - ["number", "string"], - ), - simple("charAt", 1, (value, args) => value.charAt(optNum("charAt", args, 0) ?? 0), ["number"]), - simple("at", 1, (value, args) => value.at(optNum("at", args, 0) ?? 0), ["number"]), - simple( - "substring", - 2, - (value, args) => value.substring(optNum("substring", args, 0) ?? 0, optNum("substring", args, 1)), - ["number", "number"], - ), - simple("substr", 2, (value, args) => value.substr(optNum("substr", args, 0) ?? 0, optNum("substr", args, 1)), [ - "number", - "number", - ]), - simple("isWellFormed", 0, (value) => value.isWellFormed()), - simple("toWellFormed", 0, (value) => value.toWellFormed()), - simple("charCodeAt", 1, (value, args) => value.charCodeAt(optNum("charCodeAt", args, 0) ?? 0), ["number"]), - simple("codePointAt", 1, (value, args) => value.codePointAt(optNum("codePointAt", args, 0) ?? 0), ["number"]), - simple("concat", 1, (value, args) => - withPrimitives("string", args, (parts) => { - const joined = value.concat(...parts.map((_, index) => str("concat", parts, index))) - checkStringLength(joined.length) - return joined - }), - ), - ]) - define( - builtins.String, - IteratorSymbol, - fn(builtins, "[Symbol.iterator]", 0, (thisValue) => - positionIterator(builtins, self(thisValue, "[Symbol.iterator]"), "values"), - ), - hidden, - ) - return string -} diff --git a/packages/codemode/src/language/stdlib/url.ts b/packages/codemode/src/language/stdlib/url.ts deleted file mode 100644 index 9efe74aa8a1..00000000000 --- a/packages/codemode/src/language/stdlib/url.ts +++ /dev/null @@ -1,310 +0,0 @@ -import { Invoke } from "../runtime/signals.js" -import { - constructor, - fn, - type Method, - methods, - prototypeFrom, - receiver, - requiresNew, - iteratorMethods, -} from "../runtime/native.js" -import { IteratorSymbol, PendingThrow, typeError, uriError } from "../runtime/model.js" -import { - define, - defineAccessor, - entries, - get, - hidden, - Arr, - Obj, - URLObj, - URLSearchParamsObj, - HeadersObj, - type Callable, - coerceToString, - isRuntimeReference, - type Value, -} from "../runtime/objects.js" -import { requireCallback } from "../runtime/callback.js" -import type { Interpreter } from "../runtime/interpreter.js" - -const urlProperties = [ - "href", - "origin", - "protocol", - "username", - "password", - "host", - "hostname", - "port", - "pathname", - "search", - "hash", -] as const - -type UriFunction = "encodeURI" | "encodeURIComponent" | "decodeURI" | "decodeURIComponent" - -const uriFunctions: Record string> = { - encodeURI, - encodeURIComponent, - decodeURI, - decodeURIComponent, -} - -export const uriGlobal = (ctx: Interpreter, name: UriFunction) => - fn(ctx.builtins, name, 1, (_, args) => { - const value = coerceToString(args[0]) - try { - return uriFunctions[name](value) - } catch (error) { - throw uriError(`${name} received malformed URI data: ${error instanceof Error ? error.message : String(error)}`) - } - }) - -const urlArgument = (value: Value): string => (value instanceof URLObj ? value.url.href : coerceToString(value)) - -export const urlGlobal = (ctx: Interpreter) => { - const builtins = ctx.builtins - const proto = builtins.URL - const construct = (args: Array, into: Obj): URLObj => { - if (args.length === 0) { - throw typeError("new URL(...) requires a URL string and an optional base URL.") - } - const input = urlArgument(args[0]) - const base = args[1] === undefined ? undefined : urlArgument(args[1]) - try { - return new URLObj(into, builtins.URLSearchParams, new URL(input, base)) - } catch { - throw typeError(`new URL(...) received an invalid URL${base === undefined ? "" : " or base URL"}.`) - } - } - const url = constructor(builtins, proto, { - name: "URL", - length: 1, - call: requiresNew("URL"), - construct: (args, newTarget) => construct(args, prototypeFrom(newTarget, proto)), - }) - const parse = (name: "canParse" | "parse"): Method => [ - name, - 1, - (_, args) => { - if (args.length === 0) throw typeError(`URL.${name} requires a URL argument.`) - const input = urlArgument(args[0]) - const base = args[1] === undefined ? undefined : urlArgument(args[1]) - try { - const parsed = new URL(input, base) - return name === "canParse" ? true : new URLObj(proto, builtins.URLSearchParams, parsed) - } catch { - return name === "canParse" ? false : null - } - }, - ] - methods(builtins, url, [parse("canParse"), parse("parse")]) - - const self = (thisValue: Value, name: string) => receiver(URLObj, thisValue, `URL.prototype.${name}`) - for (const name of urlProperties) { - defineAccessor( - proto, - name, - (thisValue) => self(thisValue, name).url[name], - name === "origin" - ? undefined - : (thisValue, value) => { - const target = self(thisValue, name) - try { - target.url[name] = coerceToString(value) - } catch (error) { - if (error instanceof PendingThrow) throw error - throw typeError(`URL.${name} received an invalid value.`) - } - }, - ) - } - defineAccessor(proto, "searchParams", (thisValue) => self(thisValue, "searchParams").searchParams) - methods(builtins, proto, [ - ["toString", 0, (thisValue) => self(thisValue, "toString").url.href], - ["toJSON", 0, (thisValue) => self(thisValue, "toJSON").url.href], - ]) - return url -} - -/** What `readPairs` builds from `[name, value]` pairs, or from a record of names to values when `init` is no iterable. */ -export type PairsInto = { readonly kind: "Headers" | "URLSearchParams"; readonly proto: Obj } - -/** - * Reads a synchronous iterable of `[name, value]` pairs as strings (in the prelude), then builds `into` from them; a - * record of names to values when `init` is not iterable. As in WebIDL, the whole sequence is converted before any - * pair's length is checked. - */ -export const readPairs = (ctx: Interpreter, init: Value, label: string, into: PairsInto) => - new Invoke(ctx.prelude.fn("readPairs"), undefined, [init, label, into.kind, into.proto], undefined) - -/** What `readPairs` makes of the pairs it read (an array of arrays of strings), or of a record. */ -export const buildPairs = (into: PairsInto, value: Value, label: string): Value => { - if (!(value instanceof Arr)) return fromRecord(into, value) - const pairs = value.items.map((pair) => (pair as Arr).items as Array) - if (pairs.some((entry) => entry.length !== 2)) throw typeError(`${label} expects iterable [name, value] pairs.`) - if (into.kind === "URLSearchParams") { - return new URLSearchParamsObj(into.proto, new URLSearchParams(pairs as Array<[string, string]>)) - } - return new HeadersObj( - into.proto, - attempt(() => new Headers(pairs as Array<[string, string]>)), - ) -} - -const fromRecord = (into: PairsInto, init: Value): Value => { - if (into.kind === "Headers") { - if (!(init instanceof Obj) || isRuntimeReference(init)) { - throw typeError("new Headers(...) expects a record of names to values, iterable [name, value] pairs, or Headers.") - } - return new HeadersObj( - into.proto, - attempt(() => new Headers(Object.fromEntries(entries(init).map(([key, value]) => [key, coerceToString(value)])))), - ) - } - if (isRuntimeReference(init)) { - throw typeError("new URLSearchParams(...) expects a query string, data object, or synchronous iterable pairs.") - } - if (!(init instanceof Obj)) { - throw typeError("new URLSearchParams(...) expects a query string, data object, iterable pairs, or URLSearchParams.") - } - return new URLSearchParamsObj( - into.proto, - new URLSearchParams(Object.fromEntries(entries(init).map(([key, value]) => [key, coerceToString(value)]))), - ) -} - -/** The host validates header names and values and throws its own TypeError; the program gets one of its own. */ -export const attempt = (run: () => T): T => { - try { - return run() - } catch (error) { - throw typeError(error instanceof Error ? error.message : String(error)) - } -} - -/** Headers and URLSearchParams `forEach`: the callback sees each `[name, value]` pair as listed when it started. */ -export const pairsForEach = ( - ctx: Interpreter, - target: Value, - pairs: Array<[string, string]>, - callback: Callable, - thisArg: Value, -) => { - const list = new Arr( - ctx.builtins.Array, - pairs.map((pair) => new Arr(ctx.builtins.Array, pair)), - ) - return new Invoke(ctx.prelude.fn("pairsForEach"), undefined, [target, list, callback, thisArg], undefined) -} - -const constructURLSearchParams = (ctx: Interpreter, init: Value, proto: Obj) => { - const wrap = (params: URLSearchParams) => new URLSearchParamsObj(proto, params) - if (init === undefined) return wrap(new URLSearchParams()) - if (init instanceof URLSearchParamsObj) return wrap(new URLSearchParams(init.params)) - if (typeof init === "string") return wrap(new URLSearchParams(init)) - if (init === null || typeof init === "number" || typeof init === "boolean") { - return wrap(new URLSearchParams(coerceToString(init))) - } - return readPairs(ctx, init, "new URLSearchParams(...)", { kind: "URLSearchParams", proto }) -} - -export const urlSearchParamsGlobal = (ctx: Interpreter) => { - const builtins = ctx.builtins - const proto = builtins.URLSearchParams - const searchParams = constructor(builtins, proto, { - name: "URLSearchParams", - call: requiresNew("URLSearchParams"), - construct: (args, newTarget) => constructURLSearchParams(ctx, args[0], prototypeFrom(newTarget, proto)), - }) - const self = (thisValue: Value, name: string) => - receiver(URLSearchParamsObj, thisValue, `URLSearchParams.prototype.${name}`) - const wrap = (items: Array) => new Arr(builtins.Array, items) - const arg = (args: Array, index: number): string => coerceToString(args[index]) - const requireArgs = (name: string, args: Array, count: number): void => { - if (args.length < count) { - throw typeError(`URLSearchParams.${name} requires ${count} argument${count === 1 ? "" : "s"}.`) - } - } - defineAccessor(proto, "size", (thisValue) => self(thisValue, "size").params.size) - methods(builtins, proto, [ - [ - "append", - 2, - (thisValue, args) => { - requireArgs("append", args, 2) - self(thisValue, "append").params.append(arg(args, 0), arg(args, 1)) - return undefined - }, - ], - [ - "delete", - 1, - (thisValue, args) => { - requireArgs("delete", args, 1) - const params = self(thisValue, "delete").params - if (args[1] !== undefined) params.delete(arg(args, 0), arg(args, 1)) - else params.delete(arg(args, 0)) - return undefined - }, - ], - [ - "get", - 1, - (thisValue, args) => { - requireArgs("get", args, 1) - return self(thisValue, "get").params.get(arg(args, 0)) - }, - ], - [ - "getAll", - 1, - (thisValue, args) => { - requireArgs("getAll", args, 1) - return wrap(self(thisValue, "getAll").params.getAll(arg(args, 0))) - }, - ], - [ - "has", - 1, - (thisValue, args) => { - requireArgs("has", args, 1) - const params = self(thisValue, "has").params - return args[1] !== undefined ? params.has(arg(args, 0), arg(args, 1)) : params.has(arg(args, 0)) - }, - ], - [ - "set", - 2, - (thisValue, args) => { - requireArgs("set", args, 2) - self(thisValue, "set").params.set(arg(args, 0), arg(args, 1)) - return undefined - }, - ], - [ - "sort", - 0, - (thisValue) => { - self(thisValue, "sort").params.sort() - return undefined - }, - ], - ...iteratorMethods(builtins, self), - ["toString", 0, (thisValue) => self(thisValue, "toString").params.toString()], - [ - "forEach", - 1, - (thisValue, args) => { - requireArgs("forEach", args, 1) - const target = self(thisValue, "forEach") - const callback = requireCallback(args[0], "URLSearchParams.forEach") - return pairsForEach(ctx, target, Array.from(target.params.entries()), callback, args[1]) - }, - ], - ]) - define(proto, IteratorSymbol, get(proto, "entries"), hidden) - return searchParams -} diff --git a/packages/codemode/src/language/stdlib/value.ts b/packages/codemode/src/language/stdlib/value.ts deleted file mode 100644 index 8fb96a45fc7..00000000000 --- a/packages/codemode/src/language/stdlib/value.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { fn } from "../runtime/native.js" -import { coerceToNumber, coerceToString, type Native, type Value } from "../runtime/objects.js" -import type { Interpreter } from "../runtime/interpreter.js" -import { withPrimitives } from "../runtime/callback.js" - -export type Coercion = "Number" | "String" | "Boolean" | "parseInt" | "parseFloat" | "isFinite" | "isNaN" - -export const coerce = (ctx: Interpreter, name: Coercion, args: Array) => { - // Native: Number() is 0 and String() is "", unlike their undefined-argument forms; the - // other coercers match native through the undefined-argument path below. - if (args.length === 0) { - if (name === "Number") return 0 - if (name === "String") return "" - } - const raw = args[0] - if (name === "Boolean") return Boolean(raw) - if (name === "parseInt") { - return withPrimitives(["string", "number"], [raw, args[1]], ([text, radix]) => - parseInt(coerceToString(text), coerceToNumber(radix)), - ) - } - return withPrimitives(name === "String" || name === "parseFloat" ? "string" : "number", [raw], ([value]) => { - if (name === "Number") return coerceToNumber(value) - if (name === "isFinite") return Number.isFinite(coerceToNumber(value)) - if (name === "isNaN") return Number.isNaN(coerceToNumber(value)) - if (name === "parseFloat") return parseFloat(coerceToString(value)) - return coerceToString(value) - }) -} - -/** A global coercion function such as `Number` or `parseInt`. */ -export const coercion = (ctx: Interpreter, name: Coercion, length = 1): Native => - fn(ctx.builtins, name, length, (_, args) => coerce(ctx, name, args)) diff --git a/packages/codemode/src/language/stdlib/web.ts b/packages/codemode/src/language/stdlib/web.ts deleted file mode 100644 index 5b0d0b74f2c..00000000000 --- a/packages/codemode/src/language/stdlib/web.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { fn, methods } from "../runtime/native.js" -import { withReads } from "../runtime/callback.js" -import { typeError } from "../runtime/model.js" -import { - define, - entries, - get, - getOwn, - hasOwn, - hidden, - isRuntimeReference, - Arr, - Bytes, - DateObj, - ErrorObj, - HostNamespace, - MapObj, - Obj, - RegExpObj, - SetObj, - WeakMapObj, - WeakSetObj, - coerceToString, - type Value, -} from "../runtime/objects.js" -import { createErrorValue, isErrorType } from "../runtime/intrinsics.js" -import { describeValue } from "../runtime/references.js" -import type { Interpreter } from "../runtime/interpreter.js" - -// WebIDL DOMString conversion: a missing argument is a TypeError, anything else stringifies. Invalid input is a -// TypeError as well; browsers throw a DOMException named InvalidCharacterError, which CodeMode does not have. -export const base64Global = (ctx: Interpreter, name: "atob" | "btoa") => - fn(ctx.builtins, name, 1, (_, args) => { - if (args.length === 0) throw typeError(`${name} requires 1 argument (a string)`) - const input = coerceToString(args[0]) - try { - return name === "atob" ? atob(input) : btoa(input) - } catch { - throw typeError("The string contains invalid characters.") - } - }) - -// HTML structured clone over CodeMode's data kinds. Shared references survive through the memo; prototypes and -// frozen state do not, as in JS. Without a DOMException, DataCloneError is a TypeError carrying that prefix. -export const structuredCloneGlobal = (ctx: Interpreter) => - fn(ctx.builtins, "structuredClone", 1, (_, args) => { - if (args.length === 0) throw typeError("structuredClone requires 1 argument") - const builtins = ctx.builtins - const memo = new Map() - const clone = (value: Value): Value => { - if (typeof value === "symbol" || value instanceof HostNamespace) { - throw typeError(`DataCloneError: ${describeValue(value)} could not be cloned.`) - } - if (!(value instanceof Obj)) return value - const seen = memo.get(value) - if (seen !== undefined) return seen - const remember = (copy: T): T => { - memo.set(value, copy) - return copy - } - if (value instanceof MapObj) { - const copy = remember(new MapObj(builtins.Map)) - for (const [key, item] of value.map) copy.map.set(clone(key), clone(item)) - return copy - } - if (value instanceof SetObj) { - const copy = remember(new SetObj(builtins.Set)) - for (const item of value.set.liveKeys()) copy.set.add(clone(item)) - return copy - } - if (value instanceof DateObj) return remember(new DateObj(builtins.Date, value.time)) - if (value instanceof RegExpObj) { - return remember(new RegExpObj(builtins.RegExp, value.source, value.flags)) - } - if (value instanceof Bytes) return remember(new Bytes(builtins.Uint8Array, new Uint8Array(value.bytes))) - if (value instanceof ErrorObj) { - const name = get(value, "name") - const message = get(value, "message") - const copy = remember( - createErrorValue( - builtins[typeof name === "string" && isErrorType(name) ? name : "Error"], - message === undefined ? undefined : coerceToString(message), - ), - ) - const stack = getOwn(value, "stack") - if (typeof stack === "string") define(copy, "stack", stack, hidden) - if (hasOwn(value, "cause")) define(copy, "cause", clone(getOwn(value, "cause")), hidden) - return copy - } - if (isRuntimeReference(value) || value instanceof WeakMapObj || value instanceof WeakSetObj) { - throw typeError(`DataCloneError: ${describeValue(value)} could not be cloned.`) - } - const copy = remember( - value instanceof Arr ? new Arr(builtins.Array, new Array(value.items.length)) : new Obj(builtins.Object), - ) - for (const [key, item] of entries(value)) define(copy, key, clone(item)) - return copy - } - return withReads(() => { - memo.clear() - return clone(args[0]) - }) - }) - -export const cryptoGlobal = (ctx: Interpreter) => { - const object = new Obj(ctx.builtins.Object) - methods(ctx.builtins, object, [ - ["randomUUID", 0, () => crypto.randomUUID()], - [ - "getRandomValues", - 1, - (_, args) => { - if (!(args[0] instanceof Bytes)) { - throw typeError(`crypto.getRandomValues expects a Uint8Array, received ${describeValue(args[0])}.`) - } - crypto.getRandomValues(args[0].bytes) - return args[0] - }, - ], - ]) - return object -} diff --git a/packages/codemode/src/language/streaming-response.ts b/packages/codemode/src/language/streaming-response.ts deleted file mode 100644 index a2c0afe1191..00000000000 --- a/packages/codemode/src/language/streaming-response.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** - * A live web `Response` a host function hands the program, whose body the host streams for the lifetime of the run. - * The program sees a `Response`: `url`, `status`, `statusText`, `ok`, `redirected`, `headers`, a live `bodyUsed`, - * `text()`, `json()`, `bytes()`, `arrayBuffer()`, and a `body` it can read with a reader or `for await`. - */ -export class StreamingResponse { - constructor( - readonly response: Response, - readonly redirected = response.redirected, - ) {} -} diff --git a/packages/codemode/src/language/vm.ts b/packages/codemode/src/language/vm.ts deleted file mode 100644 index 4a97d5d04f8..00000000000 --- a/packages/codemode/src/language/vm.ts +++ /dev/null @@ -1,3706 +0,0 @@ -import { parse, type Expression, type MemberExpression, type NewExpression } from "acorn" -import type { Diagnostic } from "./runtime/model.js" -import { conversions } from "./runtime/callback.js" -import { locate, materialize, stackFrame } from "./runtime/errors.js" -import type { Interpreter } from "./runtime/interpreter.js" -import { type Builtins, isErrorType } from "./runtime/intrinsics.js" -import { checkArrayLength, checkStringLength } from "./runtime/limits.js" -import { - AsyncIteratorSymbol, - type AstNode, - invalidData, - IteratorSymbol, - PendingThrow, - rangeError, - referenceError, - syntaxError, - Throw, - typeError, -} from "./runtime/model.js" -import { - Arguments, - Arr, - BoundFn, - Builtin, - type Callable, - copyDataProperties, - defineAccessorHalf, - peek, - GetterCall, - lookup, - coerceToNumber, - coerceToString, - define, - Fn, - frozen, - GeneratorObj, - get, - defineOwnProperty, - getOwn, - own, - hasOwn, - HostNamespace, - IteratorObj, - Native, - type NativeResult, - Obj, - Position, - PromiseObj, - readonly, - remove, - type Value, -} from "./runtime/objects.js" -import { - accessProperty, - applyBinaryOperator, - assignToReference, - builtinCursor, - failedAssignment, - forInKeys, - instanceofValue, - isThenable, - notAFunction, - notConstructible, - operatorConversion, - propertyKey, - requireIteratorMethod, - requireIteratorObject, - requireMemberBase, - requirePromiseProperty, - resolveProperty, - writableReference, -} from "./runtime/operations.js" -import { capability } from "./runtime/promises.js" -import { describeValue, isOpaque, typeofValue } from "./runtime/references.js" -import { - abrupt, - type Completion, - Convert, - type GeneratorRequest, - Prefetch, - Interruption, - Invoke, - MAX_CALL_DEPTH, - normal, - Push, - Resume, -} from "./runtime/signals.js" -import { Source } from "./runtime/source.js" -import type { HostCall, Stop } from "./scheduler.js" -import { compiledPrelude } from "./prelude/prelude.js" -import { constructRegExp } from "./stdlib/regexp.js" -import { enumerableSource } from "./stdlib/object.js" -import { registerAsyncIntrinsics, type SettlingTarget, VmScheduler } from "./async.js" -import type { Code } from "./code.js" -import { type CaptureOptions, captureVm, type RestoreOptions, restoreVm } from "./snapshot.js" -import { compileSource } from "./compiler/compile.js" -import { - AsyncFromSyncIterator, - completeGeneratorReturn, - execAwait, - execGeneratorStart, - execResume, - execYield, - execYstar, - execYstarResult, - handleAdapterPush, - registerGeneratorIntrinsics, - resumeVmGenerator, - unwindGenerator, -} from "./generators.js" -import { BLOCK, ENTERED, type HostResult, HostCalls, VISIT_BUDGET } from "./host.js" -import { - getInternalPrelude, - internalCode, - registerVmIntrinsics, - tryFastBoundaryOrJson, - VmIntrinsic, -} from "./internal-prelude.js" -import { - BinOpSymbols, - Cell, - CheckBaseKind, - CodeFlags, - CondKind, - type ConstValue, - EMPTY_CELLS, - type ErrorSite, - HOLE, - ImportKind, - type ImportSite, - IterContext, - NotYetImplemented, - Op, - PutKind, - type RegExpSite, - type TemplateSite, - UnaryOp, -} from "./opcodes.js" -import { ClassInfo, hidden } from "./runtime/objects.js" - -const contiguous = (): Array => { - const a: Array = [""] - a.pop() - return a as Array -} - -const INITIAL_FUEL = 10_000 -/** - * What a call to a built-in costs in fuel: one may run far longer than an instruction (describing a rejection, copying - * a value), so a loop made only of built-in calls still checks the clock every few dozen calls. - */ -const NATIVE_FUEL = 50 -const SLICE_MS = 1 - -export const Mode = { - CALLER: 0, - ASYNC: 1, - GENERATOR: 2, - SETTLE: 3, - REJECT_ONLY: 4, - PROGRAM: 5, - BOUNDARY_OUT: 6, - /** - * Runs a program getter an iterator op met (`$vmRedo`), then runs the op again from its first word: its `target` is - * `[pc, ...values the op had read]`, and the op replays those and the getter's value in order (see `redoRead`). - */ - REDO: 7, - /** A class constructor run by `new`: hands the caller its result if that is an object, else its `this`. */ - CONSTRUCT: 8, -} as const - -export type FrameMode = (typeof Mode)[keyof typeof Mode] - -/** Custom synchronous/async iterator state stored in a frame's hidden `%it` slot. */ -export class CustomIter { - done = false - rawGen = false - constructor( - readonly iterator: Obj, - readonly next: Value, - ) {} -} - -/** Single uniform activation record for the bytecode VM. */ -export class Frame { - fn: Fn | null = null - cells: ReadonlyArray = EMPTY_CELLS - code: Code - pc = 0 - sp = 0 - regs: Array - thisValue: Value = undefined - args: Array | undefined = undefined - mode: FrameMode = Mode.CALLER - target: unknown = undefined - answer: unknown = undefined - origin: AstNode | undefined = undefined - counted = false - - constructor(code: Code, regs: Array) { - this.code = code - this.regs = regs - } -} - -const EXEC_DONE = 0 -const EXEC_FUEL = 1 - -const allocRegs = (size: number): Array => { - const regs: Array = [] - for (let i = 0; i < size; i++) regs.push(HOLE) - return regs -} - -/** Internal closure wrapper that does not touch `builtins.Function` or `nativeRule.sealed`. */ -export class VmInternalFn { - constructor( - readonly code: Code, - readonly boundArgs?: ReadonlyArray, - ) {} -} - -/** - * Runs a runtime's program code: the job stack, the job queue, promises, and host calls. `execute.ts` and the driver - * use only its host surface: - * - * - **Starting.** Exactly one of `start(source)` (a new run) or `restore(saved, …)` (a saved one), once. Host call - * ids count up in program order. - * - **Running.** `run()` is synchronous, runs no host work, and returns a `Stop`: - * - `host(calls)`: start these queued calls now (they are `queued`; the driver marks them `running`), - * then call `run()` again; `host([])` means wait until `ready` (a blocking call or the inbox has input) and call - * `run()` again; - * - `slice`: the time slice is over; yield to the host scheduler and call `run()` again; - * - `done(completion)`: the program's body ended; host calls may still be running (`diagnostics()` reports - * unhandled rejections); - * - `stuck(node)`: nothing is queued or running, and the body awaits something that can never settle. - * - **Host calls.** `complete(id, completion)` reports how a handed-over call ended, at any time between `run()`s: a - * blocking call's outcome continues the job that made it; a concurrent call's waits in the inbox and settles its - * promise in a later job, in completion order. Unknown or completed ids are ignored. `call(id)`/`calls()` list the - * calls handed over and not completed, in the order they were made. - * - **Snapshots.** `capture` and `restore` run only between `run()`s, synchronously. A capture changes nothing a - * later `run()` sees; it fails (throws) only on a codec gap. A state holding live host values (`calls()` with a call - * whose function or result is still live) can't be restored faithfully. - */ -export class Vm { - readonly frames: Array = contiguous() - private readonly pool: Array = contiguous() - readonly sourceCodes = new Map>() - readonly templates = new Map() - readonly intrinsics = new Map() - readonly scheduler: VmScheduler - /** Host calls: queued, running, completed, and the blocking one the job on the stack waits on. */ - readonly hosts: HostCalls - - depth = 0 - fuel = INITIAL_FUEL - /** When the current slice began; -1 until the next `run` starts one. Host stops don't end a slice, only a yield does. */ - sliceStart = -1 - sliced = false - outcome: Completion | undefined = undefined - /** Round-trip test mode (task C): slice after this many fuel ticks, so the run is saved and restored all through. */ - tripEvery = 0 - /** - * The reads an iterator op replays while it runs again after a getter (`Mode.REDO`). It never outlives the - * `exec` turn the getter returned in, so it is never saved. - */ - redo: - | { readonly frame: Frame; readonly pc: number; readonly values: ReadonlyArray; next: number } - | undefined = undefined - - constructor(readonly ctx: Interpreter) { - this.scheduler = new VmScheduler(this) - this.scheduler.intrinsicThen = get(ctx.builtins.Promise, "then") as Callable - this.hosts = new HostCalls(ctx, this.scheduler) - const internal = getInternalPrelude() - const prelude = compiledPrelude() - this.sourceCodes.set("@vm-internal", internal.codes) - this.sourceCodes.set("@prelude", prelude.codes) - for (const val of ctx.prelude.scope.values()) { - if (val instanceof Fn && val.cells.length === 0 && val.cells !== EMPTY_CELLS) { - ;(val as { cells: ReadonlyArray }).cells = EMPTY_CELLS - } - } - } - - private initIntrinsics(): void { - registerVmIntrinsics(this.intrinsics, this) - registerAsyncIntrinsics(this.intrinsics, this) - registerGeneratorIntrinsics(this.intrinsics, this) - } - - private getIntrinsic(name: string): unknown { - const p = this.ctx.prelude.scope.get(name) - if (p !== undefined) return p - if (this.intrinsics.size === 0) this.initIntrinsics() - return this.intrinsics.get(name) - } - - /** Queues the program's body as the root frame. */ - start(source: Source): void { - if (!warmed) warmupVm(this) - this.ctx.sources.set(source.id, source) - let codes: ReadonlyArray - try { - codes = compileSource(source) - } catch (error) { - // A program nested deeper than the compiler's host stack fails the run, as running it would. - if (!(error instanceof RangeError)) throw error - this.outcome = abrupt(error) - return - } - this.sourceCodes.set(source.id, codes) - const progCode = codes[0]! - const frame = this.acquire(progCode) - frame.fn = null - frame.cells = EMPTY_CELLS - frame.pc = 0 - frame.sp = progCode.locals - frame.thisValue = undefined - frame.args = undefined - frame.mode = Mode.PROGRAM - frame.origin = undefined - frame.counted = true - this.depth = 1 - this.frames.push(frame) - } - - /** - * Runs until it has to stop (`Stop`), in this order: hand over queued host calls; a due slice; continue the job a - * completed blocking call waits on; wait while the job on the stack is blocked; continue a sliced job before any - * other; the outcome; the next job; one inbox completion; wait for running calls; stuck. - */ - run(): Stop { - if (this.sliceStart < 0) this.sliceStart = performance.now() - if (this.tripEvery > 0) this.fuel = this.tripEvery - const sched = this.scheduler - const hosts = this.hosts - while (true) { - if (hosts.queued.length > 0) return { kind: "host", calls: hosts.handOver() } - if (this.sliced) { - this.sliced = false - this.sliceStart = -1 - return { kind: "slice" } - } - const input = hosts.input - if (input !== undefined) { - hosts.input = undefined - this.resumeBlocked(input) - continue - } - if (this.frames.length > 0) { - if (hosts.blocked !== undefined) return { kind: "host", calls: [] } - // Fuel can run out on a call that then stopped for the host (a built-in or sync host call costs fuel too): - // that's a slice point as well, or a loop of such calls would refill forever without yielding. - if (this.fuel <= 0) { - this.fuel = this.tripEvery || INITIAL_FUEL - if (this.tripEvery > 0 || performance.now() - this.sliceStart >= SLICE_MS) { - this.sliced = true - continue - } - } - let signal = EXEC_DONE - try { - signal = this.exec() - } catch (error) { - if (error instanceof NotYetImplemented) throw error - this.unwind(error) - continue - } - if (signal === EXEC_FUEL) { - this.fuel = this.tripEvery || INITIAL_FUEL - if (this.tripEvery > 0 || performance.now() - this.sliceStart >= SLICE_MS) { - this.sliced = true - } - } - continue - } - if (this.outcome !== undefined) return { kind: "done", completion: this.outcome } - const job = sched.dequeue() - if (job !== undefined) { - sched.beginJob(job) - if (--this.fuel <= 0) { - this.fuel = this.tripEvery || INITIAL_FUEL - if (this.tripEvery > 0 || performance.now() - this.sliceStart >= SLICE_MS) { - this.sliced = true - } - } - continue - } - if (hosts.deliver()) continue - if (hosts.running.size > 0) return { kind: "host", calls: [] } - return { kind: "stuck", node: sched.stuckAwait() } - } - } - - // Continues the job stopped at a blocking call with the call's result, or throws its failure at the call. - private resumeBlocked(input: { readonly call: HostCall; readonly completion: Completion }): void { - const frame = this.frames[this.frames.length - 1]! - try { - const result = this.hosts.resume(input) - if (result === BLOCK || result === ENTERED) return - frame.regs[frame.sp++] = result - frame.pc++ - } catch (error) { - this.unwind(error) - } - } - - /** Reports how host work handed over by a `host` stop ended. */ - complete(id: number, completion: Completion): void { - this.hosts.complete(id, completion) - } - - /** Whether `run` has something to do: a blocking call's outcome, or one in the inbox while no job runs. */ - get ready(): boolean { - const hosts = this.hosts - return hosts.input !== undefined || (this.frames.length === 0 && (hosts.inbox.length > 0 || this.scheduler.hasJobs)) - } - - /** A host call handed over and not yet completed, by id. */ - call(id: number): HostCall | undefined { - return this.hosts.running.get(id) - } - - /** The host calls handed over and not yet completed, in the order they were made. */ - calls(): Array { - return [...this.hosts.running.values()] - } - - compact(): void { - this.scheduler.compact() - } - - /** Unhandled rejections, in promise creation order, once inbox completions are delivered. */ - diagnostics(): Array { - while (this.hosts.deliver()); - return this.scheduler.diagnostics() - } - - /** Saves the run's state as it is now. */ - capture(options: CaptureOptions) { - if (this.intrinsics.size === 0) this.initIntrinsics() - return captureVm(this, options) - } - - /** Restores a saved state into this fresh VM, after checking it belongs to this build and runtime. */ - restore(saved: unknown, options: RestoreOptions) { - if (this.intrinsics.size === 0) this.initIntrinsics() - return restoreVm(this, saved, options) - } - - deliverAnswer(frame: Frame): void { - if (frame.answer !== undefined) { - const answer = frame.answer as Value - frame.answer = undefined - const caller = this.frames[this.frames.length - 1] - if (caller !== undefined) { - caller.regs[caller.sp++] = answer - caller.pc++ - } - } - } - - acquire(code: Code): Frame { - const size = code.locals + code.maxStack - const pool = this.pool - if (pool.length === 0) { - return new Frame(code, allocRegs(size)) - } - const f = pool.pop()! - f.code = code - const regs = f.regs - if (regs.length < size) { - f.regs = allocRegs(size) - } else { - for (let i = 0, n = code.locals; i < n; i++) regs[i] = HOLE - } - return f - } - - release(frame: Frame): void { - if (frame.counted) this.depth-- - frame.fn = null - frame.cells = EMPTY_CELLS - frame.thisValue = undefined - frame.args = undefined - frame.target = undefined - frame.answer = undefined - frame.origin = undefined - frame.counted = false - if (this.pool.length < 128) this.pool.push(frame) - } - - private codesOf(code: Code): ReadonlyArray { - return this.sourceCodes.get(code.source.id)! - } - - /** - * Nearest non-internal frame's AST site, or the bottom internal frame's `origin` (§3.6). A failure the host - * boundary's own walk raises (copying out the result) has no location: the call that - * crosses reports it. - */ - currentSite(): AstNode | undefined { - for (let i = this.frames.length - 1; i >= 0; i--) { - const f = this.frames[i]! - if ((f.code.flags & CodeFlags.INTERNAL) === 0) { - return f.code.siteAt(f.pc) - } - if (f.mode === Mode.BOUNDARY_OUT || f.mode === Mode.REJECT_ONLY) return undefined - if (f.origin !== undefined) return f.origin - } - return undefined - } - - /** The program frames on the stack as `stack` lines, innermost first, at most 10 as V8's `Error.stackTraceLimit`. */ - stackTrace(): string { - let trace = "" - let shown = 0 - for (let i = this.frames.length - 1; i >= 0 && shown < 10; i--) { - const frame = this.frames[i]! - const code = frame.code - if ((code.flags & CodeFlags.INTERNAL) !== 0) continue - const site = code.siteAt(frame.pc) - if (!site?.loc) continue - const name = frame.fn ? peek(frame.fn, "name") : undefined - trace += stackFrame( - site, - (code.flags & CodeFlags.PROGRAM) !== 0 ? undefined : (typeof name === "string" && name) || "", - ) - shown++ - } - return trace - } - - private exec(): number { - const frames = this.frames - const hole = HOLE - const CellCtor = Cell - const ArrCtor = Arr - const ObjCtor = Obj - const FnCtor = Fn - const PositionCtor = Position - const globalScope = this.ctx.globalScope - const objectProto = this.ctx.builtins.Object - let frame!: Frame - let fcode!: Code - let code!: Int32Array - let regs!: Array - let consts!: ReadonlyArray - let cells!: ReadonlyArray - let pc = 0 - let sp = 0 - outer: for (;;) { - if (frames.length === 0) return 0 - frame = frames[frames.length - 1]! - fcode = frame.code - code = fcode.code - regs = frame.regs - consts = fcode.consts - pc = frame.pc | 0 - cells = frame.cells - sp = frame.sp | 0 - for (;;) { - const w = code[pc]! - switch (w & 0xff) { - case 0: // Op.PUSH_UNDEF - regs[sp++] = undefined - pc++ - continue - case 1: // Op.PUSH_NULL - regs[sp++] = null - pc++ - continue - case 2: // Op.PUSH_BOOL - regs[sp++] = (w & 0xff00) === 0x0100 - pc++ - continue - case 3: // Op.PUSH_INT - regs[sp++] = w >> 16 - pc++ - continue - case 4: // Op.PUSH_CONST - regs[sp++] = consts[w >>> 16] - pc++ - continue - case 5: // Op.POP - sp-- - pc++ - continue - case 6: // Op.POPN - sp -= w >>> 16 - pc++ - continue - case 7: // Op.DUP - regs[sp] = regs[sp - 1] - sp++ - pc++ - continue - case 8: // Op.PICK - regs[sp] = regs[sp - 1 - ((w >>> 8) & 0xff)] - sp++ - pc++ - continue - case 9: // Op.ROT - this.execRot(regs, (w >>> 8) & 0xff, sp) - pc++ - continue - case 10: { - // Op.GET_LOCAL - const slot = w >>> 16 - const v = regs[slot] - if (v === hole) this.failTdz(frame, fcode.localNames[slot]!, pc, sp) - regs[sp++] = v - pc++ - continue - } - case 11: { - // Op.PUT_LOCAL - const slot = w >>> 16 - const kind = (w >>> 8) & 0xff - const v = regs[--sp] - if (kind !== 1 && (regs[slot] === hole || kind === 2)) { - this.failPut(frame, fcode.localNames[slot]!, regs[slot], pc, sp) - } - regs[slot] = v - pc++ - continue - } - case 12: // Op.HOLE_LOCAL - regs[w >>> 16] = hole - pc++ - continue - case 13: { - // Op.NEW_CELL - const slot = w >>> 16 - regs[slot] = new CellCtor((w & 0xff00) === 0x0100 ? regs[slot] : hole) - pc++ - continue - } - case 14: { - // Op.COPY_CELL - const slot = w >>> 16 - regs[slot] = new CellCtor((regs[slot] as Cell).v) - pc++ - continue - } - case 15: { - // Op.GET_CELL - const slot = w >>> 16 - const v = (regs[slot] as Cell).v - if (v === hole) this.failTdz(frame, fcode.localNames[slot]!, pc, sp) - regs[sp++] = v - pc++ - continue - } - case 16: { - // Op.PUT_CELL - const slot = w >>> 16 - const kind = (w >>> 8) & 0xff - const v = regs[--sp] - const cell = regs[slot] as Cell - if (kind !== 1 && (cell.v === hole || kind === 2)) { - this.failPut(frame, fcode.localNames[slot]!, cell.v, pc, sp) - } - cell.v = v - pc++ - continue - } - case 17: { - // Op.GET_UPVAL - const idx = w >>> 16 - const v = cells[idx]!.v - if (v === hole) this.failTdz(frame, fcode.upvalNames[idx]!, pc, sp) - regs[sp++] = v - pc++ - continue - } - case 18: { - // Op.PUT_UPVAL - const idx = w >>> 16 - const kind = (w >>> 8) & 0xff - const v = regs[--sp] - const cell = cells[idx]! - if (kind !== 1 && (cell.v === hole || kind === 2)) { - this.failPut(frame, fcode.upvalNames[idx]!, cell.v, pc, sp) - } - cell.v = v - pc++ - continue - } - case 19: { - // Op.GET_GLOBAL - const name = consts[w >>> 16] as string - if ((w & 0xff00) === 0) { - const binding = globalScope.get(name) - if (binding !== undefined) { - regs[sp++] = binding.value - pc++ - continue - } - } - regs[sp++] = this.execGetGlobal(frame, (w >>> 8) & 0xff, name, pc, sp) - pc++ - continue - } - case 20: // Op.GET_INTRINSIC - regs[sp++] = this.getIntrinsic(consts[w >>> 16] as string) - pc++ - continue - case 21: // Op.ARGS - regs[sp++] = this.execArgs(frame, (w >>> 8) & 0xff, w >>> 16) - pc++ - continue - case 22: // Op.CLOSURE - regs[sp++] = this.makeClosure(fcode, w >>> 16, regs, cells) - pc++ - continue - case 23: // Op.SET_NAME - this.execSetName(regs, consts, (w >>> 8) & 0xff, w >>> 16, sp) - pc++ - continue - case 24: // Op.IMPORT - frame.pc = pc - frame.sp = sp - sp = this.execImport(frame, (w >>> 8) & 0xff, w >>> 16, pc, sp) - pc++ - continue - case 25: { - // Op.GET_PROP - const o = regs[sp - 1] as Value - const key = consts[w >>> 16] as string - const mode = (w >>> 8) & 0xff - if (key === "length" && mode === 0) { - if (typeof o === "string") { - regs[sp - 1] = o.length - pc++ - continue - } - if (o instanceof ArrCtor) { - regs[sp - 1] = o.items.length - pc++ - continue - } - } - frame.pc = pc - frame.sp = sp - sp = this.execGetProp(frame, o, key, mode, pc, sp) - if (sp < 0) { - if (sp === GETTER_ENTERED) continue outer - return sp === GETTER_FUEL ? 1 : 2 - } - pc++ - continue - } - case 26: { - // Op.GET_ELEM - const keyVal = regs[sp - 1] as Value - const o = regs[sp - 2] as Value - const mode = (w >>> 8) & 0xff - if ( - mode === 0 && - typeof keyVal === "number" && - keyVal >= 0 && - (keyVal | 0) === keyVal && - o instanceof ArrCtor && - keyVal in o.items - ) { - sp-- - regs[sp - 1] = o.items[keyVal] - pc++ - continue - } - frame.pc = pc - frame.sp = sp - sp = this.execGetElem(frame, o, keyVal, mode, pc, sp) - if (sp < 0) { - if (sp === GETTER_ENTERED) continue outer - return sp === GETTER_FUEL ? 1 : 2 - } - pc++ - continue - } - case 27: { - // Op.PUT_PROP - const v = regs[--sp] as Value - const o = regs[sp - 1] as Value - frame.pc = pc - frame.sp = sp - if (this.execPutProp(frame, o, consts[w >>> 16] as string, v, pc, sp)) continue outer - regs[sp - 1] = v - pc++ - continue - } - case 28: { - // Op.PUT_ELEM - const v = regs[--sp] as Value - const keyVal = regs[--sp] as Value - const o = regs[sp - 1] as Value - if ( - typeof keyVal === "number" && - keyVal >= 0 && - (keyVal | 0) === keyVal && - (typeof v !== "object" || v === null) && - o instanceof ArrCtor && - o.elements.writable && - o.extensible - ) { - const items = o.items - // A hole or a new element looks at the prototypes first, which may hold a program setter there. - if (keyVal < items.length && (keyVal in items || this.plainArrayChain(o))) { - if (keyVal === 0) items[0] = "" - items[keyVal] = v - regs[sp - 1] = v - pc++ - continue - } - if (keyVal === items.length && keyVal < 10_000_000 && this.plainArrayChain(o)) { - items.push(v) - regs[sp - 1] = v - pc++ - continue - } - } - frame.pc = pc - frame.sp = sp - if (this.execPutProp(frame, o, propertyKey(keyVal), v, pc, sp)) continue outer - regs[sp - 1] = v - pc++ - continue - } - case 29: // Op.DELETE_PROP - frame.pc = pc - frame.sp = sp - regs[sp - 1] = this.execDeleteProp(fcode, regs[sp - 1] as Value, consts[w >>> 16] as string, pc) - pc++ - continue - case 30: { - // Op.DELETE_ELEM - const keyVal = regs[--sp] as Value - const o = regs[sp - 1] as Value - frame.pc = pc - frame.sp = sp - if (this.execDeleteElem(frame, o, keyVal, pc, sp)) continue outer - sp = frame.sp - pc++ - continue - } - case 31: // Op.CHECK_BASE - frame.pc = pc - frame.sp = sp - this.execCheckBase(fcode, (w >>> 8) & 0xff, w >>> 16, regs, sp, pc) - pc++ - continue - case 32: { - // Op.TO_KEY - const v = regs[sp - 1] as Value - if (typeof v === "string" || typeof v === "number" || typeof v === "symbol") { - pc++ - continue - } - if (this.execToKey(frame, v, pc, sp)) continue outer - pc++ - continue - } - case 33: { - // Op.IN - const rhs = regs[--sp] as Value - const lhs = regs[sp - 1] as Value - if (typeof lhs === "number" && lhs >= 0 && (lhs | 0) === lhs && rhs instanceof ArrCtor) { - regs[sp - 1] = lhs in rhs.items - pc++ - continue - } - if (this.execIn(frame, lhs, rhs, pc, sp)) continue outer - pc++ - continue - } - case 34: { - // Op.INSTANCEOF - const rhs = regs[--sp] as Value - frame.pc = pc - frame.sp = sp - if (this.execInstanceof(frame, regs[sp - 1] as Value, rhs, pc, sp)) continue outer - pc++ - continue - } - case 35: // Op.NEW_OBJECT - regs[sp++] = new ObjCtor(objectProto) - pc++ - continue - case 36: // Op.NEW_ARRAY - sp = this.execNewArray(regs, w >>> 16, sp) - pc++ - continue - case 37: // Op.ARRAY_APPEND - frame.pc = pc - frame.sp = sp - sp = this.execArrayAppend(regs, (w >>> 8) & 0xff, sp) - pc++ - continue - case 38: // Op.DEFINE_FIELD - sp = this.execDefineField(regs, consts, (w >>> 8) & 0xff, w >>> 16, sp) - pc++ - continue - case 39: // Op.COPY_DATA_PROPS - frame.pc = pc - frame.sp = --sp - if (this.execCopyDataProps(frame, regs[sp - 1] as Obj, regs[sp] as Value, pc, sp)) continue outer - pc++ - continue - case 40: // Op.COPY_REST - frame.pc = pc - frame.sp = sp - sp = this.execCopyRest(frame, regs, w >>> 16, pc, sp) - if (sp < 0) continue outer - pc++ - continue - case 41: // Op.TEMPLATE - regs[sp++] = this.getTemplateObject(fcode, consts[w >>> 16] as TemplateSite) - pc++ - continue - case 42: // Op.REGEXP - frame.pc = pc - frame.sp = sp - regs[sp++] = this.execRegExp(fcode, consts[w >>> 16] as RegExpSite, pc) - pc++ - continue - case 43: { - // Op.ADD - const b = regs[--sp] as Value - const a = regs[sp - 1] as Value - if (typeof a === "number" && typeof b === "number") { - regs[sp - 1] = a + b - pc++ - continue - } - if ( - (typeof a === "string" || typeof b === "string") && - (a === null || (typeof a !== "object" && typeof a !== "symbol")) && - (b === null || (typeof b !== "object" && typeof b !== "symbol")) - ) { - const s = (a as string) + (b as string) - if (s.length > 16_777_216) { - frame.pc = pc - frame.sp = sp - this.failStringLength(s.length) - } - regs[sp - 1] = s - pc++ - continue - } - frame.pc = pc - frame.sp = sp - if (this.execBinarySlow(frame, "+", a, b, pc, sp)) continue outer - pc++ - continue - } - case 44: { - // Op.SUB - const b = regs[--sp] as Value - const a = regs[sp - 1] as Value - if (typeof a === "number" && typeof b === "number") { - regs[sp - 1] = a - b - pc++ - continue - } - frame.pc = pc - frame.sp = sp - if (this.execBinarySlow(frame, "-", a, b, pc, sp)) continue outer - pc++ - continue - } - case 45: { - // Op.MUL - const b = regs[--sp] as Value - const a = regs[sp - 1] as Value - if (typeof a === "number" && typeof b === "number") { - regs[sp - 1] = a * b - pc++ - continue - } - frame.pc = pc - frame.sp = sp - if (this.execBinarySlow(frame, "*", a, b, pc, sp)) continue outer - pc++ - continue - } - case 46: { - // Op.LT - const b = regs[--sp] as Value - const a = regs[sp - 1] as Value - if (typeof a === "number" && typeof b === "number") { - regs[sp - 1] = a < b - pc++ - continue - } - frame.pc = pc - frame.sp = sp - if (this.execBinarySlow(frame, "<", a, b, pc, sp)) continue outer - pc++ - continue - } - case 47: { - // Op.LE - const b = regs[--sp] as Value - const a = regs[sp - 1] as Value - if (typeof a === "number" && typeof b === "number") { - regs[sp - 1] = a <= b - pc++ - continue - } - frame.pc = pc - frame.sp = sp - if (this.execBinarySlow(frame, "<=", a, b, pc, sp)) continue outer - pc++ - continue - } - case 48: { - // Op.GT - const b = regs[--sp] as Value - const a = regs[sp - 1] as Value - if (typeof a === "number" && typeof b === "number") { - regs[sp - 1] = a > b - pc++ - continue - } - frame.pc = pc - frame.sp = sp - if (this.execBinarySlow(frame, ">", a, b, pc, sp)) continue outer - pc++ - continue - } - case 49: { - // Op.GE - const b = regs[--sp] as Value - const a = regs[sp - 1] as Value - if (typeof a === "number" && typeof b === "number") { - regs[sp - 1] = a >= b - pc++ - continue - } - frame.pc = pc - frame.sp = sp - if (this.execBinarySlow(frame, ">=", a, b, pc, sp)) continue outer - pc++ - continue - } - case 50: { - // Op.SEQ - const b = regs[--sp] - regs[sp - 1] = regs[sp - 1] === b - pc++ - continue - } - case 51: { - // Op.SNE - const b = regs[--sp] - regs[sp - 1] = regs[sp - 1] !== b - pc++ - continue - } - case 52: { - // Op.BINOP - const b = regs[--sp] as Value - const a = regs[sp - 1] as Value - const sub = (w >>> 8) & 0xff - if (typeof a === "number" && typeof b === "number") { - regs[sp - 1] = sub === 1 ? a % b : this.execBinopNum(sub, a, b) - pc++ - continue - } - frame.pc = pc - frame.sp = sp - if (this.execBinopSlow(frame, sub, a, b, pc, sp)) continue outer - pc++ - continue - } - case 53: { - // Op.UNARY - const sub = (w >>> 8) & 0xff - const v = regs[sp - 1] as Value - if (typeof v === "number" && sub < 3) { - regs[sp - 1] = sub === 0 ? -v : sub === 1 ? +v : ~v - pc++ - continue - } - frame.pc = pc - frame.sp = sp - if (this.execUnarySlow(frame, sub, v, pc, sp)) continue outer - pc++ - continue - } - case 54: // Op.NOT - regs[sp - 1] = !regs[sp - 1] - pc++ - continue - case 55: { - // Op.TO_NUMERIC - const v = regs[sp - 1] as Value - if (typeof v === "number") { - pc++ - continue - } - if (this.execToNumericSlow(frame, (w >>> 8) & 0xff, v, pc, sp)) continue outer - pc++ - continue - } - case 56: { - // Op.INC - const v = regs[sp - 1] as Value - if (typeof v === "number") { - regs[sp - 1] = (w & 0xff00) === 0 ? v + 1 : v - 1 - pc++ - continue - } - if (this.execIncSlow(frame, (w >>> 8) & 0xff, v, pc, sp)) continue outer - pc++ - continue - } - case 57: { - // Op.TO_STRING - const v = regs[sp - 1] as Value - if (typeof v === "string") { - pc++ - continue - } - if (typeof v === "number") { - regs[sp - 1] = "" + v - pc++ - continue - } - if (this.execToStringSlow(frame, (w >>> 8) & 0xff, v, pc, sp)) continue outer - pc++ - continue - } - case 58: { - // Op.CONCAT - const n = w >>> 16 - if (n === 2) { - const b = regs[--sp] as string - const s = (regs[sp - 1] as string) + b - if (s.length > 16_777_216) { - frame.pc = pc - frame.sp = sp - this.failStringLength(s.length) - } - regs[sp - 1] = s - pc++ - continue - } - frame.pc = pc - frame.sp = sp - sp = this.execConcat(regs, n, sp) - pc++ - continue - } - case 59: // Op.JUMP - pc = w >>> 16 - continue - case 60: // Op.LOOP - pc = w >>> 16 - if (--this.fuel <= 0) { - frame.pc = pc - frame.sp = sp - return 1 - } - continue - case 61: // Op.JUMP_IF_FALSE - if (regs[--sp]) pc++ - else pc = w >>> 16 - continue - case 62: // Op.JUMP_IF_TRUE - if (regs[--sp]) pc = w >>> 16 - else pc++ - continue - case 63: { - // Op.JUMP_COND - const v = regs[sp - 1] - const sub = (w >>> 8) & 0xff - if (sub >= 4) { - if (v === null || v === undefined) { - if (sub === 5) sp-- - regs[sp - 1] = undefined - pc = w >>> 16 - } else { - pc++ - } - continue - } - const jump = sub === 0 ? !!v : sub === 1 ? !v : sub === 2 ? v !== null && v !== undefined : v !== undefined - if (jump) { - pc = w >>> 16 - } else { - sp-- - pc++ - } - continue - } - case 64: // Op.THROW - this.execThrow(frame, regs[--sp] as Value, pc, sp) - case 65: // Op.THROW_ERROR - this.execThrowError(frame, w >>> 16, pc, sp) - case 66: // Op.END_FINALLY - pc = this.execEndFinally(frame, w >>> 16, pc, sp) - continue - case 67: // Op.RETURN - case 87: { - // Op.END_PROGRAM - const v = regs[sp - 1] as Value - if (frame.mode === 0) { - frames.pop() - if (frame.counted) this.depth-- - if (this.pool.length < 128) this.pool.push(frame) - const caller = frames[frames.length - 1]! - caller.regs[caller.sp++] = v - caller.pc++ - continue outer - } - if (this.execReturnSlow(frame, v, pc, sp)) continue outer - return 0 - } - case 68: // Op.NOP - pc++ - continue - case 69: { - // Op.EXTRA - const nextPc = this.execExtra(frame, w, pc, sp) - if (nextPc < 0) { - if (nextPc === -1) continue outer - return -2 - nextPc - } - sp = frame.sp - pc = nextPc - continue - } - case 70: { - // Op.CALL - const n = (w >>> 8) & 0xff - const base = sp - n - const callee = regs[base - 1] - if (callee instanceof FnCtor) { - const c = callee.code - // Not async, generator, needing arguments, or a class constructor. - if ((c.flags & 774) === 0) { - const counted = (c.flags & 64) === 0 - if (counted && this.depth > 10_000) { - this.failCallDepth(frame, fcode, pc, sp) - } - if (counted) this.depth++ - const f = this.acquire(c) - f.fn = callee - f.cells = callee.cells - f.counted = counted - const r = f.regs - const p = c.params - if (p === 1) { - r[0] = n > 0 ? regs[base] : undefined - } else if (p === 2) { - r[0] = n > 0 ? regs[base] : undefined - r[1] = n > 1 ? regs[base + 1] : undefined - } else if (p > 2) { - this.copyParams(r, regs, base, n, p) - } - f.thisValue = regs[base - 2] as Value - f.origin = counted ? undefined : (fcode.flags & 64) === 0 ? fcode.siteAt(pc) : frame.origin - frame.pc = pc - frame.sp = base - 2 - f.pc = 0 - f.sp = c.locals - f.mode = 0 - frames.push(f) - if (--this.fuel <= 0) return 1 - continue outer - } - } - frame.pc = pc - frame.sp = sp - const called = this.execCallSlow(frame, n, pc, sp) - if (called === 1) { - if (this.fuel <= 0) return 1 - continue outer - } - if (called === 2) return 2 - sp = frame.sp - pc++ - frame.pc = pc - if (this.fuel <= 0) return 1 - continue - } - case 71: { - // Op.CALL_SPREAD - const called = this.execCallSpread(frame, pc, sp) - if (called === 1) { - if (this.fuel <= 0) return 1 - continue outer - } - if (called === 2) return 2 - sp = frame.sp - pc++ - frame.pc = pc - if (this.fuel <= 0) return 1 - continue - } - case 72: { - // Op.NEW - const made = this.execNew(frame, (w >>> 8) & 0xff, pc, sp) - if (made === 1) continue outer - if (made === 2) return 2 - sp = frame.sp - pc++ - continue - } - case 73: { - // Op.NEW_SPREAD - const made = this.execNewSpread(frame, pc, sp) - if (made === 1) continue outer - if (made === 2) return 2 - sp = frame.sp - pc++ - continue - } - case 74: // Op.ITER_OPEN - frame.pc = pc - frame.sp = sp - pc = this.execIterOpen(frame, (w >>> 8) & 0xff, pc, sp) - if (pc < 0) continue outer - sp = frame.sp - continue - case 75: // Op.ITER_INIT - frame.pc = pc - frame.sp = sp - if (this.execIterInit(frame, (w >>> 8) & 0xff, pc, sp)) continue outer - pc++ - continue - case 76: { - // Op.ITER_STEP - const rec = regs[(w >>> 8) & 0xff] - if (rec instanceof PositionCtor) { - const step = rec.step() - if (!step.done) { - regs[sp++] = step.value - pc += 2 - } else { - pc = w >>> 16 - } - continue - } - if (this.execIterStepSlow(frame, rec as CustomIter, w >>> 16, pc, sp)) continue outer - sp = frame.sp - pc = frame.pc - continue - } - case 77: // Op.ITER_RESULT - pc = this.execIterResult(frame, (w >>> 8) & 0xff, w >>> 16, pc, sp) - if (pc < 0) continue outer - sp = frame.sp - continue - case 78: // Op.ITER_CLOSE - pc = this.execIterClose(frame, (w >>> 8) & 0xff, w >>> 16, pc, sp) - if (pc < 0) continue outer - sp = frame.sp - continue - case 79: // Op.ITER_APPEND_ALL - pc = this.execIterAppendAll(frame, (w >>> 8) & 0xff, w >>> 16, pc, sp) - continue - case 80: // Op.FOR_IN - frame.pc = pc - frame.sp = sp - regs[sp - 1] = this.execForIn(fcode, regs[sp - 1] as Value, pc) - pc++ - continue - case 81: // Op.GENERATOR_START - this.onGeneratorStart(frame, pc, sp) - continue outer - case 82: // Op.YIELD - if (this.onYield(frame, pc, sp)) continue outer - sp = frame.sp - pc = frame.pc - continue - case 83: // Op.RESUME - if (regs[sp - 1] === 0) { - sp-- - pc = w >>> 16 - continue - } - pc = this.onResume(frame, w >>> 16, pc, sp) - sp = frame.sp - continue - case 84: // Op.AWAIT - this.onAwait(frame, (w >>> 8) & 0xff, pc, sp) - continue outer - case 85: // Op.YSTAR - frame.pc = pc - frame.sp = sp - pc = this.onYstar(frame, (w >>> 8) & 0xff, w >>> 16, pc, sp) - if (pc < 0) continue outer - sp = frame.sp - continue - case 86: // Op.YSTAR_RESULT - frame.pc = pc - frame.sp = sp - pc = this.onYstarResult(frame, (w >>> 8) & 0xff, w >>> 16, pc, sp) - if (pc < 0) continue outer - sp = frame.sp - continue - case 88: // Op.DEFINE_ACCESSOR - sp = this.execDefineAccessor(regs, consts, (w >>> 8) & 0xff, w >>> 16, sp) - pc++ - continue - case 89: // Op.CLASS - sp = this.execClass(frame, (w >>> 8) & 0xff, pc, sp) - pc++ - continue - case 90: // Op.DEFINE_METHOD - sp = this.execDefineMethod(regs, consts, (w >>> 8) & 0xff, w >>> 16, sp) - pc++ - continue - case 91: // Op.SET_FIELDS - sp = this.execSetFields(regs, sp) - pc++ - continue - case 92: { - // Op.INIT_FIELDS - frame.pc = pc - const called = this.execInitFields(frame, (w >>> 8) & 0xff, pc, sp) - if (called === 1) { - if (this.fuel <= 0) return 1 - continue outer - } - if (called === 2) return 2 - sp = frame.sp - pc++ - frame.pc = pc - continue - } - case 93: // Op.SUPER_CALL - case 94: // Op.SUPER_BIND - case 96: // Op.GET_SUPER - case 98: // Op.SET_HOME - case 97: { - // Op.PUT_SUPER - frame.pc = pc - frame.sp = sp - const nextPc = this.execWide(frame, w & 0xff, (w >>> 8) & 0xff, w >>> 16, pc) - if (nextPc < 0) { - if (nextPc === -1) continue outer - return -2 - nextPc - } - sp = frame.sp - pc = nextPc - continue - } - default: - this.failOpcode(w & 0xff) - } - } - } - } - - private copyParams(r: Array, regs: Array, base: number, n: number, p: number): void { - for (let i = 0; i < p; i++) r[i] = i < n ? regs[base + i] : undefined - } - - private failCallDepth(frame: Frame, fcode: Code, pc: number, sp: number): never { - frame.pc = pc - frame.sp = sp - throw rangeError("Maximum call stack size exceeded", fcode.siteAt(pc)) - } - - private failStringLength(len: number): void { - checkStringLength(len) - } - - // `lhs instanceof rhs` into the stack at `sp - 1`; true when a program `prototype` getter runs first. - private execInstanceof(frame: Frame, lhs: Value, rhs: Value, pc: number, sp: number): boolean { - const site = frame.code.siteAt(pc)! - const result = instanceofValue(lhs, rhs, site) - if (!(result instanceof GetterCall)) { - frame.regs[sp - 1] = result - return false - } - frame.sp = sp - 1 - this.pushInternalCall("$vmInstanceof", [lhs, rhs], site) - return true - } - - // Whether an array's chain is the built-in one with no program accessors, so a hole or append can skip it. - private plainArrayChain(o: Arr): boolean { - const proto = o.proto - return ( - proto === this.ctx.builtins.Array && !proto.hasProgramAccessors && !this.ctx.builtins.Object.hasProgramAccessors - ) - } - - private execBinopSlow(frame: Frame, sub: number, a: Value, b: Value, pc: number, sp: number): boolean { - return this.execBinarySlow(frame, BinOpSymbols[sub]!, a, b, pc, sp) - } - - private execThrow(frame: Frame, val: Value, pc: number, sp: number): never { - frame.pc = pc - frame.sp = sp - throw new Throw(val) - } - - private execForIn(fcode: Code, val: Value, pc: number): Position { - return new Position(forInKeys(this.ctx, val, fcode.siteAt(pc)!), "values", this.ctx.builtins.Array) - } - - private onGeneratorStart(frame: Frame, pc: number, sp: number): void { - execGeneratorStart(this, frame, pc, sp) - } - - private onYield(frame: Frame, pc: number, sp: number): boolean { - return execYield(this, frame, pc, sp) - } - - private onResume(frame: Frame, bx: number, pc: number, sp: number): number { - return execResume(frame, bx, pc, sp) - } - - private onAwait(frame: Frame, flag: number, pc: number, sp: number): void { - execAwait(this, frame, flag, pc, sp) - } - - private onYstar(frame: Frame, slot: number, bx: number, pc: number, sp: number): number { - return execYstar(this, frame, slot, bx, pc, sp) - } - - private onYstarResult(frame: Frame, slot: number, bx: number, pc: number, sp: number): number { - return execYstarResult(this, frame, slot, bx, pc, sp) - } - - private failOpcode(op: number): never { - throw new NotYetImplemented(`opcode ${op}`) - } - - private execRot(regs: Array, n: number, sp: number): void { - const top = regs[sp - 1] - for (let i = sp - 1; i > sp - 1 - n; i--) regs[i] = regs[i - 1] - regs[sp - 1 - n] = top - } - - private failTdz(frame: Frame, name: string, pc: number, sp: number): never { - frame.pc = pc - frame.sp = sp - if (name === "this") throw referenceError(THIS_BEFORE_SUPER, frame.code.siteAt(pc)) - throw referenceError(`Cannot access '${name}' before initialization.`, frame.code.siteAt(pc)) - } - - private failPut(frame: Frame, name: string, current: unknown, pc: number, sp: number): never { - frame.pc = pc - frame.sp = sp - if (current === HOLE) { - throw referenceError(`Cannot access '${name}' before initialization.`, frame.code.siteAt(pc)) - } - throw typeError(`Cannot assign to constant '${name}'.`, frame.code.siteAt(pc)) - } - - private execGetGlobal(frame: Frame, mode: number, name: string, pc: number, sp: number): Value { - const fcode = frame.code - const binding = this.ctx.globalScope.get(name) - if (mode === 2) { - frame.pc = pc - frame.sp = sp - 1 - if (binding === undefined) throw referenceError(`Unknown identifier '${name}'.`, fcode.siteAt(pc)) - throw typeError(`Cannot assign to constant '${name}'.`, fcode.siteAt(pc)) - } - if (binding === undefined) { - if (mode === 1) return "undefined" - frame.pc = pc - frame.sp = sp - throw referenceError(`Unknown identifier '${name}'.`, fcode.siteAt(pc)) - } - return mode === 1 ? typeofValue(binding.value) : binding.value - } - - private execArgs(frame: Frame, kind: number, bx: number): unknown { - if (kind === 0) { - const made = new Arguments(this.ctx.builtins.Object, frame.args ?? []) - define(made, IteratorSymbol, this.ctx.prelude.fn("argumentsValues"), hidden) - return made - } - if (kind === 1) return new Arr(this.ctx.builtins.Array, (frame.args ?? []).slice(bx)) - if (kind === 2) return frame.fn - if (kind === 3) return frame.thisValue - if (kind === 5) return frame.fn!.home - return frame.args?.[bx] - } - - private execSetName( - regs: Array, - consts: ReadonlyArray, - mode: number, - bx: number, - sp: number, - ): void { - const fn = regs[sp - 1] - if (!(fn instanceof Fn)) return - // A class with its own static `name` member keeps it. - if (fn.klass !== undefined && hasStaticName(fn)) return - if (mode === 0) { - define(fn, "name", consts[bx] as string, readonly) - return - } - const key = regs[sp - 2] - const name = - key === IteratorSymbol - ? "[Symbol.iterator]" - : key === AsyncIteratorSymbol - ? "[Symbol.asyncIterator]" - : String(key) - // Modes 2 and 3 name an accessor's function: `get x`, `set x`. - define(fn, "name", mode === 2 ? `get ${name}` : mode === 3 ? `set ${name}` : name, readonly) - } - - private execToKey(frame: Frame, v: Value, pc: number, sp: number): boolean { - if (!(v instanceof Obj) || isOpaque(v)) { - frame.regs[sp - 1] = coerceToString(v) - return false - } - frame.pc = pc - frame.sp = sp - 1 - this.pushInternalCall("$vmToKey", [v], frame.code.siteAt(pc) ?? frame.origin) - return true - } - - private execIn(frame: Frame, lhs: Value, rhs: Value, pc: number, sp: number): boolean { - frame.pc = pc - frame.sp = sp - return this.execBinarySlow(frame, "in", lhs, rhs, pc, sp) - } - - private execNewArray(regs: Array, n: number, sp: number): number { - if (n === 0) { - regs[sp] = new Arr(this.ctx.builtins.Array, contiguous()) - return sp + 1 - } - const items = regs.slice(sp - n, sp) as Array - sp -= n - regs[sp] = new Arr(this.ctx.builtins.Array, items) - return sp + 1 - } - - private execArrayAppend(regs: Array, isHole: number, sp: number): number { - if (isHole === 1) { - const arr = regs[sp - 1] as Arr - checkArrayLength(arr.items.length + 1) - arr.items.length += 1 - return sp - } - const v = regs[--sp] as Value - const arr = regs[sp - 1] as Arr - checkArrayLength(arr.items.length + 1) - arr.items.push(v) - return sp - } - - private execDefineField( - regs: Array, - consts: ReadonlyArray, - computed: number, - bx: number, - sp: number, - ): number { - if (computed === 0) { - const v = regs[--sp] as Value - define(regs[sp - 1] as Obj, consts[bx] as string, v) - return sp - } - const v = regs[--sp] as Value - if (computed === 1) { - const k = regs[--sp] as PropertyKey - define(regs[sp - 1] as Obj, k, v) - return sp - } - // A class field (a bit 1): CreateDataPropertyOrThrow, which fails on a frozen or non-configurable target. - const k = (computed & 1) !== 0 ? (regs[--sp] as PropertyKey) : (consts[bx] as string) - const desc = { value: v, writable: true, enumerable: true, configurable: true } - if (!defineOwnProperty(regs[sp - 1] as Obj, k, desc)) throw typeError(`Cannot define property ${String(k)}.`) - return sp - } - - // An object literal's getter or setter: `[o, fn]`, or `[o, key, fn]` computed, leaves `[o]`. - private execDefineAccessor( - regs: Array, - consts: ReadonlyArray, - a: number, - bx: number, - sp: number, - ): number { - const fn = regs[--sp] as Fn - const key = (a & 1) !== 0 ? (regs[--sp] as PropertyKey) : (consts[bx] as string) - defineAccessorHalf(regs[sp - 1] as Obj, key, (a & 2) !== 0 ? "set" : "get", fn) - return sp - } - - // The constructor on top gets its prototype, `[ctor] -> [ctor, proto]`; with a parent (a 1), it inherits from it: - // `[parent, ctor] -> [ctor, proto]`. - private execClass(frame: Frame, a: number, pc: number, sp: number): number { - const regs = frame.regs - const ctor = regs[sp - 1] as Fn - if ((a & 1) === 0) { - const proto = new Obj(this.ctx.builtins.Object) - ctor.klass = new ClassInfo(false) - ctor.home = proto - define(ctor, "prototype", proto, frozen) - define(proto, "constructor", ctor, hidden) - regs[sp] = proto - return sp + 1 - } - const parent = classParent(regs[sp - 2] as Value, frame.code.siteAt(pc), this.ctx.builtins) - const proto = new Obj(get(parent, "prototype") as Obj) - ctor.proto = parent - ctor.klass = new ClassInfo(true) - ctor.home = proto - define(ctor, "prototype", proto, frozen) - define(proto, "constructor", ctor, hidden) - regs[sp - 2] = ctor - regs[sp - 1] = proto - return sp - } - - // `super(...args)`: constructs the running constructor's parent for the new target in local `bx`. - private execSuperCall(frame: Frame, a: number, bx: number, pc: number): number { - const regs = frame.regs - let sp = frame.sp - const args = a === 255 ? [...(regs[--sp] as Arr).items] : (regs.slice(sp - a, sp) as Array) - if (a !== 255) sp -= a - frame.sp = sp - frame.pc = pc - const parent = frame.fn!.proto - if (isErrorConstructor(parent, this.ctx.builtins)) { - return this.execConstruct(frame, parent, args, callSiteOf(frame, pc), regs[bx] as Fn) - } - if (!(parent instanceof Fn) || parent.klass === undefined) { - throw typeError(`Super constructor ${describeValue(parent)} of anonymous class is not a constructor`, frame.code.siteAt(pc)) - } - return this.constructClass(frame, parent, args, callSiteOf(frame, pc), regs[bx] as Fn) - } - - // A derived constructor's `this` binding (local `bx`, a cell when `a` is 1). - private thisBinding(frame: Frame, a: number, bx: number): unknown { - return a === 1 ? (frame.regs[bx] as Cell).v : frame.regs[bx] - } - - // `super()` returned the instance on top: it becomes `this`, once. - private execSuperBind(frame: Frame, a: number, bx: number, pc: number): void { - const regs = frame.regs - if (this.thisBinding(frame, a, bx) !== HOLE) { - throw referenceError("Super constructor may only be called once", frame.code.siteAt(pc)) - } - const instance = regs[frame.sp - 1] as Value - if (a === 1) (regs[bx] as Cell).v = instance - else regs[bx] = instance - frame.thisValue = instance - frame.target = undefined - } - - // `super.x` / `super[key]`: reads from the home object's prototype with `this` as the receiver. - private execGetSuper(frame: Frame, a: number, bx: number, pc: number): number { - const regs = frame.regs - let sp = frame.sp - const key = (a & 2) !== 0 ? (regs[--sp] as PropertyKey) : (frame.code.consts[bx] as string) - const self = regs[--sp] as Value - const proto = superBase(regs[--sp] as Obj, frame.code.siteAt(pc)) - const mode = a & 1 - const v = this.readObjProp(proto, typeof key === "number" ? String(key) : key, self, frame.code, pc) - if (v instanceof GetterCall) return this.enterGetter(frame, v.getter, self, sp, mode, pc) - return writeRead(regs, sp, mode, self, v) - } - - // `super.x = v`: a setter on the home object's prototype chain runs with `this`; otherwise `this` takes the write. - private execPutSuper(frame: Frame, a: number, bx: number, pc: number): boolean { - const regs = frame.regs - let sp = frame.sp - const v = regs[--sp] as Value - const key = (a & 2) !== 0 ? (regs[--sp] as PropertyKey) : (frame.code.consts[bx] as string) - const self = regs[--sp] as Value - const site = frame.code.siteAt(pc) - const proto = superBase(regs[--sp] as Obj, site) - frame.sp = sp - const slot = lookup(proto, key) - let setter: Callable | undefined - if (slot !== undefined && !("value" in slot)) { - if (slot.set === undefined) throw typeError(`Cannot set property ${String(key)}, which has only a getter.`, site) - if (typeof slot.set === "function") slot.set(self, v) - else setter = slot.set - } else { - if (!(self instanceof Obj)) throw typeError(`Cannot set property ${String(key)} of ${describeValue(self)}.`, site) - try { - setter = assignToReference(self, key, v, undefined) - } catch (err) { - throw locate(err, site) - } - } - if (setter !== undefined) { - this.pushInternalCall("$vmSet", [setter, self, v], callSiteOf(frame, pc)) - return true - } - regs[frame.sp++] = v - return false - } - - // `[ctor, proto, fn] -> [ctor, proto]`: a hidden method on the prototype, or on the constructor when static. - private execDefineMethod( - regs: Array, - consts: ReadonlyArray, - a: number, - bx: number, - sp: number, - ): number { - const fn = regs[--sp] as Fn - const key = (a & 2) !== 0 ? (regs[--sp] as PropertyKey) : (consts[bx] as string) - const home = regs[(a & 1) !== 0 ? sp - 2 : sp - 1] as Obj - const name = - typeof key === "symbol" - ? key === IteratorSymbol - ? "[Symbol.iterator]" - : key === AsyncIteratorSymbol - ? "[Symbol.asyncIterator]" - : `[${key.description ?? ""}]` - : String(key) - fn.home = home - if (key === "prototype" && home instanceof Fn && home.klass !== undefined) - throw typeError("Classes may not have a static property named 'prototype'.") - if ((a & 12) === 0) { - define(fn, "name", name, readonly) - define(home, key, fn, hidden) - return sp - } - const half = (a & 4) !== 0 ? "get" : "set" - define(fn, "name", `${half} ${name}`, readonly) - defineAccessorHalf(home, key, half, fn, false) - return sp - } - - // `[ctor, proto, fn] -> [ctor, proto]`: `fn` defines the class's instance fields, with the prototype as its home. - private execSetFields(regs: Array, sp: number): number { - const fn = regs[--sp] as Fn - fn.home = regs[sp - 1] as Obj - ;(regs[sp - 2] as Fn).klass!.fields = fn - return sp - } - - // Calls a field initializer: the running constructor's on its `this` (a 0), or a static one on the class (a 1). - private execInitFields(frame: Frame, a: number, pc: number, sp: number): number { - const regs = frame.regs - if (a === 0) { - frame.sp = sp - const fields = frame.fn!.klass!.fields - if (fields === undefined) { - regs[frame.sp++] = undefined - return 0 - } - return this.invokeCallable(frame, fields, frame.thisValue, [], callSiteOf(frame, pc), pc) - } - const fn = regs[--sp] as Fn - const target = regs[--sp] as Obj - fn.home = target - frame.sp = sp - return this.invokeCallable(frame, fn, target, [], callSiteOf(frame, pc), pc) - } - - // `{ ...src }` into `o` (at `sp - 1`, `src` popped): true when a source with program getters is copied in the prelude. - private execCopyDataProps(frame: Frame, o: Obj, src: Value, pc: number, sp: number): boolean { - if (src === null || src === undefined) return false - const source = enumerableSource(this.ctx, "Object spread", src, frame.code.siteAt(pc)!) - if (!source.hasProgramAccessors) { - copyDataProperties(o, source) - return false - } - frame.sp = sp - 1 - this.pushInternalCall("$vmCopyDataProps", [o, source, undefined], callSiteOf(frame, pc)) - return true - } - - // `{ ...rest } = src`, less the `n` keys on the stack: the new sp, or -1 when the copy runs in the prelude. - private execCopyRest(frame: Frame, regs: Array, n: number, pc: number, sp: number): number { - const consumed = new Set() - for (let i = sp - n; i < sp; i++) { - const k = regs[i] as PropertyKey - consumed.add(typeof k === "symbol" ? k : String(k)) - } - sp -= n - const rest = new Obj(this.ctx.builtins.Object) - const source = enumerableSource(this.ctx, "Object destructuring", regs[sp - 1] as Value, frame.code.siteAt(pc)!) - if (source.hasProgramAccessors) { - frame.sp = sp - 1 - const excluded = new Arr(this.ctx.builtins.Array, [...consumed] as Array) - this.pushInternalCall("$vmCopyDataProps", [rest, source, excluded], callSiteOf(frame, pc)) - return -1 - } - copyDataProperties(rest, source, consumed) - regs[sp - 1] = rest - return sp - } - - private execRegExp(fcode: Code, site: RegExpSite, pc: number): Value { - try { - return constructRegExp(this.ctx.builtins, [site.pattern, site.flags]) - } catch (err) { - throw locate(err, fcode.siteAt(pc)) - } - } - - private execBinopNum(sub: number, a: number, b: number): Value { - switch (sub) { - case 0: - return a / b - case 1: - return a % b - case 2: - return a ** b - case 3: - return a & b - case 4: - return a | b - case 5: - return a ^ b - case 6: - return a << b - case 7: - return a >> b - case 8: - return a >>> b - case 9: - return a == b - default: - return a != b - } - } - - // `helper` converts an object in the prelude: `$vmToNumeric`, or `$vmInc` for `INC`. - private execToNumericSlow(frame: Frame, flag: number, v: Value, pc: number, sp: number, helper = "$vmToNumeric") { - const fcode = frame.code - frame.pc = pc - frame.sp = sp - if (v instanceof Obj && !isOpaque(v)) { - frame.sp = sp - 1 - this.pushInternalCall(helper, [flag, v], fcode.siteAt(pc) ?? frame.origin) - return true - } - if (isOpaque(v)) { - throw invalidData(`'${flag === 0 ? "++" : "--"}' requires a data value.`, fcode.siteAt(pc)) - } - frame.regs[sp - 1] = coerceToNumber(v) - return false - } - - private execIncSlow(frame: Frame, flag: number, v: Value, pc: number, sp: number): boolean { - if (this.execToNumericSlow(frame, flag, v, pc, sp, "$vmInc")) return true - const n = frame.regs[sp - 1] as number - frame.regs[sp - 1] = flag === 0 ? n + 1 : n - 1 - return false - } - - private execToStringSlow(frame: Frame, flag: number, v: Value, pc: number, sp: number): boolean { - if (flag === 1 || !(v instanceof Obj) || isOpaque(v)) { - frame.regs[sp - 1] = coerceToString(v) - return false - } - frame.pc = pc - frame.sp = sp - 1 - this.pushInternalCall("$vmToString", [v], frame.code.siteAt(pc) ?? frame.origin) - return true - } - - private execConcat(regs: Array, n: number, sp: number): number { - let out = "" - for (let i = sp - n; i < sp; i++) { - out += regs[i] as string - if (out.length > 16_777_216) checkStringLength(out.length) - } - sp -= n - regs[sp] = out - return sp + 1 - } - - private execThrowError(frame: Frame, bx: number, pc: number, sp: number): never { - frame.pc = pc - frame.sp = sp - const site = frame.code.consts[bx] as ErrorSite - throw new PendingThrow(site.type, site.message, frame.code.siteAt(pc), site.kind, site.suggestions) - } - - private execEndFinally(frame: Frame, level: number, pc: number, sp: number): number { - const fcode = frame.code - const offset = fcode.finallyOffsets[level]! - const fin = fcode.finallies - const tag = frame.regs[fin[offset]!] as number - if (tag === 1) { - frame.pc = pc - frame.sp = sp - throw new Throw(frame.regs[fin[offset + 1]!] as Value) - } - return fin[offset + 4 + tag]! - } - - private execReturnSlow(frame: Frame, v: Value, pc: number, sp: number): boolean { - const frames = this.frames - if (frame.mode === Mode.ASYNC || frame.mode === Mode.SETTLE) { - frames.pop() - const target = frame.target as SettlingTarget - this.deliverAnswer(frame) - this.release(frame) - target.resolve(v) - return true - } - if (frame.mode === Mode.GENERATOR) { - completeGeneratorReturn(this, frame, v) - return true - } - if (frame.mode === Mode.REJECT_ONLY) { - frames.pop() - this.deliverAnswer(frame) - this.release(frame) - return true - } - if (frame.mode === Mode.BOUNDARY_OUT) { - frames.pop() - this.release(frame) - this.outcome = normal(v) - return false - } - if (frame.mode === Mode.PROGRAM) { - frame.pc = pc - frame.sp = sp - return this.finishProgram(frame, v) - } - if (frame.mode === Mode.CONSTRUCT) { - frames.pop() - // A derived constructor's return rules apply once it has returned, so its own handlers cannot catch them. - const unbound = !(v instanceof Obj) && frame.fn!.klass!.derived && (v !== undefined || frame.target !== undefined) - if (unbound) { - const site = frame.code.siteAt(pc) - this.release(frame) - if (v !== undefined) throw typeError("Derived constructors may only return object or undefined", site) - throw referenceError(THIS_BEFORE_SUPER, site) - } - const made = v instanceof Obj ? v : frame.thisValue - this.release(frame) - const caller = frames[frames.length - 1]! - caller.regs[caller.sp++] = made - caller.pc++ - return true - } - if (frame.mode === Mode.REDO) { - frames.pop() - const saved = (frame.target as Arr).items - const caller = frames[frames.length - 1]! - caller.pc = saved[0] as number - this.redo = { frame: caller, pc: caller.pc, values: [...saved.slice(1), v], next: 0 } - this.release(frame) - return true - } - frames.pop() - this.release(frame) - return true - } - - private execCallSpread(frame: Frame, pc: number, sp: number): number { - const regs = frame.regs - const argsArr = regs[--sp] as Arr - frame.pc = pc - const callee = regs[sp - 1] as Value - const thisVal = regs[sp - 2] as Value - frame.sp = sp - 2 - return this.invokeCallable(frame, callee, thisVal, [...argsArr.items], callSiteOf(frame, pc), pc) - } - - private execNew(frame: Frame, n: number, pc: number, sp: number): number { - const fcode = frame.code - const regs = frame.regs - if (n === 255) { - const callee = regs[sp - 1] as Value - if ( - !(callee instanceof Fn && callee.klass !== undefined) && - (!(callee instanceof Builtin) || callee.construct === undefined) - ) { - frame.pc = pc - frame.sp = sp - throw notConstructible(callee, fcode.siteAt(pc) as NewExpression) - } - frame.sp = sp - return 0 - } - frame.pc = pc - const base = sp - n - const callee = regs[base - 1] as Builtin | Fn - const args = regs.slice(base, sp) as Array - frame.sp = base - 1 - if (callee instanceof Fn) return this.constructClass(frame, callee, args, callSiteOf(frame, pc)) - return this.execConstruct(frame, callee, args, callSiteOf(frame, pc)) - } - - private execNewSpread(frame: Frame, pc: number, sp: number): number { - const regs = frame.regs - const argsArr = regs[--sp] as Arr - const callee = regs[--sp] as Builtin | Fn - frame.pc = pc - frame.sp = sp - if (callee instanceof Fn) return this.constructClass(frame, callee, [...argsArr.items], callSiteOf(frame, pc)) - return this.execConstruct(frame, callee, [...argsArr.items], callSiteOf(frame, pc)) - } - - // `new C(...)`, or `super(...)` for `newTarget`, runs C's constructor (`Mode.CONSTRUCT`): a base class's on a new - // instance of `newTarget.prototype`; a derived class's with `newTarget` as its `this` until `super()` binds one. - private constructClass( - callerFrame: Frame, - ctor: Fn, - args: Array, - site: AstNode | undefined, - newTarget: Fn = ctor, - ): number { - if (this.depth > MAX_CALL_DEPTH) throw rangeError("Maximum call stack size exceeded", site ?? this.currentSite()) - const proto = get(newTarget, "prototype") - const self = ctor.klass!.derived ? newTarget : new Obj(proto instanceof Obj ? proto : this.ctx.builtins.Object) - // A derived constructor's frame holds its new target until `super()` binds `this`. - this.pushFn(ctor, self, args, site ?? callerFrame.origin, Mode.CONSTRUCT, ctor.klass!.derived ? newTarget : undefined) - this.fuel-- - return 1 - } - - private execIterStepSlow(frame: Frame, custom: CustomIter, bx: number, pc: number, sp: number): boolean { - const regs = frame.regs - custom.done = true - if (custom.rawGen) { - const gen = custom.iterator as GeneratorObj - if (gen.state === "completed") { - frame.sp = sp - frame.pc = bx - return false - } - if (gen.state === "suspendedStart" || gen.state === "suspendedYield") { - gen.state = "executing" - frame.pc = pc - frame.sp = sp - resumeVmGenerator(this, gen, NEXT) - return true - } - } - regs[sp++] = custom.iterator - regs[sp++] = custom.next - frame.sp = sp - frame.pc = pc + 1 - return false - } - - // Returns the next pc, or REDO_ENTERED (here and in the other ops that read through `redoRead`). - private execIterResult(frame: Frame, slot: number, bx: number, pc: number, sp: number): number { - const regs = frame.regs - const res = regs[sp - 1] as Value - frame.pc = pc - frame.sp = sp - 1 - if (!(res instanceof Obj)) { - throw typeError("Iterator next() result must be an object.", frame.code.siteAt(pc)) - } - const reads: Array = [] - const done = this.redoRead(frame, res, "done", res, pc, sp, reads) - if (done === REDO) return REDO_ENTERED - if (done) return bx - ;(regs[slot] as CustomIter).done = false - const value = this.redoRead(frame, res, "value", res, pc, sp, reads) - if (value === REDO) return REDO_ENTERED - regs[sp - 1] = value - frame.sp = sp - return pc + 1 - } - - private execIterClose(frame: Frame, slot: number, bx: number, pc: number, sp: number): number { - const regs = frame.regs - const rec = regs[slot] - // Running again after a `return` getter, the record is already closed. - if (!(rec instanceof CustomIter) || (rec.done && !this.replaying(frame, pc))) { - frame.sp = sp - return bx - } - frame.pc = pc - frame.sp = sp - rec.done = true - const ret = this.redoRead(frame, rec.iterator, "return", rec.iterator, pc, sp, []) - if (ret === REDO) return REDO_ENTERED - if (ret === undefined || ret === null) return bx - const method = requireIteratorMethod(ret, "Iterator return", frame.code.siteAt(pc)) - regs[sp++] = rec.iterator - regs[sp++] = method - frame.sp = sp - return pc + 1 - } - - private execIterAppendAll(frame: Frame, slot: number, bx: number, pc: number, sp: number): number { - const rec = frame.regs[slot] - if (!(rec instanceof Position)) return bx - const arr = frame.regs[sp - 1] as Arr - frame.pc = pc - frame.sp = sp - for (let step = rec.step(); !step.done; step = rec.step()) { - checkArrayLength(arr.items.length + 1) - arr.items.push(step.value) - } - return pc + 1 - } - - // A named property read for an op: the value, or a program getter for the op to enter with `receiver`. - private readObjProp(target: Obj, key: string | symbol, receiver: Value, fcode: Code, pc: number): Value | GetterCall { - for (let cur: Obj | null = target; cur !== null; cur = cur.proto) { - if (cur.props.size === 0) continue - const slot = cur.props.get(key) - if (slot !== undefined) { - if ("value" in slot) return slot.value - const getter = slot.get - if (getter === undefined) return undefined - if (typeof getter !== "function") return new GetterCall(getter) - try { - return getter(receiver) - } catch (err) { - throw locate(err, fcode.siteAt(pc)) - } - } - } - return undefined - } - - /** - * One property read of an iterator op that may meet a program getter: the value, or REDO once the getter is entered - * (`Mode.REDO`), with the op's stack back as it found it (`sp0`) so it can run again from its first word. `reads` is - * the op's reads so far this run; each value read is added to it. Running again, the op's reads replay in order. - */ - redoRead( - frame: Frame, - target: Obj, - key: string | symbol, - receiver: Value, - pc: number, - sp0: number, - reads: Array, - ): Value | typeof REDO { - const start = instructionStart(frame.code.code, pc) - const redo = this.redo - if (redo !== undefined && redo.frame === frame && redo.pc === start && redo.next < redo.values.length) { - const replayed = redo.values[redo.next++] - reads.push(replayed) - return replayed - } - const v = this.readObjProp(target, key, receiver, frame.code, pc) - if (!(v instanceof GetterCall)) { - reads.push(v) - return v - } - this.redo = undefined - frame.pc = start - frame.sp = sp0 - this.pushInternal( - internalCode("$vmRedo"), - [v.getter, receiver], - callSiteOf(frame, pc), - Mode.REDO, - new Arr(this.ctx.builtins.Array, [start, ...reads]), - ) - return REDO - } - - // Whether the op at `pc` is running again after a getter, with reads left to replay. - private replaying(frame: Frame, pc: number): boolean { - const redo = this.redo - return ( - redo !== undefined && - redo.frame === frame && - redo.pc === instructionStart(frame.code.code, pc) && - redo.next < redo.values.length - ) - } - - /** - * Enters the program getter of a member read whose result goes at `at` (a method read keeps the receiver there and the - * value above it), as a call from the instruction at `pc`. Returns the new sp when the getter answered at once, or - * `GETTER_ENTERED`, `GETTER_FUEL` (entered, and the slice is over) or `GETTER_BLOCKED`. - */ - private enterGetter(frame: Frame, getter: Callable, receiver: Value, at: number, mode: number, pc: number): number { - if (mode === 1) frame.regs[at++] = receiver - frame.sp = at - frame.pc = pc - const called = this.invokeCallable(frame, getter, receiver, [], callSiteOf(frame, pc), pc) - if (called === 0) return frame.sp - if (called === 2) return GETTER_BLOCKED - return this.fuel <= 0 ? GETTER_FUEL : GETTER_ENTERED - } - - unwind(rawError: unknown): boolean { - // An interruption skips every handler, but still completes each frame by its mode: a frame that settles a - // promise rejects it, so whatever awaits that promise is interrupted in turn. - const interrupted = rawError instanceof Interruption - const error = interrupted ? rawError : locate(rawError, this.currentSite()) - this.redo = undefined - - if (this.frames.length === 0) { - this.outcome = abrupt(error) - return false - } - - while (this.frames.length > 0) { - const frame = this.frames[this.frames.length - 1]! - const fcode = frame.code - const handlers = fcode.handlers - const faultPc = frame.pc - for (let i = 0; !interrupted && i < handlers.length; i += 4) { - const start = handlers[i]! - const end = handlers[i + 1]! - if (faultPc >= start && faultPc < end) { - const target = handlers[i + 2]! - const depth = handlers[i + 3]! - const sp = fcode.locals + depth - frame.regs[sp] = materialize( - this.ctx, - error, - (fcode.flags & CodeFlags.INTERNAL) === 0 ? fcode.siteAt(faultPc) : undefined, - ) - frame.sp = sp + 1 - frame.pc = target - return true - } - } - - this.frames.pop() - const mode = frame.mode - if (mode === Mode.CALLER || mode === Mode.REDO || mode === Mode.CONSTRUCT) { - this.release(frame) - continue - } - if (mode === Mode.GENERATOR) { - if (unwindGenerator(this, frame, error)) { - return this.frames.length > 0 - } - continue - } - if (mode === Mode.ASYNC || mode === Mode.SETTLE || mode === Mode.REJECT_ONLY) { - const target = frame.target as SettlingTarget - this.deliverAnswer(frame) - this.release(frame) - target.reject(error) - return this.frames.length > 0 - } - this.release(frame) - if (mode === Mode.PROGRAM || mode === Mode.BOUNDARY_OUT) { - this.outcome = abrupt(error) - return false - } - } - return false - } - - private finishProgram(frame: Frame, value: Value): boolean { - if (!isThenable(value)) { - let fast: ReturnType - try { - fast = tryFastBoundaryOrJson(this.ctx.builtins, value, true, VISIT_BUDGET) - } catch (error) { - this.frames.pop() - this.release(frame) - this.outcome = abrupt(error) - return false - } - if (fast.ok) { - this.frames.pop() - this.release(frame) - this.outcome = normal(fast.json) - return false - } - } - this.frames.pop() - this.release(frame) - this.pushInternal(internalCode("$vmResult"), [value], undefined, Mode.BOUNDARY_OUT) - return true - } - - private makeClosure(parentCode: Code, fnIndex: number, regs: Array, cells: ReadonlyArray): Fn { - const childCode = this.codesOf(parentCode)[fnIndex]! - const caps = childCode.captures - let childCells: ReadonlyArray - if (caps.length === 0) { - childCells = EMPTY_CELLS - } else { - const arr = contiguous() - for (let i = 0; i < caps.length; i += 2) { - arr.push(caps[i] === 0 ? (regs[caps[i + 1]!] as Cell) : cells[caps[i + 1]!]!) - } - childCells = arr - } - const fn = new Fn(this.ctx.builtins.Function, childCode, childCells) - if ((childCode.flags & CodeFlags.GENERATOR) !== 0) { - const isAsync = (childCode.flags & CodeFlags.ASYNC) !== 0 - define(fn, "prototype", new Obj(isAsync ? this.ctx.builtins.AsyncGenerator : this.ctx.builtins.Generator), hidden) - } - return fn - } - - private getTemplateObject(fcode: Code, site: TemplateSite): Arr { - const key = `${fcode.source.id}:${site.nodeIndex}` - const cached = this.templates.get(key) - if (cached !== undefined) return cached - const arrayProto = this.ctx.builtins.Array - const strings = new Arr(arrayProto, [...site.cooked]) - define(strings, "raw", new Arr(arrayProto, [...site.raw]), frozen) - this.templates.set(key, strings) - return strings - } - - private execImport(frame: Frame, kind: number, k: number, pc: number, sp: number): number { - const fcode = frame.code - const siteNode = fcode.siteAt(pc) - if (kind === ImportKind.DYNAMIC) { - const specifier = frame.regs[sp - 1] as string - const promise = capability(this.ctx, siteNode) - try { - promise.resolve(this.ctx.namespace(specifier, siteNode)) - } catch (err) { - if (!(err instanceof PendingThrow)) throw err - promise.reject(err) - } - frame.regs[sp - 1] = promise.promise - return sp - } - const site = fcode.consts[k] as ImportSite - if (kind === ImportKind.SIDE_EFFECT) { - this.ctx.module(site.specifier, siteNode) - return sp - } - if (kind === ImportKind.DEFAULT) { - frame.regs[sp] = this.ctx.module(site.specifier, siteNode) - return sp + 1 - } - const ns = this.ctx.namespace(site.specifier, siteNode) - if (kind === ImportKind.NAMESPACE) { - frame.regs[sp] = ns - return sp + 1 - } - const imported = site.imported! - if (!hasOwn(ns, imported)) { - throw syntaxError(`"${site.specifier}" has no export named "${imported}".`, siteNode) - } - frame.regs[sp] = getOwn(ns, imported) - return sp + 1 - } - - // A named member read (`o.key`; mode 1 a method read, 2 a destructured property): the new sp, or a getter code. - private execGetProp(frame: Frame, o: Value, key: string, mode: number, pc: number, sp: number): number { - const regs = frame.regs - if (mode !== 2 && o instanceof Obj && !(o instanceof PromiseObj)) { - const v = key === "length" && o instanceof Arr ? o.items.length : this.readObjProp(o, key, o, frame.code, pc) - if (v instanceof GetterCall) return this.enterGetter(frame, v.getter, o, sp - 1, mode, pc) - return writeRead(regs, sp - 1, mode, o, v) - } - if (mode !== 2 && typeof o === "string") { - const v = key === "length" ? o.length : this.readObjProp(this.ctx.builtins.String, key, o, frame.code, pc) - if (v instanceof GetterCall) return this.enterGetter(frame, v.getter, o, sp - 1, mode, pc) - return writeRead(regs, sp - 1, mode, o, v) - } - if (o instanceof HostNamespace) { - return writeRead(regs, sp - 1, mode, undefined, new HostNamespace(o.root, [...o.path, key])) - } - return this.readMember(frame, sp - 1, mode, o, key, frame.code.siteAt(pc)!, pc) - } - - // A computed member read (`o[key]`), as `execGetProp`; `GETTER_ENTERED` also when the key converts in the prelude. - private execGetElem(frame: Frame, o: Value, keyVal: Value, mode: number, pc: number, sp: number): number { - if (mode === 0) { - if ( - typeof o === "string" && - typeof keyVal === "number" && - keyVal >= 0 && - keyVal < o.length && - (keyVal | 0) === keyVal - ) { - frame.regs[sp - 2] = o[keyVal] - return sp - 1 - } - if (o instanceof Obj && !(o instanceof PromiseObj)) { - if (typeof keyVal === "number" && !(o instanceof Arr)) { - if ( - o.constructor === Obj && - (o.props.size === 0 || (o.props.size === 1 && o.props.has("length"))) && - o.proto === this.ctx.builtins.Object && - o.proto.intrinsic > 0 - ) { - frame.regs[sp - 2] = undefined - return sp - 1 - } - } - if (typeof keyVal === "string" && o.constructor === Obj) { - const v = this.readObjProp(o, keyVal, o, frame.code, pc) - if (v instanceof GetterCall) return this.enterGetter(frame, v.getter, o, sp - 2, 0, pc) - frame.regs[sp - 2] = v - return sp - 1 - } - } - } - const site = frame.code.siteAt(pc)! - const memberNode = site as MemberExpression - if (mode !== 2) requireMemberBase(memberNode, o, keyVal) - if (keyVal instanceof Obj && !isOpaque(keyVal)) { - frame.sp = sp - 2 - this.pushInternalCall("$vmGetElem", [o, keyVal], memberNode.property ?? site) - return GETTER_ENTERED - } - return this.readMember(frame, sp - 2, mode, o, propertyKey(keyVal), site, pc) - } - - // Reads `o[key]` for the member expression (or destructured property, mode 2) at `site` into the stack at `at`; see - // `writeRead`. A destructured promise is read as is; a member read of one must name a property it has. - private readMember(frame: Frame, at: number, mode: number, o: Value, key: PropertyKey, site: AstNode, pc: number) { - const regs = frame.regs - const ref = this.resolveMember(o, key, site) - if (ref instanceof HostNamespace) return writeRead(regs, at, mode, undefined, ref) - if ("value" in ref) return writeRead(regs, at, mode, undefined, ref.value) - if (mode !== 2) requirePromiseProperty(ref, site) - const v = accessProperty(ref.target, ref.key, site, ref.receiver) - if (v instanceof GetterCall) return this.enterGetter(frame, v.getter, ref.receiver, at, mode, pc) - return writeRead(regs, at, mode, ref.receiver, v) - } - - // The reference `o[key]` that the member expression at `site` names. - private resolveMember(o: Value, key: PropertyKey, site: AstNode) { - const member = site as MemberExpression - return resolveProperty(this.ctx.builtins, o, key, member.object ?? site, member.property ?? site) - } - - // `o[key] = v`, with `v` popped and `o` at `sp - 1`. True when a program setter runs (`$vmSet` answers `v`). - private execPutProp(frame: Frame, o: Value, key: PropertyKey, v: Value, pc: number, sp: number): boolean { - const fcode = frame.code - let setter: Callable | undefined - try { - setter = o instanceof Obj ? assignToReference(o, key, v, undefined) : this.primitiveSetter(fcode, o, key, v, pc) - } catch (err) { - throw locate(err, fcode.siteAt(pc)) - } - if (setter === undefined) return false - frame.sp = sp - 1 - this.pushInternalCall("$vmSet", [setter, o, v], callSiteOf(frame, pc)) - return true - } - - // A write to a primitive's property: only an inherited setter can take it (with the primitive as `this`). - private primitiveSetter(fcode: Code, o: Value, key: PropertyKey, v: Value, pc: number): Callable | undefined { - const site = fcode.siteAt(pc)! - const ref = resolveProperty(this.ctx.builtins, o, key, site, site) - if (!(ref instanceof HostNamespace) && !("value" in ref)) { - const slot = lookup(ref.target, ref.key) - if (slot !== undefined && !("value" in slot)) { - const setter = slot.set - if (setter === undefined) throw failedAssignment(o, ref.key, site) - if (typeof setter !== "function") return setter - try { - setter(o, v) - } catch (err) { - throw locate(err, site) - } - return undefined - } - } - writableReference(ref, site as MemberExpression) - return undefined - } - - private execDeleteProp(fcode: Code, o: Value, key: PropertyKey, pc: number): boolean { - const site = fcode.siteAt(pc)! - const ref = this.resolveMember(o, key, site) - if (ref instanceof HostNamespace || "value" in ref || ref.receiver !== ref.target) { - throw invalidData("Only data fields may be deleted.", site) - } - if (remove(ref.target, ref.key)) return true - throw typeError(`Cannot delete property '${String(ref.key)}'.`, site) - } - - private execDeleteElem(frame: Frame, o: Value, keyVal: Value, pc: number, sp: number): boolean { - const site = frame.code.siteAt(pc)! - requireMemberBase(site as MemberExpression, o, keyVal) - if (keyVal instanceof Obj && !isOpaque(keyVal)) { - frame.sp = sp - 1 - this.pushInternalCall("$vmDeleteElem", [o, keyVal], site) - return true - } - frame.regs[sp - 1] = this.execDeleteProp(frame.code, o, propertyKey(keyVal), pc) - frame.sp = sp - return false - } - - private execCheckBase(fcode: Code, kind: number, bx: number, regs: Array, sp: number, pc: number): void { - const base = regs[kind === CheckBaseKind.READ || kind === CheckBaseKind.WRITE_ELEM ? sp - 2 : sp - 1] as Value - if (base instanceof Obj && !(base instanceof PromiseObj)) return - const site = fcode.siteAt(pc)! - if (kind === CheckBaseKind.DESTRUCTURE) { - if (base === null || base === undefined) { - throw typeError(`Cannot destructure ${describeValue(base)} as it is ${base}.`, site) - } - return - } - const memberNode = site as MemberExpression - if (kind === CheckBaseKind.READ) { - requireMemberBase(memberNode, base, regs[sp - 1] as Value) - return - } - const key = kind === CheckBaseKind.WRITE_PROP ? (fcode.consts[bx] as string) : propertyKey(regs[sp - 1] as Value) - const ref = this.resolveMember(base, key, site) - // A primitive's inherited accessor takes the write (see `primitiveSetter`); the base is all that's checked here. - if (!(ref instanceof HostNamespace) && !("value" in ref) && ref.receiver !== ref.target) { - const slot = lookup(ref.target, ref.key) - if (slot !== undefined && !("value" in slot)) return - } - requirePromiseProperty(writableReference(ref, memberNode), memberNode) - } - - private execBinarySlow(frame: Frame, op: string, a: Value, b: Value, pc: number, sp: number): boolean { - const fcode = frame.code - const site = fcode.siteAt(pc) ?? frame.origin - if (a instanceof Obj || b instanceof Obj) { - const conv = operatorConversion(op, a, b) - if (conv !== undefined) { - frame.sp = sp - 1 - this.pushInternalCall("$vmBinary", [op, a, b], site) - return true - } - } - frame.regs[sp - 1] = applyBinaryOperator(op, a, b, site!) - return false - } - - private execUnarySlow(frame: Frame, sub: number, v: Value, pc: number, sp: number): boolean { - if (sub === 3) { - frame.regs[sp - 1] = typeofValue(v) - return false - } - if (sub === 4) { - frame.regs[sp - 1] = undefined - return false - } - const fcode = frame.code - const site = fcode.siteAt(pc) ?? frame.origin - if (v instanceof Obj && !isOpaque(v)) { - frame.sp = sp - 1 - this.pushInternalCall("$vmUnary", [sub, v], site) - return true - } - if (isOpaque(v)) throw invalidData("Unary operators require data values.", site) - const n = coerceToNumber(v) - frame.regs[sp - 1] = sub === UnaryOp.NEG ? -n : sub === UnaryOp.PLUS ? +n : ~n - return false - } - - private execCallSlow(frame: Frame, n: number, pc: number, sp: number): number { - const regs = frame.regs - const base = sp - n - const callee = regs[base - 1] as Value - const thisVal = regs[base - 2] as Value - if (callee instanceof Native) { - conversions.count = 0 - const args = - n === 0 - ? [] - : n === 1 - ? [regs[base] as Value] - : n === 2 - ? [regs[base] as Value, regs[base + 1] as Value] - : (regs.slice(base, sp) as Array) - frame.pc = pc - frame.sp = base - 2 - const site = callee.callback && callee.call.length < 3 ? undefined : callSiteOf(frame, pc) - const res = callee.call(thisVal, args, site) - if (this.tripEvery === 0) this.fuel -= NATIVE_FUEL - if ( - (res as unknown) !== BLOCK && - (res as unknown) !== ENTERED && - (res === null || typeof res !== "object" || res instanceof Obj) - ) { - normalizeItems(res) - regs[base - 2] = res - frame.sp = base - 1 - return 0 - } - return this.settleNativeResult(frame, res, callee, thisVal, args, false, site ?? callSiteOf(frame, pc), pc) - } - const args = regs.slice(base, sp) as Array - frame.sp = base - 2 - return this.invokeCallable(frame, callee, thisVal, args, callSiteOf(frame, pc), pc) - } - - /** - * Dispatches a call to `callee`. Returns `0` if synchronous value pushed, `1` if a frame was entered, `2` if the job - * blocks on a host call. - */ - private invokeCallable( - callerFrame: Frame, - callee: Value | VmIntrinsic | VmInternalFn, - thisVal: Value, - args: Array, - site: AstNode | undefined, - pc: number, - ): number { - while (callee instanceof BoundFn) { - thisVal = callee.boundThis - args = [...callee.boundArgs, ...args] - callee = callee.target - } - - if (callee instanceof VmIntrinsic) { - let res: NativeResult - try { - res = callee.call(args) - } catch (err) { - throw locate(err, site ?? this.currentSite()) - } - // `$Replay` hands a built-in's next request back to `$vmReplay`'s loop. - if ((res instanceof Convert || res instanceof Prefetch) && callee.name === "$Replay") { - callerFrame.regs[callerFrame.sp++] = res as unknown as Value - return 0 - } - return this.settleNativeResult(callerFrame, res, undefined, thisVal, args, false, site, pc) - } - - if (callee instanceof VmInternalFn) { - const callArgs = callee.boundArgs !== undefined ? [...callee.boundArgs, ...args] : args - const f = this.pushInternal(callee.code, callArgs, site ?? callerFrame.origin) - if ((callee.code.flags & CodeFlags.NEEDS_ARGS) !== 0) f.args = callArgs - f.thisValue = thisVal - this.fuel-- - return 1 - } - - if (callee instanceof Fn) { - const code = callee.code - if ((code.flags & CodeFlags.CLASS_CONSTRUCTOR) !== 0) { - throw typeError( - `Class constructor ${String(get(callee, "name"))} cannot be invoked without 'new'`, - site ?? this.currentSite(), - ) - } - const counted = (code.flags & CodeFlags.INTERNAL) === 0 - if (counted && this.depth > MAX_CALL_DEPTH) { - throw rangeError("Maximum call stack size exceeded", site ?? this.currentSite()) - } - const isGenerator = (code.flags & CodeFlags.GENERATOR) !== 0 - const isAsync = (code.flags & CodeFlags.ASYNC) !== 0 - const origin = site ?? callerFrame.origin - if (isAsync && !isGenerator) { - const resolving = this.scheduler.resolving(this.scheduler.newPromise(), site ?? this.currentSite()) - this.pushFn(callee, thisVal, args, origin, Mode.ASYNC, resolving, resolving.promise) - } else this.pushFn(callee, thisVal, args, origin, Mode.CALLER) - this.fuel-- - return 1 - } - - if (callee instanceof Builtin) { - conversions.count = 0 - let res: NativeResult - try { - res = callee.invoke(thisVal, args, site ?? this.currentSite()) - } catch (err) { - throw locate(err, site ?? this.currentSite()) - } - if (this.tripEvery === 0) this.fuel -= NATIVE_FUEL - return this.settleNativeResult(callerFrame, res, callee, thisVal, args, false, site, pc) - } - - if (callee instanceof HostNamespace) { - if (callee.path.length === 0) { - const callNode = site as { readonly callee?: Expression } | undefined - throw typeError(`${callee.root} is not a function.`, callNode?.callee ?? site) - } - const result = this.ctx.callNamespace(callee, args, site ?? this.currentSite()) - if (result instanceof Prefetch) { - return this.settleNativeResult(callerFrame, result, callee, undefined, args, false, site, pc) - } - return this.hostResult(callerFrame, result) - } - - const callNode = site as { readonly callee?: Expression } | undefined - throw notAFunction(callNode?.callee, site ?? this.currentSite()) - } - - private execConstruct( - callerFrame: Frame, - ctor: Builtin, - args: Array, - site: AstNode | undefined, - newTarget: Builtin | Fn = ctor, - ): number { - conversions.count = 0 - let res: NativeResult - try { - res = ctor.construct!(args, newTarget, site ?? this.currentSite()) - } catch (err) { - throw locate(err, site ?? this.currentSite()) - } - return this.settleNativeResult(callerFrame, res, ctor, newTarget, args, true, site, callerFrame.pc) - } - - private settleNativeResult( - callerFrame: Frame, - res: NativeResult, - callable: Builtin | HostNamespace | undefined, - thisOrNewTarget: Value, - args: Array, - constructing: boolean, - site: AstNode | undefined, - pc: number, - ): number { - if (res instanceof Invoke) { - normalizeItems(res.thisValue) - for (let i = 0; i < res.args.length; i++) normalizeItems(res.args[i]) - return this.invokeCallable(callerFrame, res.callable, res.thisValue, res.args, res.site ?? site, pc) - } - if (res instanceof Resume) { - resumeVmGenerator(this, res.generator, res.request) - return 1 - } - if ((res as unknown) === BLOCK) return 2 - if ((res as unknown) === ENTERED) return 1 - if (res instanceof Convert || res instanceof Prefetch) { - const builtins = this.ctx.builtins - this.pushInternalCall( - "$vmReplay", - [ - callable!, - thisOrNewTarget, - new Arr(builtins.Array, args), - constructing, - new Arr(builtins.Array, []), - new Arr(builtins.Array, []), - res as unknown as Value, - ], - site ?? callerFrame.origin, - ) - return 1 - } - if (res instanceof Push) { - const kindName = res.kind - const slots = res.slots - const builtins = this.ctx.builtins - if (kindName === "JSON.stringify") { - const [value, replacer, properties, indent] = slots as [ - Value, - Callable | undefined, - Array | undefined, - string | number | undefined, - ] - if (replacer === undefined && properties === undefined) { - const fast = tryFastBoundaryOrJson(builtins, value, false, VISIT_BUDGET) - if (fast.ok) { - const text = JSON.stringify(fast.json, null, indent) - if (text !== undefined) checkStringLength(text.length) - callerFrame.regs[callerFrame.sp++] = text - return 0 - } - } - this.pushInternalCall( - "$vmJsonWalk", - [replacer, value, properties !== undefined ? new Arr(builtins.Array, properties) : null, indent], - site ?? callerFrame.origin, - ) - return 1 - } - if (kindName === "AsyncFromSyncIterator") { - return handleAdapterPush(this, callerFrame, slots) - } - const promiseHandled = this.scheduler.handlePromisePush(callerFrame, kindName, slots, site ?? callerFrame.origin) - if (promiseHandled !== undefined) return promiseHandled - throw new NotYetImplemented(`Push kind: ${kindName}`) - } - callerFrame.regs[callerFrame.sp++] = res as Value - return 0 - } - - // A host operation's answer, by `invokeCallable`'s convention: a value is pushed (0), a frame entered (1), or the job - // blocks (2). - private hostResult(callerFrame: Frame, result: Exclude): number { - if (result === ENTERED) return 1 - if (result === BLOCK) return 2 - callerFrame.regs[callerFrame.sp++] = result - return 0 - } - - /** - * Enters the program function `fn`, from the call at `origin`. A frame in another `mode` than `CALLER` settles - * `target`, and hands the caller `answer` when it ends. - */ - pushFn( - fn: Fn, - thisValue: Value, - args: Array, - origin: AstNode | undefined, - mode: FrameMode, - target?: unknown, - answer?: Value, - ): void { - const code = fn.code - const counted = (code.flags & CodeFlags.INTERNAL) === 0 - if (counted) this.depth++ - const f = this.acquire(code) - f.fn = fn - f.cells = fn.cells.length === 0 ? EMPTY_CELLS : fn.cells - f.counted = counted - if ((code.flags & CodeFlags.SIMPLE_PARAMS) !== 0) { - for (let i = 0; i < code.params; i++) f.regs[i] = i < args.length ? args[i] : undefined - } - f.args = (code.flags & CodeFlags.NEEDS_ARGS) !== 0 ? args : undefined - f.thisValue = thisValue - f.origin = counted ? undefined : origin - f.pc = 0 - f.sp = code.locals - f.mode = mode - f.target = target - f.answer = answer - this.frames.push(f) - } - - private pushInternalCall(name: string, args: Array, origin: AstNode | undefined): void { - this.pushInternal(internalCode(name), args, origin) - } - - /** Runs an internal prelude function at the call `origin`; see `HostVm.pushInternal`. */ - pushInternal( - code: Code, - args: ReadonlyArray, - origin: AstNode | undefined, - mode: FrameMode = Mode.CALLER, - target?: unknown, - answer?: Value, - ): Frame { - const f = this.acquire(code) - f.fn = null - f.cells = EMPTY_CELLS - for (let i = 0; i < code.params; i++) f.regs[i] = i < args.length ? args[i] : undefined - f.thisValue = undefined - f.args = undefined - f.origin = origin - f.pc = 0 - f.sp = code.locals - f.mode = mode - f.target = target - f.answer = answer - f.counted = false - this.frames.push(f) - return f - } - - private execIterOpen(frame: Frame, context: number, pc: number, sp: number): number { - const v = frame.regs[sp - 1] as Value - const fcode = frame.code - if ( - context !== IterContext.FOR_AWAIT && - context !== IterContext.ASYNC_DELEGATE && - context !== IterContext.DELEGATE - ) { - const cursor = builtinCursor(this.ctx.builtins, v) - if (cursor !== undefined) { - if (cursor instanceof Position) { - frame.regs[sp - 1] = cursor - } else { - frame.regs[sp - 1] = this.customIter(cursor.iterator, cursor.next) - } - return skipJump(fcode.code, pc) - } - } - const site = fcode.siteAt(pc) ?? frame.origin - const reads: Array = [] - if (context === IterContext.FOR_AWAIT || context === IterContext.ASYNC_DELEGATE) { - const opened = this.openWithMethod(frame, v, AsyncIteratorSymbol, site, pc, sp, reads) - if (opened !== false) return opened === REDO ? REDO_ENTERED : pc + 1 - const cursor = builtinCursor(this.ctx.builtins, v) - if (cursor !== undefined) { - const adapter = new AsyncFromSyncIterator(this.ctx.builtins.AsyncFromSyncIterator, cursor, site!) - const next = this.redoRead(frame, adapter, "next", adapter, pc, sp, reads) - if (next === REDO) return REDO_ENTERED - frame.regs[sp - 1] = new CustomIter(adapter, next) - return skipJump(fcode.code, pc) - } - if (v instanceof Obj) { - const syncMethod = this.redoRead(frame, v, IteratorSymbol, v, pc, sp, reads) - if (syncMethod === REDO) return REDO_ENTERED - if (syncMethod !== undefined && syncMethod !== null) { - const callable = requireIteratorMethod(syncMethod, "Iterator method", site) - const openCode = internalCode("$vmOpenSyncForAsync") - frame.regs[sp - 1] = undefined - frame.regs[sp] = new VmInternalFn(openCode, [v, callable]) - frame.sp = sp + 1 - return pc + 1 - } - } - if (context === IterContext.FOR_AWAIT) { - throw invalidData(`for await...of requires an iterable value, received ${describeValue(v)}.`, site) - } - throw typeError("yield* requires a compatible iterable value.", site) - } - - if (context === IterContext.DELEGATE) { - const opened = this.openWithMethod(frame, v, IteratorSymbol, site, pc, sp, reads) - if (opened !== false) return opened === REDO ? REDO_ENTERED : pc + 1 - const cursor = builtinCursor(this.ctx.builtins, v) - if (cursor !== undefined) { - const iterObj = - cursor instanceof Position ? new IteratorObj(this.ctx.builtins.Iterator, cursor) : cursor.iterator - const next = this.redoRead(frame, iterObj, "next", iterObj, pc, sp, reads) - if (next === REDO) return REDO_ENTERED - frame.regs[sp - 1] = new CustomIter(iterObj, next) - return skipJump(fcode.code, pc) - } - throw typeError("yield* requires a compatible iterable value.", site) - } - - const opened = this.openWithMethod(frame, v, IteratorSymbol, site, pc, sp, reads) - if (opened !== false) return opened === REDO ? REDO_ENTERED : pc + 1 - if (context === IterContext.FOR_OF) { - throw invalidData(`for...of requires an iterable value, received ${describeValue(v)}.`, site) - } - if (context === IterContext.DESTRUCTURE) { - throw typeError("Array destructuring requires a supported iterable value.", site) - } - throw typeError( - site?.type === "SpreadElement" && (fcode.sourceObj?.nodes.includes(site) ?? false) - ? "Spread requires a synchronous iterable." - : "Value is not iterable.", - site, - ) - } - - // True when a `next` getter is entered first. - private execIterInit(frame: Frame, context: number, pc: number, sp: number): boolean { - const site = frame.code.siteAt(pc) ?? frame.origin - const v = frame.regs[sp - 1] as Value - if (context === IterContext.CHECK_OBJECT) { - requireIteratorObject(v, "Iterator return() result", site) - return false - } - const obj = requireIteratorObject(v, "Iterator method result", site) - const read = this.redoRead(frame, obj, "next", obj, pc, sp, []) - if (read === REDO) return true - frame.regs[sp - 1] = this.customIter(obj, requireIteratorMethod(read, "Iterator next", site)) - return false - } - - // Opens `v` with its own `symbol` method, when it has one (true): the next instruction calls it. - private openWithMethod( - frame: Frame, - v: Value, - symbol: symbol, - site: AstNode | undefined, - pc: number, - sp: number, - reads: Array, - ): boolean | typeof REDO { - if (!(v instanceof Obj)) return false - const method = this.redoRead(frame, v, symbol, v, pc, sp, reads) - if (method === REDO) return REDO - if (method === undefined || method === null) return false - frame.regs[sp - 1] = v - frame.regs[sp] = requireIteratorMethod(method, "Iterator method", site) - frame.sp = sp + 1 - return true - } - - // A synchronous generator's (or iterator helper's) own `next` is stepped without a call to it. - private customIter(iterator: Obj, next: Value): CustomIter { - const custom = new CustomIter(iterator, next) - const builtins = this.ctx.builtins - custom.rawGen = - iterator instanceof GeneratorObj && - !iterator.asynchronous && - (next === peek(builtins.Generator, "next") || next === peek(builtins.IteratorHelper, "next")) - return custom - } - - // Decodes one or two `EXTRA` prefix words and dispatches the widened instruction. - // Negative returns encode outer control: `-1` = `continue outer`, `-2` = `return 0`, `-3` = `return 1`, `-4` = `return 2`. - private execExtra(frame: Frame, w: number, pc: number, sp: number): number { - const code = frame.code.code - const w1 = code[pc + 1]! - const op1 = w1 & 0xff - if (op1 === Op.EXTRA) { - const w2 = code[pc + 2]! - const wideA = ((w >>> 16) << 16) | (w1 & 0xff00) | ((w2 >>> 8) & 0xff) - const wideBx = ((w1 >>> 16) << 16) | (w2 >>> 16) - frame.pc = pc + 2 - frame.sp = sp - return this.execWide(frame, w2 & 0xff, wideA, wideBx, pc + 2) - } - const wideA = (w & 0xff00) | ((w1 >>> 8) & 0xff) - const wideBx = ((w >>> 16) << 16) | (w1 >>> 16) - frame.pc = pc + 1 - frame.sp = sp - return this.execWide(frame, op1, wideA, wideBx, pc + 1) - } - - // An instruction after its `EXTRA` prefix: the same work as in `exec`, with wide `a` and `bx`. - private execWide(frame: Frame, op: number, a: number, bx: number, pc: number): number { - const fcode = frame.code - const regs = frame.regs - const consts = fcode.consts - const cells = frame.cells - let sp = frame.sp - switch (op) { - case Op.PUSH_UNDEF: - regs[sp++] = undefined - frame.sp = sp - return pc + 1 - case Op.PUSH_NULL: - regs[sp++] = null - frame.sp = sp - return pc + 1 - case Op.PUSH_BOOL: - regs[sp++] = a === 1 - frame.sp = sp - return pc + 1 - case Op.PUSH_CONST: - regs[sp++] = consts[bx] - frame.sp = sp - return pc + 1 - case Op.POP: - frame.sp = sp - 1 - return pc + 1 - case Op.POPN: - frame.sp = sp - bx - return pc + 1 - case Op.DUP: - regs[sp] = regs[sp - 1] - frame.sp = sp + 1 - return pc + 1 - case Op.PICK: - regs[sp] = regs[sp - 1 - a] - frame.sp = sp + 1 - return pc + 1 - case Op.ROT: - this.execRot(regs, a, sp) - return pc + 1 - case Op.GET_LOCAL: - case Op.GET_CELL: { - const v = op === Op.GET_LOCAL ? regs[bx] : (regs[bx] as Cell).v - if (v === HOLE) this.failTdz(frame, fcode.localNames[bx]!, pc, sp) - regs[sp++] = v - frame.sp = sp - return pc + 1 - } - case Op.PUT_LOCAL: { - const v = regs[--sp] - frame.sp = sp - if (a !== PutKind.INIT && (regs[bx] === HOLE || a === PutKind.CONST)) { - this.failPut(frame, fcode.localNames[bx]!, regs[bx], pc, sp) - } - regs[bx] = v - return pc + 1 - } - case Op.PUT_CELL: - case Op.PUT_UPVAL: { - const v = regs[--sp] - frame.sp = sp - const cell = op === Op.PUT_CELL ? (regs[bx] as Cell) : cells[bx]! - if (a !== PutKind.INIT && (cell.v === HOLE || a === PutKind.CONST)) { - this.failPut(frame, (op === Op.PUT_CELL ? fcode.localNames : fcode.upvalNames)[bx]!, cell.v, pc, sp) - } - cell.v = v - return pc + 1 - } - case Op.HOLE_LOCAL: - regs[bx] = HOLE - return pc + 1 - case Op.NEW_CELL: - regs[bx] = new Cell(a === 1 ? regs[bx] : HOLE) - return pc + 1 - case Op.COPY_CELL: - regs[bx] = new Cell((regs[bx] as Cell).v) - return pc + 1 - case Op.GET_UPVAL: { - const v = cells[bx]!.v - if (v === HOLE) this.failTdz(frame, fcode.upvalNames[bx]!, pc, sp) - regs[sp++] = v - frame.sp = sp - return pc + 1 - } - case Op.GET_GLOBAL: - regs[sp] = this.execGetGlobal(frame, a, consts[bx] as string, pc, sp) - frame.sp = sp + 1 - return pc + 1 - case Op.GET_INTRINSIC: - regs[sp++] = this.getIntrinsic(consts[bx] as string) - frame.sp = sp - return pc + 1 - case Op.ARGS: - regs[sp++] = this.execArgs(frame, a, bx) - frame.sp = sp - return pc + 1 - case Op.CLOSURE: - regs[sp++] = this.makeClosure(fcode, bx, regs, cells) - frame.sp = sp - return pc + 1 - case Op.SET_NAME: - this.execSetName(regs, consts, a, bx, sp) - return pc + 1 - case Op.IMPORT: - frame.sp = this.execImport(frame, a, bx, pc, sp) - return pc + 1 - case Op.GET_PROP: - case Op.GET_ELEM: { - const r = - op === Op.GET_PROP - ? this.execGetProp(frame, regs[sp - 1] as Value, consts[bx] as string, a, pc, sp) - : this.execGetElem(frame, regs[sp - 2] as Value, regs[sp - 1] as Value, a, pc, sp) - if (r < 0) return r === GETTER_ENTERED ? -1 : r === GETTER_FUEL ? -3 : -4 - frame.sp = r - return pc + 1 - } - case Op.PUT_PROP: { - const v = regs[--sp] as Value - frame.sp = sp - if (this.execPutProp(frame, regs[sp - 1] as Value, consts[bx] as string, v, pc, sp)) return -1 - regs[sp - 1] = v - return pc + 1 - } - case Op.PUT_ELEM: { - const v = regs[--sp] as Value - const keyVal = regs[--sp] as Value - frame.sp = sp - if (this.execPutProp(frame, regs[sp - 1] as Value, propertyKey(keyVal), v, pc, sp)) return -1 - regs[sp - 1] = v - return pc + 1 - } - case Op.DELETE_PROP: - regs[sp - 1] = this.execDeleteProp(fcode, regs[sp - 1] as Value, consts[bx] as string, pc) - return pc + 1 - case Op.DELETE_ELEM: { - const keyVal = regs[--sp] as Value - frame.sp = sp - if (this.execDeleteElem(frame, regs[sp - 1] as Value, keyVal, pc, sp)) return -1 - return pc + 1 - } - case Op.CHECK_BASE: - this.execCheckBase(fcode, a, bx, regs, sp, pc) - return pc + 1 - case Op.TO_KEY: { - const v = regs[sp - 1] as Value - if (typeof v !== "string" && typeof v !== "number" && typeof v !== "symbol") { - if (this.execToKey(frame, v, pc, sp)) return -1 - } - return pc + 1 - } - case Op.IN: { - const rhs = regs[--sp] as Value - frame.sp = sp - if (this.execIn(frame, regs[sp - 1] as Value, rhs, pc, sp)) return -1 - return pc + 1 - } - case Op.INSTANCEOF: { - const rhs = regs[--sp] as Value - frame.sp = sp - if (this.execInstanceof(frame, regs[sp - 1] as Value, rhs, pc, sp)) return -1 - return pc + 1 - } - case Op.NEW_OBJECT: - regs[sp++] = new Obj(this.ctx.builtins.Object) - frame.sp = sp - return pc + 1 - case Op.NEW_ARRAY: - frame.sp = this.execNewArray(regs, bx, sp) - return pc + 1 - case Op.ARRAY_APPEND: - frame.sp = this.execArrayAppend(regs, a, sp) - return pc + 1 - case Op.DEFINE_FIELD: - frame.sp = this.execDefineField(regs, consts, a, bx, sp) - return pc + 1 - case Op.COPY_DATA_PROPS: - frame.sp = --sp - if (this.execCopyDataProps(frame, regs[sp - 1] as Obj, regs[sp] as Value, pc, sp)) return -1 - return pc + 1 - case Op.COPY_REST: { - const r = this.execCopyRest(frame, regs, bx, pc, sp) - if (r < 0) return -1 - frame.sp = r - return pc + 1 - } - case Op.TEMPLATE: - regs[sp++] = this.getTemplateObject(fcode, consts[bx] as TemplateSite) - frame.sp = sp - return pc + 1 - case Op.REGEXP: - regs[sp] = this.execRegExp(fcode, consts[bx] as RegExpSite, pc) - frame.sp = sp + 1 - return pc + 1 - case Op.ADD: - case Op.SUB: - case Op.MUL: - case Op.LT: - case Op.LE: - case Op.GT: - case Op.GE: { - const b = regs[--sp] as Value - const lhs = regs[sp - 1] as Value - frame.sp = sp - const sym = - op === Op.ADD - ? "+" - : op === Op.SUB - ? "-" - : op === Op.MUL - ? "*" - : op === Op.LT - ? "<" - : op === Op.LE - ? "<=" - : op === Op.GT - ? ">" - : ">=" - if (this.execBinarySlow(frame, sym, lhs, b, pc, sp)) return -1 - return pc + 1 - } - case Op.SEQ: { - const b = regs[--sp] - frame.sp = sp - regs[sp - 1] = regs[sp - 1] === b - return pc + 1 - } - case Op.SNE: { - const b = regs[--sp] - frame.sp = sp - regs[sp - 1] = regs[sp - 1] !== b - return pc + 1 - } - case Op.BINOP: { - const b = regs[--sp] as Value - const lhs = regs[sp - 1] as Value - frame.sp = sp - if (typeof lhs === "number" && typeof b === "number") { - regs[sp - 1] = this.execBinopNum(a, lhs, b) - return pc + 1 - } - if (this.execBinopSlow(frame, a, lhs, b, pc, sp)) return -1 - return pc + 1 - } - case Op.UNARY: { - const v = regs[sp - 1] as Value - if (typeof v === "number" && a < 3) { - regs[sp - 1] = a === 0 ? -v : a === 1 ? +v : ~v - return pc + 1 - } - if (this.execUnarySlow(frame, a, v, pc, sp)) return -1 - return pc + 1 - } - case Op.NOT: - regs[sp - 1] = !regs[sp - 1] - return pc + 1 - case Op.TO_NUMERIC: { - const v = regs[sp - 1] as Value - if (typeof v !== "number" && this.execToNumericSlow(frame, a, v, pc, sp)) return -1 - return pc + 1 - } - case Op.INC: { - const v = regs[sp - 1] as Value - if (typeof v === "number") { - regs[sp - 1] = a === 0 ? v + 1 : v - 1 - return pc + 1 - } - if (this.execIncSlow(frame, a, v, pc, sp)) return -1 - return pc + 1 - } - case Op.TO_STRING: { - const v = regs[sp - 1] as Value - if (typeof v !== "string" && this.execToStringSlow(frame, a, v, pc, sp)) return -1 - return pc + 1 - } - case Op.CONCAT: - frame.sp = this.execConcat(regs, bx, sp) - return pc + 1 - case Op.JUMP: - return bx - case Op.LOOP: - frame.pc = bx - if (--this.fuel <= 0) return -3 - return bx - case Op.JUMP_IF_FALSE: - frame.sp = sp - 1 - return regs[sp - 1] ? pc + 1 : bx - case Op.JUMP_IF_TRUE: - frame.sp = sp - 1 - return regs[sp - 1] ? bx : pc + 1 - case Op.JUMP_COND: { - const v = regs[sp - 1] - if (a === CondKind.NULLISH) { - if (v === null || v === undefined) { - regs[sp - 1] = undefined - return bx - } - return pc + 1 - } - if (a === CondKind.NULLISH_METHOD) { - if (v === null || v === undefined) { - frame.sp = sp - 1 - regs[sp - 2] = undefined - return bx - } - return pc + 1 - } - const jump = - a === CondKind.TRUTHY_KEEP - ? Boolean(v) - : a === CondKind.FALSY_KEEP - ? !v - : a === CondKind.NOT_NULLISH_KEEP - ? v !== null && v !== undefined - : v !== undefined - if (jump) return bx - frame.sp = sp - 1 - return pc + 1 - } - case Op.THROW: - return this.execThrow(frame, regs[--sp] as Value, pc, sp) - case Op.THROW_ERROR: - return this.execThrowError(frame, bx, pc, sp) - case Op.END_FINALLY: - return this.execEndFinally(frame, bx, pc, sp) - case Op.RETURN: - case Op.END_PROGRAM: { - const v = regs[sp - 1] as Value - if (frame.mode === 0) { - this.frames.pop() - if (frame.counted) this.depth-- - if (this.pool.length < 128) this.pool.push(frame) - const caller = this.frames[this.frames.length - 1]! - caller.regs[caller.sp++] = v - caller.pc++ - return -1 - } - return this.execReturnSlow(frame, v, pc, sp) ? -1 : -2 - } - case Op.NOP: - return pc + 1 - case Op.CALL: { - const called = this.execCallSlow(frame, a, pc, sp) - if (called === 1) return this.fuel <= 0 ? -3 : -1 - if (called === 2) return -4 - frame.pc = pc + 1 - return this.fuel <= 0 ? -3 : pc + 1 - } - case Op.CALL_SPREAD: { - const called = this.execCallSpread(frame, pc, sp) - if (called === 1) return this.fuel <= 0 ? -3 : -1 - if (called === 2) return -4 - frame.pc = pc + 1 - return this.fuel <= 0 ? -3 : pc + 1 - } - case Op.NEW: { - const made = this.execNew(frame, a, pc, sp) - if (made === 1) return -1 - if (made === 2) return -4 - return pc + 1 - } - case Op.NEW_SPREAD: { - const made = this.execNewSpread(frame, pc, sp) - if (made === 1) return -1 - if (made === 2) return -4 - return pc + 1 - } - case Op.ITER_OPEN: - return this.execIterOpen(frame, a, pc, sp) - case Op.ITER_INIT: - if (this.execIterInit(frame, a, pc, sp)) return -1 - return pc + 1 - case Op.ITER_STEP: { - const rec = regs[a] - if (rec instanceof Position) { - const step = rec.step() - if (!step.done) { - regs[sp++] = step.value - frame.sp = sp - return skipJump(fcode.code, pc) - } - return bx - } - if (this.execIterStepSlow(frame, rec as CustomIter, bx, pc, sp)) return -1 - return frame.pc - } - case Op.ITER_RESULT: - return this.execIterResult(frame, a, bx, pc, sp) - case Op.ITER_CLOSE: - return this.execIterClose(frame, a, bx, pc, sp) - case Op.ITER_APPEND_ALL: - return this.execIterAppendAll(frame, a, bx, pc, sp) - case Op.FOR_IN: - regs[sp - 1] = this.execForIn(fcode, regs[sp - 1] as Value, pc) - return pc + 1 - case Op.GENERATOR_START: - execGeneratorStart(this, frame, pc, sp) - return -1 - case Op.YIELD: - if (execYield(this, frame, pc, sp)) return -1 - return frame.pc - case Op.RESUME: - return execResume(frame, bx, pc, sp) - case Op.AWAIT: - execAwait(this, frame, a, pc, sp) - return -1 - case Op.YSTAR: - return execYstar(this, frame, a, bx, pc, sp) - case Op.YSTAR_RESULT: - return execYstarResult(this, frame, a, bx, pc, sp) - case Op.DEFINE_ACCESSOR: - frame.sp = this.execDefineAccessor(regs, consts, a, bx, sp) - return pc + 1 - case Op.CLASS: - frame.sp = this.execClass(frame, a, pc, sp) - return pc + 1 - case Op.SUPER_CALL: { - const made = this.execSuperCall(frame, a, bx, pc) - if (made === 1) return -1 - if (made === 2) return -4 - return pc + 1 - } - case Op.SUPER_BIND: - this.execSuperBind(frame, a, bx, pc) - return pc + 1 - case Op.GET_SUPER: { - const r = this.execGetSuper(frame, a, bx, pc) - if (r < 0) return r === GETTER_ENTERED ? -1 : r === GETTER_FUEL ? -3 : -4 - frame.sp = r - return pc + 1 - } - case Op.PUT_SUPER: - return this.execPutSuper(frame, a, bx, pc) ? -1 : pc + 1 - case Op.SET_HOME: - ;(regs[sp - 1] as Fn).home = regs[sp - 1 - a] as Obj - return pc + 1 - case Op.DEFINE_METHOD: - frame.sp = this.execDefineMethod(regs, consts, a, bx, sp) - return pc + 1 - case Op.SET_FIELDS: - frame.sp = this.execSetFields(regs, sp) - return pc + 1 - case Op.INIT_FIELDS: { - const called = this.execInitFields(frame, a, pc, sp) - if (called === 1) return this.fuel <= 0 ? -3 : -1 - if (called === 2) return -4 - frame.pc = pc + 1 - return pc + 1 - } - default: - throw new Error(`Unexpected wide op ${op}`) - } - } -} - -// What `execGetProp` / `execGetElem` return in place of a stack pointer once they enter a frame (a getter, say): it runs -// now (`continue outer`), the slice is over, or the job blocks on the host call the getter made. -const hasStaticName = (fn: Fn): boolean => { - const slot = own(fn, "name") - return slot !== undefined && (!("value" in slot) || typeof slot.value !== "string") -} - -const THIS_BEFORE_SUPER = - "Must call super constructor in derived class before accessing 'this' or returning from derived constructor" - -// What a class may extend: another class or an error constructor. Other built-ins and `null` are refused. -const classParent = (parent: Value, site: AstNode | undefined, builtins: Builtins): Fn | Builtin => { - if (parent === null) throw typeError("Classes extending null are not supported.", site) - if (parent instanceof Fn && parent.klass !== undefined) return parent - if (isErrorConstructor(parent, builtins)) return parent - if (parent instanceof Builtin && parent.construct !== undefined) { - throw typeError( - `Extending the built-in ${String(peek(parent, "name"))} is not supported. Only classes and Error types can be extended.`, - site, - ) - } - throw typeError(`Class extends value ${describeValue(parent)} is not a constructor or null.`, site) -} - -const isErrorConstructor = (value: Value, builtins: Builtins): value is Builtin => { - if (!(value instanceof Builtin)) return false - const name = peek(value, "name") - return typeof name === "string" && isErrorType(name) && peek(builtins[name], "constructor") === value -} - -// The object `super.x` reads from: the home object's prototype. -const superBase = (home: Obj, site: AstNode | undefined): Obj => { - if (home.proto === null) throw typeError("Cannot use 'super' here: the home object has no prototype.", site) - return home.proto -} - -const GETTER_ENTERED = -1 -const GETTER_FUEL = -2 -const GETTER_BLOCKED = -3 - -// `redoRead`'s answer once it entered a getter, and the iterator ops' (a negative pc, so `continue outer`). -export const REDO: unique symbol = Symbol("vm.redo") -export const REDO_ENTERED = -1 - -// The first word of the instruction whose opcode word is at `pc`: before its `EXTRA` prefix words, if any. -const instructionStart = (code: Int32Array, pc: number): number => { - if (pc > 0 && (code[pc - 1]! & 0xff) === Op.EXTRA) - return pc > 1 && (code[pc - 2]! & 0xff) === Op.EXTRA ? pc - 2 : pc - 1 - return pc -} - -// Skips the `JUMP slow` instruction following a test-and-skip `ITER_OPEN` or `ITER_STEP`. -const skipJump = (code: Int32Array, pc: number): number => ((code[pc + 1]! & 0xff) === Op.EXTRA ? pc + 3 : pc + 2) - -// A member read's result replaces its base at `at`; a method read (mode 1) keeps the receiver under the value. -const writeRead = (regs: Array, at: number, mode: number, receiver: Value, value: Value): number => { - if (mode !== 1) { - regs[at] = value - return at + 1 - } - regs[at] = receiver - regs[at + 1] = value - return at + 2 -} - -const NEXT: GeneratorRequest = { kind: "next", value: undefined } - -// Where the call at `pc` is located: its own node, or inside the VM's internal code, the call that entered it. -const callSiteOf = (frame: Frame, pc: number) => - (frame.code.flags & CodeFlags.INTERNAL) === 0 ? frame.code.siteAt(pc) : frame.origin - -// Rewrites an array's first item in place, so arrays a native returns share the item shape JSC sees in the VM's own. -const normalizeItems = (value: unknown) => { - if (!(value instanceof Arr) || !(0 in value.items)) return - const first = value.items[0] - value.items[0] = "" - value.items[0] = first -} - -let warmed = false - -const WARMUP_SOURCE = [ - "return (async () => {", - " let totalSum = 0", - " const fib = (n) => (n < 2 ? n : fib(n - 1) + fib(n - 2))", - " const restFn = (a, b, ...r) => r.length", - " const fiveFn = (a, b, c, d, e) => (a === b ? c : d) !== e ? 1 : 0", - " const work = async (i) => { await null; return i * 2 }", - " function* range(n) { for (let i = 0; i < n; i++) yield i }", - " for (let r = 0; r < 12; r++) {", - " let sum = 0", - " for (let i = 0; i < 6; i++) sum = (sum + i * 3 + (i === 2 ? 1 : 0)) % 1000003", - " sum += fib(3) + restFn(1, 2, 3) + fiveFn(r & 1, 1, 2, work, fib)", - " for (const x of range(3)) sum += x", - ' let out = ""', - " for (let i = 0; i < 3; i++) out += String.fromCharCode(97 + (i % 26))", - " const parts = []", - " for (let i = 0; i < 3; i++) parts.push(`item-${i}`)", - " const map = new Map(), set = new Set()", - ' for (let i = 0; i < 4; i++) { map.set("k" + (i % 2), i); set.add(i % 2) }', - " for (const [k, v] of map) sum += v", - " for (const v of set) sum += v", - ' map.delete("k0"); set.delete(0)', - " const items = Array.from({ length: 4 }, (_, i) => (i * 7919) % 4)", - " const mapped = items.map((x) => x * 2).filter((x) => x % 3 !== 0)", - " const total = mapped.reduce((a, b) => a + b, 0)", - " const sorted = mapped.slice(0, 4).sort((a, b) => a - b)", - ' const obj = { a: 1, b: "two", c: [1, r], d: null, e: sorted }', - " if (r >= 2) sum += JSON.stringify(JSON.parse(JSON.stringify(obj))).length", - " const pres = await Promise.all(Array.from({ length: 2 }, (_, i) => work(i)))", - ' totalSum += sum + total + sorted.length + pres.length + out.length + parts.join(",").length + map.size + set.size', - " }", - " return totalSum", - "})()", -].join("\n") - -const warmupVm = (vm: Vm): void => { - warmed = true - const savedTripEvery = vm.tripEvery - vm.tripEvery = 0 - try { - const ast = parse(WARMUP_SOURCE, { - ecmaVersion: "latest", - sourceType: "script", - allowReturnOutsideFunction: true, - }) - const source = new Source("", WARMUP_SOURCE, ast) - vm.start(source) - for (;;) { - const stop = vm.run() - if (stop.kind === "done" || stop.kind === "stuck") break - if (stop.kind === "host") { - for (const call of stop.calls) vm.complete(call.id, normal(1)) - } - } - vm.sourceCodes.delete(source.id) - vm.ctx.sources.delete(source.id) - } catch { - } finally { - vm.frames.length = 0 - vm.templates.clear() - vm.scheduler.parked.clear() - vm.scheduler.queue.length = 0 - vm.scheduler.head = 0 - vm.scheduler.pending = 0 - vm.scheduler.nextID = 0 - vm.scheduler.unhandled.clear() - vm.hosts.queued.length = 0 - vm.hosts.running.clear() - vm.hosts.inbox.length = 0 - vm.hosts.nextID = 0 - vm.hosts.blocked = undefined - vm.hosts.input = undefined - vm.depth = 0 - vm.fuel = INITIAL_FUEL - vm.sliced = false - vm.outcome = undefined - vm.tripEvery = savedTripEvery - } -} diff --git a/packages/codemode/test/LICENSE.test262 b/packages/codemode/test/LICENSE.test262 deleted file mode 100644 index fb7434013ba..00000000000 --- a/packages/codemode/test/LICENSE.test262 +++ /dev/null @@ -1,28 +0,0 @@ -Test262: ECMAScript Test Suite ("Software") is protected by copyright and is being -made available under the "BSD License", included below. This Software may be subject to third party rights (rights -from parties other than Ecma International), including patent rights, and no licenses under such third party rights -are granted under this license even if the third party concerned is a member of Ecma International. SEE THE ECMA -CODE OF CONDUCT IN PATENT MATTERS AVAILABLE AT https://www.ecma-international.org/ipr FOR -INFORMATION REGARDING THE LICENSING OF PATENT CLAIMS THAT ARE REQUIRED TO IMPLEMENT ECMA INTERNATIONAL STANDARDS*. - -Copyright (C) 2012 Ecma International -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the -following conditions are met: -1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following - disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the - following disclaimer in the documentation and/or other materials provided with the distribution. -3. Neither the name of the authors nor Ecma International may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE ECMA INTERNATIONAL "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT -SHALL ECMA INTERNATIONAL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -DAMAGE. - -* Ecma International Standards hereafter means Ecma International Standards as well as Ecma Technical Reports diff --git a/packages/codemode/test/LICENSE.wpt b/packages/codemode/test/LICENSE.wpt deleted file mode 100644 index 39c46d03ac2..00000000000 --- a/packages/codemode/test/LICENSE.wpt +++ /dev/null @@ -1,11 +0,0 @@ -# The 3-Clause BSD License - -Copyright © web-platform-tests contributors - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. -3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/packages/codemode/test/accessors-suspend.test.ts b/packages/codemode/test/accessors-suspend.test.ts deleted file mode 100644 index 42ae074be97..00000000000 --- a/packages/codemode/test/accessors-suspend.test.ts +++ /dev/null @@ -1,407 +0,0 @@ -import { describe, expect, test } from "bun:test" -import { tmpdir } from "node:os" -import path from "node:path" -import { Effect, Fiber } from "effect" -import { Host, Runtime, toBytes } from "../src/language/index.js" -import { parking } from "../src/language/runtime/driver.js" -import { savedFrames as frames } from "../src/language/snapshot.js" -import { runProgram } from "./run-program.js" - -// Suspending and resuming a run at every point a program getter or setter can run or be pending. Each language-level -// case runs once straight through, and once saved to bytes and restored into a fresh runtime at every slice; the -// saved stacks must include the point under test (a getter's frame, the helper running it), and both runs must end -// the same way. Host calls in flight are suspended with `program.suspend()` and resumed with `runtime.resume`, in -// this process and in another one. - -/** Runs `code` straight through and with a save and restore at every slice; what the saved stacks held. */ -const suspendEverywhere = (code: string) => { - const plain = runProgram(code) - const stacks: Array> = [] - const tripped = runProgram(code, { - roundTrip: { every: 1, max: 100_000 }, - onTrip: (snapshot) => stacks.push(frames(snapshot)), - }) - expect(tripped).toEqual(plain) - return { - result: plain, - saw: (...names: Array) => stacks.some((stack) => names.every((n) => stack.includes(n))), - } -} - -describe("suspended inside a getter", () => { - test("entered from a member read, a computed read, destructuring and a method lookup", () => { - const run = suspendEverywhere(` - const o = { - n: 2, - get member() { let s = 0; for (let i = 0; i < 3; i++) s += this.n; return s }, - get computed() { let s = 0; for (let i = 0; i < 3; i++) s += i; return s }, - get destructured() { let s = 1; for (let i = 0; i < 3; i++) s *= 2; return s }, - get method() { let k = 0; for (let i = 0; i < 3; i++) k++; return () => k }, - } - const key = "computed" - const { destructured } = o - return [o.member, o[key], destructured, o.method()]`) - expect(run.result).toMatchObject({ ok: true, value: [6, 3, 8, 3] }) - for (const name of ["get member", "get computed", "get destructured", "get method"]) - expect(run.saw(name)).toBe(true) - }) - - test("a getter that throws, caught after a resume", () => { - const run = suspendEverywhere(` - const o = { get x() { let s = 0; for (let i = 0; i < 3; i++) s += i; throw new RangeError("at " + s) } } - try { return o.x } catch (e) { return [e instanceof RangeError, e.message] }`) - expect(run.result).toMatchObject({ ok: true, value: [true, "at 3"] }) - expect(run.saw("get x")).toBe(true) - }) - - test("a getter that throws, uncaught after a resume", () => { - const run = suspendEverywhere(` - const o = { get x() { for (let i = 0; i < 3; i++) {} throw new TypeError("no") } } - return o.x`) - expect(run.result).toMatchObject({ ok: false, error: { message: expect.stringContaining("no") } }) - expect(run.saw("get x")).toBe(true) - }) -}) - -describe("suspended inside a setter", () => { - test("from =, += and ++", () => { - const run = suspendEverywhere(` - const log = [] - const o = { - v: 1, - get x() { return this.v }, - set x(v) { for (let i = 0; i < 2; i++) {} log.push(v); this.v = v }, - } - const a = (o.x = 5) - o.x += 2 - o.x++ - return [a, o.v, log]`) - expect(run.result).toMatchObject({ ok: true, value: [5, 8, [5, 7, 8]] }) - expect(run.saw("set x", "$vmSet")).toBe(true) - }) -}) - -describe("suspended in an iterator-protocol getter (Mode.REDO)", () => { - const iterable = ` - const log = [] - const make = (n) => ({ - [Symbol.iterator]() { - let i = 0 - return { - get next() { for (let k = 0; k < 2; k++) {} return () => ({ - get done() { for (let k = 0; k < 2; k++) {} log.push("done"); return ++i > n }, - get value() { for (let k = 0; k < 2; k++) {} log.push("value"); return i }, - }) }, - } - }, - })` - - test("for...of, spread and destructuring", () => { - const run = suspendEverywhere(`${iterable} - const out = [] - for (const x of make(2)) out.push(x) - const [first, second] = make(3) - return [out, [...make(2)], first, second, log.length]`) - expect(run.result).toMatchObject({ ok: true, value: [[1, 2], [1, 2], 1, 2, 14] }) - expect(run.saw("get done", "$vmRedo (redo)")).toBe(true) - expect(run.saw("get value", "$vmRedo (redo)")).toBe(true) - expect(run.saw("get next", "$vmRedo (redo)")).toBe(true) - }) - - test("a getter that throws during for...of", () => { - const run = suspendEverywhere(` - const it = { [Symbol.iterator]() { return { next() { return { get done() { for (let k = 0; k < 2; k++) {} throw new Error("bad done") } } } } } } - try { for (const x of it) {} } catch (e) { return e.message }`) - expect(run.result).toMatchObject({ ok: true, value: "bad done" }) - expect(run.saw("get done", "$vmRedo (redo)")).toBe(true) - }) -}) - -describe("suspended mid read-ahead ($vmReplay)", () => { - test("Array.from, structuredClone and Object.defineProperties with getter descriptors", () => { - const run = suspendEverywhere(` - const slow = (v) => { for (let k = 0; k < 2; k++) {} return v } - const like = { get length() { return slow(2) }, get 0() { return slow("a") }, 1: "b" } - const clone = structuredClone({ get deep() { return { get v() { return slow(1) } } } }) - const target = Object.defineProperties({}, { x: { get value() { return slow(3) }, get enumerable() { return slow(true) } } }) - return [Array.from(like), clone, target.x, Object.keys(target)]`) - expect(run.result).toMatchObject({ ok: true, value: [["a", "b"], { deep: { v: 1 } }, 3, ["x"]] }) - for (const name of ["get length", "get 0", "get deep", "get v", "get value", "get enumerable"]) { - expect(run.saw(name, "$vmReplay")).toBe(true) - } - }) -}) - -describe("suspended in the bytecode slow paths", () => { - test("Object.entries, values, assign (with target setters) and spread", () => { - const run = suspendEverywhere(` - const log = [] - const tick = () => { for (let k = 0; k < 2; k++) {} } - const source = { a: 1, get b() { tick(); return 2 } } - const target = { set b(v) { tick(); log.push(v) } } - Object.assign(target, source) - const { a, ...rest } = source - return [Object.entries(source), Object.values(source), { ...source }, rest, log]`) - expect(run.result).toMatchObject({ - ok: true, - value: [ - [ - ["a", 1], - ["b", 2], - ], - [1, 2], - { a: 1, b: 2 }, - { b: 2 }, - [2], - ], - }) - expect(run.saw("get b", "objectEntries")).toBe(true) - expect(run.saw("get b", "objectAssign")).toBe(true) - expect(run.saw("set b", "objectAssign")).toBe(true) - expect(run.saw("get b", "$vmCopyDataProps")).toBe(true) - }) -}) - -describe("suspended in the final result's conversion", () => { - test("getters run as the result is copied out", () => { - const run = suspendEverywhere(` - return { a: 1, get b() { for (let k = 0; k < 3; k++) {} return { get c() { for (let k = 0; k < 3; k++) {} return 3 } } } }`) - expect(run.result).toMatchObject({ ok: true, value: { a: 1, b: { c: 3 } } }) - expect(run.saw("get b", "$vmResult")).toBe(true) - expect(run.saw("get c", "$vmResult")).toBe(true) - }) -}) - -/** A latch the test opens by hand. */ -const latch = () => { - let resolve!: (value: A) => void - const promise = new Promise((done) => (resolve = done)) - return { promise, resolve } -} - -// A runtime whose `slow` (idempotent, so a suspend may cut it off and a resume calls it again) answers `n * 2` once -// `gate` opens, and whose sync `pick` and `keep` take arguments with promises awaited first. -const hosting = (gate: Promise | undefined) => { - const started = latch() - const kept: Array = [] - // Its host functions need no services. - const runtime = Runtime.make({ - translate: { promises: "await" }, - globals: () => ({ - slow: Host.fn( - ([n]) => - Effect.promise(async () => { - started.resolve() - await gate - return (n as number) * 2 - }), - { type: "async", idempotent: true }, - ), - pick: Host.fn(([value]) => value), - keep: Host.fn((args) => void kept.push(args)), - }), - }) as Runtime.Runtime - return { runtime, started: started.promise, kept } -} - -// Runs `code` until `slow` is in flight, suspends, and resumes the saved bytes in a fresh runtime; and runs it -// straight through. Both results, and what `keep` got in each. -const suspendInFlight = async (code: string) => { - const suspended = await suspendParked(code) - const bytes = toBytes(suspended.state) - const second = hosting(undefined) - const resumed = await Effect.runPromise(second.runtime.resume(bytes).run()) - const straight = hosting(undefined) - const plain = await Effect.runPromise(straight.runtime.execute(code)) - return { resumed, plain, kept: second.kept, keptPlain: straight.kept, state: suspended.state, bytes } -} - -// Runs `code` until it is parked waiting on `slow`, and suspends it there; the gate opens after the suspend. -const suspendParked = async (code: string) => { - const gate = latch() - const first = hosting(gate.promise) - const parked = latch() - parking.onPark = parked.resolve - const program = first.runtime.program(code, { runId: "r" }) - const fiber = Effect.runFork(program.run()) - await Promise.all([first.started, parked.promise]) - parking.onPark = undefined - const suspended = await Effect.runPromise(program.suspend()) - // The suspended run's host call settles before any resume. - gate.resolve() - await Effect.runPromise(Fiber.join(fiber)) - if (suspended.ok !== "suspended") throw new Error(`expected a suspended run, got ${JSON.stringify(suspended)}`) - return { state: suspended.state, runtime: first.runtime } -} - -describe("suspended while a getter waits on a host call", () => { - test("a getter waiting on an awaited host argument (a sync call in a getter, under REDO too)", async () => { - const code = ` - const o = { get x() { return pick(slow(21)) } } - const it = { [Symbol.iterator]() { let i = 0; return { next() { return { get done() { return i++ > 0 }, get value() { return o.x } } } } } } - return [[...it], o.x]` - const run = await suspendInFlight(code) - expect(run.plain).toMatchObject({ ok: true, value: [[42], 42] }) - expect(run.resumed).toMatchObject({ ok: true, value: [[42], 42] }) - expect(frames(run.state)).toEqual(expect.arrayContaining(["get x", "get value", "$vmRedo (redo)", "$vmHostWait"])) - }) - - test("a getter waiting under REDO itself", async () => { - const code = ` - const it = { [Symbol.iterator]() { let i = 0; return { next() { return { get done() { return pick(slow(i++)) > 0 }, value: "v" } } } } } - return [...it]` - const run = await suspendInFlight(code) - expect(run.plain).toMatchObject({ ok: true, value: ["v"] }) - expect(run.resumed).toEqual(run.plain) - expect(frames(run.state)).toEqual(expect.arrayContaining(["get done", "$vmRedo (redo)", "$vmHostWait"])) - }) - - test("a getter read ahead for a host call, waiting on its own host call", async () => { - const code = ` - const o = { a: 1, get b() { return pick(slow(5)) } } - keep(o, { get c() { return 3 } }) - return "kept"` - const run = await suspendInFlight(code) - expect(run.plain).toMatchObject({ ok: true, value: "kept" }) - expect(run.resumed).toEqual(run.plain) - expect(run.kept).toEqual([[{ a: 1, b: 10 }, { c: 3 }]]) - expect(run.keptPlain).toEqual(run.kept) - expect(frames(run.state)).toEqual(expect.arrayContaining(["get b", "$vmReplay", "$vmHostWait"])) - }) - - test("a host call's awaited arguments after its getters ran ($vmHostWait with the read table)", async () => { - const code = ` - let n = 0 - keep({ p: slow(4), get g() { n++; return "g" } }) - return n` - const run = await suspendInFlight(code) - expect(run.plain).toMatchObject({ ok: true, value: 1 }) - expect(run.resumed).toEqual(run.plain) - expect(run.kept).toEqual([[{ p: 8, g: "g" }]]) - expect(frames(run.state)).toContain("$vmHostWait") - }) - - test("the final result's getter waiting on a host call", async () => { - const run = await suspendInFlight(`return { get x() { return pick(slow(2)) } }`) - expect(run.plain).toMatchObject({ ok: true, value: { x: 4 } }) - expect(run.resumed).toEqual(run.plain) - expect(frames(run.state)).toEqual(expect.arrayContaining(["get x", "$vmResult"])) - }) - - test("a setter waiting on a host call, resumed in another process", async () => { - const code = ` - const o = { set x(v) { this.got = pick(slow(v)) } } - o.x = 8 - return o.got` - const run = await suspendInFlight(code) - expect(run.plain).toMatchObject({ ok: true, value: 16 }) - expect(run.resumed).toEqual(run.plain) - expect(frames(run.state)).toEqual(expect.arrayContaining(["set x", "$vmSet"])) - const file = path.join(tmpdir(), `codemode-getters-${crypto.randomUUID()}.state`) - await Bun.write(file, run.bytes) - try { - const child = Bun.spawn(["bun", path.join(import.meta.dir, "fixtures/resume-getters-process.ts"), file], { - stdout: "pipe", - stderr: "inherit", - }) - const output = await new Response(child.stdout).text() - expect(await child.exited).toBe(0) - expect(JSON.parse(output)).toEqual(JSON.parse(JSON.stringify(run.plain))) - } finally { - await Bun.file(file).delete() - } - }) - - test("an iterator's next getter waiting on a host call", async () => { - const code = ` - const it = { [Symbol.iterator]() { let i = 0; return { get next() { const k = pick(slow(1)); return () => ({ done: i >= 2, value: i++ * k }) } } } } - const out = [] - for (const x of it) out.push(x) - return [out, [...it]]` - const same = await suspendParked(code) - const again = hosting(undefined) - expect(await Effect.runPromise(again.runtime.resume(same.state).run())).toMatchObject({ - ok: true, - value: [ - [0, 2], - [0, 2], - ], - }) - const run = await suspendInFlight(code) - expect(run.plain).toMatchObject({ - ok: true, - value: [ - [0, 2], - [0, 2], - ], - }) - expect(run.resumed).toEqual(run.plain) - expect(frames(run.state)).toEqual(expect.arrayContaining(["get next", "$vmRedo (redo)", "$vmHostWait"])) - }) - - for (const [name, code, value] of [ - [ - "yield*", - `function* g() { return yield* { [Symbol.iterator]() { let i = 0; return { get next() { const k = pick(slow(1)); return () => ({ done: i >= 2, value: i++ * k }) } } } } } return [...g()]`, - [0, 2], - ], - [ - "for await", - `const out = []; for await (const x of { [Symbol.asyncIterator]() { let i = 0; return { get next() { const k = pick(slow(1)); return async () => ({ done: i >= 2, value: i++ * k }) } } } }) out.push(x); return out`, - [0, 2], - ], - [ - "destructure", - `const [a, b] = { [Symbol.iterator]() { let i = 0; return { get next() { const k = pick(slow(1)); return () => ({ done: false, value: ++i * k }) } } } }; return [a, b]`, - [2, 4], - ], - [ - "Array.from", - `return Array.from({ [Symbol.iterator]() { let i = 0; return { get next() { const k = pick(slow(1)); return () => ({ done: i >= 2, value: i++ * k }) } } } })`, - [0, 2], - ], - ] as const) { - test(`an iterator's next getter waiting on a host call (${name})`, async () => { - const run = await suspendInFlight(code) - expect(run.plain).toMatchObject({ ok: true, value }) - expect(run.resumed).toEqual(run.plain) - }) - } - - for (const from of ["state", "bytes"] as const) { - test(`an iterator's next getter waiting on a host call, resumed on the same runtime (${from})`, async () => { - const code = ` - const it = { [Symbol.iterator]() { let i = 0; return { get next() { const k = pick(slow(1)); return () => ({ done: i >= 2, value: i++ * k }) } } } } - return [...it]` - const suspended = await suspendParked(code) - expect(frames(suspended.state)).toEqual(expect.arrayContaining(["get next", "$vmRedo (redo)", "$vmHostWait"])) - const resumed = await Effect.runPromise( - suspended.runtime.resume(from === "state" ? suspended.state : toBytes(suspended.state)).run(), - ) - expect(resumed).toMatchObject({ ok: true, value: [0, 2] }) - }) - } - - test("a getter inside an iterator op, resumed in another process", async () => { - const code = ` - const it = { [Symbol.iterator]() { let i = 0; return { get next() { return () => ({ get done() { return pick(slow(i)) > 4 }, value: i++ }) } } } } - return [...it]` - const run = await suspendInFlight(code) - expect(run.plain).toMatchObject({ ok: true, value: [0, 1] }) - expect(run.resumed).toEqual(run.plain) - expect(frames(run.state)).toEqual(expect.arrayContaining(["get done", "$vmRedo (redo)", "$vmHostWait"])) - const file = path.join(tmpdir(), `codemode-getters-${crypto.randomUUID()}.state`) - await Bun.write(file, run.bytes) - try { - const child = Bun.spawn(["bun", path.join(import.meta.dir, "fixtures/resume-getters-process.ts"), file], { - stdout: "pipe", - stderr: "inherit", - }) - const output = await new Response(child.stdout).text() - expect(await child.exited).toBe(0) - expect(JSON.parse(output)).toEqual(JSON.parse(JSON.stringify(run.plain))) - } finally { - await Bun.file(file).delete() - } - }) -}) diff --git a/packages/codemode/test/accessors.test.ts b/packages/codemode/test/accessors.test.ts deleted file mode 100644 index ef1ba54a3ad..00000000000 --- a/packages/codemode/test/accessors.test.ts +++ /dev/null @@ -1,453 +0,0 @@ -import { describe, expect, test } from "bun:test" -import { createBuiltins } from "../src/language/runtime/intrinsics.js" -import { PendingThrow } from "../src/language/runtime/model.js" -import { accessorRule, defineAccessorHalf, get, Native, Obj, peek } from "../src/language/runtime/objects.js" -import { runProgram } from "./run-program.js" - -// Program-defined getters and setters: object literals, every read and write form, the built-ins that copy or -// enumerate objects, the iterator and promise protocols, and display, which never calls them. - -// Every program also runs saved and restored into a fresh runtime at every slice, and must end the same way. -const value = (code: string) => { - const result = runProgram(code) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - expect(runProgram(code, { roundTrip: { every: 1, max: 20_000 } })).toEqual(result) - return result.value -} -const error = (code: string) => { - const result = runProgram(code) - if (result.ok) throw new Error(`expected failure, got value ${JSON.stringify(result.value)}`) - return result.error -} - -describe("object literal accessors", () => { - test("a getter and a setter share one property", () => { - expect( - value(`const o = { _v: 2, get v() { return this._v * 10 }, set v(x) { this._v = x } } - const before = o.v - o.v = 5 - return [before, o.v, o._v, Object.keys(o)]`), - ).toEqual([20, 50, 5, ["_v", "v"]]) - }) - - test("names and lengths: get x, set x, computed and symbol keys", () => { - expect( - value(`const k = "dyn" - const o = { get x() { return 1 }, set x(v) {}, get [k + 1]() { return 2 }, get [Symbol.iterator]() { return 3 }, get 5() { return 4 } } - return [o.x, o.dyn1, o[Symbol.iterator], o[5]]`), - ).toEqual([1, 2, 3, 4]) - }) - - test("later definitions win, and data and accessors replace each other in source order", () => { - expect( - value(`const a = { get x() { return 1 }, get x() { return 2 } } - const b = { x: 1, get x() { return 3 } } - const c = { get x() { return 3 }, x: 4 } - const d = { get x() { return 5 }, x: 6, set x(v) { this.seen = v } } - d.x = 7 - const e = { ...{ x: 1 }, get x() { return 8 } } - return [a.x, b.x, c.x, d.x, d.seen, e.x]`), - ).toEqual([2, 3, 4, null, 7, 8]) - }) - - test("an accessor named __proto__ is an own property, as in JS", () => { - expect(value(`const o = { get __proto__() { return 1 } }; return [o.__proto__, Object.keys(o)]`)).toEqual([ - 1, - ["__proto__"], - ]) - }) -}) - -describe("reads call the getter", () => { - test("member, computed and object keys, with this as the receiver", () => { - expect( - value(`const o = { n: 3, get x() { return this.n } } - const key = { toString() { return "x" } } - const k = "x" - return [o.x, o["x"], o[k], o[key]]`), - ).toEqual([3, 3, 3, 3]) - }) - - test("an inherited getter sees the object read from", () => { - expect( - value(`const p = { get id() { return this.name } }; const c = Object.create(p); c.name = "c"; return c.id`), - ).toBe("c") - }) - - test("method calls keep the receiver", () => { - expect( - value(`const o = { k: 4, get m() { return function () { return this.k } } } - return [o.m(), o["m"]()]`), - ).toEqual([4, 4]) - }) - - test("optional chaining, typeof, and destructuring with defaults and nesting", () => { - expect( - value(`const o = { get a() { return undefined }, get b() { return { c: 5 } }, get f() { return () => 1 } } - const { a = 7, b: { c }, ["f"]: f } = o - return [o?.b?.c, o.missing?.x, typeof o.f, a, c, f(), o.f?.()]`), - ).toEqual([5, null, "function", 7, 5, 1, 1]) - }) - - test("each read calls the getter once", () => { - expect( - value( - `let calls = 0; const o = { get x() { calls++; return 1 } }; o.x; o["x"]; const { x } = o; o.x?.toString(); return calls`, - ), - ).toBe(4) - }) - - test("a getter that throws is caught in the caller", () => { - expect( - value(`const o = { get x() { throw new Error("boom") } }; try { return o.x } catch (e) { return e.message }`), - ).toBe("boom") - expect(error(`const o = { get x() { throw new TypeError("no") } }\nreturn o.x`)).toMatchObject({ - message: expect.stringContaining("no"), - }) - }) - - test("a recursive getter hits the call depth limit", () => { - expect(error(`const o = { get x() { return this.x } }; return o.x`).message).toContain( - "Maximum call stack size exceeded", - ) - }) - - test("a getter can return a promise, and a long getter is time sliced", () => { - expect(value(`const o = { get p() { return Promise.resolve(3) } }; return await o.p`)).toBe(3) - expect( - runProgram(`const o = { get n() { let s = 0; for (let i = 0; i < 1e5; i++) s += i; return s } }; return o.n`, { - maxSlices: 1e6, - }), - ).toMatchObject({ ok: true, value: 4999950000 }) - }) - - test("instanceof calls a prototype getter, after checking the callable", () => { - expect(error(`return {} instanceof {}`).message).toContain("is not callable") - }) -}) - -describe("writes call the setter", () => { - test("assignment answers the assigned value, not what the setter returns", () => { - expect( - value( - `const o = { set x(v) { this.y = v * 2; return 99 } }; const r = (o.x = 3); const s = (o["x"] = 4); return [r, s, o.y]`, - ), - ).toEqual([3, 4, 8]) - }) - - test("compound assignment, ++ and -- run the getter then the setter", () => { - expect( - value(`const log = [] - const o = { n: 1, get x() { log.push("get"); return this.n }, set x(v) { log.push("set " + v); this.n = v } } - o.x += 5 - const post = o.x++ - const pre = ++o["x"] - o.x-- - return [post, pre, o.n, log]`), - ).toEqual([6, 8, 7, ["get", "set 6", "get", "set 7", "get", "set 8", "get", "set 7"]]) - }) - - test("logical assignment calls the setter only when it assigns", () => { - expect( - value(`let sets = 0 - const o = { v: 0, get x() { return this.v }, set x(v) { sets++; this.v = v } } - o.x ||= 1 - o.x ||= 2 - o.x &&= 3 - o.x ??= 4 - return [o.v, sets]`), - ).toEqual([3, 2]) - }) - - test("an inherited setter takes the write; a getter-only accessor refuses it", () => { - expect( - value( - `const p = { set x(v) { this.got = v } }; const c = Object.create(p); c.x = 1; return [c.got, Object.keys(c)]`, - ), - ).toEqual([1, ["got"]]) - expect(error(`const o = { get x() { return 1 } }; o.x = 2`).message).toContain( - "Cannot set property 'x' of a data object which has only a getter.", - ) - }) - - test("a setter decides what is stored, so assigning the object itself is no cycle", () => { - expect(value(`const o = { set self(v) { this.ok = v === o } }; o.self = o; return o.ok`)).toBe(true) - }) -}) - -describe("enumeration never calls accessors", () => { - test("keys, for...in, in, hasOwnProperty, delete and console.log", () => { - expect( - runProgram(`let calls = 0 - const o = { a: 1, get b() { calls++; return 2 }, set c(v) { calls++ }, get d() { calls++ }, set d(v) {} } - const seen = [] - for (const k in o) seen.push(k) - console.log(o) - const r = [Object.keys(o), seen, "b" in o, o.hasOwnProperty("b"), delete o.a, calls] - return r`), - ).toMatchObject({ - ok: true, - value: [["a", "b", "c", "d"], ["a", "b", "c", "d"], true, true, true, 0], - logs: ['{"a":1,"b":[Getter],"c":[Setter],"d":[Getter/Setter]}'], - }) - }) - - test("console.table labels accessors, own and inherited", () => { - const result = runProgram( - `console.table([Object.create({ get a() { return 1 } }), { get a() { return 2 }, b: 3 }], ["a", "b"]); return 0`, - ) - expect(result).toMatchObject({ ok: true, logs: [expect.stringContaining("[Getter]")] }) - }) -}) - -describe("copying built-ins", () => { - test("spread and rest call each getter once in key order and copy data", () => { - expect( - value(`const log = [] - const o = { a: 1, get b() { log.push("b"); return 2 }, get c() { log.push("c"); return 3 }, [Symbol.iterator]: 4 } - const copy = { ...o } - const { a, ...rest } = o - return [copy, rest, log, Object.keys(rest), copy[Symbol.iterator], rest[Symbol.iterator]]`), - ).toEqual([{ a: 1, b: 2, c: 3 }, { b: 2, c: 3 }, ["b", "c", "b", "c"], ["b", "c"], 4, 4]) - }) - - test("Object.entries and values check enumerability as they visit", () => { - expect( - value(`const o = { get a() { delete this.b; return 1 }, b: 2, c: 3 } - const p = { get a() { return 1 }, b: 2 } - return [Object.entries(o), Object.values(p)]`), - ).toEqual([ - [ - ["a", 1], - ["c", 3], - ], - [1, 2], - ]) - }) - - test("Object.assign runs source getters and target setters, including inherited ones", () => { - expect( - value(`const log = [] - const target = Object.create({ set b(v) { log.push("set b " + v) } }) - const source = { a: 1, get b() { log.push("get b"); return 2 }, [Symbol.iterator]: 5 } - Object.assign(target, source, null, "xy") - return [Object.keys(target), target[Symbol.iterator], target[0], log]`), - ).toEqual([["0", "1", "a"], 5, "x", ["get b", "set b 2"]]) - }) - - test("JSON.stringify calls getters and leaves setter-only properties out", () => { - expect( - value(`const o = { a: 1, get b() { return [2] }, set c(v) {}, nested: { get d() { return "d" } } } - return JSON.stringify(o)`), - ).toBe('{"a":1,"b":[2],"nested":{"d":"d"}}') - }) - - test("the program's result calls getters, and a then getter is adopted", () => { - expect(value(`return { a: 1, get b() { return 2 }, set c(v) {} }`)).toEqual({ a: 1, b: 2 }) - expect(value(`return { get then() { return (resolve) => resolve(7) } }`)).toBe(7) - }) -}) - -describe("the iterator protocol", () => { - const iterable = `const log = [] - const make = (n) => ({ - get [Symbol.iterator]() { - log.push("iterator") - return () => { - let i = 0 - return { - get next() { - log.push("next") - return () => { - i++ - return { get done() { log.push("done"); return i > n }, get value() { log.push("value"); return i * 10 } } - } - }, - get return() { log.push("return"); return () => ({}) }, - } - } - }, - })` - - test("for...of, spread and array destructuring read each getter as JS does", () => { - expect( - value(`${iterable} - const out = [] - for (const x of make(2)) out.push(x) - log.push("|") - const spread = [...make(1)] - log.push("|") - const [first] = make(3) - return [out, spread, first, log]`), - ).toEqual([ - [10, 20], - [10], - 10, - [ - "iterator", - "next", - "done", - "value", - "done", - "value", - "done", - "|", - "iterator", - "next", - "done", - "value", - "done", - "|", - "iterator", - "next", - "done", - "value", - "return", - ], - ]) - }) - - test("break calls a return getter once, and yield* delegates through getters", () => { - expect( - value(`${iterable} - for (const x of make(5)) break - function* outer() { yield* make(2) } - return [[...outer()], log]`), - ).toEqual([ - [10, 20], - [ - "iterator", - "next", - "done", - "value", - "return", - "iterator", - "next", - "done", - "value", - "done", - "value", - "done", - "value", - ], - ]) - }) - - test("a self-memoizing done getter reads each property once, in order", () => { - expect( - value(`const out = [] - const it = { [Symbol.iterator]() { let i = 0; return { next() { i++; return { get done() { delete this.done; this.done = i > 2; return i > 2 }, get value() { return i } } } } } } - for (const x of it) out.push(x) - return out`), - ).toEqual([1, 2]) - }) - - test("for await over a sync iterator with getters", () => { - expect( - value(`${iterable} - const out = [] - for await (const x of make(2)) out.push(x) - return out`), - ).toEqual([10, 20]) - }) -}) - -describe("thenables", () => { - test("await reads a then getter once; a non-function then fulfills with the object", () => { - expect( - value(`let calls = 0 - const a = await { get then() { calls++; return (resolve) => resolve(1) } } - const b = await { get then() { calls++; return 5 }, x: 2 } - return [a, b.x, calls]`), - ).toEqual([1, 2, 2]) - }) - - test("a throwing then getter rejects, and Promise.resolve adopts through a getter", () => { - expect( - value(`const bad = { get then() { throw new Error("nope") } } - const caught = await Promise.resolve(bad).catch((e) => e.message) - return [caught, await Promise.resolve({ get then() { return (r) => r(3) } })]`), - ).toEqual(["nope", 3]) - }) -}) - -describe("crossing to the host", () => { - test("a setter-only native accessor is left out of an object with no program accessors", () => { - const target = new Obj(createBuiltins().Object) - target.props.set("a", { value: 1, writable: true, enumerable: true, configurable: true }) - target.props.set("w", { get: undefined, set: () => {}, enumerable: true, configurable: true }) - expect(target.hasProgramAccessors).toBe(false) - expect(target.toHost((value) => value)).toEqual({ a: 1 }) - }) -}) - -describe("the safety net", () => { - test("a built-in that reaches a program accessor with no path is a defect in tests, a TypeError otherwise", () => { - const builtins = createBuiltins() - const target = new Obj(builtins.Object) - defineAccessorHalf(target, "x", "get", new Native(builtins.Function, { name: "get x", call: () => 1 })) - expect(() => get(target, "x")).toThrow("A built-in reached the program accessor x with no path for it.") - accessorRule.check = false - try { - expect(() => get(target, "x")).toThrow(PendingThrow) - expect(peek(target, "x")).toBeUndefined() - } finally { - accessorRule.check = true - } - }) -}) - -// Each program runs in a fresh runtime, so the accessor on Object.prototype ends with it; the programs that do not -// return through it also delete it before they finish. -describe("internal arrays ignore indexed accessors on Object.prototype", () => { - test("a setter does not catch the writes of a replayed built-in", () => { - expect( - value(`Object.defineProperty(Object.prototype, 0, { set(v) {}, configurable: true }) - const o = Object.defineProperty({}, "a", { get value() { return 1 } }) - delete Object.prototype[0] - return o.a`), - ).toBe(1) - }) - - test("a getter-only accessor does not break defineProperty, JSON.stringify or Object.entries", () => { - expect( - value(`Object.defineProperty(Object.prototype, 0, { get() { return "p" }, configurable: true }) - const o = Object.defineProperty({}, "a", { get value() { return 1 } }) - const json = JSON.stringify({ x: [1, 2], y: { z: 3 } }) - const entries = Object.entries({ b: 2, c: 3 }) - const values = Object.values({ b: 2 }) - delete Object.prototype[0] - return [o.a, json, entries, values]`), - ).toEqual([1, '{"x":[1,2],"y":{"z":3}}', [["b", 2], ["c", 3]], [2]]) - }) - - test("a getter-only accessor does not break returning an object", () => { - expect( - value(`Object.defineProperty(Object.prototype, 0, { get() { return "p" }, configurable: true }) - return { list: [1, [2, 3]], nested: { k: "v" } }`), - ).toEqual({ list: [1, [2, 3]], nested: { k: "v" } }) - }) - - test("a String.prototype index getter past the string's end is read", () => { - expect( - value(`Object.defineProperty(String.prototype, 5, { get() { return "g" }, configurable: true }) - const r = ["a"[5], "abc"[1]] - delete String.prototype[5] - return r`), - ).toEqual(["g", "b"]) - }) - - test("bind gives length 0 when the target's length is NaN or not a number", () => { - expect( - value(`const f = Object.defineProperty(function (a, b) {}, "length", { value: NaN }) - const g = Object.defineProperty(function (a, b) {}, "length", { get() { return "2" } }) - return [f.bind(null).length, g.bind(null).length]`), - ).toEqual([0, 0]) - }) - - test("assigning a cycle through a data property is still rejected", () => { - const result = runProgram(`const o = {}; o.self = o; return 1`) - expect(result.ok).toBe(false) - if (!result.ok) expect(result.error.message).toContain("Object assignment result contains a circular value.") - }) -}) diff --git a/packages/codemode/test/array-callbacks-test262.test.ts b/packages/codemode/test/array-callbacks-test262.test.ts deleted file mode 100644 index 4dd98009516..00000000000 --- a/packages/codemode/test/array-callbacks-test262.test.ts +++ /dev/null @@ -1,394 +0,0 @@ -/* - * Portions adapted from Test262 at revision 250f204f23a9249ff204be2baec29600faae7b75: - * - test/built-ins/Array/prototype/map/15.4.4.19-8-1.js - * - test/built-ins/Array/prototype/map/15.4.4.19-8-2.js - * - test/built-ins/Array/prototype/map/15.4.4.19-8-b-1.js - * - test/built-ins/Array/prototype/filter/15.4.4.20-9-1.js - * - test/built-ins/Array/prototype/filter/15.4.4.20-9-2.js - * - test/built-ins/Array/prototype/filter/15.4.4.20-9-b-1.js - * - test/built-ins/Array/prototype/find/predicate-call-parameters.js - * - test/built-ins/Array/prototype/find/predicate-not-called-on-empty-array.js - * - test/built-ins/Array/prototype/find/return-found-value-predicate-result-is-true.js - * - test/built-ins/Array/prototype/find/return-undefined-if-predicate-returns-false-value.js - * - test/built-ins/Array/prototype/findIndex/predicate-call-parameters.js - * - test/built-ins/Array/prototype/findIndex/return-index-predicate-result-is-true.js - * - test/built-ins/Array/prototype/findIndex/return-negative-one-if-predicate-returns-false-value.js - * - test/built-ins/Array/prototype/findLast/predicate-call-parameters.js - * - test/built-ins/Array/prototype/findLast/return-found-value-predicate-result-is-true.js - * - test/built-ins/Array/prototype/findLast/return-undefined-if-predicate-returns-false-value.js - * - test/built-ins/Array/prototype/findLastIndex/predicate-call-parameters.js - * - test/built-ins/Array/prototype/findLastIndex/return-index-predicate-result-is-true.js - * - test/built-ins/Array/prototype/findLastIndex/return-negative-one-if-predicate-returns-false-value.js - * - test/built-ins/Array/prototype/some/15.4.4.17-7-1.js - * - test/built-ins/Array/prototype/some/15.4.4.17-8-1.js - * - test/built-ins/Array/prototype/every/15.4.4.16-7-1.js - * - test/built-ins/Array/prototype/every/15.4.4.16-8-1.js - * - test/built-ins/Array/prototype/forEach/15.4.4.18-7-1.js - * - test/built-ins/Array/prototype/forEach/15.4.4.18-7-2.js - * - test/built-ins/Array/prototype/reduce/15.4.4.21-9-5.js - * - test/built-ins/Array/prototype/reduce/15.4.4.21-9-c-ii-20.js - * - test/built-ins/Array/prototype/reduce/15.4.4.21-9-1.js - * - test/built-ins/Array/prototype/reduce/15.4.4.21-10-1.js - * - test/built-ins/Array/prototype/reduceRight/15.4.4.22-9-5.js - * - test/built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-ii-20.js - * - test/built-ins/Array/prototype/reduceRight/15.4.4.22-9-1.js - * - test/built-ins/Array/prototype/reduceRight/15.4.4.22-10-1.js - * - test/built-ins/Array/prototype/flatMap/depth-always-one.js - * - test/built-ins/Array/prototype/flatMap/mapperfunction-throws.js - * - test/built-ins/Array/prototype/sort/S15.4.4.11_A1.1_T1.js - * - test/built-ins/Array/prototype/sort/S15.4.4.11_A2.1_T1.js - * - test/built-ins/Array/prototype/sort/stability-5-elements.js - * - test/built-ins/Array/prototype/toSorted/comparefn-controls-sort.js - * - test/built-ins/Array/prototype/toSorted/comparefn-default.js - * - test/built-ins/Array/prototype/toSorted/immutable.js - * - test/built-ins/Array/prototype/toSorted/zero-or-one-element.js - * - * Copyright (C) 2015 the V8 project authors. All rights reserved. - * Copyright (C) 2018 Mathias Bynens. All rights reserved. - * Copyright (C) 2018 Shilpi Jain and Michael Ficarra. All rights reserved. - * Copyright (C) 2021 Igalia, S.L. All rights reserved. - * Copyright (C) 2021 Microsoft. All rights reserved. - * Copyright (C) 2025 Google. All rights reserved. - * Copyright (C) 2026 Garham Lee. All rights reserved. - * Copyright (c) 2012 Ecma International. All rights reserved. - * Copyright 2009 the Sputnik authors. All rights reserved. - * Test262 portions are governed by the BSD license in LICENSE.test262. - */ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" - -const value = async (code: string) => { - const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} })) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -const cases = [ - { - path: "test/built-ins/Array/prototype/map/15.4.4.19-8-1.js", - code: `const input = [1, 2]; input[3] = 4; input[4] = 5; const result = input.map((value) => { input[2] = 3; input[5] = 6; return 1 }); return [result.length, result[5] === undefined]`, - expected: [5, true], - }, - { - path: "test/built-ins/Array/prototype/map/15.4.4.19-8-2.js", - code: `const input = [1, 2, 3, 4, 5]; const result = input.map((value) => { input[4] = -1; return value > 0 ? 1 : 0 }); return [result.length, result[4]]`, - expected: [5, 0], - }, - { - path: "test/built-ins/Array/prototype/map/15.4.4.19-8-b-1.js", - code: `const input = []; input[10] = 0; input.pop(); input[1] = undefined; let calls = 0; const result = input.map(() => { calls += 1; return 1 }); return [result.length, calls, 0 in result, 1 in result]`, - expected: [10, 1, false, true], - }, - { - path: "test/built-ins/Array/prototype/filter/15.4.4.20-9-1.js", - code: `const input = [1, 2]; input[3] = 4; input[4] = 5; const result = input.filter(() => { input[2] = 3; input[5] = 6; return true }); return result`, - expected: [1, 2, 3, 4, 5], - }, - { - path: "test/built-ins/Array/prototype/filter/15.4.4.20-9-2.js", - code: `const input = [1, 2, 3, 4, 5]; return input.filter((value) => { input[2] = -1; input[4] = -1; return value > 0 })`, - expected: [1, 2, 4], - }, - { - path: "test/built-ins/Array/prototype/filter/15.4.4.20-9-b-1.js", - code: `const input = []; input[9] = 0; input.pop(); input[1] = undefined; let calls = 0; const result = input.filter(() => { calls += 1; return false }); return [result, calls]`, - expected: [[], 1], - }, - { - path: "test/built-ins/Array/prototype/find/predicate-call-parameters.js", - code: `const input = [10, 20]; const seen = []; input.find((value, index, receiver) => { seen.push([value, index, receiver === input]); return false }); return seen`, - expected: [ - [10, 0, true], - [20, 1, true], - ], - }, - { - path: "test/built-ins/Array/prototype/find/return-found-value-predicate-result-is-true.js", - code: `return [1, 2, 3].find((value) => value > 1)`, - expected: 2, - }, - { - path: "test/built-ins/Array/prototype/find/return-undefined-if-predicate-returns-false-value.js", - code: `return [1, 2, 3].find((value) => value > 4) === undefined`, - expected: true, - }, - { - path: "test/built-ins/Array/prototype/find/predicate-not-called-on-empty-array.js", - code: `let calls = 0; const result = [].find(() => { calls += 1; return true }); return [result === undefined, calls]`, - expected: [true, 0], - }, - { - path: "test/built-ins/Array/prototype/findIndex/predicate-call-parameters.js", - code: `const input = [10, 20]; const seen = []; input.findIndex((value, index, receiver) => { seen.push([value, index, receiver === input]); return false }); return seen`, - expected: [ - [10, 0, true], - [20, 1, true], - ], - }, - { - path: "test/built-ins/Array/prototype/findIndex/return-index-predicate-result-is-true.js", - code: `return [1, 2, 3].findIndex((value) => value > 1)`, - expected: 1, - }, - { - path: "test/built-ins/Array/prototype/findIndex/return-negative-one-if-predicate-returns-false-value.js", - code: `return [1, 2, 3].findIndex((value) => value > 4)`, - expected: -1, - }, - { - path: "test/built-ins/Array/prototype/findLast/predicate-call-parameters.js", - code: `const input = [10, 20]; const seen = []; input.findLast((value, index, receiver) => { seen.push([value, index, receiver === input]); return false }); return seen`, - expected: [ - [20, 1, true], - [10, 0, true], - ], - }, - { - path: "test/built-ins/Array/prototype/findLast/return-found-value-predicate-result-is-true.js", - code: `return [1, 2, 3].findLast((value) => value < 3)`, - expected: 2, - }, - { - path: "test/built-ins/Array/prototype/findLast/return-undefined-if-predicate-returns-false-value.js", - code: `return [1, 2, 3].findLast((value) => value > 4) === undefined`, - expected: true, - }, - { - path: "test/built-ins/Array/prototype/findLastIndex/predicate-call-parameters.js", - code: `const input = [10, 20]; const seen = []; input.findLastIndex((value, index, receiver) => { seen.push([value, index, receiver === input]); return false }); return seen`, - expected: [ - [20, 1, true], - [10, 0, true], - ], - }, - { - path: "test/built-ins/Array/prototype/findLastIndex/return-index-predicate-result-is-true.js", - code: `return [1, 2, 3].findLastIndex((value) => value < 3)`, - expected: 1, - }, - { - path: "test/built-ins/Array/prototype/findLastIndex/return-negative-one-if-predicate-returns-false-value.js", - code: `return [1, 2, 3].findLastIndex((value) => value > 4)`, - expected: -1, - }, - { - path: "test/built-ins/Array/prototype/some/15.4.4.17-7-1.js", - code: `const input = [1, 2]; input[3] = 4; input[4] = 5; const seen = []; const result = input.some((value) => { input[2] = 3; seen.push(value); return false }); return [result, seen.includes(3)]`, - expected: [false, true], - }, - { - path: "test/built-ins/Array/prototype/some/15.4.4.17-8-1.js", - code: `return [].some(() => true)`, - expected: false, - }, - { - path: "test/built-ins/Array/prototype/every/15.4.4.16-7-1.js", - code: `const input = [1, 2]; input[3] = 4; input[4] = 5; const seen = []; const result = input.every((value) => { input[2] = 3; seen.push(value); return true }); return [result, seen.includes(3)]`, - expected: [true, true], - }, - { - path: "test/built-ins/Array/prototype/every/15.4.4.16-8-1.js", - code: `return [].every(() => false)`, - expected: true, - }, - { - path: "test/built-ins/Array/prototype/forEach/15.4.4.18-7-1.js", - code: `const input = [1, 2]; input[3] = 4; input[4] = 5; let calls = 0; input.forEach(() => { calls += 1; input[2] = 3; input[5] = 6 }); return calls`, - expected: 5, - }, - { - path: "test/built-ins/Array/prototype/forEach/15.4.4.18-7-2.js", - code: `const input = [1, 2, 3]; const seen = []; input.forEach((value, index) => { seen.push(value); if (index === 0) input.pop() }); return seen`, - expected: [1, 2], - }, - { - path: "test/built-ins/Array/prototype/reduce/15.4.4.21-9-1.js", - code: `const input = [1, 2]; input[3] = 4; input[4] = "5"; return input.reduce((accumulator, value) => { input[2] = 3; input[5] = 6; return accumulator + value })`, - expected: "105", - }, - { - path: "test/built-ins/Array/prototype/reduce/15.4.4.21-9-5.js", - code: `let calls = 0; const result = [1].reduce(() => { calls += 1; return 2 }); return [result, calls]`, - expected: [1, 0], - }, - { - path: "test/built-ins/Array/prototype/reduce/15.4.4.21-9-c-ii-20.js", - code: `let accessed = false; const result = [11].reduce((previous) => { accessed = true; return previous === undefined }, undefined); return [result, accessed]`, - expected: [true, true], - }, - { - path: "test/built-ins/Array/prototype/reduce/15.4.4.21-10-1.js", - code: `const input = [1, 2, 3, 4, 5]; input.reduce(() => 1); return input`, - expected: [1, 2, 3, 4, 5], - }, - { - path: "test/built-ins/Array/prototype/reduceRight/15.4.4.22-9-1.js", - code: `const input = ["1", 2]; input[3] = 4; input[4] = "5"; return input.reduceRight((accumulator, value) => { input[2] = 3; input[5] = 6; return accumulator + value })`, - expected: "54321", - }, - { - path: "test/built-ins/Array/prototype/reduceRight/15.4.4.22-9-5.js", - code: `let calls = 0; const result = [1].reduceRight(() => { calls += 1; return 2 }); return [result, calls]`, - expected: [1, 0], - }, - { - path: "test/built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-ii-20.js", - code: `let accessed = false; const result = [11].reduceRight((previous) => { accessed = true; return previous === undefined }, undefined); return [result, accessed]`, - expected: [true, true], - }, - { - path: "test/built-ins/Array/prototype/reduceRight/15.4.4.22-10-1.js", - code: `const input = [1, 2, 3, 4, 5]; input.reduceRight(() => 1); return input`, - expected: [1, 2, 3, 4, 5], - }, - { - path: "test/built-ins/Array/prototype/flatMap/depth-always-one.js", - code: `return [1, 2, 3].flatMap((value) => [[value * 2]])`, - expected: [[2], [4], [6]], - }, - { - path: "test/built-ins/Array/prototype/flatMap/mapperfunction-throws.js", - code: `try { [1, 2].flatMap(() => { throw "stop" }) } catch (error) { return error === "stop" } return false`, - expected: true, - }, - { - path: "test/built-ins/Array/prototype/sort/S15.4.4.11_A1.1_T1.js", - code: `const input = []; input[2] = 0; input.pop(); input.sort(); return [input.length, input[0] === undefined, input[1] === undefined]`, - expected: [2, true, true], - }, - { - path: "test/built-ins/Array/prototype/sort/S15.4.4.11_A2.1_T1.js", - code: `return ["z", "y", "x", "w", "v", "u", "t", "s", "r", "q", "p", "o", "n", "M", "L", "K", "J", "I", "H", "G", "F", "E", "D", "C", "B", "A"].sort()`, - expected: [ - "A", - "B", - "C", - "D", - "E", - "F", - "G", - "H", - "I", - "J", - "K", - "L", - "M", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - ], - }, - { - path: "test/built-ins/Array/prototype/sort/stability-5-elements.js", - code: `const input = [{ n: "A", r: 2 }, { n: "B", r: 3 }, { n: "C", r: 2 }, { n: "D", r: 3 }, { n: "E", r: 3 }]; return input.sort((left, right) => right.r - left.r).map((item) => item.n).join("")`, - expected: "BDEAC", - }, - { - path: "test/built-ins/Array/prototype/toSorted/comparefn-controls-sort.js", - code: `const mixed = [333, 33, 3, 222, 22, 2, 111, 11, 1]; return [[1, 2, 3, 4].toSorted((a, b) => a - b), [4, 3, 2, 1].toSorted((a, b) => a - b), mixed.toSorted((a, b) => a - b), [1, 2, 3, 4].toSorted((a, b) => b - a), [4, 3, 2, 1].toSorted((a, b) => b - a), mixed.toSorted((a, b) => b - a)]`, - expected: [ - [1, 2, 3, 4], - [1, 2, 3, 4], - [1, 2, 3, 11, 22, 33, 111, 222, 333], - [4, 3, 2, 1], - [4, 3, 2, 1], - [333, 222, 111, 33, 22, 11, 3, 2, 1], - ], - }, - { - path: "test/built-ins/Array/prototype/toSorted/comparefn-default.js", - code: `return [[1, 2, 3, 4].toSorted(), [4, 3, 2, 1].toSorted(), ["a", 2, 1, "z"].toSorted(), [333, 33, 3, 222, 22, 2, 111, 11, 1].toSorted()]`, - expected: [ - [1, 2, 3, 4], - [1, 2, 3, 4], - [1, 2, "a", "z"], - [1, 11, 111, 2, 22, 222, 3, 33, 333], - ], - }, - { - path: "test/built-ins/Array/prototype/toSorted/immutable.js", - code: `const input = [2, 0, 1]; const result = input.toSorted(); return [input, result !== input]`, - expected: [[2, 0, 1], true], - }, - { - path: "test/built-ins/Array/prototype/toSorted/zero-or-one-element.js", - code: `const zero = []; const one = [1]; const zeroResult = zero.toSorted(); const oneResult = one.toSorted(); return [zeroResult, oneResult, zeroResult !== zero, oneResult !== one]`, - expected: [[], [1], true, true], - }, -] as const - -describe("Test262 Array callback adaptations", () => { - for (const item of cases) { - test(item.path, async () => { - expect(await value(item.code)).toEqual(item.expected) - }) - } -}) - -describe("Array callback regressions", () => { - test("flatMap skips holes in callback results while retaining explicit undefined", async () => { - expect( - await value(` - return [ - [1].flatMap(() => [, 2]), - [1, 2].flatMap(() => Array(2)), - [1].flatMap(() => [undefined, 2]), - [1].flatMap(() => [[, 2]])[0].length, - 0 in [1].flatMap(() => [[, 2]])[0] - ] - `), - ).toEqual([[2], [], [null, 2], 2, false]) - }) - - test("reduce and reduceRight find the first present element", async () => { - expect( - await value(` - const left = [] - left[2] = 3 - const right = [] - right[0] = 4 - right[3] = 1 - right.pop() - return [left.reduce((a, b) => a + b), right.reduceRight((a, b) => a + b)] - `), - ).toEqual([3, 4]) - }) - - test("reduce and reduceRight reject arrays containing only holes", async () => { - expect( - await value(` - const values = [] - values[2] = 1 - values.pop() - let left - let right - try { values.reduce((a, b) => a + b) } catch (error) { left = error.name } - try { values.reduceRight((a, b) => a + b) } catch (error) { right = error.name } - return [left, right] - `), - ).toEqual(["TypeError", "TypeError"]) - }) - - test("findLast returns the value observed before predicate mutation", async () => { - expect( - await value(` - const values = [1] - return values.findLast((item, index, array) => { - array[index] = 2 - return true - }) - `), - ).toBe(1) - }) -}) diff --git a/packages/codemode/test/array-core-test262.test.ts b/packages/codemode/test/array-core-test262.test.ts deleted file mode 100644 index b1c3d67447a..00000000000 --- a/packages/codemode/test/array-core-test262.test.ts +++ /dev/null @@ -1,352 +0,0 @@ -/* - * Portions adapted from Test262 at revision 250f204f23a9249ff204be2baec29600faae7b75: - * - test/built-ins/Array/prototype/includes/samevaluezero.js - * - test/built-ins/Array/prototype/includes/using-fromindex.js - * - test/built-ins/Array/prototype/join/S15.4.4.5_A3.1_T1.js - * - test/built-ins/Array/prototype/join/S15.4.4.5_A3.2_T1.js - * - test/built-ins/Array/prototype/slice/S15.4.4.10_A1.2_T2.js - * - test/built-ins/Array/prototype/concat/S15.4.4.4_A1_T1.js - * - test/built-ins/Array/prototype/concat/S15.4.4.4_A1_T2.js - * - test/built-ins/Array/prototype/concat/S15.4.4.4_A1_T3.js - * - test/built-ins/Array/prototype/indexOf/fromindex-zero-conversion.js - * - test/built-ins/Array/prototype/indexOf/length-zero-returns-minus-one.js - * - test/built-ins/Array/prototype/lastIndexOf/fromindex-zero-conversion.js - * - test/built-ins/Array/prototype/lastIndexOf/length-zero-returns-minus-one.js - * - test/built-ins/Array/prototype/at/returns-item.js - * - test/built-ins/Array/prototype/at/returns-item-relative-index.js - * - test/built-ins/Array/prototype/at/returns-undefined-for-out-of-range-index.js - * - test/built-ins/Array/prototype/flat/null-undefined-elements.js - * - test/built-ins/Array/prototype/flat/positive-infinity.js - * - test/built-ins/Array/prototype/reverse/S15.4.4.8_A1_T1.js - * - test/built-ins/Array/prototype/toReversed/immutable.js - * - test/built-ins/Array/prototype/toReversed/zero-or-one-element.js - * - test/built-ins/Array/prototype/with/immutable.js - * - test/built-ins/Array/prototype/with/index-negative.js - * - test/built-ins/Array/prototype/push/S15.4.4.7_A1_T1.js - * - test/built-ins/Array/prototype/pop/S15.4.4.6_A1.1_T1.js - * - test/built-ins/Array/prototype/shift/S15.4.4.9_A1.1_T1.js - * - test/built-ins/Array/prototype/unshift/S15.4.4.13_A1_T1.js - * - test/built-ins/Array/prototype/splice/S15.4.4.12_A1.1_T1.js - * - test/built-ins/Array/prototype/splice/S15.4.4.12_A1.2_T1.js - * - test/built-ins/Array/prototype/splice/called_with_one_argument.js - * - test/built-ins/Array/prototype/toSpliced/holes-not-preserved.js - * - test/built-ins/Array/prototype/toSpliced/immutable.js - * - test/built-ins/Array/prototype/toSpliced/start-and-deleteCount-undefineds.js - * - test/built-ins/Array/prototype/toSpliced/start-and-deleteCount-missing.js - * - test/built-ins/Array/prototype/toSpliced/start-undefined-and-deleteCount-missing.js - * - test/built-ins/Array/prototype/fill/fill-values.js - * - test/built-ins/Array/prototype/fill/fill-values-custom-start-and-end.js - * - test/built-ins/Array/prototype/fill/return-this.js - * - test/built-ins/Array/prototype/copyWithin/non-negative-target-start-and-end.js - * - test/built-ins/Array/prototype/copyWithin/return-this.js - * - test/built-ins/Array/prototype/keys/iteration.js - * - test/built-ins/Array/prototype/values/iteration.js - * - test/built-ins/Array/prototype/entries/iteration.js - * - test/built-ins/Array/isArray/15.4.3.2-0-3.js - * - test/built-ins/Array/isArray/15.4.3.2-0-4.js - * - test/built-ins/Array/from/from-array.js - * - test/built-ins/Array/from/from-string.js - * - test/built-ins/Array/from/array-like-has-length-but-no-indexes-with-values.js - * - test/built-ins/Array/of/creates-a-new-array-from-arguments.js - * - * Copyright (C) 2015 André Bargull. All rights reserved. - * Copyright (C) 2015 the V8 project authors. All rights reserved. - * Copyright (C) 2016 the V8 project authors. All rights reserved. - * Copyright (C) 2018 Shilpi Jain and Michael Ficarra. All rights reserved. - * Copyright (C) 2020 Alexey Shvayka. All rights reserved. - * Copyright (C) 2020 Rick Waldron. All rights reserved. - * Copyright (C) 2021 Igalia, S.L. All rights reserved. - * Copyright (c) 2012 Ecma International. All rights reserved. - * Copyright (c) 2014 Hank Yates. All rights reserved. - * Copyright (c) 2015 the V8 project authors. All rights reserved. - * Copyright (c) 2021 Rick Waldron. All rights reserved. - * Copyright 2009 the Sputnik authors. All rights reserved. - * Copyright 2015 Microsoft Corporation. All rights reserved. - * Copyright 2016 The V8 project authors. All rights reserved. - * Test262 portions are governed by the BSD license in LICENSE.test262. - * The toSpliced hole case omits the source test's inherited Array.prototype element because CodeMode does not expose - * prototype mutation; it retains the source test's hole-densification assertions. - */ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" - -const value = async (code: string) => { - const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} })) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -const cases = [ - { - path: "test/built-ins/Array/prototype/includes/samevaluezero.js", - code: `const input = [42, 0, 1, NaN]; return [input.includes(42), input.includes("42"), input.includes([42]), input.includes(true), input.includes(NaN), input.includes(0), input.includes(-0), input.includes(null), input.includes("")]`, - expected: [true, false, false, false, true, true, true, false, false], - }, - { - path: "test/built-ins/Array/prototype/includes/using-fromindex.js", - code: `const input = ["a", "b", "c"]; return [input.includes("a", 0), input.includes("a", 1), input.includes("a", -4), input.includes("a", -3), input.includes("a", -2), input.includes("b", 0), input.includes("b", 1), input.includes("b", 2), input.includes("b", -3), input.includes("b", -2), input.includes("b", -1), input.includes("c", 0), input.includes("c", 2), input.includes("c", 3), input.includes("c", -3), input.includes("c", -1)]`, - expected: [true, false, true, true, false, true, true, false, true, true, false, true, true, false, true, true], - }, - { - path: "test/built-ins/Array/prototype/join/S15.4.4.5_A3.1_T1.js", - code: `return [[0, 1, 2, 3].join("&"), [0, 1, 2, 3].join("")]`, - expected: ["0&1&2&3", "0123"], - }, - { - path: "test/built-ins/Array/prototype/join/S15.4.4.5_A3.2_T1.js", - code: `return [ - ["", "", ""].join(""), - ["&", "&", "&"].join("&"), - [true, true, true].join(), - [null, null, null].join(), - [undefined, undefined, undefined].join(), - [Infinity, Infinity, Infinity].join(), - [NaN, NaN, NaN].join(), - ]`, - expected: ["", "&&&&&", "true,true,true", ",,", ",,", "Infinity,Infinity,Infinity", "NaN,NaN,NaN"], - }, - { - path: "test/built-ins/Array/prototype/slice/S15.4.4.10_A1.2_T2.js", - code: `return [0, 1, 2, 3, 4].slice(-1, 5)`, - expected: [4], - }, - { - path: "test/built-ins/Array/prototype/concat/S15.4.4.4_A1_T1.js", - code: `return [].concat([0, 1], [2, 3, 4])`, - expected: [0, 1, 2, 3, 4], - }, - { - path: "test/built-ins/Array/prototype/concat/S15.4.4.4_A1_T2.js", - code: `const object = { value: 1 }; const result = [0].concat(object, [1, 2], -1, true, "NaN"); return [result, result[1] === object]`, - expected: [[0, { value: 1 }, 1, 2, -1, true, "NaN"], true], - }, - { - path: "test/built-ins/Array/prototype/concat/S15.4.4.4_A1_T3.js", - code: `const input = [0, 1]; const result = input.concat(); return [result, result !== input]`, - expected: [[0, 1], true], - }, - { - path: "test/built-ins/Array/prototype/indexOf/fromindex-zero-conversion.js", - code: `const result = [true].indexOf(true, -0); return [result, 1 / result === Infinity]`, - expected: [0, true], - }, - { - path: "test/built-ins/Array/prototype/indexOf/length-zero-returns-minus-one.js", - code: `return [].indexOf(1)`, - expected: -1, - }, - { - path: "test/built-ins/Array/prototype/lastIndexOf/fromindex-zero-conversion.js", - code: `const result = [true].lastIndexOf(true, -0); return [result, 1 / result === Infinity]`, - expected: [0, true], - }, - { - path: "test/built-ins/Array/prototype/lastIndexOf/length-zero-returns-minus-one.js", - code: `return [].lastIndexOf(1)`, - expected: -1, - }, - { - path: "test/built-ins/Array/prototype/at/returns-item.js", - code: `const input = [1, 2, 3, 4, undefined, 5]; return [input.at(0), input.at(1), input.at(2), input.at(3), input.at(4) === undefined, input.at(5)]`, - expected: [1, 2, 3, 4, true, 5], - }, - { - path: "test/built-ins/Array/prototype/at/returns-item-relative-index.js", - code: `const input = [1, 2, 3, 4, undefined, 5]; return [input.at(0), input.at(-1), input.at(-2) === undefined, input.at(-3), input.at(-4)]`, - expected: [1, 5, true, 4, 3], - }, - { - path: "test/built-ins/Array/prototype/at/returns-undefined-for-out-of-range-index.js", - code: `const input = []; return [input.at(-2) === undefined, input.at(0) === undefined, input.at(1) === undefined]`, - expected: [true, true, true], - }, - { - path: "test/built-ins/Array/prototype/flat/null-undefined-elements.js", - code: `const result = [1, [null, [undefined]]].flat(2); return [result.length, result[0], result[1] === null, result[2] === undefined]`, - expected: [3, 1, true, true], - }, - { - path: "test/built-ins/Array/prototype/flat/positive-infinity.js", - code: `return [1, [2, [3, [4]]]].flat(Infinity)`, - expected: [1, 2, 3, 4], - }, - { - path: "test/built-ins/Array/prototype/reverse/S15.4.4.8_A1_T1.js", - code: `const empty = []; const one = [1]; const input = [1, 2]; const emptyResult = empty.reverse(); const oneResult = one.reverse(); const result = input.reverse(); return [emptyResult === empty, oneResult === one, result === input, input]`, - expected: [true, true, true, [2, 1]], - }, - { - path: "test/built-ins/Array/prototype/toReversed/immutable.js", - code: `const input = [0, 1, 2]; const result = input.toReversed(); return [input, result !== input]`, - expected: [[0, 1, 2], true], - }, - { - path: "test/built-ins/Array/prototype/toReversed/zero-or-one-element.js", - code: `const zero = []; const one = [1]; const zeroResult = zero.toReversed(); const oneResult = one.toReversed(); return [zeroResult, oneResult, zeroResult !== zero, oneResult !== one]`, - expected: [[], [1], true, true], - }, - { - path: "test/built-ins/Array/prototype/with/immutable.js", - code: `const input = [0, 1, 2]; const result = input.with(1, 3); return [input, result !== input, input.with(1, 1) !== input]`, - expected: [[0, 1, 2], true, true], - }, - { - path: "test/built-ins/Array/prototype/with/index-negative.js", - code: `const input = [0, 1, 2]; return [input.with(-1, 4), input.with(-3, 4)]`, - expected: [ - [0, 1, 4], - [4, 1, 2], - ], - }, - { - path: "test/built-ins/Array/prototype/push/S15.4.4.7_A1_T1.js", - code: `const input = []; return [input.push(1), input.push(), input.push(-1), input]`, - expected: [1, 1, 2, [1, -1]], - }, - { - path: "test/built-ins/Array/prototype/pop/S15.4.4.6_A1.1_T1.js", - code: `const input = []; return [input.pop() === undefined, input.length]`, - expected: [true, 0], - }, - { - path: "test/built-ins/Array/prototype/shift/S15.4.4.9_A1.1_T1.js", - code: `const input = []; return [input.shift() === undefined, input.length]`, - expected: [true, 0], - }, - { - path: "test/built-ins/Array/prototype/unshift/S15.4.4.13_A1_T1.js", - code: `const input = []; return [input.unshift(1), input[0], input.unshift(), input.unshift(-1), input]`, - expected: [1, 1, 1, 2, [-1, 1]], - }, - { - path: "test/built-ins/Array/prototype/splice/S15.4.4.12_A1.1_T1.js", - code: `const input = [0, 1, 2, 3]; const removed = input.splice(0, 3); return [input, removed]`, - expected: [[3], [0, 1, 2]], - }, - { - path: "test/built-ins/Array/prototype/splice/S15.4.4.12_A1.2_T1.js", - code: `const input = [0, 1]; const removed = input.splice(-2, -1); return [input, removed]`, - expected: [[0, 1], []], - }, - { - path: "test/built-ins/Array/prototype/splice/called_with_one_argument.js", - code: `const input = ["first", "second", "third"]; const removed = input.splice(1); return [input, removed]`, - expected: [["first"], ["second", "third"]], - }, - { - path: "test/built-ins/Array/prototype/toSpliced/immutable.js", - code: `const input = [2, 0, 1]; const inserted = input.toSpliced(0, 0, -1); const replaced = input.toSpliced(0, 1, -1); return [input, inserted, replaced, inserted !== input, replaced !== input]`, - expected: [[2, 0, 1], [-1, 2, 0, 1], [-1, 0, 1], true, true], - }, - { - path: "test/built-ins/Array/prototype/toSpliced/start-and-deleteCount-missing.js", - code: `const input = ["first", "second", "third"]; const result = input.toSpliced(); return [result, result !== input]`, - expected: [["first", "second", "third"], true], - }, - { - path: "test/built-ins/Array/prototype/toSpliced/start-undefined-and-deleteCount-missing.js", - code: `return ["first", "second", "third"].toSpliced(undefined)`, - expected: [], - }, - { - path: "test/built-ins/Array/prototype/toSpliced/start-and-deleteCount-undefineds.js", - code: `const input = ["first", "second", "third"]; const result = input.toSpliced(undefined, undefined); return [result, result !== input]`, - expected: [["first", "second", "third"], true], - }, - { - path: "test/built-ins/Array/prototype/toSpliced/holes-not-preserved.js", - code: `const input = [0, , 2, , 4]; const result = input.toSpliced(0, 0, -1); return [result, 2 in result, 4 in result]`, - expected: [[-1, 0, null, 2, null, 4], true, true], - }, - { - path: "test/built-ins/Array/prototype/fill/fill-values-custom-start-and-end.js", - code: `const input = [0, 0, 0, 0, 0]; input.fill(8, -3, 4); const sparse = []; sparse[4] = 0; sparse.fill(8, 1, 3); return [[0, 0, 0].fill(8, 1, 2), input, [0, 0, 0, 0, 0].fill(8, -2, -1), [0, 0, 0, 0, 0].fill(8, -1, -3), [0 in sparse, sparse[1], sparse[2], 3 in sparse, sparse[4]]]`, - expected: [ - [0, 8, 0], - [0, 0, 8, 8, 0], - [0, 0, 0, 8, 0], - [0, 0, 0, 0, 0], - [false, 8, 8, false, 0], - ], - }, - { - path: "test/built-ins/Array/prototype/fill/return-this.js", - code: `const input = []; return input.fill(1) === input`, - expected: true, - }, - { - path: "test/built-ins/Array/prototype/fill/fill-values.js", - code: `const omitted = [0, 0].fill(); return [[].fill(8), omitted.map((value) => value === undefined), [0, 0, 0].fill(8)]`, - expected: [[], [true, true], [8, 8, 8]], - }, - { - path: "test/built-ins/Array/prototype/copyWithin/non-negative-target-start-and-end.js", - code: `return [[0, 1, 2, 3].copyWithin(0, 0, 0), [0, 1, 2, 3].copyWithin(0, 0, 2), [0, 1, 2, 3].copyWithin(0, 1, 2), [0, 1, 2, 3].copyWithin(1, 0, 2), [0, 1, 2, 3, 4, 5].copyWithin(1, 3, 5)]`, - expected: [ - [0, 1, 2, 3], - [0, 1, 2, 3], - [1, 1, 2, 3], - [0, 0, 1, 3], - [0, 3, 4, 3, 4, 5], - ], - }, - { - path: "test/built-ins/Array/prototype/copyWithin/return-this.js", - code: `const input = [0, 1, 2, 3]; const result = input.copyWithin(1, 0, 2); return [input, result === input]`, - expected: [[0, 0, 1, 3], true], - }, - { - path: "test/built-ins/Array/prototype/keys/iteration.js", - code: `const it = ["a", "b", "c"].keys(); return [it.next(), it.next(), it.next(), it.next()]`, - expected: [{ value: 0, done: false }, { value: 1, done: false }, { value: 2, done: false }, { done: true }], - }, - { - path: "test/built-ins/Array/prototype/values/iteration.js", - code: `const it = ["a", "b", "c"].values(); return [it.next(), it.next(), it.next(), it.next()]`, - expected: [{ value: "a", done: false }, { value: "b", done: false }, { value: "c", done: false }, { done: true }], - }, - { - path: "test/built-ins/Array/prototype/entries/iteration.js", - code: `const it = ["a", "b"].entries(); return [it.next(), it.next(), it.next()]`, - expected: [{ value: [0, "a"], done: false }, { value: [1, "b"], done: false }, { done: true }], - }, - { - path: "test/built-ins/Array/isArray/15.4.3.2-0-3.js", - code: `return [Array.isArray([]), Array.isArray([1]), Array.isArray(Array.of(1))]`, - expected: [true, true, true], - }, - { - path: "test/built-ins/Array/isArray/15.4.3.2-0-4.js", - code: `return [Array.isArray(42), Array.isArray({}), Array.isArray(null), Array.isArray("array")]`, - expected: [false, false, false, false], - }, - { - path: "test/built-ins/Array/from/from-array.js", - code: `const input = [0, "foo", undefined, Infinity]; const result = Array.from(input); return [result.length, result[0], result[1], result[2] === undefined, result[3] === Infinity, result !== input, result instanceof Array]`, - expected: [4, 0, "foo", true, true, true, true], - }, - { - path: "test/built-ins/Array/from/from-string.js", - code: `return Array.from("Test")`, - expected: ["T", "e", "s", "t"], - }, - { - path: "test/built-ins/Array/from/array-like-has-length-but-no-indexes-with-values.js", - code: `const result = Array.from({ length: 5 }); const mapped = result.map(() => 1); return [result.length, result.map((value) => value === undefined), mapped.length, mapped]`, - expected: [5, [true, true, true, true, true], 5, [1, 1, 1, 1, 1]], - }, - { - path: "test/built-ins/Array/of/creates-a-new-array-from-arguments.js", - code: `const mixed = Array.of(undefined, false, null, undefined); return [Array.of("Mike", "Rick", "Leo"), mixed.length, mixed[0] === undefined, mixed[1], mixed[2], mixed[3] === undefined, Array.of()]`, - expected: [["Mike", "Rick", "Leo"], 4, true, false, null, true, []], - }, -] as const - -describe("Test262 Array core adaptations", () => { - for (const item of cases) { - test(item.path, async () => { - expect(await value(item.code)).toEqual(item.expected) - }) - } -}) diff --git a/packages/codemode/test/buffer.test.ts b/packages/codemode/test/buffer.test.ts deleted file mode 100644 index 49213e33fba..00000000000 --- a/packages/codemode/test/buffer.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode, Extension } from "../src/index.js" - -const value = async (code: string, extensions: ReadonlyArray = []) => { - const result = await Effect.runPromise(CodeMode.make({ extensions }).execute(code)) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -describe("Buffer", () => { - test("converts text in each encoding, defaulting to UTF-8", async () => { - expect( - await value(`const b = Buffer.from("héllo") - return [b.length, b.toString(), String(b), \`\${b}\`, b.toString("hex"), b.toString("base64"), - Buffer.from("aGk=", "base64").toString(), Buffer.from("6869", "hex").toString(), Buffer.byteLength("é")]`), - ).toEqual([6, "héllo", "héllo", "héllo", "68c3a96c6c6f", "aMOpbGxv", "hi", "hi", 2]) - }) - - test("is a Uint8Array, and Buffer.isBuffer tells the two apart", async () => { - expect( - await value(`const b = Buffer.from([1, 2, 3]) - return [b instanceof Uint8Array, Buffer.isBuffer(b), Buffer.isBuffer(new Uint8Array(1)), [...b], b[1], - Object.prototype.toString.call(b)]`), - ).toEqual([true, true, false, [1, 2, 3], 2, "[object Uint8Array]"]) - }) - - test("concatenates, slices over the same memory, compares and searches like Node", async () => { - expect( - await value(`const b = Buffer.concat([Buffer.from("ab"), Buffer.from("cd")]) - const view = b.subarray(1, 3) - view[0] = 120 - return [b.toString(), view.toString(), b.equals(Buffer.from("axcd")), Buffer.compare(Buffer.from("a"), Buffer.from("b")), - b.includes("cd"), b.indexOf("c"), Buffer.alloc(3, 1).toString("hex"), Buffer.alloc(4, "ab").toString()]`), - ).toEqual(["axcd", "xc", true, -1, true, 2, "010101", "abab"]) - }) - - test("makes a Buffer from a Buffer through the inherited Uint8Array methods, like Bun", async () => { - expect( - await value(`const b = Buffer.from("abc") - const made = [b.map((x) => x + 1), b.filter((x) => x > 97), Uint8Array.prototype.slice.call(b, 1), - Uint8Array.prototype.subarray.call(b, 2)] - return [...made.map((x) => [Buffer.isBuffer(x), x.toString()]), Buffer.isBuffer(new Uint8Array(1).map((x) => x)), - String(new Uint8Array([1, 2]).slice(1))]`), - ).toEqual([[true, "bcd"], [true, "bc"], [true, "bc"], [true, "c"], false, "2"]) - }) - - test("reads and writes numbers", async () => { - expect( - await value(`const b = Buffer.alloc(4) - b.writeUInt16BE(0x1234, 0) - b.writeInt8(-1, 2) - return [b.readUInt16BE(0), b.readUInt16LE(0), b.readInt8(2), b.toString("hex")]`), - ).toEqual([0x1234, 0x3412, -1, "1234ff00"]) - }) - - test("serializes like Node and rejects unknown encodings with Node's code", async () => { - expect( - await value(`let code - try { Buffer.from("x", "nope") } catch (e) { code = [e.name, e.code] } - return [JSON.stringify(Buffer.from("hi")), code]`), - ).toEqual(['{"type":"Buffer","data":[104,105]}', ["TypeError", "ERR_UNKNOWN_ENCODING"]]) - }) - - test("crosses extensions as a Buffer in both directions", async () => { - const seen: Array = [] - const bytes = Extension.make({ - name: "bytes", - globals: { - read: () => Buffer.from("from host"), - write: (value: unknown) => void seen.push(Buffer.isBuffer(value)), - }, - }) - expect( - await value(`const b = read() - write(Buffer.from("x")) - return [Buffer.isBuffer(b), b.toString()]`, [bytes]), - ).toEqual([true, "from host"]) - expect(seen).toEqual([true]) - }) - - test("is importable from the buffer module", async () => { - expect(await value(`const { Buffer: B } = await import("node:buffer"); return B.from("ok").toString()`)).toBe("ok") - }) -}) diff --git a/packages/codemode/test/build-id.test.ts b/packages/codemode/test/build-id.test.ts deleted file mode 100644 index 27c84b726e7..00000000000 --- a/packages/codemode/test/build-id.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { describe, expect, test } from "bun:test" -import path from "node:path" - -// The snapshot build id hashes only the package's own bytecode, codecs, and built-ins, so it is the same in every -// process, whatever it imported first. - -const root = path.join(import.meta.dir, "..") - -const output = async (command: Array) => { - const child = Bun.spawn(command, { cwd: root, stdout: "pipe", stderr: "pipe" }) - const [stdout, stderr] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text()]) - expect({ code: await child.exited, stderr }).toMatchObject({ code: 0 }) - return stdout -} - -describe("build id", () => { - test("the build id is the same whatever a process imported first", async () => { - const fixture = path.join(import.meta.dir, "fixtures/build-id.ts") - const ids = await Promise.all( - [[], ["--preload", "./test/test262/run.ts"], ["--preload", "./src/index.ts"]].map((preload) => - output(["bun", ...preload, fixture]), - ), - ) - expect(ids[0]).toMatch(/\+[0-9a-f]+\n$/) - expect(ids[1]).toBe(ids[0]!) - expect(ids[2]).toBe(ids[0]!) - }) - - // A process with the test262 harness loaded saves the run; the child that resumes it has not loaded it. - test("a run saved with the test262 harness loaded resumes in another process", async () => { - await output(["bun", "test", "--preload", "./test/test262/run.ts", "test/suspend.test.ts", "-t", "another process"]) - }, 15_000) -}) diff --git a/packages/codemode/test/bytecode-limits.test.ts b/packages/codemode/test/bytecode-limits.test.ts deleted file mode 100644 index 4fe329f488d..00000000000 --- a/packages/codemode/test/bytecode-limits.test.ts +++ /dev/null @@ -1,601 +0,0 @@ -import { describe, expect, test } from "bun:test" -import { createBuiltins } from "../src/language/runtime/intrinsics.js" -import { Interpreter } from "../src/language/runtime/interpreter.js" -import { CodeBuilder, CodeSizeOverflow, hashOf } from "../src/language/code.js" -import { compileSource } from "../src/language/compiler/compile.js" -import { CodeFlags, EMPTY_CELLS, Op, packWord, PutKind } from "../src/language/opcodes.js" -import { Mode } from "../src/language/vm.js" -import { parseVmSource, type RunOptions, runProgram } from "./run-program.js" -import { verifyAll, verifyCode } from "./verify-bytecode.js" - - -const compileVerified = (code: string) => { - const parsed = parseVmSource(code) - expect(parsed.ok).toBe(true) - if (!parsed.ok) throw new Error(parsed.error.message) - const codes = compileSource(parsed.source, { noCache: true }) - expect(verifyAll(codes)).toEqual([]) - return { source: parsed.source, codes } -} - -const runVerified = (code: string, options?: RunOptions) => { - const compiled = compileVerified(code) - const res = runProgram(code, options) - if (!res.ok) throw new Error(`${res.error.kind}: ${res.error.message}`) - return { value: res.value, codes: compiled.codes } -} - -// Emits ~27 words per line in wide mode (~25 in narrow mode) with shallow AST depth, reaching >65,535 words in ~2,800 lines. -const makePaddingBlock = (count: number, accVar = "padAcc", condVar = "padCond"): string => { - const lines = Array.from( - { length: count }, - (_, i) => - `if (${condVar}) { ${accVar} += ${(i % 7) + 1} + 1 + 1 + 1 + 1 + 1 + 1 + 1 } else { ${accVar} -= 1 }`, - ) - return lines.join("\n") -} - -describe("CodeBuilder and packWord encoding bounds", () => { - test("packWord and CodeBuilder reject out-of-range operands instead of masking", () => { - expect(() => packWord(Op.NOP, -1, 0)).toThrow(RangeError) - expect(() => packWord(Op.NOP, 256, 0)).toThrow(RangeError) - expect(() => packWord(Op.NOP, 0, -1)).toThrow(RangeError) - expect(() => packWord(Op.NOP, 0, 65536)).toThrow(RangeError) - expect(() => packWord(256 as never, 0, 0)).toThrow(RangeError) - - const builder = new CodeBuilder( - { id: "test", hash: "" }, - undefined, - 0, - "test", - CodeFlags.PROGRAM, - 0, - 0, - 2, - ["a", "b"], - new Int32Array(0), - ) - expect(() => builder.emit(Op.EXTRA, 0, 0)).toThrow(RangeError) - expect(() => builder.emit(Op.GET_LOCAL, -1, 0)).toThrow(RangeError) - expect(() => builder.emit(Op.GET_LOCAL, 0, -1)).toThrow(RangeError) - expect(() => builder.emit(Op.GET_LOCAL, 0x80000000, 0)).toThrow(RangeError) - expect(() => builder.emit(Op.GET_LOCAL, 0, 0x80000000)).toThrow(RangeError) - expect(() => builder.emit(Op.NEW, 256, 0)).toThrow(RangeError) - expect(() => builder.emit(Op.PUSH_INT, 1, 0)).toThrow(RangeError) - expect(() => builder.emit(Op.PUSH_INT, 0, 0x10000)).toThrow(RangeError) - }) - - test("narrow CodeBuilder throws CodeSizeOverflow past 65,535 words, while wideJumps supports 31-bit jumps and double EXTRA", () => { - const narrow = new CodeBuilder( - { id: "test", hash: "" }, - undefined, - 0, - "narrow", - CodeFlags.PROGRAM, - 0, - 0, - 0, - [], - new Int32Array(0), - ) - for (let i = 0; i < 0xffff; i++) narrow.emit(Op.NOP) - expect(() => narrow.emit(Op.NOP)).toThrow(CodeSizeOverflow) - - const localCount = 70_000 - const wide = new CodeBuilder( - { id: "test", hash: "" }, - undefined, - 0, - "wide", - CodeFlags.PROGRAM, - 0, - 0, - localCount, - Array.from({ length: localCount }, (_, i) => `v${i}`), - new Int32Array(0), - ) - wide.wideJumps = true - const slow = wide.newLabel(2) - const join = wide.newLabel(1) - const stepSlow = wide.newLabel(2) - const got = wide.newLabel(1) - const done = wide.newLabel(0) - // Build `[42]` on stack, ITER_OPEN into slot 69,999, ITER_STEP (with a = 69,999 > 0xffff -> double EXTRA) - // jumping past 66,000 NOPs on done, and return the stepped item. - wide.emitNumber(42) - wide.emit(Op.NEW_ARRAY, 0, 1, -1, 0) - wide.emitJump(Op.ITER_OPEN, 0, slow, -1, 0, 1) - wide.emitJump(Op.JUMP, 0, slow, -1, 0, null) - wide.mark(join) - wide.emit(Op.PUT_LOCAL, PutKind.INIT, 69_999, -1, -1) - wide.emitJump(Op.ITER_STEP, 69_999, done, -1, 0, 2) - wide.emitJump(Op.JUMP, 0, stepSlow, -1, 0, null) - wide.mark(got) - wide.emit(Op.PUT_LOCAL, PutKind.INIT, 69_998, -1, -1) - for (let i = 0; i < 66_000; i++) wide.emit(Op.NOP) - // Second ITER_STEP hits done -> jumps past slow handlers to `done` (target > 66,000) - wide.emitJump(Op.ITER_STEP, 69_999, done, -1, 0, 2) - wide.emitJump(Op.JUMP, 0, stepSlow, -1, 0, null) - wide.setDepth(1) - wide.emit(Op.POP, 0, 0, -1, -1) - wide.emitJump(Op.JUMP, 0, done, -1, 0, null) - wide.mark(slow) - wide.emit(Op.CALL, 0, 0, -1, -1) - wide.emit(Op.ITER_INIT, 0, 0, -1, 0) - wide.emitJump(Op.JUMP, 0, join, -1, 0, null) - wide.mark(stepSlow) - wide.emit(Op.CALL, 0, 0, -1, -1) - wide.emitJump(Op.ITER_RESULT, 69_999, done, -1, -1, 0) - wide.emitJump(Op.JUMP, 0, got, -1, 0, null) - wide.mark(done) - wide.emit(Op.GET_LOCAL, 0, 69_998, -1, 1) - wide.emit(Op.END_PROGRAM, 0, 0, -1, -1) - const finished = wide.finish() - expect(finished.code.length).toBeGreaterThan(66_000) - expect(verifyCode(finished)).toEqual([]) - - const ctx = new Interpreter({ builtins: createBuiltins(), logs: [] }) - const vm = ctx.vm - vm.sourceCodes.set("test", [finished]) - const root = vm.acquire(finished) - root.fn = null - root.cells = EMPTY_CELLS - root.pc = 0 - root.sp = finished.locals - root.mode = Mode.PROGRAM - root.counted = true - vm.depth = 1 - vm.frames.push(root) - const stop = vm.run() - expect(stop).toEqual({ kind: "done", completion: { ok: true, value: 42 } }) - }) -}) - -describe("wide `a` operands and `execWide` coverage", () => { - test("executes a multi-feature program compiled entirely with forceExtra (every opcode widened)", () => { - const src = ` - function helper(a, b = 3, ...rest) { - let local = a + b + rest.length + arguments.length - const box = { v: local, [ "k" + 1 ]: 10 } - box.v++ - ++box.k1 - const { k1, ...rem } = { ...box, extra: 7 } - return rem.v + k1 + (typeof unknownGlobal === "undefined" ? 1 : 0) + (-2 >>> 0 > 0 ? 1 : 0) - } - function* gen(xs) { - yield* xs - const r = yield 99 - return r - } - async function run() { - const arr = [1, , ...[2, 3]] - let sum = 0 - for (const x of arr) sum += x ?? 0 - const custom = { - closed: 0, - [Symbol.iterator]() { - let i = 0 - return { - next: () => (i++ < 3 ? { value: i * 10, done: false } : { value: undefined, done: true }), - return: () => { custom.closed++; return {} }, - } - }, - } - for (const v of custom) { - sum += v - if (v === 20) break - } - const g = gen([4, 5]) - sum += g.next().value + g.next().value + g.next().value + g.next(6).value - const d = new Date(0) - return [sum, custom.closed, helper(2, undefined, 8, 9), d instanceof Date, \`\${sum}-\${custom.closed}\`] - } - return await run() - ` - const parsed = parseVmSource(src) - expect(parsed.ok).toBe(true) - if (!parsed.ok) return - const baseline = runProgram(src) - expect(baseline).toEqual({ ok: true, value: [150, 1, 25, true, "150-1"], toolCalls: [] }) - const wideCodes = compileSource(parsed.source, { forceExtra: true, noCache: true }) - expect(verifyAll(wideCodes)).toEqual([]) - - const ctx = new Interpreter({ - builtins: createBuiltins(), - logs: [], - }) - const vm = ctx.vm - ctx.sources.set(parsed.source.id, parsed.source) - vm.sourceCodes.set(parsed.source.id, wideCodes) - const root = vm.acquire(wideCodes[0]!) - root.fn = null - root.cells = EMPTY_CELLS - root.pc = 0 - root.sp = wideCodes[0]!.locals - root.mode = Mode.PROGRAM - root.counted = true - vm.depth = 1 - vm.frames.push(root) - while (true) { - const stop = vm.run() - if (stop.kind === "slice") continue - expect(stop.kind).toBe("done") - if (stop.kind === "done") { - expect(stop.completion).toEqual({ - ok: true, - value: [150, 1, 25, true, "150-1"], - }) - } - break - } - }) - - test("280+ locals with hoisted functions, for...of (array, custom, generator), spread, yield*, and destructuring", () => { - const localDecls = Array.from({ length: 280 }, (_, i) => - i % 25 === 0 ? `let v${i} = ${i}; const c${i} = () => v${i}` : `let v${i} = ${i}`, - ).join("\n") - const localReads = Array.from({ length: 280 }, (_, i) => (i % 25 === 0 ? `c${i}()` : `v${i}`)).join(" + ") - - const src = ` - function hoisted0(x) { return x + 100 } - function hoisted1(x) { return x * 2 } - function* hoistedGen(base) { - yield base + 1 - yield base + 2 - yield base + 3 - } - - async function exercise() { - function innerHoisted(z) { return hoisted0(z) + hoisted1(z) } - ${localDecls} - - let acc = ${localReads} - - // Array for...of (Position fast path with itSlot > 280) - for (const item of [10, 20, 30]) { - acc += innerHoisted(item) - } - - // Sync generator for...of (answerCaller with wide itSlot > 280, plus early break) - for (const item of hoistedGen(5)) { - acc += item - } - for (const item of hoistedGen(50)) { - acc += item - if (item === 52) break - } - - // Custom iterator with ITER_RESULT and ITER_CLOSE (break + throw) at itSlot > 280 - let closedCount = 0 - const makeCustom = (vals) => ({ - [Symbol.iterator]() { - let idx = 0 - return { - next() { - return idx < vals.length ? { value: vals[idx++], done: false } : { value: undefined, done: true } - }, - return() { - closedCount++ - return { done: true } - }, - } - }, - }) - for (const item of makeCustom([7, 8, 9])) { - acc += item - if (item === 8) break - } - try { - for (const item of makeCustom([11, 12])) { - if (item === 11) throw new Error("boom") - } - } catch (e) { - acc += e.message.length - } - - // Spread and array destructuring with itSlot > 280 - const spreadArr = [...[1, 2], ...hoistedGen(10), ...makeCustom([30, 40])] - const [d0, , d2, ...dRest] = hoistedGen(100) - acc += spreadArr.reduce((a, b) => a + b, 0) + d0 + d2 + dRest.length - - // Sync and async yield* with itSlot/kindSlot > 280 (including .return() and .throw()) - function* wideDelegate() { - ${Array.from({ length: 265 }, (_, i) => `const dLoc${i} = ${i}`).join("; ")} - const res = yield* { - [Symbol.iterator]() { - let step = 0 - return { - next(v) { - step++ - return step === 1 ? { value: dLoc264 + 1, done: false } : { value: (v ?? 0) + 5, done: true } - }, - return(v) { - return { value: v * 10, done: true } - }, - } - }, - } - return res + dLoc0 - } - const dg1 = wideDelegate() - const y1 = dg1.next().value - const y2 = dg1.next(4).value - const dg2 = wideDelegate() - dg2.next() - const yRet = dg2.return(7).value - - async function* wideAsyncGen() { - ${Array.from({ length: 265 }, (_, i) => `const aLoc${i} = ${i}`).join("; ")} - yield await Promise.resolve(aLoc260 + 2) - yield* hoistedGen(200) - } - let asyncSum = 0 - for await (const x of wideAsyncGen()) asyncSum += x - - // Hoisted functions in low slots must still be intact - return [acc, closedCount, y1, y2, yRet, asyncSum, hoisted0(1), hoisted1(3), innerHoisted(2)] - } - - return await exercise() - ` - - const { value, codes } = runVerified(src) - expect(codes.some((c) => c.locals > 280)).toBe(true) - const expectedTriangular = (279 * 280) / 2 - // innerHoisted(10)=130, (20)=160, (30)=190 => 480 - // hoistedGen(5): 6+7+8 = 21; hoistedGen(50) break at 52: 51+52 = 103 - // custom break: 7+8 = 15; custom throw "boom".length = 4 - // spreadArr: 1+2 + 11+12+13 + 30+40 = 109; destructure: d0=101, d2=103, dRest=[] (0) => 204 - const expectedAcc = expectedTriangular + 480 + 21 + 103 + 15 + 4 + 109 + 204 - expect(value).toEqual([expectedAcc, 2, 265, 9, 70, 262 + 201 + 202 + 203, 101, 6, 106]) - }) -}) - -describe("tagged templates, calls, and object rest past 254 items", () => { - test("tagged templates with 300 substitutions (plain and method tags) and 300+ call/new arguments", () => { - const parts = Array.from({ length: 300 }, (_, i) => `s${i}\${${i + 1}}`).join("") + "end" - const callArgs = Array.from({ length: 300 }, (_, i) => `${i}`).join(", ") - const src = ` - function plainTag(strings, ...vals) { - return [strings.length, strings.raw.length, strings[0], strings[300], vals.length, vals[0], vals[299], vals.reduce((a, b) => a + b, 0)] - } - const receiver = { - bias: 1000, - methodTag(strings, ...vals) { - return this.bias + strings.length + vals.length + vals[299] - }, - } - const sumFn = (...xs) => xs.length * 10000 + xs[0] + xs[299] - const constructed = new Array(${callArgs}) - return [ - plainTag\`${parts}\`, - receiver.methodTag\`${parts}\`, - sumFn(${callArgs}), - [constructed.length, constructed[0], constructed[299]], - ] - ` - const { value } = runVerified(src) - expect(value).toEqual([ - [301, 301, "s0", "end", 300, 1, 300, (300 * 301) / 2], - 1000 + 301 + 300 + 300, - 300 * 10000 + 0 + 299, - [300, 0, 299], - ]) - }) - - test("object rest destructuring after 305 static and computed keys", () => { - const objEntries = Array.from({ length: 310 }, (_, i) => `k${i}: ${i}`).join(", ") - const patternEntries = Array.from({ length: 305 }, (_, i) => - i % 40 === 0 ? `["k" + ${i}]: p${i}` : `k${i}: p${i}`, - ).join(", ") - const sumExtracted = Array.from({ length: 305 }, (_, i) => `p${i}`).join(" + ") - const src = ` - const srcObj = { ${objEntries} } - const { ${patternEntries}, ...rest } = srcObj - return [${sumExtracted}, Object.keys(rest), rest.k305, rest.k309] - ` - const { value } = runVerified(src) - expect(value).toEqual([(304 * 305) / 2, ["k305", "k306", "k307", "k308", "k309"], 305, 309]) - }) -}) - -describe("per-function wide jumps past 65,535 words and snapshot round-trips", () => { - test("a single function >65,535 words compiles with wide jumps (leaving sibling functions narrow) and runs all control flow", () => { - const padA = makePaddingBlock(1500, "padAcc", "padCond") - const padB = makePaddingBlock(1500, "padAcc", "padCond") - - const src = ` - function smallSibling(x) { - let s = 0 - for (let i = 0; i < x; i++) s += i - return s - } - - function* smallGen() { - yield 10 - yield 20 - } - - async function hugeControlFlow(mode) { - function hoistedInsideHuge(v) { return v * 3 } - let padAcc = 0 - let padCond = true - let trace = 0 - let finallyRuns = 0 - - // Outer labelled loop spanning >75,000 words from top to bottom - outer: for (let pass = 0; pass < 3; pass++) { - try { - // Switch whose dispatch jumps across the 65,535-word boundary - switch (pass) { - case 0: - ${padA} - trace += 1 - break - case 1: - ${padB} - // Continue outer across finally from past word 65,535 back to top of function - trace += 10 - continue outer - default: - // Break outer across finally and open for...of iterator past word 65,535 - for (const item of [100, 200, 300]) { - trace += item - if (item === 200) break outer - } - } - } catch (err) { - trace += 1000 - } finally { - finallyRuns++ - } - } - - // Code past word 75,000: while, do...while, for...in, for...of (array + generator), try/catch/finally, await - let w = 0 - while (w < 3) w++ - do { w += 2 } while (w < 7) - for (const k in { a: 1, b: 2 }) trace += k.length - for (const gVal of smallGen()) trace += gVal - - let caughtLate = "" - try { - await Promise.reject("late-reject") - } catch (e) { - caughtLate = e - } finally { - finallyRuns += 10 - } - - async function* lateAsyncGen() { - yield await Promise.resolve(5) - yield* smallGen() - } - for await (const av of lateAsyncGen()) trace += av - - return [ - hoistedInsideHuge(7), - smallSibling(5), - padAcc, - trace, - finallyRuns, - w, - caughtLate, - mode, - ] - } - - function* hugeGenerator() { - let padAcc = 0 - let padCond = true - const first = yield 1 - ${makePaddingBlock(2800, "padAcc", "padCond")} - yield* smallGen() - const second = yield padAcc + first - return second * 2 - } - - const mainRes = await hugeControlFlow("ok") - const hg = hugeGenerator() - const gSteps = [hg.next().value, hg.next(4).value, hg.next().value, hg.next().value, hg.next(9).value] - return { mainRes, gSteps } - ` - - const { value, codes } = runVerified(src) - const smallCode = codes.find((c) => c.name === "smallSibling")! - const hugeCode = codes.find((c) => c.name === "hugeControlFlow")! - const hugeGenCode = codes.find((c) => c.name === "hugeGenerator")! - expect(hugeCode.code.length).toBeGreaterThan(75_000) - expect(hugeGenCode.code.length).toBeGreaterThan(70_000) - // Sibling small function must NOT have any EXTRA prefixes: per-function wide mode keeps it byte-identical. - expect([...smallCode.code].some((w) => (w & 0xff) === Op.EXTRA)).toBe(false) - - // Determinism: recompiling produces identical hash - const parsed2 = parseVmSource(src) - expect(parsed2.ok).toBe(true) - if (parsed2.ok) { - expect(hashOf(compileSource(parsed2.source, { noCache: true }))).toBe(hashOf(codes)) - } - - // padA on pass 0: 1500 iterations; sum_{i=0..1499} ((i % 7) + 8) - let expectedPadA = 0 - for (let i = 0; i < 1500; i++) expectedPadA += (i % 7) + 8 - let expectedGenPad = 0 - for (let i = 0; i < 2800; i++) expectedGenPad += (i % 7) + 8 - - // trace: pass 0 (+1), pass 1 (+10), pass 2 (+100+200=300), for-in (+2), smallGen (+30), lateAsyncGen (+5+10+20=35) => 378 - expect(value).toEqual({ - mainRes: [21, 10, expectedPadA * 2, 378, 13, 7, "late-reject", "ok"], - gSteps: [1, 10, 20, expectedGenPad + 4, 18], - }) - }, 15_000) - - // Compiling a >65,535-word program and round-tripping 8 full snapshots takes ~8-9s on loaded Windows runners. - test("top-level script >65,535 words runs correctly and survives snapshot round-trips at pc > 65,535", () => { - const src = ` - function hoistedTop(n) { return n + 42 } - function* topGen() { - yield 3 - yield 4 - } - let padAcc = 0 - let padCond = true - let total = 0 - - // Jump forward over >70,000 words on iteration 0, execute padding on iteration 1, then run post-65,535 loops - for (let round = 0; round < 2; round++) { - if (round === 0) { - ${makePaddingBlock(2800, "padAcc", "padCond")} - } else { - total += hoistedTop(8) - } - } - - // Now at pc > 70,000 in top-level : exercise loop, try/finally, generator for...of, and top-level await - try { - for (let k = 0; k < 25; k++) { - total += k - } - for (const v of topGen()) { - total += v - } - total += await Promise.resolve(100) - } finally { - total += 1 - } - - return [padAcc, total] - ` - - const compiled = compileVerified(src) - expect(compiled.codes[0]!.code.length).toBeGreaterThan(70_000) - - let expectedPad = 0 - for (let i = 0; i < 2800; i++) expectedPad += (i % 7) + 8 - // hoistedTop(8)=50, sum(0..24)=300, topGen=7, await=100, finally=1 => 458 - const expected = [expectedPad, 458] - - // First verify normal execution - expect(runProgram(src)).toEqual({ ok: true, value: expected, toolCalls: [] }) - - // Now run through snapshot round-trip mode, slicing inside both the padding loop and the >70,000-pc tail loop - let trips = 0 - let sawHighPc = false - const roundTripped = runProgram(src, { - roundTrip: { every: 6, max: 8 }, - onTrip: (snap) => { - trips++ - const text = JSON.stringify(snap) - for (const rec of snap.records) { - if (rec.t === "Frame" && Array.isArray(rec.f) && typeof rec.f[2] === "number" && rec.f[2] > 65_535) { - sawHighPc = true - } - } - expect(text.length).toBeGreaterThan(0) - }, - }) - expect(roundTripped).toEqual({ ok: true, value: expected, toolCalls: [] }) - expect(trips).toBeGreaterThan(2) - expect(sawHighPc).toBe(true) - }, 15_000) -}) diff --git a/packages/codemode/test/callbacks.test.ts b/packages/codemode/test/callbacks.test.ts deleted file mode 100644 index 9722ae19a1a..00000000000 --- a/packages/codemode/test/callbacks.test.ts +++ /dev/null @@ -1,305 +0,0 @@ -import { describe, expect, test } from "bun:test" -import { Effect, Schema } from "effect" -import { CodeMode, Tool } from "../src/index.js" - -// Callback acceptance is one gate shared by array methods, sort, string replacers, -// Array.from mappers, Map/Set/URLSearchParams forEach, and promise reactions: -// interpreter functions, coercion/URI builtins, resolver capabilities, and built-in -// method references are callable; tools and other opaque callables get a wrap hint. -const run = (code: string) => Effect.runPromise(CodeMode.execute({ code, tools: {} })) -const value = async (code: string) => { - const result = await run(code) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} -const error = async (code: string) => { - const result = await run(code) - if (result.ok) throw new Error(`expected failure, got value ${JSON.stringify(result.value)}`) - return result.error -} -const logsOf = async (code: string) => { - const result = await run(code) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.logs ?? [] -} - -const echo = Tool.make({ - description: "Echo the input", - input: Schema.Struct({ id: Schema.Number }), - output: Schema.Number, - execute: (input: { id: number }) => Effect.succeed(input.id), -}) -const withTool = (code: string) => Effect.runPromise(CodeMode.make({ tools: { host: { echo } } }).execute(code)) -const toolError = async (code: string) => { - const result = await withTool(code) - if (result.ok) throw new Error(`expected failure, got value ${JSON.stringify(result.value)}`) - return result.error -} - -describe("built-in method references as callbacks", () => { - test("map accepts Math methods", async () => { - expect(await value(`return [-1, 2, -3].map(Math.abs)`)).toEqual([1, 2, 3]) - expect(await value(`return [1.5, 2.7].map(Math.floor)`)).toEqual([1, 2]) - }) - - test("map(JSON.stringify) matches JS: the index replacer and array space are ignored", async () => { - expect(await value(`return [{ a: 1 }, [2]].map(JSON.stringify)`)).toEqual(['{"a":1}', "[2]"]) - }) - - test("map(Number.parseInt) reproduces the JS radix footgun", async () => { - // parseInt("2", 1) is NaN in real JS; NaN serializes to null at the result boundary. - expect(await value(`return ["1", "2"].map(Number.parseInt)`)).toEqual([1, null]) - }) - - test("filter and find accept built-in predicates", async () => { - expect(await value(`return [0, 1, NaN, 2].filter(Number.isInteger)`)).toEqual([0, 1, 2]) - expect(await value(`return [1.5, 3, 2.5].find(Number.isInteger)`)).toBe(3) - }) - - test("forEach(console.log) captures one log line per element", async () => { - const logs = await logsOf(`["a", "b"].forEach(console.log); return null`) - expect(logs).toHaveLength(2) - expect(logs[0]).toContain("a") - expect(logs[1]).toContain("b") - }) - - test("detached method references lose their receiver, like JS", async () => { - expect((await error(`return ["a", "z"].filter("abc".includes)`)).message).toContain( - "String.prototype.includes called on null or undefined", - ) - }) - - test("promise reactions accept built-in references", async () => { - expect(await value(`return await Promise.resolve(-5).then(Math.abs)`)).toBe(5) - const logs = await logsOf(`await Promise.resolve("done").then(console.log); return null`) - expect(logs).toHaveLength(1) - expect(logs[0]).toContain("done") - }) -}) - -describe("constructors callable without new, like JS", () => { - test("Error constructors work as callbacks and direct calls", async () => { - expect(await value(`return ["boom"].map(Error)[0].message`)).toBe("boom") - expect(await value(`return TypeError("bad").name`)).toBe("TypeError") - }) - - test("error values stringify like JS Error.prototype.toString", async () => { - expect(await value(`return String(TypeError("bad"))`)).toBe("TypeError: bad") - expect(await value(`return String(Error(""))`)).toBe("Error") - expect(await value(`return "x" + RangeError("oops")`)).toBe("xRangeError: oops") - expect(await value(`return "a1b2".replace(/\\d/, Error)`)).toBe("aError: 1b2") - }) - - test("literal elisions are real holes, like JS", async () => { - expect(await value(`return (0 in [, 1])`)).toBe(false) - expect(await value(`return Object.keys([, 1, ,])`)).toEqual(["1"]) - expect(await value(`return [, 1, ,].filter(() => true).length`)).toBe(1) - expect(await value(`return [, ,].every((x) => false)`)).toBe(true) - }) - - test("Array constructs from arguments or a length", async () => { - expect(await value(`return Array(1, 2, 3)`)).toEqual([1, 2, 3]) - expect(await value(`return Array("3")`)).toEqual(["3"]) - expect(await value(`return Array(3).length`)).toBe(3) - expect(await value(`return new Array(2).length`)).toBe(2) - // Holes stay holes, like JS: map skips them (length preserved, normalized to - // null at the host boundary), spread materializes undefined. - expect(await value(`return Array(3).map((x) => 1)`)).toEqual([null, null, null]) - expect(await value(`return Array(3).map((x) => 1).length`)).toBe(3) - expect(await value(`return [...Array(3)].map((_, i) => i)`)).toEqual([0, 1, 2]) - expect((await error(`return Array(-1)`)).message).toContain("Invalid array length") - expect((await error(`return Array(1.5)`)).message).toContain("Invalid array length") - }) - - test("Object returns objects unchanged and rejects primitive wrappers", async () => { - expect(await value(`return Object()`)).toEqual({}) - expect(await value(`const o = { a: 1 }; return Object(o) === o`)).toBe(true) - expect((await error(`return Object(1)`)).message).toContain("wrapper objects are not supported") - }) - - test("Date() without new returns a deterministic ISO string and ignores arguments", async () => { - expect(await value(`return /^\\d{4}-\\d{2}-\\d{2}T.*Z$/.test(Date(1000))`)).toBe(true) - expect(await value(`return "abc".replace(RegExp("b"), "x")`)).toBe("axc") - }) - - test("map(Array) matches the JS 3-argument call", async () => { - expect(await value(`return [7].map(Array)`)).toEqual([[7, 0, [7]]]) - }) - - test("array length is bounded below the JS maximum, so one call cannot materialize an unbounded array", async () => { - expect(await value(`return Array(10000000).length`)).toBe(10_000_000) - const diagnostic = await error(`return Array(10000001)`) - expect(diagnostic.message).toContain("Invalid array length") - expect((await error(`try { Array(-1) } catch (e) { throw Error(e.name) }`)).message).toContain("RangeError") - }) - - test("returned sparse arrays normalize holes to null at the host boundary", async () => { - expect(await value(`return Array(3)`)).toEqual([null, null, null]) - }) - - test("RegExp with non-string flags throws a SyntaxError, like JS", async () => { - expect((await error(`try { RegExp("a", 0) } catch (e) { throw Error(e.name) }`)).message).toContain("SyntaxError") - }) - - test("new-requiring constructors throw a TypeError when called", async () => { - expect((await error(`return Map()`)).message).toContain("Constructor Map requires 'new'") - expect((await error(`return [1].map(Set)`)).message).toContain("Constructor Set requires 'new'") - expect((await error(`return Promise(() => 1)`)).message).toContain("Constructor Promise requires 'new'") - // As a reaction handler the TypeError rejects the derived promise catchably, like JS. - expect(await value(`return await Promise.resolve(1).then(Map).catch((e) => e.name)`)).toBe("TypeError") - }) -}) - -describe("sort accepts the unified callback set", () => { - test("sort preserves trailing holes while toSorted densifies them", async () => { - expect( - await value(` - const defaultSorted = [2, , 1] - const compared = [2, , 1] - const copied = defaultSorted.toSorted() - defaultSorted.sort() - compared.sort((a, b) => a - b) - return [ - Object.hasOwn(defaultSorted, 2), - Object.hasOwn(compared, 2), - Object.hasOwn(copied, 2), - ] - `), - ).toEqual([false, false, true]) - - expect(await value(`const values = [2, undefined, 1]; values.sort(); return Object.hasOwn(values, 2)`)).toBe(true) - }) - - test("sort writes its snapshot without discarding comparator length mutations", async () => { - expect( - await value(` - const values = [3, 2, 1] - let first = true - values.sort((a, b) => { - if (first) { - first = false - values.push("kept") - } - return a - b - }) - return values - `), - ).toEqual([1, 2, 3, "kept"]) - - expect( - await value(` - const values = [3, , 1, , 2] - let first = true - values.sort((a, b) => { - if (first) { - first = false - values.splice(0) - } - return a - b - }) - return { values, owns: values.map((_, index) => Object.hasOwn(values, index)) } - `), - ).toEqual({ values: [1, 2, 3], owns: [true, true, true] }) - }) - - test("sort and toSorted take built-in comparators", async () => { - expect(await value(`return [0, 1, 0].sort(Boolean)`)).toEqual([0, 0, 1]) - expect(await value(`return [0, 1, 0].toSorted(Boolean)`)).toEqual([0, 0, 1]) - }) - - test("a non-callable comparator is rejected", async () => { - expect((await error(`return [2, 1].sort(42)`)).message).toContain("Array.sort expects a function callback") - expect((await error(`return [2, 1].toSorted(42)`)).message).toContain("Array.toSorted expects a function callback") - }) -}) - -describe("Array.from mapper", () => { - test("maps with (value, index) over arrays, strings, and Sets", async () => { - expect(await value(`return Array.from([1, 2, 3], (x) => x * 2)`)).toEqual([2, 4, 6]) - expect(await value(`return Array.from("ab", (c, i) => c + i)`)).toEqual(["a0", "b1"]) - expect(await value(`return Array.from(new Set([1, 2]), (x) => x * 10)`)).toEqual([10, 20]) - }) - - test("accepts coercion builtins and an explicit undefined mapper", async () => { - expect(await value(`return Array.from(["5", "7"], Number)`)).toEqual([5, 7]) - expect(await value(`return Array.from([1, 2], undefined)`)).toEqual([1, 2]) - }) - - test("rejects a non-callable mapper", async () => { - expect((await error(`return Array.from([1], 42)`)).message).toContain("Array.from expects a function callback") - }) -}) - -describe("thisArg is accepted and ignored, like JS arrows", () => { - // CodeMode functions have no `this`, so a thisArg can never change behavior — - // exactly like passing one alongside an arrow function in real JS. - test("iteration methods and Array.from ignore a thisArg", async () => { - expect(await value(`return [1, 2].map((x) => x * 2, {})`)).toEqual([2, 4]) - expect(await value(`return [1, 2].map((x) => x, undefined)`)).toEqual([1, 2]) - expect(await value(`return Array.from([1], (x) => x + 1, {})`)).toEqual([2]) - }) - - test("Map, Set, and URLSearchParams forEach ignore a thisArg", async () => { - expect(await value(`const o = []; new Map([["a", 1]]).forEach((v, k) => o.push(k), {}); return o`)).toEqual(["a"]) - expect(await value(`const o = []; new Set([1]).forEach((v) => o.push(v), "self"); return o`)).toEqual([1]) - expect(await value(`const o = []; new URLSearchParams("a=1").forEach((v) => o.push(v), 0); return o`)).toEqual([ - "1", - ]) - }) -}) - -describe("still-rejected callables get the wrap hint", () => { - test("tool references as callbacks suggest an arrow wrapper", async () => { - const diagnostic = await toolError(`return [1, 2].map(tools.host.echo)`) - expect(diagnostic.message).toContain("wrap it in an arrow function") - expect(await withTool(`return await Promise.all([1, 2].map((id) => tools.host.echo({ id })))`)).toMatchObject({ - ok: true, - value: [1, 2], - }) - }) - - test("detached Promise statics as callbacks suggest an arrow wrapper", async () => { - expect((await error(`return [1].map(Promise.resolve)`)).message).toContain("wrap it in an arrow function") - }) - - test("string replacers reject opaque callables with the wrap hint, not a type error", async () => { - const diagnostic = await toolError(`return "abc".replace(/b/, tools.host.echo)`) - expect(diagnostic.message).toContain("wrap it in an arrow function") - expect(diagnostic.message).not.toContain("argument 2") - }) - - test("built-in references work as replacers", async () => { - // Like real JS: JSON.stringify(match, offset, string) quotes the match. - expect(await value(`return "abc".replace(/b/, JSON.stringify)`)).toBe('a"b"c') - // Math methods coerce the match string, as in JS. - expect(await value(`return "3.7".replace(/\\d\\.\\d/, Math.floor)`)).toBe("3") - }) - - test("non-callables still get the plain callback error", async () => { - expect((await error(`return [1].map(42)`)).message).toContain("Array.map expects a function callback") - }) - - test("promise handlers reject opaque callables with the wrap hint", async () => { - const diagnostic = await toolError(`return await Promise.resolve(1).then(tools.host.echo)`) - expect(diagnostic.message).toContain("Promise.prototype.then cannot use this callable as a handler") - expect(diagnostic.message).toContain("wrap it in an arrow function") - }) - - test("JSON callbacks use the unified callback gate", async () => { - expect( - await value(`return JSON.stringify({ a: -1 }, (key, item) => typeof item === "number" ? Math.abs(item) : item)`), - ).toBe('{"a":1}') - expect((await toolError(`return JSON.stringify({ a: 1 }, tools.host.echo)`)).message).toContain( - "wrap it in an arrow function", - ) - expect((await toolError(`return JSON.parse('{"a":1}', tools.host.echo)`)).message).toContain( - "wrap it in an arrow function", - ) - }) - - test("non-callable JSON callback arguments are ignored", async () => { - expect(await value(`return JSON.parse('{"a":1}', undefined)`)).toEqual({ a: 1 }) - expect(await value(`return JSON.parse('{"a":1}', 42)`)).toEqual({ a: 1 }) - expect(await value(`return JSON.stringify({ a: 1 }, 42)`)).toBe('{"a":1}') - }) -}) diff --git a/packages/codemode/test/classes-suspend.test.ts b/packages/codemode/test/classes-suspend.test.ts deleted file mode 100644 index 935f7dfb992..00000000000 --- a/packages/codemode/test/classes-suspend.test.ts +++ /dev/null @@ -1,236 +0,0 @@ -import { describe, expect, test } from "bun:test" -import { tmpdir } from "node:os" -import path from "node:path" -import { Effect, Fiber } from "effect" -import { Host, Runtime, toBytes } from "../src/language/index.js" -import { getInternalPrelude } from "../src/language/internal-prelude.js" -import { compiledPrelude } from "../src/language/prelude/prelude.js" -import type { Snapshot } from "../src/language/snapshot/snapshot.js" - -// Suspending a run while a host call is in flight at every point class code runs, and resuming it: from the saved -// state and from bytes in a fresh runtime, in the same runtime, and in another process. Each resumed run must end as -// an uninterrupted one does. - -type Saved = { readonly t?: string; readonly f?: ReadonlyArray; readonly o?: ReadonlyArray } - -const frames = (snapshot: Snapshot): Array => { - const records = snapshot.records as ReadonlyArray - return records.flatMap((record) => { - if (record?.t !== "Frame") return [] - const [fn, code] = record.f as [unknown, [string, [string, string, number]], ...Array] - if (Array.isArray(fn) && fn[0] === "r") { - const props = records[fn[1] as number]!.o! - return [String(props[props.indexOf("name") + 1])] - } - const [, source, index] = code[1] - const codes = source === "@vm-internal" ? getInternalPrelude().codes : compiledPrelude().codes - return [codes[index]!.name] - }) -} - -const latch = () => { - let resolve!: (value: A) => void - const promise = new Promise((done) => (resolve = done)) - return { promise, resolve } -} - -// Matches test/fixtures/resume-getters-process.ts: `slow` answers `n * 2` once `gate` opens, `pick` its argument. -const hosting = (gate: Promise | undefined) => { - const started = latch() - const runtime = Runtime.make({ - translate: { promises: "await" }, - globals: () => ({ - slow: Host.fn( - ([n]) => - Effect.promise(async () => { - started.resolve() - await gate - return (n as number) * 2 - }), - { type: "async", idempotent: true }, - ), - pick: Host.fn(([value]) => value), - keep: Host.fn(() => undefined), - }), - }) as Runtime.Runtime - return { runtime, started: started.promise } -} - -// Round-trip mode yields at its checkpoints, so `slow` starting doesn't mean the run is parked on it yet: retry, -// letting it go on longer, until the saved stack reaches `$vmHostWait`. -const suspendParked = async (code: string) => { - for (let attempt = 0; attempt < 50; attempt++) { - const gate = latch() - const first = hosting(gate.promise) - const program = first.runtime.program(code, { runId: "r" }) - const fiber = Effect.runFork(program.run()) - await first.started - for (let i = 0; i < attempt; i++) await new Promise((done) => setImmediate(done)) - const suspended = await Effect.runPromise(program.suspend()) - gate.resolve() - await Effect.runPromise(Fiber.join(fiber)) - if (suspended.ok !== "suspended") throw new Error(`expected a suspended run, got ${JSON.stringify(suspended)}`) - if (frames(suspended.state).includes("$vmHostWait")) return { suspended, runtime: first.runtime } - } - throw new Error("the run never parked on $vmHostWait while `slow` was in flight") -} - -const cases = [ - [ - "constructor", - `class A { constructor(n) { this.v = pick(slow(n)) } m() { return this.v + 1 } } - const a = new A(21) - return [a.v, a.m(), a instanceof A, Object.keys(a)]`, - [42, 43, true, ["v"]], - "A", - ], - [ - "field initializer", - `class A { static scale = 2; a = 1; v = pick(slow(this.a + 20)); w = this.v * A.scale; constructor() { this.after = this.w } } - const a = new A() - return [a.v, a.w, a.after, Object.keys(a)]`, - [42, 84, 84, ["a", "v", "w", "after"]], - "", - ], - [ - "static field initializer", - `class A { static v = pick(slow(21)); static w = A.v + 1 } - return [A.v, A.w]`, - [42, 43], - "", - ], - [ - "method", - `class A { constructor() { this.base = 1 } m(n) { return this.base + pick(slow(n)) } static s() { return new A() } } - const a = A.s() - return [a.m(20), a instanceof A]`, - [41, true], - "m", - ], - [ - "getter", - `class A { constructor() { this.n = 20 } get v() { return pick(slow(this.n)) + 1 } } - return [new A().v, Object.keys(A.prototype)]`, - [41, []], - "get v", - ], - [ - "async method", - `class A { async load(n) { const v = await pick(slow(n)); return v + 1 } } - return [await new A().load(21)]`, - [43], - "load", - ], - [ - "generator method", - `class A { *items() { yield 1; yield pick(slow(21)); yield 3 } } - const out = [] - for (const x of new A().items()) out.push(x) - return out`, - [1, 42, 3], - "items", - ], - [ - "parent constructor reached through super()", - `class A { constructor(n) { this.v = pick(slow(n)) } } - class B extends A { w = this.v + 1; constructor(n) { super(n); this.x = this.w * 2 } } - class C extends B {} - const c = new C(21) - return [c.v, c.w, c.x, c instanceof A, c instanceof C, Object.keys(c)]`, - [42, 43, 86, true, true, ["v", "w", "x"]], - "A", - ], - [ - "method called through super.method()", - `class A { m(n) { return this.base + pick(slow(n)) } } - class B extends A { constructor() { super(); this.base = 1 } m(n) { return super.m(n) * 10 } } - return [new B().m(20)]`, - [410], - "m", - ], - [ - "custom error's constructor after super()", - `class Base extends Error { name = "Base" } - class NotFound extends Base { constructor(n) { super("missing", { cause: n }); this.code = pick(slow(n)) } } - try { throw new NotFound(21) } catch (e) { - return [e instanceof NotFound, e instanceof Error, e.name, e.message, e.cause, e.code, String(e)] - }`, - [true, true, "Base", "missing", 21, 42, "Base: missing"], - "NotFound", - ], - [ - "static method", - `class A { static base = 1; static s(n) { return A.base + pick(slow(n)) } } - return [A.s(20)]`, - [41], - "s", - ], - [ - "setter", - `class A { set v(n) { this.got = pick(slow(n)) } } - const a = new A() - a.v = 21 - return [a.got, Object.keys(a)]`, - [42, ["got"]], - "set v", - ], -] as const - -const resumeIn = (runtime: Runtime.Runtime, state: Parameters["resume"]>[0]) => - Effect.runPromise(runtime.resume(state).run()) - -describe("suspended inside a class", () => { - for (const [name, code, expected, frame] of cases) { - test(`a host call parked in a ${name}, resumed from state and from bytes in a fresh runtime`, async () => { - const { suspended } = await suspendParked(code) - expect(frames(suspended.state)).toEqual(expect.arrayContaining([frame, "$vmHostWait"])) - const plain = await Effect.runPromise(hosting(undefined).runtime.execute(code)) - expect(plain).toMatchObject({ ok: true, value: expected }) - expect(await resumeIn(hosting(undefined).runtime, suspended.state)).toEqual(plain) - expect(await resumeIn(hosting(undefined).runtime, toBytes(suspended.state))).toEqual(plain) - }, 5000) - } - - for (const name of ["constructor", "parent constructor reached through super()"]) { - test(`a host call parked in a ${name}, resumed in the same runtime`, async () => { - const [, code, expected] = cases.find((row) => row[0] === name)! - const { suspended, runtime } = await suspendParked(code) - expect(await resumeIn(runtime, toBytes(suspended.state))).toMatchObject({ ok: true, value: expected }) - }, 5000) - } - - test("instances made before and after a suspend share the prototype, and this before super() still throws", async () => { - const code = ` - class A { constructor(n) { this.v = n } } - class B extends A { constructor(early) { if (early) this.x = 1; super(1) } } - const before = new A(1) - const v = pick(slow(1)) - const after = new A(v) - let threw = false - try { new B(true) } catch (e) { threw = e instanceof ReferenceError } - return [Object.getPrototypeOf(before) === Object.getPrototypeOf(after), after instanceof A, threw, new B(false).v]` - const { suspended } = await suspendParked(code) - expect(await resumeIn(hosting(undefined).runtime, toBytes(suspended.state))).toMatchObject({ - ok: true, - value: [true, true, true, 1], - }) - }, 5000) - - test("a host call parked in a custom error's constructor, resumed in another process", async () => { - const [, code, expected] = cases.find((row) => row[0] === "custom error's constructor after super()")! - const { suspended } = await suspendParked(code) - const file = path.join(tmpdir(), `codemode-classes-${crypto.randomUUID()}.state`) - await Bun.write(file, toBytes(suspended.state)) - try { - const child = Bun.spawn(["bun", path.join(import.meta.dir, "fixtures/resume-getters-process.ts"), file], { - stdout: "pipe", - stderr: "inherit", - }) - const output = await new Response(child.stdout).text() - expect(await child.exited).toBe(0) - expect(JSON.parse(output)).toMatchObject({ ok: true, value: expected }) - } finally { - await Bun.file(file).delete() - } - }, 10000) -}) diff --git a/packages/codemode/test/classes.test.ts b/packages/codemode/test/classes.test.ts deleted file mode 100644 index 475292718e0..00000000000 --- a/packages/codemode/test/classes.test.ts +++ /dev/null @@ -1,517 +0,0 @@ -import { describe, expect, test } from "bun:test" -import { compileSource } from "../src/language/compiler/compile.js" -import { verifyAll } from "./verify-bytecode.js" -import { parseVmSource, runProgram } from "./run-program.js" - -const run = (code: string) => { - const parsed = parseVmSource(code) - if (parsed.ok) expect(verifyAll(compileSource(parsed.source, { noCache: true }))).toEqual([]) - return runProgram(code) -} - -const value = (code: string) => { - const result = run(code) - if (!result.ok) throw new Error(`${result.error.kind}: ${result.error.message}`) - return result.value -} - -describe("base classes", () => { - test("a declaration and an expression", () => { - expect( - value(` - class A { get1() { return 1 } } - const B = class { two() { return 2 } } - const C = class Named { self() { return Named } } - return [new A().get1(), new B().two(), B.name, C.name, new C().self() === C, typeof A]`), - ).toEqual([1, 2, "B", "Named", true, "function"]) - }) - - test("the constructor sets fields on this", () => { - expect( - value(` - class Point { constructor(x, y) { this.x = x; this.y = y } } - const p = new Point(1, 2) - return [p.x, p.y, p, Point.length, Point.name]`), - ).toEqual([1, 2, { x: 1, y: 2 }, 2, "Point"]) - }) - - test("a constructor returning an object replaces the instance", () => { - expect( - value( - `class A { constructor() { return { other: true } } } class B { constructor() { this.a = 1; return 5 } } return [new A(), new B()]`, - ), - ).toEqual([{ other: true }, { a: 1 }]) - }) - - test("instance and static methods", () => { - expect( - value(` - class Counter { - constructor(n) { this.n = n } - inc() { this.n++; return this } - get_() { return this.n } - static make(n) { return new Counter(n) } - static "quoted"() { return this.name } - } - return [Counter.make(1).inc().inc().get_(), Counter.quoted(), Counter.prototype.inc.name, Counter.make.name]`), - ).toEqual([3, "Counter", "inc", "make"]) - }) - - test("methods are not enumerable", () => { - expect( - value(` - class A { constructor() { this.a = 1 } m() {} static s() {} } - const a = new A() - const keys = [] - for (const k in a) keys.push(k) - return [Object.keys(a), JSON.stringify(a), keys, Object.keys(A), Object.keys(A.prototype), - Object.getOwnPropertyDescriptor(A, "prototype").writable, A.prototype.constructor === A]`), - ).toEqual([["a"], '{"a":1}', ["a"], [], [], false, true]) - }) - - test("calling a class without new throws a TypeError", () => { - expect( - value(` - class A {} - const out = [] - try { A() } catch (e) { out.push(e instanceof TypeError, e.message) } - try { [1].map(A) } catch (e) { out.push(e instanceof TypeError) } - try { A.call({}) } catch (e) { out.push(e instanceof TypeError) } - return out`), - ).toEqual([true, "Class constructor A cannot be invoked without 'new'", true, true]) - }) - - test("instanceof", () => { - expect( - value( - `class A {} class B {} const a = new A(); return [a instanceof A, a instanceof B, a instanceof Object, Object.getPrototypeOf(a) === A.prototype]`, - ), - ).toEqual([true, false, true, true]) - }) - - test("the class binding has a TDZ", () => { - expect( - value(` - const out = [] - try { new A() } catch (e) { out.push(e instanceof ReferenceError) } - { try { B } catch (e) { out.push(e instanceof ReferenceError) } class B {} out.push(typeof B) } - class A {} - return out`), - ).toEqual([true, true, "function"]) - }) - - test("the inner name is immutable and the outer binding is not", () => { - expect( - value(` - class A { m() { try { A = 1 } catch (e) { return e instanceof TypeError } } } - const m = new A().m() - A = 2 - return [m, A]`), - ).toEqual([true, 2]) - }) - - test("unsupported class syntax still reports UnsupportedSyntax", () => { - for (const code of [ - "class A { #x = 1 }", - "class A { #m() {} }", - "class A { static {} }", - ]) { - const result = runProgram(code) - expect(result.ok).toBe(false) - if (!result.ok) expect(result.error.kind).toBe("UnsupportedSyntax") - } - }) - - test("a class value survives a snapshot round trip", () => { - const code = ` - class Box { - constructor(v) { let s = 0; for (let i = 0; i < 3; i++) s += i; this.v = v + s } - get_() { let s = 0; for (let i = 0; i < 3; i++) s += i; return this.v + s } - static of(v) { return new Box(v) } - } - const a = Box.of(1) - const b = new Box(2) - return [a.get_(), b.get_(), a instanceof Box, Object.getPrototypeOf(a) === Object.getPrototypeOf(b), Object.keys(a)]` - const plain = runProgram(code) - expect(plain).toMatchObject({ ok: true, value: [7, 8, true, true, ["v"]] }) - expect(runProgram(code, { roundTrip: { every: 1, max: 100_000 } })).toEqual(plain) - const err = `class A { constructor() { for (let i = 0; i < 3; i++) {} } } try { A() } catch (e) { return e.message }` - expect(runProgram(err, { roundTrip: { every: 1, max: 100_000 } })).toEqual(runProgram(err)) - }) -}) - -const failure = (code: string) => { - const result = run(code) - if (result.ok) throw new Error(`expected a failure, got ${JSON.stringify(result.value)}`) - const [kind, message] = result.error.message.replace(/ \(line \d+, col \d+\)$/, "").split(/: (.*)/s) - return [kind, message] -} - -describe("class inheritance", () => { - test("two and three levels: prototype and constructor chains, inherited methods", () => { - expect( - value(` - class A { constructor(x) { this.x = x } a() { return "a" + this.x } who() { return "A" } } - class B extends A { constructor(x, y) { super(x); this.y = y } b() { return "b" + this.y } who() { return "B" } } - class C extends B { constructor() { super(1, 2) } who() { return "C" } } - const c = new C() - return [ - c.a(), c.b(), c.who(), c, - Object.getPrototypeOf(B.prototype) === A.prototype, Object.getPrototypeOf(C) === B, Object.getPrototypeOf(B) === A, - c.constructor === C, C.name, - ]`), - ).toEqual(["a1", "b2", "C", { x: 1, y: 2 }, true, true, true, true, "C"]) - }) - - test("instanceof across the hierarchy", () => { - expect( - value(` - class A {} - class B extends A {} - class C extends B {} - const b = new B() - return [new C() instanceof A, new C() instanceof B, b instanceof C, b instanceof A, new A() instanceof B]`), - ).toEqual([true, true, false, true, false]) - }) - - test("any expression evaluating to a class can be extended", () => { - expect( - value(` - const make = (tag) => class { tag() { return tag } } - class X extends make("t") {} - const Y = class extends (0, X) { get t() { return this.tag() } } - return [new X().tag(), new Y().t]`), - ).toEqual(["t", "t"]) - }) - - test("super calls with arguments and spread, and the default derived constructor", () => { - expect( - value(` - class A { constructor(...args) { this.args = args } } - class B extends A { constructor(a, ...rest) { super(a * 10, ...rest) } } - class C extends A {} - return [new B(1, 2, 3).args, new C(4, 5).args, C.length]`), - ).toEqual([[10, 2, 3], [4, 5], 0]) - }) - - test("super.method() and super.x in instance and static methods and accessors", () => { - expect( - value(` - class A { - m(n) { return "A.m" + n + this.tag } - get g() { return "A.g" + this.tag } - set s(v) { this.stored = "A:" + v } - static sm() { return "A.sm" + this.name } - static get sg() { return "A.sg" } - } - A.prototype.data = "proto-data" - class B extends A { - constructor() { super(); this.tag = "!" } - m(n) { return "B>" + super.m(n) } - get g() { return "B>" + super.g } - set s(v) { super.s = v + "+" } - d() { return super.data + super["m"](2) } - static sm() { return "B>" + super.sm() } - static get sg() { return "B>" + super.sg } - } - const b = new B() - b.s = "v" - return [b.m(1), b.g, b.stored, b.d(), B.sm(), B.sg]`), - ).toEqual(["B>A.m1!", "B>A.g!", "A:v+", "proto-data" + "A.m2!", "B>A.smB", "B>A.sg"]) - }) - - test("super.x = v writes to this when there is no setter", () => { - expect( - value(` - class A {} - class B extends A { set(v) { super.x = v; return [this.x, Object.keys(this)] } } - return new B().set(3)`), - ).toEqual([3, ["x"]]) - }) - - test("super.x with ++, --, compound and logical assignment, and delete super.x", () => { - expect( - value(` - class A { get x() { return this._x ?? 1 } set x(v) { this._x = v } } - class B extends A { - m() { - const r = [super.x++, super.x, ++super.x] - super.x += 10 - super["x"] *= 2 - super.x ||= 5 - super.y ??= 7 - const k = "x" - r.push(this.x, this.y, super[k]--, this.x) - try { delete super.x } catch (e) { r.push(e.name) } - return r - } - } - return new B().m()`), - ).toEqual([1, 2, 3, 26, 7, 26, 25, "ReferenceError"]) - }) - - test("a field cannot be defined on a frozen instance", () => { - expect(failure(`class A { f = Object.freeze(this); g = 1 }; new A()`)[0]).toBe("TypeError") - }) - - test("an anonymous class has its name before its static fields run", () => { - expect(value(`const C = class { static n = this.name }; return C.n`)).toBe("C") - }) - - test("super in object literal methods and accessors", () => { - expect( - value(` - const o = { - n: 1, - has(k) { return super.hasOwnProperty.call(this, k) }, - get g() { return super.toString === Object.prototype.toString }, - ["k"]() { return (() => super.hasOwnProperty("n"))() }, - } - return [o.has("n"), o.has("x"), o.g, o.k()]`), - ).toEqual([true, false, true, true]) - }) - - test("arrows capture super and this", () => { - expect( - value(` - class A { m() { return "A" + this.n } } - class B extends A { - constructor() { const early = () => this.n; super(); this.n = 1; this.early = early() } - m() { return [1, 2].map((i) => super.m() + i) } - f = () => super.m() - } - const b = new B() - return [b.m(), b.f(), b.early]`), - ).toEqual([["A11", "A12"], "A1", 1]) - }) - - test("this before super() is a ReferenceError, also through an arrow", () => { - expect(failure(`class A {}; class B extends A { constructor() { this.x = 1; super() } }; new B()`)).toEqual([ - "ReferenceError", - "Must call super constructor in derived class before accessing 'this' or returning from derived constructor", - ]) - expect(failure(`class A {}; class B extends A { constructor() { const f = () => this; f(); super() } }; new B()`)[1]).toBe( - "Must call super constructor in derived class before accessing 'this' or returning from derived constructor", - ) - expect(failure(`class A {}; class B extends A { constructor() {} }; new B()`)).toEqual([ - "ReferenceError", - "Must call super constructor in derived class before accessing 'this' or returning from derived constructor", - ]) - }) - - test("a second super() is a ReferenceError", () => { - expect(failure(`class A {}; class B extends A { constructor() { super(); super() } }; new B()`)).toEqual([ - "ReferenceError", - "Super constructor may only be called once", - ]) - }) - - test("derived fields initialize right after super() returns, after the parent's", () => { - expect( - value(` - const log = [] - class A { a = log.push("A.field"); constructor() { log.push("A.ctor") } } - class B extends A { - b = log.push("B.field:" + this.a) - constructor() { log.push("B.before"); super(); log.push("B.after:" + this.b) } - } - class C extends B { c = log.push("C.field") } - new C() - return log`), - ).toEqual(["B.before", "A.field", "A.ctor", "B.field:2", "B.after:4", "C.field"]) - }) - - test("derived constructor return rules", () => { - expect( - value(` - class A {} - class Obj extends A { constructor() { super(); return { other: true } } } - class NoSuper extends A { constructor() { return { early: true } } } - class Undef extends A { constructor() { super(); return undefined } } - class Parent { constructor() { return { replaced: 1 } } } - class Child extends Parent { constructor() { super(); this.mine = 2 } } - return [new Obj(), new NoSuper(), new Undef() instanceof A, new Child()]`), - ).toEqual([{ other: true }, { early: true }, true, { replaced: 1, mine: 2 }]) - expect(failure(`class A {}; class B extends A { constructor() { super(); return 1 } }; new B()`)).toEqual([ - "TypeError", - "Derived constructors may only return object or undefined", - ]) - }) - - test("static inheritance", () => { - expect( - value(` - class A { static count = 1; static make() { return new this() } static get label() { return "L" + this.name } } - class B extends A {} - return [B.count, B.make() instanceof B, B.label, Object.keys(B), B.hasOwnProperty("count")]`), - ).toEqual([1, true, "LB", [], false]) - }) - - test("refused heritages", () => { - expect(failure(`class A extends null {}`)).toEqual(["TypeError", "Classes extending null are not supported."]) - for (const name of ["Array", "Map", "Set", "Promise", "RegExp", "Object", "Uint8Array"]) { - expect(failure(`class A extends ${name} {}`)).toEqual([ - "TypeError", - `Extending the built-in ${name} is not supported. Only classes and Error types can be extended.`, - ]) - } - expect(failure(`class A extends 1 {}`)[1]).toBe("Class extends value a number is not a constructor or null.") - expect(failure(`function f() {}; class A extends f {}`)[0]).toBe("TypeError") - }) -}) - -describe("classes extending Error", () => { - test("every error type can be subclassed", () => { - for (const name of ["Error", "TypeError", "RangeError", "SyntaxError", "ReferenceError", "EvalError", "URIError"]) { - expect( - value(` - class E extends ${name} {} - const e = new E("m") - return [e instanceof E, e instanceof ${name}, e instanceof Error, e.message, e.name, String(e), - Object.prototype.toString.call(e), Error.isError(e), Object.getPrototypeOf(e) === E.prototype]`), - ).toEqual([true, true, true, "m", name, `${name}: m`, "[object Error]", true, true]) - } - expect( - value(` - class A extends AggregateError {} - const a = new A([1, 2], "agg") - return [a.errors, a.message, a.name, a instanceof A, a instanceof AggregateError]`), - ).toEqual([[1, 2], "agg", "AggregateError", true, true]) - }) - - test("multi-level, cause, and name from a field or a getter", () => { - expect( - value(` - class A extends TypeError { name = "NotFound" } - class B extends A { constructor(m, cause) { super(m, { cause }); this.code = 404 } } - class G extends RangeError { get name() { return "Got" } } - const b = new B("x", "why") - return [b instanceof A, b instanceof TypeError, b.name, b.toString(), b.code, b.cause, b.hasOwnProperty("cause"), - new A("y").hasOwnProperty("cause"), String(new G("z")), new B().message]`), - ).toEqual([true, true, "NotFound", "NotFound: x", 404, "why", true, false, "Got: z", ""]) - }) - - test("caught, uncaught, returned, logged and stringified like plain errors", () => { - expect(value(`class E extends Error {}; try { throw new E("m") } catch (e) { return [e instanceof E, e.message] }`)).toEqual([ - true, - "m", - ]) - const uncaught = run(`class E extends TypeError { name = "NotFound" }; throw new E("gone")`) - const plain = run(`throw new TypeError("gone")`) - expect(uncaught.ok).toBe(false) - if (uncaught.ok || plain.ok) return - expect(uncaught.error.kind).toBe(plain.error.kind) - expect(uncaught.error.message).toBe("NotFound: gone") - expect(value(`class E extends Error { name = "E" }; return new E("x")`)).toEqual({ name: "E", message: "x" }) - expect(value(`return new Error("x")`)).toEqual({ name: "Error", message: "x" }) - expect( - value(`class E extends Error {}; return [JSON.stringify(new E("x")), JSON.stringify(new Error("x"))]`), - ).toEqual(['{"name":"Error","message":"x"}', '{"name":"Error","message":"x"}']) - expect(runProgram(`class E extends Error { name = "E" }; console.log(new E("hi"))`)).toMatchObject({ logs: ["E: hi"] }) - }) -}) - -describe("showing and copying class values", () => { - test("console.log shows the class name", () => { - const code = ` - class Cache { constructor() { this.size = 2 } get g() { return 1 } } - class Empty {} - class Lru extends Cache { hits = 0 } - class E extends Error { name = "E" } - console.log(new Cache()) - console.log(new Empty()) - console.log(new Lru()) - console.log([new Empty(), { c: new Cache() }]) - console.log(Cache, Lru, class {}) - console.log(new E("bad")) - console.log({ a: 1 })` - expect(runProgram(code)).toMatchObject({ - logs: [ - 'Cache {"size":2}', - "Empty {}", - 'Lru {"size":2,"hits":0}', - '[Empty {},{"c":Cache {"size":2}}]', - "[class Cache] [class Lru extends Cache] [class (anonymous)]", - "E: bad", - '{"a":1}', - ], - }) - }) - - test("JSON.stringify and structuredClone keep own enumerable fields and drop the prototype", () => { - expect( - value(` - class A { x = 1; get g() { return 2 } m() {} } - const c = structuredClone(new A()) - return [JSON.stringify(new A()), c, Object.getPrototypeOf(c) === Object.prototype, c instanceof A, typeof c.m]`), - ).toEqual(['{"x":1}', { x: 1 }, true, false, "undefined"]) - }) -}) - -describe("unsupported features", () => { - const message = async (code: string) => { - const result = await run(code) - if (result.ok) throw new Error("expected an error") - return result.error.message - } - - test("private fields", async () => { - expect(await message("class A { #x = 1 }")).toStartWith("SyntaxError: Private class members (#name) are not supported. Use a regular property instead.") - }) - - test("private methods", async () => { - expect(await message("class A { #m() {} }")).toStartWith("SyntaxError: Private class members (#name) are not supported. Use a regular property instead.") - }) - - test("#x in o", async () => { - expect(await message("class A { has(o) { return #x in o } }")).toStartWith("SyntaxError: Private class members (#name) are not supported. Use a regular property instead.") - }) - - test("static blocks", async () => { - expect(await message("class A { static { } }")).toStartWith("SyntaxError: Class static blocks are not supported. Assign static fields instead.") - }) - - test("new.target", async () => { - expect(await message("function f() { return new.target }\nreturn f()")).toStartWith("SyntaxError: new.target is not supported.") - }) - - test("decorators", async () => { - expect(await message("class A { @dec m() {} }")).toStartWith("SyntaxError: Decorators are not supported.") - }) - - test("extends null", async () => { - expect(await message("class A extends null {}")).toStartWith("TypeError: Classes extending null are not supported.") - }) - - test("new on a plain function", async () => { - expect(await message("function f() {}\nreturn new f()")).toStartWith("TypeError: f is not a constructor: only classes can be constructed with new. Use a class, or call it as a function that returns an object.") - }) - - test("calling a class", async () => { - expect(await message("class A {}\nreturn A()")).toStartWith("TypeError: Class constructor A cannot be invoked without 'new'") - }) - - test("extending a built-in", async () => { - expect(await message("class A extends Map {}")).toStartWith("TypeError: Extending the built-in Map is not supported. Only classes and Error types can be extended.") - }) - - test("this before super()", async () => { - expect(await message("class A {}\nclass B extends A { constructor() { this.x = 1; super() } }\nreturn new B()")).toStartWith("ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor") - }) - - test("super() twice", async () => { - expect(await message("class A {}\nclass B extends A { constructor() { super(); super() } }\nreturn new B()")).toStartWith("ReferenceError: Super constructor may only be called once") - }) - - test("super() in an arrow", async () => { - expect(await message("class A {}\nclass B extends A { constructor() { const f = () => super(); f() } }\nreturn new B()")).toStartWith("SyntaxError: super() inside an arrow function is not supported. Call super() directly in the constructor.") - }) - - test("destructuring into super.x", async () => { - expect(await message("class A {}\nclass B extends A { m() { [super.x] = [1] } }\nreturn new B().m()")).toStartWith("SyntaxError: Destructuring into super.x is not supported.") - }) - - test("a static member named prototype", async () => { - expect(await message("class A { static [\"prototype\"]() {} }")).toStartWith("TypeError: Classes may not have a static property named 'prototype'.") - }) -}) diff --git a/packages/codemode/test/constructor-test262.test.ts b/packages/codemode/test/constructor-test262.test.ts deleted file mode 100644 index c038f3f21c3..00000000000 --- a/packages/codemode/test/constructor-test262.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Portions adapted from Test262 at revision 250f204f23a9249ff204be2baec29600faae7b75: - * - test/built-ins/RegExp/S15.10.7_A3_T1.js - * - test/built-ins/RegExp/S15.10.7_A3_T2.js - * - test/built-ins/Object/S15.2.2.1_A1_T1.js - * - * Copyright 2009 the Sputnik authors. All rights reserved. - * Test262 portions are governed by the BSD license in LICENSE.test262. - * - * Only the instance-side assertions are ported. Test262 otherwise reaches `constructor` through - * `X.prototype.constructor`, boxed primitives (`new Object(1)`), `Function`, `isPrototypeOf`, or - * `.call`, none of which CodeMode exposes: values have no prototype chain, so `x.constructor` - * resolves directly to the owning built-in. - */ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" - -const value = async (code: string) => { - const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} })) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -describe("constructor Test262 parity", () => { - test("test/built-ins/RegExp/S15.10.7_A3_T1.js", async () => { - expect( - await value(` - const __re = /[^a]*/ - return [typeof __re, __re.constructor === RegExp, __re instanceof RegExp] - `), - ).toEqual(["object", true, true]) - }) - - test("test/built-ins/RegExp/S15.10.7_A3_T2.js", async () => { - expect( - await value(` - const __re = new RegExp() - return [typeof __re, __re.constructor === RegExp, __re instanceof RegExp] - `), - ).toEqual(["object", true, true]) - }) - - test("test/built-ins/Object/S15.2.2.1_A1_T1.js", async () => { - expect( - await value(` - const obj = new Object() - return [obj !== undefined, obj.constructor === Object] - `), - ).toEqual([true, true]) - }) - - test("every built-in reports itself for its own values", async () => { - expect( - await value(` - return [ - [].constructor === Array, "".constructor === String, (1).constructor === Number, true.constructor === Boolean, - new Date(0).constructor === Date, new Map().constructor === Map, new Set().constructor === Set, - new URL("https://a.b/").constructor === URL, new URLSearchParams("a=1").constructor === URLSearchParams, - Promise.resolve(1).constructor === Promise, new TypeError("x").constructor === TypeError, - new RangeError("x").constructor === RangeError, new AggregateError([]).constructor === AggregateError, - ] - `), - ).toEqual(Array(13).fill(true)) - }) -}) diff --git a/packages/codemode/test/date-test262.test.ts b/packages/codemode/test/date-test262.test.ts deleted file mode 100644 index ffda8cef4bf..00000000000 --- a/packages/codemode/test/date-test262.test.ts +++ /dev/null @@ -1,266 +0,0 @@ -/* - * Portions adapted from Test262 at revision 250f204f23a9249ff204be2baec29600faae7b75: - * - test/built-ins/Date/prototype/setTime/arg-to-number.js - * - test/built-ins/Date/prototype/setTime/arg-to-number-err.js - * - test/built-ins/Date/prototype/setTime/new-value-time-clip.js - * - test/built-ins/Date/prototype/setMilliseconds/this-value-valid-date.js - * - test/built-ins/Date/prototype/setUTCMilliseconds/this-value-valid-date.js - * - test/built-ins/Date/prototype/setSeconds/this-value-valid-date-sec.js - * - test/built-ins/Date/prototype/setSeconds/this-value-valid-date-ms.js - * - test/built-ins/Date/prototype/setUTCSeconds/this-value-valid-date-sec.js - * - test/built-ins/Date/prototype/setUTCSeconds/this-value-valid-date-ms.js - * - test/built-ins/Date/prototype/setMinutes/this-value-valid-date.js - * - test/built-ins/Date/prototype/setUTCMinutes/this-value-valid-date.js - * - test/built-ins/Date/prototype/setHours/this-value-valid-date-hour.js - * - test/built-ins/Date/prototype/setHours/this-value-valid-date-min.js - * - test/built-ins/Date/prototype/setHours/this-value-valid-date-sec.js - * - test/built-ins/Date/prototype/setHours/this-value-valid-date-ms.js - * - test/built-ins/Date/prototype/setUTCHours/this-value-valid-date-hour.js - * - test/built-ins/Date/prototype/setUTCHours/this-value-valid-date-min.js - * - test/built-ins/Date/prototype/setUTCHours/this-value-valid-date-sec.js - * - test/built-ins/Date/prototype/setUTCHours/this-value-valid-date-ms.js - * - test/built-ins/Date/prototype/setDate/this-value-valid-date.js - * - test/built-ins/Date/prototype/setUTCDate/date-value-read-before-tonumber-when-date-is-valid.js - * - test/built-ins/Date/prototype/setMonth/this-value-valid-date-month.js - * - test/built-ins/Date/prototype/setMonth/this-value-valid-date-date.js - * - test/built-ins/Date/prototype/setUTCMonth/this-value-valid-date-month.js - * - test/built-ins/Date/prototype/setUTCMonth/this-value-valid-date-date.js - * - test/built-ins/Date/prototype/setFullYear/this-value-valid-date-year.js - * - test/built-ins/Date/prototype/setFullYear/this-value-valid-date-month.js - * - test/built-ins/Date/prototype/setFullYear/this-value-valid-date-date.js - * - test/built-ins/Date/prototype/setFullYear/this-value-invalid-date.js - * - test/built-ins/Date/prototype/setFullYear/arg-year-to-number-err.js - * - test/built-ins/Date/prototype/setFullYear/arg-month-to-number-err.js - * - test/built-ins/Date/prototype/setFullYear/arg-date-to-number-err.js - * - test/built-ins/Date/prototype/setUTCFullYear/date-value-read-before-tonumber-when-date-is-invalid.js - * - test/built-ins/Date/prototype/setMonth/arg-coercion-order.js - * - test/language/expressions/addition/S11.6.1_A2.2_T2.js - * - * Copyright (C) 2016 the V8 project authors. All rights reserved. - * Copyright (C) 2021 Kevin Gibbons. All rights reserved. - * Copyright (C) 2024 André Bargull. All rights reserved. - * Copyright 2009 the Sputnik authors. All rights reserved. - * Test262 portions are governed by the BSD license in LICENSE.test262. - */ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" - -const value = async (code: string) => { - const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} })) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -describe("Date setter Test262 parity", () => { - test("UTC setters mutate every supported component and return the new time", async () => { - expect( - await value(` - const create = () => new Date(Date.UTC(2000, 0, 2, 3, 4, 5, 6)) - const result = [] - let date = create() - result.push([date.setTime(1234) === date.getTime(), date.getTime()]) - date = create() - result.push([date.setUTCMilliseconds(10) === date.getTime(), date.getUTCMilliseconds()]) - date = create() - result.push([date.setUTCSeconds(10, 11) === date.getTime(), date.getUTCSeconds(), date.getUTCMilliseconds()]) - date = create() - result.push([date.setUTCMinutes(10, 11, 12) === date.getTime(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds()]) - date = create() - result.push([date.setUTCHours(10, 11, 12, 13) === date.getTime(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds()]) - date = create() - result.push([date.setUTCDate(10) === date.getTime(), date.getUTCDate()]) - date = create() - result.push([date.setUTCMonth(6, 10) === date.getTime(), date.getUTCMonth(), date.getUTCDate()]) - date = create() - result.push([date.setUTCFullYear(2020, 6, 10) === date.getTime(), date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()]) - return result - `), - ).toEqual([ - [true, 1234], - [true, 10], - [true, 10, 11], - [true, 10, 11, 12], - [true, 10, 11, 12, 13], - [true, 10], - [true, 6, 10], - [true, 2020, 6, 10], - ]) - }) - - test("local setters mutate every supported component", async () => { - expect( - await value(` - const create = () => new Date(2000, 0, 2, 3, 4, 5, 6) - const result = [] - let date = create() - date.setMilliseconds(10) - result.push(date.getMilliseconds()) - date = create() - date.setSeconds(10, 11) - result.push([date.getSeconds(), date.getMilliseconds()]) - date = create() - date.setMinutes(10, 11, 12) - result.push([date.getMinutes(), date.getSeconds(), date.getMilliseconds()]) - date = create() - date.setHours(10, 11, 12, 13) - result.push([date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()]) - date = create() - date.setDate(10) - result.push(date.getDate()) - date = create() - date.setMonth(6, 10) - result.push([date.getMonth(), date.getDate()]) - date = create() - date.setFullYear(2020, 6, 10) - result.push([date.getFullYear(), date.getMonth(), date.getDate()]) - return result - `), - ).toEqual([10, [10, 11], [10, 11, 12], [10, 11, 12, 13], 10, [6, 10], [2020, 6, 10]]) - }) - - test("setter arguments use numeric coercion in source order", async () => { - expect( - await value(` - const calls = [] - const date = new Date(0) - const returned = date.setUTCSeconds( - { valueOf: () => { calls.push("seconds"); return "2" } }, - { valueOf: () => { calls.push("milliseconds"); return true } }, - ) - const fallback = new Date(0) - fallback.setTime({ valueOf: () => ({}), toString: () => "3" }) - return [returned === date.getTime(), date.getUTCSeconds(), date.getUTCMilliseconds(), fallback.getTime(), calls] - `), - ).toEqual([true, 2, 1, 3, ["seconds", "milliseconds"]]) - }) - - test("setters snapshot the Date before coercing arguments", async () => { - expect( - await value(` - const date = new Date(Date.UTC(2000, 5, 15, 1, 2, 3, 4)) - date.setUTCFullYear({ - valueOf: () => { - date.setTime(Date.UTC(2020, 11, 20)) - return 2001 - }, - }) - - const invalid = new Date(NaN) - invalid.setUTCFullYear({ valueOf: () => { invalid.setTime(0); return 1 } }) - - const effects = [] - const staysInvalid = new Date(NaN) - const result = staysInvalid.setUTCMonth( - { valueOf: () => { effects.push("month"); return 0 } }, - { valueOf: () => { effects.push("date"); return 1 } }, - ) - return [ - date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), - invalid.getUTCFullYear(), invalid.getUTCMonth(), invalid.getUTCDate(), - Number.isNaN(result), Number.isNaN(staysInvalid.getTime()), effects, - ] - `), - ).toEqual([2001, 5, 15, 1, 0, 1, true, true, ["month", "date"]]) - }) - - test("setFullYear recovers an invalid local Date", async () => { - expect( - await value(` - const year = new Date(NaN) - const yearResult = year.setFullYear(2016) - const month = new Date(NaN) - const monthResult = month.setFullYear(2016, 6) - const day = new Date(NaN) - const dayResult = day.setFullYear(2016, 6, 7) - return [ - yearResult === year.getTime(), year.getFullYear(), year.getMonth(), year.getDate(), - monthResult === month.getTime(), month.getFullYear(), month.getMonth(), month.getDate(), - dayResult === day.getTime(), day.getFullYear(), day.getMonth(), day.getDate(), - ] - `), - ).toEqual([true, 2016, 0, 1, true, 2016, 6, 1, true, 2016, 6, 7]) - }) - - test("abrupt argument coercion stops later coercion and preserves the Date", async () => { - expect( - await value(` - const calls = [] - const failure = { valueOf: () => { throw new Error("stop") } } - const counter = { valueOf: () => { calls.push("counter"); return 1 } } - const results = [] - - const time = new Date(0) - try { time.setTime(failure) } catch (error) { results.push(error.message) } - results.push(time.getTime()) - - const year = new Date(0) - try { year.setFullYear(failure, counter, counter) } catch (error) { results.push(error.message) } - results.push(year.getTime()) - - const month = new Date(0) - try { month.setFullYear(0, failure, counter) } catch (error) { results.push(error.message) } - results.push(month.getTime()) - - const day = new Date(0) - try { day.setFullYear(0, 0, failure) } catch (error) { results.push(error.message) } - results.push(day.getTime(), calls) - return results - `), - ).toEqual(["stop", 0, "stop", 0, "stop", 0, "stop", 0, []]) - }) - - test("omitted arguments, explicit undefined, extra arguments, and TimeClip match native behavior", async () => { - expect( - await value(` - const calls = [] - const omittedOptional = new Date(0) - const explicitUndefined = new Date(0) - const noArgument = new Date(0) - const extra = new Date(0) - const clipped = new Date(0) - const badPrimitive = new Date(0) - let conversionError = "" - try { - badPrimitive.setTime({ valueOf: () => ({}), toString: () => ({}) }) - } catch (error) { - conversionError = error.name - } - return [ - omittedOptional.setUTCSeconds(1), - Number.isNaN(explicitUndefined.setUTCSeconds(1, undefined)), - Number.isNaN(noArgument.setTime()), - extra.setTime(1, { valueOf: () => { calls.push("extra"); return 2 } }), - calls, - Number.isNaN(clipped.setTime(8.64e15 + 1)), - Number.isNaN(clipped.getTime()), - conversionError, - ] - `), - ).toEqual([1000, true, true, 1, [], true, true, "TypeError"]) - }) -}) - -describe("Date default primitive Test262 parity", () => { - test("addition and loose equality use the Date string primitive", async () => { - expect( - await value(` - const date = new Date(0) - const text = String(date) - return [ - date + date === text + text, - date + 0 === text + "0", - date + true === text + "true", - date == text, - text == date, - date == Number(date), - Number(date) == date, - date != Number(date), - date == date, - date == new Date(0), - date == null, - ] - `), - ).toEqual([true, true, true, true, true, false, false, true, true, false, false]) - }) -}) diff --git a/packages/codemode/test/descriptors.test.ts b/packages/codemode/test/descriptors.test.ts deleted file mode 100644 index 6f7293955f9..00000000000 --- a/packages/codemode/test/descriptors.test.ts +++ /dev/null @@ -1,265 +0,0 @@ -import { describe, expect, test } from "bun:test" -import { runProgram } from "./run-program.js" - -// The property descriptor API: Object.defineProperty(ies), getOwnPropertyDescriptor(s), getOwnPropertyNames, and -// Object.create's second argument, over plain objects, arrays, functions and built-ins. - -const value = (code: string) => { - const result = runProgram(code) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - expect(runProgram(code, { roundTrip: { every: 1, max: 20_000 } })).toEqual(result) - return result.value -} -const error = (code: string) => { - const result = runProgram(code) - if (result.ok) throw new Error(`expected failure, got value ${JSON.stringify(result.value)}`) - return result.error.message -} - -describe("Object.defineProperty", () => { - test("data properties default to false attributes, and read-only ones refuse writes", () => { - expect( - value(`const o = {} - Object.defineProperty(o, "x", { value: 1 }) - let refused - try { o.x = 2 } catch (e) { refused = e.message } - return [o.x, Object.keys(o), refused, Object.getOwnPropertyDescriptor(o, "x")]`), - ).toEqual([ - 1, - [], - "Cannot assign to read only property 'x'.", - { value: 1, writable: false, enumerable: false, configurable: false }, - ]) - }) - - test("accessors from descriptors, with a getter and a setter", () => { - expect( - value(`const o = { _v: 1 } - const r = Object.defineProperty(o, "v", { get() { return this._v }, set(x) { this._v = x * 2 }, enumerable: true, configurable: true }) - o.v = 5 - const d = Object.getOwnPropertyDescriptor(o, "v") - return [r === o, o.v, typeof d.get, typeof d.set, d.enumerable, d.configurable, Object.keys(d)]`), - ).toEqual([true, 10, "function", "function", true, true, ["get", "set", "enumerable", "configurable"]]) - }) - - test("the transitions ValidateAndApplyPropertyDescriptor allows and refuses", () => { - expect( - value(`const o = {} - Object.defineProperty(o, "a", { value: 1, configurable: true }) - Object.defineProperty(o, "a", { get() { return 2 } }) - const first = o.a - Object.defineProperty(o, "a", { value: 3 }) - const d = Object.getOwnPropertyDescriptor(o, "a") - Object.defineProperty(o, "b", { value: NaN }) - Object.defineProperty(o, "b", { value: NaN }) - Object.defineProperty(o, "c", { get() { return 1 } }) - const refusals = [] - for (const [key, desc] of [["b", { value: 1 }], ["b", { writable: true }], ["c", { value: 1 }], ["c", { get() {} }], ["c", { enumerable: true }], ["c", { configurable: true }]]) { - try { Object.defineProperty(o, key, desc) } catch (e) { refusals.push(e.message) } - } - Object.defineProperty(o, "z", { value: 0, writable: true }) - Object.defineProperty(o, "z", { value: -0 }) - return [first, o.a, d.writable, d.configurable, refusals.length, Object.is(o.z, -0), refusals[0]]`), - ).toEqual([2, 3, false, true, 6, true, "Cannot redefine property: b"]) - }) - - test("a generic descriptor updates an accessor in place", () => { - expect( - value(`const o = { get x() { return 1 } } - Object.defineProperty(o, "x", { enumerable: false }) - return [o.x, Object.keys(o), typeof Object.getOwnPropertyDescriptor(o, "x").get]`), - ).toEqual([1, [], "function"]) - }) - - test("descriptor objects are read through getters and the prototype chain", () => { - expect( - value(`const log = [] - const desc = Object.create({ get value() { log.push("value"); return 7 } }) - Object.defineProperty(desc, "enumerable", { get() { log.push("enumerable"); return true } }) - const o = Object.defineProperty({}, "x", desc) - return [o.x, Object.keys(o), log]`), - ).toEqual([7, ["x"], ["enumerable", "value"]]) - }) - - test("bad descriptors and targets are TypeErrors", () => { - expect(error(`Object.defineProperty({}, "x", 1)`)).toContain("Property description must be an object") - expect(error(`Object.defineProperty({}, "x", { get: 1 })`)).toContain("Getter must be a function") - expect(error(`Object.defineProperty({}, "x", { get() {}, value: 1 })`)).toContain("Cannot both specify accessors") - expect(error(`Object.defineProperty(1, "x", {})`)).toContain("Object.defineProperty called on non-object") - expect(error(`Object.defineProperty(Object.preventExtensions({}), "x", { value: 1 })`)).toContain( - "object is not extensible", - ) - }) - - test("frozen and sealed objects keep their accessors, and setters still run", () => { - expect( - value(`const o = Object.freeze({ n: 1, get x() { return this.n }, set x(v) { log.push(v) } }) - const log = [] - o.x = 5 - return [o.x, log, Object.isFrozen(o), Object.getOwnPropertyDescriptor(o, "x").configurable]`), - ).toEqual([1, [5], true, false]) - }) -}) - -describe("arrays", () => { - test("elements take only the array's shared attributes, never accessors", () => { - expect(error(`Object.defineProperty([1], 0, { get() { return 1 } })`)).toContain( - "Accessor properties are not supported on array elements", - ) - expect(error(`Object.defineProperty([1], 0, { value: 2, writable: false })`)).toContain( - "Array elements share their attributes", - ) - expect( - value(`const a = [1, 2] - Object.defineProperty(a, 0, { value: 9 }) - Object.defineProperty(a, 2, { value: 3, writable: true, enumerable: true, configurable: true }) - Object.defineProperty(a, "length", { value: 2 }) - Object.defineProperty(a, "extra", { get() { return this.length } }) - return [a, a.extra]`), - ).toEqual([[9, 2], 2]) - }) - - test("a frozen array refuses new values and keeps its elements", () => { - expect(error(`Object.defineProperty(Object.freeze([10]), 0, { value: 99 })`)).toContain( - "Cannot redefine property: 0", - ) - expect(error(`Object.defineProperty(Object.freeze([10]), "length", { value: 5 })`)).toContain( - "Cannot redefine property", - ) - expect(value(`const a = Object.freeze([10]); Object.defineProperty(a, 0, { value: 10 }); return a`)).toEqual([10]) - expect(error(`Object.defineProperty([1], "length", { writable: false })`)).toContain( - "Making an array's length read-only", - ) - }) -}) - -describe("reading descriptors and names", () => { - test("getOwnPropertyDescriptor(s) and getOwnPropertyNames", () => { - expect( - value(`function f(a, b) {} - return [ - Object.getOwnPropertyNames({ b: 1, a: 2, 1: 3 }), - Object.getOwnPropertyNames([5]), - Object.getOwnPropertyNames(f), - Object.getOwnPropertyNames("ab"), - Object.getOwnPropertyDescriptor("ab", 1), - Object.getOwnPropertyDescriptor("ab", "length"), - Object.getOwnPropertyDescriptor(1, "x"), - Object.keys(Object.getOwnPropertyDescriptors({ a: 1, get b() { return 2 } })), - Object.getOwnPropertyDescriptor([7], 0), - ]`), - ).toEqual([ - ["1", "b", "a"], - ["0", "length"], - ["length", "name"], - ["0", "1", "length"], - { value: "b", writable: false, enumerable: true, configurable: false }, - { value: 2, writable: false, enumerable: false, configurable: false }, - null, - ["a", "b"], - { value: 7, writable: true, enumerable: true, configurable: true }, - ]) - expect(error(`Object.getOwnPropertyDescriptor(null, "x")`)).toContain("cannot convert null") - }) - - test("built-in accessors show as callable companion functions", () => { - expect( - value(`const d = Object.getOwnPropertyDescriptor(Map.prototype, "size") - let refused - try { d.get.call({}) } catch (e) { refused = e instanceof TypeError } - Object.defineProperty(Map.prototype, "size", d) - const r = Object.getOwnPropertyDescriptor(RegExp.prototype, "lastIndex") - return [d.get.name, d.get.call(new Map([[1, 2]])), d.set, refused, new Map([[1, 1], [2, 2]]).size, typeof r]`), - ).toEqual(["get size", 1, null, true, 2, "object"]) - }) - - test("a built-in accessor copied to a plain object, and a mixed native and program slot", () => { - expect( - value(`const o = {} - Object.defineProperty(o, "flags", Object.getOwnPropertyDescriptor(RegExp.prototype, "flags")) - const u = new URL("https://a.test/x") - Object.defineProperty(URL.prototype, "pathname", { set(v) { log.push(v) } }) - const log = [] - u.pathname = "/y" - const d = Object.getOwnPropertyDescriptor(URL.prototype, "pathname") - return [typeof Object.getOwnPropertyDescriptor(o, "flags").get, u.pathname, log, typeof d.get, typeof d.set]`), - ).toEqual(["function", "/x", ["/y"], "function", "function"]) - }) - - test("built-ins' own properties follow the usual rules", () => { - expect(error(`Object.defineProperty(Math, "PI", { value: 3 })`)).toContain("Cannot redefine property: PI") - expect(value(`function f() {}; Object.defineProperty(f, "name", { value: "g" }); return f.name`)).toBe("g") - expect( - value(`Object.defineProperty(String.prototype, "first", { get() { return this[0] }, configurable: true }) - Object.defineProperty(Number.prototype, "double", { get() { return this * 2 }, set(v) { log.push(v) }, configurable: true }) - const log = [] - ;(5).double = 1 - return ["abc".first, (4).double, log]`), - ).toEqual(["a", 8, [1]]) - }) -}) - -describe("Object.create and defineProperties", () => { - test("Object.create takes descriptors, and defineProperties reads them all before defining", () => { - expect( - value(`const log = [] - const o = Object.create({ inherited: 1 }, { a: { value: 1, enumerable: true }, b: { get() { return 2 } } }) - const t = {} - try { - Object.defineProperties(t, { x: { value: 1 }, y: { get value() { log.push("y"); return 2 } }, z: 5 }) - } catch (e) { log.push(e.message) } - return [o.a, o.b, o.inherited, Object.keys(o), Object.getOwnPropertyNames(t), log]`), - ).toEqual([1, 2, 1, ["a"], [], ["y", "Property description must be an object: a number"]]) - }) - - test("defineProperties fails after the earlier ones are defined", () => { - expect( - value(`const t = Object.defineProperty({}, "b", { value: 1 }) - try { Object.defineProperties(t, { a: { value: 1 }, b: { value: 2 } }) } catch (e) {} - return Object.getOwnPropertyNames(t)`), - ).toEqual(["b", "a"]) - }) -}) - -describe("defineProperty edge cases", () => { - test("a refused length define leaves length alone, and a frozen array's length cannot change", () => { - expect( - value(`const a = [1] - let refused - try { Object.defineProperty(a, "length", { value: 5, writable: false }) } catch (e) { refused = e.message } - const f = Object.freeze([1]) - let frozen - try { Object.defineProperty(f, "length", { value: 5 }) } catch (e) { frozen = e.message } - return [a.length, refused, f.length, frozen]`), - ).toEqual([ - 1, - "Making an array's length read-only is not supported; use Object.freeze.", - 1, - "Cannot redefine property: length", - ]) - }) - - test("a Uint8Array index past the end is refused", () => { - expect( - error( - `Object.defineProperty(new Uint8Array(2), 5, { value: 99, writable: true, enumerable: true, configurable: true })`, - ), - ).toBe("TypeError: Cannot redefine property: 5 (line 1, col 1)") - }) - - test("defineProperties converts its argument with ToObject", () => { - expect(error(`Object.defineProperties({}, "ab")`)).toBe( - "TypeError: Property description must be an object: a string (line 1, col 1)", - ) - expect(value(`return [Object.defineProperties({ a: 1 }, 5), Object.defineProperties({ b: 2 }, true)]`)).toEqual([ - { a: 1 }, - { b: 2 }, - ]) - expect(error(`Object.defineProperties({}, null)`)).toBe("TypeError: Cannot convert null to object (line 1, col 1)") - }) - - test("defining a value refuses a cycle the way an assignment does", () => { - const assigned = error(`const a = {}; a.self = a`) - expect(error(`const a = {}; Object.defineProperty(a, "self", { value: a })`)).toBe(assigned) - }) -}) diff --git a/packages/codemode/test/enumeration.test.ts b/packages/codemode/test/enumeration.test.ts index 382ba3bd09e..197e5688d9a 100644 --- a/packages/codemode/test/enumeration.test.ts +++ b/packages/codemode/test/enumeration.test.ts @@ -74,154 +74,3 @@ describe("Object.keys over tool references", () => { expect(nested.message).toContain("Use Object.keys(tools) for its names") }) }) - -describe("Object.keys over arrays", () => { - test("returns index strings, like JS", async () => { - expect(await value(`return Object.keys(["a", "b", "c"])`)).toEqual(["0", "1", "2"]) - expect(await value(`return Object.keys([])`)).toEqual([]) - }) - - test("objects keep their own enumerable keys", async () => { - expect(await value(`return Object.keys({ a: 1, b: 2 })`)).toEqual(["a", "b"]) - }) - - test("non-object inputs follow ToObject, and nullish inputs name what was received", async () => { - expect( - await value(`return [Object.keys("ab"), Object.entries(42), Object.keys(() => 1), Object.keys(true)]`), - ).toEqual([["0", "1"], [], [], []]) - expect(await value(`try { Object.values(null) } catch (e) { return [e.name, e.message] }`)).toEqual([ - "TypeError", - "Object.values(...) cannot convert null to an object.", - ]) - expect((await error(`return Object.keys(tools.github.list_issues({ value: "x" }))`)).message).toContain( - "received an un-awaited Promise", - ) - expect(await value(`const { a, size } = new Map(); return [a, size]`)).toEqual([null, 0]) - expect((await error(`return Array.from(7)`)).message).toContain("received a number.") - expect(await value(`return [(() => 1).x, Object.keys(() => 1)]`)).toEqual([null, []]) - }) -}) - -describe("for...in", () => { - test("iterates own enumerable keys of a plain object with break/continue", async () => { - expect( - await value(` - const seen = [] - for (const key in { a: 1, b: 2, c: 3, d: 4 }) { - if (key === "b") continue - if (key === "d") break - seen.push(key) - } - return seen - `), - ).toEqual(["a", "c"]) - }) - - test("iterates index strings over arrays", async () => { - expect( - await value(` - const indexes = [] - for (const i in ["x", "y", "z"]) { - if (i === "2") break - indexes.push(i) - } - return indexes - `), - ).toEqual(["0", "1"]) - }) - - test("supports let declarations and bare identifiers", async () => { - expect( - await value(` - let last = "" - for (let key in { a: 1, b: 2 }) last = key - return last - `), - ).toBe("b") - expect( - await value(` - let key = "before" - for (key in { only: 1 }) {} - return key - `), - ).toBe("only") - }) - - test("enumerates namespaces and tools from the supplied tools", async () => { - expect( - await value(` - const names = [] - for (const ns in tools) { - for (const name in tools[ns]) names.push(ns + "." + name) - } - return names - `), - ).toEqual(["github.list_issues", "github.get_issue", "memory.search", "playwright.navigate"]) - }) - - test("non-object values enumerate like JS: strings by index, everything else nothing", async () => { - expect( - await value(` - const out = [] - for (const key in "ab") out.push(key) - for (const key in 42) out.push(key) - for (const key in null) out.push(key) - for (const key in undefined) out.push(key) - for (const key in new Map([[1, 2]])) out.push(key) - for (const key in Math) out.push(key) - return out - `), - ).toEqual(["0", "1"]) - expect((await error(`for (const key in tools.github.list_issues({ value: "x" })) {}`)).message).toContain( - "un-awaited Promise", - ) - }) - - const forIn = (target: string, setup = "") => - value(`${setup}; const out = []; for (const key in ${target}) out.push(key); return out`) - - test("visits inherited enumerable keys after own keys", async () => { - expect(await forIn("o", "const p = { inh: 1 }; const o = Object.create(p); o.own = 2")).toEqual(["own", "inh"]) - }) - - test("walks every level, skipping keys a nearer level already has", async () => { - expect( - await forIn( - "o", - `const top = { a: 1, top: 1 } - const mid = Object.create(top); mid.a = 2; mid.mid = 2 - const o = Object.create(mid); o.own = 3; o.mid = 3`, - ), - ).toEqual(["own", "mid", "a", "top"]) - }) - - test("orders integer-like keys first on each level", async () => { - expect( - await forIn("o", `const p = { b: 1, 10: 1, 2: 1 }; const o = Object.create(p); o.z = 1; o[5] = 1; o[1] = 1`), - ).toEqual(["1", "5", "z", "2", "10", "b"]) - }) - - test("a non-enumerable nearer property shadows an enumerable inherited one", async () => { - // An array's own length and Array.prototype.push are non-enumerable. - const setup = "Object.prototype.length = 1; Object.prototype.push = 2; Object.prototype.extra = 3" - expect(await forIn("[5]", setup)).toEqual(["0", "extra"]) - expect(await forIn("Object.create([5])", setup)).toEqual(["0", "extra"]) - }) - - test("a null prototype ends the walk", async () => { - expect(await forIn("o", "const o = Object.create(null); o.a = 1")).toEqual(["a"]) - expect(await forIn("Object.create(null)")).toEqual([]) - }) - - test("arrays and strings only visit their indexes, since built-in methods are non-enumerable", async () => { - expect(await forIn("[7, 8]")).toEqual(["0", "1"]) - expect(await forIn(`"ab"`)).toEqual(["0", "1"]) - }) - - test("visits enumerable properties a program adds to a built-in prototype", async () => { - expect(await forIn("[7, 8]", "Array.prototype.extra = 1")).toEqual(["0", "1", "extra"]) - expect(await forIn(`"ab"`, "Array.prototype.extra = 1")).toEqual(["0", "1"]) - expect(await forIn(`"ab"`, "String.prototype.extra = 1")).toEqual(["0", "1", "extra"]) - expect(await forIn("5", "Number.prototype.extra = 1")).toEqual(["extra"]) - }) -}) diff --git a/packages/codemode/test/errors.test.ts b/packages/codemode/test/errors.test.ts deleted file mode 100644 index 5716220eb4f..00000000000 --- a/packages/codemode/test/errors.test.ts +++ /dev/null @@ -1,310 +0,0 @@ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" - -// One failure is one program error object, and rethrowing it keeps the diagnostic it started with. -const run = (code: string) => Effect.runPromise(CodeMode.execute({ code, tools: {} })) -const value = async (code: string) => { - const result = await run(code) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} -const error = async (code: string) => { - const result = await run(code) - if (result.ok) throw new Error(`expected failure, got value ${JSON.stringify(result.value)}`) - return result.error -} - -describe("source syntax", () => { - test("reports a syntax error with its location and what code must look like", async () => { - expect(await error(`const = 1`)).toEqual({ - kind: "ParseError", - message: - "SyntaxError: Unexpected token. Code must be plain JavaScript written as a program body. (line 1, col 7)", - location: { line: 1, column: 7 }, - }) - }) - - test("explains that exports aren't available", async () => { - expect(await error(`const x = 1\nexport { x }`)).toEqual({ - kind: "ParseError", - message: "SyntaxError: Exports aren't available. Return the result instead. (line 2, col 1)", - location: { line: 2, column: 1 }, - }) - }) - - test("rejects TypeScript-only syntax", async () => { - const failure = await error(`const value: number = 1; return value`) - expect(failure.kind).toBe("ParseError") - expect(failure.message).toEndWith("Code must be plain JavaScript written as a program body. (line 1, col 12)") - expect(failure.location).toEqual({ line: 1, column: 12 }) - }) - - test("locates a syntax error on a later line", async () => { - const failure = await error("const a = 1\nconst b = 2\nreturn a +* b") - expect(failure.message).toBe( - "SyntaxError: Unexpected token. Code must be plain JavaScript written as a program body. (line 3, col 11)", - ) - expect(failure.location).toEqual({ line: 3, column: 11 }) - }) - - test("rejects empty code", async () => { - expect(await error(" \n\t")).toEqual({ kind: "ParseError", message: "Code cannot be empty." }) - }) -}) - -describe("error identity", () => { - test("Error.isError is true for every Error value and nothing else", async () => { - expect( - await value(` - const caught = (() => { try { null.foo } catch (error) { return error } })() - return [Error.isError(new Error("x")), Error.isError(new RangeError("x")), Error.isError(caught), - Error.isError({ name: "Error", message: "x" }), Error.isError("Error"), Error.isError(null)] - `), - ).toEqual([true, true, true, false, false, false]) - }) - - test("awaiting the same rejected promise twice yields the same error object", async () => { - expect( - await value(` - const fail = async () => { null.foo } - const p = fail() - const a = await p.catch((e) => e) - try { await p } catch (b) { return a === b } - `), - ).toBe(true) - }) - - test("allSettled reasons for the same failure are identical", async () => { - expect( - await value(` - const fail = async () => { null.foo } - const p = fail() - const [a, b] = await Promise.allSettled([p, p]) - return [a.reason === b.reason, a.reason.name, a.reason.message] - `), - ).toEqual([true, "TypeError", "Cannot read properties of null (reading 'foo')."]) - }) - - test("Promise.any collects the same object a direct catch would", async () => { - expect( - await value(` - const fail = async () => { null.foo } - const p = fail() - const direct = await p.catch((e) => e) - try { await Promise.any([p]) } catch (aggregate) { return aggregate.errors[0] === direct } - `), - ).toBe(true) - }) -}) - -describe("rethrown interpreter failures", () => { - test("keep their diagnostic kind and source location", async () => { - const failure = await error(`try { Symbol + 1 } catch (e) { throw e }`) - expect(failure.kind).toBe("InvalidDataValue") - expect(failure.message).toStartWith("TypeError: Binary operators require data values. (line ") - expect(failure.location).toBeDefined() - }) - - test("keep their location through a rejection handler", async () => { - const direct = await error(` - const fail = async () => { null.foo } - await fail() - `) - const rethrown = await error(` - const fail = async () => { null.foo } - await fail().catch((e) => { throw e }) - `) - expect(direct.location).toBeDefined() - expect(rethrown).toEqual(direct) - }) -}) - -describe("uncaught program throws", () => { - test("an Error reports as name: message", async () => { - const failure = await error(`throw new TypeError("bad input")`) - expect(failure).toEqual({ kind: "ExecutionFailure", message: "TypeError: bad input" }) - }) - - test("a custom name is honored", async () => { - const failure = await error(`const e = new Error("x"); e.name = "ValidationError"; throw e`) - expect(failure.message).toBe("ValidationError: x") - }) - - test("non-Error values keep the Uncaught prefix", async () => { - expect((await error(`throw "boom"`)).message).toBe("Uncaught: boom") - expect((await error(`throw { code: 7 }`)).message).toBe('Uncaught: {"code":7}') - }) -}) - -describe("stack", () => { - test("names the program's frames innermost first, like V8", async () => { - expect( - await value(`function inner() { return new Error("boom") } -const outer = () => inner() -return outer().stack.split("\\n")`), - ).toEqual(["Error: boom", " at inner (:1:27)", " at outer (:2:21)", " at :3:8"]) - }) - - test("a built-in failure has its location, and a message-less error just its name", async () => { - expect(await value(`try { null.x } catch (e) { return [e.stack, new RangeError().stack] }`)).toEqual([ - "TypeError: Cannot read properties of null (reading 'x').\n at :1:7", - "RangeError\n at :1:45", - ]) - }) - - test("is non-enumerable, so JSON and Object.keys don't change", async () => { - expect( - await value(`const e = new Error("x"); e.code = 1 -return [JSON.stringify(e), Object.keys(e), Object.getOwnPropertyDescriptor(e, "stack")]`), - ).toEqual([ - JSON.stringify({ name: "Error", message: "x", code: 1 }), - ["code"], - { value: "Error: x\n at :1:11", writable: true, enumerable: false, configurable: true }, - ]) - }) - - test("takes its header from the name and message at the first read, then keeps it", async () => { - expect( - await value(`class MyErr extends Error { constructor(m) { super(m); this.name = "MyErr" } } -const late = new Error("y"); late.name = "Late"; late.message = "z" -const first = late.stack -late.name = "After" -const unnamed = new Error("q"); unnamed.name = "" -const empty = new Error(""); empty.name = "N" -const getter = new Error("g"); Object.defineProperty(getter, "name", { get() { return "G" } }) -return [new MyErr("x").stack, first, late.stack, unnamed.stack, empty.stack, getter.stack.split("\\n")[0]]`), - ).toEqual([ - "MyErr: x\n at MyErr (:1:46)\n at :8:9", - "Late: z\n at :2:14", - "Late: z\n at :2:14", - "q\n at :5:17", - "N\n at :6:15", - // A program getter is not run to format a stack; it reads as undefined, as in Bun. - "Error: g", - ]) - }) - - test("an assigned stack replaces it, before or after the first read", async () => { - expect( - await value(`const a = new Error("a"); a.stack = "custom" -const b = new Error("b"); b.stack; b.stack = 1 -return [a.stack, b.stack, Object.getOwnPropertyDescriptor(a, "stack").enumerable]`), - ).toEqual(["custom", 1, false]) - }) - - test("keeps the 10 innermost frames", async () => { - expect( - await value(`function f(n) { return n === 0 ? new Error("deep") : f(n - 1) } -return f(20).stack.split("\\n")`), - ).toEqual(["Error: deep", " at f (:1:34)", ...Array(9).fill(" at f (:1:54)")]) - }) -}) - -describe("source locations", () => { - test("uses the submitted line and 1-based column", async () => { - const failure = await error("const value = 1\nreturn value()") - expect(failure.location).toEqual({ line: 2, column: 8 }) - expect(failure.message).toBe("TypeError: value is not a function. (line 2, col 8)") - }) - - test("names a missing method on a call instead of the previous line", async () => { - const failure = await error(`// Try search with different namespaces -for (const ns of ["github", "tools.github", "tools", ""]) { - const s = await search({query: "star", namespace: ns, limit: 100}).filter((item) => item.path); - return s -}`) - expect(failure.location).toEqual({ line: 3, column: 19 }) - expect(failure.message).toBe("TypeError: search(...).filter is not a function. (line 3, col 19)") - }) -}) - -describe("host errors escaping built-ins", () => { - test("become the same-named program error", async () => { - expect( - await value(` - try { (1).toFixed(200) } catch (e) { return [e.name, e instanceof RangeError, e.message] } - `), - ).toEqual(["RangeError", true, "toFixed() argument must be between 0 and 100"]) - }) - - test("report the location of the call that raised them", async () => { - const failure = await error(`return [1].map((n) => n.toFixed(200))`) - expect(failure.kind).toBe("ExecutionFailure") - expect(failure.message).toBe("RangeError: toFixed() argument must be between 0 and 100 (line 1, col 23)") - }) - - test("a built-in that rejects its arguments before doing any work is located at the call", async () => { - expect((await error(`new Promise(Symbol)`)).message).toEndWith("(line 1, col 1)") - }) - - test("a rejection born inside a promise the built-in created is located at the creating call", async () => { - expect((await error(`return await Promise.all(1)`)).message).toEndWith("(line 1, col 14)") - expect((await error(`return await Promise.race([])`)).message).toEndWith("(line 1, col 14)") - expect((await error(`return await Promise.all({ [Symbol.iterator]: () => ({ next: 1 }) })`)).message).toEndWith( - "(line 1, col 14)", - ) - expect((await error(`let p; p = Promise.resolve().then(() => p); return await p`)).message).toEndWith( - "(line 1, col 12)", - ) - }) - - test("an un-awaited rejection born inside promise machinery keeps its location in the warning", async () => { - const result = await run(`Promise.all(1); return 1`) - expect(result.ok && result.warnings?.[0]?.message).toEndWith( - "TypeError: Promise.all expects a synchronous iterable, received a number. (line 1, col 1)", - ) - }) - - test("a failure inside a built-in called by another built-in is located at the outer call", async () => { - const failure = await error(`return Array.from({ [Symbol.iterator]: () => ({ next: 1 }) })`) - expect(failure.message).toBe("TypeError: Iterator next must be a function. (line 1, col 8)") - }) -}) - -describe("call depth", () => { - test("runaway recursion fails fast with a catchable RangeError", async () => { - const started = Date.now() - expect( - await value(` - const f = (n) => f(n + 1) - try { f(0) } catch (e) { return [e.name, e instanceof RangeError, e.message] } - `), - ).toEqual(["RangeError", true, "Maximum call stack size exceeded"]) - expect(Date.now() - started).toBeLessThan(2000) - }) - - test("uncaught overflow reports the call that overflowed", async () => { - const failure = await error(`const f = (n) => f(n + 1); return f(0)`) - expect(failure.kind).toBe("ExecutionFailure") - expect(failure.message).toBe("RangeError: Maximum call stack size exceeded (line 1, col 18)") - }) - - test("the limit is 10000 nested calls", async () => { - expect(await value(`let depth = 0; const f = () => { depth++; f() }; try { f() } catch { return depth }`)).toBe( - 10000, - ) - expect(await value(`const f = (n) => (n === 0 ? 0 : 1 + f(n - 1)); return f(9000)`)).toBe(9000) - }) - - // Round-trip mode saves and restores the whole VM every slice, which is slow at 10,000 frames deep. - test("recursion through a built-in callback counts", async () => { - const failure = await error(`const f = (n) => [n].map((x) => f(x + 1)); return f(0)`) - expect(failure.message).toStartWith("RangeError: Maximum call stack size exceeded") - }, 15000) - - test("an await resets the depth, so long async chains are fine", async () => { - expect( - await value(` - const page = async (n) => { await null; return n === 0 ? "done" : page(n - 1) } - return await page(3000) - `), - ).toBe("done") - }) - - // Round-trip mode saves and restores the whole VM every slice, which is slow at 10,000 frames deep. - test("an async function that recurses before its first await overflows like JS", async () => { - const failure = await error(`const f = async (n) => f(n + 1); return await f(0)`) - expect(failure.message).toStartWith("RangeError: Maximum call stack size exceeded") - }, 15000) -}) diff --git a/packages/codemode/test/fixtures/build-id.ts b/packages/codemode/test/fixtures/build-id.ts deleted file mode 100644 index a897a977e55..00000000000 --- a/packages/codemode/test/fixtures/build-id.ts +++ /dev/null @@ -1,8 +0,0 @@ -// Prints this process's snapshot build id, from a runtime made with as few of the package's modules as it takes, so -// the id can be compared across entry points (`bun --preload build-id.ts`). -import { Interpreter } from "../../src/language/runtime/interpreter.js" -import { createBuiltins } from "../../src/language/runtime/intrinsics.js" -import { buildId } from "../../src/language/snapshot.js" - -new Interpreter({ builtins: createBuiltins() }) -console.log(buildId()) diff --git a/packages/codemode/test/fixtures/prelude-roundtrip.ts b/packages/codemode/test/fixtures/prelude-roundtrip.ts deleted file mode 100644 index d088470852f..00000000000 --- a/packages/codemode/test/fixtures/prelude-roundtrip.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Runs prelude built-ins in the round-trip mode and prints the result and how many round trips were taken while a -// prelude frame was on the stack. -import { Effect } from "effect" -import { CodeMode } from "../../src/index.js" -import { CodeFlags } from "../../src/language/opcodes.js" -import { setRoundTrip } from "../../src/language/runtime/execute.js" -import { Vm } from "../../src/language/vm.js" - -setRoundTrip(true) - -let saved = 0 -const capture = Vm.prototype.capture -Vm.prototype.capture = function (this: Vm, options) { - if (this.frames.some((frame) => (frame.code.flags & CodeFlags.INTERNAL) !== 0)) saved++ - return capture.call(this, options) -} -const result = await Effect.runPromise( - CodeMode.execute({ - tools: {}, - code: ` - const groups = Object.groupBy([1, 2, 3, 4, 5, 6], (x) => (x % 2 ? "odd" : "even")) - const union = new Set([1, 2, 3]).union({ size: 2, has: () => true, keys: () => [7, 8][Symbol.iterator]() }) - const parsed = JSON.parse('{"a":[1,2,{"b":3}]}', (k, v) => (typeof v === "number" ? v * 10 : v)) - return [groups, [...union], parsed, [1, 2, 3].values().reduce((a, b) => a + b)]`, - }), -) -console.log(JSON.stringify({ result, saved })) diff --git a/packages/codemode/test/fixtures/resume-getters-process.ts b/packages/codemode/test/fixtures/resume-getters-process.ts deleted file mode 100644 index 9d8fb04c02a..00000000000 --- a/packages/codemode/test/fixtures/resume-getters-process.ts +++ /dev/null @@ -1,17 +0,0 @@ -// Resumes a saved run in its own process: `bun resume-getters-process.ts `. The globals match -// test/accessors-suspend.test.ts: `slow` answers `n * 2`, `pick` its argument, `keep` nothing; promises in arguments are -// awaited. -import { Effect } from "effect" -import { Host, Runtime } from "../../src/language/index.js" - -const runtime = Runtime.make({ - translate: { promises: "await" }, - globals: () => ({ - slow: Host.fn(([n]) => Effect.succeed((n as number) * 2), { type: "async", idempotent: true }), - pick: Host.fn(([value]) => value), - keep: Host.fn(() => undefined), - }), -}) as Runtime.Runtime -const [file] = process.argv.slice(2) -const bytes = new Uint8Array(await Bun.file(file!).arrayBuffer()) -console.log(JSON.stringify(await Effect.runPromise(runtime.resume(bytes).run()))) diff --git a/packages/codemode/test/fixtures/resume-process.ts b/packages/codemode/test/fixtures/resume-process.ts deleted file mode 100644 index 816bd5e7c70..00000000000 --- a/packages/codemode/test/fixtures/resume-process.ts +++ /dev/null @@ -1,16 +0,0 @@ -// Resumes a saved run in its own process: `bun resume-process.ts `. The `slow` tool answers -// `{ value: input.value * 2 }`. -import { Effect, Schema } from "effect" -import { CodeMode, Tool } from "../../src/index.js" - -const Value = Schema.Struct({ value: Schema.Number }) -const slow = Tool.make({ - description: "Doubles", - input: Value, - output: Value, - execute: (input) => Effect.succeed({ value: input.value * 2 }), -}) -const [file] = process.argv.slice(2) -const bytes = new Uint8Array(await Bun.file(file!).arrayBuffer()) -const resumed = CodeMode.make({ tools: { slow } }).resume(bytes) -console.log(JSON.stringify(await Effect.runPromise(resumed.run()))) diff --git a/packages/codemode/test/fixtures/wpt-base64.json b/packages/codemode/test/fixtures/wpt-base64.json deleted file mode 100644 index 01f981a6502..00000000000 --- a/packages/codemode/test/fixtures/wpt-base64.json +++ /dev/null @@ -1,82 +0,0 @@ -[ - ["", []], - ["abcd", [105, 183, 29]], - [" abcd", [105, 183, 29]], - ["abcd ", [105, 183, 29]], - [" abcd===", null], - ["abcd=== ", null], - ["abcd ===", null], - ["a", null], - ["ab", [105]], - ["abc", [105, 183]], - ["abcde", null], - ["𐀀", null], - ["=", null], - ["==", null], - ["===", null], - ["====", null], - ["=====", null], - ["a=", null], - ["a==", null], - ["a===", null], - ["a====", null], - ["a=====", null], - ["ab=", null], - ["ab==", [105]], - ["ab===", null], - ["ab====", null], - ["ab=====", null], - ["abc=", [105, 183]], - ["abc==", null], - ["abc===", null], - ["abc====", null], - ["abc=====", null], - ["abcd=", null], - ["abcd==", null], - ["abcd===", null], - ["abcd====", null], - ["abcd=====", null], - ["abcde=", null], - ["abcde==", null], - ["abcde===", null], - ["abcde====", null], - ["abcde=====", null], - ["=a", null], - ["=a=", null], - ["a=b", null], - ["a=b=", null], - ["ab=c", null], - ["ab=c=", null], - ["abc=d", null], - ["abc=d=", null], - ["ab\u000Bcd", null], - ["ab\u3000cd", null], - ["ab\u3001cd", null], - ["ab\tcd", [105, 183, 29]], - ["ab\ncd", [105, 183, 29]], - ["ab\fcd", [105, 183, 29]], - ["ab\rcd", [105, 183, 29]], - ["ab cd", [105, 183, 29]], - ["ab\u00a0cd", null], - ["ab\t\n\f\r cd", [105, 183, 29]], - [" \t\n\f\r ab\t\n\f\r cd\t\n\f\r ", [105, 183, 29]], - ["ab\t\n\f\r =\t\n\f\r =\t\n\f\r ", [105]], - ["A", null], - ["/A", [252]], - ["//A", [255, 240]], - ["///A", [255, 255, 192]], - ["////A", null], - ["/", null], - ["A/", [3]], - ["AA/", [0, 15]], - ["AAAA/", null], - ["AAA/", [0, 0, 63]], - ["\u0000nonsense", null], - ["abcd\u0000nonsense", null], - ["YQ", [97]], - ["YR", [97]], - ["~~", null], - ["..", null], - ["--", null], - ["__", null] -] diff --git a/packages/codemode/test/for-await-test262.test.ts b/packages/codemode/test/for-await-test262.test.ts deleted file mode 100644 index fcbbcb85ccb..00000000000 --- a/packages/codemode/test/for-await-test262.test.ts +++ /dev/null @@ -1,534 +0,0 @@ -/* - * Portions adapted from Test262 at revision 250f204f23a9249ff204be2baec29600faae7b75: - * - test/language/statements/for-await-of/ticks-with-sync-iter-resolved-promise-and-constructor-lookup.js - * - test/language/statements/for-await-of/ticks-with-async-iter-resolved-promise-and-constructor-lookup.js - * - test/language/statements/for-await-of/async-func-dstr-let-ary-ptrn-elem-id-iter-val.js - * - test/language/statements/for-await-of/async-func-decl-dstr-array-rest-after-element.js - * - test/language/statements/for-await-of/iterator-close-non-throw-get-method-is-null.js - * - test/language/statements/for-await-of/iterator-close-non-throw-get-method-non-callable.js - * - test/language/statements/for-await-of/iterator-close-throw-get-method-non-callable.js - * - * Copyright (C) 2019 André Bargull. All rights reserved. - * Copyright (C) 2020 Alexey Shvayka. All rights reserved. - * Test262 portions are governed by the BSD license in LICENSE.test262. - */ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" - -const execute = (code: string) => Effect.runPromise(CodeMode.execute({ code, tools: {} })) - -const value = async (code: string) => { - const result = await execute(code) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -describe("Test262 for-await-of adaptations", () => { - test("awaits promise and plain values from a synchronous array", async () => { - expect( - await value(` - const values = [] - for await (const item of [Promise.resolve(1), 2, new Promise((resolve) => resolve(3))]) { - values.push(item) - } - return values - `), - ).toEqual([1, 2, 3]) - }) - - test("defers the body even for an already-resolved or plain value", async () => { - expect( - await value(` - const events = [] - const before = Promise.resolve().then(() => events.push("before")) - for await (const item of [Promise.resolve(1), 2]) events.push("body " + item) - await before - return events - `), - ).toEqual(["before", "body 1", "body 2"]) - }) - - test("an awaited rejection exits through normal try/catch", async () => { - const result = await execute(` - const values = [] - try { - for await (const item of [Promise.resolve(1), Promise.reject("stop"), Promise.resolve(3)]) { - values.push(item) - } - } catch (error) { - return [values, error] - } - return "missed" - `) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.value).toEqual([[1], "stop"]) - expect(result.warnings ?? []).toEqual([]) - }) - - test("destructures after resolving each yielded value", async () => { - expect( - await value(` - const values = [] - for await (const [first, ...rest] of [Promise.resolve([1, 2, 3])]) { - values.push(first, rest) - } - return values - `), - ).toEqual([1, [2, 3]]) - }) - - test("supports assignment targets", async () => { - expect( - await value(` - let first - let rest - for await ([first, ...rest] of [Promise.resolve([1, 2, 3])]) {} - return [first, rest] - `), - ).toEqual([1, [2, 3]]) - }) - - test("preserves fresh lexical bindings per iteration", async () => { - expect( - await value(` - const reads = [] - for await (const item of [Promise.resolve(1), Promise.resolve(2), Promise.resolve(3)]) { - reads.push(() => item) - } - return reads.map((read) => read()) - `), - ).toEqual([1, 2, 3]) - }) - - test("supports every existing collection iterable", async () => { - expect( - await value(` - const string = [] - for await (const item of "ab") string.push(item) - - const set = [] - for await (const item of new Set([Promise.resolve(1), 2])) set.push(item) - - const map = [] - for await (const [key, item] of new Map([["a", 1], ["b", 2]])) map.push(key, item) - - const params = [] - for await (const [key, item] of new URLSearchParams("a=1&b=2")) params.push(key, item) - return { string, set, map, params } - `), - ).toEqual({ string: ["a", "b"], set: [1, 2], map: ["a", 1, "b", 2], params: ["a", "1", "b", "2"] }) - }) - - test("preserves labeled break and continue behavior", async () => { - expect( - await value(` - const values = [] - outer: for await (const item of [1, 2, 3, 4]) { - if (item === 2) continue outer - if (item === 4) break outer - values.push(item) - } - return values - `), - ).toEqual([1, 3]) - }) - - test("drives a custom async iterator sequentially", async () => { - expect( - await value(` - let index = 0 - const iterator = { - [Symbol.asyncIterator]: () => iterator, - async next() { - index += 1 - if (index > 3) return { done: true } - return { done: false, value: index } - }, - } - const values = [] - for await (const item of iterator) values.push(item) - return values - `), - ).toEqual([1, 2, 3]) - }) - - test("leaves async iterator values under the iterator's control", async () => { - expect( - await value(` - let done = false - const iterator = { - [Symbol.asyncIterator]: () => iterator, - next: async () => done ? { done: true } : (done = true, { done: false, value: Promise.resolve(1) }), - } - for await (const item of iterator) return [item instanceof Promise, await item] - `), - ).toEqual([true, 1]) - }) - - test("awaits synchronous results from an async iterator before the body", async () => { - expect( - await value(` - const events = ["pre"] - const ticks = Promise.resolve() - .then(() => events.push("tick 1")) - .then(() => events.push("tick 2")) - let done = false - const iterator = { - [Symbol.asyncIterator]: () => iterator, - next: () => done ? { done: true } : (done = true, { done: false, value: Promise.resolve(1) }), - } - for await (const item of iterator) events.push(item instanceof Promise ? "loop" : "adopted") - events.push("post") - await ticks - return events - `), - ).toEqual(["pre", "tick 1", "loop", "tick 2", "post"]) - }) - - test("falls back to a custom synchronous iterator", async () => { - expect( - await value(` - let index = 0 - const iterator = { - [Symbol.iterator]: () => iterator, - next() { - index += 1 - return index > 2 ? { done: true } : { done: false, value: Promise.resolve(index) } - }, - } - const values = [] - for await (const item of iterator) values.push(item) - return values - `), - ).toEqual([1, 2]) - }) - - test("adopts terminal and close values from synchronous iterators", async () => { - expect( - await value(` - const terminal = { - [Symbol.iterator]: () => terminal, - next: () => ({ done: true, value: Promise.reject("terminal") }), - } - let terminalError - try { - for await (const item of terminal) {} - } catch (error) { - terminalError = error - } - - const closing = { - [Symbol.iterator]: () => closing, - next: () => ({ done: false, value: 1 }), - return: () => ({ done: true, value: Promise.reject("close") }), - } - let closeError - try { - for await (const item of closing) break - } catch (error) { - closeError = error - } - return [terminalError, closeError] - `), - ).toEqual(["terminal", "close"]) - }) - - test("captures the next method when acquiring the iterator", async () => { - expect( - await value(` - let count = 0 - const next = () => { - count += 1 - if (count === 1) iterator.next = () => ({ done: true }) - return count > 2 ? { done: true } : { done: false, value: count } - } - const iterator = { [Symbol.iterator]: () => iterator, next } - const values = [] - for await (const item of iterator) values.push(item) - return values - `), - ).toEqual([1, 2]) - }) - - test("captures synchronous iterator result fields before suspending", async () => { - expect( - await value(` - let count = 0 - const result = { done: false, value: 1 } - const iterator = { - [Symbol.iterator]: () => iterator, - next() { - count += 1 - if (count > 1) return { done: true } - Promise.resolve().then(() => { - result.done = true - result.value = 2 - }) - return result - }, - } - const values = [] - for await (const item of iterator) values.push(item) - return values - `), - ).toEqual([1]) - }) - - test("preserves the async close turn for a sync iterator without return", async () => { - expect( - await value(` - const events = [] - const iterator = { - [Symbol.iterator]: () => iterator, - next: () => ({ done: false, value: 1 }), - } - for await (const item of iterator) { - Promise.resolve().then(() => events.push("reaction")) - break - } - events.push("after") - return events - `), - ).toEqual(["reaction", "after"]) - }) - - test("defers synchronous iterator protocol errors", async () => { - expect( - await value(` - const events = [] - const throwing = { - [Symbol.iterator]: () => throwing, - next() { - Promise.resolve().then(() => events.push("next reaction")) - throw "next" - }, - } - try { - for await (const item of throwing) {} - } catch (error) { - events.push("next catch") - } - - const malformed = { - [Symbol.iterator]: () => malformed, - next() { - Promise.resolve().then(() => events.push("result reaction")) - return 1 - }, - } - try { - for await (const item of malformed) {} - } catch (error) { - events.push("result catch") - } - - const closing = { - [Symbol.iterator]: () => closing, - next: () => ({ done: false, value: 1 }), - return() { - Promise.resolve().then(() => events.push("return reaction")) - throw "return" - }, - } - try { - for await (const item of closing) break - } catch (error) { - events.push("return catch") - } - return events - `), - ).toEqual(["next reaction", "next catch", "result reaction", "result catch", "return reaction", "return catch"]) - }) - - test("prefers Symbol.asyncIterator over Symbol.iterator", async () => { - expect( - await value(` - let done = false - const asyncIterator = { - next: async () => done ? { done: true } : (done = true, { done: false, value: "async" }), - } - const syncIterator = { next: () => ({ done: true }) } - const iterable = { - [Symbol.asyncIterator]: () => asyncIterator, - [Symbol.iterator]: () => syncIterator, - } - const values = [] - for await (const item of iterable) values.push(item) - return values - `), - ).toEqual(["async"]) - }) - - test("closes a custom iterator on abrupt loop completion", async () => { - expect( - await value(` - let closed = 0 - const iterator = { - [Symbol.asyncIterator]: () => iterator, - next: async () => ({ done: false, value: 1 }), - return: async () => (closed += 1, { done: true }), - } - for await (const item of iterator) break - try { - for await (const item of iterator) throw "stop" - } catch (error) {} - return closed - `), - ).toBe(2) - }) - - test("treats a null iterator return method as absent", async () => { - expect( - await value(` - let count = 0 - const iterator = { - [Symbol.asyncIterator]: () => iterator, - next: async () => ({ done: false, value: 1 }), - return: null, - } - for await (const item of iterator) { - count += 1 - break - } - return count - `), - ).toBe(1) - }) - - test("a non-callable return method replaces break with TypeError", async () => { - expect( - await value(` - const iterator = { - [Symbol.asyncIterator]: () => iterator, - next: async () => ({ done: false, value: 1 }), - return: true, - } - try { - for await (const item of iterator) break - } catch (error) { - return error.name - } - return "missed" - `), - ).toBe("TypeError") - }) - - test("a body throw wins over a non-callable return method", async () => { - expect( - await value(` - const iterator = { - [Symbol.asyncIterator]: () => iterator, - next: async () => ({ done: false, value: 1 }), - return: true, - } - try { - for await (const item of iterator) throw "body" - } catch (error) { - return error - } - return "missed" - `), - ).toBe("body") - }) - - test("rejects a primitive iterator return result", async () => { - expect( - await value(` - const iterator = { - [Symbol.asyncIterator]: () => iterator, - next: async () => ({ done: false, value: 1 }), - return: async () => null, - } - try { - for await (const item of iterator) break - } catch (error) { - return error.name - } - return "missed" - `), - ).toBe("TypeError") - }) - - test("propagates iterator acquisition failures", async () => { - expect( - await value(` - const iterator = { - [Symbol.asyncIterator]: () => { throw "acquire" }, - } - try { - for await (const item of iterator) {} - } catch (error) { - return error - } - return "missed" - `), - ).toBe("acquire") - }) - - test("rejects malformed iterator acquisition methods and results", async () => { - expect( - await value(` - const names = [] - const invalid = [ - { [Symbol.asyncIterator]: true }, - { [Symbol.asyncIterator]: () => 1 }, - { [Symbol.asyncIterator]: () => ({ next: true }) }, - ] - for (const iterator of invalid) { - try { - for await (const item of iterator) {} - } catch (error) { - names.push(error.name) - } - } - return names - `), - ).toEqual(["TypeError", "TypeError", "TypeError"]) - }) - - test("preserves iterator protocol keys through object copies", async () => { - expect( - await value(` - let done = false - const iterable = { - plain: true, - [Symbol.asyncIterator]: () => iterable, - next: async () => done ? { done: true } : (done = true, { done: false, value: 1 }), - } - const spread = { ...iterable } - const { plain, ...rest } = iterable - const assigned = Object.assign({}, iterable) - const values = [] - for await (const item of spread) values.push(item) - return [ - values, - Object.hasOwn(spread, Symbol.asyncIterator), - Object.hasOwn(rest, Symbol.asyncIterator), - Object.hasOwn(assigned, Symbol.asyncIterator), - ] - `), - ).toEqual([[1], true, true, true]) - }) - - test("rejects malformed iterator protocol results", async () => { - const result = await execute(` - const iterator = { - [Symbol.asyncIterator]: () => iterator, - next: async () => 1, - } - for await (const item of iterator) {} - `) - expect(result.ok).toBe(false) - if (result.ok) return - expect(result.error.message).toContain("Iterator next() result must be an object") - }) - - test("rejects objects without an iterator protocol method", async () => { - const result = await execute(`for await (const item of { values: [1, 2] }) {}`) - expect(result.ok).toBe(false) - if (result.ok) return - expect(result.error.message).toContain("requires an iterable value, received a data object") - }) -}) diff --git a/packages/codemode/test/generator-test262.test.ts b/packages/codemode/test/generator-test262.test.ts deleted file mode 100644 index 9afa501c215..00000000000 --- a/packages/codemode/test/generator-test262.test.ts +++ /dev/null @@ -1,1311 +0,0 @@ -/* - * Portable portions adapted from Test262 at revision - * 250f204f23a9249ff204be2baec29600faae7b75. Exact source paths are cited - * beside the corresponding tests below. - * - * Copyright (C) 2013-2017 the V8 project authors. All rights reserved. - * Copyright (C) 2018 Valerie Young. All rights reserved. - * Copyright (C) 2020 Alexey Shvayka. All rights reserved. - * Copyright (C) 2022 Kevin Gibbons. All rights reserved. - * Copyright Ecma International. All rights reserved. - * Test262 portions are governed by the BSD license in LICENSE.test262. - */ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" - -const execute = (code: string) => Effect.runPromise(CodeMode.execute({ code, tools: {} })) - -const value = async (code: string) => { - const result = await execute(code) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -describe("confined generators", () => { - test("parameters are bound at the call; only the body waits for next()", async () => { - expect( - await value(` - const log = [] - function* g(a = log.push("param")) { log.push("body"); yield a } - const it = g() - log.push("created") - it.next() - function* bad({ x } = null) { yield x } - async function* asyncBad({ x } = null) { yield x } - let failures = [] - try { bad() } catch (error) { failures.push(error.constructor.name) } - try { asyncBad() } catch (error) { failures.push(error.constructor.name) } - return [log, failures] - `), - ).toEqual([ - ["param", "created", "body"], - ["TypeError", "TypeError"], - ]) - }) - - // test/built-ins/GeneratorPrototype/next/return-yield-expr.js - test("is lazy and preserves next(value), nested suspension, return, and exhaustion", async () => { - expect( - await value(` - const events = [] - function* generate() { - events.push("start") - const received = yield 1 + (yield 2) - return received - } - const iterator = generate() - const before = events.slice() - const first = iterator.next(99) - const second = iterator.next(3) - const third = iterator.next(7) - const fourth = iterator.next(8) - return [before, events, first, second, third, fourth] - `), - ).toEqual([ - [], - ["start"], - { value: 2, done: false }, - { value: 4, done: false }, - { value: 7, done: true }, - { done: true }, - ]) - }) - - test("routes throw and return through catch and finally", async () => { - expect( - await value(` - function* generate() { - try { - try { yield "try" } catch (error) { yield "caught " + error } - } finally { - yield "finally" - } - } - const iterator = generate() - return [iterator.next(), iterator.throw("boom"), iterator.return("done"), iterator.next()] - `), - ).toEqual([ - { value: "try", done: false }, - { value: "caught boom", done: false }, - { value: "finally", done: false }, - { value: "done", done: true }, - ]) - }) - - test("throws into a suspended generator and after exhaustion", async () => { - expect( - await value(` - function* generate() { yield 1 } - const iterator = generate() - iterator.next() - let suspended - let exhausted - try { iterator.throw("first") } catch (error) { suspended = error } - try { iterator.throw("second") } catch (error) { exhausted = error } - return [suspended, exhausted, iterator.next()] - `), - ).toEqual(["first", "second", { done: true }]) - }) - - test("rejects synchronous generator reentry", async () => { - expect( - await value(` - let iterator - function* generate() { - try { iterator.next() } catch (error) { return error.name } - } - iterator = generate() - return iterator.next() - `), - ).toEqual({ value: "TypeError", done: true }) - }) - - test("delegates yield*, forwards next values, and receives the delegate return value", async () => { - expect( - await value(` - function* inner() { - const input = yield 1 - return input * 2 - } - function* outer() { - const result = yield* inner() - return result + 1 - } - const iterator = outer() - return [iterator.next(), iterator.next(4)] - `), - ).toEqual([ - { value: 1, done: false }, - { value: 9, done: true }, - ]) - }) - - test("delegates throw and return to custom iterators", async () => { - expect( - await value(` - const calls = [] - let step = 0 - const delegate = { - [Symbol.iterator]: () => delegate, - next(...args) { - calls.push(["next", args.length, args[0]]) - step += 1 - return step === 1 ? { value: "one", done: false } : { value: "end", done: true } - }, - throw(value) { - calls.push(["throw", value]) - return { value: "recovered", done: false } - }, - return(value) { - calls.push(["return", value]) - return { value: value + "!", done: true } - }, - } - function* generate() { return yield* delegate } - const iterator = generate() - const first = iterator.next() - const second = iterator.throw("x") - const third = iterator.return("stop") - return [first, second, third, calls] - `), - ).toEqual([ - { value: "one", done: false }, - { value: "recovered", done: false }, - { value: "stop!", done: true }, - [ - ["next", 1, null], - ["throw", "x"], - ["return", "stop"], - ], - ]) - }) - - test("uses the missing-throw delegation path for built-in iterables", async () => { - expect( - await value(` - function* generate() { yield* [1, 2] } - const iterator = generate() - iterator.next() - try { iterator.throw("boom") } catch (error) { return error.name } - `), - ).toBe("TypeError") - }) - - test("exposes only the appropriate iterator symbol and works in for...of", async () => { - expect( - await value(` - function* generate() { yield 1; yield 2 } - const iterator = generate() - const symbols = [iterator[Symbol.iterator]() === iterator, iterator[Symbol.asyncIterator]] - const values = [] - for (const item of iterator) values.push(item) - return [symbols, values] - `), - ).toEqual([ - [true, null], - [1, 2], - ]) - }) - - test("accepts generator methods as iterator acquisition results", async () => { - expect( - await value(` - const sync = { - *[Symbol.iterator]() { yield 1; yield 2 }, - } - const asynchronous = { - async *[Symbol.asyncIterator]() { yield 3; yield 4 }, - } - const values = [] - for (const item of sync) values.push(item) - for await (const item of asynchronous) values.push(item) - return values - `), - ).toEqual([1, 2, 3, 4]) - }) - - test("closes a generator when for...of exits abruptly", async () => { - expect( - await value(` - const events = [] - function* generate() { - try { yield 1; yield 2 } finally { events.push("closed") } - } - for (const item of generate()) break - return events - `), - ).toEqual(["closed"]) - }) - - test("async generator requests are promises and execute in request order", async () => { - expect( - await value(` - const events = [] - async function* generate() { - events.push("start") - const input = yield Promise.resolve(1) - events.push("received " + input) - return Promise.resolve(3) - } - const iterator = generate() - const first = iterator.next() - const second = iterator.next(2) - const third = iterator.next(4) - const promiseFlags = [first instanceof Promise, second instanceof Promise, third instanceof Promise] - return [promiseFlags, await Promise.all([first, second, third]), events] - `), - ).toEqual([ - [true, true, true], - [{ value: 1, done: false }, { value: 3, done: true }, { done: true }], - ["start", "received 2"], - ]) - }) - - test("keeps requests queued while a completed generator adopts return values", async () => { - expect( - await value(` - const events = [] - let resolve - const pending = new Promise((done) => { resolve = done }) - async function* generate() { return 1 } - const iterator = generate() - const first = iterator.next() - const returned = iterator.return(pending) - const later = first.then(() => iterator.next()).then(() => events.push("later")) - returned.then(() => events.push("returned")) - await first - await Promise.resolve() - const before = events.slice() - resolve(9) - await Promise.all([returned, later]) - return [before, events] - `), - ).toEqual([[], ["returned", "later"]]) - }) - - test("serializes requests made after async generator exhaustion", async () => { - expect( - await value(` - const events = [] - let resolve - const pending = new Promise((done) => { resolve = done }) - async function* generate() { return 1 } - const iterator = generate() - await iterator.next() - const returned = iterator.return(pending).then(() => events.push("returned")) - const later = iterator.next().then(() => events.push("later")) - await Promise.resolve() - const before = events.slice() - resolve(9) - await Promise.all([returned, later]) - return [before, events] - `), - ).toEqual([[], ["returned", "later"]]) - }) - - test("async generators adopt yielded, returned, and return-request promises", async () => { - expect( - await value(` - async function* yielded() { yield Promise.resolve(1) } - async function* returned() { return Promise.resolve(2) } - async function* pending() { yield 0 } - const first = yielded() - const second = returned() - const third = pending() - const exhausted = returned() - await third.next() - await exhausted.next() - return await Promise.all([ - first.next(), - second.next(), - third.return(Promise.resolve(3)), - exhausted.return(Promise.resolve(4)), - ]) - `), - ).toEqual([ - { value: 1, done: false }, - { value: 2, done: true }, - { value: 3, done: true }, - { value: 4, done: true }, - ]) - }) - - test("awaits return-request promises before injecting completion", async () => { - expect( - await value(` - const events = [] - async function* generate() { - try { - yield 1 - } catch (error) { - events.push("caught " + error) - yield "recovered" - } finally { - events.push("finally") - } - } - const iterator = generate() - const first = await iterator.next() - const returned = await iterator.return(Promise.reject("bad")) - const beforeNext = events.slice() - const last = await iterator.next() - return [first, returned, beforeNext, last, events] - `), - ).toEqual([ - { value: 1, done: false }, - { value: "recovered", done: false }, - ["caught bad"], - { done: true }, - ["caught bad", "finally"], - ]) - }) - - test("loop consumers call iterator next with no arguments", async () => { - expect( - await value(` - const calls = [] - let syncStep = 0 - const sync = { - [Symbol.iterator]: () => sync, - next(...args) { - calls.push(["sync", args.length]) - syncStep += 1 - return { value: syncStep, done: syncStep > 1 } - }, - } - let asyncStep = 0 - const asynchronous = { - [Symbol.asyncIterator]: () => asynchronous, - async next(...args) { - calls.push(["async", args.length]) - asyncStep += 1 - return { value: asyncStep, done: asyncStep > 1 } - }, - } - for (const item of sync) {} - for await (const item of asynchronous) {} - return calls - `), - ).toEqual([ - ["sync", 0], - ["sync", 0], - ["async", 0], - ["async", 0], - ]) - }) - - test("supports async generators in for await...of and keeps them out of for...of", async () => { - expect( - await value(` - async function* generate() { yield 1; yield await Promise.resolve(2) } - const values = [] - for await (const item of generate()) values.push(item) - let name - try { for (const item of generate()) {} } catch (error) { name = error.name } - return [values, name] - `), - ).toEqual([[1, 2], "TypeError"]) - }) - - test("a returned generator serializes as {} like JSON.stringify", async () => { - expect(await value(`function* generate() { yield 1 } return generate()`)).toEqual({}) - }) - - // test/built-ins/GeneratorPrototype/return/from-state-suspended-start.js - // test/built-ins/GeneratorPrototype/throw/from-state-suspended-start.js - // test/built-ins/GeneratorPrototype/return/from-state-completed.js - // test/built-ins/GeneratorPrototype/throw/from-state-completed.js - test("honors sync return and throw in suspended-start and completed states", async () => { - expect( - await value(` - const events = [] - function* generate() { events.push("body"); yield 1 } - - const returned = generate() - const startReturn = returned.return(7) - const afterReturn = returned.next() - - const thrown = generate() - let startThrow - try { thrown.throw("start") } catch (error) { startThrow = error } - const afterThrow = thrown.next() - let completedThrow - try { thrown.throw("completed") } catch (error) { completedThrow = error } - - return [startReturn, afterReturn, startThrow, afterThrow, completedThrow, events] - `), - ).toEqual([{ value: 7, done: true }, { done: true }, "start", { done: true }, "completed", []]) - }) - - // test/built-ins/AsyncGeneratorPrototype/return/return-suspendedStart-promise.js - // test/built-ins/AsyncGeneratorPrototype/throw/throw-suspendedStart.js - // test/built-ins/AsyncGeneratorPrototype/return/return-state-completed.js - // test/built-ins/AsyncGeneratorPrototype/throw/throw-state-completed.js - test("honors async return and throw in suspended-start and completed states", async () => { - expect( - await value(` - const events = [] - async function* generate() { events.push("body"); yield 1 } - - const returned = generate() - const startReturn = await returned.return(Promise.resolve(7)) - const afterReturn = await returned.next() - - const thrown = generate() - let startThrow - try { await thrown.throw("start") } catch (error) { startThrow = error } - const afterThrow = await thrown.next() - let completedThrow - try { await thrown.throw("completed") } catch (error) { completedThrow = error } - - return [startReturn, afterReturn, startThrow, afterThrow, completedThrow, events] - `), - ).toEqual([{ value: 7, done: true }, { done: true }, "start", { done: true }, "completed", []]) - }) - - // test/built-ins/AsyncGeneratorPrototype/return/return-suspendedYield-try-finally.js - // test/built-ins/AsyncGeneratorPrototype/return/return-suspendedYield-try-finally-return.js - // test/built-ins/AsyncGeneratorPrototype/throw/throw-suspendedYield-try-finally-throw.js - test("runs finally yields and lets finally completions override requests", async () => { - expect( - await value(` - async function* yielding() { - try { yield 1 } finally { yield 2 } - } - async function* returning() { - try { yield 1 } finally { return "override" } - } - async function* throwing() { - try { yield 1 } finally { throw "override" } - } - - const first = yielding() - await first.next() - const finallyYield = await first.return("sent") - const preservedReturn = await first.next() - - const second = returning() - await second.next() - const overriddenReturn = await second.return("sent") - - const third = throwing() - await third.next() - let overriddenThrow - try { await third.throw("sent") } catch (error) { overriddenThrow = error } - return [finallyYield, preservedReturn, overriddenReturn, overriddenThrow] - `), - ).toEqual([{ value: 2, done: false }, { value: "sent", done: true }, { value: "override", done: true }, "override"]) - }) - - // test/language/statements/async-generator/yield-promise-reject-next-catch.js - // test/language/statements/async-generator/yield-promise-reject-next-yield-star-sync-iterator.js - test("rejects yielded promises and closes direct and sync-delegating async generators", async () => { - expect( - await value(` - async function* direct() { yield Promise.reject("direct") } - async function* delegated() { yield* [Promise.reject("delegated"), "unreachable"] } - const results = [] - for (const iterator of [direct(), delegated()]) { - try { await iterator.next() } catch (error) { results.push(error) } - results.push(await iterator.next()) - } - return results - `), - ).toEqual(["direct", { done: true }, "delegated", { done: true }]) - }) - - // test/built-ins/AsyncFromSyncIteratorPrototype/next/for-await-iterator-next-rejected-promise-close.js - // test/built-ins/AsyncFromSyncIteratorPrototype/next/yield-iterator-next-rejected-promise-close.js - // test/built-ins/AsyncFromSyncIteratorPrototype/throw/iterator-result-rejected-promise-close.js - test("closes sync iterators when async-from-sync values reject", async () => { - expect( - await value(` - const events = [] - function* loopSource() { - try { yield Promise.reject("loop") } finally { events.push("loop close") } - } - let loopError - try { for await (const item of loopSource()) {} } catch (error) { loopError = error } - - function* yieldSource() { - try { yield Promise.reject("yield") } finally { events.push("yield close") } - } - async function* delegate() { yield* yieldSource() } - let yieldError - try { await delegate().next() } catch (error) { yieldError = error } - - const throwing = { - [Symbol.iterator]: () => throwing, - next: () => ({ value: 1, done: false }), - throw: () => ({ value: Promise.reject("throw"), done: false }), - return: () => { events.push("throw close"); return {} }, - } - async function* throwDelegate() { yield* throwing } - const iterator = throwDelegate() - await iterator.next() - let throwError - try { await iterator.throw("sent") } catch (error) { throwError = error } - return [loopError, yieldError, throwError, events] - `), - ).toEqual(["loop", "yield", "throw", ["loop close", "yield close", "throw close"]]) - }) - - test("does not close rejected terminal or delegated return values", async () => { - expect( - await value(` - const events = [] - const terminal = { - [Symbol.iterator]: () => terminal, - next: () => ({ value: Promise.reject("terminal"), done: true }), - return: () => { events.push("terminal close"); return {} }, - } - let terminalError - try { for await (const item of terminal) {} } catch (error) { terminalError = error } - - let returnCount = 0 - const returned = { - [Symbol.iterator]: () => returned, - next: () => ({ value: 1, done: false }), - return: () => { - returnCount += 1 - return { value: Promise.reject("return"), done: false } - }, - } - async function* delegate() { yield* returned } - const iterator = delegate() - await iterator.next() - let returnError - try { await iterator.return("sent") } catch (error) { returnError = error } - return [terminalError, returnError, returnCount, events] - `), - ).toEqual(["terminal", "return", 1, []]) - }) - - test("serializes a mixed async next, throw, return, and next request queue", async () => { - expect( - await value(` - async function* generate() { - try { - try { yield 1; yield 2 } catch (error) { yield "caught " + error } - } finally { - yield "finally" - } - } - const iterator = generate() - const first = iterator.next() - const thrown = iterator.throw("x") - const returned = iterator.return("done") - const last = iterator.next() - return await Promise.all([first, thrown, returned, last]) - `), - ).toEqual([ - { value: 1, done: false }, - { value: "caught x", done: false }, - { value: "finally", done: false }, - { value: "done", done: true }, - ]) - }) - - // test/built-ins/AsyncGeneratorPrototype/next/request-queue-order.js - // test/built-ins/AsyncGeneratorPrototype/throw/request-queue-order-state-executing.js - // test/built-ins/AsyncGeneratorPrototype/return/request-queue-order-state-executing.js - test("orders async requests enqueued while generators are executing", async () => { - expect( - await value(` - const events = [] - let returned, returnRequest - async function* returnWhileExecuting() { - returnRequest = returned.return(42).then((result) => events.push(["return", result])) - yield 1 - } - returned = returnWhileExecuting() - const firstReturn = returned.next().then((result) => events.push(["first return", result])) - await Promise.all([firstReturn, returnRequest]) - - let thrown, throwRequest - async function* throwWhileExecuting() { - throwRequest = thrown.throw("boom").catch((error) => events.push(["throw", error])) - yield 2 - } - thrown = throwWhileExecuting() - const firstThrow = thrown.next().then((result) => events.push(["first throw", result])) - await Promise.all([firstThrow, throwRequest]) - - async function* queued() { yield "first"; yield "second" } - const iterator = queued() - const first = iterator.next() - const second = iterator.next() - const third = iterator.next() - await Promise.all([ - third.then(() => events.push("third")), - second.then(() => events.push("second")), - first.then(() => events.push("first")), - ]) - return events - `), - ).toEqual([ - ["first return", { value: 1, done: false }], - ["return", { value: 42, done: true }], - ["first throw", { value: 2, done: false }], - ["throw", "boom"], - "first", - "second", - "third", - ]) - }) - - // test/language/statements/async-generator/yield-star-promise-not-unwrapped.js - // test/language/statements/async-generator/yield-star-sync-next.js - test("preserves async iterator promise values but unwraps async-from-sync values", async () => { - expect( - await value(` - const asyncValue = Promise.resolve("async") - const asynchronous = { - [Symbol.asyncIterator]: () => asynchronous, - next: () => ({ value: asyncValue, done: false }), - } - const syncValue = Promise.resolve("sync") - const synchronous = { - [Symbol.iterator]: () => synchronous, - next: () => ({ value: syncValue, done: false }), - } - async function* delegate(value) { yield* value } - const asyncResult = await delegate(asynchronous).next() - const syncResult = await delegate(synchronous).next() - return [asyncResult.value === asyncValue, await asyncResult.value, syncResult] - `), - ).toEqual([true, "async", { value: "sync", done: false }]) - }) - - test("captures delegated result done before awaiting async-from-sync values", async () => { - expect( - await value(` - const result = { value: Promise.resolve(1), done: false } - result.value.then(() => { result.done = true }) - const source = { - [Symbol.iterator]: () => source, - next: () => result, - } - async function* delegate() { yield* source } - return await delegate().next() - `), - ).toEqual({ value: 1, done: false }) - }) - - // test/language/statements/async-generator/yield-star-async-next.js - // test/language/statements/async-generator/yield-star-sync-return.js - // test/language/statements/async-generator/yield-star-async-throw.js - test("forwards next, return, and throw through sync and async yield delegates", async () => { - expect( - await value(` - const calls = [] - const make = (symbol, label) => { - let step = 0 - const iterator = { - [symbol]: () => iterator, - next(...args) { - calls.push([label, "next", args.length, args[0]]) - step += 1 - return { value: step, done: false } - }, - return(value) { - calls.push([label, "return", value]) - return { value: value + "!", done: true } - }, - throw(value) { - calls.push([label, "throw", value]) - return { value: "caught " + value, done: false } - }, - } - return iterator - } - async function* delegate(iterator) { return yield* iterator } - const sync = delegate(make(Symbol.iterator, "sync")) - const asynchronous = delegate(make(Symbol.asyncIterator, "async")) - const results = [await sync.next(9), await sync.next(2), await sync.throw("x"), await sync.return("stop")] - results.push(await asynchronous.next(9), await asynchronous.next(3), await asynchronous.throw("y")) - return [results, calls] - `), - ).toEqual([ - [ - { value: 1, done: false }, - { value: 2, done: false }, - { value: "caught x", done: false }, - { value: "stop!", done: true }, - { value: 1, done: false }, - { value: 2, done: false }, - { value: "caught y", done: false }, - ], - [ - ["sync", "next", 1, null], - ["sync", "next", 1, 2], - ["sync", "throw", "x"], - ["sync", "return", "stop"], - ["async", "next", 1, null], - ["async", "next", 1, 3], - ["async", "throw", "y"], - ], - ]) - }) - - // test/language/statements/async-generator/yield-star-sync-return.js - // test/language/statements/async-generator/yield-star-async-throw.js - test("continues delegation when return and throw report done false", async () => { - expect( - await value(` - let returns = 0 - const synchronous = { - [Symbol.iterator]: () => synchronous, - next: () => ({ value: "next", done: false }), - return(value) { - returns += 1 - return { value: returns === 1 ? "return pending" : value, done: returns > 1 } - }, - } - let throws = 0 - const asynchronous = { - [Symbol.asyncIterator]: () => asynchronous, - next: () => ({ value: "next", done: false }), - throw(value) { - throws += 1 - return { value: throws === 1 ? "throw pending" : value, done: throws > 1 } - }, - } - async function* delegate(iterator) { return yield* iterator } - const returned = delegate(synchronous) - const thrown = delegate(asynchronous) - return [ - await returned.next(), - await returned.return("first"), - await returned.return("second"), - await thrown.next(), - await thrown.throw("first"), - await thrown.throw("second"), - ] - `), - ).toEqual([ - { value: "next", done: false }, - { value: "return pending", done: false }, - { value: "second", done: true }, - { value: "next", done: false }, - { value: "throw pending", done: false }, - { value: "second", done: true }, - ]) - }) - - // test/language/expressions/yield/star-rhs-iter-nrml-next-call-non-obj.js - // test/language/expressions/yield/star-rhs-iter-thrw-thrw-call-non-obj.js - // test/language/expressions/yield/star-rhs-iter-rtrn-rtrn-call-non-obj.js - // test/language/statements/async-generator/yield-star-next-not-callable-number-throw.js - test("rejects malformed yield delegate methods and iterator results", async () => { - expect( - await value(` - const run = (iterator, operation) => { - function* generate() { - try { yield* iterator } catch (error) { return error.name } - } - const value = generate() - const first = value.next() - return operation === "next" ? first : value[operation]() - } - const iterable = (fields) => ({ [Symbol.iterator]: () => fields }) - const nextResult = run(iterable({ next: () => 1 }), "next") - const throwResult = run(iterable({ next: () => ({ done: false }), throw: () => 1 }), "throw") - const returnResult = run(iterable({ next: () => ({ done: false }), return: () => 1 }), "return") - - const badAsync = { - [Symbol.asyncIterator]: () => ({ next: 1 }), - } - async function* asynchronous() { - try { yield* badAsync } catch (error) { return error.name } - } - return [nextResult, throwResult, returnResult, await asynchronous().next()] - `), - ).toEqual([ - { value: "TypeError", done: true }, - { value: "TypeError", done: true }, - { value: "TypeError", done: true }, - { value: "TypeError", done: true }, - ]) - }) - - // test/language/expressions/yield/captured-free-vars.js - // test/language/statements/generators/dflt-params-ref-prior.js - // test/language/expressions/generators/dflt-params-ref-prior.js - // test/language/expressions/object/method-definition/generator-no-yield.js - test("supports declaration, expression, and method forms with closures and parameters", async () => { - expect( - await value(` - const captured = 4 - function* declaration(x, y = x, ...rest) { yield captured + y + rest[0] } - const expression = function* (x, y = x) { yield captured + y } - const object = { *method({ value }, extra = 1) { return captured + value + extra } } - return [declaration(2, undefined, 3).next(), expression(5).next(), object.method({ value: 6 }).next()] - `), - ).toEqual([ - { value: 9, done: false }, - { value: 9, done: false }, - { value: 11, done: true }, - ]) - }) - - // test/language/expressions/assignment/dstr/array-elem-iter-nrml-close.js - test("steps holes and rest and closes array binding and assignment patterns early", async () => { - expect( - await value(` - const events = [] - function* binding() { - try { events.push("b1"); yield 1; events.push("b2"); yield 2; events.push("b3"); yield 3; yield 4 } - finally { events.push("binding close") } - } - const [first, , third] = binding() - function* assignment() { - try { yield 5; yield 6; yield 7 } - finally { events.push("assignment close") } - } - let head, rest - ;[head, ...rest] = assignment() - return [first, third, head, rest, events] - `), - ).toEqual([1, 3, 5, [6, 7], ["b1", "b2", "b3", "binding close", "assignment close"]]) - }) - - // test/language/statements/variable/dstr/ary-ptrn-elem-id-init-throws.js - // test/language/expressions/assignment/dstr/array-elem-iter-thrw-close-err.js - test("closes on destructuring defaults and preserves the binding error over return failure", async () => { - expect( - await value(` - const events = [] - const iterator = { - [Symbol.iterator]: () => iterator, - next: () => ({ value: undefined, done: false }), - return: () => { events.push("close"); throw "close error" }, - } - let caught - try { - const [value = (() => { throw "binding error" })()] = iterator - } catch (error) { caught = error } - return [caught, events] - `), - ).toEqual(["binding error", ["close"]]) - }) - - test("does not close an exhausted iterator when a destructuring default fails", async () => { - expect( - await value(` - const events = [] - const iterator = { - [Symbol.iterator]: () => iterator, - next: () => ({ done: true }), - return: () => { events.push("close"); return {} }, - } - try { const [item = (() => { throw "default" })()] = iterator } catch {} - return events - `), - ).toEqual([]) - }) - - test("consumes generators in array and argument spread without awaiting yielded promises", async () => { - expect( - await value(` - function* values() { yield 1; yield Promise.resolve(2); yield 3 } - const array = [...values()] - const args = ((...items) => items)(...values()) - return [array[0], array[1] instanceof Promise, await array[1], args[2]] - `), - ).toEqual([1, true, 2, 3]) - }) - - test("constructs Map, Set, and URLSearchParams from generators lazily", async () => { - expect( - await value(` - const events = [] - function* pairs() { events.push(1); yield ["a", 1]; events.push(2); yield ["b", 2] } - function* values() { yield 1; yield 1; yield 2 } - const map = new Map(pairs()) - const set = new Set(values()) - const params = new URLSearchParams(pairs()) - return [map.get("b"), [...set], params.toString(), events] - `), - ).toEqual([2, [1, 2], "a=1&b=2", [1, 2, 1, 2]]) - }) - - test("keeps built-in collection iteration live during callbacks", async () => { - expect( - await value(` - const map = new Map([[1, 1], [2, 2]]) - const mapped = Array.from(map, (entry, index) => { - if (index === 0) map.set(3, 3) - return entry[0] - }) - const set = new Set([1, 2]) - const grouped = Map.groupBy(set, (item, index) => { - if (index === 0) set.add(3) - return "items" - }) - return [mapped, grouped.get("items")] - `), - ).toEqual([ - [1, 2, 3], - [1, 2, 3], - ]) - }) - - test("keeps built-in collection iteration live in loops and yield delegation", async () => { - expect( - await value(` - const map = new Map([[1, 1], [2, 2]]) - const mapValues = [] - for (const [key] of map) { - mapValues.push(key) - if (key === 1) map.set(3, 3) - } - const set = new Set([1, 2]) - const setValues = [] - for await (const item of set) { - setValues.push(item) - if (item === 1) set.add(3) - } - const params = new URLSearchParams("a=1&b=2") - function* delegate() { yield* params } - const iterator = delegate() - const first = iterator.next() - params.append("c", "3") - return [mapValues, setValues, first, iterator.next(), iterator.next()] - `), - ).toEqual([ - [1, 2, 3], - [1, 2, 3], - { value: ["a", "1"], done: false }, - { value: ["b", "2"], done: false }, - { value: ["c", "3"], done: false }, - ]) - }) - - test("preserves async-from-sync turns for built-in loop completion and close", async () => { - expect( - await value(` - const completed = [] - Promise.resolve().then(() => completed.push("reaction")) - for await (const item of []) {} - completed.push("after") - - const closed = [] - for await (const item of [1]) { - Promise.resolve().then(() => closed.push("reaction")) - break - } - closed.push("after") - return [completed, closed] - `), - ).toEqual([ - ["reaction", "after"], - ["reaction", "after"], - ]) - }) - - test("reads iterator return only when closing", async () => { - expect( - await value(` - const events = [] - const iterator = { - [Symbol.iterator]: () => iterator, - next() { - iterator.return = () => { events.push("new"); return {} } - return { value: 1, done: false } - }, - return: () => { events.push("old"); return {} }, - } - const [item] = iterator - return [item, events] - `), - ).toEqual([1, ["new"]]) - }) - - test("accepts iterable URLSearchParams entry pairs", async () => { - expect( - await value(` - function* pair() { yield "a"; yield 1 } - function* entries() { yield pair() } - return new URLSearchParams(entries()).toString() - `), - ).toBe("a=1") - }) - - test("coerces URLSearchParams pair elements like JS and closes both generators", async () => { - expect( - await value(` - const events = [] - function* pair() { - try { - events.push("first") - yield Promise.resolve(1) - events.push("second") - yield 2 - } finally { events.push("pair close") } - } - function* entries() { - try { yield pair() } finally { events.push("outer close") } - } - const params = new URLSearchParams(entries()) - return [events, params.toString()] - `), - ).toEqual([["first", "second", "pair close", "outer close"], "%5Bobject+Promise%5D=2"]) - }) - - test("validates URLSearchParams pair lengths after converting the outer sequence", async () => { - expect( - await value(` - const events = [] - function* entries() { - try { - events.push("one") - yield ["a"] - events.push("two") - yield ["b", 2] - } finally { events.push("outer close") } - } - let name - try { new URLSearchParams(entries()) } catch (error) { name = error.name } - return [events, name] - `), - ).toEqual([["one", "two", "outer close"], "TypeError"]) - }) - - test("closes entry constructors when a generator yields a malformed entry", async () => { - expect( - await value(` - const events = [] - function* mapEntries() { try { yield ["a", 1]; yield null } finally { events.push("map close") } } - function* parameterEntries() { try { yield ["a"]; yield ["b", 2] } finally { events.push("params close") } } - const names = [] - try { new Map(mapEntries()) } catch (error) { names.push(error.name) } - try { new URLSearchParams(parameterEntries()) } catch (error) { names.push(error.name) } - return [names, events] - `), - ).toEqual([ - ["TypeError", "TypeError"], - ["map close", "params close"], - ]) - }) - - // test/built-ins/Array/from/iter-map-fn-args.js - // test/built-ins/Array/from/iter-map-fn-err.js - test("interleaves Array.from mapping and closes when its mapper fails", async () => { - expect( - await value(` - const events = [] - function* source() { - try { events.push("next 1"); yield 1; events.push("next 2"); yield 2 } - finally { events.push("close") } - } - const mapped = Array.from(source(), (item) => { events.push("map " + item); return item * 2 }) - let caught - try { Array.from(source(), (item) => { throw "mapper " + item }) } catch (error) { caught = error } - return [mapped, caught, events] - `), - ).toEqual([[2, 4], "mapper 1", ["next 1", "map 1", "next 2", "map 2", "close", "next 1", "close"]]) - }) - - test("reads array-like Array.from values immediately before mapping", async () => { - expect( - await value(` - const source = { 0: 1, 1: 2, length: 2 } - return Array.from(source, (item, index) => { - if (index === 0) source[1] = 9 - return item - }) - `), - ).toEqual([1, 9]) - }) - - test("interleaves Object.groupBy and Map.groupBy callbacks and closes on callback failure", async () => { - expect( - await value(` - const events = [] - function* source() { try { events.push("next"); yield 1; events.push("next"); yield 2 } finally { events.push("close") } } - const object = Object.groupBy(source(), (item) => { events.push("object " + item); return item % 2 }) - const map = Map.groupBy(source(), (item) => { events.push("map " + item); return item % 2 }) - let caught - try { Object.groupBy(source(), () => { throw "callback" }) } catch (error) { caught = error } - return [object, Object.fromEntries(map), caught, events] - `), - ).toEqual([ - { 0: [2], 1: [1] }, - { 0: [2], 1: [1] }, - "callback", - ["next", "object 1", "next", "object 2", "close", "next", "map 1", "next", "map 2", "close", "next", "close"], - ]) - }) - - test("consumes Promise combinator generators in order and observes rejections", async () => { - expect( - await value(` - function* items() { yield Promise.resolve(1); yield Promise.reject("bad"); yield 3 } - const settled = await Promise.allSettled(items()) - let all, any - try { await Promise.all(items()) } catch (error) { all = error } - try { await Promise.any((function* () { yield Promise.reject("a"); yield Promise.reject("b") })()) } - catch (error) { any = error.errors } - const race = await Promise.race((function* () { yield 4; yield Promise.resolve(5) })()) - return [settled, all, any, race] - `), - ).toEqual([ - [ - { status: "fulfilled", value: 1 }, - { status: "rejected", reason: "bad" }, - { status: "fulfilled", value: 3 }, - ], - "bad", - ["a", "b"], - 4, - ]) - }) - - test("finishes Promise combinator iterator consumption before returning the promise", async () => { - expect( - await value(` - const events = [] - function* items() { events.push("first"); yield 1; events.push("second"); yield 2 } - const promise = Promise.all(items()) - events.push("after call") - await promise - return events - `), - ).toEqual(["first", "second", "after call"]) - }) - - // test/built-ins/Object/fromEntries/iterator-closed-for-null-entry.js - test("closes Object.fromEntries on malformed entries and consumes valid generators", async () => { - expect( - await value(` - const events = [] - function* valid() { yield ["a", 1]; yield ["b", 2] } - function* invalid() { try { yield ["a", 1]; yield null; yield ["c", 3] } finally { events.push("close") } } - let name - try { Object.fromEntries(invalid()) } catch (error) { name = error.name } - return [Object.fromEntries(valid()), name, events] - `), - ).toEqual([{ a: 1, b: 2 }, "TypeError", ["close"]]) - }) - - test("consumes AggregateError and Math.sumPrecise generators and closes on invalid numbers", async () => { - expect( - await value(` - const events = [] - function* errors() { yield "a"; yield "b" } - function* numbers() { yield 1e30; yield 0.1; yield -1e30 } - function* invalid() { try { yield 1; yield "bad"; yield 2 } finally { events.push("close") } } - const aggregate = new AggregateError(errors(), "message") - let name - try { Math.sumPrecise(invalid()) } catch (error) { name = error.name } - return [aggregate.errors, aggregate.message, Math.sumPrecise(numbers()), name, events] - `), - ).toEqual([["a", "b"], "message", 0.1, "TypeError", ["close"]]) - }) - - test("rejects async generators in every synchronous iterable consumer", async () => { - expect( - await value(` - async function* source() { yield ["a", 1] } - const checks = [ - () => [...source()], - () => ((...items) => items)(...source()), - () => { const [item] = source(); return item }, - () => Array.from(source()), - () => new Map(source()), - () => new Set(source()), - () => new URLSearchParams(source()), - () => Object.fromEntries(source()), - () => Object.groupBy(source(), (item) => item), - () => Math.sumPrecise(source()), - () => new AggregateError(source()), - ] - const names = [] - for (const check of checks) { - try { check() } catch (error) { names.push(error.name) } - } - try { await Promise.all(source()) } catch (error) { names.push(error.name) } - return names - `), - ).toEqual(Array(12).fill("TypeError")) - }) - - // test/built-ins/Array/from/iter-get-iter-err.js - // test/built-ins/Array/from/iter-adv-err.js - test("does not close when iterator acquisition or next-result validation fails", async () => { - expect( - await value(` - const events = [] - const acquisition = { [Symbol.iterator]: () => { events.push("acquire"); throw "acquisition" } } - const malformed = { - [Symbol.iterator]: () => malformed, - next: () => { events.push("next"); return 1 }, - return: () => { events.push("close"); return {} }, - } - for (const source of [acquisition, malformed]) { - try { Array.from(source) } catch {} - } - return events - `), - ).toEqual(["acquire", "next"]) - }) - - test("reports synchronous iterator failures before queued promise reactions", async () => { - expect( - await value(` - const events = [] - Promise.resolve().then(() => events.push("reaction")) - const iterator = { - [Symbol.iterator]: () => iterator, - next: () => { throw "next" }, - } - try { Array.from(iterator) } catch { events.push("catch") } - await Promise.resolve() - return events - `), - ).toEqual(["catch", "reaction"]) - }) - - test("a generator's return() through for...of or destructuring surfaces a failing close, as break does", async () => { - expect( - await value(` - const make = (ret) => ({ [Symbol.iterator]: () => ({ next: () => ({ done: false, value: [1] }), return: ret }) }) - const blanks = (ret) => ({ [Symbol.iterator]: () => ({ next: () => ({ done: false }), return: ret }) }) - const outcomes = [] - for (const [label, ret] of [ - ["null", () => null], - ["throws", () => { throw new RangeError("close") }], - ["ok", () => ({ done: true })], - ]) { - function* loop() { for (const [a] of make(ret)) yield a } - function* pattern() { for ([ {} = yield ] of [blanks(ret)]) {} } - for (const g of [loop(), pattern()]) { - g.next() - try { g.return(7); outcomes.push(label + " quiet") } catch (e) { outcomes.push(label + " " + e.constructor.name) } - } - } - return outcomes - `), - ).toEqual(["null TypeError", "null TypeError", "throws RangeError", "throws RangeError", "ok quiet", "ok quiet"]) - }) -}) - -describe("generator protocol misuse", () => { - // test/built-ins/GeneratorPrototype/next/this-val-not-generator.js - test("a sync generator method borrowed by an async generator throws a catchable TypeError", async () => { - expect( - await value(` - const next = (function* () {})().next - const generator = (async function* () {})() - try { - next.call(generator) - return "no error" - } catch (e) { - return [e.name, e.message] - } - `), - ).toEqual(["TypeError", "Generator.prototype.next called on incompatible receiver an async generator."]) - }) -}) diff --git a/packages/codemode/test/groupby-test262.test.ts b/packages/codemode/test/groupby-test262.test.ts deleted file mode 100644 index bf27ad846e9..00000000000 --- a/packages/codemode/test/groupby-test262.test.ts +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Portions adapted from Test262 at revision 250f204f23a9249ff204be2baec29600faae7b75: - * - test/built-ins/Object/groupBy/evenOdd.js - * - test/built-ins/Object/groupBy/groupLength.js - * - test/built-ins/Object/groupBy/callback-arg.js - * - test/built-ins/Object/groupBy/string.js - * - test/built-ins/Object/groupBy/emptyList.js - * - test/built-ins/Object/groupBy/toPropertyKey.js - * - test/built-ins/Object/groupBy/invalid-property-key.js - * - test/built-ins/Object/groupBy/invalid-iterable.js - * - test/built-ins/Object/groupBy/invalid-callback.js - * - test/built-ins/Object/groupBy/callback-throws.js - * - test/built-ins/Object/groupBy/null-prototype.js - * - test/built-ins/Map/groupBy/evenOdd.js - * - test/built-ins/Map/groupBy/groupLength.js - * - test/built-ins/Map/groupBy/callback-arg.js - * - test/built-ins/Map/groupBy/string.js - * - test/built-ins/Map/groupBy/emptyList.js - * - test/built-ins/Map/groupBy/toPropertyKey.js - * - test/built-ins/Map/groupBy/negativeZero.js - * - test/built-ins/Map/groupBy/invalid-iterable.js - * - test/built-ins/Map/groupBy/invalid-callback.js - * - test/built-ins/Map/groupBy/callback-throws.js - * - test/built-ins/Map/groupBy/map-instance.js - * - * Copyright (c) 2023 Ecma International. All rights reserved. - * Test262 portions are governed by the BSD license in LICENSE.test262. - * Invalid-iterable cases use a plain object, equivalent to the upstream object's absent - * Symbol.iterator; CodeMode does not support symbol-keyed properties. - */ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" - -const execute = (code: string) => Effect.runPromise(CodeMode.execute({ code, tools: {} })) - -const value = async (code: string) => { - const result = await execute(code) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -describe("Object.groupBy Test262 parity", () => { - test("groups values by coerced property keys", async () => { - expect( - await value(` - const values = [1, 2, 3] - const grouped = Object.groupBy(values, (value) => value % 2 === 0 ? "even" : "odd") - const stringable = { toString: () => 1 } - const coerced = Object.groupBy([1, "1", stringable], (value) => value) - const lengths = Object.groupBy(["hello", "test", "world"], (value) => value.length) - return [ - Object.keys(grouped), grouped.even, grouped.odd, grouped.toString === undefined, - Object.keys(coerced), coerced[1].length, - Object.keys(lengths), lengths[5], lengths[4], - ] - `), - ).toEqual([["odd", "even"], [2], [1, 3], true, ["1"], 3, ["4", "5"], ["hello", "world"], ["test"]]) - }) - - test("passes each value and index to the callback", async () => { - expect( - await value(` - const values = [-0, 0, 1, 2, 3] - const seen = [] - Object.groupBy(values, (value, index, ...extra) => { - seen.push([value === values[index], index, extra.length]) - return null - }) - return seen - `), - ).toEqual([ - [true, 0, 0], - [true, 1, 0], - [true, 2, 0], - [true, 3, 0], - [true, 4, 0], - ]) - }) - - test("supports strings and empty collections", async () => { - expect( - await value(` - const grouped = Object.groupBy("🥰💩🙏😈", (char) => char < "🙏" ? "before" : "after") - const empty = Object.groupBy([], () => { throw new Error("not called") }) - return [Object.keys(grouped), grouped.before, grouped.after, Object.keys(empty)] - `), - ).toEqual([["after", "before"], ["💩", "😈"], ["🥰", "🙏"], []]) - }) - - test("rejects invalid inputs and propagates callback and key-coercion failures", async () => { - expect( - await value(` - const messages = [] - try { Object.groupBy({}, () => { throw new Error("not called") }) } catch (error) { messages.push(error.name) } - for (const callback of [null, undefined, {}]) { - try { Object.groupBy([], callback) } catch (error) { messages.push(error.name) } - } - try { Object.groupBy([1], () => { throw new Error("callback") }) } catch (error) { messages.push(error.message) } - try { - Object.groupBy([1], () => ({ - toString: () => { throw new Error("property key") }, - })) - } catch (error) { messages.push(error.message) } - return messages - `), - ).toEqual(["TypeError", "TypeError", "TypeError", "TypeError", "callback", "property key"]) - }) -}) - -describe("Map.groupBy Test262 parity", () => { - test("returns a Map with identity-preserving groups", async () => { - expect( - await value(` - const stringable = { toString: () => 1 } - const grouped = Map.groupBy([1, "1", stringable], (value) => value) - const parity = Map.groupBy([1, 2, 3], (value) => value % 2 === 0 ? "even" : "odd") - const lengths = Map.groupBy(["hello", "test", "world"], (value) => value.length) - return [ - grouped instanceof Map, - grouped.size, - grouped.get(1), - grouped.get("1"), - grouped.has(stringable), - [...grouped.keys()].length, - parity.get("even"), - parity.get("odd"), - [...lengths.keys()], - lengths.get(5), - lengths.get(4), - ] - `), - ).toEqual([true, 3, [1], ["1"], true, 3, [2], [1, 3], [5, 4], ["hello", "world"], ["test"]]) - }) - - test("normalizes negative zero and passes each value and index", async () => { - expect( - await value(` - const values = [-0, 0, 1, 2, 3] - const seen = [] - const grouped = Map.groupBy(values, (value, index, ...extra) => { - seen.push([value === values[index], index, extra.length]) - return value - }) - return [grouped.size, grouped.get(0), seen] - `), - ).toEqual([ - 4, - [-0, 0], - [ - [true, 0, 0], - [true, 1, 0], - [true, 2, 0], - [true, 3, 0], - [true, 4, 0], - ], - ]) - }) - - test("supports strings and empty collections", async () => { - expect( - await value(` - const grouped = Map.groupBy("🥰💩🙏😈", (char) => char < "🙏" ? "before" : "after") - const empty = Map.groupBy([], () => { throw new Error("not called") }) - return [[...grouped.keys()], grouped.get("before"), grouped.get("after"), empty.size] - `), - ).toEqual([["after", "before"], ["💩", "😈"], ["🥰", "🙏"], 0]) - }) - - test("rejects invalid inputs and propagates callback failures", async () => { - expect( - await value(` - const results = [] - try { Map.groupBy({}, () => { throw new Error("not called") }) } catch (error) { results.push(error.name) } - for (const callback of [null, undefined, {}]) { - try { Map.groupBy([], callback) } catch (error) { results.push(error.name) } - } - try { Map.groupBy([1], () => { throw new Error("callback") }) } - catch (error) { results.push(error.message) } - return results - `), - ).toEqual(["TypeError", "TypeError", "TypeError", "TypeError", "callback"]) - }) -}) diff --git a/packages/codemode/test/host-accessors.test.ts b/packages/codemode/test/host-accessors.test.ts deleted file mode 100644 index 3ee901cdf78..00000000000 --- a/packages/codemode/test/host-accessors.test.ts +++ /dev/null @@ -1,213 +0,0 @@ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { Host, Runtime } from "../src/language/index.js" - -// Program getters crossing to the host: they run (once per receiver and key) before the host function does, their -// values cross as data, and setter-only properties are left out. - -const run = (runtime: Runtime.Runtime, code: string) => - Effect.runPromise(runtime.execute(code) as Effect.Effect) - -const value = async (runtime: Runtime.Runtime, code: string) => { - const result = await run(runtime, code) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -const translating = (translate?: Runtime.Translate) => { - const calls: Array> = [] - const keys: Array = [] - const runtime = Runtime.make({ - translate, - globals: () => ({ - keep: Host.fn((args, call) => { - keys.push(call.key) - calls.push(args) - return args.length - }), - send: Host.fn( - (args, call) => - Effect.sync(() => { - keys.push(call.key) - calls.push(args) - return "sent" - }), - { type: "async" }, - ), - later: Host.fn(([n]) => Effect.succeed(n), { type: "async" }), - ns: Host.namespace({ - keys: () => ["echo"], - resolve: () => Host.fn((args) => args[0]), - }), - }), - }) - return { runtime, calls, keys } -} - -describe("getters crossing to the host", () => { - test("a getter's value crosses as data and a setter-only property is left out", async () => { - const { runtime, calls } = translating() - expect( - await value( - runtime, - `let n = 0 - const o = { a: 1, get b() { n++; return { c: [n] } }, set d(v) {}, get e() { n++ } } - keep(o, [o.b]) - return n`, - ), - ).toBe(3) - expect(calls).toEqual([[{ a: 1, b: { c: [2] }, e: undefined }, [{ c: [1] }]]]) - expect(Object.keys(calls[0]![0] as object)).toEqual(["a", "b", "e"]) - }) - - test("each getter runs once per crossing, nested getters too, and errors cross with getter fields", async () => { - const { runtime, calls } = translating() - expect( - await value( - runtime, - `const log = [] - const inner = { get y() { log.push("y"); return 2 } } - const o = { get x() { log.push("x"); return inner } } - const e = new Error("boom") - e.detail = { get why() { log.push("why"); return "because" } } - keep(o, o, [inner], e) - return log`, - ), - ).toEqual(["x", "y", "why"]) - expect(calls[0]!.slice(0, 3)).toEqual([{ x: { y: 2 } }, { x: { y: 2 } }, [{ y: 2 }]]) - expect((calls[0]![3] as { detail: unknown }).detail).toEqual({ why: "because" }) - }) - - test("a getter that throws fails the call before the host function runs", async () => { - const { runtime, calls } = translating() - expect( - await value(runtime, `try { keep({ get x() { throw new Error("no") } }) } catch (e) { return e.message }`), - ).toBe("no") - expect(calls).toEqual([]) - }) - - test("a getter that throws rejects an async call's promise, and a sync call still throws", async () => { - const { runtime, calls, keys } = translating() - expect( - await value( - runtime, - `const bad = { get x() { throw new Error("boom") } } - const caught = await send(bad).catch((e) => e.message) - const settled = await Promise.allSettled([send(bad), send(2)]) - let sync - try { keep(bad) } catch (e) { sync = e.message } - return [caught, settled.map((s) => s.status), sync, keep(3)]`, - ), - ).toEqual(["boom", ["rejected", "fulfilled"], "boom", 1]) - expect(calls).toEqual([[2], [3]]) - expect(keys.map((key) => key.split(":")[1])).toEqual(["0", "1"]) - }) - - test("an async host function returns its promise at once, and getter rounds take no call ids", async () => { - const { runtime, calls, keys } = translating() - expect( - await value( - runtime, - `const p = send({ get a() { return { get b() { return 1 } } } }) - const q = keep(1) - return [p instanceof Promise, await p, q]`, - ), - ).toEqual([true, "sent", 1]) - // The async call is queued first and runs after the sync one; neither id went to a getter round. - expect(calls).toEqual([[1], [{ a: { b: 1 } }]]) - expect(keys.map((key) => key.split(":")[1])).toEqual(["1", "0"]) - }) - - test("with promises: await, getters run first, then the promises they return are awaited", async () => { - const { runtime, calls } = translating({ promises: "await" }) - expect( - await value( - runtime, - `let n = 0 - const o = { get p() { n++; return later({ get q() { n++; return 3 } }) } } - keep(o) - return n`, - ), - ).toBe(2) - expect(calls).toEqual([[{ p: { q: 3 } }]]) - }) - - test("with promises: await, a sync call inside a generator or the result's getters waits there", async () => { - const { runtime, calls } = translating({ promises: "await" }) - expect( - await value( - runtime, - `function* g() { yield keep(later(1)) } - return [[...g()], { get x() { return keep(later(2)) } }]`, - ), - ).toEqual([[1], { x: 1 }]) - expect(calls).toEqual([[1], [2]]) - }) - - test("functions: drop applies to a getter's value", async () => { - const { runtime, calls } = translating({ functions: "drop" }) - await value(runtime, `keep({ get f() { return () => 1 }, a: 1 })`) - expect(calls).toEqual([[{ a: 1 }]]) - }) - - test("a namespace call reads getter arguments ahead too", async () => { - const { runtime } = translating() - expect(await value(runtime, `return ns.echo({ get v() { return 4 } })`)).toEqual({ v: 4 }) - }) - - test("a circular getter is refused", async () => { - const { runtime } = translating() - const result = await run(runtime, `const o = { get self() { return o } }; keep(o)`) - expect(result).toMatchObject({ ok: false, error: { message: expect.stringContaining("circular") } }) - }) -}) - -describe("accessor flags on copies", () => { - test("an awaited sync-thenable copy keeps its getters", async () => { - const runtime = Runtime.make({ - globals: () => ({ find: Host.fn(() => Effect.succeed({ a: 1 }), { type: "sync-thenable" }) }), - }) - expect( - await value( - runtime, - `const r = find() - Object.defineProperty(r, "x", { get() { return 42 }, enumerable: true }) - const copy = await r - console.log(copy) - return [JSON.stringify(copy), Object.entries(copy), { ...copy }]`, - ), - ).toEqual(['{"a":1,"x":42}', [["a", 1], ["x", 42]], { a: 1, x: 42 }]) - }) - - test("an Error.prototype getter is called when an error is converted", async () => { - const runtime = Runtime.make({ globals: () => ({}) }) - const setup = `Object.defineProperty(Error.prototype, "name", { get() { return "Custom" }, configurable: true })` - expect(await value(runtime, `${setup}; return JSON.stringify(new Error("hi"))`)).toBe( - '{"name":"Custom","message":"hi"}', - ) - expect(await value(runtime, `${setup}; return new Error("hi")`)).toEqual({ name: "Custom", message: "hi" }) - }) -}) - -describe("class instances crossing to the host", () => { - const classes = ` - class Base { a = 1; get proto() { return "left" } m() { return 1 } } - class Item extends Base { constructor() { super(); this.b = 2; Object.defineProperty(this, "own", { get() { return 3 }, enumerable: true }); Object.defineProperty(this, "w", { set(v) {}, enumerable: true }) } }` - - test("as tool arguments: own enumerable fields and own getters, no prototype methods or getters", async () => { - const { runtime, calls } = translating() - await value(runtime, `${classes}; keep(new Item(), [new Base()])`) - expect(calls).toEqual([[{ a: 1, b: 2, own: 3 }, [{ a: 1 }]]]) - }) - - test("as the result", async () => { - const { runtime } = translating() - expect(await value(runtime, `${classes}; return { item: new Item() }`)).toEqual({ item: { a: 1, b: 2, own: 3 } }) - }) - - test("a class constructor follows the function rule", async () => { - expect(await value(translating({ functions: "drop" }).runtime, `class A {}; return { A, n: 1 }`)).toEqual({ n: 1 }) - const strict = await run(translating().runtime, `class A {}; keep(A)`) - expect(strict.ok).toBe(false) - }) -}) diff --git a/packages/codemode/test/json-callbacks-test262.test.ts b/packages/codemode/test/json-callbacks-test262.test.ts deleted file mode 100644 index 384ec6ece4b..00000000000 --- a/packages/codemode/test/json-callbacks-test262.test.ts +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Portions adapted from Test262 at revision 250f204f23a9249ff204be2baec29600faae7b75: - * - test/built-ins/JSON/parse/reviver-call-order.js - * - test/built-ins/JSON/parse/reviver-call-err.js - * - test/built-ins/JSON/stringify/replacer-array-duplicates.js - * - test/built-ins/JSON/stringify/replacer-array-empty.js - * - test/built-ins/JSON/stringify/replacer-array-number.js - * - test/built-ins/JSON/stringify/replacer-array-order.js - * - test/built-ins/JSON/stringify/replacer-array-undefined.js - * - test/built-ins/JSON/stringify/replacer-array-wrong-type.js - * - test/built-ins/JSON/stringify/replacer-function-abrupt.js - * - test/built-ins/JSON/stringify/replacer-function-arguments.js - * - test/built-ins/JSON/stringify/replacer-function-array-circular.js - * - test/built-ins/JSON/stringify/replacer-function-object-deleted-property.js - * - test/built-ins/JSON/stringify/replacer-function-object-circular.js - * - test/built-ins/JSON/stringify/replacer-function-result-undefined.js - * - test/built-ins/JSON/stringify/replacer-function-result.js - * - * Function-context assertions are omitted because CodeMode functions intentionally - * have no `this`. Number/String wrapper cases are omitted because CodeMode does not - * support primitive wrapper objects. Proxy and Symbol cases are outside CodeMode. - * - * Copyright (C) 2012 Ecma International. All rights reserved. - * Copyright (C) 2016 the V8 project authors. All rights reserved. - * Copyright (C) 2019 Aleksey Shvayka. All rights reserved. - * Copyright 2019 Kevin Gibbons. All rights reserved. - * Test262 portions are governed by the BSD license in LICENSE.test262. - */ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" - -const value = async (code: string) => { - const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} })) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -describe("Test262 JSON.parse reviver adaptations", () => { - test("test/built-ins/JSON/parse/reviver-call-order.js", async () => { - expect( - await value(` - const calls = [] - JSON.parse('{"p1":0,"p2":0,"p1":0,"2":0,"1":0}', (key, item) => { - calls.push(key) - return item - }) - return calls - `), - ).toEqual(["1", "2", "p1", "p2", ""]) - }) - - test("deletes properties and array elements when the reviver returns undefined", async () => { - expect( - await value(` - const result = JSON.parse('{"keep":1,"drop":2,"items":[1,2,3]}', (key, item) => { - if (key === "drop" || key === "1") return undefined - return item - }) - return [result, Object.hasOwn(result, "drop"), Object.hasOwn(result.items, 1), result.items.length] - `), - ).toEqual([{ keep: 1, items: [1, null, 3] }, false, false, 3]) - }) - - test("replaces the root and may delete it", async () => { - expect(await value(`return JSON.parse('{"a":1}', (key, item) => key === "" ? item.a : item)`)).toBe(1) - expect( - await value(`return JSON.parse('{"a":1}', (key, item) => key === "" ? undefined : item) === undefined`), - ).toBe(true) - }) - - test("test/built-ins/JSON/parse/reviver-call-err.js", async () => { - expect( - await value(`try { JSON.parse("0", () => { throw "stop" }) } catch (error) { return error } return "missed"`), - ).toBe("stop") - }) -}) - -describe("Test262 JSON.stringify replacer adaptations", () => { - test("array replacers filter keys in their own order and apply recursively", async () => { - expect(await value(`return JSON.stringify({ b: 1, a: 2, c: 3 }, ["c", "b", "a"])`)).toBe('{"c":3,"b":1,"a":2}') - expect(await value(`return JSON.stringify({ a: { b: 2, c: 3 } }, ["c", "b", "a"])`)).toBe('{"a":{"c":3,"b":2}}') - expect(await value(`return JSON.stringify({ a: 1 }, [])`)).toBe("{}") - }) - - test("array replacers deduplicate and coerce number primitives", async () => { - expect(await value(`return JSON.stringify({ a: 1, b: 2 }, ["a", "a", "b"])`)).toBe('{"a":1,"b":2}') - expect( - await value( - `return JSON.stringify({ "0": 0, "1": 1, "-4": 2, "0.3": 3, "-Infinity": 4, "NaN": 5 }, [-0, 1, -4, 0.3, -Infinity, NaN])`, - ), - ).toBe('{"0":0,"1":1,"-4":2,"0.3":3,"-Infinity":4,"NaN":5}') - }) - - test("array replacers ignore unsupported entry types", async () => { - expect( - await value(`return JSON.stringify({ true: 1, false: 2, null: 3, kept: 4 }, [true, false, null, {}, "kept"])`), - ).toBe('{"kept":4}') - expect(await value(`return JSON.stringify({ a: 1 }, undefined)`)).toBe('{"a":1}') - }) - - test("function replacers receive keys and values in preorder including the root", async () => { - expect( - await value(` - const calls = [] - const output = JSON.stringify({ a: [1, 2], b: true }, (key, item) => { - calls.push([key, Array.isArray(item) ? "array" : typeof item]) - return item - }) - return [output, calls] - `), - ).toEqual([ - '{"a":[1,2],"b":true}', - [ - ["", "object"], - ["a", "array"], - ["0", "number"], - ["1", "number"], - ["b", "boolean"], - ], - ]) - }) - - test("test/built-ins/JSON/stringify/replacer-function-object-deleted-property.js", async () => { - expect( - await value(` - const input = { a: 1, b: 2 } - return JSON.stringify(input, (key, item) => { - if (key === "a") delete input.b - if (key === "b" && item === undefined) return "" - return item - }) - `), - ).toBe('{"a":1,"b":""}') - }) - - test("test/built-ins/JSON/stringify/replacer-function-object-circular.js", async () => { - expect( - await value(` - const direct = { prop: {} } - const indirect = { p1: { p2: {} } } - const errors = [] - try { JSON.stringify(direct, () => direct) } catch (error) { errors.push(error.name) } - try { - JSON.stringify(indirect, (key, item) => key === "p2" ? indirect : item) - } catch (error) { errors.push(error.name) } - return errors - `), - ).toEqual(["TypeError", "TypeError"]) - }) - - test("test/built-ins/JSON/stringify/replacer-function-array-circular.js", async () => { - expect( - await value(` - const circular = [{}] - try { JSON.stringify(circular, () => circular) } catch (error) { return error.name } - return "missed" - `), - ).toBe("TypeError") - }) - - test("repeated objects outside the active ancestor chain are not circular", async () => { - expect( - await value(` - const shared = { value: 1 } - return JSON.stringify({ left: shared, right: shared }, (key, item) => item) - `), - ).toBe('{"left":{"value":1},"right":{"value":1}}') - }) - - test("function replacers replace values and map undefined to omission or null", async () => { - expect( - await value(`return JSON.stringify({ a: 1, nested: { b: [1] } }, (key, item) => item === 1 ? undefined : item)`), - ).toBe('{"nested":{"b":[null]}}') - expect(await value(`return JSON.stringify(null, (key) => key === "" ? { value: 1 } : 2)`)).toBe('{"value":2}') - expect(await value(`return JSON.stringify(1, () => undefined) === undefined`)).toBe(true) - }) - - test("callable replacer results follow JSON omission semantics", async () => { - expect( - await value(` - const fn = () => 1 - return [ - JSON.stringify({ user: 1, builtin: 2 }, (key, item) => key === "user" ? fn : key === "builtin" ? Math.abs : item), - JSON.stringify([1, 2], (key, item) => key === "0" ? fn : key === "1" ? Number : item), - JSON.stringify(null, () => "abc".includes) === undefined, - ] - `), - ).toEqual(["{}", "[null,null]", true]) - }) - - test("built-in toJSON conversion runs before the function replacer", async () => { - expect( - await value(` - const seen = [] - const output = JSON.stringify({ date: new Date(0), url: new URL("https://example.test/a") }, (key, item) => { - if (key === "date" || key === "url") seen.push(typeof item) - return item - }) - return [output, seen] - `), - ).toEqual(['{"date":"1970-01-01T00:00:00.000Z","url":"https://example.test/a"}', ["string", "string"]]) - }) - - test("test/built-ins/JSON/stringify/replacer-function-abrupt.js", async () => { - expect( - await value(`try { JSON.stringify({}, () => { throw "stop" }) } catch (error) { return error } return "missed"`), - ).toBe("stop") - }) -}) - -describe("CodeMode JSON callback boundaries", () => { - test("revivers and replacers see the holder as this", async () => { - expect( - await value(` - const revived = JSON.parse('{"a":{"b":1}}', function (key, item) { return key === "b" ? this.b + 1 : item }) - const text = JSON.stringify({ a: 1, b: 2 }, function (key, item) { return key === "a" ? this.b : item }) - return [revived, text] - `), - ).toEqual([{ a: { b: 2 } }, '{"a":2,"b":2}']) - }) - - test("prototype-named keys parse as own data and reach the reviver", async () => { - expect( - await value(` - const seen = [] - const parsed = JSON.parse('{"__proto__":{"polluted":1},"constructor":2}', (key, item) => { seen.push(key); return item }) - return [seen, parsed.__proto__.polluted, parsed.constructor, ({}).polluted, Object.keys(parsed)] - `), - ).toEqual([["polluted", "__proto__", "constructor", ""], 1, 2, null, ["__proto__", "constructor"]]) - }) - - test("JSON.stringify serializes prototype-named own keys", async () => { - expect(await value(`return JSON.stringify({ constructor: 1, __proto__: 2 })`)).toBe( - '{"constructor":1,"__proto__":2}', - ) - }) -}) diff --git a/packages/codemode/test/labeled-control-test262.test.ts b/packages/codemode/test/labeled-control-test262.test.ts deleted file mode 100644 index 37866b17cb4..00000000000 --- a/packages/codemode/test/labeled-control-test262.test.ts +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Portions adapted from Test262 at revision 250f204f23a9249ff204be2baec29600faae7b75: - * - test/language/statements/labeled/continue.js - * - test/language/statements/break/S12.8_A4_T1.js - * - test/language/statements/continue/simple-and-labeled.js - * - test/language/statements/continue/labeled-continue.js - * - test/language/statements/continue/nested-let-bound-for-loops-labeled-continue.js - * - * Copyright (C) 2009 the Sputnik authors. All rights reserved. - * Copyright (C) 2014, 2016 the V8 project authors. All rights reserved. - * Test262 portions are governed by the BSD license in LICENSE.test262. - */ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" - -const execute = (code: string) => Effect.runPromise(CodeMode.execute({ code, tools: {} })) - -const value = async (code: string) => { - const result = await execute(code) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -describe("Test262 labeled break adaptations", () => { - test("break exits the matching labeled statement", async () => { - expect( - await value(` - const visited = [] - target: { - visited.push(1) - break target - visited.push(2) - } - visited.push(3) - return visited - `), - ).toEqual([1, 3]) - }) - - test("break crosses nested loops and switches without being consumed early", async () => { - expect( - await value(` - const visited = [] - outer: for (const item of [1, 2, 3]) { - switch (item) { - case 2: - break outer - default: - visited.push(item) - } - } - return visited - `), - ).toEqual([1]) - }) - - test("break targets every supported loop form", async () => { - expect( - await value(` - const counts = { while: 0, doWhile: 0, for: 0, forOf: 0, forIn: 0 } - whileLabel: while (true) { - counts.while++ - break whileLabel - } - doLabel: do { - counts.doWhile++ - break doLabel - } while (true) - forLabel: for (;;) { - counts.for++ - break forLabel - } - forOfLabel: for (const item of [1, 2]) { - counts.forOf++ - break forOfLabel - } - forInLabel: for (const key in { a: 1, b: 2 }) { - counts.forIn++ - break forInLabel - } - return counts - `), - ).toEqual({ while: 1, doWhile: 1, for: 1, forOf: 1, forIn: 1 }) - }) - - test("nested labels consume only their matching break", async () => { - expect( - await value(` - const visited = [] - outer: { - inner: { - visited.push(1) - break outer - } - visited.push(2) - } - visited.push(3) - return visited - `), - ).toEqual([1, 3]) - }) -}) - -describe("Test262 labeled continue adaptations", () => { - test("continue targets its labeled for loop", async () => { - expect( - await value(` - let count = 0 - label: for (let index = 0; index < 10; index++) { - count++ - continue label - } - return count - `), - ).toBe(10) - }) - - test("continue escapes an inner loop for the targeted outer loop", async () => { - expect( - await value(` - let count = 0 - outer: for (let x = 0; x < 10; x++) { - let y = 0 - while (true) { - y++ - count++ - if (y === 1) continue outer - throw new Error("inner loop consumed the outer continue") - } - } - return count - `), - ).toBe(10) - }) - - test("multiple labels can target the same iteration statement", async () => { - expect( - await value(` - const visited = [] - outer: inner: for (const item of [1, 2, 3]) { - visited.push(item) - continue outer - } - return visited - `), - ).toEqual([1, 2, 3]) - }) - - test("labeled continue works for every supported loop form", async () => { - expect( - await value(` - const counts = { while: 0, doWhile: 0, forOf: 0, forIn: 0 } - let index = 0 - whileLabel: while (index++ < 2) { - counts.while++ - continue whileLabel - } - - index = 0 - doLabel: do { - counts.doWhile++ - if (index++ < 1) continue doLabel - } while (index < 2) - - forOfLabel: for (const item of [1, 2]) { - counts.forOf += item - continue forOfLabel - } - - forInLabel: for (const key in { a: 1, b: 2 }) { - counts.forIn++ - continue forInLabel - } - return counts - `), - ).toEqual({ while: 2, doWhile: 2, forOf: 3, forIn: 2 }) - }) - - test("labeled continues preserve per-iteration lexical bindings", async () => { - expect( - await value(` - const classic = [] - classicLabel: for (let index = 0; index < 3; index++) { - classic.push(() => index) - continue classicLabel - } - - const nested = [] - nestedLabel: for (let outer = 0; outer < 3; outer++) { - for (let inner = 0; inner < 2; inner++) { - nested.push(() => outer) - continue nestedLabel - } - } - - const forOf = [] - forOfLabel: for (const item of [1, 2, 3]) { - forOf.push(() => item) - continue forOfLabel - } - return [classic.map((read) => read()), nested.map((read) => read()), forOf.map((read) => read())] - `), - ).toEqual([ - [0, 1, 2], - [0, 1, 2], - [1, 2, 3], - ]) - }) - - test("finally completions override labeled loop control", async () => { - expect( - await value(` - const visited = [] - breakWins: for (const item of [1, 2, 3]) { - try { - continue breakWins - } finally { - visited.push(item) - break breakWins - } - } - - continueWins: for (const item of [4, 5, 6]) { - try { - break continueWins - } finally { - visited.push(item) - continue continueWins - } - } - return visited - `), - ).toEqual([1, 4, 5, 6]) - }) - - test("a label on a non-iteration statement is not a continue target", async () => { - const result = await execute(` - do { - target: { - continue target - } - } while (false) - `) - expect(result.ok).toBe(false) - if (result.ok) return - expect(result.error.kind).toBe("ParseError") - }) -}) diff --git a/packages/codemode/test/language-boundary.test.ts b/packages/codemode/test/language-boundary.test.ts index 2b6316f7b55..2dbadb93df4 100644 --- a/packages/codemode/test/language-boundary.test.ts +++ b/packages/codemode/test/language-boundary.test.ts @@ -2,24 +2,19 @@ import { expect, test } from "bun:test" import { Glob } from "bun" import path from "node:path" -// The language layer (src/language/) knows nothing about Code Mode (src/codemode/), which is built on it. +// Code Mode uses the language only through psychoscript's public entry point. -test("nothing in the language layer imports Code Mode", async () => { - const root = path.join(import.meta.dir, "..") - const src = path.join(root, "src") - const language = path.join(src, "language") - const files = await Array.fromAsync(new Glob("**/*.ts").scan({ cwd: language })) - expect(files.length).toBeGreaterThan(0) - const outside = [] - for (const file of files) { - const text = await Bun.file(path.join(language, file)).text() - for (const match of text.matchAll(/(?:from|import)\s*\(?\s*"(\.[^"]+)"/g)) { - const target = path.resolve(path.dirname(path.join(language, file)), match[1]!) - // The package's own files (package.json) are shared; only the rest of src is off limits. - if (target.startsWith(src + path.sep) && !target.startsWith(language + path.sep)) { - outside.push(`${file} imports ${match[1]}`) - } - } - } - expect(outside).toEqual([]) +test("Code Mode imports psychoscript only by its package name", async () => { + const src = path.join(import.meta.dir, "..", "src") + const files = await Array.fromAsync(new Glob("**/*.ts").scan({ cwd: src })) + const deep = ( + await Promise.all( + files.map(async (file) => + [...(await Bun.file(path.join(src, file)).text()).matchAll(/"(psychoscript\/[^"]*)"/g)].map( + (match) => `${file} imports ${match[1]}`, + ), + ), + ) + ).flat() + expect(deep).toEqual([]) }) diff --git a/packages/codemode/test/language.test.ts b/packages/codemode/test/language.test.ts deleted file mode 100644 index c5d12d0edf9..00000000000 --- a/packages/codemode/test/language.test.ts +++ /dev/null @@ -1,365 +0,0 @@ -import { describe, expect, test } from "bun:test" -import { Effect, Fiber } from "effect" -import { Host, Runtime, toBytes } from "../src/language/index.js" - -// The language layer on its own: host functions, namespaces, failures, and per-run state, with no tools. - -const run = (runtime: Runtime.Runtime, code: string) => - Effect.runPromise(runtime.execute(code) as Effect.Effect) - -const value = async (runtime: Runtime.Runtime, code: string) => { - const result = await run(runtime, code) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -/** A latch the test opens by hand. */ -const latch = () => { - let resolve!: (value: A) => void - const promise = new Promise((done) => (resolve = done)) - return { promise, resolve } -} - -describe("Host.fn", () => { - test("a sync function returns its value, or blocks on an Effect, before the next statement", async () => { - const runtime = Runtime.make({ - globals: () => ({ - double: Host.fn(([n]) => (n as number) * 2), - later: Host.fn(([n]) => Effect.succeed((n as number) + 1)), - }), - }) - expect(await value(runtime, `const a = double(2); const b = later(a); return [a, b, typeof double]`)).toEqual([ - 4, - 5, - "function", - ]) - }) - - test("an async function hands the program a promise", async () => { - const runtime = Runtime.make({ globals: () => ({ load: Host.fn(([n]) => Effect.succeed(n), { type: "async" }) }) }) - expect(await value(runtime, `const p = load(1); return [p instanceof Promise, await p]`)).toEqual([true, 1]) - }) - - test("a sync-thenable result can be used directly, awaited, or chained", async () => { - const runtime = Runtime.make({ - globals: () => ({ find: Host.fn(() => Effect.succeed({ items: [1, 2] }), { type: "sync-thenable" }) }), - }) - expect( - await value( - runtime, - `return [find().items.length, (await find()).items.length, await find().then((r) => r.items[1]), Object.keys(find())]`, - ), - ).toEqual([2, 2, 2, ["items"]]) - }) - - test("every call gets its key, :", async () => { - const keys: Array = [] - const runtime = Runtime.make({ globals: () => ({ note: Host.fn((_, call) => void keys.push(call.key)) }) }) - await Effect.runPromise(runtime.program(`note(); note()`, { runId: "r" }).run()) - expect(keys).toEqual(["r:0", "r:1"]) - }) - - test("arguments and results cross as structured copies", async () => { - let seen: unknown - const runtime = Runtime.make({ - globals: () => ({ - keep: Host.fn(([input]) => { - seen = input - return { when: new Date(0), tags: new Set(["a"]), read: () => "called" } - }), - }), - }) - expect( - await value( - runtime, - `const r = keep({ at: new Date(5), m: new Map([["k", 1]]) }); return [r.when.getTime(), r.tags.has("a"), r.read()]`, - ), - ).toEqual([0, true, "called"]) - expect(seen).toEqual({ at: new Date(5), m: new Map([["k", 1]]) }) - }) - - test("a function inside a result crosses back as itself only to a function that takes functions", async () => { - const read = () => "called" - const runtime = Runtime.make({ - globals: () => ({ - open: Host.fn(() => ({ read })), - takes: Host.fn(([input]) => (input as { readonly read: unknown }).read === read, { takesFunctions: true }), - refuses: Host.fn(() => true), - }), - }) - expect(await value(runtime, `return takes({ read: open().read })`)).toBe(true) - for (const code of [`refuses(open().read)`, `takes(takes)`, `takes(() => 1)`]) { - expect(await run(runtime, code)).toMatchObject({ - ok: false, - error: { message: expect.stringContaining("contains a function, which cannot be passed to the host") }, - }) - } - }) - - test("a constructible function is called by new, and gives what it returns", async () => { - const runtime = Runtime.make({ - globals: () => ({ - Box: Host.fn(([item]) => ({ item }), { constructible: true }), - Later: Host.fn(([item]) => Effect.succeed({ item }), { constructible: true }), - plain: Host.fn(() => 1), - }), - }) - expect(await value(runtime, `return [new Box(1).item, new Later(2).item, new Later(...[3]).item]`)).toEqual([ - 1, 2, 3, - ]) - expect(await run(runtime, `new plain()`)).toMatchObject({ ok: false }) - }) - - test("idempotent applies only to async functions", () => { - // @ts-expect-error a sync function can't be idempotent - Host.fn(() => 1, { idempotent: true }) - // @ts-expect-error a sync-thenable function can't be idempotent - Host.fn(() => 1, { type: "sync-thenable", idempotent: true }) - expect(Host.fn(() => 1, { type: "async", idempotent: true }).idempotent).toBe(true) - }) -}) - -describe("Host.namespace and Host.fail", () => { - const api = Host.namespace({ - keys: (path) => (path.length === 0 ? ["issues"] : ["list"]), - resolve: (path) => - path.join(".") === "issues.list" - ? Host.fn(() => Effect.succeed(["#1"]), { type: "async" }) - : Host.missing(`No api.${path.join(".")}`, ["Try api.issues.list."], "NotFound"), - }) - const runtime = Runtime.make({ - globals: () => ({ api, refuse: Host.fn(() => Effect.fail(Host.fail("Refused", "Not today", ["Ask again."]))) }), - }) - - test("a namespace is a lazy, path-addressed object of functions", async () => { - expect( - await value(runtime, `return [await api.issues.list(), Object.keys(api), Object.keys(api.issues), typeof api.x]`), - ).toEqual([["#1"], ["issues"], ["list"], "function"]) - }) - - test("a missing function and a host failure keep their kind and suggestions", async () => { - expect(await run(runtime, `return api.issues.nope()`)).toMatchObject({ - ok: false, - error: { kind: "NotFound", message: "No api.issues.nope", suggestions: ["Try api.issues.list."] }, - }) - expect(await run(runtime, `refuse()`)).toMatchObject({ - ok: false, - error: { kind: "Refused", message: "Not today", suggestions: ["Ask again."] }, - }) - }) -}) - -describe("per-run state", () => { - test("run.metadata is the result's, and a resumed run gets it back with fresh globals", async () => { - const gate = latch() - const waiting = latch() - let made = 0 - const runtime = Runtime.make({ - globals: (run) => { - made++ - const state = (run.metadata ??= { count: 0 }) as { count: number } - return { - count: Host.fn(() => ++state.count), - wait: Host.fn( - () => - Effect.andThen( - Effect.sync(waiting.resolve), - Effect.promise(() => gate.promise), - ), - { type: "async", idempotent: true }, - ), - } - }, - }) - const program = runtime.program(`count(); count(); await wait(); return count()`, { runId: "m" }) - const fiber = Effect.runFork(program.run()) - await waiting.promise - const suspended = await Effect.runPromise(program.suspend()) - if (suspended.ok !== "suspended") throw new Error("expected a suspended run") - expect(suspended.state.header.metadata).toEqual({ count: 2 }) - expect(await Effect.runPromise(Fiber.join(fiber))).toBe(suspended) - gate.resolve() - expect(await Effect.runPromise(runtime.resume(toBytes(suspended.state)).run())).toMatchObject({ - ok: true, - value: 3, - metadata: { count: 3 }, - }) - // Made at the start and at the resume (and at every step in the round-trip test mode). - expect(made).toBeGreaterThanOrEqual(2) - }) - - test("a suspend fails while a call that isn't idempotent runs", async () => { - const called = latch() - const runtime = Runtime.make({ - globals: () => ({ - slow: Host.fn(() => Effect.andThen(Effect.sync(called.resolve), Effect.never), { type: "async" }), - }), - }) - const program = runtime.program(`await slow()`) - const fiber = Effect.runFork(program.run()) - await called.promise - const error = await Effect.runPromise(Effect.flip(program.suspend())) - expect(error.running).toMatchObject([{ path: "slow" }]) - await Effect.runPromise(Fiber.interrupt(fiber)) - }) - - test("a suspend fails while a call holds a host function, even an idempotent one", async () => { - const called = latch() - const runtime = Runtime.make({ - globals: () => ({ - open: Host.fn(() => ({ read: () => "called" })), - slow: Host.fn(() => Effect.andThen(Effect.sync(called.resolve), Effect.never), { - type: "async", - idempotent: true, - takesFunctions: true, - }), - }), - }) - const program = runtime.program(`await slow(open().read)`) - const fiber = Effect.runFork(program.run()) - await called.promise - const error = await Effect.runPromise(Effect.flip(program.suspend())) - expect(error.running).toMatchObject([{ path: "slow" }]) - await Effect.runPromise(Fiber.interrupt(fiber)) - }) - - test("a durable function keeps running across a suspend and is waited on again", async () => { - const jobs = new Map>>() - const waiting = latch() - const runtime = Runtime.make({ - globals: () => ({ - job: Host.durableFn({ - start: (_, call) => Effect.sync(() => (jobs.set(call.key, latch()), call.key)), - wait: (key) => - Effect.andThen( - Effect.sync(waiting.resolve), - Effect.promise(() => jobs.get(key)!.promise), - ), - cancel: () => Effect.void, - }), - }), - }) - const program = runtime.program(`return (await job()) + 1`, { runId: "d" }) - const fiber = Effect.runFork(program.run()) - // In `wait`, so the call is started and its data saved. - await waiting.promise - const suspended = await Effect.runPromise(program.suspend()) - if (suspended.ok !== "suspended") throw new Error("expected a suspended run") - await Effect.runPromise(Fiber.join(fiber)) - const resumed = Effect.runPromise(runtime.resume(suspended.state).run()) - jobs.get("d:0")!.resolve(41) - expect(await resumed).toMatchObject({ ok: true, value: 42 }) - }) -}) - -describe("translate", () => { - const translating = (translate?: Runtime.Translate, limits?: Runtime.Limits) => { - const calls: Array> = [] - const runtime = Runtime.make({ - translate, - limits, - globals: () => ({ - keep: Host.fn((args) => void calls.push(args)), - send: Host.fn((args) => Effect.sync(() => void calls.push(args)), { type: "async" }), - later: Host.fn(([n]) => Effect.succeed(n), { type: "async" }), - never: Host.fn(() => Effect.never, { type: "async" }), - }), - }) - return { runtime, calls } - } - - test("by default, a function or a promise inside an argument fails the call", async () => { - const strict = translating().runtime - for (const [code, message] of [ - ["keep({ f() {} })", "Argument 1 to keep contains a function, which cannot be passed to the host."], - ["keep([Promise.resolve(1)])", "Argument 1 to keep contains an un-awaited Promise, which cannot be passed"], - ["await send(() => 1)", "Argument 1 to send contains a function"], - ] as const) { - const result = await run(strict, code) - expect(result.ok).toBe(false) - if (!result.ok) expect(result.error.message).toContain(message) - } - }) - - test("functions: drop leaves functions out as JSON.stringify does", async () => { - const { runtime, calls } = translating({ functions: "drop" }) - await value( - runtime, - `keep({ q: "x", format(v) { return v }, nested: { f: Math.max } }, [1, () => 2, keep], () => 3, new Map([["k", () => 1]]))`, - ) - expect(calls).toEqual([[{ q: "x", nested: {} }, [1, null, null], undefined, new Map([["k", undefined]])]]) - expect(Object.keys(calls[0]![0] as object)).toEqual(["q", "nested"]) - const result = await run(runtime, `keep({ p: Promise.resolve(1) })`) - expect(result.ok).toBe(false) - if (!result.ok) expect(result.error.message).toContain("un-awaited Promise") - }) - - test("promises: await waits for every promise inside the arguments and uses its value", async () => { - const { runtime, calls } = translating({ promises: "await" }) - expect( - await value( - runtime, - ` - const slow = (async () => { await null; await null; return "slow" })() - const a = keep({ n: Promise.resolve(5), list: [later(1), slow] }, later({ deep: later(2) })) - const b = await send(slow, new Promise((resolve) => resolve(later(3)))) - return [a, b] - `, - ), - ).toEqual([null, null]) - expect(calls).toEqual([[{ n: 5, list: [1, "slow"] }, { deep: 2 }], ["slow", 3]]) - const result = await run(runtime, `keep({ f() {} })`) - expect(result.ok).toBe(false) - if (!result.ok) expect(result.error.message).toContain("contains a function") - }) - - test("promises: await fails the call with a rejection's reason", async () => { - const { runtime, calls } = translating({ promises: "await" }) - expect( - await value( - runtime, - ` - const failing = () => Promise.reject(new RangeError("nope")) - let thrown - try { keep({ n: failing() }) } catch (error) { thrown = error } - const sent = send([later(1), failing()]) - return [thrown instanceof RangeError, thrown.message, sent instanceof Promise, await sent.catch((e) => e.message)] - `, - ), - ).toEqual([true, "nope", true, "nope"]) - expect(calls).toEqual([]) - }) - - test("promises: await waits on a promise that never settles until the timeout", async () => { - const result = await run(translating({ promises: "await" }, { timeoutMs: 50 }).runtime, `keep({ n: never() })`) - expect(result.ok).toBe(false) - if (!result.ok) expect(result.error.kind).toBe("TimeoutExceeded") - }) - - test("promises: await keeps waiting across a suspend", async () => { - const started = latch() - const gate = latch() - const calls: Array> = [] - const runtime = Runtime.make({ - translate: { promises: "await" }, - globals: () => ({ - keep: Host.fn((args) => (calls.push(args), "kept")), - slow: Host.fn( - () => Effect.andThen(Effect.sync(started.resolve), Effect.promise(() => gate.promise)), - { type: "async", idempotent: true }, - ), - }), - }) - const program = runtime.program(`return [keep({ n: slow() }), await slow()]`) - const fiber = Effect.runFork(program.run()) - await started.promise - const suspended = await Effect.runPromise(program.suspend()) - if (suspended.ok !== "suspended") throw new Error("expected a suspended run") - await Effect.runPromise(Fiber.join(fiber)) - expect(calls).toEqual([]) - const resumed = Effect.runPromise(runtime.resume(suspended.state).run()) - gate.resolve(7) - expect(await resumed).toMatchObject({ ok: true, value: ["kept", 7] }) - expect(calls).toEqual([[{ n: 7 }]]) - }) -}) diff --git a/packages/codemode/test/lexical-test262.test.ts b/packages/codemode/test/lexical-test262.test.ts deleted file mode 100644 index 6f67a9acb9b..00000000000 --- a/packages/codemode/test/lexical-test262.test.ts +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Portions adapted from Test262 at revision 250f204f23a9249ff204be2baec29600faae7b75: - * - test/language/statements/let/global-use-before-initialization-in-prior-statement.js - * - test/language/statements/let/block-local-use-before-initialization-in-prior-statement.js - * - test/language/statements/const/global-use-before-initialization-in-prior-statement.js - * - test/language/statements/const/block-local-use-before-initialization-in-prior-statement.js - * - test/language/statements/let/block-local-use-before-initialization-in-declaration-statement.js - * - test/language/statements/const/block-local-use-before-initialization-in-declaration-statement.js - * - test/language/statements/let/block-local-closure-set-before-initialization.js - * - test/language/statements/for-of/head-let-bound-names-fordecl-tdz.js - * - test/language/statements/for-in/head-let-bound-names-fordecl-tdz.js - * - test/language/statements/let/syntax/let-iteration-variable-is-freshly-allocated-for-each-iteration-single-let-binding.js - * - test/language/statements/let/syntax/let-iteration-variable-is-freshly-allocated-for-each-iteration-multi-let-binding.js - * - test/language/statements/for-of/head-let-fresh-binding-per-iteration.js - * - test/language/statements/for-in/head-let-fresh-binding-per-iteration.js - * - test/language/statements/for/scope-head-lex-open.js - * - test/language/statements/for/scope-body-lex-open.js - * - test/language/statements/switch/scope-lex-open-case.js - * - test/language/statements/switch/scope-lex-close-case.js - * - test/language/statements/function/dflt-params-ref-prior.js - * - test/language/statements/function/dflt-params-ref-later.js - * - test/language/statements/function/dflt-params-ref-self.js - * - * Copyright (C) 2011, 2014, 2016 the V8 project authors. All rights reserved. - * Test262 portions are governed by the BSD license in LICENSE.test262. - */ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" - -const value = async (code: string) => { - const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} })) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -describe("Test262 lexical temporal dead zones", () => { - test("program and block bindings exist before initialization", async () => { - expect( - await value(` - const errors = [] - try { programLet; let programLet } catch (error) { errors.push(error.name) } - try { programConst; const programConst = 1 } catch (error) { errors.push(error.name) } - try { { blockLet; let blockLet } } catch (error) { errors.push(error.name) } - try { { blockConst; const blockConst = 1 } } catch (error) { errors.push(error.name) } - return errors - `), - ).toEqual(["ReferenceError", "ReferenceError", "ReferenceError", "ReferenceError"]) - }) - - test("self-initialization and closure assignment observe the TDZ", async () => { - expect( - await value(` - const errors = [] - try { { let item = item + 1 } } catch (error) { errors.push(error.name) } - try { { const item = item + 1 } } catch (error) { errors.push(error.name) } - try { - { - function assign() { item = 1 } - assign() - let item - } - } catch (error) { errors.push(error.name) } - return errors - `), - ).toEqual(["ReferenceError", "ReferenceError", "ReferenceError"]) - }) - - test("for-of and for-in bound names are in the head TDZ", async () => { - expect( - await value(` - const errors = [] - try { let item = [1]; for (let item of item) {} } catch (error) { errors.push(error.name) } - try { let item = { value: 1 }; for (let item in item) {} } catch (error) { errors.push(error.name) } - return errors - `), - ).toEqual(["ReferenceError", "ReferenceError"]) - }) -}) - -describe("Test262 lexical loop environments", () => { - test("classic for creates fresh single and multiple bindings", async () => { - expect( - await value(` - const single = [] - for (let index = 0; index < 5; ++index) single.push(() => index) - - const left = [] - const right = [] - for (let first = 0, second = 10; first < 5; ++first, ++second) { - left.push(() => first) - right.push(() => second) - } - return [ - single.map((read) => read()), - left.map((read) => read()), - right.map((read) => read()), - ] - `), - ).toEqual([ - [0, 1, 2, 3, 4], - [0, 1, 2, 3, 4], - [10, 11, 12, 13, 14], - ]) - }) - - test("for-of and for-in create fresh bindings", async () => { - expect( - await value(` - const values = [] - for (let item of [1, 2, 3]) values.push(() => item) - - const keys = {} - for (let key in { first: 1, second: 2, third: 3 }) keys[key] = () => key - return [values.map((read) => read()), keys.first(), keys.second(), keys.third()] - `), - ).toEqual([[1, 2, 3], "first", "second", "third"]) - }) - - test("classic for separates declaration and per-iteration environments", async () => { - expect( - await value(` - let before - let testRead - let bodyRead - let updateRead - let run = true - for ( - let item = "outside", ignored = before = () => item; - run && (item = "inside", testRead = () => item); - updateRead = () => item - ) bodyRead = () => item, run = false - return [before(), testRead(), bodyRead(), updateRead()] - `), - ).toEqual(["outside", "inside", "inside", "inside"]) - }) -}) - -describe("Test262 switch and parameter environments", () => { - test("switch creates its lexical environment after the discriminant", async () => { - expect( - await value(` - let item = "outside" - let discriminantRead - let selectorRead - let statementRead - switch ((discriminantRead = () => item, null)) { - case (selectorRead = () => item, null): - statementRead = () => item - let item = "inside" - } - return [discriminantRead(), selectorRead(), statementRead()] - `), - ).toEqual(["outside", "inside", "inside"]) - }) - - test("all switch cases share one lexical environment that closes afterward", async () => { - expect( - await value(` - let item = "outside" - let firstRead - let secondRead - switch (null) { - case null: - let item = "inside" - firstRead = () => item - case null: - secondRead = () => item - } - return [firstRead(), secondRead(), item] - `), - ).toEqual(["inside", "inside", "outside"]) - }) - - test("parameter defaults see prior bindings but not self or later bindings", async () => { - expect( - await value(` - function prior(first, second = first, third = second) { return [first, second, third] } - function later(first = second, second) { return first } - function self(item = item) { return item } - function failure(run) { - try { return run() } catch (error) { return error.name } - } - return [prior(3), failure(later), failure(self)] - `), - ).toEqual([[3, 3, 3], "ReferenceError", "ReferenceError"]) - }) -}) diff --git a/packages/codemode/test/limits.test.ts b/packages/codemode/test/limits.test.ts deleted file mode 100644 index 7388bf9f583..00000000000 --- a/packages/codemode/test/limits.test.ts +++ /dev/null @@ -1,130 +0,0 @@ -import { describe, expect, test } from "bun:test" -import { Cause, Deferred, Effect, Exit, Fiber, Schema } from "effect" -import { CodeMode, Tool } from "../src/index.js" -import { MAX_ARRAY_LENGTH, MAX_PENDING_PROMISES, MAX_STRING_LENGTH } from "../src/language/runtime/limits.js" - -const runtime = CodeMode.make({ tools: {} }) - -const value = async (code: string) => { - const result = await Effect.runPromise(runtime.execute(code)) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -const failure = async (code: string) => { - const result = await Effect.runPromise(runtime.execute(code)) - if (result.ok) throw new Error(`expected failure, got value ${JSON.stringify(result.value)}`) - return result.error.message -} - -const S = MAX_STRING_LENGTH -const A = MAX_ARRAY_LENGTH - -describe("one built-in cannot build an unbounded value", () => { - test("strings: repeat, pad, concat, join, +, template, JSON.stringify", async () => { - expect(await value(`return "x".repeat(${S}).length`)).toBe(S) - for (const code of [ - `"x".repeat(${S + 1})`, - `"x".padStart(${S + 1})`, - `"x".padEnd(${S + 1}, "y")`, - `"x".repeat(${S}).concat("y")`, - `["x".repeat(${S}), "y"].join("")`, - `"x".repeat(${S}) + "y"`, - `\`\${"x".repeat(${S})}y\``, - `JSON.stringify("x".repeat(${S}))`, - ]) { - expect(await failure(`try { ${code} } catch (e) { throw Error(e.name + ": " + e.message) }`)).toContain( - "RangeError: Invalid string length", - ) - } - }) - - // split and matchAll share the same result check but must build ten million items first to reach it, - // which is too slow for CI; flat() over MAX_ARRAY_LENGTH (10M) elements still needs a 15s budget on Windows. - test("arrays: constructor, length, Array.from, concat, flat", async () => { - expect(await value(`return Array(${A}).length`)).toBe(A) - for (const code of [ - `Array(${A + 1})`, - `const a = []; a.length = ${A + 1}`, - `Array.from({ length: ${A + 1} })`, - `Array(${A}).concat([1])`, - `[Array(${A}).fill(0), [1]].flat()`, - ]) { - expect(await failure(`try { ${code} } catch (e) { throw Error(e.name + ": " + e.message) }`)).toContain( - "RangeError: Invalid array length", - ) - } - }, 15_000) - - test("promises: too many pending at once, while settled ones do not count", async () => { - const n = MAX_PENDING_PROMISES - expect(await value(`for (let i = 0; i < ${n * 2}; i++) Promise.resolve(i); return 1`)).toBe(1) - expect( - await failure( - `try { for (let i = 0; i <= ${n}; i++) new Promise(() => {}) } catch (e) { throw Error(e.name + ": " + e.message) }`, - ), - ).toContain("RangeError: Too many pending promises") - expect(await failure(`await Promise.all(Array(${n + 1}).fill(0).map(() => new Promise(() => {})))`)).toContain( - "Too many pending promises", - ) - }, 10_000) -}) - -describe("the host stays in control", () => { - test("other host work keeps running while one long job runs", async () => { - // Once the loop starts, the runner yields to the host every millisecond, so the host takes its 20 turns within - // about 20 slices: at most about a million iterations on a fast machine, far short of the job's 30 million. A job - // that kept the thread would finish first. Counting turns instead of timing them keeps this independent of how - // fast the loop runs, and waiting for the start keeps a cold engine's setup out of the count. - const exit = await Effect.runPromise( - Effect.gen(function* () { - const started = yield* Deferred.make() - const job = yield* Effect.forkChild( - CodeMode.make({ - tools: { - host: { - started: Tool.make({ - description: "Mark the loop as started", - input: Schema.Struct({}), - output: Schema.Boolean, - execute: () => Deferred.succeed(started, undefined), - }), - }, - }, - }).execute( - `await tools.host.started({}); let t = 0; for (let i = 0; i < 30_000_000; i++) t += i % 3; return t`, - ), - ) - yield* Deferred.await(started) - for (let turn = 0; turn < 20; turn++) yield* Effect.yieldNow - yield* Fiber.interrupt(job) - return yield* Fiber.await(job) - }), - ) - expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true) - }) - - // Each case would run for seconds or forever; the timeout must still stop it promptly. - test.each([ - ["a loop of only built-in calls", `return Iterator.from({ next: Object }).drop(Infinity).next()`], - [ - "serializing shared references", - `let a = [0]; for (let i = 0; i < 24; i++) a = [a, a]; return JSON.stringify(a).length`, - ], - ["copying out shared references", `let a = [0]; for (let i = 0; i < 24; i++) a = [a, a]; return a`], - [ - "reporting many unhandled rejections", - `const a = Array(10_000).fill(0); for (let i = 0; i < 20_000; i++) Promise.reject(a); return 1`, - ], - ])("%s still times out", async (_, code) => { - const result = await Effect.runPromise(CodeMode.make({ limits: { timeoutMs: 100 } }).execute(code)) - expect(result).toMatchObject({ ok: false, error: { kind: "TimeoutExceeded" } }) - }) - - test("nesting deeper than the host stack fails cleanly, and the next run is unaffected", async () => { - expect(await failure(`const f = () => f; f${"()".repeat(100_000)}; return 1`)).toBe( - "Execution exceeded the maximum nesting depth.", - ) - expect(await value(`const f = () => f; f${"()".repeat(500)}; return 1`)).toBe(1) - }) -}) diff --git a/packages/codemode/test/new-expression.test.ts b/packages/codemode/test/new-expression.test.ts deleted file mode 100644 index 87f5a27a2cf..00000000000 --- a/packages/codemode/test/new-expression.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { describe, expect, test } from "bun:test" -import { Effect, Schema } from "effect" -import { CodeMode, Tool } from "../src/index.js" - -// `new` is supported syntax; only the callee decides whether construction succeeds. A callee without -// construction support is a TypeError naming it, like JS, rather than an unsupported-syntax diagnostic -// that would suggest `new` itself is unavailable. -const tools = { - echo: Tool.make({ - description: "Echo", - input: Schema.Struct({}), - output: Schema.Struct({}), - execute: () => Effect.succeed({}), - }), -} -const run = (code: string) => Effect.runPromise(CodeMode.execute({ code, tools })) -const value = async (code: string) => { - const result = await run(code) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} -const error = async (code: string) => { - const result = await run(code) - if (result.ok) throw new Error(`expected failure, got value ${JSON.stringify(result.value)}`) - return result.error -} - -describe("new on a non-constructible callee", () => { - test("built-in functions without construction point at the plain call", async () => { - // Number is a real constructor in JS, so the message must not claim otherwise. - const failure = await error(`return new Number(42)`) - expect(failure.kind).toBe("ExecutionFailure") - expect(failure.message).toStartWith( - "TypeError: new Number(...) is not supported; call Number(...) without new instead.", - ) - expect(failure.suggestions).toBeUndefined() - expect((await error(`return new String("a")`)).message).toStartWith("TypeError: new String(...) is not supported") - expect((await error(`return new Math.abs(1)`)).message).toStartWith( - "TypeError: new Math.abs(...) is not supported; call Math.abs(...) without new instead.", - ) - }) - - test("non-callable values are not constructors", async () => { - expect((await error(`return new tools.echo()`)).message).toStartWith("TypeError: tools.echo is not a constructor.") - expect((await error(`return new (1)()`)).message).toStartWith("TypeError: The called value is not a constructor.") - expect((await error(`const Date = 5; return new Date()`)).message).toStartWith( - "TypeError: Date is not a constructor.", - ) - }) - - test("user-defined functions explain the documented gap", async () => { - const failure = await error(`function Point(x) { return { x } }; return new Point(1)`) - expect(failure.message).toStartWith( - "TypeError: Point is not a constructor: only classes can be constructed with new. Use a class, or call it as a function that returns an object.", - ) - expect((await error(`const make = () => ({}); return new make()`)).message).toStartWith( - "TypeError: make is not a constructor", - ) - }) - - test("the failure is a catchable TypeError", async () => { - expect( - await value(` - try { new Number(1) } catch (error) { return [error.name, error instanceof TypeError] } - `), - ).toEqual(["TypeError", true]) - }) - - test("an undeclared callee still fails as an unknown identifier", async () => { - expect((await error(`return new Function("return 1")`)).message).toContain("Function") - expect((await error(`return new Function("return 1")`)).message).not.toContain("not a constructor") - }) - - test("extending a built-in other than errors is refused", async () => { - const failure = await error(`class A extends Object {}; return new A()`) - expect(failure.message).toStartWith( - "TypeError: Extending the built-in Object is not supported. Only classes and Error types can be extended.", - ) - }) -}) diff --git a/packages/codemode/test/object-coercion-test262.test.ts b/packages/codemode/test/object-coercion-test262.test.ts deleted file mode 100644 index adba9e8bd62..00000000000 --- a/packages/codemode/test/object-coercion-test262.test.ts +++ /dev/null @@ -1,214 +0,0 @@ -/** - * Portions adapted from Test262 at revision 250f204f23a9249ff204be2baec29600faae7b75: - * - test/built-ins/Object/keys/15.2.3.14-1-1.js - * - test/built-ins/Object/keys/15.2.3.14-1-2.js - * - test/built-ins/Object/keys/15.2.3.14-1-3.js - * - test/built-ins/Object/keys/15.2.3.14-1-4.js - * - test/built-ins/Object/keys/15.2.3.14-1-5.js - * - test/built-ins/Object/entries/primitive-strings.js - * - test/built-ins/Object/entries/primitive-numbers.js - * - test/built-ins/Object/entries/primitive-booleans.js - * - test/built-ins/Object/values/primitive-strings.js - * - test/built-ins/Object/values/primitive-numbers.js - * - test/built-ins/Object/values/primitive-booleans.js - * - test/built-ins/Object/hasOwn/toobject_null.js - * - test/built-ins/Object/hasOwn/toobject_undefined.js - * - test/built-ins/Object/hasOwn/hasown_nonexistent.js - * - test/built-ins/Object/assign/Source-String.js - * - test/built-ins/Object/assign/Source-Null-Undefined.js - * - test/built-ins/Object/assign/target-Array.js - * - test/built-ins/Object/assign/Target-Null.js - * - test/built-ins/Object/assign/Target-Undefined.js - * - test/built-ins/Object/assign/Target-Object.js - * - test/built-ins/Object/assign/Override.js - * - test/built-ins/Object/assign/ObjectOverride-sameproperty.js - * - * Copyright (c) 2012 Ecma International. All rights reserved. - * Copyright (C) 2015 Jordan Harband. All rights reserved. - * Copyright 2015 Microsoft Corporation. All rights reserved. - * Copyright 2021 Jamie Kyle. All rights reserved. - * Test262 portions are governed by the BSD license in LICENSE.test262. - * - * Boxed-primitive cases (`Object.assign("a")`, `Object.assign(1, …)`) are omitted: CodeMode has no - * wrapper objects, so a primitive target is a TypeError rather than a boxed result. `Override.js` - * checks `Object.keys(result).length` instead of `Object.getOwnPropertyNames`. `target-Array.js` - * omits its named-key (`-0`, `1.5`, `4294967295`), `length`, and Proxy assertions: arrays here hold - * only indexed elements, so those keys are a TypeError (pinned below) rather than array properties. - */ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" - -const value = async (code: string) => { - const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} })) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -const throwsTypeError = (expression: string) => - value(`try { ${expression}; return "no throw" } catch (error) { return error.name }`) - -describe("Object.keys Test262 parity", () => { - test("test/built-ins/Object/keys/15.2.3.14-1-{1,2,3}.js: primitives are coerced", async () => { - expect(await value(`return [Object.keys(0), Object.keys(true), Object.keys("abc")]`)).toEqual([ - [], - [], - ["0", "1", "2"], - ]) - }) - - test("test/built-ins/Object/keys/15.2.3.14-1-{4,5}.js: null and undefined throw TypeError", async () => { - expect(await throwsTypeError(`Object.keys(null)`)).toBe("TypeError") - expect(await throwsTypeError(`Object.keys(undefined)`)).toBe("TypeError") - }) -}) - -describe("Object.entries and Object.values Test262 parity", () => { - test("test/built-ins/Object/entries/primitive-strings.js", async () => { - expect( - await value(` - const result = Object.entries('abc') - return [Array.isArray(result), result.length, result[0][0], result[0][1], result[1][0], result[1][1], result[2][0], result[2][1]] - `), - ).toEqual([true, 3, "0", "a", "1", "b", "2", "c"]) - }) - - test("test/built-ins/Object/entries/primitive-numbers.js", async () => { - expect( - await value(` - return [0, -0, Infinity, -Infinity, NaN, Math.PI].map((number) => Object.entries(number).length) - `), - ).toEqual([0, 0, 0, 0, 0, 0]) - }) - - test("test/built-ins/Object/entries/primitive-booleans.js", async () => { - expect( - await value(` - const trueResult = Object.entries(true) - const falseResult = Object.entries(false) - return [Array.isArray(trueResult), trueResult.length, Array.isArray(falseResult), falseResult.length] - `), - ).toEqual([true, 0, true, 0]) - }) - - test("test/built-ins/Object/values/primitive-strings.js", async () => { - expect( - await value(` - const result = Object.values('abc') - return [Array.isArray(result), result.length, result[0], result[1], result[2]] - `), - ).toEqual([true, 3, "a", "b", "c"]) - }) - - test("test/built-ins/Object/values/primitive-numbers.js", async () => { - expect( - await value(` - return [0, -0, Infinity, -Infinity, NaN, Math.PI].map((number) => Object.values(number).length) - `), - ).toEqual([0, 0, 0, 0, 0, 0]) - }) - - test("test/built-ins/Object/values/primitive-booleans.js", async () => { - expect( - await value(` - const trueResult = Object.values(true) - const falseResult = Object.values(false) - return [Array.isArray(trueResult), trueResult.length, Array.isArray(falseResult), falseResult.length] - `), - ).toEqual([true, 0, true, 0]) - }) -}) - -describe("Object.hasOwn Test262 parity", () => { - test("test/built-ins/Object/hasOwn/toobject_{null,undefined}.js", async () => { - expect(await throwsTypeError(`Object.hasOwn(null, 'foo')`)).toBe("TypeError") - expect(await throwsTypeError(`Object.hasOwn(undefined, 'foo')`)).toBe("TypeError") - }) - - test("test/built-ins/Object/hasOwn/hasown_nonexistent.js", async () => { - expect(await value(`const o = {}; return Object.hasOwn(o, "foo")`)).toBe(false) - }) -}) - -describe("Object.assign Test262 parity", () => { - test("test/built-ins/Object/assign/Source-String.js", async () => { - expect( - await value(` - const target = new Object() - const result = Object.assign(target, "123") - return [result[0], result[1], result[2]] - `), - ).toEqual(["1", "2", "3"]) - }) - - test("test/built-ins/Object/assign/Source-Null-Undefined.js", async () => { - expect( - await value(` - const target = new Object() - const result = Object.assign(target, undefined, null) - return result === target - `), - ).toBe(true) - }) - - test("test/built-ins/Object/assign/target-Array.js", async () => { - expect( - await value(` - const target = [7, 8, 9] - let result = Object.assign(target, [1]) - const first = [result === target, [...result]] - const sparseArraySource = [] - sparseArraySource[2] = 3 - result = Object.assign(target, sparseArraySource) - const second = [result === target, [...result]] - result = Object.assign(target, { 4: 0 }) - return [...first, ...second, result === target, result.length, result[3] === undefined, result[4]] - `), - ).toEqual([true, [1, 8, 9], true, [1, 8, 3], true, 5, true, 0]) - }) - - test("test/built-ins/Object/assign/target-Array.js", async () => { - expect( - await value(` - const target = [7] - for (const source of [{ x: 1 }, { "1.5": 1 }, { "-0": 1 }, { 1: 8 }, { length: 1 }]) Object.assign(target, source) - return [[...target], target.length, Object.keys(target), target.x] - `), - ).toEqual([[7], 1, ["0", "x", "1.5", "-0"], 1]) - }) - - test("test/built-ins/Object/assign/Target-{Null,Undefined}.js", async () => { - expect(await throwsTypeError(`Object.assign(null, { a: 1 })`)).toBe("TypeError") - expect(await throwsTypeError(`Object.assign(undefined, { a: 1 })`)).toBe("TypeError") - }) - - test("test/built-ins/Object/assign/Target-Object.js", async () => { - expect( - await value(` - const target = { foo: 1 } - const result = Object.assign(target, { a: 2 }) - return [result.foo, result.a] - `), - ).toEqual([1, 2]) - }) - - test("test/built-ins/Object/assign/Override.js", async () => { - expect( - await value(` - const target = { a: 1 } - const result = Object.assign(target, "1a2c3", { a: "c" }, undefined, { b: 6 }, null, 125, { a: 5 }) - return [Object.keys(result).length, result.a, result[0], result[1], result[2], result[3], result[4], result.b] - `), - ).toEqual([7, 5, "1", "a", "2", "c", "3", 6]) - }) - - test("test/built-ins/Object/assign/ObjectOverride-sameproperty.js", async () => { - expect( - await value(` - const target = { a: 1 } - const result = Object.assign(target, { a: 2 }, { a: "c" }) - return result.a - `), - ).toBe("c") - }) -}) diff --git a/packages/codemode/test/parity.test.ts b/packages/codemode/test/parity.test.ts deleted file mode 100644 index b58b6bfd9c1..00000000000 --- a/packages/codemode/test/parity.test.ts +++ /dev/null @@ -1,2016 +0,0 @@ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" - -// Runs a CodeMode program with no host tools and returns the CodeMode.Result. These tests pin the -// JS-parity behaviors for the "99% of ordinary defensive JavaScript just works" goal: cases where -// a strict interpreter would throw but idiomatic JS yields undefined / succeeds. -// -// Note on the result boundary: this package normalizes a bare `undefined` result to `null` when -// it crosses out of CodeMode (results are JSON data), so tests asserting an in-CodeMode -// `undefined` read check `=== undefined` inside the program and `null` at the boundary. -const run = (code: string) => Effect.runPromise(CodeMode.execute({ code, tools: {} })) -const value = async (code: string) => { - const result = await run(code) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} -const error = async (code: string) => { - const result = await run(code) - if (result.ok) throw new Error(`expected failure, got value ${JSON.stringify(result.value)}`) - return result.error -} - -describe("H2: string property access reads as undefined (not a throw)", () => { - test("unknown property on a string is undefined", async () => { - expect(await value(`const s = "hi"; return s.login === undefined`)).toBe(true) - expect(await value(`const s = "hi"; return s.login`)).toBeNull() - }) - - test("optional chaining + fallback on a string does not throw", async () => { - expect(await value(`const s = "hi"; return s?.login ?? "fallback"`)).toBe("fallback") - }) - - test("the real MCP pattern: result is a JSON string, defensive read falls through", async () => { - // me.result is a string; me.result?.login is undefined, so we fall back to the raw string. - expect(await value(`const me = { result: '{"login":"x"}' }; return me.result?.login ?? me.result`)).toBe( - '{"login":"x"}', - ) - }) - - test("unknown property on a number is undefined", async () => { - expect(await value(`return (5).foo ?? "n"`)).toBe("n") - }) - - test("only canonical string index keys access characters", async () => { - expect( - await value(` - const text = "abc" - return [text[1], text["1"], text["01"], text["1.0"], text[-0], text["-0"]] - `), - ).toEqual(["b", "b", null, null, "a", null]) - }) -}) - -describe("H3: array property access reads as undefined (not a throw)", () => { - test("unknown property on an array is undefined", async () => { - expect(await value(`return [1,2,3].foo === undefined`)).toBe(true) - expect(await value(`return [1,2,3].foo`)).toBeNull() - }) - - test("optional chaining on an array does not throw", async () => { - expect(await value(`return [1,2,3]?.foo ?? "fb"`)).toBe("fb") - }) - - test("unknown property reads stay undefined for methods CodeMode does not implement", async () => { - expect(await value(`return [1,2,3].unknownMethod === undefined`)).toBe(true) - }) - - test("array indexing still works", async () => { - expect(await value(`return [1,2,3][9] === undefined`)).toBe(true) - expect(await value(`return [1,2,3][9]`)).toBeNull() - }) - - test("only canonical array index keys access elements", async () => { - expect( - await value(` - const values = ["a", "b"] - return [values[1], values["1"], values["01"], values["1.0"], values[-0], values["-0"]] - `), - ).toEqual(["b", "b", null, null, "a", null]) - }) - - test("noncanonical keys are ordinary properties that never alias an element", async () => { - expect( - await value(` - const values = ["a", "b"] - values["01"] = "c" - const before = [values["01"], values[1], values.length] - const removed = delete values["01"] - return [before, removed, values["01"], values] - `), - ).toEqual([["c", "b", 2], true, null, ["a", "b"]]) - }) - - test("the maximum array length is a property, not an index", async () => { - expect( - await value(` - const values = [] - values["4294967295"] = 1 - return [values["4294967295"], values.length] - `), - ).toEqual([1, 0]) - }) -}) - -describe("H6: object spread of null/undefined is a no-op", () => { - test("spreading null is a no-op", async () => { - expect(await value(`const o = null; return { ...o, a: 1 }`)).toEqual({ a: 1 }) - }) - - test("spreading an absent argument merges cleanly", async () => { - expect(await value(`function f(opts){ return { ...opts, a: 1 } } return f(undefined)`)).toEqual({ a: 1 }) - }) - - test("spreading a real object still works", async () => { - expect(await value(`const o = { a: 1 }; return { ...o, b: 2 }`)).toEqual({ a: 1, b: 2 }) - }) - - test("spreading an array or string into an object copies index keys, like JS", async () => { - expect(await value(`return { ...[1,2], a: 1 }`)).toEqual({ 0: 1, 1: 2, a: 1 }) - expect(await value(`return { ..."ab", ...5, ...true, ...(() => 1), ...new Map([[1, 2]]) }`)).toEqual({ - 0: "a", - 1: "b", - }) - }) -}) - -describe("H4: typeof on an undeclared identifier is 'undefined'", () => { - test("feature-detection guard does not throw", async () => { - expect(await value(`return typeof foo === "undefined" ? "safe" : "no"`)).toBe("safe") - }) - - test("typeof of a declared binding is unaffected", async () => { - expect(await value(`const x = 5; return typeof x`)).toBe("number") - expect(await value(`const s = "a"; return typeof s`)).toBe("string") - }) - - test("referencing an undeclared identifier outside typeof still throws", async () => { - const err = await error(`return foo + 1`) - expect(err.message).toContain("foo") - }) -}) - -describe("CodeMode lexical scope integration", () => { - test("keeps self, cross, and destructuring defaults in the TDZ", async () => { - expect( - await value(` - const outer = 1 - const errors = [] - try { const first = second, second = 2 } catch (error) { errors.push(error.name) } - try { const [first = second, second = 2] = [] } catch (error) { errors.push(error.name) } - return errors - `), - ).toEqual(["ReferenceError", "ReferenceError"]) - }) - - test("keeps typeof and constant assignment inside the TDZ", async () => { - expect( - await value(` - const errors = [] - try { { errors.push(typeof item); let item } } catch (error) { errors.push(error.name) } - try { { constant = 1; const constant = 2 } } catch (error) { errors.push(error.name) } - return errors - `), - ).toEqual(["ReferenceError", "ReferenceError"]) - }) - - test("shadows builtins from the start of the program scope", async () => { - expect( - await value(` - let observed - try { observed = typeof Promise } catch (error) { observed = error.name } - const Promise = 1 - return observed - `), - ).toBe("ReferenceError") - }) - - test("keeps classic for initializers inside the header TDZ", async () => { - expect( - await value(` - let index = 1 - try { for (let index = index; index < 2; index++) {} } catch (error) { return error.name } - `), - ).toBe("ReferenceError") - }) - - test("removes loop scopes when per-iteration initialization fails", async () => { - expect( - await value(` - const value = "outer" - try { for (let [value] of [1]) {} } catch {} - return value - `), - ).toBe("outer") - }) -}) - -describe("unary void", () => { - test("evaluates its operand and returns undefined", async () => { - expect( - await value(`let count = 0; const result = void (count += 1); return [count, result === undefined]`), - ).toEqual([1, true]) - }) - - test("discards opaque values", async () => { - expect(await value(`return void tools === undefined`)).toBe(true) - }) -}) - -describe("property deletion", () => { - test("deletes plain object fields and reports missing fields as successful", async () => { - expect( - await value(` - const object = { keep: 1, remove: 2 } - return [delete object.remove, delete object.missing, object] - `), - ).toEqual([true, true, { keep: 1 }]) - }) - - test("a non-reference operand is evaluated and the result is true; a variable cannot be deleted", async () => { - expect( - await value(` - let called = false - const results = [delete 0, delete null, delete { x: 1 }, delete void 0, delete (() => { called = true })()] - let variable = 1 - let failure - try { delete variable } catch (error) { failure = error.constructor.name } - return [results, called, failure] - `), - ).toEqual([[true, true, true, true, true], true, "TypeError"]) - }) - - test("evaluates computed object and key expressions once", async () => { - expect( - await value(` - const object = { remove: true } - let objectReads = 0 - let keyReads = 0 - function getObject() { objectReads++; return object } - function getKey() { keyReads++; return "remove" } - const removed = delete getObject()[getKey()] - return [removed, objectReads, keyReads, Object.hasOwn(object, "remove")] - `), - ).toEqual([true, 1, 1, false]) - }) - - test("deleting an array index creates a hole without changing its length", async () => { - expect( - await value( - `const values = [1, 2, 3]; const removed = delete values[1]; return [removed, values.length, 1 in values, values]`, - ), - ).toEqual([true, 3, false, [1, null, 3]]) - }) - - test("array length is not configurable", async () => { - expect((await error(`const values = [1, 2]; delete values.length`)).message).toContain( - "Cannot delete property 'length'", - ) - }) - - test("arrays accept named properties like JS, and they stay out of the JSON form", async () => { - expect( - await value(` - const values = [1] - values.field = 2 - return [values.field, Object.keys(values), values] - `), - ).toEqual([2, ["0", "field"], [1]]) - }) - - test("optional deletion short-circuits without evaluating the key", async () => { - expect( - await value(`let keyReads = 0; const object = null; return [delete object?.[keyReads++], keyReads]`), - ).toEqual([true, 0]) - }) - - test("rejects deletion from opaque runtime references", async () => { - expect((await error(`return delete tools.example`)).kind).toBe("InvalidDataValue") - }) - - test("prototype-named keys delete like any own data key", async () => { - expect( - await value(`const object = { __proto__: 1, a: 2 }; delete object.__proto__; return Object.keys(object)`), - ).toEqual(["a"]) - expect(await value(`const values = [1]; delete values["constructor"]; return values`)).toEqual([1]) - }) -}) - -describe("H1: NaN/Infinity flow as intermediates and normalize to null at the boundary", () => { - test("guards run instead of the program crashing on a transient NaN", async () => { - expect(await value(`return parseInt("abc") || 0`)).toBe(0) - expect(await value(`const x = Number("abc"); return Number.isNaN(x) ? 0 : x`)).toBe(0) - expect(await value(`const o = {}; o.count = (o.count || 0) + 1; return o.count`)).toBe(1) - // average of an empty list, guarded - the classic divide-by-zero that used to throw pre-guard - expect(await value(`const a = []; return a.length ? a.reduce((s,x)=>s+x,0)/a.length : 0`)).toBe(0) - }) - - test("a non-finite value becomes null when it leaves CodeMode", async () => { - expect(await value(`return 5/0`)).toBeNull() - expect(await value(`return 0/0`)).toBeNull() - expect(await value(`return Math.max()`)).toBeNull() - // nested, too - normalization walks the returned structure - expect(await value(`return { a: Number("x"), b: 2, c: [1/0] }`)).toEqual({ a: null, b: 2, c: [null] }) - }) - - test("NaN and Infinity are usable identifiers and inspectable in-CodeMode", async () => { - expect(await value(`return Number.isNaN(NaN)`)).toBe(true) - expect(await value(`return Infinity > 1e9`)).toBe(true) - expect(await value(`return Number.isFinite(1/0)`)).toBe(false) - expect(await value(`return [3,1,2].reduce((a,b)=>Math.max(a,b), -Infinity)`)).toBe(3) - // JSON.stringify inside CodeMode matches JS: non-finite serializes to null - expect(await value(`return JSON.stringify({ x: Number("z") })`)).toBe('{"x":null}') - }) - - test("the boundary normalizes non-finite numbers to null like JSON.stringify", async () => { - expect(await value(`return { a: Number("z"), b: [Infinity, -Infinity, 1] }`)).toEqual({ - a: null, - b: [null, null, 1], - }) - }) -}) - -describe("undefined at the boundary", () => { - test("vanishes like JSON.stringify", async () => { - expect(await value(`return { q: undefined, keep: 1, nested: { a: undefined, b: [undefined] } }`)).toStrictEqual({ - keep: 1, - nested: { b: [null] }, - }) - expect(await value(`return [1, undefined, 2]`)).toStrictEqual([1, null, 2]) - expect(await value(`return undefined`)).toBeNull() - }) -}) - -describe("Error values and instanceof", () => { - test("new Error carries name/message and is instanceof Error", async () => { - expect(await value(`const e = new Error("boom"); return [e instanceof Error, e.name, e.message]`)).toEqual([ - true, - "Error", - "boom", - ]) - }) - - test("Error without new behaves like new Error", async () => { - expect(await value(`const e = Error("plain"); return [e instanceof Error, e.name, e.message]`)).toEqual([ - true, - "Error", - "plain", - ]) - expect(await value(`const e = new Error(); return [e.name, e.message, e instanceof Error]`)).toEqual([ - "Error", - "", - true, - ]) - }) - - test("specific error types are instanceof themselves and Error, not each other", async () => { - expect( - await value( - `const e = new TypeError("t"); return [e instanceof TypeError, e instanceof Error, e instanceof RangeError]`, - ), - ).toEqual([true, true, false]) - expect(await value(`return new Error("e") instanceof TypeError`)).toBe(false) - }) - - test("new Error(message, { cause }) installs a non-enumerable cause only when the option is present", async () => { - expect( - await value(` - const inner = new Error("root") - const e = new TypeError("m", { cause: inner }) - const agg = new AggregateError([], "a", { cause: 3 }) - return [e.cause === inner, Object.keys(e), "cause" in new Error("m"), "cause" in new Error("m", { cause: undefined }), agg.cause]`), - ).toEqual([true, [], false, true, 3]) - }) - - test("thrown errors keep instanceof through try/catch", async () => { - expect(await value(`try { throw new Error("x") } catch (e) { return [e instanceof Error, e.message] }`)).toEqual([ - true, - "x", - ]) - }) - - test("interpreter runtime failures are caught as Error values", async () => { - expect(await value(`try { JSON.parse("nope") } catch (e) { return e instanceof Error }`)).toBe(true) - expect(await value(`try { undeclared() } catch (e) { return e instanceof Error }`)).toBe(true) - }) - - test("caught failures carry the constructor name the real-JS failure would have", async () => { - // JSON.parse throws SyntaxError: name and specific-instanceof both carry through, and the - // message keeps the engine's position detail. - expect( - await value(` - try { JSON.parse("{oops") } catch (e) { - return [e.name, e instanceof SyntaxError, e instanceof Error, e instanceof TypeError, e.message.includes("JSON")] - } - `), - ).toEqual(["SyntaxError", true, true, false, true]) - expect(await value(`try { undeclared() } catch (e) { return [e.name, e instanceof ReferenceError] }`)).toEqual([ - "ReferenceError", - true, - ]) - expect(await value(`try { const c = 1; c = 2 } catch (e) { return [e.name, e instanceof TypeError] }`)).toEqual([ - "TypeError", - true, - ]) - expect(await value(`try { "a".match("(") } catch (e) { return [e.name, e instanceof SyntaxError] }`)).toEqual([ - "SyntaxError", - true, - ]) - expect(await value(`try { new RegExp("(") } catch (e) { return [e.name, e instanceof SyntaxError] }`)).toEqual([ - "SyntaxError", - true, - ]) - }) - - test("interpreter failures are TypeErrors; unsupported syntax is a SyntaxError", async () => { - expect(await value(`try { null.x } catch (e) { return [e.name, e instanceof TypeError] }`)).toEqual([ - "TypeError", - true, - ]) - expect(await value(`try { tools + 1 } catch (e) { return e.name }`)).toBe("TypeError") - expect(await value(`try { class A { #x } } catch (e) { return [e.name, e instanceof SyntaxError] }`)).toEqual([ - "SyntaxError", - true, - ]) - }) - - test("errors inherit constructor and instanceof through a real prototype chain", async () => { - expect( - await value(` - const { constructor } = new RangeError("r") - let caught - try { const { a } = null } catch (e) { caught = e } - return [ - constructor === RangeError, - new RangeError("r") instanceof Error, - new RangeError("r") instanceof TypeError, - caught.constructor === TypeError, - ({ ...caught }).constructor === Object, - "constructor" in caught, - Object.keys(new RangeError("r")), - ] - `), - ).toEqual([true, true, false, true, true, true, []]) - }) - - test("Promise.allSettled rejection reasons are Error values", async () => { - expect( - await value(` - const settled = await Promise.allSettled([Promise.reject(new Error("b"))]) - return [settled[0].reason instanceof Error, settled[0].reason.message] - `), - ).toEqual([true, "b"]) - }) - - test("non-error thrown values are not instanceof Error", async () => { - expect(await value(`try { throw "raw" } catch (e) { return e instanceof Error }`)).toBe(false) - expect(await value(`try { throw { message: "shaped" } } catch (e) { return e instanceof Error }`)).toBe(false) - }) - - test("plain data is never instanceof Error", async () => { - expect(await value(`return [({}) instanceof Error, "s" instanceof Error, null instanceof Error]`)).toEqual([ - false, - false, - false, - ]) - }) - - test("errors serialize as { name, message } by brand; neither is enumerable", async () => { - expect(await value(`return new Error("m")`)).toEqual({ name: "Error", message: "m" }) - expect(await value(`return JSON.stringify(new Error("m"))`)).toBe('{"name":"Error","message":"m"}') - expect( - await value( - `try { throw new Error("m") } catch (e) { return [Object.keys(e), e.name, e.hasOwnProperty("message")] }`, - ), - ).toEqual([[], "Error", true]) - expect(await value(`return new Error().hasOwnProperty("message")`)).toBe(false) - }) - - test("spreading an error loses the brand, like losing the prototype in JS", async () => { - expect(await value(`const e = new Error("m"); return ({ ...e }) instanceof Error`)).toBe(false) - expect(await value(`const e = new Error("m"); return { ...e }`)).toEqual({}) - }) - - test("typeof Error is function; an unknown instanceof right-hand side is a catchable error", async () => { - expect(await value(`return typeof Error`)).toBe("function") - expect(await value(`try { return 1 instanceof 5 } catch (e) { return "caught" }`)).toBe("caught") - const err = await error(`return 1 instanceof 5`) - expect(err.message).toContain("right-hand side of 'instanceof'") - }) -}) - -describe("CodeMode-specific array behavior", () => { - test("sort with a comparator mutates and returns the receiver", async () => { - expect( - await value(` - const input = [3, 1, 2] - const result = input.sort((a, b) => a - b) - return { input, same: input === result } - `), - ).toEqual({ input: [1, 2, 3], same: true }) - }) - - test("splice can replace and insert elements", async () => { - expect(await value(`const a = ["a","d"]; a.splice(1, 0, "b", "c"); return a`)).toEqual(["a", "b", "c", "d"]) - expect(await value(`const a = [1,2,3]; const removed = a.splice(1, 1, "x"); return { removed, a }`)).toEqual({ - removed: [2], - a: [1, "x", 3], - }) - }) - - test("splice rejects inserting a container into itself", async () => { - const err = await error(`const a = [1]; a.splice(0, 0, [a]); return a`) - expect(err.kind).toBe("InvalidDataValue") - expect(err.message).toContain("circular") - }) - - test("indexOf and lastIndexOf with no argument search for undefined", async () => { - expect(await value(`return [1, undefined, 3].indexOf()`)).toBe(1) - expect(await value(`return [1, undefined, 3].lastIndexOf()`)).toBe(1) - expect(await value(`return [1, 2, 3].indexOf()`)).toBe(-1) - }) - - test("keys/values/entries return iterators usable with for...of and spread", async () => { - expect(await value(`return [...["x","y","z"].keys()]`)).toEqual([0, 1, 2]) - expect(await value(`return [...["x","y"].values()]`)).toEqual(["x", "y"]) - expect( - await value(` - const out = [] - for (const [index, item] of ["a","b"].entries()) out.push(index + ":" + item) - return out - `), - ).toEqual(["0:a", "1:b"]) - expect(await value(`return [...[7].entries()]`)).toEqual([[0, 7]]) - }) -}) - -describe("CodeMode-specific string behavior", () => { - test("localeCompare orders strings for sorting", async () => { - expect(await value(`return ["b","a","c"].sort((x, y) => x.localeCompare(y))`)).toEqual(["a", "b", "c"]) - }) - - test("localeCompare honors its locales and options like the host collator", async () => { - expect( - await value(` - const numeric = { get numeric() { return true } } - return [ - ["a10", "a9", "a1"].sort((x, y) => x.localeCompare(y, undefined, numeric)), - "a".localeCompare("A", undefined, { sensitivity: "base" }), - "a".localeCompare("á", "en", { sensitivity: "base" }), - "a".localeCompare("A", ["en"], { sensitivity: { toString() { return "accent" } } }), - "a".localeCompare("A", "en", { caseFirst: "upper" }), - "a,b".localeCompare("ab", "en", { ignorePunctuation: true }), - "ä".localeCompare("z", "sv"), - "a".localeCompare("A"), - ] - `), - ).toEqual([["a1", "a9", "a10"], 0, 0, 0, 1, 0, 1, -1]) - }) - - test("localeCompare rejects invalid locales and options with catchable errors", async () => { - expect( - await value(` - const attempt = (f) => { try { return f() } catch (e) { return e.name } } - return [ - attempt(() => "a".localeCompare("b", "xx_bad")), - attempt(() => "a".localeCompare("b", undefined, { sensitivity: "nope" })), - attempt(() => "a".localeCompare("b", undefined, null)), - attempt(() => "a".localeCompare("b", [1])), - ] - `), - ).toEqual(["RangeError", "RangeError", "TypeError", "TypeError"]) - }) - - test("an invalid normalize form is a clear catchable error", async () => { - expect(await value(`try { "x".normalize("nope"); return "no" } catch (e) { return e.message }`)).toContain('"NFC"') - }) - - test("exposes the Annex B string aliases every engine ships", async () => { - expect(await value(`return [" x ".trimLeft(), " x ".trimRight(), "abc".substr(1, 1)]`)).toEqual(["x ", " x", "b"]) - }) -}) - -describe("compound assignment matches its binary operator", () => { - // `x op= y` must behave exactly like `x = x op y`, sharing the binary operator's coercion - // semantics (Dates string-coerce for `+` and use their time value for arithmetic; data - // objects/arrays coerce to their JS string form). - const pair = async (compound: string, expanded: string) => { - const [a, b] = await Promise.all([value(compound), value(expanded)]) - expect(a).toEqual(b) - return a - } - - test("CodeMode Date += concatenates its string form, like d = d + 1", async () => { - const result = await pair(`let d = new Date(1000); d += 1; return d`, `let d = new Date(1000); d = d + 1; return d`) - expect(result).toBe("1970-01-01T00:00:01.000Z1") - }) - - test("CodeMode Date numeric compound ops use its time value", async () => { - expect( - await pair(`let d = new Date(1000); d -= 400; return d`, `let d = new Date(1000); d = d - 400; return d`), - ).toBe(600) - expect(await pair(`let d = new Date(1000); d /= 4; return d`, `let d = new Date(1000); d = d / 4; return d`)).toBe( - 250, - ) - }) - - test("string += object/array matches x = x + obj", async () => { - expect(await pair(`let x = "a"; x += { b: 1 }; return x`, `let x = "a"; x = x + { b: 1 }; return x`)).toBe( - "a[object Object]", - ) - expect(await pair(`let x = "a"; x += [1, 2]; return x`, `let x = "a"; x = x + [1, 2]; return x`)).toBe("a1,2") - }) - - test("compound assignment through a member target coerces the same way", async () => { - expect( - await pair( - `const o = { s: "t" }; o.s += new Date(0); return o.s`, - `const o = { s: "t" }; o.s = o.s + new Date(0); return o.s`, - ), - ).toBe("t1970-01-01T00:00:00.000Z") - }) - - test("numeric and string compound operators sweep identically to their expansions", async () => { - const cases: Array<[string, number | string]> = [ - [`let x = 7; x += 3; return x`, 7 + 3], - [`let x = 7; x -= 3; return x`, 7 - 3], - [`let x = 7; x *= 3; return x`, 7 * 3], - [`let x = 7; x /= 2; return x`, 7 / 2], - [`let x = 7; x %= 3; return x`, 7 % 3], - [`let x = 7; x **= 2; return x`, 7 ** 2], - [`let x = 7; x &= 3; return x`, 7 & 3], - [`let x = 7; x |= 8; return x`, 7 | 8], - [`let x = 7; x ^= 2; return x`, 7 ^ 2], - [`let x = 7; x <<= 2; return x`, 7 << 2], - [`let x = -7; x >>= 1; return x`, -7 >> 1], - [`let x = -7; x >>>= 1; return x`, -7 >>> 1], - [`let x = "a"; x += "b"; return x`, "ab"], - ] - for (const [compound, expected] of cases) { - expect(await value(compound)).toBe(expected) - expect(await value(compound.replace(/x (\S+)= /, (_, op) => `x = x ${op} `))).toBe(expected) - } - }) -}) - -describe("H5: builtin coercion functions work as array callbacks", () => { - test("filter(Boolean) drops falsy values", async () => { - expect(await value(`return [0, 1, "", 2, null, 3].filter(Boolean)`)).toEqual([1, 2, 3]) - }) - - test("map(String) coerces each element", async () => { - expect(await value(`return [1, 2, 3].map(String)`)).toEqual(["1", "2", "3"]) - }) - - test("a non-callable callback is still rejected", async () => { - const err = await error(`return [1,2,3].map(42)`) - expect(err.message).toContain("callback") - }) -}) - -describe("for...of assignment destructuring", () => { - test("assigns entry pairs into predeclared variables", async () => { - expect( - await value(` - let key - let item - const out = [] - for ([key, item] of Object.entries({ a: 1, b: 2 })) out.push(key + item) - return { key, item, out } - `), - ).toEqual({ key: "b", item: 2, out: ["a1", "b2"] }) - }) - - test("assigns object patterns and defaults", async () => { - expect( - await value(` - let id - let label - const labels = [] - for ({ id, label = "unknown" } of [{ id: 1 }, { id: 2, label: "two" }]) labels.push(label) - return { id, label, labels } - `), - ).toEqual({ id: 2, label: "two", labels: ["unknown", "two"] }) - }) -}) - -describe("sequence expressions", () => { - test("evaluate left to right and return the final value", async () => { - expect(await value(`let x = 0; const result = (x += 1, x *= 3, x + 2); return { x, result }`)).toEqual({ - x: 3, - result: 5, - }) - }) - - test("support comma-separated for-loop updates", async () => { - expect( - await value(` - const pairs = [] - for (let left = 0, right = 3; left < right; left++, right--) pairs.push([left, right]) - return pairs - `), - ).toEqual([ - [0, 3], - [1, 2], - ]) - }) -}) - -describe("destructuring assignment", () => { - test("assigns object and array patterns to existing bindings", async () => { - expect( - await value(` - let a = 0 - let b = 0 - ;({ a } = { a: 2 }) - ;[a, b] = [3, 4] - return [a, b] - `), - ).toEqual([3, 4]) - }) - - test("supports defaults, nesting, rest, and member targets", async () => { - expect( - await value(` - let first = 0 - let fallback = 0 - let rest = {} - const target = {} - ;[first, fallback = 2, ...target.tail] = [1] - ;({ nested: { value: target.value }, kept: target.kept = 3, ...rest } = { - nested: { value: 4 }, - extra: 5, - }) - return { first, fallback, target, rest } - `), - ).toEqual({ first: 1, fallback: 2, target: { tail: [], value: 4, kept: 3 }, rest: { extra: 5 } }) - }) - - test("returns the assigned value", async () => { - expect(await value(`let a = 0; const result = ([a] = [7]); return [a, result]`)).toEqual([7, [7]]) - }) - - test("supports computed object keys and evaluates them once", async () => { - expect( - await value(` - let calls = 0 - const field = () => { calls++; return "name" } - const { [field()]: name, ...rest } = { name: "Ada", role: "engineer" } - return { calls, name, rest } - `), - ).toEqual({ calls: 1, name: "Ada", rest: { role: "engineer" } }) - }) - - test("supports object patterns over arrays; detached methods lose their receiver like JS", async () => { - expect( - await value(` - const { 0: first, length, slice, ...rest } = ["a", "b", "c"] - return { first, length, sliced: slice === Array.prototype.slice, rest } - `), - ).toEqual({ first: "a", length: 3, sliced: true, rest: { 1: "b", 2: "c" } }) - expect((await error(`const { slice } = [1]; slice(0)`)).message).toContain("Array.prototype.slice called on") - }) - - test("preserves exact computed property names on arrays", async () => { - expect( - await value(` - const { ["01"]: item, ...rest } = [10, 20] - return { missing: item === undefined, rest } - `), - ).toEqual({ missing: true, rest: { 0: 10, 1: 20 } }) - }) - - test("supports array patterns over strings, Maps, Sets, and URLSearchParams", async () => { - expect( - await value(` - const [letter, ...letters] = "A😀B" - const [[mapKey, mapValue]] = new Map([["key", 1]]) - const [setFirst, setSecond] = new Set([2, 3]) - const [[queryKey, queryValue]] = new URLSearchParams("q=test&page=2") - return { letter, letters, mapKey, mapValue, setFirst, setSecond, queryKey, queryValue } - `), - ).toEqual({ - letter: "A", - letters: ["😀", "B"], - mapKey: "key", - mapValue: 1, - setFirst: 2, - setSecond: 3, - queryKey: "q", - queryValue: "test", - }) - }) - - test("supports iterable patterns in assignment and parameters", async () => { - expect( - await value(` - let first - let rest - ;[first, ...rest] = new Set([1, 2, 3]) - const read = ([[key, value]]) => key + value - return { first, rest, entry: read(new Map([["a", 4]])) } - `), - ).toEqual({ first: 1, rest: [2, 3], entry: "a4" }) - }) - - test("excludes computed numeric keys from object rest", async () => { - expect( - await value(` - const { [0]: declared, ...declarationRest } = { 0: "a", 1: "b" } - let assigned - let assignmentRest - ;({ [0]: assigned, ...assignmentRest } = { 0: "c", 1: "d" }) - return { declared, declarationRest, assigned, assignmentRest } - `), - ).toEqual({ declared: "a", declarationRest: { 1: "b" }, assigned: "c", assignmentRest: { 1: "d" } }) - }) - - test("computed keys of any type become their string form, as in JS", async () => { - expect( - await value(` - const counts = {} - for (const category of ["a", null, undefined, "a", true, 1.5]) counts[category] = (counts[category] ?? 0) + 1 - const key = {} - const { [key]: value } = { "[object Object]": 7 } - const o = { null: 1, "1,2": 2 } - return [counts, value, o[null], o[[1, 2]], undefined in o] - `), - ).toEqual([{ a: 2, null: 1, undefined: 1, true: 1, "1.5": 1 }, 7, 1, 2, false]) - }) -}) - -describe("coercion parity: zero-argument coercion functions", () => { - test("Number() is 0 and String() is empty, unlike their undefined-argument forms", async () => { - expect(await value(`return Number()`)).toBe(0) - expect(await value(`return String()`)).toBe("") - expect(await value(`return Boolean()`)).toBe(false) - expect(await value(`return Number.isNaN(Number(undefined))`)).toBe(true) - expect(await value(`return String(undefined)`)).toBe("undefined") - }) - - test("parseInt() and parseFloat() stay NaN with no argument", async () => { - expect(await value(`return Number.isNaN(parseInt())`)).toBe(true) - expect(await value(`return Number.isNaN(parseFloat())`)).toBe(true) - }) -}) - -describe("coercion parity: global isFinite and isNaN", () => { - test("coerce their argument like native JS, unlike the Number statics", async () => { - expect(await value(`return isFinite("42")`)).toBe(true) - expect(await value(`return Number.isFinite("42")`)).toBe(false) - expect(await value(`return isNaN("oops")`)).toBe(true) - expect(await value(`return isNaN("42")`)).toBe(false) - expect(await value(`return isFinite(Infinity)`)).toBe(false) - expect(await value(`return isNaN(null)`)).toBe(false) - }) - - test("zero-argument forms match native", async () => { - expect(await value(`return isFinite()`)).toBe(false) - expect(await value(`return isNaN()`)).toBe(true) - }) - - test("read as functions", async () => { - expect(await value(`return typeof isFinite`)).toBe("function") - expect(await value(`return typeof isNaN`)).toBe("function") - }) - - test("work as array callbacks", async () => { - expect(await value(`return [1, "2", "x", Infinity].filter(isFinite)`)).toEqual([1, "2"]) - expect(await value(`return ["1", "x"].map(isNaN)`)).toEqual([false, true]) - }) -}) - -describe("coercion parity: built-in arguments coerce as in JS", () => { - test("numeric arguments apply ToIntegerOrInfinity", async () => { - expect( - await value(` - return [ - [1, 2, 3].indexOf(2, "1"), [1, 2, 3].lastIndexOf(3, "5"), [1, 2, 3].includes(1, "1"), - [1, 2, 3, 4].slice("1", "3"), [1, 2, 3].at(null), [1, 2, 3].at(1.7), - [1, [2, [3]]].flat(1.9), [1, 2, 3].with(1.5, 9), [1, 2, 3, 4].splice("1", "2"), - Math.max("3", "2"), Math.floor(null), Math.hypot("3", "4"), - parseInt("11", "2"), Number.parseInt("ff", "16"), (1.5).toFixed("2"), (255).toString("16"), - String.fromCharCode("65", 66.9), new Uint8Array([1, 2, 3]).indexOf(2, "1"), - ] - `), - ).toEqual([1, 2, false, [2, 3], 1, 2, [1, 2, [3]], [1, 9, 3], [2, 3], 3, 0, 5, 3, 255, "1.50", "ff", "AB", 1]) - }) - - test("join separators, JSON.parse text, and Array.from length coerce", async () => { - expect( - await value(` - return [ - [1, 2].join(null), [1, 2].join(0), [1, 2].join(undefined), new Uint8Array([1, 2]).join(null), - JSON.parse(123), JSON.parse(true), - Array.from({ length: "2" }), Array.from({ length: 2.5 }), Array.from({ length: -1 }), Array.from({}), - ] - `), - ).toEqual(["1null2", "102", "1,2", "1null2", 123, true, [null, null], [null, null], [], []]) - expect((await error(`return JSON.parse(undefined)`)).message).toContain("JSON") - }) -}) - -describe("coercion parity: arrays coerce to numbers through their string form", () => { - test("arrays with objects become NaN instead of crashing on host ToPrimitive", async () => { - expect(await value(`let x = [{}]; x++; return Number.isNaN(x)`)).toBe(true) - expect(await value(`return isFinite([{}])`)).toBe(false) - expect(await value(`return "abc".slice([{}])`)).toBe("abc") - }) - - test("single-element and empty arrays match native Number()", async () => { - expect(await value(`return Number([5])`)).toBe(5) - expect(await value(`return Number([])`)).toBe(0) - expect(await value(`return Number.isNaN(Number([1, 2]))`)).toBe(true) - }) -}) - -describe("coercion parity: String method arguments coerce like native JS", () => { - test("includes and indexOf coerce numbers", async () => { - expect(await value(`return "v1.2".includes(1)`)).toBe(true) - expect(await value(`return "a2b".indexOf(2)`)).toBe(1) - expect(await value(`return "abc".includes("d")`)).toBe(false) - }) - - test("slice, repeat, and padStart coerce numeric strings", async () => { - expect(await value(`return "abc".slice("1")`)).toBe("bc") - expect(await value(`return "ab".repeat("2")`)).toBe("abab") - expect(await value(`return "7".padStart("3", 0)`)).toBe("007") - }) - - test("split coerces separators but treats undefined as absent", async () => { - expect(await value(`return "a1b".split(1)`)).toEqual(["a", "b"]) - expect(await value(`return "a,b".split(undefined)`)).toEqual(["a,b"]) - expect(await value(`return "a,b".split()`)).toEqual(["a,b"]) - expect(await value(`return "a,b".split(undefined, 0)`)).toEqual([]) - expect(await value(`return "a,b".split(undefined, 1)`)).toEqual(["a,b"]) - }) - - test("replace coerces search and replacement values", async () => { - expect(await value(`return "a1b".replace(1, 2)`)).toBe("a2b") - expect(await value(`return "a1b".replace(1, () => "x")`)).toBe("axb") - }) - - test("repeat rejections carry the native RangeError name", async () => { - expect(await value(`try { "a".repeat(-1) } catch (e) { return e.name }`)).toBe("RangeError") - }) - - test("includes, startsWith, and endsWith reject regular expressions with a TypeError", async () => { - expect(await value(`try { "abc".includes(/a/) } catch (e) { return e.name }`)).toBe("TypeError") - expect(await value(`try { "abc".startsWith(/a/) } catch (e) { return e.name }`)).toBe("TypeError") - expect(await value(`try { "abc".endsWith(/a/) } catch (e) { return e.name }`)).toBe("TypeError") - }) - - test("opaque runtime references still reject as data errors", async () => { - const err = await error(`const f = () => 1; return "abc".includes(f)`) - expect(err.message).toContain("data value") - const replacerErr = await error(`const f = () => 1; return "a".replace(f, () => "x")`) - expect(replacerErr.message).toContain("data value") - }) -}) - -describe("coercion parity: match() and search() with no argument", () => { - test("behave as an empty pattern like native JS", async () => { - expect(await value(`return "abc".search()`)).toBe(0) - expect(await value(`const m = "abc".match(); return { first: m[0], index: m.index }`)).toEqual({ - first: "", - index: 0, - }) - }) -}) - -describe("coercion parity: ++ and -- use CodeMode numeric coercion", () => { - test("numeric strings increment like native JS", async () => { - expect(await value(`let x = "5"; x++; return x`)).toBe(6) - expect(await value(`let x = "5"; return ++x`)).toBe(6) - expect(await value(`const o = { n: "2" }; o.n--; return o.n`)).toBe(1) - }) - - test("dates increment through their epoch time", async () => { - expect(await value(`let d = new Date(5); d++; return d`)).toBe(6) - }) - - test("plain data objects become NaN instead of crashing", async () => { - expect(await value(`let x = {}; x++; return Number.isNaN(x)`)).toBe(true) - expect(await value(`const o = { a: {} }; o.a++; return Number.isNaN(o.a)`)).toBe(true) - }) - - test("opaque runtime references reject with a clear error", async () => { - const err = await error(`let f = () => 1; f++`) - expect(err.message).toContain("data value") - }) -}) - -describe("coercion parity: unknown static members read as undefined", () => { - test("feature detection on missing statics works like native JS", async () => { - expect(await value(`return typeof Math.sum`)).toBe("undefined") - expect(await value(`return RegExp.quote === undefined`)).toBe(true) - expect(await value(`return Number.range === undefined`)).toBe(true) - expect(await value(`return String.dedent === undefined`)).toBe(true) - expect(await value(`return isFinite.something === undefined`)).toBe(true) - expect(await value(`return console.group === undefined`)).toBe(true) - expect(await value(`return Date.moment === undefined`)).toBe(true) - expect(await value(`return JSON.rawJSON === undefined`)).toBe(true) - expect(await value(`return URL.createObjectURL === undefined`)).toBe(true) - expect(await value(`return Math.sum?.([1]) ?? "fallback"`)).toBe("fallback") - }) - - test("known statics still resolve and run", async () => { - expect(await value(`return typeof Math.max`)).toBe("function") - expect(await value(`return typeof console.log`)).toBe("function") - expect(await value(`return typeof Date.now`)).toBe("function") - expect(await value(`return typeof Math.sumPrecise`)).toBe("function") - expect(await value(`return typeof RegExp.escape`)).toBe("function") - expect(await value(`return typeof Object.groupBy`)).toBe("function") - expect(await value(`return typeof Map.groupBy`)).toBe("function") - expect(await value(`return Math.max(1, 2)`)).toBe(2) - expect(await value(`return Math.sumPrecise([1, 2])`)).toBe(3) - expect(await value(`return RegExp.escape("a.b")`)).toBe("\\x61\\.b") - expect(await value(`return URL.canParse("https://example.com")`)).toBe(true) - expect(await value(`return Number.isInteger(3)`)).toBe(true) - expect(await value(`return Number.MAX_SAFE_INTEGER`)).toBe(Number.MAX_SAFE_INTEGER) - }) - - test("calling an unknown static reports a native-style TypeError", async () => { - expect(await value(`try { Math.sum([1]) } catch (e) { return e.name + ": " + e.message }`)).toBe( - "TypeError: Math.sum is not a function.", - ) - expect(await value(`try { Math["sum"]([1]) } catch (e) { return e.message }`)).toBe("Math.sum is not a function.") - expect(await value(`try { JSON.rawJSON("1") } catch (e) { return e.message }`)).toBe( - "JSON.rawJSON is not a function.", - ) - expect(await value(`try { search({ query: "star" }).filter(() => 1) } catch (e) { return e.message }`)).toBe( - "search(...).filter is not a function.", - ) - expect( - await value(`const foo = () => ({ bar: () => ({}) }); try { foo().bar().baz() } catch (e) { return e.message }`), - ).toBe("foo(...).bar(...).baz is not a function.") - }) - - test("built-ins are objects on a real prototype chain", async () => { - expect( - await value(` - return [ - Math.constructor === Object, - Number.constructor === Function, - Object.prototype.hasOwnProperty === ({}).hasOwnProperty, - Array.prototype.push.name, - Array.prototype.push.length, - Math.max.length, - Object.keys(Math), - typeof Array.prototype.map, - Array.isArray(Array.prototype), - ] - `), - ).toEqual([true, true, true, "push", 1, 2, [], "function", true]) - }) -}) - -describe("async function line breaks", () => { - test("a line break between function and the name is an async function", async () => { - expect(await value(`async function\nfoo() { return 1 }\nreturn await foo()`)).toBe(1) - }) - - test("a line break between async and function is not an async function", async () => { - const failure = await error(`async\nfunction foo() { return 1 }\nreturn foo()`) - expect(failure.message).toContain("Unknown identifier 'async'") - }) -}) - -describe("functions are objects", () => { - test("name follows NamedEvaluation and length counts required parameters", async () => { - expect( - await value(` - function decl(a, b = 1, ...rest) {} - const arrow = () => {} - const named = function inner() {} - let assigned - assigned = (a, b) => {} - const { fromDefault = () => {} } = {} - const [fromArray = function () {}] = [] - const obj = { method() {}, key: () => {}, [Symbol.iterator]: () => {} } - const passthrough = (0, () => {}) - return [ - [decl.name, decl.length], - [arrow.name, named.name, assigned.name, assigned.length], - [fromDefault.name, fromArray.name], - [obj.method.name, obj.key.name, obj[Symbol.iterator].name], - passthrough.name, - ] - `), - ).toEqual([ - ["decl", 1], - ["arrow", "inner", "assigned", 2], - ["fromDefault", "fromArray"], - ["method", "key", "[Symbol.iterator]"], - "", - ]) - }) - - test("functions hold own properties; name and length are read-only", async () => { - expect( - await value(` - const fn = () => 1 - fn.count = 2 - fn.count += 1 - let renamed = false - try { fn.name = "other" } catch (error) { renamed = error instanceof TypeError } - const { name, count } = fn - return [fn.count, Object.keys(fn), "count" in fn, "name" in fn, name, count, renamed, delete fn.count, fn.count] - `), - ).toEqual([3, ["count"], true, true, "fn", 3, true, true, null]) - }) -}) - -describe("tagged templates", () => { - test("the tag receives the cooked strings, their raw forms, and the substitutions in order", async () => { - expect( - await value(` - const tag = (strings, ...values) => [strings, strings.raw, values, Object.keys(strings)] - return tag\`a\${1}b\\n\${2}c\` - `), - ).toEqual([ - ["a", "b\n", "c"], - ["a", "b\\n", "c"], - [1, 2], - ["0", "1", "2"], - ]) - }) - - test("an invalid escape cooks to undefined and keeps its raw text", async () => { - expect(await value(`return ((strings) => [strings[0] === undefined, strings.raw[0]])\`\\unicode\``)).toEqual([ - true, - "\\unicode", - ]) - }) - - test("each site has one template object; different sites differ", async () => { - expect( - await value(` - const seen = [] - const tag = (strings) => { seen.push(strings) } - for (let i = 0; i < 2; i++) tag\`x\${i}\` - tag\`x\${0}\` - return [seen[0] === seen[1], seen[0] === seen[2]] - `), - ).toEqual([true, false]) - }) - - test("the tag is read like a callee: members, chained tags, async tags, and the not-a-function error", async () => { - expect( - await value(` - const o = { tag: (strings) => strings[0].toUpperCase() } - const chain = () => chain - const asyncTag = async (strings, value) => strings[0] + value - let failure - try { (1)\`x\` } catch (error) { failure = error instanceof TypeError } - return [o.tag\`abc\`, typeof chain\`a\`\`b\`, await asyncTag\`n=\${1}\`, failure] - `), - ).toEqual(["ABC", "function", "n=1", true]) - }) - - test("raw is read-only", async () => { - expect(await value(`try { ((strings) => { strings.raw = 1 })\`a\` } catch (error) { return error.name }`)).toBe( - "TypeError", - ) - }) -}) - -describe("String.raw", () => { - test("joins the raw strings with the substitutions", async () => { - expect(await value(`return [String.raw\`a\\n\${1}b\`, String.raw({ raw: ["x", "y", "z"] }, 1, 2, 3)]`)).toEqual([ - "a\\n1b", - "x1y2z", - ]) - }) - - test("extra substitutions are dropped, missing ones are skipped, and a program object's toString is used", async () => { - expect( - await value(` - const shout = { toString() { return "!" } } - return [String.raw({ raw: ["x", "y"] }, 1, 2), String.raw({ raw: ["x", "y", "z"] }, shout), String.raw({ raw: { length: 0 } })] - `), - ).toEqual(["x1y", "x!yz", ""]) - }) - - test("a template without a raw array is a TypeError", async () => { - const failure = await error(`String.raw(1)`) - expect(failure.message).toContain("String.raw expects a template object with a raw array") - }) -}) - -describe("sloppy duplicate parameters and for...in targets", () => { - test("a repeated parameter name binds the last argument", async () => { - expect(await value(`function f(a, b, a) { return [a, b] } return [f(1, 2, 3), f(1)]`)).toEqual([ - [3, 2], - [null, null], - ]) - }) - - test("for...in assigns to any target: members, computed members, and patterns", async () => { - expect( - await value(` - const x = {}, seen = [], a = [] - let i = 0, first - for (x.y in { p: 1, q: 2 }) seen.push(x.y) - for (a[i++] in { p: 1, q: 2 }); - for ([first] in { ab: 1 }); - return [seen, x.y, a, first] - `), - ).toEqual([["p", "q"], "q", ["p", "q"], "a"]) - }) -}) - -describe("loose equality and operator gates on opaque references", () => { - test("== follows IsLooselyEqual for data values", async () => { - expect( - await value(` - return [null == undefined, "1" == 1, true == 1, "" == 0, [1] == 1, [1, 2] == "1,2", - ({}) == "[object Object]", NaN == NaN, ({}) == ({}), null == 0, new Date(0) == 0] - `), - ).toEqual([true, true, true, true, true, true, true, false, false, false, false]) - }) - - test("functions and tool references compare by identity and are never equal to nullish", async () => { - expect( - await value(` - const fn = () => 1, other = () => 2 - return [fn == null, fn != null, fn == undefined, fn == fn, fn == other, [fn] == null, ({ f: fn }) == null, - [fn] == [fn], tools == null, tools == tools] - `), - ).toEqual([false, true, false, true, false, false, false, false, false, true]) - }) - - test("coercing an opaque reference against a non-nullish primitive still rejects", async () => { - expect((await error(`const fn = () => 1; return fn == 1`)).message).toContain( - "Binary operators require data values", - ) - expect((await error(`const fn = () => 1; return fn + ""`)).message).toContain( - "Binary operators require data values", - ) - expect((await error(`const fn = () => 1; return -fn`)).message).toContain("Unary operators require data values") - expect((await error(`let fn = () => 1; fn++`)).message).toContain("'++' requires a data value") - }) - - test("switch and Object.is match opaque references by identity", async () => { - expect( - await value(` - const fn = () => 1, other = () => 2 - const pick = (v) => { switch (v) { case fn: return "fn"; case other: return "other"; default: return "none" } } - return [pick(fn), pick(other), pick(1), Object.is(fn, fn), Object.is(fn, other), Object.is(NaN, NaN), Object.is(0, -0)] - `), - ).toEqual(["fn", "other", "none", true, false, true, false]) - }) - - test("operators look only at their direct operands, so nested functions coerce like other data", async () => { - expect( - await value(` - const fn = () => 1 - let x = [fn] - x++ - return [[1, [2]] + "", ({ a: 1 }) * 2, [fn] + "", Number.isNaN(-[fn]), Number.isNaN(x), typeof fn, !fn] - `), - ).toEqual(["1,2", null, "[object Function]", true, true, "function", false]) - }) -}) - -describe("Object.freeze, seal, and preventExtensions", () => { - test("a frozen object rejects writes, additions, and deletes with TypeErrors", async () => { - expect( - await value(` - const o = Object.freeze({ a: 1 }) - const errors = [] - try { o.a = 2 } catch (e) { errors.push(e.name + ": " + e.message) } - try { o.b = 2 } catch (e) { errors.push(e.name + ": " + e.message) } - try { delete o.a } catch (e) { errors.push(e.name + ": " + e.message) } - return [errors, o.a, Object.isFrozen(o), Object.isSealed(o), Object.isExtensible(o)] - `), - ).toEqual([ - [ - "TypeError: Cannot assign to read only property 'a'.", - "TypeError: Cannot add property b, object is not extensible.", - "TypeError: Cannot delete property 'a'.", - ], - 1, - true, - true, - false, - ]) - }) - - test("seal keeps writes, preventExtensions keeps deletes, and each returns its argument", async () => { - expect( - await value(` - const s = { a: 1 }, p = { a: 1 } - const errors = [] - Object.seal(s).a = 2 - try { delete s.a } catch (e) { errors.push(e.name) } - delete Object.preventExtensions(p).a - try { p.b = 1 } catch (e) { errors.push(e.name) } - return [errors, s.a, Object.keys(p), Object.isSealed(s), Object.isFrozen(s), Object.isSealed(p), Object.isFrozen(p)] - `), - ).toEqual([["TypeError", "TypeError"], 2, [], true, false, true, true]) - }) - - test("primitives pass through, and Object.assign honors the flags", async () => { - expect( - await value(` - return [Object.freeze(1) === 1, Object.isFrozen(1), Object.isSealed("a"), Object.isExtensible(null), Object.isFrozen({}), Object.isExtensible({})] - `), - ).toEqual([true, true, true, false, false, true]) - const failure = await error(`Object.assign(Object.freeze({ a: 1 }), { b: 1 })`) - expect(failure.message).toContain("Cannot add property b, object is not extensible") - }) - - test("frozen arrays reject element, length, and mutating-method writes like JS", async () => { - expect( - await value(` - const a = Object.freeze([1, 2]) - const attempt = (f) => { try { f(); return "ok" } catch (e) { return e.name + ": " + e.message } } - return [ - attempt(() => a.push(3)), - attempt(() => { a[0] = 9 }), - attempt(() => { a[5] = 9 }), - attempt(() => { a.length = 0 }), - attempt(() => a.pop()), - attempt(() => a.sort()), - attempt(() => a.reverse()), - attempt(() => a.fill(0)), - attempt(() => a.copyWithin(0, 1)), - attempt(() => a.splice(0, 1)), - attempt(() => a.unshift(0)), - a, a.map((x) => x * 2), Object.isFrozen(a), Object.isFrozen(Object.freeze([])), - ] - `), - ).toEqual([ - "TypeError: Cannot add property 2, object is not extensible.", - "TypeError: Cannot assign to read only property '0'.", - "TypeError: Cannot add property 5, object is not extensible.", - "TypeError: Cannot assign to read only property 'length'.", - "TypeError: Cannot delete property '1'.", - "TypeError: Cannot assign to read only property '0'.", - "TypeError: Cannot assign to read only property '0'.", - "TypeError: Cannot assign to read only property '0'.", - "TypeError: Cannot assign to read only property '0'.", - "TypeError: Cannot delete property '1'.", - "TypeError: Cannot add property 2, object is not extensible.", - [1, 2], - [2, 4], - true, - true, - ]) - }) - - test("sealed and non-extensible arrays allow exactly the writes JS does", async () => { - expect( - await value(` - const s = Object.seal([1, 2]), p = Object.preventExtensions([1, 2, 3]) - const attempt = (f) => { try { f(); return "ok" } catch (e) { return e.name } } - const results = [attempt(() => { s[0] = 5 }), attempt(() => s.pop()), attempt(() => { s.length = 0 }), attempt(() => s.push(1))] - p.pop(); p.sort(); p.reverse(); p.fill(0, 1); p.copyWithin(0, 1); p.length = 5 - results.push(attempt(() => p.push(1)), attempt(() => p.splice(0, 1, 7, 8)), p.splice(0, 1, 7), attempt(() => { p[9] = 1 })) - return [results, s, p, Object.isSealed(p), Object.isFrozen(p), Object.isSealed(Object.preventExtensions([])), Object.isFrozen(Object.preventExtensions([]))] - `), - ).toEqual([ - ["ok", "TypeError", "TypeError", "TypeError", "TypeError", "TypeError", [0], "TypeError"], - [5, 2], - [7, 0, null, null, null], - false, - false, - true, - false, - ]) - }) - - test("typed arrays with elements cannot be frozen; wrappers freeze their properties only", async () => { - const failure = await error(`Object.freeze(new Uint8Array([1]))`) - expect(failure.message).toContain("Cannot freeze array buffer views with elements") - expect( - await value(` - const empty = Object.freeze(new Uint8Array(0)) - const bytes = Object.preventExtensions(new Uint8Array([1])) - const m = Object.freeze(new Map()); m.set(1, 2) - const f = Object.freeze(() => 1) - let named = "ok" - try { f.x = 1 } catch (e) { named = e.name } - return [Object.isFrozen(empty), Object.isFrozen(bytes), Object.isExtensible(bytes), m.size, Object.isFrozen(f), named, f()] - `), - ).toEqual([true, false, false, 1, true, "TypeError", 1]) - }) -}) - -describe("Object.getPrototypeOf and Object.create", () => { - test("getPrototypeOf returns the built-in prototypes for objects and primitives", async () => { - expect( - await value(` - return [ - Object.getPrototypeOf([]) === Array.prototype, - Object.getPrototypeOf({}) === Object.prototype, - Object.getPrototypeOf(Object.prototype), - Object.getPrototypeOf("a") === String.prototype, - Object.getPrototypeOf(1) === Number.prototype, - Object.getPrototypeOf(true) === Boolean.prototype, - Object.getPrototypeOf(new TypeError("x")) === TypeError.prototype, - Object.getPrototypeOf(TypeError.prototype) === Error.prototype, - Object.getPrototypeOf(() => 1) === Function.prototype, - ] - `), - ).toEqual([true, true, null, true, true, true, true, true, true]) - }) - - test("getPrototypeOf rejects null, undefined, and symbols", async () => { - expect((await error(`Object.getPrototypeOf(null)`)).message).toContain("cannot convert null to an object") - expect((await error(`Object.getPrototypeOf(undefined)`)).message).toContain("cannot convert undefined to an object") - expect((await error(`Object.getPrototypeOf(Symbol.iterator)`)).message).toContain("cannot convert a symbol") - }) - - test("Object.create links the prototype: inherited reads, in, own-only keys, and inherited for...in", async () => { - expect( - await value(` - const p = { greet(name) { return "hi " + name }, a: 1 } - const c = Object.create(p) - c.name = "x" - const seen = [] - for (const key in c) seen.push(key) - return ["greet" in c, Object.keys(c), c.hasOwnProperty("a"), c.a, c.greet(c.name), Object.getPrototypeOf(c) === p, Object.getPrototypeOf(Object.create(null)), seen] - `), - ).toEqual([true, ["name"], false, 1, "hi x", true, null, ["name", "greet", "a"]]) - }) - - test("Object.create rejects non-object prototypes and defines properties from descriptors", async () => { - expect((await error(`Object.create(1)`)).message).toContain("Object prototype may only be an Object or null") - expect((await error(`Object.create()`)).message).toContain("Object prototype may only be an Object or null") - expect(await value(`return Object.create(null, { a: { value: 1, enumerable: true } }).a`)).toBe(1) - expect(await value(`return Object.keys(Object.create({}, undefined))`)).toEqual([]) - }) -}) - -describe("structuredClone", () => { - test("deep-copies data values and keeps shared references shared", async () => { - expect( - await value(` - const shared = { n: 1 } - const source = { a: shared, b: shared, list: [1, , shared], map: new Map([[1, { a: [1, 2] }]]), set: new Set([shared]), when: new Date(5), bytes: new Uint8Array([1, 2]) } - const c = structuredClone(source) - c.a.n = 2 - return [ - c !== source, c.a === c.b, c.a !== shared, shared.n, c.list[2] === c.a, 1 in c.list, c.list.length, - c.map.get(1).a, c.map !== source.map, c.set.has(c.a), c.when.getTime(), c.when instanceof Date, - c.bytes instanceof Uint8Array, c.bytes[1], Array.isArray(c.list), - ] - `), - ).toEqual([true, true, true, 1, true, false, 3, [1, 2], true, true, 5, true, true, 2, true]) - }) - - test("regexps reset lastIndex, errors keep name, message, and cause, and extras are dropped", async () => { - expect( - await value(` - const r = /a/g - r.lastIndex = 3 - const e = new TypeError("boom", { cause: { code: 1 } }) - e.extra = 1 - const custom = new Error("x") - custom.name = "Custom" - const [cr, ce, cc] = [structuredClone(r), structuredClone(e), structuredClone(custom)] - return [cr.source, cr.flags, cr.lastIndex, ce instanceof TypeError, ce.name, ce.message, ce.cause, ce.cause !== e.cause, ce.extra, Object.keys(ce), cc.name] - `), - ).toEqual(["a", "g", 0, true, "TypeError", "boom", { code: 1 }, true, null, [], "Error"]) - }) - - test("the clone is a plain extensible object: prototypes, symbols, undefined fields, and frozen state drop", async () => { - expect( - await value(` - const c = structuredClone(Object.freeze(Object.assign(Object.create({ inherited: 1 }), { a: undefined, [Symbol.iterator]: 1, b: 2 }))) - return [Object.isFrozen(c), Object.getPrototypeOf(c) === Object.prototype, "a" in c, Symbol.iterator in c, c.b, c.inherited] - `), - ).toEqual([false, true, true, false, 2, null]) - }) - - test("functions, symbols, promises, wrappers, and tool references throw a DataCloneError TypeError", async () => { - for (const code of [ - `structuredClone(() => 1)`, - `structuredClone({ deep: [Symbol.iterator] })`, - `structuredClone(Promise.resolve(1))`, - `structuredClone(new URL("http://x"))`, - `structuredClone(tools)`, - ]) { - const failure = await error(code) - expect(failure.message).toMatch(/^TypeError: DataCloneError: .* could not be cloned\./) - } - expect(await value(`try { structuredClone(() => 1) } catch (e) { return e.name }`)).toBe("TypeError") - expect((await error(`structuredClone()`)).message).toContain("structuredClone requires 1 argument") - }) -}) - -describe("error constructor prototype chain", () => { - test("derived error constructors extend Error and inherit its statics", async () => { - expect( - await value(` - const derived = [TypeError, RangeError, SyntaxError, ReferenceError, EvalError, URIError, AggregateError] - return [ - derived.every((ctor) => Object.getPrototypeOf(ctor) === Error), - Object.getPrototypeOf(Error) === Function.prototype, - TypeError.isError(new RangeError("x")), - new TypeError("x") instanceof Error, - ] - `), - ).toEqual([true, true, true, true]) - }) -}) - -describe("this, arguments, and Function.prototype.call/apply/bind", () => { - test("this is the call receiver for non-arrow functions and lexical for arrows", async () => { - expect( - await value(` - const o = { n: 1, m() { return this.n }, a() { return (() => this.n)() }, bare() { return this } } - const detached = o.bare - function f() { return this } - return [o.m(), o["m"](), o?.m(), (o.m)(), o.a(), o.bare() === o, detached(), f(), (0, o.bare)(), this, (() => this)()] - `), - ).toEqual([1, 1, 1, 1, 1, true, null, null, null, null, null]) - }) - - test("this reaches generator and async methods and plain-function callbacks", async () => { - expect( - await value(` - const o = { n: 2, *g() { yield this.n }, async m() { return this.n }, xs: [1, 2], go() { return this.xs.map(function (x) { return [x, this] }) } } - return [[...o.g()], await o.m(), o.go()] - `), - ).toEqual([ - [2], - 2, - [ - [1, null], - [2, null], - ], - ]) - }) - - test("arguments is an unmapped array-like that arrows and parameters interact with as in JS", async () => { - expect( - await value(` - function f(a) { arguments[0] = 9; return [arguments.length, arguments[1], a, [...arguments], Array.isArray(arguments), JSON.stringify(arguments), typeof arguments.map, (() => arguments[1])()] } - function shadow(arguments) { return arguments } - function hoisted() { var arguments; return arguments.length } - let outer - try { outer = arguments } catch (error) { outer = error.name } - return [f(1, 2), shadow(7), hoisted(1, 2, 3), outer] - `), - ).toEqual([[2, 2, 1, [9, 2], false, '{"0":9,"1":2}', "undefined", 2], 7, 3, "ReferenceError"]) - }) - - test("call, apply, and bind set this and arguments on program functions and built-ins", async () => { - expect( - await value(` - function f(a, b, c) { return [this, a, b, c] } - const g = f.bind({ k: 1 }, "A") - const arr = [1] - Array.prototype.push.call(arr, 2, 3) - return [ - f.call("t", 1, 2), - f.apply({ k: 2 }, [1, 2]), - f.apply(null, { length: 2, 0: "x", 1: "y" }), - f.apply(null).length, - g("B", "C"), g.name, g.length, - f.bind(1).bind(2)()[0], - arr, - Math.max.apply(null, [1, 5, 3]), - Math.max.bind(null, 10)(3), - [1, 2].map(f.bind(null, 0)).map((r) => r[1]), - ] - `), - ).toEqual([ - ["t", 1, 2, null], - [{ k: 2 }, 1, 2, null], - [null, "x", "y", null], - 4, - [{ k: 1 }, "A", "B", "C"], - "bound f", - 2, - 1, - [1, 2, 3], - 5, - 10, - [0, 0], - ]) - }) - - test("call and apply reject non-callable receivers and non-array-like argument lists", async () => { - expect((await error(`Function.prototype.call.call(1)`)).message).toContain( - "Function.prototype.call called on incompatible receiver", - ) - expect((await error(`(() => 1).apply(null, 5)`)).message).toContain("expects an array-like argument list") - expect((await error(`(() => 1).apply(null, { length: 1e9 })`)).message).toContain("Invalid array length") - expect( - await value( - `function f() { return arguments.length } return [f.apply(null, { length: -5 }), f.apply(null, { length: "2" })]`, - ), - ).toEqual([0, 2]) - expect((await error(`function f(n) { return f.call(null, n + 1) } f(0)`)).message).toContain( - "Maximum call stack size exceeded", - ) - }) -}) - -describe("ToPrimitive: operators and conversions honor program valueOf and toString", () => { - test("program-installed valueOf and toString on opaque values are ignored at every site", async () => { - expect( - await value(` - const f = () => 1 - f.toString = () => "custom" - f.valueOf = () => 5 - return [String(f), \`\${f}\`, [f].join(), new Error(f).message, isNaN(Number(f)), isNaN(Math.abs(f))] - `), - ).toEqual(["[object Function]", "[object Function]", "[object Function]", "[object Function]", true, true]) - }) - - test("== converts an object facing a non-nullish primitive through its own valueOf", async () => { - expect( - await value(` - const one = { valueOf() { return 1 } } - return [one == 1, 1 == one, one == true, one == "1", one == null, one == one, one == { valueOf() { return 1 } }, [1] == 1] - `), - ).toEqual([true, true, true, true, false, true, false, true]) - expect((await error(`(() => 1) == 1`)).message).toContain("Binary operators require data values") - }) - - test("operators, unary, template literals, and conversion functions use the object's own methods", async () => { - expect( - await value(` - const money = { valueOf() { return 7 } } - return [money * 2, money + 1, money + "", -money, +money, ~money, money < 8, money ** 2, money | 8, - Number(money), Math.max(money, 1), \`\${money}\`, String(money), isNaN(money), isFinite(money), - parseInt({ toString() { return "42px" } }), parseInt("ff", { valueOf() { return 16 } }), - Number.parseFloat({ toString() { return "1.5" } })] - `), - ).toEqual([ - 14, - 8, - "7", - -7, - 7, - -8, - true, - 49, - 15, - 7, - 7, - "[object Object]", - "[object Object]", - false, - true, - 42, - 255, - 1.5, - ]) - }) - - test("the hint picks the method: + and Number prefer valueOf, template literals and String prefer toString", async () => { - expect( - await value(` - const both = { valueOf() { return 1 }, toString() { return "s" } } - return [both + "", \`\${both}\`, String(both), both * 2, new Error(both).message, [both].join(), [both, 2] + ""] - `), - ).toEqual(["1", "s", "s", 2, "s", "s", "s,2"]) - }) - - test("operands convert left then right, and a throwing valueOf surfaces as the program error", async () => { - expect( - await value(` - const order = [] - const a = { valueOf() { order.push("a"); return 1 } }, b = { valueOf() { order.push("b"); return 2 } } - a + b; a < b; a - b - return order - `), - ).toEqual(["a", "b", "a", "b", "a", "b"]) - expect( - await value(` - const bad = { valueOf() { throw new RangeError("nope") } } - const names = [] - try { bad + 1 } catch (e) { names.push(e.name) } - try { Number(bad) } catch (e) { names.push(e.name) } - try { Math.abs(bad) } catch (e) { names.push(e.name) } - return names - `), - ).toEqual(["RangeError", "RangeError", "RangeError"]) - }) - - test("arrays keep their built-in join form unless the program replaces toString", async () => { - expect( - await value(` - const arr = [1, 2] - const before = [arr + "", [] + [], [1, , 3].join("-"), [1, { toString() { return "q" } }].join("-")] - arr.toString = () => "x" - return [...before, arr + "", \`\${arr}\`, String(arr)] - `), - ).toEqual(["1,2", "", "1--3", "1-q", "x", "x", "x"]) - }) - - test("update and compound assignment convert the current value", async () => { - expect( - await value(` - let x = { valueOf() { return 5 } } - const o = { n: { valueOf() { return 4 } } } - const after = x++ - o.n += 1 - o.n++ - let s = { valueOf() { return 2 } } - s *= 3 - return [after, x, o.n, s] - `), - ).toEqual([5, 6, 6, 6]) - }) - - test("functions and other opaque values still reject arithmetic, and an object without a primitive form throws", async () => { - expect((await error(`const f = () => 1; return f + 1`)).message).toContain("Binary operators require data values") - expect((await error(`return -(() => 1)`)).message).toContain("Unary operators require data values") - const failure = await error(`return { valueOf() { return {} }, toString() { return [] } } + 1`) - expect(failure.message).toContain("Cannot convert object to primitive value") - }) -}) - -describe("object destructuring from primitives", () => { - test("reads through the primitive's prototype like member access", async () => { - expect( - await value(` - const { length, 0: first, toUpperCase } = "abc" - const { toFixed } = 1.5 - const {} = true - const { 0: a, ...rest } = "xyz" - const { ...none } = 42 - let n - ;({ length: n } = "hello") - return [length, first, toUpperCase.call("q"), toFixed.call(2.345, 1), a, rest, none, n] - `), - ).toEqual([3, "a", "Q", "2.3", "x", { 1: "y", 2: "z" }, {}, 5]) - }) - - test("only null and undefined sources throw", async () => { - expect((await error(`const { a } = null`)).message).toContain("Cannot destructure null as it is null") - expect((await error(`const {} = undefined`)).message).toContain("Cannot destructure undefined") - expect((await error(`let a; ({ a } = undefined)`)).message).toContain("Cannot destructure undefined") - }) -}) - -describe("Date components convert through ToPrimitive", () => { - test("construction and Date.UTC ask each of the first seven arguments in order", async () => { - expect( - await value(` - const seen = [] - const part = (n) => ({ valueOf() { seen.push(n); return n } }) - const time = new Date(part(2024), part(1), part(2), part(3), part(4), part(5), part(6), part(99)).getTime() - const utc = Date.UTC(2024, { valueOf() { return 0 } }, 15) - return [seen, time === new Date(2024, 1, 2, 3, 4, 5, 6).getTime(), utc === Date.UTC(2024, 0, 15)] - `), - ).toEqual([[2024, 1, 2, 3, 4, 5, 6], true, true]) - expect((await error(`new Date(2024, { valueOf() { throw new RangeError("boom") } })`)).message).toContain("boom") - }) - - test("setters on an invalid Date answer NaN without overwriting a time set during coercion", async () => { - expect( - await value(` - const d = new Date(NaN) - const result = d.setDate({ valueOf() { d.setTime(0); return 1 } }) - const y = new Date(NaN) - return [Number.isNaN(result), d.getTime(), y.setFullYear(2020) === Date.UTC(2020, 0, 1) - y.getTimezoneOffset() * 60000] - `), - ).toEqual([true, 0, true]) - }) -}) - -describe("iteration callbacks receive thisArg", () => { - test("Array, Array.from, Map, Set, URLSearchParams, Headers, and Uint8Array pass it as this", async () => { - expect( - await value(` - const c = { n: 0 } - const count = function () { this.n++ } - ;[1, 2].forEach(count, c) - ;[1].map(count, c) - ;[1].filter(count, c) - ;[1].find(count, c) - ;[1].findIndex(count, c) - ;[1].findLast(count, c) - ;[1].findLastIndex(count, c) - ;[1].some(count, c) - ;[1].every(count, c) - ;[1].flatMap(count, c) - Array.from([1], count, c) - Array.from({ length: 1 }, count, c) - new Map([[1, 1]]).forEach(count, c) - new Set([1]).forEach(count, c) - new URLSearchParams("a=1").forEach(count, c) - new Headers({ a: "1" }).forEach(count, c) - new Uint8Array([1]).forEach(count, c) - return c.n - `), - ).toBe(18) - expect(await value(`return [1, 2].map(function (x) { return x + this.v }, { v: 10 })`)).toEqual([11, 12]) - }) - - test("arrows keep their lexical this, reduce takes an initial value instead, and opaque values are only bound", async () => { - expect(await value(`return [1].map(() => typeof this, { v: 1 })`)).toEqual(["undefined"]) - expect( - await value(`return [1, 2].reduce(function (a, b) { return a + b + (this === undefined ? 0 : 100) }, 0)`), - ).toBe(3) - expect( - await value(` - let seen - ;[1].forEach(function () { seen = this }, tools.nowhere) - return typeof seen - `), - ).toBe("function") - }) -}) - -describe("computed property keys convert through the object's own toString", () => { - test("reads, writes, compound assignment, in, delete, literals, and destructuring share one conversion", async () => { - expect( - await value(` - const key = { toString() { return "id" } } - const o = {} - o[key] = 1 - o[key] += 1 - const literal = { [key]: "lit" } - const had = key in o - delete literal[key] - return [o.id, had, (({ [key]: v }) => v)(o), literal, o[[1, 2]] === undefined] - `), - ).toEqual([2, true, 2, {}, true]) - expect( - await value(` - const seen = [] - const base = { x: 1 } - base[{ toString() { seen.push(1); return "" } }] ^= 0 - base[{ toString() { seen.push(2); return "x" } }]++ - return [seen, base[""], base.x] - `), - ).toEqual([[1, 2], 0, 2]) - }) - - test("valueOf is the fallback, a symbol result stays a symbol, and conversion failures surface", async () => { - expect( - await value(` - const o = { 7: "seven" } - const sym = { toString() { return Symbol.iterator } } - o[sym] = 1 - return [o[{ valueOf() { return 7 }, toString: undefined }], typeof o[Symbol.iterator], Object.keys(o)] - `), - ).toEqual(["seven", "number", ["7"]]) - expect((await error(`({})[{ toString() { throw new RangeError("bad key") } }]`)).message).toContain("bad key") - expect((await error(`({})[{ toString() { return {} }, valueOf() { return {} } }]`)).message).toContain( - "Cannot convert object to primitive value", - ) - expect((await error(`const key = { toString() { return "a" } }; key in 5`)).message).toContain( - "requires a data object on the right-hand side", - ) - }) - - test("a nullish base throws before the key converts, as ToObject precedes ToPropertyKey", async () => { - const failure = await error(`const base = null; base[{ toString() { throw new RangeError("key evaluated") } }]`) - expect(failure.message).toContain("Cannot read properties of null") - }) - - test("opaque values keep their built-in key form and a tool reference toString is never called", async () => { - expect( - await value(` - const o = { "[object Function]": 1, "[object Promise]": 2 } - return [o[() => 1], o[Promise.resolve("k")]] - `), - ).toEqual([1, 2]) - expect((await error(`({})[{ toString: tools.nowhere }] = 1`)).message).toContain( - "Cannot convert object to primitive value", - ) - }) -}) - -describe("String and Number method arguments convert through ToPrimitive", () => { - test("string positions use the string hint and numeric positions the number hint", async () => { - expect( - await value(` - const s = { toString() { return "b" } } - const n = { valueOf() { return 1 } } - return [ - "abc".indexOf(s), "abc".lastIndexOf(s), "abc".includes(s), "abc".startsWith(s, n), "abc".endsWith(s, 2), - "abc".charAt(n), "abc".at({ valueOf() { return -1 } }), "abc".slice(n), "abc".substring(n, 2), - "abc".charCodeAt(n), "a".padStart({ valueOf() { return 3 } }, s), "x".padEnd(3, s), "ab".repeat({ valueOf() { return 2 } }), - "a".concat(s, { valueOf() { return 1 }, toString() { return "T" } }), "b".localeCompare(s), - (1.005).toFixed({ valueOf() { return 2 } }), (255).toString({ valueOf() { return 16 } }), - (1234.5678).toPrecision({ valueOf() { return 6 } }), (12345).toExponential({ valueOf() { return 2 } }), - ] - `), - ).toEqual([ - 1, - 1, - true, - true, - true, - "b", - "c", - "bc", - "b", - 98, - "bba", - "xbb", - "abab", - "abT", - 0, - "1.00", - "ff", - "1234.57", - "1.23e+4", - ]) - }) - - test("split, replace, match, and search convert a plain pattern but keep a RegExp as is", async () => { - expect( - await value(` - const s = { toString() { return "b" } } - return [ - "abc".split(s), "abc".split(/b/, { valueOf() { return 1 } }), "abc".split(undefined, { valueOf() { return undefined } }), - "abc".replace(s, "X"), "abc".replace(/b/, { toString() { return "R" } }), "abc".replaceAll(s, s), - "abc".replace(s, (m) => m.toUpperCase()), "abc".match(s)[0], "abcb".matchAll(s).length, "abc".search(s), - ] - `), - ).toEqual([["a", "c"], ["a"], [], "aXc", "aRc", "abc", "aBc", "b", 2, 1]) - expect((await error(`"abc".includes(/b/)`)).message).toContain("cannot take a regular expression") - }) - - test("the receiver converts first, then each consumed argument, in spec order; extra arguments are untouched", async () => { - expect( - await value(` - const log = [] - const observer = (name, string, number) => ({ - toString() { log.push("toString:" + name); return string }, - valueOf() { log.push("valueOf:" + name); return number }, - }) - const padded = String.prototype.padStart.call(observer("receiver", {}, "abc"), observer("maxLength", 11, {}), observer("fillString", {}, "def")) - const extra = "abc".indexOf("b", 1, { valueOf() { throw new Error("extra argument converted") } }) - return [padded, log, extra, String.prototype.trim.call({ toString() { return " abc " } })] - `), - ).toEqual([ - "defdefdeabc", - [ - "toString:receiver", - "valueOf:receiver", - "valueOf:maxLength", - "toString:maxLength", - "toString:fillString", - "valueOf:fillString", - ], - 1, - "abc", - ]) - }) - - test("conversion failures surface and opaque arguments still reject", async () => { - expect((await error(`"abc".indexOf({ toString() { throw new RangeError("intostr") } })`)).message).toContain( - "intostr", - ) - expect((await error(`(1).toString({ valueOf() { throw new SyntaxError("poison") } })`)).message).toContain("poison") - expect((await error(`(1).toFixed({ toString() { return {} }, valueOf() { return {} } })`)).message).toContain( - "Cannot convert object to primitive value", - ) - expect((await error(`"abc".indexOf(tools.nowhere)`)).message).toContain("expects argument 1 to be a data value") - expect((await error(`"abc".indexOf(Promise.resolve("b"))`)).message).toContain( - "expects argument 1 to be a data value", - ) - }) -}) - -describe("WeakMap and WeakSet", () => { - test("hold program objects by identity and answer like JS for non-object keys", async () => { - expect( - await value(` - const k = {} - const f = () => 1 - const wm = new WeakMap([[k, 1]]) - const ws = new WeakSet([k]) - return [ - wm.set(f, "fn") === wm, wm.get(k), wm.get(f), wm.has({}), wm.get(1), wm.has(1), wm.delete("s"), - wm.getOrInsert(k, 9), wm.getOrInsertComputed({}, (key) => typeof key), - ws.add(f) === ws, ws.has(k), ws.has(f), ws.has(1), ws.delete(k), ws.has(k), - String(wm), wm.size, "clear" in wm, Symbol.iterator in ws, JSON.stringify(wm), - ] - `), - ).toEqual([ - true, - 1, - "fn", - false, - null, - false, - false, - 1, - "object", - true, - true, - true, - false, - true, - false, - "[object WeakMap]", - null, - false, - false, - "{}", - ]) - }) - - test("reject primitive keys, plain calls, bad receivers, and cloning", async () => { - expect((await error(`new WeakMap().set(1, 1)`)).message).toContain("Invalid value used as weak map key") - expect((await error(`new WeakSet([1])`)).message).toContain("Invalid value used in weak set") - expect((await error(`WeakMap()`)).message).toContain("new") - expect((await error(`WeakMap.prototype.get.call(new Map(), {})`)).message).toContain("incompatible receiver") - expect((await error(`structuredClone(new WeakSet())`)).message).toContain("DataCloneError") - }) -}) diff --git a/packages/codemode/test/preload.ts b/packages/codemode/test/preload.ts deleted file mode 100644 index 0663e55bc39..00000000000 --- a/packages/codemode/test/preload.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { setRoundTrip } from "../src/language/runtime/execute.js" -import { accessorRule, nativeRule } from "../src/language/runtime/objects.js" - -// Every test run checks that natives are made only with the intrinsics, and that no built-in reaches a program -// getter or setter it has no path for. -nativeRule.check = true -accessorRule.check = true - -if (process.env.CODEMODE_ROUNDTRIP === "1") { - setRoundTrip(true) -} diff --git a/packages/codemode/test/prelude-bytecode.test.ts b/packages/codemode/test/prelude-bytecode.test.ts deleted file mode 100644 index 1dd6cecd254..00000000000 --- a/packages/codemode/test/prelude-bytecode.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { describe, expect, test } from "bun:test" -import { compileBuiltins } from "../script/prelude.js" -import saved from "../src/language/prelude/bytecode.json" with { type: "json" } -import { compiledPrelude } from "../src/language/prelude/prelude.js" -import { hashOf } from "../src/language/code.js" -import { getInternalPrelude } from "../src/language/internal-prelude.js" -import { moduleUrl, runProgram } from "./run-program.js" - -// The built-in sources are compiled ahead of time (script/prelude.ts); a process loads that bytecode instead. - -describe("precompiled built-ins", () => { - test("the saved bytecode is what the compiler makes now: run `bun run script/prelude.ts` after a change", () => { - expect(JSON.parse(JSON.stringify(compileBuiltins()))).toEqual(saved) - }) - - test("are loaded without parsing their sources, and have the compiled bytecode's hash", async () => { - const fresh = compileBuiltins() - for (const [built, id] of [ - [compiledPrelude(), "@prelude"], - [getInternalPrelude(), "@vm-internal"], - ] as const) { - const code = built.codes[0]! - expect(hashOf(built.codes)).toBe(code.source.hash) - expect(code.source).toEqual(fresh[id]!.codes[0]!.source as never) - } - // A fresh process runs a program that calls into the prelude, and its source is still unparsed. - const script = ` - import { runProgram } from ${moduleUrl("run-program.js")} - import { compiledPrelude } from ${moduleUrl("../src/language/prelude/prelude.js")} - const result = runProgram("return [3, 1, 2].map((x) => x * 2).sort((a, b) => a - b)") - console.log(JSON.stringify([result.ok && result.value, typeof compiledPrelude().codes[0].sourceObj.tree]))` - const child = Bun.spawn(["bun", "-e", script], { stdout: "pipe", stderr: "inherit" }) - expect(JSON.parse(await new Response(child.stdout).text())).toEqual([[2, 4, 6], "function"]) - expect(await child.exited).toBe(0) - }) - - test("a failure inside the prelude parses its source for the site, and is located at the program's call", () => { - const result = runProgram(`const xs = [1, 2]\nreturn xs.map((x) => x.y.z)`) - expect(result).toMatchObject({ ok: false, error: { location: { line: 2, column: 22 } } }) - }) -}) diff --git a/packages/codemode/test/promise-test262.test.ts b/packages/codemode/test/promise-test262.test.ts deleted file mode 100644 index d2b60659b2d..00000000000 --- a/packages/codemode/test/promise-test262.test.ts +++ /dev/null @@ -1,1510 +0,0 @@ -/* - * Portions adapted from Test262 at revision 250f204f23a9249ff204be2baec29600faae7b75. - * Every test names its upstream source; test.failing cases are executable conformance - * targets for intended Promise behavior that CodeMode does not implement yet. - * - * Copyright 2014 Cubane Canada, Inc. All rights reserved. - * Copyright 2015 Microsoft Corporation. All rights reserved. - * Copyright 2016 Microsoft, Inc. All rights reserved. - * Copyright 2017 Caitlin Potter. All rights reserved. - * Copyright (C) 2016-2020 the V8 project authors. All rights reserved. - * Copyright (C) 2018-2020 Rick Waldron. All rights reserved. - * Copyright (C) 2019 Leo Balter. All rights reserved. - * Test262 portions are governed by the BSD license in LICENSE.test262. - */ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" - -const execute = (code: string) => Effect.runPromise(CodeMode.execute({ code, tools: {}, limits: { timeoutMs: 1_000 } })) - -const value = async (code: string) => { - const result = await execute(code) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -describe("Test262 Promise statics", () => { - test("statics are callable and return promises", async () => { - // Sources: - // test/built-ins/Promise/all/S25.4.4.1_A1.1_T1.js - // test/built-ins/Promise/allSettled/is-function.js - // test/built-ins/Promise/allSettled/returns-promise.js - // test/built-ins/Promise/race/S25.4.4.3_A1.1_T1.js - // test/built-ins/Promise/resolve/S25.4.4.5_A1.1_T1.js - // test/built-ins/Promise/reject/S25.4.4.4_A1.1_T1.js - expect( - await value(` - const values = [ - Promise.all([]), - Promise.allSettled([]), - Promise.race([undefined]), - Promise.resolve(), - Promise.reject(), - ] - const callable = [ - typeof Promise.all, - typeof Promise.allSettled, - typeof Promise.race, - typeof Promise.resolve, - typeof Promise.reject, - ] - try { await values[4] } catch {} - return [callable, values.map((item) => item instanceof Promise)] - `), - ).toEqual([ - ["function", "function", "function", "function", "function"], - [true, true, true, true, true], - ]) - }) - - test("Promise.all returns fresh arrays for empty and settled inputs", async () => { - // Sources: - // test/built-ins/Promise/all/S25.4.4.1_A2.1_T1.js - // test/built-ins/Promise/all/S25.4.4.1_A2.3_T1.js - // test/built-ins/Promise/all/S25.4.4.1_A2.3_T2.js - // test/built-ins/Promise/all/S25.4.4.1_A2.3_T3.js - // test/built-ins/Promise/all/S25.4.4.1_A7.1_T1.js - expect( - await value(` - const input = [] - const emptyPromise = Promise.all(input) - const empty = await emptyPromise - const onePromise = Promise.all([Promise.resolve(3)]) - const one = await onePromise - return [ - emptyPromise instanceof Promise, - empty instanceof Array, - empty.length, - empty !== input, - onePromise instanceof Promise, - one instanceof Array, - one.length, - one[0], - ] - `), - ).toEqual([true, true, 0, true, true, true, 1, 3]) - }) - - test("Promise.all adopts values and preserves input order and identity", async () => { - // Sources: - // test/built-ins/Promise/all/resolve-non-thenable.js - // test/built-ins/Promise/all/S25.4.4.1_A8.2_T1.js - // test/built-ins/Promise/all/S25.4.4.1_A8.2_T2.js - const result = await value(` - const first = { id: 1 } - const second = { id: 2 } - const values = await Promise.all([Promise.resolve(3), first, Promise.resolve(second)]) - const observe = async (promise) => { - try { await promise; return "fulfilled" } catch (reason) { return reason } - } - return [ - values.length, - values[0], - values[1] === first, - values[2] === second, - await observe(Promise.all([Promise.reject(1), Promise.resolve(2)])), - await observe(Promise.all([Promise.resolve(1), Promise.reject(2)])), - ] - `) - expect(result).toEqual([3, 3, true, true, 1, 2]) - }) - - test("Promise.allSettled returns fresh arrays and ordered outcome records", async () => { - // Sources: - // test/built-ins/Promise/allSettled/resolves-empty-array.js - // test/built-ins/Promise/allSettled/resolves-to-array.js - // test/built-ins/Promise/allSettled/resolved-all-fulfilled.js - // test/built-ins/Promise/allSettled/resolved-all-rejected.js - // test/built-ins/Promise/allSettled/resolved-all-mixed.js - // test/built-ins/Promise/allSettled/resolve-non-thenable.js - expect( - await value(` - const input = [] - const empty = await Promise.allSettled(input) - const reason = { id: 4 } - const object = { id: 5 } - const outcomes = await Promise.allSettled([ - Promise.resolve(1), - Promise.reject(2), - 3, - Promise.reject(reason), - object, - ]) - return [ - empty instanceof Array, - empty.length, - empty !== input, - outcomes, - outcomes[4].value === object, - outcomes.map((item) => Object.keys(item)), - ] - `), - ).toEqual([ - true, - 0, - true, - [ - { status: "fulfilled", value: 1 }, - { status: "rejected", reason: 2 }, - { status: "fulfilled", value: 3 }, - { status: "rejected", reason: { id: 4 } }, - { status: "fulfilled", value: { id: 5 } }, - ], - true, - [ - ["status", "value"], - ["status", "reason"], - ["status", "value"], - ["status", "reason"], - ["status", "value"], - ], - ]) - }) - - test("Promise.race preserves fulfillment, rejection, and iterable order", async () => { - // Sources: - // test/built-ins/Promise/race/S25.4.4.3_A6.2_T1.js - // test/built-ins/Promise/race/S25.4.4.3_A7.1_T1.js - // test/built-ins/Promise/race/S25.4.4.3_A7.2_T1.js - // test/built-ins/Promise/race/S25.4.4.3_A7.3_T1.js - // test/built-ins/Promise/race/S25.4.4.3_A7.3_T2.js - expect( - await value(` - const observe = async (promise) => { - try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] } - } - return await Promise.all([ - observe(Promise.race([23])), - observe(Promise.race([Promise.reject(7)])), - observe(Promise.race([Promise.resolve(1), Promise.resolve(2)])), - observe(Promise.race([Promise.reject(3), Promise.resolve(4)])), - ]) - `), - ).toEqual([ - ["fulfilled", 23], - ["rejected", 7], - ["fulfilled", 1], - ["rejected", 3], - ]) - }) - - test("combinators consume supported string iterables", async () => { - // Sources: - // test/built-ins/Promise/all/iter-arg-is-string-resolve.js - // test/built-ins/Promise/allSettled/iter-arg-is-string-resolve.js - // test/built-ins/Promise/race/iter-arg-is-string-resolve.js - expect( - await value(` - return [ - await Promise.all("abc"), - await Promise.allSettled("ab"), - await Promise.race("abc"), - ] - `), - ).toEqual([ - ["a", "b", "c"], - [ - { status: "fulfilled", value: "a" }, - { status: "fulfilled", value: "b" }, - ], - "a", - ]) - }) - - test("Promise.resolve adopts values and preserves CodeMode-promise identity", async () => { - // Sources: - // test/built-ins/Promise/resolve/S25.4.4.5_A2.1_T1.js - // test/built-ins/Promise/resolve/resolve-non-obj.js - // test/built-ins/Promise/resolve/resolve-non-thenable.js - expect( - await value(` - const object = { id: 1 } - const promise = Promise.resolve(1) - return [ - await Promise.resolve(23), - await Promise.resolve(Promise.resolve(24)), - (await Promise.resolve(object)) === object, - [promise].includes(Promise.resolve(promise)), - ] - `), - ).toEqual([23, 24, true, true]) - }) - - test("Promise.reject preserves primitive and object reasons", async () => { - // Sources: - // test/built-ins/Promise/reject/S25.4.4.4_A2.1_T1.js - const result = await value(` - const object = { reason: true } - const reasons = [undefined, null, false, true, 0, "", 42, object] - const observe = async (reason) => { - try { await Promise.reject(reason); return false } catch (caught) { return caught === reason } - } - return await Promise.all(reasons.map(observe)) - `) - expect(result).toEqual([true, true, true, true, true, true, true, true]) - }) - - test("Promise.all resolves duplicate members into every slot", async () => { - // Sources: - // test/built-ins/Promise/all/invoke-resolve-on-promises-every-iteration-of-promise.js - // test/built-ins/Promise/all/invoke-resolve-on-values-every-iteration-of-promise.js - // (adapted: CodeMode has no observable Promise.resolve hook, so per-iteration - // handling of a repeated member is asserted through the resolved slots) - expect( - await value(` - const settled = Promise.resolve(3) - const computed = (async () => "computed")() - return [ - await Promise.all([settled, settled, settled]), - await Promise.all([computed, "plain", computed]), - ] - `), - ).toEqual([ - [3, 3, 3], - ["computed", "plain", "computed"], - ]) - }) - - test("Promise.allSettled records duplicate members independently", async () => { - // Source: test/built-ins/Promise/allSettled/invoke-resolve-on-promises-every-iteration-of-promise.js - // (adapted: per-iteration handling of a repeated member is asserted through the - // outcome records instead of a Promise.resolve hook) - expect( - await value(` - const good = Promise.resolve(1) - const bad = Promise.reject(2) - return await Promise.allSettled([good, bad, good, bad]) - `), - ).toEqual([ - { status: "fulfilled", value: 1 }, - { status: "rejected", reason: 2 }, - { status: "fulfilled", value: 1 }, - { status: "rejected", reason: 2 }, - ]) - }) - - test("combinators adopt members that settled before the call", async () => { - // Sources: - // test/built-ins/Promise/all/reject-immed.js - // test/built-ins/Promise/allSettled/reject-immed.js - // test/built-ins/Promise/race/reject-immed.js - // (adapted: immediately-rejecting thenables become CodeMode promises that settled, - // and were even observed, before the combinator call) - expect( - await value(` - const fulfilled = Promise.resolve("done") - const rejected = Promise.reject("failed") - try { await rejected } catch {} - const observe = async (promise) => { - try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] } - } - return [ - await observe(Promise.all([fulfilled, rejected])), - await Promise.allSettled([rejected, fulfilled]), - await observe(Promise.race([rejected, fulfilled])), - ] - `), - ).toEqual([ - ["rejected", "failed"], - [ - { status: "rejected", reason: "failed" }, - { status: "fulfilled", value: "done" }, - ], - ["rejected", "failed"], - ]) - }) - - test("combinator results follow input order, not settlement order", async () => { - // Sources: - // test/built-ins/Promise/all/resolve-non-thenable.js - // test/built-ins/Promise/allSettled/resolved-all-mixed.js - // (adapted: members are created, and therefore settle, in reverse of input order; - // deferred settlement is not expressible without host-async work in this corpus) - expect( - await value(` - const third = Promise.resolve("c") - const failing = (async () => { throw "b" })() - try { await failing } catch {} - const second = (async () => "b")() - const first = Promise.resolve("a") - return [ - await Promise.all([first, second, third]), - await Promise.allSettled([first, failing, third]), - ] - `), - ).toEqual([ - ["a", "b", "c"], - [ - { status: "fulfilled", value: "a" }, - { status: "rejected", reason: "b" }, - { status: "fulfilled", value: "c" }, - ], - ]) - }) - - test("Promise.race ignores a rejected loser once the first contender wins", async () => { - // Source: test/built-ins/Promise/race/reject-ignored-immed.js - // (adapted: the losing rejection comes from an async function instead of a thenable; - // the exact-equality check also asserts the loser leaves no unhandled-rejection warning) - expect( - await execute(` - const loser = (async () => { throw "lost" })() - return await Promise.race([Promise.resolve("won"), loser]) - `), - ).toEqual({ ok: true, value: "won", toolCalls: [] }) - }) - - test("Promise.race([]) returns a promise whose CodeMode failure is catchable", async () => { - // Sources: - // test/built-ins/Promise/race/S25.4.4.3_A2.1_T1.js - // test/built-ins/Promise/race/S25.4.4.3_A5.1_T1.js - // (adapted: upstream requires Promise.race([]) to never settle; CodeMode intentionally - // rejects with a catchable diagnostic instead of hanging, so this asserts CodeMode - // divergence rather than the spec never-settles behavior) - expect( - await value(` - const empty = Promise.race([]) - try { - await empty - return "settled" - } catch (error) { - return [empty instanceof Promise, error instanceof Error] - } - `), - ).toEqual([true, true]) - }) - - test("Promise.resolve passes the same CodeMode promise through nested chains", async () => { - // Source: test/built-ins/Promise/resolve/S25.4.4.5_A2.2_T1.js - // (adapted: no executor construction, and identity is observed with Array includes - // because promises are not comparable data values in CodeMode) - expect( - await value(` - const promise = Promise.resolve({ id: 1 }) - return [ - [promise].includes(Promise.resolve(promise)), - [promise].includes(Promise.resolve(Promise.resolve(promise))), - (await Promise.resolve(Promise.resolve(promise))).id, - ] - `), - ).toEqual([true, true, 1]) - }) - - test("Promise.resolve of a rejected promise preserves identity and reason", async () => { - // Source: test/built-ins/Promise/resolve/S25.4.4.5_A2.3_T1.js - // (adapted: the source promise is already rejected instead of rejected later) - expect( - await value(` - const rejected = Promise.reject("oops") - const adopted = Promise.resolve(rejected) - const identity = [rejected].includes(adopted) - try { - await adopted - return "fulfilled" - } catch (reason) { - return [identity, reason] - } - `), - ).toEqual([true, "oops"]) - }) - - test("Promise.reject uses a promise reason without flattening it", async () => { - // Sources: - // test/built-ins/Promise/reject-via-fn-immed.js - // test/built-ins/Promise/reject-via-fn-deferred.js - // (adapted: the promise reason goes through Promise.reject instead of executor reject) - expect( - await value(` - const observe = async (reason) => { - try { - await Promise.reject(reason) - return "fulfilled" - } catch (caught) { - const identity = [reason].includes(caught) - try { return [identity, caught instanceof Promise, await caught] } - catch (inner) { return [identity, caught instanceof Promise, "rethrew " + inner] } - } - } - return [await observe(Promise.resolve(1)), await observe(Promise.reject("inner"))] - `), - ).toEqual([ - [true, true, 1], - [true, true, "rethrew inner"], - ]) - }) -}) - -describe("Test262 async functions and await", () => { - test("declaration, expression, and arrow forms return promises", async () => { - // Sources: - // test/language/statements/async-function/declaration-returns-promise.js - // test/language/expressions/async-function/expression-returns-promise.js - // test/language/expressions/async-arrow-function/arrow-returns-promise.js - expect( - await value(` - async function declaration() { return 1 } - const expression = async function() { return 2 } - const arrow = async () => 3 - const promises = [declaration(), expression(), arrow()] - return [promises.map((item) => item instanceof Promise), await Promise.all(promises)] - `), - ).toEqual([ - [true, true, true], - [1, 2, 3], - ]) - }) - - test("async bodies adopt returns and reject throws before and after await", async () => { - // Sources: - // test/language/statements/async-function/evaluation-body.js - // test/language/statements/async-function/evaluation-body-that-returns.js - // test/language/statements/async-function/evaluation-body-that-returns-after-await.js - // test/language/statements/async-function/evaluation-body-that-throws.js - // test/language/statements/async-function/evaluation-body-that-throws-after-await.js - expect( - await value(` - const order = [] - const plain = async () => { order.push("body"); return 42 } - const afterAwait = async () => { await Promise.resolve(); return 43 } - const throwsBefore = async () => { throw 1 } - const throwsAfter = async () => { await Promise.resolve(); throw 2 } - const observe = async (promise) => { - try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] } - } - const first = plain() - return [ - order, - await observe(first), - await observe(afterAwait()), - await observe(throwsBefore()), - await observe(throwsAfter()), - ] - `), - ).toEqual([["body"], ["fulfilled", 42], ["fulfilled", 43], ["rejected", 1], ["rejected", 2]]) - }) - - test("default-parameter throws reject instead of escaping the call", async () => { - // Source: test/language/statements/async-function/evaluation-default-that-throws.js - expect( - await value(` - const fail = () => { throw new Error("default") } - const run = async (value = fail()) => value - let returned = false - try { - const promise = run() - returned = promise instanceof Promise - await promise - return [returned, "fulfilled"] - } catch (error) { - return [returned, error.message] - } - `), - ).toEqual([true, "default"]) - }) - - test("async try/finally completion records override earlier completion", async () => { - // Sources: the try-{return,throw,reject}-finally-{return,throw,reject}.js matrix under - // test/language/statements/async-function, test/language/expressions/async-function, - // and test/language/expressions/async-arrow-function. - expect( - await value(` - const observe = async (promise) => { - try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] } - } - const returnReturn = async () => { try { return "early" } finally { return await Promise.resolve("override") } } - const returnThrow = async () => { try { return "early" } finally { throw "override" } } - const returnReject = async () => { try { return "early" } finally { await Promise.reject("override") } } - const throwReturn = async () => { try { throw "early" } finally { return await Promise.resolve("override") } } - const throwThrow = async () => { try { throw "early" } finally { throw "override" } } - const throwReject = async () => { try { throw "early" } finally { await Promise.reject("override") } } - const rejectReturn = async () => { try { await Promise.reject("early") } finally { return await Promise.resolve("override") } } - const rejectThrow = async () => { try { await Promise.reject("early") } finally { throw "override" } } - const rejectReject = async () => { try { await Promise.reject("early") } finally { await Promise.reject("override") } } - return await Promise.all([ - observe(returnReturn()), observe(returnThrow()), observe(returnReject()), - observe(throwReturn()), observe(throwThrow()), observe(throwReject()), - observe(rejectReturn()), observe(rejectThrow()), observe(rejectReject()), - ]) - `), - ).toEqual([ - ["fulfilled", "override"], - ["rejected", "override"], - ["rejected", "override"], - ["fulfilled", "override"], - ["rejected", "override"], - ["rejected", "override"], - ["fulfilled", "override"], - ["rejected", "override"], - ["rejected", "override"], - ]) - }) - - test("await preserves an object whose then property is not callable", async () => { - // Source: test/language/expressions/await/await-awaits-thenable-not-callable.js - expect( - await value(` - const thenable = { then: 42 } - return (await thenable) === thenable - `), - ).toBe(true) - }) - - test("await returns non-promise operands unchanged", async () => { - // Source: test/language/expressions/await/await-non-promise.js - // (adapted: only value pass-through is asserted here; the spec tick ordering around - // await of non-promises is covered by the failing interleaving test below) - expect( - await value(` - const object = { id: 1 } - const array = [1, 2] - return [ - await 1, - await "text", - await true, - (await null) === null, - (await undefined) === undefined, - (await object) === object, - (await array) === array, - ] - `), - ).toEqual([1, "text", true, true, true, true, true]) - }) -}) - -describe("Test262 expected Promise conformance", () => { - for (const name of ["all", "allSettled", "race", "any"] as const) { - test(`Promise.${name} rejects invalid input with TypeError`, async () => { - // Sources: - // test/built-ins/Promise/all/S25.4.4.1_A3.1_T1.js - // test/built-ins/Promise/all/S25.4.4.1_A3.1_T2.js - // test/built-ins/Promise/allSettled/iter-arg-is-number-reject.js - // test/built-ins/Promise/race/iter-arg-is-number-reject.js - // test/built-ins/Promise/any/iter-arg-is-number-reject.js - expect( - await value(` - try { - const promise = Promise.${name}(42) - const returned = promise instanceof Promise - await promise - return [returned, "fulfilled"] - } catch (error) { - return [true, error.name] - } - `), - ).toEqual([true, "TypeError"]) - }) - } - - test("Promise.all consumes sparse positions as undefined", async () => { - // Source: test/built-ins/Array/from/from-array.js (array iterator hole behavior) - expect( - await value(` - const input = [] - input[1] = 1 - const result = await Promise.all(input) - return [result.length, result[0] === undefined, result[1]] - `), - ).toEqual([2, true, 1]) - }) - - test("Promise.allSettled consumes sparse positions as undefined", async () => { - // Source: test/built-ins/Array/from/from-array.js (array iterator hole behavior) - expect( - await value(` - const input = [] - input[1] = 1 - const result = await Promise.allSettled(input) - return [result.length, result[0].status, result[0].value === undefined, result[1]] - `), - ).toEqual([2, "fulfilled", true, { status: "fulfilled", value: 1 }]) - }) - - test("Promise.race consumes a sparse first position as undefined", async () => { - // Source: test/built-ins/Array/from/from-array.js (array iterator hole behavior) - expect( - await value(` - const input = [] - input[1] = 1 - return (await Promise.race(input)) === undefined - `), - ).toBe(true) - }) - - test("Promise.any consumes a sparse first position as an undefined fulfillment", async () => { - // Source: test/built-ins/Array/from/from-array.js (array iterator hole behavior) - expect( - await value(` - const input = [] - input[1] = Promise.reject("loses") - return (await Promise.any(input)) === undefined - `), - ).toBe(true) - }) - - test("Promise.all settles after reactions attached to its inputs", async () => { - // Sources: - // test/built-ins/Promise/all/S25.4.4.1_A7.2_T1.js - // test/built-ins/Promise/all/S25.4.4.1_A8.1_T1.js - expect( - await value(` - const sequence = [1] - const input = Promise.resolve(1) - const aggregate = Promise.all([input]) - aggregate.then(() => sequence.push(4)) - input.then(() => sequence.push(3)).then(() => sequence.push(5)) - sequence.push(2) - await aggregate - await Promise.resolve() - return sequence - `), - ).toEqual([1, 2, 3, 4, 5]) - }) - - test("Promise.allSettled settles after reactions attached to its inputs", async () => { - // Sources: - // test/built-ins/Promise/allSettled/resolved-sequence.js - // test/built-ins/Promise/allSettled/resolved-sequence-extra-ticks.js - // test/built-ins/Promise/allSettled/resolved-sequence-mixed.js - // test/built-ins/Promise/allSettled/resolved-sequence-with-rejections.js - expect( - await value(` - const sequence = [1] - const input = Promise.resolve(1) - const aggregate = Promise.allSettled([input]) - aggregate.then(() => sequence.push(4)) - input.then(() => sequence.push(3)).then(() => sequence.push(5)) - sequence.push(2) - await aggregate - await Promise.resolve() - return sequence - `), - ).toEqual([1, 2, 3, 4, 5]) - }) - - test("Promise.race settles in a reaction after its winning input", async () => { - // Sources: - // test/built-ins/Promise/race/S25.4.4.3_A6.1_T1.js - // test/built-ins/Promise/race/resolved-sequence-extra-ticks.js - expect( - await value(` - const sequence = [1] - const race = Promise.race([1]) - race.then(() => sequence.push(4)) - Promise.resolve().then(() => sequence.push(3)).then(() => sequence.push(5)) - sequence.push(2) - await race - await Promise.resolve() - return sequence - `), - ).toEqual([1, 2, 3, 4, 5]) - }) - - test("then reactions route and propagate fulfillment and rejection", async () => { - // Sources: - // test/built-ins/Promise/prototype/then/prfm-fulfilled.js - // test/built-ins/Promise/prototype/then/prfm-rejected.js - // test/built-ins/Promise/prototype/then/rxn-handler-identity.js - // test/built-ins/Promise/prototype/then/rxn-handler-thrower.js - // test/built-ins/Promise/prototype/then/rxn-handler-fulfilled-return-normal.js - // test/built-ins/Promise/prototype/then/rxn-handler-fulfilled-return-abrupt.js - // test/built-ins/Promise/prototype/then/rxn-handler-rejected-return-normal.js - // test/built-ins/Promise/prototype/then/rxn-handler-rejected-return-abrupt.js - expect( - await value(` - const observe = async (promise) => { - try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] } - } - return await Promise.all([ - observe(Promise.resolve(1).then((value) => value + 1)), - observe(Promise.reject(2).then(undefined, (reason) => reason + 1)), - observe(Promise.resolve(3).then(undefined)), - observe(Promise.reject(4).then(undefined)), - observe(Promise.resolve(5).then(() => { throw 6 })), - observe(Promise.reject(7).then(undefined, () => { throw 8 })), - ]) - `), - ).toEqual([ - ["fulfilled", 2], - ["fulfilled", 3], - ["fulfilled", 3], - ["rejected", 4], - ["rejected", 6], - ["rejected", 8], - ]) - }) - - test("then reactions preserve breadth-first queue order", async () => { - // Source: test/built-ins/Promise/prototype/then/S25.4.4_A1.1_T1.js - expect( - await value(` - const sequence = [1] - const promise = Promise.resolve() - const first = promise.then(() => sequence.push(3)).then(() => sequence.push(5)).then(() => sequence.push(7)) - const second = promise.then(() => sequence.push(4)).then(() => sequence.push(6)).then(() => sequence.push(8)) - sequence.push(2) - await Promise.all([first, second]) - return sequence - `), - ).toEqual([1, 2, 3, 4, 5, 6, 7, 8]) - }) - - test("then rejects direct self-resolution for fulfilled and rejected sources", async () => { - // Sources: - // test/built-ins/Promise/prototype/then/resolve-settled-fulfilled-self.js - // test/built-ins/Promise/prototype/then/resolve-settled-rejected-self.js - // test/built-ins/Promise/prototype/then/resolve-pending-fulfilled-self.js - // test/built-ins/Promise/prototype/then/resolve-pending-rejected-self.js - expect( - await value(` - const observe = async (promise) => { - try { await promise; return "fulfilled" } catch (reason) { return reason.name } - } - let fulfilled - let rejected - fulfilled = Promise.resolve().then(() => fulfilled) - rejected = Promise.reject().then(undefined, () => rejected) - return await Promise.all([observe(fulfilled), observe(rejected)]) - `), - ).toEqual(["TypeError", "TypeError"]) - }) - - test("catch delegates rejection handling and preserves fulfillment", async () => { - // Sources: - // test/built-ins/Promise/prototype/catch/S25.4.5.1_A2.1_T1.js - // test/built-ins/Promise/prototype/catch/S25.4.5.1_A3.1_T1.js - // test/built-ins/Promise/prototype/catch/S25.4.5.1_A3.1_T2.js - expect( - await value(` - return [ - await Promise.resolve(1).catch(() => 2), - await Promise.reject(3).catch((reason) => reason + 1), - ] - `), - ).toEqual([1, 4]) - }) - - test("finally preserves or replaces the original settlement", async () => { - // Sources: - // test/built-ins/Promise/prototype/finally/resolution-value-no-override.js - // test/built-ins/Promise/prototype/finally/rejection-reason-no-fulfill.js - // test/built-ins/Promise/prototype/finally/rejection-reason-override-with-throw.js - expect( - await value(` - const observe = async (promise) => { - try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] } - } - return await Promise.all([ - observe(Promise.resolve(1).finally(() => 2)), - observe(Promise.reject(3).finally(() => 4)), - observe(Promise.reject(5).finally(() => { throw 6 })), - ]) - `), - ).toEqual([ - ["fulfilled", 1], - ["rejected", 3], - ["rejected", 6], - ]) - }) - - test("then ignores non-callable handlers", async () => { - // Sources: - // test/built-ins/Promise/prototype/then/S25.4.5.3_A4.1_T1.js - // test/built-ins/Promise/prototype/then/S25.4.5.3_A4.1_T2.js - // test/built-ins/Promise/prototype/then/S25.4.5.3_A5.1_T1.js - // test/built-ins/Promise/prototype/then/S25.4.5.3_A5.2_T1.js - // (adapted: only non-callable handlers are probed; callables that are not plain - // functions, such as tool references, intentionally throw in CodeMode) - expect( - await value(` - const observe = async (promise) => { - try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] } - } - return await Promise.all([ - observe(Promise.resolve(1).then(2)), - observe(Promise.resolve(4).then(null, null)), - observe(Promise.resolve(5).then({}, "x")), - observe(Promise.reject(3).then(null, "x")), - observe(Promise.reject(6).then(7, {})), - ]) - `), - ).toEqual([ - ["fulfilled", 1], - ["fulfilled", 4], - ["fulfilled", 5], - ["rejected", 3], - ["rejected", 6], - ]) - }) - - test("finally waits for a returned promise and preserves or replaces settlement", async () => { - // Sources: - // test/built-ins/Promise/prototype/finally/resolved-observable-then-calls.js - // test/built-ins/Promise/prototype/finally/rejected-observable-then-calls.js - // test/built-ins/Promise/prototype/finally/resolution-value-no-override.js - expect( - await value(` - const observe = async (promise) => { - try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] } - } - const order = [] - const cleanup = async () => { - await Promise.resolve() - order.push("cleanup") - } - const settled = await Promise.resolve("kept").finally(() => cleanup()) - order.push("settled:" + settled) - return [ - await observe(Promise.resolve(1).finally(() => Promise.resolve(99))), - order, - await observe(Promise.resolve(2).finally(() => Promise.reject(3))), - await observe(Promise.reject(4).finally(() => Promise.resolve(99))), - ] - `), - ).toEqual([ - ["fulfilled", 1], - ["cleanup", "settled:kept"], - ["rejected", 3], - ["rejected", 4], - ]) - }) - - test("then adopts a returned rejected promise", async () => { - // Sources: - // test/built-ins/Promise/prototype/then/rxn-handler-fulfilled-return-abrupt.js - // test/built-ins/Promise/resolve/resolve-promise.js - // (adapted: the fulfillment handler returns an already-rejected promise instead of - // throwing, and the rejection handler recovers with a fulfilled promise) - expect( - await value(` - const observe = async (promise) => { - try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] } - } - return await Promise.all([ - observe(Promise.resolve(1).then(() => Promise.reject("bad"))), - observe(Promise.reject(2).then(undefined, () => Promise.resolve("ok"))), - ]) - `), - ).toEqual([ - ["rejected", "bad"], - ["fulfilled", "ok"], - ]) - }) - - test("independent reactions on one source each observe the same settlement", async () => { - // Source: test/built-ins/Promise/prototype/then/S25.4.4_A2.1_T1.js - // (adapted: the multiple-reactions family is asserted through the values every - // reaction returns instead of a shared completion counter) - expect( - await value(` - const fulfilled = Promise.resolve(7) - const rejected = Promise.reject(8) - return await Promise.all([ - fulfilled.then((value) => "first:" + value), - fulfilled.then((value) => "second:" + value), - rejected.catch((reason) => "first:" + reason), - rejected.catch((reason) => "second:" + reason), - ]) - `), - ).toEqual(["first:7", "second:7", "first:8", "second:8"]) - }) - - test("await always resumes in a later reaction and interleaves async functions", async () => { - // Sources: - // test/language/expressions/await/async-await-interleaved.js - // test/language/expressions/await/await-non-promise.js - expect( - await value(` - const sequence = [] - const first = async () => { sequence.push("first:1"); await 0; sequence.push("first:2") } - const second = async () => { sequence.push("second:1"); await 0; sequence.push("second:2") } - await Promise.all([first(), second()]) - return sequence - `), - ).toEqual(["first:1", "second:1", "first:2", "second:2"]) - }) - - test("an async function rejects when it resolves with its own promise", async () => { - // Adapted from the self-resolution requirement represented by: - // test/built-ins/Promise/resolve-self.js - // test/built-ins/Promise/resolve/S25.4.4.5_A4.1_T1.js - expect( - await value(` - let promise - const run = async () => { - await Promise.resolve() - return promise - } - promise = run() - try { - await promise - return "fulfilled" - } catch (error) { - return error.name - } - `), - ).toBe("TypeError") - }) - - test("Promise.resolve recursively assimilates callable thenables", async () => { - // Source: test/built-ins/Promise/resolve/resolve-thenable.js - expect( - await value(` - const value = { id: 1 } - const nested = { then: (resolve) => resolve(value) } - const thenable = { then: (resolve) => resolve(nested) } - return (await Promise.resolve(thenable)) === value - `), - ).toBe(true) - }) - - test("Promise combinators assimilate callable thenable inputs", async () => { - // Sources: - // test/built-ins/Promise/all/reject-immed.js - // test/built-ins/Promise/all/reject-ignored-immed.js - // test/built-ins/Promise/allSettled/reject-ignored-immed.js - // test/built-ins/Promise/race/resolve-thenable.js - expect( - await value(` - const fulfills = { then: (resolve) => resolve(1) } - const rejects = { then: (_, reject) => reject(2) } - const resolvesFirst = { then: (resolve, reject) => { resolve(3); reject(4) } } - const observe = async (promise) => { - try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason] } - } - return [ - await observe(Promise.all([fulfills, rejects])), - await Promise.allSettled([fulfills, resolvesFirst]), - await observe(Promise.race([rejects])), - ] - `), - ).toEqual([ - ["rejected", 2], - [ - { status: "fulfilled", value: 1 }, - { status: "fulfilled", value: 3 }, - ], - ["rejected", 2], - ]) - }) - - test("await assimilates callable thenables", async () => { - // Source: test/language/expressions/await/await-awaits-thenables.js - expect( - await value(` - const thenable = { then: (resolve) => resolve(42) } - return await thenable - `), - ).toBe(42) - }) - - test("await rejects when a callable thenable throws", async () => { - // Source: test/language/expressions/await/await-awaits-thenables-that-throw.js - expect( - await value(` - const error = { id: 1 } - const thenable = { then: () => { throw error } } - try { - await thenable - return false - } catch (caught) { - return caught === error - } - `), - ).toBe(true) - }) - - test("thenable resolution is deferred and settles only once", async () => { - // Sources: - // test/built-ins/Promise/resolve/S25.Promise_resolve_foreign_thenable_2.js - // test/built-ins/Promise/exception-after-resolve-in-thenable-job.js - expect( - await value(` - const sequence = [] - const thenable = { - then: (resolve, reject) => { - sequence.push("then") - resolve(1) - reject(2) - throw 3 - } - } - const promise = Promise.resolve(thenable) - sequence.push("after resolve") - const result = await promise - sequence.push("after await") - return [result, sequence] - `), - ).toEqual([1, ["after resolve", "then", "after await"]]) - }) - - test("the first thenable rejection wins over later resolution and throws", async () => { - // Source: test/built-ins/Promise/exception-after-resolve-in-thenable-job.js - expect( - await value(` - const thenable = { - then: (resolve, reject) => { - reject("first") - resolve("second") - throw "third" - } - } - try { - await thenable - return "fulfilled" - } catch (reason) { - return reason - } - `), - ).toBe("first") - }) - - test("constructors, reactions, finally, and async returns assimilate thenables", async () => { - // Sources: - // test/built-ins/Promise/resolve-thenable-immed.js - // test/built-ins/Promise/prototype/then/resolve-settled-fulfilled-thenable.js - // test/built-ins/Promise/prototype/finally/resolved-observable-then-calls.js - const thenable = (value: string) => `({ then: (resolve) => resolve(${JSON.stringify(value)}) })` - expect( - await value(` - const fromAsync = async () => ${thenable("async")} - const cleanup = [] - return await Promise.all([ - new Promise((resolve) => resolve(${thenable("constructor")})), - Promise.resolve().then(() => ${thenable("reaction")}), - Promise.resolve("kept").finally(() => { - cleanup.push("ran") - return ${thenable("ignored")} - }), - fromAsync(), - ]).then((values) => [values, cleanup]) - `), - ).toEqual([["constructor", "reaction", "kept", "async"], ["ran"]]) - }) - - test("finally settles after its cleanup thenable reactions", async () => { - // Source: test/built-ins/Promise/prototype/finally/resolved-observable-then-calls-PromiseResolve.js - expect( - await value(` - const sequence = [] - const cleanup = { then: (resolve) => { sequence.push("then"); resolve() } } - const result = Promise.resolve("kept").finally(() => cleanup) - result.then(() => sequence.push("finally")) - Promise.resolve() - .then(() => sequence.push("tick1")) - .then(() => sequence.push("tick2")) - .then(() => sequence.push("tick3")) - .then(() => sequence.push("tick4")) - await result - sequence.push("await") - return sequence - `), - ).toEqual(["tick1", "then", "tick2", "tick3", "tick4", "finally", "await"]) - }) -}) - -describe("Test262 Promise.any", () => { - test("is a callable static that returns a promise", async () => { - // Sources: - // test/built-ins/Promise/any/is-function.js - // test/built-ins/Promise/any/returns-promise.js - expect( - await value(` - const promise = Promise.any([1]) - return [typeof Promise.any, promise instanceof Promise, await promise] - `), - ).toEqual(["function", true, 1]) - }) - - test("fulfills with the first fulfilled member, ignoring rejections", async () => { - // Sources: - // test/built-ins/Promise/any/resolved-sequence-mixed.js - // test/built-ins/Promise/any/resolved-sequence-with-rejections.js - // test/built-ins/Promise/any/reject-ignored-immed.js - expect( - await value(` - return [ - await Promise.any([Promise.reject("a"), Promise.resolve(1), Promise.resolve(2)]), - await Promise.any([Promise.reject("a"), "plain", Promise.reject("b")]), - ] - `), - ).toEqual([1, "plain"]) - }) - - test("a fulfillment wins over a later rejection of another member", async () => { - // Sources: - // test/built-ins/Promise/any/resolve-ignores-late-rejection.js - // test/built-ins/Promise/any/resolve-ignores-late-rejection-deferred.js - expect( - await value(` - let rejectLate - const late = new Promise((_, reject) => { rejectLate = reject }) - const result = await Promise.any([late, Promise.resolve("won")]) - rejectLate("too late") - return result - `), - ).toBe("won") - }) - - test("rejects with an AggregateError carrying the reasons in input order", async () => { - // Sources: - // test/built-ins/Promise/any/reject-all-mixed.js - // test/built-ins/Promise/any/reject-immed.js - // test/built-ins/Promise/any/reject-deferred.js - expect( - await value(` - let rejectLate - const late = new Promise((_, reject) => { rejectLate = reject }) - const aggregate = Promise.any([Promise.reject("first"), late, Promise.reject("third")]) - rejectLate("second") - try { - await aggregate - return "fulfilled" - } catch (error) { - return { - isAggregate: error instanceof AggregateError, - isError: error instanceof Error, - name: error.name, - message: error.message, - errors: error.errors, - } - } - `), - ).toEqual({ - isAggregate: true, - isError: true, - name: "AggregateError", - message: "All promises were rejected", - errors: ["first", "second", "third"], - }) - }) - - test("rejects an empty input with an empty AggregateError", async () => { - // Source: test/built-ins/Promise/any/iter-arg-is-empty-iterable-reject.js - expect( - await value(` - try { - await Promise.any([]) - return "fulfilled" - } catch (error) { - return [error instanceof AggregateError, error.errors.length] - } - `), - ).toEqual([true, 0]) - }) - - test("consumes a string input as its characters", async () => { - // Source: test/built-ins/Promise/any/iter-arg-is-string-resolve.js - expect(await value(`return await Promise.any("abc")`)).toBe("a") - }) - - test("rejects an empty string input with an empty AggregateError", async () => { - // Source: test/built-ins/Promise/any/iter-arg-is-empty-string-reject.js - expect( - await value(` - try { - await Promise.any("") - return "fulfilled" - } catch (error) { - return [error instanceof AggregateError, error.errors.length] - } - `), - ).toEqual([true, 0]) - }) - - test("fulfills with the first member that does not reject", async () => { - // Sources: - // test/built-ins/Promise/any/resolve-from-reject-catch.js - // test/built-ins/Promise/any/resolve-from-resolve-reject-catch.js - expect( - await value(` - return await Promise.any([ - Promise.reject("a"), - new Promise((resolve, reject) => reject("b")), - Promise.all([Promise.reject("c")]), - Promise.resolve(Promise.reject("d").catch((reason) => reason)), - ]) - `), - ).toBe("d") - }) - - test("settles after reactions attached to its inputs", async () => { - // Source: test/built-ins/Promise/any/resolved-sequence.js - expect( - await value(` - const sequence = [1] - const input = Promise.resolve(1) - const aggregate = Promise.any([input]) - aggregate.then(() => sequence.push(4)) - input.then(() => sequence.push(3)).then(() => sequence.push(5)) - sequence.push(2) - await aggregate - await Promise.resolve() - return sequence - `), - ).toEqual([1, 2, 3, 4, 5]) - }) -}) - -describe("Test262 AggregateError", () => { - test("constructs from an errors collection and an optional message", async () => { - // Sources: - // test/built-ins/AggregateError/errors-iterabletolist.js - // test/built-ins/AggregateError/message-undefined-no-prop.js - expect( - await value(` - const input = ["x", "y"] - const withMessage = new AggregateError(input, "msg") - const bare = new AggregateError([]) - return [ - withMessage.name, - withMessage.message, - withMessage.errors, - withMessage.errors !== input, - withMessage instanceof AggregateError, - withMessage instanceof Error, - bare.message, - bare.errors, - ] - `), - ).toEqual(["AggregateError", "msg", ["x", "y"], true, true, true, "", []]) - }) - - test("rejects a non-collection errors argument with TypeError", async () => { - // Source: test/built-ins/AggregateError/errors-iterabletolist-failures.js - expect( - await value(` - try { - new AggregateError(42) - return "constructed" - } catch (error) { - return error.name - } - `), - ).toBe("TypeError") - }) - - test("is callable without new", async () => { - // Source: test/built-ins/AggregateError/newtarget-is-undefined.js - expect( - await value(` - const error = AggregateError(["x"], "m") - return [error instanceof AggregateError, error instanceof Error, error.name, error.message, error.errors] - `), - ).toEqual([true, true, "AggregateError", "m", ["x"]]) - }) - - test("coerces a non-string message to a string", async () => { - // Source: test/built-ins/AggregateError/message-method-prop-cast.js (value coercion only; the - // upstream object-with-toString case is omitted because CodeMode has no user toString dispatch) - expect( - await value(` - return [ - new AggregateError([], 42).message, - new AggregateError([], false).message, - new AggregateError([], true).message, - new AggregateError([], null).message, - ] - `), - ).toEqual(["42", "false", "true", "null"]) - }) -}) - -describe("Test262 Promise constructor", () => { - test("constructs a promise, handing the executor callable resolve/reject", async () => { - // Sources: - // test/built-ins/Promise/constructor.js - // test/built-ins/Promise/exec-args.js - expect( - await value(` - let observed - const promise = new Promise((resolve, reject) => { - observed = [typeof resolve, typeof reject] - resolve("done") - }) - return [promise instanceof Promise, observed, await promise] - `), - ).toEqual([true, ["function", "function"], "done"]) - }) - - test("a missing or non-callable executor is a TypeError", async () => { - // Source: test/built-ins/Promise/executor-not-callable.js - expect( - await value(` - const outcomes = [] - for (const make of [() => new Promise(), () => new Promise(1), () => new Promise({})]) { - try { - make() - outcomes.push("constructed") - } catch (error) { - outcomes.push(error.name) - } - } - return outcomes - `), - ).toEqual(["TypeError", "TypeError", "TypeError"]) - }) - - test("resolves immediately or later through an escaping resolver", async () => { - // Sources: - // test/built-ins/Promise/resolve-non-thenable-immed.js - // test/built-ins/Promise/resolve-non-thenable-deferred.js - // test/built-ins/Promise/create-resolving-functions-resolve.js - expect( - await value(` - let settle - const deferred = new Promise((resolve) => { settle = resolve }) - const immediate = new Promise((resolve) => resolve("now")) - settle("later") - return [await immediate, await deferred] - `), - ).toEqual(["now", "later"]) - }) - - test("rejects through reject and through an abrupt executor completion", async () => { - // Sources: - // test/built-ins/Promise/reject-via-fn-immed.js - // test/built-ins/Promise/reject-via-abrupt.js - expect( - await value(` - const observe = async (promise) => { - try { return ["fulfilled", await promise] } catch (reason) { return ["rejected", reason.message ?? reason] } - } - return [ - await observe(new Promise((_, reject) => reject("nope"))), - await observe(new Promise(() => { throw new Error("boom") })), - ] - `), - ).toEqual([ - ["rejected", "nope"], - ["rejected", "boom"], - ]) - }) - - test("only the first settlement counts", async () => { - // Sources: - // test/built-ins/Promise/reject-ignored-via-fn-immed.js - // test/built-ins/Promise/resolve-ignored-via-fn-immed.js - expect( - await value(` - return [ - await new Promise((resolve, reject) => { resolve("first"); reject("second"); resolve("third") }), - await new Promise((resolve) => { resolve(resolve("inner") === undefined ? "unreached" : "also unreached") }), - ] - `), - ).toEqual(["first", "inner"]) - }) - - test("escaped resolvers keep first-settle-wins in both directions", async () => { - // Sources: - // test/built-ins/Promise/reject-ignored-via-fn-deferred.js - // test/built-ins/Promise/resolve-ignored-via-fn-deferred.js - expect( - await value(` - let resolveRejected, rejectRejected - const rejected = new Promise((resolve, reject) => { resolveRejected = resolve; rejectRejected = reject }) - rejectRejected("first") - const lateResolve = resolveRejected("late") - let resolveFulfilled, rejectFulfilled - const fulfilled = new Promise((resolve, reject) => { resolveFulfilled = resolve; rejectFulfilled = reject }) - resolveFulfilled() - const lateReject = rejectFulfilled(new Promise(() => {})) - try { - await rejected - return "fulfilled" - } catch (reason) { - return [reason, lateResolve === undefined, (await fulfilled) === undefined, lateReject === undefined] - } - `), - ).toEqual(["first", true, true, true]) - }) - - test("a queued reaction chain observes a later rejection through a handler-less then", async () => { - // Sources: - // test/built-ins/Promise/reject-via-fn-immed-queue.js - // test/built-ins/Promise/reject-via-fn-deferred-queue.js - // test/built-ins/Promise/reject-via-abrupt-queue.js - expect( - await value(` - const observe = (promise) => promise.then(() => "wrong").then(() => "also wrong", (reason) => "caught:" + reason) - let reject - const deferred = new Promise((_, r) => { reject = r }) - const chained = observe(deferred) - reject("boom") - return [ - await observe(new Promise((_, r) => r("immed"))), - await chained, - await observe(new Promise(() => { throw "abrupt" })), - ] - `), - ).toEqual(["caught:immed", "caught:boom", "caught:abrupt"]) - }) - - test("an exception after resolve is ignored", async () => { - // Source: test/built-ins/Promise/exception-after-resolve-in-executor.js - expect(await value(`return await new Promise((resolve) => { resolve("kept"); throw new Error("dropped") })`)).toBe( - "kept", - ) - }) - - test("resolving with a promise adopts its settlement", async () => { - // Sources: - // test/built-ins/Promise/resolve-thenable-immed.js (promise-adoption portion) - // test/built-ins/Promise/all/S25.4.4.1_A2.3_T1.js (resolution adoption semantics) - expect( - await value(` - const adoptedValue = await new Promise((resolve) => resolve(Promise.resolve("adopted"))) - try { - await new Promise((resolve) => resolve(Promise.reject("bad"))) - return [adoptedValue, "fulfilled"] - } catch (reason) { - return [adoptedValue, reason] - } - `), - ).toEqual(["adopted", "bad"]) - }) - - test("resolving with the promise itself rejects with TypeError", async () => { - // Source: test/built-ins/Promise/resolve-self.js - expect( - await value(` - let settle - const promise = new Promise((resolve) => { settle = resolve }) - settle(promise) - try { - await promise - return "fulfilled" - } catch (error) { - return error.name - } - `), - ).toBe("TypeError") - }) - - test("executor runs synchronously before the constructor returns", async () => { - // Source: test/built-ins/Promise/executor-call-context-strict.js (synchronous Call(executor) step) - expect( - await value(` - const sequence = [] - sequence.push("before") - new Promise((resolve) => { sequence.push("executor"); resolve() }) - sequence.push("after") - return sequence - `), - ).toEqual(["before", "executor", "after"]) - }) - - test("calling Promise without new throws TypeError", async () => { - // Source: test/built-ins/Promise/undefined-newtarget.js - expect( - await value(` - try { - Promise(() => {}) - return "called" - } catch (error) { - return error.name - } - `), - ).toBe("TypeError") - }) -}) diff --git a/packages/codemode/test/promise.test.ts b/packages/codemode/test/promise.test.ts index f0a1740edb6..7e48b24168b 100644 --- a/packages/codemode/test/promise.test.ts +++ b/packages/codemode/test/promise.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test" -import { Cause, Deferred, Effect, Exit, Schema } from "effect" +import { Deferred, Effect, Schema } from "effect" import { CodeMode, Tool, toolError } from "../src/index.js" // Wave 5 acceptance suite: first-class promise values. Un-awaited tool calls start eagerly as @@ -168,12 +168,6 @@ const run = ( ) } -const value = async (code: string, options: { trace?: Trace; limits?: CodeMode.ExecutionLimits } = {}) => { - const result = await run(code, options) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - const error = async (code: string, options: { trace?: Trace; limits?: CodeMode.ExecutionLimits } = {}) => { const result = await run(code, options) if (result.ok) throw new Error(`expected failure, got value ${JSON.stringify(result.value)}`) @@ -181,62 +175,6 @@ const error = async (code: string, options: { trace?: Trace; limits?: CodeMode.E } describe("first-class promise values", () => { - test("async functions return promises with isolated concurrent invocations", async () => { - expect( - await value(` - const load = async (id) => { - const result = await tools.host.echo({ id }) - return [id, result] - } - const first = load(1) - const second = load(2) - return [first instanceof Promise, second instanceof Promise, await Promise.all([first, second])] - `), - ).toEqual([ - true, - true, - [ - [1, 1], - [2, 2], - ], - ]) - }) - - test("async function errors reject instead of throwing at the call site", async () => { - expect( - await value(` - const fail = async () => { throw new Error("boom") } - const promise = fail() - try { - await promise - return "no" - } catch (error) { - return error.message - } - `), - ).toBe("boom") - }) - - test("an un-awaited tool call starts eagerly, in call order, before any await", async () => { - const trace = makeTrace() - const result = await value( - ` - const a = tools.host.gated({ id: 1 }) - const b = tools.host.gated({ id: 2 }) - await tools.host.open({ id: 1 }) - await tools.host.open({ id: 2 }) - const rb = await b - const ra = await a - return [ra, rb] - `, - { trace }, - ) - expect(result).toEqual([1, 2]) - expect(trace.starts).toEqual([1, 2]) - // Both calls overlapped even though they were awaited sequentially. - expect(trace.maxActive).toBeGreaterThan(1) - }) - test("awaiting the same promise twice settles once and never re-runs the call", async () => { const result = await run(` const p = tools.host.echo({ id: 7 }) @@ -250,62 +188,6 @@ describe("first-class promise values", () => { expect(result.toolCalls).toStrictEqual([{ name: "host.echo" }]) }) - test("await of a non-promise value passes it through unchanged", async () => { - expect(await value(`return await 42`)).toBe(42) - expect(await value(`const x = await "s"; return x`)).toBe("s") - expect(await value(`return await null`)).toBeNull() - expect(await value(`return (await [1, 2]).length`)).toBe(2) - }) - - test("returning an un-awaited tool call resolves it (async-function return semantics)", async () => { - expect(await value(`return tools.host.echo({ id: 9 })`)).toBe(9) - }) - - test("typeof a promise is 'object', and console.log renders it sensibly", async () => { - const result = await run(` - const p = Promise.resolve(1) - console.log(p) - return typeof p - `) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.value).toBe("object") - expect(result.logs).toStrictEqual(["[Promise (await it to get its value)]"]) - }) - - test("an awaited failure is catchable exactly like a synchronous throw", async () => { - const result = await run(` - const p = tools.host.fail({}) - try { - await p - return "no" - } catch (e) { - return e.message - } - `) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.value).toBe("Lookup refused") - expect(result.warnings).toBeUndefined() - }) - - test("a fire-and-forget call is interrupted when the program returns", async () => { - const trace = makeTrace() - const result = await run( - ` - tools.host.pending({ id: 1 }) - return "done" - `, - { trace }, - ) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.value).toBe("done") - expect(result.warnings).toBeUndefined() - expect(trace.completed).toBe(0) - expect(trace.interrupted).toBe(1) - }) - test("a never-awaited failing call preserves the result and reports the rejection", async () => { const result = await run(` tools.host.fail({}) @@ -319,247 +201,9 @@ describe("first-class promise values", () => { ]) expect(Schema.decodeUnknownSync(CodeMode.Result)(JSON.parse(JSON.stringify(result)))).toStrictEqual(result) }) - - test("a never-awaited failing async function is reported with a successful result", async () => { - const result = await run(` - const fail = async () => { throw new Error("boom") } - fail() - return "done" - `) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.value).toBe("done") - expect(result.warnings).toStrictEqual([ - { kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Error: boom" }, - ]) - }) - - test("output truncation bounds warning diagnostics with an in-band marker", async () => { - const result = await run( - ` - for (let i = 0; i < 100; i += 1) Promise.reject(new Error("x".repeat(1_000))) - return "done" - `, - { limits: { maxOutputBytes: 64 } }, - ) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.truncated).toBe(true) - expect(result.warnings).toStrictEqual([ - { kind: "Truncated", message: "100 additional warnings omitted by the output limit." }, - ]) - }) - - test("a budget-consuming value does not starve warnings", async () => { - const result = await run( - ` - Promise.reject(new Error("boom")) - return "x".repeat(500) - `, - { limits: { maxOutputBytes: 128 } }, - ) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.truncated).toBe(true) - expect(typeof result.value).toBe("string") - expect(result.warnings).toStrictEqual([ - { kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Error: boom" }, - ]) - }) - - test("an un-awaited async function's pending chain is interrupted at the return", async () => { - const trace = makeTrace() - const result = await run( - ` - const run = async () => { - await tools.host.pending({ id: 1 }) - tools.host.fail({}) - } - run() - return "done" - `, - { trace }, - ) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.value).toBe("done") - expect(result.warnings).toBeUndefined() - expect(trace.starts).toEqual([1]) - expect(trace.completed).toBe(0) - expect(trace.interrupted).toBe(1) - }) - - test("reports every unhandled rejection in promise creation order", async () => { - const result = await run(` - Promise.reject(new Error("first")) - tools.host.fail({}) - Promise.reject(new Error("third")) - return "done" - `) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.warnings).toStrictEqual([ - { kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Error: first" }, - { kind: "ToolFailure", message: "Unhandled rejection from an un-awaited promise: Lookup refused" }, - { kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Error: third" }, - ]) - }) - - test("orders an async function rejection before promises created inside its body", async () => { - const result = await run(` - const outer = async () => { - Promise.reject(new Error("inner")) - throw new Error("outer") - } - outer() - return "done" - `) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.warnings).toStrictEqual([ - { kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Error: outer" }, - { kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Error: inner" }, - ]) - }) - - test("un-awaited interruptions settle without becoming rejections", async () => { - const result = await run(` - tools.host.interrupt({}) - Promise.all([tools.host.interrupt({})]) - return "done" - `) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.value).toBe("done") - expect(result.warnings).toBeUndefined() - }) - - test("a fatal program error cancels outstanding work without reporting unhandled rejections", async () => { - const trace = makeTrace() - const result = await run( - ` - tools.host.pending({ id: 1 }) - throw new Error("boom") - `, - { trace }, - ) - expect(result.ok).toBe(false) - if (result.ok) return - expect(result.error.message).toBe("Error: boom") - expect("warnings" in result).toBe(false) - expect(trace.completed).toBe(0) - expect(trace.interrupted).toBe(1) - }) - - test("async-function promises remain owned by the execution after the function returns", async () => { - const trace = makeTrace() - expect( - await value( - ` - const launch = async () => { - tools.host.pending({ id: 1 }) - Promise.all([tools.host.pending({ id: 2 })]) - return "returned" - } - return await launch() - `, - { trace }, - ), - ).toBe("returned") - // Both calls outlive launch() itself - they belong to the execution, not the function - - // and are interrupted only when the whole program returns. - expect(trace.starts).toEqual([1, 2]) - expect(trace.completed).toBe(0) - expect(trace.interrupted).toBe(2) - }) -}) - -describe("promises at data boundaries", () => { - test("an un-awaited promise inside a result or a tool argument is awaited", async () => { - expect(await value(`return { result: tools.host.echo({ id: 1 }) }`)).toEqual({ result: 1 }) - expect(await value(`return Array.from([Promise.resolve(1)])`)).toEqual([1]) - expect(await value(`return await tools.host.echo({ id: tools.host.echo({ id: 1 }) })`)).toBe(1) - }) - - test("a rejected promise inside a result fails the program with its reason", async () => { - const diagnostic = await error(`return { result: tools.host.fail({}) }`) - expect(diagnostic.kind).toBe("ToolFailure") - expect(diagnostic.message).toContain("Lookup refused") - }) - - test("JSON.stringify of a promise is a diagnostic, not '{}'", async () => { - const diagnostic = await error(`return JSON.stringify(Promise.resolve(1))`) - expect(diagnostic.kind).toBe("InvalidDataValue") - expect(diagnostic.message).toContain("un-awaited Promise") - }) - - test("returning a never-settling promise inside data waits until the timeout", async () => { - const trace = makeTrace() - const result = await run( - ` - const pending = tools.host.pending({ id: 1 }) - return { pending } - `, - { trace, limits: { timeoutMs: 100 } }, - ) - expect(result.ok).toBe(false) - if (result.ok) return - expect(result.error.kind).toBe("TimeoutExceeded") - expect(trace.completed).toBe(0) - expect(trace.interrupted).toBe(1) - }) - - test("operators reject promise operands", async () => { - const diagnostic = await error(`return Promise.resolve(1) + 1`) - expect(diagnostic.kind).toBe("InvalidDataValue") - }) }) describe("Promise.all over arbitrary arrays", () => { - test("combinators return promises that can be assigned and awaited later", async () => { - expect( - await value(` - const all = Promise.all([Promise.resolve(1)]) - const settled = Promise.allSettled([Promise.reject("no")]) - const race = Promise.race([Promise.resolve(2)]) - const promises = [all instanceof Promise, settled instanceof Promise, race instanceof Promise] - return [promises, await all, await settled, await race] - `), - ).toEqual([[true, true, true], [1], [{ status: "rejected", reason: "no" }], 2]) - }) - - test("separately-created aggregate batches overlap before either is awaited", async () => { - const trace = makeTrace() - expect( - await value( - ` - const first = Promise.all([tools.host.gated({ id: 1 })]) - const second = Promise.all([tools.host.gated({ id: 2 })]) - await tools.host.open({ id: 1 }) - await tools.host.open({ id: 2 }) - return [await first, await second] - `, - { trace }, - ), - ).toEqual([[1], [2]]) - expect(trace.starts).toEqual([1, 2]) - expect(trace.maxActive).toBeGreaterThan(1) - }) - - test("an aggregate created before a try block rejects at its later await", async () => { - expect( - await value(` - const aggregate = Promise.all([tools.host.fail({})]) - try { - await aggregate - return "no" - } catch (error) { - return error.message - } - `), - ).toBe("Lookup refused") - }) - test("awaiting an aggregate repeatedly does not rerun its members", async () => { const result = await run(` const aggregate = Promise.all([tools.host.echo({ id: 7 })]) @@ -571,168 +215,6 @@ describe("Promise.all over arbitrary arrays", () => { expect(result.toolCalls).toStrictEqual([{ name: "host.echo" }]) }) - test("mixes promises and plain values, preserving order", async () => { - expect( - await value(` - return await Promise.all([tools.host.echo({ id: 1 }), "plain", tools.host.echo({ id: 2 }), 42]) - `), - ).toEqual([1, "plain", 2, 42]) - }) - - test("accepts arrays built beforehand, passed as identifiers, and spread elements", async () => { - expect( - await value(` - const calls = [] - calls.push(tools.host.echo({ id: 1 })) - calls.push(7) - const more = [tools.host.echo({ id: 2 })] - const batch = [...calls, ...more, "x"] - return await Promise.all(batch) - `), - ).toEqual([1, 7, 2, "x"]) - }) - - test("runs items.map tool calls in parallel", async () => { - const trace = makeTrace() - const result = await value( - ` - const ids = [1, 2, 3, 4] - const calls = ids.map((id) => tools.host.gated({ id })) - for (const id of ids) await tools.host.open({ id }) - return await Promise.all(calls) - `, - { trace }, - ) - expect(result).toEqual([1, 2, 3, 4]) - // maxActive counts truly-overlapping live executions, so > 1 proves real - // parallelism deterministically - no wall-clock assertion needed. - expect(trace.maxActive).toBeGreaterThan(1) - }) - - test("runs async map callbacks concurrently", async () => { - const trace = makeTrace() - const result = await value( - ` - const ids = [1, 2, 3, 4] - const calls = ids.map(async (id) => await tools.host.gated({ id })) - for (const id of ids) await tools.host.open({ id }) - return await Promise.all(calls) - `, - { trace }, - ) - expect(result).toEqual([1, 2, 3, 4]) - expect(trace.maxActive).toBeGreaterThan(1) - }) - - test("does not cap live tool-call concurrency", async () => { - const trace = makeTrace() - const result = await value( - ` - const ids = [] - for (let i = 0; i < 20; i += 1) ids.push(i) - const calls = ids.map((id) => tools.host.gated({ id })) - for (const id of ids) await tools.host.open({ id }) - const results = await Promise.all(calls) - return results.length - `, - { trace }, - ) - expect(result).toBe(20) - expect(trace.maxActive).toBe(20) - }) - - test("resolves the empty array", async () => { - expect(await value(`return await Promise.all([])`)).toEqual([]) - }) - - test("rejects with the first failure, catchable in-program", async () => { - const result = await run(` - try { - await Promise.all([tools.host.echo({ id: 1 }), tools.host.fail({})]) - return "no" - } catch (e) { - return e.message - } - `) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.value).toBe("Lookup refused") - expect(result.warnings).toBeUndefined() - }) - - test("rejects before an earlier slow promise fulfills", async () => { - const trace = makeTrace() - expect( - await value( - ` - try { - await Promise.all([ - tools.host.pending({ id: 1 }), - tools.host.fail({}), - ]) - return -1 - } catch { - return await tools.host.completed({}) - } - `, - { trace }, - ), - ).toBe(0) - // The surviving member is observed (Promise.all handled it), so completion interrupts - // it instead of waiting for it. - expect(trace.completed).toBe(0) - expect(trace.interrupted).toBe(1) - }) - - test("fail-fast does not cancel a sibling the program still holds and awaits", async () => { - const trace = makeTrace() - expect( - await value( - ` - const slow = tools.host.gated({ id: 1 }) - try { - await Promise.all([slow, tools.host.fail({})]) - return "no" - } catch {} - await tools.host.open({ id: 1 }) - return await slow - `, - { trace }, - ), - ).toBe(1) - expect(trace.completed).toBe(1) - expect(trace.interrupted).toBe(0) - }) - - test("a slower observed sibling is interrupted at completion after failing fast", async () => { - const trace = makeTrace() - expect( - await value( - ` - const failLater = async () => { - await tools.host.pending({ id: 1 }) - throw new Error("later") - } - const aggregate = Promise.all([Promise.reject(new Error("first")), failLater()]) - try { - await aggregate - return "no" - } catch (error) { - return error.message - } - `, - { trace }, - ), - ).toBe("first") - expect(trace.completed).toBe(0) - expect(trace.interrupted).toBe(1) - }) - - test("a non-collection argument is a clear error", async () => { - const diagnostic = await error(`return await Promise.all(42)`) - expect(diagnostic.message).toContain("Promise.all expects a synchronous iterable, received a number") - }) - test("exceeding maxToolCalls inside Promise.all is a ToolCallLimitExceeded diagnostic", async () => { const diagnostic = await error( `return await Promise.all([tools.host.echo({ id: 1 }), tools.host.echo({ id: 2 }), tools.host.echo({ id: 3 })])`, @@ -741,924 +223,3 @@ describe("Promise.all over arbitrary arrays", () => { expect(diagnostic.kind).toBe("ToolCallLimitExceeded") }) }) - -describe("Promise.allSettled", () => { - test("reports fulfilled and rejected outcomes with catch-normalized reasons", async () => { - expect( - await value(` - const settled = await Promise.allSettled([ - tools.host.echo({ id: 5 }), - tools.host.fail({}), - "plain", - Promise.reject(new Error("boom")), - ]) - return settled - `), - ).toEqual([ - { status: "fulfilled", value: 5 }, - { status: "rejected", reason: { name: "Error", message: "Lookup refused" } }, - { status: "fulfilled", value: "plain" }, - { status: "rejected", reason: { name: "Error", message: "boom" } }, - ]) - }) - - test("never rejects for program-level failures", async () => { - const result = await run(` - const settled = await Promise.allSettled([tools.host.fail({}), tools.host.fail({})]) - return settled.filter((s) => s.status === "rejected").length - `) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.value).toBe(2) - expect(result.warnings).toBeUndefined() - }) -}) - -describe("Promise.race", () => { - test("first settlement wins and a direct loser is interrupted at completion", async () => { - const trace = makeTrace() - const result = await value( - ` - const fast = tools.host.echo({ id: 1 }) - const slow = tools.host.pending({ id: 2 }) - return await Promise.race([fast, slow]) - `, - { trace }, - ) - expect(result).toBe(1) - // The loser is observed (the race handled it), so the execution does not wait for it. - expect(trace.completed).toBe(1) - expect(trace.interrupted).toBe(1) - }) - - test("a direct loser remains awaitable after the race settles", async () => { - expect( - await value(` - const fast = tools.host.echo({ id: 1 }) - const slow = tools.host.gated({ id: 2 }) - const winner = await Promise.race([fast, slow]) - await tools.host.open({ id: 2 }) - return { winner, loser: await slow } - `), - ).toEqual({ winner: 1, loser: 2 }) - }) - - test("a nested aggregate loser and its members are interrupted at completion", async () => { - const trace = makeTrace() - expect( - await value( - ` - const nested = Promise.all([ - tools.host.pending({ id: 1 }), - tools.host.pending({ id: 2 }), - ]) - return await Promise.race(["immediate", nested]) - `, - { trace }, - ), - ).toBe("immediate") - // The nested aggregate and its members are all observed, so nothing waits for them. - expect(trace.completed).toBe(0) - expect(trace.interrupted).toBe(2) - }) - - test("a rejection can win the race", async () => { - expect( - await value(` - try { - await Promise.race([tools.host.fail({}), tools.host.pending({ id: 1 })]) - return "no" - } catch (e) { - return e.message - } - `), - ).toBe("Lookup refused") - }) - - test("a plain value wins over pending promises", async () => { - const trace = makeTrace() - expect(await value(`return await Promise.race([tools.host.pending({ id: 1 }), "immediate"])`, { trace })).toBe( - "immediate", - ) - expect(trace.completed).toBe(0) - expect(trace.interrupted).toBe(1) - }) - - test("a rejected race loser is observed by the aggregate", async () => { - const result = await run(`return await Promise.race(["winner", tools.host.fail({})])`) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.value).toBe("winner") - expect(result.warnings).toBeUndefined() - }) - - test("an empty race is a clear error instead of hanging", async () => { - const diagnostic = await error(`return await Promise.race([])`) - expect(diagnostic.message).toContain("never settle") - }) -}) - -describe("Promise.resolve / Promise.reject", () => { - test("resolve wraps plain values and passes promises through", async () => { - expect(await value(`return await Promise.resolve(42)`)).toBe(42) - expect(await value(`return await Promise.resolve(Promise.resolve("nested"))`)).toBe("nested") - expect(await value(`return await Promise.resolve(tools.host.echo({ id: 3 }))`)).toBe(3) - expect(await value(`const promise = Promise.resolve(1); return [promise].includes(Promise.resolve(promise))`)).toBe( - true, - ) - }) - - test("reject produces a promise whose await throws the reason", async () => { - expect( - await value(` - try { - await Promise.reject("nope") - return "no" - } catch (e) { - return e - } - `), - ).toBe("nope") - }) - - test("a rejection observed after settlement is handled", async () => { - expect( - await value(` - const rejected = Promise.reject(new Error("handled")) - await tools.host.echo({ id: 1 }) - try { - await rejected - return "no" - } catch (error) { - return error.message - } - `), - ).toBe("handled") - }) - - test("an abandoned rejected promise is reported as unhandled", async () => { - const result = await run(` - Promise.reject(new Error("abandoned")) - return "done" - `) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.value).toBe("done") - expect(result.warnings).toStrictEqual([ - { kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Error: abandoned" }, - ]) - }) -}) - -describe("timeout interruption of forked calls", () => { - test("the execution timeout interrupts in-flight forked fibers", async () => { - const trace = makeTrace() - const result = await run( - ` - const a = tools.host.pending({ id: 1 }) - const b = tools.host.pending({ id: 2 }) - return await a - `, - { trace, limits: { timeoutMs: 100 } }, - ) - expect(result.ok).toBe(false) - if (result.ok) return - expect(result.error.kind).toBe("TimeoutExceeded") - // Both calls started; neither escaped the timeout - the awaited one AND the abandoned one. - expect(trace.starts).toEqual([1, 2]) - expect(trace.interrupted).toBe(2) - expect(trace.completed).toBe(0) - }) - - test("the timeout also interrupts calls inside Promise.all", async () => { - const trace = makeTrace() - const result = await run( - `return await Promise.all([tools.host.pending({ id: 1 }), tools.host.pending({ id: 2 })])`, - { trace, limits: { timeoutMs: 100 } }, - ) - expect(result.ok).toBe(false) - if (result.ok) return - expect(result.error.kind).toBe("TimeoutExceeded") - expect(trace.interrupted).toBe(2) - }) - - test("a non-settling race loser cannot hold the execution to the timeout", async () => { - const trace = makeTrace() - const result = await run(`return await Promise.race(["winner", tools.host.pending({ id: 1 })])`, { - trace, - limits: { timeoutMs: 100 }, - }) - // Completion interrupts the observed loser immediately; the race result survives. - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.value).toBe("winner") - expect(result.warnings).toBeUndefined() - expect(trace.starts).toEqual([1]) - expect(trace.completed).toBe(0) - expect(trace.interrupted).toBe(1) - }) - - test("a timeout during completion cleanup keeps the computed value and warns", async () => { - const trace = makeTrace() - const result = await run( - ` - tools.host.stubborn({ cleanupMs: 400 }) - return "done" - `, - { trace, limits: { timeoutMs: 100 } }, - ) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.value).toBe("done") - expect(result.warnings).toStrictEqual([ - { - kind: "TimeoutExceeded", - message: - "The program returned, but background work was still running at the 100ms timeout and was interrupted. Await all started promises.", - }, - ]) - expect(trace.interrupted).toBe(1) - expect(trace.completed).toBe(0) - }) - - test("a timeout during completion cleanup reports the timeout warning before settled rejections", async () => { - const result = await run( - ` - tools.host.fail({}) - tools.host.stubborn({ cleanupMs: 400 }) - return "done" - `, - { limits: { timeoutMs: 100 } }, - ) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.value).toBe("done") - expect(result.warnings).toStrictEqual([ - { - kind: "TimeoutExceeded", - message: - "The program returned, but background work was still running at the 100ms timeout and was interrupted. Await all started promises.", - }, - { kind: "ToolFailure", message: "Unhandled rejection from an un-awaited promise: Lookup refused" }, - ]) - }) -}) - -describe("promise chaining", () => { - test("then transforms tool results and adopts returned promises across a chain", async () => { - expect( - await value(` - return await tools.host - .echo({ id: 2 }) - .then((id) => tools.host.echo({ id: id + 1 })) - .then((id) => id * 10) - `), - ).toBe(30) - }) - - test("handlers are deferred and run in attach order", async () => { - expect( - await value(` - const order = [] - const promise = Promise.resolve(1) - promise.then(() => order.push("h1")) - promise.then(() => order.push("h2")) - order.push("sync") - await promise - return order - `), - ).toEqual(["sync", "h1", "h2"]) - }) - - test("catch recovers a tool failure and preserves fulfillment", async () => { - expect( - await value(` - return [ - await tools.host.fail({}).catch((error) => error.message), - await tools.host.echo({ id: 4 }).catch(() => "unused"), - ] - `), - ).toEqual(["Lookup refused", 4]) - }) - - test("finally observes settlement without changing the value", async () => { - expect( - await value(` - const events = [] - const result = await tools.host.echo({ id: 5 }).finally(() => events.push("cleanup")) - return [result, events] - `), - ).toEqual([5, ["cleanup"]]) - }) - - test("a settled, un-awaited rejected chain tail warns exactly once", async () => { - const result = await run(` - Promise.reject(new Error("boom")).then((value) => value) - await Promise.resolve() - return "done" - `) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.value).toBe("done") - // The source rejection belongs to the chain (no warning); only the derived tail warns. - expect(result.warnings).toStrictEqual([ - { kind: "ExecutionFailure", message: "Unhandled rejection from an un-awaited promise: Error: boom" }, - ]) - }) - - test("a catch handler silences the chain's rejection warning", async () => { - const result = await run(` - Promise.reject(new Error("boom")).catch(() => "handled") - await Promise.resolve() - return "done" - `) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.warnings).toBeUndefined() - }) - - test("unsupported callable handlers fail loudly with a wrap hint", async () => { - const diagnostic = await error(`return await tools.host.echo({ id: 1 }).then(tools.host.completed)`) - expect(diagnostic.message).toContain("Promise.prototype.then cannot use this callable as a handler") - expect(diagnostic.message).toContain("wrap it in an arrow function") - }) - - test("chaining methods are opaque references until called", async () => { - expect(await value(`return typeof tools.host.echo({ id: 1 }).then`)).toBe("function") - }) -}) - -describe("combinator settlement timing", () => { - test("a combinator settling one reaction turn after the program returns is interrupted silently", async () => { - // The aggregate's one-turn settlement delay (V8 parity) means an immediately-returning - // program abandons it while still pending: interrupted like any pending work, so no - // rejection warning survives - the member itself was observed by the combinator. - const result = await run(` - Promise.all([Promise.reject(new Error("boom"))]) - return "done" - `) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.value).toBe("done") - expect(result.warnings).toBeUndefined() - }) - - test("a combinator settles one reaction turn after its members, as in V8", async () => { - // Regression for the race winner flip: Promise.all's settlement burns a reaction turn, - // so a plain resolved value entered in the same race wins, and a fail-fast aggregate - // cannot beat it into rejection. - expect( - await value(` - const pending = tools.host.pending({ id: 9 }) - const winner = await Promise.race([Promise.all([Promise.resolve(1)]), Promise.resolve(2)]) - try { - const raced = await Promise.race([Promise.all([Promise.reject("x"), pending]), Promise.resolve("ok")]) - return [winner, "fulfilled", raced] - } catch (reason) { - return [winner, "rejected", reason] - } - `), - ).toEqual([2, "fulfilled", "ok"]) - }) -}) - -describe("unsupported promise surface", () => { - test("other property reads on a promise hint at the missing await", async () => { - const diagnostic = await error(`return tools.host.echo({ id: 1 }).value`) - expect(diagnostic.kind).toBe("InvalidDataValue") - expect(diagnostic.message).toContain("un-awaited Promise") - expect(diagnostic.message).toContain("await it first") - }) - - test("unknown Promise statics are not functions", async () => { - const diagnostic = await error(`return await Promise.settle(() => 1)`) - expect(diagnostic.message).toContain("Promise.settle is not a function") - }) -}) - -describe("Promise.try", () => { - test("runs the function now with its arguments; a throw rejects, a return fulfils, a promise or thenable is adopted", async () => { - expect( - await value(` - const log = [] - const sum = Promise.try((a, b) => { log.push("ran"); return a + b }, 1, 2) - log.push("after") - let caught - try { await Promise.try(() => { throw new RangeError("boom") }) } catch (e) { caught = e.constructor.name } - return [log, sum instanceof Promise, await sum, caught, await Promise.try(async () => 5), await Promise.try(() => ({ then: (r) => r("thenable") }))] - `), - ).toEqual([["ran", "after"], true, 3, "RangeError", 5, "thenable"]) - expect((await error(`return Promise.try(5)`)).message).toContain( - "Promise.try expects a function, received a number.", - ) - }) -}) - -describe("Promise.withResolvers", () => { - test("returns a pending promise with resolvers that settle it once and adopt thenables", async () => { - expect( - await value(` - const first = Promise.withResolvers() - first.resolve(Promise.resolve("adopted")) - first.resolve("ignored") - const second = Promise.withResolvers() - second.reject(new Error("no")) - let caught - try { await second.promise } catch (e) { caught = e.message } - return [Object.keys(first), first.promise instanceof Promise, await first.promise, caught] - `), - ).toEqual([["promise", "resolve", "reject"], true, "adopted", "no"]) - }) -}) - -describe("Promise.any", () => { - test("first tool success wins; failing and losing calls are handled silently", async () => { - const trace = makeTrace() - const result = await run( - ` - const winner = await Promise.any([ - tools.host.fail({}), - tools.host.echo({ id: 1 }), - tools.host.pending({ id: 2 }), - ]) - return winner - `, - { trace }, - ) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.value).toBe(1) - // The slow loser stays execution-owned and is interrupted at completion; the tool - // failure was observed by the aggregate, so no rejection warning survives. - expect(result.warnings).toBeUndefined() - expect(trace.interrupted).toBe(1) - }) - - test("all members failing rejects with catch-normalized reasons in input order", async () => { - expect( - await value(` - try { - await Promise.any([tools.host.fail({}), Promise.reject("plain")]) - return "fulfilled" - } catch (error) { - return [error.name, error.errors.map((reason) => reason.message ?? reason)] - } - `), - ).toEqual(["AggregateError", ["Lookup refused", "plain"]]) - }) - - test("settles one reaction turn after its deciding member, as in V8", async () => { - expect(await value(`return await Promise.race([Promise.any([Promise.resolve(1)]), Promise.resolve(2)])`)).toBe(2) - }) - - test("a tie is decided by settlement order, not input order", async () => { - // Handlers run in attach order, so `first` settles before `second` and wins - // despite its later input position - as in real JS. - expect( - await value(` - const first = Promise.resolve().then(() => "one") - const second = Promise.resolve().then(() => "two") - return await Promise.any([second, first]) - `), - ).toBe("one") - }) - - test("an abandoned rejecting aggregate is interrupted silently at the return", async () => { - const result = await run(` - Promise.any([Promise.reject(new Error("boom"))]) - return "done" - `) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.value).toBe("done") - expect(result.warnings).toBeUndefined() - }) -}) - -describe("promise construction", () => { - test("a deferred gate coordinates tool results across async functions", async () => { - expect( - await value(` - let openGate - const gate = new Promise((resolve) => { openGate = resolve }) - const worker = (async () => { - const id = await gate - return id * 2 - })() - openGate(await tools.host.echo({ id: 21 })) - return await worker - `), - ).toBe(42) - }) - - test("the .then(resolve) bridge settles a constructed promise", async () => { - expect( - await value(` - const bridged = new Promise((resolve, reject) => { - tools.host.echo({ id: 7 }).then(resolve, reject) - }) - return await bridged - `), - ).toBe(7) - }) - - test("constructed promises participate in combinators", async () => { - expect( - await value(` - let settle - const manual = new Promise((resolve) => { settle = resolve }) - const race = Promise.race([manual, tools.host.pending({ id: 3 })]) - const all = Promise.all([manual, "plain"]) - const any = Promise.any([manual, new Promise(() => {})]) - settle("manual") - return [await race, await all, await any] - `), - ).toEqual(["manual", ["manual", "plain"], "manual"]) - }) - - test("resolving with a pending promise adopts its later settlement", async () => { - expect( - await value(` - let innerResolve, innerReject - const adopted = new Promise((resolve) => resolve(new Promise((resolve) => { innerResolve = resolve }))) - const adoptedRejection = new Promise((resolve) => resolve(new Promise((_, reject) => { innerReject = reject }))) - innerResolve("later") - innerReject("bad") - try { - return [await adopted, await adoptedRejection] - } catch (reason) { - return [await adopted, reason] - } - `), - ).toEqual(["later", "bad"]) - }) - - test("an async executor's post-await resolve settles the promise", async () => { - expect( - await value(` - const result = new Promise(async (resolve) => { - const id = await tools.host.echo({ id: 5 }) - resolve(id * 2) - }) - return await result - `), - ).toBe(10) - }) - - test("a never-settled promise is abandoned silently at the return", async () => { - const result = await run(` - const forever = new Promise(() => {}) - forever.then(() => {}) - return "done" - `) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.value).toBe("done") - expect(result.warnings).toBeUndefined() - }) - - test("an un-awaited constructed rejection is reported like any unhandled rejection", async () => { - const result = await run(` - new Promise((_, reject) => reject(new Error("dropped"))) - await Promise.resolve() - await Promise.resolve() - return "done" - `) - expect(result.ok).toBe(true) - if (!result.ok) return - expect(result.value).toBe("done") - expect(result.warnings).toHaveLength(1) - expect(result.warnings?.[0].message).toContain("Unhandled rejection") - expect(result.warnings?.[0].message).toContain("dropped") - }) - - test("resolver functions vanish at the data boundary like JSON.stringify", async () => { - expect( - await value(` - let escaped - new Promise((resolve) => { escaped = resolve }) - return { escaped, kind: typeof escaped } - `), - ).toEqual({ kind: "function" }) - }) -}) - -describe("jobs run to completion", () => { - // The runner pauses a long job to let the host run; the paused job still finishes before any other job starts. - test("updates to shared state between awaits are not lost", async () => { - expect( - await value(` - let total = 0 - const work = async () => { - await null - for (let i = 0; i < 1000; i++) total = total + 1 - } - await Promise.all([work(), work()]) - return total - `), - ).toBe(2000) - }) - - test("an async function runs to its first await before its caller continues", async () => { - expect( - await value(` - let count = 0 - const work = async () => { - for (let i = 0; i < 1000; i++) count = count + 1 - await null - } - work() - return count - `), - ).toBe(1000) - }) - - test("a combinator's reaction runs after the continuations a preempted job queued first", async () => { - for (const op of ["race", "any", "all", "allSettled"]) { - expect( - await value(` - const burn = () => { for (let i = 0; i < 400; i++) {} } - const log = [] - const settled = Promise.${op}([{ then(resolve) { burn(); resolve(1) } }]).then(() => log.push("result")) - const job = (async () => { await null; burn(); log.push("b0"); await null; log.push("b1") })() - await Promise.all([settled, job]) - return log - `), - ).toEqual(["b0", "b1", "result"]) - } - }) - - test("a job that never awaits still times out while other jobs wait for it", async () => { - const failure = await error( - ` - const spin = async () => { await null; while (true) {} } - const quick = async () => { await null; return 1 } - return await Promise.all([spin(), quick(), quick()]) - `, - { limits: { timeoutMs: 100 } }, - ) - expect(failure.kind).toBe("TimeoutExceeded") - }) -}) - -// Each case logs from several jobs; the program then drains the queue. Expected orders are what Node 25 (V8) logs for -// the same code. -const v8Order: ReadonlyArray]> = [ - [ - "then vs await", - `Promise.resolve().then(() => log.push("then")); (async () => { await null; log.push("await") })(); log.push("sync")`, - ["sync", "then", "await"], - ], - [ - "adopt promise from async fn", - `async function f() { return Promise.resolve(1) } f().then(() => log.push("f")); Promise.resolve().then(() => log.push("a")).then(() => log.push("b")).then(() => log.push("c")).then(() => log.push("d"))`, - ["a", "b", "f", "c", "d"], - ], - [ - "resolve with promise", - `new Promise((r) => r(Promise.resolve())).then(() => log.push("adopted")); Promise.resolve().then(() => log.push(1)).then(() => log.push(2)).then(() => log.push(3))`, - [1, 2, "adopted", 3], - ], - [ - "await thenable", - `(async () => { await { then(r) { log.push("then called"); r(1) } }; log.push("after thenable") })(); Promise.resolve().then(() => log.push(1)).then(() => log.push(2)).then(() => log.push(3))`, - ["then called", 1, "after thenable", 2, 3], - ], - [ - "finally", - `Promise.resolve(1).finally(() => log.push("fin")).then(() => log.push("after finally")); Promise.resolve().then(() => log.push(1)).then(() => log.push(2)).then(() => log.push(3)).then(() => log.push(4))`, - ["fin", 1, 2, 3, "after finally", 4], - ], - [ - "finally rejected", - `Promise.reject(1).finally(() => log.push("fin")).catch(() => log.push("caught")); Promise.resolve().then(() => log.push(1)).then(() => log.push(2)).then(() => log.push(3)).then(() => log.push(4))`, - ["fin", 1, 2, 3, "caught", 4], - ], - [ - "Promise.all", - `Promise.all([1, Promise.resolve(2)]).then(() => log.push("all")); Promise.resolve().then(() => log.push(1)).then(() => log.push(2)).then(() => log.push(3))`, - [1, "all", 2, 3], - ], - [ - "Promise.all empty", - `Promise.all([]).then(() => log.push("all")); Promise.resolve().then(() => log.push(1)).then(() => log.push(2))`, - ["all", 1, 2], - ], - [ - "Promise.race", - `Promise.race([Promise.resolve(1), 2]).then((v) => log.push("race " + v)); Promise.resolve().then(() => log.push(1)).then(() => log.push(2)).then(() => log.push(3))`, - [1, "race 1", 2, 3], - ], - [ - "Promise.allSettled", - `Promise.allSettled([Promise.reject(1), 2]).then(() => log.push("settled")); Promise.resolve().then(() => log.push(1)).then(() => log.push(2)).then(() => log.push(3))`, - [1, "settled", 2, 3], - ], - [ - "Promise.any", - `Promise.any([Promise.reject(1), Promise.resolve(2)]).then(() => log.push("any")); Promise.resolve().then(() => log.push(1)).then(() => log.push(2)).then(() => log.push(3))`, - [1, "any", 2, 3], - ], - [ - "async generator", - `async function* g() { log.push("start"); yield 1; log.push("mid"); yield 2; log.push("end") } const it = g(); it.next().then((r) => log.push("n1 " + r.value)); it.next().then((r) => log.push("n2 " + r.value)); it.next().then((r) => log.push("n3 " + r.done)); Promise.resolve().then(() => log.push(1)).then(() => log.push(2)).then(() => log.push(3)).then(() => log.push(4))`, - ["start", "mid", 1, "n1 1", "end", 2, "n2 2", "n3 true", 3, 4], - ], - [ - "async generator return", - `async function* g() { try { yield 1 } finally { log.push("cleanup") } } const it = g(); it.next().then(() => it.return(5)).then((r) => log.push("ret " + r.value)); Promise.resolve().then(() => log.push(1)).then(() => log.push(2)).then(() => log.push(3)).then(() => log.push(4)).then(() => log.push(5))`, - [1, 2, "cleanup", 3, 4, "ret 5", 5], - ], - [ - "for await sync iterable", - `(async () => { for await (const x of [1, Promise.resolve(2), 3]) log.push("x" + x) })(); Promise.resolve().then(() => log.push(1)).then(() => log.push(2)).then(() => log.push(3)).then(() => log.push(4)).then(() => log.push(5)).then(() => log.push(6))`, - [1, "x1", 2, 3, "x2", 4, 5, "x3", 6], - ], - [ - "for await async gen", - `async function* g() { yield 1; yield 2 } (async () => { for await (const x of g()) log.push("x" + x) })(); Promise.resolve().then(() => log.push(1)).then(() => log.push(2)).then(() => log.push(3)).then(() => log.push(4)).then(() => log.push(5)).then(() => log.push(6))`, - [1, "x1", 2, 3, "x2", 4, 5, 6], - ], - [ - "nested async", - `async function a() { log.push("a1"); await b(); log.push("a2") } async function b() { log.push("b1"); await null; log.push("b2") } a(); Promise.resolve().then(() => log.push(1)).then(() => log.push(2)).then(() => log.push(3))`, - ["a1", "b1", "b2", 1, "a2", 2, 3], - ], - [ - "await rejected", - `(async () => { try { await Promise.reject(1) } catch { log.push("caught") } })(); Promise.resolve().then(() => log.push(1)).then(() => log.push(2))`, - ["caught", 1, 2], - ], - [ - "then handler returns promise", - `Promise.resolve().then(() => Promise.resolve("x")).then((v) => log.push(v)); Promise.resolve().then(() => log.push(1)).then(() => log.push(2)).then(() => log.push(3)).then(() => log.push(4))`, - [1, 2, 3, "x", 4], - ], - [ - "withResolvers", - `const { promise, resolve } = Promise.withResolvers(); promise.then(() => log.push("resolved")); Promise.resolve().then(() => { log.push(1); resolve() }).then(() => log.push(2)).then(() => log.push(3))`, - [1, "resolved", 2, 3], - ], - [ - "sync generator in async", - `function* g() { yield 1; yield 2 } (async () => { for (const x of g()) { await null; log.push("g" + x) } })(); Promise.resolve().then(() => log.push(1)).then(() => log.push(2)).then(() => log.push(3))`, - ["g1", 1, "g2", 2, 3], - ], - [ - "async return await", - `async function f() { return await Promise.resolve(1) } f().then(() => log.push("f")); Promise.resolve().then(() => log.push(1)).then(() => log.push(2)).then(() => log.push(3))`, - [1, "f", 2, 3], - ], - [ - "yield* sync in async gen", - `async function* g() { yield* [1, Promise.resolve(2)] } (async () => { for await (const x of g()) log.push("x" + x) })(); Promise.resolve().then(() => log.push(1)).then(() => log.push(2)).then(() => log.push(3)).then(() => log.push(4)).then(() => log.push(5)).then(() => log.push(6)).then(() => log.push(7))`, - [1, 2, "x1", 3, 4, 5, "x2", 6, 7], - ], - [ - "break in for await sync", - `(async () => { for await (const x of [1, 2]) { log.push("x" + x); break } log.push("after") })(); Promise.resolve().then(() => log.push(1)).then(() => log.push(2)).then(() => log.push(3)).then(() => log.push(4))`, - [1, "x1", 2, "after", 3, 4], - ], - [ - "for await rejected value", - `(async () => { try { for await (const x of [Promise.reject("r")]) log.push(x) } catch (e) { log.push("caught " + e) } })(); Promise.resolve().then(() => log.push(1)).then(() => log.push(2)).then(() => log.push(3)).then(() => log.push(4))`, - [1, "caught r", 2, 3, 4], - ], - [ - "unhandled then later handled", - `const p = Promise.reject(1); Promise.resolve().then(() => p.catch(() => log.push("late catch"))); Promise.resolve().then(() => log.push(1)).then(() => log.push(2)).then(() => log.push(3))`, - [1, "late catch", 2, 3], - ], - [ - "generator return in finally", - `function* g() { try { yield 1 } finally { yield 2 } } const it = g(); log.push(JSON.stringify(it.next())); log.push(JSON.stringify(it.return(9))); log.push(JSON.stringify(it.next()))`, - ['{"value":1,"done":false}', '{"value":2,"done":false}', '{"value":9,"done":true}'], - ], - [ - "async gen await in finally", - `async function* g() { try { yield 1 } finally { await null; log.push("fin") } } const it = g(); it.next().then(() => it.return(3)).then((r) => log.push("r" + r.value)); Promise.resolve().then(() => log.push(1)).then(() => log.push(2)).then(() => log.push(3)).then(() => log.push(4)).then(() => log.push(5))`, - [1, 2, 3, "fin", 4, 5, "r3"], - ], - [ - "thenable job then throws", - `Promise.resolve({ then() { throw new Error("boom") } }).catch((e) => log.push(e.message)); Promise.resolve().then(() => log.push(1)).then(() => log.push(2))`, - [1, "boom", 2], - ], - [ - "Promise.try", - `Promise.try(() => log.push("ran")).then(() => log.push("try")); Promise.resolve().then(() => log.push(1)).then(() => log.push(2))`, - ["ran", "try", 1, 2], - ], -] - -describe("job order matches V8", () => { - test.each(v8Order)("%s", async (_, code, expected) => { - expect(await value(`const log = []; ${code}; for (let i = 0; i < 20; i++) await null; return log`)).toEqual( - expected, - ) - }) -}) - -describe("a program that can never finish", () => { - const stalled = - "Error: The program is waiting on a promise that can never settle: nothing else is running, so nothing can resolve it. There are no timers or sleep, so don't wait or poll inside a program." - - // Each program stalls at the await on line `line`, column `column`; an outer await only waits on that one. - test.each([ - ["the program's own await", "await new Promise((r) => r)", 1, 1], - [ - "an async function whose result the program returns", - ["async function wait() {", " await new Promise(() => {})", "}", "return wait()"].join("\n"), - 2, - 3, - ], - [ - "an async function the program awaits", - ["async function wait() {", " await new Promise(() => {})", "}", "await wait()"].join("\n"), - 2, - 3, - ], - [ - "a later await in an async body the program awaits", - [ - "const { promise } = Promise.withResolvers()", - "const p = (async () => { await null; await promise })()", - "await p", - ].join("\n"), - 2, - 38, - ], - ])("fails at once, without a timeout, at the stuck await in %s", async (_, code, line, column) => { - expect(await error(code)).toEqual({ - kind: "ExecutionFailure", - message: `${stalled} (line ${line}, col ${column})`, - location: { line, column }, - }) - }) - - test("fails when the unsettleable promise is deep inside other async work", async () => { - const failure = await error(` - const never = async () => { await null; await new Promise(() => {}) } - return await Promise.all([never(), Promise.resolve(1)]) - `) - expect(failure.message).toStartWith(stalled) - }) - - test("cannot be caught by the program", async () => { - expect(await error(`try { await new Promise(() => {}) } catch { return "caught" }`)).toEqual({ - kind: "ExecutionFailure", - message: `${stalled} (line 1, col 7)`, - location: { line: 1, column: 7 }, - }) - }) - - test("is not stalled while a tool call that settles a hand-made promise is still running", async () => { - expect( - await value(` - const { promise, resolve } = Promise.withResolvers() - tools.host.gated({ id: 1 }).then(resolve) - tools.host.open({ id: 1 }) - return await promise - `), - ).toBe(1) - }) - - test("is not stalled while a tool call it waits on is still running", async () => { - expect( - await value(` - const call = tools.host.gated({ id: 1 }) - await tools.host.open({ id: 1 }) - return await call - `), - ).toBe(1) - }) -}) - -describe("host results", () => { - test("a tool result settles after the jobs already queued, like I/O", async () => { - expect( - await value(` - const log = [] - const call = tools.host.echo({ id: 1 }).then(() => log.push("tool")) - Promise.resolve().then(() => log.push(1)).then(() => log.push(2)).then(() => log.push(3)) - await call - return log - `), - ).toEqual([1, 2, 3, "tool"]) - }) - - test("an awaited interruption passes catch and finally and interrupts the program", async () => { - const exit = await Effect.runPromiseExit( - CodeMode.execute({ - tools: { host: { interrupt: interruptedTool } }, - code: ` - const inner = async () => { - try { await tools.host.interrupt({}) } catch { return "caught" } finally { return "finally" } - } - return await inner().catch(() => "handled") - `, - }), - ) - expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true) - }) -}) diff --git a/packages/codemode/test/regexp-math-test262.test.ts b/packages/codemode/test/regexp-math-test262.test.ts deleted file mode 100644 index bd85d3ef2db..00000000000 --- a/packages/codemode/test/regexp-math-test262.test.ts +++ /dev/null @@ -1,283 +0,0 @@ -/* - * Portions adapted from Test262 at revision 250f204f23a9249ff204be2baec29600faae7b75: - * - test/built-ins/RegExp/escape/initial-char-escape.js - * - test/built-ins/RegExp/escape/escaped-syntax-characters-simple.js - * - test/built-ins/RegExp/escape/escaped-otherpunctuators.js - * - test/built-ins/RegExp/escape/escaped-control-characters.js - * - test/built-ins/RegExp/escape/escaped-whitespace.js - * - test/built-ins/RegExp/escape/escaped-lineterminator.js - * - test/built-ins/RegExp/escape/escaped-surrogates.js - * - test/built-ins/RegExp/escape/escaped-solidus-character-simple.js - * - test/built-ins/RegExp/escape/escaped-utf16encodecodepoint.js - * - test/built-ins/RegExp/escape/not-escaped.js - * - test/built-ins/RegExp/escape/not-escaped-underscore.js - * - test/built-ins/RegExp/escape/non-string-inputs.js - * - test/built-ins/RegExp/prototype/hasIndices/this-val-regexp.js - * - test/built-ins/RegExp/prototype/unicodeSets/uv-flags-constructor.js - * - test/built-ins/RegExp/match-indices/indices-array.js - * - test/built-ins/RegExp/match-indices/indices-array-matched.js - * - test/built-ins/RegExp/match-indices/indices-array-non-unicode-match.js - * - test/built-ins/RegExp/match-indices/indices-array-unmatched.js - * - test/built-ins/RegExp/match-indices/indices-array-unicode-match.js - * - test/built-ins/RegExp/match-indices/indices-groups-object-undefined.js - * - test/built-ins/RegExp/match-indices/indices-groups-object-unmatched.js - * - test/built-ins/RegExp/match-indices/no-indices-array.js - * - test/built-ins/Math/sumPrecise/takes-iterable.js - * - test/built-ins/Math/sumPrecise/sum.js - * - test/built-ins/Math/sumPrecise/sum-is-infinite.js - * - test/built-ins/Math/sumPrecise/sum-is-minus-zero.js - * - test/built-ins/Math/sumPrecise/sum-is-NaN.js - * - test/built-ins/Math/sumPrecise/throws-on-non-number.js - * - * Copyright (C) 2019 Ron Buckton. All rights reserved. - * Copyright (C) 2021 Ron Buckton and the V8 project authors. All rights reserved. - * Copyright (C) 2024 Kevin Gibbons. All rights reserved. - * Copyright (C) 2024 Leo Balter. All rights reserved. - * Copyright (C) 2024 Leo Balter, Jordan Harband. All rights reserved. - * Copyright 2022 Mathias Bynens. All rights reserved. - * Test262 portions are governed by the BSD license in LICENSE.test262. - * Generator and custom-iterator cases are omitted because CodeMode exposes only its supported collection iterables; - * the Math.sumPrecise iterable case additionally covers Set. - */ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" - -const value = async (code: string) => { - const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} })) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -describe("RegExp Test262 parity", () => { - test("RegExp.escape encodes syntax, punctuators, whitespace, and surrogates", async () => { - expect( - await value(` - return [ - RegExp.escape("1+1"), - RegExp.escape("foo.bar"), - RegExp.escape(".*+?^$|()[]{}"), - RegExp.escape(",-=#&!%:;@~'"), - RegExp.escape("\\t\\n\\v\\f\\r"), - RegExp.escape("\\uFEFF \\u00A0\\u202F"), - RegExp.escape("\\u2028\\u2029"), - RegExp.escape("\\uD800"), - RegExp.escape("\\uDFFF"), - ] - `), - ).toEqual([ - "\\x31\\+1", - "\\x66oo\\.bar", - "\\.\\*\\+\\?\\^\\$\\|\\(\\)\\[\\]\\{\\}", - "\\x2c\\x2d\\x3d\\x23\\x26\\x21\\x25\\x3a\\x3b\\x40\\x7e\\x27", - "\\t\\n\\v\\f\\r", - "\\ufeff\\x20\\xa0\\u202f", - "\\u2028\\u2029", - "\\ud800", - "\\udfff", - ]) - }) - - test("RegExp.escape rejects non-string inputs", async () => { - expect( - await value(` - const rejects = (input) => { - try { - RegExp.escape(input) - return false - } catch (error) { - return error.name === "TypeError" - } - } - return [rejects(123), rejects({}), rejects([]), rejects(null), rejects(undefined)] - `), - ).toEqual([true, true, true, true, true]) - }) - - test("RegExp.escape preserves ordinary ASCII and Unicode code points", async () => { - expect( - await value(` - return [ - RegExp.escape(""), - RegExp.escape(".a1b2c3D4E5F6"), - RegExp.escape("_a_1_2"), - RegExp.escape("hello_world"), - RegExp.escape("//"), - RegExp.escape("\\u4F60\\u597D"), - RegExp.escape("\\u0393\\u03B5\\u03B9\\u03AC \\u03C3\\u03BF\\u03C5"), - RegExp.escape("\\uD835\\uDC01"), - ] - `), - ).toEqual([ - "", - "\\.a1b2c3D4E5F6", - "_a_1_2", - "\\x68ello_world", - "\\/\\/", - "\u4f60\u597d", - "\u0393\u03b5\u03b9\u03ac\\x20\u03c3\u03bf\u03c5", - "\uD835\uDC01", - ]) - }) - - test("d flag exposes match indices through exec, match, and matchAll", async () => { - expect( - await value(` - const match = /(?a)(b)?/d.exec("a") - const stringMatch = "a".match(/a/d) - const all = "a a".matchAll(/a/dg) - const named = /(?a)(?b)/d.exec("ab") - return [ - /./.hasIndices, - /./d.hasIndices, - new RegExp(".", "d").hasIndices, - match.indices[0], - match.indices[1], - match.indices[2], - match.indices.groups.a, - stringMatch.indices[0], - all[0].indices[0], - all[1].indices[0], - Object.keys(named.indices.groups), - ] - `), - ).toEqual([false, true, true, [0, 1], [0, 1], null, [0, 1], [0, 1], [0, 1], [2, 3], ["constructor", "safe"]]) - }) - - test("match indices preserve captures, Unicode offsets, and groups properties", async () => { - expect( - await value(` - const plain = /a/.exec("a") - const captured = "abcd".match(/b(c)/d) - const unmatched = "bab".match(/(\\w\\w)(\\W)?/d) - const nonUnicode = "\\uD835\\uDC01".match(/./d) - const unicode = "\\uD835\\uDC01".match(/./du) - const noGroups = /./d.exec("a").indices - return [ - Object.hasOwn(plain, "indices"), - captured.indices, - unmatched.indices, - nonUnicode.indices[0], - unicode.indices[0], - Object.hasOwn(noGroups, "groups"), - noGroups.groups, - ] - `), - ).toEqual([ - false, - [ - [1, 3], - [2, 3], - ], - [[0, 2], [0, 2], null], - [0, 1], - [0, 2], - true, - null, - ]) - }) - - test("match and matchAll preserve named, unmatched, and prototype-named index groups", async () => { - expect( - await value(` - const matched = "a".match(/(?a)|(?x)/d).indices.groups - const all = "a x".matchAll(/(?a)|(?x)/dg) - const namedMatch = "ab".match(/(?a)(?b)/d).indices.groups - const namedAll = "ab".matchAll(/(?a)(?b)/dg)[0].indices.groups - return [ - matched.a, - matched.x, - all[0].indices.groups.a, - all[0].indices.groups.x, - all[1].indices.groups.a, - all[1].indices.groups.x, - Object.keys(namedMatch), - Object.keys(namedAll), - ] - `), - ).toEqual([[0, 1], null, [0, 1], null, null, [2, 3], ["constructor", "safe"], ["constructor", "safe"]]) - }) - - test("v flag exposes unicodeSets and remains exclusive with u", async () => { - expect( - await value(` - const pattern = new RegExp("[a&&a]", "v") - let rejectsUV = false - try { - new RegExp(".", "uv") - } catch (error) { - rejectsUV = error.name === "SyntaxError" - } - return [pattern.unicodeSets, pattern.unicode, pattern.flags, pattern.test("a"), pattern.test("b"), rejectsUV] - `), - ).toEqual([true, false, "v", true, false, true]) - }) - - test("d and v flags compose", async () => { - expect( - await value(` - const pattern = new RegExp("(?[a&&a])", "dv") - const match = pattern.exec("a") - return [pattern.hasIndices, pattern.unicodeSets, pattern.flags, match.indices[0], match.indices.groups.a] - `), - ).toEqual([true, true, "dv", [0, 1], [0, 1]]) - }) -}) - -describe("Math.sumPrecise Test262 parity", () => { - test("performs maximally precise summation over supported iterables", async () => { - expect( - await value(` - return [ - Math.sumPrecise([1, 2, 3]), - Math.sumPrecise([1e30, 0.1, -1e30]), - Math.sumPrecise([1e308, 1e308, 0.1, 0.1, 1e30, 0.1, -1e30, -1e308, -1e308]), - Math.sumPrecise([8.98846567431158e307, 8.988465674311579e307, -1.7976931348623157e308]), - Math.sumPrecise(new Set([1, 2])), - [[1, 2], [3, 4]].map(Math.sumPrecise), - Object.is(Math.sumPrecise([]), -0), - Object.is(Math.sumPrecise([-0, -0]), -0), - Object.is(Math.sumPrecise([-0, 0]), 0), - ] - `), - ).toEqual([6, 0.1, 0.30000000000000004, 9.9792015476736e291, 3, [3, 7], true, true, true]) - }) - - test("handles infinities and NaN", async () => { - expect( - await value(` - return [ - Math.sumPrecise([Infinity, Infinity]) === Infinity, - Math.sumPrecise([-Infinity, -Infinity]) === -Infinity, - Number.isNaN(Math.sumPrecise([NaN])), - Number.isNaN(Math.sumPrecise([Infinity, -Infinity])), - ] - `), - ).toEqual([true, true, true, true]) - }) - - test("rejects missing, non-iterable, sparse, and non-number inputs", async () => { - expect( - await value(` - const rejects = (input, missing = false) => { - try { - if (missing) Math.sumPrecise() - else Math.sumPrecise(input) - return false - } catch (error) { - return error.name === "TypeError" - } - } - return [ - rejects(undefined, true), - rejects({}), - rejects(["1"]), - rejects(Array(1)), - rejects("12"), - rejects(new Map([[1, 2]])), - rejects(new URLSearchParams("a=1")), - ] - `), - ).toEqual([true, true, true, true, true, true, true]) - }) -}) diff --git a/packages/codemode/test/resumable.test.ts b/packages/codemode/test/resumable.test.ts deleted file mode 100644 index f24e32fd1b1..00000000000 --- a/packages/codemode/test/resumable.test.ts +++ /dev/null @@ -1,360 +0,0 @@ -import { describe, expect, test } from "bun:test" -import path from "node:path" -import { parseProgram } from "../src/language/runtime/execute.js" -import { Interpreter } from "../src/language/runtime/interpreter.js" -import { createBuiltins } from "../src/language/runtime/intrinsics.js" -import { getOwn, Native, nativeRule, Obj, remove, set } from "../src/language/runtime/objects.js" -import { CodeMode } from "../src/index.js" -import { decode, encode } from "../src/language/snapshot/codec.js" -import { Lost, PendingThrow } from "../src/language/runtime/model.js" -import { normalizeError } from "../src/language/runtime/errors.js" -import { Effect } from "effect" -import { nodeId, sourceOf } from "../src/language/runtime/source.js" - -// Groundwork for suspending and resuming a run: everything the state refers to has a stable name. - -const interpreter = () => - new Interpreter({ - builtins: createBuiltins(), - }) - -const parse = (code: string) => { - const parsed = parseProgram(code) - if (!parsed.ok) throw new Error(parsed.error.message) - return parsed -} - -describe("node ids", () => { - const code = `const add = (a, b) => a + b\nfor (const x of [1, 2]) { if (x) add(x, \`t\${x}\`) }\nreturn /a/g` - - test("number every node in pre-order and resolve back to it", () => { - const parsed = parse(code) - const nodes = parsed.source.nodes - expect(nodes[0]).toBe(parsed.program) - expect(nodes.map((node) => node.type).slice(0, 6)).toEqual([ - "Program", - "VariableDeclaration", - "VariableDeclarator", - "Identifier", - "ArrowFunctionExpression", - "Identifier", - ]) - nodes.forEach((node, index) => { - expect(nodeId(node)).toEqual({ source: "main", index }) - expect(parsed.source.node({ source: "main", index })).toBe(node) - expect(sourceOf(node)).toBe(parsed.source) - }) - }) - - test("give the same ids when the same code is parsed again", () => { - const first = parse(code).source.nodes - const second = parse(code).source.nodes - expect(second.map((node) => [node.type, node.start, node.end])).toEqual( - first.map((node) => [node.type, node.start, node.end]), - ) - }) - - test("do not resolve ids from another source", () => { - expect(parse(code).source.node({ source: "other", index: 0 })).toBeUndefined() - }) -}) - -describe("intrinsic names", () => { - test("name every intrinsic once, from the globals first", () => { - const names = interpreter().intrinsics - const all = names.all() - expect(new Set(all).size).toBe(all.length) - expect(new Set(names.values).size).toBe(names.values.length) - for (const name of [ - "Array.prototype.map", - "Promise.prototype.then", - "String.prototype[Symbol.iterator]", - "JSON.parse", - ]) { - expect(all).toContain(name) - } - for (const name of ["%Generator%", "%Generator%.next", "%AsyncGenerator%.return", "%IteratorHelper%.return"]) { - expect(all).toContain(name) - } - all.forEach((name, index) => { - expect(names.valueOf(name)).toBe(names.values[index]!) - expect(names.nameOf(names.values[index]!)).toBe(name) - }) - }) - - test("cover everything reachable from a named intrinsic", () => { - const names = interpreter().intrinsics - for (const value of names.values) { - for (const slot of value.props.values()) { - if ("value" in slot && slot.value instanceof Obj) expect(names.nameOf(slot.value)).toBeDefined() - } - if (value.proto !== null) expect(names.nameOf(value.proto)).toBeDefined() - } - expect(names.values.filter((value) => value instanceof Native).length).toBeGreaterThan(300) - }) - - test("are identical across fresh runtimes", () => { - const shape = (names: Interpreter["intrinsics"]) => - names.all().map((name, index) => { - const value = names.values[index]! - return [name, value.constructor.name, [...value.props.keys()].map(String)] - }) - expect(shape(interpreter().intrinsics)).toEqual(shape(interpreter().intrinsics)) - }) - - test("are taken before the program can change a built-in", () => { - const ctx = interpreter() - const map = ctx.intrinsics.valueOf("Array.prototype.map")! - const array = ctx.intrinsics.valueOf("Array.prototype")! - array.props.delete("map") - expect(ctx.intrinsics.nameOf(map)).toBe("Array.prototype.map") - }) - - test("only the intrinsics a write reaches are changed", () => { - const ctx = interpreter() - expect(ctx.intrinsics.changed()).toEqual([]) - const array = ctx.intrinsics.valueOf("Array.prototype")! - const math = ctx.intrinsics.valueOf("Math")! - set(array, "extra", 1) - remove(math, "max") - set(new Obj(array), "own", 1) - expect(ctx.intrinsics.changed().map((value) => ctx.intrinsics.nameOf(value))).toEqual(["Math", "Array.prototype"]) - }) -}) - -describe("natives only at intrinsic creation", () => { - test("every native made with the intrinsics has a name", () => { - const made: Array = [] - nativeRule.observe = (native) => made.push(native) - const ctx = (() => { - try { - return interpreter() - } finally { - nativeRule.observe = undefined - } - })() - expect(made.length).toBeGreaterThan(300) - expect( - made.filter((native) => ctx.intrinsics.nameOf(native) === undefined).map((native) => getOwn(native, "name")), - ).toEqual([]) - }) - - test("making a native once the program runs breaks the rule", () => { - const ctx = interpreter() - expect(() => new Native(ctx.builtins.Function, { name: "late", call: () => undefined })).toThrow( - 'Native "late" was made after the intrinsics', - ) - }) - - const value = async (code: string) => { - const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} })) - if (!result.ok) throw new Error(result.error.message) - return result.value - } - - test("bound functions and resolvers behave as functions", async () => { - expect( - await value(` - function add(a, b, c) { return [this?.k, a, b, c] } - const bound = add.bind({ k: 1 }, 2) - let resolve, reject - const promise = new Promise((res, rej) => { resolve = res; reject = rej }) - const thenable = await new Promise((res) => res({ then(a, b) { a([a.name, a.length, typeof b]) } })) - resolve(5) - reject(6) - return [bound.name, bound.length, typeof bound, bound(3, 4), bound.bind(null, 3).name, resolve.name, resolve.length, - reject.name, typeof resolve, await promise, thenable] - `), - ).toEqual([ - "bound add", - 2, - "function", - [1, 2, 3, 4], - "bound bound add", - "resolve", - 1, - "reject", - "function", - 5, - ["", 1, "function"], - ]) - }) -}) - -describe("heap as data", () => { - // Each program's result must match the host engine's. - const programs = { - "map iteration is live": ` - const m = new Map([[1, 1], [2, 2], [3, 3]]) - const out = [] - for (const [k] of m) { - out.push(k) - if (k === 1) { m.delete(2); m.set(4, 4) } - if (k === 3) { m.clear(); m.set(5, 5) } - } - return [out, [...m]]`, - "a live iterator survives compaction": ` - const m = new Map(Array.from({ length: 100 }, (_, i) => [i, i])) - const it = m.keys() - const seen = [] - for (let i = 0; i < 10; i++) seen.push(it.next().value) - for (let i = 0; i < 80; i++) m.delete(i) - seen.push(...it) - const s = new Set(Array.from({ length: 100 }, (_, i) => i)) - const values = s.values() - for (let i = 0; i < 50; i++) values.next() - for (let i = 50; i < 90; i++) s.delete(i) - for (let i = 0; i < 40; i++) s.delete(i) - return [seen, values.next().value, [...s].length, m.size]`, - "clear mid-iteration continues with new entries": ` - const s = new Set([1, 2, 3]) - const it = s.values() - const out = [it.next().value] - s.clear() - s.add(7) - out.push(...it) - s.add(8) - return [out, it.next().done, [...s.entries()]]`, - "keys compare by SameValueZero": ` - const s = new Set([-0, NaN, NaN, 0]) - const m = new Map([[-0, "a"]]) - return [s.size, 1 / [...s][0], 1 / [...m.keys()][0], m.get(0), s.has(NaN)]`, - "forEach visits entries added during the walk": ` - const m = new Map([["a", 1]]) - const out = [] - m.forEach((v, k) => { out.push(k); if (m.size < 4) m.set(k + "x", v + 1) }) - const s = new Set([1, 2, 3]) - const seen = [] - s.forEach((v) => { seen.push(v); s.delete(v + 1) }) - return [out, seen]`, - "set operations read the live table": ` - const a = new Set([1, 2, 3, 4]) - const other = { size: 10, has(v) { a.delete(v + 1); return true }, keys() { return [][Symbol.iterator]() } } - return [[...a.intersection(other)], [...a]]`, - "array, string and bytes iterators keep a position": ` - const a = [1, 2] - const it = a.values() - it.next() - a.push(3) - const rest = [...it] - a.push(4) - const done = it.next().done - const entries = [...[5, , 6].entries()] - return [rest, done, entries, [..."a😀b"], [...new Uint8Array([1, 2]).entries()], [...[7, 8].keys()]]`, - "headers and search params iterate the live sorted list": ` - const h = new Headers({ b: "1", d: "2" }) - const hk = h.keys() - const first = hk.next().value - h.append("a", "x") - h.append("c", "y") - const p = new URLSearchParams("b=1&d=2") - const pk = p.keys() - const pFirst = pk.next().value - p.append("a", "x") - p.delete("b") - return [first, [...hk], pFirst, [...pk], [...h.entries()], [...p]]`, - "a RegExp keeps lastIndex as a field shared with the String methods": ` - const r = /a/g - const out = [r.exec("aaa").index, r.lastIndex] - out.push("xaxa".replace(r, "b"), r.lastIndex) - r.lastIndex = 1 - out.push(r.test("ab"), r.lastIndex, r.test("ab"), r.lastIndex) - const y = /a/y - y.lastIndex = 1 - out.push("ba".search(y), y.lastIndex, "ba".match(y)?.[0], y.lastIndex, "ba".split(y), y.lastIndex) - r.lastIndex = 2 - out.push([..."aaaa".matchAll(r)].length, r.lastIndex, new RegExp(r).lastIndex, String(new RegExp(r, "i"))) - return out`, - } - - for (const [name, code] of Object.entries(programs)) { - test(name, async () => { - const expected: unknown = await new Function(`return (async () => {${code}})()`)() - const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} })) - if (!result.ok) throw new Error(result.error.message) - expect(result.value).toEqual(JSON.parse(JSON.stringify(expected))) - }) - } -}) - -describe("prelude", () => { - test("a run saved and restored while prelude built-ins run continues in their frames", async () => { - const child = Bun.spawn(["bun", path.join(import.meta.dir, "fixtures/prelude-roundtrip.ts")], { - stdout: "pipe", - stderr: "inherit", - }) - const output = JSON.parse(await new Response(child.stdout).text()) - expect(await child.exited).toBe(0) - expect(output.result).toMatchObject({ - ok: true, - value: [{ odd: [1, 3, 5], even: [2, 4, 6] }, [1, 2, 3, 7, 8], { a: [10, 20, { b: 30 }] }, 6], - }) - expect(output.saved).toBeGreaterThan(0) - }) - - test("prelude functions look like built-ins and are named by their path", () => { - const names = interpreter().intrinsics - const groupBy = names.valueOf("Object.groupBy")! - expect(getOwn(groupBy, "name")).toBe("groupBy") - expect(getOwn(groupBy, "length")).toBe(2) - expect(names.all()).toContain("%Prelude%.fillCollection") - expect(names.all()).toContain("%PreludeHelpers%.$Call") - }) - test("programs can't see the helpers or internal functions, and failures inside are located at the call", async () => { - const run = (code: string) => Effect.runPromise(CodeMode.execute({ code, tools: {} })) - expect(await run("return [typeof $Call, typeof $Throw, typeof fillCollection]")).toMatchObject({ - value: ["undefined", "undefined", "undefined"], - }) - expect(await run("const x = 1\nreturn Object.groupBy(null, (v) => v)")).toMatchObject({ - ok: false, - error: { location: { line: 2, column: 8 } }, - }) - }) -}) - -describe("lost values", () => { - const encodeEnv = (lost: Array) => ({ - nameOf: () => undefined, - unchanged: () => false, - anchorOf: () => undefined, - nodeId: () => undefined, - lost, - strict: false, - }) - const decodeEnv = { - named: () => undefined, - anchor: () => undefined, - node: () => undefined, - interruption: () => { - throw new Error("no interruption is saved") - }, - } - - test("a host function, a host object, and an unknown host error decode to what using a lost value throws", () => { - class Handle {} - class SocketError extends Error {} - const lost: Array = [] - const saved = encode( - [{ data: [1, "two", { three: 3 }], fn: () => 1, host: new Handle(), error: new SocketError("boom") }], - encodeEnv(lost), - ) - expect(lost).toEqual(["a host function", "a host Handle", "a host SocketError"]) - const [root] = decode(JSON.parse(JSON.stringify(saved)), decodeEnv) as [Record] - expect(root.data).toEqual([1, "two", { three: 3 }]) - expect(root.fn).toBeInstanceOf(Lost) - expect((root.fn as Lost).description).toBe("a host function") - expect(root.host).toBeInstanceOf(Lost) - expect((root.host as Lost).description).toBe("a host Handle") - expect(root.error).toBeInstanceOf(PendingThrow) - expect(normalizeError(root.error)).toEqual({ - kind: "ExecutionFailure", - message: - "TypeError: An error of class SocketError came from the host and was lost when the run was suspended; get it again after resuming.", - }) - // A restored placeholder saves and restores again the same way. - const again = decode(JSON.parse(JSON.stringify(encode([root], encodeEnv([])))), decodeEnv) as [ - Record, - ] - expect((again[0].fn as Lost).description).toBe("a host function") - }) -}) diff --git a/packages/codemode/test/run-program.ts b/packages/codemode/test/run-program.ts deleted file mode 100644 index 7b43a38dd6c..00000000000 --- a/packages/codemode/test/run-program.ts +++ /dev/null @@ -1,153 +0,0 @@ -import path from "node:path" -import { pathToFileURL } from "node:url" -import type { Program } from "acorn" -import type { Json as DataValue } from "../src/language/data.js" -import { normalizeError } from "../src/language/runtime/errors.js" -import { parseProgram } from "../src/language/runtime/execute.js" -import { createBuiltins } from "../src/language/runtime/intrinsics.js" -import { Interpreter } from "../src/language/runtime/interpreter.js" -import { type Diagnostic, PendingThrow } from "../src/language/runtime/model.js" -import type { Value } from "../src/language/runtime/objects.js" -import { Interruption } from "../src/language/runtime/signals.js" -import type { Source } from "../src/language/runtime/source.js" -import { fromBytes, type Snapshot, toBytes } from "../src/language/snapshot/snapshot.js" - -/** A quoted `file:` URL for a module relative to `test`, to import from a script run with `bun -e` on any platform. */ -export const moduleUrl = (relative: string) => JSON.stringify(pathToFileURL(path.join(import.meta.dir, relative)).href) - -/** How a run ended, shaped like a CodeMode result with no tool calls. */ -export type Result = - | { - readonly ok: true - readonly value: DataValue - readonly warnings?: ReadonlyArray - readonly logs?: ReadonlyArray - readonly toolCalls: ReadonlyArray - } - | { - readonly ok: false - readonly error: Diagnostic - readonly logs?: ReadonlyArray - readonly toolCalls: ReadonlyArray - } - -export type RunOptions = { - readonly globals?: (ctx: Interpreter) => ReadonlyArray - readonly bindings?: (ctx: Interpreter) => ReadonlyArray - readonly maxSlices?: number - /** - * Round-trip mode: slice after every `every` fuel ticks, then save the state to bytes and continue in a fresh runtime - * restored from it, at most `max` times (default 200). - */ - readonly roundTrip?: { readonly every: number; readonly max?: number } - /** Called with each snapshot round-trip mode takes. */ - readonly onTrip?: (snapshot: Snapshot) => void -} - -export const parseVmSource = ( - code: string, -): - | { readonly ok: true; readonly program: Program; readonly source: Source } - | { readonly ok: false; readonly error: Diagnostic } => { - if (code.trim().length === 0) { - return { ok: false, error: { kind: "ParseError", message: "Code cannot be empty." } } - } - try { - return parseProgram(code) - } catch (error) { - if (error instanceof RangeError) { - return { ok: false, error: normalizeError(error) } - } - throw error - } -} - -/** Runs a program on the VM synchronously, with no Effect and no tools: the VM tests' runner. */ -export const runProgram = (code: string, options?: RunOptions): Result => { - const parsed = parseVmSource(code) - if (!parsed.ok) { - return { ok: false, error: parsed.error, toolCalls: [] } - } - const runtime = (bindings: RunOptions["bindings"]) => - new Interpreter({ - builtins: createBuiltins(), - logs: [], - globals: options?.globals, - bindings, - }) - let ctx = runtime(options?.bindings) - let vm = ctx.vm - vm.start(parsed.source) - const roundTrip = options?.roundTrip - let trips = 0 - if (roundTrip !== undefined) vm.tripEvery = roundTrip.every - const maxSlices = options?.maxSlices ?? 5000 - let slices = 0 - while (true) { - const stop = vm.run() - if (stop.kind === "slice") { - if (roundTrip !== undefined && vm.tripEvery > 0) { - const { snapshot } = vm.capture({ strict: true }) - options?.onTrip?.(snapshot) - ctx = runtime(undefined) - vm = ctx.vm - vm.restore(fromBytes(toBytes(snapshot)), { - parse: (code) => { - const again = parseVmSource(code) - if (!again.ok) throw new Error(again.error.message) - return again.source - }, - interruption: () => { - throw new Error("No interruption is saved in round-trip mode.") - }, - }) - vm.tripEvery = ++trips < (roundTrip.max ?? 200) ? roundTrip.every : 0 - continue - } - if (++slices > maxSlices) { - return { - ok: false, - error: { kind: "TimeoutExceeded", message: "Execution timed out." }, - ...(ctx.logs.length > 0 ? { logs: [...ctx.logs] } : {}), - toolCalls: [], - } - } - continue - } - if (stop.kind === "done") { - const outcome = stop.completion - const logsPart = ctx.logs.length > 0 ? { logs: [...ctx.logs] } : {} - if (!outcome.ok) { - if (outcome.error instanceof Interruption) throw outcome.error - return { - ok: false, - error: normalizeError(outcome.error), - ...logsPart, - toolCalls: [], - } - } - const result = (outcome.value as DataValue | undefined) ?? null - const warnings = vm.diagnostics() - return { - ok: true, - value: result, - ...(warnings.length > 0 ? { warnings } : {}), - ...logsPart, - toolCalls: [], - } - } - const stuckNode = stop.kind === "stuck" ? stop.node : undefined - return { - ok: false, - error: normalizeError( - new PendingThrow( - "Error", - "The program is waiting on a promise that can never settle: nothing else is running, so nothing can resolve it. There are no timers or sleep, so don't wait or poll inside a program.", - stuckNode, - ), - ), - ...(ctx.logs.length > 0 ? { logs: [...ctx.logs] } : {}), - toolCalls: [], - } - } -} diff --git a/packages/codemode/test/set-methods-test262.test.ts b/packages/codemode/test/set-methods-test262.test.ts deleted file mode 100644 index 7d94aac1406..00000000000 --- a/packages/codemode/test/set-methods-test262.test.ts +++ /dev/null @@ -1,463 +0,0 @@ -/* - * Portions adapted from Test262 at revision 250f204f23a9249ff204be2baec29600faae7b75: - * - test/built-ins/Set/prototype/union/combines-sets.js - * - test/built-ins/Set/prototype/union/combines-empty-sets.js - * - test/built-ins/Set/prototype/union/combines-itself.js - * - test/built-ins/Set/prototype/union/combines-same-sets.js - * - test/built-ins/Set/prototype/union/combines-Map.js - * - test/built-ins/Set/prototype/union/result-order.js - * - test/built-ins/Set/prototype/union/appends-new-values.js - * - test/built-ins/Set/prototype/union/allows-set-like-object.js - * - test/built-ins/Set/prototype/union/size-is-a-number.js - * - test/built-ins/Set/prototype/union/has-is-callable.js - * - test/built-ins/Set/prototype/union/keys-is-callable.js - * - test/built-ins/Set/prototype/union/array-throws.js - * - test/built-ins/Set/prototype/union/converts-negative-zero.js - * - test/built-ins/Set/prototype/union/set-like-class-mutation.js - * - test/built-ins/Set/prototype/intersection/combines-sets.js - * - test/built-ins/Set/prototype/intersection/combines-itself.js - * - test/built-ins/Set/prototype/intersection/result-order.js - * - test/built-ins/Set/prototype/intersection/size-is-a-number.js - * - test/built-ins/Set/prototype/intersection/converts-negative-zero.js - * - test/built-ins/Set/prototype/intersection/combines-Map.js - * - test/built-ins/Set/prototype/intersection/allows-set-like-object.js - * - test/built-ins/Set/prototype/intersection/set-like-class-mutation.js - * - test/built-ins/Set/prototype/difference/combines-sets.js - * - test/built-ins/Set/prototype/difference/combines-itself.js - * - test/built-ins/Set/prototype/difference/result-order.js - * - test/built-ins/Set/prototype/difference/size-is-a-number.js - * - test/built-ins/Set/prototype/difference/converts-negative-zero.js - * - test/built-ins/Set/prototype/difference/combines-Map.js - * - test/built-ins/Set/prototype/difference/allows-set-like-object.js - * - test/built-ins/Set/prototype/difference/set-like-class-mutation.js - * - test/built-ins/Set/prototype/symmetricDifference/combines-sets.js - * - test/built-ins/Set/prototype/symmetricDifference/combines-itself.js - * - test/built-ins/Set/prototype/symmetricDifference/result-order.js - * - test/built-ins/Set/prototype/symmetricDifference/size-is-a-number.js - * - test/built-ins/Set/prototype/symmetricDifference/converts-negative-zero.js - * - test/built-ins/Set/prototype/symmetricDifference/set-like-class-mutation.js - * - test/built-ins/Set/prototype/symmetricDifference/combines-Map.js - * - test/built-ins/Set/prototype/symmetricDifference/allows-set-like-object.js - * - test/built-ins/Set/prototype/isSubsetOf/compares-sets.js - * - test/built-ins/Set/prototype/isSubsetOf/size-is-a-number.js - * - test/built-ins/Set/prototype/isSubsetOf/compares-Map.js - * - test/built-ins/Set/prototype/isSubsetOf/allows-set-like-object.js - * - test/built-ins/Set/prototype/isSubsetOf/compares-itself.js - * - test/built-ins/Set/prototype/isSubsetOf/compares-same-sets.js - * - test/built-ins/Set/prototype/isSubsetOf/set-like-class-mutation.js - * - test/built-ins/Set/prototype/isSupersetOf/compares-sets.js - * - test/built-ins/Set/prototype/isSupersetOf/size-is-a-number.js - * - test/built-ins/Set/prototype/isSupersetOf/compares-Map.js - * - test/built-ins/Set/prototype/isSupersetOf/allows-set-like-object.js - * - test/built-ins/Set/prototype/isSupersetOf/compares-itself.js - * - test/built-ins/Set/prototype/isSupersetOf/compares-same-sets.js - * - test/built-ins/Set/prototype/isSupersetOf/converts-negative-zero.js - * - test/built-ins/Set/prototype/isDisjointFrom/compares-sets.js - * - test/built-ins/Set/prototype/isDisjointFrom/size-is-a-number.js - * - test/built-ins/Set/prototype/isDisjointFrom/compares-Map.js - * - test/built-ins/Set/prototype/isDisjointFrom/allows-set-like-object.js - * - test/built-ins/Set/prototype/isDisjointFrom/compares-itself.js - * - test/built-ins/Set/prototype/isDisjointFrom/compares-same-sets.js - * - test/built-ins/Set/prototype/isDisjointFrom/converts-negative-zero.js - * - test/built-ins/Set/prototype/isDisjointFrom/set-like-class-mutation.js - * - * Copyright (C) 2023 Anthony Frehner. All rights reserved. - * Copyright (C) 2023 Anthony Frehner and Kevin Gibbons. All rights reserved. - * Copyright (C) 2023 Kevin Gibbons. All rights reserved. - * Copyright (C) 2023 Kevin Gibbons, Anthony Frehner. All rights reserved. - * Test262 portions are governed by the BSD license in LICENSE.test262. - * Set-like `keys` methods return arrays instead of iterator objects because - * CodeMode materializes supported iterators and does not support generators. - */ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" - -const value = async (code: string) => { - const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} })) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -describe("Set composition Test262 parity", () => { - test("combines Sets without mutating either operand", async () => { - expect( - await value(` - const left = new Set([1, 2]) - const right = new Set([2, 3]) - const union = left.union(right) - const intersection = left.intersection(right) - const difference = left.difference(right) - const symmetric = left.symmetricDifference(right) - return [ - [...union], union instanceof Set, - [...intersection], intersection instanceof Set, - [...difference], difference instanceof Set, - [...symmetric], symmetric instanceof Set, - [...left], [...right], - [...left.union(left)], left.union(left) !== left, - [...left.intersection(left)], left.intersection(left) !== left, - [...left.difference(left)], left.difference(left) !== left, - [...left.symmetricDifference(left)], left.symmetricDifference(left) !== left, - [...left.union(new Set())], [...new Set().union(left)], - ] - `), - ).toEqual([ - [1, 2, 3], - true, - [2], - true, - [1], - true, - [1, 3], - true, - [1, 2], - [2, 3], - [1, 2], - true, - [1, 2], - true, - [], - true, - [], - true, - [1, 2], - [1, 2], - ]) - }) - - test("preserves the specified result order", async () => { - expect( - await value(` - return [ - [...new Set([1, 3, 5]).intersection(new Set([3, 2, 1]))], - [...new Set([3, 2, 1, 0]).intersection(new Set([1, 3, 5]))], - [...new Set([1, 2, 3, 4]).difference(new Set([6, 5, 3, 2]))], - [...new Set([6, 5, 3, 2]).difference(new Set([1, 2, 3, 4]))], - [...new Set([1, 2, 3, 4]).symmetricDifference(new Set([6, 5, 4, 3]))], - [...new Set([2, 3]).union(new Set([1, 2]))], - [...new Set([1, 2, -3]).union(new Set([-1, 0]))], - ] - `), - ).toEqual([ - [1, 3], - [1, 3], - [1, 4], - [6, 5], - [1, 2, 6, 5], - [2, 3, 1], - [1, 2, -3, -1, 0], - ]) - }) - - test("accepts Maps as Set-like operands", async () => { - expect( - await value(` - const set = new Set([1, 2]) - const map = new Map([[2, "two"], [3, "three"]]) - return [ - [...set.union(map)], - [...set.intersection(map)], - [...set.difference(map)], - [...set.symmetricDifference(map)], - ] - `), - ).toEqual([[1, 2, 3], [2], [1], [1, 3]]) - }) - - test("accepts supported Set-like objects and uses the size-selected method", async () => { - expect( - await value(` - const keysOnly = { - size: 1, - has: () => { throw new Error("has should not be called") }, - keys: () => [2, 3], - } - const hasOnly = { - size: 2, - has: (value) => value === 2, - keys: () => { throw new Error("keys should not be called") }, - } - const set = new Set([1, 2]) - return [ - [...set.union(keysOnly)], - [...set.intersection(hasOnly)], - [...set.difference(hasOnly)], - [...set.symmetricDifference(keysOnly)], - ] - `), - ).toEqual([[1, 2, 3], [2], [1], [1, 3]]) - }) - - test("normalizes negative zero", async () => { - expect( - await value(` - const setlike = { - size: 1, - has: () => { throw new Error("has should not be called") }, - keys: () => [-0], - } - return [ - 1 / [...new Set([1]).union(setlike)][1] === Infinity, - 1 / [...new Set([0, 1, 2]).intersection(setlike)][0] === Infinity, - [...new Set([0, 1]).difference(setlike)], - 1 / [...new Set([1, 2]).symmetricDifference(setlike)][2] === Infinity, - ] - `), - ).toEqual([true, true, [1], true]) - }) - - test("handles duplicate Set-like keys using receiver membership", async () => { - expect( - await value(` - const other = { - size: 4, - has: () => { throw new Error("has should not be called") }, - keys: () => [2, 2, 3, 3], - } - return [...new Set([1, 2]).symmetricDifference(other)] - `), - ).toEqual([1, 3]) - }) - - test("copies receiver data before Set-like key iteration mutates it", async () => { - expect( - await value(` - const unionBase = new Set(["a", "b", "c", "d", "e"]) - const unionOther = { - size: 2, - has: () => { throw new Error("has should not be called") }, - keys: () => { - unionBase.delete("b") - unionBase.delete("c") - unionBase.add("b") - return ["x", "y"] - }, - } - const union = unionBase.union(unionOther) - - const intersectionBase = new Set(["a", "b", "c", "d", "e"]) - const intersectionOther = { - size: 3, - has: () => { throw new Error("has should not be called") }, - keys: () => { - intersectionBase.delete("b") - intersectionBase.delete("c") - intersectionBase.add("b") - return ["x", "b", "b"] - }, - } - const intersection = intersectionBase.intersection(intersectionOther) - - const differenceBase = new Set(["a", "b", "c", "d", "e"]) - const differenceOther = { - size: 3, - has: () => { throw new Error("has should not be called") }, - keys: () => { - differenceBase.delete("b") - differenceBase.delete("c") - differenceBase.add("b") - return ["x", "b", "b"] - }, - } - const difference = differenceBase.difference(differenceOther) - - const symmetricBase = new Set(["a", "b", "c", "d", "e"]) - const symmetricOther = { - size: 4, - has: () => { throw new Error("has should not be called") }, - keys: () => { - symmetricBase.delete("b") - symmetricBase.delete("c") - symmetricBase.add("b") - return ["x", "b", "c", "c"] - }, - } - const symmetric = symmetricBase.symmetricDifference(symmetricOther) - - return [ - [...union], [...unionBase], - [...intersection], [...intersectionBase], - [...difference], [...differenceBase], - [...symmetric], [...symmetricBase], - ] - `), - ).toEqual([ - ["a", "b", "c", "d", "e", "x", "y"], - ["a", "d", "e", "b"], - ["b"], - ["a", "d", "e", "b"], - ["a", "c", "d", "e"], - ["a", "d", "e", "b"], - ["a", "c", "d", "e", "x"], - ["a", "d", "e", "b"], - ]) - }) -}) - -describe("Set relation Test262 parity", () => { - test("compares Sets", async () => { - expect( - await value(` - const set = new Set([1, 2]) - return [ - set.isSubsetOf(new Set([2, 3])), set.isSubsetOf(new Set([1, 2, 3])), - set.isSupersetOf(new Set([2, 3])), set.isSupersetOf(new Set([1])), - set.isDisjointFrom(new Set([2, 3])), set.isDisjointFrom(new Set([3])), - new Set().isSubsetOf(set), set.isSupersetOf(new Set()), new Set().isDisjointFrom(new Set()), - set.isSubsetOf(set), set.isSupersetOf(set), set.isDisjointFrom(set), - set.isSubsetOf(new Set([1, 2])), set.isSupersetOf(new Set([1, 2])), - ] - `), - ).toEqual([false, true, false, true, false, true, true, true, true, true, true, false, true, true]) - }) - - test("compares Maps and supported Set-like objects", async () => { - expect( - await value(` - const set = new Set([1, 2]) - const map = new Map([[1, "one"], [2, "two"], [3, "three"]]) - const hasOnly = { - size: 2, - has: (value) => value === 1 || value === 2, - keys: () => { throw new Error("keys should not be called") }, - } - const keysOnly = { - size: 1, - has: () => { throw new Error("has should not be called") }, - keys: () => [1], - } - return [ - set.isSubsetOf(map), set.isSupersetOf(map), set.isDisjointFrom(map), - set.isSubsetOf(hasOnly), set.isSupersetOf(keysOnly), set.isDisjointFrom(hasOnly), - ] - `), - ).toEqual([true, false, false, true, true, false]) - }) - - test("normalizes negative zero from Set-like keys", async () => { - expect( - await value(` - const setlike = { - size: 1, - has: () => { throw new Error("has should not be called") }, - keys: () => [-0], - } - return [ - new Set([0, 1]).isSupersetOf(setlike), - new Set([0, 1]).isDisjointFrom(setlike), - ] - `), - ).toEqual([true, false]) - }) - - test("observes live receiver mutation while calling Set-like has", async () => { - expect( - await value(` - const subset = new Set(["a", "b", "c"]) - const subsetOther = { - size: 3, - has: (item) => { - if (item === "a") subset.delete("c") - return ["x", "a", "b"].includes(item) - }, - keys: () => { throw new Error("keys should not be called") }, - } - const disjoint = new Set(["a", "b", "c"]) - const disjointOther = { - size: 3, - has: (item) => { - if (item === "a") { - disjoint.delete("b") - disjoint.delete("c") - disjoint.add("b") - } - if (item === "c") throw new Error("deleted value should not be visited") - return false - }, - keys: () => { throw new Error("keys should not be called") }, - } - return [ - subset.isSubsetOf(subsetOther), [...subset], - disjoint.isDisjointFrom(disjointOther), [...disjoint], - ] - `), - ).toEqual([true, ["a", "b"], true, ["a", "b"]]) - }) -}) - -describe("Set-like validation Test262 parity", () => { - test("rejects arrays, invalid sizes, and non-callable methods with TypeError", async () => { - expect( - await value(` - const set = new Set([1]) - const names = [] - let coercionCalls = 0 - const invalid = [ - [], - { size: undefined, has: () => false, keys: () => [] }, - { size: NaN, has: () => false, keys: () => [] }, - { size: { valueOf: () => { coercionCalls += 1; return NaN } }, has: () => false, keys: () => [] }, - { size: "string", has: () => false, keys: () => [] }, - { size: 0, has: undefined, keys: () => [] }, - { size: 0, has: {}, keys: () => [] }, - { size: 0, has: () => false, keys: undefined }, - { size: 0, has: () => false, keys: {} }, - ] - for (const other of invalid) { - try { set.union(other) } catch (error) { names.push(error.name) } - } - return [names, coercionCalls] - `), - ).toEqual([ - [ - "TypeError", - "TypeError", - "TypeError", - "TypeError", - "TypeError", - "TypeError", - "TypeError", - "TypeError", - "TypeError", - ], - 1, - ]) - }) - - test("validates Set-like records for every method", async () => { - expect( - await value(` - const set = new Set([1]) - const invalid = { size: NaN, has: () => false, keys: () => [] } - const names = [] - const operations = [ - () => set.union(invalid), - () => set.intersection(invalid), - () => set.difference(invalid), - () => set.symmetricDifference(invalid), - () => set.isSubsetOf(invalid), - () => set.isSupersetOf(invalid), - () => set.isDisjointFrom(invalid), - ] - for (const operation of operations) { - try { operation() } catch (error) { names.push(error.name) } - } - return names - `), - ).toEqual(["TypeError", "TypeError", "TypeError", "TypeError", "TypeError", "TypeError", "TypeError"]) - }) - - test("requires Set-like keys to return CodeMode's materialized iterator representation", async () => { - expect( - await value(` - const set = new Set([1]) - const names = [] - for (const keys of [() => "ab", () => new Set([2]), () => new Map([[2, true]])]) { - try { set.union({ size: 1, has: () => false, keys }) } catch (error) { names.push(error.name) } - } - return names - `), - ).toEqual(["TypeError", "TypeError", "TypeError"]) - }) -}) diff --git a/packages/codemode/test/snapshot.test.ts b/packages/codemode/test/snapshot.test.ts deleted file mode 100644 index 7c537054f05..00000000000 --- a/packages/codemode/test/snapshot.test.ts +++ /dev/null @@ -1,311 +0,0 @@ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" -import { createBuiltins } from "../src/language/runtime/intrinsics.js" -import { Interpreter } from "../src/language/runtime/interpreter.js" -import { type Snapshot, SnapshotError } from "../src/language/snapshot/snapshot.js" -import { hashOf } from "../src/language/code.js" -import { compileSource } from "../src/language/compiler/compile.js" -import { moduleUrl, parseVmSource, runProgram } from "./run-program.js" -import { buildId } from "../src/language/snapshot.js" - -// The VM's snapshots: a run saved and restored into a fresh runtime anywhere it slices goes on as if it never stopped. - -const programs: Record = { - "a UTF-8 decoder with unread bytes after a fatal stream error": ` - const decoder = new TextDecoder('utf8', { fatal: true }) - try { decoder.decode(new Uint8Array([255, 65, 66, 67, 68]), { stream: true }) } - catch (error) { return [error.name, decoder.decode()] }`, - "a UTF-8 decoder with pending bytes and a consumed BOM": ` - const decoder = new TextDecoder('utf8', { fatal: true }) - const start = decoder.decode(new Uint8Array([0xef, 0xbb, 0xbf, 0xef]), { stream: true }) - return [start, decoder.decode(new Uint8Array([0xbb, 0xbf]))]`, - "a Buffer keeps its type and bytes": ` - const buffer = Buffer.from("héllo") - let total = 0 - for (const byte of buffer) total += byte - return [Buffer.isBuffer(buffer), buffer.toString(), buffer.toString("base64"), total]`, - "closures over per-iteration bindings": ` - const fns = [] - for (let i = 0; i < 5; i++) fns.push(() => i * 2) - let total = 0 - for (const f of fns) total += f() - return [fns.map((f) => f()), total]`, - "recursion several frames deep": ` - function fib(n) { return n < 2 ? n : fib(n - 1) + fib(n - 2) } - const walk = (node, depth) => node === null ? depth : walk(node.next, depth + 1) - return [fib(12), walk({ next: { next: { next: null } } }, 0)]`, - "finally levels, labels and pending returns": ` - const out = [] - function f(x) { - try { - try { if (x > 1) return "r" + x; out.push("t" + x) } finally { out.push("inner" + x) } - } finally { - out.push("outer" + x) - for (let i = 0; i < 2; i++) out.push("loop" + i) - } - return "n" + x - } - outer: for (let i = 0; i < 4; i++) { - for (let j = 0; j < 3; j++) { - try { if (j === 1) continue outer; if (i === 3) break outer } finally { out.push(i + ":" + j) } - } - } - return [f(1), f(2), out]`, - "a custom iterator in mid-iteration, and destructuring": ` - const log = [] - const it = { i: 0, [Symbol.iterator]() { return this }, next() { this.i++; return { value: this.i, done: this.i > 4 } }, return() { log.push("closed"); return {} } } - for (const x of it) { log.push(x); if (x === 3) break } - const [a, b = a * 10, ...rest] = [1, undefined, 3, 4] - const { p, q: { r = 5 } = {}, ...others } = { p: 1, s: 2, t: 3 } - return [log, a, b, rest, p, r, others]`, - "a tagged template keeps its strings object": ` - const seen = new Set() - const tag = (strings, ...values) => { seen.add(strings); return strings.raw.join("|") + values.join(",") } - let text = "" - for (let i = 0; i < 4; i++) text += tag\`a\${i}b\` - return [text, seen.size]`, - "prelude callbacks and sorts are interrupted and continue": ` - const xs = Array.from({ length: 30 }, (_, i) => (i * 7) % 30) - const sorted = [...xs].sort((a, b) => a - b) - const groups = Object.groupBy(xs, (x) => (x % 3 === 0 ? "three" : "other")) - const mapped = xs.map((x) => x * 2).filter((x) => x % 4 === 0).reduce((a, b) => a + b, 0) - return [sorted, groups.three.length, mapped, new Map(xs.map((x) => [x, x])).size]`, - "JSON with toJSON, replacers and revivers": ` - const value = { a: [1, { b: 2, toJSON() { return { c: 3 } } }], d: new Date(0) } - const text = JSON.stringify(value, (k, v) => (typeof v === "number" ? v + 1 : v), 2) - return [text, JSON.parse('{"a":[1,2,{"b":3}]}', (k, v) => (typeof v === "number" ? v * 10 : v))]`, - "errors keep their types and locations": ` - const caught = [] - for (let i = 0; i < 3; i++) { - try { if (i === 0) null.x; if (i === 1) undefinedName; if (i === 2) throw new RangeError("r" + i) } - catch (e) { caught.push(e.name + ": " + e.message) } - } - return caught`, - "implicit conversions run program code": ` - let calls = 0 - const o = { valueOf() { calls++; return 2 }, toString() { calls++; return "k" } } - const t = {} - t[o] = 1 - return [o + 1, o * o, \`\${o}\`, t.k, calls, String(o).padStart(3, "-")]`, - "logs and changed built-ins survive": ` - Array.prototype.extra = function () { return this.length } - Object.freeze(Math) - for (let i = 0; i < 3; i++) console.log("line", i) - return [[1, 2, 3].extra(), Object.isFrozen(Math)]`, - "an error's stack, made before a slice and read after": ` - function make() { return new TypeError("bad") } - const made = make() - let caught - try { null.x } catch (error) { caught = error } - for (let i = 0; i < 5; i++) await null - return [made.stack, caught.stack]`, - "an error's stack header, named after a slice and read after another": ` - const unread = new Error("bad") - const read = new Error("worse") - read.stack - for (let i = 0; i < 3; i++) await null - unread.name = "Late" - read.name = "Late" - for (let i = 0; i < 3; i++) await null - return [unread.stack, read.stack]`, - "the program's result is copied out after a slice in the boundary walk": ` - const rows = [] - for (let i = 0; i < 5; i++) rows.push({ i, toJSON() { return { row: this.i } } }) - return rows`, -} - -describe("round trips", () => { - for (const [name, code] of Object.entries(programs)) { - test(name, () => { - const straight = runProgram(code) - expect(straight.ok).toBe(true) - let trips = 0 - const tripped = runProgram(code, { roundTrip: { every: 1, max: 1000 }, onTrip: () => trips++ }) - expect(tripped).toEqual(straight) - expect(trips).toBeGreaterThan(0) - }) - } - - test("a failing program fails the same way, at the same place", () => { - const code = `let s = 0\nfor (let i = 0; i < 10; i++) s += i\nconst o = null\nreturn o.missing` - const straight = runProgram(code) - expect(straight.ok).toBe(false) - expect(runProgram(code, { roundTrip: { every: 1 } })).toEqual(straight) - }) -}) - -/** A runtime the way `execute.ts` makes one, with no tools. */ -const runtime = () => - new Interpreter({ - builtins: createBuiltins(), - }) as Interpreter - -const parse = (code: string) => { - const parsed = parseVmSource(code) - if (!parsed.ok) throw new Error(parsed.error.message) - return parsed.source -} - -const restoreOptions = { - parse, - interruption: () => { - throw new Error("no interruption") - }, -} - -/** A snapshot as JSON, to tamper with. */ -type Saved = { - readonly format: number - readonly header: Snapshot["header"] - readonly records: Array<{ readonly t: string; readonly f: Array }> -} - -/** A VM sliced once inside a loop, and its state. */ -const sliced = (code = `let n = 0\nfor (let i = 0; i < 10; i++) { try { n += i } finally { n += 0 } }\nreturn n`) => { - const vm = runtime().vm - vm.start(parse(code)) - vm.tripEvery = 3 - expect(vm.run().kind).toBe("slice") - const { snapshot, lost } = vm.capture({ strict: true }) - expect(lost).toEqual([]) - return JSON.parse(JSON.stringify(snapshot)) as Saved -} - -const frameOf = (snapshot: ReturnType) => snapshot.records.find((record) => record.t === "Frame")! - -/** A saved frame's registers, a record of their own. */ -const regsOf = (snapshot: ReturnType) => { - const ref = frameOf(snapshot).f[4] as [string, number] - return (snapshot.records[ref[1]] as unknown as { v: Array }).v -} - -const refusal = (snapshot: unknown) => { - try { - runtime().vm.restore(snapshot, restoreOptions) - } catch (error) { - expect(error).toBeInstanceOf(SnapshotError) - return (error as Error).message - } - throw new Error("the snapshot was restored") -} - -describe("snapshots", () => { - test("hold code by source and function index, with the source's bytecode hash, and never bytecode", () => { - const snapshot = sliced() - expect(snapshot.format).toBe(3) - const source = snapshot.header.sources[0]! - expect(source.id).toBe("main") - expect(source.bytecode).toBe(hashOf(compileSource(parse(source.code)))) - const frame = frameOf(snapshot) - expect(frame.f[1]).toEqual(["x", ["code", "main", 0]]) - expect(JSON.stringify(snapshot)).not.toContain('"code":[') - }) - - test("a restored VM runs to the same result", () => { - const vm = runtime().vm - vm.restore(sliced(), restoreOptions) - const stop = vm.run() - expect(stop).toEqual({ kind: "done", completion: { ok: true, value: 45 } }) - }) - - test("capturing changes nothing the run sees", () => { - const vm = runtime().vm - vm.start(parse(`let n = 0\nfor (let i = 0; i < 10; i++) n += i\nreturn n`)) - vm.tripEvery = 2 - for (let stop = vm.run(); ; stop = vm.run()) { - if (stop.kind !== "slice") { - expect(stop).toEqual({ kind: "done", completion: { ok: true, value: 45 } }) - break - } - vm.capture({ strict: true }) - } - }) - - test("the build id is stable", () => { - expect(buildId()).toBe(buildId()) - }) - - test("are refused by another build, or when a source compiles to other bytecode", () => { - expect(refusal({ ...sliced(), header: { ...sliced().header, build: "0.0.0+0" } })).toContain( - "another Code Mode build", - ) - const snapshot = sliced() - const sources = [{ ...snapshot.header.sources[0]!, bytecode: "0000000000000000" }] - expect(refusal({ ...snapshot, header: { ...snapshot.header, sources } })).toContain("other bytecode") - }) - - test("check every frame against its code before anything runs", () => { - const tamper = (change: (frame: Array) => void) => { - const snapshot = sliced() - change(frameOf(snapshot).f) - return refusal(snapshot) - } - expect(tamper((frame) => (frame[2] = 100_000))).toContain("pc") - expect(tamper((frame) => (frame[2] = 1.5))).toContain("pc") - expect(tamper((frame) => (frame[3] = 0))).toContain("stack pointer") - expect(tamper((frame) => (frame[7] = 99))).toContain("mode") - expect(tamper((frame) => (frame[1] = ["x", ["code", "main", 99]]))).toContain("unknown external value") - }) - - test("a hole on the operand stack is refused", () => { - const vm = runtime().vm - vm.start( - parse(`function f(a, b) { return a + b }\nlet s = 0\nfor (let i = 0; i < 3; i++) s = s + f(i, 1)\nreturn s`), - ) - vm.tripEvery = 1 - expect(vm.run().kind).toBe("slice") - const snapshot = JSON.parse(JSON.stringify(vm.capture({ strict: true }).snapshot)) - const regs = regsOf(snapshot) - const code = compileSource(parse(snapshot.header.sources[0].code))[0]! - expect(regs.length).toBeGreaterThan(code.locals) - regs[regs.length - 1] = ["x", "hole"] - expect(refusal(snapshot)).toContain("hole") - }) - - test("a finally tag out of range is refused", () => { - const snapshot = sliced() - const code = compileSource(parse(snapshot.header.sources[0]!.code))[0]! - regsOf(snapshot)[code.finallies[code.finallyOffsets[0]!]!] = 50 - expect(refusal(snapshot)).toContain("finally tag") - }) -}) - -describe("suspend", () => { - test("a sync program suspended mid-loop resumes where it stopped, in a new runtime", async () => { - const runtime = CodeMode.make({ tools: {} }) - const code = ` - const seen = [] - let n = 0 - for (let i = 0; i < 400_000; i++) { n = (n + i) % 1_000_003; if (i % 100_000 === 0) seen.push(i) } - return [n, seen]` - const expected = await Effect.runPromise(runtime.execute(code)) - const program = runtime.program(code) - const run = Effect.runPromise(program.run()) - await new Promise((done) => setTimeout(done, 5)) - const suspended = await Effect.runPromise(program.suspend()) - if (suspended.ok !== "suspended") throw new Error("the run ended before it could be suspended") - expect(await run).toBe(suspended) - expect(await Effect.runPromise(runtime.resume(suspended.state).run())).toEqual(expected) - }) -}) - -describe("determinism", () => { - test("another process compiles the same bytecode and has the same build id", async () => { - const codes = Object.values(programs) - const local = { hashes: codes.map((code) => hashOf(compileSource(parse(code)))), build: (runtime(), buildId()) } - const script = ` - import { hashOf } from ${moduleUrl("../src/language/code.js")} - import { compileSource } from ${moduleUrl("../src/language/compiler/compile.js")} - import { parseVmSource } from ${moduleUrl("run-program.js")} - import { buildId } from ${moduleUrl("../src/language/snapshot.js")} - import { createBuiltins } from ${moduleUrl("../src/language/runtime/intrinsics.js")} - import { Interpreter } from ${moduleUrl("../src/language/runtime/interpreter.js")} - new Interpreter({ builtins: createBuiltins() }) - const codes = ${JSON.stringify(codes)} - console.log(JSON.stringify({ hashes: codes.map((code) => hashOf(compileSource(parseVmSource(code).source))), build: buildId() }))` - const child = Bun.spawn(["bun", "-e", script], { stdout: "pipe", stderr: "inherit" }) - expect(JSON.parse(await new Response(child.stdout).text())).toEqual(local) - expect(await child.exited).toBe(0) - }) -}) diff --git a/packages/codemode/test/state.test.ts b/packages/codemode/test/state.test.ts deleted file mode 100644 index 5f53bd1e636..00000000000 --- a/packages/codemode/test/state.test.ts +++ /dev/null @@ -1,501 +0,0 @@ -import { describe, expect, test } from "bun:test" -import { Glob } from "bun" -import path from "node:path" -import { Effect, Schema } from "effect" -import { CodeMode, Tool } from "../src/index.js" -import { Host } from "../src/language/host-function.js" -import { parseProgram } from "../src/language/runtime/execute.js" -import { hostGlobals } from "../src/language/runtime/extensions.js" -import { Interpreter } from "../src/language/runtime/interpreter.js" -import { createBuiltins } from "../src/language/runtime/intrinsics.js" -import { GeneratorObj, type Native, nativeRule, Obj, PromiseObj, type Value } from "../src/language/runtime/objects.js" -import { normal } from "../src/language/runtime/signals.js" -import { Code } from "../src/language/code.js" -import { AsyncFromSyncIterator } from "../src/language/generators.js" -import { VmIntrinsic } from "../src/language/internal-prelude.js" -import { Cell, CodeFlags } from "../src/language/opcodes.js" -import type { Stop } from "../src/language/scheduler.js" -import { CustomIter, Frame, Mode, Vm } from "../src/language/vm.js" - -// The VM (`src/vm.ts`) runs programs as bytecode frames, and keeps the jobs, promises, and host calls they wait on as -// data: a frame is its code, pc, and registers, and every suspension point is one. The Effect driver only does what -// the VM's stops ask. - -const runtimeTools = { - echo: Tool.make({ - description: "Echo a value", - input: Schema.Struct({ value: Schema.Number }), - output: Schema.Number, - execute: ({ value }) => Effect.succeed(value), - }), -} - -const runtime = CodeMode.make({ tools: runtimeTools }) - -const run = (code: string) => Effect.runPromise(runtime.execute(code)) - -const value = async (code: string) => { - const result = await run(code) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -const error = async (code: string) => { - const result = await run(code) - if (result.ok) throw new Error(`expected failure, got value ${JSON.stringify(result.value)}`) - return result.error -} - -// Host globals for a VM stepped by hand: the test completes their calls itself. -const echo = Host.fn(([input]) => (input as { value: number }).value, { type: "async" }) -const vmGlobals = { - tools: Host.namespace({ - keys: () => ["echo"], - resolve: (path) => (path.join(".") === "echo" ? echo : Host.missing(`No tools.${path.join(".")}`)), - }), - search: Host.fn(() => Effect.succeed({ items: [] }), { type: "sync-thenable" }), -} - -// A VM for `code`, stepped by hand instead of by the Effect driver. -const vmFor = (code: string) => { - const parsed = parseProgram(code) - if (!parsed.ok) throw new Error(parsed.error.message) - const vm = new Interpreter({ builtins: createBuiltins(), globals: (ctx) => hostGlobals(ctx, vmGlobals) }).vm - vm.start(parsed.source) - return vm -} - -// The next stop that is not a slice. -const stop = (vm: Vm): Stop => { - for (;;) { - const next = vm.run() - if (next.kind !== "slice") return next - } -} - -const parked = (vm: Vm) => [...vm.scheduler.parked.keys()] - -// The value bound to `name` in the program's body, once it is parked at an `await`. -const programBinding = (vm: Vm, name: string): Value => { - const program = parked(vm).find((frame) => frame.mode === Mode.PROGRAM)! - const slot = program.code.localNames.indexOf(name) - const value = program.regs[slot] - return (value instanceof Cell ? value.v : value) as Value -} - -// Throws unless `value` is plain data: no host function or generator is reachable from it. Program values, AST -// nodes, bytecode (immutable, shared by every run), the VM's own records (back-references from what settles a -// promise), and its internal intrinsics (saved by name) are data of their own. -const requireData = (value: unknown, path: string, seen: Set): void => { - if (typeof value === "function") throw new Error(`a host function at ${path}`) - if (value === null || typeof value !== "object" || seen.has(value)) return - seen.add(value) - if (value instanceof Obj || value instanceof Code || value instanceof Vm || value instanceof VmIntrinsic) return - if (value === (value as { vm?: unknown }).vm) return - if (ArrayBuffer.isView(value)) return - const node = value as { type?: unknown; start?: unknown } - if (typeof node.type === "string" && typeof node.start === "number") return - const generator = value as { next?: unknown; throw?: unknown } - if (typeof generator.next === "function" && typeof generator.throw === "function") { - throw new Error(`a host generator at ${path}`) - } - const entries = value instanceof Map ? [...value] : Object.entries(value) - for (const [key, item] of entries) requireData(item, `${path}.${String(key)}`, seen) -} - -// Frames as saved state: every one a `Frame` whose registers, up to its stack pointer, are plain data. -const expectData = (frames: ReadonlyArray) => { - expect(frames.length).toBeGreaterThan(0) - for (const frame of frames) { - expect(frame).toBeInstanceOf(Frame) - expect(frame.pc).toBeLessThan(frame.code.code.length) - requireData({ ...frame, regs: frame.regs.slice(0, frame.sp) }, "frame", new Set()) - } -} - -describe("vm", () => { - test("runs programs as bytecode frames", async () => { - expect(await value(`const f = (n) => (n < 2 ? n : f(n - 1) + f(n - 2)); return f(12)`)).toBe(144) - }) - - test("try/catch/finally around program calls, with finally overriding the completion", async () => { - expect( - await value(` - const boom = () => { throw new Error("boom") } - const log = [] - const f = () => { try { boom() } catch (e) { log.push(e.message); return "caught" } finally { log.push("finally") } } - const g = () => { try { return f() } finally { return "override" } } - return [g(), log] - `), - ).toEqual(["override", ["boom", "finally"]]) - }) - - test("a failure in a for...of body closes the iterator and keeps the failure", async () => { - expect( - await value(` - const log = [] - const iterable = { [Symbol.iterator]() { - let i = 0 - return { next: () => ({ done: i > 3, value: i++ }), return: () => { log.push("closed"); return {} } } - } } - const check = (x) => { if (x === 2) throw new Error("at " + x) } - try { for (const x of iterable) { log.push(x); check(x) } } catch (e) { log.push(e.message) } - for (const x of iterable) { if (x === 1) break } - return log - `), - ).toEqual([0, 1, 2, "closed", "at 2", "closed"]) - }) - - test("array destructuring closes a custom iterator when a default throws", async () => { - expect( - await value(` - const log = [] - const iterable = { [Symbol.iterator]() { - return { next: () => ({ done: false, value: undefined }), return: () => { log.push("closed"); return {} } } - } } - const fail = () => { throw new Error("default") } - try { const [a = fail()] = iterable } catch (e) { log.push(e.message) } - const [b = 1, c = 2] = iterable - return [log, b, c] - `), - ).toEqual([["closed", "default", "closed"], 1, 2]) - }) - - test("labels, switch, and per-iteration bindings across program calls", async () => { - expect( - await value(` - const id = (x) => x - const out = [] - outer: for (let i = 0; i < 3; i++) { - for (let j = 0; j < 3; j++) { - if (id(j) === 1) continue outer - switch (id(i)) { case id(0): out.push("zero"); break; case 1: out.push("one"); default: out.push("d") } - } - } - const fns = [] - for (let i = 0; i < 3; i++) fns.push(() => id(i)) - return [out, fns.map((f) => f())] - `), - ).toEqual([ - ["zero", "one", "d", "d"], - [0, 1, 2], - ]) - }) - - test("conversions call program valueOf and toString", async () => { - expect( - await value(` - const v = { valueOf: () => 2, toString: () => "key" } - const o = { [v]: 1 } - return [v + 1, \`\${v}\`, o.key, "key" in o, v * v, -v] - `), - ).toEqual([3, "key", 1, true, 4, -2]) - }) - - test("generators, async functions, and tools run on the VM", async () => { - expect( - await value(` - const log = [] - function* g() { try { yield 1; yield 2 } finally { log.push("done") } } - const it = g() - it.next() - it.return(5) - const twice = async (x) => (await tools.echo({ value: x })) * 2 - const all = await Promise.all([1, 2, 3].map(twice)) - return [log, [...g()], all] - `), - ).toEqual([ - ["done", "done"], - [1, 2], - [2, 4, 6], - ]) - }) - - test("runaway recursion stops with the location of the call that overflowed", async () => { - expect((await error(`const f = (n) => f(n + 1); return f(0)`)).message).toBe( - "RangeError: Maximum call stack size exceeded (line 1, col 18)", - ) - }) - - test("a run advances in steps: sliced at every tick, it stops many times and ends the same", () => { - const code = `let s = 0; for (let i = 0; i < 50; i++) s += [i].map((x) => x * 2)[0]; return s` - const vm = vmFor(code) - vm.tripEvery = 1 - let slices = 0 - let next = vm.run() - for (; next.kind === "slice"; next = vm.run()) slices++ - expect(slices).toBeGreaterThan(100) - expect(next).toEqual({ kind: "done", completion: normal(2450) }) - }) - - // Sorting 300,000 strings (to cross multiple 65,536-item merge steps) with tripEvery = 1 takes ~7s on Windows CI. - test("a large default sort runs in bounded native steps, and sorts as JS does", () => { - const words = Array.from({ length: 300_000 }, (_, i) => ((i * 7919) % 300_007).toString(36)) - const vm = vmFor(` - const words = ${JSON.stringify(words)} - const mixed = words.slice(0, 9000).concat([undefined, 10, 9, 100]) - mixed[9100] = "hole above" - const sorted = mixed.sort() - return [words.sort(), sorted.length, Array.from(sorted.slice(-6), String), 9099 in sorted, 9100 in sorted] - `) - vm.tripEvery = 1 - let slices = 0 - let next = vm.run() - for (; next.kind === "slice"; next = vm.run()) slices++ - // At least one slice per sorted run of 4,096 values, besides the merge steps. - expect(slices).toBeGreaterThan(300_000 / 4096) - const mixed: Array = words.slice(0, 9000).concat([undefined, 10, 9, 100] as Array) - mixed[9100] = "hole above" - const sorted = mixed.sort() - expect(next).toEqual({ - kind: "done", - completion: normal([ - [...words].sort(), - sorted.length, - Array.from(sorted.slice(-6), String), - 9099 in sorted, - 9100 in sorted, - ]), - }) - }, 15_000) - - test("concurrent tool calls stop the VM once, with every call in one batch", () => { - const vm = vmFor(`return await Promise.all([1, 2, 3].map((value) => tools.echo({ value })))`) - const started = stop(vm) - if (started.kind !== "host") throw new Error(`expected a host stop, got ${started.kind}`) - expect( - started.calls.map((call) => ({ - call: { label: call.label, path: call.path, args: call.args, policy: call.policy }, - blocking: call.blocking, - status: call.status, - })), - ).toEqual( - [1, 2, 3].map((value) => ({ - call: { label: "tools.echo", path: ["tools", "echo"], args: [{ value }], policy: "async" }, - blocking: false, - status: "queued", - })), - ) - // Nothing else can run until host work completes. - expect(stop(vm)).toEqual({ kind: "host", calls: [] }) - for (const [index, call] of [...started.calls.entries()].reverse()) vm.complete(call.id, normal((index + 1) * 10)) - expect(stop(vm)).toEqual({ kind: "done", completion: normal([10, 20, 30]) }) - expect(started.calls.map((call) => call.status)).toEqual(["completed", "completed", "completed"]) - }) - - test("a blocking host call stops the job that made it until it completes", () => { - const vm = vmFor(`const found = search({ query: "echo" }); return found.items.length`) - const started = stop(vm) - if (started.kind !== "host") throw new Error(`expected a host stop, got ${started.kind}`) - expect(started.calls.map((call) => [call.label, call.blocking])).toEqual([["search", true]]) - expect(stop(vm)).toEqual({ kind: "host", calls: [] }) - vm.complete(started.calls[0]!.id, normal({ items: [1, 2], remaining: 0, next: null })) - expect(stop(vm)).toEqual({ kind: "done", completion: normal(2) }) - }) - - test("await parks the frames it cuts off the job stack as data on the promise", () => { - const vm = vmFor(` - const inner = async (x) => { const y = x + 1; return await new Promise(() => {}) } - const outer = async () => [await inner(1)] - return await outer() - `) - expect(stop(vm).kind).toBe("stuck") - const roots = parked(vm) - expect(roots.length).toBe(3) - expectData(roots) - // Each cut starts at its async boundary: the program's body, or an async function's call. - expect(roots.map((frame) => frame.mode).sort()).toEqual([Mode.ASYNC, Mode.ASYNC, Mode.PROGRAM]) - expect(vm.depth).toBe(0) - expect(vm.frames).toEqual([]) - }) - - test("a suspended generator keeps its one frame on the generator", () => { - const vm = vmFor(` - function* inner() { yield 4 } - function* g(x) { const log = []; try { log.push(yield x); yield* [2, 3]; yield* inner() } finally { log.push("f") } } - const fresh = g(0) - const array = g(1) - array.next() - array.next("a") - const nested = g(1) - for (let i = 0; i < 4; i++) nested.next() - await new Promise(() => {}) - `) - expect(stop(vm).kind).toBe("stuck") - const generator = (name: string) => { - const value = programBinding(vm, name) - if (!(value instanceof GeneratorObj)) throw new Error(`${name} is not a generator`) - return value - } - expect(generator("fresh").state).toBe("suspendedStart") - expect(generator("fresh").frame!.mode).toBe(Mode.GENERATOR) - for (const name of ["array", "nested"]) { - const frame = generator(name).frame! - expect(generator(name).state).toBe("suspendedYield") - expectData([frame]) - // `yield*` keeps the delegate's iterator record in a register, as data. - expect(frame.regs.slice(0, frame.sp).some((reg) => reg instanceof CustomIter)).toBe(true) - } - // The inner generator `nested` delegates to is suspended in its own frame. - const nested = generator("nested").frame! - const record = nested.regs - .slice(0, nested.sp) - .find((reg) => reg instanceof CustomIter && reg.iterator instanceof GeneratorObj) as CustomIter - expect((record.iterator as GeneratorObj).frame!.code.name).toBe("inner") - }) - - test("an async generator paused at an await parks its frame as data", () => { - const vm = vmFor(` - async function* ag() { const v = await new Promise(() => {}); yield v } - const it = ag() - const first = it.next() - const second = it.next() - await new Promise(() => {}) - `) - expect(stop(vm).kind).toBe("stuck") - const it = programBinding(vm, "it") - if (!(it instanceof GeneratorObj)) throw new Error("expected a generator") - expect(it.state).toBe("executing") - expect(it.queue.length).toBe(2) - expectData(parked(vm)) - expect( - parked(vm) - .map((frame) => frame.mode) - .sort(), - ).toEqual([Mode.GENERATOR, Mode.PROGRAM]) - expect(vm.frames).toEqual([]) - }) - - test("for await over a synchronous iterable keeps its adapter and reactions as data", () => { - const vm = vmFor(` - const never = new Promise(() => {}) - const log = [] - const iterable = { [Symbol.iterator]() { let i = 0; return { next: () => ({ done: false, value: i++ ? never : 1 }) } } } - for await (const x of iterable) log.push(x) - `) - // No native function is made while the program runs: the adapter's methods are intrinsics. - const made: Array = [] - nativeRule.observe = (native) => made.push(native) - try { - expect(stop(vm).kind).toBe("stuck") - } finally { - nativeRule.observe = undefined - } - expect(made).toEqual([]) - const never = programBinding(vm, "never") - if (!(never instanceof PromiseObj)) throw new Error("expected a promise") - expect(never.reactions.map((reaction) => reaction.kind)).toEqual(["asyncFromSync"]) - const reaction = never.reactions[0]! - for (const field of Object.values(reaction)) expect(typeof field).not.toBe("function") - if (reaction.kind !== "asyncFromSync") throw new Error("expected an adapter reaction") - expect(reaction.done).toBe(false) - // The iterator it would close on a rejection is the program's own, as a record. - expect(reaction.close).toMatchObject({ asynchronous: false }) - expectData(parked(vm)) - const program = parked(vm).find((frame) => frame.mode === Mode.PROGRAM)! - const loop = program.regs.find((reg) => reg instanceof CustomIter) as CustomIter - expect(loop.iterator).toBeInstanceOf(AsyncFromSyncIterator) - }) - - test("the VM does not import Effect", async () => { - const root = path.join(import.meta.dir, "..") - // The language's host boundary and driver; Code Mode (src/codemode/) is built on Effect throughout. - const host = new Set([ - "src/language/host-function.ts", - "src/language/runtime.ts", - "src/language/runtime/driver.ts", - "src/language/runtime/execute.ts", - "src/language/runtime/extensions.ts", - "src/language/runtime/signals.ts", - ]) - // Glob paths use the platform's separator. - const files = (await Array.fromAsync(new Glob("src/language/**/*.ts").scan({ cwd: root }))) - .map((file) => file.split(path.sep).join("/")) - .filter((file) => !host.has(file)) - expect(files.length).toBeGreaterThan(0) - for (const file of files) { - expect(await Bun.file(path.join(root, file)).text()).not.toMatch(/from "effect"/) - } - }) -}) - -describe("built-ins as data", () => { - test("every frame on the job stack is data at every step", () => { - const vm = vmFor(` - const log = [] - const box = (v) => ({ valueOf() { log.push("valueOf"); return v }, toString() { return "box" + v } }) - const xs = Array.from({ length: 6 }, (_, i) => (i * 7) % 6) - const sorted = xs.map((x) => x * 2).filter((x) => x !== 4).sort((a, b) => b - a) - const found = [xs.find((x) => x > 3), xs.findLast((x) => x < 3), xs.some((x) => x > 4), xs.every((x) => x >= 0)] - const flat = xs.flatMap((x) => [x, -x]).reduce((a, b) => a + b, 0) + xs.reduceRight((a, b) => a + b) - xs.forEach((x) => log.push(x)) - function* gen(n) { for (let i = 0; i < n; i++) yield [String(i), i] } - const map = new Map(gen(3)) - const set = new Set(Array.from(gen(3), ([k]) => k)) - const weak = new WeakMap([[log, 1]]) - map.forEach((v, k) => log.push(k)) - const setLike = { size: box(2), has: (v) => v === "1", keys: () => ["1", "9"][Symbol.iterator]() } - const ops = [set.union(setLike).size, set.intersection(setLike).size, set.isSubsetOf(setLike), set.isDisjointFrom(setLike)] - const groups = [Object.groupBy(xs, (x) => (x % 2 ? box("odd") : "even")), Map.groupBy(xs, (x) => x % 3).size] - const entries = Object.fromEntries(gen(2)) - const iter = gen(5).map((pair) => pair[1]).filter((n) => n % 2 === 0).flatMap((n) => [n, n]).take(5).drop(1) - const helpers = [iter.toArray(), gen(4).map(([, n]) => n).reduce((a, b) => a + b), Iterator.from({ next: () => ({ done: true }) }).toArray()] - const json = JSON.stringify({ a: box(1), d: { toJSON: (k) => "key " + k }, list: [1, undefined] }, (k, v) => (k === "a" ? String(v) : v), 1) - const parsed = JSON.parse('{"a":[1,2,{"b":3}]}', (k, v) => (typeof v === "number" ? v * 10 : v)) - const text = "a-b-c".replace(/-/g, (m) => "+").replaceAll("+", () => "_") + "x".padStart(box(3), "0") - const dates = [new Date(box(0)).getTime(), Date.UTC(box(2000), 0), new Date(0).setFullYear(box(1999))] - const numbers = [Math.max(box(5), 2), Number(box(7)), String(box(1)), [box(1), 2].join(box("|"))] - const calls = [Math.max.call(null, 1, 2), ((a, b) => a + b).apply(null, [1, 2]), ((a) => a).bind(null, 9)()] - const params = String(new URLSearchParams(gen(2))) + new Headers([["x", "1"]]).get("x") - const aggregate = new AggregateError(gen(2), box("many")).errors.length - const error = new Error(box("boxed")).message - const work = async (i) => { await null; return i * 2 } - const all = await Promise.all([work(1), work(2), 3]) - const settled = await Promise.allSettled([work(1), Promise.reject(new Error("no"))]) - const raced = await Promise.race([work(5), new Promise((resolve) => resolve("first"))]) - const any = await Promise.any([Promise.reject(1), work(4)]) - const tried = await Promise.try(() => work(6)) - const thenned = await work(1).then((v) => v + 1).catch(() => 0).finally(() => log.push("finally")) - const thenable = await { then: (resolve) => resolve("thenable") } - const tool = await tools.echo({ value: await work(10) }) - const found2 = search({ query: "echo" }).items.length - async function* agen() { yield 1; yield await work(1) } - const collected = [] - for await (const v of agen()) collected.push(v) - return { all, raced, any, tried, thenned, tool, found2, collected } - `) - vm.tripEvery = 1 - const sources = new Set() - let steps = 0 - let next = vm.run() - for (; next.kind !== "done"; next = vm.run()) { - steps++ - if (vm.frames.length > 0) expectData(vm.frames) - for (const frame of vm.frames) { - if ((frame.code.flags & CodeFlags.INTERNAL) !== 0) sources.add(frame.code.source.id) - } - if (next.kind === "stuck") throw new Error("the run is stuck") - if (next.kind !== "host") continue - for (const call of next.calls) { - if (call.policy === "async") vm.complete(call.id, normal((call.args[0] as { value: number }).value)) - else vm.complete(call.id, normal({ items: [1], remaining: 0, next: null })) - } - } - expect(steps).toBeGreaterThan(100) - // Built-ins that call program code ran as prelude and internal bytecode frames, as data. - expect([...sources].sort()).toEqual(["@prelude", "@vm-internal"]) - expect(next).toEqual({ - kind: "done", - completion: normal({ - all: [2, 4, 3], - raced: "first", - any: 8, - tried: 12, - thenned: 3, - tool: 20, - found2: 1, - collected: [1, 2], - }), - }) - }) -}) diff --git a/packages/codemode/test/stdlib.test.ts b/packages/codemode/test/stdlib.test.ts index d677ae63ca8..d09b4d587ac 100644 --- a/packages/codemode/test/stdlib.test.ts +++ b/packages/codemode/test/stdlib.test.ts @@ -1,21 +1,5 @@ -/* - * Portions adapted from Test262 at revision 250f204f23a9249ff204be2baec29600faae7b75: - * - test/built-ins/Date/value-to-primitive-result-non-string-prim.js - * - test/built-ins/Date/value-to-primitive-result-string.js - * - test/built-ins/Date/prototype/toUTCString/format.js - * - test/built-ins/Date/prototype/toUTCString/invalid-date.js - * - test/built-ins/RegExp/prototype/exec/S15.10.6.2_A4_T8.js - * - * CodeMode does not support Symbol.toPrimitive, so the Date-constructor cases exercise the same primitive-result - * handling through supported own valueOf and toString functions. - * - * Copyright (C) 2016 the V8 project authors. All rights reserved. - * Copyright (C) 2017 the V8 project authors. All rights reserved. - * Copyright 2009 the Sputnik authors. All rights reserved. - * Test262 portions are governed by the BSD license in LICENSE.test262. - */ import { describe, expect, test } from "bun:test" -import { Effect, Schema } from "effect" +import { Effect } from "effect" import { CodeMode, Tool } from "../src/index.js" // Standard-library value types: Date, RegExp, Map, Set. Programs use them as ordinary JS; @@ -29,2118 +13,8 @@ const value = async (code: string) => { if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) return result.value } -const error = async (code: string) => { - const result = await run(code) - if (result.ok) throw new Error(`expected failure, got value ${JSON.stringify(result.value)}`) - return result.error -} - -describe("Number and Math", () => { - test("Number.toString truncates the radix before checking its range", async () => { - expect( - await value(`return [36.1, 36.9, "36.9", { valueOf() { return 36.9 } }].map(radix => (35).toString(radix))`), - ).toEqual(["z", "z", "z", "z"]) - }) - - test("Number.toString keeps invalid radixes catchable as RangeError", async () => { - expect( - await value(`return [0, 1.9, 37, NaN, Infinity, -Infinity].map(radix => { - try { return (35).toString(radix) } - catch (error) { return error instanceof RangeError } - })`), - ).toEqual([true, true, true, true, true, true]) - expect(await value(`return [(35).toString(), (35).toString(undefined), (35).toString(2.9)]`)).toEqual([ - "35", - "35", - "100011", - ]) - }) - - test("Math.random returns a number in [0, 1)", async () => { - expect(await value(`const n = Math.random(); return typeof n === "number" && n >= 0 && n < 1`)).toBe(true) - }) - - test("Number exposes native non-finite constants", async () => { - expect( - await value( - `return [Number.isNaN(Number.NaN), Number.POSITIVE_INFINITY === Infinity, Number.NEGATIVE_INFINITY === -Infinity]`, - ), - ).toEqual([true, true, true]) - }) - - test("Number valueOf returns its primitive receiver", async () => { - expect(await value(`return (42).valueOf()`)).toBe(42) - }) - - test("Number valueOf does not enable boxed numbers", async () => { - const failure = await error(`return new Number(42)`) - expect(failure.kind).toBe("ExecutionFailure") - expect(failure.message).toContain("new Number(...) is not supported; call Number(...) without new instead.") - }) -}) - -describe("Date", () => { - test("Date.now() returns a number", async () => { - expect(await value(`return typeof Date.now()`)).toBe("number") - }) - - test("epoch construction and ISO rendering", async () => { - expect(await value(`return new Date(0).toISOString()`)).toBe("1970-01-01T00:00:00.000Z") - }) - - test("string parsing round-trips", async () => { - expect(await value(`return new Date("2024-01-02T03:04:05.000Z").getTime()`)).toBe(1704164645000) - expect(await value(`return Date.parse("2024-01-02T03:04:05.000Z")`)).toBe(1704164645000) - }) - - test("one-argument construction coerces supported values like JavaScript", async () => { - expect( - await value(`return [new Date(true).getTime(), new Date(false).getTime(), new Date(null).getTime()]`), - ).toEqual([1, 0, 0]) - expect(await value(`return Number.isNaN(new Date(undefined).getTime())`)).toBe(true) - expect(await value(`return Number.isNaN(new Date([]).getTime())`)).toBe(true) - expect(await value(`return new Date(["1970-01-01T00:00:00.000Z"]).getTime()`)).toBe(0) - expect(await value(`return Number.isNaN(new Date({}).getTime())`)).toBe(true) - }) - - test("one-argument construction uses valueOf then toString for objects", async () => { - expect( - await value(` - const calls = [] - const number = { valueOf: () => 8 } - const text = { - valueOf: () => { calls.push("valueOf"); return {} }, - toString: () => { calls.push("toString"); return "2016-06-05T18:40:00.000Z" }, - } - return [new Date(number).getTime(), new Date(text).getTime(), calls] - `), - ).toEqual([8, 1465152000000, ["valueOf", "toString"]]) - - expect( - await value(` - const values = [ - { valueOf: () => undefined }, - { valueOf: () => true }, - { valueOf: () => false }, - { valueOf: () => null }, - ] - return values.map((item) => new Date(item).getTime()) - `), - ).toEqual([null, 1, 0, 0]) - - expect( - await value(` - try { - new Date({ valueOf: () => ({}), toString: () => ({}) }) - } catch (error) { - return error.name - } - `), - ).toBe("TypeError") - }) - - test("date arithmetic and comparison use the time value", async () => { - expect(await value(`const a = new Date(1000); const b = new Date(3000); return b - a`)).toBe(2000) - expect(await value(`const a = new Date(1000); const b = new Date(3000); return a < b`)).toBe(true) - expect(await value(`return +new Date(42)`)).toBe(42) - }) - - test("UTC getters read calendar components", async () => { - expect( - await value( - `const d = new Date("2024-03-05T06:07:08.009Z"); return [d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds()]`, - ), - ).toEqual([2024, 2, 5, 6, 7, 8, 9]) - }) - - test("invalid dates yield NaN times, guardable in-CodeMode", async () => { - expect(await value(`return Number.isNaN(new Date("garbage").getTime())`)).toBe(true) - expect(await value(`return new Date("garbage").toJSON()`)).toBeNull() - }) - - test("toISOString on an invalid date throws RangeError", async () => { - expect(await value(`try { new Date("garbage").toISOString() } catch (error) { return error.name }`)).toBe( - "RangeError", - ) - }) - - test("template interpolation renders the ISO form", async () => { - expect(await value("return `at ${new Date(0)}`")).toBe("at 1970-01-01T00:00:00.000Z") - }) - - test("dates serialize to ISO strings at the boundary, direct and nested", async () => { - expect(await value(`return new Date(0)`)).toBe("1970-01-01T00:00:00.000Z") - expect(await value(`return { when: new Date(0), tags: [new Date(1000)] }`)).toEqual({ - when: "1970-01-01T00:00:00.000Z", - tags: ["1970-01-01T00:00:01.000Z"], - }) - expect(await value(`return JSON.stringify({ d: new Date(0) })`)).toBe('{"d":"1970-01-01T00:00:00.000Z"}') - }) - - test("coercions: Number is the time, String is ISO, Boolean is true", async () => { - expect(await value(`return Number(new Date(5))`)).toBe(5) - expect(await value(`return String(new Date(0))`)).toBe("1970-01-01T00:00:00.000Z") - expect(await value(`return Boolean(new Date(0))`)).toBe(true) - }) - - test("sorting dates with a numeric comparator", async () => { - expect( - await value(` - const dates = [new Date(3000), new Date(1000), new Date(2000)] - return dates.sort((a, b) => a - b).map((d) => d.getTime()) - `), - ).toEqual([1000, 2000, 3000]) - }) - - test("new Date(year, month, day) accepts component form", async () => { - expect(await value(`const d = new Date(2024, 0, 2); return [d.getFullYear(), d.getMonth(), d.getDate()]`)).toEqual([ - 2024, 0, 2, - ]) - }) - - test("typeof and unknown properties are forgiving", async () => { - expect(await value(`return typeof new Date(0)`)).toBe("object") - expect(await value(`return new Date(0).nope === undefined`)).toBe(true) - }) - - test("toUTCString and toGMTString use the native UTC format", async () => { - expect( - await value(` - const date = new Date(0) - return [ - date.toUTCString(), - date.toGMTString(), - new Date(NaN).toUTCString(), - new Date("0020-01-01T00:00:00Z").toUTCString(), - ] - `), - ).toEqual([ - "Thu, 01 Jan 1970 00:00:00 GMT", - "Thu, 01 Jan 1970 00:00:00 GMT", - "Invalid Date", - "Wed, 01 Jan 0020 00:00:00 GMT", - ]) - }) -}) - -describe("RegExp", () => { - test("literal test", async () => { - expect(await value(`return /ab+c/.test("xabbbc")`)).toBe(true) - expect(await value(`return /ab+c/.test("nope")`)).toBe(false) - }) - - test("exec exposes captures and index", async () => { - expect(await value(`const m = /a(b+)/.exec("xxabbc"); return { full: m[0], group: m[1], index: m.index }`)).toEqual( - { - full: "abb", - group: "bb", - index: 2, - }, - ) - expect(await value(`return /a/.exec("zzz")`)).toBeNull() - }) - - test("named groups read through", async () => { - expect( - await value(`const m = /(?[a-z]+)-(?\\d+)/.exec("id ab-42"); return m.groups.word + m.groups.num`), - ).toBe("ab42") - }) - - test("global exec advances lastIndex across calls", async () => { - expect( - await value(` - const r = /\\d+/g - const first = r.exec("a1b22c") - const second = r.exec("a1b22c") - return [first[0], second[0]] - `), - ).toEqual(["1", "22"]) - }) - - test("lastIndex is writable and stores a number", async () => { - expect( - await value(` - const pattern = /(?:ab|cd)\\d?/g - pattern.lastIndex = "12" - const stored = [pattern.lastIndex, typeof pattern.lastIndex] - const match = pattern.exec("aacd2233ab12nm444ab42") - pattern.lastIndex = 0 - return [stored, match[0], match.index, pattern.lastIndex] - `), - ).toEqual([[12, "number"], "ab4", 17, 0]) - // lastIndex is a prototype accessor, so delete is a no-op rather than a TypeError. - expect(await value(`const re = /a/; return [delete re.lastIndex, re.lastIndex]`)).toEqual([true, 0]) - }) - - test("a non-numeric lastIndex runs from 0; non-global exec and test leave it alone", async () => { - expect( - await value(` - const pattern = /a/g - pattern.lastIndex = {} - const match = pattern.exec("ba") - pattern.lastIndex = 10 - const missed = pattern.exec("a") - const plain = /a/ - plain.lastIndex = 5 - return [match.index, pattern.lastIndex, missed, plain.exec("ba").index, plain.test("ba"), plain.lastIndex] - `), - ).toEqual([1, 0, null, 1, true, 5]) - }) - - test("String methods read and update lastIndex like exec", async () => { - expect( - await value(` - const re = /a/y - re.exec("aa") - re.lastIndex = 0 - return ["aa".replace(re, "b"), re.lastIndex] - `), - ).toEqual(["ba", 1]) - expect( - await value(` - const re = /a/g - re.exec("aaa") - return ["aaa".match(re), re.lastIndex] - `), - ).toEqual([["a", "a", "a"], 0]) - expect( - await value(` - const re = /a/g - re.lastIndex = 2 - return ["aaa".replace(re, () => "b"), re.lastIndex] - `), - ).toEqual(["bbb", 0]) - expect( - await value(` - const re = /a/g - re.lastIndex = 2 - return ["aaa".replaceAll(re, "b"), re.lastIndex] - `), - ).toEqual(["bbb", 0]) - expect( - await value(` - const re = /a/y - re.lastIndex = 1 - const m = "baa".match(re) - return [m.index, re.lastIndex] - `), - ).toEqual([1, 2]) - }) - - test("split, search, and matchAll leave lastIndex unchanged like JS", async () => { - expect( - await value(` - const re = /a/y - re.lastIndex = 2 - return ["banana".split(re), re.lastIndex] - `), - ).toEqual([["b", "n", "n", ""], 2]) - expect( - await value(` - const re = /a/g - re.lastIndex = 2 - return ["banana".search(re), re.lastIndex] - `), - ).toEqual([1, 2]) - expect( - await value(` - const re = /a/y - re.lastIndex = 2 - return ["banana".search(re), re.lastIndex] - `), - ).toEqual([-1, 2]) - expect( - await value(` - const re = /a/g - re.lastIndex = 2 - return ["banana".matchAll(re).map((m) => m.index), re.lastIndex] - `), - ).toEqual([[3, 5], 2]) - expect( - await value(` - const re = /a/gy - re.lastIndex = 1 - return ["banana".matchAll(re).map((m) => m.index), re.lastIndex] - `), - ).toEqual([[1], 1]) - }) - - test("String methods leave lastIndex untouched without g or y", async () => { - expect( - await value(` - const re = /a/ - re.lastIndex = 5 - return ["aaa".replace(re, "b"), "aaa".match(re).index, "aaa".split(re), "aaa".search(re), re.lastIndex] - `), - ).toEqual(["baa", 0, ["", "", "", ""], 0, 5]) - }) - - test("an unmatched string pattern returns null", async () => { - expect(await value(`return "abc".match(/\\d/)`)).toBeNull() - }) - - test("matchAll materializes match arrays with captures", async () => { - expect(await value(`return "a1b22".matchAll(/(\\d+)/g).map((m) => m[1])`)).toEqual(["1", "22"]) - }) - - test("function replacers receive captures, offsets, input, and named groups", async () => { - expect( - await value(` - const seen = [] - const output = "a1b22".replace(/(\\d)(\\d)?/g, (match, first, second, offset, input) => { - seen.push([match, first, second === undefined, offset, input]) - return Number(match) * 2 - }) - return { output, seen } - `), - ).toEqual({ - output: "a2b44", - seen: [ - ["1", "1", true, 1, "a1b22"], - ["22", "2", false, 3, "a1b22"], - ], - }) - expect( - await value(` - return "red-blue".replace( - /(?[a-z]+)-(?[a-z]+)/, - (match, left, right, offset, input, groups) => groups.right + ":" + groups.left, - ) - `), - ).toBe("blue:red") - }) - - test("function replacers support string searches, zero-length matches, and result coercion", async () => { - expect(await value(`return "banana".replace("na", (match, offset, input) => "[" + offset + "]")`)).toBe("ba[2]na") - expect(await value(`return "ab".replaceAll("", (match, offset) => offset)`)).toBe("0a1b2") - expect(await value(`return "😀".replaceAll(/(?:)/gu, (match, offset) => "[" + offset + "]")`)).toBe("[0]😀[2]") - expect( - await value(`return "123".replace(/\\d/g, (match) => match === "1" ? 7 : match === "2" ? null : { n: 3 })`), - ).toBe("7null[object Object]") - }) - - test("promise-returning string replacers are coerced synchronously", async () => { - const decorate = Tool.make({ - description: "Decorate a string", - input: Schema.String, - output: Schema.String, - execute: (input) => Effect.succeed(`[${input}]`), - }) - const result = await Effect.runPromise( - CodeMode.execute({ - tools: { host: { decorate } }, - code: `return "a1b22".replace(/\\d+/g, async (match) => await tools.host.decorate(match))`, - }), - ) - expect(result.ok && result.value).toBe("a[object Promise]b[object Promise]") - - const missingAwait = await Effect.runPromise( - CodeMode.execute({ - tools: { host: { decorate } }, - code: `return "a1".replace(/\\d/, (match) => tools.host.decorate(match))`, - }), - ) - expect(missingAwait.ok && missingAwait.value).toBe("a[object Promise]") - }) - - test("replaceAll without the g flag is a catchable error", async () => { - expect(await value(`try { "a".replaceAll(/a/, "b"); return "no" } catch { return "caught" }`)).toBe("caught") - }) - - test("new RegExp constructs from strings; invalid patterns are catchable", async () => { - expect(await value(`return new RegExp("a+", "i").test("AAA")`)).toBe(true) - expect(await value(`try { new RegExp("("); return "no" } catch { return "caught" }`)).toBe("caught") - expect(await value(`return [/a/ instanceof RegExp, /a/.source]`)).toEqual([true, "a"]) - }) - - test("invalid patterns fail with actionable messages", async () => { - const fromString = await error(`return "abc".match("(")`) - expect(fromString.message).toContain('String.match received the string "("') - expect(fromString.message).toContain("escape them with a backslash") - - const fromConstructor = await error(`return new RegExp("(")`) - expect(fromConstructor.message).toContain('new RegExp(...) received "("') - expect(fromConstructor.message).toContain("escape them with a backslash") - - const fromFlags = await error(`return new RegExp("a", "xz")`) - expect(fromFlags.message).toContain('invalid flags "xz"') - expect(fromFlags.message).toContain("Valid flags are") - }) - - test("missing g-flag errors say how to fix the call", async () => { - expect((await error(`return "aa".replaceAll(/a/, "b")`)).message).toContain("write /a/g, or use String.replace") - expect((await error(`return "aa".matchAll(/a/)`)).message).toContain("write /a/g, or use String.match") - }) - - test("any argument is a pattern string, as new RegExp(arg) reads it", async () => { - expect( - await value( - `return ["a42b".match(42)[0], "xnullx".search(null), "abc".match(undefined), [..."1a1".matchAll(1)].length]`, - ), - ).toEqual(["42", 1, [""], 2]) - }) - - test("source and flags properties read through", async () => { - expect(await value(`const r = /ab/gi; return { source: r.source, flags: r.flags, global: r.global }`)).toEqual({ - source: "ab", - flags: "gi", - global: true, - }) - }) - - test("regexes serialize as {} like JSON.stringify, at the boundary and inside the program", async () => { - expect(await value(`return [/a/, { r: /b/gi }]`)).toEqual([{}, { r: {} }]) - expect(await value(`return JSON.stringify({ r: /a/g })`)).toBe('{"r":{}}') - }) - - test("template interpolation renders the literal form", async () => { - expect(await value("return `${/ab/g}`")).toBe("/ab/g") - }) -}) - -describe("URL and URI helpers", () => { - test("encodes and decodes complete URIs and URI components", async () => { - expect( - await value(` - return [ - encodeURI("https://example.test/a b?q=a/b"), - encodeURIComponent("a b/c?"), - decodeURI("https://example.test/a%20b?q=a/b"), - decodeURIComponent("a%20b%2Fc%3F"), - ["a b", "c/d"].map(encodeURIComponent), - ] - `), - ).toEqual([ - "https://example.test/a%20b?q=a/b", - "a%20b%2Fc%3F", - "https://example.test/a b?q=a/b", - "a b/c?", - ["a%20b", "c%2Fd"], - ]) - expect( - await value(`try { decodeURIComponent("%zz"); return false } catch (error) { return error instanceof URIError }`), - ).toBe(true) - }) - - test("resolves and mutates URLs with linked search parameters", async () => { - expect( - await value(` - const url = new URL("../users?id=old#top", "https://user:pass@example.com:8443/api/v1/") - url.pathname = "/items/a b" - url.searchParams.set("id", "a b") - url.searchParams.append("tag", "x/y") - url.hash = "part 1" - return { - href: url.href, - origin: url.origin, - host: url.host, - pathname: url.pathname, - search: url.search, - id: url.searchParams.get("id"), - string: String(url), - json: url.toJSON(), - instances: [ - url instanceof URL, - url.searchParams instanceof URLSearchParams, - url.searchParams === url.searchParams, - ], - } - `), - ).toEqual({ - href: "https://user:pass@example.com:8443/items/a%20b?id=a+b&tag=x%2Fy#part%201", - origin: "https://example.com:8443", - host: "example.com:8443", - pathname: "/items/a%20b", - search: "?id=a+b&tag=x%2Fy", - id: "a b", - string: "https://user:pass@example.com:8443/items/a%20b?id=a+b&tag=x%2Fy#part%201", - json: "https://user:pass@example.com:8443/items/a%20b?id=a+b&tag=x%2Fy#part%201", - instances: [true, true, true], - }) - }) - - test("URLSearchParams supports records, pairs, mutation, callbacks, and materialization", async () => { - expect( - await value(` - const params = new URLSearchParams([["tag", "b"], ["tag", "a"], ["q", "a b"]]) - const seen = [] - params.forEach((value, key) => seen.push(key + "=" + value)) - params.delete("tag", "b") - params.append("tag", "c") - params.sort() - return { - text: params.toString(), - size: params.size, - tags: params.getAll("tag"), - has: params.has("tag", "c"), - entries: Array.from(params), - object: Object.fromEntries(params), - record: new URLSearchParams({ page: 2, filter: "open" }).toString(), - seen, - } - `), - ).toEqual({ - text: "q=a+b&tag=a&tag=c", - size: 3, - tags: ["a", "c"], - has: true, - entries: [ - ["q", "a b"], - ["tag", "a"], - ["tag", "c"], - ], - object: { q: "a b", tag: "c" }, - record: "page=2&filter=open", - seen: ["tag=b", "tag=a", "q=a b"], - }) - }) - - test("URL parsing failures are catchable and values use native JSON forms", async () => { - expect( - await value(` - const parsed = URL.parse("/users", "https://example.test/api/") - let invalidIsTypeError = false - try { new URL("not relative without a base") } catch (error) { invalidIsTypeError = error instanceof TypeError } - return { - canParse: URL.canParse("/users", "https://example.test/api/"), - cannotParse: URL.canParse("not relative without a base"), - parsed: parsed.href, - invalidIsTypeError, - boundary: [new URL("https://example.test/a"), new URLSearchParams("q=one")], - json: JSON.stringify({ url: new URL("https://example.test/a"), params: new URLSearchParams("q=one") }), - } - `), - ).toEqual({ - canParse: true, - cannotParse: false, - parsed: "https://example.test/users", - invalidIsTypeError: true, - boundary: ["https://example.test/a", "q=one"], - json: '{"url":"https://example.test/a","params":{}}', - }) - }) - - test("distinguishes omitted URL arguments from explicit undefined", async () => { - expect( - await value(` - function throwsTypeError(run) { - try { run(); return false } catch (error) { return error instanceof TypeError } - } - const params = new URLSearchParams() - const required = [ - () => params.append(), - () => params.delete(), - () => params.get(), - () => params.getAll(), - () => params.has(), - () => params.set(), - () => params.forEach(), - ].map(throwsTypeError) - params.append(undefined, undefined) - return { - construct: throwsTypeError(() => new URL()), - canParse: throwsTypeError(() => URL.canParse()), - parse: throwsTypeError(() => URL.parse()), - explicitUndefined: new URL(undefined, "https://example.test/base/").href, - params: params.toString(), - required, - } - `), - ).toEqual({ - construct: true, - canParse: true, - parse: true, - explicitUndefined: "https://example.test/base/undefined", - params: "undefined=undefined", - required: [true, true, true, true, true, true, true], - }) - }) -}) - -describe("Headers", () => { - test("constructs from records, pairs, Maps, and Headers; names fold to lowercase and values combine", async () => { - expect( - await value(` - const headers = new Headers({ "Content-Type": "text/plain", "X-Count": 1, "X-Null": null }) - headers.append("Accept", "text/html") - headers.append("accept", "application/json") - headers.set("x-count", "2") - headers.delete("x-null") - const copy = new Headers(headers) - copy.set("content-type", "text/html") - return { - get: headers.get("content-type"), - missing: headers.get("x-missing"), - combined: headers.get("ACCEPT"), - has: [headers.has("Accept"), headers.has("x-null")], - count: headers.get("x-count"), - copied: [headers.get("content-type"), copy.get("content-type")], - pairs: [...new Headers([["b", "2"], ["A", "1"]])], - map: [...new Headers(new Map([["k", "v"]]))], - keys: [...headers.keys()], - values: [...headers.values()], - entries: [...headers.entries()], - } - `), - ).toEqual({ - get: "text/plain", - missing: null, - combined: "text/html, application/json", - has: [true, false], - count: "2", - copied: ["text/plain", "text/html"], - pairs: [ - ["a", "1"], - ["b", "2"], - ], - map: [["k", "v"]], - keys: ["accept", "content-type", "x-count"], - values: ["text/html, application/json", "text/plain", "2"], - entries: [ - ["accept", "text/html, application/json"], - ["content-type", "text/plain"], - ["x-count", "2"], - ], - }) - }) - - test("iterates in sorted order everywhere iteration is allowed, and getSetCookie keeps cookies apart", async () => { - expect( - await value(` - const headers = new Headers({ b: "2", a: "1" }) - headers.append("Set-Cookie", "x=1") - headers.append("set-cookie", "y=2") - const seen = [] - headers.forEach((value, name, self) => seen.push(name + "=" + value + ":" + (self === headers))) - const [first] = headers - function* pairs() { yield* headers } - return { - seen, - first, - spread: [...headers], - from: Array.from(headers).length, - generator: [...pairs()].length, - object: Object.fromEntries(headers), - cookies: headers.getSetCookie(), - } - `), - ).toEqual({ - seen: ["a=1:true", "b=2:true", "set-cookie=x=1:true", "set-cookie=y=2:true"], - first: ["a", "1"], - spread: [ - ["a", "1"], - ["b", "2"], - ["set-cookie", "x=1"], - ["set-cookie", "y=2"], - ], - from: 4, - generator: 4, - object: { a: "1", b: "2", "set-cookie": "y=2" }, - cookies: ["x=1", "y=2"], - }) - }) - - test("serializes as a name-to-value object at the boundary and in JSON; prints for console", async () => { - const result = await run(` - const headers = new Headers({ "X-A": "1", b: "2" }) - console.log(headers) - return { headers, json: JSON.stringify({ headers }), text: String(headers), type: typeof headers, is: headers instanceof Headers } - `) - expect(result.ok && result.value).toEqual({ - headers: { b: "2", "x-a": "1" }, - json: '{"headers":{"b":"2","x-a":"1"}}', - text: "[object Headers]", - type: "object", - is: true, - }) - expect(result.ok && result.logs?.[0]).toBe('Headers {"b":"2","x-a":"1"}') - }) - - test("rejects what it cannot build from, and invalid names and values, with TypeErrors the program can catch", async () => { - expect( - await value(` - function message(run) { - try { run(); return null } catch (error) { return error instanceof TypeError ? error.message : error } - } - const headers = new Headers() - return [ - message(() => Headers()), - message(() => new Headers(null)), - message(() => new Headers(1)), - message(() => new Headers("a=1")), - message(() => new Headers(new Date())), - message(() => new Headers(() => 1)), - message(() => new Headers([["name"]])), - message(() => new Headers([["a", "b", "c"]])), - message(() => new Headers({ "bad name": "x" })), - message(() => new Headers({ name: "bad\u0000value" })), - message(() => headers.get("invalid\u0100")), - message(() => headers.has({})), - message(() => headers.set("a", "invalid\u0100")), - message(() => headers.append("a")), - message(() => headers.forEach()), - message(() => headers.forEach(1)), - message(() => { const get = headers.get; return get("a") }), - ] - `), - ).toEqual([ - "Constructor Headers requires 'new'.", - "new Headers(...) expects a record of names to values, iterable [name, value] pairs, or Headers.", - "new Headers(...) expects a record of names to values, iterable [name, value] pairs, or Headers.", - "new Headers(...) expects a record of names to values, iterable [name, value] pairs, or Headers.", - "new Headers(...) expects a record of names to values, iterable [name, value] pairs, or Headers.", - "new Headers(...) expects a record of names to values, iterable [name, value] pairs, or Headers.", - "new Headers(...) expects iterable [name, value] pairs.", - "new Headers(...) expects iterable [name, value] pairs.", - expect.stringContaining("bad name"), - expect.stringContaining("invalid value"), - expect.stringContaining("Invalid header name"), - expect.stringContaining("[object Object]"), - expect.stringContaining("invalid value"), - "Headers.append requires 2 arguments.", - "Headers.forEach requires 1 argument.", - "Headers.forEach expects a function callback.", - "Headers.prototype.get called on incompatible receiver undefined.", - ]) - }) -}) - -describe("Map", () => { - test("get/set/has/size with chaining", async () => { - expect( - await value(` - const m = new Map() - m.set("a", 1).set("b", 2) - return { a: m.get("a"), b: m.get("b"), has: m.has("a"), miss: m.get("zz") === undefined, size: m.size } - `), - ).toEqual({ a: 1, b: 2, has: true, miss: true, size: 5 - 3 }) - }) - - test("object keys use identity", async () => { - expect( - await value(` - const key = { id: 1 } - const m = new Map() - m.set(key, "hit") - return [m.get(key), m.get({ id: 1 }) === undefined] - `), - ).toEqual(["hit", true]) - }) - - test("construction from entry pairs and another Map", async () => { - expect(await value(`const m = new Map([["a", 1], ["b", 2]]); return m.get("b")`)).toBe(2) - expect( - await value( - `const m = new Map([["a", 1]]); const n = new Map(m); n.set("b", 2); return [n.get("a"), n.get("b"), m.has("b")]`, - ), - ).toEqual([1, 2, false]) - expect((await error(`return new Map("nope")`)).message).toMatch(/\[key, value\] pairs/) - expect((await error(`return new Map(["flat"])`)).message).toMatch(/\[key, value\] pairs/) - }) - - test("keys/values/entries return live iterators", async () => { - expect( - await value(` - const m = new Map([["a", 1], ["b", 2]]) - const keys = m.keys() - const first = keys.next() - m.set("c", 3) - return { first, rest: [...keys], values: [...m.values()], entries: [...m.entries()], same: [...m[Symbol.iterator]()] } - `), - ).toEqual({ - first: { value: "a", done: false }, - rest: ["b", "c"], - values: [1, 2, 3], - entries: [ - ["a", 1], - ["b", 2], - ["c", 3], - ], - same: [ - ["a", 1], - ["b", 2], - ["c", 3], - ], - }) - }) - - test("Object.fromEntries(map) and Array.from(map)", async () => { - expect(await value(`return Object.fromEntries(new Map([["a", 1], ["b", 2]]))`)).toEqual({ a: 1, b: 2 }) - expect(await value(`return Array.from(new Map([["a", 1]]))`)).toEqual([["a", 1]]) - }) - - test("for...of iterates [key, value] pairs with destructuring", async () => { - expect( - await value(` - const m = new Map([["a", 1], ["b", 2]]) - let total = 0 - let names = "" - for (const [key, count] of m) { names += key; total += count } - return names + total - `), - ).toBe("ab3") - }) - - test("spread produces entry pairs", async () => { - expect(await value(`return [...new Map([["a", 1]])]`)).toEqual([["a", 1]]) - }) - - test("forEach passes (value, key)", async () => { - expect( - await value(` - const m = new Map([["a", 1], ["b", 2]]) - const seen = [] - m.forEach((count, key) => seen.push(key + count)) - return seen - `), - ).toEqual(["a1", "b2"]) - }) - - test("delete and clear", async () => { - expect( - await value(` - const m = new Map([["a", 1], ["b", 2]]) - const removed = m.delete("a") - const missed = m.delete("zz") - const sizeAfterDelete = m.size - m.clear() - return [removed, missed, sizeAfterDelete, m.size] - `), - ).toEqual([true, false, 1, 0]) - }) - - test("counting idiom: grouped tallies", async () => { - expect( - await value(` - const words = ["a", "b", "a", "c", "a"] - const counts = new Map() - for (const word of words) counts.set(word, (counts.get(word) ?? 0) + 1) - return Object.fromEntries(counts) - `), - ).toEqual({ a: 3, b: 1, c: 1 }) - }) - - test("getOrInsert and getOrInsertComputed insert only when the key is missing", async () => { - expect( - await value(` - const groups = new Map() - groups.getOrInsert("a", []).push(1) - groups.getOrInsert("a", []).push(2) - let calls = 0 - const computed = (key) => { calls++; return key + "!" } - const first = groups.getOrInsertComputed("b", computed) - const second = groups.getOrInsertComputed("b", computed) - const zero = groups.getOrInsertComputed(-0, (key) => 1 / key === Infinity) - return [[...groups], first, second, calls, zero] - `), - ).toEqual([ - [ - ["a", [1, 2]], - ["b", "b!"], - [0, true], - ], - "b!", - "b!", - 1, - true, - ]) - expect( - await value(` - const m = new Map() - const outer = m.getOrInsertComputed("k", () => { m.set("k", "inner"); return "outer" }) - let thrown - try { m.getOrInsertComputed("j", () => { throw new Error("boom") }) } catch (error) { thrown = error.message } - return [outer, m.get("k"), thrown, m.has("j")] - `), - ).toEqual(["outer", "outer", "boom", false]) - expect((await error(`new Map().getOrInsertComputed("k", 5)`)).message).toContain("expects a function callback") - }) - - test("maps serialize to {} at the boundary, like JSON", async () => { - expect(await value(`return new Map([["a", 1]])`)).toEqual({}) - expect(await value(`return JSON.stringify(new Map([["a", 1]]))`)).toBe("{}") - }) - - test("console.log renders map contents for debugging", async () => { - const result = await run(`console.log(new Map([["a", 1]])); return null`) - expect(result.ok).toBe(true) - expect(result.logs?.[0]).toBe(`Map(1) [["a",1]]`) - }) -}) - -describe("Set", () => { - test("forEach is live on Map and Set: deleted entries are skipped and added ones visited", async () => { - expect( - await value(` - const m = new Map([[1, "a"], [2, "b"]]) - const s = new Set([1, 2]) - const seen = [] - m.forEach((v, k) => { seen.push(k); if (k === 1) { m.delete(2); m.set(3, "c") } }) - s.forEach((v) => { seen.push(v); if (v === 1) { s.delete(2); s.add(3) } }) - return seen - `), - ).toEqual([1, 3, 1, 3]) - }) - - test("add/has/delete/size with chaining", async () => { - expect( - await value(` - const s = new Set() - s.add(1).add(2).add(1) - const removed = s.delete(2) - return [s.size, s.has(1), s.has(2), removed] - `), - ).toEqual([1, true, false, true]) - }) - - test("dedupe idiom: [...new Set(items)]", async () => { - expect(await value(`return [...new Set([1, 2, 2, 3, 1])]`)).toEqual([1, 2, 3]) - }) - - test("construction from strings and other Sets", async () => { - expect(await value(`return [...new Set("aba")]`)).toEqual(["a", "b"]) - expect(await value(`return Array.from(new Set(new Set([1, 2])))`)).toEqual([1, 2]) - }) - - test("SameValueZero: NaN is findable", async () => { - expect(await value(`const s = new Set([NaN]); return s.has(NaN)`)).toBe(true) - }) - - test("for...of iterates values", async () => { - expect( - await value(` - let total = 0 - for (const n of new Set([1, 2, 3])) total += n - return total - `), - ).toBe(6) - }) - - test("sets cross the boundary as arrays; JSON.stringify keeps {} like JS", async () => { - expect(await value(`return { s: new Set([1, "a", { n: 1 }, undefined]) }`)).toEqual({ s: [1, "a", { n: 1 }, null] }) - expect(await value(`return JSON.stringify(new Set([1]))`)).toBe("{}") - }) -}) - -describe("Uint8Array", () => { - test("from maps the original values with thisArg, after consuming the source", async () => { - expect( - await value(` - const events = [] - function* source() { - events.push("start") - yield 300 - events.push("end") - } - return [ - [...Uint8Array.from([300, 2], (value, index) => value / 2 + index)], - [...Uint8Array.from(new Uint8Array([2, 3]), (value, index) => value + 255 + index)], - [...Uint8Array.from([1, 2], function (value, index) { return value + index + this.offset }, { offset: 5 })], - [...Uint8Array.from(atob("aGk="), (c) => c.charCodeAt(0))], - [...Uint8Array.from([300, 2], undefined)], - [...Uint8Array.from(source(), (value) => { events.push("map"); return value })], - events, - ] - `), - ).toEqual([[150, 2], [1, 3], [6, 8], [104, 105], [44, 2], [44], ["start", "end", "map"]]) - }) - - test("from rejects a non-callable mapper even for an empty source", async () => { - for (const mapper of ["42", "null", "{}"]) { - expect((await error(`return Uint8Array.from([], ${mapper}).length`)).message).toContain( - "TypeError: Uint8Array.from expects a function callback", - ) - } - }) - - test("constructs from a length, an array, an iterable, or another Uint8Array", async () => { - expect( - await value(` - const a = new Uint8Array(2) - const b = new Uint8Array([1, 2, 300]) - const c = Uint8Array.from(new Set([7, 8])) - const d = new Uint8Array(b) - d[0] = 9 - return [[...a], [...b], [...c], [...d], [...b], new Uint8Array("3").length, [...Uint8Array.of(1, "2")]] - `), - ).toEqual([[0, 0], [1, 2, 44], [7, 8], [9, 2, 44], [1, 2, 44], 3, [1, 2]]) - expect((await error(`new Uint8Array(-1)`)).message).toContain("Invalid typed array length: -1") - expect((await error(`new Uint8Array(1.5)`)).message).toContain("Invalid typed array length") - expect((await error(`new Uint8Array(20_000_000)`)).message).toContain("Invalid array length") - expect((await error(`Uint8Array.from(/x/)`)).message).toContain("received a RegExp") - }) - - test("BYTES_PER_ELEMENT is a read-only 1 on Uint8Array, Buffer and their instances", async () => { - expect( - await value(`const d = Object.getOwnPropertyDescriptor(Uint8Array, "BYTES_PER_ELEMENT") - return [Uint8Array.BYTES_PER_ELEMENT, new Uint8Array(1).BYTES_PER_ELEMENT, Buffer.BYTES_PER_ELEMENT, - Buffer.alloc(1).BYTES_PER_ELEMENT, 4 * Uint8Array.BYTES_PER_ELEMENT, d.writable, d.enumerable, Object.keys(Uint8Array)]`), - ).toEqual([1, 1, 1, 1, 4, false, false, []]) - }) - - test("index reads and writes clamp to a byte and ignore out-of-range writes, like JS", async () => { - expect( - await value(` - const b = new Uint8Array(3) - b[0] = 300 - b[1] = -1 - b["2"] = "7" - b[5] = 9 - b.tag = "x" - return [b[0], b[1], b[2], b[5], b.length, Object.keys(b), 1 in b, 5 in b, b.tag] - `), - ).toEqual([44, 255, 7, null, 3, ["0", "1", "2", "tag"], true, false, "x"]) - expect((await error(`delete new Uint8Array(1)[0]`)).message).toContain("Cannot delete property '0'") - expect((await error(`Uint8Array.prototype.length`)).message).toContain("incompatible receiver") - }) - - test("iteration, spread, destructuring, and Array.from", async () => { - expect( - await value(` - const b = new Uint8Array([1, 2, 3]) - const [x, ...rest] = b - const seen = [] - for (const byte of b) seen.push(byte) - function* g() { yield* b } - return [x, rest, seen, [...g()], Array.from(b, (n) => n * 2), new Set(b).size, Array.isArray(b)] - `), - ).toEqual([1, [2, 3], [1, 2, 3], [1, 2, 3], [2, 4, 6], 3, false]) - }) - - test("methods", async () => { - expect( - await value(` - const b = Uint8Array.from([1, 2, 3, 2]) - const view = b.subarray(1, 3) - view.fill(9) - const copy = b.slice(0, 2) - copy[0] = 5 - const target = new Uint8Array(4) - target.set([1, 2], 2) - target.set(b.subarray(0, 1)) - return [ - b.at(-1), [...b], [...copy], [...target], b.indexOf(9), b.lastIndexOf(9), b.includes(3), b.includes(2, 1), - b.join("-"), b.toString(), [...b.keys()], [...b.values()], [...b.entries()], [...Uint8Array.from([1, 2]).reverse()], - ] - `), - ).toEqual([ - 2, - [1, 9, 9, 2], - [5, 9], - [1, 0, 1, 2], - 1, - 2, - false, - true, - "1-9-9-2", - "1,9,9,2", - [0, 1, 2, 3], - [1, 9, 9, 2], - [ - [0, 1], - [1, 9], - [2, 9], - [3, 2], - ], - [2, 1], - ]) - expect((await error(`new Uint8Array(2).set([1, 2, 3])`)).message).toContain("does not fit") - expect((await error(`new Uint8Array(2).set([1], 2)`)).message).toContain("does not fit") - }) - - test("base64 and hex", async () => { - expect( - await value(` - return [ - new Uint8Array([104, 105]).toBase64(), new Uint8Array([255, 0]).toHex(), - [...Uint8Array.fromBase64("aGk=")], [...Uint8Array.fromHex("ff00")], - ] - `), - ).toEqual(["aGk=", "ff00", [104, 105], [255, 0]]) - expect(await error(`Uint8Array.fromBase64("!!!")`)).toMatchObject({ - message: expect.stringContaining("SyntaxError"), - }) - expect(await error(`Uint8Array.fromHex("zz")`)).toMatchObject({ message: expect.stringContaining("SyntaxError") }) - }) - - test("base64 alphabet, omitPadding, and lastChunkHandling options", async () => { - expect( - await value(` - const bytes = new Uint8Array([251, 255]) - let reads = 0 - return [ - bytes.toBase64({ alphabet: "base64url" }), bytes.toBase64({ omitPadding: true }), - bytes.toBase64({ alphabet: "base64url", omitPadding: 1 }), bytes.toBase64({}), - bytes.toBase64({ get alphabet() { reads++; return "base64url" } }), reads, - [...Uint8Array.fromBase64("-_8=", { alphabet: "base64url" })], [...Uint8Array.fromBase64("+/8")], - [...Uint8Array.fromBase64("AQ", { lastChunkHandling: "stop-before-partial" })], - [...Uint8Array.fromBase64("AR==")], - Buffer.from([251, 255]).toString("base64url"), [...Buffer.from("-_8", "base64url")], - ] - `), - ).toEqual(["-_8=", "+/8", "-_8", "+/8=", "-_8=", 1, [251, 255], [251, 255], [], [1], "-_8", [251, 255]]) - const message = async (code: string) => (await error(code)).message - expect(await message(`Uint8Array.fromBase64("-_8=")`)).toContain("SyntaxError") - expect(await message(`Uint8Array.fromBase64("AQ", { lastChunkHandling: "strict" })`)).toContain("SyntaxError") - expect(await message(`Uint8Array.fromBase64("AR==", { lastChunkHandling: "strict" })`)).toContain("SyntaxError") - expect(await message(`new Uint8Array(1).toBase64({ alphabet: "hex" })`)).toContain( - 'TypeError: Uint8Array.prototype.toBase64 requires that alphabet be "base64" or "base64url"', - ) - expect(await message(`new Uint8Array(1).toBase64(null)`)).toContain("requires that options be an object") - expect(await message(`Uint8Array.fromBase64("AQ", { lastChunkHandling: "partial" })`)).toContain( - "TypeError: Uint8Array.fromBase64 requires that lastChunkHandling be", - ) - }) - - test("coercion, console, JSON, and Object.prototype.toString", async () => { - expect( - await value(` - const b = new Uint8Array([1, 2]) - console.log(b, new Uint8Array()) - return [String(b), b + "", +new Uint8Array([5]), Number.isNaN(Number(b)), b == "1,2", JSON.stringify(b), b.toLocaleString(), typeof b, b instanceof Uint8Array] - `), - ).toEqual(["1,2", "1,2", 5, true, true, '{"0":1,"1":2}', "1,2", "object", true]) - expect((await run(`console.log(new Uint8Array([1, 2]), new Uint8Array())`)).logs).toEqual([ - "Uint8Array(2) [1,2] Uint8Array(0) []", - ]) - }) - - test("cannot cross the tool boundary; the error says how to encode it", async () => { - expect((await error(`return new Uint8Array(1)`)).message).toContain("pass text instead") - expect((await error(`return { deep: [new Uint8Array(1)] }`)).message).toContain("bytes.toBase64()") - expect(await value(`return new Uint8Array([7, 8]).toBase64()`)).toBe("Bwg=") - }) -}) - -describe("TextEncoder and TextDecoder", () => { - test("encodes null as text while omitted and undefined inputs stay empty", async () => { - expect( - await value(` - const encoder = new TextEncoder() - return [[...encoder.encode(null)], [...encoder.encode()], [...encoder.encode(undefined)]] - `), - ).toEqual([[110, 117, 108, 108], [], []]) - }) - - test("round-trips UTF-8 and exposes the standard fields", async () => { - expect( - await value(` - const encoder = new TextEncoder() - const bytes = encoder.encode("héllo ✓") - const decoder = new TextDecoder() - return [ - [...bytes], decoder.decode(bytes), decoder.decode(), [...encoder.encode()], encoder.encoding, - decoder.encoding, decoder.fatal, decoder.ignoreBOM, new TextDecoder("UTF8", { fatal: true }).fatal, - new TextDecoder().decode(new Uint8Array([0xef, 0xbb, 0xbf, 0x41])), - new TextDecoder("utf-8", { ignoreBOM: true }).decode(new Uint8Array([0xef, 0xbb, 0xbf, 0x41])), - new TextDecoder().decode(new Uint8Array([0xff])), - encoder instanceof TextEncoder, decoder instanceof TextDecoder, - ] - `), - ).toEqual([ - [104, 195, 169, 108, 108, 111, 32, 226, 156, 147], - "héllo ✓", - "", - [], - "utf-8", - "utf-8", - false, - false, - true, - "A", - "\ufeffA", - "\ufffd", - true, - true, - ]) - }) - - test("streams an emoji one byte at a time and copies the pending bytes", async () => { - expect( - await value(` - const decoder = new TextDecoder() - const chunk = new Uint8Array([65, 0xf0]) - const stream = { stream: true } - const start = decoder.decode(chunk, stream) - chunk[1] = 0 - return [start, decoder.decode(undefined, stream), decoder.decode(new Uint8Array([0x9f]), stream), - decoder.decode(new Uint8Array([0x98]), stream), decoder.decode(new Uint8Array([0x80, 66])), decoder.decode()] - `), - ).toEqual(["A", "", "", "", "😀B", ""]) - }) - - test("only strips the first BOM of each stream, including a split BOM", async () => { - expect( - await value(` - return [false, true].map(ignoreBOM => { - const decoder = new TextDecoder('utf8', { ignoreBOM }) - const bom = new Uint8Array([0xef, 0xbb, 0xbf]) - return [decoder.decode(bom.slice(0, 1), { stream: true }), decoder.decode(bom.slice(1), { stream: true }), - decoder.decode(bom), decoder.decode(bom)] - }) - `), - ).toEqual([ - ["", "", "\ufeff", ""], - ["", "\ufeff", "\ufeff", "\ufeff"], - ]) - }) - - test("reports malformed UTF-8 immediately and truncated UTF-8 on flush", async () => { - expect( - await value(` - return [false, true].map(fatal => { - return [[[0xe0], [0x80]], [[0xed, 0xa0]], [[0xf0, 0x80]], [[0xf4, 0x90]], - [[0xe2, 0x82], [65]], [[0xf0, 0x9f], undefined, undefined, [0xef, 0xbb, 0xbf, 66]]].flatMap(chunks => { - const decoder = new TextDecoder('utf8', { fatal }) - return chunks.map(bytes => { - try { return bytes ? decoder.decode(new Uint8Array(bytes), { stream: true }) : decoder.decode() } - catch (error) { return error.name } - }) - }) - }) - `), - ).toEqual([ - ["", "��", "��", "��", "��", "", "�A", "", "�", "", "B"], - ["", "TypeError", "TypeError", "TypeError", "TypeError", "", "TypeError", "", "TypeError", "", "B"], - ]) - }) - - test("keeps unread input in order after a fatal stream error", async () => { - expect( - await value(` - const decoder = new TextDecoder('utf8', { fatal: true }) - const stream = { stream: true } - const fail = bytes => { - try { return decoder.decode(bytes, stream) } catch (error) { return error.name } - } - const chunk = new Uint8Array([0xff, 65]) - const first = fail(chunk) - chunk[1] = 0 - return [first, decoder.decode(), fail(new Uint8Array([0xe2, 0x82])), - fail(new Uint8Array([66, 67])), decoder.decode(new Uint8Array([68])), decoder.decode()] - `), - ).toEqual(["TypeError", "A", "", "TypeError", "BCD", ""]) - }) - - test("rejects primitive options before touching the partial character", async () => { - expect( - await value(` - const decoder = new TextDecoder() - decoder.decode(new Uint8Array([0xc2]), { stream: true }) - const errors = [true, false, 0, '', Symbol.iterator].map(options => { - try { return decoder.decode(undefined, options) } catch (error) { return error.name } - }) - return [...errors, decoder.decode(new Uint8Array([0xa2]), null)] - `), - ).toEqual(["TypeError", "TypeError", "TypeError", "TypeError", "TypeError", "¢"]) - }) - - test("only UTF-8 is supported; fatal decoding rejects malformed input", async () => { - expect((await error(`new TextDecoder("latin1")`)).message).toContain('The "latin1" encoding is not supported') - expect((await error(`new TextDecoder("utf-8", { fatal: true }).decode(new Uint8Array([0xff]))`)).message).toContain( - "not valid utf-8", - ) - expect((await error(`new TextDecoder().decode("text")`)).message).toContain( - "expects a Uint8Array, received a string", - ) - expect((await error(`TextDecoder()`)).message).toContain("requires 'new'") - }) - - test("crypto.getRandomValues fills the given bytes in place", async () => { - expect( - await value( - `const b = new Uint8Array(16); const same = crypto.getRandomValues(b) === b; return [same, b.length, b.some((n) => n !== 0)]`, - ), - ).toEqual([true, 16, true]) - expect((await error(`crypto.getRandomValues([1])`)).message).toContain("expects a Uint8Array, received an array") - }) -}) - -describe("Iterator helpers", () => { - test("lazy helpers chain over collection iterators and generators, one source step per result", async () => { - expect( - await value(` - const pulled = [] - function* naturals() { let n = 0; while (true) { pulled.push(n); yield n++ } } - const squares = naturals().map((n) => n * n).filter((n) => n % 2 === 0).drop(1).take(3) - const first = squares.next() - return { - first, - rest: squares.toArray(), - after: squares.next(), - pulled, - values: new Map([["a", 1], ["b", 2]]).values().map((v, i) => v * 10 + i).toArray(), - flat: [1, 2].values().flatMap((n) => [n, [n]]).toArray(), - entries: [...new Map([[1, 2]]).entries().map(([k, v]) => k + v)], - } - `), - ).toEqual({ - first: { value: 4, done: false }, - rest: [16, 36], - after: { done: true }, - pulled: [0, 1, 2, 3, 4, 5, 6], - values: [10, 21], - flat: [1, [1], 2, [2]], - entries: [3], - }) - }) - - test("eager helpers consume the source and close it on early exit", async () => { - expect( - await value(` - const log = [] - function* g() { try { yield 1; yield 2; yield 3 } finally { log.push("closed") } } - const seen = [] - g().forEach((v, i) => seen.push([v, i])) - return { - seen, - sum: g().reduce((a, b) => a + b), - sumFrom: g().reduce((a, b) => a + b, 10), - some: g().some((v) => v === 2), - every: g().every((v) => v < 2), - find: g().find((v) => v > 1), - missing: g().find((v) => v > 5), - log, - } - `), - ).toEqual({ - seen: [ - [1, 0], - [2, 1], - [3, 2], - ], - sum: 6, - sumFrom: 16, - some: true, - every: false, - find: 2, - log: ["closed", "closed", "closed", "closed", "closed", "closed", "closed"], - }) - }) - - test("a helper closes its source when a callback throws, on return(), and on early for...of exit", async () => { - expect( - await value(` - const log = [] - function* g(name) { try { yield 1; yield 2 } finally { log.push(name) } } - const throwing = g("throw").map((v) => { if (v === 2) throw new Error("boom"); return v }) - throwing.next() - let message - try { throwing.next() } catch (error) { message = error.message } - const returned = g("return").map((v) => v) - returned.next() - const closed = returned.return() - for (const v of g("loop").filter((v) => true)) break - return { message, afterThrow: throwing.next(), closed, afterReturn: returned.next(), log } - `), - ).toEqual({ - message: "boom", - afterThrow: { done: true }, - closed: { done: true }, - afterReturn: { done: true }, - log: ["throw", "return", "loop"], - }) - }) - - test("collection iterators have no return() and continue after an early exit, as in JS", async () => { - expect( - await value(` - const it = [1, 2, 3].values() - const found = it.some((v) => v === 2) - return [typeof it.return, found, it.next().value, typeof it.map(x => x).return] - `), - ).toEqual(["undefined", true, 3, "function"]) - }) - - test("Iterator.from and the abstract Iterator constructor", async () => { - expect( - await value(` - const it = [1].values() - let n = 0 - const errors = [] - for (const attempt of [() => Iterator(), () => new Iterator(), () => Iterator.from(5)]) { - try { attempt() } catch (error) { errors.push(error.name) } - } - return [ - Iterator.from(it) === it, - Iterator.from("ab").toArray(), - Iterator.from([1, 2]).map((v) => v * 2).toArray(), - Iterator.from({ next: () => ({ done: n > 1, value: n++ }) }).toArray(), - it instanceof Iterator, - errors, - ] - `), - ).toEqual([true, ["a", "b"], [2, 4], [0, 1], true, ["TypeError", "TypeError", "TypeError"]]) - }) - - test("argument validation", async () => { - const cases: Array<[string, string]> = [ - ["[1].values().map(1)", "Iterator.prototype.map expects a function callback."], - ["[1].values().take(-1)", "Iterator.prototype.take expects a non-negative count, received -1."], - ["[1].values().drop()", "Iterator.prototype.drop expects a non-negative count, received NaN."], - [ - "[1].values().flatMap((v) => 'ab').toArray()", - "Iterator.prototype.flatMap expects an iterable or iterator, received a string.", - ], - ["[].values().reduce((a, b) => a)", "Iterator.prototype.reduce of an empty iterator with no initial value."], - ] - for (const [code, message] of cases) { - expect((await error(`return ${code}`)).message).toContain(message) - } - expect( - await error(` - function* g() { while (true) yield 1 } - const it = g().map(() => it.next()) - return it.next() - `), - ).toMatchObject({ message: expect.stringContaining("Iterator helper is already running.") }) - }) -}) - -describe("built-in iterators", () => { - test("keys/values/entries and [Symbol.iterator] step with next() and stay live", async () => { - expect( - await value(` - const items = ["a"] - const it = items.entries() - items.push("b") - const steps = [it.next(), it.next(), it.next()] - items.push("c") - return { steps, after: it.next(), same: items[Symbol.iterator] === items.values } - `), - ).toEqual({ - steps: [{ value: [0, "a"], done: false }, { value: [1, "b"], done: false }, { done: true }], - after: { done: true }, - same: true, - }) - expect( - await value(` - const s = new Set([1, 2]) - const u = new URLSearchParams("a=1&b=2") - const h = new Headers({ b: "2", a: "1" }) - const bytes = new Uint8Array([7, 8]) - return [ - [...s.entries()], [...s[Symbol.iterator]()], s[Symbol.iterator] === s.values, - [...u.keys()], [...u[Symbol.iterator]()], u[Symbol.iterator] === u.entries, - [...h.values()], [...h[Symbol.iterator]()], h[Symbol.iterator] === h.entries, - [...bytes.entries()], [...bytes[Symbol.iterator]()], bytes[Symbol.iterator] === bytes.values, - [..."ab"[Symbol.iterator]()], - ] - `), - ).toEqual([ - [ - [1, 1], - [2, 2], - ], - [1, 2], - true, - ["a", "b"], - [ - ["a", "1"], - ["b", "2"], - ], - true, - ["1", "2"], - [ - ["a", "1"], - ["b", "2"], - ], - true, - [ - [0, 7], - [1, 8], - ], - [7, 8], - true, - ["a", "b"], - ]) - }) - - test("iterators are consumed once by every iteration site", async () => { - expect( - await value(` - const it = [1, 2, 3, 4].values() - const picked = [] - for (const item of it) { picked.push(item); if (item === 2) break } - const [third] = it - return { picked, third, rest: [...it], spent: Array.from(it), again: it[Symbol.iterator]() === it } - `), - ).toEqual({ picked: [1, 2], third: 3, rest: [4], spent: [], again: true }) - expect( - await value(` - const m = new Map([["a", 1], ["b", 2]]) - return [ - Object.fromEntries(m.entries()), Array.from(m.keys(), (k) => k + "!"), new Set(m.values()).size, - await Promise.all([Promise.resolve(1), 2].values()), - ] - `), - ).toEqual([{ a: 1, b: 2 }, ["a!", "b!"], 2, [1, 2]]) - expect(await value(`let s = 0; for await (const v of [Promise.resolve(1), 2].values()) s += v; return s`)).toBe(3) - expect( - await value(`return new Set([1, 2]).union({ size: 1, has: () => false, keys: () => new Set([3]).keys() })`), - ).toEqual([1, 2, 3]) - }) - - test("iterators are opaque references", async () => { - expect(await value(`return [1].keys()`)).toEqual({}) - expect(await value(`return JSON.stringify({ it: [1].keys() })`)).toBe('{"it":{}}') - expect(await value(`return [typeof [1].keys(), Array.isArray([1].keys()), Object.keys([1].keys())]`)).toEqual([ - "object", - false, - [], - ]) - const logged = await run(`console.log([1].keys()); return null`) - expect(logged.logs?.[0]).toBe("[opaque reference]") - expect((await error(`return [1].keys() + ""`)).message).toContain("Binary operators require data values") - expect((await error(`return [1].keys().next.call({})`)).message).toContain( - "Iterator.prototype.next called on incompatible receiver a data object", - ) - expect((await error(`const it = [1].keys(); const next = it.next; return next()`)).message).toContain( - "Iterator.prototype.next called on incompatible receiver undefined", - ) - }) -}) - -describe("Object.prototype.toString", () => { - test("reports the built-in kind it is inherited by, as JS does through Symbol.toStringTag", async () => { - expect( - await value(` - return [ - new Map().toString(), new Set().toString(), new Headers().toString(), Promise.resolve(1).toString(), - [1].values().toString(), ({}).toString(), String(new Map()), String(Promise.resolve(1)), - \`\${new Set([1])}\`, [new Map()] + "", new Map() == "[object Map]", - ] - `), - ).toEqual([ - "[object Map]", - "[object Set]", - "[object Headers]", - "[object Promise]", - "[object Iterator]", - "[object Object]", - "[object Map]", - "[object Promise]", - "[object Set]", - "[object Map]", - true, - ]) - }) -}) - -describe("console.log of errors", () => { - test("prints name and message, nested too", async () => { - const result = await run(`console.log(new Error("boom"), { e: new RangeError("r") })`) - expect(result.logs).toEqual(['Error: boom {"e":RangeError: r}']) - }) -}) - -describe("toLocaleString", () => { - test("numbers format as en-US and dates as en-US in the local timezone; everything else falls back to toString", async () => { - expect( - await value(` - return [ - (1234567.891).toLocaleString(), new Date(0).toLocaleString(), new Date(0).toLocaleDateString(), - new Date(0).toLocaleTimeString(), "a".toLocaleString(), true.toLocaleString(), ({}).toLocaleString(), - ({ toString: () => "custom" }).toLocaleString(), new Uint8Array([1, 2]).toLocaleString(), - ] - `), - ).toEqual([ - "1,234,567.891", - new Date(0).toLocaleString("en-US"), - new Date(0).toLocaleDateString("en-US"), - new Date(0).toLocaleTimeString("en-US"), - "a", - "true", - "[object Object]", - "custom", - "1,2", - ]) - }) - - test("arrays join each element's toLocaleString, skipping holes and nullish elements", async () => { - expect( - await value(` - let calls = 0 - const item = { toLocaleString() { calls++; return "o" } } - return [[1234.5, "x", null, undefined, item, new Date(0)].toLocaleString(), [, item, , item].toLocaleString(), calls] - `), - ).toEqual([`1,234.5,x,,,o,${new Date(0).toLocaleString("en-US")}`, ",o,,o", 3]) - expect((await error(`const f = ({}).toLocaleString; f()`)).message).toContain( - "Object.prototype.toLocaleString called on null or undefined", - ) - }) - - test("dates honor the locale and options, through Intl", async () => { - expect( - await value(` - const d = new Date(Date.UTC(2024, 0, 15, 13, 5, 9)) - return [ - d.toLocaleString("en-US", { timeZone: "Asia/Tokyo" }), - d.toLocaleDateString(undefined, { weekday: "long", timeZone: "UTC" }), - d.toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" }), - d.toLocaleString("de-DE", { timeZone: "UTC" }), - d.toLocaleString("en-GB", { timeZone: "UTC" }), - d.toLocaleString(["fr-FR"], { timeZone: "UTC", dateStyle: "full", timeStyle: "short" }), - d.toLocaleTimeString("en-US", { timeZone: "America/New_York", timeZoneName: "short", hour: "2-digit", minute: "2-digit" }), - d.toLocaleString("en-US", { timeZone: "UTC", hour12: false }), - new Date(NaN).toLocaleString("en-US", { timeZone: "UTC" }), - d.toLocaleDateString({ length: 1, 0: "de-DE" }, { timeZone: "UTC" }), - d.toLocaleDateString({}, { timeZone: "UTC" }), - ] - `), - ).toEqual([ - "1/15/2024, 10:05:09 PM", - "Monday", - "Jan 15", - "15.1.2024, 13:05:09", - "15/01/2024, 13:05:09", - "lundi 15 janvier 2024 à 13:05", - "08:05 AM EST", - "1/15/2024, 13:05:09", - "Invalid Date", - "15.1.2024", - "1/15/2024", - ]) - }) - - test("date formatting without a timeZone uses the local time, like getHours", async () => { - expect( - await value(` - const d = new Date(Date.UTC(2024, 0, 15, 13, 5, 9)) - return [d.toLocaleString(), Number(d.toLocaleTimeString("en-US", { hour: "numeric", hour12: false })) === d.getHours()] - `), - ).toEqual([new Date(Date.UTC(2024, 0, 15, 13, 5, 9)).toLocaleString("en-US"), true]) - }) - - test("date options are read once, through getters and conversions", async () => { - expect( - await value(` - let calls = 0 - const options = { get timeZone() { calls++; return { toString: () => "Asia/Tokyo" } }, hour: "numeric", hour12: false } - return [new Date(Date.UTC(2024, 0, 15, 13)).toLocaleTimeString([{ toString: () => "en-US" }], options), calls] - `), - ).toEqual(["22", 1]) - }) - - test("invalid date options throw like Intl", async () => { - expect( - await value(` - const d = new Date(0) - return [ - () => d.toLocaleString("en-US", { timeZone: "Nope" }), - () => d.toLocaleTimeString("en-US", { dateStyle: "short" }), - () => d.toLocaleString("en-US", null), - () => d.toLocaleString(null), - () => d.toLocaleString("!!"), - ].map((f) => { try { return f() } catch (e) { return e.name } }) - `), - ).toEqual(["RangeError", "TypeError", "TypeError", "TypeError", "RangeError"]) - }) - - test("toLocaleLowerCase and toLocaleUpperCase ignore the locale argument", async () => { - expect( - await value(`return ["ABC".toLocaleLowerCase("tr"), "abc".toLocaleUpperCase(), "İ".toLocaleLowerCase()]`), - ).toEqual(["abc", "ABC", "i̇"]) - }) -}) - -describe("stdlib integration", () => { - test("constructor follows own keys, shadowing, writes, and new", async () => { - expect( - await value(`return [JSON.parse('{"constructor":"Foo"}').constructor, ({ constructor: 1 }).constructor]`), - ).toEqual(["Foo", 1]) - expect(await value(`const Array = 5; return [].constructor.isArray([])`)).toBe(true) - expect(await value(`const o = {}; o.constructor = 7; return o.constructor`)).toBe(7) - expect(await value(`return new ([].constructor)(3).length`)).toBe(3) - expect(await value(`return typeof ({}).constructor`)).toBe("function") - expect(await value(`return ({}).constructor.constructor === Function`)).toBe(true) - }) - - test("new dispatches on the constructor value, not its name", async () => { - expect(await value(`const D = Date; return new D(0) instanceof Date`)).toBe(true) - expect(await value(`const make = (C) => new C([["a", 1]]); return make(Map).get("a")`)).toBe(1) - expect(await value(`const t = { M: Map }; return new t.M() instanceof Map`)).toBe(true) - const shadowed = await error(`const Date = 5; return new Date()`) - expect(shadowed.message).toStartWith("TypeError: Date is not a constructor.") - const fn = await error(`const f = () => 1; return new f()`) - expect(fn.message).toStartWith("TypeError: f is not a constructor: only classes") - }) - - test("Object.is uses SameValue semantics", async () => { - expect( - await value(` - const object = {} - return [ - Object.is(NaN, NaN), - Object.is(0, -0), - Object.is(object, object), - Object.is({}, {}), - ] - `), - ).toEqual([true, false, true, false]) - }) - - test("Object.is compares opaque runtime references by identity", async () => { - expect(await value(`return [Object.is(Math.max, Math.max), Object.is(Math.max, Math.min)]`)).toEqual([true, false]) - }) - - test("Object values and entries accept arrays", async () => { - expect(await value(`return [Object.values(["a", "b"]), Object.entries(["a", "b"])]`)).toEqual([ - ["a", "b"], - [ - ["0", "a"], - ["1", "b"], - ], - ]) - expect(await value(`const match = /a/.exec("ba"); return [Object.values(match), Object.entries(match)]`)).toEqual([ - ["a", 1, "ba"], - [ - ["0", "a"], - ["index", 1], - ["input", "ba"], - ], - ]) - expect(await value(`return Object.keys(Object.values({ match: /a/.exec("ba") })[0])`)).toEqual([ - "0", - "index", - "input", - ]) - }) - - test("Object.fromEntries accepts every supported entry collection", async () => { - expect( - await value(` - return [ - Object.fromEntries([["a", 1]]), - Object.fromEntries(new Map([["b", 2]])), - Object.fromEntries(new Set([["c", 3]])), - Object.fromEntries(new URLSearchParams("d=4")), - Object.fromEntries([{ 0: "e", 1: 5 }]), - Object.fromEntries(new Set([[{}, 6], [new Date(0), 7], [null, 8], [undefined, 9]])), - ] - `), - ).toEqual([ - { a: 1 }, - { b: 2 }, - { c: 3 }, - { d: "4" }, - { e: 5 }, - { "[object Object]": 6, "1970-01-01T00:00:00.000Z": 7, null: 8, undefined: 9 }, - ]) - expect(await value(`try { Object.fromEntries(new Set([Math.max])); return false } catch { return true }`)).toBe( - true, - ) - expect( - await value(`try { Object.fromEntries(new Map([["fn", Math.max]])); return false } catch { return true }`), - ).toBe(true) - }) - - test("deterministic Math methods match the host runtime", async () => { - const result = await value(` - return [ - Math.acos(0.5), Math.acosh(2), Math.asin(0.5), Math.asinh(2), Math.atan(1), Math.atan2(1, 2), Math.atanh(0.5), - Math.cos(0.5), Math.cosh(0.5), Math.sin(0.5), Math.sinh(0.5), Math.tan(0.5), Math.tanh(0.5), - Math.log1p(0.5), Math.expm1(0.5), Math.f16round(1.337), Math.fround(1.337), Math.clz32(1), Math.imul(2, 3), - ] - `) - expect(result).toEqual([ - Math.acos(0.5), - Math.acosh(2), - Math.asin(0.5), - Math.asinh(2), - Math.atan(1), - Math.atan2(1, 2), - Math.atanh(0.5), - Math.cos(0.5), - Math.cosh(0.5), - Math.sin(0.5), - Math.sinh(0.5), - Math.tan(0.5), - Math.tanh(0.5), - Math.log1p(0.5), - Math.expm1(0.5), - Math.f16round(1.337), - Math.fround(1.337), - Math.clz32(1), - Math.imul(2, 3), - ]) - }) - - test("Object.assign mutates and returns its target", async () => { - expect( - await value(` - const target = { a: 1 } - const result = Object.assign(target, { b: 2 }) - return { target, result, same: target === result } - `), - ).toEqual({ target: { a: 1, b: 2 }, result: { a: 1, b: 2 }, same: true }) - expect(await value(`try { Object.assign(null, { a: 1 }); return false } catch { return true }`)).toBe(true) - }) - - test("Object.assign rejects direct and nested cycles", async () => { - expect( - await value(` - const target = { kept: true } - try { Object.assign(target, { self: target }) } catch { return target } - return null - `), - ).toEqual({ kept: true }) - expect( - await value(` - const target = { kept: true } - const nested = { target } - try { Object.assign(target, { nested }) } catch { return target } - return null - `), - ).toEqual({ kept: true }) - expect( - await value(` - const target = {} - const source = {} - source[Symbol.iterator] = target - try { Object.assign(target, source) } catch { return Object.hasOwn(target, Symbol.iterator) } - return true - `), - ).toBe(false) - expect( - await value(` - const target = {} - const nested = {} - nested[Symbol.iterator] = target - try { Object.assign(target, { nested }) } catch { return Object.hasOwn(target, "nested") } - return true - `), - ).toBe(false) - }) - - test("Object.assign preserves mutations before a circular field", async () => { - expect( - await value(` - const target = {} - try { Object.assign(target, { before: 1, cycle: { target }, after: 2 }) } catch { return target } - return null - `), - ).toEqual({ before: 1 }) - expect( - await value(` - const target = {} - const marker = {} - const source = {} - source[Symbol.iterator] = marker - source[Symbol.asyncIterator] = target - try { Object.assign(target, source) } catch { - return [target[Symbol.iterator] === marker, Object.hasOwn(target, Symbol.asyncIterator)] - } - return null - `), - ).toEqual([true, false]) - }) - - test("Object.assign preserves target identity and acyclic shared aliases", async () => { - expect( - await value(` - const shared = { count: 1 } - const target = {} - const result = Object.assign(target, { left: shared, right: shared }) - result.left.count = 2 - return [result === target, result.left === shared, result.left === result.right, shared.count] - `), - ).toEqual([true, true, true, 2]) - }) - - test("assignment resolves and reads its left side before evaluating the right side", async () => { - expect(await value(`let x = 1; x += (x = 5); return x`)).toBe(6) - expect(await value(`let i = 0; const values = [9]; values[i++] = i; return [values, i]`)).toEqual([[1], 1]) - expect(await value(`let i = 0; const values = [10, 20]; values[i++] += i; return [values, i]`)).toEqual([ - [11, 20], - 1, - ]) - }) - - test("typeof reports constructors as functions and never throws", async () => { - expect(await value(`return typeof Map`)).toBe("function") - expect(await value(`return typeof ((x) => x)`)).toBe("function") - expect(await value(`return typeof Math`)).toBe("object") - expect(await value(`return typeof tools`)).toBe("object") - }) - - test("negation works on any value", async () => { - expect(await value(`return !new Map()`)).toBe(false) - expect(await value(`const fn = () => 1; return !fn`)).toBe(false) - }) - - test("object spread of CodeMode values is a no-op, like JS", async () => { - expect(await value(`return { ...new Map([["a", 1]]), kept: true }`)).toEqual({ kept: true }) - }) - - test("dates inside Map values survive in-CodeMode reads", async () => { - expect( - await value(` - const m = new Map([["start", new Date(1000)]]) - return m.get("start").getTime() - `), - ).toBe(1000) - }) - - test("instanceof recognizes the stdlib value types", async () => { - expect( - await value( - `return [new Date(0) instanceof Date, /a/ instanceof RegExp, new Map() instanceof Map, new Set() instanceof Set]`, - ), - ).toEqual([true, true, true, true]) - expect( - await value(`return [[1] instanceof Array, [1] instanceof Object, ({}) instanceof Object, 5 instanceof Object]`), - ).toEqual([true, true, true, false]) - expect(await value(`return [new Map() instanceof Set, "s" instanceof Date]`)).toEqual([false, false]) - expect( - await value(`const p = Promise.resolve(1); const isPromise = p instanceof Promise; await p; return isPromise`), - ).toBe(true) - }) - - test("realistic pipeline: parse, extract with regex, dedupe, count by day", async () => { - expect( - await value(` - const raw = '[{"at":"2024-01-01T05:00:00Z","tag":"a b"},{"at":"2024-01-01T09:00:00Z","tag":"b c"},{"at":"2024-01-02T01:00:00Z","tag":"a"}]' - const rows = JSON.parse(raw) - const tags = new Set() - const byDay = new Map() - for (const row of rows) { - for (const m of row.tag.matchAll(/[a-z]+/g)) tags.add(m[0]) - const day = new Date(row.at).toISOString().slice(0, 10) - byDay.set(day, (byDay.get(day) ?? 0) + 1) - } - return { tags: [...tags].sort((a, b) => (a < b ? -1 : 1)), byDay: Object.fromEntries(byDay) } - `), - ).toEqual({ tags: ["a", "b", "c"], byDay: { "2024-01-01": 2, "2024-01-02": 1 } }) - }) -}) describe("CodeMode values at intra-CodeMode checkpoints", () => { - test("Object.values/entries keep Dates usable", async () => { - expect(await value(`return Object.values({ d: new Date(0) })[0].getTime()`)).toBe(0) - expect(await value(`const [key, d] = Object.entries({ d: new Date(0) })[0]; return key + ":" + d.getTime()`)).toBe( - "d:0", - ) - }) - - test("Object.values/entries preserve nested object identity", async () => { - expect( - await value(` - const child = { selected: false } - const rows = { a: child } - Object.values(rows)[0].selected = true - return child.selected - `), - ).toBe(true) - expect( - await value(` - const child = { selected: false } - const rows = { a: child } - Object.entries(rows)[0][1].selected = true - return child.selected - `), - ).toBe(true) - }) - - test("Object enumeration preserves promises and callable references", async () => { - expect( - await value(` - const pending = Promise.resolve(1) - const source = { pending } - return [Object.keys(source), Object.hasOwn(source, "pending"), await Object.values(source)[0], await Object.entries(source)[0][1]] - `), - ).toEqual([["pending"], true, 1, 1]) - expect(await value(`return Object.values({ max: Math.max })[0](1, 2)`)).toBe(2) - }) - - test("Object enumeration rejects invalid receivers and gives promises an await hint", async () => { - const diagnostic = await error(`return Object.keys(Promise.resolve({ a: 1 }))`) - expect(diagnostic.kind).toBe("InvalidDataValue") - expect(diagnostic.message).toContain("await") - expect(await value(`return Object.keys(Math)`)).toEqual([]) - }) - - test("Object.assign keeps Maps usable", async () => { - expect(await value(`const merged = Object.assign({}, { m: new Map([["a", 1]]) }); return merged.m.get("a")`)).toBe( - 1, - ) - }) - - test("object and array spread keep CodeMode values usable", async () => { - expect( - await value(` - const src = { m: new Map([["a", 1]]) } - const copy = { ...src } - copy.m.set("b", 2) - return [copy.m.get("a"), src.m.get("b")] - `), - ).toEqual([1, 2]) - expect(await value(`const list = [new Date(1000)]; const copy = [...list]; return copy[0].getTime()`)).toBe(1000) - }) - - test("Array.from over arrays keeps nested CodeMode values usable", async () => { - expect(await value(`return Array.from([new Date(5)])[0].getTime()`)).toBe(5) - }) - - test("Array.from and Array.of preserve nested object identity", async () => { - expect( - await value(` - const child = { selected: false } - Array.from([child])[0].selected = true - return child.selected - `), - ).toBe(true) - expect( - await value(` - const child = { selected: false } - Array.of(child)[0].selected = true - return child.selected - `), - ).toBe(true) - }) - - test("Array.from and Array.of preserve promises and callable references", async () => { - expect( - await value(` - const pending = Promise.resolve(1) - return [await Array.from([pending])[0], await Array.of(pending)[0]] - `), - ).toEqual([1, 1]) - expect(await value(`return [Array.from([Math.max])[0](1, 2), Array.of(Math.max)[0](3, 4)]`)).toEqual([2, 4]) - }) - - test("Array.from preserves identity across supported collection shapes", async () => { - expect( - await value(` - const child = { selected: false } - const fromArrayLike = Array.from({ 0: child, length: 1 }) - const fromMap = Array.from(new Map([["child", child]])) - const fromSet = Array.from(new Set([child])) - fromArrayLike[0].selected = true - return [fromMap[0][1] === child, fromSet[0] === child, child.selected] - `), - ).toEqual([true, true, true]) - }) - - test("Array.from rejects invalid receivers and gives promises an await hint", async () => { - const diagnostic = await error(`return Array.from(Promise.resolve([1]))`) - expect(diagnostic.kind).toBe("InvalidDataValue") - expect(diagnostic.message).toContain("await") - expect(await value(`return Array.from((a, b) => 1)`)).toEqual([null, null]) - }) - - test("regexes stay callable through Object.values", async () => { - expect(await value(`return Object.values({ r: /ab+/ })[0].test("abb")`)).toBe(true) - }) - - test("Object.* helpers see CodeMode values as empty objects, never internals", async () => { - expect(await value(`return Object.keys(new Map([["a", 1]]))`)).toEqual([]) - expect(await value(`return Object.values(new Date(0))`)).toEqual([]) - expect(await value(`return Object.entries(new Set([1]))`)).toEqual([]) - expect(await value(`return Object.assign({}, new Map([["a", 1]]))`)).toEqual({}) - expect(await value(`return Object.hasOwn(new Date(0), "time")`)).toBe(false) - }) - test("the host boundary still serializes JSON forms: results, JSON.stringify, and tool arguments", async () => { expect(await value(`return { d: new Date(0), m: new Map([["a", 1]]) }`)).toEqual({ d: "1970-01-01T00:00:00.000Z", @@ -2168,121 +42,3 @@ describe("CodeMode values at intra-CodeMode checkpoints", () => { expect(observed).toStrictEqual([{ when: "1970-01-01T00:00:00.000Z", tags: {} }]) }) }) - -describe("Uint8Array callback methods", () => { - test.each(["'1'", "true", "false", "null", "{}", "undefined", "NaN"])( - "typed-array searches do not coerce %s into a byte", - async (search) => { - expect( - await value(` - const bytes = new Uint8Array([0, 1, 2, 1]) - return [bytes.indexOf(${search}), bytes.lastIndexOf(${search}), bytes.includes(${search})] - `), - ).toEqual([-1, -1, false]) - }, - ) - - test("typed-array searches keep numeric matching and start-index coercion", async () => { - expect( - await value(` - const bytes = new Uint8Array([0, 1, 2, 1]) - return [ - bytes.indexOf(1, "2"), bytes.lastIndexOf(1, "2"), bytes.includes(2, "3"), - bytes.indexOf(-0), bytes.includes(257), bytes.indexOf(1, -1) - ] - `), - ).toEqual([3, 1, false, 0, false, 3]) - }) - - test("map and filter return new Uint8Arrays with clamped bytes", async () => { - expect( - await value(` - const b = new Uint8Array([1, 2, 3]) - const mapped = b.map((byte) => byte * 100) - const filtered = b.filter((byte) => byte > 1) - mapped[0] = 9 - return [ - [...mapped], mapped instanceof Uint8Array, Array.isArray(mapped), [...b], [...filtered], - [...b.map(() => "7")], b.map((byte) => byte, {}).length, [...new Uint8Array().map((byte) => byte)], - ] - `), - ).toEqual([[9, 200, 44], true, false, [1, 2, 3], [2, 3], [7, 7, 7], 3, []]) - }) - - test("find, findIndex, findLast, findLastIndex, some, every, and forEach", async () => { - expect( - await value(` - const b = new Uint8Array([1, 2, 3]) - const seen = [] - b.forEach((byte, index, array) => seen.push([byte, index, array === b])) - return [ - b.find((byte) => byte > 1), b.find((byte) => byte > 5) === undefined, b.findIndex((byte) => byte > 1), - b.findIndex((byte) => byte > 5), b.findLast((byte) => byte < 3), b.findLastIndex((byte) => byte < 3), - b.findLastIndex((byte) => byte > 9), b.some((byte) => byte > 2), b.every((byte) => byte > 2), - new Uint8Array().some(() => true), new Uint8Array().every(() => false), - b.every((byte, index, array) => array === b), seen, - ] - `), - ).toEqual([ - 2, - true, - 1, - -1, - 2, - 1, - -1, - true, - false, - false, - true, - true, - [ - [1, 0, true], - [2, 1, true], - [3, 2, true], - ], - ]) - }) - - test("reduce and reduceRight", async () => { - expect( - await value(` - const b = new Uint8Array([1, 2, 3]) - return [ - b.reduce((sum, byte) => sum + byte), b.reduce((sum, byte) => sum + byte, 10), - b.reduceRight((text, byte) => text + byte, ""), new Uint8Array().reduce((sum, byte) => sum + byte, 5), - b.reduce((_, byte, index, array) => array === b && index, 0), - ] - `), - ).toEqual([6, 16, "321", 5, 2]) - expect((await error(`new Uint8Array().reduce((sum, byte) => sum + byte)`)).message).toContain( - "Uint8Array.reduce of an empty array with no initial value", - ) - expect((await error(`new Uint8Array().reduceRight((sum, byte) => sum + byte)`)).message).toContain( - "Uint8Array.reduceRight of an empty array with no initial value", - ) - expect((await error(`new Uint8Array([1]).map(null)`)).message).toContain("Uint8Array.map expects a function") - }) - - test("sort is numeric by default and in place, with an optional comparator", async () => { - expect( - await value(` - const b = new Uint8Array([10, 9, 1]) - const same = b.sort() === b - const desc = new Uint8Array([3, 1, 2]).sort((x, y) => y - x) - return [same, [...b], [...desc], desc instanceof Uint8Array, [...new Uint8Array([2, 1]).sort(() => NaN)]] - `), - ).toEqual([true, [1, 9, 10], [3, 2, 1], true, [2, 1]]) - expect((await error(`new Uint8Array([2, 1]).sort(null)`)).message).toContain("Uint8Array.sort expects a function") - }) - - test("lastIndexOf treats an explicit undefined fromIndex as 0", async () => { - expect( - await value(` - const a = [1, 2, 1] - const b = new Uint8Array([1, 2, 1]) - return [a.lastIndexOf(1, undefined), a.lastIndexOf(1), a.lastIndexOf(2, undefined), b.lastIndexOf(1, undefined), b.lastIndexOf(1)] - `), - ).toEqual([0, 2, -1, 0, 2]) - }) -}) diff --git a/packages/codemode/test/string-core-test262.test.ts b/packages/codemode/test/string-core-test262.test.ts deleted file mode 100644 index 9173fe352da..00000000000 --- a/packages/codemode/test/string-core-test262.test.ts +++ /dev/null @@ -1,758 +0,0 @@ -/* - * Portions adapted from Test262 at revision 250f204f23a9249ff204be2baec29600faae7b75: - * - test/built-ins/String/prototype/toLowerCase/S15.5.4.16_A2_T1.js - * - test/built-ins/String/prototype/toLowerCase/special_casing.js - * - test/built-ins/String/prototype/toLowerCase/special_casing_conditional.js - * - test/built-ins/String/prototype/toLowerCase/Final_Sigma_U180E.js - * - test/built-ins/String/prototype/toLowerCase/supplementary_plane.js - * - test/built-ins/String/prototype/toUpperCase/S15.5.4.18_A2_T1.js - * - test/built-ins/String/prototype/toUpperCase/special_casing.js - * - test/built-ins/String/prototype/toUpperCase/supplementary_plane.js - * - test/built-ins/String/prototype/trim/15.5.4.20-3-1.js - * - test/built-ins/String/prototype/trim/15.5.4.20-3-2.js - * - test/built-ins/String/prototype/trim/15.5.4.20-3-3.js - * - test/built-ins/String/prototype/trim/15.5.4.20-3-4.js - * - test/built-ins/String/prototype/trim/15.5.4.20-3-5.js - * - test/built-ins/String/prototype/trim/15.5.4.20-3-6.js - * - test/built-ins/String/prototype/trim/15.5.4.20-3-7.js - * - test/built-ins/String/prototype/trim/15.5.4.20-3-8.js - * - test/built-ins/String/prototype/trim/15.5.4.20-3-9.js - * - test/built-ins/String/prototype/trim/15.5.4.20-3-10.js - * - test/built-ins/String/prototype/trim/15.5.4.20-3-11.js - * - test/built-ins/String/prototype/trim/15.5.4.20-3-12.js - * - test/built-ins/String/prototype/trim/15.5.4.20-3-13.js - * - test/built-ins/String/prototype/trim/15.5.4.20-3-14.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-1.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-2.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-3.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-4.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-5.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-6.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-8.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-10.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-11.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-12.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-13.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-14.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-16.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-18.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-19.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-20.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-21.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-22.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-24.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-27.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-28.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-29.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-30.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-32.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-34.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-35.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-36.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-37.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-38.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-39.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-40.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-41.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-42.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-43.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-44.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-45.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-46.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-47.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-48.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-49.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-50.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-51.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-52.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-53.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-54.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-55.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-56.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-57.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-58.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-59.js - * - test/built-ins/String/prototype/trim/15.5.4.20-4-60.js - * - test/built-ins/String/prototype/trim/u180e.js - * - test/built-ins/String/prototype/trimStart/this-value-whitespace.js - * - test/built-ins/String/prototype/trimStart/this-value-line-terminator.js - * - test/built-ins/String/prototype/trimEnd/this-value-whitespace.js - * - test/built-ins/String/prototype/trimEnd/this-value-line-terminator.js - * - test/built-ins/String/prototype/repeat/repeat-string-n-times.js - * - test/built-ins/String/prototype/repeat/empty-string-returns-empty.js - * - test/built-ins/String/prototype/repeat/count-is-zero-returns-empty-string.js - * - test/built-ins/String/prototype/repeat/count-coerced-to-zero-returns-empty-string.js - * - test/built-ins/String/prototype/padStart/fill-string-empty.js - * - test/built-ins/String/prototype/padStart/normal-operation.js - * - test/built-ins/String/prototype/padStart/fill-string-omitted.js - * - test/built-ins/String/prototype/padStart/max-length-not-greater-than-string.js - * - test/built-ins/String/prototype/padEnd/fill-string-empty.js - * - test/built-ins/String/prototype/padEnd/normal-operation.js - * - test/built-ins/String/prototype/padEnd/fill-string-omitted.js - * - test/built-ins/String/prototype/padEnd/max-length-not-greater-than-string.js - * - test/built-ins/String/prototype/charAt/S15.5.4.4_A1_T4.js - * - test/built-ins/String/prototype/charAt/S15.5.4.4_A1_T7.js - * - test/built-ins/String/prototype/charAt/S15.5.4.4_A1_T8.js - * - test/built-ins/String/prototype/charAt/S15.5.4.4_A4_T1.js - * - test/built-ins/String/prototype/charAt/S15.5.4.4_A4_T2.js - * - test/built-ins/String/prototype/charAt/S15.5.4.4_A4_T3.js - * - test/built-ins/String/prototype/charAt/S9.4_A1.js - * - test/built-ins/String/prototype/charAt/S9.4_A2.js - * - test/built-ins/String/prototype/charAt/pos-rounding.js - * - test/built-ins/String/prototype/charCodeAt/S15.5.4.5_A1_T4.js - * - test/built-ins/String/prototype/charCodeAt/S15.5.4.5_A1_T7.js - * - test/built-ins/String/prototype/charCodeAt/S15.5.4.5_A1_T8.js - * - test/built-ins/String/prototype/charCodeAt/pos-rounding.js - * - test/built-ins/String/prototype/codePointAt/return-single-code-unit.js - * - test/built-ins/String/prototype/codePointAt/return-first-code-unit.js - * - test/built-ins/String/prototype/codePointAt/return-utf16-decode.js - * - test/built-ins/String/prototype/codePointAt/return-code-unit-coerced-position.js - * - test/built-ins/String/prototype/codePointAt/returns-undefined-on-position-less-than-zero.js - * - test/built-ins/String/prototype/codePointAt/returns-undefined-on-position-equal-or-more-than-size.js - * - test/built-ins/String/prototype/at/returns-code-unit.js - * - test/built-ins/String/prototype/at/returns-item.js - * - test/built-ins/String/prototype/at/returns-item-relative-index.js - * - test/built-ins/String/prototype/at/returns-undefined-for-out-of-range-index.js - * - test/built-ins/String/prototype/at/index-non-numeric-argument-tointeger.js - * - test/built-ins/String/prototype/concat/S15.5.4.6_A1_T4.js - * - test/built-ins/String/prototype/toString/string-primitive.js - * - test/built-ins/String/prototype/normalize/return-normalized-string.js - * - test/built-ins/String/prototype/normalize/return-normalized-string-using-default-parameter.js - * - test/built-ins/String/prototype/normalize/form-is-not-valid-throws.js - * - test/built-ins/String/prototype/localeCompare/15.5.4.9_CE.js - * - test/built-ins/String/fromCharCode/S15.5.3.2_A2.js - * - test/built-ins/String/fromCharCode/S15.5.3.2_A3_T1.js - * - test/built-ins/String/fromCharCode/S9.7_A1.js - * - test/built-ins/String/fromCharCode/S9.7_A2.1.js - * - test/built-ins/String/fromCharCode/S9.7_A2.2.js - * - test/built-ins/String/fromCharCode/S9.7_A3.2_T1.js - * - test/built-ins/String/fromCodePoint/arguments-is-empty.js - * - test/built-ins/String/fromCodePoint/return-string-value.js - * - test/built-ins/String/fromCodePoint/argument-is-not-integer.js - * - test/built-ins/String/fromCodePoint/number-is-out-of-range.js - * - * Copyright 2009 the Sputnik authors. All rights reserved. - * Copyright (C) 2009 the Sputnik authors. All rights reserved. - * Copyright (c) 2012 Ecma International. All rights reserved. - * Copyright 2012 Norbert Lindenberg. All rights reserved. - * Copyright 2012 Mozilla Corporation. All rights reserved. - * Copyright 2013 Microsoft Corporation. All rights reserved. - * Copyright (C) 2015 the V8 project authors. All rights reserved. - * Copyright (C) 2015 André Bargull. All rights reserved. - * Copyright (C) 2016 the V8 project authors. All rights reserved. - * Copyright (C) 2016 André Bargull. All rights reserved. - * Copyright (C) 2016 Jordan Harband. All rights reserved. - * Copyright (C) 2016 Mathias Bynens. All rights reserved. - * Copyright (c) 2017 Valerie Young. All rights reserved. - * Copyright (C) 2017 Valerie Young. All rights reserved. - * Copyright (C) 2020 Rick Waldron. All rights reserved. - * Copyright (C) 2022 Richard Gibson. All rights reserved. - * Test262 portions are governed by the BSD license in LICENSE.test262. - */ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" - -type Argument = string | number | undefined -type Outcome = "undefined" | "length" | "RangeError" -type Assertion = { - label: string - input?: string - args?: ReadonlyArray - expected?: string | number - outcome?: Outcome -} -type Vector = { - path: string - method: string - static?: boolean - assertions: ReadonlyArray -} - -const value = async (code: string) => { - const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} })) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -const literal = (input: Argument) => { - if (input === undefined) return "undefined" - if (typeof input === "string") return JSON.stringify(input) - if (Number.isNaN(input)) return "NaN" - if (input === Infinity) return "Infinity" - if (input === -Infinity) return "-Infinity" - if (Object.is(input, -0)) return "-0" - return JSON.stringify(input) -} - -const vectors: Array = [] -const add = (path: string, method: string, assertions: ReadonlyArray, staticMethod = false) => { - vectors.push({ path, method, assertions, static: staticMethod }) -} -const assertion = (label: string, input: string, expected: string | number, args: ReadonlyArray = []) => ({ - label, - input, - args, - expected, -}) - -add("test/built-ins/String/prototype/toLowerCase/S15.5.4.16_A2_T1.js", "toLowerCase", [ - assertion("#1 direct value", "Hello, WoRlD!", "hello, world!"), - assertion("#2 String value", "Hello, WoRlD!", "hello, world!"), -]) -add("test/built-ins/String/prototype/toLowerCase/special_casing.js", "toLowerCase", [ - assertion( - "103 SpecialCasing mappings", - "\u00DF\u0130\uFB00\uFB01\uFB02\uFB03\uFB04\uFB05\uFB06\u0587\uFB13\uFB14\uFB15\uFB16\uFB17\u0149\u0390\u03B0\u01F0\u1E96\u1E97\u1E98\u1E99\u1E9A\u1F50\u1F52\u1F54\u1F56\u1FB6\u1FC6\u1FD2\u1FD3\u1FD6\u1FD7\u1FE2\u1FE3\u1FE4\u1FE6\u1FE7\u1FF6\u1F80\u1F81\u1F82\u1F83\u1F84\u1F85\u1F86\u1F87\u1F88\u1F89\u1F8A\u1F8B\u1F8C\u1F8D\u1F8E\u1F8F\u1F90\u1F91\u1F92\u1F93\u1F94\u1F95\u1F96\u1F97\u1F98\u1F99\u1F9A\u1F9B\u1F9C\u1F9D\u1F9E\u1F9F\u1FA0\u1FA1\u1FA2\u1FA3\u1FA4\u1FA5\u1FA6\u1FA7\u1FA8\u1FA9\u1FAA\u1FAB\u1FAC\u1FAD\u1FAE\u1FAF\u1FB3\u1FBC\u1FC3\u1FCC\u1FF3\u1FFC\u1FB2\u1FB4\u1FC2\u1FC4\u1FF2\u1FF4\u1FB7\u1FC7\u1FF7", - "\u00DF\u0069\u0307\uFB00\uFB01\uFB02\uFB03\uFB04\uFB05\uFB06\u0587\uFB13\uFB14\uFB15\uFB16\uFB17\u0149\u0390\u03B0\u01F0\u1E96\u1E97\u1E98\u1E99\u1E9A\u1F50\u1F52\u1F54\u1F56\u1FB6\u1FC6\u1FD2\u1FD3\u1FD6\u1FD7\u1FE2\u1FE3\u1FE4\u1FE6\u1FE7\u1FF6\u1F80\u1F81\u1F82\u1F83\u1F84\u1F85\u1F86\u1F87\u1F80\u1F81\u1F82\u1F83\u1F84\u1F85\u1F86\u1F87\u1F90\u1F91\u1F92\u1F93\u1F94\u1F95\u1F96\u1F97\u1F90\u1F91\u1F92\u1F93\u1F94\u1F95\u1F96\u1F97\u1FA0\u1FA1\u1FA2\u1FA3\u1FA4\u1FA5\u1FA6\u1FA7\u1FA0\u1FA1\u1FA2\u1FA3\u1FA4\u1FA5\u1FA6\u1FA7\u1FB3\u1FB3\u1FC3\u1FC3\u1FF3\u1FF3\u1FB2\u1FB4\u1FC2\u1FC4\u1FF2\u1FF4\u1FB7\u1FC7\u1FF7", - ), -]) -add("test/built-ins/String/prototype/toLowerCase/special_casing_conditional.js", "toLowerCase", [ - assertion("single sigma", "\u03A3", "\u03C3"), - assertion("preceded by cased", "A\u03A3", "a\u03C2"), - assertion("preceded by supplementary cased", "\uD835\uDCA2\u03A3", "\uD835\uDCA2\u03C2"), - assertion("preceded by full stop", "A.\u03A3", "a.\u03C2"), - assertion("preceded by soft hyphen", "A\u00AD\u03A3", "a\u00AD\u03C2"), - assertion("preceded by combining mark", "A\uD834\uDE42\u03A3", "a\uD834\uDE42\u03C2"), - assertion("preceded by uncased combining mark", "\u0345\u03A3", "\u0345\u03C3"), - assertion("preceded by cased and combining mark", "\u0391\u0345\u03A3", "\u03B1\u0345\u03C2"), - assertion("followed by cased", "A\u03A3B", "a\u03C3b"), - assertion("followed by supplementary cased", "A\u03A3\uD835\uDCA2", "a\u03C3\uD835\uDCA2"), - assertion("followed by full stop and cased", "A\u03A3.b", "a\u03C3.b"), - assertion("followed by soft hyphen and cased", "A\u03A3\u00ADB", "a\u03C3\u00ADb"), - assertion("followed by combining mark and cased", "A\u03A3\uD834\uDE42B", "a\u03C3\uD834\uDE42b"), - assertion("followed by uncased combining mark", "A\u03A3\u0345", "a\u03C2\u0345"), - assertion("followed by combining mark and cased Greek", "A\u03A3\u0345\u0391", "a\u03C3\u0345\u03B1"), -]) -add("test/built-ins/String/prototype/toLowerCase/Final_Sigma_U180E.js", "toLowerCase", [ - assertion("preceded by U+180E", "A\u180E\u03A3", "a\u180E\u03C2"), - assertion("preceded by U+180E and followed by cased", "A\u180E\u03A3B", "a\u180E\u03C3b"), - assertion("followed by U+180E", "A\u03A3\u180E", "a\u03C2\u180E"), - assertion("followed by U+180E and cased", "A\u03A3\u180EB", "a\u03C3\u180Eb"), - assertion("surrounded by U+180E", "A\u180E\u03A3\u180E", "a\u180E\u03C2\u180E"), - assertion("surrounded by U+180E and followed by cased", "A\u180E\u03A3\u180EB", "a\u180E\u03C3\u180Eb"), -]) -add("test/built-ins/String/prototype/toLowerCase/supplementary_plane.js", "toLowerCase", [ - assertion( - "40 Deseret mappings", - "\uD801\uDC00\uD801\uDC01\uD801\uDC02\uD801\uDC03\uD801\uDC04\uD801\uDC05\uD801\uDC06\uD801\uDC07\uD801\uDC08\uD801\uDC09\uD801\uDC0A\uD801\uDC0B\uD801\uDC0C\uD801\uDC0D\uD801\uDC0E\uD801\uDC0F\uD801\uDC10\uD801\uDC11\uD801\uDC12\uD801\uDC13\uD801\uDC14\uD801\uDC15\uD801\uDC16\uD801\uDC17\uD801\uDC18\uD801\uDC19\uD801\uDC1A\uD801\uDC1B\uD801\uDC1C\uD801\uDC1D\uD801\uDC1E\uD801\uDC1F\uD801\uDC20\uD801\uDC21\uD801\uDC22\uD801\uDC23\uD801\uDC24\uD801\uDC25\uD801\uDC26\uD801\uDC27", - "\uD801\uDC28\uD801\uDC29\uD801\uDC2A\uD801\uDC2B\uD801\uDC2C\uD801\uDC2D\uD801\uDC2E\uD801\uDC2F\uD801\uDC30\uD801\uDC31\uD801\uDC32\uD801\uDC33\uD801\uDC34\uD801\uDC35\uD801\uDC36\uD801\uDC37\uD801\uDC38\uD801\uDC39\uD801\uDC3A\uD801\uDC3B\uD801\uDC3C\uD801\uDC3D\uD801\uDC3E\uD801\uDC3F\uD801\uDC40\uD801\uDC41\uD801\uDC42\uD801\uDC43\uD801\uDC44\uD801\uDC45\uD801\uDC46\uD801\uDC47\uD801\uDC48\uD801\uDC49\uD801\uDC4A\uD801\uDC4B\uD801\uDC4C\uD801\uDC4D\uD801\uDC4E\uD801\uDC4F", - ), -]) -add("test/built-ins/String/prototype/toUpperCase/S15.5.4.18_A2_T1.js", "toUpperCase", [ - assertion("#1 direct value", "Hello, WoRlD!", "HELLO, WORLD!"), - assertion("#2 String value", "Hello, WoRlD!", "HELLO, WORLD!"), -]) -add("test/built-ins/String/prototype/toUpperCase/special_casing.js", "toUpperCase", [ - assertion( - "103 SpecialCasing mappings", - "\u00DF\u0130\uFB00\uFB01\uFB02\uFB03\uFB04\uFB05\uFB06\u0587\uFB13\uFB14\uFB15\uFB16\uFB17\u0149\u0390\u03B0\u01F0\u1E96\u1E97\u1E98\u1E99\u1E9A\u1F50\u1F52\u1F54\u1F56\u1FB6\u1FC6\u1FD2\u1FD3\u1FD6\u1FD7\u1FE2\u1FE3\u1FE4\u1FE6\u1FE7\u1FF6\u1F80\u1F81\u1F82\u1F83\u1F84\u1F85\u1F86\u1F87\u1F88\u1F89\u1F8A\u1F8B\u1F8C\u1F8D\u1F8E\u1F8F\u1F90\u1F91\u1F92\u1F93\u1F94\u1F95\u1F96\u1F97\u1F98\u1F99\u1F9A\u1F9B\u1F9C\u1F9D\u1F9E\u1F9F\u1FA0\u1FA1\u1FA2\u1FA3\u1FA4\u1FA5\u1FA6\u1FA7\u1FA8\u1FA9\u1FAA\u1FAB\u1FAC\u1FAD\u1FAE\u1FAF\u1FB3\u1FBC\u1FC3\u1FCC\u1FF3\u1FFC\u1FB2\u1FB4\u1FC2\u1FC4\u1FF2\u1FF4\u1FB7\u1FC7\u1FF7", - "\u0053\u0053\u0130\u0046\u0046\u0046\u0049\u0046\u004C\u0046\u0046\u0049\u0046\u0046\u004C\u0053\u0054\u0053\u0054\u0535\u0552\u0544\u0546\u0544\u0535\u0544\u053B\u054E\u0546\u0544\u053D\u02BC\u004E\u0399\u0308\u0301\u03A5\u0308\u0301\u004A\u030C\u0048\u0331\u0054\u0308\u0057\u030A\u0059\u030A\u0041\u02BE\u03A5\u0313\u03A5\u0313\u0300\u03A5\u0313\u0301\u03A5\u0313\u0342\u0391\u0342\u0397\u0342\u0399\u0308\u0300\u0399\u0308\u0301\u0399\u0342\u0399\u0308\u0342\u03A5\u0308\u0300\u03A5\u0308\u0301\u03A1\u0313\u03A5\u0342\u03A5\u0308\u0342\u03A9\u0342\u1F08\u0399\u1F09\u0399\u1F0A\u0399\u1F0B\u0399\u1F0C\u0399\u1F0D\u0399\u1F0E\u0399\u1F0F\u0399\u1F08\u0399\u1F09\u0399\u1F0A\u0399\u1F0B\u0399\u1F0C\u0399\u1F0D\u0399\u1F0E\u0399\u1F0F\u0399\u1F28\u0399\u1F29\u0399\u1F2A\u0399\u1F2B\u0399\u1F2C\u0399\u1F2D\u0399\u1F2E\u0399\u1F2F\u0399\u1F28\u0399\u1F29\u0399\u1F2A\u0399\u1F2B\u0399\u1F2C\u0399\u1F2D\u0399\u1F2E\u0399\u1F2F\u0399\u1F68\u0399\u1F69\u0399\u1F6A\u0399\u1F6B\u0399\u1F6C\u0399\u1F6D\u0399\u1F6E\u0399\u1F6F\u0399\u1F68\u0399\u1F69\u0399\u1F6A\u0399\u1F6B\u0399\u1F6C\u0399\u1F6D\u0399\u1F6E\u0399\u1F6F\u0399\u0391\u0399\u0391\u0399\u0397\u0399\u0397\u0399\u03A9\u0399\u03A9\u0399\u1FBA\u0399\u0386\u0399\u1FCA\u0399\u0389\u0399\u1FFA\u0399\u038F\u0399\u0391\u0342\u0399\u0397\u0342\u0399\u03A9\u0342\u0399", - ), -]) -add("test/built-ins/String/prototype/toUpperCase/supplementary_plane.js", "toUpperCase", [ - assertion( - "40 Deseret mappings", - "\uD801\uDC28\uD801\uDC29\uD801\uDC2A\uD801\uDC2B\uD801\uDC2C\uD801\uDC2D\uD801\uDC2E\uD801\uDC2F\uD801\uDC30\uD801\uDC31\uD801\uDC32\uD801\uDC33\uD801\uDC34\uD801\uDC35\uD801\uDC36\uD801\uDC37\uD801\uDC38\uD801\uDC39\uD801\uDC3A\uD801\uDC3B\uD801\uDC3C\uD801\uDC3D\uD801\uDC3E\uD801\uDC3F\uD801\uDC40\uD801\uDC41\uD801\uDC42\uD801\uDC43\uD801\uDC44\uD801\uDC45\uD801\uDC46\uD801\uDC47\uD801\uDC48\uD801\uDC49\uD801\uDC4A\uD801\uDC4B\uD801\uDC4C\uD801\uDC4D\uD801\uDC4E\uD801\uDC4F", - "\uD801\uDC00\uD801\uDC01\uD801\uDC02\uD801\uDC03\uD801\uDC04\uD801\uDC05\uD801\uDC06\uD801\uDC07\uD801\uDC08\uD801\uDC09\uD801\uDC0A\uD801\uDC0B\uD801\uDC0C\uD801\uDC0D\uD801\uDC0E\uD801\uDC0F\uD801\uDC10\uD801\uDC11\uD801\uDC12\uD801\uDC13\uD801\uDC14\uD801\uDC15\uD801\uDC16\uD801\uDC17\uD801\uDC18\uD801\uDC19\uD801\uDC1A\uD801\uDC1B\uD801\uDC1C\uD801\uDC1D\uD801\uDC1E\uD801\uDC1F\uD801\uDC20\uD801\uDC21\uD801\uDC22\uD801\uDC23\uD801\uDC24\uD801\uDC25\uD801\uDC26\uD801\uDC27", - ), -]) - -const whitespace = - "\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF" -const lineTerminators = "\u000A\u000D\u2028\u2029" -const trim = (file: string, input: string, expected: string) => - add(`test/built-ins/String/prototype/trim/${file}`, "trim", [assertion("upstream assertion", input, expected)]) - -trim("15.5.4.20-3-1.js", lineTerminators, "") -trim("15.5.4.20-3-2.js", whitespace, "") -trim("15.5.4.20-3-3.js", whitespace + lineTerminators, "") -trim("15.5.4.20-3-4.js", whitespace + lineTerminators + "abc", "abc") -trim("15.5.4.20-3-5.js", "abc" + whitespace + lineTerminators, "abc") -trim("15.5.4.20-3-6.js", whitespace + lineTerminators + "abc" + whitespace + lineTerminators, "abc") -trim("15.5.4.20-3-7.js", "ab" + whitespace + lineTerminators + "cd", "ab" + whitespace + lineTerminators + "cd") -trim("15.5.4.20-3-8.js", "\0\u0000", "\0\u0000") -trim("15.5.4.20-3-9.js", "\0", "\0") -trim("15.5.4.20-3-10.js", "\u0000", "\u0000") -trim("15.5.4.20-3-11.js", "\0\u0000abc", "\0\u0000abc") -trim("15.5.4.20-3-12.js", "abc\0\u0000", "abc\0\u0000") -trim("15.5.4.20-3-13.js", "\0\u0000abc\0\u0000", "\0\u0000abc\0\u0000") -trim("15.5.4.20-3-14.js", "a\0\u0000bc", "a\0\u0000bc") -trim("15.5.4.20-4-1.js", "\u0009a bc \u0009", "a bc") -trim("15.5.4.20-4-2.js", " \u0009abc \u0009", "abc") -trim("15.5.4.20-4-3.js", "\u0009abc", "abc") -trim("15.5.4.20-4-4.js", "\u000Babc", "abc") -trim("15.5.4.20-4-5.js", "\u000Cabc", "abc") -trim("15.5.4.20-4-6.js", "\u0020abc", "abc") -trim("15.5.4.20-4-8.js", "\u00A0abc", "abc") -trim("15.5.4.20-4-10.js", "\uFEFFabc", "abc") -trim("15.5.4.20-4-11.js", "abc\u0009", "abc") -trim("15.5.4.20-4-12.js", "abc\u000B", "abc") -trim("15.5.4.20-4-13.js", "abc\u000C", "abc") -trim("15.5.4.20-4-14.js", "abc\u0020", "abc") -trim("15.5.4.20-4-16.js", "abc\u00A0", "abc") -trim("15.5.4.20-4-18.js", "abc\uFEFF", "abc") -trim("15.5.4.20-4-19.js", "\u0009abc\u0009", "abc") -trim("15.5.4.20-4-20.js", "\u000Babc\u000B", "abc") -trim("15.5.4.20-4-21.js", "\u000Cabc\u000C", "abc") -trim("15.5.4.20-4-22.js", "\u0020abc\u0020", "abc") -trim("15.5.4.20-4-24.js", "\u00A0abc\u00A0", "abc") -trim("15.5.4.20-4-27.js", "\u0009\u0009", "") -trim("15.5.4.20-4-28.js", "\u000B\u000B", "") -trim("15.5.4.20-4-29.js", "\u000C\u000C", "") -trim("15.5.4.20-4-30.js", "\u0020\u0020", "") -trim("15.5.4.20-4-32.js", "\u00A0\u00A0", "") -trim("15.5.4.20-4-34.js", "\uFEFF\uFEFF", "") -trim("15.5.4.20-4-35.js", "ab\u0009c", "ab\u0009c") -trim("15.5.4.20-4-36.js", "ab\u000Bc", "ab\u000Bc") -trim("15.5.4.20-4-37.js", "ab\u000Cc", "ab\u000Cc") -trim("15.5.4.20-4-38.js", "ab\u0020c", "ab\u0020c") -trim("15.5.4.20-4-39.js", "ab\u0085c", "ab\u0085c") -trim("15.5.4.20-4-40.js", "ab\u00A0c", "ab\u00A0c") -trim("15.5.4.20-4-41.js", "ab\u200Bc", "ab\u200Bc") -trim("15.5.4.20-4-42.js", "ab\uFEFFc", "ab\uFEFFc") -trim("15.5.4.20-4-43.js", "\u000Aabc", "abc") -trim("15.5.4.20-4-44.js", "\u000Dabc", "abc") -trim("15.5.4.20-4-45.js", "\u2028abc", "abc") -trim("15.5.4.20-4-46.js", "\u2029abc", "abc") -trim("15.5.4.20-4-47.js", "abc\u000A", "abc") -trim("15.5.4.20-4-48.js", "abc\u000D", "abc") -trim("15.5.4.20-4-49.js", "abc\u2028", "abc") -trim("15.5.4.20-4-50.js", "abc\u2029", "abc") -trim("15.5.4.20-4-51.js", "\u000Aabc\u000A", "abc") -trim("15.5.4.20-4-52.js", "\u000Dabc\u000D", "abc") -trim("15.5.4.20-4-53.js", "\u2028abc\u2028", "abc") -trim("15.5.4.20-4-54.js", "\u2029abc\u2029", "abc") -trim("15.5.4.20-4-55.js", "\u000A\u000A", "") -trim("15.5.4.20-4-56.js", "\u000D\u000D", "") -trim("15.5.4.20-4-57.js", "\u2028\u2028", "") -trim("15.5.4.20-4-58.js", "\u2029\u2029", "") -trim("15.5.4.20-4-59.js", "\u2029 abc", "abc") -trim("15.5.4.20-4-60.js", " ", "") -add("test/built-ins/String/prototype/trim/u180e.js", "trim", [ - assertion("trailing U+180E", "_\u180E", "_\u180E"), - assertion("only U+180E", "\u180E", "\u180E"), - assertion("leading U+180E", "\u180E_", "\u180E_"), -]) - -const directionalWhitespace = - "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF" -add("test/built-ins/String/prototype/trimStart/this-value-whitespace.js", "trimStart", [ - assertion( - "all whitespace", - directionalWhitespace + "a" + directionalWhitespace + "b" + directionalWhitespace, - "a" + directionalWhitespace + "b" + directionalWhitespace, - ), -]) -add("test/built-ins/String/prototype/trimStart/this-value-line-terminator.js", "trimStart", [ - assertion( - "all line terminators", - lineTerminators + "a" + lineTerminators + "b" + lineTerminators, - "a" + lineTerminators + "b" + lineTerminators, - ), -]) -add("test/built-ins/String/prototype/trimEnd/this-value-whitespace.js", "trimEnd", [ - assertion( - "all whitespace", - directionalWhitespace + "a" + directionalWhitespace + "b" + directionalWhitespace, - directionalWhitespace + "a" + directionalWhitespace + "b", - ), -]) -add("test/built-ins/String/prototype/trimEnd/this-value-line-terminator.js", "trimEnd", [ - assertion( - "all line terminators", - lineTerminators + "a" + lineTerminators + "b" + lineTerminators, - lineTerminators + "a" + lineTerminators + "b", - ), -]) -add("test/built-ins/String/prototype/repeat/repeat-string-n-times.js", "repeat", [ - assertion("repeat once", "abc", "abc", [1]), - assertion("repeat three times", "abc", "abcabcabc", [3]), - { label: "repeat 10000 times length", input: ".", args: [10000], expected: 10000, outcome: "length" }, -]) -add("test/built-ins/String/prototype/repeat/empty-string-returns-empty.js", "repeat", [ - assertion("count 1", "", "", [1]), - assertion("count 3", "", "", [3]), - assertion("maximum 32-bit count", "", "", [0xffffffff]), -]) -add("test/built-ins/String/prototype/repeat/count-is-zero-returns-empty-string.js", "repeat", [ - assertion("zero", "foo", "", [0]), -]) -add("test/built-ins/String/prototype/repeat/count-coerced-to-zero-returns-empty-string.js", "repeat", [ - assertion("fraction truncates to zero", "abc", "", [0.9]), -]) -add("test/built-ins/String/prototype/padStart/fill-string-empty.js", "padStart", [ - assertion("empty fill", "abc", "abc", [5, ""]), -]) -add("test/built-ins/String/prototype/padStart/normal-operation.js", "padStart", [ - assertion("truncated multi-character fill", "abc", "defdabc", [7, "def"]), - assertion("single-character fill", "abc", "**abc", [5, "*"]), - assertion("truncated surrogate pair", "abc", "\uD83D\uDCA9\uD83Dabc", [6, "\uD83D\uDCA9"]), -]) -add("test/built-ins/String/prototype/padStart/fill-string-omitted.js", "padStart", [ - assertion("omitted fill", "abc", " abc", [5]), - assertion("undefined fill", "abc", " abc", [5, undefined]), -]) -add("test/built-ins/String/prototype/padStart/max-length-not-greater-than-string.js", "padStart", [ - assertion("NaN", "abc", "abc", [NaN, "def"]), - assertion("negative infinity", "abc", "abc", [-Infinity, "def"]), - assertion("zero", "abc", "abc", [0, "def"]), - assertion("negative one", "abc", "abc", [-1, "def"]), - assertion("equal length", "abc", "abc", [3, "def"]), - assertion("fraction truncates", "abc", "abc", [3.9999, "def"]), -]) -add("test/built-ins/String/prototype/padEnd/fill-string-empty.js", "padEnd", [ - assertion("empty fill", "abc", "abc", [5, ""]), -]) -add("test/built-ins/String/prototype/padEnd/normal-operation.js", "padEnd", [ - assertion("truncated multi-character fill", "abc", "abcdefd", [7, "def"]), - assertion("single-character fill", "abc", "abc**", [5, "*"]), - assertion("truncated surrogate pair", "abc", "abc\uD83D\uDCA9\uD83D", [6, "\uD83D\uDCA9"]), -]) -add("test/built-ins/String/prototype/padEnd/fill-string-omitted.js", "padEnd", [ - assertion("omitted fill", "abc", "abc ", [5]), - assertion("undefined fill", "abc", "abc ", [5, undefined]), -]) -add("test/built-ins/String/prototype/padEnd/max-length-not-greater-than-string.js", "padEnd", [ - assertion("NaN", "abc", "abc", [NaN, "def"]), - assertion("negative infinity", "abc", "abc", [-Infinity, "def"]), - assertion("zero", "abc", "abc", [0, "def"]), - assertion("negative one", "abc", "abc", [-1, "def"]), - assertion("equal length", "abc", "abc", [3, "def"]), - assertion("fraction truncates", "abc", "abc", [3.9999, "def"]), -]) - -add("test/built-ins/String/prototype/charAt/S15.5.4.4_A1_T4.js", "charAt", [assertion("omitted position", "lego", "l")]) -add("test/built-ins/String/prototype/charAt/S15.5.4.4_A1_T7.js", "charAt", [ - assertion("undefined position", "lego", "l", [undefined]), -]) -add("test/built-ins/String/prototype/charAt/S15.5.4.4_A1_T8.js", "charAt", [ - assertion("undefined position", "42", "4", [undefined]), -]) -add( - "test/built-ins/String/prototype/charAt/S15.5.4.4_A4_T1.js", - "charAt", - ["A", "B", "C", "A", "B", "C"].map((expected, position) => - assertion(`position ${position}`, "ABCABC", expected, [position]), - ), -) -add( - "test/built-ins/String/prototype/charAt/S15.5.4.4_A4_T2.js", - "charAt", - [-2, -1].map((position) => assertion(`position ${position}`, "ABCABC", "", [position])), -) -add( - "test/built-ins/String/prototype/charAt/S15.5.4.4_A4_T3.js", - "charAt", - [6, 7].map((position) => assertion(`position ${position}`, "ABCABC", "", [position])), -) -add("test/built-ins/String/prototype/charAt/S9.4_A1.js", "charAt", [assertion("NaN position", "abc", "a", [NaN])]) -add("test/built-ins/String/prototype/charAt/S9.4_A2.js", "charAt", [ - assertion("positive zero", "abc", "a", [0]), - assertion("negative zero", "abc", "a", [-0]), -]) -add("test/built-ins/String/prototype/charAt/pos-rounding.js", "charAt", [ - assertion("-0.99999", "abc", "a", [-0.99999]), - assertion("-0.00001", "abc", "a", [-0.00001]), - assertion("0.00001", "abc", "a", [0.00001]), - assertion("0.99999", "abc", "a", [0.99999]), - assertion("1.00001", "abc", "b", [1.00001]), - assertion("1.99999", "abc", "b", [1.99999]), -]) - -add("test/built-ins/String/prototype/charCodeAt/S15.5.4.5_A1_T4.js", "charCodeAt", [ - assertion("omitted position", "smart", 0x73), -]) -add("test/built-ins/String/prototype/charCodeAt/S15.5.4.5_A1_T7.js", "charCodeAt", [ - assertion("undefined position", "lego", 0x6c, [undefined]), -]) -add("test/built-ins/String/prototype/charCodeAt/S15.5.4.5_A1_T8.js", "charCodeAt", [ - assertion("undefined position", "42", 0x34, [undefined]), -]) -add("test/built-ins/String/prototype/charCodeAt/pos-rounding.js", "charCodeAt", [ - assertion("-0.99999", "abc", 0x61, [-0.99999]), - assertion("-0.00001", "abc", 0x61, [-0.00001]), - assertion("0.00001", "abc", 0x61, [0.00001]), - assertion("0.99999", "abc", 0x61, [0.99999]), - assertion("1.00001", "abc", 0x62, [1.00001]), - assertion("1.99999", "abc", 0x62, [1.99999]), -]) - -add("test/built-ins/String/prototype/codePointAt/return-single-code-unit.js", "codePointAt", [ - assertion("a", "abc", 97, [0]), - assertion("b", "abc", 98, [1]), - assertion("c", "abc", 99, [2]), - assertion("ordinary BMP", "\uAAAA\uBBBB", 0xaaaa, [0]), - assertion("before high-surrogate range", "\uD7FF\uAAAA", 0xd7ff, [0]), - assertion("low surrogate", "\uDC00\uAAAA", 0xdc00, [0]), - assertion("trailing D800", "123\uD800", 0xd800, [3]), - assertion("trailing DAAA", "123\uDAAA", 0xdaaa, [3]), - assertion("trailing DBFF", "123\uDBFF", 0xdbff, [3]), -]) -add("test/built-ins/String/prototype/codePointAt/return-first-code-unit.js", "codePointAt", [ - assertion("D800 before DBFF", "\uD800\uDBFF", 0xd800, [0]), - assertion("D800 before E000", "\uD800\uE000", 0xd800, [0]), - assertion("DAAA before DBFF", "\uDAAA\uDBFF", 0xdaaa, [0]), - assertion("DAAA before E000", "\uDAAA\uE000", 0xdaaa, [0]), - assertion("DBFF before DBFF", "\uDBFF\uDBFF", 0xdbff, [0]), - assertion("DBFF before E000", "\uDBFF\uE000", 0xdbff, [0]), - assertion("D800 before NUL", "\uD800\u0000", 0xd800, [0]), - assertion("D800 before FFFF", "\uD800\uFFFF", 0xd800, [0]), - assertion("DAAA before NUL", "\uDAAA\u0000", 0xdaaa, [0]), - assertion("DAAA before FFFF", "\uDAAA\uFFFF", 0xdaaa, [0]), - assertion("DBFF before FFFF", "\uDBFF\uFFFF", 0xdbff, [0]), -]) -add("test/built-ins/String/prototype/codePointAt/return-utf16-decode.js", "codePointAt", [ - assertion("U+10000", "\uD800\uDC00", 65536, [0]), - assertion("U+101D0", "\uD800\uDDD0", 66000, [0]), - assertion("U+103FF", "\uD800\uDFFF", 66559, [0]), - assertion("U+BA800", "\uDAAA\uDC00", 763904, [0]), - assertion("U+BA9D0", "\uDAAA\uDDD0", 764368, [0]), - assertion("U+BABFF", "\uDAAA\uDFFF", 764927, [0]), - assertion("U+10FC00", "\uDBFF\uDC00", 1113088, [0]), - assertion("U+10FDD0", "\uDBFF\uDDD0", 1113552, [0]), - assertion("U+10FFFF", "\uDBFF\uDFFF", 1114111, [0]), -]) -add("test/built-ins/String/prototype/codePointAt/return-code-unit-coerced-position.js", "codePointAt", [ - assertion("NaN", "\uD800\uDC00", 65536, [NaN]), - assertion("undefined", "\uD800\uDC00", 65536, [undefined]), -]) -add("test/built-ins/String/prototype/codePointAt/returns-undefined-on-position-less-than-zero.js", "codePointAt", [ - { label: "negative one", input: "abc", args: [-1], outcome: "undefined" }, - { label: "negative infinity", input: "abc", args: [-Infinity], outcome: "undefined" }, -]) -add( - "test/built-ins/String/prototype/codePointAt/returns-undefined-on-position-equal-or-more-than-size.js", - "codePointAt", - [ - { label: "equal to size", input: "abc", args: [3], outcome: "undefined" }, - { label: "greater than size", input: "abc", args: [4], outcome: "undefined" }, - { label: "positive infinity", input: "abc", args: [Infinity], outcome: "undefined" }, - ], -) - -add("test/built-ins/String/prototype/at/returns-code-unit.js", "at", [ - assertion("position 0", "12\uD80034", "1", [0]), - assertion("position 1", "12\uD80034", "2", [1]), - assertion("unpaired surrogate", "12\uD80034", "\uD800", [2]), - assertion("position 3", "12\uD80034", "3", [3]), - assertion("position 4", "12\uD80034", "4", [4]), -]) -add( - "test/built-ins/String/prototype/at/returns-item.js", - "at", - ["1", "2", "3", "4", "5"].map((expected, position) => - assertion(`position ${position}`, "12345", expected, [position]), - ), -) -add("test/built-ins/String/prototype/at/returns-item-relative-index.js", "at", [ - assertion("zero", "12345", "1", [0]), - assertion("negative one", "12345", "5", [-1]), - assertion("negative three", "12345", "3", [-3]), - assertion("negative four", "12345", "2", [-4]), -]) -add( - "test/built-ins/String/prototype/at/returns-undefined-for-out-of-range-index.js", - "at", - [-2, 0, 1].map((position) => ({ label: `position ${position}`, input: "", args: [position], outcome: "undefined" })), -) -add("test/built-ins/String/prototype/at/index-non-numeric-argument-tointeger.js", "at", [ - assertion("undefined", "01", "0", [undefined]), -]) - -add("test/built-ins/String/prototype/concat/S15.5.4.6_A1_T4.js", "concat", [assertion("no arguments", "lego", "lego")]) -add("test/built-ins/String/prototype/toString/string-primitive.js", "toString", [ - assertion("empty string", "", ""), - assertion("non-empty string", "str", "str"), -]) - -add("test/built-ins/String/prototype/normalize/return-normalized-string.js", "normalize", [ - assertion("NFC short", "\u1E9B\u0323", "\u1E9B\u0323", ["NFC"]), - assertion("NFD short", "\u1E9B\u0323", "\u017F\u0323\u0307", ["NFD"]), - assertion("NFKC short", "\u1E9B\u0323", "\u1E69", ["NFKC"]), - assertion("NFKD short", "\u1E9B\u0323", "\u0073\u0323\u0307", ["NFKD"]), - assertion("NFC long", "\u00C5\u2ADC\u0958\u2126\u0344", "\xC5\u2ADD\u0338\u0915\u093C\u03A9\u0308\u0301", ["NFC"]), - assertion("NFD long", "\u00C5\u2ADC\u0958\u2126\u0344", "A\u030A\u2ADD\u0338\u0915\u093C\u03A9\u0308\u0301", ["NFD"]), - assertion("NFKC long", "\u00C5\u2ADC\u0958\u2126\u0344", "\xC5\u2ADD\u0338\u0915\u093C\u03A9\u0308\u0301", ["NFKC"]), - assertion("NFKD long", "\u00C5\u2ADC\u0958\u2126\u0344", "A\u030A\u2ADD\u0338\u0915\u093C\u03A9\u0308\u0301", [ - "NFKD", - ]), -]) -add("test/built-ins/String/prototype/normalize/return-normalized-string-using-default-parameter.js", "normalize", [ - assertion("omitted", "\u00C5\u2ADC\u0958\u2126\u0344", "\xC5\u2ADD\u0338\u0915\u093C\u03A9\u0308\u0301"), - assertion("undefined", "\u00C5\u2ADC\u0958\u2126\u0344", "\xC5\u2ADD\u0338\u0915\u093C\u03A9\u0308\u0301", [ - undefined, - ]), -]) -add("test/built-ins/String/prototype/normalize/form-is-not-valid-throws.js", "normalize", [ - { label: "bar", input: "foo", args: ["bar"], outcome: "RangeError" }, - { label: "NFC1", input: "foo", args: ["NFC1"], outcome: "RangeError" }, -]) - -add("test/built-ins/String/prototype/localeCompare/15.5.4.9_CE.js", "localeCompare", [ - assertion("D70", "o\u0308", 0, ["ö"]), - assertion("reordered diaeresis", "ä\u0323", 0, ["a\u0323\u0308"]), - assertion("reordered marks", "a\u0308\u0323", 0, ["a\u0323\u0308"]), - assertion("precomposed dot below", "ạ\u0308", 0, ["a\u0323\u0308"]), - assertion("breve after diaeresis", "ä\u0306", 0, ["a\u0308\u0306"]), - assertion("diaeresis after breve", "ă\u0308", 0, ["a\u0306\u0308"]), - assertion("Hangul", "\u1111\u1171\u11B6", 0, ["퓛"]), - assertion("angstrom compatibility", "Å", 0, ["Å"]), - assertion("angstrom decomposed", "Å", 0, ["A\u030A"]), - assertion("reordered horn and dot", "x\u031B\u0323", 0, ["x\u0323\u031B"]), - assertion("Vietnamese precomposed 1", "ự", 0, ["ụ\u031B"]), - assertion("Vietnamese decomposed", "ự", 0, ["u\u031B\u0323"]), - assertion("Vietnamese precomposed 2", "ự", 0, ["ư\u0323"]), - assertion("Vietnamese reordered", "ự", 0, ["u\u0323\u031B"]), - assertion("cedilla", "Ç", 0, ["C\u0327"]), - assertion("q reordered", "q\u0307\u0323", 0, ["q\u0323\u0307"]), - assertion("Hangul syllable", "가", 0, ["\u1100\u1161"]), - assertion("ohm", "Ω", 0, ["Ω"]), - assertion("angstrom", "Å", 0, ["A\u030A"]), - assertion("circumflex", "ô", 0, ["o\u0302"]), - assertion("s with marks", "ṩ", 0, ["s\u0323\u0307"]), - assertion("d composed plus dot", "ḋ\u0323", 0, ["d\u0323\u0307"]), - assertion("d two precompositions", "ḋ\u0323", 0, ["ḍ\u0307"]), -]) - -add( - "test/built-ins/String/fromCharCode/S15.5.3.2_A2.js", - "fromCharCode", - [{ label: "no arguments", expected: "" }], - true, -) -add( - "test/built-ins/String/fromCharCode/S15.5.3.2_A3_T1.js", - "fromCharCode", - [{ label: "ABBA", args: [65, 66, 66, 65], expected: "ABBA" }], - true, -) -add( - "test/built-ins/String/fromCharCode/S9.7_A1.js", - "fromCharCode", - [ - { label: "NaN", args: [NaN], expected: 0 }, - { label: "zero", args: [0], expected: 0 }, - { label: "negative zero", args: [-0], expected: 0 }, - { label: "positive infinity", args: [Infinity], expected: 0 }, - { label: "negative infinity", args: [-Infinity], expected: 0 }, - ], - true, -) -add( - "test/built-ins/String/fromCharCode/S9.7_A2.1.js", - "fromCharCode", - [ - [0, 0], - [1, 1], - [-1, 65535], - [65535, 65535], - [65534, 65534], - [65536, 0], - [4294967295, 65535], - [4294967294, 65534], - [4294967296, 0], - ].map(([input, expected]) => ({ label: String(input), args: [input!], expected })), - true, -) -add( - "test/built-ins/String/fromCharCode/S9.7_A2.2.js", - "fromCharCode", - [ - [-32767, 32769], - [-32768, 32768], - [-32769, 32767], - [-65535, 1], - [-65536, 0], - [-65537, 65535], - [65535, 65535], - [65536, 0], - [65537, 1], - [131071, 65535], - [131072, 0], - [131073, 1], - ].map(([input, expected]) => ({ label: String(input), args: [input!], expected })), - true, -) -add( - "test/built-ins/String/fromCharCode/S9.7_A3.2_T1.js", - "fromCharCode", - [ - { label: "positive fraction", args: [1.2345], expected: 1 }, - { label: "negative fraction", args: [-5.4321], expected: 65531 }, - ], - true, -) - -add( - "test/built-ins/String/fromCodePoint/arguments-is-empty.js", - "fromCodePoint", - [{ label: "no arguments", expected: "" }], - true, -) -add( - "test/built-ins/String/fromCodePoint/return-string-value.js", - "fromCodePoint", - [ - { label: "NUL", args: [0], expected: "\x00" }, - { label: "asterisk", args: [42], expected: "*" }, - { label: "AZ", args: [65, 90], expected: "AZ" }, - { label: "Cyrillic", args: [0x404], expected: "\u0404" }, - { label: "hex supplementary", args: [0x2f804], expected: "\uD87E\uDC04" }, - { label: "decimal supplementary", args: [194564], expected: "\uD87E\uDC04" }, - { label: "mixed supplementary", args: [0x1d306, 0x61, 0x1d307], expected: "\uD834\uDF06a\uD834\uDF07" }, - { label: "maximum code point", args: [1114111], expected: "\uDBFF\uDFFF" }, - ], - true, -) -add( - "test/built-ins/String/fromCodePoint/argument-is-not-integer.js", - "fromCodePoint", - [ - { label: "fraction", args: [3.14], outcome: "RangeError" }, - { label: "fraction after valid", args: [42, 3.14], outcome: "RangeError" }, - ], - true, -) -add( - "test/built-ins/String/fromCodePoint/number-is-out-of-range.js", - "fromCodePoint", - [ - { label: "negative one", args: [-1], outcome: "RangeError" }, - { label: "negative after valid", args: [1, -1], outcome: "RangeError" }, - { label: "above maximum", args: [1114112], outcome: "RangeError" }, - { label: "infinity", args: [Infinity], outcome: "RangeError" }, - ], - true, -) - -describe("Test262-adapted core String behavior", () => { - for (const vector of vectors) { - test(vector.path, async () => { - const results = vector.assertions.map((item) => { - const args = (item.args ?? []).map(literal).join(", ") - const expression = vector.static - ? `String.${vector.method}(${args})` - : `${JSON.stringify(item.input)}.${vector.method}(${args})` - const observed = - vector.static && vector.method === "fromCharCode" && typeof item.expected === "number" - ? `${expression}.charCodeAt(0)` - : expression - const checked = - item.outcome === "undefined" - ? `${observed} === undefined` - : item.outcome === "length" - ? `${observed}.length` - : item.outcome === "RangeError" - ? `(() => { try { ${observed}; return false } catch (error) { return error instanceof RangeError } })()` - : observed - return `{ label: ${JSON.stringify(item.label)}, value: ${checked} }` - }) - const expected = vector.assertions.map((item) => ({ - label: item.label, - value: item.outcome === undefined || item.outcome === "length" ? item.expected! : true, - })) - expect(await value(`return [${results.join(",")}]`)).toEqual(expected) - }) - } -}) diff --git a/packages/codemode/test/string-date-methods-test262.test.ts b/packages/codemode/test/string-date-methods-test262.test.ts deleted file mode 100644 index 41757052756..00000000000 --- a/packages/codemode/test/string-date-methods-test262.test.ts +++ /dev/null @@ -1,179 +0,0 @@ -/** - * Portions adapted from Test262 at revision 250f204f23a9249ff204be2baec29600faae7b75: - * - test/annexB/built-ins/String/prototype/substr/length-falsey.js - * - test/annexB/built-ins/String/prototype/substr/length-negative.js - * - test/annexB/built-ins/String/prototype/substr/length-positive.js - * - test/annexB/built-ins/String/prototype/substr/length-undef.js - * - test/annexB/built-ins/String/prototype/substr/start-negative.js - * - test/annexB/built-ins/String/prototype/substr/surrogate-pairs.js - * - test/built-ins/String/prototype/isWellFormed/returns-boolean.js - * - test/built-ins/String/prototype/toWellFormed/returns-well-formed-string.js - * - test/built-ins/Date/prototype/toDateString/format.js - * - test/built-ins/Date/prototype/toDateString/invalid-date.js - * - test/built-ins/Date/prototype/toDateString/negative-year.js - * - test/built-ins/Date/prototype/toTimeString/format.js - * - test/built-ins/Date/prototype/toTimeString/invalid-date.js - * - * Copyright (C) 2016, 2017 the V8 project authors. All rights reserved. - * Copyright (C) 2018 Richard Gibson. All rights reserved. - * Copyright (C) 2022 Jordan Harband. All rights reserved. - * Test262 portions are governed by the BSD license in LICENSE.test262. - * - * The `typeof String.prototype.method` checks are replaced with `typeof "".method` because - * CodeMode has no prototype objects. - */ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" - -const value = async (code: string) => { - const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} })) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -describe("String.prototype.substr Test262 parity", () => { - test("test/annexB/built-ins/String/prototype/substr/length-falsey.js", async () => { - expect( - await value(` - return [false, NaN, "", null].flatMap((length) => [0, 1, 2, 3].map((start) => "abc".substr(start, length))) - `), - ).toEqual(Array(16).fill("")) - }) - - test("test/annexB/built-ins/String/prototype/substr/length-negative.js", async () => { - expect( - await value(` - return [0, 1, 2, 3].flatMap((start) => [-1, -2, -3, -4].map((length) => "abc".substr(start, length))) - `), - ).toEqual(Array(16).fill("")) - }) - - test("test/annexB/built-ins/String/prototype/substr/length-positive.js", async () => { - expect( - await value(` - return [0, 1, 2, 3].map((start) => [1, 2, 3, 4].map((length) => "abc".substr(start, length))) - `), - ).toEqual([ - ["a", "ab", "abc", "abc"], - ["b", "bc", "bc", "bc"], - ["c", "c", "c", "c"], - ["", "", "", ""], - ]) - }) - - test("test/annexB/built-ins/String/prototype/substr/length-undef.js", async () => { - expect( - await value(` - return [ - "abc".substr(0), "abc".substr(1), "abc".substr(2), "abc".substr(3), - "abc".substr(0, undefined), "abc".substr(1, undefined), "abc".substr(2, undefined), "abc".substr(3, undefined), - ] - `), - ).toEqual(["abc", "bc", "c", "", "abc", "bc", "c", ""]) - }) - - test("test/annexB/built-ins/String/prototype/substr/start-negative.js", async () => { - expect( - await value(` - return ["abc".substr(-1), "abc".substr(-2), "abc".substr(-3), "abc".substr(-4), "abc".substr(-1.1)] - `), - ).toEqual(["c", "bc", "abc", "abc", "c"]) - }) - - test("test/annexB/built-ins/String/prototype/substr/surrogate-pairs.js", async () => { - expect( - await value(` - const pair = "\\ud834\\udf06" - return [pair.substr(0), pair.substr(1), pair.substr(2), pair.substr(0, 0), pair.substr(0, 1), pair.substr(0, 2)] - `), - ).toEqual(["\ud834\udf06", "\udf06", "", "", "\ud834", "\ud834\udf06"]) - }) -}) - -describe("String well-formedness Test262 parity", () => { - test("test/built-ins/String/prototype/isWellFormed/returns-boolean.js", async () => { - expect( - await value(` - const leadingPoo = "\\uD83D" - const trailingPoo = "\\uDCA9" - const wholePoo = leadingPoo + trailingPoo - return [ - typeof "".isWellFormed, - ("a" + leadingPoo + "c" + leadingPoo + "e").isWellFormed(), - ("a" + trailingPoo + "c" + trailingPoo + "e").isWellFormed(), - ("a" + trailingPoo + leadingPoo + "d").isWellFormed(), - "a💩c".isWellFormed(), - "a\\uD83D\\uDCA9c".isWellFormed(), - ("a" + leadingPoo + trailingPoo + "d").isWellFormed(), - wholePoo.slice(0, 1).isWellFormed(), - wholePoo.slice(1).isWellFormed(), - "abc".isWellFormed(), - "a\\u25A8c".isWellFormed(), - ] - `), - ).toEqual(["function", false, false, false, true, true, true, false, false, true, true]) - }) - - test("test/built-ins/String/prototype/toWellFormed/returns-well-formed-string.js", async () => { - expect( - await value(` - const replacementChar = "\\uFFFD" - const leadingPoo = "\\uD83D" - const trailingPoo = "\\uDCA9" - const wholePoo = leadingPoo + trailingPoo - return [ - typeof "".toWellFormed, - ("a" + leadingPoo + "c" + leadingPoo + "e").toWellFormed() === "a" + replacementChar + "c" + replacementChar + "e", - ("a" + trailingPoo + "c" + trailingPoo + "e").toWellFormed() === "a" + replacementChar + "c" + replacementChar + "e", - ("a" + trailingPoo + leadingPoo + "d").toWellFormed() === "a" + replacementChar + replacementChar + "d", - "a💩c".toWellFormed() === "a💩c", - "a\\uD83D\\uDCA9c".toWellFormed() === "a\\uD83D\\uDCA9c", - ("a" + leadingPoo + trailingPoo + "d").toWellFormed() === "a" + wholePoo + "d", - wholePoo.slice(0, 1).toWellFormed() === replacementChar, - wholePoo.slice(1).toWellFormed() === replacementChar, - "abc".toWellFormed() === "abc", - "a\\u25A8c".toWellFormed() === "a\\u25A8c", - ] - `), - ).toEqual(["function", true, true, true, true, true, true, true, true, true, true]) - }) -}) - -describe("Date string formatting Test262 parity", () => { - test("test/built-ins/Date/prototype/toDateString/format.js", async () => { - expect( - await value(` - const dateRegExp = /^(Sun|Mon|Tue|Wed|Thu|Fri|Sat) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [0-9]{2} [0-9]{4}$/ - return [dateRegExp.test(new Date(0).toDateString()), dateRegExp.test(new Date("0020-01-01T00:00:00Z").toDateString())] - `), - ).toEqual([true, true]) - }) - - test("test/built-ins/Date/prototype/toDateString/invalid-date.js", async () => { - expect(await value(`return new Date(NaN).toDateString()`)).toBe("Invalid Date") - }) - - test("test/built-ins/Date/prototype/toDateString/negative-year.js", async () => { - expect( - await value(` - return ["-000001", "-000012", "-000123", "-001234", "-012345", "-123456"].map( - (year) => new Date(year + "-07-01T00:00Z").toDateString().split(" ")[3], - ) - `), - ).toEqual(["-0001", "-0012", "-0123", "-1234", "-12345", "-123456"]) - }) - - test("test/built-ins/Date/prototype/toTimeString/format.js", async () => { - expect( - await value(` - const timeRegExp = /^[0-9]{2}:[0-9]{2}:[0-9]{2} GMT[+-][0-9]{4}( \\(.+\\))?$/ - return timeRegExp.test(new Date(0).toTimeString()) - `), - ).toBe(true) - }) - - test("test/built-ins/Date/prototype/toTimeString/invalid-date.js", async () => { - expect(await value(`return new Date(NaN).toTimeString()`)).toBe("Invalid Date") - }) -}) diff --git a/packages/codemode/test/string-regexp-test262.test.ts b/packages/codemode/test/string-regexp-test262.test.ts deleted file mode 100644 index fa0d6f709d6..00000000000 --- a/packages/codemode/test/string-regexp-test262.test.ts +++ /dev/null @@ -1,731 +0,0 @@ -/* - * Portions adapted from Test262 at revision 250f204f23a9249ff204be2baec29600faae7b75: - * - test/built-ins/String/prototype/split/separator-regexp.js - * - test/built-ins/String/prototype/split/arguments-are-regexp-s-and-3-and-instance-is-string-a-b-c-de-f.js - * - test/built-ins/String/prototype/split/argument-is-regexp-s-and-instance-is-string-a-b-c-de-f.js - * - test/built-ins/String/prototype/split/argument-is-regexp-d-and-instance-is-string-dfe23iu-34-65.js - * - test/built-ins/String/prototype/split/argument-is-regexp-reg-exp-d-and-instance-is-string-dfe23iu-34-65.js - * - test/built-ins/String/prototype/split/argument-is-regexp-a-z-and-instance-is-string-abc.js - * - test/built-ins/String/prototype/split/argument-is-reg-exp-a-z-and-instance-is-string-abc.js - * - test/built-ins/String/prototype/split/arguments-are-regexp-l-and-undefined-and-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/arguments-are-regexp-l-and-0-and-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/arguments-are-regexp-l-and-1-and-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/arguments-are-regexp-l-and-2-and-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/arguments-are-regexp-l-and-3-and-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/arguments-are-regexp-l-and-4-and-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/argument-is-regexp-l-and-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/argument-is-new-reg-exp-and-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/arguments-are-new-reg-exp-and-0-and-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/arguments-are-new-reg-exp-and-1-and-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/arguments-are-new-reg-exp-and-2-and-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/arguments-are-new-reg-exp-and-3-and-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/arguments-are-new-reg-exp-and-4-and-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/arguments-are-new-reg-exp-and-undefined-and-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/call-split-2-instance-is-string-one-two-three-four-five.js - * - test/built-ins/String/prototype/split/separator-regexp-comma-instance-is-string-one-1-two-2-four-4.js - * - test/built-ins/String/prototype/split/argument-is-regexp-x-and-instance-is-string-a-b-c-de-f.js - * - test/built-ins/String/prototype/replace/regexp-capture-by-index.js - * - test/built-ins/String/prototype/replace/S15.5.4.11_A1_T17.js - * - test/built-ins/String/prototype/replace/S15.5.4.11_A2_T1.js - * - test/built-ins/String/prototype/replace/S15.5.4.11_A2_T2.js - * - test/built-ins/String/prototype/replace/S15.5.4.11_A2_T3.js - * - test/built-ins/String/prototype/replace/S15.5.4.11_A2_T4.js - * - test/built-ins/String/prototype/replace/S15.5.4.11_A2_T5.js - * - test/built-ins/String/prototype/replace/S15.5.4.11_A2_T6.js - * - test/built-ins/String/prototype/replace/S15.5.4.11_A2_T7.js - * - test/built-ins/String/prototype/replace/S15.5.4.11_A2_T8.js - * - test/built-ins/String/prototype/replace/S15.5.4.11_A2_T9.js - * - test/built-ins/String/prototype/replace/S15.5.4.11_A2_T10.js - * - test/built-ins/String/prototype/replace/S15.5.4.11_A3_T1.js - * - test/built-ins/String/prototype/replace/S15.5.4.11_A3_T2.js - * - test/built-ins/String/prototype/replace/S15.5.4.11_A3_T3.js - * - test/built-ins/String/prototype/replace/S15.5.4.11_A5_T1.js - * - test/built-ins/String/prototype/replaceAll/searchValue-replacer-RegExp-call.js - * - test/built-ins/String/prototype/replaceAll/searchValue-empty-string.js - * - test/built-ins/String/prototype/replaceAll/searchValue-empty-string-this-empty-string.js - * - test/built-ins/String/prototype/replaceAll/replaceValue-value-replaces-string.js - * - test/built-ins/String/prototype/replaceAll/getSubstitution-0x0024.js - * - test/built-ins/String/prototype/replaceAll/getSubstitution-0x0024-0x0024.js - * - test/built-ins/String/prototype/replaceAll/getSubstitution-0x0024-0x0026.js - * - test/built-ins/String/prototype/replaceAll/getSubstitution-0x0024-0x0060.js - * - test/built-ins/String/prototype/replaceAll/getSubstitution-0x0024-0x0027.js - * - test/built-ins/String/prototype/replaceAll/getSubstitution-0x0024N.js - * - test/built-ins/String/prototype/replaceAll/getSubstitution-0x0024NN.js - * - test/built-ins/String/prototype/replaceAll/getSubstitution-0x0024-0x003C.js - * - test/built-ins/String/prototype/match/S15.5.4.10_A1_T14.js - * - test/built-ins/String/prototype/match/S15.5.4.10_A2_T2.js - * - test/built-ins/String/prototype/match/S15.5.4.10_A2_T3.js - * - test/built-ins/String/prototype/match/S15.5.4.10_A2_T4.js - * - test/built-ins/String/prototype/match/S15.5.4.10_A2_T5.js - * - test/built-ins/String/prototype/match/S15.5.4.10_A2_T6.js - * - test/built-ins/String/prototype/match/S15.5.4.10_A2_T7.js - * - test/built-ins/String/prototype/match/S15.5.4.10_A2_T8.js - * - test/built-ins/String/prototype/match/S15.5.4.10_A2_T12.js - * - test/built-ins/String/prototype/matchAll/regexp-prototype-matchAll-v-u-flag.js - * - test/built-ins/String/prototype/search/S15.5.4.12_A1_T14.js - * - test/built-ins/String/prototype/search/S15.5.4.12_A2_T1.js - * - test/built-ins/String/prototype/search/S15.5.4.12_A2_T2.js - * - test/built-ins/String/prototype/search/S15.5.4.12_A2_T3.js - * - test/built-ins/String/prototype/search/S15.5.4.12_A2_T4.js - * - test/built-ins/String/prototype/search/S15.5.4.12_A2_T5.js - * - test/built-ins/String/prototype/search/S15.5.4.12_A2_T6.js - * - test/built-ins/String/prototype/search/S15.5.4.12_A2_T7.js - * - test/built-ins/String/prototype/search/S15.5.4.12_A3_T1.js - * - test/built-ins/String/prototype/search/S15.5.4.12_A3_T2.js - * - * Copyright 2009 the Sputnik authors. All rights reserved. - * Copyright (C) 2019 Leo Balter. All rights reserved. - * Copyright (C) 2020 Rick Waldron. All rights reserved. - * Copyright (C) 2023 Richard Gibson. All rights reserved. - * Copyright (C) 2024 Tan Meng. All rights reserved. - * Test262 portions are governed by the BSD license in LICENSE.test262. - */ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" - -type Vector = { - readonly path: string - readonly code: string - readonly expected: CodeMode.DataValue -} - -const value = async (code: string) => { - const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} })) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -const run = (name: string, vectors: ReadonlyArray) => { - describe(name, () => { - for (const vector of vectors) { - test(vector.path, async () => { - expect(await value(vector.code)).toEqual(vector.expected) - }) - } - }) -} - -run("Test262-adapted regexp split behavior", [ - { - path: "test/built-ins/String/prototype/split/separator-regexp.js", - code: ` - return [ - "x".split(/^/), "x".split(/$/), "x".split(/.?/), "x".split(/.*/), "x".split(/.+/), - "x".split(/.*?/), "x".split(/.{1}/), "x".split(/.{1,}/), "x".split(/.{1,2}/), - "x".split(/()/), "x".split(/./), "x".split(/(?:)/), "x".split(/(...)/), - "x".split(/(|)/), "x".split(/[]/), "x".split(/[^]/), "x".split(/[.-.]/), - "x".split(/\\0/), "x".split(/\\b/), "x".split(/\\B/), "x".split(/\\d/), - "x".split(/\\D/), "x".split(/\\n/), "x".split(/\\r/), "x".split(/\\s/), - "x".split(/\\S/), "x".split(/\\v/), "x".split(/\\w/), "x".split(/\\W/), - ] - `, - expected: [ - ["x"], - ["x"], - ["", ""], - ["", ""], - ["", ""], - ["x"], - ["", ""], - ["", ""], - ["", ""], - ["x"], - ["", ""], - ["x"], - ["x"], - ["x"], - ["x"], - ["", ""], - ["x"], - ["x"], - ["x"], - ["x"], - ["x"], - ["", ""], - ["x"], - ["x"], - ["x"], - ["", ""], - ["x"], - ["", ""], - ["x"], - ], - }, - { - path: "test/built-ins/String/prototype/split/arguments-are-regexp-s-and-3-and-instance-is-string-a-b-c-de-f.js", - code: `return "a b c de f".split(/\\s/, 3)`, - expected: ["a", "b", "c"], - }, - { - path: "test/built-ins/String/prototype/split/argument-is-regexp-s-and-instance-is-string-a-b-c-de-f.js", - code: `return "a b c de f".split(/\\s/)`, - expected: ["a", "b", "c", "de", "f"], - }, - { - path: "test/built-ins/String/prototype/split/argument-is-regexp-d-and-instance-is-string-dfe23iu-34-65.js", - code: `return "dfe23iu 34 =+65--".split(/\\d+/)`, - expected: ["dfe", "iu ", " =+", "--"], - }, - { - path: "test/built-ins/String/prototype/split/argument-is-regexp-reg-exp-d-and-instance-is-string-dfe23iu-34-65.js", - code: `return "dfe23iu 34 =+65--".split(new RegExp("\\\\d+"))`, - expected: ["dfe", "iu ", " =+", "--"], - }, - { - path: "test/built-ins/String/prototype/split/argument-is-regexp-a-z-and-instance-is-string-abc.js", - code: `return "abc".split(/[a-z]/)`, - expected: ["", "", "", ""], - }, - { - path: "test/built-ins/String/prototype/split/argument-is-reg-exp-a-z-and-instance-is-string-abc.js", - code: `return "abc".split(new RegExp("[a-z]"))`, - expected: ["", "", "", ""], - }, - { - path: "test/built-ins/String/prototype/split/arguments-are-regexp-l-and-undefined-and-instance-is-string-hello.js", - code: `return "hello".split(/l/, undefined)`, - expected: ["he", "", "o"], - }, - { - path: "test/built-ins/String/prototype/split/arguments-are-regexp-l-and-0-and-instance-is-string-hello.js", - code: `return "hello".split(/l/, 0)`, - expected: [], - }, - { - path: "test/built-ins/String/prototype/split/arguments-are-regexp-l-and-1-and-instance-is-string-hello.js", - code: `return "hello".split(/l/, 1)`, - expected: ["he"], - }, - { - path: "test/built-ins/String/prototype/split/arguments-are-regexp-l-and-2-and-instance-is-string-hello.js", - code: `return "hello".split(/l/, 2)`, - expected: ["he", ""], - }, - { - path: "test/built-ins/String/prototype/split/arguments-are-regexp-l-and-3-and-instance-is-string-hello.js", - code: `return "hello".split(/l/, 3)`, - expected: ["he", "", "o"], - }, - { - path: "test/built-ins/String/prototype/split/arguments-are-regexp-l-and-4-and-instance-is-string-hello.js", - code: `return "hello".split(/l/, 4)`, - expected: ["he", "", "o"], - }, - { - path: "test/built-ins/String/prototype/split/argument-is-regexp-l-and-instance-is-string-hello.js", - code: `return "hello".split(/l/)`, - expected: ["he", "", "o"], - }, - { - path: "test/built-ins/String/prototype/split/argument-is-new-reg-exp-and-instance-is-string-hello.js", - code: `return "hello".split(new RegExp())`, - expected: ["h", "e", "l", "l", "o"], - }, - { - path: "test/built-ins/String/prototype/split/arguments-are-new-reg-exp-and-0-and-instance-is-string-hello.js", - code: `return "hello".split(new RegExp(), 0)`, - expected: [], - }, - { - path: "test/built-ins/String/prototype/split/arguments-are-new-reg-exp-and-1-and-instance-is-string-hello.js", - code: `return "hello".split(new RegExp(), 1)`, - expected: ["h"], - }, - { - path: "test/built-ins/String/prototype/split/arguments-are-new-reg-exp-and-2-and-instance-is-string-hello.js", - code: `return "hello".split(new RegExp(), 2)`, - expected: ["h", "e"], - }, - { - path: "test/built-ins/String/prototype/split/arguments-are-new-reg-exp-and-3-and-instance-is-string-hello.js", - code: `return "hello".split(new RegExp(), 3)`, - expected: ["h", "e", "l"], - }, - { - path: "test/built-ins/String/prototype/split/arguments-are-new-reg-exp-and-4-and-instance-is-string-hello.js", - code: `return "hello".split(new RegExp(), 4)`, - expected: ["h", "e", "l", "l"], - }, - { - path: "test/built-ins/String/prototype/split/arguments-are-new-reg-exp-and-undefined-and-instance-is-string-hello.js", - code: `return "hello".split(new RegExp(), undefined)`, - expected: ["h", "e", "l", "l", "o"], - }, - { - path: "test/built-ins/String/prototype/split/call-split-2-instance-is-string-one-two-three-four-five.js", - code: `return "one two three four five".split(/ /, 2)`, - expected: ["one", "two"], - }, - { - path: "test/built-ins/String/prototype/split/separator-regexp-comma-instance-is-string-one-1-two-2-four-4.js", - code: `return "one-1,two-2,four-4".split(/,/)`, - expected: ["one-1", "two-2", "four-4"], - }, - { - path: "test/built-ins/String/prototype/split/argument-is-regexp-x-and-instance-is-string-a-b-c-de-f.js", - code: `return "a b c de f".split(/X/)`, - expected: ["a b c de f"], - }, -]) - -run("Test262-adapted replace behavior", [ - { - path: "test/built-ins/String/prototype/replace/regexp-capture-by-index.js", - code: ` - const str = "foo-x-bar" - const patterns = ["x", /x/, /(x)/, /(x)($^)?/, /((((((((((x))))))))))/] - const replacements = ["|$0|", "|$00|", "|$000|", "|$1|", "|$01|", "|$010|", "|$2|", "|$02|", "|$020|", "|$10|", "|$100|", "|$20|", "|$200|"] - return replacements.flatMap((replacement) => patterns.map((pattern) => str.replace(pattern, replacement))) - `, - expected: [ - "foo-|$0|-bar", - "foo-|$0|-bar", - "foo-|$0|-bar", - "foo-|$0|-bar", - "foo-|$0|-bar", - "foo-|$00|-bar", - "foo-|$00|-bar", - "foo-|$00|-bar", - "foo-|$00|-bar", - "foo-|$00|-bar", - "foo-|$000|-bar", - "foo-|$000|-bar", - "foo-|$000|-bar", - "foo-|$000|-bar", - "foo-|$000|-bar", - "foo-|$1|-bar", - "foo-|$1|-bar", - "foo-|x|-bar", - "foo-|x|-bar", - "foo-|x|-bar", - "foo-|$01|-bar", - "foo-|$01|-bar", - "foo-|x|-bar", - "foo-|x|-bar", - "foo-|x|-bar", - "foo-|$010|-bar", - "foo-|$010|-bar", - "foo-|x0|-bar", - "foo-|x0|-bar", - "foo-|x0|-bar", - "foo-|$2|-bar", - "foo-|$2|-bar", - "foo-|$2|-bar", - "foo-||-bar", - "foo-|x|-bar", - "foo-|$02|-bar", - "foo-|$02|-bar", - "foo-|$02|-bar", - "foo-||-bar", - "foo-|x|-bar", - "foo-|$020|-bar", - "foo-|$020|-bar", - "foo-|$020|-bar", - "foo-|0|-bar", - "foo-|x0|-bar", - "foo-|$10|-bar", - "foo-|$10|-bar", - "foo-|x0|-bar", - "foo-|x0|-bar", - "foo-|x|-bar", - "foo-|$100|-bar", - "foo-|$100|-bar", - "foo-|x00|-bar", - "foo-|x00|-bar", - "foo-|x0|-bar", - "foo-|$20|-bar", - "foo-|$20|-bar", - "foo-|$20|-bar", - "foo-|0|-bar", - "foo-|x0|-bar", - "foo-|$200|-bar", - "foo-|$200|-bar", - "foo-|$200|-bar", - "foo-|00|-bar", - "foo-|x00|-bar", - ], - }, - { - path: "test/built-ins/String/prototype/replace/S15.5.4.11_A1_T17.js", - code: `return "asdf".replace(new RegExp(undefined, "g"), "1")`, - expected: "1a1s1d1f1", - }, - { - path: "test/built-ins/String/prototype/replace/S15.5.4.11_A2_T1.js", - code: `return "She sells seashells by the seashore.".replace(/sh/g, "sch")`, - expected: "She sells seaschells by the seaschore.", - }, - { - path: "test/built-ins/String/prototype/replace/S15.5.4.11_A2_T2.js", - code: `return "She sells seashells by the seashore.".replace(/sh/g, "$$sch")`, - expected: "She sells sea$schells by the sea$schore.", - }, - { - path: "test/built-ins/String/prototype/replace/S15.5.4.11_A2_T3.js", - code: `return "She sells seashells by the seashore.".replace(/sh/g, "$&sch")`, - expected: "She sells seashschells by the seashschore.", - }, - { - path: "test/built-ins/String/prototype/replace/S15.5.4.11_A2_T4.js", - code: `return "She sells seashells by the seashore.".replace(/sh/g, "$\`sch")`, - expected: "She sells seaShe sells seaschells by the seaShe sells seashells by the seaschore.", - }, - { - path: "test/built-ins/String/prototype/replace/S15.5.4.11_A2_T5.js", - code: `return "She sells seashells by the seashore.".replace(/sh/g, "$'sch")`, - expected: "She sells seaells by the seashore.schells by the seaore.schore.", - }, - { - path: "test/built-ins/String/prototype/replace/S15.5.4.11_A2_T6.js", - code: `return "She sells seashells by the seashore.".replace(/sh/, "sch")`, - expected: "She sells seaschells by the seashore.", - }, - { - path: "test/built-ins/String/prototype/replace/S15.5.4.11_A2_T7.js", - code: `return "She sells seashells by the seashore.".replace(/sh/, "$$sch")`, - expected: "She sells sea$schells by the seashore.", - }, - { - path: "test/built-ins/String/prototype/replace/S15.5.4.11_A2_T8.js", - code: `return "She sells seashells by the seashore.".replace(/sh/, "$&sch")`, - expected: "She sells seashschells by the seashore.", - }, - { - path: "test/built-ins/String/prototype/replace/S15.5.4.11_A2_T9.js", - code: `return "She sells seashells by the seashore.".replace(/sh/, "$\`sch")`, - expected: "She sells seaShe sells seaschells by the seashore.", - }, - { - path: "test/built-ins/String/prototype/replace/S15.5.4.11_A2_T10.js", - code: `return "She sells seashells by the seashore.".replace(/sh/, "$'sch")`, - expected: "She sells seaells by the seashore.schells by the seashore.", - }, - { - path: "test/built-ins/String/prototype/replace/S15.5.4.11_A3_T1.js", - code: `return "uid=31".replace(/(uid=)(\\d+)/, "$1115")`, - expected: "uid=115", - }, - { - path: "test/built-ins/String/prototype/replace/S15.5.4.11_A3_T2.js", - code: `return "uid=31".replace(/(uid=)(\\d+)/, "$1115")`, - expected: "uid=115", - }, - { - path: "test/built-ins/String/prototype/replace/S15.5.4.11_A3_T3.js", - code: `return "uid=31".replace(/(uid=)(\\d+)/, "$11A15")`, - expected: "uid=1A15", - }, - { - path: "test/built-ins/String/prototype/replace/S15.5.4.11_A5_T1.js", - code: `return "aaaaaaaaaa,aaaaaaaaaaaaaaa".replace(/^(a+)\\1*,\\1+$/, "$1")`, - expected: "aaaaa", - }, -]) - -run("Test262-adapted replaceAll behavior", [ - { - path: "test/built-ins/String/prototype/replaceAll/searchValue-replacer-RegExp-call.js", - code: ` - return [ - "abc abc abc".replaceAll(new RegExp("b", "g"), "z"), - "abc abc abc".replaceAll(new RegExp("b", "gy"), "z"), - "abc abc abc".replaceAll(new RegExp("b", "giy"), "z"), - "No Uppercase!".replaceAll(new RegExp("[A-Z]", "g"), ""), - "No Uppercase?".replaceAll(new RegExp("[A-Z]", "gy"), ""), - "NO UPPERCASE!".replaceAll(new RegExp("[A-Z]", "gy"), ""), - "abcabcabcabc".replaceAll(new RegExp("a(b)(ca)", "g"), "$2-$1"), - "abcabcabcabc".replaceAll(new RegExp("(a(.))", "g"), "$1$2$3"), - "aabacadaeafagahaiajakalamano a azaya".replaceAll(new RegExp("(((((((((((((a(.).).).).).).).).))))))", "g"), "($10)-($12)-($1)"), - "abcba".replaceAll(new RegExp("b", "g"), "$'"), - "abcba".replaceAll(new RegExp("b", "g"), "$\`"), - "abcba".replaceAll(new RegExp("(?b)", "g"), "($)"), - "abcba".replaceAll(new RegExp("(?b)", "g"), "($b)", "g"), "($)"), - "abcabcabcabc".replaceAll(new RegExp("a(b)(ca)", "g"), "($$)"), - "abcabcabcabc".replaceAll(new RegExp("a(b)(ca)", "g"), "($)"), - "abcabcabcabc".replaceAll(new RegExp("a(b)(ca)", "g"), "($$$$)"), - "abcabcabcabc".replaceAll(new RegExp("a(b)(ca)", "g"), "($$$)"), - "abcabcabcabc".replaceAll(new RegExp("a(b)(ca)", "g"), "($$&)"), - "abcabcabcabc".replaceAll(new RegExp("a(b)(ca)", "g"), "($$1)"), - "abcabcabcabc".replaceAll(new RegExp("a(b)(ca)", "g"), "($$\`)"), - "abcabcabcabc".replaceAll(new RegExp("a(b)(ca)", "g"), "($$')"), - "abcabcabcabc".replaceAll(new RegExp("a(?b)(ca)", "g"), "($$)"), - "abcabcabcabc".replaceAll(new RegExp("a(b)(ca)", "g"), "($&)"), - ] - `, - expected: [ - "azc azc azc", - "abc abc abc", - "abc abc abc", - "o ppercase!", - "o Uppercase?", - " UPPERCASE!", - "ca-bbcca-bbc", - "abb$3cabb$3cabb$3cabb$3c", - "(aabaca)-(aaba)-(aabacadaea)f(agahai)-(agah)-(agahaiajak)(alaman)-(alam)-(alamano a )azaya", - "acbacaa", - "aacabca", - "a(b)c(b)a", - "a($)bc($)bc", - "(abca)bc(abca)bc", - ], - }, - { - path: "test/built-ins/String/prototype/replaceAll/searchValue-empty-string.js", - code: `return ["aab c \\nx".replaceAll("", "_"), "a".replaceAll("", "_")]`, - expected: ["_a_a_b_ _c_ _ _\n_x_", "_a_"], - }, - { - path: "test/built-ins/String/prototype/replaceAll/searchValue-empty-string-this-empty-string.js", - code: `return "".replaceAll("", "abc")`, - expected: "abc", - }, - { - path: "test/built-ins/String/prototype/replaceAll/replaceValue-value-replaces-string.js", - code: `return ["aaab a a aac".replaceAll("aa", "z"), "aaab a a aac".replaceAll("aa", "a"), "aaab a a aac".replaceAll("a", "a"), "aaab a a aac".replaceAll("a", "z")]`, - expected: ["zab a a zc", "aab a a ac", "aaab a a aac", "zzzb z z zzc"], - }, - { - path: "test/built-ins/String/prototype/replaceAll/getSubstitution-0x0024.js", - code: ` - const str = "Ninguém é igual a ninguém. Todo o ser humano é um estranho ímpar." - return [str.replaceAll("ninguém", "$"), str.replaceAll("é", "$"), str.replaceAll("é", "$ -"), str.replaceAll("é", "$$$")] - `, - expected: [ - "Ninguém é igual a $. Todo o ser humano é um estranho ímpar.", - "Ningu$m $ igual a ningu$m. Todo o ser humano $ um estranho ímpar.", - "Ningu$ -m $ - igual a ningu$ -m. Todo o ser humano $ - um estranho ímpar.", - "Ningu$$m $$ igual a ningu$$m. Todo o ser humano $$ um estranho ímpar.", - ], - }, - { - path: "test/built-ins/String/prototype/replaceAll/getSubstitution-0x0024-0x0024.js", - code: ` - const str = "Ninguém é igual a ninguém. Todo o ser humano é um estranho ímpar." - return [str.replaceAll("ninguém", "$$"), str.replaceAll("é", "$$"), str.replaceAll("é", "$$ -"), str.replaceAll("é", "$$&"), str.replaceAll("é", "$$$"), str.replaceAll("é", "$$$$")] - `, - expected: [ - "Ninguém é igual a $. Todo o ser humano é um estranho ímpar.", - "Ningu$m $ igual a ningu$m. Todo o ser humano $ um estranho ímpar.", - "Ningu$ -m $ - igual a ningu$ -m. Todo o ser humano $ - um estranho ímpar.", - "Ningu$&m $& igual a ningu$&m. Todo o ser humano $& um estranho ímpar.", - "Ningu$$m $$ igual a ningu$$m. Todo o ser humano $$ um estranho ímpar.", - "Ningu$$m $$ igual a ningu$$m. Todo o ser humano $$ um estranho ímpar.", - ], - }, - { - path: "test/built-ins/String/prototype/replaceAll/getSubstitution-0x0024-0x0026.js", - code: ` - const str = "Ninguém é igual a ninguém. Todo o ser humano é um estranho ímpar." - return [str.replaceAll("ninguém", "$&"), str.replaceAll("ninguém", "($&)"), str.replaceAll("é", "($&)"), str.replaceAll("é", "($&) $&")] - `, - expected: [ - "Ninguém é igual a ninguém. Todo o ser humano é um estranho ímpar.", - "Ninguém é igual a (ninguém). Todo o ser humano é um estranho ímpar.", - "Ningu(é)m (é) igual a ningu(é)m. Todo o ser humano (é) um estranho ímpar.", - "Ningu(é) ém (é) é igual a ningu(é) ém. Todo o ser humano (é) é um estranho ímpar.", - ], - }, - { - path: "test/built-ins/String/prototype/replaceAll/getSubstitution-0x0024-0x0060.js", - code: ` - const str = "Ninguém é igual a ninguém. Todo o ser humano é um estranho ímpar." - return [str.replaceAll("ninguém", "$\`"), str.replaceAll("Ninguém", "$\`"), str.replaceAll("ninguém", "($\`)"), str.replaceAll("é", "($\`)")] - `, - expected: [ - "Ninguém é igual a Ninguém é igual a . Todo o ser humano é um estranho ímpar.", - " é igual a ninguém. Todo o ser humano é um estranho ímpar.", - "Ninguém é igual a (Ninguém é igual a ). Todo o ser humano é um estranho ímpar.", - "Ningu(Ningu)m (Ninguém ) igual a ningu(Ninguém é igual a ningu)m. Todo o ser humano (Ninguém é igual a ninguém. Todo o ser humano ) um estranho ímpar.", - ], - }, - { - path: "test/built-ins/String/prototype/replaceAll/getSubstitution-0x0024-0x0027.js", - code: ` - const str = "Ninguém é igual a ninguém. Todo o ser humano é um estranho ímpar." - return [str.replaceAll("ninguém", "$'"), str.replaceAll(".", "--- $'"), str.replaceAll("é", "($')")] - `, - expected: [ - "Ninguém é igual a . Todo o ser humano é um estranho ímpar.. Todo o ser humano é um estranho ímpar.", - "Ninguém é igual a ninguém--- Todo o ser humano é um estranho ímpar. Todo o ser humano é um estranho ímpar--- ", - "Ningu(m é igual a ninguém. Todo o ser humano é um estranho ímpar.)m ( igual a ninguém. Todo o ser humano é um estranho ímpar.) igual a ningu(m. Todo o ser humano é um estranho ímpar.)m. Todo o ser humano ( um estranho ímpar.) um estranho ímpar.", - ], - }, - { - path: "test/built-ins/String/prototype/replaceAll/getSubstitution-0x0024N.js", - code: ` - const str = "ABC AAA ABC AAA" - return ["$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9"].map((replacement) => str.replaceAll("ABC", replacement)) - `, - expected: [ - "$1 AAA $1 AAA", - "$2 AAA $2 AAA", - "$3 AAA $3 AAA", - "$4 AAA $4 AAA", - "$5 AAA $5 AAA", - "$6 AAA $6 AAA", - "$7 AAA $7 AAA", - "$8 AAA $8 AAA", - "$9 AAA $9 AAA", - ], - }, - { - path: "test/built-ins/String/prototype/replaceAll/getSubstitution-0x0024NN.js", - code: ` - const str = "aaaaaaaaaaaaaaaa aaaaaaaa aaaaaaaaaaaaaaaa" - return [str.replaceAll("a", "$11"), str.replaceAll("a", "$29")] - `, - expected: [ - "$11$11$11$11$11$11$11$11$11$11$11$11$11$11$11$11 $11$11$11$11$11$11$11$11 $11$11$11$11$11$11$11$11$11$11$11$11$11$11$11$11", - "$29$29$29$29$29$29$29$29$29$29$29$29$29$29$29$29 $29$29$29$29$29$29$29$29 $29$29$29$29$29$29$29$29$29$29$29$29$29$29$29$29", - ], - }, - { - path: "test/built-ins/String/prototype/replaceAll/getSubstitution-0x0024-0x003C.js", - code: `return "aaaaaaaaaaaaaaaa aaaaaaaa aaaaaaaaaaaaaaaa".replaceAll("a", "$<")`, - expected: "$<$<$<$<$<$<$<$<$<$<$<$<$<$<$<$< $<$<$<$<$<$<$<$< $<$<$<$<$<$<$<$<$<$<$<$<$<$<$<$<", - }, -]) - -run("Test262-adapted match behavior", [ - { - path: "test/built-ins/String/prototype/match/S15.5.4.10_A1_T14.js", - code: `const match = "ABBABABAB77BBAA".match(new RegExp("77")); return [match[0], match.index]`, - expected: ["77", 9], - }, - { - path: "test/built-ins/String/prototype/match/S15.5.4.10_A2_T2.js", - code: `return "343443444".match(/34/g)`, - expected: ["34", "34", "34"], - }, - { - path: "test/built-ins/String/prototype/match/S15.5.4.10_A2_T3.js", - code: `return "123456abcde7890".match(/\\d{1}/g)`, - expected: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"], - }, - { - path: "test/built-ins/String/prototype/match/S15.5.4.10_A2_T4.js", - code: `return "123456abcde7890".match(/\\d{2}/g)`, - expected: ["12", "34", "56", "78", "90"], - }, - { - path: "test/built-ins/String/prototype/match/S15.5.4.10_A2_T5.js", - code: `return "123456abcde7890".match(/\\D{2}/g)`, - expected: ["ab", "cd"], - }, - { - path: "test/built-ins/String/prototype/match/S15.5.4.10_A2_T6.js", - code: `const match = "Boston, Mass. 02134".match(/([\\d]{5})([- ]?[\\d]{4})?$/); return [match[0], match[1], match[2] === undefined, match.length, match.index]`, - expected: ["02134", "02134", true, 3, 14], - }, - { - path: "test/built-ins/String/prototype/match/S15.5.4.10_A2_T7.js", - code: `return "Boston, Mass. 02134".match(/([\\d]{5})([- ]?[\\d]{4})?$/g)`, - expected: ["02134"], - }, - { - path: "test/built-ins/String/prototype/match/S15.5.4.10_A2_T8.js", - code: `const match = "Boston, MA 02134".match(/([\\d]{5})([- ]?[\\d]{4})?$/); return [match[0], match[1], match[2] === undefined, match.length, match.index]`, - expected: ["02134", "02134", true, 3, 11], - }, - { - path: "test/built-ins/String/prototype/match/S15.5.4.10_A2_T12.js", - code: `return "Boston, MA 02134".match(/([\\d]{5})([- ]?[\\d]{4})?$/g)`, - expected: ["02134"], - }, -]) - -run("Test262-adapted matchAll behavior", [ - { - path: "test/built-ins/String/prototype/matchAll/regexp-prototype-matchAll-v-u-flag.js", - code: ` - const text = "𠮷a𠮷b𠮷" - const collect = (regex) => { - const matches = text.matchAll(regex) - return matches.map((match) => match[0]).concat(matches.map((match) => match.index)) - } - const empty = text.matchAll(/(?:)/gu) - const complex = "a𠮷b􏿿c".matchAll(/\\P{ASCII}/gu) - return [ - collect(/𠮷/g), - collect(/𠮷/gu), - collect(/\\p{Script=Han}/gu), - collect(/./gu), - empty.map((match) => match[0]).concat(empty.map((match) => match.index)).length, - complex.map((match) => match[0]), - ] - `, - expected: [ - ["𠮷", "𠮷", "𠮷", 0, 3, 6], - ["𠮷", "𠮷", "𠮷", 0, 3, 6], - ["𠮷", "𠮷", "𠮷", 0, 3, 6], - ["𠮷", "a", "𠮷", "b", "𠮷", 0, 2, 3, 5, 6], - 12, - ["𠮷", "􏿿"], - ], - }, -]) - -run("Test262-adapted search behavior", [ - { - path: "test/built-ins/String/prototype/search/S15.5.4.12_A1_T14.js", - code: `return "ABBABABAB77BBAA".search(new RegExp("77"))`, - expected: 9, - }, - { - path: "test/built-ins/String/prototype/search/S15.5.4.12_A2_T1.js", - code: `return "test string".search("string")`, - expected: 5, - }, - { - path: "test/built-ins/String/prototype/search/S15.5.4.12_A2_T2.js", - code: `return "test string".search("String")`, - expected: -1, - }, - { - path: "test/built-ins/String/prototype/search/S15.5.4.12_A2_T3.js", - code: `return "test string".search(/String/i)`, - expected: 5, - }, - { - path: "test/built-ins/String/prototype/search/S15.5.4.12_A2_T4.js", - code: `return "one two three four five".search(/Four/)`, - expected: -1, - }, - { - path: "test/built-ins/String/prototype/search/S15.5.4.12_A2_T5.js", - code: `return "one two three four five".search(/four/)`, - expected: 14, - }, - { - path: "test/built-ins/String/prototype/search/S15.5.4.12_A2_T6.js", - code: `return "test string".search("notexist")`, - expected: -1, - }, - { - path: "test/built-ins/String/prototype/search/S15.5.4.12_A2_T7.js", - code: `return "test string probe".search("string pro")`, - expected: 5, - }, - { - path: "test/built-ins/String/prototype/search/S15.5.4.12_A3_T1.js", - code: `const text = "power of the power of the power of the great sword"; return [text.search(/the/), text.search(/the/g)]`, - expected: [9, 9], - }, - { - path: "test/built-ins/String/prototype/search/S15.5.4.12_A3_T2.js", - code: `const text = "power of the power of the power of the great sword"; return [text.search(/of/), text.search(/of/g)]`, - expected: [6, 6], - }, -]) diff --git a/packages/codemode/test/string-search-test262.test.ts b/packages/codemode/test/string-search-test262.test.ts deleted file mode 100644 index b596fc7bf9a..00000000000 --- a/packages/codemode/test/string-search-test262.test.ts +++ /dev/null @@ -1,811 +0,0 @@ -/* - * Portions adapted from Test262 at revision 250f204f23a9249ff204be2baec29600faae7b75: - * - test/built-ins/String/prototype/split/call-split-l-0-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/call-split-l-1-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/call-split-l-2-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/call-split-l-3-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/call-split-l-4-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/call-split-l-na-n-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/call-split-l-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/call-split-ll-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/call-split-h-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/call-split-hello-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/call-split-hellothere-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/call-split-o-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/call-split-x-instance-is-string-hello.js - * - test/built-ins/String/prototype/split/call-split-x-instance-is-empty-string.js - * - test/built-ins/String/prototype/split/call-split-4-instance-is-string-one-1-two-2-four-4.js - * - test/built-ins/String/prototype/split/call-split-on-instance-is-string-one-1-two-2-four-4.js - * - test/built-ins/String/prototype/split/call-split-instance-is-string-one-two-three-four-five.js - * - test/built-ins/String/prototype/split/call-split-instance-is-string-one-two-three.js - * - test/built-ins/String/prototype/split/call-split-instance-is-string.js - * - test/built-ins/String/prototype/split/instance-is-string-one-two-three-four-five.js - * - test/built-ins/String/prototype/split/instance-is-string.js - * - test/built-ins/String/prototype/split/separator-colon-instance-is-string-one-1-two-2-four-4.js - * - test/built-ins/String/prototype/split/separator-comma-instance-is-string-one-two-three-four-five.js - * - test/built-ins/String/prototype/split/separator-empty-string-instance-is-string.js - * - test/built-ins/String/prototype/split/call-split-without-arguments-and-instance-is-empty-string.js - * - test/built-ins/String/prototype/split/separator-undef.js - * - test/built-ins/String/prototype/slice/S15.5.4.13_A1_T6.js - * - test/built-ins/String/prototype/slice/S15.5.4.13_A1_T14.js - * - test/built-ins/String/prototype/slice/S15.5.4.13_A2_T1.js - * - test/built-ins/String/prototype/slice/S15.5.4.13_A2_T2.js - * - test/built-ins/String/prototype/slice/S15.5.4.13_A2_T3.js - * - test/built-ins/String/prototype/slice/S15.5.4.13_A2_T4.js - * - test/built-ins/String/prototype/slice/S15.5.4.13_A2_T5.js - * - test/built-ins/String/prototype/slice/S15.5.4.13_A2_T6.js - * - test/built-ins/String/prototype/slice/S15.5.4.13_A2_T7.js - * - test/built-ins/String/prototype/slice/S15.5.4.13_A2_T8.js - * - test/built-ins/String/prototype/slice/S15.5.4.13_A2_T9.js - * - test/built-ins/String/prototype/substring/S15.5.4.15_A1_T6.js - * - test/built-ins/String/prototype/substring/S15.5.4.15_A1_T14.js - * - test/built-ins/String/prototype/substring/S15.5.4.15_A2_T1.js - * - test/built-ins/String/prototype/substring/S15.5.4.15_A2_T2.js - * - test/built-ins/String/prototype/substring/S15.5.4.15_A2_T3.js - * - test/built-ins/String/prototype/substring/S15.5.4.15_A2_T4.js - * - test/built-ins/String/prototype/substring/S15.5.4.15_A2_T5.js - * - test/built-ins/String/prototype/substring/S15.5.4.15_A2_T6.js - * - test/built-ins/String/prototype/substring/S15.5.4.15_A2_T7.js - * - test/built-ins/String/prototype/substring/S15.5.4.15_A2_T8.js - * - test/built-ins/String/prototype/substring/S15.5.4.15_A2_T9.js - * - test/built-ins/String/prototype/substring/S15.5.4.15_A2_T10.js - * - test/built-ins/String/prototype/includes/String.prototype.includes_FailMissingLetter.js - * - test/built-ins/String/prototype/includes/String.prototype.includes_SuccessNoLocation.js - * - test/built-ins/String/prototype/includes/String.prototype.includes_FailBadLocation.js - * - test/built-ins/String/prototype/includes/String.prototype.includes_FailLocation.js - * - test/built-ins/String/prototype/includes/String.prototype.includes_Success.js - * - test/built-ins/String/prototype/includes/searchstring-found-with-position.js - * - test/built-ins/String/prototype/includes/searchstring-found-without-position.js - * - test/built-ins/String/prototype/includes/searchstring-not-found-with-position.js - * - test/built-ins/String/prototype/includes/searchstring-not-found-without-position.js - * - test/built-ins/String/prototype/includes/return-false-with-out-of-bounds-position.js - * - test/built-ins/String/prototype/includes/return-true-if-searchstring-is-empty.js - * - test/built-ins/String/prototype/includes/coerced-values-of-position.js - * - test/built-ins/String/prototype/startsWith/searchstring-found-with-position.js - * - test/built-ins/String/prototype/startsWith/searchstring-found-without-position.js - * - test/built-ins/String/prototype/startsWith/searchstring-not-found-with-position.js - * - test/built-ins/String/prototype/startsWith/searchstring-not-found-without-position.js - * - test/built-ins/String/prototype/startsWith/out-of-bounds-position.js - * - test/built-ins/String/prototype/startsWith/return-true-if-searchstring-is-empty.js - * - test/built-ins/String/prototype/startsWith/coerced-values-of-position.js - * - test/built-ins/String/prototype/endsWith/String.prototype.endsWith_Success.js - * - test/built-ins/String/prototype/endsWith/String.prototype.endsWith_Success_2.js - * - test/built-ins/String/prototype/endsWith/String.prototype.endsWith_Success_3.js - * - test/built-ins/String/prototype/endsWith/String.prototype.endsWith_Success_4.js - * - test/built-ins/String/prototype/endsWith/String.prototype.endsWith_Fail.js - * - test/built-ins/String/prototype/endsWith/String.prototype.endsWith_Fail_2.js - * - test/built-ins/String/prototype/endsWith/searchstring-found-with-position.js - * - test/built-ins/String/prototype/endsWith/searchstring-found-without-position.js - * - test/built-ins/String/prototype/endsWith/searchstring-not-found-with-position.js - * - test/built-ins/String/prototype/endsWith/searchstring-not-found-without-position.js - * - test/built-ins/String/prototype/endsWith/return-false-if-search-start-is-less-than-zero.js - * - test/built-ins/String/prototype/endsWith/return-true-if-searchstring-is-empty.js - * - test/built-ins/String/prototype/endsWith/coerced-values-of-position.js - * - test/built-ins/String/prototype/indexOf/S15.5.4.7_A2_T1.js - * - test/built-ins/String/prototype/indexOf/S15.5.4.7_A2_T2.js - * - test/built-ins/String/prototype/indexOf/S15.5.4.7_A2_T3.js - * - test/built-ins/String/prototype/indexOf/S15.5.4.7_A2_T4.js - * - test/built-ins/String/prototype/indexOf/S15.5.4.7_A3_T1.js - * - test/built-ins/String/prototype/indexOf/S15.5.4.7_A3_T3.js - * - test/built-ins/String/prototype/indexOf/position-tointeger.js - * - test/built-ins/String/prototype/indexOf/searchstring-tostring.js - * - test/built-ins/String/prototype/lastIndexOf/not-a-substring.js - * - * Copyright 2009 the Sputnik authors. All rights reserved. - * Copyright (c) 2014 Ryan Lewis. All rights reserved. - * Copyright (C) 2015 the V8 project authors. All rights reserved. - * Copyright (C) 2016 the V8 project authors. All rights reserved. - * Copyright (C) 2017 Josh Wolfe. All rights reserved. - * Copyright (C) 2020 Leo Balter. All rights reserved. - * Copyright (C) 2026 Garham Lee. All rights reserved. - * Test262 portions are governed by the BSD license in LICENSE.test262. - */ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" - -const value = async (code: string) => { - const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} })) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -const cases = [ - { - path: "test/built-ins/String/prototype/split/call-split-l-0-instance-is-string-hello.js", - code: `const result = "hello".split("l", 0); return [result.length, result[0] === undefined]`, - expected: [0, true], - labels: [ - "The value of __split.length is expected to equal the value of __expected.length", - "The value of __split[0] is expected to equal the value of __expected[0]", - ], - }, - { - path: "test/built-ins/String/prototype/split/call-split-l-1-instance-is-string-hello.js", - code: `const result = "hello".split("l", 1); return [result.length, result[0]]`, - expected: [1, "he"], - labels: [ - "The value of __split.length is expected to equal the value of __expected.length", - "The value of __split[0] is expected to equal the value of __expected[0]", - ], - }, - { - path: "test/built-ins/String/prototype/split/call-split-l-2-instance-is-string-hello.js", - code: `const result = "hello".split("l", 2); return [result.length, result[0], result[1]]`, - expected: [2, "he", ""], - labels: [ - "The value of __split.length is expected to equal the value of __expected.length", - "The value of __split[index] is expected to equal the value of __expected[index]", - "The value of __split[index] is expected to equal the value of __expected[index]", - ], - }, - { - path: "test/built-ins/String/prototype/split/call-split-l-3-instance-is-string-hello.js", - code: `const result = "hello".split("l", 3); return [result.length, result[0], result[1], result[2]]`, - expected: [3, "he", "", "o"], - labels: [ - "The value of __split.length is expected to equal the value of __expected.length", - "The value of __split[index] is expected to equal the value of __expected[index]", - "The value of __split[index] is expected to equal the value of __expected[index]", - "The value of __split[index] is expected to equal the value of __expected[index]", - ], - }, - { - path: "test/built-ins/String/prototype/split/call-split-l-4-instance-is-string-hello.js", - code: `const result = "hello".split("l", 4); return [result.length, result[0], result[1], result[2]]`, - expected: [3, "he", "", "o"], - labels: [ - "The value of __split.length is expected to equal the value of __expected.length", - "The value of __split[index] is expected to equal the value of __expected[index]", - "The value of __split[index] is expected to equal the value of __expected[index]", - "The value of __split[index] is expected to equal the value of __expected[index]", - ], - }, - { - path: "test/built-ins/String/prototype/split/call-split-l-na-n-instance-is-string-hello.js", - code: `const result = "hello".split("l", NaN); return [result.length, result[0] === undefined]`, - expected: [0, true], - labels: [ - "The value of __split.length is expected to equal the value of __expected.length", - "The value of __split[0] is expected to equal the value of __expected[0]", - ], - }, - { - path: "test/built-ins/String/prototype/split/call-split-l-instance-is-string-hello.js", - code: `const result = "hello".split("l"); return [result.length, result[0], result[1], result[2]]`, - expected: [3, "he", "", "o"], - labels: [ - "The value of __split.length is 3", - 'The value of __split[0] is "he"', - 'The value of __split[1] is ""', - 'The value of __split[2] is "o"', - ], - }, - { - path: "test/built-ins/String/prototype/split/call-split-ll-instance-is-string-hello.js", - code: `const result = "hello".split("ll"); return [result.length, result[0], result[1]]`, - expected: [2, "he", "o"], - labels: ["The value of __split.length is 2", 'The value of __split[0] is "he"', 'The value of __split[1] is "o"'], - }, - { - path: "test/built-ins/String/prototype/split/call-split-h-instance-is-string-hello.js", - code: `const result = "hello".split("h"); return [result.length, result[0], result[1]]`, - expected: [2, "", "ello"], - labels: ["The value of __split.length is 2", 'The value of __split[0] is ""', 'The value of __split[1] is "ello"'], - }, - { - path: "test/built-ins/String/prototype/split/call-split-hello-instance-is-string-hello.js", - code: `const result = "hello".split("hello"); return [result.length, result[0], result[1]]`, - expected: [2, "", ""], - labels: ["The value of __split.length is 2", 'The value of __split[0] is ""', 'The value of __split[1] is ""'], - }, - { - path: "test/built-ins/String/prototype/split/call-split-hellothere-instance-is-string-hello.js", - code: `const result = "hello".split("hellothere"); return [result.length, result[0]]`, - expected: [1, "hello"], - labels: ["The value of __split.length is 1", 'The value of __split[0] is "hello"'], - }, - { - path: "test/built-ins/String/prototype/split/call-split-o-instance-is-string-hello.js", - code: `const result = "hello".split("o"); return [result.length, result[0], result[1]]`, - expected: [2, "hell", ""], - labels: ["The value of __split.length is 2", 'The value of __split[0] is "hell"', 'The value of __split[1] is ""'], - }, - { - path: "test/built-ins/String/prototype/split/call-split-x-instance-is-string-hello.js", - code: `const result = "hello".split("x"); return [result.length, result[0]]`, - expected: [1, "hello"], - labels: ["The value of __split.length is 1", 'The value of __split[0] is "hello"'], - }, - { - path: "test/built-ins/String/prototype/split/call-split-x-instance-is-empty-string.js", - code: `const result = "".split("x"); return [result.length, result[0]]`, - expected: [1, ""], - labels: ["The value of __split.length is 1", 'The value of __split[0] is ""'], - }, - { - path: "test/built-ins/String/prototype/split/call-split-4-instance-is-string-one-1-two-2-four-4.js", - code: `const result = "one-1 two-2 four-4".split("-4"); return [result.length, result[0], result[1]]`, - expected: [2, "one-1 two-2 four", ""], - labels: [ - "The value of __split.length is 2", - 'The value of __split[0] is "one-1 two-2 four"', - 'The value of __split[1] is ""', - ], - }, - { - path: "test/built-ins/String/prototype/split/call-split-on-instance-is-string-one-1-two-2-four-4.js", - code: `const result = "one-1 two-2 four-4".split("on"); return [result.length, result[0], result[1]]`, - expected: [2, "", "e-1 two-2 four-4"], - labels: [ - "The value of __split.length is 2", - 'The value of __split[0] is ""', - 'The value of __split[1] is "e-1 two-2 four-4"', - ], - }, - { - path: "test/built-ins/String/prototype/split/call-split-instance-is-string-one-two-three-four-five.js", - code: `const result = "one two three four five".split(" "); return [result.length, ...result]`, - expected: [5, "one", "two", "three", "four", "five"], - labels: [ - "The value of __split.length is 5", - 'The value of __split[0] is "one"', - 'The value of __split[1] is "two"', - 'The value of __split[2] is "three"', - 'The value of __split[3] is "four"', - 'The value of __split[4] is "five"', - ], - }, - { - path: "test/built-ins/String/prototype/split/call-split-instance-is-string-one-two-three.js", - code: `const result = "one two three".split(""); return [result[0], result[1], result[11], result[12]]`, - expected: ["o", "n", "e", "e"], - labels: [ - 'The value of __split[0] is "o"', - 'The value of __split[1] is "n"', - 'The value of __split[11] is "e"', - 'The value of __split[12] is "e"', - ], - }, - { - path: "test/built-ins/String/prototype/split/call-split-instance-is-string.js", - code: `const result = " ".split(" "); return [result.length, result[0], result[1]]`, - expected: [2, "", ""], - labels: ["The value of __split.length is 2", 'The value of __split[0] is ""', 'The value of __split[1] is ""'], - }, - { - path: "test/built-ins/String/prototype/split/instance-is-string-one-two-three-four-five.js", - code: `const result = "one,two,three,four,five".split(); return [result.length, result[0]]`, - expected: [1, "one,two,three,four,five"], - labels: ["The value of __split.length is 1", 'The value of __split[0] is "one,two,three,four,five"'], - }, - { - path: "test/built-ins/String/prototype/split/instance-is-string.js", - code: `const result = " ".split(); return [result.length, result[0]]`, - expected: [1, " "], - labels: ["The value of __split.length is 1", 'The value of __split[0] is " "'], - }, - { - path: "test/built-ins/String/prototype/split/separator-colon-instance-is-string-one-1-two-2-four-4.js", - code: `const result = "one-1,two-2,four-4".split(":"); return [result.length, result[0]]`, - expected: [1, "one-1,two-2,four-4"], - labels: ["The value of __split.length is 1", 'The value of __split[0] is "one-1,two-2,four-4"'], - }, - { - path: "test/built-ins/String/prototype/split/separator-comma-instance-is-string-one-two-three-four-five.js", - code: `const result = "one,two,three,four,five".split(","); return [result.length, ...result]`, - expected: [5, "one", "two", "three", "four", "five"], - labels: [ - "The value of __split.length is 5", - 'The value of __split[0] is "one"', - 'The value of __split[1] is "two"', - 'The value of __split[2] is "three"', - 'The value of __split[3] is "four"', - 'The value of __split[4] is "five"', - ], - }, - { - path: "test/built-ins/String/prototype/split/separator-empty-string-instance-is-string.js", - code: `const result = " ".split(""); return [result.length, result[0]]`, - expected: [1, " "], - labels: ["The value of __split.length is 1", 'The value of __split[0] is " "'], - }, - { - path: "test/built-ins/String/prototype/split/call-split-without-arguments-and-instance-is-empty-string.js", - code: `const result = "".split(); return [result.length, result[0]]`, - expected: [1, ""], - labels: ["The value of __split.length is 1", 'The value of __split[0] is ""'], - }, - { - path: "test/built-ins/String/prototype/split/separator-undef.js", - code: `const result = "undefined is not a function".split(); return [Array.isArray(result), result.length, result[0]]`, - expected: [true, 1, "undefined is not a function"], - labels: [ - "implicit separator, result is array", - "implicit separator, result.length", - "implicit separator, [0] is the same string", - ], - }, - { - path: "test/built-ins/String/prototype/slice/S15.5.4.13_A1_T6.js", - code: `return ["undefined".slice(undefined, 3)]`, - expected: ["und"], - labels: ['#1: new String("undefined").slice(x,3) === "und"'], - }, - { - path: "test/built-ins/String/prototype/slice/S15.5.4.13_A1_T14.js", - code: `return ["report".slice(undefined)]`, - expected: ["report"], - labels: ['#1: "report".slice(function(){}()) === "report"'], - }, - { - path: "test/built-ins/String/prototype/slice/S15.5.4.13_A2_T1.js", - code: `return [typeof "this is a string object".slice()]`, - expected: ["string"], - labels: ['#1: typeof __string.slice() === "string"'], - }, - { - path: "test/built-ins/String/prototype/slice/S15.5.4.13_A2_T2.js", - code: `return ["this is a string object".slice(NaN, Infinity)]`, - expected: ["this is a string object"], - labels: ['#1: __string.slice(NaN, Infinity) === "this is a string object"'], - }, - { - path: "test/built-ins/String/prototype/slice/S15.5.4.13_A2_T3.js", - code: `return ["".slice(1, 0)]`, - expected: [""], - labels: ['#1: __string.slice(1,0) === ""'], - }, - { - path: "test/built-ins/String/prototype/slice/S15.5.4.13_A2_T4.js", - code: `return ["this is a string object".slice(Infinity, NaN)]`, - expected: [""], - labels: ['#1: __string.slice(Infinity, NaN) === ""'], - }, - { - path: "test/built-ins/String/prototype/slice/S15.5.4.13_A2_T5.js", - code: `return ["this is a string object".slice(Infinity, Infinity)]`, - expected: [""], - labels: ['#1: __string.slice(Infinity, Infinity) === ""'], - }, - { - path: "test/built-ins/String/prototype/slice/S15.5.4.13_A2_T6.js", - code: `return ["this is a string object".slice(-0.01, 0)]`, - expected: [""], - labels: ['#1: __string.slice(-0.01,0) === ""'], - }, - { - path: "test/built-ins/String/prototype/slice/S15.5.4.13_A2_T7.js", - code: `const text = "this is a string object"; return [text.slice(text.length, text.length)]`, - expected: [""], - labels: ['#1: __string.slice(__string.length, __string.length) === ""'], - }, - { - path: "test/built-ins/String/prototype/slice/S15.5.4.13_A2_T8.js", - code: `const text = "this is a string object"; return [text.slice(text.length + 1, 0)]`, - expected: [""], - labels: ['#1: __string.slice(__string.length+1, 0) === ""'], - }, - { - path: "test/built-ins/String/prototype/slice/S15.5.4.13_A2_T9.js", - code: `return ["this is a string object".slice(-Infinity, -Infinity)]`, - expected: [""], - labels: ['#1: __string.slice(-Infinity, -Infinity) === ""'], - }, - { - path: "test/built-ins/String/prototype/substring/S15.5.4.15_A1_T6.js", - code: `return ["undefined".substring(undefined, 3)]`, - expected: ["und"], - labels: ['#1: new String("undefined").substring(x,3) === "und"'], - }, - { - path: "test/built-ins/String/prototype/substring/S15.5.4.15_A1_T14.js", - code: `return ["report".substring(undefined)]`, - expected: ["report"], - labels: ['#1: "report".substring(function(){}()) === "report"'], - }, - { - path: "test/built-ins/String/prototype/substring/S15.5.4.15_A2_T1.js", - code: `return [typeof "this is a string object".substring()]`, - expected: ["string"], - labels: ['#1: typeof __string.substring() === "string"'], - }, - { - path: "test/built-ins/String/prototype/substring/S15.5.4.15_A2_T2.js", - code: `return ["this is a string object".substring(NaN, Infinity)]`, - expected: ["this is a string object"], - labels: ['#1: __string.substring(NaN, Infinity) === "this is a string object"'], - }, - { - path: "test/built-ins/String/prototype/substring/S15.5.4.15_A2_T3.js", - code: `return ["".substring(1, 0)]`, - expected: [""], - labels: ['#1: __string.substring(1,0) === ""'], - }, - { - path: "test/built-ins/String/prototype/substring/S15.5.4.15_A2_T4.js", - code: `return ["this is a string object".substring(Infinity, NaN)]`, - expected: ["this is a string object"], - labels: ['#1: __string.substring(Infinity, NaN) === "this is a string object"'], - }, - { - path: "test/built-ins/String/prototype/substring/S15.5.4.15_A2_T5.js", - code: `return ["this is a string object".substring(Infinity, Infinity)]`, - expected: [""], - labels: ['#1: __string.substring(Infinity, Infinity) === ""'], - }, - { - path: "test/built-ins/String/prototype/substring/S15.5.4.15_A2_T6.js", - code: `return ["this is a string object".substring(-0.01, 0)]`, - expected: [""], - labels: ['#1: __string.substring(-0.01,0) === ""'], - }, - { - path: "test/built-ins/String/prototype/substring/S15.5.4.15_A2_T7.js", - code: `const text = "this is a string object"; return [text.substring(text.length, text.length)]`, - expected: [""], - labels: ['#1: __string.substring(__string.length, __string.length) === ""'], - }, - { - path: "test/built-ins/String/prototype/substring/S15.5.4.15_A2_T8.js", - code: `const text = "this is a string object"; return [text.substring(text.length + 1, 0)]`, - expected: ["this is a string object"], - labels: ['#1: __string.substring(__string.length+1, 0) === "this is a string object"'], - }, - { - path: "test/built-ins/String/prototype/substring/S15.5.4.15_A2_T9.js", - code: `return ["this is a string object".substring(-Infinity, -Infinity)]`, - expected: [""], - labels: ['#1: __string.substring(-Infinity, -Infinity) === ""'], - }, - { - path: "test/built-ins/String/prototype/substring/S15.5.4.15_A2_T10.js", - code: `return ["this_is_a_string object".substring(0, 8)]`, - expected: ["this_is_"], - labels: ['#1: __string.substring(0,8) === "this_is_"'], - }, - { - path: "test/built-ins/String/prototype/includes/String.prototype.includes_FailMissingLetter.js", - code: `return ["word".includes("a", 0)]`, - expected: [false], - labels: ['"word".includes("a", 0)'], - }, - { - path: "test/built-ins/String/prototype/includes/String.prototype.includes_SuccessNoLocation.js", - code: `return ["word".includes("w")]`, - expected: [true], - labels: ['"word".includes("w")'], - }, - { - path: "test/built-ins/String/prototype/includes/String.prototype.includes_FailBadLocation.js", - code: `return ["word".includes("w", 5)]`, - expected: [false], - labels: ['"word".includes("w", 5)'], - }, - { - path: "test/built-ins/String/prototype/includes/String.prototype.includes_FailLocation.js", - code: `return ["word".includes("o", 3)]`, - expected: [false], - labels: ['"word".includes("o", 3)'], - }, - { - path: "test/built-ins/String/prototype/includes/String.prototype.includes_Success.js", - code: `return ["word".includes("w", 0)]`, - expected: [true], - labels: ['"word".includes("w", 0)'], - }, - { - path: "test/built-ins/String/prototype/includes/searchstring-found-with-position.js", - code: `const text = "The future is cool!"; return [text.includes("The future", 0), text.includes(" is ", 1), text.includes("cool!", 10)]`, - expected: [true, true, true], - labels: [ - 'Returns true for str.includes("The future", 0)', - 'Returns true for str.includes(" is ", 1)', - 'Returns true for str.includes("cool!", 10)', - ], - }, - { - path: "test/built-ins/String/prototype/includes/searchstring-found-without-position.js", - code: `const text = "The future is cool!"; return [text.includes("The future"), text.includes("is cool!"), text.includes(text)]`, - expected: [true, true, true], - labels: [ - 'Returns true for str.includes("The future")', - 'Returns true for str.includes("is cool!")', - "Returns true for str.includes(str)", - ], - }, - { - path: "test/built-ins/String/prototype/includes/searchstring-not-found-with-position.js", - code: `const text = "The future is cool!"; return [text.includes("The future", 1), text.includes(text, 1)]`, - expected: [false, false], - labels: ['Returns false on str.includes("The future", 1)', "Returns false on str.includes(str, 1)"], - }, - { - path: "test/built-ins/String/prototype/includes/searchstring-not-found-without-position.js", - code: `const text = "The future is cool!"; return [text.includes("Flash"), text.includes("FUTURE")]`, - expected: [false, false], - labels: ["Flash if not included", "includes is case sensitive"], - }, - { - path: "test/built-ins/String/prototype/includes/return-false-with-out-of-bounds-position.js", - code: `const text = "The future is cool!"; return [ - text.includes("!", text.length + 1), text.includes("!", 100), text.includes("!", Infinity), text.includes("!", text.length), - ]`, - expected: [false, false, false, false], - labels: [ - 'str.includes("!", str.length + 1) returns false', - 'str.includes("!", 100) returns false', - 'str.includes("!", Infinity) returns false', - 'str.includes("!", str.length) returns false', - ], - }, - { - path: "test/built-ins/String/prototype/includes/return-true-if-searchstring-is-empty.js", - code: `const text = "The future is cool!"; return [text.includes("", text.length), text.includes(""), text.includes("", Infinity)]`, - expected: [true, true, true], - labels: [ - 'str.includes("", str.length) returns true', - 'str.includes("") returns true', - 'str.includes("", Infinity) returns true', - ], - }, - { - path: "test/built-ins/String/prototype/includes/coerced-values-of-position.js", - code: `const text = "The future is cool!"; return [ - text.includes("The future", NaN), text.includes("The future", undefined), text.includes("The future", 0.4), - text.includes("The future", -1), text.includes("The future", 1.4), - ]`, - expected: [true, true, true, true, false], - labels: ["NaN coerced to 0", "undefined coerced to 0", "0.4 coerced to 0", "negative position", "1.4 coerced to 1"], - }, - { - path: "test/built-ins/String/prototype/startsWith/searchstring-found-with-position.js", - code: `const text = "The future is cool!"; return [text.startsWith("The future", 0), text.startsWith("future", 4), text.startsWith(" is cool!", 10)]`, - expected: [true, true, true], - labels: [ - 'str.startsWith("The future", 0) === true', - 'str.startsWith("future", 4) === true', - 'str.startsWith(" is cool!", 10) === true', - ], - }, - { - path: "test/built-ins/String/prototype/startsWith/searchstring-found-without-position.js", - code: `const text = "The future is cool!"; return [text.startsWith("The "), text.startsWith("The future"), text.startsWith(text)]`, - expected: [true, true, true], - labels: [ - 'str.startsWith("The ") === true', - 'str.startsWith("The future") === true', - "str.startsWith(str) === true", - ], - }, - { - path: "test/built-ins/String/prototype/startsWith/searchstring-not-found-with-position.js", - code: `const text = "The future is cool!"; return [text.startsWith("The future", 1), text.startsWith(text, 1)]`, - expected: [false, false], - labels: ['str.startsWith("The future", 1) === false', "str.startsWith(str, 1) === false"], - }, - { - path: "test/built-ins/String/prototype/startsWith/searchstring-not-found-without-position.js", - code: `const text = "The future is cool!"; return [text.startsWith("Flash"), text.startsWith("THE FUTURE"), text.startsWith("future is cool!")]`, - expected: [false, false, false], - labels: [ - 'str.startsWith("Flash") === false', - "startsWith is case sensitive", - 'str.startsWith("future is cool!") === false', - ], - }, - { - path: "test/built-ins/String/prototype/startsWith/out-of-bounds-position.js", - code: `const text = "The future is cool!"; return [ - text.startsWith("!", text.length), text.startsWith("!", 100), text.startsWith("!", Infinity), - text.startsWith("The future", -1), text.startsWith("The future", -Infinity), - ]`, - expected: [false, false, false, true, true], - labels: [ - 'str.startsWith("!", str.length) returns false', - 'str.startsWith("!", 100) returns false', - 'str.startsWith("!", Infinity) returns false', - "position argument < 0 will search from the start of the string (-1)", - "position argument < 0 will search from the start of the string (-Infinity)", - ], - }, - { - path: "test/built-ins/String/prototype/startsWith/return-true-if-searchstring-is-empty.js", - code: `const text = "The future is cool!"; return [text.startsWith(""), text.startsWith("", text.length), text.startsWith("", Infinity)]`, - expected: [true, true, true], - labels: [ - 'str.startsWith("") returns true', - 'str.startsWith("", str.length) returns true', - 'str.startsWith("", Infinity) returns true', - ], - }, - { - path: "test/built-ins/String/prototype/startsWith/coerced-values-of-position.js", - code: `const text = "The future is cool!"; return [ - text.startsWith("The future", NaN), text.startsWith("The future", undefined), - text.startsWith("The future", 0.4), text.startsWith("The future", 1.4), - ]`, - expected: [true, true, true, false], - labels: ["NaN coerced to 0", "undefined coerced to 0", "0.4 coerced to 0", "1.4 coerced to 1"], - }, - { - path: "test/built-ins/String/prototype/endsWith/String.prototype.endsWith_Success.js", - code: `return ["word".endsWith("d")]`, - expected: [true], - labels: ['"word".endsWith("d")'], - }, - { - path: "test/built-ins/String/prototype/endsWith/String.prototype.endsWith_Success_2.js", - code: `return ["word".endsWith("d", 4)]`, - expected: [true], - labels: ['"word".endsWith("d", 4)'], - }, - { - path: "test/built-ins/String/prototype/endsWith/String.prototype.endsWith_Success_3.js", - code: `return ["word".endsWith("d", 25)]`, - expected: [true], - labels: ['"word".endsWith("d", 25)'], - }, - { - path: "test/built-ins/String/prototype/endsWith/String.prototype.endsWith_Success_4.js", - code: `return ["word".endsWith("r", 3)]`, - expected: [true], - labels: ['"word".endsWith("r", 3)'], - }, - { - path: "test/built-ins/String/prototype/endsWith/String.prototype.endsWith_Fail.js", - code: `return ["word".endsWith("r")]`, - expected: [false], - labels: ['"word".endsWith("r")'], - }, - { - path: "test/built-ins/String/prototype/endsWith/String.prototype.endsWith_Fail_2.js", - code: `return ["word".endsWith("d", 3)]`, - expected: [false], - labels: ['"word".endsWith("d", 3)'], - }, - { - path: "test/built-ins/String/prototype/endsWith/searchstring-found-with-position.js", - code: `const text = "The future is cool!"; return [text.endsWith("The future", 10), text.endsWith("future", 10), text.endsWith(" is cool!", text.length)]`, - expected: [true, true, true], - labels: [ - 'str.endsWith("The future", 10) === true', - 'str.endsWith("future", 10) === true', - 'str.endsWith(" is cool!", str.length) === true', - ], - }, - { - path: "test/built-ins/String/prototype/endsWith/searchstring-found-without-position.js", - code: `const text = "The future is cool!"; return [text.endsWith("cool!"), text.endsWith("!"), text.endsWith(text)]`, - expected: [true, true, true], - labels: ['str.endsWith("cool!") === true', 'str.endsWith("!") === true', "str.endsWith(str) === true"], - }, - { - path: "test/built-ins/String/prototype/endsWith/searchstring-not-found-with-position.js", - code: `const text = "The future is cool!"; return [text.endsWith("is cool!", text.length - 1), text.endsWith("!", 1)]`, - expected: [false, false], - labels: ['str.endsWith("is cool!", str.length - 1) === false', 'str.endsWith("!", 1) === false'], - }, - { - path: "test/built-ins/String/prototype/endsWith/searchstring-not-found-without-position.js", - code: `const text = "The future is cool!"; return [text.endsWith("is Flash!"), text.endsWith("IS COOL!"), text.endsWith("The future")]`, - expected: [false, false, false], - labels: [ - 'str.endsWith("is Flash!") === false', - "endsWith is case sensitive", - 'str.endsWith("The future") === false', - ], - }, - { - path: "test/built-ins/String/prototype/endsWith/return-false-if-search-start-is-less-than-zero.js", - code: `return ["web".endsWith("w", 0), "Bob".endsWith(" Bob")]`, - expected: [false, false], - labels: ['"web".endsWith("w", 0) returns false', '"Bob".endsWith(" Bob") returns false'], - }, - { - path: "test/built-ins/String/prototype/endsWith/return-true-if-searchstring-is-empty.js", - code: `const text = "The future is cool!"; return [ - text.endsWith(""), text.endsWith("", text.length), text.endsWith("", Infinity), - text.endsWith("", -1), text.endsWith("", -Infinity), - ]`, - expected: [true, true, true, true, true], - labels: [ - 'str.endsWith("") returns true', - 'str.endsWith("", str.length) returns true', - 'str.endsWith("", Infinity) returns true', - 'str.endsWith("", -1) returns true', - 'str.endsWith("", -Infinity) returns true', - ], - }, - { - path: "test/built-ins/String/prototype/endsWith/coerced-values-of-position.js", - code: `const text = "The future is cool!"; return [ - text.endsWith("", NaN), text.endsWith("", undefined), text.endsWith("The future", 10.4), - ]`, - expected: [true, true, true], - labels: ["NaN coerced to 0", "undefined coerced to 0", "10.4 coerced to 10"], - }, - { - path: "test/built-ins/String/prototype/indexOf/S15.5.4.7_A2_T1.js", - code: `return ["abcd".indexOf("abcdab")]`, - expected: [-1], - labels: ['#1: "abcd".indexOf("abcdab")===-1'], - }, - { - path: "test/built-ins/String/prototype/indexOf/S15.5.4.7_A2_T2.js", - code: `return ["abcd".indexOf("abcdab", 0)]`, - expected: [-1], - labels: ['#1: "abcd".indexOf("abcdab",0)===-1'], - }, - { - path: "test/built-ins/String/prototype/indexOf/S15.5.4.7_A2_T3.js", - code: `return ["abcd".indexOf("abcdab", 99)]`, - expected: [-1], - labels: ['#1: "abcd".indexOf("abcdab",99)===-1'], - }, - { - path: "test/built-ins/String/prototype/indexOf/S15.5.4.7_A2_T4.js", - code: `return ["abcd".indexOf("abcdab", NaN)]`, - expected: [-1], - labels: ['#1: "abcd".indexOf("abcdab",NaN)===-1'], - }, - { - path: "test/built-ins/String/prototype/indexOf/S15.5.4.7_A3_T1.js", - code: `return ["$$abcdabcd".indexOf("ab", NaN)]`, - expected: [2], - labels: ['#1: "$$abcdabcd".indexOf("ab",NaN)===2'], - }, - { - path: "test/built-ins/String/prototype/indexOf/S15.5.4.7_A3_T3.js", - code: `return ["$$abcdabcd".indexOf("ab", -Infinity)]`, - expected: [2], - labels: ['#1: "$$abcdabcd".indexOf("ab", function(){return -Infinity;}())===2'], - }, - { - path: "test/built-ins/String/prototype/indexOf/position-tointeger.js", - code: `return [ - "aaaa".indexOf("aa", 0), "aaaa".indexOf("aa", 1), "aaaa".indexOf("aa", -0.9), - "aaaa".indexOf("aa", 0.9), "aaaa".indexOf("aa", 1.9), "aaaa".indexOf("aa", NaN), - "aaaa".indexOf("aa", Infinity), "aaaa".indexOf("aa", undefined), - "aaaa".indexOf("aa", 2), "aaaa".indexOf("aa", 2.9), - ]`, - expected: [0, 1, 0, 0, 1, 0, -1, 0, 2, 2], - labels: [ - "position 0", - "position 1", - "ToInteger: truncate towards 0 (-0.9)", - "ToInteger: truncate towards 0 (0.9)", - "ToInteger: truncate towards 0 (1.9)", - "ToInteger: NaN => 0", - "position Infinity", - "ToInteger: undefined => NaN => 0", - "position 2", - "ToInteger: truncate towards 0 (2.9)", - ], - }, - { - path: "test/built-ins/String/prototype/indexOf/searchstring-tostring.js", - code: `return ["foo".indexOf(""), "__foo__".indexOf("foo")]`, - expected: [0, 2], - labels: ['"foo".indexOf("")', '"__foo__".indexOf("foo")'], - }, - { - path: "test/built-ins/String/prototype/lastIndexOf/not-a-substring.js", - code: `return ["abc".lastIndexOf("d")]`, - expected: [-1], - labels: [ - "String.prototype.lastIndexOf returns -1 when searchString is shorter than this and searchString is not a substring of this.", - ], - }, -] as const - -describe("Test262-adapted String search and extraction behavior", () => { - for (const item of cases) { - test(item.path, async () => { - const actual = await value(item.code) - if (!Array.isArray(actual)) throw new Error(`expected assertion values for ${item.path}`) - expect(actual.length, "adapted assertion count").toBe(item.expected.length) - item.expected.forEach((expected, index) => expect(actual[index], item.labels[index]!).toEqual(expected)) - }) - } -}) diff --git a/packages/codemode/test/suspend.test.ts b/packages/codemode/test/suspend.test.ts index 557d4163366..74bec30f12f 100644 --- a/packages/codemode/test/suspend.test.ts +++ b/packages/codemode/test/suspend.test.ts @@ -1,6 +1,4 @@ import { describe, expect, test } from "bun:test" -import { tmpdir } from "node:os" -import path from "node:path" import { Context, Effect, Fiber, Schema } from "effect" import { CodeMode, Extension, Tool } from "../src/index.js" @@ -193,80 +191,7 @@ const suspendBetweenCalls = async ( return { step, runtime, run } } -describe("synchronous host calls", () => { - // Each sync extension call stops the VM; the slice clock must keep running across those stops, or a loop of them - // never yields: suspend can't land and timeouts can't interrupt it. - const counter = () => { - let calls = 0 - let reached = latch() - const extension = Extension.make({ - name: "draw", - globals: { - draw: (n: number) => { - calls += 1 - if (calls === 500) reached.resolve() - return n - }, - }, - }) - return { extension, reached: () => reached.promise, calls: () => calls } - } - - // Round-trip mode also yields at every host stop, where a suspend lands mid-call and is rightly refused. - test.skipIf(process.env.CODEMODE_ROUNDTRIP === "1")( - "a loop of sync extension calls can be suspended and resumed", - async () => { - const draw = counter() - const runtime = CodeMode.make({ extensions: [draw.extension] }) - const run = background(runtime.program("let n = 0\nwhile (n < 200000) draw(n++)\nreturn n")) - await draw.reached() - const suspended = suspendedOf(await Effect.runPromise(run.suspend)) - expect(draw.calls()).toBeLessThan(200000) - const resumed = await Effect.runPromise(background(runtime.resume(CodeMode.toBytes(suspended.state))).result) - expect(resumed).toMatchObject({ ok: true, value: 200000 }) - }, - ) - - test("a loop of sync extension calls is interrupted by the timeout", async () => { - const draw = counter() - const outcome = await Effect.runPromise( - CodeMode.make({ extensions: [draw.extension], limits: { timeoutMs: 100 } }).execute( - "let n = 0\nwhile (true) draw(n++)", - ), - ) - expect(outcome).toMatchObject({ ok: false, error: { kind: "TimeoutExceeded" } }) - }) -}) - describe("suspend", () => { - test("a run suspended while idle-awaiting between calls resumes from state and from bytes", async () => { - const code = ` - const log = ["before"] - const a = await tools.step({ value: 20 }) - const started = Date.now() - while (Date.now() - started < 300) await Promise.resolve() - const b = await tools.step({ value: 1 }) - log.push("after " + (a.value + b.value)) - console.log("resumed") - return { log, total: a.value + b.value }` - const { step, run } = await suspendBetweenCalls(code) - const suspended = suspendedOf(await Effect.runPromise(run.suspend)) - // The run's own result is the same saved state. - expect(suspendedOf(await Effect.runPromise(run.result))).toBe(suspended) - - for (const state of [suspended.state, CodeMode.toBytes(suspended.state)] as const) { - const outcome = await Effect.runPromise( - background(CodeMode.make({ tools: { step: step.tool } }).resume(state)).result, - ) - expect(outcome).toEqual({ - ok: true, - value: { log: ["before", "after 42"], total: 42 }, - logs: ["resumed"], - toolCalls: [{ name: "step" }, { name: "step" }], - }) - } - }) - test("a suspend fails while a tool, search, or an extension call is running, and the run goes on", async () => { const slow = manual() const searching = latch() @@ -375,89 +300,6 @@ describe("suspend", () => { { key: "n:1", path: "tools.slow" }, ]) }) - - test("a suspend after the run ended gives its result", async () => { - const program = CodeMode.make().program(`return 1 + 1`) - expect(await Effect.runPromise(program.run())).toEqual({ ok: true, value: 2, toolCalls: [] }) - expect(await Effect.runPromise(program.suspend())).toEqual({ ok: true, value: 2, toolCalls: [] }) - }) - - test("a program runs inline in the current fiber", async () => { - const runtime = CodeMode.make({ tools: { step: stepTool().tool } }) - expect( - await Effect.runPromise(runtime.program(`return (await tools.step({ value: x })).value`, { x: 21 }).run()), - ).toEqual({ ok: true, value: 42, toolCalls: [{ name: "step" }] }) - }) - - test("a suspend from another fiber stops a background run, which returns the same state", async () => { - const runtime = CodeMode.make({ tools: {} }) - const code = `let n = 0; for (let i = 0; i < 2_000_000; i++) n = (n + i) % 1_000_003; return n` - const expected = await Effect.runPromise(runtime.execute(code)) - const [suspended, outcome] = await Effect.runPromise( - Effect.gen(function* () { - const program = runtime.program(code) - const fiber = yield* Effect.forkChild(program.run()) - // Issued before the run starts: it waits for it. - const suspended = yield* program.suspend() - return [suspended, yield* Fiber.join(fiber)] as const - }), - ) - expect(outcome).toBe(suspended) - const fresh = CodeMode.make({ tools: {} }) - expect(await Effect.runPromise(fresh.resume(CodeMode.toBytes(suspendedOf(suspended).state)).run())).toEqual( - expected, - ) - }) - - test("a program runs once", async () => { - const program = CodeMode.make().program(`return 1`) - expect(await Effect.runPromise(program.run())).toMatchObject({ ok: true, value: 1 }) - const exit = await Effect.runPromise(Effect.exit(program.run())) - expect(String(exit)).toContain("A program runs once") - }) - - test("interrupting run interrupts the program and its running calls", async () => { - const called = latch() - const interrupted = latch() - const hang = Tool.make({ - description: "Never answers", - input: Value, - output: Value, - execute: () => - Effect.sync(() => called.resolve()).pipe( - Effect.andThen(Effect.never), - Effect.onInterrupt(() => Effect.sync(() => interrupted.resolve())), - ), - }) - const program = CodeMode.make({ tools: { hang } }).program(`return await tools.hang({ value: 1 })`) - const fiber = Effect.runFork(program.run()) - await called.promise - await Effect.runPromise(Fiber.interrupt(fiber)) - await interrupted.promise - }) - - test("a state over the byte budget fails the suspend, and the run goes on", async () => { - const { run } = await suspendBetweenCalls( - `const big = "x".repeat(1000); await tools.step({ value: 1 }); const t = Date.now(); while (Date.now() - t < 300) {} return big.length`, - ) - const error = await blocked({ suspend: run.program.suspend({ maxBytes: 100 }) }) - expect(error.running).toEqual([]) - expect(error.message).toMatch(/^The run's state takes \d+ bytes, more than the 100-byte limit/) - expect(await Effect.runPromise(run.result)).toMatchObject({ ok: true, value: 1000 }) - }) - - test("a maxBytes that isn't a non-negative integer is rejected", () => { - const program = CodeMode.make().program("return 1") - expect(() => program.suspend({ maxBytes: -1 })).toThrow(RangeError) - }) - - test("the snapshot codec does not import Effect", async () => { - for (const file of ["codec.ts", "snapshot.ts"]) { - expect(await Bun.file(path.join(import.meta.dir, "../src/language/snapshot", file)).text()).not.toMatch( - /from "effect"/, - ) - } - }) }) describe("resume", () => { @@ -466,34 +308,6 @@ describe("resume", () => { return { step, suspended: suspendedOf(await Effect.runPromise(run.suspend)) } } - test("a run saved to a file resumes in another process", async () => { - const step = stepTool() - const run = background( - CodeMode.make({ tools: { slow: step.tool } }).program(` - const seen = new Map([["first", await tools.slow({ value: 10 })]]) - const started = Date.now() - while (Date.now() - started < 300) {} - const second = await tools.slow({ value: 21 }) - return [seen.get("first").value, second.value]`), - ) - await step.called() - await Bun.sleep(10) - const suspended = suspendedOf(await Effect.runPromise(run.suspend)) - const file = path.join(tmpdir(), `codemode-${crypto.randomUUID()}.state`) - await Bun.write(file, CodeMode.toBytes(suspended.state)) - try { - const child = Bun.spawn(["bun", path.join(import.meta.dir, "fixtures/resume-process.ts"), file], { - stdout: "pipe", - stderr: "inherit", - }) - const output = await new Response(child.stdout).text() - expect(await child.exited).toBe(0) - expect(JSON.parse(output)).toEqual({ ok: true, value: [20, 42], toolCalls: [{ name: "slow" }, { name: "slow" }] }) - } finally { - await Bun.file(file).delete() - } - }) - test("a resumed run keeps the limits it was saved with", async () => { const { step, run } = await suspendBetweenCalls( `await tools.step({ value: 1 }); const t = Date.now(); while (Date.now() - t < 300) {} await tools.step({ value: 2 }); await tools.step({ value: 3 }); return "done"`, @@ -573,7 +387,7 @@ describe("resume", () => { const header = state.header const runtime = CodeMode.make({ tools: {} }) expect((await refusal(runtime.resume({ ...state, header: { ...header, build: "0.0.0+0" } }))).message).toMatch( - /saved by another Code Mode build \(0\.0\.0\+0\)/, + /saved by another psychoscript build \(0\.0\.0\+0\)/, ) const other = CodeMode.make({ extensions: [Extension.make({ name: "x", globals: { f: () => 1 } })] }) expect((await refusal(other.resume(state))).message).toMatch("saved by a runtime with other host globals") @@ -625,116 +439,6 @@ describe("resume", () => { }, }) }) - - test("program state of every kind survives a suspend", async () => { - const code = ` - const shared = { n: 1 } - const map = new Map([[shared, "a"], ["k", shared]]) - const set = new Set([1, shared]) - const it = map.keys() - it.next() - const url = new URL("https://example.com/a?x=1") - const params = url.searchParams - const bytes = new Uint8Array([1, 2, 3, 4]) - const view = bytes.subarray(1, 3) - const re = /a(b)/g - re.test("abab") - const date = new Date(0) - const weak = new WeakMap([[shared, 5]]) - function* counter() { let i = 0; while (true) yield i++ } - const gen = counter() - gen.next() - const bound = ((a, b) => a + b).bind(null, 10) - const sparse = [] - sparse[5000] = "far" - const pending = new Promise((resolve) => (globalResolve = resolve)) - var globalResolve - Array.prototype.extra = "patched" - await tools.step({ value: 1 }) - const t = Date.now() - while (Date.now() - t < 300) {} - params.append("y", "2") - view[0] = 9 - globalResolve("later") - return { - same: map.get("k") === shared && set.has(shared) && weak.get(shared) === 5, - next: it.next().value, - url: url.href, - bytes: [...bytes], - lastIndex: re.lastIndex, - date: date.getTime(), - gen: [gen.next().value, gen.next().value], - bound: bound(5), - sparse: [5001, "far", false], - pending: await pending, - extra: [].extra, - negative: Object.is(-0, -0 * 1), - }` - const { step, suspended } = await suspendAt(code) - const outcome = await Effect.runPromise( - background(CodeMode.make({ tools: { step: step.tool } }).resume(CodeMode.toBytes(suspended.state))).result, - ) - expect(outcome).toMatchObject({ - ok: true, - value: { - same: true, - next: "k", - url: "https://example.com/a?x=1&y=2", - bytes: [1, 9, 3, 4], - lastIndex: 2, - date: 0, - gen: [1, 2], - bound: 15, - sparse: [5001, "far", false], - pending: "later", - extra: "patched", - negative: true, - }, - }) - }) - - test("changes to built-ins survive a second suspend, including freeze, seal, and deletes", async () => { - const code = ` - Array.prototype.extra = "patched" - delete Math.max - Object.freeze(JSON) - Object.seal(Number.prototype) - Object.preventExtensions(Date.prototype) - await tools.step({ value: 1 }) - const t1 = Date.now() - while (Date.now() - t1 < 300) {} - await tools.step({ value: 2 }) - const t2 = Date.now() - while (Date.now() - t2 < 300) {} - return { - extra: [].extra, - max: typeof Math.max, - frozen: Object.isFrozen(JSON), - sealed: Object.isSealed(Number.prototype) && !Object.isFrozen(Number.prototype), - extensible: Object.isExtensible(Date.prototype), - untouched: Object.isExtensible(Map.prototype) && typeof Math.min, - }` - const { step, suspended } = await suspendAt(code) - step.reset() - const runtime = CodeMode.make({ tools: { step: step.tool } }) - const again = background(runtime.resume(CodeMode.toBytes(suspended.state))) - await step.called() - await Bun.sleep(10) - // Nothing changed a built-in since the first resume: the second state keeps what changed before. - const second = suspendedOf(await Effect.runPromise(again.suspend)) - const outcome = await Effect.runPromise(background(runtime.resume(CodeMode.toBytes(second.state))).result) - expect(outcome).toMatchObject({ - ok: true, - value: { - extra: "patched", - max: "undefined", - frozen: true, - sealed: true, - extensible: false, - untouched: "function", - }, - }) - }) }) describe("idempotent and durable tools", () => { diff --git a/packages/codemode/test/test262.test.ts b/packages/codemode/test/test262.test.ts deleted file mode 100644 index e368e54510c..00000000000 --- a/packages/codemode/test/test262.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Runs the test262 files vendored under test/test262 (see test/test262/README.md) verbatim. - * Files listed in test/test262/skipped.txt fail on a known interpreter gap and are skipped; - * `bun run script/test262-report.ts` shows current gaps and which skipped files pass again. - * Licensed under test/LICENSE.test262. - */ -import { test } from "bun:test" -import { root, run, skipped } from "./test262/run.js" - -for (const file of [...new Bun.Glob("**/*.js").scanSync({ cwd: root, followSymlinks: true })].sort()) { - const define = skipped.has(file) ? test.skip : test - define( - file, - async () => { - const outcome = await run(file) - if (outcome.status === "fail") throw new Error(outcome.reason) - }, - 10_000, - ) -} diff --git a/packages/codemode/test/test262/.gitignore b/packages/codemode/test/test262/.gitignore deleted file mode 100644 index 30b435be793..00000000000 --- a/packages/codemode/test/test262/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -# Upstream test262 files are populated locally by script/sync-test262.ts and not committed yet. -# No trailing slash, so local symlinks to a corpus elsewhere are ignored too. -built-ins -language diff --git a/packages/codemode/test/test262/README.md b/packages/codemode/test/test262/README.md deleted file mode 100644 index 05af4899e74..00000000000 --- a/packages/codemode/test/test262/README.md +++ /dev/null @@ -1,43 +0,0 @@ -# test262 - -Runs upstream [test262](https://github.com/tc39/test262) files verbatim through `test/test262.test.ts`. The files -themselves are not committed yet: populate them from a local checkout with - -```sh -git clone https://github.com/tc39/test262 ~/development/test262 -bun run script/sync-test262.ts ~/development/test262 -``` - -Without them the runner registers no tests, so CI is unaffected. Licensed under `test/LICENSE.test262`. - -## Layout - -- `manifest.json` — the pinned upstream revision, which upstream directories are copied (every `built-ins` and - `language` directory, about 22,300 files after filtering), and what is left out. -- `built-ins/`, `language/` — the copied files, mirroring upstream `test/`; gitignored. -- `skipped.txt` — vendored files that fail on a known interpreter gap, one `path # reason` per line. They are - skipped, and each gap is listed as unchecked in `interpreter-support.md`. -- `run.ts` — runs one file: prepends `"use strict"`, provides the harness (`assert`, `Test262Error`, - `compareArray`, `$DONE`, `$DONOTEVALUATE`) as host globals, and interprets the file's frontmatter (`negative`, - `flags: [async]`). - -## What is not vendored - -`script/sync-test262.ts` skips a file when its frontmatter declares a `flags`, `features`, or `includes` value the -manifest marks unsupported, or when its code matches one of the manifest's `boundaries` patterns. The sync checks the -checkout is at the pinned revision, so every machine runs the same files. Boundaries are -intentional limits of the interpreter, not compatibility work: prototype mutation, legacy accessors -(`__defineGetter__` and friends), boxed primitives, typed arrays and buffers, `WeakRef` and `FinalizationRegistry`, `Reflect` and `Proxy`, sloppy mode, `eval`, -`Symbol()`, and the `$262` host API. If one -of those decisions changes, delete its entry and re-sync; the tests are upstream, not lost. - -## Commands - -```sh -bun run script/sync-test262.ts /path/to/test262 # re-copy at the pinned revision; edit manifest.json to change scope -bun run script/test262-report.ts [--write] [dir] # run everything, group failures by cause; --write regenerates skipped.txt -bun test test/test262.test.ts # what CI runs -``` - -When a fix makes skipped files pass, the report lists them so they can be removed from `skipped.txt`, and the -matching gap in `interpreter-support.md` is checked in the same change. diff --git a/packages/codemode/test/test262/manifest.json b/packages/codemode/test/test262/manifest.json deleted file mode 100644 index 43b18c59449..00000000000 --- a/packages/codemode/test/test262/manifest.json +++ /dev/null @@ -1,101 +0,0 @@ -{ - "revision": "250f204f23a9249ff204be2baec29600faae7b75", - "directories": ["built-ins", "language"], - "harness": ["assert.js", "sta.js", "compareArray.js", "doneprintHandle.js"], - "flags": ["module", "raw", "noStrict"], - "boundaries": { - "prototype mutation": "Object\\.setPrototypeOf\\b", - "legacy accessors": "\\b__(define|lookup)(Getter|Setter)__\\b", - "boxed primitives": "\\b(new\\s+(String|Number|Boolean)\\b|Object\\s*\\(\\s*(true|false|-?\\d|['\"]))", - "typed arrays and buffers": "\\b(ArrayBuffer|SharedArrayBuffer|DataView|Int8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float16Array|Float32Array|Float64Array|BigInt64Array|BigUint64Array)\\b", - "weak collections": "\\b(WeakRef|FinalizationRegistry)\\b", - "Reflect and Proxy": "\\b(Reflect|Proxy)\\b", - "sloppy mode": "\\bwith\\s*\\(", - "eval": "\\b(eval|Function)\\b", - "new.target": "\\bnew\\.target\\b", - "globalThis": "\\bglobalThis\\b", - "Symbol": "\\bSymbol\\b(?!\\.(iterator|asyncIterator)\\b)", - "$262 host API": "\\$262" - }, - "features": [ - "BigInt", - "Proxy", - "proxy-missing-checks", - "Reflect", - "Reflect.construct", - "Reflect.set", - "Reflect.setPrototypeOf", - "Symbol", - "Symbol.hasInstance", - "Symbol.isConcatSpreadable", - "Symbol.match", - "Symbol.matchAll", - "Symbol.prototype.description", - "Symbol.replace", - "Symbol.search", - "Symbol.species", - "Symbol.split", - "Symbol.toPrimitive", - "Symbol.toStringTag", - "Symbol.unscopables", - "symbols-as-weakmap-keys", - "class-fields-private", - "class-fields-private-in", - "class-methods-private", - "class-static-block", - "class-static-fields-private", - "class-static-methods-private", - "new.target", - "decorators", - "TypedArray", - "TypedArray.prototype.at", - "ArrayBuffer", - "SharedArrayBuffer", - "DataView", - "Atomics", - "Atomics.pause", - "Atomics.waitAsync", - "resizable-arraybuffer", - "arraybuffer-transfer", - "immutable-arraybuffer", - "Float16Array", - "Float32Array", - "Float64Array", - "Int8Array", - "Int16Array", - "Int32Array", - "Uint8Array", - "Uint8ClampedArray", - "Uint16Array", - "Uint32Array", - "uint8array-base64", - "WeakRef", - "FinalizationRegistry", - "Intl-enumeration", - "Temporal", - "ShadowRealm", - "cross-realm", - "dynamic-import", - "import.meta", - "import-attributes", - "import-defer", - "export-defer", - "source-phase-imports", - "source-phase-imports-module-source", - "import-text", - "import-bytes", - "json-modules", - "top-level-await", - "explicit-resource-management", - "tail-call-optimization", - "caller", - "IsHTMLDDA", - "host-gc-required", - "legacy-regexp", - "__proto__", - "__getter__", - "__setter__", - "iterator-sequencing", - "joint-iteration" - ] -} diff --git a/packages/codemode/test/test262/run.ts b/packages/codemode/test/test262/run.ts deleted file mode 100644 index ebc69d0c40c..00000000000 --- a/packages/codemode/test/test262/run.ts +++ /dev/null @@ -1,185 +0,0 @@ -// Runs one vendored test262 file verbatim. The harness (assert, Test262Error, compareArray, $DONE, -// $DONOTEVALUATE) is host-provided, except `assert` itself: a program function made by the prelude, so that -// `assert.throws` can call the function it tests and catch what it throws as plain program code. Its checks and -// failure messages are the host's (`$assert`). -import path from "node:path" -import { Effect } from "effect" -import { finishExecution, type Setup, startProgram } from "../../src/language/runtime/execute.js" -import type { Interpreter } from "../../src/language/runtime/interpreter.js" -import { Throw } from "../../src/language/runtime/model.js" -import { createErrorValue } from "../../src/language/runtime/intrinsics.js" -import { constructor, fn, methods } from "../../src/language/runtime/native.js" -import { Callable, define, get, hidden, Arr, Fn, Obj, type Value } from "../../src/language/runtime/objects.js" - -export const root = import.meta.dir - -/** Files that fail on a known gap, mapped to the gap; see skipped.txt. */ -export const skipped = new Map( - (await Bun.file(path.join(root, "skipped.txt")).text()) - .split("\n") - .filter((line) => line.includes("#")) - .map((line) => [line.slice(0, line.indexOf("#")).trim(), line.slice(line.indexOf("#") + 1).trim()]), -) - -export type Outcome = { readonly status: "pass" } | { readonly status: "fail"; readonly reason: string } - -type Frontmatter = { - flags?: Array - negative?: { phase: "parse" | "resolution" | "runtime"; type: string } -} - -const setup: Setup = { limits: { timeoutMs: 5000, maxOutputBytes: undefined } } - -// One line, on the line of the "use strict" directive, so the test's own line numbers stay as they are. -const prelude = [ - "function assert(mustBeTrue, message) { $assert(mustBeTrue, message) }", - "assert.sameValue = $assert.sameValue; assert.notSameValue = $assert.notSameValue;", - "assert.compareArray = $assert.compareArray;", - "assert.throws = function (expected, func, message) {", - "try { func() } catch (thrown) { $assert.thrown(expected, message, thrown); return }", - "$assert.notThrown(expected, message) };", -].join(" ") - -export const run = async (file: string): Promise => { - const source = await Bun.file(path.join(root, file)).text() - const start = source.indexOf("/*---") - const meta = Bun.YAML.parse(source.slice(start + 5, source.indexOf("---*/", start))) as Frontmatter - let done: { error: unknown } | undefined - // Sloppy-only tests are never vendored, so every file runs as the strict half of test262's two-mode run. - // A host drains the job queue after an async test's script ends; the program end interrupts un-awaited - // work instead, so drain explicitly. - const drain = meta.flags?.includes("async") ? "\nfor (let i = 0; i < 100; i++) await null" : "" - const result = await Effect.runPromise( - finishExecution( - startProgram( - { - ...setup, - programGlobals: (ctx) => - harness(ctx, (error) => { - done ??= { error } - }), - }, - `"use strict"; ${prelude}\n${source}${drain}`, - ).run(), - ), - ) - if (meta.negative !== undefined) { - // Runtime negatives only check that execution failed: diagnostics do not carry the error name. - if (result.ok) return { status: "fail", reason: `expected ${meta.negative.type} but completed` } - if (meta.negative.phase === "runtime" || result.error.kind === "ParseError") return { status: "pass" } - return { - status: "fail", - reason: `expected ${meta.negative.type} but got ${result.error.kind}: ${result.error.message}`, - } - } - if (!result.ok) return { status: "fail", reason: `${result.error.kind}: ${result.error.message}` } - if (!meta.flags?.includes("async")) return { status: "pass" } - if (done === undefined) return { status: "fail", reason: "$DONE was never called" } - if (done.error !== undefined) return { status: "fail", reason: `$DONE: ${show(done.error)}` } - return { status: "pass" } -} - -const harness = (ctx: Interpreter, onDone: (error: Value) => void): ReadonlyArray => { - const builtins = ctx.builtins - const test262Prototype = new Obj(builtins.Object) - define(test262Prototype, "name", "Test262Error", hidden) - const test262 = (args: Array) => - createErrorValue(test262Prototype, args[0] === undefined ? "" : String(args[0])) - const fail = (message: string) => { - throw new Throw(test262([message])) - } - const prefix = (message: unknown) => (message === undefined ? "" : `${String(message)} `) - const expectedName = (ctor: unknown) => (ctor instanceof Callable ? String(get(ctor, "name")) : show(ctor)) - const compare = (a: unknown, b: unknown) => - a instanceof Arr && - b instanceof Arr && - a.items.length === b.items.length && - a.items.every((value, i) => Object.is(value, b.items[i])) - const test262Error = constructor(builtins, test262Prototype, { - name: "Test262Error", - call: (_, args) => test262(args), - construct: (args) => test262(args), - }) - methods(builtins, test262Error, [["thrower", 1, (_, args) => fail(String(args[0]))]]) - const compareArray = fn(builtins, "compareArray", 2, (_, args) => compare(args[0], args[1])) - methods(builtins, compareArray, [["format", 1, (_, args) => show(args[0])]]) - const assert = fn(builtins, "$assert", 2, (_, args) => - args[0] === true - ? undefined - : fail(args[1] === undefined ? `Expected true but got ${show(args[0])}` : String(args[1])), - ) - methods(builtins, assert, [ - [ - "sameValue", - 3, - (_, args) => - Object.is(args[0], args[1]) - ? undefined - : fail(`${prefix(args[2])}Expected SameValue(«${show(args[0])}», «${show(args[1])}») to be true`), - ], - [ - "notSameValue", - 3, - (_, args) => - Object.is(args[0], args[1]) - ? fail(`${prefix(args[2])}Expected SameValue(«${show(args[0])}», «${show(args[1])}») to be false`) - : undefined, - ], - [ - "compareArray", - 3, - (_, args) => - compare(args[0], args[1]) - ? undefined - : fail( - `Actual ${show(args[0])} and expected ${show(args[1])} should have the same contents. ${prefix(args[2])}`, - ), - ], - [ - "notThrown", - 2, - (_, args) => - fail(`${prefix(args[1])}Expected a ${expectedName(args[0])} to be thrown but no exception was thrown at all`), - ], - [ - "thrown", - 3, - (_, args) => { - if (!(args[2] instanceof Obj)) return fail(`${prefix(args[1])}Thrown value was not an object!`) - const actual = get(args[2], "constructor") - return actual === args[0] - ? undefined - : fail(`${prefix(args[1])}Expected a ${expectedName(args[0])} but got a ${show(actual)}`) - }, - ], - ]) - return [ - ["$assert", assert], - ["compareArray", compareArray], - ["Test262Error", test262Error], - [ - "$DONE", - fn(builtins, "$DONE", 1, (_, args) => { - onDone(args[0]) - return undefined - }), - ], - [ - "$DONOTEVALUATE", - fn(builtins, "$DONOTEVALUATE", 0, () => { - throw new Throw("Test262: This statement should not be evaluated.") - }), - ], - ] -} - -const show = (value: unknown): string => { - if (typeof value === "string") return JSON.stringify(value) - if (Object.is(value, -0)) return "-0" - if (value instanceof Arr) return `[${value.items.map(show).join(", ")}]` - if (value instanceof Fn) return "program function" - if (value instanceof Callable) return String(get(value, "name")) - if (!(value instanceof Obj)) return String(value) - const message = get(value, "message") - return typeof message === "string" ? `${String(get(value, "name") ?? "object")}: ${message}` : "object" -} diff --git a/packages/codemode/test/test262/skipped.txt b/packages/codemode/test/test262/skipped.txt deleted file mode 100644 index c88f580d829..00000000000 --- a/packages/codemode/test/test262/skipped.txt +++ /dev/null @@ -1,2845 +0,0 @@ -built-ins/AggregateError/message-undefined-no-prop.js # explicit Expected SameValue(«true», «false») to be true -built-ins/Array/S15.4.5.2_A3_T3.js # RangeError: Invalid array length -built-ins/Array/from/Array.from_forwards-length-for-array-likes.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Array/from/elements-deleted-after.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Array/from/iter-cstm-ctor-err.js # Array.from.call(C, items) throws a Test262Error exception Expected a Test262Error but got a TypeErro -built-ins/Array/from/iter-cstm-ctor.js # TypeError: The right-hand side of '…' has no '…' object. -built-ins/Array/from/iter-set-elem-prop-err.js # Array.from.call(constructorSetsIndex0ConfigurableFalse, items) throws a TypeError exception Expected -built-ins/Array/from/iter-set-length-err.js # TypeError: Object.defineProperty called on non-object -built-ins/Array/from/source-array-boundary.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Array/from/source-object-constructor.js # The value of Array.from.call(Object, []).constructor is expected to equal the value of Object Expect -built-ins/Array/from/source-object-length-set-elem-prop-err.js # Array.from.call(A1, items) throws a TypeError exception Expected a TypeError to be thrown but no exc -built-ins/Array/isArray/15.4.3.2-2-1.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/isArray/15.4.3.2-2-2.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/length/15.4.5.1-3.d-3.js # RangeError: Invalid array length -built-ins/Array/length/S15.4.2.2_A2.1_T1.js # RangeError: Invalid array length. -built-ins/Array/length/S15.4.5.1_A1.3_T2.js # RangeError: Invalid array length -built-ins/Array/length/define-own-prop-length-error.js # Expected a RangeError but got a TypeError -built-ins/Array/length/define-own-prop-length-overflow-order.js # Object.defineProperty([], "length", {value: -1, configurable: true}) throws a RangeError exception E -built-ins/Array/of/construct-this-with-the-number-of-arguments.js # The value of len is expected to be 0 Expected SameValue(«undefined», «0») to be true -built-ins/Array/of/does-not-use-prototype-properties.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/of/return-a-custom-instance.js # TypeError: The right-hand side of '…' has no '…' object. -built-ins/Array/of/return-abrupt-from-contructor.js # Array.of.call(T) throws a Test262Error exception Expected a Test262Error to be thrown but no excepti -built-ins/Array/of/return-abrupt-from-data-property.js # Array.of.call(T1, "Bob") throws a TypeError exception Expected a TypeError to be thrown but no excep -built-ins/Array/of/return-abrupt-from-setting-length.js # Array.of.call(T) throws a Test262Error exception Expected a Test262Error to be thrown but no excepti -built-ins/Array/of/sets-length.js # The value of hits is expected to be 1 Expected SameValue(«0», «1») to be true -built-ins/Array/prototype/at/index-argument-tointeger.js # a.at({valueOf() {valueOfCallCount++; return 1;}}) must return 1 Expected SameValue(«0», «1») to be t -built-ins/Array/prototype/concat/Array.prototype.concat_non-array.js # TypeError: Array.prototype.concat called on incompatible receiver a data object. -built-ins/Array/prototype/concat/S15.4.4.4_A2_T1.js # TypeError: Array.prototype.concat called on incompatible receiver a data object. -built-ins/Array/prototype/concat/S15.4.4.4_A2_T2.js # TypeError: Array.prototype.concat called on incompatible receiver a data object. -built-ins/Array/prototype/concat/S15.4.4.4_A3_T1.js # arr.hasOwnProperty("1") must return true Expected SameValue(«false», «true») to be true -built-ins/Array/prototype/concat/S15.4.4.4_A3_T2.js # b.hasOwnProperty("2") must return true Expected SameValue(«false», «true») to be true -built-ins/Array/prototype/concat/S15.4.4.4_A3_T3.js # b.hasOwnProperty("2") must return true Expected SameValue(«false», «true») to be true -built-ins/Array/prototype/concat/call-with-boolean.js # TypeError: Array.prototype.concat called on incompatible receiver a boolean. -built-ins/Array/prototype/concat/create-ctor-non-object.js # a.concat() throws a TypeError exception Expected a TypeError to be thrown but no exception was throw -built-ins/Array/prototype/concat/create-ctor-poisoned.js # a.concat() throws a Test262Error exception Expected a Test262Error to be thrown but no exception was -built-ins/Array/prototype/concat/create-non-array.js # TypeError: Array.prototype.concat called on incompatible receiver a data object. -built-ins/Array/prototype/copyWithin/call-with-boolean.js # TypeError: Array.prototype.copyWithin called on incompatible receiver a boolean. -built-ins/Array/prototype/copyWithin/coerced-values-start-change-target.js # Actual [0, 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 -built-ins/Array/prototype/copyWithin/length-near-integer-limit.js # TypeError: Array.prototype.copyWithin called on incompatible receiver a data object. -built-ins/Array/prototype/copyWithin/return-abrupt-from-end.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Array/prototype/copyWithin/return-abrupt-from-get-start-value.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/copyWithin/return-abrupt-from-set-target-value.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/copyWithin/return-abrupt-from-start.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Array/prototype/copyWithin/return-abrupt-from-target.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Array/prototype/copyWithin/return-abrupt-from-this-length.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/copyWithin/return-this.js # TypeError: Array.prototype.copyWithin called on incompatible receiver a data object. -built-ins/Array/prototype/entries/returns-iterator-from-object.js # TypeError: Array.prototype.entries called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-1-10.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-1-11.js # TypeError: Array.prototype.every called on incompatible receiver a Date. -built-ins/Array/prototype/every/15.4.4.16-1-12.js # TypeError: Array.prototype.every called on incompatible receiver a RegExp. -built-ins/Array/prototype/every/15.4.4.16-1-13.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-1-14.js # TypeError: Array.prototype.every called on incompatible receiver an Error. -built-ins/Array/prototype/every/15.4.4.16-1-15.js # TypeError: Array.prototype.every called on incompatible receiver an Arguments. -built-ins/Array/prototype/every/15.4.4.16-1-3.js # TypeError: Array.prototype.every called on incompatible receiver a boolean. -built-ins/Array/prototype/every/15.4.4.16-1-5.js # TypeError: Array.prototype.every called on incompatible receiver a number. -built-ins/Array/prototype/every/15.4.4.16-1-7.js # TypeError: Array.prototype.every called on incompatible receiver a string. -built-ins/Array/prototype/every/15.4.4.16-2-1.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-2-10.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-2-11.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-2-12.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-2-13.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-2-14.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-2-17.js # TypeError: Array.prototype.every called on incompatible receiver an Arguments. -built-ins/Array/prototype/every/15.4.4.16-2-19.js # TypeError: Array.prototype.every called on incompatible receiver a function. -built-ins/Array/prototype/every/15.4.4.16-2-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-2-5.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-2-6.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-2-7.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-2-8.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-2-9.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-3-1.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-10.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-11.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-12.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-13.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-14.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-15.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-16.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-17.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-18.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-19.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-2.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-20.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-21.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-22.js # toStringAccessed !== true -built-ins/Array/prototype/every/15.4.4.16-3-23.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-3-24.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-25.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-29.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-3.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-4.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-5.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-6.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-7.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-8.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-3-9.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-4-10.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/every/15.4.4.16-4-11.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/every/15.4.4.16-4-15.js # lengthAccessed !== true -built-ins/Array/prototype/every/15.4.4.16-4-8.js # accessed !== true -built-ins/Array/prototype/every/15.4.4.16-4-9.js # accessed !== true -built-ins/Array/prototype/every/15.4.4.16-5-4.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Array/prototype/every/15.4.4.16-5-5.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-7-6.js # res Expected SameValue(«true», «false») to be true -built-ins/Array/prototype/every/15.4.4.16-7-8.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-9.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-b-10.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-b-11.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/every/15.4.4.16-7-b-12.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-b-13.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/every/15.4.4.16-7-b-14.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/every/15.4.4.16-7-b-15.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/every/15.4.4.16-7-b-2.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-b-3.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-b-4.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-b-5.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/every/15.4.4.16-7-b-6.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-b-7.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/every/15.4.4.16-7-b-8.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-b-9.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/every/15.4.4.16-7-c-i-1.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-c-i-10.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/every/15.4.4.16-7-c-i-11.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-7-c-i-12.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/every/15.4.4.16-7-c-i-13.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-7-c-i-14.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/every/15.4.4.16-7-c-i-15.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-7-c-i-16.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/every/15.4.4.16-7-c-i-17.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-c-i-18.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/every/15.4.4.16-7-c-i-19.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-c-i-20.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/every/15.4.4.16-7-c-i-21.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-7-c-i-22.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/every/15.4.4.16-7-c-i-25.js # TypeError: Array.prototype.every called on incompatible receiver an Arguments. -built-ins/Array/prototype/every/15.4.4.16-7-c-i-26.js # TypeError: Array.prototype.every called on incompatible receiver an Arguments. -built-ins/Array/prototype/every/15.4.4.16-7-c-i-27.js # TypeError: Array.prototype.every called on incompatible receiver an Arguments. -built-ins/Array/prototype/every/15.4.4.16-7-c-i-28.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/every/15.4.4.16-7-c-i-29.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-c-i-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-7-c-i-30.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/every/15.4.4.16-7-c-i-31.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/every/15.4.4.16-7-c-i-5.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-7-c-i-6.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/every/15.4.4.16-7-c-i-7.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-7-c-i-8.js # [, , , ].every(callbackfn) Expected SameValue(«true», «false») to be true -built-ins/Array/prototype/every/15.4.4.16-7-c-i-9.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-c-ii-16.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-c-ii-17.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-c-ii-18.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-c-ii-19.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-c-ii-20.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-c-ii-21.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-c-ii-22.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-c-ii-23.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-c-ii-6.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-c-ii-7.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/every/15.4.4.16-7-c-ii-8.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-c-iii-1.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-c-iii-2.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-c-iii-27.js # [11].every(callbackfn) !== true -built-ins/Array/prototype/every/15.4.4.16-7-c-iii-28.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-c-iii-3.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-7-c-iii-4.js # TypeError: Array.prototype.every called on incompatible receiver a data object. -built-ins/Array/prototype/every/15.4.4.16-8-10.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-8-2.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-8-3.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-8-4.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-8-5.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-8-6.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-8-7.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/15.4.4.16-8-8.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/every/call-with-boolean.js # TypeError: Array.prototype.every called on incompatible receiver a boolean. -built-ins/Array/prototype/fill/call-with-boolean.js # TypeError: Array.prototype.fill called on incompatible receiver a boolean. -built-ins/Array/prototype/fill/length-near-integer-limit.js # TypeError: Array.prototype.fill called on incompatible receiver a data object. -built-ins/Array/prototype/fill/return-abrupt-from-end.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Array/prototype/fill/return-abrupt-from-setting-property-value.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/fill/return-abrupt-from-start.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Array/prototype/fill/return-abrupt-from-this-length.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/fill/return-this.js # TypeError: Array.prototype.fill called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-1-10.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-1-11.js # TypeError: Array.prototype.filter called on incompatible receiver a Date. -built-ins/Array/prototype/filter/15.4.4.20-1-12.js # TypeError: Array.prototype.filter called on incompatible receiver a RegExp. -built-ins/Array/prototype/filter/15.4.4.20-1-13.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-1-14.js # TypeError: Array.prototype.filter called on incompatible receiver an Error. -built-ins/Array/prototype/filter/15.4.4.20-1-15.js # TypeError: Array.prototype.filter called on incompatible receiver an Arguments. -built-ins/Array/prototype/filter/15.4.4.20-1-3.js # TypeError: Array.prototype.filter called on incompatible receiver a boolean. -built-ins/Array/prototype/filter/15.4.4.20-1-5.js # TypeError: Array.prototype.filter called on incompatible receiver a number. -built-ins/Array/prototype/filter/15.4.4.20-1-7.js # TypeError: Array.prototype.filter called on incompatible receiver a string. -built-ins/Array/prototype/filter/15.4.4.20-10-3.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-2-1.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-2-10.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-2-11.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-2-12.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-2-13.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-2-14.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-2-17.js # TypeError: Array.prototype.filter called on incompatible receiver an Arguments. -built-ins/Array/prototype/filter/15.4.4.20-2-19.js # TypeError: Array.prototype.filter called on incompatible receiver a function. -built-ins/Array/prototype/filter/15.4.4.20-2-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-2-5.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-2-6.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-2-7.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-2-8.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-2-9.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-3-1.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-3-10.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-3-11.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-3-12.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-3-13.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-3-14.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-3-15.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-3-16.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-3-17.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-3-18.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-3-19.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-3-2.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-3-20.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-3-21.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-3-22.js # firstStepOccured !== true -built-ins/Array/prototype/filter/15.4.4.20-3-23.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-3-24.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-3-25.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-3-3.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-3-4.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-3-5.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-3-6.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-3-7.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-3-9.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-4-10.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/filter/15.4.4.20-4-11.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/filter/15.4.4.20-4-15.js # lengthAccessed !== true -built-ins/Array/prototype/filter/15.4.4.20-4-8.js # accessed !== true -built-ins/Array/prototype/filter/15.4.4.20-4-9.js # accessed !== true -built-ins/Array/prototype/filter/15.4.4.20-5-4.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Array/prototype/filter/15.4.4.20-5-5.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-6-2.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-6-3.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-6-4.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-6-5.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-6-6.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-6-7.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-6-8.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-9-6.js # resArr.length Expected SameValue(«3», «4») to be true -built-ins/Array/prototype/filter/15.4.4.20-9-8.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-9.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-b-10.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-b-11.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/filter/15.4.4.20-9-b-12.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-b-13.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/filter/15.4.4.20-9-b-14.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/filter/15.4.4.20-9-b-15.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/filter/15.4.4.20-9-b-2.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-b-3.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-b-4.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-b-5.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/filter/15.4.4.20-9-b-6.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-b-7.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/filter/15.4.4.20-9-b-8.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-b-9.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-1.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-10.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-11.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-12.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-13.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-14.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-15.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-16.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-17.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-18.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-19.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-20.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-21.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-22.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-25.js # TypeError: Array.prototype.filter called on incompatible receiver an Arguments. -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-26.js # TypeError: Array.prototype.filter called on incompatible receiver an Arguments. -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-27.js # TypeError: Array.prototype.filter called on incompatible receiver an Arguments. -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-28.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-29.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-30.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-31.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-5.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-6.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-7.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-8.js # newArr.length Expected SameValue(«0», «1») to be true -built-ins/Array/prototype/filter/15.4.4.20-9-c-i-9.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-ii-16.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-ii-17.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-ii-18.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-ii-19.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-ii-20.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-ii-21.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-ii-22.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-ii-23.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-ii-6.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-ii-7.js # Expected a Error but got a TypeError -built-ins/Array/prototype/filter/15.4.4.20-9-c-ii-8.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-iii-1-1.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-iii-1-2.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-iii-1-3.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-iii-1-4.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-iii-2.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-iii-28.js # newArr.length Expected SameValue(«0», «1») to be true -built-ins/Array/prototype/filter/15.4.4.20-9-c-iii-29.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-iii-3.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-iii-4.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/15.4.4.20-9-c-iii-5.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/filter/call-with-boolean.js # TypeError: Array.prototype.filter called on incompatible receiver a boolean. -built-ins/Array/prototype/filter/create-ctor-non-object.js # null value Expected a TypeError to be thrown but no exception was thrown at all -built-ins/Array/prototype/filter/create-ctor-poisoned.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Array/prototype/filter/create-non-array.js # TypeError: Array.prototype.filter called on incompatible receiver a data object. -built-ins/Array/prototype/find/call-with-boolean.js # TypeError: Array.prototype.find called on incompatible receiver a boolean. -built-ins/Array/prototype/find/return-abrupt-from-property.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/find/return-abrupt-from-this-length.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/findIndex/call-with-boolean.js # TypeError: Array.prototype.findIndex called on incompatible receiver a boolean. -built-ins/Array/prototype/findIndex/return-abrupt-from-property.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/findIndex/return-abrupt-from-this-length.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/findLast/call-with-boolean.js # TypeError: Array.prototype.findLast called on incompatible receiver a boolean. -built-ins/Array/prototype/findLast/maximum-index.js # TypeError: Array.prototype.findLast called on incompatible receiver a data object. -built-ins/Array/prototype/findLast/return-abrupt-from-property.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/findLast/return-abrupt-from-this-length.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/findLastIndex/call-with-boolean.js # TypeError: Array.prototype.findLastIndex called on incompatible receiver a boolean. -built-ins/Array/prototype/findLastIndex/maximum-index.js # TypeError: Array.prototype.findLastIndex called on incompatible receiver a data object. -built-ins/Array/prototype/findLastIndex/return-abrupt-from-property.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/findLastIndex/return-abrupt-from-this-length.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/flat/array-like-objects.js # TypeError: Array.prototype.flat called on incompatible receiver an Arguments. -built-ins/Array/prototype/flat/call-with-boolean.js # TypeError: Array.prototype.flat called on incompatible receiver a boolean. -built-ins/Array/prototype/flat/non-object-ctor-throws.js # null value Expected a TypeError to be thrown but no exception was thrown at all -built-ins/Array/prototype/flatMap/array-like-objects.js # TypeError: Array.prototype.flatMap called on incompatible receiver a data object. -built-ins/Array/prototype/flatMap/call-with-boolean.js # TypeError: Array.prototype.flatMap called on incompatible receiver a boolean. -built-ins/Array/prototype/forEach/15.4.4.18-1-10.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-1-11.js # TypeError: Array.prototype.forEach called on incompatible receiver a Date. -built-ins/Array/prototype/forEach/15.4.4.18-1-12.js # TypeError: Array.prototype.forEach called on incompatible receiver a RegExp. -built-ins/Array/prototype/forEach/15.4.4.18-1-13.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-1-14.js # TypeError: Array.prototype.forEach called on incompatible receiver an Error. -built-ins/Array/prototype/forEach/15.4.4.18-1-15.js # TypeError: Array.prototype.forEach called on incompatible receiver an Arguments. -built-ins/Array/prototype/forEach/15.4.4.18-1-3.js # TypeError: Array.prototype.forEach called on incompatible receiver a boolean. -built-ins/Array/prototype/forEach/15.4.4.18-1-5.js # TypeError: Array.prototype.forEach called on incompatible receiver a number. -built-ins/Array/prototype/forEach/15.4.4.18-1-7.js # TypeError: Array.prototype.forEach called on incompatible receiver a string. -built-ins/Array/prototype/forEach/15.4.4.18-2-1.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-2-10.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-2-11.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-2-12.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-2-13.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-2-14.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-2-17.js # TypeError: Array.prototype.forEach called on incompatible receiver an Arguments. -built-ins/Array/prototype/forEach/15.4.4.18-2-19.js # TypeError: Array.prototype.forEach called on incompatible receiver a function. -built-ins/Array/prototype/forEach/15.4.4.18-2-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-2-5.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-2-6.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-2-7.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-2-8.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-2-9.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-3-1.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-3-10.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-3-11.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-3-12.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-3-13.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-3-14.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-3-15.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-3-16.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-3-17.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-3-18.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-3-19.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-3-2.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-3-20.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-3-21.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-3-23.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-3-24.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-3-25.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-3-3.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-3-4.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-3-5.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-3-6.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-3-7.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-3-9.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-4-10.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/forEach/15.4.4.18-4-11.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/forEach/15.4.4.18-4-15.js # lengthAccessed !== true -built-ins/Array/prototype/forEach/15.4.4.18-4-8.js # accessed !== true -built-ins/Array/prototype/forEach/15.4.4.18-4-9.js # accessed !== true -built-ins/Array/prototype/forEach/15.4.4.18-5-4.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Array/prototype/forEach/15.4.4.18-5-5.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-7-5.js # callCnt Expected SameValue(«4», «5») to be true -built-ins/Array/prototype/forEach/15.4.4.18-7-8.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-9.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-b-10.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-b-11.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/forEach/15.4.4.18-7-b-12.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-b-13.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/forEach/15.4.4.18-7-b-14.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/forEach/15.4.4.18-7-b-15.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/forEach/15.4.4.18-7-b-2.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-b-3.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-b-4.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-b-5.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/forEach/15.4.4.18-7-b-6.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-b-7.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/forEach/15.4.4.18-7-b-8.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-b-9.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-1.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-10.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-11.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-12.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-13.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-14.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-15.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-16.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-17.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-18.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-19.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-20.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-21.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-22.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-25.js # TypeError: Array.prototype.forEach called on incompatible receiver an Arguments. -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-26.js # TypeError: Array.prototype.forEach called on incompatible receiver an Arguments. -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-27.js # TypeError: Array.prototype.forEach called on incompatible receiver an Arguments. -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-28.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-29.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-30.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-31.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-5.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-6.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-7.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-8.js # testResult !== true -built-ins/Array/prototype/forEach/15.4.4.18-7-c-i-9.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-c-ii-16.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-c-ii-17.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-c-ii-18.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-c-ii-19.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-c-ii-20.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-c-ii-21.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-c-ii-22.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-c-ii-23.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-c-ii-6.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-7-c-ii-7.js # Expected a Error but got a TypeError -built-ins/Array/prototype/forEach/15.4.4.18-7-c-ii-8.js # TypeError: Array.prototype.forEach called on incompatible receiver a data object. -built-ins/Array/prototype/forEach/15.4.4.18-8-10.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-8-2.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-8-3.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-8-4.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-8-5.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-8-6.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-8-7.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-8-8.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/15.4.4.18-8-9.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/forEach/call-with-boolean.js # TypeError: Array.prototype.forEach called on incompatible receiver a boolean. -built-ins/Array/prototype/includes/call-with-boolean.js # TypeError: Array.prototype.includes called on incompatible receiver a boolean. -built-ins/Array/prototype/includes/length-boundaries.js # TypeError: Array.prototype.includes called on incompatible receiver a data object. -built-ins/Array/prototype/includes/return-abrupt-get-length.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/includes/return-abrupt-get-prop.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/includes/return-abrupt-tointeger-fromindex.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Array/prototype/includes/return-abrupt-tonumber-length.js # valueOf Expected a Test262Error but got a TypeError -built-ins/Array/prototype/includes/tointeger-fromindex.js # object [0] Expected SameValue(«true», «false») to be true -built-ins/Array/prototype/includes/tolength-length.js # TypeError: Array.prototype.includes called on incompatible receiver a data object. -built-ins/Array/prototype/includes/values-are-not-cached.js # TypeError: Array.prototype.includes called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-1-10.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-1-11.js # TypeError: Array.prototype.indexOf called on incompatible receiver a Date. -built-ins/Array/prototype/indexOf/15.4.4.14-1-12.js # TypeError: Array.prototype.indexOf called on incompatible receiver a RegExp. -built-ins/Array/prototype/indexOf/15.4.4.14-1-13.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-1-14.js # TypeError: Array.prototype.indexOf called on incompatible receiver an Error. -built-ins/Array/prototype/indexOf/15.4.4.14-1-15.js # TypeError: Array.prototype.indexOf called on incompatible receiver an Arguments. -built-ins/Array/prototype/indexOf/15.4.4.14-1-3.js # TypeError: Array.prototype.indexOf called on incompatible receiver a boolean. -built-ins/Array/prototype/indexOf/15.4.4.14-1-5.js # TypeError: Array.prototype.indexOf called on incompatible receiver a number. -built-ins/Array/prototype/indexOf/15.4.4.14-1-7.js # TypeError: Array.prototype.indexOf called on incompatible receiver a string. -built-ins/Array/prototype/indexOf/15.4.4.14-1-9.js # TypeError: Array.prototype.indexOf called on incompatible receiver a function. -built-ins/Array/prototype/indexOf/15.4.4.14-10-2.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-2-1.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-2-10.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/indexOf/15.4.4.14-2-11.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-2-12.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-2-13.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/indexOf/15.4.4.14-2-14.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-2-17.js # TypeError: Array.prototype.indexOf called on incompatible receiver an Arguments. -built-ins/Array/prototype/indexOf/15.4.4.14-2-19.js # TypeError: Array.prototype.indexOf called on incompatible receiver a function. -built-ins/Array/prototype/indexOf/15.4.4.14-2-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/indexOf/15.4.4.14-2-5.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/indexOf/15.4.4.14-2-6.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/indexOf/15.4.4.14-2-7.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-2-8.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/indexOf/15.4.4.14-2-9.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/indexOf/15.4.4.14-3-1.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-10.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-11.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-12.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-13.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-14.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-15.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-16.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-17.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-18.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-19.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-2.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-20.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-21.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-22.js # toStringAccessed -built-ins/Array/prototype/indexOf/15.4.4.14-3-23.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/indexOf/15.4.4.14-3-24.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-25.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-28.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-29.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-3.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-4.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-5.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-6.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-7.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-8.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-3-9.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-4-10.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-4-11.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-4-2.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-4-3.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-4-4.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-4-5.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-4-6.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-4-7.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-4-8.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-4-9.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-5-23.js # toStringAccessed !== true -built-ins/Array/prototype/indexOf/15.4.4.14-5-24.js # Expected a TypeError to be thrown but no exception was thrown at all -built-ins/Array/prototype/indexOf/15.4.4.14-5-25.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/indexOf/15.4.4.14-5-26.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-5-27.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-5-29.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/indexOf/15.4.4.14-9-11.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/indexOf/15.4.4.14-9-7.js # TypeError: Array assignment result contains a circular value. -built-ins/Array/prototype/indexOf/15.4.4.14-9-a-1.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-9-a-10.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/indexOf/15.4.4.14-9-a-11.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-9-a-12.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/indexOf/15.4.4.14-9-a-13.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-9-a-14.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/indexOf/15.4.4.14-9-a-15.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-9-a-16.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/indexOf/15.4.4.14-9-a-17.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/indexOf/15.4.4.14-9-a-18.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/indexOf/15.4.4.14-9-a-2.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-9-a-3.js # arr.indexOf(targetObj, fromIndex) Expected SameValue(«-1», «4») to be true -built-ins/Array/prototype/indexOf/15.4.4.14-9-a-4.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-9-a-5.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-9-a-6.js # arr.indexOf("10", fromIndex) Expected SameValue(«10», «-1») to be true -built-ins/Array/prototype/indexOf/15.4.4.14-9-a-7.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-9-a-8.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/indexOf/15.4.4.14-9-a-9.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-1.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-10.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-11.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-12.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-13.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-14.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-15.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-16.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-17.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-18.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-19.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-20.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-21.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-22.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-25.js # TypeError: Array.prototype.indexOf called on incompatible receiver an Arguments. -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-26.js # TypeError: Array.prototype.indexOf called on incompatible receiver an Arguments. -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-27.js # TypeError: Array.prototype.indexOf called on incompatible receiver an Arguments. -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-28.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-29.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-30.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-4.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-5.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-6.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-7.js # [, , , ].indexOf(true) Expected SameValue(«-1», «0») to be true -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-8.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-i-9.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/indexOf/15.4.4.14-9-b-iii-2.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/indexOf/call-with-boolean.js # TypeError: Array.prototype.indexOf called on incompatible receiver a boolean. -built-ins/Array/prototype/indexOf/length-near-integer-limit.js # TypeError: Array.prototype.indexOf called on incompatible receiver a data object. -built-ins/Array/prototype/join/S15.4.4.5_A2_T1.js # TypeError: Array.prototype.join called on incompatible receiver a data object. -built-ins/Array/prototype/join/S15.4.4.5_A2_T4.js # TypeError: Array.prototype.join called on incompatible receiver a data object. -built-ins/Array/prototype/join/S15.4.4.5_A4_T3.js # TypeError: Array.prototype.join called on incompatible receiver a data object. -built-ins/Array/prototype/join/S15.4.4.5_A5_T1.js # #1: Array.prototype[1] = 1; x = [0]; x.length = 2; x.join() === "0,1". Actual: 0, -built-ins/Array/prototype/join/call-with-boolean.js # TypeError: Array.prototype.join called on incompatible receiver a boolean. -built-ins/Array/prototype/keys/returns-iterator-from-object.js # TypeError: Array.prototype.keys called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-1-10.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-1-11.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a Date. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-1-12.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a RegExp. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-1-13.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-1-14.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver an Error. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-1-15.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver an Arguments. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-1-3.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a boolean. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-1-5.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a number. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-1-7.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a string. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-1-9.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a function. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-2-1.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-2-10.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/lastIndexOf/15.4.4.15-2-11.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-2-12.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-2-13.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/lastIndexOf/15.4.4.15-2-14.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-2-17.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver an Arguments. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-2-19.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a function. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-2-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/lastIndexOf/15.4.4.15-2-5.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/lastIndexOf/15.4.4.15-2-6.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/lastIndexOf/15.4.4.15-2-7.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-2-9.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-1.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-10.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-11.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-12.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-13.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-14.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-15.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-16.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-17.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-19.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-2.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-20.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-21.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-22.js # toStringAccessed -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-23.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-24.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-25.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-28.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-3.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-4.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-5.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-6.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-7.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-3-9.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-4-10.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-4-11.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-4-2.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-4-3.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-4-4.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/lastIndexOf/15.4.4.15-4-5.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-4-6.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-4-7.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/lastIndexOf/15.4.4.15-4-8.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-4-9.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-5-21.js # [0, true, targetObj, 3, false].lastIndexOf(targetObj, fromIndex) Expected SameValue(«-1», «2») to be -built-ins/Array/prototype/lastIndexOf/15.4.4.15-5-22.js # [0, true, targetObj, 3, false].lastIndexOf(targetObj, fromIndex) Expected SameValue(«-1», «2») to be -built-ins/Array/prototype/lastIndexOf/15.4.4.15-5-23.js # [0, true].lastIndexOf(true, fromIndex) Expected SameValue(«-1», «1») to be true -built-ins/Array/prototype/lastIndexOf/15.4.4.15-5-24.js # Expected a TypeError to be thrown but no exception was thrown at all -built-ins/Array/prototype/lastIndexOf/15.4.4.15-5-25.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/lastIndexOf/15.4.4.15-5-26.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-5-27.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-5-29.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-11.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-7.js # TypeError: Array assignment result contains a circular value. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-a-1.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-a-10.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-a-11.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-a-12.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-a-13.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-a-14.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-a-15.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-a-16.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-a-17.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-a-18.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-a-2.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-a-3.js # arr.lastIndexOf(targetObj, fromIndex) Expected SameValue(«-1», «4») to be true -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-a-4.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-a-5.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-a-7.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-a-8.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-a-9.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-1.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-10.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-11.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-12.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-13.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-14.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-15.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-16.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-17.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-18.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-19.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-20.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-21.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-22.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-25.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver an Arguments. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-26.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver an Arguments. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-27.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver an Arguments. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-28.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-29.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-30.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-4.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-5.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-6.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-7.js # [, , , ].lastIndexOf(true) Expected SameValue(«-1», «0») to be true -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-8.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-i-9.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/lastIndexOf/15.4.4.15-8-b-iii-2.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/lastIndexOf/15.4.4.15-9-2.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/lastIndexOf/call-with-boolean.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a boolean. -built-ins/Array/prototype/lastIndexOf/length-near-integer-limit.js # TypeError: Array.prototype.lastIndexOf called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-1-10.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-1-11.js # TypeError: Array.prototype.map called on incompatible receiver a Date. -built-ins/Array/prototype/map/15.4.4.19-1-12.js # TypeError: Array.prototype.map called on incompatible receiver a RegExp. -built-ins/Array/prototype/map/15.4.4.19-1-13.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-1-14.js # TypeError: Array.prototype.map called on incompatible receiver an Error. -built-ins/Array/prototype/map/15.4.4.19-1-15.js # TypeError: Array.prototype.map called on incompatible receiver an Arguments. -built-ins/Array/prototype/map/15.4.4.19-1-3.js # TypeError: Array.prototype.map called on incompatible receiver a boolean. -built-ins/Array/prototype/map/15.4.4.19-1-5.js # TypeError: Array.prototype.map called on incompatible receiver a number. -built-ins/Array/prototype/map/15.4.4.19-1-7.js # TypeError: Array.prototype.map called on incompatible receiver a string. -built-ins/Array/prototype/map/15.4.4.19-2-1.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-2-10.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-2-11.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-2-12.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-2-13.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-2-14.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-2-17.js # TypeError: Array.prototype.map called on incompatible receiver an Arguments. -built-ins/Array/prototype/map/15.4.4.19-2-19.js # TypeError: Array.prototype.map called on incompatible receiver a function. -built-ins/Array/prototype/map/15.4.4.19-2-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-2-5.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-2-6.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-2-7.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-2-8.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-2-9.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-3-1.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-3-10.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-3-11.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-3-12.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-3-13.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-3-14.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/map/15.4.4.19-3-15.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-3-16.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-3-17.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-3-18.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-3-19.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-3-2.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-3-20.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-3-21.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-3-23.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-3-24.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-3-25.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-3-28.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/map/15.4.4.19-3-29.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/map/15.4.4.19-3-3.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-3-4.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-3-5.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-3-6.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-3-7.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-3-8.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/map/15.4.4.19-3-9.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-4-10.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/map/15.4.4.19-4-11.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/map/15.4.4.19-4-15.js # lengthAccessed !== true -built-ins/Array/prototype/map/15.4.4.19-4-8.js # accessed !== true -built-ins/Array/prototype/map/15.4.4.19-4-9.js # accessed !== true -built-ins/Array/prototype/map/15.4.4.19-5-4.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Array/prototype/map/15.4.4.19-5-5.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-8-6.js # resArr[4] Expected SameValue(«undefined», «1») to be true -built-ins/Array/prototype/map/15.4.4.19-8-8.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-9.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/map/15.4.4.19-8-b-10.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-b-11.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/map/15.4.4.19-8-b-12.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-b-13.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/map/15.4.4.19-8-b-14.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/map/15.4.4.19-8-b-15.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/map/15.4.4.19-8-b-2.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-b-3.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-b-4.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-b-5.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/map/15.4.4.19-8-b-6.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-b-7.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/map/15.4.4.19-8-b-8.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-b-9.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/map/15.4.4.19-8-c-i-1.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-c-i-10.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/map/15.4.4.19-8-c-i-11.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-8-c-i-12.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/map/15.4.4.19-8-c-i-13.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-8-c-i-14.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/map/15.4.4.19-8-c-i-15.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-8-c-i-16.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/map/15.4.4.19-8-c-i-17.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-c-i-18.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/map/15.4.4.19-8-c-i-19.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/map/15.4.4.19-8-c-i-20.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-8-c-i-21.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-8-c-i-22.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/map/15.4.4.19-8-c-i-25.js # TypeError: Array.prototype.map called on incompatible receiver an Arguments. -built-ins/Array/prototype/map/15.4.4.19-8-c-i-26.js # TypeError: Array.prototype.map called on incompatible receiver an Arguments. -built-ins/Array/prototype/map/15.4.4.19-8-c-i-27.js # TypeError: Array.prototype.map called on incompatible receiver an Arguments. -built-ins/Array/prototype/map/15.4.4.19-8-c-i-28.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/map/15.4.4.19-8-c-i-29.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-c-i-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-8-c-i-30.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/map/15.4.4.19-8-c-i-31.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/map/15.4.4.19-8-c-i-5.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-8-c-i-6.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/map/15.4.4.19-8-c-i-7.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-8-c-i-8.js # newArr[1] Expected SameValue(«13», «true») to be true -built-ins/Array/prototype/map/15.4.4.19-8-c-i-9.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-c-ii-16.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-c-ii-17.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-c-ii-18.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-c-ii-19.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-c-ii-20.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-c-ii-21.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-c-ii-22.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-c-ii-23.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-c-ii-6.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-c-ii-7.js # Expected a Error but got a TypeError -built-ins/Array/prototype/map/15.4.4.19-8-c-ii-8.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-c-iii-2.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-c-iii-3.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-c-iii-4.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-8-c-iii-5.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-9-10.js # TypeError: Foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-9-11.js # TypeError: Foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-9-12.js # TypeError: Foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-9-3.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-9-5.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/map/15.4.4.19-9-6.js # TypeError: Foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-9-7.js # TypeError: Foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-9-8.js # TypeError: Foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/15.4.4.19-9-9.js # TypeError: Foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/map/call-with-boolean.js # TypeError: Array.prototype.map called on incompatible receiver a boolean. -built-ins/Array/prototype/map/create-ctor-non-object.js # null value Expected a TypeError to be thrown but no exception was thrown at all -built-ins/Array/prototype/map/create-ctor-poisoned.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Array/prototype/map/create-non-array-invalid-len.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/map/create-non-array.js # TypeError: Array.prototype.map called on incompatible receiver a data object. -built-ins/Array/prototype/pop/S15.4.4.6_A2_T1.js # TypeError: Array.prototype.pop called on incompatible receiver a data object. -built-ins/Array/prototype/pop/S15.4.4.6_A2_T4.js # TypeError: Array.prototype.pop called on incompatible receiver a data object. -built-ins/Array/prototype/pop/S15.4.4.6_A3_T1.js # TypeError: Array.prototype.pop called on incompatible receiver a data object. -built-ins/Array/prototype/pop/S15.4.4.6_A3_T2.js # TypeError: Array.prototype.pop called on incompatible receiver a data object. -built-ins/Array/prototype/pop/S15.4.4.6_A3_T3.js # TypeError: Array.prototype.pop called on incompatible receiver a data object. -built-ins/Array/prototype/pop/S15.4.4.6_A4_T1.js # #1: Array.prototype[1] = 1; x = [0]; x.length = 2; x.pop() === 1. Actual: undefined -built-ins/Array/prototype/pop/S15.4.4.6_A4_T2.js # TypeError: Array.prototype.pop called on incompatible receiver a data object. -built-ins/Array/prototype/pop/call-with-boolean.js # TypeError: Array.prototype.pop called on incompatible receiver a boolean. -built-ins/Array/prototype/pop/clamps-to-integer-limit.js # TypeError: Array.prototype.pop called on incompatible receiver a data object. -built-ins/Array/prototype/pop/length-near-integer-limit.js # TypeError: Array.prototype.pop called on incompatible receiver a data object. -built-ins/Array/prototype/pop/set-length-array-is-frozen.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/pop/set-length-array-length-is-non-writable.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/pop/set-length-zero-array-length-is-non-writable.js # TypeError: Making an array's length read-only is not supported; use Object.freeze. -built-ins/Array/prototype/push/S15.4.4.7_A2_T1.js # TypeError: Array.prototype.push called on incompatible receiver a data object. -built-ins/Array/prototype/push/S15.4.4.7_A2_T3.js # TypeError: Array.prototype.push called on incompatible receiver a data object. -built-ins/Array/prototype/push/S15.4.4.7_A3.js # RangeError: Invalid array length -built-ins/Array/prototype/push/S15.4.4.7_A4_T1.js # TypeError: Array.prototype.push called on incompatible receiver a data object. -built-ins/Array/prototype/push/S15.4.4.7_A4_T2.js # TypeError: Array.prototype.push called on incompatible receiver a data object. -built-ins/Array/prototype/push/S15.4.4.7_A4_T3.js # TypeError: Array.prototype.push called on incompatible receiver a data object. -built-ins/Array/prototype/push/S15.4.4.7_A5_T1.js # TypeError: Array.prototype.push called on incompatible receiver a data object. -built-ins/Array/prototype/push/call-with-boolean.js # TypeError: Array.prototype.push called on incompatible receiver a boolean. -built-ins/Array/prototype/push/clamps-to-integer-limit.js # TypeError: Array.prototype.push called on incompatible receiver a data object. -built-ins/Array/prototype/push/length-near-integer-limit-set-failure.js # Expected SameValue(«undefined», «1») to be true -built-ins/Array/prototype/push/length-near-integer-limit.js # TypeError: Array.prototype.push called on incompatible receiver a data object. -built-ins/Array/prototype/push/set-length-array-is-frozen.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/push/set-length-array-length-is-non-writable.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/push/set-length-zero-array-length-is-non-writable.js # TypeError: Making an array's length read-only is not supported; use Object.freeze. -built-ins/Array/prototype/reduce/15.4.4.21-1-10.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-1-11.js # TypeError: Array.prototype.reduce called on incompatible receiver a Date. -built-ins/Array/prototype/reduce/15.4.4.21-1-12.js # TypeError: Array.prototype.reduce called on incompatible receiver a RegExp. -built-ins/Array/prototype/reduce/15.4.4.21-1-13.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-1-14.js # TypeError: Array.prototype.reduce called on incompatible receiver an Error. -built-ins/Array/prototype/reduce/15.4.4.21-1-15.js # TypeError: Array.prototype.reduce called on incompatible receiver an Arguments. -built-ins/Array/prototype/reduce/15.4.4.21-1-3.js # TypeError: Array.prototype.reduce called on incompatible receiver a boolean. -built-ins/Array/prototype/reduce/15.4.4.21-1-5.js # TypeError: Array.prototype.reduce called on incompatible receiver a number. -built-ins/Array/prototype/reduce/15.4.4.21-1-7.js # TypeError: Array.prototype.reduce called on incompatible receiver a string. -built-ins/Array/prototype/reduce/15.4.4.21-10-3.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-10-4.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-10-6.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-10-7.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-2-1.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-2-10.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-2-11.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-2-12.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-2-13.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-2-14.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-2-17.js # TypeError: Array.prototype.reduce called on incompatible receiver an Arguments. -built-ins/Array/prototype/reduce/15.4.4.21-2-19.js # TypeError: Array.prototype.reduce called on incompatible receiver a function. -built-ins/Array/prototype/reduce/15.4.4.21-2-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-2-5.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-2-6.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-2-7.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-2-8.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-2-9.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-3-1.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-3-10.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-3-11.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-3-12.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-3-13.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-3-14.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-3-15.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-3-16.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-3-17.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-3-18.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-3-19.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-3-2.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-3-20.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-3-21.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-3-22.js # toStringAccessed !== true -built-ins/Array/prototype/reduce/15.4.4.21-3-23.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-3-24.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-3-25.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-3-3.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-3-4.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-3-5.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-3-6.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-3-7.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-3-9.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-4-10.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/reduce/15.4.4.21-4-11.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/reduce/15.4.4.21-4-15.js # lengthAccessed !== true -built-ins/Array/prototype/reduce/15.4.4.21-4-8.js # accessed !== true -built-ins/Array/prototype/reduce/15.4.4.21-4-9.js # accessed !== true -built-ins/Array/prototype/reduce/15.4.4.21-5-10.js # accessed !== true -built-ins/Array/prototype/reduce/15.4.4.21-5-11.js # accessed !== true -built-ins/Array/prototype/reduce/15.4.4.21-5-12.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/reduce/15.4.4.21-5-13.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/reduce/15.4.4.21-5-2.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-5-3.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-5-4.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-5-5.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-5-6.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-5-7.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-5-8.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-7-2.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-7-3.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-7-4.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-7-5.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-7-6.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-7-7.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-7-8.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-7-9.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-8-b-2.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-8-b-3.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-8-b-ii-1.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-8-b-ii-2.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-1.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-10.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-11.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-12.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-13.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-14.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-15.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-16.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-17.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-18.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-19.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-20.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-21.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-22.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-25.js # TypeError: Array.prototype.reduce called on incompatible receiver an Arguments. -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-26.js # TypeError: Array.prototype.reduce called on incompatible receiver an Arguments. -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-27.js # TypeError: Array.prototype.reduce called on incompatible receiver an Arguments. -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-29.js # TypeError: Array.prototype.reduce called on incompatible receiver a function. -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-30.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-31.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-32.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-33.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-5.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-6.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-7.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-8.js # TypeError: Array.reduce of an empty array with no initial value. -built-ins/Array/prototype/reduce/15.4.4.21-8-b-iii-1-9.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-8-c-4.js # TypeError: Array.reduce of an empty array with no initial value. -built-ins/Array/prototype/reduce/15.4.4.21-8-c-5.js # accessed !== true -built-ins/Array/prototype/reduce/15.4.4.21-8-c-6.js # accessed !== true -built-ins/Array/prototype/reduce/15.4.4.21-8-c-7.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/reduce/15.4.4.21-8-c-8.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/reduce/15.4.4.21-9-6.js # res Expected SameValue(«"123"», «"1235"») to be true -built-ins/Array/prototype/reduce/15.4.4.21-9-8.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-9.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-b-10.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-b-11.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-b-12.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-b-13.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-b-14.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-b-15.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-b-17.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-b-18.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-b-19.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-b-2.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-b-20.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-b-21.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-b-22.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-b-23.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-b-24.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-b-25.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-b-26.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-b-27.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-b-28.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-b-3.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-b-4.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-b-5.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-b-6.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-b-7.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-b-8.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-b-9.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-1.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-10.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-11.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-12.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-13.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-14.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-15.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-16.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-17.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-18.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-19.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-20.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-21.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-22.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-25.js # TypeError: Array.prototype.reduce called on incompatible receiver an Arguments. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-26.js # TypeError: Array.prototype.reduce called on incompatible receiver an Arguments. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-27.js # TypeError: Array.prototype.reduce called on incompatible receiver an Arguments. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-29.js # TypeError: Array.prototype.reduce called on incompatible receiver a function. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-30.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-31.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-32.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-33.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-5.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-6.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-7.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-8.js # testResult !== true -built-ins/Array/prototype/reduce/15.4.4.21-9-c-i-9.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-ii-16.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-ii-18.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-ii-20.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-ii-21.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-ii-22.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-ii-23.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-ii-24.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-ii-25.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-ii-26.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-ii-30.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-ii-31.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-ii-32.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-ii-33.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-ii-34.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-ii-35.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-ii-37.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/15.4.4.21-9-c-ii-7.js # Expected a Error but got a TypeError -built-ins/Array/prototype/reduce/15.4.4.21-9-c-ii-8.js # TypeError: Array.prototype.reduce called on incompatible receiver a data object. -built-ins/Array/prototype/reduce/call-with-boolean.js # TypeError: Array.prototype.reduce called on incompatible receiver a boolean. -built-ins/Array/prototype/reduceRight/15.4.4.22-1-10.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-1-11.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a Date. -built-ins/Array/prototype/reduceRight/15.4.4.22-1-12.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a RegExp. -built-ins/Array/prototype/reduceRight/15.4.4.22-1-13.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-1-14.js # TypeError: Array.prototype.reduceRight called on incompatible receiver an Error. -built-ins/Array/prototype/reduceRight/15.4.4.22-1-15.js # TypeError: Array.prototype.reduceRight called on incompatible receiver an Arguments. -built-ins/Array/prototype/reduceRight/15.4.4.22-1-3.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a boolean. -built-ins/Array/prototype/reduceRight/15.4.4.22-1-5.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a number. -built-ins/Array/prototype/reduceRight/15.4.4.22-1-7.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a string. -built-ins/Array/prototype/reduceRight/15.4.4.22-10-3.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-10-4.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-10-6.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-10-7.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-2-1.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-2-10.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-2-11.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-2-12.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-2-13.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-2-14.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-2-17.js # TypeError: Array.prototype.reduceRight called on incompatible receiver an Arguments. -built-ins/Array/prototype/reduceRight/15.4.4.22-2-19.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a function. -built-ins/Array/prototype/reduceRight/15.4.4.22-2-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-2-5.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-2-6.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-2-7.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-2-8.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-2-9.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-3-1.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-3-10.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-3-11.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-3-12.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-3-13.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-3-14.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-3-15.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-3-16.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-3-17.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-3-18.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-3-19.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-3-2.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-3-20.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-3-21.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-3-22.js # toStringAccessed !== true -built-ins/Array/prototype/reduceRight/15.4.4.22-3-23.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-3-24.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-3-25.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-3-3.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-3-4.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-3-5.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-3-6.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-3-7.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-3-9.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-4-10.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/reduceRight/15.4.4.22-4-11.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/reduceRight/15.4.4.22-4-15.js # lengthAccessed !== true -built-ins/Array/prototype/reduceRight/15.4.4.22-4-8.js # accessed !== true -built-ins/Array/prototype/reduceRight/15.4.4.22-4-9.js # accessed !== true -built-ins/Array/prototype/reduceRight/15.4.4.22-5-10.js # accessed !== true -built-ins/Array/prototype/reduceRight/15.4.4.22-5-11.js # accessed !== true -built-ins/Array/prototype/reduceRight/15.4.4.22-5-12.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/reduceRight/15.4.4.22-5-13.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/reduceRight/15.4.4.22-5-2.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-5-3.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-5-4.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-5-5.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-5-6.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-5-7.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-5-8.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-7-2.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-7-3.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-7-4.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-7-5.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-7-6.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-7-7.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-7-8.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-7-9.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-2.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-3.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-ii-1.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-ii-2.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-1.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-10.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-11.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-12.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-13.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-14.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-15.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-16.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-17.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-18.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-19.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-20.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-21.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-22.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-25.js # TypeError: Array.prototype.reduceRight called on incompatible receiver an Arguments. -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-26.js # TypeError: Array.prototype.reduceRight called on incompatible receiver an Arguments. -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-27.js # TypeError: Array.prototype.reduceRight called on incompatible receiver an Arguments. -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-29.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a function. -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-30.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-31.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-32.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-33.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-5.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-6.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-7.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-8.js # TypeError: Array.reduceRight of an empty array with no initial value. -built-ins/Array/prototype/reduceRight/15.4.4.22-8-b-iii-1-9.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-8-c-4.js # TypeError: Array.reduceRight of an empty array with no initial value. -built-ins/Array/prototype/reduceRight/15.4.4.22-8-c-5.js # accessed !== true -built-ins/Array/prototype/reduceRight/15.4.4.22-8-c-6.js # accessed !== true -built-ins/Array/prototype/reduceRight/15.4.4.22-8-c-7.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/reduceRight/15.4.4.22-8-c-8.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/reduceRight/15.4.4.22-9-6.js # res Expected SameValue(«"91"», «"151"») to be true -built-ins/Array/prototype/reduceRight/15.4.4.22-9-8.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-9.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-10.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-11.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-12.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-13.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-14.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-15.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-17.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-18.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-19.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-2.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-20.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-21.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-22.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-23.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-24.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-25.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-26.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-27.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-28.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-3.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-4.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-5.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-6.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-7.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-8.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-b-9.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-1.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-10.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-11.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-12.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-13.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-14.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-15.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-16.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-17.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-18.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-19.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-20.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-21.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-22.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-25.js # TypeError: Array.prototype.reduceRight called on incompatible receiver an Arguments. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-26.js # TypeError: Array.prototype.reduceRight called on incompatible receiver an Arguments. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-27.js # TypeError: Array.prototype.reduceRight called on incompatible receiver an Arguments. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-29.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a function. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-30.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-31.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-32.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-33.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-5.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-6.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-7.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-8.js # testResult !== true -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-i-9.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-ii-16.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-ii-20.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-ii-21.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-ii-22.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-ii-23.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-ii-24.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-ii-25.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-ii-26.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-ii-30.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-ii-31.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-ii-32.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-ii-33.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-ii-34.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-ii-35.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-ii-37.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-ii-7.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/reduceRight/15.4.4.22-9-c-ii-8.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a data object. -built-ins/Array/prototype/reduceRight/call-with-boolean.js # TypeError: Array.prototype.reduceRight called on incompatible receiver a boolean. -built-ins/Array/prototype/reduceRight/length-near-integer-limit.js # The value of acc.length is expected to be 2 Expected SameValue(«undefined», «2») to be true -built-ins/Array/prototype/reverse/S15.4.4.8_A2_T1.js # TypeError: Array.prototype.reverse called on incompatible receiver a data object. -built-ins/Array/prototype/reverse/S15.4.4.8_A3_T3.js # TypeError: Array.prototype.reverse called on incompatible receiver a data object. -built-ins/Array/prototype/reverse/S15.4.4.8_A4_T1.js # #1: Array.prototype[1] = 1; x = [0]; x.length = 2; x.reverse(); x[0] === 1. Actual: undefined -built-ins/Array/prototype/reverse/S15.4.4.8_A4_T2.js # TypeError: Array.prototype.reverse called on incompatible receiver a data object. -built-ins/Array/prototype/reverse/call-with-boolean.js # TypeError: Array.prototype.reverse called on incompatible receiver a boolean. -built-ins/Array/prototype/reverse/get_if_present_with_delete.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/reverse/length-exceeding-integer-limit-with-object.js # Expected a StopReverse but got a TypeError -built-ins/Array/prototype/shift/S15.4.4.9_A2_T1.js # TypeError: Array.prototype.shift called on incompatible receiver a data object. -built-ins/Array/prototype/shift/S15.4.4.9_A2_T4.js # TypeError: Array.prototype.shift called on incompatible receiver a data object. -built-ins/Array/prototype/shift/S15.4.4.9_A2_T5.js # TypeError: Array.prototype.shift called on incompatible receiver a data object. -built-ins/Array/prototype/shift/S15.4.4.9_A3_T3.js # TypeError: Array.prototype.shift called on incompatible receiver a data object. -built-ins/Array/prototype/shift/S15.4.4.9_A4_T1.js # #2: Array.prototype[1] = 1; x = [0]; x.length = 2; x.shift(); x[0] === 1. Actual: undefined -built-ins/Array/prototype/shift/S15.4.4.9_A4_T2.js # TypeError: Array.prototype.shift called on incompatible receiver a data object. -built-ins/Array/prototype/shift/call-with-boolean.js # TypeError: Array.prototype.shift called on incompatible receiver a boolean. -built-ins/Array/prototype/shift/set-length-array-is-frozen.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/shift/set-length-array-length-is-non-writable.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/shift/set-length-zero-array-length-is-non-writable.js # TypeError: Making an array's length read-only is not supported; use Object.freeze. -built-ins/Array/prototype/slice/15.4.4.10-10-c-ii-1.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Array/prototype/slice/S15.4.4.10_A2.2_T5.js # #2: var x = [0,1,2,3,4]; var arr = x.slice(0,{valueOf: function() {return 3}, toString: function() { -built-ins/Array/prototype/slice/S15.4.4.10_A2_T1.js # TypeError: Array.prototype.slice called on incompatible receiver a data object. -built-ins/Array/prototype/slice/S15.4.4.10_A2_T2.js # TypeError: Array.prototype.slice called on incompatible receiver a data object. -built-ins/Array/prototype/slice/S15.4.4.10_A2_T3.js # TypeError: Array.prototype.slice called on incompatible receiver a data object. -built-ins/Array/prototype/slice/S15.4.4.10_A2_T4.js # TypeError: Array.prototype.slice called on incompatible receiver a data object. -built-ins/Array/prototype/slice/S15.4.4.10_A2_T5.js # TypeError: Array.prototype.slice called on incompatible receiver a data object. -built-ins/Array/prototype/slice/S15.4.4.10_A2_T6.js # TypeError: Array.prototype.slice called on incompatible receiver a data object. -built-ins/Array/prototype/slice/S15.4.4.10_A3_T1.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/slice/S15.4.4.10_A3_T2.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/slice/S15.4.4.10_A3_T3.js # TypeError: Array.prototype.slice called on incompatible receiver a data object. -built-ins/Array/prototype/slice/S15.4.4.10_A4_T1.js # #3: Array.prototype[1] = 1; x = [0]; x.length = 2; var arr = x.slice(); arr.hasOwnProperty('…') === -built-ins/Array/prototype/slice/call-with-boolean.js # TypeError: Array.prototype.slice called on incompatible receiver a boolean. -built-ins/Array/prototype/slice/create-ctor-non-object.js # null value Expected a TypeError to be thrown but no exception was thrown at all -built-ins/Array/prototype/slice/create-ctor-poisoned.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Array/prototype/slice/create-non-array-invalid-len.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/slice/create-non-array.js # TypeError: Array.prototype.slice called on incompatible receiver a data object. -built-ins/Array/prototype/slice/length-exceeding-integer-limit.js # TypeError: Array.prototype.slice called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-1-10.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-1-11.js # TypeError: Array.prototype.some called on incompatible receiver a Date. -built-ins/Array/prototype/some/15.4.4.17-1-12.js # TypeError: Array.prototype.some called on incompatible receiver a RegExp. -built-ins/Array/prototype/some/15.4.4.17-1-13.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-1-14.js # TypeError: Array.prototype.some called on incompatible receiver an Error. -built-ins/Array/prototype/some/15.4.4.17-1-15.js # TypeError: Array.prototype.some called on incompatible receiver an Arguments. -built-ins/Array/prototype/some/15.4.4.17-1-3.js # TypeError: Array.prototype.some called on incompatible receiver a boolean. -built-ins/Array/prototype/some/15.4.4.17-1-5.js # TypeError: Array.prototype.some called on incompatible receiver a number. -built-ins/Array/prototype/some/15.4.4.17-1-7.js # TypeError: Array.prototype.some called on incompatible receiver a string. -built-ins/Array/prototype/some/15.4.4.17-2-1.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-2-10.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-2-11.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-2-12.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-2-13.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-2-14.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-2-17.js # TypeError: Array.prototype.some called on incompatible receiver an Arguments. -built-ins/Array/prototype/some/15.4.4.17-2-19.js # TypeError: Array.prototype.some called on incompatible receiver a function. -built-ins/Array/prototype/some/15.4.4.17-2-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-2-5.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-2-6.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-2-7.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-2-8.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-2-9.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-3-1.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-10.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-11.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-12.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-13.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-14.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-15.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-16.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-17.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-18.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-19.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-2.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-20.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-21.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-22.js # toStringAccessed !== true -built-ins/Array/prototype/some/15.4.4.17-3-23.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-3-24.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-25.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-28.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-29.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-3.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-4.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-5.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-6.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-7.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-8.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-3-9.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-4-10.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/some/15.4.4.17-4-11.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/some/15.4.4.17-4-15.js # lengthAccessed !== true -built-ins/Array/prototype/some/15.4.4.17-4-8.js # accessed !== true -built-ins/Array/prototype/some/15.4.4.17-4-9.js # accessed !== true -built-ins/Array/prototype/some/15.4.4.17-5-4.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Array/prototype/some/15.4.4.17-5-5.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-7-6.js # res Expected SameValue(«false», «true») to be true -built-ins/Array/prototype/some/15.4.4.17-7-8.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-9.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-b-10.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-b-11.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/some/15.4.4.17-7-b-12.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-b-13.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/some/15.4.4.17-7-b-14.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/some/15.4.4.17-7-b-15.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/some/15.4.4.17-7-b-2.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-b-3.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-b-4.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-b-5.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/some/15.4.4.17-7-b-6.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-b-7.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/some/15.4.4.17-7-b-8.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-b-9.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/some/15.4.4.17-7-c-i-1.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-c-i-10.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/some/15.4.4.17-7-c-i-11.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-7-c-i-12.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/some/15.4.4.17-7-c-i-13.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-7-c-i-14.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/some/15.4.4.17-7-c-i-15.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-7-c-i-16.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/some/15.4.4.17-7-c-i-17.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-c-i-18.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/some/15.4.4.17-7-c-i-19.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-c-i-20.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/some/15.4.4.17-7-c-i-21.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-7-c-i-22.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/some/15.4.4.17-7-c-i-25.js # TypeError: Array.prototype.some called on incompatible receiver an Arguments. -built-ins/Array/prototype/some/15.4.4.17-7-c-i-26.js # TypeError: Array.prototype.some called on incompatible receiver an Arguments. -built-ins/Array/prototype/some/15.4.4.17-7-c-i-27.js # TypeError: Array.prototype.some called on incompatible receiver an Arguments. -built-ins/Array/prototype/some/15.4.4.17-7-c-i-28.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/some/15.4.4.17-7-c-i-29.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-c-i-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-7-c-i-30.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/some/15.4.4.17-7-c-i-31.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/some/15.4.4.17-7-c-i-5.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-7-c-i-6.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/some/15.4.4.17-7-c-i-7.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-7-c-i-8.js # [, ].some(callbackfn) !== true -built-ins/Array/prototype/some/15.4.4.17-7-c-i-9.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-c-ii-16.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-c-ii-17.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-c-ii-18.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-c-ii-19.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-c-ii-20.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-c-ii-21.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-c-ii-22.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-c-ii-23.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-c-ii-6.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-c-ii-7.js # Expected a Error but got a TypeError -built-ins/Array/prototype/some/15.4.4.17-7-c-ii-8.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-c-iii-1.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-c-iii-2.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-c-iii-26.js # [11].some(callbackfn) !== true -built-ins/Array/prototype/some/15.4.4.17-7-c-iii-28.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-c-iii-3.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-7-c-iii-4.js # TypeError: Array.prototype.some called on incompatible receiver a data object. -built-ins/Array/prototype/some/15.4.4.17-8-10.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-8-2.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-8-3.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-8-4.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-8-5.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-8-6.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-8-7.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/15.4.4.17-8-8.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Array/prototype/some/call-with-boolean.js # TypeError: Array.prototype.some called on incompatible receiver a boolean. -built-ins/Array/prototype/sort/S15.4.4.11_A2.1_T3.js # #1: Check ToString operator -built-ins/Array/prototype/sort/S15.4.4.11_A3_T1.js # TypeError: Array.prototype.sort called on incompatible receiver a data object. -built-ins/Array/prototype/sort/S15.4.4.11_A3_T2.js # TypeError: Array.prototype.sort called on incompatible receiver a data object. -built-ins/Array/prototype/sort/S15.4.4.11_A4_T3.js # TypeError: Array.prototype.sort called on incompatible receiver a data object. -built-ins/Array/prototype/sort/S15.4.4.11_A6_T2.js # TypeError: Array.prototype.sort called on incompatible receiver a data object. -built-ins/Array/prototype/sort/bug_596_1.js # #1: [object, object].sort(); counter < 2. Actual: 0 -built-ins/Array/prototype/sort/precise-comparefn-throws.js # Expected SameValue(«undefined», «"get"») to be true -built-ins/Array/prototype/sort/precise-getter-appends-elements.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/sort/precise-getter-decreases-length.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/sort/precise-getter-deletes-predecessor.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/sort/precise-getter-deletes-successor.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/sort/precise-getter-increases-length.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/sort/precise-getter-pops-elements.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/sort/precise-getter-sets-predecessor.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/sort/precise-getter-sets-successor.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/sort/precise-prototype-accessors.js # Expected SameValue(«undefined», «"get"») to be true -built-ins/Array/prototype/sort/precise-prototype-element.js # Expected SameValue(«undefined», «4») to be true -built-ins/Array/prototype/sort/precise-setter-appends-elements.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/sort/precise-setter-decreases-length.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/sort/precise-setter-deletes-predecessor.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/sort/precise-setter-deletes-successor.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/sort/precise-setter-increases-length.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/sort/precise-setter-pops-elements.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/sort/precise-setter-sets-predecessor.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/sort/precise-setter-sets-successor.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/splice/S15.4.4.12_A2.2_T5.js # #2: var x = [0,1,2,3]; var arr = x.splice(0,{valueOf: function() {return 3}, toString: function() {r -built-ins/Array/prototype/splice/S15.4.4.12_A2_T1.js # TypeError: Array.prototype.splice called on incompatible receiver a data object. -built-ins/Array/prototype/splice/S15.4.4.12_A2_T2.js # TypeError: Array.prototype.splice called on incompatible receiver a data object. -built-ins/Array/prototype/splice/S15.4.4.12_A2_T3.js # TypeError: Array.prototype.splice called on incompatible receiver a data object. -built-ins/Array/prototype/splice/S15.4.4.12_A2_T4.js # TypeError: Array.prototype.splice called on incompatible receiver a data object. -built-ins/Array/prototype/splice/S15.4.4.12_A3_T1.js # TypeError: Array.prototype.splice called on incompatible receiver a data object. -built-ins/Array/prototype/splice/S15.4.4.12_A3_T3.js # TypeError: Array.prototype.splice called on incompatible receiver a data object. -built-ins/Array/prototype/splice/S15.4.4.12_A4_T1.js # TypeError: Array.prototype.splice called on incompatible receiver a data object. -built-ins/Array/prototype/splice/S15.4.4.12_A4_T2.js # TypeError: Array.prototype.splice called on incompatible receiver a data object. -built-ins/Array/prototype/splice/S15.4.4.12_A4_T3.js # TypeError: Array.prototype.splice called on incompatible receiver a data object. -built-ins/Array/prototype/splice/S15.4.4.12_A6.1_T2.js # TypeError: Making an array's length read-only is not supported; use Object.freeze. -built-ins/Array/prototype/splice/call-with-boolean.js # TypeError: Array.prototype.splice called on incompatible receiver a boolean. -built-ins/Array/prototype/splice/clamps-length-to-integer-limit.js # TypeError: Array.prototype.splice called on incompatible receiver a data object. -built-ins/Array/prototype/splice/create-ctor-non-object.js # null value Expected a TypeError to be thrown but no exception was thrown at all -built-ins/Array/prototype/splice/create-ctor-poisoned.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Array/prototype/splice/create-non-array-invalid-len.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/splice/create-non-array.js # TypeError: Array.prototype.splice called on incompatible receiver a data object. -built-ins/Array/prototype/splice/length-and-deleteCount-exceeding-integer-limit.js # TypeError: Array.prototype.splice called on incompatible receiver a data object. -built-ins/Array/prototype/splice/length-exceeding-integer-limit-shrink-array.js # TypeError: Array.prototype.splice called on incompatible receiver a data object. -built-ins/Array/prototype/splice/length-near-integer-limit-grow-array.js # TypeError: Array.prototype.splice called on incompatible receiver a data object. -built-ins/Array/prototype/splice/set_length_no_args.js # TypeError: Array.prototype.splice called on incompatible receiver a data object. -built-ins/Array/prototype/toLocaleString/primitive_this_value_getter.js # Expected SameValue(«"object,object"», «"boolean,boolean"») to be true -built-ins/Array/prototype/toReversed/frozen-this-value.js # TypeError: Array.prototype.toReversed called on incompatible receiver a data object. -built-ins/Array/prototype/toReversed/get-descending-order.js # TypeError: Array.prototype.toReversed called on incompatible receiver a data object. -built-ins/Array/prototype/toReversed/holes-not-preserved.js # Actual [4, undefined, 2, undefined, 0] and expected [4, 3, 2, undefined, 0] should have the same con -built-ins/Array/prototype/toReversed/length-casted-to-zero.js # TypeError: Array.prototype.toReversed called on incompatible receiver a data object. -built-ins/Array/prototype/toReversed/length-decreased-while-iterating.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/toReversed/length-exceeding-array-length-limit.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/toReversed/length-increased-while-iterating.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/toReversed/length-tolength.js # TypeError: Array.prototype.toReversed called on incompatible receiver a data object. -built-ins/Array/prototype/toReversed/this-value-boolean.js # TypeError: Array.prototype.toReversed called on incompatible receiver a boolean. -built-ins/Array/prototype/toSorted/comparefn-called-after-get-elements.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/toSorted/comparefn-stop-after-error.js # Expected a Test262Error but got a TypeError -built-ins/Array/prototype/toSorted/frozen-this-value.js # TypeError: Array.prototype.toSorted called on incompatible receiver a data object. -built-ins/Array/prototype/toSorted/holes-not-preserved.js # Actual [1, 3, 4, undefined, undefined] and expected [1, 2, 3, 4, undefined] should have the same con -built-ins/Array/prototype/toSorted/length-casted-to-zero.js # TypeError: Array.prototype.toSorted called on incompatible receiver a data object. -built-ins/Array/prototype/toSorted/length-decreased-while-iterating.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/toSorted/length-exceeding-array-length-limit.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/toSorted/length-increased-while-iterating.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/toSorted/length-tolength.js # TypeError: Array.prototype.toSorted called on incompatible receiver a data object. -built-ins/Array/prototype/toSorted/this-value-boolean.js # TypeError: Array.prototype.toSorted called on incompatible receiver a boolean. -built-ins/Array/prototype/toSpliced/discarded-element-not-read.js # TypeError: Array.prototype.toSpliced called on incompatible receiver a data object. -built-ins/Array/prototype/toSpliced/elements-read-in-order.js # TypeError: Array.prototype.toSpliced called on incompatible receiver a data object. -built-ins/Array/prototype/toSpliced/frozen-this-value.js # TypeError: Array.prototype.toSpliced called on incompatible receiver a data object. -built-ins/Array/prototype/toSpliced/holes-not-preserved.js # Actual [0, undefined, 2, undefined, 4] and expected [0, undefined, 2, 3, 4] should have the same con -built-ins/Array/prototype/toSpliced/length-casted-to-zero.js # TypeError: Array.prototype.toSpliced called on incompatible receiver a data object. -built-ins/Array/prototype/toSpliced/length-clamped-to-2pow53minus1.js # TypeError: Array.prototype.toSpliced called on incompatible receiver a data object. -built-ins/Array/prototype/toSpliced/length-decreased-while-iterating.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/toSpliced/length-exceeding-array-length-limit.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/toSpliced/length-increased-while-iterating.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/toSpliced/length-tolength.js # TypeError: Array.prototype.toSpliced called on incompatible receiver a data object. -built-ins/Array/prototype/toSpliced/mutate-while-iterating.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/toSpliced/this-value-boolean.js # TypeError: Array.prototype.toSpliced called on incompatible receiver a boolean. -built-ins/Array/prototype/toString/S15.4.4.2_A3_T1.js # #1: Array.prototype[1] = 1; x = [0]; x.length = 2; x.toString() === "0,1". Actual: 0, -built-ins/Array/prototype/toString/call-with-boolean.js # TypeError: Array.prototype.toString called on incompatible receiver a boolean. -built-ins/Array/prototype/unshift/S15.4.4.13_A2_T1.js # TypeError: Array.prototype.unshift called on incompatible receiver a data object. -built-ins/Array/prototype/unshift/S15.4.4.13_A2_T3.js # TypeError: Array.prototype.unshift called on incompatible receiver a data object. -built-ins/Array/prototype/unshift/S15.4.4.13_A3_T2.js # TypeError: Array.prototype.unshift called on incompatible receiver a data object. -built-ins/Array/prototype/unshift/S15.4.4.13_A4_T1.js # TypeError: Array.prototype.unshift called on incompatible receiver a data object. -built-ins/Array/prototype/unshift/S15.4.4.13_A4_T2.js # #3: Array.prototype[0] = 1; x = []; x.length = 1; x.unshift(0); x[1] === 1. Actual: undefined -built-ins/Array/prototype/unshift/call-with-boolean.js # TypeError: Array.prototype.unshift called on incompatible receiver a boolean. -built-ins/Array/prototype/unshift/clamps-to-integer-limit.js # TypeError: Array.prototype.unshift called on incompatible receiver a data object. -built-ins/Array/prototype/unshift/length-near-integer-limit.js # Expected a StopUnshift but got a TypeError -built-ins/Array/prototype/unshift/set-length-array-is-frozen.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/unshift/set-length-array-length-is-non-writable.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Array/prototype/unshift/set-length-zero-array-length-is-non-writable.js # TypeError: Making an array's length read-only is not supported; use Object.freeze. -built-ins/Array/prototype/values/returns-iterator-from-object.js # TypeError: Array.prototype.values called on incompatible receiver a data object. -built-ins/Array/prototype/with/length-exceeding-array-length-limit.js # Expected a RangeError but got a TypeError -built-ins/Array/prototype/with/length-tolength.js # TypeError: Array.prototype.with called on incompatible receiver a data object. -built-ins/Array/prototype/with/this-value-boolean.js # TypeError: Array.prototype.with called on incompatible receiver a boolean. -built-ins/ArrayIteratorPrototype/Symbol.toStringTag/value-from-to-string.js # Expected SameValue(«"[object Array Iterator]"», «"[object Iterator]"») to be true -built-ins/AsyncFunction/AsyncFunction-construct.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/AsyncFunction/AsyncFunctionPrototype-is-not-callable.js # Expected SameValue(«"function"», «"object"») to be true -built-ins/AsyncFunction/instance-construct-throws.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/AsyncGeneratorFunction/has-instance.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/AsyncGeneratorFunction/instance-await-expr-in-param.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/AsyncGeneratorFunction/instance-construct-throws.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/AsyncGeneratorFunction/instance-yield-expr-in-param.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/AsyncGeneratorFunction/invoked-as-constructor-no-arguments.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/AsyncGeneratorFunction/invoked-as-function-multiple-arguments.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/AsyncGeneratorFunction/invoked-as-function-no-arguments.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/AsyncGeneratorFunction/invoked-as-function-single-argument.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/AsyncGeneratorFunction/prototype/not-callable.js # Expected SameValue(«"function"», «"object"») to be true -built-ins/AsyncGeneratorPrototype/next/this-val-not-async-generator.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/AsyncGeneratorPrototype/return/return-state-completed-broken-promise.js # Expected rejection -built-ins/AsyncGeneratorPrototype/return/return-suspendedStart-broken-promise.js # Expected rejection -built-ins/AsyncGeneratorPrototype/return/return-suspendedYield-broken-promise-try-catch.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/AsyncGeneratorPrototype/return/this-val-not-async-generator.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/AsyncGeneratorPrototype/throw/this-val-not-async-generator.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Boolean/prototype/S15.6.3.1_A1.js # TypeError: Boolean.prototype.valueOf requires that '…' be a Boolean. -built-ins/Date/S15.9.3.1_A4_T0.js # `new Date(new PoisonedValueOf(1))` throws a Test262Error exception Expected a Test262Error but got a -built-ins/Date/S15.9.3.1_A4_T1.js # `new Date(new PoisonedValueOf(1), new PoisonedValueOf(2))` throws a Test262Error exception Expected -built-ins/Date/S15.9.3.1_A4_T2.js # `new Date(new PoisonedValueOf(1), new PoisonedValueOf(2), new PoisonedValueOf(3))` throws a Test262E -built-ins/Date/S15.9.3.1_A4_T3.js # `new Date(new PoisonedValueOf(1), new PoisonedValueOf(2), new PoisonedValueOf(3), new PoisonedValueO -built-ins/Date/S15.9.3.1_A4_T4.js # `new Date(new PoisonedValueOf(1), new PoisonedValueOf(2), new PoisonedValueOf(3), new PoisonedValueO -built-ins/Date/S15.9.3.1_A4_T5.js # `new Date(new PoisonedValueOf(1), new PoisonedValueOf(2), new PoisonedValueOf(3), new PoisonedValueO -built-ins/Date/S15.9.3.1_A4_T6.js # `new Date(new PoisonedValueOf(1), new PoisonedValueOf(2), new PoisonedValueOf(3), new PoisonedValueO -built-ins/Date/prototype/toJSON/invoke-abrupt.js # Expected a Test262Error but got a TypeError -built-ins/Date/prototype/toJSON/invoke-arguments.js # TypeError: Date.prototype.toJSON called on incompatible receiver a data object. -built-ins/Date/prototype/toJSON/invoke-result.js # TypeError: Date.prototype.toJSON called on incompatible receiver a data object. -built-ins/Date/prototype/toJSON/to-primitive-abrupt.js # Expected a Test262Error but got a TypeError -built-ins/Date/prototype/toJSON/to-primitive-value-of.js # TypeError: Date.prototype.toJSON called on incompatible receiver a data object. -built-ins/Date/prototype/toString/format.js # Expected SameValue(«null», «null») to be false -built-ins/Date/prototype/toString/negative-year.js # Date.prototype.toString serializes year -1 to "-0001" Expected SameValue(«undefined», «"-0001"») to -built-ins/Error/prototype/stack/setter-receiver-is-prototype.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Error/prototype/toString/called-as-function.js # TypeError: Object.defineProperty called on non-object -built-ins/Error/prototype/toString/tostring-message-throws-toprimitive.js # ToPrimitive(msg) called by ToString(msg) throws TypeError Expected a TypeError to be thrown but no e -built-ins/Function/S10.1.1_A1_T3.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -built-ins/Function/internals/Construct/derived-return-val.js # TypeError: Extending the built-in Object is not supported. Only classes and Error types can be exten -built-ins/Function/internals/Construct/derived-this-uninitialized.js # TypeError: Extending the built-in Object is not supported. Only classes and Error types can be exten -built-ins/Function/prototype/bind/15.3.4.5-2-6.js # TypeError: Object(number) wrapper objects are not supported; use the primitive value directly. -built-ins/GeneratorFunction/has-instance.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/GeneratorFunction/instance-construct-throws.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/GeneratorFunction/instance-restricted-properties.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/GeneratorFunction/instance-yield-expr-in-param.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/GeneratorFunction/invoked-as-constructor-no-arguments.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/GeneratorFunction/invoked-as-function-multiple-arguments.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/GeneratorFunction/invoked-as-function-no-arguments.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/GeneratorFunction/invoked-as-function-single-argument.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/GeneratorFunction/prototype/not-callable.js # Expected SameValue(«"function"», «"object"») to be true -built-ins/GeneratorPrototype/throw/from-state-completed.js # Expected a E but got a TypeError -built-ins/GeneratorPrototype/throw/from-state-suspended-start.js # Expected a E but got a TypeError -built-ins/Infinity/15.1.1.2-0.js # TypeError: Object.getOwnPropertyDescriptor cannot convert undefined to an object. -built-ins/Iterator/from/result-proto.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/Symbol.iterator/is-function.js # Expected SameValue(«"undefined"», «"function"») to be true -built-ins/Iterator/prototype/constructor/prop-desc.js # Expected SameValue(«"undefined"», «"function"») to be true -built-ins/Iterator/prototype/constructor/weird-setter.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Iterator/prototype/drop/argument-effect-order.js # Actual ["get next", "ToNumber limit"] and expected ["ToNumber limit", "get next"] should have the sa -built-ins/Iterator/prototype/drop/argument-validation-failure-closes-underlying.js # Expected a RangeError but got a TypeError -built-ins/Iterator/prototype/drop/exhaustion-does-not-call-return.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/drop/get-next-method-only-once.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/drop/get-next-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/drop/get-return-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/drop/next-method-returns-non-object.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/drop/next-method-returns-throwing-done.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/drop/next-method-returns-throwing-value-done.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/drop/next-method-returns-throwing-value.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/drop/next-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/drop/return-is-forwarded.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/drop/return-is-not-forwarded-after-exhaustion.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/drop/throws-typeerror-when-generator-is-running.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/every/argument-effect-order.js # Actual ["get next"] and expected [] should have the same contents. -built-ins/Iterator/prototype/every/argument-validation-failure-closes-underlying.js # Expected SameValue(«false», «true») to be true -built-ins/Iterator/prototype/every/get-next-method-only-once.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/every/get-next-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/every/get-return-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/every/iterator-return-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/every/next-method-returns-non-object.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/every/next-method-returns-throwing-done.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/every/next-method-returns-throwing-value-done.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/every/next-method-returns-throwing-value.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/every/next-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/every/predicate-throws-then-closing-iterator-also-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/every/predicate-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/filter/argument-effect-order.js # Actual ["get next"] and expected [] should have the same contents. -built-ins/Iterator/prototype/filter/argument-validation-failure-closes-underlying.js # Expected SameValue(«false», «true») to be true -built-ins/Iterator/prototype/filter/exhaustion-does-not-call-return.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/filter/get-next-method-only-once.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/filter/get-next-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/filter/get-return-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/filter/iterator-return-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/filter/next-method-returns-non-object.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/filter/next-method-returns-throwing-done.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/filter/next-method-returns-throwing-value-done.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/filter/next-method-returns-throwing-value.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/filter/next-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/filter/predicate-throws-then-closing-iterator-also-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/filter/predicate-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/filter/return-is-forwarded.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/filter/return-is-not-forwarded-after-exhaustion.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/find/argument-effect-order.js # Actual ["get next"] and expected [] should have the same contents. -built-ins/Iterator/prototype/find/argument-validation-failure-closes-underlying.js # Expected SameValue(«false», «true») to be true -built-ins/Iterator/prototype/find/get-next-method-only-once.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/find/get-next-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/find/get-return-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/find/iterator-return-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/find/next-method-returns-non-object.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/find/next-method-returns-throwing-done.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/find/next-method-returns-throwing-value-done.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/find/next-method-returns-throwing-value.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/find/next-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/find/predicate-throws-then-closing-iterator-also-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/find/predicate-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/flatMap/argument-effect-order.js # Actual ["get next"] and expected [] should have the same contents. -built-ins/Iterator/prototype/flatMap/argument-validation-failure-closes-underlying.js # Expected SameValue(«false», «true») to be true -built-ins/Iterator/prototype/flatMap/exhaustion-does-not-call-return.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/flatMap/get-next-method-only-once.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/flatMap/get-next-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/flatMap/get-return-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/flatMap/iterator-return-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/flatMap/mapper-throws-then-closing-iterator-also-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/flatMap/mapper-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/flatMap/next-method-returns-non-object.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/flatMap/next-method-returns-throwing-done.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/flatMap/next-method-returns-throwing-value-done.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/flatMap/next-method-returns-throwing-value.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/flatMap/next-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/flatMap/return-is-forwarded-to-underlying-iterator.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/flatMap/return-is-not-forwarded-after-exhaustion.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/forEach/argument-effect-order.js # Actual ["get next"] and expected [] should have the same contents. -built-ins/Iterator/prototype/forEach/argument-validation-failure-closes-underlying.js # Expected SameValue(«false», «true») to be true -built-ins/Iterator/prototype/forEach/fn-throws-then-closing-iterator-also-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/forEach/fn-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/forEach/get-next-method-only-once.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/forEach/get-next-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/forEach/next-method-returns-non-object.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/forEach/next-method-returns-throwing-done.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/forEach/next-method-returns-throwing-value-done.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/forEach/next-method-returns-throwing-value.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/forEach/next-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/map/argument-effect-order.js # Actual ["get next"] and expected [] should have the same contents. -built-ins/Iterator/prototype/map/argument-validation-failure-closes-underlying.js # Expected SameValue(«false», «true») to be true -built-ins/Iterator/prototype/map/exhaustion-does-not-call-return.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/map/get-next-method-only-once.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/map/get-next-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/map/get-return-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/map/iterator-return-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/map/mapper-throws-then-closing-iterator-also-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/map/mapper-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/map/next-method-returns-non-object.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/map/next-method-returns-throwing-done.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/map/next-method-returns-throwing-value-done.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/map/next-method-returns-throwing-value.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/map/next-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/map/return-is-forwarded-to-underlying-iterator.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/map/return-is-not-forwarded-after-exhaustion.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/reduce/argument-effect-order.js # Actual ["get next"] and expected [] should have the same contents. -built-ins/Iterator/prototype/reduce/argument-validation-failure-closes-underlying.js # Expected SameValue(«false», «true») to be true -built-ins/Iterator/prototype/reduce/get-next-method-only-once.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/reduce/get-next-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/reduce/next-method-returns-non-object.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/reduce/next-method-returns-throwing-done.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/reduce/next-method-returns-throwing-value-done.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/reduce/next-method-returns-throwing-value.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/reduce/next-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/reduce/reducer-throws-then-closing-iterator-also-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/reduce/reducer-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/some/argument-effect-order.js # Actual ["get next"] and expected [] should have the same contents. -built-ins/Iterator/prototype/some/argument-validation-failure-closes-underlying.js # Expected SameValue(«false», «true») to be true -built-ins/Iterator/prototype/some/get-next-method-only-once.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/some/get-next-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/some/get-return-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/some/iterator-return-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/some/next-method-returns-non-object.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/some/next-method-returns-throwing-done.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/some/next-method-returns-throwing-value-done.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/some/next-method-returns-throwing-value.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/some/next-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/some/predicate-throws-then-closing-iterator-also-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/some/predicate-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/take/argument-effect-order.js # Actual ["get next", "ToNumber limit"] and expected ["ToNumber limit", "get next"] should have the sa -built-ins/Iterator/prototype/take/argument-validation-failure-closes-underlying.js # Expected a RangeError but got a TypeError -built-ins/Iterator/prototype/take/exhaustion-calls-return.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/take/get-next-method-only-once.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/take/get-next-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/take/get-return-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/take/next-method-returns-non-object.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/take/next-method-returns-throwing-done.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/take/next-method-returns-throwing-value-done.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/take/next-method-returns-throwing-value.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/take/next-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/take/return-is-forwarded.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/take/return-is-not-forwarded-after-exhaustion.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/take/throws-typeerror-when-generator-is-running.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/toArray/get-next-method-only-once.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/toArray/get-next-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/toArray/next-method-returns-non-object.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/toArray/next-method-returns-throwing-done.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/toArray/next-method-returns-throwing-value-done.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/toArray/next-method-returns-throwing-value.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/prototype/toArray/next-method-throws.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/Iterator/subclassable.js # TypeError: Extending the built-in Iterator is not supported. Only classes and Error types can be ext -built-ins/JSON/parse/reviver-array-non-configurable-prop-create.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/JSON/parse/reviver-array-non-configurable-prop-delete.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/JSON/parse/reviver-call-args-after-forward-modification.js # TypeError: Cannot destructure undefined as it is undefined. -built-ins/JSON/parse/reviver-forward-modifies-object.js # TypeError: Cannot destructure undefined as it is undefined. -built-ins/JSON/parse/reviver-get-name-err.js # Expected a Test262Error but got a TypeError -built-ins/JSON/parse/reviver-object-non-configurable-prop-create.js # Expected SameValue(«22», «2») to be true -built-ins/JSON/parse/reviver-object-non-configurable-prop-delete.js # TypeError: Cannot delete property '…'. -built-ins/JSON/parse/text-object-abrupt.js # Expected a Test262Error but got a SyntaxError -built-ins/JSON/parse/text-object.js # SyntaxError: JSON.parse received invalid JSON: JSON Parse error: Unexpected identifier "object" -built-ins/JSON/rawJSON/basic.js # TypeError: JSON.rawJSON is not a function. -built-ins/JSON/rawJSON/illegal-empty-and-start-end-chars.js # Expected a SyntaxError but got a TypeError -built-ins/JSON/rawJSON/returns-expected-object.js # TypeError: JSON.rawJSON is not a function. -built-ins/JSON/stringify/value-array-circular.js # TypeError: Array.push result contains a circular value. -built-ins/JSON/stringify/value-object-circular.js # TypeError: Object assignment result contains a circular value. -built-ins/Map/get-set-method-failure.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Map/iterable-calls-set.js # `Map.prototype.set` called twice. Expected SameValue(«0», «2») to be true -built-ins/Map/iterator-close-after-set-failure.js # TimeoutExceeded: Execution timed out after 5000ms. -built-ins/Map/iterator-close-failure-after-set-failure.js # TimeoutExceeded: Execution timed out after 5000ms. -built-ins/Map/iterator-item-first-entry-returns-abrupt.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Map/iterator-item-second-entry-returns-abrupt.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Map/map-iterable-throws-when-set-is-not-callable.js # Expected a TypeError to be thrown but no exception was thrown at all -built-ins/Math/sumPrecise/takes-iterable.js # Expected SameValue(«4», «3») to be true -built-ins/NaN/15.1.1.1-0.js # TypeError: Object.getOwnPropertyDescriptor cannot convert undefined to an object. -built-ins/Number/prototype/S15.7.3.1_A2_T1.js # Number.prototype.toString() must return "[object Number]" Expected SameValue(«"[object Object]"», «" -built-ins/Number/prototype/S15.7.3.1_A2_T2.js # Number.prototype.toString() must return "[object Number]" Expected SameValue(«"[object Object]"», «" -built-ins/Number/prototype/S15.7.3.1_A3.js # TypeError: Number.prototype.valueOf requires that '…' be a Number. -built-ins/Number/prototype/S15.7.4_A1.js # TypeError: Number.prototype.valueOf requires that '…' be a Number. -built-ins/Number/prototype/toExponential/this-is-0-fractiondigits-is-0.js # TypeError: Number.prototype.toExponential requires that '…' be a Number. -built-ins/Number/prototype/toFixed/S15.7.4.5_A1.1_T01.js # TypeError: Number.prototype.toFixed requires that '…' be a Number. -built-ins/Number/prototype/toPrecision/return-abrupt-tointeger-precision.js # valueOf Expected a Test262Error but got a TypeError -built-ins/Number/prototype/toPrecision/this-is-0-precision-is-1.js # TypeError: Number.prototype.toPrecision requires that '…' be a Number. -built-ins/Object/S15.2.1.1_A2_T1.js # TypeError: Object(boolean) wrapper objects are not supported; use the primitive value directly. -built-ins/Object/S15.2.1.1_A2_T13.js # TypeError: Object(boolean) wrapper objects are not supported; use the primitive value directly. -built-ins/Object/S15.2.1.1_A2_T2.js # TypeError: Object(number) wrapper objects are not supported; use the primitive value directly. -built-ins/Object/S15.2.1.1_A2_T3.js # TypeError: Object(string) wrapper objects are not supported; use the primitive value directly. -built-ins/Object/S15.2.1.1_A2_T5.js # TypeError: Object(number) wrapper objects are not supported; use the primitive value directly. -built-ins/Object/S15.2.1.1_A2_T6.js # TypeError: Object(number) wrapper objects are not supported; use the primitive value directly. -built-ins/Object/S15.2.1.1_A2_T7.js # TypeError: Object(string) wrapper objects are not supported; use the primitive value directly. -built-ins/Object/S15.2.1.1_A3_T3.js # TypeError: Object(number) wrapper objects are not supported; use the primitive value directly. -built-ins/Object/S15.2.2.1_A3_T1.js # TypeError: Object(string) wrapper objects are not supported; use the primitive value directly. -built-ins/Object/S15.2.2.1_A3_T2.js # TypeError: Object(string) wrapper objects are not supported; use the primitive value directly. -built-ins/Object/S15.2.2.1_A4_T1.js # TypeError: Object(boolean) wrapper objects are not supported; use the primitive value directly. -built-ins/Object/S15.2.2.1_A4_T2.js # TypeError: Object(boolean) wrapper objects are not supported; use the primitive value directly. -built-ins/Object/S15.2.2.1_A4_T3.js # TypeError: Object(boolean) wrapper objects are not supported; use the primitive value directly. -built-ins/Object/S15.2.2.1_A5_T1.js # TypeError: Object(number) wrapper objects are not supported; use the primitive value directly. -built-ins/Object/S15.2.2.1_A5_T2.js # TypeError: Object(number) wrapper objects are not supported; use the primitive value directly. -built-ins/Object/S15.2.2.1_A5_T3.js # TypeError: Object(number) wrapper objects are not supported; use the primitive value directly. -built-ins/Object/S15.2.2.1_A6_T3.js # TypeError: Object(number) wrapper objects are not supported; use the primitive value directly. -built-ins/Object/S15.2_A1.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Object/S9.9_A6.js # TypeError: MyObject is not a constructor: only classes can be constructed with new. Use a class, or -built-ins/Object/assign/OnlyOneArgument.js # TypeError: Object.assign expects a data object or array target, received a string. -built-ins/Object/assign/Override-notstringtarget.js # TypeError: Object.assign expects a data object or array target, received a number. -built-ins/Object/assign/Target-Boolean.js # TypeError: Object.assign expects a data object or array target, received a boolean. -built-ins/Object/assign/Target-Number.js # TypeError: Object.assign expects a data object or array target, received a number. -built-ins/Object/assign/Target-String.js # TypeError: Object.assign expects a data object or array target, received a string. -built-ins/Object/create/15.2.3.5-2-1.js # TypeError: base is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/create/15.2.3.5-3-1.js # TypeError: base is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/create/15.2.3.5-4-1.js # TypeError: base is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/create/15.2.3.5-4-102.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-106.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-124.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Object/create/15.2.3.5-4-149.js # TypeError: Cannot delete property '…'. -built-ins/Object/create/15.2.3.5-4-155.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-156.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-157.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-159.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-160.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-161.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-163.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-164.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-165.js # TypeError: Func is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/create/15.2.3.5-4-177.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Object/create/15.2.3.5-4-18.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-181.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-182.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-183.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-185.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-186.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-187.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-191.js # TypeError: Func is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/create/15.2.3.5-4-203.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Object/create/15.2.3.5-4-21.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-22.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-228.js # TypeError: Cannot assign to read only property '…'. -built-ins/Object/create/15.2.3.5-4-23.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-234.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-235.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-236.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-238.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-239.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-24.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-240.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-242.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-243.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-25.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-256.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Object/create/15.2.3.5-4-269.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-27.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-270.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-271.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-273.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-274.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-275.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-277.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-278.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-291.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Object/create/15.2.3.5-4-300.js # Expected a TypeError to be thrown but no exception was thrown at all -built-ins/Object/create/15.2.3.5-4-49.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-50.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-51.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-53.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-54.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-55.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-57.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-58.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/create/15.2.3.5-4-71.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Object/create/15.2.3.5-4-96.js # accessed !== true -built-ins/Object/defineProperties/15.2.3.7-2-16.js # TypeError: Fun is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-2-18.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Object/defineProperties/15.2.3.7-3-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-3-6.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-a-1.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-a-2.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-a-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-a-4.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-a-6.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-10.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-109.js # TypeError: Cannot delete property '…'. -built-ins/Object/defineProperties/15.2.3.7-5-b-11.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-115.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-116.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-117.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-119.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-120.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-121.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-123.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-124.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-13.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-137.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Object/defineProperties/15.2.3.7-5-b-14.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-145.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-15.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-17.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-18.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-188.js # TypeError: Cannot assign to read only property '…'. -built-ins/Object/defineProperties/15.2.3.7-5-b-194.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-195.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-196.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-198.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-199.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-200.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-202.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-203.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-216.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Object/defineProperties/15.2.3.7-5-b-229.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-230.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-231.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-233.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-234.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-235.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-237.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-238.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-31.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Object/defineProperties/15.2.3.7-5-b-56.js # accessed !== true -built-ins/Object/defineProperties/15.2.3.7-5-b-62.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-66.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-5-b-84.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Object/defineProperties/15.2.3.7-5-b-9.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-6-a-10.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-6-a-11.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-6-a-112.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/defineProperties/15.2.3.7-6-a-119.js # TypeError: Making an array's length read-only is not supported; use Object.freeze. -built-ins/Object/defineProperties/15.2.3.7-6-a-142.js # RangeError: Invalid array length -built-ins/Object/defineProperties/15.2.3.7-6-a-143.js # RangeError: Invalid array length -built-ins/Object/defineProperties/15.2.3.7-6-a-144.js # RangeError: Invalid array length -built-ins/Object/defineProperties/15.2.3.7-6-a-145.js # RangeError: Invalid array length -built-ins/Object/defineProperties/15.2.3.7-6-a-146.js # Expected a TypeError but got a RangeError -built-ins/Object/defineProperties/15.2.3.7-6-a-147.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-6-a-150.js # RangeError: Invalid array length -built-ins/Object/defineProperties/15.2.3.7-6-a-151.js # RangeError: Invalid array length -built-ins/Object/defineProperties/15.2.3.7-6-a-158.js # TypeError: Making an array's length read-only is not supported; use Object.freeze. -built-ins/Object/defineProperties/15.2.3.7-6-a-159.js # TypeError: Making an array's length read-only is not supported; use Object.freeze. -built-ins/Object/defineProperties/15.2.3.7-6-a-160.js # TypeError: Making an array's length read-only is not supported; use Object.freeze. -built-ins/Object/defineProperties/15.2.3.7-6-a-165.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/defineProperties/15.2.3.7-6-a-169.js # Array.prototype[1] Expected SameValue(«undefined», «2») to be true -built-ins/Object/defineProperties/15.2.3.7-6-a-171.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Object/defineProperties/15.2.3.7-6-a-172.js # arr[1] Expected SameValue(«1», «2») to be true -built-ins/Object/defineProperties/15.2.3.7-6-a-173.js # Array.prototype[1] Expected SameValue(«undefined», «2») to be true -built-ins/Object/defineProperties/15.2.3.7-6-a-175.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/defineProperties/15.2.3.7-6-a-179.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/defineProperties/15.2.3.7-6-a-183.js # TypeError: Making an array's length read-only is not supported; use Object.freeze. -built-ins/Object/defineProperties/15.2.3.7-6-a-184.js # TypeError: Making an array's length read-only is not supported; use Object.freeze. -built-ins/Object/defineProperties/15.2.3.7-6-a-185.js # TypeError: Making an array's length read-only is not supported; use Object.freeze. -built-ins/Object/defineProperties/15.2.3.7-6-a-186.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/defineProperties/15.2.3.7-6-a-187.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/defineProperties/15.2.3.7-6-a-188.js # arr[0] Expected SameValue(«undefined», «12») to be true -built-ins/Object/defineProperties/15.2.3.7-6-a-189.js # arr[0] Expected SameValue(«undefined», «12») to be true -built-ins/Object/defineProperties/15.2.3.7-6-a-190.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Object/defineProperties/15.2.3.7-6-a-191.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Object/defineProperties/15.2.3.7-6-a-192.js # arr[0] Expected SameValue(«undefined», «12») to be true -built-ins/Object/defineProperties/15.2.3.7-6-a-193.js # arr[0] Expected SameValue(«undefined», «12») to be true -built-ins/Object/defineProperties/15.2.3.7-6-a-196.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/defineProperties/15.2.3.7-6-a-198.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/defineProperties/15.2.3.7-6-a-201.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Object/defineProperties/15.2.3.7-6-a-203.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Object/defineProperties/15.2.3.7-6-a-263.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/defineProperties/15.2.3.7-6-a-264.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/defineProperties/15.2.3.7-6-a-265.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/defineProperties/15.2.3.7-6-a-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-6-a-4.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-6-a-6.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-6-a-7.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperties/15.2.3.7-6-a-8.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/defineProperty/15.2.3.6-2-48.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-123.js # TypeError: Cannot delete property '…'. -built-ins/Object/defineProperty/15.2.3.6-3-129.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-130.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-131.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-133.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-134.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-135.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-137.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-138.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-151.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Object/defineProperty/15.2.3.6-3-155.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-156.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-157.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-159.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-160.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-161.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-177.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Object/defineProperty/15.2.3.6-3-202.js # TypeError: Cannot assign to read only property '…'. -built-ins/Object/defineProperty/15.2.3.6-3-208.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-209.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-210.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-212.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-213.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-214.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-216.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-217.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-23.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-230.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Object/defineProperty/15.2.3.6-3-238.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-239.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-24.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-240.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-242.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-243.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-244.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-25.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-260.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Object/defineProperty/15.2.3.6-3-27.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-28.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-29.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-31.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-32.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-45.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Object/defineProperty/15.2.3.6-3-70.js # accessed !== true -built-ins/Object/defineProperty/15.2.3.6-3-77.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-78.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-80.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-81.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-82.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-3-98.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Object/defineProperty/15.2.3.6-4-146.js # RangeError: Invalid array length -built-ins/Object/defineProperty/15.2.3.6-4-147.js # RangeError: Invalid array length -built-ins/Object/defineProperty/15.2.3.6-4-148.js # RangeError: Invalid array length -built-ins/Object/defineProperty/15.2.3.6-4-149.js # RangeError: Invalid array length -built-ins/Object/defineProperty/15.2.3.6-4-150.js # Expected a TypeError but got a RangeError -built-ins/Object/defineProperty/15.2.3.6-4-151.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-4-154.js # RangeError: Invalid array length -built-ins/Object/defineProperty/15.2.3.6-4-155.js # RangeError: Invalid array length -built-ins/Object/defineProperty/15.2.3.6-4-162.js # TypeError: Making an array's length read-only is not supported; use Object.freeze. -built-ins/Object/defineProperty/15.2.3.6-4-163.js # TypeError: Making an array's length read-only is not supported; use Object.freeze. -built-ins/Object/defineProperty/15.2.3.6-4-164.js # TypeError: Making an array's length read-only is not supported; use Object.freeze. -built-ins/Object/defineProperty/15.2.3.6-4-168.js # arrObj.length Expected SameValue(«3», «2») to be true -built-ins/Object/defineProperty/15.2.3.6-4-169.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/defineProperty/15.2.3.6-4-175.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Object/defineProperty/15.2.3.6-4-179-1.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/defineProperty/15.2.3.6-4-182.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/defineProperty/15.2.3.6-4-183.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/defineProperty/15.2.3.6-4-187.js # TypeError: Making an array's length read-only is not supported; use Object.freeze. -built-ins/Object/defineProperty/15.2.3.6-4-188.js # TypeError: Making an array's length read-only is not supported; use Object.freeze. -built-ins/Object/defineProperty/15.2.3.6-4-189.js # TypeError: Making an array's length read-only is not supported; use Object.freeze. -built-ins/Object/defineProperty/15.2.3.6-4-191.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/defineProperty/15.2.3.6-4-192.js # Array.prototype[0] Expected SameValue(«undefined», «11») to be true -built-ins/Object/defineProperty/15.2.3.6-4-193.js # Array.prototype[0] Expected SameValue(«undefined», «11») to be true -built-ins/Object/defineProperty/15.2.3.6-4-206.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Object/defineProperty/15.2.3.6-4-23.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-4-24.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-4-25.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-4-27.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-4-274.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/defineProperty/15.2.3.6-4-275.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/defineProperty/15.2.3.6-4-276.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/defineProperty/15.2.3.6-4-28.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-4-29.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-4-31.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-4-32.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/defineProperty/15.2.3.6-4-333-4.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/defineProperty/15.2.3.6-4-339-1.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/defineProperty/15.2.3.6-4-360-1.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/defineProperty/15.2.3.6-4-540-4.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Object/defineProperty/15.2.3.6-4-625gs.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Object/entries/inherited-properties-omitted.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Object/freeze/15.2.3.9-2-2.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/freeze/15.2.3.9-2-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/fromEntries/evaluation-order.js # Actual ["get Symbol.iterator", "next 0", "access property \"0\" of first entry", "toString of first -built-ins/Object/fromEntries/iterator-closed-for-throwing-entry-key-accessor.js # Expected a DummyError but got a TypeError -built-ins/Object/fromEntries/iterator-closed-for-throwing-entry-key-tostring.js # Expected a DummyError but got a TypeError -built-ins/Object/fromEntries/iterator-closed-for-throwing-entry-value-accessor.js # Expected a DummyError but got a TypeError -built-ins/Object/fromEntries/iterator-not-closed-for-throwing-done-accessor.js # Expected a DummyError but got a TypeError -built-ins/Object/fromEntries/iterator-not-closed-for-throwing-next.js # Expected a DummyError but got a TypeError -built-ins/Object/getOwnPropertyDescriptor/15.2.3.3-2-47.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/getOwnPropertyDescriptor/15.2.3.3-3-2.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/getOwnPropertyDescriptor/15.2.3.3-3-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/getOwnPropertyDescriptor/15.2.3.3-3-4.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/getOwnPropertyDescriptor/15.2.3.3-3-6.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/getOwnPropertyDescriptor/15.2.3.3-3-7.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/getOwnPropertyDescriptor/15.2.3.3-3-8.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/getOwnPropertyDescriptor/15.2.3.3-4-10.js # TypeError: Object.getOwnPropertyDescriptor cannot convert undefined to an object. -built-ins/Object/getOwnPropertyDescriptor/15.2.3.3-4-11.js # TypeError: Object.getOwnPropertyDescriptor cannot convert undefined to an object. -built-ins/Object/getOwnPropertyDescriptor/15.2.3.3-4-178.js # TypeError: Object.getOwnPropertyDescriptor cannot convert undefined to an object. -built-ins/Object/getOwnPropertyDescriptor/15.2.3.3-4-179.js # TypeError: Object.getOwnPropertyDescriptor cannot convert undefined to an object. -built-ins/Object/getOwnPropertyDescriptor/15.2.3.3-4-180.js # TypeError: Object.getOwnPropertyDescriptor cannot convert undefined to an object. -built-ins/Object/getOwnPropertyDescriptor/15.2.3.3-4-5.js # TypeError: Object.getOwnPropertyDescriptor cannot convert undefined to an object. -built-ins/Object/getOwnPropertyDescriptor/15.2.3.3-4-6.js # TypeError: Object.getOwnPropertyDescriptor cannot convert undefined to an object. -built-ins/Object/getOwnPropertyDescriptor/15.2.3.3-4-7.js # TypeError: Object.getOwnPropertyDescriptor cannot convert undefined to an object. -built-ins/Object/getOwnPropertyDescriptor/15.2.3.3-4-8.js # TypeError: Object.getOwnPropertyDescriptor cannot convert undefined to an object. -built-ins/Object/getOwnPropertyDescriptor/15.2.3.3-4-9.js # TypeError: Object.getOwnPropertyDescriptor cannot convert undefined to an object. -built-ins/Object/getOwnPropertyDescriptors/inherited-properties-omitted.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Object/getOwnPropertyDescriptors/tamper-with-global-object.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Object/getOwnPropertyNames/15.2.3.4-2-4.js # TypeError: Cannot assign to constant '…'. -built-ins/Object/getOwnPropertyNames/15.2.3.4-4-36.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/getOwnPropertyNames/15.2.3.4-4-37.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/getPrototypeOf/15.2.3.2-2-2.js # TypeError: base is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/getPrototypeOf/15.2.3.2-2-30.js # TypeError: Object.getPrototypeOf cannot convert undefined to an object. -built-ins/Object/isExtensible/15.2.3.13-2-1.js # Expected true but got false -built-ins/Object/isExtensible/15.2.3.13-2-24.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/isExtensible/15.2.3.13-2-25.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/isExtensible/15.2.3.13-2-26.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/isExtensible/15.2.3.13-2-27.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/isExtensible/15.2.3.13-2-29.js # Object.isExtensible(this) !== true -built-ins/Object/isFrozen/15.2.3.12-2-1.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/isFrozen/15.2.3.12-2-2.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/isFrozen/15.2.3.12-2-a-2.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/isFrozen/15.2.3.12-2-a-3.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/isFrozen/15.2.3.12-2-a-5.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/isFrozen/15.2.3.12-2-a-6.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/isFrozen/15.2.3.12-2-a-8.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/isFrozen/15.2.3.12-3-1.js # Expected true but got false -built-ins/Object/isSealed/15.2.3.11-4-1.js # Expected true but got false -built-ins/Object/keys/15.2.3.14-5-10.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/keys/15.2.3.14-5-13.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -built-ins/Object/keys/15.2.3.14-5-14.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Object/keys/15.2.3.14-5-5.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/keys/15.2.3.14-5-6.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/keys/15.2.3.14-5-7.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/keys/15.2.3.14-5-8.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/keys/15.2.3.14-5-9.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/Object/preventExtensions/15.2.3.10-3-24.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/prototype/hasOwnProperty/S15.2.4.5_A1_T3.js # TypeError: FACTORY is not a constructor: only classes can be constructed with new. Use a class, or c -built-ins/Object/prototype/isPrototypeOf/this-value-is-in-prototype-chain-of-arg.js # TypeError: USER_FACTORY is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/prototype/propertyIsEnumerable/S15.2.4.7_A1_T1.js # TypeError: AVISFACTORY is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/prototype/toLocaleString/primitive_this_value_getter.js # Expected SameValue(«"object"», «"boolean"») to be true -built-ins/Object/prototype/valueOf/15.2.4.4-1.js # typeof Object.prototype.valueOf.call(true) Expected SameValue(«"boolean"», «"object"») to be true -built-ins/Object/prototype/valueOf/15.2.4.4-2.js # typeof Object.prototype.valueOf.call(false) Expected SameValue(«"boolean"», «"object"») to be true -built-ins/Object/seal/object-seal-inherited-accessor-properties-are-ignored.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/seal/object-seal-inherited-data-properties-are-ignored.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -built-ins/Object/seal/seal-arrowfunction.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/Object/seal/seal-asyncarrowfunction.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/Object/seal/seal-asyncfunction.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/Object/seal/seal-asyncgeneratorfunction.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/Object/seal/seal-generatorfunction.js # TypeError: The Function constructor is not supported; write the function inline. -built-ins/Object/seal/seal-promise.js # The program is waiting on a promise that can never settle: nothing else is running, so nothing can r -built-ins/Object/seal/seal-uint8array.js # TypeError: A Uint8Array cannot cross to the host; pass text instead, e.g. `new TextDecoder().decode( -built-ins/Object/values/inherited-properties-omitted.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Promise/all/S25.4.4.1_A4.1_T1.js # Expected a TypeError to be thrown but no exception was thrown at all -built-ins/Promise/all/call-resolve-element-after-return.js # callCount after call to all() Expected SameValue(«0», «1») to be true -built-ins/Promise/all/call-resolve-element-items.js # callCount after call to all() Expected SameValue(«0», «1») to be true -built-ins/Promise/all/call-resolve-element.js # callCount after call to all() Expected SameValue(«0», «1») to be true -built-ins/Promise/all/capability-resolve-throws-reject.js # "Promise incorrectly fulfilled." -built-ins/Promise/all/ctx-ctor-throws.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Promise/all/ctx-ctor.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -built-ins/Promise/all/does-not-invoke-array-setters.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Promise/all/invoke-resolve-error-close.js # TimeoutExceeded: Execution timed out after 5000ms. -built-ins/Promise/all/invoke-resolve-error-reject.js # The promise should not be fulfilled. -built-ins/Promise/all/invoke-resolve-get-error-reject.js # $DONE was never called -built-ins/Promise/all/invoke-resolve-get-error.js # Expected SameValue(«Test262Error: unreachable», «object») to be true -built-ins/Promise/all/invoke-resolve-get-once-multiple-calls.js # Got `resolve` only once for each iterated value Expected SameValue(«0», «1») to be true -built-ins/Promise/all/invoke-resolve-get-once-no-calls.js # Got `resolve` only once for each iterated value Expected SameValue(«0», «1») to be true -built-ins/Promise/all/invoke-resolve-on-promises-every-iteration-of-custom.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -built-ins/Promise/all/invoke-resolve-on-promises-every-iteration-of-promise.js # `then` invoked once for every iterated promise Expected SameValue(«0», «3») to be true -built-ins/Promise/all/invoke-resolve-on-values-every-iteration-of-promise.js # `Promise.resolve` invoked once for every iterated value Expected SameValue(«0», «3») to be true -built-ins/Promise/all/invoke-resolve-return.js # new `then` method invoked exactly once Expected SameValue(«0», «1») to be true -built-ins/Promise/all/invoke-resolve.js # `resolve` invoked once for each iterated value Expected SameValue(«0», «3») to be true -built-ins/Promise/all/invoke-then-error-close.js # TimeoutExceeded: Execution timed out after 5000ms. -built-ins/Promise/all/invoke-then-error-reject.js # $DONE was never called -built-ins/Promise/all/invoke-then-get-error-close.js # TimeoutExceeded: Execution timed out after 5000ms. -built-ins/Promise/all/invoke-then-get-error-reject.js # $DONE was never called -built-ins/Promise/all/invoke-then.js # `then` invoked once for every iterated value Expected SameValue(«0», «3») to be true -built-ins/Promise/all/new-resolve-function.js # p1.then call count Expected SameValue(«0», «1») to be true -built-ins/Promise/all/resolve-before-loop-exit-from-same.js # TypeError: p1OnFulfilled is not a function. -built-ins/Promise/all/resolve-before-loop-exit.js # callCount after call to all() Expected SameValue(«0», «1») to be true -built-ins/Promise/all/resolve-element-function-extensible.js # Expected true but got false -built-ins/Promise/all/resolve-element-function-nonconstructor.js # TypeError: Object.prototype.hasOwnProperty called on incompatible receiver undefined. -built-ins/Promise/all/resolve-element-function-property-order.js # TypeError: Object.getOwnPropertyNames cannot convert undefined to an object. -built-ins/Promise/all/resolve-from-same-thenable.js # TypeError: p1OnFulfilled is not a function. -built-ins/Promise/all/resolve-non-callable.js # Expected true but got false -built-ins/Promise/all/resolve-not-callable-reject-with-typeerror.js # "The promise should not be resolved." -built-ins/Promise/all/resolve-poisoned-then.js # "The promise should not be fulfilled." -built-ins/Promise/all/resolve-throws-iterator-return-null-or-undefined.js # TimeoutExceeded: Execution timed out after 5000ms. -built-ins/Promise/all/same-reject-function.js # p1.then call count Expected SameValue(«0», «1») to be true -built-ins/Promise/allKeyed/ctx-ctor-throws.js # Expected a Test262Error but got a TypeError -built-ins/Promise/allKeyed/extensible.js # Expected true but got false -built-ins/Promise/allKeyed/invoke-resolve-custom.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Promise/allKeyed/invoke-resolve-get-once.js # TypeError: Promise.allKeyed is not a function. -built-ins/Promise/allKeyed/invoke-resolve-return.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Promise/allKeyed/resolve-from-same-thenable.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Promise/allSettled/capability-resolve-throws-reject.js # "Promise incorrectly fulfilled." -built-ins/Promise/allSettled/ctx-ctor-throws.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Promise/allSettled/ctx-ctor.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -built-ins/Promise/allSettled/does-not-invoke-array-setters.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/Promise/allSettled/invoke-resolve-error-close.js # TimeoutExceeded: Execution timed out after 5000ms. -built-ins/Promise/allSettled/invoke-resolve-error-reject.js # The promise should not be fulfilled. -built-ins/Promise/allSettled/invoke-resolve-get-error-reject.js # $DONE was never called -built-ins/Promise/allSettled/invoke-resolve-get-error.js # Expected SameValue(«Test262Error: unreachable», «object») to be true -built-ins/Promise/allSettled/invoke-resolve-get-once-multiple-calls.js # Got `resolve` only once for each iterated value Expected SameValue(«0», «1») to be true -built-ins/Promise/allSettled/invoke-resolve-get-once-no-calls.js # Got `resolve` only once for each iterated value Expected SameValue(«0», «1») to be true -built-ins/Promise/allSettled/invoke-resolve-on-promises-every-iteration-of-custom.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -built-ins/Promise/allSettled/invoke-resolve-on-promises-every-iteration-of-promise.js # `then` invoked once for every iterated promise Expected SameValue(«0», «3») to be true -built-ins/Promise/allSettled/invoke-resolve-on-values-every-iteration-of-promise.js # `Promise.resolve` invoked once for every iterated value Expected SameValue(«0», «3») to be true -built-ins/Promise/allSettled/invoke-resolve-return.js # new `then` method invoked exactly once Expected SameValue(«0», «1») to be true -built-ins/Promise/allSettled/invoke-resolve.js # `resolve` invoked once for each iterated value Expected SameValue(«0», «3») to be true -built-ins/Promise/allSettled/invoke-then-error-close.js # TimeoutExceeded: Execution timed out after 5000ms. -built-ins/Promise/allSettled/invoke-then-error-reject.js # $DONE was never called -built-ins/Promise/allSettled/invoke-then-get-error-close.js # TimeoutExceeded: Execution timed out after 5000ms. -built-ins/Promise/allSettled/invoke-then-get-error-reject.js # $DONE was never called -built-ins/Promise/allSettled/invoke-then.js # `then` invoked once for every iterated value Expected SameValue(«0», «3») to be true -built-ins/Promise/allSettled/iter-arg-is-poisoned.js # "The promise should be rejected, but was resolved" -built-ins/Promise/allSettled/new-reject-function.js # p1.then call count Expected SameValue(«0», «1») to be true -built-ins/Promise/allSettled/new-resolve-function.js # p1.then call count Expected SameValue(«0», «1») to be true -built-ins/Promise/allSettled/reject-element-function-extensible.js # Expected true but got false -built-ins/Promise/allSettled/reject-element-function-multiple-calls.js # rejectCallCount after call to allSettled() Expected SameValue(«0», «1») to be true -built-ins/Promise/allSettled/reject-element-function-nonconstructor.js # TypeError: Object.prototype.hasOwnProperty called on incompatible receiver undefined. -built-ins/Promise/allSettled/reject-element-function-property-order.js # TypeError: Object.getOwnPropertyNames cannot convert undefined to an object. -built-ins/Promise/allSettled/resolve-element-function-extensible.js # Expected true but got false -built-ins/Promise/allSettled/resolve-element-function-nonconstructor.js # TypeError: Object.prototype.hasOwnProperty called on incompatible receiver undefined. -built-ins/Promise/allSettled/resolve-element-function-property-order.js # TypeError: Object.getOwnPropertyNames cannot convert undefined to an object. -built-ins/Promise/allSettled/resolve-non-callable.js # Expected true but got false -built-ins/Promise/allSettled/resolve-not-callable-reject-with-typeerror.js # "The promise should not be resolved." -built-ins/Promise/allSettled/resolve-poisoned-then.js # "The promise should not be fulfilled." -built-ins/Promise/allSettled/resolve-throws-iterator-return-null-or-undefined.js # TimeoutExceeded: Execution timed out after 5000ms. -built-ins/Promise/allSettledKeyed/ctx-ctor-throws.js # Expected a Test262Error but got a TypeError -built-ins/Promise/allSettledKeyed/extensible.js # Expected true but got false -built-ins/Promise/allSettledKeyed/invoke-resolve-custom.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Promise/allSettledKeyed/invoke-resolve-get-once.js # TypeError: Promise.allSettledKeyed is not a function. -built-ins/Promise/allSettledKeyed/invoke-resolve-return.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Promise/allSettledKeyed/reject-from-same-thenable.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Promise/allSettledKeyed/resolve-from-same-thenable.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Promise/any/call-reject-element-after-return.js # callCount after call to any() Expected SameValue(«0», «1») to be true -built-ins/Promise/any/call-reject-element-items.js # callCount after call to any() Expected SameValue(«0», «1») to be true -built-ins/Promise/any/capability-reject-throws-no-close.js # Expected SameValue(«2», «5») to be true -built-ins/Promise/any/capability-resolve-throws-no-close.js # Expected SameValue(«2», «5») to be true -built-ins/Promise/any/capability-resolve-throws-reject.js # "Promise incorrectly fulfilled." -built-ins/Promise/any/ctx-ctor-throws.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Promise/any/ctx-ctor.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -built-ins/Promise/any/invoke-resolve-error-reject.js # "The promise should be rejected, but was resolved" -built-ins/Promise/any/invoke-resolve-get-error-reject.js # "The promise should be rejected, but was resolved" -built-ins/Promise/any/invoke-resolve-get-error.js # Expected SameValue(«Test262Error: unreachable», «object») to be true -built-ins/Promise/any/invoke-resolve-get-once-multiple-calls.js # Expected SameValue(«0», «1») to be true -built-ins/Promise/any/invoke-resolve-get-once-no-calls.js # Expected SameValue(«0», «1») to be true -built-ins/Promise/any/invoke-resolve-on-promises-every-iteration-of-custom.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -built-ins/Promise/any/invoke-resolve-on-promises-every-iteration-of-promise.js # `then` invoked once for every iterated promise Expected SameValue(«0», «3») to be true -built-ins/Promise/any/invoke-resolve-on-values-every-iteration-of-custom.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -built-ins/Promise/any/invoke-resolve-on-values-every-iteration-of-promise.js # `Promise.resolve` invoked once for every iterated value Expected SameValue(«0», «3») to be true -built-ins/Promise/any/invoke-resolve-return.js # new `then` method invoked exactly once Expected SameValue(«0», «1») to be true -built-ins/Promise/any/invoke-then-error-reject.js # "The promise should be rejected, but was resolved" -built-ins/Promise/any/invoke-then-get-error-reject.js # "The promise should be rejected, but was resolved" -built-ins/Promise/any/invoke-then-on-promises-every-iteration.js # `then` invoked once for every iterated value Expected SameValue(«0», «3») to be true -built-ins/Promise/any/invoke-then.js # $DONE was never called -built-ins/Promise/any/new-reject-function.js # p1.then call count Expected SameValue(«0», «1») to be true -built-ins/Promise/any/reject-element-function-extensible.js # Expected true but got false -built-ins/Promise/any/reject-element-function-nonconstructor.js # TypeError: Object.prototype.hasOwnProperty called on incompatible receiver undefined. -built-ins/Promise/any/reject-element-function-property-order.js # TypeError: Object.getOwnPropertyNames cannot convert undefined to an object. -built-ins/Promise/any/reject-from-same-thenable.js # TypeError: p1OnRejected is not a function. -built-ins/Promise/any/resolve-before-loop-exit-from-same.js # TypeError: p1OnRejected is not a function. -built-ins/Promise/any/resolve-before-loop-exit.js # callCount after call to any() Expected SameValue(«0», «1») to be true -built-ins/Promise/any/resolve-non-callable.js # Expected true but got false -built-ins/Promise/any/resolve-not-callable-reject-with-typeerror.js # "The promise should not be resolved." -built-ins/Promise/any/resolve-throws-iterator-return-null-or-undefined.js # TimeoutExceeded: Execution timed out after 5000ms. -built-ins/Promise/executor-function-extensible.js # Expected true but got false -built-ins/Promise/executor-function-property-order.js # TypeError: Object.getOwnPropertyNames cannot convert undefined to an object. -built-ins/Promise/prototype/catch/invokes-then.js # TypeError: Promise.prototype.catch called on incompatible receiver a data object. -built-ins/Promise/prototype/catch/this-value-then-poisoned.js # Expected a Test262Error but got a TypeError -built-ins/Promise/prototype/catch/this-value-then-throws.js # Expected a Test262Error but got a TypeError -built-ins/Promise/prototype/finally/invokes-then-with-non-function.js # Invokes `then` method exactly once Expected SameValue(«0», «1») to be true -built-ins/Promise/prototype/finally/rejected-observable-then-calls-PromiseResolve.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -built-ins/Promise/prototype/finally/resolved-observable-then-calls-PromiseResolve.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -built-ins/Promise/prototype/finally/species-constructor.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -built-ins/Promise/prototype/finally/subclass-reject-count.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -built-ins/Promise/prototype/finally/subclass-resolve-count.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -built-ins/Promise/prototype/finally/this-value-then-poisoned.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Promise/prototype/finally/this-value-then-throws.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Promise/prototype/finally/this-value-thenable.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/Promise/prototype/then/S25.4.5.3_A2.1_T2.js # TypeError: ZeroArgConstructor is not a constructor: only classes can be constructed with new. Use a -built-ins/Promise/prototype/then/ctor-access-count.js # "Expected constructor access count: 1. Actual: 0" -built-ins/Promise/prototype/then/ctor-null.js # Expected a TypeError to be thrown but no exception was thrown at all -built-ins/Promise/prototype/then/ctor-poisoned.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Promise/prototype/then/deferred-is-resolved-value.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -built-ins/Promise/race/S25.4.4.3_A3.1_T1.js # Expected a TypeError to be thrown but no exception was thrown at all -built-ins/Promise/race/S25.4.4.3_A3.1_T2.js # Expected a TypeError to be thrown but no exception was thrown at all -built-ins/Promise/race/S25.4.4.3_A5.1_T1.js # Never settles. -built-ins/Promise/race/ctx-ctor-throws.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Promise/race/ctx-ctor.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -built-ins/Promise/race/invoke-resolve-error-close.js # TimeoutExceeded: Execution timed out after 5000ms. -built-ins/Promise/race/invoke-resolve-error-reject.js # $DONE was never called -built-ins/Promise/race/invoke-resolve-get-error-reject.js # $DONE was never called -built-ins/Promise/race/invoke-resolve-get-error.js # Expected SameValue(«Test262Error: unreachable», «object») to be true -built-ins/Promise/race/invoke-resolve-get-once-multiple-calls.js # Got `resolve` only once for each iterated value Expected SameValue(«0», «1») to be true -built-ins/Promise/race/invoke-resolve-get-once-no-calls.js # Got `resolve` only once for each iterated value Expected SameValue(«0», «1») to be true -built-ins/Promise/race/invoke-resolve-on-promises-every-iteration-of-custom.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -built-ins/Promise/race/invoke-resolve-on-promises-every-iteration-of-promise.js # `then` invoked once for every item in iterable arg Expected SameValue(«0», «3») to be true -built-ins/Promise/race/invoke-resolve-on-values-every-iteration-of-promise.js # `Promise.resolve` invoked once for every item in iterable arg Expected SameValue(«0», «3») to be tru -built-ins/Promise/race/invoke-resolve-return.js # new `then` method invoked exactly once Expected SameValue(«0», «1») to be true -built-ins/Promise/race/invoke-resolve.js # `resolve` invoked once for each iterated value Expected SameValue(«0», «3») to be true -built-ins/Promise/race/invoke-then-error-close.js # TimeoutExceeded: Execution timed out after 5000ms. -built-ins/Promise/race/invoke-then-error-reject.js # $DONE was never called -built-ins/Promise/race/invoke-then-get-error-close.js # TimeoutExceeded: Execution timed out after 5000ms. -built-ins/Promise/race/invoke-then-get-error-reject.js # $DONE was never called -built-ins/Promise/race/invoke-then.js # `then` invoked once for every iterated value Expected SameValue(«0», «3») to be true -built-ins/Promise/race/resolve-non-callable.js # Expected true but got false -built-ins/Promise/race/resolve-prms-cstm-then.js # "The promise should be resolved with the correct value." -built-ins/Promise/race/resolve-self.js # TypeError: resolve is not a function. -built-ins/Promise/race/resolve-throws-iterator-return-null-or-undefined.js # TimeoutExceeded: Execution timed out after 5000ms. -built-ins/Promise/race/same-reject-function.js # p1.then call count Expected SameValue(«0», «1») to be true -built-ins/Promise/race/same-resolve-function.js # p1.then call count Expected SameValue(«0», «1») to be true -built-ins/Promise/reject/S25.4.4.4_A3.1_T1.js # Expected a TypeError to be thrown but no exception was thrown at all -built-ins/Promise/reject/capability-invocation-error.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Promise/reject/capability-invocation.js # Expected SameValue(«"undefined"», «"object"») to be true -built-ins/Promise/reject/ctx-ctor-throws.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Promise/reject/ctx-ctor.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -built-ins/Promise/resolve/arg-uniq-ctor.js # Expected SameValue(«true», «false») to be true -built-ins/Promise/resolve/capability-invocation-error.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Promise/resolve/ctx-ctor-throws.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Promise/resolve/ctx-ctor.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -built-ins/Promise/resolve/resolve-from-promise-capability.js # callCount after call to resolve() Expected SameValue(«0», «1») to be true -built-ins/Promise/resolve/resolve-self.js # $DONE was never called -built-ins/Promise/try/ctx-ctor-throws.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/Promise/try/ctx-ctor.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -built-ins/Promise/withResolvers/ctx-ctor.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -built-ins/Promise/withResolvers/resolvers.js # Expected SameValue(«"resolve"», «""») to be true -built-ins/RegExp/S15.10.3.1_A1_T1.js # The value of __instance.indicator is expected to be 1 Expected SameValue(«undefined», «1») to be tru -built-ins/RegExp/S15.10.3.1_A1_T2.js # The value of __instance.indicator is expected to be 1 Expected SameValue(«undefined», «1») to be tru -built-ins/RegExp/S15.10.3.1_A1_T3.js # The value of __instance.indicator is expected to be 1 Expected SameValue(«undefined», «1») to be tru -built-ins/RegExp/S15.10.3.1_A1_T4.js # The value of __instance.indicator is expected to be 1 Expected SameValue(«undefined», «1») to be tru -built-ins/RegExp/S15.10.3.1_A1_T5.js # The value of __instance.indicator is expected to be 1 Expected SameValue(«undefined», «1») to be tru -built-ins/RegExp/S15.10.3.1_A3_T2.js # The value of __instance.source is expected to be "[a-c]*" Expected SameValue(«"[object Object]"», «" -built-ins/RegExp/S15.10.4.1_A8_T12.js # The value of e is expected to be "invalof" Expected SameValue(«SyntaxError: RegExp flags must be a s -built-ins/RegExp/S15.10.4.1_A8_T13.js # The value of e is expected to be "intostr" Expected SameValue(«SyntaxError: RegExp flags must be a s -built-ins/RegExp/S15.10.4.1_A8_T4.js # SyntaxError: RegExp flags must be a string of flag characters (e.g. "g", "gi"), not object. -built-ins/RegExp/S15.10.4.1_A8_T6.js # The value of e is expected to be "intostr" Expected SameValue(«Test262Error: #1.1: new RegExp({toStr -built-ins/RegExp/S15.10.4.1_A8_T7.js # The value of e is expected to be "invalof" Expected SameValue(«Test262Error: #1.1: new RegExp({toStr -built-ins/RegExp/S15.10.4.1_A8_T8.js # The value of e is expected to be "intostr" Expected SameValue(«SyntaxError: new RegExp(...) received -built-ins/RegExp/named-groups/groups-object-subclass-sans.js # TypeError: Extending the built-in RegExp is not supported. Only classes and Error types can be exten -built-ins/RegExp/named-groups/groups-object-subclass.js # TypeError: Extending the built-in RegExp is not supported. Only classes and Error types can be exten -built-ins/RegExp/named-groups/unicode-match.js # Actual object and expected object should have the same contents. -built-ins/RegExp/prototype/dotAll/this-val-regexp-prototype.js # TypeError: RegExp.prototype.dotAll called on incompatible receiver a data object. -built-ins/RegExp/prototype/exec/S15.10.6.2_A1_T12.js # The result of evaluating (__executed instanceof Array) is expected to be true Expected SameValue(«fa -built-ins/RegExp/prototype/exec/S15.10.6.2_A1_T15.js # The result of evaluating (__executed instanceof Array) is expected to be true Expected SameValue(«fa -built-ins/RegExp/prototype/exec/S15.10.6.2_A1_T4.js # The result of evaluating (__executed instanceof Array) is expected to be true Expected SameValue(«fa -built-ins/RegExp/prototype/exec/S15.10.6.2_A1_T5.js # The value of __executed.input is expected to equal the value of __expected.input Expected SameValue( -built-ins/RegExp/prototype/exec/S15.10.6.2_A1_T7.js # The value of e is expected to be "intostr" Expected SameValue(«Test262Error: #1.1: /[a-z]/.exec({toS -built-ins/RegExp/prototype/exec/S15.10.6.2_A1_T8.js # The value of e is expected to be "invalof" Expected SameValue(«Test262Error: #1.1: /[a-z]/.exec({toS -built-ins/RegExp/prototype/exec/S15.10.6.2_A4_T10.js # The value of __executed.index is expected to equal the value of __expected.index Expected SameValue( -built-ins/RegExp/prototype/exec/S15.10.6.2_A4_T11.js # The value of e is expected to be "intoint" Expected SameValue(«Test262Error: #5.1: __obj = {valueOf: -built-ins/RegExp/prototype/exec/S15.10.6.2_A4_T12.js # The value of __executed.index is expected to equal the value of __expected.index Expected SameValue( -built-ins/RegExp/prototype/exec/failure-g-lastindex-reset.js # Expected SameValue(«["a"]», «null») to be true -built-ins/RegExp/prototype/exec/failure-lastindex-access.js # Expected SameValue(«NaN», «object») to be true -built-ins/RegExp/prototype/exec/success-g-lastindex-no-access.js # Expected SameValue(«0», «1») to be true -built-ins/RegExp/prototype/exec/success-lastindex-access.js # Expected SameValue(«NaN», «object») to be true -built-ins/RegExp/prototype/exec/y-fail-lastindex-no-write.js # Expected a TypeError to be thrown but no exception was thrown at all -built-ins/RegExp/prototype/flags/get-order.js # TypeError: RegExp.prototype.flags called on incompatible receiver a data object. -built-ins/RegExp/prototype/flags/rethrow.js # Let hasIndices be ToBoolean(? Get(R, "hasIndices")) Expected a Test262Error but got a TypeError -built-ins/RegExp/prototype/flags/this-val-regexp-prototype.js # TypeError: RegExp.prototype.flags called on incompatible receiver a data object. -built-ins/RegExp/prototype/global/this-val-regexp-prototype.js # TypeError: RegExp.prototype.global called on incompatible receiver a data object. -built-ins/RegExp/prototype/hasIndices/this-val-regexp-prototype.js # TypeError: RegExp.prototype.hasIndices called on incompatible receiver a data object. -built-ins/RegExp/prototype/ignoreCase/this-val-regexp-prototype.js # TypeError: RegExp.prototype.ignoreCase called on incompatible receiver a data object. -built-ins/RegExp/prototype/multiline/this-val-regexp-prototype.js # TypeError: RegExp.prototype.multiline called on incompatible receiver a data object. -built-ins/RegExp/prototype/source/this-val-regexp-prototype.js # TypeError: RegExp.prototype.source called on incompatible receiver a data object. -built-ins/RegExp/prototype/sticky/this-val-regexp-prototype.js # TypeError: RegExp.prototype.sticky called on incompatible receiver a data object. -built-ins/RegExp/prototype/test/S15.10.6.3_A1_T7.js # The value of e is expected to be "intostr" Expected SameValue(«Test262Error: #1.1: /[a-z]/.test({toS -built-ins/RegExp/prototype/test/S15.10.6.3_A1_T8.js # The value of e is expected to be "invalof" Expected SameValue(«Test262Error: #1.1: /[a-z]/.test({toS -built-ins/RegExp/prototype/test/y-fail-lastindex-no-write.js # Expected a TypeError to be thrown but no exception was thrown at all -built-ins/RegExp/prototype/toString/called-as-function.js # TypeError: Object.defineProperty called on non-object -built-ins/RegExp/prototype/unicode/this-val-regexp-prototype.js # TypeError: RegExp.prototype.unicode called on incompatible receiver a data object. -built-ins/RegExp/prototype/unicodeSets/this-val-regexp-prototype.js # TypeError: RegExp.prototype.unicodeSets called on incompatible receiver a data object. -built-ins/Set/prototype/difference/size-is-a-number.js # TypeError: BigInt literals are not supported. -built-ins/Set/prototype/difference/subclass-receiver-methods.js # TypeError: Extending the built-in Set is not supported. Only classes and Error types can be extended -built-ins/Set/prototype/difference/subclass.js # TypeError: Extending the built-in Set is not supported. Only classes and Error types can be extended -built-ins/Set/prototype/intersection/size-is-a-number.js # TypeError: BigInt literals are not supported. -built-ins/Set/prototype/intersection/subclass-receiver-methods.js # TypeError: Extending the built-in Set is not supported. Only classes and Error types can be extended -built-ins/Set/prototype/intersection/subclass.js # TypeError: Extending the built-in Set is not supported. Only classes and Error types can be extended -built-ins/Set/prototype/isDisjointFrom/size-is-a-number.js # TypeError: BigInt literals are not supported. -built-ins/Set/prototype/isDisjointFrom/subclass-receiver-methods.js # TypeError: Extending the built-in Set is not supported. Only classes and Error types can be extended -built-ins/Set/prototype/isSubsetOf/size-is-a-number.js # TypeError: BigInt literals are not supported. -built-ins/Set/prototype/isSubsetOf/subclass-receiver-methods.js # TypeError: Extending the built-in Set is not supported. Only classes and Error types can be extended -built-ins/Set/prototype/isSupersetOf/size-is-a-number.js # TypeError: BigInt literals are not supported. -built-ins/Set/prototype/isSupersetOf/subclass-receiver-methods.js # TypeError: Extending the built-in Set is not supported. Only classes and Error types can be extended -built-ins/Set/prototype/keys/keys.js # The value of `Set.prototype.keys` is `Set.prototype.values` Expected SameValue(«keys», «values») to -built-ins/Set/prototype/symmetricDifference/size-is-a-number.js # TypeError: BigInt literals are not supported. -built-ins/Set/prototype/symmetricDifference/subclass-receiver-methods.js # TypeError: Extending the built-in Set is not supported. Only classes and Error types can be extended -built-ins/Set/prototype/symmetricDifference/subclass.js # TypeError: Extending the built-in Set is not supported. Only classes and Error types can be extended -built-ins/Set/prototype/union/size-is-a-number.js # TypeError: BigInt literals are not supported. -built-ins/Set/prototype/union/subclass-receiver-methods.js # TypeError: Extending the built-in Set is not supported. Only classes and Error types can be extended -built-ins/Set/prototype/union/subclass.js # TypeError: Extending the built-in Set is not supported. Only classes and Error types can be extended -built-ins/Set/set-get-add-method-failure.js # Expected a MyError to be thrown but no exception was thrown at all -built-ins/Set/set-iterable-calls-add.js # `Set.prototype.add` called twice. Expected SameValue(«0», «2») to be true -built-ins/Set/set-iterable-throws-when-add-is-not-callable.js # Expected a TypeError to be thrown but no exception was thrown at all -built-ins/Set/set-iterator-close-after-add-failure.js # TimeoutExceeded: Execution timed out after 5000ms. -built-ins/Set/set-iterator-next-failure.js # Expected a MyError but got a TypeError -built-ins/Set/set-iterator-value-failure.js # Expected a MyError but got a TypeError -built-ins/String/S15.5.1.1_A1_T9.js # #2: toString=function(){return "__THIS__";}; __str = String(this); __str === "__THIS__". Actual: __s -built-ins/String/fromCharCode/S9.7_A3.1_T4.js # #1: var object = {valueOf: function() {return 1}}; String.fromCharCode(object).charCodeAt(0) === 1. -built-ins/String/fromCharCode/touint16-tonumber-throws-valueof.js # ToNumber throws when its argument's ToPrimitive step calls a throwing valueOf, and String.fromCharCo -built-ins/String/fromCodePoint/argument-not-coercible.js # Expected a Test262Error but got a RangeError -built-ins/String/fromCodePoint/to-number-conversions.js # RangeError: Arguments contain a value that is out of range of code points -built-ins/String/prototype/S15.5.4_A1.js # #1: delete String.prototype.toString; String.prototype.toString() === "[object "+"String"+"]". Actua -built-ins/String/prototype/S15.5.4_A2.js # TimeoutExceeded: Execution timed out after 5000ms. -built-ins/String/prototype/S15.5.4_A3.js # #2: delete String.prototype.toString; String.prototype.toString() == "[object "+"String"+"]". Actual -built-ins/String/prototype/Symbol.iterator/this-val-to-str-err.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/String/prototype/at/index-non-numeric-argument-tointeger.js # TypeError: String.at expects argument 1 to be a data value. -built-ins/String/prototype/charAt/S15.5.4.4_A2.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/String/prototype/charCodeAt/S15.5.4.5_A2.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/String/prototype/constructor/S15.5.4.1_A1_T2.js # TypeError: new __constr(...) is not supported; call __constr(...) without new instead. -built-ins/String/prototype/repeat/count-coerced-to-zero-returns-empty-string.js # RangeError: String.repeat expects a finite non-negative count. -built-ins/String/prototype/slice/S15.5.4.13_A3_T4.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/String/prototype/split/instance-is-math.js # The value of __split[0] is "[object Math]" Expected SameValue(«"[object Object]"», «"[object Math]"» -built-ins/String/prototype/split/separator-tostring-error.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/String/prototype/split/transferred-to-custom.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/String/prototype/substring/S15.5.4.15_A3_T10.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/String/prototype/trim/15.5.4.20-2-43.js # TypeError: Con is not a constructor: only classes can be constructed with new. Use a class, or call -built-ins/ThrowTypeError/extensible.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/ThrowTypeError/forbidden-arguments.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/ThrowTypeError/forbidden-caller.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/ThrowTypeError/frozen.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/ThrowTypeError/is-function.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/ThrowTypeError/property-order.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/ThrowTypeError/throws-type-error.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/ThrowTypeError/unique-per-realm-non-simple.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/ThrowTypeError/unique-per-realm-unmapped-args.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/WeakMap/get-set-method-failure.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/WeakMap/iterable-with-object-keys.js # Called WeakMap#set for each object Expected SameValue(«0», «2») to be true -built-ins/WeakMap/iterator-close-after-set-failure.js # Expected a Test262Error but got a TypeError -built-ins/WeakMap/iterator-item-first-entry-returns-abrupt.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/WeakMap/iterator-item-second-entry-returns-abrupt.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -built-ins/WeakMap/set-not-callable-throws.js # Expected a TypeError to be thrown but no exception was thrown at all -built-ins/WeakSet/add-not-callable-throws.js # Expected a TypeError to be thrown but no exception was thrown at all -built-ins/WeakSet/get-add-method-failure.js # Expected a Test262Error to be thrown but no exception was thrown at all -built-ins/WeakSet/iterable-with-object-values.js # Called WeakSet#add for each object Expected SameValue(«0», «2») to be true -built-ins/WeakSet/iterator-close-after-add-failure.js # Expected a Test262Error but got a TypeError -built-ins/decodeURI/S15.1.3.1_A5.5.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/decodeURI/S15.1.3.1_A6_T1.js # #2: var object = {valueOf: function() {return ""}, toString: function() {return "%5E"}}; decodeURI(o -built-ins/decodeURIComponent/S15.1.3.2_A5.5.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/decodeURIComponent/S15.1.3.2_A6_T1.js # #2: var object = {valueOf: function() {return ""}, toString: function() {return "%5E"}}; decodeURICo -built-ins/encodeURI/S15.1.3.3_A5.5.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/encodeURI/S15.1.3.3_A6_T1.js # #2: var object = {valueOf: function() {return ""}, toString: function() {return "^"}}; encodeURI(obj -built-ins/encodeURIComponent/S15.1.3.4_A5.5.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/encodeURIComponent/S15.1.3.4_A6_T1.js # #2: var object = {valueOf: function() {return ""}, toString: function() {return "^"}}; encodeURIComp -built-ins/global/10.2.1.1.3-4-22.js # TypeError: Cannot assign to constant '…'. -built-ins/global/10.2.1.1.3-4-27.js # TypeError: Cannot assign to constant '…'. -built-ins/parseFloat/S15.1.2.3_A7.5.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/parseInt/S15.1.2.2_A9.5.js # TypeError: Cannot read properties of undefined (reading '…'). -built-ins/undefined/15.1.1.3-0.js # TypeError: Object.getOwnPropertyDescriptor cannot convert undefined to an object. -built-ins/undefined/15.1.1.3-2.js # TypeError: Cannot read properties of undefined (reading '…'). -language/arguments-object/10.6-13-c-1-s.js # Expected a TypeError to be thrown but no exception was thrown at all -language/arguments-object/10.6-13-c-2-s.js # Expected SameValue(«undefined», «undefined») to be false -language/arguments-object/10.6-13-c-3-s.js # TypeError: Cannot read properties of undefined (reading '…'). -language/arguments-object/10.6-14-c-4-s.js # Expected a TypeError to be thrown but no exception was thrown at all -language/arguments-object/10.6-2gs.js # Expected a TypeError to be thrown but no exception was thrown at all -language/arguments-object/S10.6_A3_T1.js # #1: arguments object doesn't exists -language/comments/S7.4_A1_T1.js # TypeError: Cannot read properties of undefined (reading '…'). -language/comments/S7.4_A2_T1.js # TypeError: Cannot read properties of undefined (reading '…'). -language/expressions/addition/S11.6.1_A2.2_T3.js # TypeError: Binary operators require data values. -language/expressions/addition/S11.6.1_A3.2_T1.2.js # TypeError: Binary operators require data values. -language/expressions/array/11.1.4_4-5-1.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -language/expressions/array/11.1.4_5-6-1.js # TypeError: Array elements share their attributes; only writable, enumerable and configurable equal t -language/expressions/arrow-function/dstr/ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/arrow-function/dstr/ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/arrow-function/dstr/dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/arrow-function/dstr/dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/arrow-function/lexical-super-call-from-within-constructor.js # Expected a ReferenceError but got a SyntaxError -language/expressions/arrow-function/lexical-supercall-from-immediately-invoked-arrow.js # UnsupportedSyntax: SyntaxError: super() inside an arrow function is not supported. Call super() dire -language/expressions/arrow-function/lexical-this.js # TypeError: F is not a constructor: only classes can be constructed with new. Use a class, or call it -language/expressions/assignment/8.14.4-8-b_2.js # TypeError: Object.defineProperty called on non-object -language/expressions/assignment/destructuring/default-expr-throws-iterator-return-get-throws.js # Expected a MyError but got a TypeError -language/expressions/assignment/destructuring/iterator-destructuring-property-reference-target-evaluation-order.js # Actual ["source", "iterator", "iterator-step", "iterator-done", "target", "target-key", "target-key- -language/expressions/assignment/destructuring/keyed-destructuring-property-reference-target-evaluation-order.js # Actual ["source", "source-key", "source-key-tostring", "get", "target", "target-key", "target-key-to -language/expressions/assignment/destructuring/target-assign-throws-iterator-return-get-throws.js # Expected a MyError but got a TypeError -language/expressions/assignment/dstr/array-elem-iter-rtrn-close-err.js # TypeError: Iterator next must be a function. -language/expressions/assignment/dstr/array-elem-iter-thrw-close-err.js # Expected SameValue(«1», «0») to be true -language/expressions/assignment/dstr/array-elem-iter-thrw-close.js # Expected SameValue(«1», «0») to be true -language/expressions/assignment/dstr/array-elem-trlg-iter-list-thrw-close-err.js # Expected SameValue(«1», «0») to be true -language/expressions/assignment/dstr/array-elem-trlg-iter-list-thrw-close.js # Expected SameValue(«1», «0») to be true -language/expressions/assignment/dstr/array-elem-trlg-iter-rest-rtrn-close-err.js # Expected a Test262Error to be thrown but no exception was thrown at all -language/expressions/assignment/dstr/array-elem-trlg-iter-rest-rtrn-close-null.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/assignment/dstr/array-elem-trlg-iter-rest-rtrn-close.js # Expected SameValue(«11», «1») to be true -language/expressions/assignment/dstr/array-elem-trlg-iter-rest-thrw-close-err.js # Expected SameValue(«11», «1») to be true -language/expressions/assignment/dstr/array-elem-trlg-iter-rest-thrw-close.js # Expected SameValue(«11», «1») to be true -language/expressions/assignment/dstr/array-rest-iter-rtrn-close-err.js # TypeError: Iterator next must be a function. -language/expressions/assignment/dstr/array-rest-iter-rtrn-close-null.js # TypeError: Iterator next must be a function. -language/expressions/assignment/dstr/array-rest-iter-rtrn-close.js # Test262Error -language/expressions/assignment/dstr/array-rest-iter-thrw-close-err.js # Expected SameValue(«11», «0») to be true -language/expressions/assignment/dstr/array-rest-iter-thrw-close.js # Expected SameValue(«11», «0») to be true -language/expressions/assignment/dstr/array-rest-lref-err.js # Expected SameValue(«1», «0») to be true -language/expressions/assignment/target-member-computed-reference-null.js # Expected a DummyError but got a TypeError -language/expressions/assignment/target-member-computed-reference-undefined.js # Expected a DummyError but got a TypeError -language/expressions/assignment/target-member-computed-reference.js # Expected a DummyError but got a TypeError -language/expressions/assignment/target-member-identifier-reference-null.js # Expected SameValue(«0», «1») to be true -language/expressions/assignment/target-member-identifier-reference-undefined.js # Expected SameValue(«0», «1») to be true -language/expressions/assignment/target-super-computed-reference.js # Expected a DummyError but got a TypeError -language/expressions/assignmenttargettype/simple-basic-identifierreference-await.js # SyntaxError: Unexpected token. Code must be plain JavaScript written as a program body. -language/expressions/async-generator/dstr/ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/async-generator/dstr/ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/async-generator/dstr/dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/async-generator/dstr/dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/async-generator/dstr/named-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/async-generator/dstr/named-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/async-generator/dstr/named-dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/async-generator/dstr/named-dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/await/await-in-global.js # SyntaxError: Unexpected token. Code must be plain JavaScript written as a program body. -language/expressions/await/await-in-nested-function.js # SyntaxError: Unexpected token. Code must be plain JavaScript written as a program body. -language/expressions/await/await-in-nested-generator.js # SyntaxError: Unexpected token. Code must be plain JavaScript written as a program body. -language/expressions/bitwise-and/S11.10.1_A3_T1.5.js # TypeError: Binary operators require data values. -language/expressions/bitwise-not/S11.4.8_A3_T5.js # TypeError: Unary operators require data values. -language/expressions/bitwise-or/S11.10.3_A3_T1.5.js # TypeError: Binary operators require data values. -language/expressions/bitwise-xor/S11.10.2_A3_T1.5.js # TypeError: Binary operators require data values. -language/expressions/class/dstr/async-gen-meth-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/class/dstr/async-gen-meth-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/class/dstr/async-gen-meth-dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/class/dstr/async-gen-meth-dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/class/dstr/async-gen-meth-static-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/class/dstr/async-gen-meth-static-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/class/dstr/async-gen-meth-static-dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/class/dstr/async-gen-meth-static-dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/class/dstr/gen-meth-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/class/dstr/gen-meth-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/class/dstr/gen-meth-dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/class/dstr/gen-meth-dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/class/dstr/gen-meth-static-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/class/dstr/gen-meth-static-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/class/dstr/gen-meth-static-dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/class/dstr/gen-meth-static-dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/class/dstr/meth-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/class/dstr/meth-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/class/dstr/meth-dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/class/dstr/meth-dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/class/dstr/meth-static-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/class/dstr/meth-static-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/class/dstr/meth-static-dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/class/dstr/meth-static-dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/class/elements/fields-run-once-on-double-super.js # Expected a ReferenceError but got a SyntaxError -language/expressions/class/scope-name-lex-open-heritage.js # TypeError: Class extends value a function is not a constructor or null. -language/expressions/class/subclass-builtins/subclass-Array.js # TypeError: Extending the built-in Array is not supported. Only classes and Error types can be extend -language/expressions/class/subclass-builtins/subclass-Boolean.js # TypeError: Class extends value a function is not a constructor or null. -language/expressions/class/subclass-builtins/subclass-Date.js # TypeError: Extending the built-in Date is not supported. Only classes and Error types can be extende -language/expressions/class/subclass-builtins/subclass-Map.js # TypeError: Extending the built-in Map is not supported. Only classes and Error types can be extended -language/expressions/class/subclass-builtins/subclass-Number.js # TypeError: Class extends value a function is not a constructor or null. -language/expressions/class/subclass-builtins/subclass-Object.js # TypeError: Extending the built-in Object is not supported. Only classes and Error types can be exten -language/expressions/class/subclass-builtins/subclass-Promise.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -language/expressions/class/subclass-builtins/subclass-RegExp.js # TypeError: Extending the built-in RegExp is not supported. Only classes and Error types can be exten -language/expressions/class/subclass-builtins/subclass-Set.js # TypeError: Extending the built-in Set is not supported. Only classes and Error types can be extended -language/expressions/class/subclass-builtins/subclass-String.js # TypeError: Class extends value a function is not a constructor or null. -language/expressions/class/subclass-builtins/subclass-WeakMap.js # TypeError: Extending the built-in WeakMap is not supported. Only classes and Error types can be exte -language/expressions/class/subclass-builtins/subclass-WeakSet.js # TypeError: Extending the built-in WeakSet is not supported. Only classes and Error types can be exte -language/expressions/compound-assignment/S11.13.2_A7.10_T1.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.10_T2.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.10_T3.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.11_T1.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.11_T2.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.11_T3.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.1_T1.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.1_T2.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.1_T3.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.2_T1.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.2_T2.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.2_T3.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.3_T1.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.3_T2.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.3_T3.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.4_T1.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.4_T2.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.4_T3.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.5_T1.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.5_T2.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.5_T3.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.6_T1.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.6_T2.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.6_T3.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.7_T1.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.7_T2.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.7_T3.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.8_T1.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.8_T2.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.8_T3.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.9_T1.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.9_T2.js # Expected a DummyError but got a TypeError -language/expressions/compound-assignment/S11.13.2_A7.9_T3.js # Expected a DummyError but got a TypeError -language/expressions/delete/S11.4.1_A2.2_T2.js # TypeError: MyFunction is not a constructor: only classes can be constructed with new. Use a class, o -language/expressions/delete/S11.4.1_A2.2_T3.js # TypeError: Cannot read properties of undefined (reading '…'). -language/expressions/delete/S11.4.1_A3.2_T3.js # TypeError: MyFunction is not a constructor: only classes can be constructed with new. Use a class, o -language/expressions/delete/S11.4.1_A3.3_T3.js # TypeError: MyFunction is not a constructor: only classes can be constructed with new. Use a class, o -language/expressions/delete/S8.12.7_A2_T2.js # TypeError: Palette is not a constructor: only classes can be constructed with new. Use a class, or c -language/expressions/delete/non-reference-return-true.js # TypeError: Only data fields may be deleted. -language/expressions/delete/super-property-topropertykey.js # Expected a ReferenceError but got a SyntaxError -language/expressions/delete/super-property.js # TypeError: Extending the built-in Object is not supported. Only classes and Error types can be exten -language/expressions/division/S11.5.2_A3_T1.5.js # TypeError: Binary operators require data values. -language/expressions/function/dstr/ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/function/dstr/ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/function/dstr/dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/function/dstr/dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/generators/default-proto.js # Expected SameValue(«object», «undefined») to be true -language/expressions/generators/dstr/ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/generators/dstr/ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/generators/dstr/dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/generators/dstr/dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/generators/prototype-relation-to-function.js # Expected SameValue(«object», «») to be true -language/expressions/greater-than-or-equal/S11.8.4_A3.2_T1.2.js # TypeError: Binary operators require data values. -language/expressions/greater-than/S11.8.2_A3.2_T1.2.js # TypeError: Binary operators require data values. -language/expressions/in/S8.12.6_A2_T2.js # TypeError: Robin is not a constructor: only classes can be constructed with new. Use a class, or cal -language/expressions/left-shift/S11.7.1_A3_T1.5.js # TypeError: Binary operators require data values. -language/expressions/less-than-or-equal/S11.8.3_A3.2_T1.2.js # TypeError: Binary operators require data values. -language/expressions/less-than/S11.8.1_A3.2_T1.2.js # TypeError: Binary operators require data values. -language/expressions/logical-assignment/lgcl-and-assignment-operator-lhs-before-rhs.js # Expected a DummyError but got a TypeError -language/expressions/logical-assignment/lgcl-nullish-assignment-operator-lhs-before-rhs.js # Expected a DummyError but got a TypeError -language/expressions/logical-assignment/lgcl-or-assignment-operator-lhs-before-rhs.js # Expected a DummyError but got a TypeError -language/expressions/modulus/S11.5.3_A3_T1.5.js # TypeError: Binary operators require data values. -language/expressions/multiplication/S11.5.1_A3_T1.5.js # TypeError: Binary operators require data values. -language/expressions/new/ctorExpr-fn-ref-before-args-eval-fn-wrapup.js # TypeError: x is not a constructor: only classes can be constructed with new. Use a class, or call it -language/expressions/new/ctorExpr-fn-ref-before-args-eval.js # TypeError: x is not a constructor: only classes can be constructed with new. Use a class, or call it -language/expressions/new/ctorExpr-isCtor-after-args-eval-fn-wrapup.js # arguments evaluated before checking valid ctor Expected SameValue(«undefined», «39») to be true -language/expressions/new/ctorExpr-isCtor-after-args-eval.js # Expected SameValue(«object», «Array») to be true -language/expressions/new/spread-err-mult-err-expr-throws.js # Expected a Test262Error but got a TypeError -language/expressions/new/spread-err-mult-err-itr-get-call.js # Expected a Test262Error but got a TypeError -language/expressions/new/spread-err-mult-err-itr-get-get.js # Expected a Test262Error but got a TypeError -language/expressions/new/spread-err-mult-err-itr-step.js # Expected a Test262Error but got a TypeError -language/expressions/new/spread-err-mult-err-itr-value.js # Expected a Test262Error but got a TypeError -language/expressions/new/spread-err-mult-err-obj-unresolvable.js # Expected a ReferenceError but got a TypeError -language/expressions/new/spread-err-mult-err-unresolvable.js # Expected a ReferenceError but got a TypeError -language/expressions/new/spread-err-sngl-err-expr-throws.js # Expected a Test262Error but got a TypeError -language/expressions/new/spread-err-sngl-err-itr-get-call.js # Expected a Test262Error but got a TypeError -language/expressions/new/spread-err-sngl-err-itr-get-get.js # Expected a Test262Error but got a TypeError -language/expressions/new/spread-err-sngl-err-itr-step.js # Expected a Test262Error but got a TypeError -language/expressions/new/spread-err-sngl-err-itr-value.js # Expected a Test262Error but got a TypeError -language/expressions/new/spread-err-sngl-err-obj-unresolvable.js # Expected a ReferenceError but got a TypeError -language/expressions/new/spread-err-sngl-err-unresolvable.js # Expected a ReferenceError but got a TypeError -language/expressions/new/spread-mult-empty.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/expressions/new/spread-mult-expr.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/expressions/new/spread-mult-iter.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/expressions/new/spread-mult-literal.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/expressions/new/spread-mult-obj-null.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/expressions/new/spread-mult-obj-undefined.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/expressions/new/spread-obj-getter-init.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/expressions/new/spread-obj-manipulate-outter-obj-in-getter.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/expressions/new/spread-obj-mult-spread-getter.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/expressions/new/spread-obj-mult-spread.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/expressions/new/spread-obj-null.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/expressions/new/spread-obj-overrides-prev-properties.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/expressions/new/spread-obj-skip-non-enumerable.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/expressions/new/spread-obj-undefined.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/expressions/new/spread-sngl-empty.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/expressions/new/spread-sngl-expr.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/expressions/new/spread-sngl-iter.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/expressions/new/spread-sngl-literal.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/expressions/object/__proto__-duplicate-computed.js # prototype is defined Expected SameValue(«object», «object») to be true -language/expressions/object/__proto__-poisoned-object-prototype.js # Expected true but got false -language/expressions/object/__proto__-value-null.js # Expected SameValue(«object», «null») to be true -language/expressions/object/__proto__-value-obj.js # Expected SameValue(«object», «object») to be true -language/expressions/object/dstr/async-gen-meth-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/object/dstr/async-gen-meth-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/object/dstr/async-gen-meth-dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/object/dstr/async-gen-meth-dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/object/dstr/gen-meth-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/object/dstr/gen-meth-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/object/dstr/gen-meth-dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/object/dstr/gen-meth-dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/object/dstr/meth-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/object/dstr/meth-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/object/dstr/meth-dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/object/dstr/meth-dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/expressions/optional-chaining/optional-call-preserves-this.js # TypeError: Cannot read properties of undefined (reading '…'). -language/expressions/postfix-decrement/S11.3.2_A2.1_T1.js # TypeError: Cannot read properties of undefined (reading '…'). -language/expressions/postfix-decrement/S11.3.2_A3_T5.js # TypeError: '…' requires a data value. -language/expressions/postfix-decrement/S11.3.2_A4_T5.js # TypeError: '…' requires a data value. -language/expressions/postfix-decrement/S11.3.2_A6_T1.js # Expected a DummyError but got a TypeError -language/expressions/postfix-decrement/S11.3.2_A6_T2.js # Expected a DummyError but got a TypeError -language/expressions/postfix-increment/S11.3.1_A2.1_T1.js # TypeError: Cannot read properties of undefined (reading '…'). -language/expressions/postfix-increment/S11.3.1_A3_T5.js # TypeError: '…' requires a data value. -language/expressions/postfix-increment/S11.3.1_A4_T5.js # TypeError: '…' requires a data value. -language/expressions/postfix-increment/S11.3.1_A6_T1.js # Expected a DummyError but got a TypeError -language/expressions/postfix-increment/S11.3.1_A6_T2.js # Expected a DummyError but got a TypeError -language/expressions/prefix-decrement/S11.4.5_A2.1_T1.js # TypeError: Cannot read properties of undefined (reading '…'). -language/expressions/prefix-decrement/S11.4.5_A3_T5.js # TypeError: '…' requires a data value. -language/expressions/prefix-decrement/S11.4.5_A4_T5.js # TypeError: '…' requires a data value. -language/expressions/prefix-decrement/S11.4.5_A6_T1.js # Expected a DummyError but got a TypeError -language/expressions/prefix-decrement/S11.4.5_A6_T2.js # Expected a DummyError but got a TypeError -language/expressions/prefix-increment/S11.4.4_A2.1_T1.js # TypeError: Cannot read properties of undefined (reading '…'). -language/expressions/prefix-increment/S11.4.4_A3_T5.js # TypeError: '…' requires a data value. -language/expressions/prefix-increment/S11.4.4_A4_T5.js # TypeError: '…' requires a data value. -language/expressions/prefix-increment/S11.4.4_A6_T1.js # Expected a DummyError but got a TypeError -language/expressions/prefix-increment/S11.4.4_A6_T2.js # Expected a DummyError but got a TypeError -language/expressions/property-accessors/S11.2.1_A4_T5.js # #27: typeof String.prototype.length === "number". Actual: undefined -language/expressions/property-accessors/S8.12.3_A1.js # TypeError: Cannot read properties of undefined (reading '…'). -language/expressions/right-shift/S11.7.2_A3_T1.5.js # TypeError: Binary operators require data values. -language/expressions/subtraction/S11.6.2_A3_T1.5.js # TypeError: Binary operators require data values. -language/expressions/super/call-arg-evaluation-err.js # TypeError: Extending the built-in Object is not supported. Only classes and Error types can be exten -language/expressions/super/call-bind-this-value-twice.js # TypeError: Class extends value a function is not a constructor or null. -language/expressions/super/call-bind-this-value.js # TypeError: Class extends value a function is not a constructor or null. -language/expressions/super/call-construct-error.js # TypeError: Class extends value a function is not a constructor or null. -language/expressions/super/call-expr-value.js # TypeError: Class extends value a function is not a constructor or null. -language/expressions/super/call-poisoned-underscore-proto.js # TypeError: Extending the built-in Array is not supported. Only classes and Error types can be extend -language/expressions/super/prop-dot-cls-null-proto.js # TypeError: Classes extending null are not supported. -language/expressions/super/prop-dot-cls-this-uninit.js # TypeError: Extending the built-in Object is not supported. Only classes and Error types can be exten -language/expressions/super/prop-expr-cls-null-proto.js # TypeError: Classes extending null are not supported. -language/expressions/super/prop-expr-cls-this-uninit.js # TypeError: Extending the built-in Object is not supported. Only classes and Error types can be exten -language/expressions/tagged-template/constructor-invocation.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/expressions/tagged-template/template-object-frozen-strict.js # Expected a TypeError to be thrown but no exception was thrown at all -language/expressions/this/11.1.1-1.js # Expected SameValue(«undefined», «undefined») to be false -language/expressions/typeof/get-value.js # TypeError: Object.defineProperties called on non-object -language/expressions/unary-minus/S11.4.7_A3_T5.js # TypeError: Unary operators require data values. -language/expressions/unary-plus/S11.4.6_A3_T5.js # TypeError: Unary operators require data values. -language/expressions/unsigned-right-shift/S11.7.3_A3_T1.5.js # TypeError: Binary operators require data values. -language/expressions/yield/star-in-rltn-expr.js # TypeError: yield* requires a compatible iterable value. -language/expressions/yield/star-iterable.js # First result `done` flag Expected SameValue(«false», «undefined») to be true -language/expressions/yield/star-rhs-iter-nrml-res-done-no-value.js # access count (first iteration) Expected SameValue(«1», «0») to be true -language/expressions/yield/star-rhs-iter-rtrn-res-done-no-value.js # access count (second iteration) Expected SameValue(«1», «0») to be true -language/expressions/yield/star-rhs-iter-thrw-res-done-no-value.js # access count (second iteration) Expected SameValue(«1», «0») to be true -language/function-code/10.4.3-1-21-s.js # TypeError: f is not a constructor: only classes can be constructed with new. Use a class, or call it -language/function-code/10.4.3-1-21gs.js # TypeError: f is not a constructor: only classes can be constructed with new. Use a class, or call it -language/function-code/10.4.3-1-23-s.js # TypeError: f is not a constructor: only classes can be constructed with new. Use a class, or call it -language/function-code/10.4.3-1-23gs.js # TypeError: f is not a constructor: only classes can be constructed with new. Use a class, or call it -language/function-code/10.4.3-1-25-s.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/function-code/10.4.3-1-25gs.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/global-code/decl-lex-configurable-global.js # TypeError: Cannot read properties of undefined (reading '…'). -language/global-code/decl-lex-restricted-global.js # expected SyntaxError but completed -language/global-code/decl-lex.js # TypeError: Cannot read properties of undefined (reading '…'). -language/global-code/import.js # expected SyntaxError but the program ran -language/global-code/return.js # expected SyntaxError but the program ran -language/identifier-resolution/S11.1.2_A1_T1.js # TypeError: Cannot read properties of undefined (reading '…'). -language/identifier-resolution/S11.1.2_A1_T2.js # #1.2: this.z; z === undefined throw ReferenceError. Actual: TypeError: Cannot read properties of und -language/identifiers/part-unicode-17.0.0-escaped.js # SyntaxError: Invalid Unicode escape. Code must be plain JavaScript written as a program body. -language/identifiers/part-unicode-17.0.0.js # SyntaxError: Unexpected character '…'. Code must be plain JavaScript written as a program body. -language/identifiers/start-unicode-17.0.0-escaped.js # SyntaxError: Invalid Unicode escape. Code must be plain JavaScript written as a program body. -language/identifiers/start-unicode-17.0.0.js # SyntaxError: Unexpected character '…'. Code must be plain JavaScript written as a program body. -language/punctuators/S7.7_A1.js # TypeError: Cannot read properties of undefined (reading '…'). -language/statements/async-generator/dstr/ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/async-generator/dstr/ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/async-generator/dstr/dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/async-generator/dstr/dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/async-generator/yield-return-then-getter-ticks.js # Actual ["start", "tick 1", "tick 2", "get then"] and expected ["start", "tick 1", "get then", "tick -language/statements/async-generator/yield-star-async-from-sync-iterator-inaccessible.js # TypeError: Object.getPrototypeOf cannot convert undefined to an object. -language/statements/async-generator/yield-star-return-then-getter-ticks.js # Actual ["start", "tick 1", "tick 2", "get then", "tick 3", "get return"] and expected ["start", "tic -language/statements/class/definition/prototype-getter.js # TypeError: Class extends value a function is not a constructor or null. -language/statements/class/definition/side-effects-in-property-define.js # TypeError: Object assignment result contains a circular value. -language/statements/class/definition/this-access-restriction.js # TypeError: Extending the built-in Object is not supported. Only classes and Error types can be exten -language/statements/class/dstr/async-gen-meth-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/class/dstr/async-gen-meth-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/class/dstr/async-gen-meth-dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/class/dstr/async-gen-meth-dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/class/dstr/async-gen-meth-static-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/class/dstr/async-gen-meth-static-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/class/dstr/async-gen-meth-static-dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/class/dstr/async-gen-meth-static-dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/class/dstr/gen-meth-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/class/dstr/gen-meth-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/class/dstr/gen-meth-dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/class/dstr/gen-meth-dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/class/dstr/gen-meth-static-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/class/dstr/gen-meth-static-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/class/dstr/gen-meth-static-dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/class/dstr/gen-meth-static-dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/class/dstr/meth-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/class/dstr/meth-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/class/dstr/meth-dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/class/dstr/meth-dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/class/dstr/meth-static-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/class/dstr/meth-static-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/class/dstr/meth-static-dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/class/dstr/meth-static-dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/class/poisoned-underscore-proto.js # TypeError: Extending the built-in Array is not supported. Only classes and Error types can be extend -language/statements/class/scope-name-lex-open-heritage.js # TypeError: Class extends value a function is not a constructor or null. -language/statements/class/strict-mode/arguments-callee.js # TypeError: Class extends value a function is not a constructor or null. -language/statements/class/subclass-builtins/subclass-Array.js # TypeError: Extending the built-in Array is not supported. Only classes and Error types can be extend -language/statements/class/subclass-builtins/subclass-Boolean.js # TypeError: Class extends value a function is not a constructor or null. -language/statements/class/subclass-builtins/subclass-Date.js # TypeError: Extending the built-in Date is not supported. Only classes and Error types can be extende -language/statements/class/subclass-builtins/subclass-Map.js # TypeError: Extending the built-in Map is not supported. Only classes and Error types can be extended -language/statements/class/subclass-builtins/subclass-Number.js # TypeError: Class extends value a function is not a constructor or null. -language/statements/class/subclass-builtins/subclass-Object.js # TypeError: Extending the built-in Object is not supported. Only classes and Error types can be exten -language/statements/class/subclass-builtins/subclass-Promise.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -language/statements/class/subclass-builtins/subclass-RegExp.js # TypeError: Extending the built-in RegExp is not supported. Only classes and Error types can be exten -language/statements/class/subclass-builtins/subclass-Set.js # TypeError: Extending the built-in Set is not supported. Only classes and Error types can be extended -language/statements/class/subclass-builtins/subclass-String.js # TypeError: Class extends value a function is not a constructor or null. -language/statements/class/subclass-builtins/subclass-WeakMap.js # TypeError: Extending the built-in WeakMap is not supported. Only classes and Error types can be exte -language/statements/class/subclass-builtins/subclass-WeakSet.js # TypeError: Extending the built-in WeakSet is not supported. Only classes and Error types can be exte -language/statements/class/subclass/binding.js # TypeError: new f(...) is not supported; call f(...) without new instead. -language/statements/class/subclass/builtin-objects/Array/contructor-calls-super-multiple-arguments.js # TypeError: Extending the built-in Array is not supported. Only classes and Error types can be extend -language/statements/class/subclass/builtin-objects/Array/contructor-calls-super-single-argument.js # TypeError: Extending the built-in Array is not supported. Only classes and Error types can be extend -language/statements/class/subclass/builtin-objects/Array/length.js # TypeError: Extending the built-in Array is not supported. Only classes and Error types can be extend -language/statements/class/subclass/builtin-objects/Array/regular-subclassing.js # TypeError: Extending the built-in Array is not supported. Only classes and Error types can be extend -language/statements/class/subclass/builtin-objects/Array/super-must-be-called.js # TypeError: Extending the built-in Array is not supported. Only classes and Error types can be extend -language/statements/class/subclass/builtin-objects/Boolean/regular-subclassing.js # TypeError: Class extends value a function is not a constructor or null. -language/statements/class/subclass/builtin-objects/Boolean/super-must-be-called.js # TypeError: Class extends value a function is not a constructor or null. -language/statements/class/subclass/builtin-objects/Date/regular-subclassing.js # TypeError: Extending the built-in Date is not supported. Only classes and Error types can be extende -language/statements/class/subclass/builtin-objects/Date/super-must-be-called.js # TypeError: Extending the built-in Date is not supported. Only classes and Error types can be extende -language/statements/class/subclass/builtin-objects/GeneratorFunction/regular-subclassing.js # TypeError: Extending the built-in Function is not supported. Only classes and Error types can be ext -language/statements/class/subclass/builtin-objects/GeneratorFunction/super-must-be-called.js # TypeError: Extending the built-in Function is not supported. Only classes and Error types can be ext -language/statements/class/subclass/builtin-objects/Map/regular-subclassing.js # TypeError: Extending the built-in Map is not supported. Only classes and Error types can be extended -language/statements/class/subclass/builtin-objects/Map/super-must-be-called.js # TypeError: Extending the built-in Map is not supported. Only classes and Error types can be extended -language/statements/class/subclass/builtin-objects/Number/regular-subclassing.js # TypeError: Class extends value a function is not a constructor or null. -language/statements/class/subclass/builtin-objects/Number/super-must-be-called.js # TypeError: Class extends value a function is not a constructor or null. -language/statements/class/subclass/builtin-objects/Object/constructor-return-undefined-throws.js # TypeError: Extending the built-in Object is not supported. Only classes and Error types can be exten -language/statements/class/subclass/builtin-objects/Object/constructor-returns-non-object.js # TypeError: Extending the built-in Object is not supported. Only classes and Error types can be exten -language/statements/class/subclass/builtin-objects/Object/regular-subclassing.js # TypeError: Extending the built-in Object is not supported. Only classes and Error types can be exten -language/statements/class/subclass/builtin-objects/Object/replacing-prototype.js # TypeError: Extending the built-in Object is not supported. Only classes and Error types can be exten -language/statements/class/subclass/builtin-objects/Promise/regular-subclassing.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -language/statements/class/subclass/builtin-objects/Promise/super-must-be-called.js # TypeError: Extending the built-in Promise is not supported. Only classes and Error types can be exte -language/statements/class/subclass/builtin-objects/RegExp/regular-subclassing.js # TypeError: Extending the built-in RegExp is not supported. Only classes and Error types can be exten -language/statements/class/subclass/builtin-objects/RegExp/super-must-be-called.js # TypeError: Extending the built-in RegExp is not supported. Only classes and Error types can be exten -language/statements/class/subclass/builtin-objects/Set/regular-subclassing.js # TypeError: Extending the built-in Set is not supported. Only classes and Error types can be extended -language/statements/class/subclass/builtin-objects/Set/super-must-be-called.js # TypeError: Extending the built-in Set is not supported. Only classes and Error types can be extended -language/statements/class/subclass/builtin-objects/String/regular-subclassing.js # TypeError: Class extends value a function is not a constructor or null. -language/statements/class/subclass/builtin-objects/String/super-must-be-called.js # TypeError: Class extends value a function is not a constructor or null. -language/statements/class/subclass/builtin-objects/WeakMap/regular-subclassing.js # TypeError: Extending the built-in WeakMap is not supported. Only classes and Error types can be exte -language/statements/class/subclass/builtin-objects/WeakMap/super-must-be-called.js # TypeError: Extending the built-in WeakMap is not supported. Only classes and Error types can be exte -language/statements/class/subclass/builtin-objects/WeakSet/regular-subclassing.js # TypeError: Extending the built-in WeakSet is not supported. Only classes and Error types can be exte -language/statements/class/subclass/builtin-objects/WeakSet/super-must-be-called.js # TypeError: Extending the built-in WeakSet is not supported. Only classes and Error types can be exte -language/statements/class/subclass/builtins.js # TypeError: Extending the built-in Uint8Array is not supported. Only classes and Error types can be e -language/statements/class/subclass/class-definition-null-proto-contains-return-override.js # TypeError: Classes extending null are not supported. -language/statements/class/subclass/class-definition-null-proto-missing-return-override.js # TypeError: Classes extending null are not supported. -language/statements/class/subclass/class-definition-null-proto-super.js # TypeError: Classes extending null are not supported. -language/statements/class/subclass/class-definition-null-proto-this.js # TypeError: Classes extending null are not supported. -language/statements/class/subclass/class-definition-parent-proto-null.js # TypeError: Class extends value a function is not a constructor or null. -language/statements/class/subclass/default-constructor-2.js # TypeError: new f(...) is not supported; call f(...) without new instead. -language/statements/class/subclass/derived-class-return-override-catch-finally-arrow.js # UnsupportedSyntax: SyntaxError: super() inside an arrow function is not supported. Call super() dire -language/statements/class/subclass/derived-class-return-override-finally-super-arrow.js # UnsupportedSyntax: SyntaxError: super() inside an arrow function is not supported. Call super() dire -language/statements/class/subclass/derived-class-return-override-for-of-arrow.js # ReferenceError: Must call super constructor in derived class before accessing '…' or returning from -language/statements/class/subclass/superclass-bound-function.js # TypeError: Class extends value a function is not a constructor or null. -language/statements/class/subclass/superclass-prototype-setter-constructor.js # TypeError: Class extends value a function is not a constructor or null. -language/statements/class/subclass/superclass-prototype-setter-method-override.js # TypeError: Class extends value a function is not a constructor or null. -language/statements/class/subclass/superclass-static-method-override.js # TypeError: Class extends value a function is not a constructor or null. -language/statements/class/super/in-constructor-superproperty-evaluation.js # TypeError: Extending the built-in Object is not supported. Only classes and Error types can be exten -language/statements/const/dstr/ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/const/dstr/ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/for-await-of/async-from-sync-iterator-continuation-abrupt-completion-get-constructor.js # Actual ["start", "tick 1", "tick 2"] and expected ["start", "tick 1", "tick 2", "catch"] should have -language/statements/for-await-of/ticks-with-async-iter-resolved-promise-and-constructor-lookup-two.js # Actual ["pre", "tick 1", "loop", "tick 2", "post"] and expected ["pre", "constructor", "tick 1", "lo -language/statements/for-await-of/ticks-with-sync-iter-resolved-promise-and-constructor-lookup.js # Actual ["pre", "tick 1", "tick 2", "loop", "tick 3", "tick 4", "post"] and expected ["pre", "constru -language/statements/for-in/12.6.4-2.js # TypeError: ConstructFun is not a constructor: only classes can be constructed with new. Use a class, -language/statements/for-in/S12.6.4_A6.1.js # TypeError: FACTORY is not a constructor: only classes can be constructed with new. Use a class, or c -language/statements/for-in/S12.6.4_A6.js # TypeError: FACTORY is not a constructor: only classes can be constructed with new. Use a class, or c -language/statements/for-in/S12.6.4_A7_T2.js # Unexpected value: '…' -language/statements/for-of/array-key-get-error.js # TypeError: Accessor properties are not supported on array elements; store the value or use a plain o -language/statements/for-of/dstr/array-elem-iter-rtrn-close-err.js # TypeError: Iterator next must be a function. -language/statements/for-of/dstr/array-elem-iter-thrw-close-err.js # Expected SameValue(«1», «0») to be true -language/statements/for-of/dstr/array-elem-iter-thrw-close.js # Expected SameValue(«1», «0») to be true -language/statements/for-of/dstr/array-elem-trlg-iter-list-thrw-close-err.js # Expected SameValue(«1», «0») to be true -language/statements/for-of/dstr/array-elem-trlg-iter-list-thrw-close.js # Expected SameValue(«1», «0») to be true -language/statements/for-of/dstr/array-elem-trlg-iter-rest-rtrn-close-err.js # Expected a Test262Error to be thrown but no exception was thrown at all -language/statements/for-of/dstr/array-elem-trlg-iter-rest-rtrn-close-null.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/for-of/dstr/array-elem-trlg-iter-rest-rtrn-close.js # Expected SameValue(«11», «1») to be true -language/statements/for-of/dstr/array-elem-trlg-iter-rest-thrw-close-err.js # Expected SameValue(«11», «1») to be true -language/statements/for-of/dstr/array-elem-trlg-iter-rest-thrw-close.js # Expected SameValue(«11», «1») to be true -language/statements/for-of/dstr/array-rest-iter-rtrn-close-err.js # TypeError: Iterator next must be a function. -language/statements/for-of/dstr/array-rest-iter-rtrn-close-null.js # TypeError: Iterator next must be a function. -language/statements/for-of/dstr/array-rest-iter-rtrn-close.js # Test262Error -language/statements/for-of/dstr/array-rest-iter-thrw-close-err.js # Expected SameValue(«11», «0») to be true -language/statements/for-of/dstr/array-rest-iter-thrw-close.js # Expected SameValue(«11», «0») to be true -language/statements/for-of/dstr/array-rest-lref-err.js # Expected SameValue(«1», «0») to be true -language/statements/for-of/dstr/const-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/for-of/dstr/const-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/for-of/dstr/let-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/for-of/dstr/let-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/for-of/dstr/var-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/for-of/dstr/var-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/for-of/throw-from-catch.js # TypeError: CustomError is not a constructor: only classes can be constructed with new. Use a class, -language/statements/for-of/throw-from-finally.js # TypeError: CustomError is not a constructor: only classes can be constructed with new. Use a class, -language/statements/for-of/throw.js # TypeError: CustomError is not a constructor: only classes can be constructed with new. Use a class, -language/statements/for/dstr/const-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/for/dstr/const-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/for/dstr/let-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/for/dstr/let-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/for/dstr/var-ary-init-iter-get-err-array-prototype.js # Expected a TypeError but got a ReferenceError -language/statements/for/dstr/var-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/function/13.2-1-s.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -language/statements/function/13.2-3-s.js # TypeError: foo is not a constructor: only classes can be constructed with new. Use a class, or call -language/statements/function/S13.2.2_A10.js # #1: var obj = new FACTORY() does not lead to throwing exception. Actual: Exception is TypeError: FAC -language/statements/function/S13.2.2_A12.js # #1: var obj = new FACTORY() does not lead to throwing exception. Actual: Exception is TypeError: FAC -language/statements/function/S13.2.2_A15_T1.js # TypeError: __FACTORY is not a constructor: only classes can be constructed with new. Use a class, or -language/statements/function/S13.2.2_A15_T2.js # TypeError: __FACTORY is not a constructor: only classes can be constructed with new. Use a class, or -language/statements/function/S13.2.2_A15_T3.js # TypeError: __FACTORY is not a constructor: only classes can be constructed with new. Use a class, or -language/statements/function/S13.2.2_A15_T4.js # TypeError: __FACTORY is not a constructor: only classes can be constructed with new. Use a class, or -language/statements/function/S13.2.2_A16_T1.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/statements/function/S13.2.2_A16_T2.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/statements/function/S13.2.2_A16_T3.js # TypeError: The called value is not a constructor: only classes can be constructed with new. Use a cl -language/statements/function/S13.2.2_A1_T1.js # TypeError: __FACTORY is not a constructor: only classes can be constructed with new. Use a class, or -language/statements/function/S13.2.2_A1_T2.js # TypeError: __FACTORY is not a constructor: only classes can be constructed with new. Use a class, or -language/statements/function/S13.2.2_A2.js # TypeError: __FACTORY is not a constructor: only classes can be constructed with new. Use a class, or -language/statements/function/S13.2.2_A3_T1.js # TypeError: __FACTORY is not a constructor: only classes can be constructed with new. Use a class, or -language/statements/function/S13.2.2_A3_T2.js # TypeError: __FACTORY is not a constructor: only classes can be constructed with new. Use a class, or -language/statements/function/S13.2.2_A4_T1.js # TypeError: __FACTORY is not a constructor: only classes can be constructed with new. Use a class, or -language/statements/function/S13.2.2_A4_T2.js # TypeError: __FACTORY is not a constructor: only classes can be constructed with new. Use a class, or -language/statements/function/S13.2.2_A5_T1.js # TypeError: __FACTORY is not a constructor: only classes can be constructed with new. Use a class, or -language/statements/function/S13.2.2_A5_T2.js # TypeError: __FACTORY is not a constructor: only classes can be constructed with new. Use a class, or -language/statements/function/S13.2.2_A6_T1.js # TypeError: __func is not a constructor: only classes can be constructed with new. Use a class, or ca -language/statements/function/S13.2.2_A6_T2.js # TypeError: __func is not a constructor: only classes can be constructed with new. Use a class, or ca -language/statements/function/S13.2.2_A7_T1.js # TypeError: __func is not a constructor: only classes can be constructed with new. Use a class, or ca -language/statements/function/S13.2.2_A7_T2.js # TypeError: __func is not a constructor: only classes can be constructed with new. Use a class, or ca -language/statements/function/S13.2.2_A8_T1.js # TypeError: __func is not a constructor: only classes can be constructed with new. Use a class, or ca -language/statements/function/S13.2.2_A8_T2.js # TypeError: __func is not a constructor: only classes can be constructed with new. Use a class, or ca -language/statements/function/S13.2_A1_T1.js # #1: __func.prototype !== undefined -language/statements/function/S13.2_A1_T2.js # #1: __func.prototype !== undefined -language/statements/function/S13.2_A4_T1.js # ReferenceError: Unknown identifier '…'. -language/statements/function/S13.2_A4_T2.js # #1: typeof __gunc.prototype === '…'. Actual: typeof __gunc.prototype ===undefined -language/statements/function/dstr/ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/function/dstr/ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/function/dstr/dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/function/dstr/dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/generators/default-proto.js # Expected SameValue(«object», «undefined») to be true -language/statements/generators/dstr/ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/generators/dstr/ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/generators/dstr/dflt-ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/generators/dstr/dflt-ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/generators/prototype-relation-to-function.js # Expected SameValue(«object», «») to be true -language/statements/labeled/value-await-non-module.js # SyntaxError: Unexpected token. Code must be plain JavaScript written as a program body. -language/statements/let/dstr/ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/let/dstr/ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/return/S12.9_A1_T1.js # expected SyntaxError but the program ran -language/statements/return/S12.9_A1_T10.js # expected SyntaxError but the program ran -language/statements/return/S12.9_A1_T2.js # expected SyntaxError but the program ran -language/statements/return/S12.9_A1_T3.js # expected SyntaxError but the program ran -language/statements/return/S12.9_A1_T4.js # expected SyntaxError but the program ran -language/statements/return/S12.9_A1_T5.js # expected SyntaxError but the program ran -language/statements/return/S12.9_A1_T6.js # expected SyntaxError but the program ran -language/statements/return/S12.9_A1_T7.js # expected SyntaxError but the program ran -language/statements/return/S12.9_A1_T8.js # expected SyntaxError but the program ran -language/statements/return/S12.9_A1_T9.js # expected SyntaxError but the program ran -language/statements/try/S12.14_A17.js # TypeError: Integer is not a constructor: only classes can be constructed with new. Use a class, or c -language/statements/try/dstr/ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/try/dstr/ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/statements/variable/S12.2_A11.js # TypeError: Cannot read properties of undefined (reading '…'). -language/statements/variable/S12.2_A9.js # #1: When using property attributes, {DontEnum} not used -language/statements/variable/dstr/ary-init-iter-get-err-array-prototype.js # Expected a TypeError to be thrown but no exception was thrown at all -language/statements/variable/dstr/ary-ptrn-elem-id-iter-val-array-prototype.js # Expected SameValue(«3», «42») to be true -language/types/object/S8.6.2_A1.js # TypeError: FooObj is not a constructor: only classes can be constructed with new. Use a class, or ca -language/types/object/S8.6.2_A2.js # TypeError: Cannot read properties of undefined (reading '…'). -language/types/object/S8.6.2_A5_T1.js # TypeError: Cannot read properties of undefined (reading '…'). -language/types/object/S8.6.2_A5_T2.js # TypeError: Cannot read properties of undefined (reading '…'). -language/types/object/S8.6.2_A5_T3.js # TypeError: Cannot read properties of undefined (reading '…'). -language/types/object/S8.6.2_A5_T4.js # TypeError: Cannot read properties of undefined (reading '…'). -language/types/reference/S8.7.1_A1.js # TypeError: Cannot read properties of undefined (reading '…'). -language/types/reference/S8.7.2_A3.js # TypeError: Cannot read properties of undefined (reading '…'). diff --git a/packages/codemode/test/var-hoisting-test262.test.ts b/packages/codemode/test/var-hoisting-test262.test.ts deleted file mode 100644 index 667603f5232..00000000000 --- a/packages/codemode/test/var-hoisting-test262.test.ts +++ /dev/null @@ -1,280 +0,0 @@ -/** - * Portions adapted from Test262 at revision 250f204f23a9249ff204be2baec29600faae7b75: - * - test/language/statements/variable/S12.2_A1.js - * - test/language/statements/variable/S12.2_A3.js - * - test/language/statements/variable/S12.2_A6_T1.js - * - test/language/statements/variable/S12.2_A7.js - * - test/language/statements/variable/S12.2_A10.js - * - test/language/statements/variable/S12.2_A12.js - * - test/language/block-scope/shadowing/hoisting-var-declarations-out-of-blocks.js - * - test/language/block-scope/shadowing/catch-parameter-shadowing-var-variable.js - * - test/language/statements/for/head-var-bound-names-in-stmt.js - * - test/language/statements/function/scope-paramsbody-var-open.js - * - test/language/statements/function/scope-paramsbody-var-close.js - * - * Copyright 2009 the Sputnik authors. All rights reserved. - * Copyright (C) 2011, 2016 the V8 project authors. All rights reserved. - * Test262 portions are governed by the BSD license in LICENSE.test262. - * - * Files that observe `var` through `eval`, `this`, `delete`, or the global object (S12.2_A2, A5, A9, - * A11, `scope-*-none.js`, `scope-param-elem-*.js`) have no analogue here and are not ported. - */ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" - -const value = async (code: string) => { - const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} })) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -describe("var hoisting Test262 parity", () => { - test("test/language/statements/variable/S12.2_A1.js: use before declaration reads undefined", async () => { - expect( - await value(` - __x = __x - __y = __x ? "good fellow" : "liar" - __z = __z === __x ? 1 : 0 - let unknown - try { __something__undefined = __something__undefined } catch (error) { unknown = error.name } - const before = [__y, __z, unknown] - var __x, __y = true, __z = __y ? "smeagol" : "golum" - return [...before, __y, __z] - `), - ).toEqual(["liar", 1, "ReferenceError", true, "smeagol"]) - }) - - test("test/language/statements/variable/S12.2_A3.js: nested functions redeclare or assign", async () => { - expect( - await value(` - var __var = "OUT" - const inner = (function () { - var __var = "IN" - ;(function () { __var = "INNER_SPACE" })() - ;(function () { var __var = "INNER_SUN" })() - return __var - })() - const after = __var - const assigned = (function () { - __var = "IN" - ;(function () { __var = "INNERED" })() - ;(function () { var __var = "INNAGER" })() - return __var - })() - return [inner, after, assigned, __var] - `), - ).toEqual(["INNER_SPACE", "OUT", "INNERED", "INNERED"]) - }) - - test("test/language/statements/variable/S12.2_A6_T1.js: var inside try and catch is hoisted", async () => { - expect( - await value(` - intry__var = intry__var - incatch__var = incatch__var - try { var intry__var } catch (e) { var incatch__var } - return [typeof intry__var, typeof incatch__var] - `), - ).toEqual(["undefined", "undefined"]) - }) - - test("test/language/statements/variable/S12.2_A7.js: var after break inside for is hoisted", async () => { - expect( - await value(` - infor_var = infor_var - for (;;) { break; var infor_var } - return typeof infor_var - `), - ).toBe("undefined") - }) - - test("test/language/statements/variable/S12.2_A10.js: var in for head is hoisted", async () => { - expect( - await value(` - __ind = __ind - for (var __ind; ; ) { break } - return typeof __ind - `), - ).toBe("undefined") - }) - - test("test/language/statements/variable/S12.2_A12.js: var in do-while body is hoisted", async () => { - expect( - await value(` - x = x - do var x; while (false) - return typeof x - `), - ).toBe("undefined") - }) - - test("test/language/block-scope/shadowing/hoisting-var-declarations-out-of-blocks.js", async () => { - expect( - await value(` - function fn() { - { var x = 1; var y } - return [x, typeof y] - } - return fn() - `), - ).toEqual([1, "undefined"]) - }) - - test("test/language/block-scope/shadowing/catch-parameter-shadowing-var-variable.js", async () => { - expect( - await value(` - function fn() { - var a = 1 - let caught - try { throw "stuff3" } catch (a) { caught = a } - return [caught, a] - } - return fn() - `), - ).toEqual(["stuff3", 1]) - }) - - test("test/language/statements/for/head-var-bound-names-in-stmt.js: redeclaring the head var in the body", async () => { - expect( - await value(` - var iterCount = 0 - var first = true - for (var x; first; first = false) { - var x - iterCount += 1 - } - return iterCount - `), - ).toBe(1) - }) - - test("test/language/statements/function/scope-paramsbody-var-open.js: parameter defaults see the outer var", async () => { - expect( - await value(` - var x = "outside" - var probeParams, probeBody - function f(_ = probeParams = function () { return x }) { - var x = "inside" - probeBody = function () { return x } - } - f() - return [probeParams(), probeBody()] - `), - ).toEqual(["outside", "inside"]) - }) - - test("test/language/statements/function/scope-paramsbody-var-close.js: body var does not leak out", async () => { - expect( - await value(` - var probe - function f(_ = null) { - var x = "inside" - probe = function () { return x } - } - f() - var x = "outside" - return [probe(), x] - `), - ).toEqual(["inside", "outside"]) - }) -}) - -describe("var semantics beyond Test262", () => { - test("redeclaration and block-level var assign the one function-scoped binding", async () => { - expect(await value(`var a = 1; var a = 2; { var a = 3 } return a`)).toBe(3) - expect(await value(`var q = 1; { let q = 2 } return q`)).toBe(1) - }) - - test("var loop counters are shared by closures, let counters are not", async () => { - expect( - await value(` - const byVar = [] - for (var i = 0; i < 3; i++) byVar.push(() => i) - const byLet = [] - for (let j = 0; j < 3; j++) byLet.push(() => j) - return [byVar.map((f) => f()), byLet.map((f) => f())] - `), - ).toEqual([ - [3, 3, 3], - [0, 1, 2], - ]) - }) - - test("for...in and for...of var heads survive the loop", async () => { - expect(await value(`for (var k in { a: 1 }) {} for (var [p, q] of [[1, 2]]) {} return [k, p, q]`)).toEqual([ - "a", - 1, - 2, - ]) - }) - - test("var and function declarations of the same name share a binding", async () => { - expect(await value(`var fn = 1; function fn() {} return typeof fn`)).toBe("number") - expect(await value(`function fn() {} var fn; return typeof fn`)).toBe("function") - expect(await value(`function h() { var fn = 1; function fn() {} return typeof fn } return h()`)).toBe("number") - }) - - test("a var named after a parameter keeps the argument until assigned", async () => { - expect(await value(`function f(a) { var a; return a } return f(7)`)).toBe(7) - expect(await value(`function f(a) { var a = 2; return a } return f(7)`)).toBe(2) - }) - - test("var does not hoist across function boundaries", async () => { - expect(await value(`return [typeof b, (() => { var b = 1; return b })()]; var b`)).toEqual(["undefined", 1]) - expect( - await value( - `function outer() { var o = 1; function inner() { var o = 2; return o } return [inner(), o] } return outer()`, - ), - ).toEqual([2, 1]) - }) - - test("switch cases, labels, and generators hoist var", async () => { - expect(await value(`switch (1) { case 1: var s = 9 } label: { var lb = 1 } return [s, lb]`)).toEqual([9, 1]) - expect(await value(`function* gen() { var t = 1; yield t; var t = 2; yield t } return [...gen()]`)).toEqual([1, 2]) - }) -}) - -describe("function declarations and expressions", () => { - test("the last of repeated function declarations wins, and a var may share the name", async () => { - expect( - await value(` - function f() { return 1 } - const first = f() - function f() { return 2 } - var g = 1 - function g() { return 3 } - return [first, f(), typeof g] - `), - ).toEqual([2, 2, "number"]) - }) - - test("a named function expression sees its own name inside its body, read-only", async () => { - expect( - await value(` - const fact = function inner(n) { return n <= 1 ? 1 : n * inner(n - 1) } - const reassign = function inner() { inner = 5 } - let failure - try { reassign() } catch (error) { failure = error.constructor.name } - return [fact(4), typeof inner, failure] - `), - ).toEqual([24, "undefined", "TypeError"]) - }) - - test("generator functions have their own prototype", async () => { - expect( - await value(` - function* g() {} - async function* ag() {} - function f() {} - return [g() instanceof g, ag() instanceof ag, g.prototype === ag.prototype, typeof g.prototype, typeof f.prototype] - `), - ).toEqual([true, true, false, "object", "undefined"]) - }) -}) - -describe("switch case function hoisting", () => { - test("function declarations are visible across all cases before their statement runs", async () => { - expect(await value(`switch (1) { case 1: return foo(); function foo() { return "hoisted" } }`)).toBe("hoisted") - expect(await value(`switch (2) { case 1: function foo() { return "a" } break; case 2: return foo() }`)).toBe("a") - }) -}) diff --git a/packages/codemode/test/verify-bytecode.ts b/packages/codemode/test/verify-bytecode.ts deleted file mode 100644 index bbfcff4c26a..00000000000 --- a/packages/codemode/test/verify-bytecode.ts +++ /dev/null @@ -1,388 +0,0 @@ -import type { Code } from "../src/language/code.js" -import { CheckBaseKind, CondKind, ImportKind, Op, OpNames } from "../src/language/opcodes.js" - -/** - * Stack-depth verifier (C5): runs abstract interpretation over packed bytecode independent of `CodeBuilder`, - * proving a single static operand depth at every reachable pc, `0 <= depth <= maxStack`, valid handler and - * `END_FINALLY` entry depths, T&S successor depths, and valid local/upvalue slot bounds. - */ -export const verifyCode = (c: Code): Array => { - const errors: Array = [] - const label = `${c.source.id}#${c.index}(${c.name || ""})` - const words = c.code - const depth = new Int32Array(words.length).fill(-1) - const work: Array = [] - - const at = (pc: number, d: number, from: number) => { - if (pc < 0 || pc >= words.length) { - errors.push(`${label}: pc ${pc} out of range (from ${from})`) - return - } - if (pc > 0 && (words[pc - 1]! & 0xff) === Op.EXTRA) { - errors.push(`${label}: jump into middle of EXTRA sequence at pc ${pc} (from ${from})`) - return - } - if (d < 0) { - errors.push(`${label}: negative depth ${d} at pc ${pc} (from ${from})`) - return - } - if (d > c.maxStack) { - errors.push(`${label}: depth ${d} > maxStack ${c.maxStack} at pc ${pc}`) - } - if (depth[pc] === -1) { - depth[pc] = d - work.push(pc) - } else if (depth[pc] !== d) { - errors.push(`${label}: depth conflict at pc ${pc}: ${depth[pc]} vs ${d} (from ${from})`) - } - } - - if (words.length > 0) at(0, 0, -1) - - const h = c.handlers - for (let i = 0; i < h.length; i += 4) { - at(h[i + 2]!, h[i + 3]! + 1, -2) - } - - const checkSlot = (s: number, pc: number) => { - if (s < 0 || s >= c.locals) { - errors.push(`${label}: local slot ${s} out of [0, ${c.locals}) at pc ${pc}`) - } - } - - const checkUpval = (u: number, pc: number) => { - const count = c.captures.length >>> 1 - if (u < 0 || u >= count) { - errors.push(`${label}: upval ${u} out of [0, ${count}) at pc ${pc}`) - } - } - - while (work.length > 0) { - const pc = work.pop()! - const d = depth[pc]! - const w = words[pc]! - let op = w & 0xff - let stride = 1 - let a = (w >>> 8) & 0xff - let bx = w >>> 16 - if (op === Op.EXTRA) { - if (pc + 1 >= words.length) { - errors.push(`${label}: trailing EXTRA at pc ${pc}`) - continue - } - const w1 = words[pc + 1]! - if ((w1 & 0xff) === Op.EXTRA) { - if (pc + 2 >= words.length) { - errors.push(`${label}: trailing EXTRA at pc ${pc + 1}`) - continue - } - const w2 = words[pc + 2]! - op = w2 & 0xff - a = ((w >>> 16) << 16) | (w1 & 0xff00) | ((w2 >>> 8) & 0xff) - bx = ((w1 >>> 16) << 16) | (w2 >>> 16) - stride = 3 - } else { - op = w1 & 0xff - a = (w & 0xff00) | ((w1 >>> 8) & 0xff) - bx = ((w >>> 16) << 16) | (w1 >>> 16) - stride = 2 - } - if (op === Op.EXTRA) { - errors.push(`${label}: more than two EXTRA prefixes at pc ${pc}`) - continue - } - } - const next = (delta: number) => at(pc + stride, d + delta, pc) - - switch (op) { - case Op.PUSH_UNDEF: - case Op.PUSH_NULL: - case Op.PUSH_BOOL: - case Op.PUSH_INT: - case Op.PUSH_CONST: - case Op.DUP: - case Op.GET_INTRINSIC: - case Op.ARGS: - case Op.CLOSURE: - case Op.NEW_OBJECT: - case Op.TEMPLATE: - case Op.REGEXP: - next(1) - break - case Op.GET_GLOBAL: - next(a === 2 ? -1 : 1) - break - case Op.IMPORT: - next(a === ImportKind.SIDE_EFFECT ? 0 : a === ImportKind.DYNAMIC ? 0 : 1) - break - case Op.PICK: - if (a >= d) errors.push(`${label}: PICK ${a} at depth ${d} (pc ${pc})`) - next(1) - break - case Op.ROT: - if (a >= d) errors.push(`${label}: ROT ${a} at depth ${d} (pc ${pc})`) - next(0) - break - case Op.GET_LOCAL: - case Op.GET_CELL: - checkSlot(bx, pc) - next(1) - break - case Op.PUT_LOCAL: - case Op.PUT_CELL: - checkSlot(bx, pc) - next(-1) - break - case Op.HOLE_LOCAL: - case Op.NEW_CELL: - case Op.COPY_CELL: - checkSlot(bx, pc) - next(0) - break - case Op.GET_UPVAL: - checkUpval(bx, pc) - next(1) - break - case Op.PUT_UPVAL: - checkUpval(bx, pc) - next(-1) - break - case Op.POP: - case Op.PUT_PROP: - case Op.COPY_DATA_PROPS: - case Op.IN: - case Op.INSTANCEOF: - case Op.ADD: - case Op.SUB: - case Op.MUL: - case Op.LT: - case Op.LE: - case Op.GT: - case Op.GE: - case Op.SEQ: - case Op.SNE: - case Op.BINOP: - case Op.DELETE_ELEM: - case Op.NEW_SPREAD: - next(-1) - break - case Op.POPN: - case Op.COPY_REST: - next(-bx) - break - case Op.SET_NAME: - case Op.DELETE_PROP: - case Op.CHECK_BASE: - case Op.TO_KEY: - case Op.UNARY: - case Op.NOT: - case Op.TO_NUMERIC: - case Op.INC: - case Op.TO_STRING: - case Op.NOP: - case Op.FOR_IN: - case Op.ITER_INIT: - case Op.GENERATOR_START: - if (op === Op.CHECK_BASE && a === CheckBaseKind.READ && d < 2) { - errors.push(`${label}: CHECK_BASE.read at depth ${d} (pc ${pc})`) - } - next(0) - break - case Op.GET_PROP: - next(a === 1 ? 1 : 0) - break - case Op.GET_ELEM: - next(a === 1 ? 0 : -1) - break - case Op.PUT_ELEM: - case Op.CALL_SPREAD: - next(-2) - break - case Op.DEFINE_FIELD: - next((a & 1) === 0 ? -1 : -2) - break - case Op.DEFINE_ACCESSOR: - next((a & 1) === 0 ? -1 : -2) - break - case Op.CLASS: - next((a & 1) === 0 ? 1 : 0) - break - case Op.SUPER_CALL: - next(a === 255 ? 0 : 1 - a) - break - case Op.SUPER_BIND: - next(0) - break - case Op.SET_HOME: - next(0) - break - case Op.GET_SUPER: - next(((a & 1) === 0 ? -1 : 0) - ((a & 2) === 0 ? 0 : 1)) - break - case Op.PUT_SUPER: - next((a & 2) === 0 ? -2 : -3) - break - case Op.DEFINE_METHOD: - next((a & 2) === 0 ? -1 : -2) - break - case Op.SET_FIELDS: - next(-1) - break - case Op.INIT_FIELDS: - next(a === 0 ? 1 : -1) - break - case Op.NEW_ARRAY: - case Op.CONCAT: - next(1 - bx) - break - case Op.ARRAY_APPEND: - next(a === 1 ? 0 : -1) - break - case Op.JUMP: - case Op.LOOP: - at(bx, d, pc) - break - case Op.JUMP_IF_FALSE: - case Op.JUMP_IF_TRUE: - at(bx, d - 1, pc) - next(-1) - break - case Op.JUMP_COND: - if (a === CondKind.NULLISH) { - at(bx, d, pc) - next(0) - } else if (a === CondKind.NULLISH_METHOD) { - at(bx, d - 1, pc) - next(0) - } else { - at(bx, d, pc) - next(-1) - } - break - case Op.THROW: - case Op.RETURN: - case Op.END_PROGRAM: - if (d < 1) errors.push(`${label}: ${OpNames[op]} on empty stack at pc ${pc}`) - break - case Op.THROW_ERROR: - break - case Op.END_FINALLY: { - if (bx < 0 || bx >= c.finallyOffsets.length) { - errors.push(`${label}: END_FINALLY level ${bx} out of range at pc ${pc}`) - break - } - const off = c.finallyOffsets[bx]! - const fin = c.finallies - const tagSlot = fin[off]! - const valSlot = fin[off + 1]! - const entryDepth = fin[off + 2]! - const n = fin[off + 3]! - if (d !== entryDepth) { - errors.push(`${label}: END_FINALLY ${bx} at depth ${d}, expected ${entryDepth} (pc ${pc})`) - } - checkSlot(tagSlot, pc) - checkSlot(valSlot, pc) - for (let k = 0; k < n; k++) { - const target = fin[off + 4 + k]! - if (k !== 1 && target >= 0) at(target, entryDepth, pc) - } - break - } - case Op.CALL: - if (d < a + 2) errors.push(`${label}: CALL ${a} at depth ${d} (pc ${pc})`) - next(-(a + 1)) - break - case Op.NEW: - if (a === 255) { - if (d < 1) errors.push(`${label}: NEW.check at depth ${d} (pc ${pc})`) - next(0) - } else { - if (d < a + 1) errors.push(`${label}: NEW ${a} at depth ${d} (pc ${pc})`) - next(-a) - } - break - case Op.ITER_OPEN: { - const jumpPc = pc + stride - const jumpStride = jumpPc < words.length && (words[jumpPc]! & 0xff) === Op.EXTRA ? 2 : 1 - if (jumpPc + jumpStride > words.length || (words[jumpPc + jumpStride - 1]! & 0xff) !== Op.JUMP) { - errors.push(`${label}: T&S ITER_OPEN at pc ${pc} not followed by JUMP`) - break - } - at(jumpPc, d + 1, pc) - at(jumpPc + jumpStride, d, pc) - break - } - case Op.ITER_STEP: { - checkSlot(a, pc) - const jumpPc = pc + stride - const jumpStride = jumpPc < words.length && (words[jumpPc]! & 0xff) === Op.EXTRA ? 2 : 1 - if (jumpPc + jumpStride > words.length || (words[jumpPc + jumpStride - 1]! & 0xff) !== Op.JUMP) { - errors.push(`${label}: T&S ITER_STEP at pc ${pc} not followed by JUMP`) - break - } - at(jumpPc, d + 2, pc) - at(jumpPc + jumpStride, d + 1, pc) - at(bx, d, pc) - break - } - case Op.ITER_RESULT: - checkSlot(a, pc) - next(0) - at(bx, d - 1, pc) - break - case Op.ITER_CLOSE: - checkSlot(a, pc) - next(2) - at(bx, d, pc) - break - case Op.ITER_APPEND_ALL: - checkSlot(a, pc) - next(0) - at(bx, d, pc) - break - case Op.AWAIT: - if (d < 1) errors.push(`${label}: AWAIT on empty stack at pc ${pc}`) - next(0) - break - case Op.YIELD: - if (d < 1) errors.push(`${label}: YIELD on empty stack at pc ${pc}`) - next(1) - break - case Op.RESUME: - if (d < 2) errors.push(`${label}: RESUME at depth ${d} (pc ${pc})`) - at(bx, d - 1, pc) - next(-1) - break - case Op.YSTAR: - checkSlot(a, pc) - if (d < 2) errors.push(`${label}: YSTAR at depth ${d} (pc ${pc})`) - at(bx, d + 1, pc) - next(-1) - break - case Op.YSTAR_RESULT: - checkSlot(a, pc) - if (d < 1) errors.push(`${label}: YSTAR_RESULT on empty stack at pc ${pc}`) - at(bx, d, pc) - next(0) - break - default: - errors.push(`${label}: unhandled op ${OpNames[op] ?? op} at pc ${pc}`) - break - } - } - - for (let i = 0; i < h.length; i += 4) { - const start = h[i]! - const end = h[i + 1]! - const handlerDepth = h[i + 3]! - for (let pc = start; pc < end; pc++) { - if (depth[pc]! !== -1 && depth[pc]! < handlerDepth) { - errors.push(`${label}: pc ${pc} depth ${depth[pc]} < handler depth ${handlerDepth}`) - } - } - } - - return errors -} - -export const verifyAll = (codes: ReadonlyArray): Array => codes.flatMap((c) => verifyCode(c)) diff --git a/packages/codemode/test/vm.test.ts b/packages/codemode/test/vm.test.ts deleted file mode 100644 index aba7a22f2fb..00000000000 --- a/packages/codemode/test/vm.test.ts +++ /dev/null @@ -1,584 +0,0 @@ -import { describe, expect, test } from "bun:test" -import { disassembleSource } from "../script/disasm.js" -import { hashOf } from "../src/language/code.js" -import { compileSource } from "../src/language/compiler/compile.js" -import { verifyAll } from "./verify-bytecode.js" -import { parseVmSource, runProgram } from "./run-program.js" - -const val = (code: string) => { - const parsed = parseVmSource(code) - if (parsed.ok) { - const errors = verifyAll(compileSource(parsed.source)) - expect(errors).toEqual([]) - } - const res = runProgram(code) - if (!res.ok) throw new Error(`${res.error.kind}: ${res.error.message}`) - return res.value -} - -const err = (code: string) => { - const res = runProgram(code) - if (res.ok) throw new Error(`Expected failure, got ${JSON.stringify(res.value)}`) - return res.error -} - -describe("VM compiler, verifier, and determinism", () => { - test("compiles deterministically and passes the stack-depth verifier", () => { - const src = ` - function fib(n) { return n < 2 ? n : fib(n - 1) + fib(n - 2) } - const fns = [] - for (let i = 0; i < 3; i++) fns.push(() => i) - try { - return [fib(6), fns.map((f) => f())] - } catch (e) { - return null - } finally { - fns.length = 0 - } - ` - const p1 = parseVmSource(src) - const p2 = parseVmSource(src) - expect(p1.ok && p2.ok).toBe(true) - if (!p1.ok || !p2.ok) return - const c1 = compileSource(p1.source, { noCache: true }) - const c2 = compileSource(p2.source, { noCache: true }) - expect(hashOf(c1)).toBe(hashOf(c2)) - expect(verifyAll(c1)).toEqual([]) - }) - - test("disassembler formats bytecode, locals, upvalues, handlers, and finallies", () => { - const out = disassembleSource(` - const fns = [] - for (let i = 0; i < 3; i++) fns.push(() => i) - try { return fns[1]() } catch (e) { return -1 } finally { fns.pop() } - `) - expect(out).toContain("fn#0 ") - expect(out).toContain("COPY_CELL") - expect(out).toContain("CLOSURE") - expect(out).toContain("END_FINALLY") - expect(out).toContain("GET_UPVAL") - }) - - test("forceExtra mode exercises EXTRA-prefixed 32-bit operands", () => { - const src = ` - let total = 0 - const add = (a, b = 10) => a + b - for (let i = 0; i < 10; i++) total += add(i) - return total - ` - const parsed = parseVmSource(src) - expect(parsed.ok).toBe(true) - if (!parsed.ok) return - const codes = compileSource(parsed.source, { forceExtra: true }) - expect(verifyAll(codes)).toEqual([]) - expect(val(src)).toBe(145) - }) -}) - -describe("scopes, TDZ, hoisting, and closures", () => { - test("var hoisting, function hoisting, and block-scoped function declarations", () => { - expect( - val(` - const before = [typeof hoistedFn, hoistedVar] - var hoistedVar = 42 - function hoistedFn() { return "top" } - function hoistedFn() { return "second" } - let blockVal - { - blockVal = inner() - function inner() { return "inner" } - } - return [before, hoistedVar, hoistedFn(), blockVal] - `), - ).toEqual([["function", null], 42, "second", "inner"]) - }) - - test("always-checked TDZ for let and const, including hoisted functions and loop blocks", () => { - expect(err(`const x = x + 1`).message).toContain("Cannot access 'x' before initialization") - expect(err(`{ f(); let x = 1; function f() { return x } }`).message).toContain( - "Cannot access 'x' before initialization", - ) - expect(err(`{ x = 1; const x = 2 }`).message).toContain("Cannot access 'x' before initialization") - expect(err(`const x = 1; x = 2`).message).toContain("Cannot assign to constant 'x'") - }) - - test("per-iteration let bindings in for, for-in, and for-of loops", () => { - expect( - val(` - const a = [] - for (let i = 0; i < 4; i++) a.push(() => i) - const b = [] - for (const k in { x: 1, y: 2 }) b.push(() => k) - const c = [] - for (let v of [10, 20, 30]) { - c.push(() => v) - v += 1 - } - return [a.map((f) => f()), b.map((f) => f()), c.map((f) => f())] - `), - ).toEqual([ - [0, 1, 2, 3], - ["x", "y"], - [11, 21, 31], - ]) - }) - - test("parameter scopes, TDZ between defaults, and parameter -> body var copy", () => { - expect( - val(` - const outer = "outer" - function f(a = () => outer, x = 1, b = () => x) { - var outer = "inner" - var x = 2 - return [a(), x, b()] - } - return f() - `), - ).toEqual(["outer", 2, 1]) - - expect(err(`function f(a = b, b = 1) { return a }; return f()`).message).toContain( - "Cannot access 'b' before initialization", - ) - }) - - test("arguments, rest parameters, duplicate non-strict params, and named function expressions", () => { - expect( - val(` - function dup(a, a) { return a } - function withArgs(a, b = 1) { - var arguments - const arrow = () => [...arguments] - return [arguments.length, arrow()] - } - const named = function self(n) { - return n <= 0 ? "done" : self(n - 1) - } - return [dup(1, 2), withArgs(10, 20, 30), named(2)] - `), - ).toEqual([2, [3, [10, 20, 30]], "done"]) - - expect(err(`const f = function me() { me = 1 }; f()`).message).toContain("Cannot assign to constant 'me'") - }) -}) - -describe("expressions, evaluation order, and destructuring", () => { - test("member evaluation order: nullish base before key conversion, base check before rhs", () => { - expect(err(`const base = null; base[{ toString() { throw new RangeError("boom") } }]`).message).toContain( - "Cannot read properties of null", - ) - expect(err(`(1).x = (() => { throw new RangeError("rhs ran") })()`).message).toContain( - "Cannot create property 'x' on number '1'", - ) - expect( - val(` - const log = [] - const key = { toString() { log.push("key"); return "a" } } - const o = { a: 10 } - o[key] += (log.push("rhs"), 5) - const post = o[key]++ - const pre = ++o[key] - return [o.a, post, pre, log] - `), - ).toEqual([17, 15, 17, ["key", "rhs", "key", "key"]]) - }) - - test("optional chaining and short-circuiting", () => { - expect( - val(` - const o = { a: { b: (x) => ({ c: x * 2 }) } } - const n = null - return [ - o?.a.b(21).c, - n?.a.b(1).c, - o.a.missing?.(1), - delete n?.a.b, - ] - `), - ).toEqual([42, null, null, true]) - }) - - test("object and array destructuring with defaults, rest, and custom iterator close", () => { - expect( - val(` - const closed = [] - const iterable = { - [Symbol.iterator]() { - let i = 0 - return { - next() { return { value: ++i, done: false } }, - return() { closed.push(i); return {} }, - } - } - } - const [first, , third] = iterable - const { a = 1, b: { c = 2 } = {}, ...rest } = { b: { c: 3 }, x: 4, y: 5 } - return [first, third, closed, a, c, rest] - `), - ).toEqual([1, 3, [3], 1, 3, { x: 4, y: 5 }]) - }) -}) - -describe("try/catch/finally static tag routing", () => { - test("all synchronous spike finally cases pass and verify", () => { - expect( - val(` - const out = [] - function f() { try { out.push("t"); return "r" } finally { out.push("f") } } - out.push(f()) - return out.join(",") - `), - ).toBe("t,f,r") - - expect( - val(` - const out = [] - function f() { try { out.push("t"); throw "e" } finally { out.push("f") } } - try { f() } catch (e) { out.push("c:" + e) } - return out.join(",") - `), - ).toBe("t,f,c:e") - - expect( - val(` - const out = [] - outer: for (let i = 0; i < 4; i++) { - try { - for (let j = 0; j < 3; j++) { - try { - try { - if (j === 1) continue - if (i === 1 && j === 2) continue outer - if (i === 2 && j === 2) break outer - out.push(i + ":" + j) - } finally { out.push("a" + j) } - } finally { out.push("b" + j) } - } - } finally { out.push("c" + i) } - } - out.push("end") - return out.join(",") - `), - ).toBe("0:0,a0,b0,a1,b1,0:2,a2,b2,c0,1:0,a0,b0,a1,b1,a2,b2,c1,2:0,a0,b0,a1,b1,a2,b2,c2,end") - - expect( - val(` - const out = [] - function f() { try { throw "e" } finally { return "fin" } } - out.push(f()) - function g() { try { return "a" } finally { return "b" } } - out.push(g()) - return out.join(",") - `), - ).toBe("fin,b") - - expect( - val(` - const out = [] - function f() { - try { return "r" } finally { - try { throw "x" } catch (e) { out.push("c" + e) } - out.push("after") - } - } - out.push(f()) - function g(n) { - for (let i = 0; i < 3; i++) { - try { if (i === n) return "ret" + i } finally { - try { if (i === 1) throw "boom" } catch (e) { out.push("caught " + e) } finally { out.push("inner" + i) } - } - } - return "none" - } - out.push(g(1)) - out.push(g(5)) - return out.join(",") - `), - ).toBe("cx,after,r,inner0,caught boom,inner1,ret1,inner0,caught boom,inner1,inner2,none") - - expect( - val(` - const out = [] - function f() { - try { throw "outer" } finally { - try { try { throw "inner" } finally { out.push("if") } } catch (e) { out.push("caught " + e) } - out.push("of") - } - } - try { f() } catch (e) { out.push("final " + e) } - return out.join(",") - `), - ).toBe("if,caught inner,of,final outer") - - expect( - val(` - const out = [] - for (let i = 0; i < 3; i++) { try { throw "e" + i } finally { out.push("f" + i); break } } - out.push("done") - let k = 0 - while (k < 3) { k++; try { try { throw "x" } finally { out.push("in" + k); continue } } finally { out.push("out" + k) } } - out.push("k" + k) - return out.join(",") - `), - ).toBe("f0,done,in1,out1,in2,out2,in3,out3,k3") - - // Spike cases 8-12: generators + yield in try/finally + for-of - expect( - val(` - const out = [] - function* g() { try { yield 1; yield 2 } finally { out.push("cleanup") } out.push("unreached") } - const it = g() - out.push(it.next().value) - const r = it.return(9) - out.push(r.value + "/" + r.done) - out.push(String(it.next().done)) - const it2 = g() - const r2 = it2.return(3) - out.push(r2.value + "/" + r2.done) - return out.join(",") - `), - ).toBe("1,cleanup,9/true,true,3/true") - - expect( - val(` - const out = [] - function* g() { try { yield 1 } finally { yield "f"; out.push("after-f") } } - const it = g() - it.next() - let r = it.return(9) - out.push(r.value + "/" + r.done) - r = it.next() - out.push(r.value + "/" + r.done) - r = it.next() - out.push(String(r.value) + "/" + r.done) - const it2 = g() - it2.next() - it2.return(1) - r = it2.return(2) - out.push(r.value + "/" + r.done) - return out.join(",") - `), - ).toBe("f/false,after-f,9/true,undefined/true,2/true") - - expect( - val(` - const out = [] - function* g() { try { yield 1 } finally { try { yield "f" } catch (e) { out.push("caught " + e) } out.push("end-f") } } - const it = g() - it.next() - let r = it.return(5) - out.push(r.value + "/" + r.done) - r = it.throw("boom") - out.push(r.value + "/" + r.done) - function* g2() { try { yield 1 } finally { yield 2; out.push("g2-after") } } - const it2 = g2() - it2.next() - r = it2.throw("x") - out.push(r.value + "/" + r.done) - try { it2.next() } catch (e) { out.push("rethrown " + e) } - r = it2.next() - out.push(String(r.value) + "/" + r.done) - return out.join(",") - `), - ).toBe("f/false,caught boom,end-f,5/true,2/false,g2-after,rethrown x,undefined/true") - - expect( - val(` - const out = [] - function* g() { try { const v = 1 + (yield 2); out.push(v) } finally { out.push("f") } return "end" } - const it = g() - out.push(it.next().value) - let r = it.return(7) - out.push(r.value + "/" + r.done) - const it2 = g() - it2.next() - r = it2.next(10) - out.push(r.value + "/" + r.done) - function* h() { const xs = [1, 2]; try { xs.push(3 + (yield xs.length) * (yield 5)) } finally { out.push("h" + xs.join("")) } } - const it3 = h() - it3.next() - it3.next(4) - r = it3.return(8) - out.push(r.value + "/" + r.done) - return out.join(",") - `), - ).toBe("2,f,7/true,11,f,end/true,h12,8/true") - - expect( - val(` - const out = [] - function* src() { try { yield 1; yield 2; yield 3 } finally { out.push("src-closed") } } - function f() { - for (const x of src()) { - try { if (x === 2) return x * 10 } finally { out.push("f" + x) } - } - return "no" - } - out.push(f()) - function g() { - for (const x of [1, 2, 3]) { try { if (x === 2) return "arr" + x } finally { out.push("af" + x) } } - } - out.push(g()) - function* outer() { - try { for (const x of src()) { try { yield x } finally { out.push("of" + x) } } } finally { out.push("outer-f") } - } - const it = outer() - it.next() - it.next() - const r = it.return(42) - out.push(r.value + "/" + r.done) - function h() { - for (const x of src()) { for (const y of [7, 8]) { try { if (x === 1 && y === 8) break } finally { out.push("y" + y) } } if (x === 2) break } - return "h" - } - out.push(h()) - function t() { - try { for (const x of src()) { if (x === 2) throw "thrown" + x } } catch (e) { out.push("t:" + e) } - } - t() - return out.join(",") - `), - ).toBe( - "f1,f2,src-closed,20,af1,af2,arr2,of1,of2,src-closed,outer-f,42/true,y7,y8,y7,y8,src-closed,h,src-closed,t:thrown2", - ) - }) -}) - -describe("generators, async functions, async generators, yield*, and for-await", () => { - test("verifies and executes sync/async generators, yield*, for-await, and Promise combinators (including forceExtra)", () => { - const src = ` - function* innerSync() { - const x = yield 10 - return x * 2 - } - function* outerSync() { - const r = yield* innerSync() - yield r + 1 - } - async function* innerAsync() { - yield await Promise.resolve(1) - return Promise.resolve(5) - } - async function* outerAsync() { - const d = yield* innerAsync() - yield d * 10 - } - const syncOut = [] - const g = outerSync() - syncOut.push(g.next().value) - syncOut.push(g.next(3).value) - const asyncOut = [] - for await (const item of outerAsync()) { - asyncOut.push(item) - } - const all = await Promise.all([Promise.resolve("a"), "b", Promise.try(() => "c")]) - const iterHelper = [1, 2, 3, 4].values().map((x) => x * 10).filter((x) => x > 10).toArray() - return [syncOut, asyncOut, all, iterHelper] - ` - const parsed = parseVmSource(src) - expect(parsed.ok).toBe(true) - if (!parsed.ok) return - expect(verifyAll(compileSource(parsed.source, { forceExtra: true }))).toEqual([]) - const dis = disassembleSource(src) - expect(dis).toContain("GENERATOR_START") - expect(dis).toContain("YIELD") - expect(dis).toContain("RESUME") - expect(dis).toContain("AWAIT") - expect(dis).toContain("YSTAR") - expect(dis).toContain("YSTAR_RESULT") - expect(val(src)).toEqual([ - [10, 7], - [1, 50], - ["a", "b", "c"], - [20, 30, 40], - ]) - }) -}) - -describe("built-ins, prelude, and coercion", () => { - test("array callbacks, sort, Map/Set, Object.groupBy, JSON reviver/replacer, and ToPrimitive", () => { - expect( - val(` - const arr = Array.from({ length: 6 }, (_, i) => i + 1) - const mapped = arr.map((x) => x * 2).filter((x) => x > 4) - const sum = mapped.reduce((a, b) => a + b, 0) - const sorted = [3, 1, 4, 1, 5].sort((a, b) => a - b) - const grouped = Object.groupBy(["a", "bb", "c", "dd"], (s) => s.length) - const parsed = JSON.parse('{"a":1,"b":2}', (k, v) => (typeof v === "number" ? v * 10 : v)) - const str = JSON.stringify({ x: 1, y: { toJSON() { return 99 } } }) - const coerced = { valueOf() { return 7 } } * 6 - return [mapped, sum, sorted, grouped, parsed, str, coerced] - `), - ).toEqual([ - [6, 8, 10, 12], - 36, - [1, 1, 3, 4, 5], - { "1": ["a", "c"], "2": ["bb", "dd"] }, - { a: 10, b: 20 }, - '{"x":1,"y":99}', - 42, - ]) - }) - - test("Function.prototype.call, apply, bind, and built-in callbacks", () => { - expect( - val(` - function greet(prefix, suffix) { - return prefix + ":" + this.name + ":" + suffix - } - const bound = greet.bind({ name: "vm" }, "hi") - return [ - greet.call({ name: "c" }, "a", "b"), - greet.apply({ name: "ap" }, ["x", "y"]), - bound("!"), - bound.name, - bound.length, - [-1, 2, -3].map(Math.abs), - ["1", "2"].map(Number.parseInt), - ["a", "b"].map(Error).map((e) => e.message), - ] - `), - ).toEqual(["a:c:b", "x:ap:y", "hi:vm:!", "bound greet", 1, [1, 2, 3], [1, null], ["a", "b"]]) - }) - - test("new expressions, Set composition, Uint8Array, String callbacks, and imports", () => { - expect( - val(` - import { URL as ImportedURL } from "node:url" - const s1 = new Set([1, 2, 3]) - const s2 = new Set([2, 3, 4]) - const bytes = Uint8Array.from([1, 2, 3], (x) => x * 10) - const replaced = "a1b22c".replace(/(\\d+)/g, (m) => "[" + m + "]") - const u = new ImportedURL("https://example.com/p?q=1") - const errWithCause = new TypeError("bad", { cause: "root" }) - return [ - [...s1.union(s2)], - [...s1.intersection(s2)], - [...s1.difference(s2)], - [...bytes.map((b) => b + 1)], - replaced, - u.searchParams.get("q"), - errWithCause.cause, - ] - `), - ).toEqual([[1, 2, 3, 4], [2, 3], [1], [11, 21, 31], "a[1]b[22]c", "1", "root"]) - }) - - test("error locations, rethrow preservation, and call stack depth limit", () => { - const e1 = err(`const a = 1\nconst b = null\nreturn b.foo`) - expect(e1.location).toEqual({ line: 3, column: 8 }) - - const e2 = err(`const a = 1\ntry {\n null.bar\n} catch (e) {\n throw e\n}`) - expect(e2.location).toEqual({ line: 3, column: 3 }) - - expect( - val(` - function recurse(n) { return recurse(n + 1) } - try { - recurse(0) - } catch (e) { - return [e instanceof RangeError, e.message.includes("Maximum call stack size exceeded")] - } - `), - ).toEqual([true, true]) - }) -}) diff --git a/packages/codemode/test/web-wpt.test.ts b/packages/codemode/test/web-wpt.test.ts deleted file mode 100644 index 05e51d06457..00000000000 --- a/packages/codemode/test/web-wpt.test.ts +++ /dev/null @@ -1,424 +0,0 @@ -/** - * Portions adapted from web-platform-tests at revision 863077959ca8c1a7ceecfbe2534b75d2527b9013: - * - html/webappapis/atob/base64.any.js (btoa reference encoder, input list, and atob WebIDL cases) - * - fetch/data-urls/resources/base64.json (copied to fixtures/wpt-base64.json) - * - WebCryptoAPI/randomUUID.https.any.js - * - fetch/api/headers/{headers-basic,headers-errors}.any.js - * - * Copyright © web-platform-tests contributors. Governed by the 3-Clause BSD license in LICENSE.wpt. - * - * `assert_throws_dom("InvalidCharacterError", …)` becomes a check for a TypeError: CodeMode has no DOMException. - * `checkIteratorProperties` (prototype chain and property descriptors) and the custom iterator on a Headers - * instance are left out. - */ -import { describe, expect, test } from "bun:test" -import { Effect } from "effect" -import { CodeMode } from "../src/index.js" - -const base64Cases = (await Bun.file(new URL("./fixtures/wpt-base64.json", import.meta.url)).json()) as Array< - [string, Array | null] -> - -const value = async (code: string) => { - const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} })) - if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`) - return result.value -} - -// The reference encoder from base64.any.js, run inside the interpreter so btoa is checked against -// an independent implementation rather than against the host's btoa. -const referenceEncoder = ` - function btoaLookup(idx) { - if (idx < 26) return String.fromCharCode(idx + "A".charCodeAt(0)) - if (idx < 52) return String.fromCharCode(idx - 26 + "a".charCodeAt(0)) - if (idx < 62) return String.fromCharCode(idx - 52 + "0".charCodeAt(0)) - if (idx == 62) return "+" - if (idx == 63) return "/" - } - function mybtoa(s) { - s = String(s) - for (var i = 0; i < s.length; i++) if (s.charCodeAt(i) > 255) return "INVALID_CHARACTER_ERR" - var out = "" - for (var i = 0; i < s.length; i += 3) { - var groupsOfSix = [undefined, undefined, undefined, undefined] - groupsOfSix[0] = s.charCodeAt(i) >> 2 - groupsOfSix[1] = (s.charCodeAt(i) & 0x03) << 4 - if (s.length > i + 1) { - groupsOfSix[1] |= s.charCodeAt(i + 1) >> 4 - groupsOfSix[2] = (s.charCodeAt(i + 1) & 0x0f) << 2 - } - if (s.length > i + 2) { - groupsOfSix[2] |= s.charCodeAt(i + 2) >> 6 - groupsOfSix[3] = s.charCodeAt(i + 2) & 0x3f - } - for (var j = 0; j < groupsOfSix.length; j++) { - out += typeof groupsOfSix[j] == "undefined" ? "=" : btoaLookup(groupsOfSix[j]) - } - } - return out - } - function testBtoa(input) { - var expected = mybtoa(input) - if (expected === "INVALID_CHARACTER_ERR") { - try { btoa(input) } catch (error) { return error instanceof TypeError ? "ok" : error.name } - return "did not throw" - } - if (btoa(input) !== expected) return "btoa mismatch" - if (atob(btoa(input)) !== String(input)) return "roundtrip mismatch" - return "ok" - } -` - -describe("btoa WPT parity (html/webappapis/atob/base64.any.js)", () => { - test("every input encodes like the reference encoder and round-trips through atob", async () => { - expect( - await value(` - ${referenceEncoder} - var tests = ["עברית", "", "ab", "abc", "abcd", "abcde", "\\xff\\xff\\xc0", "\\0a", "a\\0b", - undefined, null, 7, 12, 1.5, true, false, NaN, +Infinity, -Infinity, 0, -0] - for (var i = 0; i < 258; i++) tests.push(String.fromCharCode(i)) - tests.push(String.fromCharCode(10000), String.fromCharCode(65534), String.fromCharCode(65535)) - tests.push(String.fromCharCode(0xd800, 0xdc00)) - var everything = "" - for (var i = 0; i < 256; i++) everything += String.fromCharCode(i) - tests.push(everything) - return tests.map(testBtoa).filter((outcome) => outcome !== "ok") - `), - ).toEqual([]) - }) -}) - -describe("atob WPT parity (fetch/data-urls/resources/base64.json)", () => { - const idlCases: Array<[unknown, Array | null]> = [ - [undefined, null], - [null, [158, 233, 101]], - [7, null], - [12, [215]], - [1.5, null], - [true, [182, 187]], - [false, null], - [NaN, [53, 163]], - [Infinity, [34, 119, 226, 158, 43, 114]], - [-Infinity, null], - [0, null], - [-0, null], - ] - - test(`${base64Cases.length} forgiving-base64 inputs decode to the expected bytes or throw a TypeError`, async () => { - expect( - await value(` - const cases = ${JSON.stringify(base64Cases)} - return cases.flatMap(([input, output]) => { - try { - const result = atob(input) - if (output === null) return [[input, "expected throw"]] - const bytes = Array.from({ length: result.length }, (_, i) => result.charCodeAt(i)) - return JSON.stringify(bytes) === JSON.stringify(output) ? [] : [[input, bytes]] - } catch (error) { - return output === null && error instanceof TypeError ? [] : [[input, error.name]] - } - }) - `), - ).toEqual([]) - }) - - test("WebIDL argument conversion stringifies non-string inputs", async () => { - const literal = (input: unknown) => - Object.is(input, -0) - ? "-0" - : typeof input === "number" || input === undefined - ? String(input) - : JSON.stringify(input) - expect( - await value(` - const cases = [${idlCases.map(([input, output]) => `[${literal(input)}, ${JSON.stringify(output)}]`).join(",")}] - return cases.flatMap(([input, output]) => { - try { - const result = atob(input) - if (output === null) return [[String(input), "expected throw"]] - // The source loop checks only the listed prefix of the decoded bytes. - const bytes = output.map((_, i) => result.charCodeAt(i)) - return JSON.stringify(bytes) === JSON.stringify(output) ? [] : [[String(input), bytes]] - } catch (error) { - return output === null && error instanceof TypeError ? [] : [[String(input), error.name]] - } - }) - `), - ).toEqual([]) - }) -}) - -describe("crypto.randomUUID WPT parity (WebCryptoAPI/randomUUID.https.any.js)", () => { - test("namespace format, version, and variant bits over 256 iterations without collision", async () => { - expect( - await value(` - const uuids = new Set() - const randomUUID = () => { - const uuid = crypto.randomUUID() - if (uuids.has(uuid)) throw new Error("uuid collision " + uuid) - uuids.add(uuid) - return uuid - } - const UUIDRegex = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/ - let format = true, version = true, variant = true - for (let i = 0; i < 256; i++) format = format && UUIDRegex.test(randomUUID()) - for (let i = 0; i < 256; i++) version = version && (parseInt(randomUUID().split("-")[2].slice(0, 2), 16) & 0b11110000) === 0b01000000 - for (let i = 0; i < 256; i++) variant = variant && (parseInt(randomUUID().split("-")[3].slice(0, 2), 16) & 0b11000000) === 0b10000000 - return [format, version, variant, uuids.size] - `), - ).toEqual([true, true, true, 768]) - }) -}) - -// Enough of testharness.js to run the Headers files close to verbatim; each `test` records its failure, if any. -const testharness = ` - const failures = [] - function test(run, name) { try { run() } catch (error) { failures.push(name + ": " + (error && error.message ? error.message : error)) } } - function assert_equals(actual, expected, message) { if (actual !== expected) throw new Error((message || "") + " expected " + JSON.stringify(expected) + " got " + JSON.stringify(actual)) } - function assert_true(actual, message) { assert_equals(actual, true, message) } - function assert_false(actual, message) { assert_equals(actual, false, message) } - function assert_array_equals(actual, expected, message) { assert_equals(JSON.stringify(actual), JSON.stringify(expected), message) } - function assert_throws_js(type, run) { try { run() } catch (error) { if (error instanceof type) return; throw new Error("threw " + error.name) } throw new Error("did not throw") } - function assert_unreached() { throw new Error("unreachable") } -` - -describe("Headers WPT parity (fetch/api/headers)", () => { - test("headers-basic.any.js", async () => { - expect( - await value(` - ${testharness} - test(function() { new Headers() }, "Create headers from no parameter") - test(function() { new Headers(undefined) }, "Create headers from undefined parameter") - test(function() { new Headers({}) }, "Create headers from empty object") - var parameters = [null, 1] - parameters.forEach(function(parameter) { - test(function() { assert_throws_js(TypeError, function() { new Headers(parameter) }) }, "Create headers with " + parameter + " should throw") - }) - var headerDict = {"name1": "value1", "name2": "value2", "name3": "value3", "name4": null, "name5": undefined, "name6": 1, "Content-Type": "value4"} - var headerSeq = [] - for (var name in headerDict) headerSeq.push([name, headerDict[name]]) - test(function() { - var headers = new Headers(headerSeq) - for (name in headerDict) assert_equals(headers.get(name), String(headerDict[name]), "name: " + name + " has value: " + headerDict[name]) - assert_equals(headers.get("length"), null, "init should be treated as a sequence, not as a dictionary") - }, "Create headers with sequence") - test(function() { - var headers = new Headers(headerDict) - for (name in headerDict) assert_equals(headers.get(name), String(headerDict[name]), "name: " + name + " has value: " + headerDict[name]) - }, "Create headers with record") - test(function() { - var headers = new Headers(headerDict) - var headers2 = new Headers(headers) - for (name in headerDict) assert_equals(headers2.get(name), String(headerDict[name]), "name: " + name + " has value: " + headerDict[name]) - }, "Create headers with existing headers") - test(function() { - var headers = new Headers() - for (name in headerDict) { - headers.append(name, headerDict[name]) - assert_equals(headers.get(name), String(headerDict[name]), "name: " + name + " has value: " + headerDict[name]) - } - }, "Check append method") - test(function() { - var headers = new Headers() - for (name in headerDict) { - headers.set(name, headerDict[name]) - assert_equals(headers.get(name), String(headerDict[name]), "name: " + name + " has value: " + headerDict[name]) - } - }, "Check set method") - test(function() { - var headers = new Headers(headerDict) - for (name in headerDict) assert_true(headers.has(name), "headers has name " + name) - assert_false(headers.has("nameNotInHeaders"), "headers do not have header: nameNotInHeaders") - }, "Check has method") - test(function() { - var headers = new Headers(headerDict) - for (name in headerDict) { - assert_true(headers.has(name), "headers have a header: " + name) - headers.delete(name) - assert_true(!headers.has(name), "headers do not have anymore a header: " + name) - } - }, "Check delete method") - test(function() { - var headers = new Headers(headerDict) - for (name in headerDict) assert_equals(headers.get(name), String(headerDict[name]), "name: " + name + " has value: " + headerDict[name]) - assert_equals(headers.get("nameNotInHeaders"), null, "header: nameNotInHeaders has no value") - }, "Check get method") - var headerEntriesDict = {"name1": "value1", "Name2": "value2", "name": "value3", "content-Type": "value4", "Content-Typ": "value5", "Content-Types": "value6"} - var sortedHeaderDict = {} - var headerValues = [] - var sortedHeaderKeys = Object.keys(headerEntriesDict).map(function(value) { - sortedHeaderDict[value.toLowerCase()] = headerEntriesDict[value] - headerValues.push(headerEntriesDict[value]) - return value.toLowerCase() - }).sort() - test(function() { - var headers = new Headers(headerEntriesDict) - var actual = headers.keys() - sortedHeaderKeys.forEach(function(key) { - const entry = actual.next() - assert_false(entry.done) - assert_equals(entry.value, key) - }) - assert_true(actual.next().done) - assert_true(actual.next().done) - for (const key of headers.keys()) assert_true(sortedHeaderKeys.indexOf(key) != -1) - }, "Check keys method") - test(function() { - var headers = new Headers(headerEntriesDict) - var actual = headers.values() - sortedHeaderKeys.forEach(function(key) { - const entry = actual.next() - assert_false(entry.done) - assert_equals(entry.value, sortedHeaderDict[key]) - }) - assert_true(actual.next().done) - assert_true(actual.next().done) - for (const value of headers.values()) assert_true(headerValues.indexOf(value) != -1) - }, "Check values method") - test(function() { - var headers = new Headers(headerEntriesDict) - var actual = headers.entries() - sortedHeaderKeys.forEach(function(key) { - const entry = actual.next() - assert_false(entry.done) - assert_equals(entry.value[0], key) - assert_equals(entry.value[1], sortedHeaderDict[key]) - }) - assert_true(actual.next().done) - assert_true(actual.next().done) - for (const entry of headers.entries()) assert_equals(entry[1], sortedHeaderDict[entry[0]]) - }, "Check entries method") - test(function() { - var headers = new Headers(headerEntriesDict) - var actual = headers[Symbol.iterator]() - sortedHeaderKeys.forEach(function(key) { - const entry = actual.next() - assert_false(entry.done) - assert_equals(entry.value[0], key) - assert_equals(entry.value[1], sortedHeaderDict[key]) - }) - assert_true(actual.next().done) - assert_true(actual.next().done) - }, "Check Symbol.iterator method") - test(function() { - var headers = new Headers(headerEntriesDict) - var reference = sortedHeaderKeys[Symbol.iterator]() - headers.forEach(function(value, key, container) { - assert_equals(headers, container) - const entry = reference.next() - assert_false(entry.done) - assert_equals(key, entry.value) - assert_equals(value, sortedHeaderDict[entry.value]) - }) - assert_true(reference.next().done) - }, "Check forEach method") - test(() => { - const headers = new Headers({"foo": "2", "baz": "1", "BAR": "0"}) - const actualKeys = [] - const actualValues = [] - for (const [header, value] of headers) { - actualKeys.push(header) - actualValues.push(value) - headers.delete("foo") - } - assert_array_equals(actualKeys, ["bar", "baz"]) - assert_array_equals(actualValues, ["0", "1"]) - }, "Iteration skips elements removed while iterating") - test(() => { - const headers = new Headers({"foo": "2", "baz": "1", "BAR": "0", "quux": "3"}) - const actualKeys = [] - const actualValues = [] - for (const [header, value] of headers) { - actualKeys.push(header) - actualValues.push(value) - if (header === "baz") headers.delete("bar") - } - assert_array_equals(actualKeys, ["bar", "baz", "quux"]) - assert_array_equals(actualValues, ["0", "1", "3"]) - }, "Removing elements already iterated over causes an element to be skipped during iteration") - test(() => { - const headers = new Headers({"foo": "2", "baz": "1", "BAR": "0", "quux": "3"}) - const actualKeys = [] - const actualValues = [] - for (const [header, value] of headers) { - actualKeys.push(header) - actualValues.push(value) - if (header === "baz") headers.append("X-yZ", "4") - } - assert_array_equals(actualKeys, ["bar", "baz", "foo", "quux", "x-yz"]) - assert_array_equals(actualValues, ["0", "1", "2", "3", "4"]) - }, "Appending a value pair during iteration causes it to be reached during iteration") - test(() => { - const headers = new Headers({"foo": "2", "baz": "1", "BAR": "0", "quux": "3"}) - const actualKeys = [] - const actualValues = [] - for (const [header, value] of headers) { - actualKeys.push(header) - actualValues.push(value) - if (header === "baz") headers.append("abc", "-1") - } - assert_array_equals(actualKeys, ["bar", "baz", "baz", "foo", "quux"]) - assert_array_equals(actualValues, ["0", "1", "1", "2", "3"]) - }, "Prepending a value pair before the current element position causes it to be skipped during iteration and adds the current element a second time") - return failures - `), - ).toEqual([]) - }) - - test("headers-errors.any.js", async () => { - expect( - await value(` - ${testharness} - test(function() { assert_throws_js(TypeError, function() { new Headers([["name"]]) }) }, "Create headers giving an array having one string as init argument") - test(function() { assert_throws_js(TypeError, function() { new Headers([["invalid", "invalidValue1", "invalidValue2"]]) }) }, "Create headers giving an array having three strings as init argument") - test(function() { assert_throws_js(TypeError, function() { new Headers([["invalid\u0100", "Value1"]]) }) }, "Create headers giving bad header name as init argument") - test(function() { assert_throws_js(TypeError, function() { new Headers([["name", "invalidValue\u0100"]]) }) }, "Create headers giving bad header value as init argument") - var badNames = ["invalid\u0100", {}] - var badValues = ["invalid\u0100"] - badNames.forEach(function(name) { - test(function() { var headers = new Headers(); assert_throws_js(TypeError, function() { headers.get(name) }) }, "Check headers get with an invalid name " + name) - }) - badNames.forEach(function(name) { - test(function() { var headers = new Headers(); assert_throws_js(TypeError, function() { headers.delete(name) }) }, "Check headers delete with an invalid name " + name) - }) - badNames.forEach(function(name) { - test(function() { var headers = new Headers(); assert_throws_js(TypeError, function() { headers.has(name) }) }, "Check headers has with an invalid name " + name) - }) - badNames.forEach(function(name) { - test(function() { var headers = new Headers(); assert_throws_js(TypeError, function() { headers.set(name, "Value1") }) }, "Check headers set with an invalid name " + name) - }) - badValues.forEach(function(value) { - test(function() { var headers = new Headers(); assert_throws_js(TypeError, function() { headers.set("name", value) }) }, "Check headers set with an invalid value " + value) - }) - badNames.forEach(function(name) { - test(function() { var headers = new Headers(); assert_throws_js(TypeError, function() { headers.append("invalid\u0100", "Value1") }) }, "Check headers append with an invalid name " + name) - }) - badValues.forEach(function(value) { - test(function() { var headers = new Headers(); assert_throws_js(TypeError, function() { headers.append("name", value) }) }, "Check headers append with an invalid value " + value) - }) - test(function() { - var headers = new Headers([["name", "value"]]) - assert_throws_js(TypeError, function() { headers.forEach() }) - assert_throws_js(TypeError, function() { headers.forEach(undefined) }) - assert_throws_js(TypeError, function() { headers.forEach(1) }) - }, "Headers forEach throws if argument is not callable") - test(function() { - var headers = new Headers([["name1", "value1"], ["name2", "value2"], ["name3", "value3"]]) - var counter = 0 - try { - headers.forEach(function(value, name) { - counter++ - if (name == "name2") throw "error" - }) - } catch (e) { - assert_equals(counter, 2) - assert_equals(e, "error") - return - } - assert_unreached() - }, "Headers forEach loop should stop if callback is throwing exception") - return failures - `), - ).toEqual([]) - }) -})