mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-26 23:28:43 +00:00
refactor(codemode): use the psychoscript package for the language (#65011)
This commit is contained in:
parent
aaa9bff2a3
commit
eb2dfb2638
141 changed files with 62 additions and 47568 deletions
|
|
@ -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": [
|
||||
|
|
|
|||
3
bun.lock
3
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=="],
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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`).
|
||||
|
|
|
|||
|
|
@ -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 }`
|
||||
(`<runId>:<callId>`). `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
|
||||
|
||||
|
|
|
|||
|
|
@ -1,2 +0,0 @@
|
|||
[test]
|
||||
preload = ["./test/preload.ts"]
|
||||
|
|
@ -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 `<Buffer ..>`.
|
||||
- [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 (<program>: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 <program>: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: <value>`.
|
||||
|
|
@ -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:",
|
||||
|
|
|
|||
|
|
@ -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<readonly [name: string, code: string]> = [
|
||||
[
|
||||
"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<number>) => {
|
||||
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<number>) => {
|
||||
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<number> => [])
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
|
@ -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`
|
||||
|
|
|
|||
|
|
@ -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<string> = []
|
||||
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<string> = []
|
||||
const header = `=== fn#${c.index} ${c.name || "<anonymous>"} (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<string> = []
|
||||
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<string> = []
|
||||
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<string> = []
|
||||
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<number> = []
|
||||
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> | 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 <code-or-file>")
|
||||
process.exit(1)
|
||||
}
|
||||
const file = Bun.file(arg)
|
||||
const source = (await file.exists()) ? await file.text() : arg
|
||||
console.log(disassembleSource(source))
|
||||
}
|
||||
|
|
@ -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`,
|
||||
)
|
||||
}
|
||||
|
|
@ -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<number> = []
|
||||
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")))
|
||||
|
|
@ -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<string>; features?: Array<string>; includes?: Array<string> }
|
||||
|
||||
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<string>
|
||||
harness: Array<string>
|
||||
flags: Array<string>
|
||||
features: Array<string>
|
||||
boundaries: Record<string, string>
|
||||
}
|
||||
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<string, number>()
|
||||
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}`)
|
||||
}
|
||||
|
|
@ -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<string> = []
|
||||
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<string, Array<string>>()
|
||||
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`)
|
||||
}
|
||||
|
|
@ -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<R = never, E = never> = {
|
|||
}
|
||||
|
||||
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<string, unknown>,
|
||||
|
|
@ -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<string, Language.Runtime.Runtime<R>>()
|
||||
const runtimes = new Map<string, Language.Runtime<R>>()
|
||||
const runtimeFor = (selected: ReadonlyArray<Extension> = 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<R>
|
||||
}) as unknown as Language.Runtime<R>
|
||||
runtimes.set(key, made)
|
||||
return made
|
||||
}
|
||||
|
|
@ -365,13 +374,13 @@ const extensionFunction = <R>(
|
|||
}
|
||||
|
||||
// A language program whose outcomes report the run's tool calls in place of its metadata.
|
||||
const reported = <R, E>(program: Language.Runtime.Program<R, E>): Program<R, E> => ({
|
||||
const reported = <R, E>(program: Language.Program<R, E>): Program<R, E> => ({
|
||||
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
|
||||
|
|
|
|||
|
|
@ -69,7 +69,7 @@ export const make = <const Globals extends Readonly<Record<string, unknown>>>(
|
|||
|
||||
const asyncGlobals = new WeakSet<Function>()
|
||||
|
||||
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. */
|
||||
|
|
|
|||
|
|
@ -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.<path>` referenced by a Code Mode program, in first-seen order. Fails on syntax errors,
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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<Frame, Parked>()
|
||||
readonly queue: Array<Job> = []
|
||||
head = 0
|
||||
pending = 0
|
||||
nextID = 0
|
||||
readonly unhandled = new Map<PromiseObj, Diagnostic>()
|
||||
|
||||
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<Frame>, 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<Value>()
|
||||
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<Diagnostic> {
|
||||
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<Value>,
|
||||
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<unknown>,
|
||||
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<Value>,
|
||||
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<string, unknown>, vm: Vm): void => {
|
||||
const ctx = vm.ctx
|
||||
const builtins = ctx.builtins
|
||||
const add = (name: string, fn: (args: Array<Value>) => 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))
|
||||
}
|
||||
|
|
@ -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<number>
|
||||
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<ConstValue>
|
||||
/** 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<string>
|
||||
readonly upvalNames: ReadonlyArray<string>
|
||||
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<ConstValue>
|
||||
readonly captures: Int32Array
|
||||
readonly handlers: Int32Array
|
||||
readonly finallies: Int32Array
|
||||
readonly finallyOffsets: Int32Array
|
||||
readonly sites: Int32Array
|
||||
readonly localNames: ReadonlyArray<string>
|
||||
readonly upvalNames?: ReadonlyArray<string> | 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<ConstValue> = [""]
|
||||
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<typeof Code>[0]),
|
||||
...Object.fromEntries(words.map((field) => [field, Int32Array.from(data[field] as Array<number>)])),
|
||||
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<number> = []
|
||||
private readonly sitePairs: Array<number> = []
|
||||
private lastNodeIndex = -2
|
||||
private readonly constList: Array<ConstValue> = []
|
||||
// Strings and numbers (but -0) are pooled; other constants are each their own.
|
||||
private readonly pooled = new Map<string | number, number>()
|
||||
private readonly handlerWords: Array<number> = []
|
||||
private readonly finallyWords: Array<number> = []
|
||||
private readonly finallyLevelOffsets: Array<number> = []
|
||||
|
||||
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<string>,
|
||||
readonly captures: Int32Array,
|
||||
readonly upvalNames: ReadonlyArray<string> = [],
|
||||
) {}
|
||||
|
||||
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<number>,
|
||||
): 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<Code>): 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")
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -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<string, Decl>()
|
||||
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<Pattern>
|
||||
readonly selfScope: Scope | undefined
|
||||
readonly paramScope: Scope
|
||||
readonly bodyScope: Scope
|
||||
readonly allDecls: Array<Decl>
|
||||
readonly upvalues: Array<UpvalueInfo>
|
||||
readonly upvalueMap: Map<Decl, number>
|
||||
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<string>
|
||||
}
|
||||
|
||||
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<FunctionInfo>
|
||||
readonly nodeToFunction: ReadonlyMap<FunctionNode, FunctionInfo>
|
||||
readonly scopeOfNode: ReadonlyMap<AnyNode, Scope>
|
||||
readonly refs: ReadonlyMap<Identifier, ResolvedRef>
|
||||
readonly thisRefs: ReadonlyMap<AnyNode, ResolvedRef>
|
||||
/** Each `super` of a `super.x`: its home object and `this`. Missing when it is outside a class method. */
|
||||
readonly superRefs: ReadonlyMap<AnyNode, { readonly home: ResolvedRef; readonly self: ResolvedRef }>
|
||||
/** Each class's constructor: its own, or a synthetic empty one when it has none. */
|
||||
readonly classConstructors: ReadonlyMap<ClassNode, FunctionExpression>
|
||||
/** Each class's synthetic field-initializer functions, when it has instance or static fields. */
|
||||
readonly classFieldInits: ReadonlyMap<ClassNode, { instance?: FunctionExpression; static?: FunctionExpression }>
|
||||
/** The fields a synthetic field-initializer function defines, in order. */
|
||||
readonly fieldInitMembers: ReadonlyMap<FunctionNode, ReadonlyArray<PropertyDefinition>>
|
||||
/** A computed field's key, evaluated once at class definition into a hidden class-scope binding read by this name. */
|
||||
readonly fieldKeys: ReadonlyMap<PropertyDefinition, Identifier>
|
||||
}
|
||||
|
||||
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<FunctionInfo> = []
|
||||
const nodeToFunction = new Map<FunctionNode, FunctionInfo>()
|
||||
const scopeOfNode = new Map<AnyNode, Scope>()
|
||||
const classConstructors = new Map<ClassNode, FunctionExpression>()
|
||||
const classFieldInits = new Map<ClassNode, { instance?: FunctionExpression; static?: FunctionExpression }>()
|
||||
const fieldInitMembers = new Map<FunctionNode, ReadonlyArray<PropertyDefinition>>()
|
||||
const fieldKeys = new Map<PropertyDefinition, Identifier>()
|
||||
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<Pattern> = 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 ? "<program>" : 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<Statement | ModuleDeclaration>,
|
||||
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,
|
||||
"<instance_members_initializer>",
|
||||
fields.filter((f) => !f.static),
|
||||
)
|
||||
const statics = fieldInit(
|
||||
node,
|
||||
classScope,
|
||||
fnInfo,
|
||||
"<static_initializer>",
|
||||
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<PropertyDefinition>,
|
||||
): 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<Identifier, ResolvedRef>()
|
||||
const thisRefs = new Map<AnyNode, ResolvedRef>()
|
||||
// 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<AnyNode, { home: ResolvedRef; self: ResolvedRef }>()
|
||||
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<string> = []): Array<string> => {
|
||||
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
|
||||
}
|
||||
|
|
@ -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 = <R>(ctx: Interpreter<R>, 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
|
||||
}
|
||||
|
|
@ -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<GeneratorRequestKind> = ["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<Value> = []
|
||||
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<unknown>): number => {
|
||||
const adapter = slots[0] as AsyncFromSyncIterator
|
||||
const kind = slots[1] as GeneratorRequestKind
|
||||
const args = slots[2] as Array<Value>
|
||||
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<string, unknown>, vm: Vm): void => {
|
||||
const ctx = vm.ctx
|
||||
const builtins = ctx.builtins
|
||||
const add = (name: string, fn: (args: Array<Value>) => 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
|
||||
})
|
||||
}
|
||||
|
|
@ -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, `<runId>:<callId>`: 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<unknown> }
|
||||
|
||||
/**
|
||||
* 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<R = never> {
|
||||
declare readonly requirements?: (_: never) => R
|
||||
constructor(
|
||||
readonly run: (args: ReadonlyArray<unknown>, 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<R = never> {
|
||||
declare readonly requirements?: (_: never) => R
|
||||
constructor(
|
||||
readonly start: (args: ReadonlyArray<unknown>, call: Call) => Effect.Effect<Json, unknown, R>,
|
||||
readonly wait: (data: Json, call: DurableCall) => Effect.Effect<unknown, unknown, R>,
|
||||
readonly cancel: (data: Json, call: DurableCall) => Effect.Effect<void, unknown, R>,
|
||||
) {}
|
||||
}
|
||||
|
||||
/** A lazy object of host functions, addressed by path; see `namespace`. */
|
||||
export class Namespace<R = never> {
|
||||
declare readonly requirements?: (_: never) => R
|
||||
constructor(
|
||||
readonly keys: (path: ReadonlyArray<string>) => ReadonlyArray<string>,
|
||||
readonly resolve: (path: ReadonlyArray<string>) => Fn<R> | DurableFn<R> | HostFailure,
|
||||
) {}
|
||||
}
|
||||
|
||||
export { HostFailure as Failure }
|
||||
|
||||
type Requirements<A> = A extends Effect.Effect<infer _A, infer _E, infer R> ? R : never
|
||||
|
||||
/** A host function: `f` gets the program's arguments, as they crossed, and the call. */
|
||||
export const fn = <F extends (args: ReadonlyArray<any>, call: Call) => unknown>(
|
||||
f: F,
|
||||
options: Options = {},
|
||||
): Fn<Requirements<ReturnType<F>>> =>
|
||||
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 = <Data extends Json, R = never>(options: {
|
||||
readonly start: (args: ReadonlyArray<any>, call: Call) => Effect.Effect<Data, unknown, R>
|
||||
readonly wait: (data: Data, call: DurableCall) => Effect.Effect<unknown, unknown, R>
|
||||
readonly cancel: (data: Data, call: DurableCall) => Effect.Effect<void, unknown, R>
|
||||
}): DurableFn<R> =>
|
||||
new DurableFn<R>(
|
||||
options.start,
|
||||
options.wait as (data: Json, call: DurableCall) => Effect.Effect<unknown, unknown, R>,
|
||||
options.cancel as (data: Json, call: DurableCall) => Effect.Effect<void, unknown, R>,
|
||||
)
|
||||
|
||||
/**
|
||||
* 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 = <R = never>(options: {
|
||||
readonly keys: (path: ReadonlyArray<string>) => ReadonlyArray<string>
|
||||
readonly resolve: (path: ReadonlyArray<string>) => Fn<R> | DurableFn<R> | HostFailure
|
||||
}): Namespace<R> => 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<string>): 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<string>, kind = "ExecutionFailure"): HostFailure =>
|
||||
new HostFailure(kind, message, suggestions)
|
||||
|
|
@ -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<Diagnostic>
|
||||
}
|
||||
|
||||
/** 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<unknown>
|
||||
/**
|
||||
* 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<unknown>,
|
||||
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<string> | 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 `<runId>:<id>`.
|
||||
*/
|
||||
export class HostCalls {
|
||||
/** Names this run's host calls (`<runId>:<callId>`). */
|
||||
runId = ""
|
||||
queued: Array<HostCall> = []
|
||||
readonly running = new Map<number, HostCall>()
|
||||
readonly inbox: Array<Delivery> = []
|
||||
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<unknown>,
|
||||
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<unknown> | DurableFn<unknown>,
|
||||
values: Array<Value>,
|
||||
site: AstNode | undefined,
|
||||
target: HostTarget,
|
||||
callee: Value,
|
||||
): HostResult {
|
||||
const hosts = this.ctx.hosts!
|
||||
const waiting: Array<PromiseObj> = []
|
||||
// The host functions that cross back among the arguments, when the function takes them.
|
||||
const back: Array<Function> | 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<Value>,
|
||||
label: string,
|
||||
waiting: Array<PromiseObj>,
|
||||
back: Array<Function> | undefined,
|
||||
):
|
||||
| { readonly ok: true; readonly args: ReadonlyArray<unknown> }
|
||||
| { 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<PromiseObj>,
|
||||
callee: Value,
|
||||
values: Array<Value>,
|
||||
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<Value>, 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<unknown>,
|
||||
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<HostCall> {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
|
@ -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"
|
||||
|
|
@ -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<Value>) => 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<typeof builtinCodes> | 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<string, unknown>, 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<Value>) => 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<Value, Map<string | symbol, Value>>()
|
||||
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<string | symbol, Value>()
|
||||
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<string>) : 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<string>) : 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<string, Json> = {}
|
||||
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<string, Json> = {}
|
||||
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<Obj>()
|
||||
const seen = new Set<Obj>()
|
||||
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<Json> = 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<string, Json> = {}
|
||||
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)
|
||||
}
|
||||
|
|
@ -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<Cell> => {
|
||||
const arr: Array<unknown> = []
|
||||
arr.push(initCell)
|
||||
arr.length = 0
|
||||
return arr as Array<Cell>
|
||||
}
|
||||
|
||||
export const EMPTY_CELLS: ReadonlyArray<Cell> = 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<string> = Object.entries(Op).reduce<Array<string>>((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<string> = ["/", "%", "**", "&", "|", "^", "<<", ">>", ">>>", "==", "!="]
|
||||
|
||||
/** 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<string> = ["-", "+", "~", "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<string | undefined>
|
||||
readonly raw: ReadonlyArray<string>
|
||||
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<string>
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -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<CodeJson> }
|
||||
|
||||
/**
|
||||
* 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<string, Code>()
|
||||
// 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<Code>): SavedCodes => ({
|
||||
text: hash(text),
|
||||
codes: codes.map(codeToJson),
|
||||
})
|
||||
|
|
@ -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<Value>) => 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>): number
|
||||
}
|
||||
}
|
||||
|
||||
export const helpers = (ctx: Interpreter<unknown>): Array<readonly [string, Value]> => {
|
||||
const builtins = ctx.builtins
|
||||
const helpers: Record<string, Helper> = {
|
||||
/** 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<Obj>(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<number>)],
|
||||
/** 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<Value>(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<string>
|
||||
const from = (slots[1] as Arr).items as Array<number>
|
||||
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<number>
|
||||
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
|
||||
}
|
||||
|
|
@ -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<typeof builtinCodes> | 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<string, Value>()
|
||||
/** 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<unknown>, globals: ReadonlyArray<readonly [string, Value]>) {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
||||
}
|
||||
`
|
||||
|
|
@ -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<Record<string, unknown>>
|
||||
|
||||
export type Options<G extends Globals = Globals> = {
|
||||
/**
|
||||
* 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<Record<string, string>> | 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<Record<string, Json>> | undefined
|
||||
/** Names this run's host calls (`<runId>:<callId>`); 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<R = never> = {
|
||||
/** Runs a program to its end. */
|
||||
readonly execute: (code: string, options?: ProgramOptions) => Effect.Effect<Result, never, R>
|
||||
/** A program ready to run once; nothing runs until `program.run()`. */
|
||||
readonly program: (code: string, options?: ProgramOptions) => Program<R>
|
||||
/**
|
||||
* 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<R, SnapshotError>
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<R = never, E = never> = {
|
||||
readonly run: () => Effect.Effect<Outcome, E, R>
|
||||
/**
|
||||
* 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<Outcome, SuspendError>
|
||||
}
|
||||
|
||||
/** The Effect environment the host functions among `G` need, at any depth. */
|
||||
export type Services<G> = ServicesOf<G, []>
|
||||
|
||||
type ServicesOf<T, Depth extends ReadonlyArray<unknown>> = Depth["length"] extends 8
|
||||
? never
|
||||
: T extends Fn<infer R> | DurableFn<infer R> | Namespace<infer R>
|
||||
? R
|
||||
: T extends object
|
||||
? ServicesOf<T[keyof T], [...Depth, unknown]>
|
||||
: never
|
||||
|
||||
/** Creates a runtime whose programs reach `globals`. */
|
||||
export const make = <const G extends Globals = {}>(options: Options<G> = {}): Runtime<Services<G>> => {
|
||||
type R = Services<G>
|
||||
const setup: Setup<R> = {
|
||||
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 = <R, E>(start: () => Effect.Effect<Running<R>, E>): Program<R, E> => {
|
||||
let claimed = false
|
||||
const started = Deferred.makeUnsafe<Running<R>, 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))
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
@ -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<Array<Value> | 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<Value>,
|
||||
body: (primitives: Array<Value>) => 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)
|
||||
|
|
@ -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<R> {
|
||||
private readonly fibers = new Map<number, Fiber.Fiber<unknown, unknown>>()
|
||||
// Calls whose fibers were interrupted to suspend or end the run: their outcomes are not reported.
|
||||
private readonly detached = new Set<number>()
|
||||
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<unknown> | undefined
|
||||
/** Called at every slice and host stop, before queued calls start: the round-trip test mode swaps the VM. */
|
||||
checkpoint: Effect.Effect<void, unknown, R> | 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<R>,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 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<Completion | typeof SUSPENDED, unknown, R> {
|
||||
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<void> {
|
||||
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<void, unknown, R>).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<unknown> | DurableFn<unknown> | 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<unknown, unknown, unknown>, next?: (value: unknown) => void): void {
|
||||
const fiber = Effect.runForkWith(this.services)(work as Effect.Effect<unknown, unknown, R>)
|
||||
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<void> {
|
||||
return Effect.callback<void>((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<unknown, unknown, unknown> => {
|
||||
if (Effect.isEffect(result)) return result as Effect.Effect<unknown, unknown, unknown>
|
||||
if (result instanceof Promise) return Effect.tryPromise({ try: () => result, catch: (reason) => reason })
|
||||
return Effect.succeed(result)
|
||||
}
|
||||
|
|
@ -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 = <R>(ctx: Interpreter<R>, 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 (<program>:line:col)`, or `at <program>: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 = `<program>:${location.line}:${location.column}`
|
||||
return `\n at ${name === undefined ? at : `${name} (${at})`}`
|
||||
}
|
||||
|
||||
export const createAggregateErrorValue = <R>(
|
||||
ctx: Interpreter<R>,
|
||||
errors: Array<Value>,
|
||||
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 = <R>(type: ErrorType, ctx: Interpreter<R>) => {
|
||||
const builtins = ctx.builtins
|
||||
const prototype = builtins[type]
|
||||
const construct = (args: Array<Value>, 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
|
||||
}
|
||||
|
|
@ -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>()("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<Diagnostic>
|
||||
readonly logs?: ReadonlyArray<string>
|
||||
readonly truncated?: boolean
|
||||
readonly metadata: Json
|
||||
}
|
||||
| {
|
||||
readonly ok: false
|
||||
readonly error: Diagnostic
|
||||
readonly logs?: ReadonlyArray<string>
|
||||
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<R> = (ctx: Interpreter<R>) => ReadonlyArray<readonly [string, Value]>
|
||||
|
||||
/** How a runtime runs programs: its limits and host globals, shared by every run it starts. */
|
||||
export type Setup<R> = {
|
||||
readonly limits: Limits
|
||||
readonly translate?: Required<Translate> | undefined
|
||||
/** Each run's host globals (see `Host`): made when it starts, and again for a restored run. */
|
||||
readonly globals?: ((run: Run) => Readonly<Record<string, unknown>>) | undefined
|
||||
/** Module names that load a global, beyond its own name; see `Runtime.Options`. */
|
||||
readonly modules?: Readonly<Record<string, string>> | undefined
|
||||
/** Globals made as program values (a test harness), made again the same way for a restored run. */
|
||||
readonly programGlobals?: Globals<R> | undefined
|
||||
}
|
||||
|
||||
/** Turns a suspended outcome into a failure, for callers that only run programs to their end. */
|
||||
export const finishExecution = <E, R>(outcome: Effect.Effect<Outcome, E, R>): Effect.Effect<Result, E, R> =>
|
||||
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 = <R>(
|
||||
setup: Setup<R>,
|
||||
code: string,
|
||||
bindings?: Readonly<Record<string, Json>>,
|
||||
runId: string = crypto.randomUUID(),
|
||||
): Running<R> =>
|
||||
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 = <R>(
|
||||
setup: Setup<R>,
|
||||
saved: Snapshot | Uint8Array | unknown,
|
||||
): Effect.Effect<Running<R>, SnapshotError> =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
const state = saved instanceof Uint8Array ? fromBytes(saved) : saved
|
||||
const saw = header(state)
|
||||
const resumed: Setup<R> = {
|
||||
...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<string, Source>()
|
||||
|
||||
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 = <R>(setup: Setup<R>, run: Run, bindings?: Readonly<Record<string, Json>>): Interpreter<R> => {
|
||||
const ctx = new Interpreter<R>({
|
||||
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<R> {
|
||||
private ctx!: Interpreter<R>
|
||||
private run_!: Run
|
||||
private driver!: Driver<R>
|
||||
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<void>()
|
||||
private readonly done = Deferred.makeUnsafe<Outcome>()
|
||||
|
||||
constructor(
|
||||
private readonly setup: Setup<R>,
|
||||
/** Active milliseconds used before this run, by earlier ones of the same execution. */
|
||||
private readonly activeBefore: number,
|
||||
private readonly prepare: () => readonly [Interpreter<R>, 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<Outcome, never, R> {
|
||||
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<R>, Run]
|
||||
self.ctx = ctx
|
||||
self.run_ = run
|
||||
self.driver = new Driver(ctx.vm, yield* Effect.context<R>())
|
||||
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<Outcome, SuspendError> {
|
||||
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<Outcome, never, R> {
|
||||
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<Diagnostic> } | 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 = <A>(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 = <T>(items: ReadonlyArray<T>, budget: number, size: (item: T) => number): Array<T> => {
|
||||
const kept: Array<T> = []
|
||||
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 }
|
||||
}
|
||||
|
|
@ -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<string> | 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<string | number> | 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 = <R>(
|
||||
ctx: Interpreter<R>,
|
||||
globals: Readonly<Record<string, unknown>>,
|
||||
translate: Required<Translate> = { functions: "error", promises: "error" },
|
||||
): ReadonlyArray<readonly [string, Value]> => {
|
||||
const builtins = ctx.builtins
|
||||
// The `snapshot` hooks of the host functions among the globals that have them, by label.
|
||||
const owners = new Map<string, Snapshot>()
|
||||
const shape: Array<string> = []
|
||||
// The program functions wrapping functions inside values a hooked host function returned, by where they came from.
|
||||
const origins = new WeakMap<object, HostOrigin>()
|
||||
// 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<object, Function>()
|
||||
|
||||
// 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<object>,
|
||||
waiting: Array<PromiseObj> | undefined,
|
||||
back: Array<Function> | 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<object>(), 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<string, unknown>
|
||||
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<Value> = []
|
||||
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<unknown> | DurableFn<unknown>,
|
||||
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<unknown>, label: string, global: ReadonlyArray<string>) => {
|
||||
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<string>((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<unknown>(
|
||||
(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 = <A>(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 = <T>(convert: () => T): T | typeof left => {
|
||||
try {
|
||||
return convert()
|
||||
} catch (reason) {
|
||||
if (reason instanceof PendingThrow) return left
|
||||
throw reason
|
||||
}
|
||||
}
|
||||
|
||||
const hostErrors = new Map<string, ErrorConstructor>([
|
||||
["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}`
|
||||
}
|
||||
|
|
@ -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 = <R>(ctx: Interpreter<R>): 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,
|
||||
)
|
||||
}
|
||||
|
|
@ -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 = <R>(ctx: Interpreter<R>) => {
|
||||
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<Value> => {
|
||||
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 = <R>(ctx: Interpreter<R>) => {
|
||||
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 = <R>(ctx: Interpreter<R>) => Value
|
||||
|
||||
// A table rather than a list so the names are known before any runtime exists.
|
||||
const table: Record<string, Factory> = {
|
||||
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: <R>(ctx: Interpreter<R>) => 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, <R>(ctx: Interpreter<R>) => errorGlobal(type, ctx)])),
|
||||
}
|
||||
|
||||
/** Names bound in every program before extensions apply. */
|
||||
export const globalNames: ReadonlySet<string> = new Set(Object.keys(table))
|
||||
|
||||
/** The immutable global bindings of every program, in declaration order. */
|
||||
export const globals = <R>(ctx: Interpreter<R>): ReadonlyArray<readonly [string, Value]> => {
|
||||
generatorGlobals(ctx)
|
||||
return Object.entries(table).map(([name, factory]) => [name, factory(ctx)] as const)
|
||||
}
|
||||
|
|
@ -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<string>) => ReadonlyArray<string>
|
||||
/** Calls the function at `path`. */
|
||||
readonly call: (path: ReadonlyArray<string>, args: Array<Value>, site: AstNode | undefined) => HostResult
|
||||
}
|
||||
|
||||
/** One program execution: the VM that runs it, captured logs, and the global scope built once. */
|
||||
export class Interpreter<R> {
|
||||
readonly builtins: Builtins
|
||||
readonly logs: Array<string>
|
||||
/** 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<string, NamespaceHandler>()
|
||||
/** The parsed sources this execution runs, by id, so a `NodeId` resolves to its node. */
|
||||
readonly sources = new Map<string, Source>()
|
||||
/** The global bindings: the intrinsics, the host's globals, and the program's bindings. */
|
||||
readonly globalScope: Map<string, Binding>
|
||||
private readonly modules = new Map<string, Value>()
|
||||
private readonly moduleGlobals: Readonly<Record<string, string>>
|
||||
private readonly namespaces = new Map<string, Obj>()
|
||||
|
||||
constructor(options: {
|
||||
readonly builtins: Builtins
|
||||
readonly logs?: Array<string>
|
||||
/** Module names that load a global, beyond its own name; see `Runtime.Options`. */
|
||||
readonly modules?: Readonly<Record<string, string>> | undefined
|
||||
/** The host's globals (extensions, a test harness): made again, the same way, when a saved run is restored. */
|
||||
readonly globals?: (ctx: Interpreter<R>) => ReadonlyArray<readonly [string, Value]>
|
||||
/** Data bound for this program, part of its saved state; host globals of the same name win. */
|
||||
readonly bindings?: (ctx: Interpreter<R>) => ReadonlyArray<readonly [string, Value]>
|
||||
}) {
|
||||
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<string, Binding>([["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<unknown>, 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<unknown>)
|
||||
}
|
||||
|
||||
/** 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<string> {
|
||||
return this.namespaceHandler(value).keys(value.path)
|
||||
}
|
||||
|
||||
/** Calls the function a namespace path names. */
|
||||
callNamespace(value: HostNamespace, args: Array<Value>, 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.`
|
||||
}
|
||||
|
|
@ -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<Obj> = []
|
||||
private readonly hostNames: Array<string> = []
|
||||
private readonly hostIndex = new Map<Obj, number>()
|
||||
private named: Array<Obj> | undefined
|
||||
|
||||
constructor(
|
||||
/** The objects made with the intrinsics, by id. */
|
||||
private readonly made: ReadonlyArray<Obj>,
|
||||
roots: Roots,
|
||||
hosts: ReadonlyArray<readonly [string, Value]> = [],
|
||||
) {
|
||||
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<Obj> {
|
||||
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<string> {
|
||||
return [...table!.names, ...this.hostNames]
|
||||
}
|
||||
|
||||
/** The host globals' names, `@name`, in walk order. */
|
||||
hosts(): ReadonlyArray<string> {
|
||||
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<Obj> {
|
||||
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<string> => {
|
||||
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 [string, Value]>
|
||||
readonly builtins: Builtins
|
||||
/** Internal objects no global reaches (the prelude's functions and helpers), named like the builtins. */
|
||||
readonly internals: ReadonlyArray<readonly [string, Obj]>
|
||||
}
|
||||
|
||||
type Table = {
|
||||
readonly count: number
|
||||
/** Static ids in walk order, and their names. */
|
||||
readonly order: ReadonlyArray<number>
|
||||
readonly names: ReadonlyArray<string>
|
||||
/** By id: the position in `order`, or -1 for an object the walk does not reach. */
|
||||
readonly position: ReadonlyArray<number>
|
||||
}
|
||||
|
||||
let table: Table | undefined
|
||||
let ids: Map<string, number> | undefined
|
||||
|
||||
const staticIds = () => (ids ??= new Map(table!.names.map((name, at) => [name, table!.order[at]!])))
|
||||
|
||||
const walk = (made: ReadonlyArray<Obj>, roots: Roots): Table => {
|
||||
type Path = string | readonly [parent: number, key: string | symbol, half?: "get" | "set"]
|
||||
const order: Array<number> = []
|
||||
const paths: Array<Path> = []
|
||||
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<Path, string>) =>
|
||||
`${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<string> = []
|
||||
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<symbol, string>([
|
||||
[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)}]`
|
||||
}
|
||||
|
|
@ -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<string>).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<Record<(typeof builtins)[number] | ErrorType, Obj>>
|
||||
|
||||
/** 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"),
|
||||
}
|
||||
}
|
||||
|
|
@ -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")
|
||||
}
|
||||
|
|
@ -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<string>
|
||||
}
|
||||
|
||||
/** 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<string>,
|
||||
) {
|
||||
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<string> = [],
|
||||
) {
|
||||
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})` : ""
|
||||
|
|
@ -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<string, (global: (name: string) => 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<Record<string, string>> = {},
|
||||
): 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<string>): 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
|
||||
}
|
||||
|
|
@ -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<Method>): 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<Method> =>
|
||||
(["keys", "values", "entries"] as const).map((kind) => [
|
||||
kind,
|
||||
0,
|
||||
(thisValue) => positionIterator(builtins, self(thisValue, kind), kind),
|
||||
])
|
||||
|
||||
export const constants = (target: Obj, table: Record<string, Value>): 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 = <T extends Obj>(
|
||||
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)}.`)
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -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 = <R>(ctx: Interpreter<R>, value: Value, node: AstNode): Array<string> => {
|
||||
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<MemberExpression>).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)
|
||||
}
|
||||
|
|
@ -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 = <R>(ctx: Interpreter<R>, 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 = <R>(ctx: Interpreter<R>, 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 = <R>(
|
||||
ctx: Interpreter<R>,
|
||||
reaction: Exclude<Reaction, { readonly kind: "await" | "asyncFromSync" }>,
|
||||
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<Value>
|
||||
}
|
||||
| { 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 = <R>(
|
||||
ctx: Interpreter<R>,
|
||||
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 = <R>(
|
||||
ctx: Interpreter<R>,
|
||||
reaction: Extract<Reaction, { readonly kind: "handler" }>,
|
||||
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 = <R>(
|
||||
ctx: Interpreter<R>,
|
||||
name: (typeof promiseStatics)[number],
|
||||
args: Array<Value>,
|
||||
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 = <R>(
|
||||
ctx: Interpreter<R>,
|
||||
reaction: Extract<Reaction, { readonly kind: "combinator" }>,
|
||||
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 = <R>(ctx: Interpreter<R>, combination: Combination) => {
|
||||
for (const [item, reaction] of combination.attached) ctx.vm.scheduler.detach(item, reaction)
|
||||
}
|
||||
|
||||
export const finishCombination = <R>(ctx: Interpreter<R>, 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 = <R>(
|
||||
ctx: Interpreter<R>,
|
||||
name: "then" | "catch" | "finally",
|
||||
thisValue: Value,
|
||||
args: Array<Value>,
|
||||
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 = <R>(
|
||||
ctx: Interpreter<R>,
|
||||
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 = <R>(
|
||||
_ctx: Interpreter<R>,
|
||||
reaction: Extract<Reaction, { readonly kind: "finally" }>,
|
||||
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 = <R>(ctx: Interpreter<R>, 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 = <R>(ctx: Interpreter<R>, 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 = <R>(ctx: Interpreter<R>) => {
|
||||
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 = <R>(ctx: Interpreter<R>) => {
|
||||
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
|
||||
}
|
||||
|
|
@ -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<object>,
|
||||
): boolean => {
|
||||
const pending: Array<Iterator<Value>> = [[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<object>(),
|
||||
): void => {
|
||||
if (hasCircularReference(container, value, seen)) throw circularValue(label)
|
||||
}
|
||||
|
||||
export const hasCircularReference = (container: Obj, value: Value, seen = new Set<object>()): 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
|
||||
}
|
||||
|
|
@ -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<unknown>,
|
||||
) {}
|
||||
}
|
||||
|
||||
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<Value>,
|
||||
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<Value>) {}
|
||||
}
|
||||
|
||||
export type Hint = "number" | "string" | "default"
|
||||
export type Hints = Hint | ReadonlyArray<Hint>
|
||||
|
||||
/**
|
||||
* 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<unknown>) {}
|
||||
}
|
||||
|
||||
/** 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<Value>,
|
||||
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
|
||||
|
|
@ -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<AstNode> | 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<AstNode> {
|
||||
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<AstNode, { readonly source: Source; readonly index: number }>()
|
||||
|
||||
/** 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<AstNode> => {
|
||||
const nodes: Array<AstNode> = []
|
||||
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<AstNode> = []
|
||||
for (const key in node) {
|
||||
if (key === "loc") continue
|
||||
const child: unknown = (node as unknown as Record<string, unknown>)[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
|
||||
|
|
@ -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<Value | typeof deleted> = []
|
||||
readonly values: Array<Value> = []
|
||||
// Derived from `keys`: where each live key is.
|
||||
private readonly index = new Map<Value, number>()
|
||||
private cursors: Array<TableCursor> = []
|
||||
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<C extends TableCursor>(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<Value> {
|
||||
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<number> = []
|
||||
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)]!
|
||||
}
|
||||
}
|
||||
|
|
@ -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<Value>
|
||||
readonly reasons: Array<Value>
|
||||
/** Members still to settle, plus one until iteration ends. */
|
||||
remaining: number
|
||||
/** Every member's reaction, detached once the result is decided. */
|
||||
readonly attached: Array<readonly [PromiseObj, Reaction]>
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<Frame> }
|
||||
| { 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<unknown> | DurableFn<unknown> | 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<string> | undefined
|
||||
readonly owner: string | undefined
|
||||
constructor(
|
||||
readonly id: number,
|
||||
/** The call's stable idempotency key, `<runId>:<callId>`. */
|
||||
readonly key: string,
|
||||
target: HostTarget,
|
||||
readonly policy: HostPolicy,
|
||||
/** The arguments as they crossed to the host. */
|
||||
public args: ReadonlyArray<unknown>,
|
||||
/** 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<HostCall> }
|
||||
| { readonly kind: "slice" }
|
||||
| { readonly kind: "stuck"; readonly node: AstNode | undefined }
|
||||
|
|
@ -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<ClassSpec> | 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<ClassSpec> =>
|
||||
(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<string> => {
|
||||
const fields = vmSpecs().find((spec) => spec.name === "Frame")!.fields
|
||||
const records = snapshot.records as ReadonlyArray<
|
||||
{ t?: string; f?: ReadonlyArray<unknown>; o?: ReadonlyArray<unknown> } | 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<string> } => {
|
||||
vm.compact()
|
||||
const ctx = vm.ctx
|
||||
const lost: Array<string> = []
|
||||
const names = ctx.intrinsics
|
||||
const programs = [...ctx.sources.values()]
|
||||
const sources = sourcesOf(vm)
|
||||
const anchors = new Map(anchorsOf(vm))
|
||||
const internals = new Map<unknown, string>()
|
||||
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<readonly [object, string]> => [
|
||||
[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<string, Source> => {
|
||||
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<number>).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 })
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -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<Encoded>
|
||||
readonly records: ReadonlyArray<Record>
|
||||
}
|
||||
|
||||
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<unknown>): 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<unknown> =>
|
||||
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<Encoded>,
|
||||
records: array(root.records, "the records") as ReadonlyArray<Record>,
|
||||
}
|
||||
}
|
||||
|
||||
// --- 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")
|
||||
}
|
||||
|
|
@ -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 = <R>(ctx: Interpreter<R>, args: Array<Value>) => withReads(() => arrayFromReads(ctx, args))
|
||||
|
||||
// Under `withReads`: an iterator method that is a getter is read before `length` could be.
|
||||
const arrayFromReads = <R>(ctx: Interpreter<R>, args: Array<Value>): 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 = <R>(
|
||||
ctx: Interpreter<R>,
|
||||
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<number> = []
|
||||
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<Value>,
|
||||
) => {
|
||||
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 = <R>(ctx: Interpreter<R>) => {
|
||||
const builtins = ctx.builtins
|
||||
const proto = builtins.Array
|
||||
const wrap = (items: Array<Value>) => new Arr(proto, items)
|
||||
const construct = (args: Array<Value>, 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<Value>, depth: number): Array<Value> =>
|
||||
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
|
||||
}
|
||||
|
|
@ -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 `<Buffer${shown === "" ? "" : ` ${shown}`}${more}>`
|
||||
}
|
||||
}
|
||||
|
||||
// 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 = <R>(ctx: Interpreter<R>) => {
|
||||
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 = <A>(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<Value>) => {
|
||||
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<string, (...items: Array<unknown>) => 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
|
||||
}
|
||||
|
|
@ -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 = <R>(
|
||||
ctx: Interpreter<R>,
|
||||
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 = <R>(ctx: Interpreter<R>, args: Array<Value>, 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 = <const T extends string>(
|
||||
options: Obj | undefined,
|
||||
key: string,
|
||||
allowed: ReadonlyArray<T>,
|
||||
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 = <R>(ctx: Interpreter<R>) => {
|
||||
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<Value>, 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 = <R>(ctx: Interpreter<R>) => {
|
||||
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 = <R>(ctx: Interpreter<R>) => {
|
||||
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"),
|
||||
),
|
||||
)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
@ -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 = <R>(ctx: Interpreter<R>, 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 = <R>(
|
||||
ctx: Interpreter<R>,
|
||||
owner: MapObj | WeakMapObj,
|
||||
key: Value,
|
||||
callback: Callable,
|
||||
): Value | Invoke => {
|
||||
const table = owner.map as Map<Value, Value>
|
||||
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 = <R>(ctx: Interpreter<R>) => {
|
||||
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 = <R>(ctx: Interpreter<R>) => {
|
||||
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 = <R>(ctx: Interpreter<R>) => {
|
||||
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 = <R>(ctx: Interpreter<R>) => {
|
||||
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
|
||||
}
|
||||
|
|
@ -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 = <R>(ctx: Interpreter<R>) => {
|
||||
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<Value>): 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<object>, 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<string> | undefined,
|
||||
): Array<{ readonly index: string; readonly values: Record<string, Value> }> => {
|
||||
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<string> | undefined): Record<string, Value> => {
|
||||
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)
|
||||
}
|
||||
|
|
@ -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<Value>, 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<Value>, body: (numbers: Array<number>) => 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<Getter> = [
|
||||
"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>) => number ? K : never]: never
|
||||
}
|
||||
|
||||
const setters: ReadonlyArray<readonly [Setter, number]> = [
|
||||
["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 = <R>(ctx: Interpreter<R>) => {
|
||||
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<typeof Date.UTC>))),
|
||||
],
|
||||
])
|
||||
|
||||
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
|
||||
}
|
||||
|
|
@ -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 = <R>(ctx: Interpreter<R>, 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 = <R>(ctx: Interpreter<R>) => {
|
||||
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<Value>) => new Arr(builtins.Array, items)
|
||||
const arg = (args: Array<Value>, index: number): string => coerceToString(args[index])
|
||||
const requireArgs = (name: string, args: Array<Value>, 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
|
||||
}
|
||||
|
|
@ -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 = <R>(ctx: Interpreter<R>) => {
|
||||
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.")
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
@ -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 = <R>(ctx: Interpreter<R>) => {
|
||||
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 = <R>(ctx: Interpreter<R>, args: Array<Value>) => {
|
||||
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<Value>) => {
|
||||
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])
|
||||
}
|
||||
|
|
@ -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 = <R>(ctx: Interpreter<R>) => {
|
||||
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>) => 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
|
||||
}
|
||||
|
|
@ -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 = <R>(ctx: Interpreter<R>) => {
|
||||
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 = <R>(ctx: Interpreter<R>) => {
|
||||
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
|
||||
}
|
||||
|
|
@ -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 = <R>(ctx: Interpreter<R>, 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 = <R>(ctx: Interpreter<R>, args: Array<Value>): 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<object>()
|
||||
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<string, Value> =
|
||||
"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<string> =>
|
||||
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 = <R>(ctx: Interpreter<R>) => {
|
||||
const builtins = ctx.builtins
|
||||
const construct = (args: Array<Value>): 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
|
||||
}
|
||||
|
|
@ -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 = <T>(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<Value>, 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 = <R>(ctx: Interpreter<R>) => {
|
||||
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
|
||||
}
|
||||
|
|
@ -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 = <R>(
|
||||
ctx: Interpreter<R>,
|
||||
value: string,
|
||||
name: "replace" | "replaceAll",
|
||||
args: Array<Value>,
|
||||
): Invoke => {
|
||||
const builtins = ctx.builtins
|
||||
const callback = requireCallback(args[1], `String.${name}`)
|
||||
const matches: Array<Match> = []
|
||||
// The host calls back with (match, ...captures, offset, string, groups?); only groups is not already a Value.
|
||||
const collect = (
|
||||
...callbackArgs: Array<string | number | undefined | Record<string, string | undefined>>
|
||||
): 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<Value> }
|
||||
|
||||
// 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 = <R>(ctx: Interpreter<R>) => {
|
||||
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<number>) => 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<Value>, index: number): string =>
|
||||
coerceToString(requireDataArgument(name, index, args[index]))
|
||||
const num = (name: string, args: Array<Value>, index: number): number =>
|
||||
coerceToNumber(requireDataArgument(name, index, args[index]))
|
||||
const optNum = (name: string, args: Array<Value>, index: number): number | undefined =>
|
||||
args[index] === undefined ? undefined : num(name, args, index)
|
||||
const optStr = (name: string, args: Array<Value>, 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<Value>) => NativeResult,
|
||||
hints: ReadonlyArray<Hint> = [],
|
||||
): 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<Value>, 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<string>, 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<string>) => 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<Value> = []
|
||||
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
|
||||
}
|
||||
|
|
@ -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<UriFunction, (value: string) => string> = {
|
||||
encodeURI,
|
||||
encodeURIComponent,
|
||||
decodeURI,
|
||||
decodeURIComponent,
|
||||
}
|
||||
|
||||
export const uriGlobal = <R>(ctx: Interpreter<R>, 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 = <R>(ctx: Interpreter<R>) => {
|
||||
const builtins = ctx.builtins
|
||||
const proto = builtins.URL
|
||||
const construct = (args: Array<Value>, 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 = <R>(ctx: Interpreter<R>, 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<string>)
|
||||
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 = <T>(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 = <R>(
|
||||
ctx: Interpreter<R>,
|
||||
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 = <R>(ctx: Interpreter<R>, 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 = <R>(ctx: Interpreter<R>) => {
|
||||
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<Value>) => new Arr(builtins.Array, items)
|
||||
const arg = (args: Array<Value>, index: number): string => coerceToString(args[index])
|
||||
const requireArgs = (name: string, args: Array<Value>, 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
|
||||
}
|
||||
|
|
@ -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 = <R>(ctx: Interpreter<R>, name: Coercion, args: Array<Value>) => {
|
||||
// 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 = <R>(ctx: Interpreter<R>, name: Coercion, length = 1): Native =>
|
||||
fn(ctx.builtins, name, length, (_, args) => coerce(ctx, name, args))
|
||||
|
|
@ -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 = <R>(ctx: Interpreter<R>, 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 = <R>(ctx: Interpreter<R>) =>
|
||||
fn(ctx.builtins, "structuredClone", 1, (_, args) => {
|
||||
if (args.length === 0) throw typeError("structuredClone requires 1 argument")
|
||||
const builtins = ctx.builtins
|
||||
const memo = new Map<Obj, Obj>()
|
||||
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 = <T extends Obj>(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 = <R>(ctx: Interpreter<R>) => {
|
||||
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
|
||||
}
|
||||
|
|
@ -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,
|
||||
) {}
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -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
|
||||
|
|
@ -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.
|
||||
|
|
@ -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<Array<string>> = []
|
||||
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<string>) => 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 = <A = void>() => {
|
||||
let resolve!: (value: A) => void
|
||||
const promise = new Promise<A>((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<void> | undefined) => {
|
||||
const started = latch()
|
||||
const kept: Array<unknown> = []
|
||||
// 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<never>
|
||||
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()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
|
@ -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.")
|
||||
})
|
||||
})
|
||||
|
|
@ -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)
|
||||
})
|
||||
})
|
||||
|
|
@ -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)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
|
@ -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<Extension.Extension> = []) => {
|
||||
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<boolean> = []
|
||||
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")
|
||||
})
|
||||
})
|
||||
|
|
@ -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<string>) => {
|
||||
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)
|
||||
})
|
||||
|
|
@ -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<never>({ 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<never>({
|
||||
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 <program>: 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)
|
||||
})
|
||||
|
|
@ -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}')
|
||||
})
|
||||
})
|
||||
|
|
@ -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<unknown>; readonly o?: ReadonlyArray<unknown> }
|
||||
|
||||
const frames = (snapshot: Snapshot): Array<string> => {
|
||||
const records = snapshot.records as ReadonlyArray<Saved | undefined>
|
||||
return records.flatMap((record) => {
|
||||
if (record?.t !== "Frame") return []
|
||||
const [fn, code] = record.f as [unknown, [string, [string, string, number]], ...Array<unknown>]
|
||||
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 = <A = void>() => {
|
||||
let resolve!: (value: A) => void
|
||||
const promise = new Promise<A>((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<void> | 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<never>
|
||||
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"]],
|
||||
"<instance_members_initializer>",
|
||||
],
|
||||
[
|
||||
"static field initializer",
|
||||
`class A { static v = pick(slow(21)); static w = A.v + 1 }
|
||||
return [A.v, A.w]`,
|
||||
[42, 43],
|
||||
"<static_initializer>",
|
||||
],
|
||||
[
|
||||
"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<never>, state: Parameters<Runtime.Runtime<never>["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)
|
||||
})
|
||||
|
|
@ -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'.")
|
||||
})
|
||||
})
|
||||
|
|
@ -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))
|
||||
})
|
||||
})
|
||||
|
|
@ -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])
|
||||
})
|
||||
})
|
||||
|
|
@ -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)
|
||||
})
|
||||
})
|
||||
|
|
@ -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"])
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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 (<program>:1:27)", " at outer (<program>:2:21)", " at <program>: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 <program>:1:7",
|
||||
"RangeError\n at <program>: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 <program>: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 (<program>:1:46)\n at <program>:8:9",
|
||||
"Late: z\n at <program>:2:14",
|
||||
"Late: z\n at <program>:2:14",
|
||||
"q\n at <program>:5:17",
|
||||
"N\n at <program>: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 (<program>:1:34)", ...Array(9).fill(" at f (<program>: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)
|
||||
})
|
||||
8
packages/codemode/test/fixtures/build-id.ts
vendored
8
packages/codemode/test/fixtures/build-id.ts
vendored
|
|
@ -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 <module> 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())
|
||||
|
|
@ -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 }))
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
// Resumes a saved run in its own process: `bun resume-getters-process.ts <state file>`. 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<never>
|
||||
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())))
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue