Skip to main content

quickjs/builtins/
disposable.rs

1//! `DisposableStack` and `AsyncDisposableStack`.
2//!
3//! A stack is an ordered list of resources disposed in reverse order, which is what makes
4//! it the imperative counterpart of a `using` declaration: `use`/`adopt`/`defer` push, and
5//! `dispose` pops until the list is empty.
6//!
7//! # Intrinsics, not the global binding
8//!
9//! `move` returns a *new* stack of the same kind. It builds that object from the recorded
10//! intrinsic prototype rather than from `globalThis.DisposableStack`, because a script is
11//! allowed to reassign or delete the global — and the disposables proposal is explicit that
12//! doing so must not change what `move` returns. The test suite checks exactly that.
13//!
14//! # Known gap
15//!
16//! `AsyncDisposableStack` disposes synchronously: this runtime has no `Promise` builtin, so
17//! an `asyncDispose` that returns a promise has that promise dropped rather than awaited.
18//! The bookkeeping — reverse order, error aggregation, `move` — is the same.
19
20use crate::builtins::{arg, define_method};
21use crate::interp::{Interp, JsResult, Signal, WellKnown};
22use crate::object::{JsObject, Property, PropertyKey};
23use crate::value::Value;
24use js_gc::Gc;
25
26/// The resources a stack still holds, plus whether it is the async kind.
27///
28/// Cloned out of the object on every access because the interpreter may reallocate the
29/// object table while a method runs; the authoritative copy is written back afterwards.
30#[derive(Clone)]
31pub struct StackState {
32    /// `(resource, dispose method)` pairs, in the order they were pushed.
33    pub resources: Vec<(Value, Value)>,
34    /// Whether this is an `AsyncDisposableStack`.
35    pub async_form: bool,
36    /// Whether `dispose` has already run, which makes it a no-op and `use` a `TypeError`.
37    pub disposed: bool,
38}
39
40impl StackState {
41    /// An empty stack of the given kind.
42    pub fn new(async_form: bool) -> StackState {
43        StackState {
44            resources: Vec::new(),
45            async_form,
46            disposed: false,
47        }
48    }
49}
50
51impl js_gc::Trace for StackState {
52    fn trace(&self, tracer: &mut js_gc::Tracer) {
53        for (value, method) in &self.resources {
54            js_gc::Trace::trace(value, tracer);
55            js_gc::Trace::trace(method, tracer);
56        }
57    }
58}
59
60/// Install both stacks.
61pub fn install(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
62    let disposable_proto = interp.new_object(Some(object_proto.clone()));
63    let constructor = install_one(interp, &disposable_proto, "DisposableStack", false);
64    interp.realm.disposable_stack_proto = Some(disposable_proto);
65
66    let async_proto = interp.new_object(Some(object_proto.clone()));
67    let async_constructor = install_one(interp, &async_proto, "AsyncDisposableStack", true);
68    interp.realm.async_disposable_stack_proto = Some(async_proto);
69
70    let global = interp.realm.global.clone();
71    global.define(
72        "DisposableStack",
73        Property::with_attributes(Value::Object(constructor), true, false),
74    );
75    global.define(
76        "AsyncDisposableStack",
77        Property::with_attributes(Value::Object(async_constructor), true, false),
78    );
79}
80
81fn install_one(
82    interp: &mut Interp<'_>,
83    prototype: &Gc<JsObject>,
84    name: &str,
85    async_form: bool,
86) -> Gc<JsObject> {
87    let constructor = interp.new_native_constructor(name, 0, constructor);
88    constructor.define(
89        "prototype",
90        Property::with_attributes(Value::Object(prototype.clone()), false, false),
91    );
92    prototype.define(
93        "constructor",
94        Property::with_attributes(Value::Object(constructor.clone()), true, false),
95    );
96
97    for (method, length, func) in [
98        ("use", 1, use_ as crate::object::NativeFn),
99        ("adopt", 2, adopt),
100        ("defer", 1, defer),
101        ("move", 0, move_),
102        ("dispose", 0, dispose),
103        ("disposeAsync", 0, dispose_async),
104    ] {
105        // `DisposableStack.prototype` has no `disposeAsync` and `AsyncDisposableStack`'s
106        // has no `dispose`: §24.3.3 and §24.4.3 are separate interfaces, and a shared
107        // method would also make the two stacks interchangeable to `state_of`.
108        let wrong_kind =
109            (method == "dispose" && async_form) || (method == "disposeAsync" && !async_form);
110        if wrong_kind {
111            continue;
112        }
113        define_method(prototype, method, length, func, interp);
114        // Stamp which interface this method belongs to, so `state_of_kind` can refuse a
115        // receiver of the other kind.
116        if let Some(Value::Object(function)) = prototype
117            .own_property(method)
118            .and_then(|property| property.value)
119        {
120            interp.internal_set(&function, "_stack_async", Value::Bool(async_form));
121        }
122    }
123    // `disposed` is an accessor so it cannot be set, and `Symbol.dispose` is what makes
124    // `using stack = new DisposableStack()` work.
125    let getter = interp.new_native("get disposed", 0, disposed_getter);
126    prototype.define(
127        "disposed",
128        Property {
129            getter: Some(Value::Object(getter)),
130            enumerable: false,
131            configurable: true,
132            ..Property::default()
133        },
134    );
135    // `Symbol.dispose` **is** `dispose` and `Symbol.asyncDispose` **is** `disposeAsync` —
136    // one function object each, so `===` holds and the `name` is the method's
137    // (`Symbol.dispose.js`, `Symbol.asyncDispose.js`). Building fresh natives gave two
138    // extra functions whose names were the symbol spelling.
139    let (symbol, name) = if async_form {
140        (WellKnown::AsyncDisposable, "disposeAsync")
141    } else {
142        (WellKnown::Disposable, "dispose")
143    };
144    if let Some(method) = prototype
145        .own_property(name)
146        .and_then(|property| property.value)
147    {
148        prototype.define_key(
149            &interp.realm.well_known_key(symbol),
150            Property::with_attributes(method, true, false),
151        );
152    }
153    // A **data** property holding the string, not a method that answers it: the two
154    // differ in `Object.getOwnPropertyDescriptor(..., Symbol.toStringTag).value` and in
155    // whether the property is writable, and `DisposableStack/prototype/Symbol.toStringTag.js`
156    // checks both. The tag is per-prototype here, so the two stacks get their own.
157    let tag = if async_form {
158        "AsyncDisposableStack"
159    } else {
160        "DisposableStack"
161    };
162    crate::builtins::install_tag(prototype, tag, interp);
163    let _ = async_form;
164    constructor
165}
166
167fn state_of(interp: &Interp<'_>, this: &Value) -> JsResult<StackState> {
168    match this
169        .as_object()
170        .and_then(|object| object.disposable_stack())
171    {
172        Some(state) => Ok(state),
173        None => Err(interp.type_error("method called on a non-DisposableStack")),
174    }
175}
176
177/// [`state_of`] for a method of one interface, refusing the other stack.
178///
179/// Both stacks share one internal slot here, so `RequireInternalSlot(stack,
180/// [[DisposableState]])` cannot be answered from the slot alone: an
181/// `AsyncDisposableStack` has a perfectly good stack on its hands. The interfaces are
182/// separate (§24.3.3 vs §24.4.3), and using one's method on the other is a `TypeError`
183/// (`*/this-does-not-have-internal-*-state-throws`).
184fn state_of_kind(interp: &Interp<'_>, this: &Value) -> JsResult<StackState> {
185    // Which interface the *method* belongs to, stamped on the function object by
186    // [`mark_async`] when it is installed. The receiver alone cannot say: the two stacks
187    // share one internal slot here, exactly like `Map` and `Set`.
188    let async_form = interp
189        .current_native()
190        .and_then(|callee| interp.internal_get(&callee, "_stack_async"))
191        .is_some_and(|value| value.to_boolean());
192    let state = state_of(interp, this)?;
193    if state.async_form != async_form {
194        return Err(interp.type_error("method called on the wrong kind of stack"));
195    }
196    Ok(state)
197}
198
199fn write_back(object: &Gc<JsObject>, state: StackState) {
200    object.set_disposable_stack(state);
201}
202
203/// `new DisposableStack()`.
204fn constructor(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
205    // §24.3.1.1 / §24.4.1.1 step 1: `If NewTarget is undefined, throw a TypeError`. The
206    // call form builds a stack here, which is what `undefined-newtarget-throws` refuses.
207    if !interp.is_constructing() {
208        return Err(interp.type_error("Constructor DisposableStack requires 'new'"));
209    }
210    // `new` hands us the fresh object, whose prototype came from the constructor; a plain
211    // call has no receiver and builds one from the intrinsic prototype.
212    let object = match this.as_object() {
213        Some(object) => object.clone(),
214        None => {
215            let proto = interp
216                .realm
217                .disposable_stack_proto
218                .clone()
219                .unwrap_or_else(|| interp.realm.object_proto.clone());
220            interp.new_object(Some(proto))
221        }
222    };
223    // Which kind this is follows from the prototype the object was built with, so the same
224    // native function can serve both constructors.
225    let async_form = interp
226        .realm
227        .async_disposable_stack_proto
228        .as_ref()
229        .is_some_and(|proto| object.proto().is_some_and(|own| own.ptr_eq(proto)));
230    object.set_disposable_stack(StackState::new(async_form));
231    Ok(Value::Object(object))
232}
233
234/// `stack.use(value)` — validate and push, returning the value.
235fn use_(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
236    let Some(object) = this.as_object() else {
237        return Err(interp.type_error("use called on a non-object"));
238    };
239    let value = arg(args, 0);
240    let mut state = state_of_kind(interp, &this)?;
241    if state.disposed {
242        // §24.3.3.x: a disposed stack's `defer` is a **ReferenceError**, not a `TypeError`.
243        return Err(interp.reference_error("DisposableStack has already been disposed"));
244    }
245    let method = interp.using_method_for(&value, state.async_form)?;
246    // A nullish resource has a nullish method and is still *counted*: `use(null)` is legal
247    // and disposes to nothing.
248    if !value.is_nullish() {
249        state.resources.push((value.clone(), method));
250    }
251    write_back(object, state);
252    Ok(value)
253}
254
255/// `stack.adopt(value, onDispose)` — wrap a resource that has no dispose protocol.
256fn adopt(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
257    let Some(object) = this.as_object() else {
258        return Err(interp.type_error("adopt called on a non-object"));
259    };
260    let value = arg(args, 0);
261    let on_dispose = arg(args, 1);
262    if !on_dispose
263        .as_object()
264        .is_some_and(|function| function.is_callable())
265    {
266        return Err(interp.type_error("adopt needs a disposal function"));
267    }
268    let mut state = state_of_kind(interp, &this)?;
269    if state.disposed {
270        // §24.3.3.x: a disposed stack's `defer` is a **ReferenceError**, not a `TypeError`.
271        return Err(interp.reference_error("DisposableStack has already been disposed"));
272    }
273    // The callback receives the value: `adopt` is how a resource that does not know
274    // `Symbol.dispose` is given a disposer that does. The wrapper *is* the resource as far
275    // as disposal is concerned — it is passed as both the receiver and the method — which is
276    // how it can carry the callback and the value without capturing them.
277    let callable = interp.new_native("onDispose", 1, adopt_callback);
278    callable.define(
279        "_adopts",
280        Property::with_attributes(value.clone(), false, false),
281    );
282    callable.define(
283        "_callback",
284        Property::with_attributes(on_dispose, false, false),
285    );
286    state
287        .resources
288        .push((Value::Object(callable.clone()), Value::Object(callable)));
289    write_back(object, state);
290    Ok(value)
291}
292
293/// The wrapper `adopt` pushes: calls the script's callback with the adopted value.
294fn adopt_callback(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
295    let wrapper = this
296        .as_object()
297        .ok_or_else(|| interp.type_error("adopt wrapper called without a receiver"))?;
298    let value = wrapper
299        .own_property("_adopts")
300        .and_then(|property| property.value)
301        .unwrap_or(Value::Undefined);
302    let callback = wrapper
303        .own_property("_callback")
304        .and_then(|property| property.value)
305        .unwrap_or(Value::Undefined);
306    interp.call_value(callback, Value::Undefined, vec![value])
307}
308
309/// `stack.defer(fn)` — push a plain callback.
310fn defer(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
311    let Some(object) = this.as_object() else {
312        return Err(interp.type_error("defer called on a non-object"));
313    };
314    let callback = arg(args, 0);
315    if !callback
316        .as_object()
317        .is_some_and(|function| function.is_callable())
318    {
319        return Err(interp.type_error("defer needs a callback"));
320    }
321    let mut state = state_of_kind(interp, &this)?;
322    if state.disposed {
323        // §24.3.3.x: a disposed stack's `defer` is a **ReferenceError**, not a `TypeError`.
324        return Err(interp.reference_error("DisposableStack has already been disposed"));
325    }
326    // A deferred callback takes no arguments, so the resource is an absent receiver and the
327    // method is the callback itself.
328    state.resources.push((Value::Undefined, callback));
329    write_back(object, state);
330    Ok(Value::Undefined)
331}
332
333/// `stack.move()` — empty this stack into a fresh one.
334fn move_(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
335    let Some(object) = this.as_object() else {
336        return Err(interp.type_error("move called on a non-object"));
337    };
338    let mut state = state_of_kind(interp, &this)?;
339    if state.disposed {
340        // §24.3.3.x: a disposed stack's `defer` is a **ReferenceError**, not a `TypeError`.
341        return Err(interp.reference_error("DisposableStack has already been disposed"));
342    }
343    let moved = StackState {
344        resources: std::mem::take(&mut state.resources),
345        async_form: state.async_form,
346        disposed: false,
347    };
348    // §24.3.3.7 step 6: the **old** stack is marked disposed, so a second `move` or a
349    // later `defer` on it is refused (`move/sets-state-to-disposed`).
350    state.disposed = true;
351    write_back(object, state);
352    // The new stack comes from the *intrinsic* prototype — replacing or deleting the global
353    // binding must not redirect `move`, which is what the test suite checks.
354    let proto = if moved.async_form {
355        interp.realm.async_disposable_stack_proto.clone()
356    } else {
357        interp.realm.disposable_stack_proto.clone()
358    }
359    .unwrap_or_else(|| interp.realm.object_proto.clone());
360    let fresh = interp.new_object(Some(proto));
361    fresh.set_disposable_stack(moved);
362    Ok(Value::Object(fresh))
363}
364
365/// `stack.dispose()` — dispose everything in reverse order.
366fn dispose(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
367    let Some(object) = this.as_object() else {
368        return Err(interp.type_error("dispose called on a non-object"));
369    };
370    let mut state = state_of_kind(interp, &this)?;
371    if state.disposed {
372        return Ok(Value::Undefined);
373    }
374    state.disposed = true;
375    let resources = std::mem::take(&mut state.resources);
376    write_back(object, state);
377    dispose_all(interp, resources)?;
378    Ok(Value::Undefined)
379}
380
381/// `stack.disposeAsync()` — dispose everything in reverse order, awaiting each disposer.
382///
383/// The resources are handed to the interpreter rather than run here: awaiting a disposer
384/// means parking between two of them, which is the microtask queue's job.
385fn dispose_async(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
386    // `disposeAsync` is an **async function**: a bad receiver or a disposed stack is a
387    // *rejected promise*, never a synchronous throw
388    // (`disposeAsync/this-not-object-rejects`, `…-state-rejects`).
389    let failure = |interp: &mut Interp<'_>, signal: crate::interp::Signal| -> JsResult<Value> {
390        let crate::interp::Signal::Throw(reason) = signal else {
391            return Err(signal);
392        };
393        let promise = interp.new_promise();
394        interp.reject_promise(&promise, reason);
395        Ok(Value::Object(promise))
396    };
397    let Some(object) = this.as_object() else {
398        return failure(
399            interp,
400            interp.type_error("disposeAsync called on a non-object"),
401        );
402    };
403    let state = match state_of_kind(interp, &this) {
404        Ok(state) => state,
405        Err(signal) => return failure(interp, signal),
406    };
407    let mut state = state;
408    if state.disposed {
409        return interp.promise_resolve_value(Value::Undefined);
410    }
411    state.disposed = true;
412    let resources = std::mem::take(&mut state.resources);
413    write_back(object, state);
414    interp.dispose_async_all(resources)
415}
416
417/// Pop and call every resource, folding failures into one `SuppressedError` chain.
418fn dispose_all(interp: &mut Interp<'_>, resources: Vec<(Value, Value)>) -> JsResult<()> {
419    let mut error_state = Value::Uninitialized;
420    for (value, method) in resources.into_iter().rev() {
421        let Some(function) = method.as_object() else {
422            continue;
423        };
424        if !function.is_callable() {
425            continue;
426        }
427        match interp.call_value(Value::Object(function.clone()), value, Vec::new()) {
428            Ok(_) => {}
429            Err(Signal::Throw(thrown)) => {
430                error_state = interp.merge_dispose_error(thrown, error_state);
431            }
432            Err(other) => return Err(other),
433        }
434    }
435    if matches!(error_state, Value::Uninitialized) {
436        return Ok(());
437    }
438    Err(Signal::Throw(error_state))
439}
440
441/// The `disposed` getter.
442fn disposed_getter(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
443    Ok(Value::Bool(state_of(interp, &this)?.disposed))
444}
445
446/// Silence the unused-import warning for `PropertyKey`, which the `define_key` calls above
447/// need only through inference.
448#[allow(dead_code)]
449fn _property_key_is_used(_: PropertyKey) {}