Skip to content

Commit 10ae321

Browse files
authored
refactor(codemode): give programs their own objects and arrays (anomalyco#48527)
1 parent 6e8ff0c commit 10ae321

23 files changed

Lines changed: 568 additions & 637 deletions

‎packages/codemode/interpreter-support.md‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ ultimate source of truth. Upstream test262 files run verbatim from `test/test262
243243
- [x] Circular references are rejected when created (`o.self = o`, `array.push(array)`), not at serialization as in JS.
244244
- [x] `Object.is` for supported data values.
245245
- [x] `Object.groupBy` over finite collections and custom synchronous iterators/generators, with string-key coercion
246-
and null-prototype results.
246+
and plain-object results.
247247
- [ ] `Object.prototype` methods on values: `toString`, `toLocaleString`, `valueOf`, and `hasOwnProperty`.
248248

249249
## Arrays
@@ -264,12 +264,13 @@ ultimate source of truth. Upstream test262 files run verbatim from `test/test262
264264
- [x] `length`, numeric indexing, index assignment, spread, and `for...of`.
265265
- [x] The `thisArg` argument of `Array.from` is accepted and ignored, like JS arrows.
266266
- [x] `Array.prototype.toSpliced`.
267-
- [x] Canonical array/string index parsing: keys such as `"01"` remain non-index properties rather than aliasing index
268-
`1`; arbitrary array-property assignment remains unsupported.
267+
- [x] Canonical array/string index parsing: keys such as `"01"` are ordinary properties rather than aliases of index
268+
`1`.
269269
- [x] `Array.prototype.sort` preserves trailing holes, while `toSorted` densifies holes into `undefined` elements,
270270
like JavaScript.
271-
- [ ] Assigning `length` to truncate or extend an array.
272-
- [ ] Non-index own properties on arrays (`arr.foo = 1`, `arr.constructor = null`).
271+
- [x] Assigning `length` to truncate or extend an array; invalid lengths throw `RangeError`.
272+
- [x] Non-index own properties on arrays (`arr.foo = 1`, `arr.constructor = null`). They are excluded from the JSON
273+
form, like `JSON.stringify`.
273274
- [ ] Argument coercion for `indexOf`, `lastIndexOf`, `includes`, `fill`, `flat`, `copyWithin`, and the `join`
274275
separator: JavaScript applies ToIntegerOrInfinity/ToString (including `valueOf`, strings, and `undefined`), the
275276
interpreter requires numbers and strings; `includes()`/`indexOf()` with no argument should search for
@@ -358,7 +359,7 @@ ultimate source of truth. Upstream test262 files run verbatim from `test/test262
358359
- [x] `test`, `exec`, and `toString`.
359360
- [x] Readable `source`, `flags`, `lastIndex`, `hasIndices`, `global`, `ignoreCase`, `multiline`, `sticky`, `unicode`,
360361
`unicodeSets`, and `dotAll`.
361-
- [x] Captures, named groups, match `.index`, and stateful global matching.
362+
- [x] Captures, named groups, match `.index` and `.input`, and stateful global matching.
362363
- [x] Integration with supported String methods, including function replacers.
363364
- [x] Writable `lastIndex`.
364365
- [x] Match `indices` metadata for the `d` flag, including named groups on `exec`, `match`, and `matchAll` results.

‎packages/codemode/src/data.ts‎

Lines changed: 40 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
export * as Data from "./data.js"
22

33
import type { DiagnosticKind } from "./codemode.js"
4+
import { ownEntries, parseArrayIndex, ProgramArray, ProgramObject, set } from "./interpreter/objects.js"
45
import { Values } from "./values.js"
56

6-
/** A null-prototype object owned by the program. */
7-
export type SafeObject = Record<string, unknown>
8-
97
const MAX_VALUE_DEPTH = 32
108

119
export class ToolRuntimeError extends Error {
@@ -23,15 +21,15 @@ export class ToolRuntimeError extends Error {
2321
}
2422

2523
/**
26-
* Brings a host-produced runtime value into the program: runtime values pass through, their host
27-
* counterparts (Date, RegExp, Map, Set, URL, URLSearchParams) are wrapped, and objects become
28-
* null-prototype copies. Arrays keep extra enumerable properties such as `index` and `groups`.
24+
* Brings a host-produced value into the program: program and runtime values pass through, their
25+
* host counterparts (Date, RegExp, Map, Set, URL, URLSearchParams) are wrapped, and host objects
26+
* and arrays are copied.
2927
*/
3028
export const toProgram = (value: unknown, label: string): unknown => copy(value, label, "program", 0, new Set())
3129

3230
/**
3331
* Brings host data into the program: Date and URL become strings, other host collections become
34-
* empty objects, and objects become null-prototype copies. Used for tool results and parsed JSON.
32+
* empty objects, and objects become program copies. Used for tool results and parsed JSON.
3533
*/
3634
export const fromData = (value: unknown, label: string): unknown => copy(value, label, "data", 0, new Set())
3735

@@ -44,8 +42,7 @@ export const fromData = (value: unknown, label: string): unknown => copy(value,
4442
export const toData = (value: unknown, label: string, undefinedAs: "json" | "result" = "json"): unknown =>
4543
copy(value, label, undefinedAs, 0, new Set())
4644

47-
// "program" and "data" build program-owned null-prototype objects; "json" and "result" build
48-
// ordinary objects for the host.
45+
// "program" and "data" build program objects; "json" and "result" build ordinary objects for the host.
4946
type Mode = "program" | "data" | "json" | "result"
5047

5148
const copy = (value: unknown, label: string, mode: Mode, depth: number, seen: Set<object>): unknown => {
@@ -65,8 +62,9 @@ const copy = (value: unknown, label: string, mode: Mode, depth: number, seen: Se
6562
)
6663
}
6764

65+
const plain = mode === "program" || mode === "data"
6866
if (mode === "program") {
69-
if (Values.isValue(value)) return value
67+
if (value instanceof ProgramObject || Values.isValue(value)) return value
7068
if (value instanceof Date) return new Values.Date(value.getTime())
7169
if (value instanceof RegExp) return new Values.RegExp(value.source, value.flags)
7270
if (value instanceof Map) {
@@ -85,7 +83,6 @@ const copy = (value: unknown, label: string, mode: Mode, depth: number, seen: Se
8583
if (value instanceof URLSearchParams) return new Values.URLSearchParams(new URLSearchParams(value))
8684
}
8785

88-
const plain = mode === "program" || mode === "data"
8986
if (value instanceof Values.Date) return Number.isFinite(value.time) ? new Date(value.time).toISOString() : null
9087
if (value instanceof Date) return Number.isFinite(value.getTime()) ? value.toISOString() : null
9188
if (value instanceof Values.URL) return value.url.href
@@ -98,25 +95,40 @@ const copy = (value: unknown, label: string, mode: Mode, depth: number, seen: Se
9895
value instanceof Set ||
9996
value instanceof URLSearchParams
10097
) {
101-
return plain ? (Object.create(null) as SafeObject) : {}
98+
return plain ? new ProgramObject() : {}
10299
}
103100

104101
if (seen.has(value)) {
105102
throw new ToolRuntimeError("InvalidDataValue", `${label} contains a circular value.`)
106103
}
107104
seen.add(value)
108105

106+
if (value instanceof ProgramArray) {
107+
const copied = Array.from(value.items, (item) => copy(item, label, mode, depth + 1, seen) ?? null)
108+
seen.delete(value)
109+
return copied
110+
}
111+
if (value instanceof ProgramObject) {
112+
const copied: Record<string, unknown> = {}
113+
for (const [key, item] of ownEntries(value)) {
114+
const next = copy(item, label, mode, depth + 1, seen)
115+
if (next === undefined && mode === "json") continue
116+
define(copied, key, next)
117+
}
118+
seen.delete(value)
119+
return copied
120+
}
121+
109122
if (Array.isArray(value)) {
110-
// Host output densifies holes to null like JSON; program copies keep them.
111-
const copied = plain
112-
? value.map((item) => copy(item, label, mode, depth + 1, seen))
113-
: Array.from(value, (item) => copy(item, label, mode, depth + 1, seen) ?? null)
114-
if (mode === "program") {
123+
if (plain) {
124+
const copied = new ProgramArray(value.map((item) => copy(item, label, mode, depth + 1, seen)))
115125
for (const [key, item] of Object.entries(value)) {
116-
if (Object.hasOwn(copied, key)) continue
117-
define(copied, key, copy(item, label, mode, depth + 1, seen))
126+
if (parseArrayIndex(key) === undefined) set(copied, key, copy(item, label, mode, depth + 1, seen))
118127
}
128+
seen.delete(value)
129+
return copied
119130
}
131+
const copied = Array.from(value, (item) => copy(item, label, mode, depth + 1, seen) ?? null)
120132
seen.delete(value)
121133
return copied
122134
}
@@ -126,7 +138,13 @@ const copy = (value: unknown, label: string, mode: Mode, depth: number, seen: Se
126138
throw new ToolRuntimeError("InvalidDataValue", `${label} must contain plain objects only.`)
127139
}
128140

129-
const copied: SafeObject = plain ? (Object.create(null) as SafeObject) : {}
141+
if (plain) {
142+
const copied = new ProgramObject()
143+
for (const [key, item] of Object.entries(value)) set(copied, key, copy(item, label, mode, depth + 1, seen))
144+
seen.delete(value)
145+
return copied
146+
}
147+
const copied: Record<string, unknown> = {}
130148
for (const [key, item] of Object.entries(value)) {
131149
const next = copy(item, label, mode, depth + 1, seen)
132150
if (next === undefined && mode === "json") continue
@@ -136,8 +154,8 @@ const copy = (value: unknown, label: string, mode: Mode, depth: number, seen: Se
136154
return copied
137155
}
138156

139-
// Own data property regardless of the target's prototype, so a "__proto__" key on a host object or
140-
// array never reaches the Object.prototype setter.
157+
// Own data property regardless of the target's prototype, so a "__proto__" key on a host object
158+
// never reaches the Object.prototype setter.
141159
const define = (target: object, key: string, value: unknown): void => {
142160
Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true })
143161
}

‎packages/codemode/src/interpreter/errors.ts‎

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
import { Effect } from "effect"
22
import type { Diagnostic } from "../codemode.js"
33
import { ToolError } from "../tool-error.js"
4-
import { type SafeObject, toData, ToolRuntimeError } from "../data.js"
4+
import { toData, ToolRuntimeError } from "../data.js"
55
import { type AstNode, formatLocation, InterpreterRuntimeError, ProgramThrow, sourceLocation } from "./model.js"
66
import { containsRuntimeReference } from "./references.js"
77
import { type HostCall, HostFunction } from "./host.js"
8+
import { get, ProgramError, ProgramObject } from "./objects.js"
89
import { type Runner } from "./runner.js"
910
import {
1011
coerceToString,
@@ -44,12 +45,8 @@ export const normalizeError = (error: unknown): Diagnostic => {
4445
message = "a non-data value"
4546
} else if (typeof value === "string") {
4647
message = value
47-
} else if (
48-
value !== null &&
49-
typeof value === "object" &&
50-
typeof (value as { message?: unknown }).message === "string"
51-
) {
52-
message = (value as { message: string }).message
48+
} else if (value instanceof ProgramObject && typeof get(value, "message") === "string") {
49+
message = get(value, "message") as string
5350
} else {
5451
try {
5552
message = JSON.stringify(toData(value, "Thrown value")) ?? String(value)
@@ -87,14 +84,14 @@ export const caughtErrorValue = (thrown: unknown): unknown => {
8784
return createErrorValue(name, normalizeError(thrown).message)
8885
}
8986

90-
const constructErrorValue = (name: string, args: Array<unknown>): SafeObject =>
87+
const constructErrorValue = (name: string, args: Array<unknown>): ProgramError =>
9188
createErrorValue(name, args[0] === undefined ? "" : coerceToString(args[0]))
9289

9390
const constructAggregateErrorValue = <R>(
9491
runner: Runner<R>,
9592
args: Array<unknown>,
9693
node: AstNode,
97-
): Effect.Effect<SafeObject, unknown, R> =>
94+
): Effect.Effect<ProgramError, unknown, R> =>
9895
Effect.gen(function* () {
9996
const cursor = yield* runner.syncIterator(args[0], node)
10097
if (cursor === undefined) {

0 commit comments

Comments
 (0)