quickjs-pure 0.17.12

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
//! `DisposableStack` and `AsyncDisposableStack`.
//!
//! A stack is an ordered list of resources disposed in reverse order, which is what makes
//! it the imperative counterpart of a `using` declaration: `use`/`adopt`/`defer` push, and
//! `dispose` pops until the list is empty.
//!
//! # Intrinsics, not the global binding
//!
//! `move` returns a *new* stack of the same kind. It builds that object from the recorded
//! intrinsic prototype rather than from `globalThis.DisposableStack`, because a script is
//! allowed to reassign or delete the global — and the disposables proposal is explicit that
//! doing so must not change what `move` returns. The test suite checks exactly that.
//!
//! # Known gap
//!
//! `AsyncDisposableStack` disposes synchronously: this runtime has no `Promise` builtin, so
//! an `asyncDispose` that returns a promise has that promise dropped rather than awaited.
//! The bookkeeping — reverse order, error aggregation, `move` — is the same.

use crate::builtins::{arg, define_method};
use crate::interp::{Interp, JsResult, Signal, WellKnown};
use crate::object::{JsObject, Property, PropertyKey};
use crate::value::Value;
use js_gc::Gc;

/// The resources a stack still holds, plus whether it is the async kind.
///
/// Cloned out of the object on every access because the interpreter may reallocate the
/// object table while a method runs; the authoritative copy is written back afterwards.
#[derive(Clone)]
pub struct StackState {
    /// `(resource, dispose method)` pairs, in the order they were pushed.
    pub resources: Vec<(Value, Value)>,
    /// Whether this is an `AsyncDisposableStack`.
    pub async_form: bool,
    /// Whether `dispose` has already run, which makes it a no-op and `use` a `TypeError`.
    pub disposed: bool,
}

impl StackState {
    /// An empty stack of the given kind.
    pub fn new(async_form: bool) -> StackState {
        StackState {
            resources: Vec::new(),
            async_form,
            disposed: false,
        }
    }
}

impl js_gc::Trace for StackState {
    fn trace(&self, tracer: &mut js_gc::Tracer) {
        for (value, method) in &self.resources {
            js_gc::Trace::trace(value, tracer);
            js_gc::Trace::trace(method, tracer);
        }
    }
}

/// Install both stacks.
pub fn install(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
    let disposable_proto = interp.new_object(Some(object_proto.clone()));
    let constructor = install_one(interp, &disposable_proto, "DisposableStack", false);
    interp.realm.disposable_stack_proto = Some(disposable_proto);

    let async_proto = interp.new_object(Some(object_proto.clone()));
    let async_constructor = install_one(interp, &async_proto, "AsyncDisposableStack", true);
    interp.realm.async_disposable_stack_proto = Some(async_proto);

    let global = interp.realm.global.clone();
    global.define(
        "DisposableStack",
        Property::with_attributes(Value::Object(constructor), true, false),
    );
    global.define(
        "AsyncDisposableStack",
        Property::with_attributes(Value::Object(async_constructor), true, false),
    );
}

fn install_one(
    interp: &mut Interp<'_>,
    prototype: &Gc<JsObject>,
    name: &str,
    async_form: bool,
) -> Gc<JsObject> {
    let constructor = interp.new_native_constructor(name, 0, constructor);
    constructor.define(
        "prototype",
        Property::with_attributes(Value::Object(prototype.clone()), false, false),
    );
    prototype.define(
        "constructor",
        Property::with_attributes(Value::Object(constructor.clone()), true, false),
    );

    for (method, length, func) in [
        ("use", 1, use_ as crate::object::NativeFn),
        ("adopt", 2, adopt),
        ("defer", 1, defer),
        ("move", 0, move_),
        ("dispose", 0, dispose),
        ("disposeAsync", 0, dispose_async),
    ] {
        // `DisposableStack.prototype` has no `disposeAsync` and `AsyncDisposableStack`'s
        // has no `dispose`: §24.3.3 and §24.4.3 are separate interfaces, and a shared
        // method would also make the two stacks interchangeable to `state_of`.
        let wrong_kind =
            (method == "dispose" && async_form) || (method == "disposeAsync" && !async_form);
        if wrong_kind {
            continue;
        }
        define_method(prototype, method, length, func, interp);
        // Stamp which interface this method belongs to, so `state_of_kind` can refuse a
        // receiver of the other kind.
        if let Some(Value::Object(function)) = prototype
            .own_property(method)
            .and_then(|property| property.value)
        {
            interp.internal_set(&function, "_stack_async", Value::Bool(async_form));
        }
    }
    // `disposed` is an accessor so it cannot be set, and `Symbol.dispose` is what makes
    // `using stack = new DisposableStack()` work.
    let getter = interp.new_native("get disposed", 0, disposed_getter);
    prototype.define(
        "disposed",
        Property {
            getter: Some(Value::Object(getter)),
            enumerable: false,
            configurable: true,
            ..Property::default()
        },
    );
    // `Symbol.dispose` **is** `dispose` and `Symbol.asyncDispose` **is** `disposeAsync` —
    // one function object each, so `===` holds and the `name` is the method's
    // (`Symbol.dispose.js`, `Symbol.asyncDispose.js`). Building fresh natives gave two
    // extra functions whose names were the symbol spelling.
    let (symbol, name) = if async_form {
        (WellKnown::AsyncDisposable, "disposeAsync")
    } else {
        (WellKnown::Disposable, "dispose")
    };
    if let Some(method) = prototype
        .own_property(name)
        .and_then(|property| property.value)
    {
        prototype.define_key(
            &interp.realm.well_known_key(symbol),
            Property::with_attributes(method, true, false),
        );
    }
    // A **data** property holding the string, not a method that answers it: the two
    // differ in `Object.getOwnPropertyDescriptor(..., Symbol.toStringTag).value` and in
    // whether the property is writable, and `DisposableStack/prototype/Symbol.toStringTag.js`
    // checks both. The tag is per-prototype here, so the two stacks get their own.
    let tag = if async_form {
        "AsyncDisposableStack"
    } else {
        "DisposableStack"
    };
    crate::builtins::install_tag(prototype, tag, interp);
    let _ = async_form;
    constructor
}

fn state_of(interp: &Interp<'_>, this: &Value) -> JsResult<StackState> {
    match this
        .as_object()
        .and_then(|object| object.disposable_stack())
    {
        Some(state) => Ok(state),
        None => Err(interp.type_error("method called on a non-DisposableStack")),
    }
}

/// [`state_of`] for a method of one interface, refusing the other stack.
///
/// Both stacks share one internal slot here, so `RequireInternalSlot(stack,
/// [[DisposableState]])` cannot be answered from the slot alone: an
/// `AsyncDisposableStack` has a perfectly good stack on its hands. The interfaces are
/// separate (§24.3.3 vs §24.4.3), and using one's method on the other is a `TypeError`
/// (`*/this-does-not-have-internal-*-state-throws`).
fn state_of_kind(interp: &Interp<'_>, this: &Value) -> JsResult<StackState> {
    // Which interface the *method* belongs to, stamped on the function object by
    // [`mark_async`] when it is installed. The receiver alone cannot say: the two stacks
    // share one internal slot here, exactly like `Map` and `Set`.
    let async_form = interp
        .current_native()
        .and_then(|callee| interp.internal_get(&callee, "_stack_async"))
        .is_some_and(|value| value.to_boolean());
    let state = state_of(interp, this)?;
    if state.async_form != async_form {
        return Err(interp.type_error("method called on the wrong kind of stack"));
    }
    Ok(state)
}

fn write_back(object: &Gc<JsObject>, state: StackState) {
    object.set_disposable_stack(state);
}

/// `new DisposableStack()`.
fn constructor(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    // §24.3.1.1 / §24.4.1.1 step 1: `If NewTarget is undefined, throw a TypeError`. The
    // call form builds a stack here, which is what `undefined-newtarget-throws` refuses.
    if !interp.is_constructing() {
        return Err(interp.type_error("Constructor DisposableStack requires 'new'"));
    }
    // `new` hands us the fresh object, whose prototype came from the constructor; a plain
    // call has no receiver and builds one from the intrinsic prototype.
    let object = match this.as_object() {
        Some(object) => object.clone(),
        None => {
            let proto = interp
                .realm
                .disposable_stack_proto
                .clone()
                .unwrap_or_else(|| interp.realm.object_proto.clone());
            interp.new_object(Some(proto))
        }
    };
    // Which kind this is follows from the prototype the object was built with, so the same
    // native function can serve both constructors.
    let async_form = interp
        .realm
        .async_disposable_stack_proto
        .as_ref()
        .is_some_and(|proto| object.proto().is_some_and(|own| own.ptr_eq(proto)));
    object.set_disposable_stack(StackState::new(async_form));
    Ok(Value::Object(object))
}

/// `stack.use(value)` — validate and push, returning the value.
fn use_(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let Some(object) = this.as_object() else {
        return Err(interp.type_error("use called on a non-object"));
    };
    let value = arg(args, 0);
    let mut state = state_of_kind(interp, &this)?;
    if state.disposed {
        // §24.3.3.x: a disposed stack's `defer` is a **ReferenceError**, not a `TypeError`.
        return Err(interp.reference_error("DisposableStack has already been disposed"));
    }
    let method = interp.using_method_for(&value, state.async_form)?;
    // A nullish resource has a nullish method and is still *counted*: `use(null)` is legal
    // and disposes to nothing.
    if !value.is_nullish() {
        state.resources.push((value.clone(), method));
    }
    write_back(object, state);
    Ok(value)
}

/// `stack.adopt(value, onDispose)` — wrap a resource that has no dispose protocol.
fn adopt(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let Some(object) = this.as_object() else {
        return Err(interp.type_error("adopt called on a non-object"));
    };
    let value = arg(args, 0);
    let on_dispose = arg(args, 1);
    if !on_dispose
        .as_object()
        .is_some_and(|function| function.is_callable())
    {
        return Err(interp.type_error("adopt needs a disposal function"));
    }
    let mut state = state_of_kind(interp, &this)?;
    if state.disposed {
        // §24.3.3.x: a disposed stack's `defer` is a **ReferenceError**, not a `TypeError`.
        return Err(interp.reference_error("DisposableStack has already been disposed"));
    }
    // The callback receives the value: `adopt` is how a resource that does not know
    // `Symbol.dispose` is given a disposer that does. The wrapper *is* the resource as far
    // as disposal is concerned — it is passed as both the receiver and the method — which is
    // how it can carry the callback and the value without capturing them.
    let callable = interp.new_native("onDispose", 1, adopt_callback);
    callable.define(
        "_adopts",
        Property::with_attributes(value.clone(), false, false),
    );
    callable.define(
        "_callback",
        Property::with_attributes(on_dispose, false, false),
    );
    state
        .resources
        .push((Value::Object(callable.clone()), Value::Object(callable)));
    write_back(object, state);
    Ok(value)
}

/// The wrapper `adopt` pushes: calls the script's callback with the adopted value.
fn adopt_callback(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let wrapper = this
        .as_object()
        .ok_or_else(|| interp.type_error("adopt wrapper called without a receiver"))?;
    let value = wrapper
        .own_property("_adopts")
        .and_then(|property| property.value)
        .unwrap_or(Value::Undefined);
    let callback = wrapper
        .own_property("_callback")
        .and_then(|property| property.value)
        .unwrap_or(Value::Undefined);
    interp.call_value(callback, Value::Undefined, vec![value])
}

/// `stack.defer(fn)` — push a plain callback.
fn defer(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let Some(object) = this.as_object() else {
        return Err(interp.type_error("defer called on a non-object"));
    };
    let callback = arg(args, 0);
    if !callback
        .as_object()
        .is_some_and(|function| function.is_callable())
    {
        return Err(interp.type_error("defer needs a callback"));
    }
    let mut state = state_of_kind(interp, &this)?;
    if state.disposed {
        // §24.3.3.x: a disposed stack's `defer` is a **ReferenceError**, not a `TypeError`.
        return Err(interp.reference_error("DisposableStack has already been disposed"));
    }
    // A deferred callback takes no arguments, so the resource is an absent receiver and the
    // method is the callback itself.
    state.resources.push((Value::Undefined, callback));
    write_back(object, state);
    Ok(Value::Undefined)
}

/// `stack.move()` — empty this stack into a fresh one.
fn move_(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let Some(object) = this.as_object() else {
        return Err(interp.type_error("move called on a non-object"));
    };
    let mut state = state_of_kind(interp, &this)?;
    if state.disposed {
        // §24.3.3.x: a disposed stack's `defer` is a **ReferenceError**, not a `TypeError`.
        return Err(interp.reference_error("DisposableStack has already been disposed"));
    }
    let moved = StackState {
        resources: std::mem::take(&mut state.resources),
        async_form: state.async_form,
        disposed: false,
    };
    // §24.3.3.7 step 6: the **old** stack is marked disposed, so a second `move` or a
    // later `defer` on it is refused (`move/sets-state-to-disposed`).
    state.disposed = true;
    write_back(object, state);
    // The new stack comes from the *intrinsic* prototype — replacing or deleting the global
    // binding must not redirect `move`, which is what the test suite checks.
    let proto = if moved.async_form {
        interp.realm.async_disposable_stack_proto.clone()
    } else {
        interp.realm.disposable_stack_proto.clone()
    }
    .unwrap_or_else(|| interp.realm.object_proto.clone());
    let fresh = interp.new_object(Some(proto));
    fresh.set_disposable_stack(moved);
    Ok(Value::Object(fresh))
}

/// `stack.dispose()` — dispose everything in reverse order.
fn dispose(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let Some(object) = this.as_object() else {
        return Err(interp.type_error("dispose called on a non-object"));
    };
    let mut state = state_of_kind(interp, &this)?;
    if state.disposed {
        return Ok(Value::Undefined);
    }
    state.disposed = true;
    let resources = std::mem::take(&mut state.resources);
    write_back(object, state);
    dispose_all(interp, resources)?;
    Ok(Value::Undefined)
}

/// `stack.disposeAsync()` — dispose everything in reverse order, awaiting each disposer.
///
/// The resources are handed to the interpreter rather than run here: awaiting a disposer
/// means parking between two of them, which is the microtask queue's job.
fn dispose_async(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    // `disposeAsync` is an **async function**: a bad receiver or a disposed stack is a
    // *rejected promise*, never a synchronous throw
    // (`disposeAsync/this-not-object-rejects`, `…-state-rejects`).
    let failure = |interp: &mut Interp<'_>, signal: crate::interp::Signal| -> JsResult<Value> {
        let crate::interp::Signal::Throw(reason) = signal else {
            return Err(signal);
        };
        let promise = interp.new_promise();
        interp.reject_promise(&promise, reason);
        Ok(Value::Object(promise))
    };
    let Some(object) = this.as_object() else {
        return failure(
            interp,
            interp.type_error("disposeAsync called on a non-object"),
        );
    };
    let state = match state_of_kind(interp, &this) {
        Ok(state) => state,
        Err(signal) => return failure(interp, signal),
    };
    let mut state = state;
    if state.disposed {
        return interp.promise_resolve_value(Value::Undefined);
    }
    state.disposed = true;
    let resources = std::mem::take(&mut state.resources);
    write_back(object, state);
    interp.dispose_async_all(resources)
}

/// Pop and call every resource, folding failures into one `SuppressedError` chain.
fn dispose_all(interp: &mut Interp<'_>, resources: Vec<(Value, Value)>) -> JsResult<()> {
    let mut error_state = Value::Uninitialized;
    for (value, method) in resources.into_iter().rev() {
        let Some(function) = method.as_object() else {
            continue;
        };
        if !function.is_callable() {
            continue;
        }
        match interp.call_value(Value::Object(function.clone()), value, Vec::new()) {
            Ok(_) => {}
            Err(Signal::Throw(thrown)) => {
                error_state = interp.merge_dispose_error(thrown, error_state);
            }
            Err(other) => return Err(other),
        }
    }
    if matches!(error_state, Value::Uninitialized) {
        return Ok(());
    }
    Err(Signal::Throw(error_state))
}

/// The `disposed` getter.
fn disposed_getter(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    Ok(Value::Bool(state_of(interp, &this)?.disposed))
}

/// Silence the unused-import warning for `PropertyKey`, which the `define_key` calls above
/// need only through inference.
#[allow(dead_code)]
fn _property_key_is_used(_: PropertyKey) {}