GeezerVison is showing github.com — feat(codemode): honor program valueOf and toString in operators and c… · Parad0X/opencode@5256f30
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: packages/codemode/interpreter-support.md +15-9Lines changed: 15 additions & 9 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -224,20 +224,25 @@ ultimate source of truth. Upstream test262 files run verbatim from `test/test262 | 224 | 224 | - [x] Coercion helpers and template interpolation accept functions and namespaces: `String(fn)` and `${fn}` give | 225 | 225 | `"[object Function]"` rather than the source text, `isNaN(fn)` is `true`. | 226 | 226 | - [x] `==` and `!=` follow IsLooselyEqual: objects (including functions and tool references) compare by identity, a | 227 | | - nullish operand never coerces the other side, and a data object facing a primitive coerces through its built-in | 228 | | - primitive form (`fn == null` is `false`, `fn == fn` is `true`, `[1] == 1` and `[1, 2] == "1,2"` are `true`). | | 227 | + nullish operand never coerces the other side, and a data object facing a primitive converts through its own | | 228 | + `valueOf`/`toString` (default hint) (`fn == null` is `false`, `fn == fn` is `true`, `[1] == 1` and `[1, 2] == "1,2"` are `true`). | 229 | 229 | `switch` matches cases with `===`, so `switch (fn) { case fn: }` selects, and `Object.is` compares any two | 230 | 230 | values. Operators inspect only their direct operands, so `rows == null` on a large array costs the same as | 231 | 231 | `rows === null`, and an object merely holding a function inside (`[fn] + ""`, `-[fn]`) coerces like any other | 232 | 232 | data object (`"[object Function]"`, `NaN`). | 233 | 233 | - [ ] Coercing a function, promise, generator, or tool reference itself: `fn + ""`, `-fn`, `fn++`, and `fn == 1` | 234 | 234 | throw `TypeError: Binary operators require data values.` (or the unary/update form) where JavaScript would use | 235 | 235 | the source text or `NaN`. | 236 | | -- [ ] ToPrimitive on program objects: operators, `Number`/`String`, `Error(message)`, `parseInt` radix, multi-argument | 237 | | - `Date` construction and `Date.UTC`, and numeric built-in arguments (`Math.max`, `at`, `indexOf` start) should call | 238 | | - the object's own `valueOf`/`toString` in spec order and surface their throws. Today they use the built-in form | 239 | | - (`NaN`, `"[object Object]"`) and ignore own methods. Date setters and one-argument `Date` construction already | 240 | | - follow ToPrimitive. | | 236 | +- [x] ToPrimitive on program objects: `+ - * / % **`, the relational and bitwise operators, unary `+ - ~`, `++`/`--`, | | 237 | + compound assignment, `${x}`, `Number`/`String`/`isNaN`/`isFinite`, `parseInt`/`parseFloat` (text and radix), | | 238 | + `Math.*` arguments, `Error(message)`, and `Array.prototype.join`/`toString` elements call the object's own | | 239 | + `valueOf`/`toString` in spec order (both operands left then right, `+` with the default hint) and surface their | | 240 | + throws: `{ valueOf() { return 7 } } * 2` is `14`, `` `${{ toString() { return "x" } }}` `` is `"x"`, and | | 241 | + `[1, 2]` with `arr.toString = () => "x"` makes `arr + ""` `"x"`. Dates keep their `Symbol.toPrimitive` | | 242 | + behavior (`date + 1` concatenates, `date - date` subtracts). | | 243 | +- [ ] ToPrimitive elsewhere: multi-argument `Date` construction, `Date.UTC`, `Error.prototype.toString` on an object | | 244 | + `message`, and numeric built-in arguments outside `Math` (`at`, `indexOf` start, `toFixed` digits) still use the | | 245 | + built-in form (`NaN`, `"[object Object]"`) and ignore own methods. | 241 | 246 | - [x] Property keys follow ToPropertyKey: `x[null]`, `x[true]`, and objects (via their built-in string form) become | 242 | 247 | string keys. | 243 | 248 |
| @@ -375,8 +380,9 @@ reject }` object. | 375 | 380 | `flat(1.9)`, `with(1.5, v)`, `Math.max("3", "2")`, `parseInt("11", "2")`, `(1.5).toFixed("2")`, | 376 | 381 | `String.fromCharCode("65")`, and the Uint8Array equivalents. `join(sep)` and `JSON.parse(text)` apply ToString | 377 | 382 | (`join(null)` is `"1null2"`, `JSON.parse(123)` is `123`). `Array.from({ length: "2" })` applies ToLength; a | 378 | | - promise source still throws with an `await` hint rather than JS's silent `[]`. A program object's own | 379 | | - `valueOf`/`toString` is not consulted yet (see ToPrimitive above). | | 383 | + promise source still throws with an `await` hint rather than JS's silent `[]`. `join`, `Math.*`, and | | 384 | + `parseInt` consult a program object's own `valueOf`/`toString`; the array and number methods do not yet (see | | 385 | + ToPrimitive above). | 380 | 386 |
| 381 | 387 | ## Strings | 382 | 388 |
| |
Collapse file Copy file name to clipboardExpand all lines: packages/codemode/src/interpreter/callback.ts +26-8Lines changed: 26 additions & 8 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -13,7 +13,7 @@ import { | 13 | 13 | type Cursor, | 14 | 14 | type Value, | 15 | 15 | } from "./objects.js" | 16 | | -import { typeofValue } from "./references.js" | | 16 | +import { isOpaque, typeofValue } from "./references.js" | 17 | 17 |
| 18 | 18 | /** IteratorClose: a consumer failure closes the iterator and wins over any close failure, except that a generator's | 19 | 19 | * return() is a return completion, so a failing close wins over it, as after `break`. */ | @@ -31,16 +31,15 @@ export const preserveConsumerError = <A, R>( | 31 | 31 | }) | 32 | 32 | }) | 33 | 33 |
| | 34 | +export type Hint = "number" | "string" | "default" | | 35 | + | 34 | 36 | /** | 35 | 37 | * ToPrimitive: calls `valueOf`/`toString` in hint order and returns the first primitive result. Dates treat the | 36 | | - * default hint as "string", like their `Symbol.toPrimitive`. | | 38 | + * default hint as "string", like their `Symbol.toPrimitive`. Opaque values (functions, promises, generators, tool | | 39 | + * references) pass through unchanged so callers reject or describe them in their built-in form. | 37 | 40 | */ | 38 | | -export const toPrimitive = <R>( | 39 | | - ctx: Interpreter<R>, | 40 | | - value: Value, | 41 | | - hint: "number" | "string" | "default", | 42 | | -): Effect.Effect<Value, unknown, R> => { | 43 | | - if (!(value instanceof Obj)) return Effect.succeed(value) | | 41 | +export const toPrimitive = <R>(ctx: Interpreter<R>, value: Value, hint: Hint): Effect.Effect<Value, unknown, R> => { | | 42 | + if (!(value instanceof Obj) || isOpaque(value)) return Effect.succeed(value) | 44 | 43 | const asString = hint === "string" || (hint === "default" && value instanceof DateObj) | 45 | 44 | const order = asString ? ["toString", "valueOf"] : ["valueOf", "toString"] | 46 | 45 | return Effect.gen(function* () { | @@ -67,6 +66,25 @@ export const toPrimitiveString = <R>(ctx: Interpreter<R>, value: Value) => | 67 | 66 | export const toPrimitiveNumber = <R>(ctx: Interpreter<R>, value: Value) => | 68 | 67 | Effect.map(toPrimitive(ctx, value, "number"), coerceToNumber) | 69 | 68 |
| | 69 | +/** | | 70 | + * Runs a synchronous native body on its arguments after ToPrimitive, in order, with one hint for all positions or | | 71 | + * one per position. Primitive arguments skip the Effect entirely. | | 72 | + */ | | 73 | +export const withPrimitives = <R>( | | 74 | + ctx: Interpreter<R>, | | 75 | + hints: Hint | ReadonlyArray<Hint>, | | 76 | + values: Array<Value>, | | 77 | + body: (primitives: Array<Value>) => Value, | | 78 | +): Value | Effect.Effect<Value, unknown, R> => { | | 79 | + if (!values.some((value) => value instanceof Obj)) return body(values) | | 80 | + return Effect.map( | | 81 | + Effect.forEach(values, (value, index) => | | 82 | + toPrimitive(ctx, value, typeof hints === "string" ? hints : hints[index]!), | | 83 | + ), | | 84 | + body, | | 85 | + ) | | 86 | +} | | 87 | + | 70 | 88 | // The single acceptance list for callbacks: collections, sort, string replacers, | 71 | 89 | // Array.from mappers, and promise reactions all admit exactly these callables. | 72 | 90 | // Admission means dispatchable, not necessarily invocable: new-requiring | |
Collapse file Copy file name to clipboardExpand all lines: packages/codemode/src/interpreter/errors.ts +6-4Lines changed: 6 additions & 4 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -20,6 +20,7 @@ import { | 20 | 20 | type Value, | 21 | 21 | } from "./objects.js" | 22 | 22 | import type { Interpreter } from "./interpreter.js" | | 23 | +import { toPrimitiveString } from "./callback.js" | 23 | 24 | import { formatValue } from "../stdlib/console.js" | 24 | 25 |
| 25 | 26 | export const normalizeError = (error: unknown): Diagnostic => { | @@ -139,14 +140,13 @@ const constructAggregateErrorValue = <R>( | 139 | 140 | proto: Obj, | 140 | 141 | ): Effect.Effect<ErrorObj, unknown, R> => | 141 | 142 | Effect.gen(function* () { | | 143 | + const message = args[1] === undefined ? "" : yield* toPrimitiveString(ctx, args[1]) | 142 | 144 | const cursor = yield* ctx.iterate(args[0]) | 143 | 145 | if (cursor === undefined) throw typeError("new AggregateError(...) expects a synchronous iterable of errors.") | 144 | 146 | const errors: Array<Value> = [] | 145 | 147 | while (true) { | 146 | 148 | const step = yield* cursor.next | 147 | | - if (step.done) { | 148 | | - return createAggregateErrorValue(ctx, errors, args[1] === undefined ? "" : coerceToString(args[1]), proto) | 149 | | - } | | 149 | + if (step.done) return createAggregateErrorValue(ctx, errors, message, proto) | 150 | 150 | errors.push(step.value) | 151 | 151 | } | 152 | 152 | }) | @@ -160,7 +160,9 @@ export const errorGlobal = <R>(type: ErrorType, ctx: Interpreter<R>) => { | 160 | 160 | const created = | 161 | 161 | type === "AggregateError" | 162 | 162 | ? constructAggregateErrorValue(ctx, args, proto) | 163 | | - : Effect.sync(() => createErrorValue(proto, args[0] === undefined ? undefined : coerceToString(args[0]))) | | 163 | + : Effect.map(args[0] === undefined ? Effect.undefined : toPrimitiveString(ctx, args[0]), (message) => | | 164 | + createErrorValue(proto, message), | | 165 | + ) | 164 | 166 | // ES2022 `new Error(message, { cause })`: installed only when the options object has the property at all. | 165 | 167 | const options = args[type === "AggregateError" ? 2 : 1] | 166 | 168 | if (!(options instanceof Obj) || !has(options, "cause")) return created | |
|