lua_types/trace_impls.rs
1//! Phase-D `Trace` implementations for types defined in this crate.
2//!
3//! Each impl enumerates the type's GC-bearing fields and either calls
4//! `field.trace(m)` (delegating to the field's own `Trace` impl) or
5//! `m.mark(field)` (when the field is a `Gc<T>` from `lua-gc`). During the
6//! Phase A/B/C/D-0 window `GcRef<T>` is still an `Rc<T>` newtype rather
7//! than the real `Gc<T>`, so the mark-queue path is not yet reachable —
8//! method resolution dispatches through `Deref` to each underlying type's
9//! own `trace` method.
10
11use lua_gc::{Marker, Trace};
12use crate::gc::GcRef;
13use crate::value::LuaValue;
14use crate::table::LuaTable;
15use crate::upval::UpVal;
16use crate::string::LuaString;
17use crate::proto::LuaProto;
18use crate::closure::{LuaClosure, LuaLClosure, LuaCClosure};
19use crate::userdata::LuaUserData;
20use crate::value::LuaThread;
21
22/// Forwarder for `GcRef<T>`. Now that `GcRef` wraps a real `lua_gc::Gc<T>`
23/// (D-1e), tracing must enqueue the box onto the gray queue via
24/// `Marker::mark` — that is what flips its header color from White to Gray
25/// and ultimately to Black during gray-queue drainage. The previous
26/// `try_visit` short-circuit was a Phase A-D-0 workaround for the
27/// `Rc`-backed handle (no header, no color), and produced a silent bug
28/// post-D-1e: every GC-tracked allocation stayed White and was freed in
29/// the sweep on the first `collectgarbage()`. Cycles are now handled
30/// natively by the heap's gray-queue (Color::Gray check in `mark` makes
31/// re-visits idempotent).
32impl<T: Trace + 'static> Trace for GcRef<T> {
33 fn trace(&self, m: &mut Marker) {
34 m.mark(self.0);
35 }
36}
37
38/// LuaValue — central enum. Variants Nil/Bool/Int/Float/LightUserData carry
39/// no GC; Str/Table/Function/UserData/Thread carry collectable payloads.
40impl Trace for LuaValue {
41 fn trace(&self, m: &mut Marker) {
42 match self {
43 LuaValue::Nil
44 | LuaValue::Bool(_)
45 | LuaValue::Int(_)
46 | LuaValue::Float(_)
47 | LuaValue::LightUserData(_) => {}
48 LuaValue::Str(s) => s.trace(m),
49 LuaValue::Table(t) => t.trace(m),
50 LuaValue::Function(c) => c.trace(m),
51 LuaValue::UserData(u) => {
52 u.trace(m);
53 }
54 LuaValue::Thread(t) => {
55 // Mark the thread identity itself. lua-vm's GC post-mark hook
56 // uses the visited identities to trace only reachable
57 // suspended LuaState stacks.
58 t.trace(m);
59 }
60 }
61 }
62}
63
64/// LuaString — interned byte string. The `Rc<[u8]>` backing buffer is
65/// owned, not GC-managed, so this impl is intentionally empty.
66impl Trace for LuaString {
67 fn trace(&self, _m: &mut Marker) {}
68}
69
70/// UpVal — Open (refers to a thread stack slot by index) or Closed (owns a
71/// LuaValue). The Open variant carries no direct GC reference; the slot it
72/// points at is traced through the owning thread's stack walk.
73impl Trace for UpVal {
74 fn trace(&self, m: &mut Marker) {
75 if self.try_open_payload().is_some() {
76 return;
77 }
78 if let Some(v) = self.try_closed_value() {
79 v.trace(m);
80 }
81 }
82}
83
84/// LuaTable — array+hash entries plus optional metatable.
85///
86/// Weak-table semantics (matches `lgc.c::traversetable`):
87/// * `__mode = "v"` — strong keys, weak values. Trace keys here; value
88/// side is deferred — string values get marked in `prune_weak_dead`'s
89/// surviving-entry pass (Lua's `iscleared`), non-string dead values
90/// trigger entry removal.
91/// * `__mode = "kv"` — both sides weak. Trace NEITHER here; everything
92/// is handled by `prune_weak_dead` (matches Lua's "just add to allweak,
93/// traverse nothing" path).
94/// * `__mode = "k"` — weak keys, strong values. Trace NEITHER here. The
95/// post-mark ephemeron convergence pass walks each weak-key table's
96/// entries and marks values only for entries whose keys are
97/// independently reachable. String keys get marked in `prune_weak_dead`.
98/// * No `__mode` — trace both unconditionally.
99///
100/// Marking strings inline for weak slots (the previous behavior) would
101/// pin them alive even when their containing entry is about to be cleared
102/// because the other side died — breaking the `gc.lua` weak-string-key
103/// block, which expects unreferenced long strings to free their bytes
104/// after a single `collectgarbage()` cycle.
105impl Trace for LuaTable {
106 fn trace(&self, m: &mut Marker) {
107 const WEAK_KEYS: u8 = 1;
108 const WEAK_VALUES: u8 = 1 << 1;
109 let mode = self.weak_mode();
110 let trace_keys = (mode & WEAK_KEYS) == 0;
111 let trace_values = (mode & WEAK_VALUES) == 0 && trace_keys;
112 self.for_each_entry(|k, v| {
113 if trace_keys { k.trace(m); }
114 if trace_values { v.trace(m); }
115 });
116 if let Some(mt) = self.metatable() {
117 mt.trace(m);
118 }
119 }
120}
121
122/// LuaProto — bytecode prototype. k (constants), p (child protos),
123/// source, upvalue names, locvar names.
124impl Trace for LuaProto {
125 fn trace(&self, m: &mut Marker) {
126 for v in self.k.iter() {
127 v.trace(m);
128 }
129 for p in self.p.iter() {
130 p.trace(m);
131 }
132 if let Some(src) = &self.source {
133 src.trace(m);
134 }
135 for uv in self.upvalues.iter() {
136 if let Some(name) = &uv.name {
137 name.trace(m);
138 }
139 }
140 for lv in self.locvars.iter() {
141 lv.varname.trace(m);
142 }
143 if let Some(c) = self.cache.borrow().as_ref() {
144 c.trace(m);
145 }
146 }
147}
148
149/// LuaLClosure — Lua closure carrying a Proto and its captured upvalues.
150impl Trace for LuaLClosure {
151 fn trace(&self, m: &mut Marker) {
152 self.proto.trace(m);
153 for uv in self.upvals.iter() {
154 uv.get().trace(m);
155 }
156 }
157}
158
159/// LuaClosure — dispatch to Lua/C variants; LightC is a bare function-ptr
160/// index with no payload.
161impl Trace for LuaClosure {
162 fn trace(&self, m: &mut Marker) {
163 match self {
164 LuaClosure::Lua(l) => l.trace(m),
165 LuaClosure::C(c) => c.trace(m),
166 LuaClosure::LightC(_) => {}
167 }
168 }
169}
170
171/// LuaCClosure — Rust-side C closure carrying captured upvalues.
172impl Trace for LuaCClosure {
173 fn trace(&self, m: &mut Marker) {
174 for v in self.upvalues.borrow().iter() {
175 v.trace(m);
176 }
177 }
178}
179
180/// LuaUserData — boxed payload + optional metatable + user values.
181impl Trace for LuaUserData {
182 fn trace(&self, m: &mut Marker) {
183 if let Some(mt) = self.metatable() {
184 mt.trace(m);
185 }
186 for v in self.uv.borrow().iter() {
187 v.trace(m);
188 }
189 }
190}
191
192/// LuaThread — value-side thread identity. Carries only a `ThreadId`
193/// (the registry key); the real per-thread `LuaState` lives in
194/// `lua-vm`'s `GlobalState::threads` map and is traced from
195/// `GlobalState::trace` as a root.
196impl Trace for LuaThread {
197 fn trace(&self, _m: &mut Marker) {}
198}
199
200// ──────────────────────────────────────────────────────────────────────────────
201// PORT STATUS
202// source: n/a (GC Trace impls scoped to lua-types public surface)
203// target_crate: lua-types
204// confidence: high
205// todos: 0
206// port_notes: 0
207// unsafe_blocks: 0
208// notes: Trace impls for GC visitor over the canonical type set. No C analogue;
209// the C GC walks struct fields directly via macros.
210// ──────────────────────────────────────────────────────────────────────────────