GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(codemode): bind this and arguments in functions, add Function.pr… · Parad0X/opencode@5626212

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages/codemode
    • interpreter-support.md
    • src
      • data.ts
      • interpreter
        • callback.ts
        • globals.ts
        • interpreter.ts
        • model.ts
        • objects.ts
      • stdlib
        • json.ts
    • test
      • json-callbacks-test262.test.ts
      • new-expression.test.ts
      • parity.test.ts
      • stdlib.test.ts
      • test262
        • README.md
        • manifest.json
        • skipped.txt
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/codemode/interpreter-support.md‎

Copy file name to clipboardExpand all lines: packages/codemode/interpreter-support.md
+21-8Lines changed: 21 additions & 8 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -139,11 +139,24 @@ ultimate source of truth. Upstream test262 files run verbatim from `test/test262
139139
arrow function.
140140
- [x] Promise-returning string replacers are coerced synchronously to `"[object Promise]"`, like JavaScript; they are
141141
not automatically awaited.
142-
- [x] The optional `thisArg` of iteration methods is accepted and ignored: CodeMode functions have no `this`, so
143-
ignoring it matches JS arrow-function semantics exactly.
144-
- [ ] `this` in non-arrow CodeMode functions and callbacks.
142+
- [x] `this` in non-arrow functions is the call's receiver: `obj.m()` and `obj["m"]()` see `obj`, a bare or detached
143+
call (`f()`, `const m = obj.m; m()`, `(0, obj.m)()`) sees `undefined`, as in strict JS. Arrows read the enclosing
144+
function's `this`. Program code has no receiver, so top-level `this` is `undefined`, as in a module.
145+
- [x] `arguments` in non-arrow functions: an unmapped ordinary object with the call's arguments as indexed
146+
properties and a hidden `length`; iterable, so spread, `for...of`, and `Array.from` work. It is not an Array
147+
(`JSON.stringify` gives `{"0":1}`, `String` gives `[object Arguments]`). A parameter named `arguments` shadows
148+
it; arrows read the enclosing function's; it is only created for functions whose body mentions it. `callee`
149+
and `caller` are absent rather than poisoned.
150+
- [ ] Array methods on `arguments` and other array-likes (`Array.prototype.slice.call(arguments, 1)`); use
151+
`[...arguments]` or a rest parameter meanwhile.
152+
- [x] `Function.prototype.call`, `apply`, and `bind` on program functions and built-ins:
153+
`Array.prototype.push.call(arr, 1)`, `Math.max.apply(null, values)`, `fn.bind(obj, first)`. `apply` accepts an
154+
array, an array-like object (its `length` clamped and capped like `Array.from`), or `null`/`undefined`. A
155+
bound function is named `bound f`, has its remaining `length`, and is not constructible.
156+
- [x] `JSON.parse` revivers and `JSON.stringify` function replacers see the holder object as `this`.
157+
- [ ] The optional `thisArg` of iteration methods (`map`, `forEach`, `Map.prototype.forEach`, `Array.from`, …) is
158+
accepted but not yet passed as `this`; callbacks run with `this` undefined.
145159
- [ ] User-defined constructor calls.
146-
- [ ] `Function.prototype.call`, `apply`, and `bind` for CodeMode functions.
147160
- [ ] Classes and private fields.
148161
- [x] Functions are objects: they hold own properties (`fn.count = 1`), enumerate them, and expose read-only `name`
149162
and `length`. Names follow JavaScript's NamedEvaluation: declarations, named expressions, bindings,
@@ -178,7 +191,7 @@ ultimate source of truth. Upstream test262 files run verbatim from `test/test262
178191
yielded promises; mixed async request queues; sync and async `yield*` forwarding; malformed methods/results;
179192
and declaration, expression, and object-method forms with closure and parameter behavior. The adapted suite
180193
deliberately skips Test262 variants whose observation mechanism requires unsupported getter definitions,
181-
proxies, prototype inspection or mutation, non-arrow `this`, classes, or arbitrary symbols. It also skips tests
194+
proxies, prototype inspection or mutation, classes, or arbitrary symbols. It also skips tests
182195
asserting exact promise reaction-turn counts beyond the observable ordering guarantee documented below. These
183196
are interpreter-surface boundaries, not claims that the corresponding full Test262 families pass unchanged.
184197

@@ -269,7 +282,7 @@ reject }` object.
269282
- [x] Recursive assimilation of objects with an own callable `then` field across `Promise.resolve`, combinators,
270283
constructors, reactions, `finally`, `await`, and async returns. Thenable methods run deferred, receive
271284
first-call-wins resolve/reject functions, and ignore throws after settlement. Inherited/accessor `then` fields
272-
and a JavaScript `this` receiver remain outside the supported object/function model.
285+
remain outside the supported object model.
273286
- [x] Dotted tool names are canonicalized into namespace paths; a path can be both callable and a namespace, and the
274287
last tool supplied for a canonical path wins.
275288
- [x] Tool path segments may be named `constructor`, `prototype`, or `__proto__` because paths use inert Map keys.
@@ -419,9 +432,9 @@ reject }` object.
419432
- [x] `JSON.parse` and `JSON.stringify` for supported data objects.
420433
- [x] Numeric/string indentation for `JSON.stringify`.
421434
- [x] `JSON.parse` reviver callbacks, including postorder traversal, deletion through `undefined`, and root replacement.
422-
Revivers receive `(key, value)` but no `this` holder because CodeMode functions intentionally have no `this`.
435+
Revivers receive `(key, value)` with the holder as `this`.
423436
- [x] `JSON.stringify` function and array replacers. Function replacers receive `(key, value)` in preorder, including
424-
the root, but no `this` holder. Array replacers preserve requested property order, deduplicate names, coerce
437+
the root, with the holder as `this`. Array replacers preserve requested property order, deduplicate names, coerce
425438
number primitives, and ignore non-string/non-number entries. Primitive wrapper entries remain unsupported.
426439
- [x] Captured `console.log`, `console.info`, `console.debug`, `console.warn`, and `console.error`. An Error prints as
427440
`Error.prototype.toString` would show it (`Error: boom`), wherever it appears in the logged value.
Collapse file

‎packages/codemode/src/data.ts‎

Copy file name to clipboardExpand all lines: packages/codemode/src/data.ts
+2-2Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import { typeofValue } from "./interpreter/references.js"
2424

2525
export type Json = Schema.Json
2626

27-
type Replacer<R> = (args: Array<Value>) => Effect.Effect<Value, unknown, R>
27+
type Replacer<R> = (args: Array<Value>, holder: Obj) => Effect.Effect<Value, unknown, R>
2828

2929
/**
3030
* What `JSON.stringify` would serialize for a program value, as host JSON: `toJSON` is honored, functions and
@@ -60,7 +60,7 @@ const walk = <R>(
6060
const settled = raw instanceof PromiseObj ? yield* ctx.await(raw) : raw
6161
const toJSON = settled instanceof Obj ? get(settled, "toJSON") : undefined
6262
const own = toJSON instanceof Callable ? yield* ctx.call(toJSON, settled, [key]) : settled
63-
const value = replacer === undefined ? own : yield* replacer([key, own])
63+
const value = replacer === undefined ? own : yield* replacer([key, own], holder)
6464
if (value === undefined || typeofValue(value) === "function") return undefined
6565
if (typeof value === "number") return Number.isFinite(value) ? value : null
6666
if (value === null || typeof value === "string" || typeof value === "boolean") return value
Collapse file

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

Copy file name to clipboardExpand all lines: packages/codemode/src/interpreter/callback.ts
+2-2Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ export const applyCollectionCallback = <R>(
7878
ctx: Interpreter<R>,
7979
callback: Value,
8080
name: string,
81-
): ((args: Array<Value>) => Effect.Effect<Value, unknown, R>) => {
81+
): ((args: Array<Value>, thisValue?: Value) => Effect.Effect<Value, unknown, R>) => {
8282
if (!isSupportedCallback(callback)) {
8383
if (typeofValue(callback) === "function") {
8484
throw typeError(
@@ -87,5 +87,5 @@ export const applyCollectionCallback = <R>(
8787
}
8888
throw typeError(`${name} expects a function callback.`)
8989
}
90-
return (callbackArgs) => ctx.call(callback, undefined, callbackArgs)
90+
return (callbackArgs, thisValue) => ctx.call(callback, thisValue, callbackArgs)
9191
}
Collapse file

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

Copy file name to clipboardExpand all lines: packages/codemode/src/interpreter/globals.ts
+31-2Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { Effect } from "effect"
2-
import type { Value } from "./objects.js"
2+
import { Arr, Callable, coerceToInteger, coerceToString, get, Obj, type Value } from "./objects.js"
33
import { arrayGlobal } from "../stdlib/array.js"
44
import { textDecoderGlobal, textEncoderGlobal, uint8ArrayGlobal } from "../stdlib/bytes.js"
55
import { mapGlobal, setGlobal } from "../stdlib/collections.js"
@@ -19,8 +19,9 @@ import { base64Global, cryptoGlobal, structuredCloneGlobal } from "../stdlib/web
1919
import { ToolReference } from "../tool-runtime.js"
2020
import { errorGlobal } from "./errors.js"
2121
import { errorTypes } from "./intrinsics.js"
22-
import { constants, constructor, native } from "./native.js"
22+
import { constants, constructor, methods, native, receiver } from "./native.js"
2323
import { AsyncIteratorSymbol, IteratorSymbol, typeError } from "./model.js"
24+
import { checkArrayLength } from "./limits.js"
2425
import { generatorGlobals } from "./generators.js"
2526
import { promiseGlobal } from "./promises.js"
2627
import type { Interpreter } from "./interpreter.js"
@@ -31,6 +32,24 @@ const functionGlobal = <R>(ctx: Interpreter<R>) => {
3132
Effect.sync(() => {
3233
throw typeError("The Function constructor is not supported; write the function inline.")
3334
})
35+
const target = (thisValue: Value, method: string) => receiver(Callable, thisValue, `Function.prototype.${method}`)
36+
methods(ctx.builtins, ctx.builtins.Function, [
37+
["call", 1, (thisValue, args) => ctx.call(target(thisValue, "call"), args[0], args.slice(1))],
38+
["apply", 2, (thisValue, args) => ctx.call(target(thisValue, "apply"), args[0], listFromArrayLike(args[1]))],
39+
[
40+
"bind",
41+
1,
42+
(thisValue, args) => {
43+
const fn = target(thisValue, "bind")
44+
const bound = args.slice(1)
45+
return native<R>(ctx.builtins, {
46+
name: `bound ${coerceToString(get(fn, "name"))}`,
47+
length: Math.max(0, fn.length - bound.length),
48+
call: (_, rest) => ctx.call(fn, args[0], [...bound, ...rest]),
49+
})
50+
},
51+
],
52+
])
3453
return constructor<R>(ctx.builtins, ctx.builtins.Function, {
3554
name: "Function",
3655
length: 1,
@@ -39,6 +58,16 @@ const functionGlobal = <R>(ctx: Interpreter<R>) => {
3958
})
4059
}
4160

61+
// CreateListFromArrayLike: `apply` reads `length` and the indexed properties of any object.
62+
const listFromArrayLike = (value: Value): Array<Value> => {
63+
if (value === undefined || value === null) return []
64+
if (value instanceof Arr) return [...value.items]
65+
if (!(value instanceof Obj)) throw typeError("Function.prototype.apply expects an array-like argument list.")
66+
const length = Math.max(0, coerceToInteger(get(value, "length")))
67+
checkArrayLength(length)
68+
return Array.from({ length }, (_, index) => get(value, String(index)))
69+
}
70+
4271
const symbolGlobal = <R>(ctx: Interpreter<R>) => {
4372
const symbol = native<R>(ctx.builtins, {
4473
name: "Symbol",
Collapse file

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

Copy file name to clipboardExpand all lines: packages/codemode/src/interpreter/interpreter.ts
+38-4Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type {
2+
AnyNode,
23
ArrayExpression,
34
ArrayPattern,
45
AssignmentPattern,
@@ -81,6 +82,7 @@ import {
8182
keys,
8283
Native,
8384
parseArrayIndex,
85+
Arguments,
8486
Arr,
8587
Fn,
8688
GeneratorObj,
@@ -178,6 +180,24 @@ const collectPatternNames = (pattern: Pattern, out: Array<string> = []): Array<s
178180
return out
179181
}
180182

183+
// Whether a function body (or a parameter default) reads `arguments`, looking through arrows but not nested
184+
// functions, which own theirs. Memoized so the object is only built for calls that can observe it.
185+
const argumentsUse = new WeakMap<Fn["body"], boolean>()
186+
const usesArguments = (fn: Fn): boolean => {
187+
const cached = argumentsUse.get(fn.body)
188+
if (cached !== undefined) return cached
189+
const found = [...fn.parameters, fn.body].some(function visit(node: AnyNode | null): boolean {
190+
if (node === null || typeof node !== "object") return false
191+
if (node.type === "Identifier") return node.name === "arguments"
192+
if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression") return false
193+
return Object.values(node).some((child) =>
194+
Array.isArray(child) ? child.some((item) => visit(item)) : visit(child as AnyNode | null),
195+
)
196+
})
197+
argumentsUse.set(fn.body, found)
198+
return found
199+
}
200+
181201
// `var` names declared anywhere in a function body except inside nested functions, which own theirs.
182202
// Memoized per body: a function's var names never change, and hoisting runs on every call.
183203
const varNames = new WeakMap<ReadonlyArray<Statement | ModuleDeclaration>, ReadonlyArray<string>>()
@@ -287,7 +307,8 @@ export class Interpreter<R> {
287307
this.pending = options.pending
288308
this.builtins = options.builtins
289309
this.logs = options.logs ?? []
290-
const globalScope = new Map<string, Binding>()
310+
// Program code has no receiver: top-level `this` is undefined, as in a module.
311+
const globalScope = new Map<string, Binding>([["this", { mutable: false, value: undefined }]])
291312
// Calling back into the program never reads frame state, so any frame serves; the root is always alive.
292313
this.root = new Frame(this, new ScopeStack([globalScope]))
293314
for (const [name, value] of [...globals(this), ...(options.globals?.(this) ?? [])]) {
@@ -468,6 +489,7 @@ class Frame<R> {
468489
this.scopes.capture(),
469490
node.async,
470491
node.generator,
492+
node.type === "ArrowFunctionExpression",
471493
)
472494
// Each generator function gets its own prototype, so `g() instanceof g` holds as in JS.
473495
if (node.generator)
@@ -1257,6 +1279,8 @@ class Frame<R> {
12571279
}
12581280
case "Identifier":
12591281
return Effect.sync(() => this.scopes.get(node.name, node))
1282+
case "ThisExpression":
1283+
return Effect.sync(() => this.scopes.get("this", node))
12601284
case "BinaryExpression":
12611285
return this.evaluateBinaryExpression(node)
12621286
case "LogicalExpression":
@@ -1622,7 +1646,7 @@ class Frame<R> {
16221646
}
16231647
return yield* self.createToolCallPromise(callable.path, args)
16241648
}
1625-
if (callable instanceof Fn) return yield* self.invokeFunction(callable, args, node)
1649+
if (callable instanceof Fn) return yield* self.invokeFunction(callable, thisValue, args, node)
16261650
if (callable instanceof Native) {
16271651
return yield* self.native(() => (callable as Native<R>).call(thisValue, args), node)
16281652
}
@@ -1664,14 +1688,24 @@ class Frame<R> {
16641688
}
16651689

16661690
// A callback invoked by a built-in runs below the call that invoked the built-in, so the deeper of the two counts.
1667-
invokeFunction(fn: Fn, args: Array<Value>, node?: AstNode): Effect.Effect<Value, unknown, R> {
1691+
invokeFunction(fn: Fn, thisValue: Value, args: Array<Value>, node?: AstNode): Effect.Effect<Value, unknown, R> {
16681692
const self = this
16691693
return Effect.flatMap(CallSite, (site) => {
16701694
const depth = Math.max(self.depth, site.depth) + 1
16711695
if (depth > MAX_CALL_DEPTH) throw rangeError("Maximum call stack size exceeded", node)
16721696
const invocation = new Frame(this.ctx, new ScopeStack([...fn.capturedScopes, new Map()]), depth)
1673-
// Seed all parameters first so defaults cannot fall through to same-named outer bindings.
16741697
const paramScope = invocation.scopes.current()
1698+
// `this` and `arguments` are scope bindings so arrows resolve them lexically; a parameter named
1699+
// `arguments` shadows the object, as in JS.
1700+
if (!fn.arrow) paramScope.set("this", { mutable: false, value: thisValue, initialized: true })
1701+
if (!fn.arrow && usesArguments(fn)) {
1702+
paramScope.set("arguments", {
1703+
mutable: true,
1704+
value: new Arguments(self.ctx.builtins.Object, args),
1705+
initialized: true,
1706+
})
1707+
}
1708+
// Seed all parameters first so defaults cannot fall through to same-named outer bindings.
16751709
for (const parameter of fn.parameters) {
16761710
for (const name of collectPatternNames(parameter)) {
16771711
paramScope.set(name, { mutable: true, value: undefined, initialized: false })
Collapse file

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

Copy file name to clipboardExpand all lines: packages/codemode/src/interpreter/model.ts
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ export const uriError = failure("URIError")
7272

7373
// Orient the agent rather than enumerate JavaScript; interpreter-support.md is the full matrix.
7474
export const supportedSyntaxMessage =
75-
"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, this, getters/setters, BigInt, and custom Symbols. Use plain functions and data objects instead."
75+
"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."
7676

7777
export const unsupportedSyntax = (kind: string, node: AstNode): PendingThrow =>
7878
new PendingThrow(
Collapse file

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

Copy file name to clipboardExpand all lines: packages/codemode/src/interpreter/objects.ts
+22-1Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,11 @@ export abstract class Opaque extends Obj {
149149

150150
export abstract class Callable extends Opaque {
151151
override readonly tag = "Function"
152-
constructor(proto: Obj, name: string, length: number) {
152+
constructor(
153+
proto: Obj,
154+
name: string,
155+
readonly length: number,
156+
) {
153157
super(proto)
154158
define(this, "length", length, readonly)
155159
define(this, "name", name, readonly)
@@ -168,12 +172,29 @@ export class Fn extends Callable {
168172
readonly capturedScopes: Array<Map<string, Binding>>,
169173
readonly async: boolean,
170174
readonly generator: boolean,
175+
/** Arrows have no `this` or `arguments` of their own; they read the enclosing function's. */
176+
readonly arrow: boolean,
171177
) {
172178
const optional = parameters.findIndex((p) => p.type === "AssignmentPattern" || p.type === "RestElement")
173179
super(proto, name, optional === -1 ? parameters.length : optional)
174180
}
175181
}
176182

183+
/** The strict `arguments` object: an ordinary object with indexed own properties and a hidden `length`. */
184+
export class Arguments extends Obj {
185+
override readonly tag = "Arguments"
186+
constructor(proto: Obj, args: Array<Value>) {
187+
super(proto)
188+
args.forEach((arg, index) => define(this, String(index), arg))
189+
define(this, "length", args.length, hidden)
190+
}
191+
override iterator() {
192+
return keys(this)
193+
.map((key) => get(this, key))
194+
.values()
195+
}
196+
}
197+
177198
export type NativeCall<R> = (thisValue: Value, args: Array<Value>) => Effect.Effect<Value, unknown, R>
178199
export type NativeConstruct<R> = (args: Array<Value>, newTarget: Callable) => Effect.Effect<Value, unknown, R>
179200

Collapse file

‎packages/codemode/src/stdlib/json.ts‎

Copy file name to clipboardExpand all lines: packages/codemode/src/stdlib/json.ts
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ const parse = <R>(ctx: Interpreter<R>, args: Array<Value>): Effect.Effect<Value,
4040
else set(value, name, revived)
4141
}
4242
}
43-
return yield* apply([key, value])
43+
return yield* apply([key, value], holder)
4444
})
4545
return visit(record(ctx.builtins.Object, { "": parsed }), "")
4646
}
Collapse file

‎packages/codemode/test/json-callbacks-test262.test.ts‎

Copy file name to clipboardExpand all lines: packages/codemode/test/json-callbacks-test262.test.ts
+8-5Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -210,11 +210,14 @@ describe("Test262 JSON.stringify replacer adaptations", () => {
210210
})
211211

212212
describe("CodeMode JSON callback boundaries", () => {
213-
test("this remains unsupported rather than exposing callback holders", async () => {
214-
const result = await Effect.runPromise(
215-
CodeMode.execute({ code: `return JSON.parse("1", function (key, item) { return this })`, tools: {} }),
216-
)
217-
expect(result).toMatchObject({ ok: false, error: { kind: "UnsupportedSyntax" } })
213+
test("revivers and replacers see the holder as this", async () => {
214+
expect(
215+
await value(`
216+
const revived = JSON.parse('{"a":{"b":1}}', function (key, item) { return key === "b" ? this.b + 1 : item })
217+
const text = JSON.stringify({ a: 1, b: 2 }, function (key, item) { return key === "a" ? this.b : item })
218+
return [revived, text]
219+
`),
220+
).toEqual([{ a: { b: 2 } }, '{"a":2,"b":2}'])
218221
})
219222

220223
test("prototype-named keys parse as own data and reach the reviver", async () => {
Collapse file

‎packages/codemode/test/new-expression.test.ts‎

Copy file name to clipboardExpand all lines: packages/codemode/test/new-expression.test.ts
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,6 @@ describe("new on a non-constructible callee", () => {
7777
expect(failure.message).toStartWith(
7878
"SyntaxError: Syntax 'ClassDeclaration' is not supported. This is a restricted JavaScript-like language. Supported: ",
7979
)
80-
expect(failure.message).toContain("Unsupported: classes, this, getters/setters, BigInt, and custom Symbols.")
80+
expect(failure.message).toContain("Unsupported: classes, getters/setters, BigInt, and custom Symbols.")
8181
})
8282
})

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.