quickjs-pure 0.17.8

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
//! `%GeneratorPrototype%`: `next`, `return` and `throw`.
//!
//! The object itself is an ordinary object — the state that matters lives in its
//! `ObjectKind::Generator` payload — so all three methods do the same thing: ask the
//! interpreter to advance the frame with a different "which method was this" tag.
//!
//! `%GeneratorPrototype%[Symbol.iterator]` is installed here too: it answers `this`, which
//! is what makes a generator usable directly in `for (… of …)` and `[...g]`.

use crate::interp::{Interp, JsResult, ResumeKind, Signal};
use crate::object::{JsObject, ObjectKind, Property, PropertyKey};
use crate::value::Value;
use js_gc::Gc;

/// The generator a `this` refers to, or the `TypeError` the spec raises.
///
/// `want_async` selects between `RequireInternalSlot(…, [[AsyncGeneratorState]])` and
/// `[[GeneratorState]]`. Both kinds share `ObjectKind::Generator`, so a sync generator is
/// otherwise indistinguishable — and `%AsyncGeneratorPrototype%.next.call(syncGenerator)`
/// must reject, not run the sync body.
fn generator_of(
    interp: &Interp<'_>,
    this: &Value,
    want_async: bool,
) -> Result<Gc<JsObject>, Value> {
    match this {
        Value::Object(object)
            if object.with(|data| match &data.kind {
                ObjectKind::Generator(state) => state.is_async == want_async,
                _ => false,
            }) =>
        {
            Ok(object.clone())
        }
        _ => Err(interp.make_error("TypeError", "not a generator")),
    }
}

fn next(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let generator = match generator_of(interp, &this, false) {
        Ok(generator) => generator,
        Err(error) => return Err(Signal::Throw(error)),
    };
    let value = args.first().cloned().unwrap_or(Value::Undefined);
    interp.resume_generator(&generator, ResumeKind::Next, value)
}

fn generator_return(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let generator = match generator_of(interp, &this, false) {
        Ok(generator) => generator,
        Err(error) => return Err(Signal::Throw(error)),
    };
    let value = args.first().cloned().unwrap_or(Value::Undefined);
    interp.resume_generator(&generator, ResumeKind::Return, value)
}

fn generator_throw(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let generator = match generator_of(interp, &this, false) {
        Ok(generator) => generator,
        Err(error) => return Err(Signal::Throw(error)),
    };
    let value = args.first().cloned().unwrap_or(Value::Undefined);
    interp.resume_generator(&generator, ResumeKind::Throw, value)
}

pub fn install(interp: &mut Interp<'_>, proto: &Gc<JsObject>) {
    let function_proto = interp.realm.function_proto.clone();
    let object_proto = interp.realm.object_proto.clone();
    let iterator_proto = interp.realm.iterator_proto.clone();
    let tag_key = interp
        .realm
        .well_known_key(crate::interp::WellKnown::ToStringTag);

    // `%AsyncIteratorPrototype%`: the object between `%AsyncGeneratorPrototype%` and
    // `Object.prototype`. It carries exactly two methods, and both are reached by *every*
    // async iterator, which is why the 13 `AsyncIteratorPrototype` cases only needed this
    // object to exist. test262 finds it as
    // `Object.getPrototypeOf(Object.getPrototypeOf(generator.prototype))`.
    let async_iterator_proto = interp.new_object(Some(object_proto.clone()));
    let async_key = interp
        .realm
        .well_known_key(crate::interp::WellKnown::AsyncIterator);
    let identity = interp.new_native("[Symbol.asyncIterator]", 0, iterator);
    async_iterator_proto.define_key(
        &async_key,
        Property::with_attributes(Value::Object(identity), true, false),
    );
    let async_dispose_key = interp
        .realm
        .well_known_key(crate::interp::WellKnown::AsyncDisposable);
    let async_dispose = interp.new_native("[Symbol.asyncDispose]", 0, dispose_async_self);
    async_iterator_proto.define_key(
        &async_dispose_key,
        Property::with_attributes(Value::Object(async_dispose), true, false),
    );
    interp.realm.async_iterator_proto = Some(async_iterator_proto.clone());

    // -- `%GeneratorFunction%` and `%GeneratorFunction.prototype%` ----------------
    //
    // `%GeneratorFunction%` is a real (but unreachable from script other than through
    // `Object.getPrototypeOf(function*(){}).constructor`) constructor whose `prototype` is
    // `%GeneratorFunction.prototype%`. It has to exist because `g.constructor` resolves
    // through the proto chain and must be *this*, not `Function`: deleting
    // `g.constructor.prototype[Symbol.toStringTag]` is how a test removes the tag, and if
    // `constructor` pointed at `Function` that `delete` would hit the wrong object.
    let generator_function = interp.new_native("GeneratorFunction", 1, {
        // A native fn is a plain pointer, so the kind is baked in by building one closure
        // per kind and boxing the pointer.
        fn trampoline(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
            generator_function_constructor(FunctionFactory::Generator)(interp, this, args)
        }
        trampoline
    });
    generator_function.set_constructible(true);
    let generator_function_proto = interp.new_object(Some(function_proto.clone()));
    generator_function.define(
        "prototype",
        Property::with_attributes(
            Value::Object(generator_function_proto.clone()),
            false,
            false,
        ),
    );
    // §27.3.3.1: `constructor` is `{writable: false, enumerable: false, configurable:
    // true}`. `with_attributes` ties `configurable` to `writable`, so it produced
    // `{w:false, e:false, c:false}` and `GeneratorFunction/prototype/constructor.js` read
    // the difference back.
    generator_function_proto.define(
        "constructor",
        Property::name_or_length(Value::Object(generator_function.clone())),
    );
    // §27.3.3.1: `%GeneratorFunction.prototype%.prototype` is `%GeneratorPrototype%` —
    // **not** a per-function object; the per-function one is installed on each generator
    // function by `install_function_prototype`.
    generator_function_proto.define(
        "prototype",
        Property::name_or_length(Value::Object(proto.clone())),
    );
    generator_function_proto.define_key(
        &tag_key,
        Property {
            value: Some(interp.string("GeneratorFunction")),
            writable: false,
            enumerable: false,
            configurable: true,
            ..Property::data(Value::Undefined)
        },
    );
    // A generator function's `[[Prototype]]` *is* this object, so `g.constructor` finds
    // the constructor above.
    interp.realm.generator_function_proto = Some(generator_function_proto.clone());

    // -- `%GeneratorPrototype%` -------------------------------------------------
    //
    // It inherits from `%IteratorPrototype%`, so a generator *is* an `Iterator` and
    // `gen().map(f)` resolves `map` up the chain. Hanging it off `Object.prototype`
    // instead left `.map` undefined.
    proto.set_proto(iterator_proto);
    for (name, length, func) in [
        ("next", 1, next as crate::object::NativeFn),
        ("return", 1, generator_return),
        ("throw", 1, generator_throw),
    ] {
        super::define_method(proto, name, length, func, interp);
    }
    // §27.5.1.2: `%GeneratorPrototype%.constructor` is `%GeneratorFunction.prototype%`,
    // not `%GeneratorFunction%`. It is what makes `Object.getPrototypeOf(g).prototype
    // .constructor === Object.getPrototypeOf(g)` hold.
    proto.define(
        "constructor",
        Property::name_or_length(Value::Object(generator_function_proto.clone())),
    );
    proto.define_key(
        &tag_key,
        Property {
            value: Some(interp.string("Generator")),
            writable: false,
            enumerable: false,
            configurable: true,
            ..Property::data(Value::Undefined)
        },
    );
    // `%GeneratorPrototype%` deliberately has **no** own `@@iterator`: it is inherited
    // from `%IteratorPrototype%`, whose `@@iterator` answers `this`, and that is enough for
    // a generator to be its own iterator. An own copy was invisible except in
    // `Object.getOwnPropertySymbols(%GeneratorPrototype%)`.

    // -- `%AsyncFunction%` (plain `async function`) ------------------------------
    let async_function = interp.new_native("AsyncFunction", 1, {
        fn trampoline(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
            generator_function_constructor(FunctionFactory::Async)(interp, this, args)
        }
        trampoline
    });
    async_function.set_constructible(true);
    let async_function_proto = interp.new_object(Some(function_proto.clone()));
    async_function.define(
        "prototype",
        Property::with_attributes(Value::Object(async_function_proto.clone()), false, false),
    );
    async_function_proto.define(
        "constructor",
        Property::name_or_length(Value::Object(async_function.clone())),
    );
    async_function_proto.define_key(
        &tag_key,
        Property {
            value: Some(interp.string("AsyncFunction")),
            writable: false,
            enumerable: false,
            configurable: true,
            ..Property::data(Value::Undefined)
        },
    );
    interp.realm.async_function_proto = Some(async_function_proto.clone());

    // -- `%AsyncGeneratorFunction%`, `%AsyncGeneratorPrototype%` ------------------
    //
    // `%AsyncGeneratorFunction.prototype%` inherits from **`%Function.prototype%`**, not
    // from `%AsyncFunction.prototype%`: an async generator function is not an async
    // function (§27.4.3.1). The extra link was visible as an extra level in the chain and
    // cost the four `AsyncGeneratorFunction/*` cases.
    let async_generator_function = interp.new_native("AsyncGeneratorFunction", 1, {
        fn trampoline(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
            generator_function_constructor(FunctionFactory::AsyncGenerator)(interp, this, args)
        }
        trampoline
    });
    async_generator_function.set_constructible(true);
    let async_generator_function_proto = interp.new_object(Some(function_proto.clone()));
    async_generator_function.define(
        "prototype",
        Property::with_attributes(
            Value::Object(async_generator_function_proto.clone()),
            false,
            false,
        ),
    );
    async_generator_function_proto.define(
        "constructor",
        Property::name_or_length(Value::Object(async_generator_function.clone())),
    );
    async_generator_function_proto.define_key(
        &tag_key,
        Property {
            value: Some(interp.string("AsyncGeneratorFunction")),
            writable: false,
            enumerable: false,
            configurable: true,
            ..Property::data(Value::Undefined)
        },
    );
    let async_proto = interp.new_object(Some(async_iterator_proto.clone()));
    interp.realm.async_generator_proto = Some(async_proto.clone());
    async_generator_function_proto.define(
        "prototype",
        Property::name_or_length(Value::Object(async_proto.clone())),
    );
    interp.realm.async_generator_function_proto = Some(async_generator_function_proto.clone());
    for (name, length, func) in [
        ("next", 1, async_next as crate::object::NativeFn),
        ("return", 1, async_generator_return),
        ("throw", 1, async_generator_throw),
    ] {
        super::define_method(&async_proto, name, length, func, interp);
    }
    async_proto.define(
        "constructor",
        Property::name_or_length(Value::Object(async_generator_function_proto.clone())),
    );
    async_proto.define_key(
        &tag_key,
        Property {
            value: Some(interp.string("AsyncGenerator")),
            writable: false,
            enumerable: false,
            configurable: true,
            ..Property::data(Value::Undefined)
        },
    );
}

/// `%AsyncGeneratorPrototype%.next`.
fn async_next(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let generator = match generator_of(interp, &this, true) {
        Ok(generator) => generator,
        // §27.6.3.2 step 4: `IfAbruptRejectPromise(AsyncGeneratorValidate(generator), …)`.
        // A bad `this` **rejects** the returned promise; it does not throw out of the
        // method, which is what `this-val-not-object.js` and
        // `this-val-not-async-generator.js` check for all three methods.
        Err(error) => return Ok(rejected_promise(interp, error)),
    };
    let value = args.first().cloned().unwrap_or(Value::Undefined);
    interp.resume_async_generator(&generator, ResumeKind::Next, value)
}

fn async_generator_return(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let generator = match generator_of(interp, &this, true) {
        Ok(generator) => generator,
        Err(error) => return Ok(rejected_promise(interp, error)),
    };
    let value = args.first().cloned().unwrap_or(Value::Undefined);
    interp.resume_async_generator(&generator, ResumeKind::Return, value)
}

fn async_generator_throw(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let generator = match generator_of(interp, &this, true) {
        Ok(generator) => generator,
        Err(error) => return Ok(rejected_promise(interp, error)),
    };
    let value = args.first().cloned().unwrap_or(Value::Undefined);
    interp.resume_async_generator(&generator, ResumeKind::Throw, value)
}

/// An already-rejected promise, for the paths the spec routes through
/// `IfAbruptRejectPromise`.
fn rejected_promise(interp: &mut Interp<'_>, reason: Value) -> Value {
    let promise = interp.new_promise();
    interp.reject_promise(&promise, reason);
    Value::Object(promise)
}

/// `%GeneratorPrototype%[Symbol.iterator]` and `%AsyncIteratorPrototype%[@@asyncIterator]`.
///
/// Both answer `this` for **any** receiver, primitives and `undefined` included:
/// `AsyncIteratorPrototype/Symbol.asyncIterator/return-val.js` calls the method with
/// `Symbol()`, `4`, `4n`, `true`, `undefined` and `null` and expects each back unchanged.
fn iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    Ok(this)
}

/// `%AsyncIteratorPrototype%[@@asyncDispose]()` — §27.1.4.2.
///
/// `GetMethod(O, "return")`, then call it and **await** the answer, settling on
/// `undefined` whether or not the iterator's `return` resolved with anything. Three
/// things can fail and each one rejects the *returned promise* rather than throwing:
/// a throwing `return` getter, a `return` that is present but not callable, and a `return`
/// call or its awaited value that rejects.
///
/// The awaiting half is [`Interp::dispose_async_all`], which already implements exactly
/// this chain for `AsyncDisposableStack.disposeAsync`: call the method with no arguments,
/// follow a thenable, fulfil with `undefined`, reject with whatever came out of the first
/// failure.
fn dispose_async_self(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let key = PropertyKey::from("return");
    let method = match interp.read_field_key(&this, &key) {
        Ok(Value::Undefined | Value::Null) => {
            let promise = interp.new_promise();
            interp.fulfill_promise(&promise, Value::Undefined);
            return Ok(Value::Object(promise));
        }
        Ok(Value::Object(function)) if function.is_callable() => Value::Object(function),
        Ok(_) => {
            let reason = interp.make_error("TypeError", "return is not a function");
            let promise = interp.new_promise();
            interp.reject_promise(&promise, reason);
            return Ok(Value::Object(promise));
        }
        Err(Signal::Throw(reason)) => {
            let promise = interp.new_promise();
            interp.reject_promise(&promise, reason);
            return Ok(Value::Object(promise));
        }
        Err(other) => return Err(other),
    };
    interp.dispose_async_all(vec![(this, method)])
}

/// `new %GeneratorFunction%(…)` and its async siblings: compile a function of that kind.
///
/// `%GeneratorFunction%` is reachable — `Object.getPrototypeOf(function*(){}).constructor`
/// — and `new (that)("a", "yield a")` really does produce a generator function. Sharing
/// `Function`'s constructor would give a plain function, so the *kind* is spliced into the
/// source instead of the call being refused.
fn generator_function_constructor(
    kind: FunctionFactory,
) -> impl Fn(&mut Interp<'_>, Value, &[Value]) -> JsResult<Value> {
    move |interp, _this, args| {
        let body = match args.last() {
            Some(value) => interp.to_js_string(value)?,
            None => String::new(),
        };
        let params: Vec<String> = {
            let mut out = Vec::new();
            for value in args.iter().take(args.len().saturating_sub(1)) {
                out.push(interp.to_js_string(value)?);
            }
            out
        };
        let params = params.join(",");
        let prefix = match kind {
            FunctionFactory::Generator => "function*",
            FunctionFactory::Async => "async function",
            FunctionFactory::AsyncGenerator => "async function*",
        };
        // The newline before `)` keeps a trailing `//` in the parameter text from
        // swallowing it; see `Function`'s constructor.
        let source = format!("({prefix}({params}\n) {{\n{body}\n}})");
        let program = js_parse::parse_script(&source).map_err(|error| {
            crate::interp::Signal::Throw(interp.make_error("SyntaxError", &error.message))
        })?;
        let compiled = js_compile::compile_script(&program).map_err(|error| {
            crate::interp::Signal::Throw(interp.make_error("SyntaxError", &error.message))
        })?;
        // `new` hands us the instance the runtime built from `NewTarget.prototype`; a
        // generator function is a function object, so the compiled closure *is* the answer.
        let function = interp.run_function_source(compiled)?;
        if let Value::Object(object) = &function {
            // §CreateDynamicFunction step 29 `SetFunctionName(F, "anonymous")` →
            // `{writable: false, enumerable: false, configurable: true}`.
            // `with_attributes` ties `configurable` to `writable`, so the name came back
            // non-configurable and `instance-name.js` read the difference back.
            object.define("name", Property::name_or_length(interp.string("anonymous")));
            // The synthesised text, as for `Function` — `GeneratorFunction.js`,
            // `AsyncFunction.js` and `AsyncGenerator.js` each compare it verbatim.
            let text = crate::builtins::function::dynamic_source_text(prefix, &params, &body);
            interp.internal_set(object, "_source_text", interp.string(text));
        }
        Ok(function)
    }
}

/// Which function kind a `%…Function%` constructor builds.
#[derive(Clone, Copy)]
enum FunctionFactory {
    Generator,
    Async,
    AsyncGenerator,
}