quickjs-pure 0.14.2

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
//! `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> {
    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"));
    }
    let (promise, resolve, reject) = interp.new_promise_capability();
    // A throw from the executor rejects the promise rather than escaping. This is the
    // documented way to build a rejected promise: `new Promise(() => { throw e })`.
    if let Err(Signal::Throw(reason)) =
        interp.call_value(executor, Value::Undefined, vec![resolve, reject])
    {
        interp.reject_promise(&promise, 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 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)
}

/// 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()));
    state.define_data("remaining", Value::Int(0));
    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,
    };
    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 callback that saw `remaining === 0` would settle
        // the outer promise too early.
        state.define_data("remaining", Value::Int(index as i32 + 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])?;
            // §27.2.4.1.1: the two element functions are built-ins with an empty name and
            // length 1, in `length`-then-`name` order.
            let fulfilled = interp.builtin_function(
                "",
                1,
                Callable::CombinatorSettle {
                    state: state.clone(),
                    index,
                    fulfilled: true,
                },
            );
            let rejected = interp.builtin_function(
                "",
                1,
                Callable::CombinatorSettle {
                    state: state.clone(),
                    index,
                    fulfilled: false,
                },
            );
            interp.invoke_then(
                next_promise,
                Value::Object(fulfilled),
                Value::Object(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;
    }
    state.define_data("remaining", Value::Int(index as i32));
    if index == 0 {
        // Inside the loop this is step "if remaining is 0"; with an empty iteration the
        // spec settles from the same place, and `race([])` stays pending forever.
        settle_combinator_empty(interp, &state, &results, kind)?;
    }
    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())],
                )?;
            }
        }
        CombinatorKind::Any => {
            if let Some(reject) = reject {
                let error = interp.aggregate_error(Vec::new(), "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 (promise, resolve, reject) = interp.new_promise_capability_for(&this)?;
    let callback = arg(args, 0);
    let rest: Vec<Value> = args.iter().skip(1).cloned().collect();
    match interp.call_value(callback, Value::Undefined, rest) {
        Ok(value) => {
            interp.call_value(resolve, Value::Undefined, vec![value])?;
        }
        Err(Signal::Throw(reason)) => {
            interp.call_value(reject, Value::Undefined, vec![reason])?;
        }
        Err(other) => return Err(other),
    }
    Ok(promise)
}

/// `Promise.withResolvers()` → `{promise, resolve, reject}`.
fn with_resolvers(interp: &mut Interp<'_>, _this: Value, _args: &[Value]) -> JsResult<Value> {
    let (promise, resolve, reject) = interp.new_promise_capability();
    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.
    let tag = interp.string("Promise");
    proto.define_key(
        &interp
            .realm
            .well_known_key(crate::interp::WellKnown::ToStringTag),
        Property::with_attributes(tag, false, false),
    );

    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),
        ("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),
    );
}