Skip to main content

Crate js_gc

Crate js_gc 

Source
Expand description

quickjs-gc — reference counting with cycle collection.

QuickJS frees memory by reference counting and removes reference cycles with a periodic collector (see JS_RunGC / JS_SetGCThreshold in the C API). Its observable behaviour — an object is released as soon as the last reference goes away, finalizers run at that moment, and cycles are reclaimed only when the collector runs — is part of the semantics we have to reproduce, so we use the same algorithm instead of a tracing GC.

This crate provides:

  • Heap — one per [Runtime]-equivalent; owns the registry of live boxes, the allocation accounting and the collector.
  • Gc<T> — a strong, reference-counted handle. Cheap to clone, derefs to T, releases the value deterministically when the last handle dies.
  • WeakGc<T> — a non-owning handle that does not keep the value alive and does not participate in cycle detection (used by WeakRef, WeakMap and FinalizationRegistry).
  • Trace — implemented by every type that can own Gc handles, so the collector can walk the object graph.

§The collector

Heap::collect implements trial deletion (Bacon–Rajan “synchronous cycle collection”):

  1. Every live box starts with gc_refs = strong_count.
  2. Every internal edge (a Gc field inside another box) decrements the child’s gc_refs. After this pass gc_refs > 0 means “at least one reference lives outside the heap”, i.e. the box is a root.
  3. Mark everything reachable from the roots.
  4. Unmarked boxes are only reachable from garbage: their values are dropped (which releases the handles they hold) and the boxes themselves are freed once their strong count reaches zero.

§Contract

  • A Heap must outlive every Gc created from it. Dropping a heap with live boxes leaks them; it is not undefined behaviour.
  • Trace::trace must not mutate the object graph, allocate, or panic: it runs while the collector holds a snapshot of the heap.
  • Gc<T>/WeakGc<T> are !Send + !Sync: a heap is single threaded, which matches a QuickJS JSRuntime (JS_SetSharedArrayBufferFunctions is the only cross-thread escape hatch and it is handled in js-value).

Structs§

CollectStats
Statistics returned by Heap::collect.
Gc
A strong, reference-counted handle to a heap value.
Heap
Owns the live-object registry for one JavaScript runtime.
Tracer
Visitor used by Trace implementations.
WeakGc
A non-owning handle to a heap value.

Traits§

Trace
Types that may own Gc handles.