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): honor program valueOf and toString in operators and c… · Parad0X/opencode@5256f30

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages/codemode
    • interpreter-support.md
    • src
      • interpreter
        • callback.ts
        • errors.ts
        • interpreter.ts
      • stdlib
        • array.ts
        • math.ts
        • number.ts
        • value.ts
    • test
      • parity.test.ts
      • test262
        • manifest.json
        • skipped.txt
      • tool-paths.test.ts
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
+15-9Lines changed: 15 additions & 9 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -224,20 +224,25 @@ ultimate source of truth. Upstream test262 files run verbatim from `test/test262
224224
- [x] Coercion helpers and template interpolation accept functions and namespaces: `String(fn)` and `${fn}` give
225225
`"[object Function]"` rather than the source text, `isNaN(fn)` is `true`.
226226
- [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`).
229229
`switch` matches cases with `===`, so `switch (fn) { case fn: }` selects, and `Object.is` compares any two
230230
values. Operators inspect only their direct operands, so `rows == null` on a large array costs the same as
231231
`rows === null`, and an object merely holding a function inside (`[fn] + ""`, `-[fn]`) coerces like any other
232232
data object (`"[object Function]"`, `NaN`).
233233
- [ ] Coercing a function, promise, generator, or tool reference itself: `fn + ""`, `-fn`, `fn++`, and `fn == 1`
234234
throw `TypeError: Binary operators require data values.` (or the unary/update form) where JavaScript would use
235235
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.
241246
- [x] Property keys follow ToPropertyKey: `x[null]`, `x[true]`, and objects (via their built-in string form) become
242247
string keys.
243248

@@ -375,8 +380,9 @@ reject }` object.
375380
`flat(1.9)`, `with(1.5, v)`, `Math.max("3", "2")`, `parseInt("11", "2")`, `(1.5).toFixed("2")`,
376381
`String.fromCharCode("65")`, and the Uint8Array equivalents. `join(sep)` and `JSON.parse(text)` apply ToString
377382
(`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).
380386

381387
## Strings
382388

Collapse file

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

Copy file name to clipboardExpand all lines: packages/codemode/src/interpreter/callback.ts
+26-8Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import {
1313
type Cursor,
1414
type Value,
1515
} from "./objects.js"
16-
import { typeofValue } from "./references.js"
16+
import { isOpaque, typeofValue } from "./references.js"
1717

1818
/** IteratorClose: a consumer failure closes the iterator and wins over any close failure, except that a generator's
1919
* return() is a return completion, so a failing close wins over it, as after `break`. */
@@ -31,16 +31,15 @@ export const preserveConsumerError = <A, R>(
3131
})
3232
})
3333

34+
export type Hint = "number" | "string" | "default"
35+
3436
/**
3537
* 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.
3740
*/
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)
4443
const asString = hint === "string" || (hint === "default" && value instanceof DateObj)
4544
const order = asString ? ["toString", "valueOf"] : ["valueOf", "toString"]
4645
return Effect.gen(function* () {
@@ -67,6 +66,25 @@ export const toPrimitiveString = <R>(ctx: Interpreter<R>, value: Value) =>
6766
export const toPrimitiveNumber = <R>(ctx: Interpreter<R>, value: Value) =>
6867
Effect.map(toPrimitive(ctx, value, "number"), coerceToNumber)
6968

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+
7088
// The single acceptance list for callbacks: collections, sort, string replacers,
7189
// Array.from mappers, and promise reactions all admit exactly these callables.
7290
// Admission means dispatchable, not necessarily invocable: new-requiring
Collapse file

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

Copy file name to clipboardExpand all lines: packages/codemode/src/interpreter/errors.ts
+6-4Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import {
2020
type Value,
2121
} from "./objects.js"
2222
import type { Interpreter } from "./interpreter.js"
23+
import { toPrimitiveString } from "./callback.js"
2324
import { formatValue } from "../stdlib/console.js"
2425

2526
export const normalizeError = (error: unknown): Diagnostic => {
@@ -139,14 +140,13 @@ const constructAggregateErrorValue = <R>(
139140
proto: Obj,
140141
): Effect.Effect<ErrorObj, unknown, R> =>
141142
Effect.gen(function* () {
143+
const message = args[1] === undefined ? "" : yield* toPrimitiveString(ctx, args[1])
142144
const cursor = yield* ctx.iterate(args[0])
143145
if (cursor === undefined) throw typeError("new AggregateError(...) expects a synchronous iterable of errors.")
144146
const errors: Array<Value> = []
145147
while (true) {
146148
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)
150150
errors.push(step.value)
151151
}
152152
})
@@ -160,7 +160,9 @@ export const errorGlobal = <R>(type: ErrorType, ctx: Interpreter<R>) => {
160160
const created =
161161
type === "AggregateError"
162162
? 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+
)
164166
// ES2022 `new Error(message, { cause })`: installed only when the options object has the property at all.
165167
const options = args[type === "AggregateError" ? 2 : 1]
166168
if (!(options instanceof Obj) || !has(options, "cause")) return created

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.