quickjs-pure 0.17.33

Embeddable JavaScript engine written in pure Rust (QuickJS-compatible)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
//! `Promise`, its prototype, and the combinator statics.
//!
//! Most of the machinery lives in the interpreter: the state is an
//! `ObjectKind::Promise`, and settling, `then` and the microtask queue are internal
//! operations `await` needs too. What is here is the surface a script touches — the
//! constructor, `then`/`catch`/`finally`, and the combinators, all of which are
//! arrangements of `perform_then` and the capability pair.
//!
//! Two things here are `Callable` variants rather than `Native`s. A `NativeFn` is a
//! function pointer and cannot capture, and both the per-element callbacks a combinator
//! installs and the shims `finally` installs have to remember state — so they carry it in
//! the callable itself, the same way `Proxy.revocable`'s `revoke` does.

use crate::builtins::{arg, define_method, install_species_accessor};
use crate::interp::{Interp, JsResult, Signal};
use crate::object::{Callable, CombinatorKind, JsObject, ObjectKind, Property};
use crate::value::Value;
use js_gc::Gc;

/// The `this` of a prototype method, which must be a promise.
fn this_promise(interp: &Interp<'_>, this: &Value) -> Result<Gc<JsObject>, Signal> {
    match this {
        Value::Object(object)
            if object.with(|data| matches!(data.kind, ObjectKind::Promise(_))) =>
        {
            Ok(object.clone())
        }
        _ => Err(interp.type_error("not a promise")),
    }
}

/// An argument as a callable, or `None` when it is not one.
///
/// A non-callable handler is not an error: it is dropped and the settlement passes
/// through, which is what makes `p.then(null, f)` behave as a `catch`.
fn callable(value: Option<&Value>) -> Option<Value> {
    match value {
        Some(value @ Value::Object(object)) if object.is_callable() => Some(value.clone()),
        _ => None,
    }
}

/// `new Promise(executor)`.
///
/// The executor runs **synchronously** — a `resolve` inside it settles the promise before
/// the constructor returns, and only the reactions are deferred.
fn constructor(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    // §27.2.3.1 step 1: `If NewTarget is undefined, throw a TypeError exception` — the
    // `Promise(…)` call form (with or without a receiver) is refused
    // (`undefined-newtarget`).
    if !matches!(interp.current_new_target(), Value::Object(_)) {
        return Err(interp.type_error("Constructor Promise requires 'new'"));
    }
    let executor = arg(args, 0);
    if !matches!(&executor, Value::Object(object) if object.is_callable()) {
        return Err(interp.type_error("Promise executor is not a function"));
    }
    // §27.2.3.1 step 3: `OrdinaryCreateFromConstructor(NewTarget, "%PromisePrototype%")`, whose
    // `Get(newTarget, "prototype")` is fallible. The read happens **after** the executor
    // check — `Reflect.construct(Promise, [1], badTarget)` is the executor's `TypeError` — but
    // a getter that throws has to escape as itself (`get-prototype-abrupt`).
    let new_target = interp.current_new_target();
    let proto = match new_target.as_object() {
        Some(target) => match interp.get_property(target, "prototype")? {
            Some(Value::Object(proto)) => Some(proto),
            _ => interp.realm.promise_proto.clone(),
        },
        None => interp.realm.promise_proto.clone(),
    };
    let promise = Interp::make_promise_object(interp.heap, proto);
    let resolve = interp.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
    let reject = interp.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
    let reject_value = Value::Object(reject.clone());
    // Step 9–10: a throw from the executor goes to the *resolving function*, not to the state
    // machine directly — so it is a no-op once the executor has already settled the promise by
    // calling `resolve` (`exception-after-resolve-in-executor`,
    // `exception-after-resolve-in-thenable-job`).
    if let Err(Signal::Throw(reason)) = interp.call_value(
        executor,
        Value::Undefined,
        vec![Value::Object(resolve), reject_value.clone()],
    ) {
        interp.call_value(reject_value, Value::Undefined, vec![reason])?;
    }
    Ok(Value::Object(promise))
}

/// `Promise.prototype.then(onFulfilled, onRejected)`.
///
/// The result comes from `SpeciesConstructor(this)`, so `class Sub extends Promise {}`
/// answers a `Sub` from `then` — and a `constructor` whose `@@species` is not a constructor
/// is the `TypeError` that `then/ctor-null` and friends assert.
fn then(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let promise = this_promise(interp, &this)?;
    let on_fulfilled = callable(args.first());
    let on_rejected = callable(args.get(1));
    let default = interp
        .realm
        .promise_constructor
        .clone()
        .map(Value::Object)
        .unwrap_or(Value::Undefined);
    let species = interp.species_constructor(&promise, default.clone())?;
    // The intrinsic takes the direct path: `perform_then` builds the derived promise and
    // the reaction together, which is what every `then` in ordinary code goes through.
    let same_constructor = match (species.as_object(), default.as_object()) {
        (Some(species), Some(default)) => species.ptr_eq(default),
        _ => false,
    };
    if same_constructor {
        return interp.perform_then(&promise, on_fulfilled, on_rejected);
    }
    let (result, resolve, reject) = interp.new_promise_capability_for(&species)?;
    // The user's handlers ride on the shims rather than on `perform_then`, because
    // `perform_then` settles the engine's own derived promise — which nobody can see here.
    let fulfilled = interp.builtin_function(
        "",
        1,
        Callable::ThenShim {
            handler: on_fulfilled,
            resolve: resolve.clone(),
            reject: reject.clone(),
            fulfilled: true,
        },
    );
    let rejected = interp.builtin_function(
        "",
        1,
        Callable::ThenShim {
            handler: on_rejected,
            resolve,
            reject,
            fulfilled: false,
        },
    );
    interp.perform_then(
        &promise,
        Some(Value::Object(fulfilled)),
        Some(Value::Object(rejected)),
    )?;
    Ok(result)
}

/// `Promise.prototype.catch(onRejected)`.
///
/// `Invoke(this, "then", «undefined, onRejected»)`: the property read is observable, and
/// `catch/invokes-then` replaces it to prove so.
fn catch(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let then = interp.read_field(&this, "then")?;
    if !matches!(&then, Value::Object(object) if object.is_callable()) {
        return Err(interp.type_error("then is not a function"));
    }
    interp.call_value(then, this, vec![Value::Undefined, arg(args, 0)])
}

/// `Promise.prototype.finally(onFinally)`.
///
/// Not `then(onFinally, onFinally)`: the callback runs for both outcomes, its return
/// value is *ignored* unless it is a thenable, and the original value or reason continues
/// down the chain. Passing the callback straight to `then` would turn
/// `p.finally(() => 1)` into a promise of `1`.
fn finally(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    // §27.2.5.3 step 2 is only `Type(promise) is Object` — an object that merely inherits
    // `Promise.prototype` is accepted, and it is `then` that decides whether it can work.
    let Some(object) = this.as_object().cloned() else {
        return Err(interp.type_error("not a promise"));
    };
    // `C = SpeciesConstructor(promise, %Promise%)`: the shims below re-resolve the
    // callback's result through `C`, so `mp1.finally(() => mp2)` keeps `mp2`.
    let default = interp
        .realm
        .promise_constructor
        .clone()
        .map(Value::Object)
        .unwrap_or(Value::Undefined);
    let constructor = interp.species_constructor(&object, default)?;
    let on_finally = args.first().cloned().unwrap_or(Value::Undefined);
    // §27.2.5.3 step 3: when `onFinally` is **not callable** the two arguments handed to
    // `then` are `onFinally` itself, not shims around it. That is observable whenever
    // `then` is replaced — `invokes-then-with-non-function` checks that `then` receives `1`
    // rather than a native function.
    if !matches!(&on_finally, Value::Object(function) if function.is_callable()) {
        let then = interp.read_field(&this, "then")?;
        if !matches!(&then, Value::Object(object) if object.is_callable()) {
            return Err(interp.type_error("then is not a function"));
        }
        return interp.call_value(then, this, vec![on_finally.clone(), on_finally]);
    }
    let callback = callable(args.first());
    let on_fulfilled = interp.builtin_function(
        "",
        1,
        Callable::FinallyShim {
            callback: callback.clone(),
            fulfilled: true,
            constructor: constructor.clone(),
        },
    );
    let on_rejected = interp.builtin_function(
        "",
        1,
        Callable::FinallyShim {
            callback,
            fulfilled: false,
            constructor,
        },
    );
    // `Invoke(promise, "then", «thenFinally, catchFinally»)`: the `then` read is observable
    // — `rejected-observable-then-calls-PromiseResolve` replaces it and counts the calls.
    let then = interp.read_field(&this, "then")?;
    if !matches!(&then, Value::Object(object) if object.is_callable()) {
        return Err(interp.type_error("then is not a function"));
    }
    interp.call_value(
        then,
        this,
        vec![Value::Object(on_fulfilled), Value::Object(on_rejected)],
    )
}

/// `Promise.resolve(value)`.
///
/// `this` decides the constructor: `Sub.resolve(1)` answers a `Sub`, and a primitive `this`
/// is the `TypeError` §27.2.3.1 step 1 asks for.
fn resolve(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    if this.as_object().is_none() {
        return Err(interp.type_error("promise constructor is not an object"));
    }
    interp.promise_resolve_for(&this, arg(args, 0))
}

/// `Promise.reject(reason)`, through `this` for the same reason.
fn reject(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    if this.as_object().is_none() {
        return Err(interp.type_error("promise constructor is not an object"));
    }
    let (promise, _resolve, reject) = interp.new_promise_capability_for(&this)?;
    interp.call_value(reject, Value::Undefined, vec![arg(args, 0)])?;
    Ok(promise)
}

fn all(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    combinator(interp, this, args, CombinatorKind::All)
}

fn all_settled(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    combinator(interp, this, args, CombinatorKind::AllSettled)
}

fn any(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    combinator(interp, this, args, CombinatorKind::Any)
}

fn race(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    combinator(interp, this, args, CombinatorKind::Race)
}

/// `Promise.allKeyed(promises)` — the "await dictionary" proposal.
///
/// The input is an *object*, not an iterable: its own **enumerable** keys name the output
/// slots, and the result is an ordinary null-prototype object with those keys in input
/// order. Absent from this engine until §4.43, which cost 89 test262 cases — they were
/// counted as *skipped* rather than failed, so the number never moved.
fn all_keyed(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    combinator_keyed(interp, this, args, CombinatorKind::AllKeyed)
}

/// `Promise.allSettledKeyed(promises)` — the same, recording each outcome.
fn all_settled_keyed(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    combinator_keyed(interp, this, args, CombinatorKind::AllSettledKeyed)
}

/// The shared body of `all`/`allSettled`/`any`/`race`.
///
/// Three things about the order are load-bearing and each one is a test:
///
/// * the capability comes **first**, built from `this` — `Promise.all.call(eval, …)` is a
///   `TypeError`, and `Promise.all.call(Sub, …)` has to let `Sub` build the result;
/// * `C.resolve` is read **once**, before the iterator — `invoke-resolve-get-error` counts
///   the reads;
/// * any abrupt completion along the way **rejects** the returned promise rather than
///   throwing, after closing the iterator — that is `IfAbruptRejectPromise`, and without it
///   `Promise.all(false).catch(…)` never runs.
fn combinator(
    interp: &mut Interp<'_>,
    this: Value,
    args: &[Value],
    kind: CombinatorKind,
) -> JsResult<Value> {
    let (promise, resolve, reject) = interp.new_promise_capability_for(&this)?;
    match perform_combinator(
        interp,
        &this,
        &arg(args, 0),
        kind,
        &promise,
        &resolve,
        &reject,
    ) {
        Ok(()) => Ok(promise),
        // §27.2.4.1.1 step 12: a throw from the loop rejects. A throw from `reject` itself
        // is not caught here — it propagates, which is what the spec's `?` does.
        Err(Signal::Throw(reason)) => {
            interp.call_value(reject, Value::Undefined, vec![reason])?;
            Ok(promise)
        }
        Err(signal) => Err(signal),
    }
}

/// The iteration itself: `PerformPromiseAll` and its three siblings, sharing one shape.
///
/// The per-element callbacks are `Callable::CombinatorSettle` objects holding the `state`
/// object plus the element's index; a `NativeFn` is a plain function pointer and cannot
/// carry either.
#[allow(clippy::too_many_arguments)]
fn perform_combinator(
    interp: &mut Interp<'_>,
    constructor: &Value,
    iterable: &Value,
    kind: CombinatorKind,
    _promise: &Value,
    resolve: &Value,
    reject: &Value,
) -> JsResult<()> {
    // `GetPromiseResolve(C)`: one read, and it must be callable. Read before the iterator
    // because a throwing getter here must still leave the iterable untouched.
    let resolve_method = match constructor.as_object() {
        Some(object) => interp.get_property(object, "resolve")?,
        None => None,
    };
    let resolve_method = match resolve_method {
        Some(Value::Object(object)) if object.is_callable() => Value::Object(object),
        _ => return Err(interp.type_error("constructor has no resolve method")),
    };
    let iterator = interp.get_iterator(iterable)?;
    // The results array is `ArrayCreate(0)` grown per element, not a species array: the
    // spec builds it with the intrinsic, so a species override cannot change it.
    let results = interp.new_array(Vec::new());
    let state = interp.new_object(Some(interp.realm.object_proto.clone()));
    // `remainingElementsCount`, and it starts at **1**, not 0: the reference's initial 1 is
    // its own "the loop is still running" marker and is removed after the loop. Starting at
    // 0 made a synchronous settle during the first attach reach 0 and resolve early —
    // `all/resolve-before-loop-exit.js` (which this batch also fixed) has a custom
    // constructor whose `then` calls both element functions inline.
    state.define_data("remaining", Value::Int(1));
    state.define_data("results", Value::Object(results.clone()));
    state.define_data("resolve", resolve.clone());
    state.define_data("reject", reject.clone());
    state.define_data("settled", Value::Bool(false));
    let kind_value = match kind {
        CombinatorKind::All => 0,
        CombinatorKind::AllSettled => 1,
        CombinatorKind::Any => 2,
        CombinatorKind::Race => 3,
        // The keyed pair settle exactly like `all`/`allSettled`; only the object the
        // result is built into differs, so they are separate numbers rather than a flag.
        CombinatorKind::AllKeyed => 4,
        CombinatorKind::AllSettledKeyed => 5,
    };
    state.define_data("kind", Value::Int(kind_value));
    // `alreadyCalled` per element, as a plain array: index `i` is true once element `i` has
    // settled, and the second settlement of one element is ignored.
    let done = interp.new_array(Vec::new());
    state.define_data("done", Value::Object(done));
    let mut index = 0usize;
    loop {
        // `IteratorStepValue`: an abrupt completion here closes nothing (the iterator is
        // already exhausted or broken), it just propagates to the caller.
        let (element, done) = interp.iterator_step(&iterator)?;
        if done {
            break;
        }
        // Everything from here to the `then` call is inside the spec's try/catch, so a
        // throw has to close the iterator first. Doing it in one place keeps `?` usable.
        // `remaining` grows *before* the attach: a thenable whose `then` runs inline can
        // settle during this call, and a count that reached 0 there would settle the outer
        // promise with a partial result.
        bump_remaining(&state, 1);
        let step = (|interp: &mut Interp<'_>| -> JsResult<()> {
            // `Call(resolve, C, «element»)`, then `Invoke(nextPromise, "then", …)`.
            let next_promise =
                interp.call_value(resolve_method.clone(), constructor.clone(), vec![element])?;
            // `race` hands the **capability's own** pair to every thenable — there is no
            // per-element function, so `then` receives exactly the `resolve`/`reject` the
            // executor was given (`race/same-resolve-function`, `…/same-reject-function`
            // compare them by identity).
            if kind == CombinatorKind::Race {
                return interp.invoke_then(next_promise, resolve.clone(), reject.clone());
            }
            // §27.2.4.1.1: the element functions are built-ins with an empty name and
            // length 1, in `length`-then-`name` order. **Only one of the two is
            // per-element**, and which one differs by combinator:
            //
            // * `all`/`any` pass the capability's *shared* reject (resp. resolve), because
            //   one rejection (resp. fulfilment) settles the whole thing
            //   (`all/same-reject-function`, `any/same-resolve-function` compare the
            //   function the thenable receives by identity);
            // * `allSettled` needs a per-element function on **both** sides — every
            //   element reports its own outcome.
            let per_element = |interp: &mut Interp<'_>, fulfilled: bool| {
                interp.builtin_function(
                    "",
                    1,
                    Callable::CombinatorSettle {
                        state: state.clone(),
                        index,
                        fulfilled,
                    },
                )
            };
            let (on_fulfilled, on_rejected) = match kind {
                // `all` creates the *fulfilled* element function and shares the reject;
                // `any` is the mirror image — shared resolve, per-element rejected.
                CombinatorKind::All => (Value::Object(per_element(interp, true)), reject.clone()),
                CombinatorKind::Any => (resolve.clone(), Value::Object(per_element(interp, false))),
                _ => (
                    Value::Object(per_element(interp, true)),
                    Value::Object(per_element(interp, false)),
                ),
            };
            interp.invoke_then(next_promise, on_fulfilled, on_rejected)
        })(interp);
        if let Err(signal) = step {
            // §7.4.11: only on the throw path, and a failure from `return` is swallowed.
            let _ = close_iterator(interp, &iterator);
            return Err(signal);
        }
        index += 1;
    }
    // The loop's own marker comes off; if nothing is left, everything settled inline.
    if bump_remaining(&state, -1) == 0 {
        // `race` settles nothing here — an empty race stays pending forever, which is why
        // this is shared rather than a plain `resolve`.
        settle_combinator_empty(interp, &state, &results, kind)?;
    }
    let _ = index;
    Ok(())
}

/// `remainingElementsCount + delta`, answering the new count.
///
/// The exact arithmetic matters and is the reason this is a function rather than an
/// assignment at each site: the count is decremented by every element that settles *during*
/// the loop, so "the value before element `i` attaches" is not a function of `i`.
fn bump_remaining(state: &Gc<JsObject>, delta: i32) -> i32 {
    let current = state
        .own_property("remaining")
        .and_then(|property| property.value)
        .map(|value| value.to_int32())
        .unwrap_or(0);
    let next = current + delta;
    state.define_data("remaining", Value::Int(next));
    next
}

/// `Promise.allKeyed` / `Promise.allSettledKeyed`: the same capability-then-iterate shape
/// as [`combinator`], over an object's own enumerable keys instead of an iterator.
fn combinator_keyed(
    interp: &mut Interp<'_>,
    this: Value,
    args: &[Value],
    kind: CombinatorKind,
) -> JsResult<Value> {
    // The capability is built from `this` **before** anything else, so a non-constructor
    // receiver throws synchronously — `ctx-non-ctor.js` does `Promise.allKeyed.call(eval)`
    // inside `assert.throws`. Everything after it rejects instead (`arg-not-object-reject`).
    let (promise, resolve, reject) = interp.new_promise_capability_for(&this)?;
    match perform_keyed(interp, &this, &arg(args, 0), kind, &resolve, &reject) {
        Ok(()) => Ok(promise),
        Err(Signal::Throw(reason)) => {
            interp.call_value(reject, Value::Undefined, vec![reason])?;
            Ok(promise)
        }
        Err(signal) => Err(signal),
    }
}

/// `PerformPromiseAllKeyed`. The differences from the iterator form are all in the first
/// few steps, and each has a test:
///
/// * the argument is an object, checked *after* `GetPromiseResolve` (`arg-not-object-reject`
///   expects a rejection, and the `resolve` read must be observable);
/// * only own **enumerable** keys count, so a non-enumerable key is fetched by
///   `[[GetOwnProperty]]` and then dropped (`getownproperty-not-enumerable`);
/// * the `[[GetOwnProperty]]` lookup happens **before** `Get`, which is what
///   `get-value-not-called-for-non-enumerable` counts.
#[allow(clippy::too_many_arguments)]
fn perform_keyed(
    interp: &mut Interp<'_>,
    constructor: &Value,
    promises: &Value,
    kind: CombinatorKind,
    resolve: &Value,
    reject: &Value,
) -> JsResult<()> {
    let resolve_method = match constructor.as_object() {
        Some(object) => interp.get_property(object, "resolve")?,
        None => None,
    };
    let resolve_method = match resolve_method {
        Some(Value::Object(object)) if object.is_callable() => Value::Object(object),
        _ => return Err(interp.type_error("constructor has no resolve method")),
    };
    let Some(promises) = promises.as_object().cloned() else {
        return Err(interp.type_error("not an object"));
    };
    // `keys` and `values` are parallel arrays, exactly as the reference builds them: the
    // keys are collected once so the result object's order is the input's order, not the
    // order the elements happen to settle in (`key-order-preserved.js`).
    let keys = interp.new_array(Vec::new());
    let values = interp.new_array(Vec::new());
    let state = interp.new_object(Some(interp.realm.object_proto.clone()));
    state.define_data("remaining", Value::Int(1));
    state.define_data("keys", Value::Object(keys.clone()));
    state.define_data("results", Value::Object(values.clone()));
    state.define_data("resolve", resolve.clone());
    state.define_data("reject", reject.clone());
    state.define_data("settled", Value::Bool(false));
    state.define_data(
        "kind",
        Value::Int(match kind {
            CombinatorKind::AllSettledKeyed => 5,
            _ => 4,
        }),
    );
    let done = interp.new_array(Vec::new());
    state.define_data("done", Value::Object(done));

    let mut index = 0usize;
    for key in interp.object_own_property_keys(&promises)? {
        let Some(descriptor) = interp.object_get_own_property(&promises, &key)? else {
            continue;
        };
        if !descriptor.enumerable {
            continue;
        }
        bump_remaining(&state, 1);
        let step = (|interp: &mut Interp<'_>| -> JsResult<()> {
            let element = interp
                .get_property_key(&promises, &key)?
                .unwrap_or(Value::Undefined);
            let key_value = match &key {
                crate::object::PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
                other => interp.string(other.as_str().unwrap_or_default()),
            };
            keys.array_set(interp.heap, index, key_value);
            values.array_set(interp.heap, index, Value::Undefined);
            let next_promise =
                interp.call_value(resolve_method.clone(), constructor.clone(), vec![element])?;
            let fulfilled = interp.builtin_function(
                "",
                1,
                Callable::CombinatorSettle {
                    state: state.clone(),
                    index,
                    fulfilled: true,
                },
            );
            let rejected = if kind == CombinatorKind::AllSettledKeyed {
                Value::Object(interp.builtin_function(
                    "",
                    1,
                    Callable::CombinatorSettle {
                        state: state.clone(),
                        index,
                        fulfilled: false,
                    },
                ))
            } else {
                // `Promise.allKeyed` rejects the result outright, so the rejection handler
                // *is* the capability's reject — there is no per-element wrapper to build.
                reject.clone()
            };
            interp.invoke_then(next_promise, Value::Object(fulfilled), rejected)
        })(interp);
        step?;
        index += 1;
    }
    if bump_remaining(&state, -1) == 0 {
        settle_combinator_empty(interp, &state, &values, kind)?;
    }
    let _ = index;
    Ok(())
}

/// The `remaining === 0` settlement for an iteration that produced no elements.
fn settle_combinator_empty(
    interp: &mut Interp<'_>,
    state: &Gc<JsObject>,
    results: &Gc<JsObject>,
    kind: CombinatorKind,
) -> JsResult<()> {
    let resolve = state.own_property("resolve").and_then(|p| p.value);
    let reject = state.own_property("reject").and_then(|p| p.value);
    match kind {
        CombinatorKind::All | CombinatorKind::AllSettled => {
            if let Some(resolve) = resolve {
                interp.call_value(
                    resolve,
                    Value::Undefined,
                    vec![Value::Object(results.clone())],
                )?;
            }
        }
        // The keyed result object, from whatever has been collected. Usually every element
        // already settled *during* the loop (a custom constructor's `then` may run inline),
        // so this is the normal completion path rather than an edge case — building an
        // empty object here is exactly the bug `resolve-before-loop-exit.js` reports as
        // "result has 0 keys".
        CombinatorKind::AllKeyed | CombinatorKind::AllSettledKeyed => {
            if let Some(resolve) = resolve {
                let keys = state.own_property("keys").and_then(|p| p.value);
                let result = interp.keyed_result_object(keys.as_ref(), results)?;
                interp.call_value(resolve, Value::Undefined, vec![result])?;
            }
        }
        CombinatorKind::Any => {
            if let Some(reject) = reject {
                // `errors` is the results array — every element rejected, so its slots are
                // the reasons in input order. This used to be `Vec::new()` because the only
                // way to get here was an *empty* iteration; once the counts were fixed a
                // synchronous rejection also arrives at this path, and
                // `any/call-reject-element-after-return.js` caught the empty list.
                let errors = results.array_elements().unwrap_or_default();
                let error = interp.aggregate_error(errors, "all promises were rejected");
                interp.call_value(reject, Value::Undefined, vec![error])?;
            }
        }
        CombinatorKind::Race => {}
    }
    Ok(())
}

/// `IteratorClose`, ignoring a failure from `return` itself.
///
/// Only used on the throw path, where the original error is the one worth reporting.
fn close_iterator(interp: &mut Interp<'_>, iterator: &crate::interp::Iterator) -> JsResult<()> {
    let Some(source) = iterator.object.as_object().cloned() else {
        return Ok(());
    };
    match interp.get_property(&source, "return")? {
        Some(Value::Object(function)) if function.is_callable() => {
            interp.call_value(Value::Object(function), iterator.object.clone(), Vec::new())?;
            Ok(())
        }
        _ => Ok(()),
    }
}

/// `Promise.try(callback, ...args)`.
///
/// Calls the callback and settles with its result, turning a synchronous throw into a
/// rejection — the point of it is that the caller need not write
/// `new Promise(resolve => resolve(callback()))`.
fn try_(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    // `this` is the constructor, so `Sub.try(f)` answers a `Sub`; a non-constructor
    // receiver is the `TypeError` that `try/ctx-non-ctor` asserts.
    let callback = arg(args, 0);
    let rest: Vec<Value> = args.iter().skip(1).cloned().collect();
    let outcome = interp.call_value(callback, Value::Undefined, rest);
    // The fulfilled path goes through `PromiseResolve(C, result)`, which answers the value
    // **itself** when it is already a promise of `C` — `Promise.try(() => p) === p`, and
    // the same for a subclass (`try/avoids-wrap`, `…-for-subclass`). Building a capability
    // and resolving that always made a second promise.
    let value = match outcome {
        Ok(value) => value,
        Err(Signal::Throw(reason)) => {
            let (promise, _resolve, reject) = interp.new_promise_capability_for(&this)?;
            interp.call_value(reject, Value::Undefined, vec![reason])?;
            return Ok(promise);
        }
        Err(other) => return Err(other),
    };
    interp.promise_resolve_for(&this, value)
}

/// `Promise.withResolvers()` → `{promise, resolve, reject}`.
fn with_resolvers(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    // §27.2.4.1 `NewPromiseCapability(%Promise%)`? No — `NewPromiseCapability(this)`: the
    // *receiver* is the constructor, so `SubPromise.withResolvers()` answers a
    // `SubPromise`, and a non-object or non-constructor receiver is a `TypeError`
    // (`withResolvers/ctx-ctor`, `ctx-non-object`, `ctx-non-ctor`).
    let (promise, resolve, reject) = interp.new_promise_capability_for(&this)?;
    let promise = match promise {
        Value::Object(promise) => promise,
        _ => return Err(interp.type_error("promise capability is not an object")),
    };
    let result = interp.new_object(Some(interp.realm.object_proto.clone()));
    result.define_data("promise", Value::Object(promise));
    result.define_data("resolve", resolve);
    result.define_data("reject", reject);
    Ok(Value::Object(result))
}

/// Install `Promise` and `%Promise.prototype%`.
pub fn install(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
    let proto = interp.new_object(Some(object_proto.clone()));
    interp.realm.promise_proto = Some(proto.clone());
    define_method(&proto, "then", 2, then, interp);
    define_method(&proto, "catch", 1, catch, interp);
    define_method(&proto, "finally", 1, finally, interp);
    // `Object.prototype.toString.call(p)` says `[object Promise]` through this.
    //
    // `install_tag` is the one place that knows the attributes every
    // `Symbol.toStringTag` uses — `{writable:false, enumerable:false, configurable:true}`.
    // Hand-rolling it here with `with_attributes(tag, false, false)` made `configurable`
    // false as well (that helper ties the two together), which
    // `Promise/prototype/Symbol.toStringTag.js` checks.
    crate::builtins::install_tag(&proto, "Promise", interp);

    let constructor = interp.new_native_ctor("Promise", 1, constructor);
    constructor.define(
        "prototype",
        Property::with_attributes(Value::Object(proto.clone()), false, false),
    );
    proto.define(
        "constructor",
        Property::data(Value::Object(constructor.clone())),
    );
    for (name, length, func) in [
        ("resolve", 1, resolve as crate::object::NativeFn),
        ("reject", 1, reject),
        ("all", 1, all),
        ("allSettled", 1, all_settled),
        ("allKeyed", 1, all_keyed),
        ("allSettledKeyed", 1, all_settled_keyed),
        ("any", 1, any),
        ("race", 1, race),
        ("try", 1, try_),
        ("withResolvers", 0, with_resolvers),
    ] {
        define_method(&constructor, name, length, func, interp);
    }
    install_species_accessor(&constructor, interp);
    interp.realm.promise_constructor = Some(constructor.clone());
    let global = interp.realm.global.clone();
    global.define(
        "Promise",
        Property::with_attributes(Value::Object(constructor), true, false),
    );
}