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. The **chain** is walked, not just the
225    // first link: `class My extends AsyncDisposableStack {}` gives an instance whose own
226    // prototype is `My.prototype`, and reading one level made its `move()`/`use()` think it
227    // was the synchronous kind (`move/still-returns-new-asyncdisposablestack-when-subclassed`).
228    let async_form = interp
229        .realm
230        .async_disposable_stack_proto
231        .as_ref()
232        .is_some_and(|proto| {
233            let mut current = object.proto();
234            while let Some(link) = current {
235                if link.ptr_eq(proto) {
236                    return true;
237                }
238                current = link.proto();
239            }
240            false
241        });
242    object.set_disposable_stack(StackState::new(async_form));
243    Ok(Value::Object(object))
244}
245
246/// `stack.use(value)` — validate and push, returning the value.
247fn use_(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
248    let Some(object) = this.as_object() else {
249        return Err(interp.type_error("use called on a non-object"));
250    };
251    let value = arg(args, 0);
252    let mut state = state_of_kind(interp, &this)?;
253    if state.disposed {
254        // §24.3.3.x: a disposed stack's `defer` is a **ReferenceError**, not a `TypeError`.
255        return Err(interp.reference_error("DisposableStack has already been disposed"));
256    }
257    let method = interp.using_method_for(&value, state.async_form)?;
258    // A nullish resource has a nullish method and is still *counted*: `use(null)` is legal,
259    // disposes to nothing, and — because every resource on an `AsyncDisposableStack` carries
260    // the async-dispose hint — still makes `disposeAsync` perform its closing
261    // `Await(undefined)`. Dropping the entry made `use(null); disposeAsync()` settle a tick
262    // early (`disposeAsync/explicit-await-for-null`).
263    state.resources.push((value.clone(), method));
264    write_back(object, state);
265    Ok(value)
266}
267
268/// `stack.adopt(value, onDispose)` — wrap a resource that has no dispose protocol.
269fn adopt(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
270    let Some(object) = this.as_object() else {
271        return Err(interp.type_error("adopt called on a non-object"));
272    };
273    let value = arg(args, 0);
274    let on_dispose = arg(args, 1);
275    if !on_dispose
276        .as_object()
277        .is_some_and(|function| function.is_callable())
278    {
279        return Err(interp.type_error("adopt needs a disposal function"));
280    }
281    let mut state = state_of_kind(interp, &this)?;
282    if state.disposed {
283        // §24.3.3.x: a disposed stack's `defer` is a **ReferenceError**, not a `TypeError`.
284        return Err(interp.reference_error("DisposableStack has already been disposed"));
285    }
286    // The callback receives the value: `adopt` is how a resource that does not know
287    // `Symbol.dispose` is given a disposer that does. The wrapper *is* the resource as far
288    // as disposal is concerned — it is passed as both the receiver and the method — which is
289    // how it can carry the callback and the value without capturing them.
290    let callable = interp.new_native("onDispose", 1, adopt_callback);
291    callable.define(
292        "_adopts",
293        Property::with_attributes(value.clone(), false, false),
294    );
295    callable.define(
296        "_callback",
297        Property::with_attributes(on_dispose, false, false),
298    );
299    state
300        .resources
301        .push((Value::Object(callable.clone()), Value::Object(callable)));
302    write_back(object, state);
303    Ok(value)
304}
305
306/// The wrapper `adopt` pushes: calls the script's callback with the adopted value.
307fn adopt_callback(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
308    let wrapper = this
309        .as_object()
310        .ok_or_else(|| interp.type_error("adopt wrapper called without a receiver"))?;
311    let value = wrapper
312        .own_property("_adopts")
313        .and_then(|property| property.value)
314        .unwrap_or(Value::Undefined);
315    let callback = wrapper
316        .own_property("_callback")
317        .and_then(|property| property.value)
318        .unwrap_or(Value::Undefined);
319    interp.call_value(callback, Value::Undefined, vec![value])
320}
321
322/// `stack.defer(fn)` — push a plain callback.
323fn defer(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
324    let Some(object) = this.as_object() else {
325        return Err(interp.type_error("defer called on a non-object"));
326    };
327    let callback = arg(args, 0);
328    if !callback
329        .as_object()
330        .is_some_and(|function| function.is_callable())
331    {
332        return Err(interp.type_error("defer needs a callback"));
333    }
334    let mut state = state_of_kind(interp, &this)?;
335    if state.disposed {
336        // §24.3.3.x: a disposed stack's `defer` is a **ReferenceError**, not a `TypeError`.
337        return Err(interp.reference_error("DisposableStack has already been disposed"));
338    }
339    // A deferred callback takes no arguments, so the resource is an absent receiver and the
340    // method is the callback itself.
341    state.resources.push((Value::Undefined, callback));
342    write_back(object, state);
343    Ok(Value::Undefined)
344}
345
346/// `stack.move()` — empty this stack into a fresh one.
347fn move_(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
348    let Some(object) = this.as_object() else {
349        return Err(interp.type_error("move called on a non-object"));
350    };
351    let mut state = state_of_kind(interp, &this)?;
352    if state.disposed {
353        // §24.3.3.x: a disposed stack's `defer` is a **ReferenceError**, not a `TypeError`.
354        return Err(interp.reference_error("DisposableStack has already been disposed"));
355    }
356    let moved = StackState {
357        resources: std::mem::take(&mut state.resources),
358        async_form: state.async_form,
359        disposed: false,
360    };
361    // §24.3.3.7 step 6: the **old** stack is marked disposed, so a second `move` or a
362    // later `defer` on it is refused (`move/sets-state-to-disposed`).
363    state.disposed = true;
364    write_back(object, state);
365    // The new stack comes from the *intrinsic* prototype — replacing or deleting the global
366    // binding must not redirect `move`, which is what the test suite checks.
367    let proto = if moved.async_form {
368        interp.realm.async_disposable_stack_proto.clone()
369    } else {
370        interp.realm.disposable_stack_proto.clone()
371    }
372    .unwrap_or_else(|| interp.realm.object_proto.clone());
373    let fresh = interp.new_object(Some(proto));
374    fresh.set_disposable_stack(moved);
375    Ok(Value::Object(fresh))
376}
377
378/// `stack.dispose()` — dispose everything in reverse order.
379fn dispose(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
380    let Some(object) = this.as_object() else {
381        return Err(interp.type_error("dispose called on a non-object"));
382    };
383    let mut state = state_of_kind(interp, &this)?;
384    if state.disposed {
385        return Ok(Value::Undefined);
386    }
387    state.disposed = true;
388    let resources = std::mem::take(&mut state.resources);
389    write_back(object, state);
390    dispose_all(interp, resources)?;
391    Ok(Value::Undefined)
392}
393
394/// `stack.disposeAsync()` — dispose everything in reverse order, awaiting each disposer.
395///
396/// The resources are handed to the interpreter rather than run here: awaiting a disposer
397/// means parking between two of them, which is the microtask queue's job.
398fn dispose_async(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
399    // `disposeAsync` is an **async function**: a bad receiver or a disposed stack is a
400    // *rejected promise*, never a synchronous throw
401    // (`disposeAsync/this-not-object-rejects`, `…-state-rejects`).
402    let failure = |interp: &mut Interp<'_>, signal: crate::interp::Signal| -> JsResult<Value> {
403        let crate::interp::Signal::Throw(reason) = signal else {
404            return Err(signal);
405        };
406        let promise = interp.new_promise();
407        interp.reject_promise(&promise, reason);
408        Ok(Value::Object(promise))
409    };
410    let Some(object) = this.as_object() else {
411        return failure(
412            interp,
413            interp.type_error("disposeAsync called on a non-object"),
414        );
415    };
416    let state = match state_of_kind(interp, &this) {
417        Ok(state) => state,
418        Err(signal) => return failure(interp, signal),
419    };
420    let mut state = state;
421    if state.disposed {
422        return interp.promise_resolve_value(Value::Undefined);
423    }
424    state.disposed = true;
425    let resources = std::mem::take(&mut state.resources);
426    write_back(object, state);
427    interp.dispose_async_all(resources)
428}
429
430/// Pop and call every resource, folding failures into one `SuppressedError` chain.
431fn dispose_all(interp: &mut Interp<'_>, resources: Vec<(Value, Value)>) -> JsResult<()> {
432    let mut error_state = Value::Uninitialized;
433    for (value, method) in resources.into_iter().rev() {
434        let Some(function) = method.as_object() else {
435            continue;
436        };
437        if !function.is_callable() {
438            continue;
439        }
440        match interp.call_value(Value::Object(function.clone()), value, Vec::new()) {
441            Ok(_) => {}
442            Err(Signal::Throw(thrown)) => {
443                error_state = interp.merge_dispose_error(thrown, error_state);
444            }
445            Err(other) => return Err(other),
446        }
447    }
448    if matches!(error_state, Value::Uninitialized) {
449        return Ok(());
450    }
451    Err(Signal::Throw(error_state))
452}
453
454/// The `disposed` getter.
455fn disposed_getter(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
456    Ok(Value::Bool(state_of(interp, &this)?.disposed))
457}
458
459/// Silence the unused-import warning for `PropertyKey`, which the `define_key` calls above
460/// need only through inference.
461#[allow(dead_code)]
462fn _property_key_is_used(_: PropertyKey) {}