Skip to content

Truly independent web browser

Meta+LibJS: Add a rustc driver with lints for libjs_rust's GC

Shannon Booth3adec3652454
diff --git a/Cargo.toml b/Cargo.toml
index bee09548595..af979efa78a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -40,6 +40,9 @@ incremental = false
codegen-units = 1
lto = true
+[workspace.lints.rust]
+unexpected_cfgs = { level = "deny", check-cfg = ["cfg(ladybird_gc_lints)"] }
+
[workspace.lints.clippy]
all = "deny" # includes lintgroups: correctness, suspicious, style, complexity, perf
# from clippy:nursery:
diff --git a/Libraries/LibJS/Rust/src/bytecode/executable.rs b/Libraries/LibJS/Rust/src/bytecode/executable.rs
index 67a350c0a16..9b93fc6f7e0 100644
--- a/Libraries/LibJS/Rust/src/bytecode/executable.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/executable.rs
@@ -28,6 +28,7 @@ use crate::gc::defer_gc::DeferGc;
use crate::gc::root::MarkedVec;
use crate::gc::sweep::Sweep;
use crate::gc::visitor::{Trace, Visitor};
+use crate::gc::weak::SweptAfterCollection;
use crate::interpreter::vm::Vm;
use crate::jit::InterpreterTier;
use crate::jit::code::ExecutableJitState;
@@ -140,6 +141,10 @@ impl PropertyLookupCacheEntryData {
}
}
+// SAFETY: Entries live in the inline caches of executables and of the VM, which the VM sweeps after each collection (see
+// Vm::remove_dead_cells_from_property_lookup_caches()).
+unsafe impl SweptAfterCollection for PropertyLookupCacheEntry {}
+
impl PropertyLookupCacheEntry {
pub fn new() -> Self {
Self::from_data(PropertyLookupCacheEntryData::default())
@@ -887,6 +892,10 @@ pub struct KeyedPropertyLookupCacheEntry {
}
const _: () = assert!(size_of::<KeyedPropertyLookupCacheEntry>() == 64);
+
+// SAFETY: Entries only live in the VM's keyed property lookup caches, which the VM sweeps after each collection (see
+// Vm::remove_dead_cells_from_property_lookup_caches()).
+unsafe impl SweptAfterCollection for KeyedPropertyLookupCacheEntry {}
// NB: The interpreter reads entries with the layout of KeyedPropertyLookupCacheEntryLayout, and finds them the way
// entry_index_for() does.
const _: () = assert!(
diff --git a/Libraries/LibJS/Rust/src/gc/lint_markers.rs b/Libraries/LibJS/Rust/src/gc/lint_markers.rs
new file mode 100644
index 00000000000..5ce320f1928
--- /dev/null
+++ b/Libraries/LibJS/Rust/src/gc/lint_markers.rs
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The traits Ladybird's Rust GC lints (Meta/RustLints) find the types of the GC by, so that moving or renaming one
+//! does not hide it from them. The lints stop with an error if one of these traits is missing. A GC pointer needs no
+//! marker: the lints count every type that implements Trace by hand as one, as Gc, Value and PropertyKey do.
+
+use super::defer_gc::{DeferGc, Deferred};
+use super::root::{MarkedVec, Root};
+use super::sweep::Sweep;
+use super::visitor::Trace;
+use crate::interpreter::vm::Vm;
+
+/// A type whose values keep everything they hold alive, wherever they are.
+///
+/// # Safety
+///
+/// Nothing that a value of the type holds may be collected while the value lives.
+pub unsafe trait KeepsAlive {}
+
+// SAFETY: The value is registered as a root while the Root lives.
+unsafe impl<T: Trace + 'static> KeepsAlive for Root<'_, T> {}
+// SAFETY: The values are held by a Root.
+unsafe impl<T: Trace + Clone + 'static> KeepsAlive for MarkedVec<'_, T> {}
+// SAFETY: The value cannot outlive the deferral it is tied to, while which nothing is collected.
+unsafe impl<T> KeepsAlive for Deferred<'_, T> {}
+// SAFETY: The VM is the root set: the heap traces it through gather_roots() wherever it is held.
+unsafe impl KeepsAlive for Vm {}
+
+/// A guard that keeps the heap from collecting garbage while it lives.
+///
+/// # Safety
+///
+/// Nothing may be collected while a value of the type lives.
+pub unsafe trait DefersCollections {}
+
+// SAFETY: The heap defers collections from new() until drop().
+unsafe impl DefersCollections for DeferGc<'_> {}
+// SAFETY: The value cannot outlive the deferral it is tied to.
+unsafe impl<T> DefersCollections for Deferred<'_, T> {}
+// SAFETY: The sweep callback runs inside a collection, which no other collection interrupts.
+unsafe impl DefersCollections for Sweep<'_> {}
+
+/// A type whose values hold no cell, whatever the types of their fields can hold.
+///
+/// # Safety
+///
+/// No value of the type may hold a pointer to a cell.
+pub unsafe trait HoldsNoCells {}
diff --git a/Libraries/LibJS/Rust/src/gc/mod.rs b/Libraries/LibJS/Rust/src/gc/mod.rs
index ac61d455c8c..72d62fc686f 100644
--- a/Libraries/LibJS/Rust/src/gc/mod.rs
+++ b/Libraries/LibJS/Rust/src/gc/mod.rs
@@ -17,6 +17,7 @@ pub mod gc_ref_cell;
pub mod heap;
pub mod heap_function;
pub mod interpreter_buffer;
+pub mod lint_markers;
pub mod primitive_storage;
pub mod root;
pub mod shared_memory;
diff --git a/Libraries/LibJS/Rust/src/gc/weak.rs b/Libraries/LibJS/Rust/src/gc/weak.rs
index b859f69a1ab..cf93fdcb36d 100644
--- a/Libraries/LibJS/Rust/src/gc/weak.rs
+++ b/Libraries/LibJS/Rust/src/gc/weak.rs
@@ -9,6 +9,7 @@ use core::ptr::NonNull;
use super::capi::{self, GCWeakImpl};
use super::heap::Heap;
+use super::lint_markers::HoldsNoCells;
use super::visitor::{Trace, Visitor};
use crate::layout::cell::Gc;
@@ -16,6 +17,15 @@ use crate::layout::cell::Gc;
/// collected. The startup layout check compares the offset with the one gc_get_layout() reports.
pub(super) const WEAK_IMPL_POINTER_OFFSET: usize = 16;
+/// A type whose GC pointers do not keep their cells alive: wherever a value of it is, the pointers to cells that a
+/// collection frees are cleared before anything reads them. Ladybird's Rust GC lints accept such values in a Box or a
+/// Vec.
+///
+/// # Safety
+///
+/// Every value of the type must have its pointers to dead cells cleared after each collection.
+pub unsafe trait SweptAfterCollection {}
+
/// A reference to a cell that does not keep it alive.
pub struct GcWeak<T> {
weak_impl: NonNull<GCWeakImpl>,
@@ -79,3 +89,6 @@ impl<T> Drop for GcWeak<T> {
unsafe impl<T> Trace for GcWeak<T> {
fn trace(&self, _: &mut Visitor) {}
}
+
+// SAFETY: A weak reference holds LibGC's weak impl of its cell, not the cell.
+unsafe impl<T> HoldsNoCells for GcWeak<T> {}
diff --git a/Libraries/LibJS/Rust/src/jit/mod.rs b/Libraries/LibJS/Rust/src/jit/mod.rs
index 83b805a0724..b953a6b3524 100644
--- a/Libraries/LibJS/Rust/src/jit/mod.rs
+++ b/Libraries/LibJS/Rust/src/jit/mod.rs
@@ -198,6 +198,10 @@ pub struct JitState {
}
impl JitState {
+ #[cfg_attr(
+ ladybird_gc_lints,
+ expect(gc_container_on_stack, reason = "the VM makes its JIT state before its heap")
+ )]
pub fn new(options: Options) -> Self {
translate::RegisterDump::assert_layout();
let warming_up_dispatch_table = options
diff --git a/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs b/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs
index 41ae8235d39..735cb448609 100644
--- a/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs
+++ b/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs
@@ -2111,6 +2111,10 @@ pub struct DisposableResource {
}
// 2.1.3 NewDisposeCapability ( ), https://tc39.es/proposal-explicit-resource-management/#sec-newdisposecapability
+#[cfg_attr(
+ ladybird_gc_lints,
+ expect(gc_container_on_stack, reason = "a new capability holds no resources")
+)]
pub fn new_dispose_capability() -> DisposeCapability {
// 1. Let stack be a new empty List.
// 2. Return the DisposeCapability Record { [[DisposableResourceStack]]: stack }.
diff --git a/Libraries/LibJS/Rust/src/runtime/json_object.rs b/Libraries/LibJS/Rust/src/runtime/json_object.rs
index e6165269e08..91ac4c169f1 100644
--- a/Libraries/LibJS/Rust/src/runtime/json_object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/json_object.rs
@@ -238,6 +238,10 @@ pub struct JsonStringifyCache {
}
impl JsonStringifyCache {
+ #[cfg_attr(
+ ladybird_gc_lints,
+ expect(gc_container_on_stack, reason = "the VM makes its caches before its heap")
+ )]
pub(crate) fn new() -> Self {
Self {
entries: RefCell::new(Box::new([const { None }; JsonStringifyCache::ENTRY_COUNT])),
diff --git a/Libraries/LibJS/Rust/src/runtime/object.rs b/Libraries/LibJS/Rust/src/runtime/object.rs
index ffb79a8df46..547fba3c966 100644
--- a/Libraries/LibJS/Rust/src/runtime/object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/object.rs
@@ -1190,6 +1190,13 @@ impl Object {
return false;
}
+ #[cfg_attr(
+ ladybird_gc_lints,
+ expect(
+ gc_container_on_stack,
+ reason = "the keys are those of `shape`, which keeps their symbols alive"
+ )
+ )]
let mut properties = Vec::with_capacity(shape.property_count() as usize);
let mut has_accessors = false;
shape.for_each_property_in_insertion_order(|property_key, metadata| {
@@ -1448,6 +1455,13 @@ impl Object {
return false;
}
let mut copy_shape = new_object_shape;
+ #[cfg_attr(
+ ladybird_gc_lints,
+ expect(
+ gc_container_on_stack,
+ reason = "the keys are those of `from_shape`, which keeps their symbols alive"
+ )
+ )]
let mut enumerable_keys = Vec::new();
from_shape.for_each_property_in_insertion_order(|property_key, metadata| {
if metadata.attributes.is_enumerable() {
diff --git a/Libraries/LibJS/Rust/src/runtime/property_key.rs b/Libraries/LibJS/Rust/src/runtime/property_key.rs
index 3ac313077a4..ecb3593ca45 100644
--- a/Libraries/LibJS/Rust/src/runtime/property_key.rs
+++ b/Libraries/LibJS/Rust/src/runtime/property_key.rs
@@ -13,6 +13,7 @@ use core::ptr::NonNull;
use ak::{Utf16FlyString, Utf16String};
+use crate::gc::lint_markers::HoldsNoCells;
use crate::gc::visitor::{Trace, Visitor};
use crate::interpreter::vm::Vm;
use crate::layout::cell::Gc;
@@ -267,6 +268,9 @@ unsafe impl Trace for PropertyKey {
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct NonSymbolPropertyKey(PropertyKey);
+// SAFETY: new() takes no symbols, the only keys that hold a cell.
+unsafe impl HoldsNoCells for NonSymbolPropertyKey {}
+
impl NonSymbolPropertyKey {
pub fn new(key: PropertyKey) -> Option<Self> {
(!key.is_symbol()).then_some(Self(key))
diff --git a/Meta/RustLints/Cargo.lock b/Meta/RustLints/Cargo.lock
new file mode 100644
index 00000000000..0a6fdcecd74
--- /dev/null
+++ b/Meta/RustLints/Cargo.lock
@@ -0,0 +1,7 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "ladybird_rust_lints"
+version = "0.1.0"
diff --git a/Meta/RustLints/Cargo.toml b/Meta/RustLints/Cargo.toml
new file mode 100644
index 00000000000..647670af858
--- /dev/null
+++ b/Meta/RustLints/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+name = "ladybird_rust_lints"
+version = "0.1.0"
+edition = "2024"
+
+[[bin]]
+name = "ladybird-rust-lints"
+path = "src/main.rs"
+
+[[test]]
+name = "ui"
+harness = false
+
+[package.metadata.rust-analyzer]
+rustc_private = true
+
+# The driver links the compiler of the pinned nightly, so it cannot be a member of the stable workspace.
+[workspace]
diff --git a/Meta/RustLints/README.md b/Meta/RustLints/README.md
new file mode 100644
index 00000000000..4ef7cf3b27c
--- /dev/null
+++ b/Meta/RustLints/README.md
@@ -0,0 +1,70 @@
+# Rust GC lints
+
+A rustc driver with lints for the Rust crates that use libjs_rust's GC, ported from the LibJSGC clang plugin:
+
+- `gc_container_on_stack` (`gc_pointer_container_on_stack` in C++): a local, parameter, return value or unsizing
+ coercion whose type owns a GC pointer through heap memory that the collector does not scan (`Vec`, `VecDeque`,
+ `HashMap`, `BTreeMap`, `Box`, `Rc`, `Arc`, `SmallVec`, a boxed closure that captures one, a struct holding any of
+ these, ...). Keep such lists in a `MarkedVec`, or lend them from one.
+- `root_in_traced_type` (`strong_root_fields_in_gc_allocated_types`): a field that holds a `Root` or `MarkedVec` in a
+ type that implements `Trace`.
+
+A GC pointer is a reference to a `GcCell`, a value of a type of the crate that implements `Trace` by hand, as `Gc`,
+`Value` and `PropertyKey` do, or a trait object whose trait requires `Trace`. A type that hides cell pointers in its
+bits has to trace them to keep their cells alive, so no type can hide them from the lints. What `#[derive(Trace)]`
+implements is checked through the fields.
+
+The check reads types after inference, so `let cells = make_cells();` is checked as `Vec<Gc<Cell>>`. Std containers
+need no list: a container owns its storage through a `PhantomData<T>` next to its pointer, and the lint treats that `T`
+as heap memory. `SmallVec` keeps its spill behind a bare pointer, so it is listed by path.
+
+These pass:
+
+- Types that implement the unsafe `KeepsAlive` marker: `Root` and `MarkedVec`, whose values are roots, `Deferred`,
+ which cannot outlive the `DeferGc` it is tied to, and the `Vm`, which is the root set. References and slices borrow,
+ and pass too.
+- Types that implement the unsafe `SweptAfterCollection` marker, whose pointers do not keep cells alive, or the unsafe
+ `HoldsNoCells` marker, like `NonSymbolPropertyKey`.
+- The parameters, locals and return values of a function or closure that takes a `&DeferGc` (a type that implements
+ the unsafe `DefersCollections` marker, as the `Sweep` of a collection's sweep callback does too), and of the closures
+ in it, which nothing collects while they live. What such a function returns is checked where its caller holds it. A
+ guard bound in a body covers nothing, as it can be dropped while what it should cover lives on.
+- A struct with a field of a type that implements `DefersCollections`, a `&DeferGc` or a `Deferred`, which its values
+ cannot outlive.
+
+A cell exists by value only while `Heap::allocate()` builds it, in the closure it is given, which takes the deferral
+that lasts until the cell is in the heap: C++ constructs cells in place the same way. The constructors of cells and of
+their storage that hold GC pointers in heap memory take a `&DeferGc`, so that only such a builder can call them.
+
+The lints find the types of the GC through the traits in `libjs_rust::gc::lint_markers` (and `Trace`, `GcCell` and
+`SweptAfterCollection`), and stop with an error if libjs_rust no longer has one, so that moving a type does not hide it.
+
+## Running
+
+```bash
+Meta/RustLints/run.sh
+```
+
+builds the driver on the nightly pinned in `rust-toolchain.toml` (it links that nightly's compiler, so it needs the
+`rustc-dev` component) and runs `cargo check` on `libjs_rust`, `libweb_bindings_rust` and `libweb_rust` with the driver
+as `RUSTC_WORKSPACE_WRAPPER`. Dependencies outside the workspace are compiled by the nightly's plain rustc. Set
+`LADYBIRD_RUST_LINTS_WARN=1` to report hits as warnings, so crates that depend on one with hits are still checked, and
+`LIBWEB_RUST_BINDINGS` to the `RustBindings.rs` of a build to check the generated bindings too.
+
+The tests compile each `tests/ui/*.rs` against stand-ins for libjs_rust and smallvec and compare the diagnostics with
+the `//~ ERROR` annotations:
+
+```bash
+cargo test --manifest-path Meta/RustLints/Cargo.toml
+```
+
+## Suppressing a hit
+
+The lints exist only under the driver, so name them under the cfg it sets, with a reason:
+
+```rust
+#[cfg_attr(ladybird_gc_lints, expect(gc_container_on_stack, reason = "every cell is also in the realm's list"))]
+let cells = ...;
+```
+
+An `allow` or `expect` without a reason is an error. Prefer `expect`, which warns once the hit is gone.
diff --git a/Meta/RustLints/build.rs b/Meta/RustLints/build.rs
new file mode 100644
index 00000000000..2aeb7e027a2
--- /dev/null
+++ b/Meta/RustLints/build.rs
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::env;
+use std::process::Command;
+
+fn main() {
+ // The driver loads librustc_driver from the toolchain it was built with.
+ let rustc = env::var("RUSTC").unwrap_or_else(|_| "rustc".into());
+ let output = Command::new(rustc)
+ .args(["--print", "sysroot"])
+ .output()
+ .expect("rustc --print sysroot");
+ let sysroot = String::from_utf8(output.stdout).expect("UTF-8 sysroot");
+ println!("cargo:rustc-link-arg=-Wl,-rpath,{}/lib", sysroot.trim());
+}
diff --git a/Meta/RustLints/run.sh b/Meta/RustLints/run.sh
new file mode 100755
index 00000000000..fb2e8abcd2b
--- /dev/null
+++ b/Meta/RustLints/run.sh
@@ -0,0 +1,25 @@
+#!/usr/bin/env bash
+
+# Builds the lint driver on its pinned nightly and checks the crates that use libjs_rust's GC with it.
+# Extra arguments go to `cargo check`.
+
+set -euo pipefail
+
+script_path=$(cd -P -- "$(dirname -- "$0")" && pwd -P)
+root="${script_path}/../.."
+
+toolchain=$(sed -n 's/^channel = "\(.*\)"$/\1/p' "${script_path}/rust-toolchain.toml")
+export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-${root}/Build/rust-lints}"
+
+cargo +"${toolchain}" build --release --manifest-path "${script_path}/Cargo.toml"
+
+# Cargo fingerprints the wrapper's path, not its contents, so give each build of the driver its own path.
+driver="${CARGO_TARGET_DIR}/release/ladybird-rust-lints"
+driver_hash=$(shasum "${driver}" | cut -c1-16)
+mkdir -p "${CARGO_TARGET_DIR}/drivers/${driver_hash}"
+cp "${driver}" "${CARGO_TARGET_DIR}/drivers/${driver_hash}/"
+
+cd "${root}"
+RUSTC_WORKSPACE_WRAPPER="${CARGO_TARGET_DIR}/drivers/${driver_hash}/ladybird-rust-lints" \
+ cargo +"${toolchain}" check --release \
+ -p libjs_rust -p libweb_bindings_rust -p libweb_rust "$@"
diff --git a/Meta/RustLints/rust-toolchain.toml b/Meta/RustLints/rust-toolchain.toml
new file mode 100644
index 00000000000..56756b9a4eb
--- /dev/null
+++ b/Meta/RustLints/rust-toolchain.toml
@@ -0,0 +1,5 @@
+[toolchain]
+# The nightly that matches the workspace's stable toolchain (1.98) most closely. The driver links its compiler, so
+# rustc-dev must match it exactly.
+channel = "nightly-2026-06-22"
+components = ["rustc-dev", "llvm-tools", "rust-src"]
diff --git a/Meta/RustLints/src/gc_lints.rs b/Meta/RustLints/src/gc_lints.rs
new file mode 100644
index 00000000000..b38c0593578
--- /dev/null
+++ b/Meta/RustLints/src/gc_lints.rs
@@ -0,0 +1,626 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Ports of the LibJSGC clang plugin checks to libjs_rust's GC.
+//!
+//! The collector scans the stack conservatively and traces cells precisely, so a `Gc` or `Value` in a local needs no
+//! root. Heap memory that is not a cell is never scanned: a GC pointer that a local owns through a `Vec`, `Box`,
+//! `HashMap`, boxed closure and so on can be collected while the local still uses it.
+
+use rustc_data_structures::fx::{FxHashMap, FxHashSet};
+use rustc_errors::DiagDecorator;
+use rustc_hir::def::DefKind;
+use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
+use rustc_hir::intravisit::FnKind;
+use rustc_hir::{Body, ByRef, Expr, ExprKind, FnDecl, FnRetTy, HirId, Item, ItemKind, Node, Pat, PatKind};
+use rustc_lint::{LateContext, LateLintPass, Lint};
+use rustc_middle::lint::LintLevelSource;
+use rustc_middle::ty::adjustment::{Adjust, PointerCoercion};
+use rustc_middle::ty::print::with_forced_trimmed_paths;
+use rustc_middle::ty::{self, Ty, TyCtxt};
+use rustc_session::{declare_lint, impl_lint_pass};
+
+use rustc_span::{DesugaringKind, Span};
+
+declare_lint! {
+ /// A local, parameter or return value owns GC pointers through heap memory that the collector does not scan.
+ ///
+ /// Use `MarkedVec` (or a `Root`) for such temporaries, or keep them in a traced cell. When the GC pointers are
+ /// kept alive some other way, say so:
+ /// `#[cfg_attr(ladybird_gc_lints, expect(gc_container_on_stack, reason = "..."))]`.
+ pub GC_CONTAINER_ON_STACK,
+ Deny,
+ "GC pointers kept in heap memory that is not scanned for roots"
+}
+
+declare_lint! {
+ /// A type that implements `Trace` holds a `Root`. A traced value is reachable from the heap, so its root keeps
+ /// alive whatever reaches the value back, which leaks the cycle.
+ pub ROOT_IN_TRACED_TYPE,
+ Deny,
+ "`Root` held by a type that implements `Trace`"
+}
+
+pub static LINTS: &[&Lint] = &[GC_CONTAINER_ON_STACK, ROOT_IN_TRACED_TYPE];
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Kind {
+ /// A type of the crate that implements `Trace` by hand, like `Gc<T>`, `Value` or `PropertyKey`: it can hold GC
+ /// pointers that its fields do not show, as `PropertyKey` does in a tagged word, and has to trace them to keep them
+ /// alive.
+ GcPointer,
+ /// A type that implements `KeepsAlive`, like `Root`, `MarkedVec` or `Deferred`: whatever these hold stays alive.
+ Rooted,
+ /// A type that implements `SweptAfterCollection`, whose pointers do not keep cells alive, or `HoldsNoCells`.
+ Weak,
+ /// A container whose storage the type structure does not show as owned (`SmallVec` keeps its spill behind a
+ /// pointer, with no `PhantomData`).
+ HeapContainer,
+ /// A type that implements `DefersCollections`, like `DeferGc`, which keeps the heap from collecting while it lives.
+ DeferGc,
+ Other,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Target {
+ /// GC pointers that live in unscanned heap memory.
+ UnscannedGcPointer,
+ /// Roots anywhere in a value.
+ Root,
+}
+
+#[derive(Default)]
+pub struct GcLints<'tcx> {
+ kinds: FxHashMap<DefId, Kind>,
+ traced_types: FxHashSet<DefId>,
+ cell_types: FxHashSet<DefId>,
+ swept_types: FxHashSet<DefId>,
+ holds_no_cells_types: FxHashSet<DefId>,
+ keeps_alive_types: FxHashSet<DefId>,
+ defers_collections_types: FxHashSet<DefId>,
+ /// Whether each type has a field that defers collections, which its values cannot outlive.
+ deferral_scoped: FxHashMap<DefId, bool>,
+ reaches_gc_pointer: FxHashMap<Ty<'tcx>, bool>,
+ reported_attributes: FxHashSet<Span>,
+ hand_traced_types: FxHashSet<DefId>,
+ trace_trait: Option<DefId>,
+ enabled: bool,
+}
+
+impl_lint_pass!(GcLints<'_> => [
+ GC_CONTAINER_ON_STACK,
+ ROOT_IN_TRACED_TYPE,
+]);
+
+const LIBJS_CRATE: &str = "libjs_rust";
+
+fn def_path(tcx: TyCtxt<'_>, def_id: DefId) -> String {
+ let mut path = tcx.crate_name(def_id.krate).to_string();
+ for component in tcx.def_path(def_id).data {
+ if let Some(name) = component.data.get_opt_name() {
+ path.push_str("::");
+ path.push_str(name.as_str());
+ }
+ }
+ path
+}
+
+fn normalize<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
+ let ty = cx.tcx.erase_and_anonymize_regions(ty);
+ cx.tcx
+ .try_normalize_erasing_regions(cx.typing_env(), ty::Unnormalized::new(ty))
+ .unwrap_or(ty)
+}
+
+impl<'tcx> GcLints<'tcx> {
+ fn kind(&mut self, tcx: TyCtxt<'_>, def_id: DefId) -> Kind {
+ if self.swept_types.contains(&def_id) || self.holds_no_cells_types.contains(&def_id) {
+ return Kind::Weak;
+ }
+ if self.keeps_alive_types.contains(&def_id) {
+ return Kind::Rooted;
+ }
+ if self.defers_collections_types.contains(&def_id) {
+ return Kind::DeferGc;
+ }
+ if self.hand_traced_types.contains(&def_id) {
+ return Kind::GcPointer;
+ }
+ *self
+ .kinds
+ .entry(def_id)
+ .or_insert_with(|| match def_path(tcx, def_id).as_str() {
+ "smallvec::SmallVec" => Kind::HeapContainer,
+ _ => Kind::Other,
+ })
+ }
+
+ fn is_leaf(&mut self, tcx: TyCtxt<'_>, ty: Ty<'_>, target: Target) -> bool {
+ match ty.kind() {
+ ty::Adt(adt, _) => {
+ let kind = self.kind(tcx, adt.did());
+ match target {
+ Target::UnscannedGcPointer => kind == Kind::GcPointer,
+ Target::Root => kind == Kind::Rooted,
+ }
+ }
+ // A reference to a cell is a GC pointer too, like a raw GC::Cell* in C++.
+ ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => {
+ target == Target::UnscannedGcPointer
+ && matches!(pointee.kind(), ty::Adt(adt, _) if self.cell_types.contains(&adt.did()))
+ }
+ // A trait object that implements Trace traces what it hides, like a type that implements Trace by hand.
+ ty::Dynamic(predicates, ..) => {
+ target == Target::UnscannedGcPointer
+ && predicates.principal_def_id().is_some_and(|principal| {
+ rustc_middle::ty::elaborate::supertrait_def_ids(tcx, principal)
+ .any(|supertrait| Some(supertrait) == self.trace_trait)
+ })
+ }
+ _ => false,
+ }
+ }
+
+ /// The types `ty` holds by value, with whether the holding owns them through heap memory.
+ fn components(&mut self, cx: &LateContext<'tcx>, ty: Ty<'tcx>, target: Target) -> Vec<(Ty<'tcx>, bool)> {
+ let tcx = cx.tcx;
+ let normalize = |ty| normalize(cx, ty);
+ match ty.kind() {
+ ty::Adt(adt, _) if self.is_deferral_scoped(tcx, adt.did()) => Vec::new(),
+ ty::Adt(adt, args) => match self.kind(tcx, adt.did()) {
+ Kind::Weak | Kind::DeferGc => Vec::new(),
+ // Everything a root holds is traced, but a root found inside one is still a root.
+ Kind::Rooted if target == Target::UnscannedGcPointer => Vec::new(),
+ Kind::Rooted | Kind::HeapContainer => args.types().map(|ty| (normalize(ty), true)).collect(),
+ Kind::Other if adt.is_phantom_data() => vec![(normalize(args.type_at(0)), true)],
+ Kind::GcPointer | Kind::Other => adt
+ .all_fields()
+ .map(|field| (normalize(field.ty(tcx, args).skip_normalization()), false))
+ .collect(),
+ },
+ ty::Tuple(types) => types.iter().map(|ty| (ty, false)).collect(),
+ // An empty array holds nothing, which `Box::new([])` coerced to a boxed slice relies on.
+ ty::Array(_, length) if length.try_to_target_usize(tcx) == Some(0) => Vec::new(),
+ ty::Array(element, _) | ty::Slice(element) | ty::Pat(element, _) => vec![(*element, false)],
+ ty::Closure(_, args) => args
+ .as_closure()
+ .upvar_tys()
+ .iter()
+ .map(|ty| (normalize(ty), false))
+ .collect(),
+ _ => Vec::new(),
+ }
+ }
+
+ /// Whether any value of `ty` can hold a GC pointer, wherever it lives. Recursive types are cut at the cycle.
+ fn reaches_gc_pointer(&mut self, cx: &LateContext<'tcx>, ty: Ty<'tcx>, in_progress: &mut Vec<Ty<'tcx>>) -> bool {
+ if let Some(&reaches) = self.reaches_gc_pointer.get(&ty) {
+ return reaches;
+ }
+ if self.is_leaf(cx.tcx, ty, Target::UnscannedGcPointer) {
+ self.reaches_gc_pointer.insert(ty, true);
+ return true;
+ }
+ if in_progress.contains(&ty) {
+ return false;
+ }
+ in_progress.push(ty);
+ let reaches = self
+ .components(cx, ty, Target::UnscannedGcPointer)
+ .into_iter()
+ .any(|(component, _)| self.reaches_gc_pointer(cx, component, in_progress));
+ in_progress.pop();
+ // A negative answer reached while an enclosing type was still in progress may be cut short.
+ if reaches || in_progress.is_empty() {
+ self.reaches_gc_pointer.insert(ty, reaches);
+ }
+ reaches
+ }
+
+ /// Finds a `target` leaf in `ty`, returning it with the outermost container that holds it on the heap (for roots,
+ /// the type itself).
+ fn find(
+ &mut self,
+ cx: &LateContext<'tcx>,
+ ty: Ty<'tcx>,
+ target: Target,
+ ancestors: &mut Vec<Ty<'tcx>>,
+ heap_owner: Option<usize>,
+ ) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
+ if self.is_leaf(cx.tcx, ty, target) {
+ match target {
+ Target::Root => return Some((ty, ty)),
+ // NB: Held by value, a type that traces itself can still keep GC pointers in its own containers.
+ Target::UnscannedGcPointer => {
+ if let Some(owner) = heap_owner {
+ return Some((ty, self.container(cx, ancestors, owner)));
+ }
+ }
+ }
+ }
+ if target == Target::UnscannedGcPointer && !self.reaches_gc_pointer(cx, ty, &mut Vec::new()) {
+ return None;
+ }
+ if ancestors.contains(&ty) {
+ return None;
+ }
+ ancestors.push(ty);
+ let index = ancestors.len() - 1;
+ let mut found = None;
+ // The type that holds a PhantomData owns the storage it marks.
+ let storage_owner = match ty.kind() {
+ ty::Adt(adt, _) if adt.is_phantom_data() => index.saturating_sub(1),
+ _ => index,
+ };
+ for (component, owned_on_heap) in self.components(cx, ty, target) {
+ let owner = if owned_on_heap {
+ heap_owner.or(Some(storage_owner))
+ } else {
+ heap_owner
+ };
+ found = self.find(cx, component, target, ancestors, owner);
+ if found.is_some() {
+ break;
+ }
+ }
+ ancestors.pop();
+ found
+ }
+
+ /// Names the container for a diagnostic: the innermost public type around the storage, so `Vec<Gc<T>>` rather
+ /// than the `RawVec<Gc<T>>` that owns it.
+ fn container(&self, cx: &LateContext<'tcx>, ancestors: &[Ty<'tcx>], owner: usize) -> Ty<'tcx> {
+ let is_public = |ty: Ty<'tcx>| match ty.kind() {
+ ty::Adt(adt, _) if adt.did().is_local() => true,
+ ty::Adt(adt, _) => {
+ cx.tcx.visible_parent_map(()).contains_key(&adt.did())
+ && !cx
+ .tcx
+ .lookup_stability(adt.did())
+ .is_some_and(|stability| stability.is_unstable())
+ }
+ _ => true,
+ };
+ let mut index = owner;
+ while index > 0 && !is_public(ancestors[index]) {
+ index -= 1;
+ }
+ ancestors[index]
+ }
+
+ /// The outermost container of `ty` that keeps GC pointers in unscanned heap memory.
+ fn unscanned_container(&mut self, cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
+ let ty = normalize(cx, ty);
+ self.find(cx, ty, Target::UnscannedGcPointer, &mut Vec::new(), None)
+ .map(|(_, container)| container)
+ }
+
+ /// Whether the type has a field that defers collections, like a `&DeferGc` or a `Deferred`, which its values
+ /// cannot outlive, so that nothing collects while one lives.
+ fn is_deferral_scoped(&mut self, tcx: TyCtxt<'_>, def_id: DefId) -> bool {
+ if let Some(&scoped) = self.deferral_scoped.get(&def_id) {
+ return scoped;
+ }
+ let adt = tcx.adt_def(def_id);
+ let scoped = adt.is_struct()
+ && adt.all_fields().any(|field| {
+ let ty = tcx.type_of(field.did).instantiate_identity().skip_normalization();
+ let held = match ty.kind() {
+ ty::Ref(_, pointee, _) => *pointee,
+ _ => ty,
+ };
+ matches!(held.kind(), ty::Adt(held, _) if self.defers_collections_types.contains(&held.did()))
+ });
+ self.deferral_scoped.insert(def_id, scoped);
+ scoped
+ }
+
+ fn is_defer_gc_reference(&mut self, tcx: TyCtxt<'_>, ty: Ty<'_>) -> bool {
+ matches!(ty.kind(), ty::Ref(_, pointee, _)
+ if matches!(pointee.kind(), ty::Adt(adt, _) if self.kind(tcx, adt.did()) == Kind::DeferGc))
+ }
+
+ /// Whether the function takes a `&DeferGc`, which its caller keeps alive for as long as the function runs.
+ fn takes_defer_gc(&mut self, cx: &LateContext<'tcx>, def_id: LocalDefId) -> bool {
+ if !matches!(cx.tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) {
+ return false;
+ }
+ let signature = cx.tcx.fn_sig(def_id).instantiate_identity().skip_normalization();
+ signature
+ .inputs()
+ .skip_binder()
+ .iter()
+ .any(|&input| self.is_defer_gc_reference(cx.tcx, input))
+ }
+
+ /// Whether the closure takes a `&DeferGc`, like the one Heap::allocate() builds a cell with.
+ fn closure_takes_defer_gc(&mut self, cx: &LateContext<'tcx>, def_id: LocalDefId) -> bool {
+ let ty::Closure(_, args) = cx
+ .tcx
+ .type_of(def_id)
+ .instantiate_identity()
+ .skip_normalization()
+ .kind()
+ else {
+ return false;
+ };
+ // NB: A closure's signature takes its arguments as one tuple.
+ let inputs = args.as_closure().sig().inputs().skip_binder();
+ inputs.iter().any(|&input| match input.kind() {
+ ty::Tuple(types) => types.iter().any(|ty| self.is_defer_gc_reference(cx.tcx, ty)),
+ _ => self.is_defer_gc_reference(cx.tcx, input),
+ })
+ }
+
+ /// Whether `hir_id` is in the body of a function or closure that takes a `&DeferGc`, which outlives the body. A
+ /// guard bound in a body proves nothing, as it can be dropped before what it should cover.
+ fn in_defer_gc_scope(&mut self, cx: &LateContext<'tcx>, hir_id: HirId) -> bool {
+ for (parent, node) in cx.tcx.hir_parent_iter(hir_id) {
+ match node {
+ Node::Expr(Expr {
+ kind: ExprKind::Closure(closure),
+ ..
+ }) if self.closure_takes_defer_gc(cx, closure.def_id) => return true,
+ Node::Item(_) | Node::ImplItem(_) | Node::TraitItem(_) => {
+ return self.takes_defer_gc(cx, parent.owner.def_id);
+ }
+ _ => {}
+ }
+ }
+ false
+ }
+
+ fn emit(&mut self, cx: &LateContext<'_>, lint: &'static Lint, hir_id: HirId, span: Span, message: String) {
+ let spec = cx.tcx.lint_level_spec_at_node(lint, hir_id);
+ if (spec.is_allow() || spec.is_expect())
+ && let LintLevelSource::Node {
+ span: attribute_span,
+ reason: None,
+ ..
+ } = spec.src
+ && self.reported_attributes.insert(attribute_span)
+ {
+ cx.tcx.dcx().span_err(
+ attribute_span,
+ format!("allowing `{}` needs a `reason = \"...\"`", lint.name_lower()),
+ );
+ }
+ cx.tcx.emit_node_span_lint(
+ lint,
+ hir_id,
+ span,
+ DiagDecorator(|diag| {
+ diag.primary_message(message);
+ }),
+ );
+ }
+
+ fn check_unscanned(&mut self, cx: &LateContext<'tcx>, ty: Ty<'tcx>, hir_id: HirId, span: Span, what: &str) {
+ if let Some(container) = self.unscanned_container(cx, ty) {
+ self.emit(
+ cx,
+ GC_CONTAINER_ON_STACK,
+ hir_id,
+ span,
+ with_forced_trimmed_paths!(format!(
+ "{what} '{container}' keeps GC pointers in heap memory that is not scanned for roots"
+ )),
+ );
+ }
+ }
+}
+
+impl<'tcx> LateLintPass<'tcx> for GcLints<'tcx> {
+ fn check_crate(&mut self, cx: &LateContext<'tcx>) {
+ let tcx = cx.tcx;
+ let libjs = if tcx.crate_name(LOCAL_CRATE).as_str() == LIBJS_CRATE {
+ Some(LOCAL_CRATE)
+ } else {
+ tcx.crates(())
+ .iter()
+ .copied()
+ .find(|&krate| tcx.crate_name(krate).as_str() == LIBJS_CRATE)
+ };
+ let Some(libjs) = libjs else {
+ return;
+ };
+ self.enabled = true;
+
+ // Only implementations in the type's own crate count: libjs_rust implements Trace for Vec, Box and the like.
+ let collect = |path: &str, into: &mut FxHashSet<DefId>| {
+ let Some(trait_def_id) = tcx
+ .all_traits_including_private()
+ .find(|&def_id| def_id.krate == libjs && def_path(tcx, def_id) == path)
+ else {
+ tcx.dcx().fatal(format!(
+ "the Rust GC lints find GC types through `{path}`, which libjs_rust no longer has"
+ ));
+ };
+ for implementation in tcx.all_impls(trait_def_id) {
+ if let ty::Adt(adt, _) = tcx
+ .type_of(implementation)
+ .instantiate_identity()
+ .skip_normalization()
+ .kind()
+ && adt.did().krate == implementation.krate
+ {
+ into.insert(adt.did());
+ }
+ }
+ trait_def_id
+ };
+ let mut traced_types = FxHashSet::default();
+ let mut cell_types = FxHashSet::default();
+ let mut swept_types = FxHashSet::default();
+ let mut holds_no_cells_types = FxHashSet::default();
+ let mut keeps_alive_types = FxHashSet::default();
+ let mut defers_collections_types = FxHashSet::default();
+ let trace = collect("libjs_rust::gc::visitor::Trace", &mut traced_types);
+ // NB: #[derive(Trace)] traces the fields, which the type shows. A hand-written trace() can visit cells that
+ // the type hides, as PropertyKey does in a tagged usize.
+ let hand_traced_types = tcx
+ .all_impls(trace)
+ .filter(|&implementation| !tcx.def_span(implementation).from_expansion())
+ .filter_map(|implementation| {
+ match tcx
+ .type_of(implementation)
+ .instantiate_identity()
+ .skip_normalization()
+ .kind()
+ {
+ ty::Adt(adt, _) if adt.did().krate == implementation.krate => Some(adt.did()),
+ _ => None,
+ }
+ })
+ .collect();
+ collect("libjs_rust::gc::class::GcCell", &mut cell_types);
+ collect("libjs_rust::gc::weak::SweptAfterCollection", &mut swept_types);
+ collect("libjs_rust::gc::lint_markers::HoldsNoCells", &mut holds_no_cells_types);
+ collect("libjs_rust::gc::lint_markers::KeepsAlive", &mut keeps_alive_types);
+ collect(
+ "libjs_rust::gc::lint_markers::DefersCollections",
+ &mut defers_collections_types,
+ );
+ self.traced_types = traced_types;
+ self.cell_types = cell_types;
+ self.swept_types = swept_types;
+ self.holds_no_cells_types = holds_no_cells_types;
+ self.keeps_alive_types = keeps_alive_types;
+ self.defers_collections_types = defers_collections_types;
+ self.hand_traced_types = hand_traced_types;
+ self.trace_trait = Some(trace);
+ }
+
+ fn check_pat(&mut self, cx: &LateContext<'tcx>, pat: &'tcx Pat<'tcx>) {
+ if !self.enabled {
+ return;
+ }
+ let PatKind::Binding(_, hir_id, ident, _) = pat.kind else {
+ return;
+ };
+ let what = match pat.span.desugaring_kind() {
+ Some(DesugaringKind::ForLoop) => "the iterator".to_owned(),
+ Some(_) => return,
+ // Other lowerings (`?`) bind names without a span; the value reaches a checked local anyway.
+ None if ident.span.is_dummy() => return,
+ None => format!("`{ident}` of type"),
+ };
+ if self.in_defer_gc_scope(cx, hir_id) {
+ return;
+ }
+ let results = cx.typeck_results();
+ if results
+ .pat_binding_modes()
+ .get(hir_id)
+ .is_some_and(|mode| matches!(mode.0, ByRef::Yes(..)))
+ {
+ return;
+ }
+ self.check_unscanned(cx, results.node_type(hir_id), hir_id, pat.span, &what);
+ }
+
+ fn check_fn(
+ &mut self,
+ cx: &LateContext<'tcx>,
+ kind: FnKind<'tcx>,
+ decl: &'tcx FnDecl<'tcx>,
+ body: &'tcx Body<'tcx>,
+ _: Span,
+ def_id: LocalDefId,
+ ) {
+ if !self.enabled {
+ return;
+ }
+ let output = match kind {
+ FnKind::Closure => match cx
+ .tcx
+ .type_of(def_id)
+ .instantiate_identity()
+ .skip_normalization()
+ .kind()
+ {
+ ty::Closure(_, args) => args.as_closure().sig().output().skip_binder(),
+ _ => return,
+ },
+ FnKind::ItemFn(..) | FnKind::Method(..) => cx
+ .tcx
+ .fn_sig(def_id)
+ .instantiate_identity()
+ .skip_normalization()
+ .output()
+ .skip_binder(),
+ };
+ let span = match decl.output {
+ FnRetTy::Return(ty) => ty.span,
+ FnRetTy::DefaultReturn(_) => body.value.span,
+ };
+ // NB: What a function or closure that takes a deferral returns, like a cell that Heap::allocate() builds, is
+ // checked where its caller holds it, which the deferral outlives until a binding the checks see. What a
+ // closure in a deferral's scope returns stays in that scope, like a local.
+ let hir_id = cx.tcx.local_def_id_to_hir_id(def_id);
+ let takes_defer_gc = match kind {
+ FnKind::Closure => {
+ self.closure_takes_defer_gc(cx, def_id) || self.in_defer_gc_scope(cx, cx.tcx.parent_hir_id(hir_id))
+ }
+ FnKind::ItemFn(..) | FnKind::Method(..) => self.takes_defer_gc(cx, def_id),
+ };
+ if takes_defer_gc {
+ return;
+ }
+ self.check_unscanned(cx, output, hir_id, span, "return type");
+ }
+
+ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
+ if !self.enabled {
+ return;
+ }
+ // Boxing a closure into a `dyn Fn` hides its captures from the type of whatever holds it next, unless the trait
+ // object still shows them by implementing Trace.
+ let results = cx.typeck_results();
+ let mut source = results.expr_ty(expr);
+ for adjustment in results.expr_adjustments(expr) {
+ if let Adjust::Pointer(PointerCoercion::Unsize) = adjustment.kind
+ && !self.reaches_gc_pointer(cx, normalize(cx, adjustment.target), &mut Vec::new())
+ {
+ self.check_unscanned(cx, source, expr.hir_id, expr.span, "coercion from");
+ }
+ source = adjustment.target;
+ }
+ }
+
+ fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) {
+ if !self.enabled
+ || !matches!(
+ item.kind,
+ ItemKind::Struct(..) | ItemKind::Enum(..) | ItemKind::Union(..)
+ )
+ {
+ return;
+ }
+ let def_id = item.owner_id.to_def_id();
+ if !self.traced_types.contains(&def_id) {
+ return;
+ }
+ let tcx = cx.tcx;
+ let adt = tcx.adt_def(item.owner_id);
+ for field in adt.all_fields() {
+ let ty = tcx.type_of(field.did).instantiate_identity().skip_normalization();
+ if let Some((root, _)) = self.find(cx, ty, Target::Root, &mut Vec::new(), None) {
+ let field_id = field.did.expect_local();
+ self.emit(
+ cx,
+ ROOT_IN_TRACED_TYPE,
+ tcx.local_def_id_to_hir_id(field_id),
+ tcx.def_span(field_id),
+ with_forced_trimmed_paths!(format!(
+ "'{}' implements Trace but holds the root '{root}'",
+ tcx.def_path_str(item.owner_id)
+ )),
+ );
+ }
+ }
+ }
+}
diff --git a/Meta/RustLints/src/main.rs b/Meta/RustLints/src/main.rs
new file mode 100644
index 00000000000..dd290c7143f
--- /dev/null
+++ b/Meta/RustLints/src/main.rs
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! A rustc driver that adds Ladybird's GC lints. Use it as cargo's `RUSTC_WORKSPACE_WRAPPER`, so it compiles the
+//! workspace members and leaves dependencies to plain rustc, or run it in place of rustc on a single file.
+
+#![feature(rustc_private)]
+
+extern crate rustc_data_structures;
+extern crate rustc_driver;
+extern crate rustc_errors;
+extern crate rustc_hir;
+extern crate rustc_interface;
+extern crate rustc_lint;
+extern crate rustc_middle;
+extern crate rustc_session;
+extern crate rustc_span;
+
+mod gc_lints;
+
+use std::path::Path;
+use std::process::ExitCode;
+
+struct Callbacks;
+
+impl rustc_driver::Callbacks for Callbacks {
+ fn config(&mut self, config: &mut rustc_interface::Config) {
+ config.register_lints = Some(Box::new(|_, lint_store| {
+ lint_store.register_lints(gc_lints::LINTS);
+ lint_store.register_late_pass(|_| Box::new(gc_lints::GcLints::default()));
+ }));
+ }
+}
+
+fn main() -> ExitCode {
+ let mut args: Vec<String> = std::env::args().collect();
+
+ // As a wrapper, cargo passes the path of the real rustc first.
+ if args
+ .get(1)
+ .is_some_and(|arg| Path::new(arg).file_stem().is_some_and(|stem| stem == "rustc"))
+ {
+ args.remove(1);
+ }
+
+ // Code that names the lints in an attribute does so under this cfg, which only the driver sets:
+ // #[cfg_attr(ladybird_gc_lints, expect(gc_container_on_stack, reason = "..."))]
+ let is_query = args
+ .iter()
+ .any(|arg| arg == "-vV" || arg == "-V" || arg.starts_with("--print"));
+ if !is_query {
+ args.extend(
+ ["--cfg", "ladybird_gc_lints", "--check-cfg", "cfg(ladybird_gc_lints)"]
+ .into_iter()
+ .map(String::from),
+ );
+ // For surveying a tree with hits: a deny would stop the crates that depend on the first crate with one.
+ if std::env::var_os("LADYBIRD_RUST_LINTS_WARN").is_some() {
+ for lint in gc_lints::LINTS {
+ args.extend(["--warn".to_owned(), lint.name_lower()]);
+ }
+ }
+ }
+
+ rustc_driver::install_ice_hook("https://github.com/LadybirdBrowser/ladybird/issues", |_| ());
+ rustc_driver::catch_with_exit_code(|| rustc_driver::run_compiler(&args, &mut Callbacks))
+}
diff --git a/Meta/RustLints/tests/ui.rs b/Meta/RustLints/tests/ui.rs
new file mode 100644
index 00000000000..4c0ed3145a3
--- /dev/null
+++ b/Meta/RustLints/tests/ui.rs
@@ -0,0 +1,158 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Compiles each tests/ui/*.rs with the driver against stand-ins for libjs_rust and smallvec, and checks the diagnostics against
+//! the file's annotations: `//~ ERROR text` for a diagnostic on the same line, `//~^ ERROR text` for the line above.
+
+use std::path::{Path, PathBuf};
+use std::process::{Command, ExitCode};
+
+const DRIVER: &str = env!("CARGO_BIN_EXE_ladybird-rust-lints");
+
+fn run_driver(args: &[&str]) -> String {
+ let output = Command::new(DRIVER).args(args).output().expect("run the driver");
+ String::from_utf8_lossy(&output.stderr).into_owned()
+}
+
+fn expected_diagnostics(source: &str) -> Vec<(usize, String, String)> {
+ let mut expected = Vec::new();
+ for (index, line) in source.lines().enumerate() {
+ for annotation in line.split("//~").skip(1) {
+ let carets = annotation.chars().take_while(|&c| c == '^').count();
+ let mut words = annotation[carets..].trim_start().splitn(2, ' ');
+ let level = match words.next().unwrap_or_default() {
+ "WARN" => "warning".to_owned(),
+ level => level.to_lowercase(),
+ };
+ let text = words.next().unwrap_or_default().trim().to_owned();
+ expected.push((index + 1 - carets, level, text));
+ }
+ }
+ expected
+}
+
+// With --error-format=short, each diagnostic is one line: "path:line:column: level: message".
+fn actual_diagnostics(stderr: &str, file: &str) -> Vec<(usize, String, String)> {
+ let mut actual = Vec::new();
+ for line in stderr.lines() {
+ let Some(rest) = line.strip_prefix(file).and_then(|rest| rest.strip_prefix(':')) else {
+ continue;
+ };
+ let mut parts = rest.splitn(4, ':');
+ let (Some(line_number), Some(_), Some(level), Some(message)) =
+ (parts.next(), parts.next(), parts.next(), parts.next())
+ else {
+ continue;
+ };
+ let level = level.trim().split('[').next().unwrap_or_default().to_owned();
+ actual.push((line_number.parse().unwrap_or(0), level, message.trim().to_owned()));
+ }
+ actual
+}
+
+fn check(test: &Path, out_dir: &Path, externs: &[String]) -> bool {
+ let file = test.to_str().expect("UTF-8 path");
+ let source = std::fs::read_to_string(test).expect("read the test");
+ let out_dir_arg = out_dir.to_str().expect("UTF-8 path");
+ let mut args = vec![
+ file,
+ "--crate-type=lib",
+ "--edition=2024",
+ "--emit=metadata",
+ "--error-format=short",
+ "-L",
+ out_dir_arg,
+ "--out-dir",
+ out_dir_arg,
+ ];
+ for extern_arg in externs {
+ args.extend(["--extern", extern_arg.as_str()]);
+ }
+ let stderr = run_driver(&args);
+
+ let mut unmatched = expected_diagnostics(&source);
+ let mut unexpected = Vec::new();
+ for (line, level, message) in actual_diagnostics(&stderr, file) {
+ if level == "error" && message.starts_with("aborting due to") {
+ continue;
+ }
+ match unmatched
+ .iter()
+ .position(|(l, lv, text)| *l == line && *lv == level && message.contains(text.as_str()))
+ {
+ Some(index) => {
+ unmatched.remove(index);
+ }
+ None => unexpected.push((line, level, message)),
+ }
+ }
+
+ for (line, level, message) in &unexpected {
+ eprintln!("{file}:{line}: unexpected {level}: {message}");
+ }
+ for (line, level, text) in &unmatched {
+ eprintln!("{file}:{line}: missing {level}: {text}");
+ }
+ let passed = unexpected.is_empty() && unmatched.is_empty();
+ if !passed {
+ eprintln!("--- driver output for {file}:\n{stderr}");
+ }
+ passed
+}
+
+fn main() -> ExitCode {
+ let ui = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/ui");
+ let out_dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("ui");
+ std::fs::create_dir_all(&out_dir).expect("create the output directory");
+
+ // Stand-ins for the crates whose items the lints know by path. The tests name libjs_rust's as `js`, as code outside
+ // LibJS may not name the runtime's own modules (see Meta/Linters/check_libjs_rust_api.py).
+ let mut externs = Vec::new();
+ for (crate_name, alias) in [("libjs_rust", "js"), ("smallvec", "smallvec")] {
+ let source = ui.join(format!("auxiliary/{crate_name}.rs"));
+ let rlib = out_dir.join(format!("lib{crate_name}.rlib"));
+ let _ = std::fs::remove_file(&rlib);
+ let stderr = run_driver(&[
+ source.to_str().expect("UTF-8 path"),
+ "--crate-type=lib",
+ &format!("--crate-name={crate_name}"),
+ "--edition=2024",
+ "--out-dir",
+ out_dir.to_str().expect("UTF-8 path"),
+ ]);
+ if !rlib.exists() {
+ eprintln!("building the {crate_name} stand-in failed:\n{stderr}");
+ return ExitCode::FAILURE;
+ }
+ externs.push(format!("{alias}={}", rlib.display()));
+ }
+
+ let filter = std::env::args().nth(1);
+ let mut tests: Vec<PathBuf> = std::fs::read_dir(&ui)
+ .expect("list tests/ui")
+ .map(|entry| entry.expect("directory entry").path())
+ .filter(|path| path.extension().is_some_and(|extension| extension == "rs"))
+ .filter(|path| {
+ filter
+ .as_ref()
+ .is_none_or(|filter| path.to_string_lossy().contains(filter.as_str()))
+ })
+ .collect();
+ tests.sort();
+
+ let mut failures = 0;
+ for test in &tests {
+ let passed = check(test, &out_dir, &externs);
+ println!("{} {}", if passed { "PASS" } else { "FAIL" }, test.display());
+ failures += usize::from(!passed);
+ }
+ println!("{} passed, {failures} failed", tests.len() - failures);
+ if failures == 0 {
+ ExitCode::SUCCESS
+ } else {
+ ExitCode::FAILURE
+ }
+}
diff --git a/Meta/RustLints/tests/ui/auxiliary/libjs_rust.rs b/Meta/RustLints/tests/ui/auxiliary/libjs_rust.rs
new file mode 100644
index 00000000000..2919c994fdb
--- /dev/null
+++ b/Meta/RustLints/tests/ui/auxiliary/libjs_rust.rs
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The libjs_rust items the lints know by path, at the same paths, and the types they find through its marker traits.
+
+pub mod layout {
+ pub mod cell {
+ pub struct Gc<T: ?Sized>(core::ptr::NonNull<T>);
+
+ impl<T: ?Sized> Clone for Gc<T> {
+ fn clone(&self) -> Self {
+ *self
+ }
+ }
+
+ impl<T: ?Sized> Copy for Gc<T> {}
+ }
+
+ pub mod value {
+ #[derive(Clone, Copy)]
+ pub struct Value(pub u64);
+ }
+}
+
+pub mod gc {
+ pub mod visitor {
+ pub struct Visitor;
+
+ /// # Safety
+ ///
+ /// Stand-in.
+ pub unsafe trait Trace {
+ fn trace(&self, visitor: &mut Visitor);
+ }
+
+ unsafe impl<T> Trace for crate::layout::cell::Gc<T> {
+ fn trace(&self, _: &mut Visitor) {}
+ }
+
+ unsafe impl Trace for crate::layout::value::Value {
+ fn trace(&self, _: &mut Visitor) {}
+ }
+
+ unsafe impl<T: Trace> Trace for Vec<T> {
+ fn trace(&self, _: &mut Visitor) {}
+ }
+ }
+
+ pub mod class {
+ /// # Safety
+ ///
+ /// Stand-in.
+ pub unsafe trait GcCell: super::visitor::Trace {}
+ }
+
+ pub mod root {
+ use super::visitor::Trace;
+
+ pub struct Vm {
+ pub roots: Vec<crate::layout::value::Value>,
+ }
+
+ pub struct Root<'vm, T: Trace + 'static> {
+ pub vm: &'vm Vm,
+ pub value: Box<T>,
+ }
+
+ pub struct MarkedVec<'vm, T: Trace + Clone + 'static> {
+ pub vm: &'vm Vm,
+ pub values: core::cell::OnceCell<Root<'vm, Vec<T>>>,
+ }
+
+ impl<'vm, T: Trace + Clone + 'static> MarkedVec<'vm, T> {
+ pub fn new(vm: &'vm Vm) -> Self {
+ Self {
+ vm,
+ values: core::cell::OnceCell::new(),
+ }
+ }
+ }
+ }
+
+ pub mod defer_gc {
+ pub struct DeferGc<'vm>(pub &'vm super::root::Vm);
+
+ impl Drop for DeferGc<'_> {
+ fn drop(&mut self) {}
+ }
+
+ impl DeferGc<'_> {
+ pub fn cover<T>(&self, value: T) -> Deferred<'_, T> {
+ Deferred(value, core::marker::PhantomData)
+ }
+ }
+
+ pub struct Deferred<'d, T>(pub T, pub core::marker::PhantomData<&'d ()>);
+ }
+
+ pub mod lint_markers {
+ /// # Safety
+ ///
+ /// Stand-in.
+ pub unsafe trait KeepsAlive {}
+
+ unsafe impl<T: super::visitor::Trace + 'static> KeepsAlive for super::root::Root<'_, T> {}
+ unsafe impl<T: super::visitor::Trace + Clone + 'static> KeepsAlive for super::root::MarkedVec<'_, T> {}
+ unsafe impl<T> KeepsAlive for super::defer_gc::Deferred<'_, T> {}
+ unsafe impl KeepsAlive for super::root::Vm {}
+
+ /// # Safety
+ ///
+ /// Stand-in.
+ pub unsafe trait DefersCollections {}
+
+ unsafe impl DefersCollections for super::defer_gc::DeferGc<'_> {}
+
+ unsafe impl<T> DefersCollections for super::defer_gc::Deferred<'_, T> {}
+
+ /// # Safety
+ ///
+ /// Stand-in.
+ pub unsafe trait HoldsNoCells {}
+ }
+
+ pub mod weak {
+ /// # Safety
+ ///
+ /// Stand-in.
+ pub unsafe trait SweptAfterCollection {}
+
+ pub struct GcWeak<T> {
+ pub slot: usize,
+ pub cell: core::marker::PhantomData<fn() -> crate::layout::cell::Gc<T>>,
+ }
+ }
+}
+
+pub use gc::defer_gc::{DeferGc, Deferred};
+pub use gc::root::{MarkedVec, Root, Vm};
+pub use gc::visitor::{Trace, Visitor};
+pub use gc::weak::GcWeak;
+pub use layout::cell::Gc;
+pub use layout::value::Value;
+
+pub struct Cell;
+
+unsafe impl Trace for Cell {
+ fn trace(&self, _: &mut Visitor) {}
+}
+
+unsafe impl gc::class::GcCell for Cell {}
diff --git a/Meta/RustLints/tests/ui/auxiliary/smallvec.rs b/Meta/RustLints/tests/ui/auxiliary/smallvec.rs
new file mode 100644
index 00000000000..2907a53e840
--- /dev/null
+++ b/Meta/RustLints/tests/ui/auxiliary/smallvec.rs
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The layout of smallvec 1.x: the spill is a bare pointer, so the type structure does not show that it owns items.
+
+use core::mem::{ManuallyDrop, MaybeUninit};
+use core::ptr::NonNull;
+
+pub trait Array {
+ type Item;
+}
+
+impl<T, const N: usize> Array for [T; N] {
+ type Item = T;
+}
+
+union SmallVecData<A: Array> {
+ inline: ManuallyDrop<MaybeUninit<A>>,
+ heap: (NonNull<A::Item>, usize),
+}
+
+pub struct SmallVec<A: Array> {
+ capacity: usize,
+ data: SmallVecData<A>,
+}
+
+impl<A: Array> SmallVec<A> {
+ pub fn new() -> Self {
+ Self {
+ capacity: 0,
+ data: SmallVecData {
+ inline: ManuallyDrop::new(MaybeUninit::uninit()),
+ },
+ }
+ }
+}
diff --git a/Meta/RustLints/tests/ui/gc_container_on_stack.rs b/Meta/RustLints/tests/ui/gc_container_on_stack.rs
new file mode 100644
index 00000000000..90ee0c65a4c
--- /dev/null
+++ b/Meta/RustLints/tests/ui/gc_container_on_stack.rs
@@ -0,0 +1,335 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+// Mirrors Tests/ClangPlugins/LibJSGCTests/gc_pointer_container_on_stack.cpp.
+
+#![allow(unused, clippy::all)]
+
+use std::cell::RefCell;
+use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
+use std::rc::Rc;
+use std::sync::Arc;
+
+use js::{Cell, Gc, GcWeak, MarkedVec, Root, Value, Vm};
+use smallvec::SmallVec;
+
+pub struct Entry {
+ cell: Gc<Cell>,
+}
+
+pub struct EntryWithoutGcPointers {
+ value: i32,
+}
+
+pub struct State {
+ cells: Vec<Gc<Cell>>,
+}
+
+pub struct EntryWithArray {
+ cells: [Option<Gc<Cell>>; 2],
+}
+
+pub struct Wrapper<T>(T);
+
+pub enum Either {
+ Cell(Gc<Cell>),
+ Cells(Box<[Gc<Cell>]>),
+}
+
+pub fn make_cells() -> Vec<Gc<Cell>> { //~ ERROR return type 'Vec<Gc<Cell>>' keeps GC pointers in heap memory
+ Vec::new()
+}
+
+pub fn make_value() -> Value {
+ Value(0)
+}
+
+pub fn unrooted_locals(cell: Gc<Cell>) {
+ let refs: Vec<Gc<Cell>> = Vec::new(); //~ ERROR `refs` of type 'Vec<Gc<Cell>>' keeps GC pointers in heap memory
+ let values: Vec<Value> = Vec::new(); //~ ERROR 'Vec<Value>' keeps GC pointers
+ let optional_refs: Vec<Option<Gc<Cell>>> = Vec::new(); //~ ERROR 'Vec<Option<Gc<Cell>>>'
+ let nested: Vec<Vec<Gc<Cell>>> = Vec::new(); //~ ERROR 'Vec<Vec<Gc<Cell>>>'
+ let entries: Vec<Entry> = Vec::new(); //~ ERROR 'Vec<Entry>'
+ let map_values: HashMap<i32, Gc<Cell>> = HashMap::new(); //~ ERROR 'HashMap<i32, Gc<Cell>>'
+ let map_keys: HashMap<Gc<Cell>, i32> = HashMap::new(); //~ ERROR 'HashMap<Gc<Cell>, i32>'
+ let set: HashSet<Gc<Cell>> = HashSet::new(); //~ ERROR 'HashSet<Gc<Cell>>'
+ let ordered: BTreeMap<i32, Value> = BTreeMap::new(); //~ ERROR 'BTreeMap<i32, Value>'
+ let deque: VecDeque<Gc<Cell>> = VecDeque::new(); //~ ERROR 'VecDeque<Gc<Cell>>'
+ let boxed = Box::new(cell); //~ ERROR 'Box<Gc<Cell>>'
+ let shared = Rc::new(cell); //~ ERROR 'Rc<Gc<Cell>>'
+ let atomic = Arc::new(make_value()); //~ ERROR 'Arc<Value>'
+ let boxed_slice: Box<[Gc<Cell>]> = Box::new([cell]); //~ ERROR 'Box<[Gc<Cell>]>'
+ let optional_vector: Option<Vec<Gc<Cell>>> = None; //~ ERROR keeps GC pointers in heap memory
+ let state = State { cells: Vec::new() }; //~ ERROR `state` of type 'Vec<Gc<Cell>>'
+ let entries_with_arrays: Vec<EntryWithArray> = Vec::new(); //~ ERROR 'Vec<EntryWithArray>'
+ let groups: [Vec<Gc<Cell>>; 2] = [Vec::new(), Vec::new()]; //~ ERROR 'Vec<Gc<Cell>>'
+ let wrapped: Wrapper<Vec<Value>> = Wrapper(Vec::new()); //~ ERROR 'Vec<Value>'
+ let either = Either::Cell(cell); //~ ERROR 'Box<[Gc<Cell>]>'
+ let cell_ref_cell: RefCell<Vec<Gc<Cell>>> = RefCell::new(Vec::new()); //~ ERROR 'Vec<Gc<Cell>>'
+ let references: Vec<&Cell> = Vec::new(); //~ ERROR 'Vec<&Cell>'
+ let deduced = make_cells(); //~ ERROR `deduced` of type 'Vec<Gc<Cell>>'
+ let (first, second) = (make_cells(), 1); //~ ERROR `first` of type 'Vec<Gc<Cell>>'
+ let State { cells } = State { cells: Vec::new() }; //~ ERROR `cells` of type 'Vec<Gc<Cell>>'
+ let mut collected = Vec::new(); //~ ERROR `collected` of type 'Vec<Gc<Cell>>'
+ collected.push(cell);
+}
+
+pub fn generic_local<T>(cell: Gc<T>) {
+ let refs = vec![cell]; //~ ERROR 'Vec<Gc<T>>'
+}
+
+pub fn closure_local() {
+ let closure = || {
+ let refs: Vec<Gc<Cell>> = Vec::new(); //~ ERROR 'Vec<Gc<Cell>>'
+ };
+}
+
+pub fn parameter_by_value(cells: Vec<Gc<Cell>>, state: &mut State) { //~ ERROR `cells` of type 'Vec<Gc<Cell>>'
+ state.cells = cells;
+}
+
+pub fn state_by_value(state: State) {} //~ ERROR `state` of type 'Vec<Gc<Cell>>'
+
+pub fn closure_parameter() {
+ let closure = |cells: Vec<Gc<Cell>>| {}; //~ ERROR `cells` of type 'Vec<Gc<Cell>>'
+}
+
+pub struct Holder {
+ cells: Vec<Gc<Cell>>,
+}
+
+impl Holder {
+ pub fn new(cells: Vec<Gc<Cell>>) -> Self { //~ ERROR `cells` of type 'Vec<Gc<Cell>>'
+ Self { cells } //~^ ERROR return type 'Vec<Gc<Cell>>'
+ }
+
+ pub fn cells(&self) -> &[Gc<Cell>] {
+ &self.cells
+ }
+
+ pub fn cells_vec(&self) -> &Vec<Gc<Cell>> {
+ &self.cells
+ }
+
+ pub fn copy_cells(&self) -> Vec<Gc<Cell>> { //~ ERROR return type 'Vec<Gc<Cell>>'
+ self.cells.clone()
+ }
+}
+
+pub trait Provider {
+ fn declared_without_body(&self, cells: Vec<Gc<Cell>>);
+
+ fn provided(&self) -> Vec<Value> { //~ ERROR return type 'Vec<Value>'
+ Vec::new()
+ }
+}
+
+pub fn rooted_or_borrowed_parameters(
+ root: Root<'_, Vec<Gc<Cell>>>,
+ marked: MarkedVec<'_, Gc<Cell>>,
+ reference: &Vec<Gc<Cell>>,
+ mutable_reference: &mut Vec<Gc<Cell>>,
+ slice: &[Gc<Cell>],
+) {
+}
+
+pub fn rooted_or_not_holding_gc_pointers(vm: &Vm, state: &State, cell: Gc<Cell>) {
+ let marked = MarkedVec::<Gc<Cell>>::new(vm);
+ let roots: Vec<Root<'_, Gc<Cell>>> = Vec::new();
+ let weak_refs: Vec<GcWeak<Cell>> = Vec::new();
+ let entries_without_gc_pointers: Vec<EntryWithoutGcPointers> = Vec::new();
+ let integers: Vec<i32> = Vec::new();
+ let member_reference: &Vec<Gc<Cell>> = &state.cells;
+ let slice: &[Gc<Cell>] = &state.cells;
+ let pointer_into_member: *const Gc<Cell> = state.cells.as_ptr();
+ let single = cell;
+ let optional = Some(cell);
+ let array = [cell, cell];
+ let tuple = (cell, make_value());
+ let inline = Entry { cell };
+ let cell_value = std::cell::Cell::new(cell);
+ let iterator = state.cells.iter();
+ for cell in &state.cells {}
+ for cell in state.cells.iter().copied() {}
+ if let Some(ref cells) = Some(&state.cells) {}
+ match &Some(State { cells: Vec::new() }) {
+ Some(State { cells }) => {}
+ None => {}
+ }
+}
+
+pub struct TracedStorage {
+ cells: Vec<Gc<Cell>>,
+}
+
+unsafe impl js::Trace for TracedStorage {
+ fn trace(&self, _: &mut js::Visitor) {}
+}
+
+impl TracedStorage {
+ pub fn new(_: &js::DeferGc<'_>, cells: Vec<Gc<Cell>>) -> Self {
+ Self { cells }
+ }
+
+ pub fn with_cell(mut self, cell: Gc<Cell>) -> Self { //~ ERROR `self` of type 'Vec<Gc<Cell>>' //~ ERROR return type 'Vec<Gc<Cell>>'
+ self.cells.push(cell);
+ self
+ }
+}
+
+pub fn traced_storage_in_a_deferral(cell: Gc<Cell>) {
+ let build = |defer_gc: &js::DeferGc<'_>| TracedStorage::new(defer_gc, vec![cell]);
+}
+
+pub fn traced_storage_outside_a_deferral(cell: Gc<Cell>, vm: &Vm) {
+ let defer_gc = js::DeferGc(vm);
+ let storage = TracedStorage::new(&defer_gc, Vec::new()); //~ ERROR `storage` of type 'Vec<Gc<Cell>>'
+ let storages = vec![TracedStorage::new(&defer_gc, Vec::new())]; //~ ERROR 'Vec<TracedStorage>'
+}
+
+pub struct WeakCacheEntry {
+ shape: Option<Gc<Cell>>,
+}
+
+unsafe impl js::gc::weak::SweptAfterCollection for WeakCacheEntry {}
+
+pub fn swept_after_collection() -> Box<[WeakCacheEntry]> {
+ let entries: Vec<WeakCacheEntry> = Vec::new();
+ entries.into_boxed_slice()
+}
+
+pub fn traced_storage_in_a_box(storage: TracedStorage) -> Option<Box<TracedStorage>> { //~ ERROR `storage` of type 'Vec<Gc<Cell>>' //~ ERROR return type 'Box<TracedStorage>'
+ let boxed = Box::new(storage); //~ ERROR `boxed` of type 'Box<TracedStorage>'
+ Some(boxed)
+}
+
+pub fn takes_defer_gc(cell: Gc<Cell>, cells: Vec<Gc<Cell>>, _: &js::DeferGc<'_>) -> Vec<Gc<Cell>> {
+ let local = vec![cell];
+ let closure = || {
+ let in_closure = vec![cell];
+ };
+ let returns_cells = || make_cells();
+ cells
+}
+
+pub fn returns_deferred<'d>(cell: Gc<Cell>, defer_gc: &'d js::DeferGc<'_>) -> js::Deferred<'d, Vec<Gc<Cell>>> {
+ defer_gc.cover(vec![cell])
+}
+
+pub fn closure_takes_defer_gc(cell: Gc<Cell>) {
+ let build = |_: &js::DeferGc<'_>| {
+ let in_closure = vec![cell];
+ };
+ let build_cells = |_: &js::DeferGc<'_>| make_cells();
+ let nested = |_: &js::DeferGc<'_>| {
+ let inner = || {
+ let in_inner = vec![cell];
+ };
+ };
+}
+
+pub fn deferred_local(vm: &Vm, cell: Gc<Cell>) {
+ let defer_gc = js::DeferGc(vm);
+ let covered = defer_gc.cover(vec![cell]);
+ let uncovered = covered.0; //~ ERROR `uncovered` of type 'Vec<Gc<Cell>>'
+}
+
+pub fn under_defer_gc(vm: &Vm, cell: Gc<Cell>) {
+ let before = vec![cell]; //~ ERROR `before` of type 'Vec<Gc<Cell>>'
+ let defer_gc = js::DeferGc(vm);
+ let after = vec![cell]; //~ ERROR `after` of type 'Vec<Gc<Cell>>'
+ drop(defer_gc);
+ let closure = || {
+ let in_closure = vec![cell]; //~ ERROR `in_closure` of type 'Vec<Gc<Cell>>'
+ };
+}
+
+pub fn return_root(vm: &Vm) -> Root<'_, Vec<Gc<Cell>>> {
+ Root {
+ vm,
+ value: Box::new(Vec::new()),
+ }
+}
+
+pub fn return_reference(state: &State) -> &Vec<Gc<Cell>> {
+ &state.cells
+}
+
+pub fn return_optional() -> Option<Vec<Gc<Cell>>> { //~ ERROR return type 'Vec<Gc<Cell>>'
+ None
+}
+
+pub fn return_state() -> State { //~ ERROR return type 'Vec<Gc<Cell>>'
+ State { cells: Vec::new() }
+}
+
+pub fn return_from_closure() {
+ let closure = || make_cells(); //~ ERROR return type 'Vec<Gc<Cell>>'
+}
+
+pub fn range_over_temporary() {
+ for cell in make_cells() {} //~ ERROR the iterator 'IntoIter<Gc<Cell>>'
+}
+
+pub fn question_mark() -> Result<(), ()> {
+ let cells = Ok::<_, ()>(make_cells())?; //~ ERROR `cells` of type 'Vec<Gc<Cell>>'
+ Ok(())
+}
+
+pub fn closures(cell: Gc<Cell>, state: &State) {
+ let inline = move || cell;
+ let borrowed = || state.cells.len();
+ let boxed = Box::new(move || cell); //~ ERROR 'Box<{closure
+ let job: Box<dyn Fn() -> Gc<Cell>> = Box::new(move || cell); //~ ERROR coercion from 'Box<{closure
+ let borrowing_job: Box<dyn Fn() -> usize + '_> = Box::new(|| state.cells.len());
+ let empty: Box<[Gc<Cell>]> = Box::new([]); //~ ERROR `empty` of type 'Box<[Gc<Cell>]>'
+ run(Box::new(move || { //~ ERROR coercion from 'Box<{closure
+ let captured = cell;
+ }));
+}
+
+fn run(_: Box<dyn FnOnce()>) {}
+
+pub fn small_vectors(cell: Gc<Cell>) {
+ let spilled: SmallVec<[Gc<Cell>; 2]> = SmallVec::new(); //~ ERROR 'SmallVec<[Gc<Cell>; 2]>'
+ let integers: SmallVec<[i32; 2]> = SmallVec::new();
+}
+
+pub fn suppressed(cell: Gc<Cell>) {
+ #[cfg_attr(ladybird_gc_lints, expect(gc_container_on_stack, reason = "cell stays alive in the caller"))]
+ let cells = vec![cell];
+
+ #[cfg_attr(ladybird_gc_lints, allow(gc_container_on_stack))] //~ ERROR allowing `gc_container_on_stack` needs a `reason = "..."`
+ let without_reason = vec![cell];
+
+ #[cfg_attr(ladybird_gc_lints, expect(gc_container_on_stack, reason = "nothing to suppress"))] //~ WARN this lint expectation is unfulfilled
+ let nothing = cell;
+}
+
+/// A cell pointer in a tagged word, which only its hand-written trace() knows about.
+pub struct Tagged(usize);
+
+unsafe impl js::Trace for Tagged {
+ fn trace(&self, _: &mut js::Visitor) {}
+}
+
+pub trait TracedBehaviour: js::Trace {}
+
+impl TracedBehaviour for Tagged {}
+
+pub fn hand_traced(tagged: Tagged, more: Tagged) {
+ let words = vec![tagged]; //~ ERROR `words` of type 'Vec<Tagged>'
+ let behaviour: Box<dyn TracedBehaviour> = Box::new(more); //~ ERROR `behaviour` of type 'Box<dyn TracedBehaviour>'
+}
+
+/// A tagged word that holds no cell pointer, as a key that is never a symbol does.
+pub struct Untagged(Tagged);
+
+unsafe impl js::gc::lint_markers::HoldsNoCells for Untagged {}
+
+pub fn holds_no_cells(untagged: Untagged) {
+ let words = vec![untagged];
+}
diff --git a/Meta/RustLints/tests/ui/root_in_traced_type.rs b/Meta/RustLints/tests/ui/root_in_traced_type.rs
new file mode 100644
index 00000000000..75d499a5150
--- /dev/null
+++ b/Meta/RustLints/tests/ui/root_in_traced_type.rs
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+// Mirrors Tests/ClangPlugins/LibJSGCTests/strong_root_fields_in_gc_allocated_types.cpp.
+
+#![allow(unused, clippy::all)]
+
+use js::{Cell, Gc, MarkedVec, Root, Trace, Visitor};
+
+pub struct CellClass {
+ root: Root<'static, Gc<Cell>>, //~ ERROR 'CellClass' implements Trace but holds the root 'Root<'static, Gc<Cell>>'
+ marked: MarkedVec<'static, Gc<Cell>>, //~ ERROR holds the root 'MarkedVec<'static, Gc<Cell>>'
+ nested: Option<Vec<Root<'static, Gc<Cell>>>>, //~ ERROR holds the root 'Root<'_, Gc<Cell>>'
+ cell: Gc<Cell>,
+}
+
+unsafe impl Trace for CellClass {
+ fn trace(&self, _: &mut Visitor) {}
+}
+
+pub enum TracedEnum {
+ Rooted(Root<'static, Gc<Cell>>), //~ ERROR 'TracedEnum' implements Trace but holds the root
+ Plain(Gc<Cell>),
+}
+
+unsafe impl Trace for TracedEnum {
+ fn trace(&self, _: &mut Visitor) {}
+}
+
+pub struct NonTracedClass {
+ root: Root<'static, Gc<Cell>>,
+}
+
+pub struct SuppressedClass {
+ #[cfg_attr(ladybird_gc_lints, expect(root_in_traced_type, reason = "the root is cleared before the cell dies"))]
+ root: Root<'static, Gc<Cell>>,
+}
+
+unsafe impl Trace for SuppressedClass {
+ fn trace(&self, _: &mut Visitor) {}
+}