Truly independent web browser
Meta+LibJS: Reject GcRefCells around state the collector never reads
Shannon Boothc9d0126f0b6f
diff --git a/Libraries/LibJS/Rust/src/gc/lint_markers.rs b/Libraries/LibJS/Rust/src/gc/lint_markers.rsindex 5ce320f1928..b1141f3df8c 100644--- a/Libraries/LibJS/Rust/src/gc/lint_markers.rs+++ b/Libraries/LibJS/Rust/src/gc/lint_markers.rs@@ -9,6 +9,7 @@//! 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::gc_ref_cell::GcRefCell;use super::root::{MarkedVec, Root};use super::sweep::Sweep;use super::visitor::Trace;@@ -50,3 +51,8 @@ unsafe impl DefersCollections for Sweep<'_> {}////// No value of the type may hold a pointer to a cell.pub unsafe trait HoldsNoCells {}++/// Interior mutability for state that the collector traces, which state without GC pointers has no use for.+pub trait TracedState {}++impl<T> TracedState for GcRefCell<T> {}diff --git a/Meta/RustLints/README.md b/Meta/RustLints/README.mdindex 62f6c26deda..3ff4fb2497f 100644--- a/Meta/RustLints/README.md+++ b/Meta/RustLints/README.md@@ -17,6 +17,8 @@ plugin:- `gc_container_in_untraced_type`: a type that does not implement `Trace` keeps a GC pointer in a field through heapmemory, an `Rc` or a `Box` included. Nothing traces its values wherever they are held: implement `Trace` for it, sothat its owner traces it, or tie it to a deferral.+- `gc_ref_cell_without_gc_pointers`: a `GcRefCell` field whose state the collector never reads, because the field is+ untraced or its type holds no GC pointer and no type with a hand-written `Trace`. Such state takes a `RefCell`.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 itsdiff --git a/Meta/RustLints/src/gc_lints.rs b/Meta/RustLints/src/gc_lints.rsindex d858da8c36e..b0e2ee090bf 100644--- a/Meta/RustLints/src/gc_lints.rs+++ b/Meta/RustLints/src/gc_lints.rs@@ -20,7 +20,7 @@ use rustc_lint::{LateContext, LateLintPass, Lint};use rustc_middle::lint::LintLevelSource;use rustc_middle::ty::adjustment::{Adjust, DerefAdjustKind, PointerCoercion};use rustc_middle::ty::print::with_forced_trimmed_paths;-use rustc_middle::ty::{self, Ty, TyCtxt};+use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt};use rustc_session::{declare_lint, impl_lint_pass};use rustc_span::{DesugaringKind, Span, Symbol};@@ -70,12 +70,21 @@ declare_lint! {"GC pointers kept in heap memory by a type that is not traced"}+declare_lint! {+ /// A `GcRefCell` holds state that the collector never reads: the state cannot hold a GC pointer, or its field is+ /// untraced. Use a `RefCell`, which a collection never borrows.+ pub GC_REF_CELL_WITHOUT_GC_POINTERS,+ Deny,+ "`GcRefCell` around state that the collector does not trace"+}+pub static LINTS: &[&Lint] = &[GC_CONTAINER_ON_STACK,ROOT_IN_TRACED_TYPE,UNTRACED_GC_POINTER,GC_POINTER_IN_DROP,GC_CONTAINER_IN_UNTRACED_TYPE,+ GC_REF_CELL_WITHOUT_GC_POINTERS,];#[derive(Clone, Copy, PartialEq, Eq)]@@ -119,6 +128,7 @@ pub struct GcLints<'tcx> {deferral_scoped: FxHashMap<DefId, bool>,reaches_gc_pointer: FxHashMap<Ty<'tcx>, bool>,reported_attributes: FxHashSet<Span>,+ traced_state_types: FxHashSet<DefId>,hand_traced_types: FxHashSet<DefId>,trace_trait: Option<DefId>,enabled: bool,@@ -130,6 +140,7 @@ impl_lint_pass!(GcLints<'_> => [UNTRACED_GC_POINTER,GC_POINTER_IN_DROP,GC_CONTAINER_IN_UNTRACED_TYPE,+ GC_REF_CELL_WITHOUT_GC_POINTERS,]);const LIBJS_CRATE: &str = "libjs_rust";@@ -497,6 +508,46 @@ impl<'tcx> GcLints<'tcx> {);}+ /// Rejects the fields of `def_id` that keep state the collector never reads in a type for traced state.+ fn check_traced_state(&mut self, cx: &LateContext<'tcx>, def_id: DefId) {+ let tcx = cx.tcx;+ let untraced = Symbol::intern("untraced");+ for field in tcx.adt_def(def_id).all_fields() {+ let ty = normalize(cx, tcx.type_of(field.did).instantiate_identity().skip_normalization());+ let ty::Adt(adt, args) = ty.kind() else {+ continue;+ };+ if !self.traced_state_types.contains(&adt.did()) {+ continue;+ }+ let state = args.type_at(0);+ if state.has_param() {+ continue;+ }+ let field_id = tcx.local_def_id_to_hir_id(field.did.expect_local());+ let is_untraced = tcx.hir_attrs(field_id).iter().any(|attribute| {+ attribute.has_name(Symbol::intern("gc"))+ && attribute+ .meta_item_list()+ .is_some_and(|items| items.iter().any(|item| item.has_name(untraced)))+ });+ let why = if is_untraced {+ "is untraced"+ } else if !self.reaches_gc_pointer(cx, state, &mut Vec::new()) {+ "holds no GC pointers"+ } else {+ continue;+ };+ self.emit(+ cx,+ GC_REF_CELL_WITHOUT_GC_POINTERS,+ field_id,+ tcx.def_span(field.did),+ with_forced_trimmed_paths!(format!("field of type '{ty}' {why}; use a RefCell")),+ );+ }+ }+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(@@ -557,6 +608,7 @@ impl<'tcx> LateLintPass<'tcx> for GcLints<'tcx> {let mut holds_no_cells_types = FxHashSet::default();let mut keeps_alive_types = FxHashSet::default();let mut defers_collections_types = FxHashSet::default();+ let mut traced_state_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.@@ -583,12 +635,14 @@ impl<'tcx> LateLintPass<'tcx> for GcLints<'tcx> {"libjs_rust::gc::lint_markers::DefersCollections",&mut defers_collections_types,);+ collect("libjs_rust::gc::lint_markers::TracedState", &mut traced_state_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.traced_state_types = traced_state_types;self.hand_traced_types = hand_traced_types;self.trace_trait = Some(trace);}@@ -714,6 +768,7 @@ impl<'tcx> LateLintPass<'tcx> for GcLints<'tcx> {return;}let def_id = item.owner_id.to_def_id();+ self.check_traced_state(cx, def_id);if !self.traced_types.contains(&def_id) {// NB: The GC's own types, like Root, are what the markers say they are, whatever their fields hold.if self.kind(cx.tcx, def_id) != Kind::Other || self.is_deferral_scoped(cx.tcx, def_id) {diff --git a/Meta/RustLints/tests/ui/auxiliary/libjs_rust.rs b/Meta/RustLints/tests/ui/auxiliary/libjs_rust.rsindex 57cc4116653..7adbb7d40eb 100644--- a/Meta/RustLints/tests/ui/auxiliary/libjs_rust.rs+++ b/Meta/RustLints/tests/ui/auxiliary/libjs_rust.rs@@ -92,6 +92,10 @@ pub mod gc {}}+ pub mod gc_ref_cell {+ pub struct GcRefCell<T>(pub core::cell::RefCell<T>);+ }+pub mod defer_gc {pub struct DeferGc<'vm>(pub &'vm super::root::Vm);@@ -132,6 +136,10 @@ pub mod gc {////// Stand-in.pub unsafe trait HoldsNoCells {}++ pub trait TracedState {}++ impl<T> TracedState for super::gc_ref_cell::GcRefCell<T> {}}pub mod weak {@@ -148,6 +156,7 @@ pub mod gc {}pub use gc::defer_gc::{DeferGc, Deferred};+pub use gc::gc_ref_cell::GcRefCell;pub use gc::root::{MarkedVec, Root, Vm};pub use gc::visitor::{Trace, Visitor};pub use gc::weak::GcWeak;diff --git a/Meta/RustLints/tests/ui/gc_ref_cell_without_gc_pointers.rs b/Meta/RustLints/tests/ui/gc_ref_cell_without_gc_pointers.rsnew file mode 100644index 00000000000..6bea6a06e04--- /dev/null+++ b/Meta/RustLints/tests/ui/gc_ref_cell_without_gc_pointers.rs@@ -0,0 +1,39 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#![allow(unused, clippy::all)]++use js::{Cell, Gc, GcRefCell, GcWeak, Value, Visitor};+use libjs_runtime_macros::Trace;++#[derive(Trace)]+pub struct Traced {+ cells: GcRefCell<Vec<Gc<Cell>>>,+ value: GcRefCell<Option<Value>>,+ counts: GcRefCell<Vec<u32>>, //~ ERROR field of type 'GcRefCell<Vec<u32>>' holds no GC pointers; use a RefCell+ weak: GcRefCell<Vec<GcWeak<Cell>>>, //~ ERROR field of type 'GcRefCell<Vec<GcWeak<Cell>>>' holds no GC pointers; use a RefCell+ #[gc(untraced)]+ name: GcRefCell<String>, //~ ERROR field of type 'GcRefCell<String>' is untraced; use a RefCell+ #[gc(untraced = "the owner traces it")]+ owned: GcRefCell<Gc<Cell>>, //~ ERROR field of type 'GcRefCell<Gc<Cell>>' is untraced; use a RefCell+ plain: core::cell::RefCell<Vec<u32>>,+ tagged: GcRefCell<Vec<Tagged>>,+}++unsafe impl js::Trace for Traced {+ fn trace(&self, _: &mut Visitor) {}+}++/// 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 Visitor) {}+}++pub struct Generic<T> {+ state: GcRefCell<T>,+}