fix(codemode): add Promise.try and surface a failing iterator close on generator return (#50419)

This commit is contained in:
Aiden Cline
2026-09-21 15:35:11 -05:00
committed by GitHub
Unverified
parent 990463aa9f
commit 4cc9b90f27
12 changed files with 97 additions and 37 deletions
+5 -3
View File
@@ -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
+25 -14
View File
@@ -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<R> = {
readonly next: Effect.Effect<{ readonly done: boolean; readonly value: Value }, unknown, R>
readonly close: Effect.Effect<void, unknown, R>
}
/** 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 = <A, R>(
cursor: IteratorCursor<R>,
close: Cursor<R>["close"],
effect: Effect.Effect<A, unknown, R>,
): Effect.Effect<A, unknown, R> =>
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
@@ -713,10 +713,8 @@ class Frame<R> {
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<R> {
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
})
+11 -1
View File
@@ -136,7 +136,7 @@ export const resolvePromise = <R>(ctx: Interpreter<R>, 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 = <R>(
ctx: Interpreter<R>,
@@ -154,6 +154,16 @@ const invokePromiseMethod = <R>(
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* () {
+3 -1
View File
@@ -55,7 +55,9 @@ const arrayFrom = <R>(ctx: Interpreter<R>, args: Array<Value>): Effect.Effect<Va
while (true) {
const step = yield* cursor.next
if (step.done) return new Arr(proto, values)
values.push(apply === undefined ? step.value : yield* preserveConsumerError(cursor, apply([step.value, index])))
values.push(
apply === undefined ? step.value : yield* preserveConsumerError(cursor.close, apply([step.value, index])),
)
index += 1
}
})
+3 -3
View File
@@ -56,7 +56,7 @@ export const groupBy = <R>(ctx: Interpreter<R>, 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 = <R>(ctx: Interpreter<R>, 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 = <R>(ctx: Interpreter<R>, 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.")
+1 -1
View File
@@ -105,7 +105,7 @@ export const mathGlobal = <R>(ctx: Interpreter<R>) => {
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.")
+1 -1
View File
@@ -82,7 +82,7 @@ const objectFromEntries = <R>(ctx: Interpreter<R>, 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.")
+2 -2
View File
@@ -129,7 +129,7 @@ const readPair = <R>(ctx: Interpreter<R>, 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 = <R>(
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)))
}
})
@@ -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"])
})
})
+20 -2
View File
@@ -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.",
)
})
})
@@ -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