From 4cc9b90f273ec8476878cd21d68d848936c4d550 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Mon, 21 Sep 2026 15:35:11 -0500 Subject: [PATCH] fix(codemode): add Promise.try and surface a failing iterator close on generator return (#50419) --- packages/codemode/interpreter-support.md | 8 ++-- packages/codemode/src/interpreter/callback.ts | 39 ++++++++++++------- .../codemode/src/interpreter/interpreter.ts | 8 ++-- packages/codemode/src/interpreter/promises.ts | 12 +++++- packages/codemode/src/stdlib/array.ts | 4 +- packages/codemode/src/stdlib/collections.ts | 6 +-- packages/codemode/src/stdlib/math.ts | 2 +- packages/codemode/src/stdlib/object.ts | 2 +- packages/codemode/src/stdlib/url.ts | 4 +- .../codemode/test/generator-test262.test.ts | 23 +++++++++++ packages/codemode/test/promise.test.ts | 22 ++++++++++- packages/codemode/test/test262/skipped.txt | 4 -- 12 files changed, 97 insertions(+), 37 deletions(-) diff --git a/packages/codemode/interpreter-support.md b/packages/codemode/interpreter-support.md index a4be9bb4be5..059e0e00db0 100644 --- a/packages/codemode/interpreter-support.md +++ b/packages/codemode/interpreter-support.md @@ -87,7 +87,6 @@ ultimate source of truth. Upstream test262 files run verbatim from `test/test262 - [x] Destructuring reads through the prototype chain like member access: `const { constructor } = error` and `const { slice } = values` find the inherited built-in. - [ ] Member expressions as `for...in` targets (`for (x.y in obj)`). -- [ ] `IteratorClose` during destructuring should throw a `TypeError` when `return()` yields a non-object. ## Statements and control flow @@ -162,7 +161,8 @@ ultimate source of truth. Upstream test262 files run verbatim from `test/test262 rejected by every synchronous consumer. - [x] Synchronous iterator acquisition and result validation follow `IteratorClose` boundaries: consumer errors and intentional early stops invoke `return()`, acquisition/`next()` failures do not, and an original consumer error - wins over a cleanup failure. Async iterator consumption remains limited to `for await...of` and async `yield*`. + wins over a cleanup failure. A generator's `return()` is an intentional stop, so a `return()` that throws or + yields a non-object surfaces from it as a `TypeError`. Async iterator consumption remains limited to `for await...of` and async `yield*`. - [x] Portable generator protocol coverage is adapted from pinned Test262 cases for suspended-start, suspended-yield, and completed states; sync and async `next`/`return`/`throw`; finally yields and completion overrides; rejected yielded promises; mixed async request queues; sync and async `yield*` forwarding; malformed methods/results; @@ -239,7 +239,9 @@ ultimate source of truth. Upstream test262 files run verbatim from `test/test262 accepted, including `.then`/`.catch` handlers and collection callbacks, and vanish at the data boundary like any function. - [x] `Promise.withResolvers()`: the same promise and resolver callables as the constructor, as a `{ promise, resolve, - reject }` object. + reject }` object. +- [x] `Promise.try(fn, ...args)`: calls `fn` synchronously; a throw rejects, a return fulfils, and a returned promise or + 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 diff --git a/packages/codemode/src/interpreter/callback.ts b/packages/codemode/src/interpreter/callback.ts index 051dbfdf1a6..df2266b5c6c 100644 --- a/packages/codemode/src/interpreter/callback.ts +++ b/packages/codemode/src/interpreter/callback.ts @@ -1,24 +1,35 @@ -import { Effect, Exit } from "effect" +import { Cause, Effect, Exit } from "effect" import type { Interpreter } from "./interpreter.js" import { primitivePrototype } from "./intrinsics.js" -import { typeError } from "./model.js" -import { Callable, get, Native, DateObj, Obj, coerceToNumber, coerceToString, type Value } from "./objects.js" +import { GeneratorReturn, typeError } from "./model.js" +import { + Callable, + get, + Native, + DateObj, + Obj, + coerceToNumber, + coerceToString, + type Cursor, + type Value, +} from "./objects.js" import { typeofValue } from "./references.js" -export type IteratorCursor = { - readonly next: Effect.Effect<{ readonly done: boolean; readonly value: Value }, unknown, R> - readonly close: Effect.Effect -} - +/** IteratorClose: a consumer failure closes the iterator and wins over any close failure, except that a generator's + * return() is a return completion, so a failing close wins over it, as after `break`. */ export const preserveConsumerError = ( - cursor: IteratorCursor, + close: Cursor["close"], effect: Effect.Effect, ): Effect.Effect => - Effect.flatMap(Effect.exit(effect), (exit) => - Exit.isSuccess(exit) - ? Effect.succeed(exit.value) - : Effect.andThen(Effect.exit(cursor.close), Effect.failCause(exit.cause)), - ) + Effect.flatMap(Effect.exit(effect), (exit) => { + if (Exit.isSuccess(exit)) return Effect.succeed(exit.value) + return Effect.flatMap(Effect.exit(close), (closed) => { + if (!Exit.isSuccess(closed) && Cause.squash(exit.cause) instanceof GeneratorReturn) { + return Effect.failCause(closed.cause) + } + return Effect.failCause(exit.cause) + }) + }) /** * ToPrimitive: calls `valueOf`/`toString` in hint order and returns the first primitive result. Dates treat the diff --git a/packages/codemode/src/interpreter/interpreter.ts b/packages/codemode/src/interpreter/interpreter.ts index 1ce1be234e5..03fd1035c14 100644 --- a/packages/codemode/src/interpreter/interpreter.ts +++ b/packages/codemode/src/interpreter/interpreter.ts @@ -713,10 +713,8 @@ class Frame { const bodyExit = yield* Effect.exit(evaluateBody(step.value)) if (!Exit.isSuccess(bodyExit)) { // Process interruption must remain prompt; user cleanup cannot extend a timeout. - if (!Cause.hasInterruptsOnly(bodyExit.cause)) { - yield* Effect.exit(close()) - } - return yield* Effect.failCause(bodyExit.cause) + if (Cause.hasInterruptsOnly(bodyExit.cause)) return yield* Effect.failCause(bodyExit.cause) + return yield* preserveConsumerError(close(), Effect.failCause(bodyExit.cause)) } const exit = loopExit(bodyExit.value, labels) if (exit !== undefined) { @@ -1223,7 +1221,7 @@ class Frame { return } const consumed = consume(element, step.done ? undefined : step.value, pattern) - yield* step.done ? consumed : preserveConsumerError(cursor, consumed) + yield* step.done ? consumed : preserveConsumerError(cursor.close, consumed) } if (!done) yield* cursor.close }) diff --git a/packages/codemode/src/interpreter/promises.ts b/packages/codemode/src/interpreter/promises.ts index 43a18097052..4a82667e076 100644 --- a/packages/codemode/src/interpreter/promises.ts +++ b/packages/codemode/src/interpreter/promises.ts @@ -136,7 +136,7 @@ export const resolvePromise = (ctx: Interpreter, value: Value): Effect.Eff return ctx.pending.createWithSelf((self) => resolvePromiseValue(ctx, value, self)) } -const promiseStatics = ["all", "allSettled", "race", "any", "resolve", "reject", "withResolvers"] as const +const promiseStatics = ["all", "allSettled", "race", "any", "resolve", "reject", "withResolvers", "try"] as const const invokePromiseMethod = ( ctx: Interpreter, @@ -154,6 +154,16 @@ const invokePromiseMethod = ( record(ctx.builtins.Object, { promise: made.promise, resolve: made.resolve, reject: made.reject }), ) } + if (name === "try") { + if (typeofValue(args[0]) !== "function") { + throw typeError(`Promise.try expects a function, received ${describeValue(args[0])}.`) + } + return Effect.flatMap(Effect.exit(ctx.call(args[0], undefined, args.slice(1))), (called) => { + if (Exit.isSuccess(called)) return resolvePromise(ctx, called.value) + if (Cause.hasInterruptsOnly(called.cause)) return Effect.failCause(called.cause) + return ctx.pending.create(Effect.fail(Cause.squash(called.cause))) + }) + } return ctx.pending.create( Effect.gen(function* () { diff --git a/packages/codemode/src/stdlib/array.ts b/packages/codemode/src/stdlib/array.ts index 658469740de..b8110568a7c 100644 --- a/packages/codemode/src/stdlib/array.ts +++ b/packages/codemode/src/stdlib/array.ts @@ -55,7 +55,9 @@ const arrayFrom = (ctx: Interpreter, args: Array): Effect.Effect(ctx: Interpreter, namespace: "Map" | "Object") => const step = yield* cursor.next if (step.done) return result const item = step.value - const key = yield* preserveConsumerError(cursor, apply([item, index])) + const key = yield* preserveConsumerError(cursor.close, apply([item, index])) const group = result.map.get(key) if (group === undefined) result.map.set(key, new Arr(builtins.Array, [item])) else (group as Arr).items.push(item) @@ -72,7 +72,7 @@ export const groupBy = (ctx: Interpreter, namespace: "Map" | "Object") => if (step.done) return result const item = step.value const key = yield* preserveConsumerError( - cursor, + cursor.close, Effect.flatMap(apply([item, index]), (value) => coerceGroupByPropertyKey(ctx, value)), ) const group = getOwn(result, key) @@ -95,7 +95,7 @@ const constructMap = (ctx: Interpreter, init: Value, proto: Obj) => { const step = yield* cursor.next if (step.done) return target yield* preserveConsumerError( - cursor, + cursor.close, Effect.sync(() => { if (!(step.value instanceof Obj)) { throw typeError("new Map(...) expects [key, value] pairs as entry objects.") diff --git a/packages/codemode/src/stdlib/math.ts b/packages/codemode/src/stdlib/math.ts index 4e84936802c..23f35d50a52 100644 --- a/packages/codemode/src/stdlib/math.ts +++ b/packages/codemode/src/stdlib/math.ts @@ -105,7 +105,7 @@ export const mathGlobal = (ctx: Interpreter) => { const step = yield* cursor.next if (step.done) return Math.sumPrecise(numbers) yield* preserveConsumerError( - cursor, + cursor.close, Effect.sync(() => { if (typeof step.value !== "number") { throw typeError("Math.sumPrecise expects an iterable of numbers.") diff --git a/packages/codemode/src/stdlib/object.ts b/packages/codemode/src/stdlib/object.ts index 201361b6c96..427bf43141e 100644 --- a/packages/codemode/src/stdlib/object.ts +++ b/packages/codemode/src/stdlib/object.ts @@ -82,7 +82,7 @@ const objectFromEntries = (ctx: Interpreter, source: Value): Effect.Effect const step = yield* cursor.next if (step.done) return out yield* preserveConsumerError( - cursor, + cursor.close, Effect.sync(() => { if (!(step.value instanceof Obj) || containsOpaqueReference(step.value)) { throw typeError("Object.fromEntries expects [key, value] entry objects.") diff --git a/packages/codemode/src/stdlib/url.ts b/packages/codemode/src/stdlib/url.ts index b17494ecdef..e6ea6c472af 100644 --- a/packages/codemode/src/stdlib/url.ts +++ b/packages/codemode/src/stdlib/url.ts @@ -129,7 +129,7 @@ const readPair = (ctx: Interpreter, value: Value, label: string): Effect.E if (step.done) return items items.push( yield* preserveConsumerError( - cursor, + cursor.close, Effect.sync(() => coerceToString(step.value)), ), ) @@ -155,7 +155,7 @@ export const readPairs = ( if (pairs.some((entry) => entry.length !== 2)) throw typeError(`${label} expects iterable [name, value] pairs.`) return pairs as Array<[string, string]> } - pairs.push(yield* preserveConsumerError(cursor, readPair(ctx, step.value, label))) + pairs.push(yield* preserveConsumerError(cursor.close, readPair(ctx, step.value, label))) } }) diff --git a/packages/codemode/test/generator-test262.test.ts b/packages/codemode/test/generator-test262.test.ts index abf2b6ccad7..fa0695ef8bb 100644 --- a/packages/codemode/test/generator-test262.test.ts +++ b/packages/codemode/test/generator-test262.test.ts @@ -1246,4 +1246,27 @@ describe("confined generators", () => { `), ).toEqual(["catch", "reaction"]) }) + + test("a generator's return() through for...of or destructuring surfaces a failing close, as break does", async () => { + expect( + await value(` + const make = (ret) => ({ [Symbol.iterator]: () => ({ next: () => ({ done: false, value: [1] }), return: ret }) }) + const blanks = (ret) => ({ [Symbol.iterator]: () => ({ next: () => ({ done: false }), return: ret }) }) + const outcomes = [] + for (const [label, ret] of [ + ["null", () => null], + ["throws", () => { throw new RangeError("close") }], + ["ok", () => ({ done: true })], + ]) { + function* loop() { for (const [a] of make(ret)) yield a } + function* pattern() { for ([ {} = yield ] of [blanks(ret)]) {} } + for (const g of [loop(), pattern()]) { + g.next() + try { g.return(7); outcomes.push(label + " quiet") } catch (e) { outcomes.push(label + " " + e.constructor.name) } + } + } + return outcomes + `), + ).toEqual(["null TypeError", "null TypeError", "throws RangeError", "throws RangeError", "ok quiet", "ok quiet"]) + }) }) diff --git a/packages/codemode/test/promise.test.ts b/packages/codemode/test/promise.test.ts index 8f91a585f53..7d6bfda7472 100644 --- a/packages/codemode/test/promise.test.ts +++ b/packages/codemode/test/promise.test.ts @@ -1131,8 +1131,26 @@ describe("unsupported promise surface", () => { }) test("unknown Promise statics are not functions", async () => { - const diagnostic = await error(`return await Promise.try(() => 1)`) - expect(diagnostic.message).toContain("Promise.try is not a function") + const diagnostic = await error(`return await Promise.settle(() => 1)`) + expect(diagnostic.message).toContain("Promise.settle is not a function") + }) +}) + +describe("Promise.try", () => { + test("runs the function now with its arguments; a throw rejects, a return fulfils, a promise or thenable is adopted", async () => { + expect( + await value(` + const log = [] + const sum = Promise.try((a, b) => { log.push("ran"); return a + b }, 1, 2) + log.push("after") + let caught + try { await Promise.try(() => { throw new RangeError("boom") }) } catch (e) { caught = e.constructor.name } + return [log, sum instanceof Promise, await sum, caught, await Promise.try(async () => 5), await Promise.try(() => ({ then: (r) => r("thenable") }))] + `), + ).toEqual([["ran", "after"], true, 3, "RangeError", 5, "thenable"]) + expect((await error(`return Promise.try(5)`)).message).toContain( + "Promise.try expects a function, received a number.", + ) }) }) diff --git a/packages/codemode/test/test262/skipped.txt b/packages/codemode/test/test262/skipped.txt index a680ff1aca5..6686621a034 100644 --- a/packages/codemode/test/test262/skipped.txt +++ b/packages/codemode/test/test262/skipped.txt @@ -295,7 +295,6 @@ language/statements/for-await-of/async-func-decl-dstr-obj-empty-num.js # TypeEr language/statements/for-await-of/async-func-decl-dstr-obj-empty-string.js # TypeError: Object destructuring requires a data object or array value, received a string. language/statements/for-await-of/async-func-decl-dstr-obj-rest-number.js # TypeError: Object destructuring requires a data object or array value, received a number. language/statements/for-await-of/async-func-decl-dstr-obj-rest-str-val.js # TypeError: Object destructuring requires a data object or array value, received a string. -language/statements/for-await-of/async-gen-decl-dstr-array-elem-iter-rtrn-close-null.js # "Promise incorrectly fulfilled." language/statements/for-await-of/async-gen-decl-dstr-obj-empty-bool.js # TypeError: Object destructuring requires a data object or array value, received a boolean. language/statements/for-await-of/async-gen-decl-dstr-obj-empty-num.js # TypeError: Object destructuring requires a data object or array value, received a number. language/statements/for-await-of/async-gen-decl-dstr-obj-empty-string.js # TypeError: Object destructuring requires a data object or array value, received a string. @@ -303,10 +302,7 @@ language/statements/for-await-of/async-gen-decl-dstr-obj-rest-number.js # TypeE language/statements/for-await-of/async-gen-decl-dstr-obj-rest-str-val.js # TypeError: Object destructuring requires a data object or array value, received a string. language/statements/for-in/head-lhs-member.js # Unsupported for...in binding. language/statements/for-of/dstr/array-elem-iter-rtrn-close-err.js # Iterator next must be a function. -language/statements/for-of/dstr/array-elem-iter-rtrn-close-null.js # Expected a TypeError to be thrown but no exception was thrown at all language/statements/for-of/dstr/array-elem-iter-thrw-close-err.js # Expected SameValue(«1», «0») to be true -language/statements/for-of/dstr/array-elem-trlg-iter-list-rtrn-close-err.js # Expected a Test262Error to be thrown but no exception was thrown at all -language/statements/for-of/dstr/array-elem-trlg-iter-list-rtrn-close-null.js # Expected a TypeError to be thrown but no exception was thrown at all language/statements/for-of/dstr/array-elem-trlg-iter-list-thrw-close-err.js # Expected SameValue(«1», «0») to be true language/statements/for-of/dstr/array-elem-trlg-iter-rest-rtrn-close-err.js # Expected a Test262Error to be thrown but no exception was thrown at all language/statements/for-of/dstr/array-elem-trlg-iter-rest-rtrn-close-null.js # Expected a TypeError to be thrown but no exception was thrown at all