mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 03:24:54 +00:00
feat(codemode): getters and setters (#64908)
This commit is contained in:
parent
5ef7657335
commit
d3f6559d93
50 changed files with 4357 additions and 782 deletions
|
|
@ -116,8 +116,9 @@ global rejects its promise, and a synchronous global throws.
|
|||
Tool arguments cross into the host the way extension arguments do, as copies (plain data, `Date`, `Map`, `Set`, `URL`,
|
||||
`Headers`, errors), and Code Mode then turns them into JSON next to the tool's schema: a `Date` is its ISO string, a
|
||||
`Set` its items, a `URLSearchParams` its query string, an `Error` `{ name, message, ...own fields }`, and `Map` and
|
||||
`RegExp` values `{}`. A `Uint8Array` asks to be encoded as text first. A program's own `toJSON` is not called, and a
|
||||
promise or function inside an argument fails the call: await it, or pass its data.
|
||||
`RegExp` values `{}`. A `Uint8Array` asks to be encoded as text first. A program's own `toJSON` is not called, but its
|
||||
getters are: each runs once, before the host function does, and its value crosses as data; a property with only a setter
|
||||
is left out. A promise or function inside an argument fails the call: await it, or pass its data.
|
||||
|
||||
### Suspending and resuming a run
|
||||
|
||||
|
|
@ -262,8 +263,8 @@ const web = Extension.make({
|
|||
const result = yield* CodeMode.make({ extensions: [web] }).execute(code).pipe(Effect.provideService(Session, session))
|
||||
```
|
||||
|
||||
Every value crossing in either direction is converted, never shared: arguments come in as copies, results go out as
|
||||
copies, and a function inside a result is callable the same way. When the program passes such a function back to an
|
||||
Every value crossing in either direction is converted, never shared: arguments come in as copies (a program getter runs
|
||||
and crosses as its value; a setter-only property is left out), results go out as copies, and a function inside a result is callable the same way. When the program passes such a function back to an
|
||||
extension, it arrives as the host function itself, so `copy(dest, file(src))` can tell what it was given. Globals and
|
||||
the program's own functions never cross back: they are left out, as in tool arguments. A global that shadows a
|
||||
built-in or another extension throws at `CodeMode.make`.
|
||||
|
|
|
|||
|
|
@ -70,7 +70,21 @@ the ultimate source of truth. Upstream test262 files run verbatim from `test/tes
|
|||
- [ ] 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.
|
||||
- [ ] Getter and setter definitions in object literals.
|
||||
- [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
|
||||
|
||||
|
|
@ -310,8 +324,8 @@ reject }` object.
|
|||
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/accessor `then` fields
|
||||
remain outside the supported object model.
|
||||
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.
|
||||
|
|
@ -350,8 +364,14 @@ reject }` object.
|
|||
- [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 other than `undefined` throws a `TypeError`: property descriptors are not supported (there is no
|
||||
`Object.defineProperty` either).
|
||||
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'`,
|
||||
|
|
|
|||
|
|
@ -72,6 +72,26 @@ 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`,
|
||||
],
|
||||
]
|
||||
|
||||
const argument = (flag: string) => {
|
||||
|
|
|
|||
|
|
@ -186,6 +186,8 @@ const formatOperand = (c: Code, op: number, a: number, bx: number, sbx: number):
|
|||
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"
|
||||
|
|
|
|||
|
|
@ -3,11 +3,15 @@ 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,
|
||||
get,
|
||||
GetterCall,
|
||||
isProgramAccessor,
|
||||
lookup,
|
||||
peek,
|
||||
iteratorResult,
|
||||
Obj,
|
||||
Position,
|
||||
|
|
@ -148,7 +152,12 @@ export class VmScheduler {
|
|||
this.settle(promise, normal(resolution))
|
||||
return
|
||||
}
|
||||
const then = get(resolution, "then")
|
||||
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
|
||||
|
|
@ -220,6 +229,18 @@ export class VmScheduler {
|
|||
|
||||
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
|
||||
|
|
@ -415,9 +436,10 @@ export const registerAsyncIntrinsics = (map: Map<string, unknown>, vm: Vm): void
|
|||
|
||||
add("$CombineStart", ([nameVal, items]) => {
|
||||
const name = nameVal as Combination["name"]
|
||||
const isIter =
|
||||
builtinCursor(builtins, items) !== undefined ||
|
||||
(items instanceof Obj && get(items, IteratorSymbol) !== undefined && get(items, IteratorSymbol) !== null)
|
||||
// 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)}.`)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -144,7 +144,7 @@ type ControlEntry =
|
|||
const idx = (node: AstNode | undefined | null): number => (node ? (nodeId(node)?.index ?? -1) : -1)
|
||||
|
||||
/** Bump when the compiler emits different bytecode for the same source; it is part of the snapshot build id. */
|
||||
export const COMPILER_VERSION = 1
|
||||
export const COMPILER_VERSION = 2
|
||||
|
||||
const compileCache = new Map<string, ReadonlyArray<Code>>()
|
||||
const MAX_CACHE_SIZE = 64
|
||||
|
|
@ -1027,7 +1027,20 @@ const compileFunctionBody = (
|
|||
compileExpression(prop.argument)
|
||||
builder.emit(Op.COPY_DATA_PROPS, 0, 0, idx(prop), -1)
|
||||
} else if (prop.kind !== "init") {
|
||||
emitThrowError({ type: "TypeError", message: "Only init object properties are supported." }, prop)
|
||||
const setter = prop.kind === "set" ? 2 : 0
|
||||
if (prop.computed) {
|
||||
compileExpression(prop.key as Expression)
|
||||
builder.emit(Op.TO_KEY, 0, 0, idx(prop.key), 0)
|
||||
compileExpression(prop.value as Expression)
|
||||
builder.emit(Op.SET_NAME, setter === 0 ? 2 : 3, 0, idx(prop.value), 0)
|
||||
builder.emit(Op.DEFINE_ACCESSOR, 1 | setter, 0, idx(prop), -2)
|
||||
} else {
|
||||
const bigint = prop.key.type === "Literal" && typeof prop.key.value === "bigint"
|
||||
if (bigint) emitThrowError({ type: "TypeError", message: "BigInt literals are not supported." }, prop.key)
|
||||
const name = bigint ? "" : keyName(prop.key)
|
||||
compileNamedExpression(prop.value as Expression, `${prop.kind} ${name}`)
|
||||
builder.emit(Op.DEFINE_ACCESSOR, setter, builder.constant(name), idx(prop), -1)
|
||||
}
|
||||
} else if (prop.computed) {
|
||||
compileExpression(prop.key as Expression)
|
||||
builder.emit(Op.TO_KEY, 0, 0, idx(prop.key), 0)
|
||||
|
|
|
|||
|
|
@ -11,13 +11,13 @@ import {
|
|||
type PromiseObj,
|
||||
type Value,
|
||||
} from "./runtime/objects.js"
|
||||
import { readProperty, requireIteratorMethod, requireIteratorObject } from "./runtime/operations.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, type Vm } from "./vm.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
|
||||
|
|
@ -275,6 +275,11 @@ export const execResume = (frame: Frame, bx: number, pc: number, sp: number): nu
|
|||
return pc + 1
|
||||
}
|
||||
|
||||
const synchronous = (frame: Frame): boolean =>
|
||||
frame.mode === Mode.CALLER ||
|
||||
frame.mode === Mode.REDO ||
|
||||
(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
|
||||
|
|
@ -283,9 +288,9 @@ export const execAwait = (vm: Vm, frame: Frame, a: number, pc: number, sp: numbe
|
|||
const site = a === 1 ? undefined : frame.code.siteAt(pc)
|
||||
frame.pc = pc + 1
|
||||
let bIdx = vm.frames.length - 1
|
||||
while (bIdx > 0 && vm.frames[bIdx]!.mode === Mode.CALLER) {
|
||||
bIdx--
|
||||
}
|
||||
// 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--
|
||||
|
|
@ -301,7 +306,7 @@ export const execAwait = (vm: Vm, frame: Frame, a: number, pc: number, sp: numbe
|
|||
vm.scheduler.park(cut, promise, site, result)
|
||||
}
|
||||
|
||||
export const execYstar = (frame: Frame, itSlot: number, bx: number, pc: number, sp: number): number => {
|
||||
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
|
||||
|
|
@ -314,7 +319,8 @@ export const execYstar = (frame: Frame, itSlot: number, bx: number, pc: number,
|
|||
return bx
|
||||
}
|
||||
const methodName = REQUEST_KINDS[kind]!
|
||||
const method = readProperty(rec.iterator, methodName, site)
|
||||
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
|
||||
|
|
@ -327,13 +333,16 @@ export const execYstar = (frame: Frame, itSlot: number, bx: number, pc: number,
|
|||
return bx
|
||||
}
|
||||
|
||||
export const execYstarResult = (frame: Frame, kindSlot: number, bx: number, pc: number, sp: number): number => {
|
||||
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 done = Boolean(readProperty(obj, "done", site))
|
||||
const value = readProperty(obj, "value", 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
|
||||
}
|
||||
|
|
@ -444,13 +453,14 @@ export const registerGeneratorIntrinsics = (map: Map<string, unknown>, vm: Vm):
|
|||
// The `$vmAsyncFromSync` frame running now settles this.
|
||||
const made = () => vm.frames[vm.frames.length - 1]!.target as Resolving
|
||||
|
||||
add("$WrapAsyncFromSync", ([syncVal]) => {
|
||||
add("$AfsRequireObj", ([syncVal]) => requireIteratorObject(syncVal, "Iterator method result", vm.currentSite()))
|
||||
|
||||
add("$WrapAsyncFromSync", ([obj, nextVal]) => {
|
||||
const site = vm.currentSite()
|
||||
const obj = requireIteratorObject(syncVal, "Iterator method result", site)
|
||||
const next = requireIteratorMethod(readProperty(obj, "next", site), "Iterator next", site)
|
||||
const next = requireIteratorMethod(nextVal, "Iterator next", site)
|
||||
return new AsyncFromSyncIterator(
|
||||
builtins.AsyncFromSyncIterator,
|
||||
{ iterator: obj, next, asynchronous: false },
|
||||
{ iterator: obj as Obj, next, asynchronous: false },
|
||||
site!,
|
||||
)
|
||||
})
|
||||
|
|
@ -459,9 +469,9 @@ export const registerGeneratorIntrinsics = (map: Map<string, unknown>, vm: Vm):
|
|||
|
||||
add("$AfsGetNext", ([adapter]) => ((adapter as AsyncFromSyncIterator).sync as CustomIterator).next)
|
||||
|
||||
add("$AfsGetMethod", ([adapter, iterator, kind]) => {
|
||||
// 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
|
||||
const method = readProperty(iterator as Obj, kind as string, site)
|
||||
if (method === undefined || method === null) return undefined
|
||||
return requireIteratorMethod(method, `Iterator ${kind as string}`, site)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -3,9 +3,9 @@ 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, type Value } from "./runtime/objects.js"
|
||||
import { Arr, type PromiseObj, reads, type Value } from "./runtime/objects.js"
|
||||
import { promiseLike } from "./runtime/promises.js"
|
||||
import type { Completion } from "./runtime/signals.js"
|
||||
import { type Completion, Prefetch } from "./runtime/signals.js"
|
||||
import { HostCall, type HostPolicy, Resolving } from "./scheduler.js"
|
||||
import { type FrameMode, Mode } from "./vm.js"
|
||||
|
||||
|
|
@ -25,7 +25,8 @@ 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")
|
||||
|
||||
export type HostResult = Value | typeof BLOCK | typeof 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 = {
|
||||
|
|
@ -99,23 +100,28 @@ export class HostCalls {
|
|||
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
|
||||
if (fn instanceof DurableFn || fn.type === "async") {
|
||||
// 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)
|
||||
let args: ReadonlyArray<unknown>
|
||||
try {
|
||||
args = hosts.toHost(values, target.label, waiting, back)
|
||||
} catch (error) {
|
||||
resolving.reject(error)
|
||||
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, args, false, resolving, site)
|
||||
const call = this.queue(target, policy, crossed.args, false, resolving, site)
|
||||
call.fn = fn
|
||||
call.holdsFunctions = back !== undefined && back.length > 0
|
||||
return resolving.promise
|
||||
}
|
||||
const args = hosts.toHost(values, target.label, waiting, back)
|
||||
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)
|
||||
|
|
@ -131,8 +137,34 @@ export class HostCalls {
|
|||
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. A sync function's call waits where it is, as an `await` would; an async one's settles `resolving`.
|
||||
// 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,
|
||||
|
|
@ -143,7 +175,12 @@ export class HostCalls {
|
|||
const builtins = this.ctx.builtins
|
||||
this.ctx.vm.pushInternal(
|
||||
internalCode("$vmHostWait"),
|
||||
[new Arr(builtins.Array, promises), callee, new Arr(builtins.Array, values)],
|
||||
[
|
||||
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,
|
||||
|
|
@ -152,6 +189,29 @@ export class HostCalls {
|
|||
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)
|
||||
|
|
|
|||
|
|
@ -13,7 +13,12 @@ import {
|
|||
DateObj,
|
||||
ErrorObj,
|
||||
get,
|
||||
type Getter,
|
||||
HeadersObj,
|
||||
HostNamespace,
|
||||
isProgramAccessor,
|
||||
reads,
|
||||
lookup,
|
||||
keys,
|
||||
type NativeResult,
|
||||
Obj,
|
||||
|
|
@ -22,9 +27,10 @@ import {
|
|||
URLSearchParamsObj,
|
||||
type Value,
|
||||
} from "./runtime/objects.js"
|
||||
import { applyBinaryOperator, operatorConversion, propertyKey } from "./runtime/operations.js"
|
||||
import { applyBinaryOperator, hasInstance, operatorConversion, propertyKey } from "./runtime/operations.js"
|
||||
import { isOpaque, typeofValue } from "./runtime/references.js"
|
||||
import { Convert } from "./runtime/signals.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"
|
||||
|
|
@ -46,13 +52,13 @@ 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 = $GetMethod(v, first)
|
||||
if (m1 !== undefined) {
|
||||
const m1 = v[first]
|
||||
if ($IsCallableAny(m1)) {
|
||||
const r1 = $Call(m1, v)
|
||||
if (!$IsObj(r1)) return r1
|
||||
}
|
||||
const m2 = $GetMethod(v, second)
|
||||
if (m2 !== undefined) {
|
||||
const m2 = v[second]
|
||||
if ($IsCallableAny(m2)) {
|
||||
const r2 = $Call(m2, v)
|
||||
if (!$IsObj(r2)) return r2
|
||||
}
|
||||
|
|
@ -93,6 +99,40 @@ function $vmBinary(op, lhs, rhs) {
|
|||
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)]
|
||||
}
|
||||
|
|
@ -101,24 +141,40 @@ function $vmDeleteElem(o, k) {
|
|||
return delete o[$vmToKey(k)]
|
||||
}
|
||||
|
||||
function $vmConvert(callable, target, args, constructing, replay, req) {
|
||||
// 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) {
|
||||
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
|
||||
converted[i] = coerce ? $ConvCoerce(hint, prim) : prim
|
||||
i++
|
||||
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)
|
||||
}
|
||||
replay[ordinal] = converted
|
||||
const res = $ConvReplay(callable, target, args, constructing, replay)
|
||||
if (!$IsConvert(res)) return res
|
||||
const res = $Replay(callable, target, args, constructing, replay, read)
|
||||
if (!$IsConvert(res) && !$IsPrefetch(res)) return res
|
||||
req = res
|
||||
}
|
||||
}
|
||||
|
|
@ -147,7 +203,7 @@ function $vmJsonVisitor(boundary, replacer, properties) {
|
|||
if (kind === 2) return null
|
||||
if (kind === 3) return $JsonSpecial(val, boundary)
|
||||
const target = kind === 4 ? $SetToArray(val) : val
|
||||
ancestors[ancestors.length] = target
|
||||
$ArraySet(ancestors, ancestors.length, target)
|
||||
let out
|
||||
if ($IsArray(target)) {
|
||||
out = []
|
||||
|
|
@ -155,7 +211,7 @@ function $vmJsonVisitor(boundary, replacer, properties) {
|
|||
let i = 0
|
||||
while (i < len) {
|
||||
const elem = yield* visit(target, String(i), depth + 1)
|
||||
out[i] = elem === undefined ? null : elem
|
||||
$ArraySet(out, i, elem === undefined ? null : elem)
|
||||
i++
|
||||
}
|
||||
} else {
|
||||
|
|
@ -193,18 +249,19 @@ function $vmCombine(name, items) {
|
|||
}
|
||||
|
||||
function $vmOpenSyncForAsync(v, method) {
|
||||
return $WrapAsyncFromSync($Call(method, v))
|
||||
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) : $AfsGetMethod(adapter, iter, kind)
|
||||
const method = kind === "next" ? $AfsGetNext(adapter) : $AfsMethod(adapter, iter[kind], kind)
|
||||
if (method === undefined || method === null) {
|
||||
if (kind === "return") {
|
||||
$AfsResolveDone(val)
|
||||
return
|
||||
}
|
||||
const ret = $AfsGetMethod(adapter, iter, "return")
|
||||
const ret = $AfsMethod(adapter, iter.return, "return")
|
||||
if (ret !== undefined && ret !== null) {
|
||||
$AfsCheckObj(adapter, $Call(ret, iter), "return")
|
||||
}
|
||||
|
|
@ -223,14 +280,15 @@ function $vmAsyncFromSyncClose(iter) {
|
|||
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.
|
||||
async function $vmHostWait(promises, callee, args) {
|
||||
// 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 $Apply(callee, undefined, args)
|
||||
return $vmReplay(callee, undefined, args, false, [], read, undefined)
|
||||
}
|
||||
|
||||
async function $vmResult(value) {
|
||||
|
|
@ -271,11 +329,17 @@ export const registerVmIntrinsics = (map: Map<string, unknown>, vm: Vm): void =>
|
|||
add("$IsPromise", ([v]) => v instanceof PromiseObj)
|
||||
add("$IsArray", ([v]) => v instanceof Arr)
|
||||
add("$IsCallableAny", ([v]) => v instanceof Callable)
|
||||
add("$GetMethod", ([v, name]) => {
|
||||
const m = get(v as Obj, name as string)
|
||||
return m instanceof Callable ? m : undefined
|
||||
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)) {
|
||||
|
|
@ -309,18 +373,35 @@ export const registerVmIntrinsics = (map: Map<string, unknown>, vm: Vm): void =>
|
|||
})
|
||||
add("$ConvCoerce", ([hint, val]) => (hint === "string" ? coerceToString(val) : coerceToNumber(val)))
|
||||
add("$IsConvert", ([res]) => res instanceof Convert)
|
||||
add("$ConvReplay", ([callable, target, args, constructing, replay]) => {
|
||||
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 fnObj = callable as Builtin
|
||||
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]
|
||||
}
|
||||
})
|
||||
|
||||
|
|
@ -361,6 +442,8 @@ export const registerVmIntrinsics = (map: Map<string, unknown>, vm: Vm): void =>
|
|||
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
|
||||
|
|
@ -463,16 +546,20 @@ export const tryFastBoundaryOrJson = (
|
|||
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 toJSON =
|
||||
const toJSONSlot =
|
||||
plain && cur.proto === objectProto && objectProto.intrinsic > 0 && !cur.props.has("toJSON")
|
||||
? undefined
|
||||
: get(cur, "toJSON")
|
||||
: 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 }
|
||||
|
|
@ -505,6 +592,8 @@ export const tryFastBoundaryOrJson = (
|
|||
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
|
||||
|
|
@ -514,7 +603,8 @@ export const tryFastBoundaryOrJson = (
|
|||
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?.(cur)
|
||||
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) {
|
||||
|
|
|
|||
|
|
@ -145,6 +145,9 @@ export const Op = {
|
|||
|
||||
// Program (1)
|
||||
END_PROGRAM: 87,
|
||||
|
||||
// Literals, added later: `get x() {}` / `set x(v) {}` (a bit 0: computed key; bit 1: setter)
|
||||
DEFINE_ACCESSOR: 88,
|
||||
} as const
|
||||
|
||||
export type OpCode = (typeof Op)[keyof typeof Op]
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
|
|
@ -1,4 +1,4 @@
|
|||
import { isSupportedCallback, requireCallback } from "../runtime/callback.js"
|
||||
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"
|
||||
|
|
@ -6,7 +6,7 @@ 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 { invalidData, IteratorSymbol, PendingThrow } from "../runtime/model.js"
|
||||
import { AsyncIteratorSymbol, invalidData, IteratorSymbol, PendingThrow } from "../runtime/model.js"
|
||||
import { native, receiver } from "../runtime/native.js"
|
||||
import {
|
||||
Arr,
|
||||
|
|
@ -18,6 +18,8 @@ import {
|
|||
hasPrototype,
|
||||
keys,
|
||||
getOwn,
|
||||
own,
|
||||
ownKeys,
|
||||
IteratorObj,
|
||||
positionIterator,
|
||||
coerceToNumber,
|
||||
|
|
@ -74,17 +76,38 @@ export const helpers = (ctx: Interpreter<unknown>): Array<readonly [string, Valu
|
|||
/** Whether `for...of` can iterate `value`. */
|
||||
$IsIterable: [
|
||||
1,
|
||||
([value]) => {
|
||||
if (builtinCursor(builtins, value) !== undefined) return true
|
||||
if (!(value instanceof Obj)) return false
|
||||
const method = get(value, IteratorSymbol)
|
||||
return method !== undefined && method !== null
|
||||
},
|
||||
([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,
|
||||
|
|
@ -93,6 +116,14 @@ export const helpers = (ctx: Interpreter<unknown>): Array<readonly [string, Valu
|
|||
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: [
|
||||
|
|
@ -107,7 +138,7 @@ export const helpers = (ctx: Interpreter<unknown>): Array<readonly [string, Valu
|
|||
$Pairs: [
|
||||
4,
|
||||
([kind, proto, value, label]) =>
|
||||
buildPairs({ kind: kind as "Headers", proto: proto as Obj }, value, String(label)),
|
||||
withReads(() => buildPairs({ kind: kind as "Headers", proto: proto as Obj }, value, String(label))),
|
||||
],
|
||||
$IsCallable: [1, ([value]) => isSupportedCallback(value)],
|
||||
/**
|
||||
|
|
@ -121,11 +152,14 @@ export const helpers = (ctx: Interpreter<unknown>): Array<readonly [string, Valu
|
|||
? positionIterator(builtins, value, "values")
|
||||
: value instanceof IteratorObj
|
||||
? value
|
||||
: new IteratorObj(builtins.Iterator, {
|
||||
iterator: requireIteratorObject(value, "An iterator"),
|
||||
next: get(value as Obj, "next"),
|
||||
asynchronous: false,
|
||||
}),
|
||||
: 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,7 +5,7 @@ function arrayFromIterable(items, mapper, thisArg) {
|
|||
const result = []
|
||||
let index = 0
|
||||
for (const item of items) {
|
||||
result[index] = mapper === undefined ? item : $Call(mapper, thisArg, item, index)
|
||||
$ArraySet(result, index, mapper === undefined ? item : $Call(mapper, thisArg, item, index))
|
||||
index++
|
||||
}
|
||||
return result
|
||||
|
|
@ -16,7 +16,7 @@ function arrayFromLike(source, length, mapper, thisArg) {
|
|||
const result = new Array(length)
|
||||
let index = 0
|
||||
while (index < length) {
|
||||
result[index] = $Call(mapper, thisArg, source[index], index)
|
||||
$ArraySet(result, index, $Call(mapper, thisArg, source[index], index))
|
||||
index++
|
||||
}
|
||||
return result
|
||||
|
|
@ -38,7 +38,7 @@ function mapItems(array, callback, thisArg, label) {
|
|||
const result = new Array(length)
|
||||
let index = 0
|
||||
while (index < length) {
|
||||
if (index in array) result[index] = $Call(callback, thisArg, array[index], index, array)
|
||||
if (index in array) $ArraySet(result, index, $Call(callback, thisArg, array[index], index, array))
|
||||
index++
|
||||
}
|
||||
return result
|
||||
|
|
@ -227,10 +227,10 @@ function sortWith(target, into, holes, comparator, work, undefs, merges) {
|
|||
order = +$Call(comparator, undefined, work[left], work[right])
|
||||
// A NaN result counts as equal, which keeps the order stable.
|
||||
if (order <= 0 || order !== order) {
|
||||
merged[count] = work[left]
|
||||
$ArraySet(merged, count, work[left])
|
||||
left++
|
||||
} else {
|
||||
merged[count] = work[right]
|
||||
$ArraySet(merged, count, work[right])
|
||||
right++
|
||||
}
|
||||
count++
|
||||
|
|
@ -387,7 +387,7 @@ function Math$sumPrecise(items) {
|
|||
const numbers = []
|
||||
for (const item of items) {
|
||||
if (typeof item !== "number") $Throw("TypeError", "Math.sumPrecise expects an iterable of numbers.")
|
||||
numbers[numbers.length] = item
|
||||
$ArraySet(numbers, numbers.length, item)
|
||||
}
|
||||
return $SumPrecise(numbers)
|
||||
}
|
||||
|
|
@ -395,7 +395,7 @@ function Math$sumPrecise(items) {
|
|||
// 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) list[list.length] = item
|
||||
for (const item of errors) $ArraySet(list, list.length, item)
|
||||
return $Define(error, "errors", list, false)
|
||||
}
|
||||
|
||||
|
|
@ -404,7 +404,7 @@ function aggregateError(error, errors) {
|
|||
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) values[values.length] = item
|
||||
for (const item of source) $ArraySet(values, values.length, item)
|
||||
let index = 0
|
||||
if (mapper !== undefined) {
|
||||
while (index < values.length) {
|
||||
|
|
@ -415,6 +415,47 @@ function collectBytes(source, name, mapper, thisArg, into, offset) {
|
|||
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) {
|
||||
|
|
@ -424,8 +465,8 @@ function readPairs(init, label, kind, proto) {
|
|||
for (const pair of init) {
|
||||
if (!$IsIterable(pair)) $Throw("TypeError", label + " expects iterable [name, value] pairs.")
|
||||
strings = []
|
||||
for (const item of pair) strings[strings.length] = String(item)
|
||||
pairs[pairs.length] = strings
|
||||
for (const item of pair) $ArraySet(strings, strings.length, String(item))
|
||||
$ArraySet(pairs, pairs.length, strings)
|
||||
}
|
||||
return $Pairs(kind, proto, pairs, label)
|
||||
}
|
||||
|
|
@ -573,7 +614,7 @@ function closeIterator(iterator) {
|
|||
|
||||
function Iterator$prototype$toArray() {
|
||||
const result = []
|
||||
for (const item of $Direct(this, false)) result[result.length] = item
|
||||
for (const item of $Direct(this, false)) $ArraySet(result, result.length, item)
|
||||
return result
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import { type Builtins, primitivePrototype } from "./intrinsics.js"
|
||||
import { typeError } from "./model.js"
|
||||
import { Callable, get, Builtin, Obj, type NativeResult, type Value } from "./objects.js"
|
||||
import { Callable, get, Builtin, Obj, type NativeResult, reads, type Value } from "./objects.js"
|
||||
import { typeofValue } from "./references.js"
|
||||
import { Convert, type Hints, Invoke } from "./signals.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 => {
|
||||
|
|
@ -41,6 +41,32 @@ export const withPrimitives = (
|
|||
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
|
||||
|
|
|
|||
|
|
@ -22,10 +22,11 @@ import {
|
|||
Obj,
|
||||
coerceToString,
|
||||
type Value,
|
||||
peek,
|
||||
} from "./objects.js"
|
||||
import type { Interpreter } from "./interpreter.js"
|
||||
import { Invoke } from "./signals.js"
|
||||
import { withPrimitives } from "./callback.js"
|
||||
import { withPrimitives, withReads } from "./callback.js"
|
||||
import { formatValue } from "../stdlib/console.js"
|
||||
import { inPrelude } from "./source.js"
|
||||
|
||||
|
|
@ -137,9 +138,9 @@ export const materialize = <R>(ctx: Interpreter<R>, thrown: unknown): Value => {
|
|||
}
|
||||
|
||||
/** Error.prototype.toString: `name: message`, omitting whichever side is empty. */
|
||||
const errorToString = (self: Obj): string => {
|
||||
const name = get(self, "name")
|
||||
const message = get(self, "message")
|
||||
const errorToString = (self: Obj, read: (target: Obj, key: string) => Value = peek): string => {
|
||||
const name = read(self, "name")
|
||||
const message = read(self, "message")
|
||||
const shownName = name === undefined ? "Error" : coerceToString(name)
|
||||
const shownMessage = message === undefined ? "" : coerceToString(message)
|
||||
if (shownMessage === "") return shownName
|
||||
|
|
@ -176,8 +177,13 @@ export const errorGlobal = <R>(type: ErrorType, ctx: Interpreter<R>) => {
|
|||
"string",
|
||||
message === undefined ? [] : [message],
|
||||
([text]) => {
|
||||
const created = withCause(createErrorValue(proto, message === undefined ? "" : coerceToString(text)), args[2])
|
||||
return new Invoke(ctx.prelude.fn("aggregateError"), undefined, [created, args[0]], undefined)
|
||||
return withReads(() => {
|
||||
const created = withCause(
|
||||
createErrorValue(proto, message === undefined ? "" : coerceToString(text)),
|
||||
args[2],
|
||||
)
|
||||
return new Invoke(ctx.prelude.fn("aggregateError"), undefined, [created, args[0]], undefined)
|
||||
})
|
||||
},
|
||||
true,
|
||||
)
|
||||
|
|
@ -186,7 +192,10 @@ export const errorGlobal = <R>(type: ErrorType, ctx: Interpreter<R>) => {
|
|||
return withPrimitives(
|
||||
"string",
|
||||
message === undefined ? [] : [message],
|
||||
([text]) => withCause(createErrorValue(proto, message === undefined ? undefined : coerceToString(text)), args[1]),
|
||||
([text]) =>
|
||||
withReads(() =>
|
||||
withCause(createErrorValue(proto, message === undefined ? undefined : coerceToString(text)), args[1]),
|
||||
),
|
||||
true,
|
||||
)
|
||||
}
|
||||
|
|
@ -198,7 +207,11 @@ export const errorGlobal = <R>(type: ErrorType, ctx: Interpreter<R>) => {
|
|||
})
|
||||
if (type === "Error") {
|
||||
methods(builtins, prototype, [
|
||||
["toString", 0, (thisValue) => errorToString(receiver(Obj, thisValue, "Error.prototype.toString"))],
|
||||
[
|
||||
"toString",
|
||||
0,
|
||||
(thisValue) => withReads(() => errorToString(receiver(Obj, thisValue, "Error.prototype.toString"), get)),
|
||||
],
|
||||
])
|
||||
methods(builtins, ctor, [["isError", 1, (_, args) => args[0] instanceof ErrorObj]])
|
||||
return ctor
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import { AsyncIteratorSymbol, HostFailure, PendingThrow, rangeError, Throw, type
|
|||
import { native } from "./native.js"
|
||||
import {
|
||||
define,
|
||||
defineAccessor,
|
||||
defineAccessorHalf,
|
||||
get,
|
||||
has,
|
||||
hidden,
|
||||
|
|
@ -33,6 +33,8 @@ import {
|
|||
URLSearchParamsObj,
|
||||
coerceToString,
|
||||
type Value,
|
||||
lookup,
|
||||
type Slot,
|
||||
} from "./objects.js"
|
||||
import { describeValue, isOpaque, typeofValue } from "./references.js"
|
||||
import type { Translate } from "../runtime.js"
|
||||
|
|
@ -63,6 +65,8 @@ type Within = {
|
|||
* 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>>,
|
||||
|
|
@ -124,7 +128,7 @@ export const hostGlobals = <R>(
|
|||
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)) continue
|
||||
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, {
|
||||
|
|
@ -142,6 +146,10 @@ export const hostGlobals = <R>(
|
|||
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
|
||||
|
|
@ -184,7 +192,13 @@ export const hostGlobals = <R>(
|
|||
const body = response.body
|
||||
const stream = new Obj(builtins.Object)
|
||||
if (body) {
|
||||
defineAccessor(stream, "locked", () => body.locked)
|
||||
defineAccessorHalf(
|
||||
stream,
|
||||
"locked",
|
||||
"get",
|
||||
hostGetter("locked", () => body.locked),
|
||||
false,
|
||||
)
|
||||
define(
|
||||
stream,
|
||||
"cancel",
|
||||
|
|
@ -220,7 +234,13 @@ export const hostGlobals = <R>(
|
|||
define(result, key, next(response[key], `${label}.${key}`))
|
||||
define(result, "redirected", value.redirected)
|
||||
define(result, "body", body ? stream : null)
|
||||
defineAccessor(result, "bodyUsed", () => response.bodyUsed)
|
||||
defineAccessorHalf(
|
||||
result,
|
||||
"bodyUsed",
|
||||
"get",
|
||||
hostGetter("bodyUsed", () => response.bodyUsed),
|
||||
false,
|
||||
)
|
||||
for (const key of ["text", "json", "bytes", "arrayBuffer"] as const)
|
||||
define(
|
||||
result,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { Arr, BoundFn, Callable, coerceToInteger, 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"
|
||||
|
|
@ -37,12 +38,28 @@ const functionGlobal = <R>(ctx: Interpreter<R>) => {
|
|||
[
|
||||
"apply",
|
||||
2,
|
||||
(thisValue, args, site) => new Invoke(target(thisValue, "apply"), args[0], listFromArrayLike(args[1]), site),
|
||||
(thisValue, args, site) =>
|
||||
withReads(() => new Invoke(target(thisValue, "apply"), args[0], listFromArrayLike(args[1]), site)),
|
||||
],
|
||||
[
|
||||
"bind",
|
||||
1,
|
||||
(thisValue, args) => new BoundFn(ctx.builtins.Function, target(thisValue, "bind"), args[0], args.slice(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,
|
||||
)
|
||||
}),
|
||||
],
|
||||
])
|
||||
return constructor(ctx.builtins, ctx.builtins.Function, {
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ 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, entries, type HostNamespace, makingIntrinsics, nativeRule, Obj, type Value } from "./objects.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"
|
||||
|
|
@ -56,7 +56,7 @@ export class Interpreter<R> {
|
|||
// 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), () => {
|
||||
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
|
||||
})
|
||||
|
|
@ -103,7 +103,8 @@ export class Interpreter<R> {
|
|||
const cached = this.namespaces.get(name)
|
||||
if (cached) return cached
|
||||
const namespace = new Obj(null)
|
||||
if (module instanceof Obj) for (const [key, value] of entries(module)) define(namespace, key, value)
|
||||
// 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
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import type { Builtins } from "./intrinsics.js"
|
||||
import { AsyncIteratorSymbol, IteratorSymbol } from "./model.js"
|
||||
import { Arr, Fn, Native, Obj, type Value } from "./objects.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
|
||||
|
|
@ -139,10 +139,11 @@ 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<string | readonly [parent: number, key: string | symbol]> = []
|
||||
const paths: Array<Path> = []
|
||||
const position = made.map(() => -1)
|
||||
const visit = (value: Value, path: string | readonly [number, string | symbol]) => {
|
||||
const visit = (value: Value, path: Path) => {
|
||||
if (!(value instanceof Obj)) return
|
||||
const id = value.intrinsic - 1
|
||||
if (id < 0 || made[id] !== value) {
|
||||
|
|
@ -153,13 +154,21 @@ const walk = (made: ReadonlyArray<Obj>, roots: Roots): Table => {
|
|||
order.push(id)
|
||||
paths.push(path)
|
||||
}
|
||||
const describe = (path: string | readonly [number, string | symbol]): string =>
|
||||
typeof path === "string" ? path : member(describe(paths[path[0]]!), path[1])
|
||||
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])
|
||||
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])
|
||||
}
|
||||
}
|
||||
|
|
@ -170,7 +179,7 @@ const walk = (made: ReadonlyArray<Obj>, roots: Roots): Table => {
|
|||
drain()
|
||||
}
|
||||
const names: Array<string> = []
|
||||
for (const path of paths) names.push(typeof path === "string" ? path : member(names[path[0]]!, path[1]))
|
||||
for (const path of paths) names.push(typeof path === "string" ? path : name(names[path[0]]!, path))
|
||||
return { count: made.length, order, names, position }
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -93,7 +93,7 @@ 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, getters/setters, BigInt, and custom Symbols. Use plain functions and data objects instead."
|
||||
"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 } => ({
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ import {
|
|||
Throw,
|
||||
typeError,
|
||||
} from "./model.js"
|
||||
import { type Convert, type GeneratorRequest, Invoke, type Push, type Resume } from "./signals.js"
|
||||
import { type Convert, type GeneratorRequest, Invoke, type Prefetch, type Push, type Resume } from "./signals.js"
|
||||
import type { Code } from "../code.js"
|
||||
import { type Cell, CodeFlags } from "../opcodes.js"
|
||||
import type { Reaction, Resolving } from "../scheduler.js"
|
||||
|
|
@ -26,25 +26,67 @@ export type Attributes = {
|
|||
export type Getter = (receiver: Value) => Value
|
||||
export type Setter = (receiver: Value, value: Value) => void
|
||||
|
||||
/** One own property: a data slot or a native accessor pair. */
|
||||
/**
|
||||
* One own property: a data slot, or an accessor whose halves are each a native closure (`typeof half === "function"`)
|
||||
* or a program function (a `Callable`, which is never a JS function).
|
||||
*/
|
||||
export type Slot =
|
||||
| { value: Value; writable: boolean; enumerable: boolean; configurable: boolean }
|
||||
| { get: Getter | undefined; set: Setter | undefined; enumerable: boolean; configurable: boolean }
|
||||
| {
|
||||
get: Getter | Callable | undefined
|
||||
set: Setter | Callable | undefined
|
||||
enumerable: boolean
|
||||
configurable: boolean
|
||||
}
|
||||
export type AccessorSlot = Extract<Slot, { get: unknown }>
|
||||
|
||||
/** Whether an accessor half is a program function, which only program code can call. */
|
||||
export const isProgramHalf = (half: unknown): half is Callable => half !== undefined && typeof half !== "function"
|
||||
|
||||
/** Whether a slot is an accessor with at least one program half. */
|
||||
export const isProgramAccessor = (slot: Slot): slot is AccessorSlot =>
|
||||
!("value" in slot) && (isProgramHalf(slot.get) || isProgramHalf(slot.set))
|
||||
|
||||
/** Whether a slot is an accessor with no getter, which reads as undefined and never crosses to the host. */
|
||||
const isSetterOnly = (slot: Slot): boolean => !("value" in slot) && slot.get === undefined
|
||||
|
||||
// The objects made while a runtime's intrinsics are being made, in creation order; see `makingIntrinsics`.
|
||||
let making: Array<Obj> | undefined
|
||||
// The `Function.prototype` of the intrinsics being made, for the companions of native accessors.
|
||||
let makingFunctions: Obj | undefined
|
||||
|
||||
/**
|
||||
* The program function that stands for each native accessor half (`Object.getOwnPropertyDescriptor(Map.prototype,
|
||||
* "size").get`), made with the intrinsics so it is named like one, and the half each one stands for.
|
||||
*/
|
||||
const companions = new WeakMap<Getter | Setter, Native>()
|
||||
const companionHalves = new WeakMap<Native, Getter | Setter>()
|
||||
|
||||
/** The function a program sees for an accessor half: the program function, or a native half's companion. */
|
||||
export const accessorFunction = (half: Getter | Setter | Callable | undefined): Callable | undefined =>
|
||||
half === undefined || isProgramHalf(half) ? half : companions.get(half)
|
||||
|
||||
/** The half to store for a function a program gives: a companion's native closure, so reads stay on the native path. */
|
||||
export const accessorHalf = (fn: Callable | undefined): Getter | Setter | Callable | undefined =>
|
||||
fn instanceof Native ? (companionHalves.get(fn) ?? fn) : fn
|
||||
|
||||
/**
|
||||
* Runs `make`, which makes a runtime's intrinsics, and returns every object made meanwhile, in creation order, after
|
||||
* `first` (the built-in prototypes, made before). An object's index in the list is its static intrinsic id.
|
||||
*/
|
||||
export const makingIntrinsics = <A>(first: ReadonlyArray<Obj>, make: () => A): readonly [A, Array<Obj>] => {
|
||||
export const makingIntrinsics = <A>(
|
||||
first: ReadonlyArray<Obj>,
|
||||
functions: Obj,
|
||||
make: () => A,
|
||||
): readonly [A, Array<Obj>] => {
|
||||
const made = [...first]
|
||||
making = made
|
||||
makingFunctions = functions
|
||||
try {
|
||||
return [make(), made]
|
||||
} finally {
|
||||
making = undefined
|
||||
makingFunctions = undefined
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -78,6 +120,8 @@ export class Obj {
|
|||
* once it changes (see `changed` and `IntrinsicNames`).
|
||||
*/
|
||||
intrinsic = 0
|
||||
/** Whether a program accessor was ever defined here: the bulk readers' cue to take their slow paths. */
|
||||
hasProgramAccessors = false
|
||||
constructor(public proto: Obj | null) {
|
||||
if (making !== undefined) making.push(this)
|
||||
}
|
||||
|
|
@ -108,17 +152,39 @@ export class Obj {
|
|||
|
||||
/** How `console.log` shows the value; `item` formats a child with cycle and depth tracking. */
|
||||
inspect(item: (value: Value) => string): string {
|
||||
return `{${entries(this)
|
||||
.map(([key, value]) => `${JSON.stringify(key)}:${item(value)}`)
|
||||
if (!this.hasProgramAccessors) {
|
||||
return `{${entries(this)
|
||||
.map(([key, value]) => `${JSON.stringify(key)}:${item(value)}`)
|
||||
.join(",")}}`
|
||||
}
|
||||
// Showing a value never runs program code, so a program accessor shows what it is, as Node does.
|
||||
return `{${keys(this)
|
||||
.map((key) => {
|
||||
const slot = own(this, key)!
|
||||
return `${JSON.stringify(key)}:${isProgramAccessor(slot) ? accessorLabel(slot) : item(getOwn(this, key))}`
|
||||
})
|
||||
.join(",")}}`
|
||||
}
|
||||
|
||||
/** A copy the host can hold; `item` converts a child. A `__proto__` key never reaches host code. */
|
||||
toHost(item: (value: Value) => unknown): unknown {
|
||||
if (!this.hasProgramAccessors) {
|
||||
return Object.fromEntries(
|
||||
entries(this).flatMap(([key, value]) => {
|
||||
if (key === "__proto__") return []
|
||||
// A setter-only native accessor reads as undefined; it is left out like a program one.
|
||||
if (value === undefined && isSetterOnly(own(this, key)!)) return []
|
||||
const copied = item(value)
|
||||
return copied === OMITTED ? [] : [[key, copied]]
|
||||
}),
|
||||
)
|
||||
}
|
||||
// A getter's value crosses as data (read ahead by the call; see `HostCalls`), and a setter-only property is left out.
|
||||
return Object.fromEntries(
|
||||
entries(this).flatMap(([key, value]) => {
|
||||
if (key === "__proto__") return []
|
||||
const copied = item(value)
|
||||
keys(this).flatMap((key) => {
|
||||
const slot = own(this, key)!
|
||||
if (key === "__proto__" || isSetterOnly(slot)) return []
|
||||
const copied = item(getOwn(this, key))
|
||||
return copied === OMITTED ? [] : [[key, copied]]
|
||||
}),
|
||||
)
|
||||
|
|
@ -171,8 +237,8 @@ export class ErrorObj extends Obj {
|
|||
failure?: PendingThrow
|
||||
/** Error.prototype.toString: "name: message", or just one when the other is empty. */
|
||||
override toString() {
|
||||
const name = get(this, "name")
|
||||
const message = get(this, "message")
|
||||
const name = peek(this, "name")
|
||||
const message = peek(this, "message")
|
||||
const shownName = typeof name === "string" ? name : "Error"
|
||||
const shownMessage = typeof message === "string" ? message : ""
|
||||
if (shownMessage === "") return shownName
|
||||
|
|
@ -231,6 +297,8 @@ export class Arguments extends Obj {
|
|||
define(this, "length", args.length, hidden)
|
||||
}
|
||||
override iterator(builtins: Builtins) {
|
||||
// With program accessors, its own `[Symbol.iterator]` (the prelude's `argumentsValues`) reads it in program code.
|
||||
if (this.hasProgramAccessors) return undefined
|
||||
return new Position(
|
||||
keys(this).map((key) => get(this, key)),
|
||||
"values",
|
||||
|
|
@ -244,7 +312,7 @@ export class Arguments extends Obj {
|
|||
* suspended generator to continue (`Resume`), a call it hands on (`Invoke`), or conversions to run before it runs again
|
||||
* (`Convert`). A native never runs program code itself.
|
||||
*/
|
||||
export type NativeResult = Value | Push | Resume | Invoke | Convert
|
||||
export type NativeResult = Value | Push | Resume | Invoke | Convert | Prefetch
|
||||
/** `site` is the call running the built-in, where a failure it reports later (a rejection) is located. */
|
||||
export type NativeCall = (thisValue: Value, args: Array<Value>, site: AstNode | undefined) => NativeResult
|
||||
export type NativeConstruct = (args: Array<Value>, newTarget: Callable, site: AstNode | undefined) => NativeResult
|
||||
|
|
@ -319,8 +387,10 @@ export class BoundFn extends Builtin {
|
|||
readonly target: Callable,
|
||||
readonly boundThis: Value,
|
||||
readonly boundArgs: ReadonlyArray<Value>,
|
||||
name: string,
|
||||
length: number,
|
||||
) {
|
||||
super(proto, `bound ${coerceToString(get(target, "name"))}`, Math.max(0, target.length - boundArgs.length))
|
||||
super(proto, `bound ${name}`, length)
|
||||
}
|
||||
|
||||
invoke(_: Value, args: Array<Value>, site: AstNode | undefined): NativeResult {
|
||||
|
|
@ -775,14 +845,30 @@ export const own = (target: Obj, key: PropertyKey): Slot | undefined => {
|
|||
return target.props.get(typeof name === "number" ? String(name) : name)
|
||||
}
|
||||
|
||||
const read = (slot: Slot, receiver: Value): Value =>
|
||||
"value" in slot ? slot.value : slot.get === undefined ? undefined : slot.get(receiver)
|
||||
// A slot's value for `receiver`. A program getter can only run as program code: inside `withReads` its value comes from
|
||||
// the read-ahead table (or is recorded as missing); anywhere else reaching one is an error.
|
||||
const read = (slot: Slot, receiver: Value, key: PropertyKey): Value => {
|
||||
if ("value" in slot) return slot.value
|
||||
const getter = slot.get
|
||||
if (getter === undefined) return undefined
|
||||
if (typeof getter === "function") return getter(receiver)
|
||||
return programRead(receiver, key)
|
||||
}
|
||||
|
||||
export const hasOwn = (target: Obj, key: PropertyKey): boolean => own(target, key) !== undefined
|
||||
|
||||
export const getOwn = (target: Obj, key: PropertyKey): Value => {
|
||||
const slot = own(target, key)
|
||||
return slot === undefined ? undefined : read(slot, target)
|
||||
return slot === undefined ? undefined : read(slot, target, key)
|
||||
}
|
||||
|
||||
/** [[Get]]'s lookup: the slot `key` names on `target` or its prototype chain. */
|
||||
export const lookup = (target: Obj, key: PropertyKey): Slot | undefined => {
|
||||
for (let current: Obj | null = target; current !== null; current = current.proto) {
|
||||
const slot = own(current, key)
|
||||
if (slot !== undefined) return slot
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** [[Get]]: walks the prototype chain; accessors see `receiver`, which is the primitive for wrapper prototypes. */
|
||||
|
|
@ -792,11 +878,82 @@ export const get = (target: Obj, key: PropertyKey, receiver: Value = target): Va
|
|||
return target.items[key]
|
||||
for (let current: Obj | null = target; current !== null; current = current.proto) {
|
||||
const slot = own(current, key)
|
||||
if (slot !== undefined) return read(slot, receiver)
|
||||
if (slot !== undefined) return read(slot, receiver, key)
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** A program getter a caller that runs program code calls itself, with the read's receiver as `this`. */
|
||||
export class GetterCall {
|
||||
constructor(readonly getter: Callable) {}
|
||||
}
|
||||
|
||||
/** [[Get]] for callers that can run program code (the VM's ops): the value, or the program getter to call. */
|
||||
export const access = (target: Obj, key: PropertyKey, receiver: Value = target): Value | GetterCall => {
|
||||
if (typeof key === "number" && target instanceof Arr && key in target.items && parseArrayIndex(key) !== undefined)
|
||||
return target.items[key]
|
||||
const slot = lookup(target, key)
|
||||
if (slot === undefined || "value" in slot) return slot?.value
|
||||
const getter = slot.get
|
||||
if (getter === undefined) return undefined
|
||||
if (typeof getter === "function") return getter(receiver)
|
||||
return new GetterCall(getter)
|
||||
}
|
||||
|
||||
/**
|
||||
* [[Get]] for display and diagnostics, which never run program code: a program getter reads as `undefined`.
|
||||
*/
|
||||
export const peek = (target: Obj, key: PropertyKey, receiver: Value = target): Value => {
|
||||
const slot = lookup(target, key)
|
||||
if (slot === undefined || "value" in slot) return slot?.value
|
||||
const getter = slot.get
|
||||
return typeof getter === "function" ? getter(receiver) : undefined
|
||||
}
|
||||
|
||||
/** How display shows a program accessor in place of its value, in Node's words. */
|
||||
export const accessorLabel = (slot: AccessorSlot): string =>
|
||||
slot.get !== undefined && slot.set !== undefined
|
||||
? "[Getter/Setter]"
|
||||
: slot.get !== undefined
|
||||
? "[Getter]"
|
||||
: "[Setter]"
|
||||
|
||||
/**
|
||||
* The program getters a built-in reads ahead (see `withReads` in callback.ts): while it runs again after the VM read
|
||||
* them, `table` has their values by receiver and key (canonical), and `list` is the program array they came from
|
||||
* (receiver, key, value, …). Inside `withReads` (`depth` > 0), a getter not in the table reads as `undefined` and is
|
||||
* recorded in `missing` (receiver, key, …), once per pair.
|
||||
*/
|
||||
export const reads: {
|
||||
table: Map<Value, Map<string | symbol, Value>> | undefined
|
||||
list: Arr | undefined
|
||||
depth: number
|
||||
missing: Array<Value> | undefined
|
||||
} = { table: undefined, list: undefined, depth: 0, missing: undefined }
|
||||
|
||||
/** When `check` is on (tests turn it on), a built-in reaching a program accessor it has no path for is a defect. */
|
||||
export const accessorRule = { check: false }
|
||||
|
||||
const programRead = (receiver: Value, key: PropertyKey): Value => {
|
||||
const name = canonical(key)
|
||||
const known = reads.table?.get(receiver)
|
||||
if (known !== undefined && known.has(name)) return known.get(name)
|
||||
if (reads.depth === 0) return unreachableAccessor(name)
|
||||
const missing = (reads.missing ??= [])
|
||||
for (let at = 0; at < missing.length; at += 2)
|
||||
if (missing[at] === receiver && missing[at + 1] === name) return undefined
|
||||
missing.push(receiver, name)
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** A built-in met a program getter or setter it cannot call: a TypeError, or a defect under `accessorRule.check`. */
|
||||
export const unreachableAccessor = (key: PropertyKey): never => {
|
||||
if (accessorRule.check) throw new Error(`A built-in reached the program accessor ${String(key)} with no path for it.`)
|
||||
throw typeError(
|
||||
`A built-in cannot call the getter or setter '${String(key)}' here; read the property into a variable first.`,
|
||||
)
|
||||
}
|
||||
|
||||
export const has = (target: Obj, key: PropertyKey): boolean => {
|
||||
for (let current: Obj | null = target; current !== null; current = current.proto) {
|
||||
if (own(current, key) !== undefined) return true
|
||||
|
|
@ -834,8 +991,11 @@ const writeElement = (target: Indexed, name: string | number | symbol, value: Va
|
|||
return true
|
||||
}
|
||||
|
||||
/** [[Set]]: an inherited setter or read-only property decides before an own data property is created. */
|
||||
export const set = (target: Obj, key: PropertyKey, value: Value): boolean => {
|
||||
/**
|
||||
* [[Set]]: an inherited setter or read-only property decides before an own data property is created. A program setter
|
||||
* is not called here: it is returned, for the caller to call with `target` as `this` and `[value]`.
|
||||
*/
|
||||
export const set = (target: Obj, key: PropertyKey, value: Value): boolean | Callable => {
|
||||
// Overwriting an array's present, writable element: no setter or read-only slot can decide first.
|
||||
if (typeof key === "number" && target instanceof Arr && target.elements.writable && key in target.items) {
|
||||
if (parseArrayIndex(key) !== undefined) {
|
||||
|
|
@ -849,8 +1009,10 @@ export const set = (target: Obj, key: PropertyKey, value: Value): boolean => {
|
|||
const slot = own(current, key)
|
||||
if (slot === undefined) continue
|
||||
if (!("value" in slot)) {
|
||||
if (slot.set === undefined) return false
|
||||
slot.set(target, value)
|
||||
const setter = slot.set
|
||||
if (setter === undefined) return false
|
||||
if (typeof setter !== "function") return setter
|
||||
setter(target, value)
|
||||
return true
|
||||
}
|
||||
if (!slot.writable) return false
|
||||
|
|
@ -887,9 +1049,180 @@ export const define = (target: Obj, key: PropertyKey, value: Value, attrs: Attri
|
|||
target.props.set(name, { value, ...attrs })
|
||||
}
|
||||
|
||||
/** A built-in's native accessor. Made with the intrinsics, each half gets its companion program function. */
|
||||
export const defineAccessor = (target: Obj, key: PropertyKey, get: Getter | undefined, set?: Setter): void => {
|
||||
changed(target)
|
||||
target.props.set(canonical(key), { get, set, enumerable: false, configurable: true })
|
||||
const name = canonical(key)
|
||||
target.props.set(name, { get, set, enumerable: false, configurable: true })
|
||||
if (making === undefined) return
|
||||
const label = typeof name === "symbol" ? `[${name.description}]` : name
|
||||
if (get !== undefined) {
|
||||
const getter = new Native(makingFunctions!, { name: `get ${label}`, call: (thisValue) => get(thisValue) })
|
||||
companions.set(get, getter)
|
||||
companionHalves.set(getter, get)
|
||||
}
|
||||
if (set !== undefined) {
|
||||
const setter = new Native(makingFunctions!, {
|
||||
name: `set ${label}`,
|
||||
length: 1,
|
||||
call: (thisValue, args) => {
|
||||
set(thisValue, args[0])
|
||||
return undefined
|
||||
},
|
||||
})
|
||||
companions.set(set, setter)
|
||||
companionHalves.set(setter, set)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An object literal's `get x() {}` or `set x(v) {}`: an existing accessor keeps its other half; a data property, or no
|
||||
* property, becomes an accessor with only this half.
|
||||
*/
|
||||
export const defineAccessorHalf = (
|
||||
target: Obj,
|
||||
key: PropertyKey,
|
||||
half: "get" | "set",
|
||||
fn: Callable,
|
||||
enumerable = true,
|
||||
): void => {
|
||||
const name = canonical(key)
|
||||
const current = target.props.get(name)
|
||||
const slot: AccessorSlot =
|
||||
current !== undefined && !("value" in current)
|
||||
? { get: current.get, set: current.set, enumerable, configurable: true }
|
||||
: { get: undefined, set: undefined, enumerable, configurable: true }
|
||||
slot[half] = fn
|
||||
changed(target)
|
||||
target.hasProgramAccessors = true
|
||||
target.props.set(name, slot)
|
||||
}
|
||||
|
||||
/** A property descriptor a program gave: a field present means the descriptor has it (`"get" in desc`), as in the spec. */
|
||||
export type Descriptor = {
|
||||
value?: Value
|
||||
writable?: boolean
|
||||
get?: Callable | undefined
|
||||
set?: Callable | undefined
|
||||
enumerable?: boolean
|
||||
configurable?: boolean
|
||||
}
|
||||
|
||||
const isAccessorDescriptor = (desc: Descriptor) => "get" in desc || "set" in desc
|
||||
const isDataDescriptor = (desc: Descriptor) => "value" in desc || "writable" in desc
|
||||
|
||||
/**
|
||||
* ValidateAndApplyPropertyDescriptor for an own property: false where the spec answers false (the caller throws), and
|
||||
* a TypeError for what the object model cannot hold (an accessor on an array element, elements whose attributes differ
|
||||
* from their array's shared ones). Everything is checked before anything changes.
|
||||
*/
|
||||
export const defineOwnProperty = (target: Obj, key: PropertyKey, desc: Descriptor): boolean => {
|
||||
const name = canonical(key)
|
||||
const current = own(target, key)
|
||||
if (current === undefined && !target.extensible) return false
|
||||
if (current !== undefined && !compatible(current, desc)) return false
|
||||
if (isIndexed(target)) {
|
||||
const at = index(target, name)
|
||||
if (at !== undefined) return defineElement(target, at, current, desc)
|
||||
if (target instanceof Arr && name === "length") return defineLength(target, desc)
|
||||
}
|
||||
const slot = current === undefined ? created(desc) : applied(current, desc)
|
||||
if (isProgramAccessor(slot)) target.hasProgramAccessors = true
|
||||
changed(target)
|
||||
target.props.set(name, slot)
|
||||
return true
|
||||
}
|
||||
|
||||
// Whether `desc` may change a non-configurable `current` (a configurable one may change in any way).
|
||||
const compatible = (current: Slot, desc: Descriptor): boolean => {
|
||||
if (current.configurable) return true
|
||||
if (desc.configurable === true) return false
|
||||
if ("enumerable" in desc && desc.enumerable !== current.enumerable) return false
|
||||
if ("value" in current) {
|
||||
if (isAccessorDescriptor(desc)) return false
|
||||
if (current.writable) return true
|
||||
return desc.writable !== true && !("value" in desc && !Object.is(desc.value, current.value))
|
||||
}
|
||||
if (isDataDescriptor(desc)) return false
|
||||
return (
|
||||
(!("get" in desc) || accessorHalf(desc.get) === current.get) &&
|
||||
(!("set" in desc) || accessorHalf(desc.set) === current.set)
|
||||
)
|
||||
}
|
||||
|
||||
// A new property: what the descriptor gives, and false or undefined for what it leaves out.
|
||||
const created = (desc: Descriptor): Slot => {
|
||||
const enumerable = desc.enumerable ?? false
|
||||
const configurable = desc.configurable ?? false
|
||||
if (isAccessorDescriptor(desc)) {
|
||||
return {
|
||||
get: accessorHalf(desc.get) as Getter | Callable | undefined,
|
||||
set: accessorHalf(desc.set) as Setter | Callable | undefined,
|
||||
enumerable,
|
||||
configurable,
|
||||
}
|
||||
}
|
||||
return { value: desc.value, writable: desc.writable ?? false, enumerable, configurable }
|
||||
}
|
||||
|
||||
// An existing property with the descriptor's fields applied: a kind change keeps only the attributes.
|
||||
const applied = (current: Slot, desc: Descriptor): Slot => {
|
||||
const enumerable = desc.enumerable ?? current.enumerable
|
||||
const configurable = desc.configurable ?? current.configurable
|
||||
if ("value" in current && isAccessorDescriptor(desc)) return created({ ...desc, enumerable, configurable })
|
||||
if (!("value" in current) && isDataDescriptor(desc)) return created({ ...desc, enumerable, configurable })
|
||||
if ("value" in current) {
|
||||
return {
|
||||
value: "value" in desc ? desc.value : current.value,
|
||||
writable: desc.writable ?? current.writable,
|
||||
enumerable,
|
||||
configurable,
|
||||
}
|
||||
}
|
||||
return {
|
||||
get: "get" in desc ? (accessorHalf(desc.get) as Getter | Callable | undefined) : current.get,
|
||||
set: "set" in desc ? (accessorHalf(desc.set) as Setter | Callable | undefined) : current.set,
|
||||
enumerable,
|
||||
configurable,
|
||||
}
|
||||
}
|
||||
|
||||
// An array or Uint8Array element: elements have no slots, so only data with the collection's own attributes fits.
|
||||
const defineElement = (target: Indexed, at: number, current: Slot | undefined, desc: Descriptor): boolean => {
|
||||
if (isAccessorDescriptor(desc)) {
|
||||
throw typeError("Accessor properties are not supported on array elements; store the value or use a plain object.")
|
||||
}
|
||||
if (target instanceof Bytes && at >= target.bytes.length) return false
|
||||
const shared = target instanceof Arr ? target.elements : data
|
||||
// An element's own() slot is always data.
|
||||
const base = (current as Attributes | undefined) ?? { writable: false, enumerable: false, configurable: false }
|
||||
const writable = desc.writable ?? base.writable
|
||||
const enumerable = desc.enumerable ?? base.enumerable
|
||||
const configurable = desc.configurable ?? base.configurable
|
||||
if (writable !== shared.writable || enumerable !== shared.enumerable || configurable !== shared.configurable) {
|
||||
throw typeError(
|
||||
"Array elements share their attributes; only writable, enumerable and configurable equal to the array's are supported.",
|
||||
)
|
||||
}
|
||||
if (current === undefined || "value" in desc) {
|
||||
changed(target)
|
||||
if (target instanceof Bytes) target.bytes[at] = coerceToNumber(desc.value)
|
||||
else target.items[at] = desc.value
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// An array's `length`: its value, or making it read-only, which the shared element attributes can't separate.
|
||||
const defineLength = (target: Arr, desc: Descriptor): boolean => {
|
||||
if (isAccessorDescriptor(desc) || desc.configurable === true || desc.enumerable === true) return false
|
||||
if (desc.writable === false && target.elements.writable) {
|
||||
throw typeError("Making an array's length read-only is not supported; use Object.freeze.")
|
||||
}
|
||||
if ("value" in desc) {
|
||||
const length = coerceToNumber(desc.value)
|
||||
if (length !== target.items.length && writeElement(target, "length", length) === false) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
export const remove = (target: Obj, key: PropertyKey): boolean => {
|
||||
|
|
@ -941,6 +1274,15 @@ export const keys = (target: Obj): Array<string> =>
|
|||
/** Own enumerable string entries: `Object.entries` and serialization. */
|
||||
export const entries = (target: Obj): Array<[string, Value]> => keys(target).map((key) => [key, getOwn(target, key)])
|
||||
|
||||
/** Own enumerable string entries for display, which runs no program code: a program accessor shows as its label. */
|
||||
export const shownEntries = (target: Obj): Array<[string, Value]> => {
|
||||
if (!target.hasProgramAccessors) return entries(target)
|
||||
return keys(target).map((key) => {
|
||||
const slot = own(target, key)!
|
||||
return [key, isProgramAccessor(slot) ? accessorLabel(slot) : getOwn(target, key)]
|
||||
})
|
||||
}
|
||||
|
||||
/** An iterator result `{ value, done }`, built directly since every iteration step makes one. */
|
||||
export const iteratorResult = (proto: Obj, value: Value, done: boolean): Obj => {
|
||||
const target = new Obj(proto)
|
||||
|
|
@ -955,9 +1297,13 @@ export const record = (proto: Obj, fields: Record<string, Value>): Obj => {
|
|||
return target
|
||||
}
|
||||
|
||||
export const assign = (target: Obj, source: Obj, skip?: ReadonlySet<PropertyKey>): void => {
|
||||
/**
|
||||
* CopyDataProperties for a source without program accessors (spread and rest): defines data on `target`, so no setter
|
||||
* on its chain runs.
|
||||
*/
|
||||
export const copyDataProperties = (target: Obj, source: Obj, skip?: ReadonlySet<PropertyKey>): void => {
|
||||
for (const key of enumerableKeys(source)) {
|
||||
if (skip?.has(key)) continue
|
||||
set(target, key, getOwn(source, key))
|
||||
define(target, key, getOwn(source, key))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,9 +4,14 @@ 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,
|
||||
|
|
@ -24,7 +29,7 @@ import {
|
|||
coerceToString,
|
||||
type Value,
|
||||
} from "./objects.js"
|
||||
import { isOpaque, rejectCircularInsertion, typeofValue } from "./references.js"
|
||||
import { circularValue, describeValue, hasCircularReference, isOpaque, typeofValue } from "./references.js"
|
||||
import type { Interpreter } from "./interpreter.js"
|
||||
import { enumerableSource } from "../stdlib/object.js"
|
||||
|
||||
|
|
@ -98,12 +103,19 @@ export const notConstructible = (callee: Value, node: NewExpression) => {
|
|||
return typeError(message, node)
|
||||
}
|
||||
|
||||
// OrdinaryHasInstance: walk the left operand's chain looking for the constructor's `prototype`.
|
||||
export const instanceofValue = (lhs: Value, rhs: Value, node: AstNode): boolean => {
|
||||
// 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 = get(rhs, "prototype")
|
||||
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)
|
||||
}
|
||||
|
|
@ -205,9 +217,16 @@ type MemberReference = {
|
|||
receiver: Value
|
||||
}
|
||||
|
||||
// A thenable the program's implicit async body adopts before copy-out.
|
||||
export const isThenable = (value: Value): boolean =>
|
||||
value instanceof PromiseObj || (value instanceof Obj && typeofValue(get(value, "then")) === "function")
|
||||
// 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 => {
|
||||
|
|
@ -273,7 +292,7 @@ export const resolveProperty = (
|
|||
if (typeof objectValue === "string") {
|
||||
if (key === "length") return { value: objectValue.length }
|
||||
const index = typeof key === "symbol" ? undefined : parseArrayIndex(key)
|
||||
if (index !== undefined) return { value: objectValue[index] }
|
||||
if (index !== undefined && index < objectValue.length) return { value: objectValue[index] }
|
||||
}
|
||||
const proto = primitivePrototype(builtins, objectValue)
|
||||
if (proto !== undefined) return { target: proto, key, receiver: objectValue }
|
||||
|
|
@ -284,23 +303,28 @@ export const resolveProperty = (
|
|||
throw typeError("Cannot access a property on a non-object value.", objectNode)
|
||||
}
|
||||
|
||||
// One destructured property, read the way a member expression would read it (primitives use their prototype).
|
||||
export const destructuredProperty = (builtins: Builtins, source: Value, key: PropertyKey, node: AstNode): Value => {
|
||||
const reference = resolveProperty(builtins, source, key, node, node)
|
||||
if (reference instanceof HostNamespace) return reference
|
||||
if ("value" in reference) return reference.value
|
||||
return readProperty(reference.target, reference.key, node, reference.receiver)
|
||||
}
|
||||
|
||||
export const readReference = (reference: MemberReference, node: MemberExpression): Value => {
|
||||
// Reject unknown promise properties so a missing await cannot hide.
|
||||
/** 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.object,
|
||||
(node as Partial<MemberExpression>).object ?? node,
|
||||
)
|
||||
}
|
||||
return readProperty(reference.target, reference.key, node, reference.receiver)
|
||||
}
|
||||
|
||||
/** [[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.
|
||||
|
|
@ -334,19 +358,39 @@ export const writableReference = (
|
|||
return reference
|
||||
}
|
||||
|
||||
export const assignToReference = (target: Obj, key: PropertyKey, next: Value, node: AstNode): void => {
|
||||
const written = (() => {
|
||||
try {
|
||||
rejectCircularInsertion(
|
||||
target,
|
||||
next,
|
||||
target instanceof Arr ? "Array assignment result" : "Object assignment result",
|
||||
)
|
||||
return set(target, key, next)
|
||||
} catch (error) {
|
||||
throw locate(error, node)
|
||||
/** 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")
|
||||
}
|
||||
})()
|
||||
if (written) return
|
||||
throw typeError(`Cannot assign to read only property '${String(key)}'.`, node)
|
||||
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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -279,6 +279,7 @@ const promiseLikeMethods = <R>(ctx: Interpreter<R>) => {
|
|||
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(
|
||||
|
|
|
|||
|
|
@ -1,10 +1,22 @@
|
|||
import { invalidData } from "./model.js"
|
||||
import { Callable, getOwn, HostNamespace, isRuntimeReference, Obj, Opaque, ownKeys, type Value } from "./objects.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.
|
||||
// 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,
|
||||
|
|
@ -22,11 +34,10 @@ const find = (
|
|||
if (match(current)) return true
|
||||
if (!(current instanceof Obj) || skip(current) || seen.has(current)) continue
|
||||
seen.add(current)
|
||||
pending.push(
|
||||
ownKeys(current)
|
||||
.map((key) => getOwn(current, key))
|
||||
.values(),
|
||||
)
|
||||
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
|
||||
}
|
||||
|
|
@ -45,11 +56,14 @@ export const rejectCircularInsertion = (
|
|||
label: string,
|
||||
seen = new Set<object>(),
|
||||
): void => {
|
||||
if (find(value, (current) => current === container, isRuntimeReference, seen)) {
|
||||
throw invalidData(`${label} contains a circular value.`)
|
||||
}
|
||||
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
|
||||
|
|
|
|||
|
|
@ -53,6 +53,14 @@ export class Convert {
|
|||
) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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>
|
||||
|
||||
|
|
|
|||
|
|
@ -66,6 +66,7 @@ export type Reaction =
|
|||
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
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import packageJson from "../../package.json" with { type: "json" }
|
||||
import type { Interruption } from "./runtime/signals.js"
|
||||
import { staticNames, unchanged } from "./runtime/intrinsic-names.js"
|
||||
import { Fn, Obj } from "./runtime/objects.js"
|
||||
import { Arr, 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"
|
||||
|
|
@ -50,7 +50,7 @@ const vmSpecs = (): ReadonlyArray<ClassSpec> =>
|
|||
ctor: Vm,
|
||||
anchor: "vm",
|
||||
fields: ["frames", "templates", "scheduler", "hosts", "depth", "sliced", "outcome"],
|
||||
skip: ["ctx", "pool", "sourceCodes", "intrinsics", "fuel", "sliceStart", "tripEvery"],
|
||||
skip: ["ctx", "pool", "sourceCodes", "intrinsics", "fuel", "sliceStart", "tripEvery", "redo"],
|
||||
reset: restoreStack,
|
||||
},
|
||||
{
|
||||
|
|
@ -302,6 +302,11 @@ function restoreFrame(frame: Frame): void {
|
|||
invalid("a frame's mode does not fit its code.")
|
||||
const settles = frame.mode !== Mode.CALLER && frame.mode !== Mode.PROGRAM && frame.mode !== Mode.BOUNDARY_OUT
|
||||
if (!settles && frame.target !== undefined) 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.")
|
||||
|
|
@ -318,8 +323,15 @@ function restoreStack(vm: Vm): void {
|
|||
invalid("the job stack is not frames.")
|
||||
vm.frames.forEach((frame, at) => {
|
||||
const bottomOnly = frame.mode === Mode.PROGRAM || frame.mode === Mode.BOUNDARY_OUT
|
||||
if ((at === 0 && frame.mode === Mode.CALLER) || (at > 0 && bottomOnly))
|
||||
invalid("a frame is out of place on the job stack.")
|
||||
const above = frame.mode === Mode.CALLER || frame.mode === Mode.REDO
|
||||
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.")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,9 +11,15 @@ import {
|
|||
Throw,
|
||||
} from "../runtime/model.js"
|
||||
import {
|
||||
accessorFunction,
|
||||
accessorHalf,
|
||||
Arguments,
|
||||
Arr,
|
||||
BoundFn,
|
||||
Callable,
|
||||
type Getter,
|
||||
isProgramAccessor,
|
||||
type Setter,
|
||||
Bytes,
|
||||
changed,
|
||||
DateObj,
|
||||
|
|
@ -37,7 +43,7 @@ import {
|
|||
WeakMapObj,
|
||||
WeakSetObj,
|
||||
} from "../runtime/objects.js"
|
||||
import { Convert, Interruption, Invoke } from "../runtime/signals.js"
|
||||
import { Convert, Interruption, Invoke, Prefetch } from "../runtime/signals.js"
|
||||
import { deleted, OrderedTable } from "../runtime/table.js"
|
||||
import { AsyncFromSyncIterator } from "../generators.js"
|
||||
import { HostCall, Resolving } from "../scheduler.js"
|
||||
|
|
@ -315,6 +321,7 @@ const builtinSpecs = (): ReadonlyArray<ClassSpec> => [
|
|||
{ name: "Throw", ctor: Throw, fields: ["value"] },
|
||||
{ name: "PendingThrow", ctor: PendingThrow, fields: ["type", "message", "kind", "suggestions", "node", "value"] },
|
||||
{ name: "Convert", ctor: Convert, fields: ["hints", "values", "ordinal", "coerce"] },
|
||||
{ name: "Prefetch", ctor: Prefetch, fields: ["reads"] },
|
||||
{ name: "Invoke", ctor: Invoke, fields: ["callable", "thisValue", "args", "site"] },
|
||||
{ name: "HostNamespace", ctor: HostNamespace, fields: ["root", "path"] },
|
||||
{ name: "Lost", ctor: Lost, fields: ["description"] },
|
||||
|
|
@ -571,7 +578,7 @@ class Encoder {
|
|||
for (const key of Object.keys(object)) {
|
||||
if (fields.includes(key) || spec.skip?.includes(key) || (spec.constants !== undefined && key in spec.constants))
|
||||
continue
|
||||
if (spec.obj && (objFields.includes(key) || key === "tag")) continue
|
||||
if (spec.obj && (objFields.includes(key) || key === "tag" || key === "hasProgramAccessors")) continue
|
||||
throw new SnapshotError(`Codec gap: ${spec.name}.${key} is not saved.`)
|
||||
}
|
||||
}
|
||||
|
|
@ -588,11 +595,26 @@ class Encoder {
|
|||
this.value(slot.value),
|
||||
(slot.writable ? 1 : 0) | (slot.enumerable ? 2 : 0) | (slot.configurable ? 4 : 0),
|
||||
)
|
||||
} else props.push(null, 8 | (slot.enumerable ? 2 : 0) | (slot.configurable ? 4 : 0))
|
||||
} else {
|
||||
props.push(
|
||||
[this.accessorHalf(slot.get, key), this.accessorHalf(slot.set, key)],
|
||||
8 | (slot.enumerable ? 2 : 0) | (slot.configurable ? 4 : 0),
|
||||
)
|
||||
}
|
||||
}
|
||||
return { f: values, p: object.proto === null ? null : this.value(object.proto), x: object.extensible, o: props }
|
||||
}
|
||||
|
||||
// An accessor half: a program function as itself, a native one as its companion (a named intrinsic).
|
||||
private accessorHalf(half: Getter | Setter | Callable | undefined, key: string | symbol): Encoded {
|
||||
const fn = accessorFunction(half)
|
||||
if (half !== undefined && fn === undefined) {
|
||||
this.lose(`the native accessor ${String(key)}`)
|
||||
return this.value(undefined)
|
||||
}
|
||||
return this.value(fn)
|
||||
}
|
||||
|
||||
private error(error: Error): Record {
|
||||
const name = errorNames.get(error.constructor)
|
||||
if (name === undefined) {
|
||||
|
|
@ -919,7 +941,7 @@ class Decoder {
|
|||
return root
|
||||
}
|
||||
|
||||
// An object's prototype, extensibility, and properties. A named object's accessors stay the ones it was made with.
|
||||
// An object's prototype, extensibility, and properties. A native accessor half comes back as its companion's closure.
|
||||
private fillObj(target: Obj, record: { readonly [field: string]: unknown }): void {
|
||||
const proto = record.p === null ? null : this.value(record.p)
|
||||
if (proto !== null && !(proto instanceof Obj)) invalid("a prototype is not an object.")
|
||||
|
|
@ -934,10 +956,19 @@ class Decoder {
|
|||
const enumerable = (flags & 2) !== 0
|
||||
const configurable = (flags & 4) !== 0
|
||||
if ((flags & 8) !== 0) {
|
||||
const original = target.props?.get(key as string | symbol)
|
||||
if (original === undefined || "value" in original) invalid(`the accessor ${String(key)} has no original.`)
|
||||
const accessor = original as Extract<Slot, { get: unknown }>
|
||||
props.set(key as string | symbol, { get: accessor.get, set: accessor.set, enumerable, configurable })
|
||||
const halves = list(entries[at + 1], "an accessor's halves")
|
||||
if (halves.length !== 2) invalid(`the accessor ${String(key)} does not have two halves.`)
|
||||
const half = (data: unknown) => {
|
||||
const fn = this.value(data)
|
||||
if (fn !== undefined && !(fn instanceof Callable)) invalid(`the accessor ${String(key)} is not a function.`)
|
||||
return accessorHalf(fn as Callable | undefined)
|
||||
}
|
||||
props.set(key as string | symbol, {
|
||||
get: half(halves[0]) as Getter | Callable | undefined,
|
||||
set: half(halves[1]) as Setter | Callable | undefined,
|
||||
enumerable,
|
||||
configurable,
|
||||
})
|
||||
continue
|
||||
}
|
||||
props.set(key as string | symbol, {
|
||||
|
|
@ -952,9 +983,11 @@ class Decoder {
|
|||
proto: Obj | null
|
||||
extensible: boolean
|
||||
intrinsic: number
|
||||
hasProgramAccessors: boolean
|
||||
}
|
||||
writable.intrinsic ??= 0
|
||||
writable.props = props
|
||||
writable.hasProgramAccessors = [...props.values()].some(isProgramAccessor)
|
||||
writable.extensible = record.x as boolean
|
||||
writable.proto = proto as Obj | null
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ import {
|
|||
type Value,
|
||||
} from "../runtime/objects.js"
|
||||
import { describeValue, rejectCircularInsertion } from "../runtime/references.js"
|
||||
import { requireCallback, withPrimitives } from "../runtime/callback.js"
|
||||
import { requireCallback, withPrimitives, readsPending, withReads } from "../runtime/callback.js"
|
||||
import type { Interpreter } from "../runtime/interpreter.js"
|
||||
import { compareText } from "../runtime/operations.js"
|
||||
|
||||
|
|
@ -42,12 +42,16 @@ const iterable = (builtins: Builtins, value: Value) => {
|
|||
return method !== undefined && method !== null
|
||||
}
|
||||
|
||||
const arrayFrom = <R>(ctx: Interpreter<R>, args: Array<Value>): Value | Invoke => {
|
||||
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)}.`)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { 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"
|
||||
|
|
@ -149,7 +150,10 @@ export const bufferGlobal = <R>(ctx: Interpreter<R>) => {
|
|||
if (value instanceof Arr) return Uint8Array.from(value.items, coerceToNumber)
|
||||
if (value instanceof Obj) {
|
||||
const data = get(value, "data")
|
||||
if (get(value, "type") === "Buffer" && data instanceof Arr) return Uint8Array.from(data.items, coerceToNumber)
|
||||
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))))
|
||||
|
|
@ -171,12 +175,12 @@ export const bufferGlobal = <R>(ctx: Interpreter<R>) => {
|
|||
const buffer = constructor(builtins, proto, {
|
||||
name: "Buffer",
|
||||
length: 2,
|
||||
call: (_, args) => wrap(bytesFrom(args[0], args[1], args[2])),
|
||||
call: (_, args) => withReads(() => wrap(bytesFrom(args[0], args[1], args[2]))),
|
||||
construct: (args, newTarget) =>
|
||||
new BufferObj(prototypeFrom(newTarget, proto), bytesFrom(args[0], args[1], args[2])),
|
||||
withReads(() => new BufferObj(prototypeFrom(newTarget, proto), bytesFrom(args[0], args[1], args[2]))),
|
||||
})
|
||||
methods(builtins, buffer, [
|
||||
["from", 3, (_, args) => wrap(bytesFrom(args[0], args[1], args[2]))],
|
||||
["from", 3, (_, args) => withReads(() => wrap(bytesFrom(args[0], args[1], args[2])))],
|
||||
[
|
||||
"alloc",
|
||||
3,
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ import {
|
|||
type Value,
|
||||
} from "../runtime/objects.js"
|
||||
import { describeValue } from "../runtime/references.js"
|
||||
import { requireCallback } from "../runtime/callback.js"
|
||||
import { requireCallback, readsPending, withReads } from "../runtime/callback.js"
|
||||
import type { Interpreter } from "../runtime/interpreter.js"
|
||||
import { sortArray } from "./array.js"
|
||||
|
||||
|
|
@ -289,8 +289,10 @@ export const textDecoderGlobal = <R>(ctx: Interpreter<R>) => {
|
|||
if (options !== undefined && typeof options !== "object") {
|
||||
throw typeError("TextDecoder.decode expects an options object.")
|
||||
}
|
||||
const stream = options instanceof Obj && Boolean(get(options, "stream"))
|
||||
return decoder.decode(args[0]?.bytes ?? empty, stream)
|
||||
return withReads(() => {
|
||||
const stream = options instanceof Obj && Boolean(get(options, "stream"))
|
||||
return readsPending() ? undefined : decoder.decode((args[0] as Bytes | undefined)?.bytes ?? empty, stream)
|
||||
})
|
||||
},
|
||||
],
|
||||
])
|
||||
|
|
@ -302,10 +304,13 @@ export const textDecoderGlobal = <R>(ctx: Interpreter<R>) => {
|
|||
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 new TextDecoderObj(
|
||||
prototypeFrom(newTarget, proto),
|
||||
new TextDecoder("utf-8", { fatal: flag("fatal"), ignoreBOM: true }),
|
||||
flag("ignoreBOM"),
|
||||
return withReads(
|
||||
() =>
|
||||
new TextDecoderObj(
|
||||
prototypeFrom(newTarget, proto),
|
||||
new TextDecoder("utf-8", { fatal: flag("fatal"), ignoreBOM: true }),
|
||||
flag("ignoreBOM"),
|
||||
),
|
||||
)
|
||||
},
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,5 +1,15 @@
|
|||
import { type Method, methods } from "../runtime/native.js"
|
||||
import { entries, get, Arr, HostNamespace, Obj, type Value } from "../runtime/objects.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"
|
||||
|
||||
|
|
@ -77,19 +87,26 @@ const consoleTableRows = (
|
|||
return data.items.map((item, index) => ({ index: String(index), values: consoleTableValues(item, columns) }))
|
||||
}
|
||||
if (data instanceof Obj) {
|
||||
return entries(data).map(([index, item]) => ({ index, values: consoleTableValues(item, columns) }))
|
||||
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, get(value, column)]))
|
||||
return Object.fromEntries(entries(value))
|
||||
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
|
||||
|
|
|
|||
|
|
@ -18,10 +18,21 @@ import {
|
|||
set,
|
||||
coerceToString,
|
||||
type Value,
|
||||
accessorFunction,
|
||||
Callable,
|
||||
define,
|
||||
defineOwnProperty,
|
||||
type Descriptor,
|
||||
get,
|
||||
has,
|
||||
parseArrayIndex,
|
||||
record,
|
||||
type Slot,
|
||||
} from "../runtime/objects.js"
|
||||
import { primitivePrototype } from "../runtime/intrinsics.js"
|
||||
import { type Builtins, primitivePrototype } from "../runtime/intrinsics.js"
|
||||
import { describeValue, rejectCircularInsertion } from "../runtime/references.js"
|
||||
import { invokeMethod } from "../runtime/callback.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.
|
||||
|
|
@ -43,19 +54,30 @@ export const enumerableSource = <R>(ctx: Interpreter<R>, label: string, value: V
|
|||
return new Obj(ctx.builtins.Object)
|
||||
}
|
||||
|
||||
export const objectAssign = <R>(ctx: Interpreter<R>, args: Array<Value>): Value => {
|
||||
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 source of args.slice(1)) {
|
||||
if (source === null || source === undefined) continue
|
||||
const from = enumerableSource(ctx, "Object.assign(...)", source)
|
||||
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))) {
|
||||
if (set(target, key, getOwn(from, key)) !== true) {
|
||||
throw typeError(`Cannot assign to read only property '${String(key)}'.`)
|
||||
}
|
||||
}
|
||||
|
|
@ -63,6 +85,13 @@ export const objectAssign = <R>(ctx: Interpreter<R>, args: Array<Value>): Value
|
|||
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"
|
||||
|
|
@ -105,6 +134,96 @@ const integrity = (value: Value, frozen: boolean): boolean => {
|
|||
})
|
||||
}
|
||||
|
||||
// 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>) => {
|
||||
|
|
@ -136,20 +255,28 @@ export const objectGlobal = <R>(ctx: Interpreter<R>) => {
|
|||
[
|
||||
"values",
|
||||
1,
|
||||
(_, args) =>
|
||||
new Arr(
|
||||
(_, 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(enumerableSource(ctx, "Object.values(...)", args[0])).map((entry) => entry[1]),
|
||||
),
|
||||
entries(source).map((entry) => entry[1]),
|
||||
)
|
||||
},
|
||||
],
|
||||
[
|
||||
"entries",
|
||||
1,
|
||||
(_, args) =>
|
||||
new Arr(
|
||||
(_, 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(enumerableSource(ctx, "Object.entries(...)", args[0])).map((entry) => new Arr(builtins.Array, entry)),
|
||||
),
|
||||
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])],
|
||||
|
|
@ -176,15 +303,72 @@ export const objectGlobal = <R>(ctx: Interpreter<R>) => {
|
|||
"create",
|
||||
2,
|
||||
(_, args) => {
|
||||
if (args[0] !== null && !(args[0] instanceof Obj)) {
|
||||
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) {
|
||||
throw typeError(
|
||||
"Object.create property descriptors are not supported; assign the fields after creating the object.",
|
||||
)
|
||||
}
|
||||
return new Obj(args[0])
|
||||
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)
|
||||
},
|
||||
],
|
||||
])
|
||||
|
|
@ -210,7 +394,8 @@ export const objectGlobal = <R>(ctx: Interpreter<R>) => {
|
|||
[
|
||||
"toLocaleString",
|
||||
0,
|
||||
(thisValue) => invokeMethod(ctx.builtins, thisValue, "toString", "Object.prototype.toLocaleString"),
|
||||
(thisValue) =>
|
||||
withReads(() => invokeMethod(ctx.builtins, thisValue, "toString", "Object.prototype.toLocaleString")),
|
||||
],
|
||||
[
|
||||
"valueOf",
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ import {
|
|||
type Value,
|
||||
} from "../runtime/objects.js"
|
||||
import { containsOpaqueReference, typeofValue } from "../runtime/references.js"
|
||||
import { isSupportedCallback, requireCallback, withPrimitives } from "../runtime/callback.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"
|
||||
|
|
@ -85,7 +85,12 @@ const replaceWithCallback = <R>(
|
|||
)
|
||||
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)
|
||||
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> }
|
||||
|
|
@ -108,27 +113,28 @@ export const stringGlobal = <R>(ctx: Interpreter<R>) => {
|
|||
[
|
||||
"raw",
|
||||
1,
|
||||
(_, args) => {
|
||||
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,
|
||||
)
|
||||
},
|
||||
(_, 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,
|
||||
)
|
||||
}),
|
||||
],
|
||||
])
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { fn, methods } from "../runtime/native.js"
|
||||
import { withReads } from "../runtime/callback.js"
|
||||
import { typeError } from "../runtime/model.js"
|
||||
import {
|
||||
define,
|
||||
|
|
@ -95,7 +96,10 @@ export const structuredCloneGlobal = <R>(ctx: Interpreter<R>) =>
|
|||
for (const [key, item] of entries(value)) define(copy, key, clone(item))
|
||||
return copy
|
||||
}
|
||||
return clone(args[0])
|
||||
return withReads(() => {
|
||||
memo.clear()
|
||||
return clone(args[0])
|
||||
})
|
||||
})
|
||||
|
||||
export const cryptoGlobal = <R>(ctx: Interpreter<R>) => {
|
||||
|
|
|
|||
|
|
@ -19,10 +19,14 @@ import {
|
|||
import {
|
||||
Arguments,
|
||||
Arr,
|
||||
assign,
|
||||
BoundFn,
|
||||
Builtin,
|
||||
type Callable,
|
||||
copyDataProperties,
|
||||
defineAccessorHalf,
|
||||
peek,
|
||||
GetterCall,
|
||||
lookup,
|
||||
coerceToNumber,
|
||||
coerceToString,
|
||||
define,
|
||||
|
|
@ -44,10 +48,11 @@ import {
|
|||
type Value,
|
||||
} from "./runtime/objects.js"
|
||||
import {
|
||||
accessProperty,
|
||||
applyBinaryOperator,
|
||||
assignToReference,
|
||||
builtinCursor,
|
||||
destructuredProperty,
|
||||
failedAssignment,
|
||||
forInKeys,
|
||||
instanceofValue,
|
||||
isThenable,
|
||||
|
|
@ -55,11 +60,10 @@ import {
|
|||
notConstructible,
|
||||
operatorConversion,
|
||||
propertyKey,
|
||||
readProperty,
|
||||
readReference,
|
||||
requireIteratorMethod,
|
||||
requireIteratorObject,
|
||||
requireMemberBase,
|
||||
requirePromiseProperty,
|
||||
resolveProperty,
|
||||
writableReference,
|
||||
} from "./runtime/operations.js"
|
||||
|
|
@ -70,6 +74,7 @@ import {
|
|||
type Completion,
|
||||
Convert,
|
||||
type GeneratorRequest,
|
||||
Prefetch,
|
||||
Interruption,
|
||||
Invoke,
|
||||
MAX_CALL_DEPTH,
|
||||
|
|
@ -152,6 +157,11 @@ export const Mode = {
|
|||
REJECT_ONLY: 4,
|
||||
PROGRAM: 5,
|
||||
BOUNDARY_OUT: 6,
|
||||
/**
|
||||
* Runs a program getter an iterator op met (`$vmRedo`), then runs the op again from its first word: its `target` is
|
||||
* `[pc, ...values the op had read]`, and the op replays those and the getter's value in order (see `redoRead`).
|
||||
*/
|
||||
REDO: 7,
|
||||
} as const
|
||||
|
||||
export type FrameMode = (typeof Mode)[keyof typeof Mode]
|
||||
|
|
@ -245,6 +255,13 @@ export class Vm {
|
|||
outcome: Completion | undefined = undefined
|
||||
/** Round-trip test mode (task C): slice after this many fuel ticks, so the run is saved and restored all through. */
|
||||
tripEvery = 0
|
||||
/**
|
||||
* The reads an iterator op replays while it runs again after a getter (`Mode.REDO`). It never outlives the
|
||||
* `exec` turn the getter returned in, so it is never saved.
|
||||
*/
|
||||
redo:
|
||||
| { readonly frame: Frame; readonly pc: number; readonly values: ReadonlyArray<Value>; next: number }
|
||||
| undefined = undefined
|
||||
|
||||
constructor(readonly ctx: Interpreter<unknown>) {
|
||||
this.scheduler = new VmScheduler(this)
|
||||
|
|
@ -703,6 +720,10 @@ export class Vm {
|
|||
frame.pc = pc
|
||||
frame.sp = sp
|
||||
sp = this.execGetProp(frame, o, key, mode, pc, sp)
|
||||
if (sp < 0) {
|
||||
if (sp === GETTER_ENTERED) continue outer
|
||||
return sp === GETTER_FUEL ? 1 : 2
|
||||
}
|
||||
pc++
|
||||
continue
|
||||
}
|
||||
|
|
@ -726,8 +747,11 @@ export class Vm {
|
|||
}
|
||||
frame.pc = pc
|
||||
frame.sp = sp
|
||||
if (this.execGetElem(frame, o, keyVal, mode, pc, sp)) continue outer
|
||||
sp = frame.sp
|
||||
sp = this.execGetElem(frame, o, keyVal, mode, pc, sp)
|
||||
if (sp < 0) {
|
||||
if (sp === GETTER_ENTERED) continue outer
|
||||
return sp === GETTER_FUEL ? 1 : 2
|
||||
}
|
||||
pc++
|
||||
continue
|
||||
}
|
||||
|
|
@ -737,7 +761,7 @@ export class Vm {
|
|||
const o = regs[sp - 1] as Value
|
||||
frame.pc = pc
|
||||
frame.sp = sp
|
||||
this.execPutProp(fcode, o, consts[w >>> 16] as string, v, pc)
|
||||
if (this.execPutProp(frame, o, consts[w >>> 16] as string, v, pc, sp)) continue outer
|
||||
regs[sp - 1] = v
|
||||
pc++
|
||||
continue
|
||||
|
|
@ -757,14 +781,15 @@ export class Vm {
|
|||
o.extensible
|
||||
) {
|
||||
const items = o.items
|
||||
if (keyVal < items.length) {
|
||||
// A hole or a new element looks at the prototypes first, which may hold a program setter there.
|
||||
if (keyVal < items.length && (keyVal in items || this.plainArrayChain(o))) {
|
||||
if (keyVal === 0) items[0] = ""
|
||||
items[keyVal] = v
|
||||
regs[sp - 1] = v
|
||||
pc++
|
||||
continue
|
||||
}
|
||||
if (keyVal === items.length && keyVal < 10_000_000) {
|
||||
if (keyVal === items.length && keyVal < 10_000_000 && this.plainArrayChain(o)) {
|
||||
items.push(v)
|
||||
regs[sp - 1] = v
|
||||
pc++
|
||||
|
|
@ -773,7 +798,7 @@ export class Vm {
|
|||
}
|
||||
frame.pc = pc
|
||||
frame.sp = sp
|
||||
this.execPutElem(fcode, o, keyVal, v, pc)
|
||||
if (this.execPutProp(frame, o, propertyKey(keyVal), v, pc, sp)) continue outer
|
||||
regs[sp - 1] = v
|
||||
pc++
|
||||
continue
|
||||
|
|
@ -830,7 +855,7 @@ export class Vm {
|
|||
const rhs = regs[--sp] as Value
|
||||
frame.pc = pc
|
||||
frame.sp = sp
|
||||
regs[sp - 1] = this.execInstanceof(fcode, regs[sp - 1] as Value, rhs, pc)
|
||||
if (this.execInstanceof(frame, regs[sp - 1] as Value, rhs, pc, sp)) continue outer
|
||||
pc++
|
||||
continue
|
||||
}
|
||||
|
|
@ -855,13 +880,14 @@ export class Vm {
|
|||
case 39: // Op.COPY_DATA_PROPS
|
||||
frame.pc = pc
|
||||
frame.sp = --sp
|
||||
this.execCopyDataProps(fcode, regs[sp - 1] as Obj, regs[sp] as Value, pc)
|
||||
if (this.execCopyDataProps(frame, regs[sp - 1] as Obj, regs[sp] as Value, pc, sp)) continue outer
|
||||
pc++
|
||||
continue
|
||||
case 40: // Op.COPY_REST
|
||||
frame.pc = pc
|
||||
frame.sp = sp
|
||||
sp = this.execCopyRest(fcode, regs, w >>> 16, pc, sp)
|
||||
sp = this.execCopyRest(frame, regs, w >>> 16, pc, sp)
|
||||
if (sp < 0) continue outer
|
||||
pc++
|
||||
continue
|
||||
case 41: // Op.TEMPLATE
|
||||
|
|
@ -1271,12 +1297,13 @@ export class Vm {
|
|||
frame.pc = pc
|
||||
frame.sp = sp
|
||||
pc = this.execIterOpen(frame, (w >>> 8) & 0xff, pc, sp)
|
||||
if (pc < 0) continue outer
|
||||
sp = frame.sp
|
||||
continue
|
||||
case 75: // Op.ITER_INIT
|
||||
frame.pc = pc
|
||||
frame.sp = sp
|
||||
this.execIterInit(frame, (w >>> 8) & 0xff, pc, sp)
|
||||
if (this.execIterInit(frame, (w >>> 8) & 0xff, pc, sp)) continue outer
|
||||
pc++
|
||||
continue
|
||||
case 76: {
|
||||
|
|
@ -1299,10 +1326,12 @@ export class Vm {
|
|||
}
|
||||
case 77: // Op.ITER_RESULT
|
||||
pc = this.execIterResult(frame, (w >>> 8) & 0xff, w >>> 16, pc, sp)
|
||||
if (pc < 0) continue outer
|
||||
sp = frame.sp
|
||||
continue
|
||||
case 78: // Op.ITER_CLOSE
|
||||
pc = this.execIterClose(frame, (w >>> 8) & 0xff, w >>> 16, pc, sp)
|
||||
if (pc < 0) continue outer
|
||||
sp = frame.sp
|
||||
continue
|
||||
case 79: // Op.ITER_APPEND_ALL
|
||||
|
|
@ -1338,14 +1367,20 @@ export class Vm {
|
|||
frame.pc = pc
|
||||
frame.sp = sp
|
||||
pc = this.onYstar(frame, (w >>> 8) & 0xff, w >>> 16, pc, sp)
|
||||
if (pc < 0) continue outer
|
||||
sp = frame.sp
|
||||
continue
|
||||
case 86: // Op.YSTAR_RESULT
|
||||
frame.pc = pc
|
||||
frame.sp = sp
|
||||
pc = this.onYstarResult(frame, (w >>> 8) & 0xff, w >>> 16, pc, sp)
|
||||
if (pc < 0) continue outer
|
||||
sp = frame.sp
|
||||
continue
|
||||
case 88: // Op.DEFINE_ACCESSOR
|
||||
sp = this.execDefineAccessor(regs, consts, (w >>> 8) & 0xff, w >>> 16, sp)
|
||||
pc++
|
||||
continue
|
||||
default:
|
||||
this.failOpcode(w & 0xff)
|
||||
}
|
||||
|
|
@ -1367,8 +1402,25 @@ export class Vm {
|
|||
checkStringLength(len)
|
||||
}
|
||||
|
||||
private execInstanceof(fcode: Code, lhs: Value, rhs: Value, pc: number): boolean {
|
||||
return instanceofValue(lhs, rhs, fcode.siteAt(pc)!)
|
||||
// `lhs instanceof rhs` into the stack at `sp - 1`; true when a program `prototype` getter runs first.
|
||||
private execInstanceof(frame: Frame, lhs: Value, rhs: Value, pc: number, sp: number): boolean {
|
||||
const site = frame.code.siteAt(pc)!
|
||||
const result = instanceofValue(lhs, rhs, site)
|
||||
if (!(result instanceof GetterCall)) {
|
||||
frame.regs[sp - 1] = result
|
||||
return false
|
||||
}
|
||||
frame.sp = sp - 1
|
||||
this.pushInternalCall("$vmInstanceof", [lhs, rhs], site)
|
||||
return true
|
||||
}
|
||||
|
||||
// Whether an array's chain is the built-in one with no program accessors, so a hole or append can skip it.
|
||||
private plainArrayChain(o: Arr): boolean {
|
||||
const proto = o.proto
|
||||
return (
|
||||
proto === this.ctx.builtins.Array && !proto.hasProgramAccessors && !this.ctx.builtins.Object.hasProgramAccessors
|
||||
)
|
||||
}
|
||||
|
||||
private execBinopSlow(frame: Frame, sub: number, a: Value, b: Value, pc: number, sp: number): boolean {
|
||||
|
|
@ -1402,11 +1454,11 @@ export class Vm {
|
|||
}
|
||||
|
||||
private onYstar(frame: Frame, slot: number, bx: number, pc: number, sp: number): number {
|
||||
return execYstar(frame, slot, bx, pc, sp)
|
||||
return execYstar(this, frame, slot, bx, pc, sp)
|
||||
}
|
||||
|
||||
private onYstarResult(frame: Frame, slot: number, bx: number, pc: number, sp: number): number {
|
||||
return execYstarResult(frame, slot, bx, pc, sp)
|
||||
return execYstarResult(this, frame, slot, bx, pc, sp)
|
||||
}
|
||||
|
||||
private failOpcode(op: number): never {
|
||||
|
|
@ -1453,7 +1505,11 @@ export class Vm {
|
|||
}
|
||||
|
||||
private execArgs(frame: Frame, kind: number, bx: number): unknown {
|
||||
if (kind === 0) return new Arguments(this.ctx.builtins.Object, frame.args ?? [])
|
||||
if (kind === 0) {
|
||||
const made = new Arguments(this.ctx.builtins.Object, frame.args ?? [])
|
||||
define(made, IteratorSymbol, this.ctx.prelude.fn("argumentsValues"), hidden)
|
||||
return made
|
||||
}
|
||||
if (kind === 1) return new Arr(this.ctx.builtins.Array, (frame.args ?? []).slice(bx))
|
||||
if (kind === 2) return frame.fn
|
||||
if (kind === 3) return frame.thisValue
|
||||
|
|
@ -1480,7 +1536,8 @@ export class Vm {
|
|||
: key === AsyncIteratorSymbol
|
||||
? "[Symbol.asyncIterator]"
|
||||
: String(key)
|
||||
define(fn, "name", name, readonly)
|
||||
// Modes 2 and 3 name an accessor's function: `get x`, `set x`.
|
||||
define(fn, "name", mode === 2 ? `get ${name}` : mode === 3 ? `set ${name}` : name, readonly)
|
||||
}
|
||||
|
||||
private execToKey(frame: Frame, v: Value, pc: number, sp: number): boolean {
|
||||
|
|
@ -1543,22 +1600,50 @@ export class Vm {
|
|||
return sp
|
||||
}
|
||||
|
||||
private execCopyDataProps(fcode: Code, o: Obj, src: Value, pc: number): void {
|
||||
if (src !== null && src !== undefined) {
|
||||
assign(o, enumerableSource(this.ctx, "Object spread", src, fcode.siteAt(pc)!))
|
||||
}
|
||||
// An object literal's getter or setter: `[o, fn]`, or `[o, key, fn]` computed, leaves `[o]`.
|
||||
private execDefineAccessor(
|
||||
regs: Array<unknown>,
|
||||
consts: ReadonlyArray<ConstValue>,
|
||||
a: number,
|
||||
bx: number,
|
||||
sp: number,
|
||||
): number {
|
||||
const fn = regs[--sp] as Fn
|
||||
const key = (a & 1) !== 0 ? (regs[--sp] as PropertyKey) : (consts[bx] as string)
|
||||
defineAccessorHalf(regs[sp - 1] as Obj, key, (a & 2) !== 0 ? "set" : "get", fn)
|
||||
return sp
|
||||
}
|
||||
|
||||
private execCopyRest(fcode: Code, regs: Array<unknown>, n: number, pc: number, sp: number): number {
|
||||
// `{ ...src }` into `o` (at `sp - 1`, `src` popped): true when a source with program getters is copied in the prelude.
|
||||
private execCopyDataProps(frame: Frame, o: Obj, src: Value, pc: number, sp: number): boolean {
|
||||
if (src === null || src === undefined) return false
|
||||
const source = enumerableSource(this.ctx, "Object spread", src, frame.code.siteAt(pc)!)
|
||||
if (!source.hasProgramAccessors) {
|
||||
copyDataProperties(o, source)
|
||||
return false
|
||||
}
|
||||
frame.sp = sp - 1
|
||||
this.pushInternalCall("$vmCopyDataProps", [o, source, undefined], callSiteOf(frame, pc))
|
||||
return true
|
||||
}
|
||||
|
||||
// `{ ...rest } = src`, less the `n` keys on the stack: the new sp, or -1 when the copy runs in the prelude.
|
||||
private execCopyRest(frame: Frame, regs: Array<unknown>, n: number, pc: number, sp: number): number {
|
||||
const consumed = new Set<PropertyKey>()
|
||||
for (let i = sp - n; i < sp; i++) {
|
||||
const k = regs[i] as PropertyKey
|
||||
consumed.add(typeof k === "symbol" ? k : String(k))
|
||||
}
|
||||
sp -= n
|
||||
const src = regs[sp - 1] as Value
|
||||
const rest = new Obj(this.ctx.builtins.Object)
|
||||
assign(rest, enumerableSource(this.ctx, "Object destructuring", src, fcode.siteAt(pc)!), consumed)
|
||||
const source = enumerableSource(this.ctx, "Object destructuring", regs[sp - 1] as Value, frame.code.siteAt(pc)!)
|
||||
if (source.hasProgramAccessors) {
|
||||
frame.sp = sp - 1
|
||||
const excluded = new Arr(this.ctx.builtins.Array, [...consumed] as Array<Value>)
|
||||
this.pushInternalCall("$vmCopyDataProps", [rest, source, excluded], callSiteOf(frame, pc))
|
||||
return -1
|
||||
}
|
||||
copyDataProperties(rest, source, consumed)
|
||||
regs[sp - 1] = rest
|
||||
return sp
|
||||
}
|
||||
|
|
@ -1695,6 +1780,15 @@ export class Vm {
|
|||
frame.sp = sp
|
||||
return this.finishProgram(frame, v)
|
||||
}
|
||||
if (frame.mode === Mode.REDO) {
|
||||
frames.pop()
|
||||
const saved = (frame.target as Arr).items
|
||||
const caller = frames[frames.length - 1]!
|
||||
caller.pc = saved[0] as number
|
||||
this.redo = { frame: caller, pc: caller.pc, values: [...saved.slice(1), v], next: 0 }
|
||||
this.release(frame)
|
||||
return true
|
||||
}
|
||||
frames.pop()
|
||||
this.release(frame)
|
||||
return true
|
||||
|
|
@ -1765,33 +1859,40 @@ export class Vm {
|
|||
return false
|
||||
}
|
||||
|
||||
// Returns the next pc, or REDO_ENTERED (here and in the other ops that read through `redoRead`).
|
||||
private execIterResult(frame: Frame, slot: number, bx: number, pc: number, sp: number): number {
|
||||
const regs = frame.regs
|
||||
const res = regs[--sp] as Value
|
||||
const res = regs[sp - 1] as Value
|
||||
frame.pc = pc
|
||||
frame.sp = sp
|
||||
frame.sp = sp - 1
|
||||
if (!(res instanceof Obj)) {
|
||||
throw typeError("Iterator next() result must be an object.", frame.code.siteAt(pc))
|
||||
}
|
||||
const done = Boolean(this.readObjProp(res, "done", frame.code, pc))
|
||||
const reads: Array<Value> = []
|
||||
const done = this.redoRead(frame, res, "done", res, pc, sp, reads)
|
||||
if (done === REDO) return REDO_ENTERED
|
||||
if (done) return bx
|
||||
;(regs[slot] as CustomIter).done = false
|
||||
regs[sp] = this.readObjProp(res, "value", frame.code, pc)
|
||||
frame.sp = sp + 1
|
||||
const value = this.redoRead(frame, res, "value", res, pc, sp, reads)
|
||||
if (value === REDO) return REDO_ENTERED
|
||||
regs[sp - 1] = value
|
||||
frame.sp = sp
|
||||
return pc + 1
|
||||
}
|
||||
|
||||
private execIterClose(frame: Frame, slot: number, bx: number, pc: number, sp: number): number {
|
||||
const regs = frame.regs
|
||||
const rec = regs[slot]
|
||||
if (!(rec instanceof CustomIter) || rec.done) {
|
||||
// Running again after a `return` getter, the record is already closed.
|
||||
if (!(rec instanceof CustomIter) || (rec.done && !this.replaying(frame, pc))) {
|
||||
frame.sp = sp
|
||||
return bx
|
||||
}
|
||||
frame.pc = pc
|
||||
frame.sp = sp
|
||||
rec.done = true
|
||||
const ret = this.readObjProp(rec.iterator, "return", frame.code, pc)
|
||||
const ret = this.redoRead(frame, rec.iterator, "return", rec.iterator, pc, sp, [])
|
||||
if (ret === REDO) return REDO_ENTERED
|
||||
if (ret === undefined || ret === null) return bx
|
||||
const method = requireIteratorMethod(ret, "Iterator return", frame.code.siteAt(pc))
|
||||
regs[sp++] = rec.iterator
|
||||
|
|
@ -1813,15 +1914,18 @@ export class Vm {
|
|||
return pc + 1
|
||||
}
|
||||
|
||||
private readObjProp(target: Obj, key: string | symbol, fcode: Code, pc: number): Value {
|
||||
// A named property read for an op: the value, or a program getter for the op to enter with `receiver`.
|
||||
private readObjProp(target: Obj, key: string | symbol, receiver: Value, fcode: Code, pc: number): Value | GetterCall {
|
||||
for (let cur: Obj | null = target; cur !== null; cur = cur.proto) {
|
||||
if (cur.props.size === 0) continue
|
||||
const slot = cur.props.get(key)
|
||||
if (slot !== undefined) {
|
||||
if ("value" in slot) return slot.value
|
||||
if (slot.get === undefined) return undefined
|
||||
const getter = slot.get
|
||||
if (getter === undefined) return undefined
|
||||
if (typeof getter !== "function") return new GetterCall(getter)
|
||||
try {
|
||||
return slot.get(target)
|
||||
return getter(receiver)
|
||||
} catch (err) {
|
||||
throw locate(err, fcode.siteAt(pc))
|
||||
}
|
||||
|
|
@ -1830,11 +1934,77 @@ export class Vm {
|
|||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* One property read of an iterator op that may meet a program getter: the value, or REDO once the getter is entered
|
||||
* (`Mode.REDO`), with the op's stack back as it found it (`sp0`) so it can run again from its first word. `reads` is
|
||||
* the op's reads so far this run; each value read is added to it. Running again, the op's reads replay in order.
|
||||
*/
|
||||
redoRead(
|
||||
frame: Frame,
|
||||
target: Obj,
|
||||
key: string | symbol,
|
||||
receiver: Value,
|
||||
pc: number,
|
||||
sp0: number,
|
||||
reads: Array<Value>,
|
||||
): Value | typeof REDO {
|
||||
const start = instructionStart(frame.code.code, pc)
|
||||
const redo = this.redo
|
||||
if (redo !== undefined && redo.frame === frame && redo.pc === start && redo.next < redo.values.length) {
|
||||
const replayed = redo.values[redo.next++]
|
||||
reads.push(replayed)
|
||||
return replayed
|
||||
}
|
||||
const v = this.readObjProp(target, key, receiver, frame.code, pc)
|
||||
if (!(v instanceof GetterCall)) {
|
||||
reads.push(v)
|
||||
return v
|
||||
}
|
||||
this.redo = undefined
|
||||
frame.pc = start
|
||||
frame.sp = sp0
|
||||
this.pushInternal(
|
||||
internalCode("$vmRedo"),
|
||||
[v.getter, receiver],
|
||||
callSiteOf(frame, pc),
|
||||
Mode.REDO,
|
||||
new Arr(this.ctx.builtins.Array, [start, ...reads]),
|
||||
)
|
||||
return REDO
|
||||
}
|
||||
|
||||
// Whether the op at `pc` is running again after a getter, with reads left to replay.
|
||||
private replaying(frame: Frame, pc: number): boolean {
|
||||
const redo = this.redo
|
||||
return (
|
||||
redo !== undefined &&
|
||||
redo.frame === frame &&
|
||||
redo.pc === instructionStart(frame.code.code, pc) &&
|
||||
redo.next < redo.values.length
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Enters the program getter of a member read whose result goes at `at` (a method read keeps the receiver there and the
|
||||
* value above it), as a call from the instruction at `pc`. Returns the new sp when the getter answered at once, or
|
||||
* `GETTER_ENTERED`, `GETTER_FUEL` (entered, and the slice is over) or `GETTER_BLOCKED`.
|
||||
*/
|
||||
private enterGetter(frame: Frame, getter: Callable, receiver: Value, at: number, mode: number, pc: number): number {
|
||||
if (mode === 1) frame.regs[at++] = receiver
|
||||
frame.sp = at
|
||||
frame.pc = pc
|
||||
const called = this.invokeCallable(frame, getter, receiver, [], callSiteOf(frame, pc), pc)
|
||||
if (called === 0) return frame.sp
|
||||
if (called === 2) return GETTER_BLOCKED
|
||||
return this.fuel <= 0 ? GETTER_FUEL : GETTER_ENTERED
|
||||
}
|
||||
|
||||
unwind(rawError: unknown): boolean {
|
||||
// An interruption skips every handler, but still completes each frame by its mode: a frame that settles a
|
||||
// promise rejects it, so whatever awaits that promise is interrupted in turn.
|
||||
const interrupted = rawError instanceof Interruption
|
||||
const error = interrupted ? rawError : locate(rawError, this.currentSite())
|
||||
this.redo = undefined
|
||||
|
||||
if (this.frames.length === 0) {
|
||||
this.outcome = abrupt(error)
|
||||
|
|
@ -1862,7 +2032,7 @@ export class Vm {
|
|||
|
||||
this.frames.pop()
|
||||
const mode = frame.mode
|
||||
if (mode === Mode.CALLER) {
|
||||
if (mode === Mode.CALLER || mode === Mode.REDO) {
|
||||
this.release(frame)
|
||||
continue
|
||||
}
|
||||
|
|
@ -1981,33 +2151,37 @@ export class Vm {
|
|||
return sp + 1
|
||||
}
|
||||
|
||||
// A named member read (`o.key`; mode 1 a method read, 2 a destructured property): the new sp, or a getter code.
|
||||
private execGetProp(frame: Frame, o: Value, key: string, mode: number, pc: number, sp: number): number {
|
||||
const regs = frame.regs
|
||||
if (mode !== 2 && o instanceof Obj && !(o instanceof PromiseObj)) {
|
||||
const v = key === "length" && o instanceof Arr ? o.items.length : this.readObjProp(o, key, frame.code, pc)
|
||||
const v = key === "length" && o instanceof Arr ? o.items.length : this.readObjProp(o, key, o, frame.code, pc)
|
||||
if (v instanceof GetterCall) return this.enterGetter(frame, v.getter, o, sp - 1, mode, pc)
|
||||
return writeRead(regs, sp - 1, mode, o, v)
|
||||
}
|
||||
if (mode !== 2 && typeof o === "string") {
|
||||
const v = key === "length" ? o.length : this.readObjProp(this.ctx.builtins.String, key, frame.code, pc)
|
||||
const v = key === "length" ? o.length : this.readObjProp(this.ctx.builtins.String, key, o, frame.code, pc)
|
||||
if (v instanceof GetterCall) return this.enterGetter(frame, v.getter, o, sp - 1, mode, pc)
|
||||
return writeRead(regs, sp - 1, mode, o, v)
|
||||
}
|
||||
if (o instanceof HostNamespace) {
|
||||
return writeRead(regs, sp - 1, mode, undefined, new HostNamespace(o.root, [...o.path, key]))
|
||||
}
|
||||
const site = frame.code.siteAt(pc)!
|
||||
if (mode === 2) {
|
||||
regs[sp - 1] = destructuredProperty(this.ctx.builtins, o, key, site)
|
||||
return sp
|
||||
}
|
||||
return this.readMember(regs, sp - 1, mode, o, key, site)
|
||||
return this.readMember(frame, sp - 1, mode, o, key, frame.code.siteAt(pc)!, pc)
|
||||
}
|
||||
|
||||
private execGetElem(frame: Frame, o: Value, keyVal: Value, mode: number, pc: number, sp: number): boolean {
|
||||
// A computed member read (`o[key]`), as `execGetProp`; `GETTER_ENTERED` also when the key converts in the prelude.
|
||||
private execGetElem(frame: Frame, o: Value, keyVal: Value, mode: number, pc: number, sp: number): number {
|
||||
if (mode === 0) {
|
||||
if (typeof o === "string" && typeof keyVal === "number" && keyVal >= 0 && (keyVal | 0) === keyVal) {
|
||||
if (
|
||||
typeof o === "string" &&
|
||||
typeof keyVal === "number" &&
|
||||
keyVal >= 0 &&
|
||||
keyVal < o.length &&
|
||||
(keyVal | 0) === keyVal
|
||||
) {
|
||||
frame.regs[sp - 2] = o[keyVal]
|
||||
frame.sp = sp - 1
|
||||
return false
|
||||
return sp - 1
|
||||
}
|
||||
if (o instanceof Obj && !(o instanceof PromiseObj)) {
|
||||
if (typeof keyVal === "number" && !(o instanceof Arr)) {
|
||||
|
|
@ -2018,14 +2192,14 @@ export class Vm {
|
|||
o.proto.intrinsic > 0
|
||||
) {
|
||||
frame.regs[sp - 2] = undefined
|
||||
frame.sp = sp - 1
|
||||
return false
|
||||
return sp - 1
|
||||
}
|
||||
}
|
||||
if (typeof keyVal === "string" && o.constructor === Obj) {
|
||||
frame.regs[sp - 2] = this.readObjProp(o, keyVal, frame.code, pc)
|
||||
frame.sp = sp - 1
|
||||
return false
|
||||
const v = this.readObjProp(o, keyVal, o, frame.code, pc)
|
||||
if (v instanceof GetterCall) return this.enterGetter(frame, v.getter, o, sp - 2, 0, pc)
|
||||
frame.regs[sp - 2] = v
|
||||
return sp - 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -2035,31 +2209,22 @@ export class Vm {
|
|||
if (keyVal instanceof Obj && !isOpaque(keyVal)) {
|
||||
frame.sp = sp - 2
|
||||
this.pushInternalCall("$vmGetElem", [o, keyVal], memberNode.property ?? site)
|
||||
return true
|
||||
return GETTER_ENTERED
|
||||
}
|
||||
const key = propertyKey(keyVal)
|
||||
if (mode === 2) {
|
||||
frame.regs[sp - 2] = destructuredProperty(this.ctx.builtins, o, key, site)
|
||||
frame.sp = sp - 1
|
||||
return false
|
||||
}
|
||||
frame.sp = this.readMember(frame.regs, sp - 2, mode, o, key, site)
|
||||
return false
|
||||
return this.readMember(frame, sp - 2, mode, o, propertyKey(keyVal), site, pc)
|
||||
}
|
||||
|
||||
// Reads `o[key]` for the member expression at `site` into `regs` at `at`; see `writeRead`.
|
||||
private readMember(
|
||||
regs: Array<unknown>,
|
||||
at: number,
|
||||
mode: number,
|
||||
o: Value,
|
||||
key: PropertyKey,
|
||||
site: AstNode,
|
||||
): number {
|
||||
// Reads `o[key]` for the member expression (or destructured property, mode 2) at `site` into the stack at `at`; see
|
||||
// `writeRead`. A destructured promise is read as is; a member read of one must name a property it has.
|
||||
private readMember(frame: Frame, at: number, mode: number, o: Value, key: PropertyKey, site: AstNode, pc: number) {
|
||||
const regs = frame.regs
|
||||
const ref = this.resolveMember(o, key, site)
|
||||
if (ref instanceof HostNamespace) return writeRead(regs, at, mode, undefined, ref)
|
||||
if ("value" in ref) return writeRead(regs, at, mode, undefined, ref.value)
|
||||
return writeRead(regs, at, mode, ref.receiver, readReference(ref, site as MemberExpression))
|
||||
if (mode !== 2) requirePromiseProperty(ref, site)
|
||||
const v = accessProperty(ref.target, ref.key, site, ref.receiver)
|
||||
if (v instanceof GetterCall) return this.enterGetter(frame, v.getter, ref.receiver, at, mode, pc)
|
||||
return writeRead(regs, at, mode, ref.receiver, v)
|
||||
}
|
||||
|
||||
// The reference `o[key]` that the member expression at `site` names.
|
||||
|
|
@ -2068,22 +2233,41 @@ export class Vm {
|
|||
return resolveProperty(this.ctx.builtins, o, key, member.object ?? site, member.property ?? site)
|
||||
}
|
||||
|
||||
private execPutProp(fcode: Code, o: Value, key: PropertyKey, v: Value, pc: number): void {
|
||||
if (!(o instanceof Obj)) {
|
||||
const site = fcode.siteAt(pc)!
|
||||
const ref = resolveProperty(this.ctx.builtins, o, key, site, site)
|
||||
writableReference(ref, site as MemberExpression)
|
||||
return
|
||||
}
|
||||
// `o[key] = v`, with `v` popped and `o` at `sp - 1`. True when a program setter runs (`$vmSet` answers `v`).
|
||||
private execPutProp(frame: Frame, o: Value, key: PropertyKey, v: Value, pc: number, sp: number): boolean {
|
||||
const fcode = frame.code
|
||||
let setter: Callable | undefined
|
||||
try {
|
||||
assignToReference(o, key, v, undefined!)
|
||||
setter = o instanceof Obj ? assignToReference(o, key, v, undefined) : this.primitiveSetter(fcode, o, key, v, pc)
|
||||
} catch (err) {
|
||||
throw locate(err, fcode.siteAt(pc))
|
||||
}
|
||||
if (setter === undefined) return false
|
||||
frame.sp = sp - 1
|
||||
this.pushInternalCall("$vmSet", [setter, o, v], callSiteOf(frame, pc))
|
||||
return true
|
||||
}
|
||||
|
||||
private execPutElem(fcode: Code, o: Value, keyVal: Value, v: Value, pc: number): void {
|
||||
this.execPutProp(fcode, o, propertyKey(keyVal), v, pc)
|
||||
// A write to a primitive's property: only an inherited setter can take it (with the primitive as `this`).
|
||||
private primitiveSetter(fcode: Code, o: Value, key: PropertyKey, v: Value, pc: number): Callable | undefined {
|
||||
const site = fcode.siteAt(pc)!
|
||||
const ref = resolveProperty(this.ctx.builtins, o, key, site, site)
|
||||
if (!(ref instanceof HostNamespace) && !("value" in ref)) {
|
||||
const slot = lookup(ref.target, ref.key)
|
||||
if (slot !== undefined && !("value" in slot)) {
|
||||
const setter = slot.set
|
||||
if (setter === undefined) throw failedAssignment(o, ref.key, site)
|
||||
if (typeof setter !== "function") return setter
|
||||
try {
|
||||
setter(o, v)
|
||||
} catch (err) {
|
||||
throw locate(err, site)
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
writableReference(ref, site as MemberExpression)
|
||||
return undefined
|
||||
}
|
||||
|
||||
private execDeleteProp(fcode: Code, o: Value, key: PropertyKey, pc: number): boolean {
|
||||
|
|
@ -2125,7 +2309,13 @@ export class Vm {
|
|||
return
|
||||
}
|
||||
const key = kind === CheckBaseKind.WRITE_PROP ? (fcode.consts[bx] as string) : propertyKey(regs[sp - 1] as Value)
|
||||
readReference(writableReference(this.resolveMember(base, key, site), memberNode), memberNode)
|
||||
const ref = this.resolveMember(base, key, site)
|
||||
// A primitive's inherited accessor takes the write (see `primitiveSetter`); the base is all that's checked here.
|
||||
if (!(ref instanceof HostNamespace) && !("value" in ref) && ref.receiver !== ref.target) {
|
||||
const slot = lookup(ref.target, ref.key)
|
||||
if (slot !== undefined && !("value" in slot)) return
|
||||
}
|
||||
requirePromiseProperty(writableReference(ref, memberNode), memberNode)
|
||||
}
|
||||
|
||||
private execBinarySlow(frame: Frame, op: string, a: Value, b: Value, pc: number, sp: number): boolean {
|
||||
|
|
@ -2185,7 +2375,11 @@ export class Vm {
|
|||
const site = callee.callback && callee.call.length < 3 ? undefined : callSiteOf(frame, pc)
|
||||
const res = callee.call(thisVal, args, site)
|
||||
if (this.tripEvery === 0) this.fuel -= NATIVE_FUEL
|
||||
if ((res as unknown) !== BLOCK && (res as unknown) !== ENTERED && (res === null || typeof res !== "object" || res instanceof Obj)) {
|
||||
if (
|
||||
(res as unknown) !== BLOCK &&
|
||||
(res as unknown) !== ENTERED &&
|
||||
(res === null || typeof res !== "object" || res instanceof Obj)
|
||||
) {
|
||||
normalizeItems(res)
|
||||
regs[base - 2] = res
|
||||
frame.sp = base - 1
|
||||
|
|
@ -2223,7 +2417,8 @@ export class Vm {
|
|||
} catch (err) {
|
||||
throw locate(err, site ?? this.currentSite())
|
||||
}
|
||||
if (res instanceof Convert) {
|
||||
// `$Replay` hands a built-in's next request back to `$vmReplay`'s loop.
|
||||
if ((res instanceof Convert || res instanceof Prefetch) && callee.name === "$Replay") {
|
||||
callerFrame.regs[callerFrame.sp++] = res as unknown as Value
|
||||
return 0
|
||||
}
|
||||
|
|
@ -2273,7 +2468,11 @@ export class Vm {
|
|||
const callNode = site as { readonly callee?: Expression } | undefined
|
||||
throw typeError(`${callee.root} is not a function.`, callNode?.callee ?? site)
|
||||
}
|
||||
return this.hostResult(callerFrame, this.ctx.callNamespace(callee, args, site ?? this.currentSite()))
|
||||
const result = this.ctx.callNamespace(callee, args, site ?? this.currentSite())
|
||||
if (result instanceof Prefetch) {
|
||||
return this.settleNativeResult(callerFrame, result, callee, undefined, args, false, site, pc)
|
||||
}
|
||||
return this.hostResult(callerFrame, result)
|
||||
}
|
||||
|
||||
const callNode = site as { readonly callee?: Expression } | undefined
|
||||
|
|
@ -2294,7 +2493,7 @@ export class Vm {
|
|||
private settleNativeResult(
|
||||
callerFrame: Frame,
|
||||
res: NativeResult,
|
||||
callable: Builtin | undefined,
|
||||
callable: Builtin | HostNamespace | undefined,
|
||||
thisOrNewTarget: Value,
|
||||
args: Array<Value>,
|
||||
constructing: boolean,
|
||||
|
|
@ -2312,16 +2511,17 @@ export class Vm {
|
|||
}
|
||||
if ((res as unknown) === BLOCK) return 2
|
||||
if ((res as unknown) === ENTERED) return 1
|
||||
if (res instanceof Convert) {
|
||||
if (res instanceof Convert || res instanceof Prefetch) {
|
||||
const builtins = this.ctx.builtins
|
||||
this.pushInternalCall(
|
||||
"$vmConvert",
|
||||
"$vmReplay",
|
||||
[
|
||||
callable!,
|
||||
thisOrNewTarget,
|
||||
new Arr(builtins.Array, args),
|
||||
constructing,
|
||||
new Arr(builtins.Array, []),
|
||||
new Arr(builtins.Array, []),
|
||||
res as unknown as Value,
|
||||
],
|
||||
site ?? callerFrame.origin,
|
||||
|
|
@ -2368,7 +2568,7 @@ export class Vm {
|
|||
|
||||
// A host operation's answer, by `invokeCallable`'s convention: a value is pushed (0), a frame entered (1), or the job
|
||||
// blocks (2).
|
||||
private hostResult(callerFrame: Frame, result: HostResult): number {
|
||||
private hostResult(callerFrame: Frame, result: Exclude<HostResult, Prefetch>): number {
|
||||
if (result === ENTERED) return 1
|
||||
if (result === BLOCK) return 2
|
||||
callerFrame.regs[callerFrame.sp++] = result
|
||||
|
|
@ -2458,16 +2658,21 @@ export class Vm {
|
|||
}
|
||||
}
|
||||
const site = fcode.siteAt(pc) ?? frame.origin
|
||||
const reads: Array<Value> = []
|
||||
if (context === IterContext.FOR_AWAIT || context === IterContext.ASYNC_DELEGATE) {
|
||||
if (this.openWithMethod(frame, v, AsyncIteratorSymbol, site, sp)) return pc + 1
|
||||
const opened = this.openWithMethod(frame, v, AsyncIteratorSymbol, site, pc, sp, reads)
|
||||
if (opened !== false) return opened === REDO ? REDO_ENTERED : pc + 1
|
||||
const cursor = builtinCursor(this.ctx.builtins, v)
|
||||
if (cursor !== undefined) {
|
||||
const adapter = new AsyncFromSyncIterator(this.ctx.builtins.AsyncFromSyncIterator, cursor, site!)
|
||||
frame.regs[sp - 1] = new CustomIter(adapter, get(adapter, "next"))
|
||||
const next = this.redoRead(frame, adapter, "next", adapter, pc, sp, reads)
|
||||
if (next === REDO) return REDO_ENTERED
|
||||
frame.regs[sp - 1] = new CustomIter(adapter, next)
|
||||
return skipJump(fcode.code, pc)
|
||||
}
|
||||
if (v instanceof Obj) {
|
||||
const syncMethod = readProperty(v, IteratorSymbol, site)
|
||||
const syncMethod = this.redoRead(frame, v, IteratorSymbol, v, pc, sp, reads)
|
||||
if (syncMethod === REDO) return REDO_ENTERED
|
||||
if (syncMethod !== undefined && syncMethod !== null) {
|
||||
const callable = requireIteratorMethod(syncMethod, "Iterator method", site)
|
||||
const openCode = internalCode("$vmOpenSyncForAsync")
|
||||
|
|
@ -2484,18 +2689,22 @@ export class Vm {
|
|||
}
|
||||
|
||||
if (context === IterContext.DELEGATE) {
|
||||
if (this.openWithMethod(frame, v, IteratorSymbol, site, sp)) return pc + 1
|
||||
const opened = this.openWithMethod(frame, v, IteratorSymbol, site, pc, sp, reads)
|
||||
if (opened !== false) return opened === REDO ? REDO_ENTERED : pc + 1
|
||||
const cursor = builtinCursor(this.ctx.builtins, v)
|
||||
if (cursor !== undefined) {
|
||||
const iterObj =
|
||||
cursor instanceof Position ? new IteratorObj(this.ctx.builtins.Iterator, cursor) : cursor.iterator
|
||||
frame.regs[sp - 1] = new CustomIter(iterObj, get(iterObj, "next"))
|
||||
const next = this.redoRead(frame, iterObj, "next", iterObj, pc, sp, reads)
|
||||
if (next === REDO) return REDO_ENTERED
|
||||
frame.regs[sp - 1] = new CustomIter(iterObj, next)
|
||||
return skipJump(fcode.code, pc)
|
||||
}
|
||||
throw typeError("yield* requires a compatible iterable value.", site)
|
||||
}
|
||||
|
||||
if (this.openWithMethod(frame, v, IteratorSymbol, site, sp)) return pc + 1
|
||||
const opened = this.openWithMethod(frame, v, IteratorSymbol, site, pc, sp, reads)
|
||||
if (opened !== false) return opened === REDO ? REDO_ENTERED : pc + 1
|
||||
if (context === IterContext.FOR_OF) {
|
||||
throw invalidData(`for...of requires an iterable value, received ${describeValue(v)}.`, site)
|
||||
}
|
||||
|
|
@ -2510,22 +2719,34 @@ export class Vm {
|
|||
)
|
||||
}
|
||||
|
||||
private execIterInit(frame: Frame, context: number, pc: number, sp: number): void {
|
||||
// True when a `next` getter is entered first.
|
||||
private execIterInit(frame: Frame, context: number, pc: number, sp: number): boolean {
|
||||
const site = frame.code.siteAt(pc) ?? frame.origin
|
||||
const v = frame.regs[sp - 1] as Value
|
||||
if (context === IterContext.CHECK_OBJECT) {
|
||||
requireIteratorObject(v, "Iterator return() result", site)
|
||||
return
|
||||
return false
|
||||
}
|
||||
const obj = requireIteratorObject(v, "Iterator method result", site)
|
||||
const next = requireIteratorMethod(readProperty(obj, "next", site), "Iterator next", site)
|
||||
frame.regs[sp - 1] = this.customIter(obj, next)
|
||||
const read = this.redoRead(frame, obj, "next", obj, pc, sp, [])
|
||||
if (read === REDO) return true
|
||||
frame.regs[sp - 1] = this.customIter(obj, requireIteratorMethod(read, "Iterator next", site))
|
||||
return false
|
||||
}
|
||||
|
||||
// Opens `v` with its own `symbol` method, when it has one: the next instruction calls it.
|
||||
private openWithMethod(frame: Frame, v: Value, symbol: symbol, site: AstNode | undefined, sp: number): boolean {
|
||||
// Opens `v` with its own `symbol` method, when it has one (true): the next instruction calls it.
|
||||
private openWithMethod(
|
||||
frame: Frame,
|
||||
v: Value,
|
||||
symbol: symbol,
|
||||
site: AstNode | undefined,
|
||||
pc: number,
|
||||
sp: number,
|
||||
reads: Array<Value>,
|
||||
): boolean | typeof REDO {
|
||||
if (!(v instanceof Obj)) return false
|
||||
const method = readProperty(v, symbol, site)
|
||||
const method = this.redoRead(frame, v, symbol, v, pc, sp, reads)
|
||||
if (method === REDO) return REDO
|
||||
if (method === undefined || method === null) return false
|
||||
frame.regs[sp - 1] = v
|
||||
frame.regs[sp] = requireIteratorMethod(method, "Iterator method", site)
|
||||
|
|
@ -2540,7 +2761,7 @@ export class Vm {
|
|||
custom.rawGen =
|
||||
iterator instanceof GeneratorObj &&
|
||||
!iterator.asynchronous &&
|
||||
(next === get(builtins.Generator, "next") || next === get(builtins.IteratorHelper, "next"))
|
||||
(next === peek(builtins.Generator, "next") || next === peek(builtins.IteratorHelper, "next"))
|
||||
return custom
|
||||
}
|
||||
|
||||
|
|
@ -2673,15 +2894,19 @@ export class Vm {
|
|||
frame.sp = this.execImport(frame, a, bx, pc, sp)
|
||||
return pc + 1
|
||||
case Op.GET_PROP:
|
||||
frame.sp = this.execGetProp(frame, regs[sp - 1] as Value, consts[bx] as string, a, pc, sp)
|
||||
return pc + 1
|
||||
case Op.GET_ELEM:
|
||||
if (this.execGetElem(frame, regs[sp - 2] as Value, regs[sp - 1] as Value, a, pc, sp)) return -1
|
||||
case Op.GET_ELEM: {
|
||||
const r =
|
||||
op === Op.GET_PROP
|
||||
? this.execGetProp(frame, regs[sp - 1] as Value, consts[bx] as string, a, pc, sp)
|
||||
: this.execGetElem(frame, regs[sp - 2] as Value, regs[sp - 1] as Value, a, pc, sp)
|
||||
if (r < 0) return r === GETTER_ENTERED ? -1 : r === GETTER_FUEL ? -3 : -4
|
||||
frame.sp = r
|
||||
return pc + 1
|
||||
}
|
||||
case Op.PUT_PROP: {
|
||||
const v = regs[--sp] as Value
|
||||
frame.sp = sp
|
||||
this.execPutProp(fcode, regs[sp - 1] as Value, consts[bx] as string, v, pc)
|
||||
if (this.execPutProp(frame, regs[sp - 1] as Value, consts[bx] as string, v, pc, sp)) return -1
|
||||
regs[sp - 1] = v
|
||||
return pc + 1
|
||||
}
|
||||
|
|
@ -2689,7 +2914,7 @@ export class Vm {
|
|||
const v = regs[--sp] as Value
|
||||
const keyVal = regs[--sp] as Value
|
||||
frame.sp = sp
|
||||
this.execPutElem(fcode, regs[sp - 1] as Value, keyVal, v, pc)
|
||||
if (this.execPutProp(frame, regs[sp - 1] as Value, propertyKey(keyVal), v, pc, sp)) return -1
|
||||
regs[sp - 1] = v
|
||||
return pc + 1
|
||||
}
|
||||
|
|
@ -2721,7 +2946,7 @@ export class Vm {
|
|||
case Op.INSTANCEOF: {
|
||||
const rhs = regs[--sp] as Value
|
||||
frame.sp = sp
|
||||
regs[sp - 1] = this.execInstanceof(fcode, regs[sp - 1] as Value, rhs, pc)
|
||||
if (this.execInstanceof(frame, regs[sp - 1] as Value, rhs, pc, sp)) return -1
|
||||
return pc + 1
|
||||
}
|
||||
case Op.NEW_OBJECT:
|
||||
|
|
@ -2739,11 +2964,14 @@ export class Vm {
|
|||
return pc + 1
|
||||
case Op.COPY_DATA_PROPS:
|
||||
frame.sp = --sp
|
||||
this.execCopyDataProps(fcode, regs[sp - 1] as Obj, regs[sp] as Value, pc)
|
||||
if (this.execCopyDataProps(frame, regs[sp - 1] as Obj, regs[sp] as Value, pc, sp)) return -1
|
||||
return pc + 1
|
||||
case Op.COPY_REST:
|
||||
frame.sp = this.execCopyRest(fcode, regs, bx, pc, sp)
|
||||
case Op.COPY_REST: {
|
||||
const r = this.execCopyRest(frame, regs, bx, pc, sp)
|
||||
if (r < 0) return -1
|
||||
frame.sp = r
|
||||
return pc + 1
|
||||
}
|
||||
case Op.TEMPLATE:
|
||||
regs[sp++] = this.getTemplateObject(fcode, consts[bx] as TemplateSite)
|
||||
frame.sp = sp
|
||||
|
|
@ -2928,7 +3156,7 @@ export class Vm {
|
|||
case Op.ITER_OPEN:
|
||||
return this.execIterOpen(frame, a, pc, sp)
|
||||
case Op.ITER_INIT:
|
||||
this.execIterInit(frame, a, pc, sp)
|
||||
if (this.execIterInit(frame, a, pc, sp)) return -1
|
||||
return pc + 1
|
||||
case Op.ITER_STEP: {
|
||||
const rec = regs[a]
|
||||
|
|
@ -2965,15 +3193,35 @@ export class Vm {
|
|||
execAwait(this, frame, a, pc, sp)
|
||||
return -1
|
||||
case Op.YSTAR:
|
||||
return execYstar(frame, a, bx, pc, sp)
|
||||
return execYstar(this, frame, a, bx, pc, sp)
|
||||
case Op.YSTAR_RESULT:
|
||||
return execYstarResult(frame, a, bx, pc, sp)
|
||||
return execYstarResult(this, frame, a, bx, pc, sp)
|
||||
case Op.DEFINE_ACCESSOR:
|
||||
frame.sp = this.execDefineAccessor(regs, consts, a, bx, sp)
|
||||
return pc + 1
|
||||
default:
|
||||
throw new Error(`Unexpected wide op ${op}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// What `execGetProp` / `execGetElem` return in place of a stack pointer once they enter a frame (a getter, say): it runs
|
||||
// now (`continue outer`), the slice is over, or the job blocks on the host call the getter made.
|
||||
const GETTER_ENTERED = -1
|
||||
const GETTER_FUEL = -2
|
||||
const GETTER_BLOCKED = -3
|
||||
|
||||
// `redoRead`'s answer once it entered a getter, and the iterator ops' (a negative pc, so `continue outer`).
|
||||
export const REDO: unique symbol = Symbol("vm.redo")
|
||||
export const REDO_ENTERED = -1
|
||||
|
||||
// The first word of the instruction whose opcode word is at `pc`: before its `EXTRA` prefix words, if any.
|
||||
const instructionStart = (code: Int32Array, pc: number): number => {
|
||||
if (pc > 0 && (code[pc - 1]! & 0xff) === Op.EXTRA)
|
||||
return pc > 1 && (code[pc - 2]! & 0xff) === Op.EXTRA ? pc - 2 : pc - 1
|
||||
return pc
|
||||
}
|
||||
|
||||
// Skips the `JUMP slow` instruction following a test-and-skip `ITER_OPEN` or `ITER_STEP`.
|
||||
const skipJump = (code: Int32Array, pc: number): number => ((code[pc + 1]! & 0xff) === Op.EXTRA ? pc + 3 : pc + 2)
|
||||
|
||||
|
|
|
|||
418
packages/codemode/test/accessors-suspend.test.ts
Normal file
418
packages/codemode/test/accessors-suspend.test.ts
Normal file
|
|
@ -0,0 +1,418 @@
|
|||
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"
|
||||
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.
|
||||
|
||||
type Saved = { readonly t?: string; readonly f?: ReadonlyArray<unknown>; readonly o?: ReadonlyArray<unknown> }
|
||||
|
||||
// The frames a saved state holds (the job stack, parked awaits, suspended generators): each one's function name, or
|
||||
// the internal helper it runs, with "(redo)" for a getter an iterator op is running (`Mode.REDO`).
|
||||
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, , , , , , mode] = record.f as [unknown, [string, [string, string, number]], ...Array<unknown>]
|
||||
const redo = mode === 7 ? " (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] = code[1]
|
||||
const codes = source === "@vm-internal" ? getInternalPrelude().codes : compiledPrelude().codes
|
||||
return [`${codes[index]!.name}${redo}`]
|
||||
})
|
||||
}
|
||||
|
||||
/** 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 }
|
||||
}
|
||||
|
||||
// Round-trip mode yields at its checkpoints, so `slow` starting doesn't mean the run is parked on it yet. Suspend
|
||||
// after `slow` starts, and if the saved stack hasn't reached `$vmHostWait`, run again and let it go on longer.
|
||||
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
|
||||
}
|
||||
throw new Error("the run never parked on $vmHostWait while `slow` was in flight")
|
||||
}
|
||||
|
||||
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"]))
|
||||
}, 3000)
|
||||
|
||||
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)
|
||||
}, 3000)
|
||||
}
|
||||
|
||||
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]`
|
||||
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())
|
||||
// The suspended run's host call settles before the resume.
|
||||
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")) continue
|
||||
expect(frames(suspended.state)).toEqual(expect.arrayContaining(["get next", "$vmRedo (redo)"]))
|
||||
const resumed = await Effect.runPromise(
|
||||
first.runtime.resume(from === "state" ? suspended.state : toBytes(suspended.state)).run(),
|
||||
)
|
||||
expect(resumed).toMatchObject({ ok: true, value: [0, 2] })
|
||||
return
|
||||
}
|
||||
throw new Error("the run never parked on $vmHostWait while `slow` was in flight")
|
||||
}, 3000)
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
})
|
||||
})
|
||||
453
packages/codemode/test/accessors.test.ts
Normal file
453
packages/codemode/test/accessors.test.ts
Normal file
|
|
@ -0,0 +1,453 @@
|
|||
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.")
|
||||
})
|
||||
})
|
||||
265
packages/codemode/test/descriptors.test.ts
Normal file
265
packages/codemode/test/descriptors.test.ts
Normal file
|
|
@ -0,0 +1,265 @@
|
|||
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)
|
||||
})
|
||||
})
|
||||
|
|
@ -223,10 +223,11 @@ describe("call depth", () => {
|
|||
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(
|
||||
|
|
@ -237,8 +238,9 @@ describe("call depth", () => {
|
|||
).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)
|
||||
})
|
||||
|
|
|
|||
17
packages/codemode/test/fixtures/resume-getters-process.ts
vendored
Normal file
17
packages/codemode/test/fixtures/resume-getters-process.ts
vendored
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
// 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())))
|
||||
190
packages/codemode/test/host-accessors.test.ts
Normal file
190
packages/codemode/test/host-accessors.test.ts
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
import { describe, expect, test } from "bun:test"
|
||||
import { Effect } from "effect"
|
||||
import { Host, Runtime } from "../src/language/index.js"
|
||||
|
||||
// Program getters crossing to the host: they run (once per receiver and key) before the host function does, their
|
||||
// values cross as data, and setter-only properties are left out.
|
||||
|
||||
const run = <R>(runtime: Runtime.Runtime<R>, code: string) =>
|
||||
Effect.runPromise(runtime.execute(code) as Effect.Effect<Runtime.Result>)
|
||||
|
||||
const value = async <R>(runtime: Runtime.Runtime<R>, code: string) => {
|
||||
const result = await run(runtime, code)
|
||||
if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`)
|
||||
return result.value
|
||||
}
|
||||
|
||||
const translating = (translate?: Runtime.Translate) => {
|
||||
const calls: Array<ReadonlyArray<unknown>> = []
|
||||
const keys: Array<string> = []
|
||||
const runtime = Runtime.make({
|
||||
translate,
|
||||
globals: () => ({
|
||||
keep: Host.fn((args, call) => {
|
||||
keys.push(call.key)
|
||||
calls.push(args)
|
||||
return args.length
|
||||
}),
|
||||
send: Host.fn(
|
||||
(args, call) =>
|
||||
Effect.sync(() => {
|
||||
keys.push(call.key)
|
||||
calls.push(args)
|
||||
return "sent"
|
||||
}),
|
||||
{ type: "async" },
|
||||
),
|
||||
later: Host.fn(([n]) => Effect.succeed(n), { type: "async" }),
|
||||
ns: Host.namespace({
|
||||
keys: () => ["echo"],
|
||||
resolve: () => Host.fn((args) => args[0]),
|
||||
}),
|
||||
}),
|
||||
})
|
||||
return { runtime, calls, keys }
|
||||
}
|
||||
|
||||
describe("getters crossing to the host", () => {
|
||||
test("a getter's value crosses as data and a setter-only property is left out", async () => {
|
||||
const { runtime, calls } = translating()
|
||||
expect(
|
||||
await value(
|
||||
runtime,
|
||||
`let n = 0
|
||||
const o = { a: 1, get b() { n++; return { c: [n] } }, set d(v) {}, get e() { n++ } }
|
||||
keep(o, [o.b])
|
||||
return n`,
|
||||
),
|
||||
).toBe(3)
|
||||
expect(calls).toEqual([[{ a: 1, b: { c: [2] }, e: undefined }, [{ c: [1] }]]])
|
||||
expect(Object.keys(calls[0]![0] as object)).toEqual(["a", "b", "e"])
|
||||
})
|
||||
|
||||
test("each getter runs once per crossing, nested getters too, and errors cross with getter fields", async () => {
|
||||
const { runtime, calls } = translating()
|
||||
expect(
|
||||
await value(
|
||||
runtime,
|
||||
`const log = []
|
||||
const inner = { get y() { log.push("y"); return 2 } }
|
||||
const o = { get x() { log.push("x"); return inner } }
|
||||
const e = new Error("boom")
|
||||
e.detail = { get why() { log.push("why"); return "because" } }
|
||||
keep(o, o, [inner], e)
|
||||
return log`,
|
||||
),
|
||||
).toEqual(["x", "y", "why"])
|
||||
expect(calls[0]!.slice(0, 3)).toEqual([{ x: { y: 2 } }, { x: { y: 2 } }, [{ y: 2 }]])
|
||||
expect((calls[0]![3] as { detail: unknown }).detail).toEqual({ why: "because" })
|
||||
})
|
||||
|
||||
test("a getter that throws fails the call before the host function runs", async () => {
|
||||
const { runtime, calls } = translating()
|
||||
expect(
|
||||
await value(runtime, `try { keep({ get x() { throw new Error("no") } }) } catch (e) { return e.message }`),
|
||||
).toBe("no")
|
||||
expect(calls).toEqual([])
|
||||
})
|
||||
|
||||
test("a getter that throws rejects an async call's promise, and a sync call still throws", async () => {
|
||||
const { runtime, calls, keys } = translating()
|
||||
expect(
|
||||
await value(
|
||||
runtime,
|
||||
`const bad = { get x() { throw new Error("boom") } }
|
||||
const caught = await send(bad).catch((e) => e.message)
|
||||
const settled = await Promise.allSettled([send(bad), send(2)])
|
||||
let sync
|
||||
try { keep(bad) } catch (e) { sync = e.message }
|
||||
return [caught, settled.map((s) => s.status), sync, keep(3)]`,
|
||||
),
|
||||
).toEqual(["boom", ["rejected", "fulfilled"], "boom", 1])
|
||||
expect(calls).toEqual([[2], [3]])
|
||||
expect(keys.map((key) => key.split(":")[1])).toEqual(["0", "1"])
|
||||
})
|
||||
|
||||
test("an async host function returns its promise at once, and getter rounds take no call ids", async () => {
|
||||
const { runtime, calls, keys } = translating()
|
||||
expect(
|
||||
await value(
|
||||
runtime,
|
||||
`const p = send({ get a() { return { get b() { return 1 } } } })
|
||||
const q = keep(1)
|
||||
return [p instanceof Promise, await p, q]`,
|
||||
),
|
||||
).toEqual([true, "sent", 1])
|
||||
// The async call is queued first and runs after the sync one; neither id went to a getter round.
|
||||
expect(calls).toEqual([[1], [{ a: { b: 1 } }]])
|
||||
expect(keys.map((key) => key.split(":")[1])).toEqual(["1", "0"])
|
||||
})
|
||||
|
||||
test("with promises: await, getters run first, then the promises they return are awaited", async () => {
|
||||
const { runtime, calls } = translating({ promises: "await" })
|
||||
expect(
|
||||
await value(
|
||||
runtime,
|
||||
`let n = 0
|
||||
const o = { get p() { n++; return later({ get q() { n++; return 3 } }) } }
|
||||
keep(o)
|
||||
return n`,
|
||||
),
|
||||
).toBe(2)
|
||||
expect(calls).toEqual([[{ p: { q: 3 } }]])
|
||||
})
|
||||
|
||||
test("with promises: await, a sync call inside a generator or the result's getters waits there", async () => {
|
||||
const { runtime, calls } = translating({ promises: "await" })
|
||||
expect(
|
||||
await value(
|
||||
runtime,
|
||||
`function* g() { yield keep(later(1)) }
|
||||
return [[...g()], { get x() { return keep(later(2)) } }]`,
|
||||
),
|
||||
).toEqual([[1], { x: 1 }])
|
||||
expect(calls).toEqual([[1], [2]])
|
||||
})
|
||||
|
||||
test("functions: drop applies to a getter's value", async () => {
|
||||
const { runtime, calls } = translating({ functions: "drop" })
|
||||
await value(runtime, `keep({ get f() { return () => 1 }, a: 1 })`)
|
||||
expect(calls).toEqual([[{ a: 1 }]])
|
||||
})
|
||||
|
||||
test("a namespace call reads getter arguments ahead too", async () => {
|
||||
const { runtime } = translating()
|
||||
expect(await value(runtime, `return ns.echo({ get v() { return 4 } })`)).toEqual({ v: 4 })
|
||||
})
|
||||
|
||||
test("a circular getter is refused", async () => {
|
||||
const { runtime } = translating()
|
||||
const result = await run(runtime, `const o = { get self() { return o } }; keep(o)`)
|
||||
expect(result).toMatchObject({ ok: false, error: { message: expect.stringContaining("circular") } })
|
||||
})
|
||||
})
|
||||
|
||||
describe("accessor flags on copies", () => {
|
||||
test("an awaited sync-thenable copy keeps its getters", async () => {
|
||||
const runtime = Runtime.make({
|
||||
globals: () => ({ find: Host.fn(() => Effect.succeed({ a: 1 }), { type: "sync-thenable" }) }),
|
||||
})
|
||||
expect(
|
||||
await value(
|
||||
runtime,
|
||||
`const r = find()
|
||||
Object.defineProperty(r, "x", { get() { return 42 }, enumerable: true })
|
||||
const copy = await r
|
||||
console.log(copy)
|
||||
return [JSON.stringify(copy), Object.entries(copy), { ...copy }]`,
|
||||
),
|
||||
).toEqual(['{"a":1,"x":42}', [["a", 1], ["x", 42]], { a: 1, x: 42 }])
|
||||
})
|
||||
|
||||
test("an Error.prototype getter is called when an error is converted", async () => {
|
||||
const runtime = Runtime.make({ globals: () => ({}) })
|
||||
const setup = `Object.defineProperty(Error.prototype, "name", { get() { return "Custom" }, configurable: true })`
|
||||
expect(await value(runtime, `${setup}; return JSON.stringify(new Error("hi"))`)).toBe(
|
||||
'{"name":"Custom","message":"hi"}',
|
||||
)
|
||||
expect(await value(runtime, `${setup}; return new Error("hi")`)).toEqual({ name: "Custom", message: "hi" })
|
||||
})
|
||||
})
|
||||
|
|
@ -77,6 +77,6 @@ describe("new on a non-constructible callee", () => {
|
|||
expect(failure.message).toStartWith(
|
||||
"SyntaxError: Syntax 'ClassDeclaration' is not supported. This is a restricted JavaScript-like language. Supported: ",
|
||||
)
|
||||
expect(failure.message).toContain("Unsupported: classes, getters/setters, BigInt, and custom Symbols.")
|
||||
expect(failure.message).toContain("Unsupported: classes, BigInt, and custom Symbols.")
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1395,12 +1395,10 @@ describe("Object.getPrototypeOf and Object.create", () => {
|
|||
).toEqual([true, ["name"], false, 1, "hi x", true, null, ["name", "greet", "a"]])
|
||||
})
|
||||
|
||||
test("Object.create rejects non-object prototypes and property descriptors", async () => {
|
||||
test("Object.create rejects non-object prototypes and defines properties from descriptors", async () => {
|
||||
expect((await error(`Object.create(1)`)).message).toContain("Object prototype may only be an Object or null")
|
||||
expect((await error(`Object.create()`)).message).toContain("Object prototype may only be an Object or null")
|
||||
expect((await error(`Object.create(null, { a: { value: 1 } })`)).message).toContain(
|
||||
"Object.create property descriptors are not supported",
|
||||
)
|
||||
expect(await value(`return Object.create(null, { a: { value: 1, enumerable: true } }).a`)).toBe(1)
|
||||
expect(await value(`return Object.keys(Object.create({}, undefined))`)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
import { setRoundTrip } from "../src/language/runtime/execute.js"
|
||||
import { nativeRule } from "../src/language/runtime/objects.js"
|
||||
import { accessorRule, nativeRule } from "../src/language/runtime/objects.js"
|
||||
|
||||
// Every test run checks that natives are made only with the intrinsics.
|
||||
// Every test run checks that natives are made only with the intrinsics, and that no built-in reaches a program
|
||||
// getter or setter it has no path for.
|
||||
nativeRule.check = true
|
||||
accessorRule.check = true
|
||||
|
||||
if (process.env.CODEMODE_ROUNDTRIP === "1") {
|
||||
setRoundTrip(true)
|
||||
|
|
|
|||
|
|
@ -10,11 +10,10 @@ import { type Diagnostic, PendingThrow } from "../src/language/runtime/model.js"
|
|||
import type { Value } from "../src/language/runtime/objects.js"
|
||||
import { Interruption } from "../src/language/runtime/signals.js"
|
||||
import type { Source } from "../src/language/runtime/source.js"
|
||||
import type { Snapshot } from "../src/language/snapshot/snapshot.js"
|
||||
import { fromBytes, type Snapshot, toBytes } from "../src/language/snapshot/snapshot.js"
|
||||
|
||||
/** A quoted `file:` URL for a module relative to `test`, to import from a script run with `bun -e` on any platform. */
|
||||
export const moduleUrl = (relative: string) =>
|
||||
JSON.stringify(pathToFileURL(path.join(import.meta.dir, relative)).href)
|
||||
export const moduleUrl = (relative: string) => JSON.stringify(pathToFileURL(path.join(import.meta.dir, relative)).href)
|
||||
|
||||
/** How a run ended, shaped like a CodeMode result with no tool calls. */
|
||||
export type Result =
|
||||
|
|
@ -37,7 +36,7 @@ export type RunOptions = {
|
|||
readonly bindings?: (ctx: Interpreter<never>) => ReadonlyArray<readonly [string, Value]>
|
||||
readonly maxSlices?: number
|
||||
/**
|
||||
* Round-trip mode: slice after every `every` fuel ticks, then save the state as JSON and continue in a fresh runtime
|
||||
* Round-trip mode: slice after every `every` fuel ticks, then save the state to bytes and continue in a fresh runtime
|
||||
* restored from it, at most `max` times (default 200).
|
||||
*/
|
||||
readonly roundTrip?: { readonly every: number; readonly max?: number }
|
||||
|
|
@ -92,7 +91,7 @@ export const runProgram = (code: string, options?: RunOptions): Result => {
|
|||
options?.onTrip?.(snapshot)
|
||||
ctx = runtime(undefined)
|
||||
vm = ctx.vm
|
||||
vm.restore(JSON.parse(JSON.stringify(snapshot)), {
|
||||
vm.restore(fromBytes(toBytes(snapshot)), {
|
||||
parse: (code) => {
|
||||
const again = parseVmSource(code)
|
||||
if (!again.ok) throw new Error(again.error.message)
|
||||
|
|
|
|||
|
|
@ -26,8 +26,8 @@ Without them the runner registers no tests, so CI is unaffected. Licensed under
|
|||
`script/sync-test262.ts` skips a file when its frontmatter declares a `flags`, `features`, or `includes` value the
|
||||
manifest marks unsupported, or when its code matches one of the manifest's `boundaries` patterns. The sync checks the
|
||||
checkout is at the pinned revision, so every machine runs the same files. Boundaries are
|
||||
intentional limits of the interpreter, not compatibility work: classes, prototype objects, property descriptors,
|
||||
accessors, boxed primitives, typed arrays and buffers, `WeakRef` and `FinalizationRegistry`, `Reflect` and `Proxy`, sloppy mode, `eval`,
|
||||
intentional limits of the interpreter, not compatibility work: classes, prototype mutation, legacy accessors
|
||||
(`__defineGetter__` and friends), boxed primitives, typed arrays and buffers, `WeakRef` and `FinalizationRegistry`, `Reflect` and `Proxy`, sloppy mode, `eval`,
|
||||
`Symbol()`, and the `$262` host API. If one
|
||||
of those decisions changes, delete its entry and re-sync; the tests are upstream, not lost.
|
||||
|
||||
|
|
|
|||
|
|
@ -5,8 +5,8 @@
|
|||
"flags": ["module", "raw", "noStrict"],
|
||||
"boundaries": {
|
||||
"class": "\\bclass\\s*[A-Za-z_${]",
|
||||
"accessor properties": "\\b(get|set)\\s+[\\w$\\[][^\\n(]*\\(",
|
||||
"property descriptors": "Object\\.(defineProperty|defineProperties|getOwnPropertyDescriptors?|getOwnPropertyNames|setPrototypeOf)\\b",
|
||||
"prototype mutation": "Object\\.setPrototypeOf\\b",
|
||||
"legacy accessors": "\\b__(define|lookup)(Getter|Setter)__\\b",
|
||||
"boxed primitives": "\\b(new\\s+(String|Number|Boolean)\\b|Object\\s*\\(\\s*(true|false|-?\\d|['\"]))",
|
||||
"typed arrays and buffers": "\\b(ArrayBuffer|SharedArrayBuffer|DataView|Int8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float16Array|Float32Array|Float64Array|BigInt64Array|BigUint64Array)\\b",
|
||||
"weak collections": "\\b(WeakRef|FinalizationRegistry)\\b",
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -201,6 +201,9 @@ export const verifyCode = (c: Code): Array<string> => {
|
|||
case Op.DEFINE_FIELD:
|
||||
next(a === 0 ? -1 : -2)
|
||||
break
|
||||
case Op.DEFINE_ACCESSOR:
|
||||
next((a & 1) === 0 ? -1 : -2)
|
||||
break
|
||||
case Op.NEW_ARRAY:
|
||||
case Op.CONCAT:
|
||||
next(1 - bx)
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue