Skip to main content

quickjs/builtins/
weak.rs

1//! `WeakMap`, `WeakSet`, `WeakRef` and `FinalizationRegistry`.
2//!
3//! # Why these are cheap here
4//!
5//! The engine frees memory by reference counting with a cycle collector, so a box is
6//! released the instant its last strong handle dies. [`WeakGc`] therefore already has the
7//! two properties these classes need:
8//!
9//! * it does not keep the target alive (it owns no strong reference), and
10//! * it does not participate in cycle detection (`Trace for WeakGc` visits nothing), so a
11//!   `WeakMap` whose key is only reachable through the map does not keep the cycle alive.
12//!
13//! That means a `WeakMap` entry disappears exactly when its key dies, with no second
14//! "clear the dead entries" pass and no tracing-collector machinery: the map stores a
15//! `WeakGc` per key, and looking a key up simply finds nothing once `upgrade` fails.
16//!
17//! # What is *not* free: scheduling the cleanup callback
18//!
19//! `FinalizationRegistry`'s cleanup callback must run "some time after" the target dies,
20//! at a point when script is not running. Reference counting can notice a death precisely
21//! (the strong count hits zero) but the crate gives no hook for it, and running script from
22//! inside a `Drop` would be a re-entrancy hazard of the worst kind — the drop can happen
23//! while a `RefCell` is borrowed, in the middle of arbitrary engine bookkeeping.
24//!
25//! So the registry is drained at a *safe point* instead: [`drain_finalizers`] is called
26//! from the microtask checkpoint, which is where a host may run script after a job anyway,
27//! and it collects every registration whose target has expired by then. The observable
28//! difference from a real GC is only *when* the callback fires — "at the next turn of the
29//! event loop" rather than "at an unpredictable later moment" — which is within what
30//! §9.10 permits and is what test262's own `$262.gc` hook models.
31//!
32//! # Why `WeakMap` uses `WeakGc<JsObject>` and not a symbol-keyed secret
33//!
34//! A key must be an object, and two objects are one key exactly when they are the same
35//! object. `ptr_eq` on a `WeakGc` answers that in one comparison, with no property written
36//! onto the key — which matters, because a `WeakMap` must not add observable properties.
37
38use crate::builtins::{arg, define_method};
39use crate::interp::{Interp, JsResult, WellKnown};
40use crate::object::{FinalizationState, JsObject, Property, Registration, weak_key};
41use crate::value::Value;
42use js_gc::Gc;
43
44/// Install the four globals.
45pub fn install(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
46    install_weak_collection(interp, object_proto, true);
47    install_weak_collection(interp, object_proto, false);
48    install_weak_ref(interp, object_proto);
49    install_finalization(interp, object_proto);
50}
51
52/// The `Symbol.toStringTag` a prototype carries, so `Object.prototype.toString` can name it.
53///
54/// `{ [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }` — the read-only,
55/// non-enumerable shape every builtin tag uses. `Property::data` defaults to writable and
56/// enumerable, which `verifyProperty` catches.
57fn install_tag(interp: &mut Interp<'_>, proto: &Gc<JsObject>, tag: &str) {
58    let key = interp.realm.well_known_key(WellKnown::ToStringTag);
59    proto.define_key(
60        &key,
61        Property {
62            value: Some(interp.string(tag)),
63            writable: false,
64            enumerable: false,
65            configurable: true,
66            ..Property::default()
67        },
68    );
69}
70
71/// `WeakMap` (`is_map`) and `WeakSet`, whose surface differs only in the value slot.
72fn install_weak_collection(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>, is_map: bool) {
73    let name = if is_map { "WeakMap" } else { "WeakSet" };
74    let proto = interp.new_object(Some(object_proto.clone()));
75    // `length` is 0: the constructor takes an optional `iterable` and nothing required.
76    //
77    // Two distinct function pointers rather than one that reads a flag off the callee: a
78    // native constructor runs with `this = undefined` and its callee is not reliably
79    // reachable from inside the call, so a flag lookup silently fell back to `WeakMap` and
80    // made `new WeakSet().add(1)` complain about the receiver's brand.
81    let constructor = interp.new_native_constructor(
82        name,
83        0,
84        if is_map {
85            weak_map_constructor as crate::object::NativeFn
86        } else {
87            weak_set_constructor
88        },
89    );
90    constructor.define(
91        "prototype",
92        Property::with_attributes(Value::Object(proto.clone()), false, false),
93    );
94    proto.define(
95        "constructor",
96        Property::with_attributes(Value::Object(constructor.clone()), true, false),
97    );
98    if is_map {
99        for (method_name, length, func) in [
100            ("get", 1, weak_get as crate::object::NativeFn),
101            ("set", 2, weak_set),
102            ("has", 1, weak_has),
103            ("delete", 1, weak_delete),
104            // `getOrInsert`/`getOrInsertComputed` are the ES2026 proposal methods; the
105            // reference implementation has them and test262 already tests them.
106            ("getOrInsert", 2, weak_get_or_insert),
107            ("getOrInsertComputed", 2, weak_get_or_insert_computed),
108        ] {
109            define_method(&proto, method_name, length, func, interp);
110        }
111    } else {
112        for (method_name, length, func) in [
113            ("add", 1, weak_add as crate::object::NativeFn),
114            ("has", 1, weak_has),
115            ("delete", 1, weak_delete),
116        ] {
117            define_method(&proto, method_name, length, func, interp);
118        }
119    }
120    install_tag(interp, &proto, name);
121    let global = interp.realm.global.clone();
122    global.define(
123        name,
124        Property::with_attributes(Value::Object(constructor), true, false),
125    );
126}
127
128/// The `prototype` of the global constructor called `name`.
129///
130/// A native constructor builds its own instance, so it has to name its default prototype
131/// itself. Looking it up through the global keeps `WeakMap.prototype = {...}` observable in
132/// the constructor path the way it is for a script class.
133fn constructor_prototype(interp: &mut Interp<'_>, name: &str) -> Option<Gc<JsObject>> {
134    let property = interp.realm.global.own_property(name)?;
135    let constructor = property.value?.as_object().cloned()?;
136    Some(interp.prototype_of(&constructor))
137}
138
139/// `IteratorClose`, ignoring an error from `return` itself.
140///
141/// The "we are already leaving" path swallows a throwing `return`, which is what §7.4.11
142/// asks for: the original abrupt completion is the one the script sees.
143fn close_iterator(interp: &mut Interp<'_>, iterator: &crate::interp::Iterator) -> JsResult<()> {
144    let Some(target) = iterator.object.as_object().cloned() else {
145        return Ok(());
146    };
147    match interp.get_property(&target, "return")? {
148        Some(Value::Object(function)) if function.is_callable() => {
149            interp.call_value(Value::Object(function), iterator.object.clone(), Vec::new())?;
150            Ok(())
151        }
152        _ => Ok(()),
153    }
154}
155
156/// The receiver, which must be a weak collection of the expected kind.
157///
158/// Two refusals to keep apart: a receiver that is not a weak collection at all is
159/// `TypeError: WeakMap object expected`, and a `WeakSet` passed to a `WeakMap` method (or
160/// the reverse) is a `TypeError` as well — the spec brands each prototype separately, which
161/// is why one shared implementation still has to check the kind.
162fn this_weak(interp: &Interp<'_>, this: &Value, want_map: bool) -> JsResult<(Gc<JsObject>, bool)> {
163    let object = this
164        .as_object()
165        .cloned()
166        .ok_or_else(|| interp.type_error("invalid receiver"))?;
167    let is_map = match object.weak_is_set() {
168        Some(is_set) => !is_set,
169        None => {
170            let name = if want_map { "WeakMap" } else { "WeakSet" };
171            return Err(interp.type_error(format!("{name} object expected")));
172        }
173    };
174    if is_map != want_map {
175        let name = if want_map { "WeakMap" } else { "WeakSet" };
176        return Err(interp.type_error(format!("{name} object expected")));
177    }
178    Ok((object, is_map))
179}
180
181/// `new WeakMap(iterable)`.
182fn weak_map_constructor(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
183    new_weak_collection(interp, this, args, true)
184}
185
186/// `new WeakSet(iterable)`.
187fn weak_set_constructor(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
188    new_weak_collection(interp, this, args, false)
189}
190
191/// The shared body of the two constructors.
192fn new_weak_collection(
193    interp: &mut Interp<'_>,
194    _this: Value,
195    args: &[Value],
196    is_map: bool,
197) -> JsResult<Value> {
198    if !interp.is_constructing() {
199        return Err(interp.type_error("must be called with new"));
200    }
201    let default_proto =
202        match constructor_prototype(interp, if is_map { "WeakMap" } else { "WeakSet" }) {
203            Some(proto) => proto,
204            None => interp.realm.object_proto.clone(),
205        };
206    // `new.target.prototype` is read *after* the arguments are validated in the spec, but
207    // for these two there is nothing to validate before the instance exists, so building it
208    // first is observable only through a `prototype` getter — which the reference also does
209    // not hit early.
210    let object = interp.new_ctor_instance(default_proto)?;
211    object.set_weak_collection(interp.heap, Vec::new(), !is_map);
212
213    // `AddEntriesFromIterable`: a non-iterable, non-undefined argument is a `TypeError` from
214    // `GetIterator`, and each entry of a `WeakMap` must itself be a two-element object.
215    //
216    // Iterated one step at a time rather than through `collect_iterable`, because the body
217    // can throw (a poisoned `[[1]]` getter, an unyieldable entry) and an abrupt completion
218    // has to close the iterator. Draining first would read an *infinite* iterator to the end
219    // before noticing: `iterator-item-second-entry-returns-abrupt` is exactly that shape,
220    // and draining it is a hang rather than a failure.
221    let source = arg(args, 0);
222    if matches!(source, Value::Undefined | Value::Null) {
223        return Ok(Value::Object(object));
224    }
225    // §24.2.1.1 step 7: the *adder* is `Get(instance, "set")` (or `"add"`) and is called for
226    // every entry. Going straight to the internal slot instead would hide two things the
227    // spec makes observable: a script that replaces `WeakMap.prototype.set` must see the
228    // constructor's calls, and a non-callable `set` must make `new WeakMap([])` a
229    // `TypeError` even though there is nothing to insert.
230    let adder_name = if is_map { "set" } else { "add" };
231    let adder = interp
232        .get_property(&object, adder_name)?
233        .unwrap_or(Value::Undefined);
234    if !adder.as_object().is_some_and(|adder| adder.is_callable()) {
235        return Err(interp.type_error(format!("{adder_name} is not callable")));
236    }
237    let iterator = interp.get_iterator(&source)?;
238    loop {
239        let (entry, done) = interp.iterator_step(&iterator)?;
240        if done {
241            break;
242        }
243        // `IfAbruptCloseIterator` around the body: whatever goes wrong here, the iterator
244        // is told, and the original error is the one that propagates.
245        let body = (|| -> JsResult<()> {
246            if is_map {
247                // `Get(nextItem, "0")` then `Get(nextItem, "1")`, both observable.
248                let Some(pair) = entry.as_object().cloned() else {
249                    return Err(interp.type_error("iterator value is not an entry object"));
250                };
251                let key = interp.get_property(&pair, "0")?.unwrap_or(Value::Undefined);
252                let value = interp.get_property(&pair, "1")?.unwrap_or(Value::Undefined);
253                interp.call_value(
254                    adder.clone(),
255                    Value::Object(object.clone()),
256                    vec![key, value],
257                )?;
258            } else {
259                interp.call_value(adder.clone(), Value::Object(object.clone()), vec![entry])?;
260            }
261            Ok(())
262        })();
263        if let Err(signal) = body {
264            let _ = close_iterator(interp, &iterator);
265            return Err(signal);
266        }
267    }
268    Ok(Value::Object(object))
269}
270
271/// `WeakMap.prototype.set`'s and the constructor's shared "insert one pair" step.
272fn set_weak_entry(
273    interp: &Interp<'_>,
274    object: &Gc<JsObject>,
275    key: &Value,
276    value: Value,
277) -> JsResult<()> {
278    // `CanBeHeldWeakly`: an object, or a *registered* symbol. A plain `Symbol()` is a fresh
279    // primitive every time it is written, so there is nothing whose lifetime could be
280    // observed — but `Symbol.for("k")` answers the same symbol for the same key and can be
281    // referenced again, so the proposal allows it.
282    let Some(key) = weak_key(key) else {
283        return Err(interp.type_error("invalid value used as WeakMap key"));
284    };
285    object.weak_set(key, value);
286    Ok(())
287}
288
289/// `WeakSet.prototype.add`'s and the constructor's shared "insert one key" step.
290fn add_weak_entry(interp: &Interp<'_>, object: &Gc<JsObject>, key: &Value) -> JsResult<()> {
291    let Some(key) = weak_key(key) else {
292        return Err(interp.type_error("invalid value used as WeakSet key"));
293    };
294    object.weak_set(key, Value::Undefined);
295    Ok(())
296}
297
298/// `WeakMap.prototype.set(key, value)`.
299fn weak_set(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
300    let (object, _) = this_weak(interp, &this, true)?;
301    set_weak_entry(interp, &object, &arg(args, 0), arg(args, 1))?;
302    Ok(this)
303}
304
305/// `WeakSet.prototype.add(value)`.
306fn weak_add(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
307    let (object, _) = this_weak(interp, &this, false)?;
308    add_weak_entry(interp, &object, &arg(args, 0))?;
309    Ok(this)
310}
311
312/// `WeakMap.prototype.get(key)` and, for a `WeakSet`, the value behind `has`/`delete`.
313///
314/// A key that is not an object answers `undefined`/`false` rather than throwing: the
315/// spec's `CanBeHeldWeakly` check returns early instead of raising.
316fn weak_lookup(_interp: &Interp<'_>, object: &Gc<JsObject>, key: &Value) -> Option<Value> {
317    object
318        .weak_entries()?
319        .into_iter()
320        .find(|(existing, _)| existing.same_value(key))
321        .map(|(_, value)| value)
322}
323
324/// `WeakMap.prototype.get(key)`.
325fn weak_get(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
326    let (object, _) = this_weak(interp, &this, true)?;
327    Ok(weak_lookup(interp, &object, &arg(args, 0)).unwrap_or(Value::Undefined))
328}
329
330/// `WeakMap.prototype.has(key)` / `WeakSet.prototype.has(value)`.
331fn weak_has(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
332    let object = this
333        .as_object()
334        .cloned()
335        .ok_or_else(|| interp.type_error("invalid receiver"))?;
336    if object.weak_is_set().is_none() {
337        return Err(interp.type_error("invalid receiver"));
338    }
339    Ok(Value::Bool(
340        weak_lookup(interp, &object, &arg(args, 0)).is_some(),
341    ))
342}
343
344/// `WeakMap.prototype.delete(key)` / `WeakSet.prototype.delete(value)`.
345fn weak_delete(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
346    let object = this
347        .as_object()
348        .cloned()
349        .ok_or_else(|| interp.type_error("invalid receiver"))?;
350    if object.weak_is_set().is_none() {
351        return Err(interp.type_error("invalid receiver"));
352    }
353    Ok(Value::Bool(object.weak_delete(&arg(args, 0))))
354}
355
356/// `WeakMap.prototype.getOrInsert(key, value)`.
357fn weak_get_or_insert(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
358    let (object, _) = this_weak(interp, &this, true)?;
359    if let Some(found) = weak_lookup(interp, &object, &arg(args, 0)) {
360        return Ok(found);
361    }
362    let value = arg(args, 1);
363    set_weak_entry(interp, &object, &arg(args, 0), value.clone())?;
364    Ok(value)
365}
366
367/// `WeakMap.prototype.getOrInsertComputed(key, callback)`.
368///
369/// The callback runs *only* on a miss, and it runs before the entry is stored — so a
370/// re-entrant insert from inside the callback wins, which is what `GetOrInsertComputed`
371/// specifies and what a test checks.
372fn weak_get_or_insert_computed(
373    interp: &mut Interp<'_>,
374    this: Value,
375    args: &[Value],
376) -> JsResult<Value> {
377    let (object, _) = this_weak(interp, &this, true)?;
378    let key = arg(args, 0);
379    let Some(key_handle) = weak_key(&key) else {
380        return Err(interp.type_error("invalid value used as WeakMap key"));
381    };
382    let callback = arg(args, 1);
383    if !callback
384        .as_object()
385        .is_some_and(|object| object.is_callable())
386    {
387        return Err(interp.type_error("callback is not callable"));
388    }
389    if let Some(found) = weak_lookup(interp, &object, &key) {
390        return Ok(found);
391    }
392    let computed = interp.call_value(callback, Value::Undefined, vec![key.clone()])?;
393    // No second lookup: the upsert stages say "set the value, append the record" *after* the
394    // callback returns, unconditionally. Re-checking here would keep whatever the callback
395    // inserted and made `map.getOrInsertComputed(k, () => { map.set(k, 0); return 3 })`
396    // answer `0` where the spec settles on `3`. Note that `bar`'s callback returns
397    // `undefined`, and that `undefined` does overwrite.
398    object.weak_set(key_handle, computed.clone());
399    Ok(computed)
400}
401
402/// `WeakRef`.
403fn install_weak_ref(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
404    let proto = interp.new_object(Some(object_proto.clone()));
405    let constructor = interp.new_native_constructor("WeakRef", 1, weak_ref_constructor);
406    constructor.define(
407        "prototype",
408        Property::with_attributes(Value::Object(proto.clone()), false, false),
409    );
410    proto.define(
411        "constructor",
412        Property::with_attributes(Value::Object(constructor.clone()), true, false),
413    );
414    define_method(&proto, "deref", 0, deref, interp);
415    install_tag(interp, &proto, "WeakRef");
416    let global = interp.realm.global.clone();
417    global.define(
418        "WeakRef",
419        Property::with_attributes(Value::Object(constructor), true, false),
420    );
421}
422
423/// `new WeakRef(target)`.
424fn weak_ref_constructor(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
425    if !interp.is_constructing() {
426        return Err(interp.type_error("constructor requires 'new'"));
427    }
428    // The target has to be an object: a primitive cannot be weakly referenced because there
429    // would be nothing whose lifetime to observe. The error text matches the reference.
430    let Some(target) = weak_key(&arg(args, 0)) else {
431        return Err(interp.type_error("invalid target"));
432    };
433    let default_proto = match constructor_prototype(interp, "WeakRef") {
434        Some(proto) => proto,
435        None => interp.realm.object_proto.clone(),
436    };
437    let object = interp.new_ctor_instance(default_proto)?;
438    object.set_weak_ref(target);
439    Ok(Value::Object(object))
440}
441
442/// `WeakRef.prototype.deref()`.
443///
444/// Answers the target while it is alive and `undefined` afterwards. Because the engine
445/// frees on the last strong release, this becomes `undefined` *immediately* once nothing
446/// else holds the target — which is the strongest form of the guarantee the spec requires
447/// ("no earlier than" the end of the current job).
448fn deref(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
449    let object = this
450        .as_object()
451        .ok_or_else(|| interp.type_error("invalid receiver"))?;
452    let target = object
453        .weak_ref_target()
454        .ok_or_else(|| interp.type_error("invalid receiver"))?;
455    Ok(target.upgrade().unwrap_or(Value::Undefined))
456}
457
458/// `FinalizationRegistry`.
459fn install_finalization(interp: &mut Interp<'_>, object_proto: &Gc<JsObject>) {
460    let proto = interp.new_object(Some(object_proto.clone()));
461    let constructor =
462        interp.new_native_constructor("FinalizationRegistry", 1, finalization_constructor);
463    constructor.define(
464        "prototype",
465        Property::with_attributes(Value::Object(proto.clone()), false, false),
466    );
467    proto.define(
468        "constructor",
469        Property::with_attributes(Value::Object(constructor.clone()), true, false),
470    );
471    define_method(&proto, "register", 2, register, interp);
472    define_method(&proto, "unregister", 1, unregister, interp);
473    define_method(&proto, "cleanupSome", 0, cleanup_some, interp);
474    install_tag(interp, &proto, "FinalizationRegistry");
475    let global = interp.realm.global.clone();
476    global.define(
477        "FinalizationRegistry",
478        Property::with_attributes(Value::Object(constructor), true, false),
479    );
480}
481
482/// `new FinalizationRegistry(cleanupCallback)`.
483fn finalization_constructor(
484    interp: &mut Interp<'_>,
485    _this: Value,
486    args: &[Value],
487) -> JsResult<Value> {
488    if !interp.is_constructing() {
489        return Err(interp.type_error("constructor requires 'new'"));
490    }
491    // The callback is validated *before* the instance is built, so
492    // `Reflect.construct(FinalizationRegistry, [1], badTarget)` throws for the callback
493    // rather than for the poisoned `prototype`.
494    let cleanup = arg(args, 0);
495    if !cleanup
496        .as_object()
497        .is_some_and(|object| object.is_callable())
498    {
499        return Err(interp.type_error("argument must be a function"));
500    }
501    let default_proto = match constructor_prototype(interp, "FinalizationRegistry") {
502        Some(proto) => proto,
503        None => interp.realm.object_proto.clone(),
504    };
505    let object = interp.new_ctor_instance(default_proto)?;
506    object.set_finalization_state(FinalizationState {
507        registrations: Vec::new(),
508        cleanup,
509    });
510    // Tell the safe point about this registry. The handle is weak, so the registry stays
511    // collectable and being on this list never keeps it — or its held values — alive.
512    interp
513        .realm
514        .finalization_registries
515        .push(object.downgrade());
516    Ok(Value::Object(object))
517}
518
519/// The registry behind `this`, or a `TypeError`.
520fn this_registry(interp: &Interp<'_>, this: &Value) -> JsResult<(Gc<JsObject>, FinalizationState)> {
521    let object = this
522        .as_object()
523        .cloned()
524        .ok_or_else(|| interp.type_error("invalid receiver"))?;
525    let state = object
526        .finalization_state()
527        .ok_or_else(|| interp.type_error("invalid receiver"))?;
528    Ok((object, *state))
529}
530
531/// `FinalizationRegistry.prototype.register(target, heldValue, unregisterToken)`.
532fn register(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
533    let (object, mut state) = this_registry(interp, &this)?;
534    let target_value = arg(args, 0);
535    let Some(target) = weak_key(&target_value) else {
536        return Err(interp.type_error("invalid target"));
537    };
538    // The held value must not be the target: the registry keeps held values alive, so
539    // `fr.register(t, t)` would keep `t` alive through the registry forever and the
540    // callback could never fire. The spec refuses it for exactly that reason.
541    let held_value = arg(args, 1);
542    if held_value.same_value(&target_value) {
543        return Err(interp.type_error("the held value must not be the target itself"));
544    }
545    // The token, on the other hand, *may* be the target: §26.2.3.1 step 5 only requires it
546    // to be an object or `undefined`. A registry does not keep tokens alive, so using the
547    // target as its own token cannot resurrect it — `unregisterToken-same-as-target` asks
548    // for precisely this and expects success.
549    let token = match args.get(2) {
550        None | Some(Value::Undefined) => None,
551        Some(token) => {
552            // The token follows `CanBeHeldWeakly`: an object, or an *unregistered* symbol.
553            // Unlike the target, a registered symbol is refused here. §26.2.3.1 is about
554            // what the registry can hold weakly, and a registered symbol never dies.
555            if weak_key(token).is_none() {
556                return Err(interp.type_error("invalid unregister token"));
557            }
558            Some(token.clone())
559        }
560    };
561    state.registrations.push(Registration {
562        target,
563        held_value,
564        token,
565    });
566    object.set_finalization_state(state);
567    Ok(Value::Undefined)
568}
569
570/// `FinalizationRegistry.prototype.unregister(token)`, answering whether anything was
571/// removed. `SameValue` decides identity, so `0` and `-0` are one token and `NaN` is its
572/// own — which is why this compares with `Value::same_value` rather than a hash.
573fn unregister(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
574    let (object, mut state) = this_registry(interp, &this)?;
575    let token = arg(args, 0);
576    // The same `CanBeHeldWeakly` rule as `register`: an object, or a symbol that is not in
577    // the registry. A *well-known* symbol qualifies (it is one unique allocation), while
578    // `Symbol.for("k")` does not — so `unregister(Symbol.hasInstance)` answers `false`
579    // where `unregister(Symbol.for("s"))` is a `TypeError`. A primitive is a `TypeError`
580    // rather than `false`.
581    if weak_key(&token).is_none() {
582        return Err(interp.type_error("invalid unregister token"));
583    }
584    let before = state.registrations.len();
585    state
586        .registrations
587        .retain(|registration| match &registration.token {
588            Some(existing) => !existing.same_value(&token),
589            None => true,
590        });
591    let removed = state.registrations.len() != before;
592    object.set_finalization_state(state);
593    Ok(Value::Bool(removed))
594}
595
596/// `FinalizationRegistry.prototype.cleanupSome(callback)`.
597///
598/// Runs the registrations whose targets have died *now*, optionally through a one-off
599/// callback instead of the one the registry was built with.
600fn cleanup_some(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
601    let (object, state) = this_registry(interp, &this)?;
602    let callback = match arg(args, 0) {
603        Value::Undefined => state.cleanup.clone(),
604        other => {
605            if !other.as_object().is_some_and(|object| object.is_callable()) {
606                return Err(interp.type_error("argument must be a function"));
607            }
608            other
609        }
610    };
611    let dead: Vec<Value> = state
612        .registrations
613        .iter()
614        .filter(|registration| registration.target.is_expired())
615        .map(|registration| registration.held_value.clone())
616        .collect();
617    // Drop them first: the callback may throw, and a registration whose held value was
618    // already handed over must not be handed over twice.
619    let mut remaining = state;
620    remaining
621        .registrations
622        .retain(|registration| !registration.target.is_expired());
623    object.set_finalization_state(remaining);
624    for held in dead {
625        interp.call_value(callback.clone(), Value::Undefined, vec![held])?;
626    }
627    Ok(Value::Undefined)
628}
629
630/// Run every expired registration, across every registry on the realm.
631///
632/// Called from the microtask checkpoint rather than from a drop hook: see this module's
633/// header for why. The registries are found by walking the heap's live objects, which is
634/// acceptable because this runs once per drain and not per operation.
635pub fn drain_finalizers(interp: &mut Interp<'_>) -> JsResult<()> {
636    let registries = interp.live_registries();
637    for (object, state) in registries {
638        let dead: Vec<Value> = state
639            .registrations
640            .iter()
641            .filter(|registration| registration.target.is_expired())
642            .map(|registration| registration.held_value.clone())
643            .collect();
644        if dead.is_empty() {
645            continue;
646        }
647        let mut remaining = state;
648        remaining
649            .registrations
650            .retain(|registration| !registration.target.is_expired());
651        let cleanup = remaining.cleanup.clone();
652        object.set_finalization_state(remaining);
653        for held in dead {
654            interp.call_value(cleanup.clone(), Value::Undefined, vec![held])?;
655        }
656    }
657    Ok(())
658}