Skip to main content

lua_vm/
state.rs

1//! Global interpreter state.
2//!
3//! Manages per-thread ([`LuaState`]) and process-wide ([`GlobalState`]) Lua state:
4//! creation, initialization, teardown, and coroutine lifecycle helpers. Mirrors
5//! the responsibilities of Lua's `lstate.c`/`lstate.h`.
6//!
7//! C's `LX`/`LG` structs and the `fromstate` macro exist only to allocate the
8//! main thread and global state as one contiguous block via pointer
9//! arithmetic; here `GlobalState` and `LuaState` are separate heap-allocated
10//! values linked via `Rc<RefCell<GlobalState>>`, so no equivalent is needed.
11
12use std::cell::RefCell;
13use std::hash::{BuildHasherDefault, Hasher};
14use std::rc::Rc;
15
16pub use lua_types::error::LuaError;
17pub use lua_types::{CallInfoIdx, StackIdx};
18
19/// Thin wrapper letting stack-indexing methods accept either `StackIdx` or a
20/// raw integer via a single `impl Into<StackIdxConv>` bound.
21pub struct StackIdxConv(pub StackIdx);
22
23/// Explicit `StackIdx` → `i32` conversion for call sites that need a signed
24/// index and would otherwise hit an ambiguous non-primitive-cast error.
25#[inline(always)]
26pub fn stack_idx_to_i32(i: StackIdx) -> i32 {
27    i.0 as i32
28}
29
30impl From<u32> for StackIdxConv {
31    #[inline(always)]
32    fn from(v: u32) -> Self {
33        StackIdxConv(StackIdx(v))
34    }
35}
36impl From<i32> for StackIdxConv {
37    #[inline(always)]
38    fn from(v: i32) -> Self {
39        StackIdxConv(StackIdx(v.max(0) as u32))
40    }
41}
42impl From<usize> for StackIdxConv {
43    #[inline(always)]
44    fn from(v: usize) -> Self {
45        StackIdxConv(StackIdx(v as u32))
46    }
47}
48impl From<StackIdx> for StackIdxConv {
49    #[inline(always)]
50    fn from(v: StackIdx) -> Self {
51        StackIdxConv(v)
52    }
53}
54pub use lua_types::closure::{
55    LuaCClosure as LuaClosureC, LuaCFnPtr, LuaClosure, LuaLClosure as LuaClosureLua,
56};
57pub use lua_types::gc::GcRef;
58pub use lua_types::proto::LuaProto;
59pub use lua_types::string::LuaString;
60pub use lua_types::upval::UpVal;
61pub use lua_types::userdata::LuaUserData;
62pub use lua_types::value::{F2Imod, LuaTable, LuaValue};
63
64pub struct LuaByteHasher {
65    hash: u64,
66}
67
68impl Default for LuaByteHasher {
69    fn default() -> Self {
70        Self {
71            hash: 0xcbf2_9ce4_8422_2325,
72        }
73    }
74}
75
76impl Hasher for LuaByteHasher {
77    #[inline]
78    fn write(&mut self, bytes: &[u8]) {
79        const PRIME: u64 = 0x0000_0100_0000_01b3;
80        for &byte in bytes {
81            self.hash ^= u64::from(byte);
82            self.hash = self.hash.wrapping_mul(PRIME);
83        }
84    }
85
86    #[inline]
87    fn write_u8(&mut self, i: u8) {
88        self.write(&[i]);
89    }
90
91    #[inline]
92    fn write_usize(&mut self, i: usize) {
93        self.write(&i.to_ne_bytes());
94    }
95
96    #[inline]
97    fn finish(&self) -> u64 {
98        self.hash
99    }
100}
101
102pub type LuaByteBuildHasher = BuildHasherDefault<LuaByteHasher>;
103
104/// The short-string intern table, shaped like C-Lua's `stringtable`
105/// (lstring.c): power-of-two hash buckets of `GcRef<LuaString>` chained by
106/// Vec instead of `u.hnext`. Compared to the previous
107/// `HashMap<Box<[u8]>, GcRef<LuaString>>`:
108///
109/// - lookup hashes the input bytes ONCE and never allocates (the entry-API
110///   shape boxed the key on every call — rejected experiment
111///   `intern-hitpath-borrowed-lookup` documents why a partial fix loses);
112/// - insert reuses the same hash, no second probe;
113/// - bytes are stored once (in the `LuaString`), not duplicated in a map key;
114/// - dead strings are removed O(dead) by `(hash, identity)` pairs collected
115///   during the GC mark phase, replacing the O(table·log live)
116///   sort + binary-search retain that dominated churn-heavy profiles
117///   (concat_chain 20260609T2201Z: intern machinery ~25% of wall).
118pub struct InternedStringMap {
119    buckets: Vec<Vec<GcRef<LuaString>>>,
120    count: usize,
121}
122
123impl Default for InternedStringMap {
124    fn default() -> Self {
125        InternedStringMap {
126            buckets: (0..64).map(|_| Vec::new()).collect(),
127            count: 0,
128        }
129    }
130}
131
132impl InternedStringMap {
133    #[inline]
134    fn mask(&self) -> usize {
135        self.buckets.len() - 1
136    }
137
138    pub fn len(&self) -> usize {
139        self.count
140    }
141
142    pub fn is_empty(&self) -> bool {
143        self.count == 0
144    }
145
146    /// Number of hash buckets currently allocated (the power-of-two table
147    /// size, C's `strt.size`). Exposed for the shrink-policy test, which
148    /// asserts the array grows under a flood and shrinks back toward 64 once
149    /// the interned strings are collected.
150    pub fn bucket_count(&self) -> usize {
151        self.buckets.len()
152    }
153
154    #[inline]
155    pub fn find(&self, bytes: &[u8], hash: u32) -> Option<GcRef<LuaString>> {
156        let bucket = &self.buckets[hash as usize & self.mask()];
157        bucket
158            .iter()
159            .find(|s| s.hash() == hash && s.as_bytes() == bytes)
160            .cloned()
161    }
162
163    /// C's `luaS_resize` growth rule: keep average chain length ~1.
164    pub fn insert(&mut self, s: GcRef<LuaString>) {
165        if self.count >= self.buckets.len() {
166            self.resize(self.buckets.len() * 2);
167        }
168        let m = self.mask();
169        self.buckets[s.hash() as usize & m].push(s);
170        self.count += 1;
171    }
172
173    fn resize(&mut self, new_len: usize) {
174        let old = std::mem::replace(
175            &mut self.buckets,
176            (0..new_len).map(|_| Vec::new()).collect(),
177        );
178        let m = self.mask();
179        for bucket in old {
180            for s in bucket {
181                self.buckets[s.hash() as usize & m].push(s);
182            }
183        }
184    }
185
186    /// C's `luaS_resize` shrink path, driven by `lgc.c:checkSizes`
187    /// (`if (g->strt.nuse < g->strt.size / 4) luaS_resize(L, size/2)`).
188    /// Shrinks the bucket array when the live load factor falls below 25%
189    /// (`count * 4 < buckets.len()`), down to `next_power_of_two(count)`
190    /// floored at the initial 64 (C's `MINSTRTABSIZE`). The 4× gap is
191    /// hysteresis: a table at load factor just under 1.0 will not thrash,
192    /// since the next grow-then-shrink cycle needs the population to drop
193    /// fourfold first. Rehashing only relocates the surviving
194    /// `GcRef<LuaString>` entries by their cached `hash()`; it never derefs a
195    /// string, so it is safe to call from the post-mark/sweep GC hook AFTER
196    /// all dead entries have been removed (only live refs remain).
197    pub fn shrink_if_sparse(&mut self) {
198        if self.count * 4 >= self.buckets.len() {
199            return;
200        }
201        let target = self.count.next_power_of_two().max(64);
202        if target < self.buckets.len() {
203            self.resize(target);
204        }
205    }
206
207    /// O(dead): removes one entry located by its cached hash + GC identity.
208    pub fn remove(&mut self, hash: u32, identity: usize) {
209        let m = self.mask();
210        let bucket = &mut self.buckets[hash as usize & m];
211        if let Some(pos) = bucket.iter().position(|s| s.identity() == identity) {
212            bucket.swap_remove(pos);
213            self.count -= 1;
214        }
215    }
216
217    pub fn iter(&self) -> impl Iterator<Item = &GcRef<LuaString>> {
218        self.buckets.iter().flatten()
219    }
220
221    pub fn contains_key(&self, bytes: &[u8]) -> bool {
222        self.find(bytes, LuaString::hash_bytes(bytes, 0)).is_some()
223    }
224}
225
226/// A Lua-callable function pointer. C: `lua_CFunction`.
227///
228/// `lua_types::closure::LuaCFnPtr` is a `usize`-sized placeholder in that
229/// crate (which cannot reference `LuaState` without a circular dependency);
230/// this alias carries the real, lua-vm-facing signature.
231pub type LuaCFunction = fn(&mut LuaState) -> Result<usize, LuaError>;
232
233pub type LuaRustFunction = Rc<dyn Fn(&mut LuaState) -> Result<usize, LuaError>>;
234
235#[derive(Clone)]
236pub enum LuaCallable {
237    Bare(LuaCFunction),
238    Rust(LuaRustFunction),
239}
240
241impl std::fmt::Debug for LuaCallable {
242    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
243        match self {
244            LuaCallable::Bare(_) => f.write_str("LuaCallable::Bare(..)"),
245            LuaCallable::Rust(_) => f.write_str("LuaCallable::Rust(..)"),
246        }
247    }
248}
249
250impl LuaCallable {
251    pub fn bare(f: LuaCFunction) -> Self {
252        LuaCallable::Bare(f)
253    }
254
255    pub fn rust(f: LuaRustFunction) -> Self {
256        LuaCallable::Rust(f)
257    }
258
259    pub fn as_bare(&self) -> Option<LuaCFunction> {
260        match self {
261            LuaCallable::Bare(f) => Some(*f),
262            LuaCallable::Rust(_) => None,
263        }
264    }
265
266    pub fn call(&self, state: &mut LuaState) -> Result<usize, LuaError> {
267        match self {
268            LuaCallable::Bare(f) => f(state),
269            LuaCallable::Rust(f) => f(state),
270        }
271    }
272}
273
274#[derive(Clone, Debug)]
275pub enum FinalizerObject {
276    Table(GcRef<LuaTable>),
277    UserData(GcRef<LuaUserData>),
278}
279
280impl FinalizerObject {
281    pub fn identity(&self) -> usize {
282        match self {
283            FinalizerObject::Table(t) => t.identity(),
284            FinalizerObject::UserData(u) => u.identity(),
285        }
286    }
287
288    pub fn metatable(&self) -> Option<GcRef<LuaTable>> {
289        match self {
290            FinalizerObject::Table(t) => t.metatable(),
291            FinalizerObject::UserData(u) => u.metatable(),
292        }
293    }
294
295    pub fn as_lua_value(&self) -> LuaValue {
296        match self {
297            FinalizerObject::Table(t) => LuaValue::Table(t.clone()),
298            FinalizerObject::UserData(u) => LuaValue::UserData(u.clone()),
299        }
300    }
301
302    pub fn mark(&self, marker: &mut lua_gc::Marker) {
303        match self {
304            FinalizerObject::Table(t) => marker.mark(t.0),
305            FinalizerObject::UserData(u) => marker.mark(u.0),
306        }
307    }
308
309    pub fn heap_ptr(&self) -> Option<std::ptr::NonNull<lua_gc::GcBox<dyn lua_gc::Trace>>> {
310        Some(match self {
311            FinalizerObject::Table(t) => t.0.as_trace_ptr(),
312            FinalizerObject::UserData(u) => u.0.as_trace_ptr(),
313        })
314    }
315
316    pub fn age(&self) -> lua_gc::GcAge {
317        match self {
318            FinalizerObject::Table(t) => t.0.age(),
319            FinalizerObject::UserData(u) => u.0.age(),
320        }
321    }
322
323    pub fn is_finalized(&self) -> bool {
324        match self {
325            FinalizerObject::Table(t) => t.0.is_finalized(),
326            FinalizerObject::UserData(u) => u.0.is_finalized(),
327        }
328    }
329
330    pub fn set_finalized(&self, finalized: bool) {
331        match self {
332            FinalizerObject::Table(t) => t.0.set_finalized(finalized),
333            FinalizerObject::UserData(u) => u.0.set_finalized(finalized),
334        }
335    }
336}
337
338impl lua_gc::FinalizerEntry for FinalizerObject {
339    fn identity(&self) -> usize {
340        FinalizerObject::identity(self)
341    }
342
343    fn heap_ptr(&self) -> Option<std::ptr::NonNull<lua_gc::GcBox<dyn lua_gc::Trace>>> {
344        FinalizerObject::heap_ptr(self)
345    }
346
347    fn age(&self) -> lua_gc::GcAge {
348        FinalizerObject::age(self)
349    }
350
351    fn is_finalized(&self) -> bool {
352        FinalizerObject::is_finalized(self)
353    }
354
355    fn set_finalized(&self, finalized: bool) {
356        FinalizerObject::set_finalized(self, finalized);
357    }
358}
359
360#[derive(Clone, Debug)]
361pub struct WeakTableEntry {
362    table: lua_types::gc::GcWeak<LuaTable>,
363    kind: lua_gc::WeakListKind,
364}
365
366impl WeakTableEntry {
367    pub fn new(table: &GcRef<LuaTable>) -> Self {
368        let mode = table.weak_mode();
369        let weak_keys = (mode & (1 << 0)) != 0;
370        let weak_values = (mode & (1 << 1)) != 0;
371        let kind = match (weak_keys, weak_values) {
372            (true, true) => lua_gc::WeakListKind::AllWeak,
373            (true, false) => lua_gc::WeakListKind::Ephemeron,
374            (false, true) => lua_gc::WeakListKind::WeakValues,
375            (false, false) => lua_gc::WeakListKind::WeakValues,
376        };
377        Self {
378            table: table.downgrade(),
379            kind,
380        }
381    }
382}
383
384impl lua_gc::WeakEntry for WeakTableEntry {
385    type Strong = GcRef<LuaTable>;
386
387    fn identity(&self) -> usize {
388        self.table.identity()
389    }
390
391    fn list_kind(&self) -> lua_gc::WeakListKind {
392        self.kind
393    }
394
395    fn upgrade(&self) -> Option<Self::Strong> {
396        self.table.upgrade()
397    }
398}
399
400// ─── Constants ───────────────────────────────────────────────────────────────
401
402pub(crate) const EXTRA_STACK: usize = 5;
403
404pub(crate) const LUA_MINSTACK: usize = 20;
405
406pub(crate) const BASIC_STACK_SIZE: usize = 2 * LUA_MINSTACK;
407
408/// Maximum nested non-yielding C-call recursion depth — the single source of
409/// truth for the call-depth guard (also used by `do_::ccall_inner` and
410/// `do_::lua_resume`).
411///
412/// This is the structural defense that keeps a recursive interpreter sound for
413/// untrusted code: a recursive Rust interpreter consumes host (Rust) stack per
414/// nested Lua→Lua call, so unbounded Lua recursion would otherwise overflow the
415/// OS thread stack and crash the process. Tripping this limit instead raises a
416/// catchable `"stack overflow"` / `"C stack overflow"` Lua error.
417///
418/// Safe margin: each nested call frame consumes a bounded amount of Rust stack,
419/// so `MAXCCALLS` frames fit within the default ~8 MiB thread stack with room to
420/// spare — verified on macOS/Linux release builds against deep non-tail
421/// recursion, infinite `__index`/`__concat`/`__tostring` metamethod chains, and
422/// nested-coroutine `__close` cascades, all of which error cleanly rather than
423/// SIGSEGV (see the `recursion_*` sandbox tests). Embedders that run the VM on a
424/// smaller thread stack should lower this constant proportionally (roughly
425/// `stack_bytes / 40_000`).
426
427pub(crate) const LUAI_MAXCCALLS: u32 = 200;
428
429pub(crate) const CIST_C: u16 = 1 << 1;
430
431pub(crate) const CIST_OAH: u16 = 1 << 0;
432pub(crate) const CIST_FRESH: u16 = 1 << 2;
433pub(crate) const CIST_HOOKED: u16 = 1 << 3;
434pub(crate) const CIST_YPCALL: u16 = 1 << 4;
435pub(crate) const CIST_TAIL: u16 = 1 << 5;
436pub(crate) const CIST_HOOKYIELD: u16 = 1 << 6;
437pub(crate) const CIST_FIN: u16 = 1 << 7;
438pub(crate) const CIST_TRAN: u16 = 1 << 8;
439pub(crate) const CIST_RECST: u32 = 10;
440/// Marks a CallInfo whose `__lt` call is standing in for a missing `__le`, so
441/// that if the `__lt` metamethod yields, the comparison-resume path
442/// (`vm::finish_op`) knows to negate the result — the synchronous derive in
443/// `tagmethods::call_order_tm` cannot, since the negation happens after the
444/// yield unwinds the stack. Bits 10-12 are CIST_RECST, so this is bit 13.
445pub(crate) const CIST_LEQ: u16 = 1 << 13;
446
447/// Per-frame hook trap flag, folded out of `CallInfoFrame` into a free
448/// callstatus bit by T2-C2. C 5.4 stores trap in `ci->u.l.trap` (a Lua-only
449/// union field); we instead store it in callstatus bit 14 so reading it costs
450/// one mask with no enum-discriminant branch. Bit 14 is free (LEQ=13 is the
451/// top used bit; RECST occupies 10-12). Only Lua frames are ever trapped
452/// (`set_traps` guards on `is_lua()`), and the bit is cleared whenever a
453/// CallInfo slot is repurposed for a new call (see `prep_call_info`).
454pub(crate) const CIST_TRAP: u16 = 1 << 14;
455
456const LUA_NUMTYPES: usize = 9;
457
458const GCSTPUSR: u8 = 1;
459const GCSTPGC: u8 = 2;
460
461const GCS_PAUSE: u8 = 0;
462
463const LUAI_GCPAUSE: u32 = 200;
464const LUAI_GCMUL: u32 = 100;
465const LUAI_GCSTEPSIZE: u8 = 13;
466const LUAI_GENMAJORMUL: u32 = 100;
467const LUAI_GENMINORMUL: u8 = 20;
468
469const WHITE0BIT: u8 = 0;
470
471const STRCACHE_N: usize = 53;
472const STRCACHE_M: usize = 2;
473
474/// `registry[LUA_RIDX_MAINTHREAD]`'s integer key on 5.2-5.4 (`lua.h`'s
475/// `LUA_RIDX_MAINTHREAD`). 5.5 renumbers it to `3`; see
476/// [`set_versioned_registry_slots`].
477const LUA_RIDX_MAINTHREAD: i64 = 1;
478
479/// `registry[LUA_RIDX_GLOBALS]`'s integer key on 5.2+ (`lua.h`'s
480/// `LUA_RIDX_GLOBALS`). Absent on 5.1.
481const LUA_RIDX_GLOBALS: i64 = 2;
482
483// ─── GcKind enum ─────────────────────────────────────────────────────────────
484
485/// Garbage collector operating mode.
486#[derive(Debug, Clone, Copy, PartialEq, Eq)]
487pub enum GcKind {
488    Incremental = 0,
489    Generational = 1,
490}
491
492/// State of the built-in warning handler, mirroring the `warnfoff` /
493/// `warnfon` / `warnfcont` static functions in upstream `lauxlib.c`.
494///
495/// `Off` is the install-time default (warnings disabled until `warn("@on")`).
496/// `On` is ready to begin a fresh message. `Cont` means the previous `warn`
497/// call had `tocont` set, so the next message part continues the current line
498/// without re-printing the `Lua warning: ` prefix.
499#[derive(Debug, Clone, Copy, PartialEq, Eq)]
500pub enum WarnMode {
501    Off,
502    On,
503    Cont,
504}
505
506/// Output mode for the testC/ltests warning sink.
507#[derive(Debug, Clone, Copy, PartialEq, Eq)]
508pub enum TestWarnMode {
509    Normal,
510    Allow,
511    Store,
512}
513
514// ─── LuaStatus enum ──────────────────────────────────────────────────────────
515
516/// Thread / call status codes.
517///
518pub use lua_types::status::LuaStatus;
519
520// ─── StackValue ───────────────────────────────────────────────────────────────
521
522/// One slot on the Lua value stack.
523///
524/// C's `StackValue` overlays a to-be-closed delta (`tbclist.delta: u16`) in a
525/// union with the value, because C threads its tbclist through the stack
526/// itself. The Rust port keeps that list as a side structure
527/// (`LuaState.tbclist: Vec<StackIdx>`), so the slot is just the value and
528/// stays 16 bytes — matching C's slot size without the union. A vestigial
529/// `tbc_delta: u16` field (written, never read) padded every slot to 24 bytes
530/// until it was removed on 2026-06-09 (PERF_PUSH_SPEC.md P3).
531#[derive(Clone)]
532pub struct StackValue {
533    pub val: LuaValue,
534}
535
536impl Default for StackValue {
537    fn default() -> Self {
538        StackValue {
539            val: LuaValue::Nil,
540        }
541    }
542}
543
544// ─── CallInfo ────────────────────────────────────────────────────────────────
545
546/// Saved state for a Lua or C call frame.
547///
548/// The C intrusive doubly-linked list (`previous`, `next` as raw pointers) is
549/// replaced by `Option<CallInfoIdx>` indices into `LuaState::call_info`.
550#[derive(Clone)]
551pub struct CallInfo {
552    pub func: StackIdx,
553
554    pub top: StackIdx,
555
556    pub previous: Option<CallInfoIdx>,
557
558    pub next: Option<CallInfoIdx>,
559
560    pub u: CallInfoFrame,
561
562    pub u2: CallInfoExtra,
563
564    pub nresults: i16,
565
566    /// Bit-packed `CIST_*` flags.
567    pub callstatus: u16,
568
569    /// Lua 5.5: number of `__call` metamethods traversed before entering this
570    /// frame. Upstream stores this in the repacked 5.5 `callstatus` bits; keep
571    /// it separate here so older transfer/recover-status bits stay unchanged.
572    pub call_metamethods: u8,
573
574    /// Lua 5.1: count of tail calls "lost" into this reused frame. Mirrors C
575    /// 5.1's `ci->tailcalls`. Each `OP_TAILCALL` reuses the current frame and
576    /// increments this; a normal call gets a fresh slot (via `next_ci`) where
577    /// it is reset to 0. Used only by the 5.1 `debug.getstack` level walk to
578    /// synthesize the `(tail call)` frames the 5.1 debug model exposes; 5.2+
579    /// dropped that model in favour of the `istailcall` flag and never read it.
580    /// Lives in the 3 spare bytes after `call_metamethods`, so `CallInfo` stays
581    /// 72 B (the size guard above still holds).
582    pub tailcalls: u16,
583}
584
585/// Compile-time guard that the T2-C2 `CallInfoFrame` flatten kept the per-frame
586/// footprint unchanged: the payload stays 32 B and `CallInfo` stays 72 B. The
587/// approved design (Option A) is conditioned on not growing `CallInfo`; if a
588/// future field change breaks this, the build fails here rather than silently
589/// regressing per-frame RSS. The byte counts are 64-bit-specific (the payload
590/// holds a fn pointer and two `isize`s), so the guard is gated off 32-bit
591/// targets — on wasm32 the struct is naturally smaller and there is no C
592/// layout-parity claim to enforce.
593#[cfg(target_pointer_width = "64")]
594const _: () = {
595    assert!(core::mem::size_of::<CallInfoFrame>() == 32);
596    assert!(core::mem::size_of::<CallInfo>() == 72);
597};
598
599/// Payload of `CallInfo.u`.
600///
601/// C 5.4 declares this as an anonymous union with a Lua-frame member (`l`)
602/// and a C-frame member (`c`); which member is live is implied by the
603/// `CIST_C` callstatus bit. T2-C2 flattened the previous 2-variant Rust enum
604/// into this branch-free struct: all fields are always present, so the hot
605/// accessors (`saved_pc`, `set_saved_pc`, `nextra_args`) are plain field
606/// reads with no discriminant test. The C-frame fields (`k`, `old_errfunc`,
607/// `ctx`) are only meaningful on C frames; the Lua-frame fields (`savedpc`,
608/// `nextraargs`) only on Lua frames. Accessors carry `debug_assert!`s on the
609/// frame kind that replace the old enum's wrong-variant panic tripwire at
610/// zero release cost. The `trap` flag that used to live in the Lua variant
611/// now lives in callstatus bit `CIST_TRAP`.
612///
613/// Layout: `u32 + i32 + Option<fn> + isize + isize` = 32 B (8-byte aligned),
614/// identical to the previous enum payload, so `CallInfo` stays 72 B.
615#[derive(Clone, Copy)]
616pub struct CallInfoFrame {
617    /// Lua-frame: index of the next bytecode instruction. C: `u.l.savedpc`.
618    pub savedpc: u32,
619    /// Lua-frame: count of extra varargs collected at entry. C: `u.l.nextraargs`.
620    pub nextraargs: i32,
621    /// C-frame: continuation function for a yieldable C call. C: `u.c.k`.
622    pub k: Option<LuaKFunction>,
623    /// C-frame: saved `errfunc` to restore on pcall recovery. C: `u.c.old_errfunc`.
624    pub old_errfunc: isize,
625    /// C-frame: continuation context. C: `u.c.ctx`.
626    pub ctx: isize,
627}
628
629/// Continuation function for yieldable C calls.  C: `lua_KFunction`.
630pub type LuaKFunction = fn(&mut LuaState, status: i32, ctx: isize) -> Result<usize, LuaError>;
631
632/// Payload of `CallInfo.u2`.
633#[derive(Default, Clone, Copy)]
634pub struct CallInfoExtra {
635    pub value: i32,
636    pub ftransfer: u16,
637    pub ntransfer: u16,
638}
639
640impl CallInfoFrame {
641    /// Default C-call frame: no continuation, zero context. The Lua-frame
642    /// fields are benignly zeroed so any latent read on a misclassified frame
643    /// reads the same value the old C variant produced.
644    pub fn c_default() -> Self {
645        CallInfoFrame {
646            savedpc: 0,
647            nextraargs: 0,
648            k: None,
649            old_errfunc: 0,
650            ctx: 0,
651        }
652    }
653
654    /// Default Lua-call frame: pc=0, no extra args. The C-frame fields are
655    /// benignly zeroed to exactly the values `c_default` produced, so a Lua
656    /// frame that is later reclassified or read as a C frame sees identical
657    /// defaults to the pre-flatten enum (which carried no C fields). The
658    /// `trap` flag now lives in callstatus bit `CIST_TRAP`, cleared by the
659    /// `callstatus` write in `prep_call_info`, not here.
660    pub fn lua_default() -> Self {
661        CallInfoFrame {
662            savedpc: 0,
663            nextraargs: 0,
664            k: None,
665            old_errfunc: 0,
666            ctx: 0,
667        }
668    }
669}
670
671impl Default for CallInfo {
672    fn default() -> Self {
673        CallInfo {
674            func: StackIdx(0),
675            top: StackIdx(0),
676            previous: None,
677            next: None,
678            u: CallInfoFrame::c_default(),
679            u2: CallInfoExtra::default(),
680            nresults: 0,
681            callstatus: 0,
682            call_metamethods: 0,
683            tailcalls: 0,
684        }
685    }
686}
687
688impl CallInfo {
689    pub fn is_lua(&self) -> bool {
690        (self.callstatus & CIST_C) == 0
691    }
692    pub fn is_lua_code(&self) -> bool {
693        self.is_lua()
694    }
695    /// Whether the active function is a vararg function.
696    ///
697    /// Currently returns `false` unconditionally — vararg introspection via
698    /// `debug.getinfo` reports no vararg info instead of panicking.
699    pub fn is_vararg_func(&self) -> bool {
700        false
701    }
702    /// Index of the next bytecode instruction on this Lua frame.
703    ///
704    /// `debug_assert!` guards that the frame is a Lua frame, restoring the
705    /// wrong-variant tripwire the pre-flatten enum gave for free.
706    pub fn saved_pc(&self) -> u32 {
707        debug_assert!(self.is_lua(), "saved_pc on a C frame");
708        self.u.savedpc
709    }
710    /// Write the next-instruction index on this Lua frame.
711    pub fn set_saved_pc(&mut self, pc: u32) {
712        debug_assert!(self.is_lua(), "set_saved_pc on a C frame");
713        self.u.savedpc = pc;
714    }
715    /// Count of extra varargs collected at entry on this Lua frame.
716    pub fn nextra_args(&self) -> i32 {
717        debug_assert!(self.is_lua(), "nextra_args on a C frame");
718        self.u.nextraargs
719    }
720    /// Write the extra-vararg count on this Lua frame.
721    pub fn set_nextra_args(&mut self, n: i32) {
722        debug_assert!(self.is_lua(), "set_nextra_args on a C frame");
723        self.u.nextraargs = n;
724    }
725    pub fn transfer_ftransfer(&self) -> u16 {
726        self.u2.ftransfer
727    }
728    pub fn transfer_ntransfer(&self) -> u16 {
729        self.u2.ntransfer
730    }
731    /// Set or clear the per-frame hook trap, stored in callstatus bit
732    /// `CIST_TRAP` (T2-C2 moved it out of the `CallInfoFrame` payload). Only
733    /// Lua frames are ever trapped: `set_traps` guards on `is_lua()` before
734    /// calling here, and `trace_call`/`trace_exec` operate on the current Lua
735    /// frame. The `debug_assert!` preserves that invariant. Reusing a slot for
736    /// a new call clears the bit via the `callstatus = mask` write in
737    /// `prep_call_info`, exactly as the old full-variant store reset `trap`.
738    pub fn set_trap(&mut self, t: bool) {
739        debug_assert!(self.is_lua(), "set_trap on a C frame");
740        if t {
741            self.callstatus |= CIST_TRAP;
742        } else {
743            self.callstatus &= !CIST_TRAP;
744        }
745    }
746    /// Read the per-frame hook trap from callstatus bit `CIST_TRAP`. One mask,
747    /// no enum-discriminant branch — this is the hot read in the OP_CALL /
748    /// OP_RETURN `updatetrap` paths.
749    #[inline(always)]
750    pub fn trap(&self) -> bool {
751        (self.callstatus & CIST_TRAP) != 0
752    }
753    /// Read the 3-bit recover-status field packed into bits 10-12 of callstatus.
754    ///
755    pub fn recover_status(&self) -> i32 {
756        ((self.callstatus >> CIST_RECST) & 7) as i32
757    }
758    /// Write the 3-bit recover-status field. `status` must fit in three bits.
759    ///
760    pub fn set_recover_status<T: Into<i32>>(&mut self, status: T) {
761        let st = (status.into() & 7) as u16;
762        self.callstatus = (self.callstatus & !(7u16 << CIST_RECST)) | (st << CIST_RECST);
763    }
764    pub fn get_oah(&self) -> bool {
765        (self.callstatus & CIST_OAH) != 0
766    }
767    /// Store the current `allowhook` value into callstatus bit 0 (CIST_OAH).
768    ///
769    pub fn set_oah(&mut self, allow: bool) {
770        self.callstatus = (self.callstatus & !CIST_OAH) | (if allow { CIST_OAH } else { 0 });
771    }
772    /// Saved `errfunc` to restore on pcall recovery (C-call frame).
773    ///
774    /// `debug_assert!` guards that the frame is a C frame, restoring the
775    /// wrong-variant tripwire the pre-flatten enum gave for free.
776    pub fn u_c_old_errfunc(&self) -> isize {
777        debug_assert!(!self.is_lua(), "u_c_old_errfunc on a Lua frame");
778        self.u.old_errfunc
779    }
780    /// Continuation context on a C-call frame.
781    pub fn u_c_ctx(&self) -> isize {
782        debug_assert!(!self.is_lua(), "u_c_ctx on a Lua frame");
783        self.u.ctx
784    }
785    /// Continuation function on a C-call frame.
786    pub fn u_c_k(&self) -> Option<LuaKFunction> {
787        debug_assert!(!self.is_lua(), "u_c_k on a Lua frame");
788        self.u.k
789    }
790    /// Set continuation function on a C-call frame.
791    ///
792    /// `debug_assert!` guards that the frame is a C frame (callers reach here
793    /// from `lua_callk`/`lua_pcallk`, where `L->ci` is the calling C builtin's
794    /// frame).
795    pub fn set_u_c_k(&mut self, k: Option<LuaKFunction>) {
796        debug_assert!(!self.is_lua(), "set_u_c_k on a Lua frame");
797        self.u.k = k;
798    }
799    /// Set continuation context on a C-call frame.
800    pub fn set_u_c_ctx(&mut self, ctx: isize) {
801        debug_assert!(!self.is_lua(), "set_u_c_ctx on a Lua frame");
802        self.u.ctx = ctx;
803    }
804    /// Set saved old_errfunc on a C-call frame.
805    pub fn set_u_c_old_errfunc(&mut self, old_errfunc: isize) {
806        debug_assert!(!self.is_lua(), "set_u_c_old_errfunc on a Lua frame");
807        self.u.old_errfunc = old_errfunc;
808    }
809    /// Set the `u2.funcidx` field, used by yieldable pcall for error recovery.
810    ///
811    pub fn set_u2_funcidx(&mut self, idx: i32) {
812        self.u2.value = idx;
813    }
814}
815
816// ─── Value/proto/instruction helpers ───────────────────────────────────────────
817
818/// Extension methods on `LuaValue`, kept in lua-vm alongside `LuaState`
819/// rather than in `lua_types::value`.
820pub trait LuaValueExt {
821    fn base_type(&self) -> lua_types::LuaType;
822    fn to_number_no_strconv(&self) -> Option<f64>;
823    fn to_number_with_strconv(&self) -> Option<f64>;
824    fn to_integer_no_strconv(&self) -> Option<i64>;
825    fn to_integer_with_strconv(&self) -> Option<i64>;
826    fn full_type_tag(&self) -> u8;
827}
828
829impl LuaValueExt for LuaValue {
830    fn base_type(&self) -> lua_types::LuaType {
831        self.type_tag()
832    }
833    fn to_number_no_strconv(&self) -> Option<f64> {
834        match self {
835            LuaValue::Float(f) => Some(*f),
836            LuaValue::Int(i) => Some(*i as f64),
837            _ => None,
838        }
839    }
840    fn to_number_with_strconv(&self) -> Option<f64> {
841        if let Some(n) = self.to_number_no_strconv() {
842            return Some(n);
843        }
844        if let LuaValue::Str(s) = self {
845            let mut tmp = LuaValue::Nil;
846            let sz = crate::object::str2num(s.as_bytes(), &mut tmp);
847            if sz == 0 {
848                return None;
849            }
850            return match tmp {
851                LuaValue::Int(i) => Some(i as f64),
852                LuaValue::Float(f) => Some(f),
853                _ => None,
854            };
855        }
856        None
857    }
858    fn to_integer_no_strconv(&self) -> Option<i64> {
859        match self {
860            LuaValue::Int(i) => Some(*i),
861            LuaValue::Float(f) if f.fract() == 0.0 && f.is_finite() => {
862                //   d >= LUA_MININTEGER && d < -(lua_Number)LUA_MININTEGER.
863                // Without this, Rust's `as i64` saturates and silently
864                // produces i64::MAX / i64::MIN for out-of-range floats.
865                let min_f = i64::MIN as f64;
866                let max_plus1_f = -(i64::MIN as f64);
867                if *f >= min_f && *f < max_plus1_f {
868                    Some(*f as i64)
869                } else {
870                    None
871                }
872            }
873            _ => None,
874        }
875    }
876    fn to_integer_with_strconv(&self) -> Option<i64> {
877        if let Some(i) = self.to_integer_no_strconv() {
878            return Some(i);
879        }
880        if let LuaValue::Str(s) = self {
881            let mut tmp = LuaValue::Nil;
882            let sz = crate::object::str2num(s.as_bytes(), &mut tmp);
883            if sz == 0 {
884                return None;
885            }
886            return tmp.to_integer_no_strconv();
887        }
888        None
889    }
890    fn full_type_tag(&self) -> u8 {
891        match self {
892            LuaValue::Nil => 0x00,
893            LuaValue::Bool(false) => 0x01,
894            LuaValue::Bool(true) => 0x11,
895            LuaValue::Int(_) => 0x03,
896            LuaValue::Float(_) => 0x13,
897            LuaValue::Str(s) if s.is_short() => 0x04,
898            LuaValue::Str(_) => 0x14,
899            LuaValue::LightUserData(_) => 0x02,
900            LuaValue::Table(_) => 0x05,
901            LuaValue::Function(LuaClosure::Lua(_)) => 0x06,
902            LuaValue::Function(LuaClosure::LightC(_)) => 0x16,
903            LuaValue::Function(LuaClosure::C(_)) => 0x26,
904            LuaValue::UserData(_) => 0x07,
905            LuaValue::Thread(_) => 0x08,
906        }
907    }
908}
909
910/// Extension methods on `lua_types::LuaType`.
911pub trait LuaTypeExt {
912    fn type_name(&self) -> &'static [u8];
913}
914
915impl LuaTypeExt for lua_types::LuaType {
916    fn type_name(&self) -> &'static [u8] {
917        use lua_types::LuaType::*;
918        match self {
919            None => b"no value",
920            Nil => b"nil",
921            Boolean => b"boolean",
922            LightUserData => b"userdata",
923            Number => b"number",
924            String => b"string",
925            Table => b"table",
926            Function => b"function",
927            UserData => b"userdata",
928            Thread => b"thread",
929        }
930    }
931}
932
933/// StackIdx checked-arithmetic helpers. Returns the raw `u32` because
934/// callers use the result in arithmetic comparisons against other `u32`
935/// quantities (stack-distance offsets).
936pub trait StackIdxExt {
937    fn saturating_sub(self, n: impl Into<StackIdxConv>) -> u32;
938    fn wrapping_sub(self, n: impl Into<StackIdxConv>) -> u32;
939    fn raw(self) -> u32;
940}
941impl StackIdxExt for StackIdx {
942    #[inline(always)]
943    fn saturating_sub(self, n: impl Into<StackIdxConv>) -> u32 {
944        self.0.saturating_sub(n.into().0 .0)
945    }
946    #[inline(always)]
947    fn wrapping_sub(self, n: impl Into<StackIdxConv>) -> u32 {
948        self.0.wrapping_sub(n.into().0 .0)
949    }
950    #[inline(always)]
951    fn raw(self) -> u32 {
952        self.0
953    }
954}
955
956/// `GcRef<LuaTable>` / `GcRef<LuaUserData>` field-access helpers, forwarding
957/// to the canonical `LuaTable`/`LuaUserData` methods through the deref, for
958/// use by api.rs and tagmethods.rs.
959///
960/// Nil/NaN key validation lives inside [`LuaTable::try_raw_set`] (alongside
961/// the integer-fast-path match), so this wrapper does not double-check.
962pub trait LuaTableRefExt {
963    fn metatable(&self) -> Option<GcRef<LuaTable>>;
964    fn has_metatable(&self) -> bool;
965    fn as_ptr(&self) -> *const ();
966    fn get(&self, _k: &LuaValue) -> LuaValue;
967    fn get_int(&self, _k: i64) -> LuaValue;
968    fn get_short_str(&self, _k: &GcRef<LuaString>) -> LuaValue;
969    fn raw_set(&self, _state: &mut LuaState, _k: LuaValue, _v: LuaValue) -> Result<(), LuaError>;
970    fn raw_set_int(&self, _state: &mut LuaState, _k: i64, _v: LuaValue) -> Result<(), LuaError>;
971    fn raw_set_short_str(
972        &self,
973        _state: &mut LuaState,
974        _k: GcRef<LuaString>,
975        _v: LuaValue,
976    ) -> Result<(), LuaError>;
977    fn invalidate_tm_cache(&self);
978    fn resize(&self, _state: &mut LuaState, _na: usize, _nh: usize) -> Result<(), LuaError>;
979    fn next(&self, _k: LuaValue) -> Result<Option<(LuaValue, LuaValue)>, LuaError>;
980}
981impl LuaTableRefExt for GcRef<LuaTable> {
982    #[inline]
983    fn metatable(&self) -> Option<GcRef<LuaTable>> {
984        (**self).metatable()
985    }
986    #[inline]
987    fn has_metatable(&self) -> bool {
988        (**self).has_metatable()
989    }
990    #[inline]
991    fn as_ptr(&self) -> *const () {
992        GcRef::identity(self) as *const ()
993    }
994    #[inline]
995    fn get(&self, k: &LuaValue) -> LuaValue {
996        (**self).get(k)
997    }
998    #[inline]
999    fn get_int(&self, k: i64) -> LuaValue {
1000        (**self).get_int(k)
1001    }
1002    #[inline]
1003    fn get_short_str(&self, k: &GcRef<LuaString>) -> LuaValue {
1004        (**self).get_short_str(k)
1005    }
1006    /// Forwards to [`LuaTable::try_raw_set`], which performs the nil/NaN
1007    /// key validation internally as part of its integer-fast-path match.
1008    ///
1009    /// A collectable KEY stored into the table needs its own backward
1010    /// barrier, mirroring C-Lua's `luaC_barrierback(L, obj2gco(t), key)`
1011    /// inside `luaH_newkey` (ltable.c:717). Without it a young key inserted
1012    /// into an old table is invisible to the generational collector and is
1013    /// freed while still referenced — the 2026-06-09 table livelock.
1014    #[inline(always)]
1015    fn raw_set(&self, state: &mut LuaState, k: LuaValue, v: LuaValue) -> Result<(), LuaError> {
1016        match k {
1017            LuaValue::Int(i) => return self.raw_set_int(state, i, v),
1018            LuaValue::Str(s) if s.is_short() => return self.raw_set_short_str(state, s, v),
1019            k => {
1020                if k.is_collectable() {
1021                    state.gc_table_barrier_back(self, &k);
1022                }
1023                let before = (**self).buffer_bytes();
1024                let result = (**self).try_raw_set(k, v);
1025                if result.is_ok() {
1026                    account_table_buffer_delta(self, before);
1027                }
1028                result
1029            }
1030        }
1031    }
1032    #[inline(always)]
1033    fn raw_set_int(&self, _state: &mut LuaState, k: i64, v: LuaValue) -> Result<(), LuaError> {
1034        match (**self).try_update_int(k, v) {
1035            Ok(()) => Ok(()),
1036            Err(v) => {
1037                let before = (**self).buffer_bytes();
1038                let result = (**self).try_raw_set_int(k, v);
1039                if result.is_ok() {
1040                    account_table_buffer_delta(self, before);
1041                }
1042                result
1043            }
1044        }
1045    }
1046    /// The miss arm inserts a NEW short-string key, so the key itself is
1047    /// barriered (C-Lua does this inside `luaH_newkey`, ltable.c:717); the
1048    /// hit arm only overwrites a value whose key is already traced.
1049    #[inline(always)]
1050    fn raw_set_short_str(
1051        &self,
1052        state: &mut LuaState,
1053        k: GcRef<LuaString>,
1054        v: LuaValue,
1055    ) -> Result<(), LuaError> {
1056        match (**self).try_update_short_str(&k, v) {
1057            Ok(()) => Ok(()),
1058            Err(v) => {
1059                state.gc_table_barrier_back(self, &LuaValue::Str(k));
1060                let before = (**self).buffer_bytes();
1061                let result = (**self).try_raw_set(LuaValue::Str(k), v);
1062                if result.is_ok() {
1063                    account_table_buffer_delta(self, before);
1064                }
1065                result
1066            }
1067        }
1068    }
1069    fn invalidate_tm_cache(&self) {}
1070    fn resize(&self, _state: &mut LuaState, na: usize, nh: usize) -> Result<(), LuaError> {
1071        let before = (**self).buffer_bytes();
1072        let na32 = na.min(u32::MAX as usize) as u32;
1073        let nh32 = nh.min(u32::MAX as usize) as u32;
1074        let result = (**self).resize(na32, nh32);
1075        if result.is_ok() {
1076            account_table_buffer_delta(self, before);
1077        }
1078        result
1079    }
1080    fn next(&self, k: LuaValue) -> Result<Option<(LuaValue, LuaValue)>, LuaError> {
1081        (**self).try_next_pair(&k)
1082    }
1083}
1084
1085#[inline]
1086fn account_table_buffer_delta(t: &GcRef<LuaTable>, before: usize) {
1087    let after = (**t).buffer_bytes();
1088    if after > before {
1089        t.account_buffer((after - before) as isize);
1090    } else if before > after {
1091        t.account_buffer(-((before - after) as isize));
1092    }
1093}
1094
1095pub trait LuaUserDataRefExt {
1096    fn metatable(&self) -> Option<GcRef<LuaTable>>;
1097    fn set_metatable(&self, mt: Option<GcRef<LuaTable>>);
1098    fn as_ptr(&self) -> *const ();
1099    fn len(&self) -> usize;
1100}
1101impl LuaUserDataRefExt for GcRef<LuaUserData> {
1102    fn metatable(&self) -> Option<GcRef<LuaTable>> {
1103        (**self).metatable()
1104    }
1105    fn set_metatable(&self, mt: Option<GcRef<LuaTable>>) {
1106        (**self).set_metatable(mt);
1107    }
1108    fn as_ptr(&self) -> *const () {
1109        GcRef::identity(self) as *const ()
1110    }
1111    fn len(&self) -> usize {
1112        self.0.data.len()
1113    }
1114}
1115
1116pub trait LuaStringRefExt {
1117    fn is_white(&self) -> bool;
1118    fn hash(&self) -> u32;
1119    fn as_gc_ref(&self) -> GcRef<LuaString>;
1120}
1121impl LuaStringRefExt for GcRef<LuaString> {
1122    fn is_white(&self) -> bool {
1123        false
1124    }
1125    fn hash(&self) -> u32 {
1126        self.0.hash()
1127    }
1128    fn as_gc_ref(&self) -> GcRef<LuaString> {
1129        self.clone()
1130    }
1131}
1132
1133pub trait LuaLClosureRefExt {
1134    fn proto(&self) -> &GcRef<LuaProto>;
1135    fn nupvalues(&self) -> usize;
1136}
1137impl LuaLClosureRefExt for GcRef<lua_types::closure::LuaLClosure> {
1138    fn proto(&self) -> &GcRef<LuaProto> {
1139        &self.0.proto
1140    }
1141    fn nupvalues(&self) -> usize {
1142        self.0.upvals.len()
1143    }
1144}
1145
1146/// `LuaClosure` accessor — `nupvalues()` reports the upvalue count uniformly.
1147pub trait LuaClosureExt {
1148    fn nupvalues(&self) -> usize;
1149}
1150impl LuaClosureExt for LuaClosure {
1151    fn nupvalues(&self) -> usize {
1152        match self {
1153            LuaClosure::Lua(l) => l.0.upvals.len(),
1154            LuaClosure::C(c) => c.0.upvalues.borrow().len(),
1155            LuaClosure::LightC(_) => 0,
1156        }
1157    }
1158}
1159
1160/// `LuaProto` source bytes accessor.
1161pub trait LuaProtoExt {
1162    fn source_bytes(&self) -> &[u8];
1163    fn source_string(&self) -> Option<&GcRef<LuaString>>;
1164}
1165impl LuaProtoExt for LuaProto {
1166    fn source_bytes(&self) -> &[u8] {
1167        match &self.source {
1168            Some(s) => s.0.as_bytes(),
1169            None => &[],
1170        }
1171    }
1172    fn source_string(&self) -> Option<&GcRef<LuaString>> {
1173        self.source.as_ref()
1174    }
1175}
1176
1177// ─── Collectable trait (GC interface) ────────────────────────────────────────
1178
1179/// Marker trait for GC-managed objects.
1180pub trait Collectable: std::fmt::Debug {}
1181
1182impl std::fmt::Debug for LuaState {
1183    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1184        write!(f, "LuaState")
1185    }
1186}
1187impl Collectable for LuaState {}
1188
1189// ─── GlobalState ─────────────────────────────────────────────────────────────
1190
1191/// Function-pointer signature for the text-source parser, installed on
1192/// [`GlobalState::parser_hook`] by the embedder.
1193///
1194/// The implementation lives in `lua-parse`; `lua-vm` cannot depend on it
1195/// directly (that would form a cycle), so the parser is reached via this
1196/// function pointer registered at startup.
1197///
1198/// The parser receives the live [`ZIO`](crate::zio::ZIO) (already positioned
1199/// past `firstchar`) rather than a fully-materialised buffer, so it can pull
1200/// reader chunks on demand and stop at the first syntax error — matching C's
1201/// `lua_load`, where the lexer drives the `lua_Reader` byte by byte.
1202pub type ParserHook = fn(
1203    state: &mut LuaState,
1204    z: &mut crate::zio::ZIO,
1205    name: &[u8],
1206    firstchar: i32,
1207) -> Result<GcRef<lua_types::closure::LuaLClosure>, LuaError>;
1208
1209/// Function-pointer signature for reading a file's full contents into memory,
1210/// installed on [`GlobalState::file_loader_hook`] by the embedder.
1211///
1212/// `std::fs` is banned outside `lua-cli`, so `lua-stdlib`'s `loadfile` and
1213/// `searcher_lua` reach the filesystem via this hook. `None` keeps the file
1214/// system unreachable, which is appropriate for embeddings where modules are
1215/// served exclusively from `package.preload`.
1216pub type FileLoaderHook = fn(filename: &[u8]) -> Result<Vec<u8>, LuaError>;
1217
1218/// Function-pointer signature for opening a file handle, installed on
1219/// [`GlobalState::file_open_hook`] by the embedder.
1220///
1221/// `std::fs` is banned outside `lua-cli`, so `lua-stdlib`'s io library reaches
1222/// the filesystem via this hook. `None` causes `io.open` and `io.output(name)`
1223/// to return a "file system not available" error, which is appropriate for
1224/// sandboxed embeddings.
1225///
1226/// `mode` is a Lua fopen-style mode string (e.g. `b"r"`, `b"w"`, `b"a"`,
1227/// `b"r+"`, etc.). The hook must honour at least `r`, `w`, and `a`.
1228///
1229/// The error type is `std::io::Error`, not `LuaError`: `io::Error` is the only
1230/// type in this boundary that can carry `raw_os_error()` end to end.
1231/// `lua-stdlib`'s `io.open`/`io.input`/`io.output` read the errno straight off
1232/// this error and render the message with `strerror`-shaped text, matching
1233/// C-Lua's `luaL_fileresult`/`luaL_error(..., strerror(errno))`. Converting to
1234/// `LuaError` here (as earlier revisions did) discards `raw_os_error()`, which
1235/// was issue #301 (errno 0 + a verbose Rust `Display` message reaching Lua).
1236pub type FileOpenHook =
1237    fn(filename: &[u8], mode: &[u8]) -> std::io::Result<Box<dyn lua_types::LuaFileHandle>>;
1238
1239/// Function-pointer signature for writing bytes to a host-provided output
1240/// stream, installed on [`GlobalState::stdout_hook`] or
1241/// [`GlobalState::stderr_hook`] by the embedder.
1242///
1243/// Bare `wasm32-unknown-unknown` has no ambient stdout/stderr. Keeping output
1244/// behind explicit hooks lets sandboxed and WASM hosts decide whether output is
1245/// unavailable, buffered, or bridged to something like a browser console.
1246pub type OutputHook = fn(bytes: &[u8]) -> std::io::Result<()>;
1247
1248/// Function-pointer signature for reading bytes from a host-provided input
1249/// stream, installed on [`GlobalState::stdin_hook`] by the embedder.
1250pub type InputHook = fn(buf: &mut [u8]) -> std::io::Result<usize>;
1251
1252/// Function-pointer signature for reading a host environment variable.
1253///
1254/// Returning `None` maps naturally to Lua's `os.getenv` result for a missing
1255/// variable and is also the sandbox/bare-WASM default when no environment is
1256/// exposed.
1257pub type EnvHook = fn(name: &[u8]) -> Option<Vec<u8>>;
1258
1259/// Function-pointer signature for retrieving the current Unix time in seconds.
1260pub type UnixTimeHook = fn() -> i64;
1261
1262/// Function-pointer signature for retrieving program CPU time in seconds.
1263///
1264/// Backs `os.clock`. C's `clock()` reads `CLOCK_PROCESS_CPUTIME_ID`, which has no
1265/// `std` equivalent and is unavailable on bare WASM; the stdlib falls back to a
1266/// monotonic wall-clock baseline (matching wasi-libc/Emscripten's emulation) when
1267/// this hook is unset. A host wanting true CPU time can install one (e.g. via the
1268/// `cpu-time` crate) without changing the sandboxed crates.
1269pub type CpuClockHook = fn() -> f64;
1270
1271/// Function-pointer signature for the host's local timezone offset.
1272///
1273/// Given a Unix timestamp (seconds, UTC), returns the offset in seconds that the
1274/// host's local timezone applies at that instant, such that
1275/// `local_broken_down = gmtime(timestamp + offset)`. Positive east of UTC (e.g.
1276/// `+3600` for CET), negative west (e.g. `-14400` for US EDT). This backs the
1277/// local-time semantics of `os.date` (non-`!` formats) and `os.time`, which C
1278/// implements with `localtime_r`/`mktime`. Reading the host timezone database
1279/// requires `libc` FFI (`unsafe`), banned in `lua-stdlib`, so the host installs
1280/// this hook. When unset the stdlib uses UTC (offset 0), keeping the
1281/// `os.date`/`os.time` round-trip exact on hosts without a timezone.
1282pub type LocalOffsetHook = fn(timestamp: i64) -> i64;
1283
1284/// Function-pointer signature for host entropy used by default PRNG seeds and
1285/// table-sort pivot randomisation. Hosts without entropy may leave it unset; the
1286/// stdlib then uses deterministic fallback values instead of touching OS stubs.
1287pub type EntropyHook = fn() -> u64;
1288
1289/// Function-pointer signature for generating a host temporary filename.
1290///
1291/// Used by `os.tmpname` and `io.tmpfile`. The hook should return a path-like byte
1292/// string that the host's `file_open_hook` can understand.
1293pub type TempNameHook = fn() -> Result<Vec<u8>, LuaError>;
1294
1295/// Function-pointer signature for spawning a child process with a connected
1296/// pipe, installed on [`GlobalState::popen_hook`] by the embedder.
1297///
1298/// `std::process::Command` is banned outside `lua-cli`, so `lua-stdlib`'s
1299/// `io.popen` reaches the OS through this hook. `None` causes `io.popen` to
1300/// raise a clean Lua error ("popen not enabled in this build"), which is
1301/// appropriate for sandboxed embeddings.
1302///
1303/// `mode` is the Lua popen mode string — `b"r"` for reading the child's
1304/// stdout, `b"w"` for writing to the child's stdin.
1305pub type PopenHook =
1306    fn(cmd: &[u8], mode: &[u8]) -> Result<Box<dyn lua_types::LuaFileHandle>, LuaError>;
1307
1308/// Function-pointer signature for removing a file, installed on
1309/// [`GlobalState::file_remove_hook`] by the embedder.
1310///
1311/// `std::fs` is banned outside `lua-cli`, so `lua-stdlib`'s `os.remove`
1312/// reaches the filesystem via this hook. Returns `Ok(())` on success.
1313///
1314/// The error type is `std::io::Error` so `os.remove`'s failure triple
1315/// (`nil, msg, errno`) can report the real `raw_os_error()` — see
1316/// [`FileOpenHook`]'s doc for why `LuaError` cannot carry it (#301).
1317pub type FileRemoveHook = fn(filename: &[u8]) -> std::io::Result<()>;
1318
1319/// Function-pointer signature for renaming a file, installed on
1320/// [`GlobalState::file_rename_hook`] by the embedder.
1321///
1322/// `std::fs` is banned outside `lua-cli`, so `lua-stdlib`'s `os.rename`
1323/// reaches the filesystem via this hook. Returns `Ok(())` on success.
1324///
1325/// The error type is `std::io::Error`, for the same reason as
1326/// [`FileRemoveHook`] (#301).
1327pub type FileRenameHook = fn(from: &[u8], to: &[u8]) -> std::io::Result<()>;
1328
1329/// Reason a shell command terminated, returned by [`OsExecuteHook`].
1330///
1331/// Mirrors the two string literals that C-Lua's `l_inspectstat` / `luaL_execresult`
1332/// can produce: `"exit"` for normal process exit, `"signal"` for signal termination
1333/// (POSIX only).
1334#[derive(Clone, Copy, Debug)]
1335pub enum OsExecuteReason {
1336    /// Process exited with an exit code (`WIFEXITED` / `ExitStatus::code()` is `Some`).
1337    Exit,
1338    /// Process was terminated by a signal (`WIFSIGNALED` / `ExitStatus::signal()` is `Some`).
1339    Signal,
1340}
1341
1342/// Result returned by [`OsExecuteHook`], carrying the three values that
1343/// C-Lua's `luaL_execresult` pushes: `(boolean|nil, "exit"|"signal", int)`.
1344#[derive(Debug)]
1345pub struct OsExecuteResult {
1346    /// `true` when the command exited successfully (exit code 0).
1347    pub success: bool,
1348    /// How the process terminated.
1349    pub reason: OsExecuteReason,
1350    /// Exit code (for `Exit`) or signal number (for `Signal`).
1351    pub code: i32,
1352}
1353
1354/// Function-pointer signature for executing a shell command, installed on
1355/// [`GlobalState::os_execute_hook`] by the embedder.
1356///
1357/// `std::process` is banned outside `lua-cli`, so `lua-stdlib`'s `os.execute`
1358/// reaches the shell via this hook. Returns an [`OsExecuteResult`] on success,
1359/// or a [`LuaError`] when the spawn itself fails.
1360pub type OsExecuteHook = fn(cmd: &[u8]) -> Result<OsExecuteResult, LuaError>;
1361
1362/// Opaque handle to a dynamically loaded library, allocated by a
1363/// [`DynLibLoadHook`] backend and stored in `package._CLIBS`.
1364///
1365/// The handle is a backend-owned `u64`; the embedder is free to use it as an
1366/// index into a `Vec<libloading::Library>` or a `HashMap` key. `lua-stdlib`
1367/// stores the value verbatim and never inspects it.
1368#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1369pub struct DynLibId(pub u64);
1370
1371/// Resolved dynamic-library symbol.
1372///
1373/// Only `RustNative` is callable by this build of the VM. `LuaCAbi` resolves
1374/// to a real C function pointer compiled against stock Lua 5.4's `lua_State *`
1375/// ABI but cannot be safely invoked here — it is reported as an `"init"`
1376/// failure with a clear message. `Unsupported` carries an embedder-provided
1377/// reason byte-string.
1378pub enum DynamicSymbol {
1379    /// Function pointer that follows this build's Rust-native module ABI:
1380    /// `fn(&mut LuaState) -> Result<usize, LuaError>`.
1381    RustNative(LuaCFunction),
1382    /// Symbol exported against stock Lua 5.4's C ABI. The function pointer is
1383    /// resolved but never called from this build, since `lua_State *` is not
1384    /// our `LuaState`. Kept as a payload so a future C-ABI facade can pick it
1385    /// up; the embedder is responsible for ensuring the underlying library
1386    /// outlives this value.
1387    LuaCAbi(*const ()),
1388    /// Embedder-provided refusal reason, e.g. "symbol resolved but ABI version
1389    /// mismatch". Reported verbatim as an `"init"` failure.
1390    Unsupported { reason: Vec<u8> },
1391}
1392
1393/// Function-pointer signature for loading a dynamic library, installed on
1394/// [`GlobalState::dynlib_load_hook`] by the embedder.
1395///
1396/// `libloading`/`dlopen`/`LoadLibraryEx` are FFI calls and require `unsafe`,
1397/// which is banned in `lua-stdlib`. `lua-cli` installs a `libloading`-backed
1398/// implementation. `None` causes `package.loadlib` to return the C-Lua
1399/// `"absent"` failure shape, matching the fallback platform stub.
1400///
1401/// `see_global` mirrors C-Lua's `seeglb` (POSIX `RTLD_GLOBAL`): set when the
1402/// caller invokes `package.loadlib(path, "*")`.
1403pub type DynLibLoadHook =
1404    fn(state: &mut LuaState, path: &[u8], see_global: bool) -> Result<DynLibId, LuaError>;
1405
1406/// Function-pointer signature for resolving a symbol in a previously loaded
1407/// dynamic library, installed on [`GlobalState::dynlib_symbol_hook`].
1408///
1409/// The hook receives the [`DynLibId`] returned by [`DynLibLoadHook`] and the
1410/// requested symbol name. Returning `DynamicSymbol::RustNative` makes the
1411/// symbol callable; `LuaCAbi`/`Unsupported` propagate to `package.loadlib`
1412/// as an `"init"` failure with a clear message.
1413pub type DynLibSymbolHook =
1414    fn(state: &mut LuaState, handle: DynLibId, symbol: &[u8]) -> Result<DynamicSymbol, LuaError>;
1415
1416/// Function-pointer signature for unloading a dynamic library, installed on
1417/// [`GlobalState::dynlib_unload_hook`].
1418///
1419/// Called from the `_CLIBS` `__gc` metamethod when the Lua state closes.
1420/// `libloading`'s safety model requires every loaded library to outlive the
1421/// last symbol it exports; the CLI backend is therefore free to ignore this
1422/// hook and keep libraries alive until process exit.
1423pub type DynLibUnloadHook = fn(handle: DynLibId);
1424
1425/// One row of [`GlobalState::threads`]. Pairs the per-thread `LuaState`
1426/// with the canonical `GcRef<LuaThread>` so every `push_thread` for the
1427/// same id shares pointer-identity; the state is wrapped in
1428/// `Rc<RefCell<...>>` so `resume`/`yield` can mutate the child thread while
1429/// the parent holds a borrow.
1430pub struct ThreadRegistryEntry {
1431    /// The owned coroutine `LuaState`. Wrapped in `Rc<RefCell<...>>` so
1432    /// that `coroutine.resume` can borrow the child mutably while the
1433    /// parent is still in scope. Single-threaded — borrows never overlap
1434    /// in practice because only one resume path is live at a time.
1435    pub state: Rc<RefCell<LuaState>>,
1436    /// Canonical thread-value handle. Reused on every push so
1437    /// `GcRef::ptr_eq` is true across pushes.
1438    pub value: GcRef<lua_types::value::LuaThread>,
1439}
1440
1441/// Stable key for a value pinned in [`ExternalRootSet`].
1442///
1443/// The generation is part of the key so a handle that has already unrooted its
1444/// slot cannot accidentally observe a later handle's value after slot reuse.
1445#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1446pub struct ExternalRootKey {
1447    index: usize,
1448    generation: u64,
1449}
1450
1451#[derive(Debug)]
1452struct ExternalRootSlot {
1453    value: Option<LuaValue>,
1454    generation: u64,
1455}
1456
1457/// Values held alive by external Rust handles.
1458///
1459/// This is the embedding API's GC anchor. It intentionally lives directly on
1460/// `GlobalState` instead of inside the Lua registry table: handle drop/unroot
1461/// must be cheap, infallible, and independent of the Lua stack protocol.
1462#[derive(Debug, Default)]
1463pub struct ExternalRootSet {
1464    slots: Vec<ExternalRootSlot>,
1465    free: Vec<usize>,
1466    live: usize,
1467}
1468
1469impl ExternalRootSet {
1470    pub fn insert(&mut self, value: LuaValue) -> ExternalRootKey {
1471        if let Some(index) = self.free.pop() {
1472            let slot = &mut self.slots[index];
1473            debug_assert!(slot.value.is_none(), "free external-root slot is occupied");
1474            slot.generation = slot.generation.wrapping_add(1).max(1);
1475            slot.value = Some(value);
1476            self.live += 1;
1477            ExternalRootKey {
1478                index,
1479                generation: slot.generation,
1480            }
1481        } else {
1482            let index = self.slots.len();
1483            self.slots.push(ExternalRootSlot {
1484                value: Some(value),
1485                generation: 1,
1486            });
1487            self.live += 1;
1488            ExternalRootKey {
1489                index,
1490                generation: 1,
1491            }
1492        }
1493    }
1494
1495    pub fn get(&self, key: ExternalRootKey) -> Option<&LuaValue> {
1496        let slot = self.slots.get(key.index)?;
1497        if slot.generation == key.generation {
1498            slot.value.as_ref()
1499        } else {
1500            None
1501        }
1502    }
1503
1504    pub fn replace(&mut self, key: ExternalRootKey, value: LuaValue) -> Option<LuaValue> {
1505        let slot = self.slots.get_mut(key.index)?;
1506        if slot.generation != key.generation || slot.value.is_none() {
1507            return None;
1508        }
1509        slot.value.replace(value)
1510    }
1511
1512    pub fn remove(&mut self, key: ExternalRootKey) -> Option<LuaValue> {
1513        let slot = self.slots.get_mut(key.index)?;
1514        if slot.generation != key.generation {
1515            return None;
1516        }
1517        let old = slot.value.take()?;
1518        self.free.push(key.index);
1519        self.live -= 1;
1520        Some(old)
1521    }
1522
1523    pub fn iter_values(&self) -> impl Iterator<Item = &LuaValue> {
1524        self.slots.iter().filter_map(|slot| slot.value.as_ref())
1525    }
1526
1527    pub fn len(&self) -> usize {
1528        self.live
1529    }
1530
1531    pub fn is_empty(&self) -> bool {
1532        self.live == 0
1533    }
1534
1535    pub fn vacant_len(&self) -> usize {
1536        self.free.len()
1537    }
1538}
1539
1540/// Process-wide state shared by all Lua threads.
1541///
1542/// Not exposed directly at the API; accessed via `state.global()` / `state.global_mut()`.
1543pub struct GlobalState {
1544    /// Hook for the Lua text parser. Set by the embedder (`lua-cli`
1545    /// or stdlib host) to bridge the cyclic crate split between `lua-vm` and
1546    /// `lua-parse`: when `f_parser` decides the chunk is text, it invokes
1547    /// this hook instead of the parser stub. `None` leaves the stub in place
1548    /// so unit tests that never load text still work.
1549    pub parser_hook: Option<ParserHook>,
1550
1551    /// Transient slot carrying the CLI's `argv` into the `pmain` C closure.
1552    /// Mirrors `lua.c`'s `lua_pushinteger(argc)/lua_pushlightuserdata(argv)`
1553    /// arguments to `pmain`: a lua-rs C closure cannot capture Rust values, so
1554    /// `lua-cli`'s `run` parks `argv` here, pushes a zero-arg `pmain` closure,
1555    /// and `pcall_k`s it; `pmain` `take()`s it back out. Lives on `GlobalState`
1556    /// to keep `lua-cli` free of `unsafe` light-userdata round-tripping.
1557    pub cli_argv: Option<Vec<Vec<u8>>>,
1558
1559    /// Transient slot carrying the CLI's native-module `preload` callback into
1560    /// the `pmain` C closure, paired with [`GlobalState::cli_argv`]. The type
1561    /// matches `lua-cli::interp::run`'s `preload` parameter.
1562    pub cli_preload: Option<fn(&mut LuaState) -> Result<(), LuaError>>,
1563
1564    /// The Lua language version this state speaks. The single source of truth
1565    /// for version-gated behavior in the layers that read the state (parser,
1566    /// stdlib openers). The embedder sets this from the [`Lua`] instance's
1567    /// [`lua_types::LuaVersion`] at construction; it defaults to
1568    /// [`lua_types::LuaVersion::V54`] so any state built without an explicit
1569    /// version keeps the existing 5.4 behavior unchanged.
1570    pub lua_version: lua_types::LuaVersion,
1571
1572    /// Hook for reading a Lua source file from disk. Set by `lua-cli`
1573    /// (or any embedder that wants `require`/`loadfile` to reach the file
1574    /// system) since `std::fs` is banned in `lua-stdlib`. `None` makes
1575    /// `loadfile` and the Lua-file searcher report a file-not-found error.
1576    pub file_loader_hook: Option<FileLoaderHook>,
1577
1578    /// Hook for opening a file handle for read/write/append. Set by
1579    /// `lua-cli` since `std::fs` is banned in `lua-stdlib`. `None` causes
1580    /// `io.open` and `io.output(name)` to return an error; standard output and
1581    /// error are controlled separately through output hooks/native fallbacks.
1582    pub file_open_hook: Option<FileOpenHook>,
1583
1584    /// Hook for host stdout. When absent, native builds fall back to Rust stdout
1585    /// for compatibility; bare `wasm32-unknown-unknown` reports stdout
1586    /// unavailable instead of touching a stubbed stdio implementation.
1587    pub stdout_hook: Option<OutputHook>,
1588
1589    /// Hook for host stderr. See [`GlobalState::stdout_hook`].
1590    pub stderr_hook: Option<OutputHook>,
1591
1592    /// Hook for host stdin. When absent, native builds fall back to Rust stdin
1593    /// for compatibility; bare `wasm32-unknown-unknown` behaves like EOF.
1594    pub stdin_hook: Option<InputHook>,
1595
1596    /// Hook for host environment lookups. `None` makes `os.getenv` return nil.
1597    pub env_hook: Option<EnvHook>,
1598
1599    /// Hook for host wall-clock time. Required for `os.time()` and `os.date()`
1600    /// without an explicit timestamp under bare WASM.
1601    pub unix_time_hook: Option<UnixTimeHook>,
1602
1603    /// Hook for host program CPU time. Backs `os.clock`. When unset, native builds
1604    /// use a monotonic wall-clock baseline and bare WASM reports it unavailable.
1605    pub cpu_clock_hook: Option<CpuClockHook>,
1606
1607    /// Hook for the host's local timezone offset at a given instant. Backs the
1608    /// local-time semantics of `os.date` (non-`!` formats) and `os.time`. When
1609    /// unset, both use UTC, matching the prior behaviour and keeping the
1610    /// `os.date`/`os.time` round-trip exact under bare WASM.
1611    pub local_offset_hook: Option<LocalOffsetHook>,
1612
1613    /// Hook for host entropy. Used by default `math.randomseed` and table sort
1614    /// pivot randomisation; absent hooks fall back to deterministic seeds.
1615    pub entropy_hook: Option<EntropyHook>,
1616
1617    /// Hook for host temporary filenames. Used by `os.tmpname` and `io.tmpfile`.
1618    pub temp_name_hook: Option<TempNameHook>,
1619
1620    /// Hook for spawning a child process and connecting one stream
1621    /// (stdin or stdout) to a Lua file handle. Set by `lua-cli` since
1622    /// `std::process::Command` is banned in `lua-stdlib`. `None` causes
1623    /// `io.popen` to raise a Lua error rather than panic.
1624    pub popen_hook: Option<PopenHook>,
1625
1626    /// Per-VM slot for `lua-stdlib`'s `io` stream side table (the `LStream`
1627    /// map keyed by file-handle userdata identity). Type-erased because the
1628    /// concrete map type lives in `lua-stdlib`, which this crate cannot name;
1629    /// `io_lib` lazily installs it on first use and downcasts on access.
1630    /// Owned here — rather than in a process-wide `thread_local!` — so the
1631    /// table dies with the VM: issue #317 traced the leak canary's
1632    /// per-iteration retention to stream entries of dropped VMs accumulating
1633    /// forever in the thread-global map whenever a file userdata landed at a
1634    /// never-before-seen address.
1635    pub io_streams: Option<std::rc::Rc<dyn std::any::Any>>,
1636
1637    /// Hook for removing a file. Set by `lua-cli` since `std::fs` is
1638    /// banned in `lua-stdlib`. `None` causes `os.remove` to return an error.
1639    pub file_remove_hook: Option<FileRemoveHook>,
1640
1641    /// Hook for renaming a file. Set by `lua-cli` since `std::fs` is
1642    /// banned in `lua-stdlib`. `None` causes `os.rename` to return an error.
1643    pub file_rename_hook: Option<FileRenameHook>,
1644
1645    /// Hook for executing a shell command. Set by `lua-cli` since
1646    /// `std::process` is banned in `lua-stdlib`. `None` causes `os.execute`
1647    /// to report no shell available (matching C-Lua's `system(NULL) == 0`).
1648    pub os_execute_hook: Option<OsExecuteHook>,
1649
1650    /// Hook for loading a dynamic library (`dlopen` /
1651    /// `LoadLibraryEx`). Set by `lua-cli` since `libloading` is FFI and
1652    /// requires `unsafe`, which is banned in `lua-stdlib`. `None` causes
1653    /// `package.loadlib` to return the `"absent"` fallback shape.
1654    pub dynlib_load_hook: Option<DynLibLoadHook>,
1655
1656    /// Hook for resolving a symbol in a previously loaded
1657    /// dynamic library (`dlsym` / `GetProcAddress`). Set by `lua-cli`.
1658    /// `None` is treated as "absent" by `package.loadlib`.
1659    pub dynlib_symbol_hook: Option<DynLibSymbolHook>,
1660
1661    /// Hook for unloading a dynamic library (`dlclose` /
1662    /// `FreeLibrary`). Set by `lua-cli`. `None` keeps libraries loaded
1663    /// until process exit, which matches `libloading`'s safety model.
1664    pub dynlib_unload_hook: Option<DynLibUnloadHook>,
1665
1666    /// Per-runtime sandbox budget shared across all threads. Inactive by
1667    /// default (`interval == 0`); see [`SandboxLimits`].
1668    pub sandbox: SandboxLimits,
1669
1670    pub gc_debt: isize,
1671
1672    pub gc_estimate: usize,
1673
1674    pub lastatomic: usize,
1675
1676    pub l_registry: LuaValue,
1677
1678    /// External Rust handles root their referents here while they are live.
1679    /// Traced from `GlobalState::trace`.
1680    pub external_roots: ExternalRootSet,
1681
1682    /// The globals table, kept as a direct field rather than through the
1683    /// canonical registry path (`registry[LUA_RIDX_GLOBALS]`) because the
1684    /// lua-types `LuaTable` placeholder has no storage of its own;
1685    /// `get_global_table` reads it from here. Same reasoning for `loaded`
1686    /// (the module cache normally at `registry[_LOADED]`).
1687    pub globals: LuaValue,
1688    pub loaded: LuaValue,
1689
1690    /// A dedicated completeness flag rather than C's trick of checking
1691    /// `ttisnil(&g->nilvalue)`. See `is_complete()`.
1692    pub nilvalue: LuaValue,
1693
1694    pub seed: u32,
1695
1696    pub currentwhite: u8,
1697
1698    pub gcstate: u8,
1699
1700    pub gckind: u8,
1701
1702    pub gcstopem: bool,
1703
1704    pub genminormul: u8,
1705
1706    pub genmajormul: u8,
1707
1708    pub gcstp: u8,
1709
1710    pub gcemergency: bool,
1711
1712    pub gcpause: u8,
1713
1714    pub gcstepmul: u8,
1715
1716    pub gcstepsize: u8,
1717
1718    /// Lua 5.5 `collectgarbage("param", name [, value])` storage, indexed by
1719    /// [`Gc55Param`]: `[minormul, majorminor, minormajor, pause, stepmul,
1720    /// stepsize]`. The 5.5 GC parameters use a wider value range than the
1721    /// packed `u8` fields above, so they get their own storage. This is a
1722    /// faithful-shape backing store: it preserves the read-current /
1723    /// write-returns-old contract and the upstream default values, without
1724    /// claiming to retune the incremental collector. Initialized to the
1725    /// values observed on the reference `lua5.5.0` binary.
1726    pub gc55_params: [i64; 6],
1727
1728    /// The GC owns its allgc/finobj/tobefnz/grayagain intrusive lists inside
1729    /// `self.heap` (`lua_gc::Heap`), not on `GlobalState` directly.
1730    pub sweepgc_cursor: usize,
1731
1732    /// Cross-table weak-sweep registry.
1733    ///
1734    /// Heap collection snapshots this list before mark, then the post-mark
1735    /// weak-table pass clears entries whose weak target is held only by other
1736    /// weak slots. The registry holds weak table entries so it does not pin
1737    /// dead weak tables after sweep removes their heap allocation token.
1738    /// Replaced by proper `weak` / `ephemeron` / `allweak` cohorts once the
1739    /// Lua-style generational lists land.
1740    pub weak_tables_registry: lua_gc::WeakRegistry<WeakTableEntry>,
1741
1742    /// Typed handles for finalizable tables/userdata. The heap owns the
1743    /// corresponding intrusive finobj/tobefnz list placement.
1744    pub finalizers: lua_gc::FinalizerRegistry<FinalizerObject>,
1745
1746    /// Error raised by a `__gc` finalizer during an explicit `collectgarbage`
1747    /// on 5.2 / 5.3, parked here for the `collectgarbage` wrapper to re-raise.
1748    ///
1749    /// C-Lua re-throws the wrapped `error in __gc metamethod (%s)` directly out
1750    /// of `GCTM` via `luaD_throw`. The Rust `api::gc` entry point returns `i32`
1751    /// (its many callers cannot all thread a `Result`), so the explicit-collect
1752    /// path stashes the wrapped error here and the `collectgarbage` built-in
1753    /// drains it into the `Result<usize, LuaError>` it already returns. Only
1754    /// the explicit-collect path sets this; the automatic GC-step and close
1755    /// paths never do (matching `GCTM(L, 0)` and the dispatch-loop swallow).
1756    pub gc_finalizer_error: Option<LuaValue>,
1757
1758    pub twups: Vec<GcRef<LuaState>>,
1759
1760    pub panic: Option<LuaCFunction>,
1761
1762    /// Always `None`: populating this would create a self-referential `Rc`
1763    /// cycle from the main thread's `LuaState` back to its own
1764    /// `GlobalState`. See `new_state`.
1765    pub mainthread: Option<GcRef<LuaState>>,
1766
1767    /// Registry of all live coroutine threads, keyed by `ThreadId`.
1768    /// `coroutine.create` allocates a fresh `LuaState`, registers it here,
1769    /// and returns a value that resolves back to the same state on every
1770    /// `coroutine.status` / `coroutine.resume` call.
1771    ///
1772    /// Each entry pairs the per-thread `LuaState` with the canonical
1773    /// `GcRef<LuaThread>` value, so two `LuaValue::Thread` pushes of the
1774    /// same id share `GcRef::ptr_eq` identity. The main thread is NOT
1775    /// stored here — its `LuaState` is owned externally by the embedder.
1776    /// `main_thread_id` is reserved as `0` and a `LuaValue::Thread`
1777    /// carrying id `0` is recognized as the main thread by lookup helpers.
1778    pub threads: std::collections::HashMap<u64, ThreadRegistryEntry>,
1779
1780    /// Cached `LuaValue::Thread` payload for the main thread (id 0).
1781    /// Built once during `new_state` so every `push_thread` on the main
1782    /// thread shares the same `GcRef<LuaThread>` and thus compares
1783    /// pointer-equal under `LuaValue::PartialEq`.
1784    pub main_thread_value: GcRef<lua_types::value::LuaThread>,
1785
1786    /// Identity of the currently-running thread. `0` (main) until
1787    /// `coro_lib::resume` swaps it to the child coroutine's id; restored to
1788    /// the parent's id on yield or return.
1789    pub current_thread_id: u64,
1790
1791    /// Thread currently being reset/closed by `coroutine.close`, if any. This is
1792    /// used to recognize reentrant closes from that thread's `__close` methods.
1793    pub closing_thread_id: Option<u64>,
1794
1795    /// Identity of the main thread. Convention: `0`. Held as a field so
1796    /// the lookup helpers can read it without hard-coding the constant.
1797    pub main_thread_id: u64,
1798
1799    /// Monotonic counter handing out fresh ids in `new_thread`. Starts
1800    /// at `1` because `0` is reserved for the main thread.
1801    pub next_thread_id: u64,
1802
1803    /// Lua 5.1 per-thread global table (`lua_State.l_gt`) for coroutine
1804    /// threads, keyed by thread id.
1805    ///
1806    /// In 5.1 every thread has its own global table: `setfenv(0, t)` and
1807    /// `getfenv(0)` read/write the *running* thread's `l_gt`, and a freshly
1808    /// loaded top-level chunk takes the running thread's `l_gt` as its
1809    /// environment. A coroutine inherits its creator's `l_gt` at creation,
1810    /// after which the two are independent — a coroutine's `setfenv(0, t)`
1811    /// must not clobber the main thread's globals.
1812    ///
1813    /// The main thread (`main_thread_id`) is the single exception: its `l_gt`
1814    /// is the existing [`Self::globals`] field (single source of truth, never
1815    /// duplicated here). Only coroutine ids appear as keys, seeded in
1816    /// `new_thread`. Empty (and never read) on 5.2–5.5, where all threads
1817    /// share one global table and this field is inert. Traced as a root and
1818    /// pruned of dead-thread entries after each collection.
1819    pub thread_globals: std::collections::HashMap<u64, LuaValue>,
1820
1821    /// Lua 5.1 per-closure environment for closures that carry no `_ENV`
1822    /// upvalue, keyed by closure identity ([`GcRef::identity`]).
1823    ///
1824    /// The reused modern parser threads an `_ENV` upvalue only onto closures
1825    /// that reference a free (global) name; a closure that references none has
1826    /// no such upvalue. 5.1's `setfenv(f, t)` must still set such a closure's
1827    /// environment and `getfenv(f)` must read it back, so the environment is
1828    /// stored here, independent of the upvalue array. A closure that *does*
1829    /// have an `_ENV` upvalue never appears here — its environment is that
1830    /// upvalue's closed value. Empty (and never read) on 5.2–5.5. Traced as a
1831    /// root and pruned of dead-closure entries after each collection.
1832    pub closure_envs: std::collections::HashMap<usize, LuaValue>,
1833
1834    pub memerrmsg: GcRef<LuaString>,
1835
1836    pub tmname: Vec<GcRef<LuaString>>,
1837
1838    pub mt: [Option<GcRef<LuaTable>>; LUA_NUMTYPES],
1839
1840    pub strcache: [[GcRef<LuaString>; STRCACHE_M]; STRCACHE_N],
1841
1842    /// Stable intern map for the public [`LuaString`] type. The parser and
1843    /// stdlib need pointer-equality across `intern_str` calls so
1844    /// `GcRef::ptr_eq` can resolve variable identity. Without this map each
1845    /// call allocates a fresh `GcRef` and locals/upvalues fail to resolve.
1846    pub interned_lt: InternedStringMap,
1847
1848    pub warnf: Option<Box<dyn FnMut(&[u8], bool)>>,
1849
1850    /// State of the default warning handler (the `warnfoff`/`warnfon`/
1851    /// `warnfcont` chain from upstream `lauxlib.c`). `luaL_openlibs` installs
1852    /// `warnfoff`, so warnings start disabled until `warn("@on")`. Only
1853    /// consulted when no custom `warnf` was installed via the C API.
1854    pub warn_mode: WarnMode,
1855
1856    /// testC/ltests warning sink, enabled only by the CLI's `LUA_RS_TESTC`
1857    /// support. It mirrors `ltests.c`'s `warnf`: a separate on/off bit, an
1858    /// output mode (`normal`, `allow`, `store`), and a continuation buffer so
1859    /// multi-part warnings can be asserted via global `_WARN`.
1860    pub test_warn_enabled: bool,
1861    pub test_warn_on: bool,
1862    pub test_warn_mode: TestWarnMode,
1863    pub test_warn_last_to_cont: bool,
1864    pub test_warn_buffer: Vec<u8>,
1865
1866    /// Registry of native `LuaCFunction` pointers. Lua-types cannot reference
1867    /// `LuaState`, so `LuaClosure::LightC` carries a `usize` index into this
1868    /// vector instead of the real function pointer. `push_c_function`
1869    /// registers the function and stores the resulting index in the closure.
1870    pub c_functions: Vec<LuaCallable>,
1871
1872    /// Owns the allgc intrusive list and runs collections. Starts paused;
1873    /// `new_state` unpauses it once the state is fully initialized, after
1874    /// which `step` runs during VM dispatch.
1875    pub heap: std::rc::Rc<lua_gc::Heap>,
1876
1877    /// Cross-thread open-upvalue mirror. Maps `(thread_id, stack_idx)`
1878    /// to the live value of an open upvalue whose home thread is currently
1879    /// suspended while another thread runs. `coroutine.resume` snapshots the
1880    /// parent's open upvalues into this map before yielding control to the
1881    /// child, and reads the (possibly mutated) values back into the parent's
1882    /// stack when the child suspends or returns. From the running thread's
1883    /// perspective, `upvalue_get` / `upvalue_set` consult the mirror whenever
1884    /// an open upvalue's `thread_id` does not match `current_thread_id`.
1885    ///
1886    /// This avoids a stack refactor: the parent's `LuaState` is held by a
1887    /// `&mut` reference up the call stack during resume, so its stack cannot
1888    /// be reached directly through any `Rc<RefCell<_>>`. The mirror is the
1889    /// shared scratchpad that bridges the gap for the duration of a resume.
1890    pub cross_thread_upvals: std::collections::HashMap<(u64, StackIdx), LuaValue>,
1891
1892    /// Workaround for GC use-after-free across coroutine boundaries.
1893    /// When `aux_resume` switches to a child thread, the parent's live stack
1894    /// values would otherwise become unreachable to the tracer for the duration
1895    /// of the resume (the parent `LuaState` is held only as a stack-borrowed
1896    /// `&mut` up the call chain and is not part of any traced root set). To
1897    /// keep those values alive, `aux_resume` pushes a snapshot of the parent
1898    /// stack here before transferring control, and pops it on suspension or
1899    /// completion. The tracer visits every snapshot as a GC root via the
1900    /// `Trace for GlobalState` impl in `trace_impls.rs`.
1901    ///
1902    /// A reachability-driven thread sweep supersedes most of this, but the
1903    /// snapshot still guards values that live only on the parent's stack
1904    /// (i.e. not yet rooted by any thread node).
1905    pub suspended_parent_stacks: Vec<Vec<LuaValue>>,
1906
1907    /// Open-upvalue handles belonging to the same suspended parent windows as
1908    /// `suspended_parent_stacks`. Stack snapshots keep the pointed-to values
1909    /// alive; this roots the `UpVal` objects themselves so a GC inside the
1910    /// child coroutine cannot sweep entries still present in the parent's
1911    /// `openupval` list.
1912    pub suspended_parent_open_upvals: Vec<Vec<GcRef<UpVal>>>,
1913
1914    /// Capacity pools for the two snapshot kinds above. A resume previously
1915    /// allocated and freed a fresh `Vec` per snapshot — 2 mallocs + 2 frees
1916    /// on every `coroutine.resume` (the top allocator frames in the
1917    /// coroutine_pingpong profile, 20260609T2243Z). Popped snapshots park
1918    /// their (cleared) buffers here for reuse; pool depth is bounded by the
1919    /// maximum resume nesting depth. The pooled vectors are always empty, so
1920    /// they root nothing.
1921    pub snapshot_stack_pool: Vec<Vec<LuaValue>>,
1922    pub snapshot_upval_pool: Vec<Vec<GcRef<UpVal>>>,
1923
1924    /// Capacity pool for the transient value buffers a single `aux_resume`
1925    /// builds — the argument list copied off the parent stack on entry and the
1926    /// result list copied off the child stack on return. Each was a fresh
1927    /// `Vec<LuaValue>` allocated and freed per resume. Callers pop a buffer,
1928    /// fill it, drain it back to empty, then park it here; pool depth is
1929    /// bounded by the maximum resume-nesting depth. Parked buffers are always
1930    /// empty, so they root nothing.
1931    pub resume_value_pool: Vec<Vec<LuaValue>>,
1932
1933    /// Capacity pool for the open-upvalue slot list `aux_resume` snapshots on
1934    /// entry (parent thread id + stack index per open upvalue). This buffer
1935    /// spans the child resume — it is read again on return to flush
1936    /// cross-thread upvalues back — so it follows the same pop/park discipline
1937    /// as the snapshot pools. The pairs are plain `Copy` data and root nothing.
1938    pub resume_upval_slot_pool: Vec<Vec<(u64, StackIdx)>>,
1939
1940    /// Capacity pool for the upvalue-flush buffer `aux_resume` builds on return
1941    /// (stack index + mutated value per cross-thread upvalue). Popped, filled,
1942    /// drained back to the parent stack, then parked empty.
1943    pub resume_flush_pool: Vec<Vec<(StackIdx, LuaValue)>>,
1944}
1945
1946/// `LUA_MASKCOUNT` (`1 << LUA_HOOKCOUNT`) — the count-hook event mask the
1947/// sandbox arms on every thread to drive per-interval budget enforcement.
1948const SANDBOX_COUNT_MASK: u8 = 1 << 3;
1949
1950/// Sandbox trip code: not tripped.
1951pub const SANDBOX_TRIP_NONE: u8 = 0;
1952/// Sandbox trip code: the instruction budget reached zero.
1953pub const SANDBOX_TRIP_INSTRUCTIONS: u8 = 1;
1954/// Sandbox trip code: GC-tracked memory exceeded the configured ceiling.
1955pub const SANDBOX_TRIP_MEMORY: u8 = 2;
1956
1957/// Per-runtime sandbox budget, shared by every thread (main + coroutines) via
1958/// the `Rc<RefCell<GlobalState>>` they all hold. Every field is a `Cell` so the
1959/// VM can charge the budget through the shared `Ref` it borrows in the
1960/// count-hook path — no `&mut` and no write-borrow on the hot path.
1961/// `interval == 0` means inactive; in that case the VM never sets the
1962/// count-hook mask, so there is zero overhead.
1963#[derive(Default)]
1964pub struct SandboxLimits {
1965    /// Count-hook interval in instructions; `0` = sandbox inactive.
1966    pub interval: std::cell::Cell<i32>,
1967    /// Whether an instruction budget is enforced.
1968    pub instr_limited: std::cell::Cell<bool>,
1969    /// Instructions left before the budget trips.
1970    pub instr_remaining: std::cell::Cell<u64>,
1971    /// Configured instruction limit, retained so `reset` can refill.
1972    pub instr_limit: std::cell::Cell<u64>,
1973    /// GC-byte ceiling; `None` = no memory limit.
1974    pub mem_limit: std::cell::Cell<Option<usize>>,
1975    /// One of the `SANDBOX_TRIP_*` codes.
1976    pub tripped: std::cell::Cell<u8>,
1977    /// Sticky once a limit trips: the abort is *uncatchable*. While set,
1978    /// `pcall`/`xpcall`/`coroutine.resume` re-raise the trip error instead of
1979    /// swallowing it, so untrusted code cannot defeat the budget by catching
1980    /// it in a loop. Cleared only by [`LuaState::sandbox_reset`].
1981    pub aborting: std::cell::Cell<bool>,
1982}
1983
1984impl GlobalState {
1985    /// True while a sandbox instruction/memory budget is active on this runtime.
1986    pub fn sandbox_active(&self) -> bool {
1987        self.sandbox.interval.get() != 0
1988    }
1989
1990    /// Total live bytes allocated, as reported by the collector-owned heap
1991    /// accounting model.
1992    pub fn total_bytes(&self) -> usize {
1993        self.heap.bytes_used().max(1)
1994    }
1995
1996    /// Look up the coroutine `LuaState` registered under `id`. Returns
1997    /// `None` for the main-thread id (the main `LuaState` is owned by
1998    /// the embedder, not stored in `threads`) and for ids that were
1999    /// never issued or have already been closed.
2000    pub fn get_thread(&self, id: u64) -> Option<&ThreadRegistryEntry> {
2001        self.threads.get(&id)
2002    }
2003
2004    /// Return the canonical `GcRef<LuaThread>` for `id`. For the main
2005    /// thread that's `main_thread_value`; for a coroutine it's the
2006    /// value stored in the registry. Returns `None` if `id` is unknown.
2007    pub fn thread_value_for(&self, id: u64) -> Option<GcRef<lua_types::value::LuaThread>> {
2008        if id == self.main_thread_id {
2009            Some(self.main_thread_value.clone())
2010        } else {
2011            self.threads.get(&id).map(|e| e.value.clone())
2012        }
2013    }
2014
2015    /// Returns `true` when the state has been fully initialized. Checks
2016    /// `nilvalue == Nil`, mirroring C's check of `ttisnil(&g->nilvalue)`.
2017    pub fn is_complete(&self) -> bool {
2018        matches!(self.nilvalue, LuaValue::Nil)
2019    }
2020
2021    /// Returns the "current white" GC color bitmask.
2022    ///
2023    /// The effective dual-white collector state lives in `lua_gc::Heap`;
2024    /// this field preserves the translated `global_State` shape for code
2025    /// that still reads the upstream bitmask.
2026    pub fn current_white(&self) -> u8 {
2027        self.currentwhite
2028    }
2029
2030    /// Returns the "other white" GC color bitmask.
2031    pub fn other_white(&self) -> u8 {
2032        self.currentwhite ^ 0x03
2033    }
2034
2035    /// Returns `true` if the GC is in generational mode.
2036    pub fn is_gen_mode(&self) -> bool {
2037        self.gckind == GcKind::Generational as u8 || self.lastatomic != 0
2038    }
2039
2040    /// Returns `true` if the GC is currently running.
2041    pub fn gc_running(&self) -> bool {
2042        self.gcstp == 0
2043    }
2044
2045    /// Returns `true` while the GC is in its propagation phase.
2046    pub fn keep_invariant(&self) -> bool {
2047        self.heap.gc_state().is_invariant()
2048    }
2049
2050    /// Returns `true` while the GC is in a sweep phase.
2051    pub fn is_sweep_phase(&self) -> bool {
2052        self.heap.gc_state().is_sweep()
2053    }
2054
2055    // ── GC parameter accessors ────────────────────────────────────────────────
2056    pub fn gc_debt(&self) -> isize {
2057        self.gc_debt
2058    }
2059    pub fn set_gc_debt(&mut self, d: isize) {
2060        self.gc_debt = d;
2061    }
2062    pub fn gc_at_pause(&self) -> bool {
2063        self.heap.gc_state().is_pause()
2064    }
2065    fn get_gc_param(p: u8) -> i32 {
2066        (p as i32) * 4
2067    }
2068    fn set_gc_param_slot(slot: &mut u8, p: i32) {
2069        *slot = (p / 4) as u8;
2070    }
2071    pub fn gc_pause_param(&self) -> i32 {
2072        Self::get_gc_param(self.gcpause)
2073    }
2074    pub fn set_gc_pause_param(&mut self, p: i32) {
2075        Self::set_gc_param_slot(&mut self.gcpause, p);
2076    }
2077    pub fn gc_stepmul_param(&self) -> i32 {
2078        Self::get_gc_param(self.gcstepmul)
2079    }
2080    pub fn set_gc_stepmul_param(&mut self, p: i32) {
2081        Self::set_gc_param_slot(&mut self.gcstepmul, p);
2082    }
2083    pub fn gc_genmajormul_param(&self) -> i32 {
2084        Self::get_gc_param(self.genmajormul)
2085    }
2086    pub fn set_gc_genmajormul(&mut self, p: i32) {
2087        Self::set_gc_param_slot(&mut self.genmajormul, p);
2088    }
2089    /// Lua 5.5 `collectgarbage("param", name [, value])`. `idx` is the 0-based
2090    /// param index (`minormul=0 .. stepsize=5`). When `value >= 0` the param is
2091    /// set; the previous value is always returned.
2092    pub fn gc55_param(&mut self, idx: usize, value: i64) -> i64 {
2093        let old = self.gc55_params[idx];
2094        if value >= 0 {
2095            self.gc55_params[idx] = value;
2096        }
2097        old
2098    }
2099    pub fn gc_stop_flags(&self) -> u8 {
2100        self.gcstp
2101    }
2102    pub fn set_gc_stop_flags(&mut self, f: u8) {
2103        self.gcstp = f;
2104    }
2105    pub fn stop_gc_internal(&mut self) -> u8 {
2106        let old = self.gcstp;
2107        self.gcstp |= GCSTPGC;
2108        old
2109    }
2110    pub fn set_gc_stop_user(&mut self) {
2111        // GCSTPUSR (lgc.h:155) = 1 — bit set when GC is stopped by user (lua_gc(L, LUA_GCSTOP)).
2112        self.gcstp = GCSTPUSR;
2113    }
2114    pub fn clear_gc_stop(&mut self) {
2115        self.gcstp = 0;
2116    }
2117    pub fn is_gc_running(&self) -> bool {
2118        self.gcstp == 0
2119    }
2120    /// True when the GC has been disabled internally (state setup, mid-GC,
2121    /// or while closing); user-stop via `collectgarbage("stop")` does NOT
2122    /// set this bit, so `lua_gc` continues to honour Count/Step/etc.
2123    ///
2124    pub fn is_gc_stopped_internally(&self) -> bool {
2125        (self.gcstp & GCSTPGC) != 0
2126    }
2127
2128    /// Returns the interned `__xxx` name string for tag method `tm`, or
2129    /// `None` if `tmname` has not yet been initialised (early bootstrap).
2130    ///
2131    /// The lua-vm crate carries two distinct `TagMethod` enums (one in
2132    /// `lua-types`, one in `crate::tagmethods`) with identical
2133    /// `#[repr(u8)]` ordering. The [`TmIndex`] trait bridges them so callers
2134    /// from either side can index `tmname` uniformly.
2135    pub fn tm_name<T: TmIndex>(&self, tm: T) -> Option<GcRef<LuaString>> {
2136        self.tmname.get(tm.tm_index()).cloned()
2137    }
2138}
2139
2140/// Discriminant-to-index conversion for the two parallel `TagMethod` enums.
2141///
2142/// Both `lua_types::tagmethod::TagMethod` and `crate::tagmethods::TagMethod`
2143/// are `#[repr(u8)]` with the same ORDER TM layout, so casting through `u8`
2144/// yields the correct `GlobalState.tmname` index for either type.
2145pub trait TmIndex: Copy {
2146    fn tm_index(self) -> usize;
2147}
2148impl TmIndex for lua_types::tagmethod::TagMethod {
2149    fn tm_index(self) -> usize {
2150        self as u8 as usize
2151    }
2152}
2153impl TmIndex for crate::tagmethods::TagMethod {
2154    fn tm_index(self) -> usize {
2155        self as u8 as usize
2156    }
2157}
2158impl TmIndex for usize {
2159    fn tm_index(self) -> usize {
2160        self
2161    }
2162}
2163impl TmIndex for u8 {
2164    fn tm_index(self) -> usize {
2165        self as usize
2166    }
2167}
2168
2169use lua_types::tagmethod::TagMethod;
2170
2171// ─── LuaState ────────────────────────────────────────────────────────────────
2172
2173/// Per-thread Lua execution state.
2174///
2175/// All stack-pointer fields in C (`StkIdRel`, `StkId`) become `StackIdx` (u32
2176/// index into `stack: Vec<StackValue>`).  The C intrusive `CallInfo` linked list
2177/// becomes `call_info: Vec<CallInfo>` indexed by `CallInfoIdx`.
2178///
2179/// No `extra_space` field: C's `LUA_EXTRASPACE` reserves a small, fixed-size
2180/// raw memory region immediately before `lua_State` for embedder bookkeeping,
2181/// addressable via `lua_getextraspace` without a registry lookup — a niche
2182/// embedding feature (issue #275 item 3). This port has no equivalent field
2183/// or accessor; an embedder that needs per-thread scratch storage should use
2184/// the registry (`Lua::create_registry_value`/`set_named_registry_value`) or
2185/// a side table keyed by thread identity instead. Tracked as a known
2186/// unsupported embedding feature in `docs/EMBEDDING_API_IMPLEMENTATION.md`'s
2187/// Known Limits.
2188pub struct LuaState {
2189    // ── Thread status ──
2190
2191    pub status: u8,
2192
2193    pub allowhook: bool,
2194
2195    pub nci: u32,
2196
2197    // ── Stack ──
2198
2199    pub top: StackIdx,
2200
2201    /// Redundant once the stack is a `Vec` (kept for parity with the C
2202    /// field).
2203    pub stack_last: StackIdx,
2204
2205    pub stack: Vec<StackValue>,
2206
2207    // ── Call info ──
2208
2209    pub ci: CallInfoIdx,
2210
2211    /// C's `base_ci` is `call_info[0]` here; there is no separate field.
2212    pub call_info: Vec<CallInfo>,
2213
2214    // ── Upvalues / to-be-closed ──
2215
2216    pub openupval: Vec<GcRef<UpVal>>,
2217
2218    /// Per-thread mirror of C 5.3's per-open-upvalue `touched` flag
2219    /// (`lfunc.h` `UpVal.u.open.touched`). Set when this thread creates or
2220    /// writes an open upvalue; consulted only by the legacy (5.1/5.2/5.3)
2221    /// `remarkupvals` pass in [`trace_reachable_threads`]. In those versions
2222    /// an unmarked thread's touched open upvalues have their values re-marked
2223    /// **once** during the atomic phase, then the flag is cleared (mirroring
2224    /// C clearing `touched` and dropping the thread from `g->twups`). This is
2225    /// what makes a cycle reachable only through a suspended thread survive
2226    /// one extra collection before being finalized. From 5.4 the C condition
2227    /// became `!iswhite(uv)` instead of `touched`, so this flag is never read
2228    /// for modern versions and the baked 5.4/5.5 behavior is unchanged.
2229    pub legacy_open_upval_touched: std::cell::Cell<bool>,
2230
2231    pub tbclist: Vec<StackIdx>,
2232
2233    // ── Global state ──
2234
2235    /// Shared via `Rc<RefCell<>>` for shared ownership across coroutine
2236    /// threads. C's `l_G` is accessed through the [`LuaState::global`] /
2237    /// [`LuaState::global_mut`] methods rather than a raw field.
2238    pub(crate) global: Rc<RefCell<GlobalState>>,
2239
2240    // ── Hooks ──
2241
2242    pub hook: Option<Box<dyn FnMut(&mut LuaState, &crate::debug::LuaDebug)>>,
2243
2244    pub hookmask: u8,
2245
2246    pub basehookcount: i32,
2247
2248    pub hookcount: i32,
2249
2250    // ── Error handling ──
2251
2252    // C's `errorJmp` (setjmp/longjmp chain) has no field here — the `?`
2253    // operator on `Result<T, LuaError>` replaces it entirely.
2254
2255    pub errfunc: isize,
2256
2257    // ── C-call depth ──
2258
2259    pub n_ccalls: u32,
2260
2261    // ── Debug / hooks ──
2262
2263    pub oldpc: u32,
2264
2265    // ── GC color ──
2266
2267    pub marked: u8,
2268
2269    /// Owner thread id for this `LuaState`, cached as a plain `u64` so the
2270    /// hot path of `upvalue_get` can compare against an open upvalue's
2271    /// `thread_id` without taking a `RefCell::borrow` on the shared
2272    /// `GlobalState`.
2273    ///
2274    /// Invariant: while this `LuaState` is the actively running thread,
2275    /// `GlobalState::current_thread_id == self.cached_thread_id`. This is
2276    /// maintained structurally by `new_state`/`new_thread` (which set
2277    /// `cached_thread_id` to the thread's own id once at construction)
2278    /// combined with the coroutine resume protocol: `coro_lib::resume`
2279    /// writes `co_state.global.current_thread_id = co_id` before the
2280    /// coroutine runs, and restores `parent_thread_id` on yield/return.
2281    /// Because each thread caches its own id (not the global's id), the
2282    /// invariant survives every context switch without an explicit refresh
2283    /// at the resume site.
2284    pub cached_thread_id: u64,
2285
2286    /// Local GC gate.
2287    ///
2288    /// Avoids borrowing `GlobalState` on every call edge when GC/finalizers
2289    /// are not currently due.
2290    pub gc_check_needed: bool,
2291}
2292
2293impl LuaState {
2294    /// Access the process-wide `GlobalState` immutably.
2295    ///
2296    /// Returns `std::cell::Ref<GlobalState>` because `GlobalState` is held in
2297    /// `Rc<RefCell<...>>`. Call sites that do `state.global().field` work fine
2298    /// via `Deref`. Callers must not hold the `Ref` across a `global_mut()` call.
2299    pub fn global(&self) -> std::cell::Ref<'_, GlobalState> {
2300        self.global.borrow()
2301    }
2302
2303    /// Access the process-wide `GlobalState` mutably.
2304    pub fn global_mut(&self) -> std::cell::RefMut<'_, GlobalState> {
2305        self.global.borrow_mut()
2306    }
2307
2308    /// Clone the `Rc` handle to the GlobalState for sharing with a new coroutine.
2309    ///
2310    /// Used in `new_thread` to give the child thread access to the same GlobalState.
2311    pub fn global_rc(&self) -> Rc<RefCell<GlobalState>> {
2312        Rc::clone(&self.global)
2313    }
2314
2315    /// Lua 5.1 global table of the thread `id` (`lua_State.l_gt`).
2316    ///
2317    /// The main thread's `l_gt` is the shared [`GlobalState::globals`] field;
2318    /// a coroutine's lives in [`GlobalState::thread_globals`] under its id,
2319    /// seeded at creation in `new_thread`. A coroutine id that is missing from
2320    /// the map is a `new_thread` seeding bug, not a recoverable state.
2321    ///
2322    /// 5.1 only. Other versions never call this — they share one global table.
2323    pub fn v51_thread_lgt(&self, id: u64) -> LuaValue {
2324        let g = self.global();
2325        if id == g.main_thread_id {
2326            g.globals.clone()
2327        } else {
2328            g.thread_globals
2329                .get(&id)
2330                .expect("v51 coroutine l_gt must be seeded in new_thread")
2331                .clone()
2332        }
2333    }
2334
2335    /// Set the Lua 5.1 global table of thread `id` (`lua_State.l_gt`).
2336    ///
2337    /// Writes the main thread's `l_gt` through [`GlobalState::globals`] and a
2338    /// coroutine's through [`GlobalState::thread_globals`]. 5.1 only.
2339    pub fn v51_set_thread_lgt(&self, id: u64, t: LuaValue) {
2340        let mut g = self.global_mut();
2341        if id == g.main_thread_id {
2342            g.globals = t;
2343        } else {
2344            g.thread_globals.insert(id, t);
2345        }
2346    }
2347
2348    /// Enable the ltests-style warning sink used by `LUA_RS_TESTC`.
2349    pub fn enable_test_warning_handler(&mut self) -> Result<(), LuaError> {
2350        {
2351            let mut g = self.global_mut();
2352            g.test_warn_enabled = true;
2353            g.test_warn_on = false;
2354            g.test_warn_mode = TestWarnMode::Normal;
2355            g.test_warn_last_to_cont = false;
2356            g.test_warn_buffer.clear();
2357        }
2358        self.push(LuaValue::Bool(false));
2359        crate::api::set_global(self, b"_WARN")
2360    }
2361
2362    /// Return the current C-call recursion depth (lower 16 bits of `n_ccalls`).
2363    pub fn c_calls(&self) -> u32 {
2364        self.n_ccalls & 0xffff
2365    }
2366
2367    /// Increment the non-yieldable call count (upper 16 bits of `n_ccalls`).
2368    pub fn inc_nny(&mut self) {
2369        self.n_ccalls += 0x10000;
2370    }
2371
2372    /// Decrement the non-yieldable call count.
2373    pub fn dec_nny(&mut self) {
2374        self.n_ccalls -= 0x10000;
2375    }
2376
2377    /// Returns `true` if the thread can yield (no non-yieldable frames on the stack).
2378    pub fn is_yieldable(&self) -> bool {
2379        (self.n_ccalls & 0xffff0000) == 0
2380    }
2381
2382    /// Reset the hook countdown to the baseline.
2383    pub fn reset_hook_count(&mut self) {
2384        self.hookcount = self.basehookcount;
2385    }
2386
2387    /// Activate the per-runtime sandbox budget and arm the current thread.
2388    ///
2389    /// Stores the budget in `GlobalState` (shared across every thread) and
2390    /// sets the count-hook mask on this thread so the dispatch loop traps every
2391    /// `interval` instructions. Coroutines created afterwards inherit the mask
2392    /// via `preinit_thread`, so metering spans all threads — closing the
2393    /// coroutine-escape that a per-thread closure could not. Pass `None` for a
2394    /// limit to leave that dimension unbounded.
2395    pub fn install_sandbox_limits(
2396        &mut self,
2397        interval: i32,
2398        instr_limit: Option<u64>,
2399        mem_limit: Option<usize>,
2400    ) {
2401        let interval = interval.max(1);
2402        {
2403            let g = self.global();
2404            g.sandbox.interval.set(interval);
2405            g.sandbox.instr_limited.set(instr_limit.is_some());
2406            g.sandbox.instr_remaining.set(instr_limit.unwrap_or(0));
2407            g.sandbox.instr_limit.set(instr_limit.unwrap_or(0));
2408            g.sandbox.mem_limit.set(mem_limit);
2409            g.sandbox.tripped.set(SANDBOX_TRIP_NONE);
2410        }
2411        self.hookmask |= SANDBOX_COUNT_MASK;
2412        self.basehookcount = interval;
2413        self.hookcount = interval;
2414        crate::debug::arm_traps(self);
2415    }
2416
2417    /// Charge the shared budget for one count-hook interval. Returns the abort
2418    /// error if a limit has been crossed (and records why in `tripped`).
2419    /// Called from `trace_exec` on every thread, once per `interval`
2420    /// instructions — never on the budget-disabled hot path.
2421    pub fn sandbox_charge_interval(&self) -> Option<LuaError> {
2422        let interval = self.global().sandbox.interval.get();
2423        self.sandbox_charge(interval as u64)
2424    }
2425
2426    /// Charge `amount` instructions against the runtime-wide budget and sample
2427    /// the memory ceiling. Returns the uncatchable abort error if a limit is
2428    /// crossed (recording the reason and arming the sticky `aborting` flag), or
2429    /// `None` otherwise. No-op when no sandbox is active.
2430    ///
2431    /// Used both by the per-interval VM charge and by loop-heavy stdlib
2432    /// functions (the pattern matcher) so a single native call cannot run for
2433    /// longer than the instruction budget allows.
2434    pub fn sandbox_charge(&self, amount: u64) -> Option<LuaError> {
2435        let g = self.global();
2436        if g.sandbox.interval.get() == 0 {
2437            return None;
2438        }
2439        if g.sandbox.instr_limited.get() {
2440            let rem = g.sandbox.instr_remaining.get().saturating_sub(amount);
2441            g.sandbox.instr_remaining.set(rem);
2442            if rem == 0 {
2443                g.sandbox.tripped.set(SANDBOX_TRIP_INSTRUCTIONS);
2444                g.sandbox.aborting.set(true);
2445                return Some(LuaError::runtime(format_args!(
2446                    "sandbox: instruction budget exhausted"
2447                )));
2448            }
2449        }
2450        if let Some(limit) = g.sandbox.mem_limit.get() {
2451            if g.total_bytes() > limit {
2452                g.sandbox.tripped.set(SANDBOX_TRIP_MEMORY);
2453                g.sandbox.aborting.set(true);
2454                return Some(LuaError::runtime(format_args!(
2455                    "sandbox: memory limit exceeded"
2456                )));
2457            }
2458        }
2459        None
2460    }
2461
2462    /// Reject a size-known-upfront allocation that would push GC-tracked memory
2463    /// past the ceiling, *before* the buffer is built. Returns the uncatchable
2464    /// memory abort if `total_bytes() + additional` exceeds the limit. Used by
2465    /// stdlib functions that allocate a large buffer of a computed size in one
2466    /// instruction (e.g. `string.rep`, `table.concat` and the `..` operator), where the
2467    /// per-instruction `sandbox_check_memory` would only fire *after* the
2468    /// allocation already happened.
2469    pub fn sandbox_reserve(&self, additional: usize) -> Option<LuaError> {
2470        let g = self.global();
2471        if g.sandbox.interval.get() == 0 {
2472            return None;
2473        }
2474        if let Some(limit) = g.sandbox.mem_limit.get() {
2475            let projected = g.total_bytes().saturating_add(additional);
2476            if projected > limit {
2477                g.sandbox.tripped.set(SANDBOX_TRIP_MEMORY);
2478                g.sandbox.aborting.set(true);
2479                return Some(LuaError::runtime(format_args!(
2480                    "sandbox: memory limit exceeded"
2481                )));
2482            }
2483        }
2484        None
2485    }
2486
2487    /// Upper bound on the work a single pattern-match call may do before it must
2488    /// stop and let the caller charge the budget. Equal to the remaining
2489    /// instruction budget when an instruction limit is active, else `0` meaning
2490    /// "unlimited" (preserving non-sandboxed behavior exactly).
2491    pub fn sandbox_match_step_limit(&self) -> u64 {
2492        let g = self.global();
2493        if g.sandbox.interval.get() != 0 && g.sandbox.instr_limited.get() {
2494            g.sandbox.instr_remaining.get()
2495        } else {
2496            0
2497        }
2498    }
2499
2500    /// Whether a sandbox abort is in flight. While true, protected-call builtins
2501    /// (`pcall`/`xpcall`/`coroutine.resume`) must re-raise rather than catch, so
2502    /// the budget trip is uncatchable. Set on trip, cleared by `sandbox_reset`.
2503    pub fn sandbox_aborting(&self) -> bool {
2504        self.global().sandbox.aborting.get()
2505    }
2506
2507    /// Whether an instruction budget is active (vs. only a memory limit / none).
2508    pub fn sandbox_instr_limited(&self) -> bool {
2509        self.global().sandbox.instr_limited.get()
2510    }
2511
2512    /// Instructions left before the budget trips (meaningful only when
2513    /// [`sandbox_instr_limited`](Self::sandbox_instr_limited)).
2514    pub fn sandbox_instr_remaining(&self) -> u64 {
2515        self.global().sandbox.instr_remaining.get()
2516    }
2517
2518    /// The configured instruction limit (for computing "used").
2519    pub fn sandbox_instr_limit(&self) -> u64 {
2520        self.global().sandbox.instr_limit.get()
2521    }
2522
2523    /// The current trip code (one of the `SANDBOX_TRIP_*` constants).
2524    pub fn sandbox_tripped_code(&self) -> u8 {
2525        self.global().sandbox.tripped.get()
2526    }
2527
2528    /// Refill the instruction budget to its configured limit and clear the
2529    /// trip flag, so the same runtime can run another chunk.
2530    pub fn sandbox_reset(&self) {
2531        let g = self.global();
2532        if g.sandbox.instr_limited.get() {
2533            g.sandbox.instr_remaining.set(g.sandbox.instr_limit.get());
2534        }
2535        g.sandbox.tripped.set(SANDBOX_TRIP_NONE);
2536        g.sandbox.aborting.set(false);
2537    }
2538
2539    /// Returns the current stack capacity (slots between base and stack_last).
2540    pub fn stack_size(&self) -> usize {
2541        self.stack_last.0 as usize
2542    }
2543
2544    /// Push a value onto the stack, incrementing `top`.
2545    #[inline(always)]
2546    pub fn push(&mut self, val: LuaValue) {
2547        let top = self.top.0 as usize;
2548        if top < self.stack.len() {
2549            self.stack[top] = StackValue { val };
2550        } else {
2551            self.stack.push(StackValue { val });
2552        }
2553        self.top = StackIdx(self.top.0 + 1);
2554    }
2555
2556    /// Pop the top value from the stack, decrementing `top`.
2557    ///
2558    #[inline(always)]
2559    pub fn pop(&mut self) -> LuaValue {
2560        if self.top.0 == 0 {
2561            return LuaValue::Nil;
2562        }
2563        self.top = StackIdx(self.top.0 - 1);
2564        self.stack[self.top.0 as usize].val.clone()
2565    }
2566
2567    /// Retrieve the value at the given stack index without removing it.
2568    #[inline(always)]
2569    pub fn stack_val(&self, idx: StackIdx) -> &LuaValue {
2570        &self.stack[idx.0 as usize].val
2571    }
2572
2573    /// Write a value to a specific stack slot.
2574    #[inline(always)]
2575    pub fn set_stack_val(&mut self, idx: StackIdx, val: LuaValue) {
2576        self.stack[idx.0 as usize].val = val;
2577    }
2578
2579    /// Returns a handle for GC operations (checked/forced collection,
2580    /// barriers) implemented in `lua-gc`.
2581    pub fn gc(&mut self) -> GcHandle<'_> {
2582        GcHandle { _state: self }
2583    }
2584
2585    /// Pin a Lua value in the external root set and return its stable key.
2586    pub fn external_root_value(&mut self, value: LuaValue) -> ExternalRootKey {
2587        self.global_mut().external_roots.insert(value)
2588    }
2589
2590    /// Read a value currently pinned by an external root key.
2591    pub fn external_rooted_value(&self, key: ExternalRootKey) -> Option<LuaValue> {
2592        self.global().external_roots.get(key).cloned()
2593    }
2594
2595    /// Replace the value pinned by an external root key.
2596    pub fn external_replace_root(
2597        &mut self,
2598        key: ExternalRootKey,
2599        value: LuaValue,
2600    ) -> Option<LuaValue> {
2601        self.global_mut().external_roots.replace(key, value)
2602    }
2603
2604    /// Remove an external root. Returns `None` for stale or already-removed keys.
2605    pub fn external_unroot_value(&mut self, key: ExternalRootKey) -> Option<LuaValue> {
2606        self.global_mut().external_roots.remove(key)
2607    }
2608
2609    /// Best-effort external root removal for destructors that may run while
2610    /// the collector holds an immutable `GlobalState` borrow.
2611    pub fn try_external_unroot_value(
2612        &mut self,
2613        key: ExternalRootKey,
2614    ) -> std::result::Result<Option<LuaValue>, std::cell::BorrowMutError> {
2615        self.global
2616            .try_borrow_mut()
2617            .map(|mut global| global.external_roots.remove(key))
2618    }
2619
2620    /// Create a new empty table and register it with the GC.
2621    pub fn new_table(&mut self) -> GcRef<LuaTable> {
2622        self.mark_gc_check_needed();
2623        GcRef::new(LuaTable::placeholder())
2624    }
2625
2626    /// Create a fresh table with pre-sized array/hash parts.
2627    ///
2628    /// mirrors the `luaH_new` + `luaH_resize` pair in one call so we don't
2629    /// pay an extra resize path for hot construction sites.
2630    pub fn new_table_with_sizes(
2631        &mut self,
2632        array_size: u32,
2633        hash_size: u32,
2634    ) -> Result<GcRef<LuaTable>, LuaError> {
2635        self.mark_gc_check_needed();
2636        let t = GcRef::new(LuaTable::placeholder());
2637        self.table_resize(&t, array_size as usize, hash_size as usize)?;
2638        Ok(t)
2639    }
2640
2641    /// Intern a byte string in the global string pool.
2642    ///
2643    /// In C, short strings (≤ LUAI_MAXSHORTLEN = 40 bytes) are interned globally
2644    /// via `luaS_newlstr`, while long strings allocate a fresh TString each
2645    /// call so distinct long strings keep distinct object identity (observable
2646    /// via `string.format("%p", s)`). The parser separately deduplicates
2647    /// long-string literals within a single chunk through `luaX_newstring`'s
2648    /// `ls->h` anchor table.
2649    ///
2650    /// Short-string interning, `luaS_newlstr` shape: one hash of the input
2651    /// bytes, a bucket walk on hit (zero allocation), and an insert that
2652    /// reuses the same hash on miss. See the `InternedStringMap` doc for why
2653    /// this replaced the owned-key `HashMap` entry API.
2654    pub fn intern_str(&mut self, bytes: &[u8]) -> Result<GcRef<LuaString>, LuaError> {
2655        if bytes.len() <= crate::string::MAX_SHORT_LEN {
2656            let hash = LuaString::hash_bytes(bytes, 0);
2657            {
2658                let global = self.global();
2659                if let Some(existing) = global.interned_lt.find(bytes, hash) {
2660                    return Ok(existing);
2661                }
2662            }
2663            let new_ref = GcRef::new(LuaString::from_slice(bytes));
2664            new_ref.account_buffer(new_ref.buffer_bytes() as isize);
2665            self.global_mut().interned_lt.insert(new_ref.clone());
2666            self.mark_gc_check_needed();
2667            Ok(new_ref)
2668        } else {
2669            self.mark_gc_check_needed();
2670            let new_ref = GcRef::new(LuaString::from_slice(bytes));
2671            new_ref.account_buffer(new_ref.buffer_bytes() as isize);
2672            Ok(new_ref)
2673        }
2674    }
2675
2676    /// Returns the current CallInfo index (the active call frame).
2677    #[inline(always)]
2678    pub fn top_idx(&self) -> StackIdx {
2679        self.top
2680    }
2681}
2682
2683// ─── Stack / register access ───────────────────────────────────────────────
2684//
2685// Methods used by api.rs, debug.rs, do_.rs, vm.rs, tagmethods.rs, etc.
2686
2687impl LuaState {
2688    #[inline(always)]
2689    pub fn get_at(&self, idx: impl Into<StackIdxConv>) -> LuaValue {
2690        let i: StackIdx = idx.into().0;
2691        match self.stack.get(i.0 as usize) {
2692            Some(slot) => slot.val.clone(),
2693            None => LuaValue::Nil,
2694        }
2695    }
2696    #[inline(always)]
2697    pub fn set_at(&mut self, idx: impl Into<StackIdxConv>, v: LuaValue) {
2698        let i: StackIdx = idx.into().0;
2699        self.stack[i.0 as usize].val = v;
2700    }
2701
2702    /// Clear stack slots in `[start, end)` without changing `top`.
2703    ///
2704    /// Under the exact-rooting model (abe2b52) the collector traces only the
2705    /// live window `[0, top)` and, per collect, nils the dead tail above `top`
2706    /// up to the high-water mark before tracing — so a reserved-but-unused tail
2707    /// is normally cleared by the collector itself, not by callers. This helper
2708    /// exists for the call-setup paths that raise `ci.top` above the live `top`
2709    /// (e.g. a tail call reserving its callee frame): on those paths the gap
2710    /// `[live_top, new_ci_top)` can be reached by the per-collect dead-tail
2711    /// clear and the trace within a single collect off the same raised top, so
2712    /// it must not retain stale collectable `GcRef`s left by a previous frame —
2713    /// retaining them is the #140 use-after-free class. Callers clear the gap
2714    /// here so the raised top is GC-safe before any allocation can collect.
2715    pub fn clear_stack_range(&mut self, start: StackIdx, end: StackIdx) {
2716        if end.0 <= start.0 {
2717            return;
2718        }
2719        let end_u = end.0 as usize;
2720        if end_u > self.stack.len() {
2721            self.stack.resize_with(end_u, StackValue::default);
2722        }
2723        for i in start.0..end.0 {
2724            self.stack[i as usize].val = LuaValue::Nil;
2725        }
2726    }
2727    /// Hot-path accessor: returns `Some(i)` only when the stack slot at `idx`
2728    /// holds a `LuaValue::Int(i)`. Returns `None` for any other tag (including
2729    /// out-of-bounds, which behaves as `Nil`).
2730    ///
2731    /// `ttisinteger` predicate that gates the integer arithmetic fast path in
2732    /// `lvm.c`'s `op_arith_aux` macro. Avoids the full `LuaValue` clone that
2733    /// `get_at` performs — the operand is only needed for its `i64` payload.
2734    #[inline(always)]
2735    pub fn get_int_at(&self, idx: impl Into<StackIdxConv>) -> Option<i64> {
2736        let i: StackIdx = idx.into().0;
2737        match self.stack.get(i.0 as usize) {
2738            Some(slot) => match &slot.val {
2739                LuaValue::Int(v) => Some(*v),
2740                _ => None,
2741            },
2742            None => None,
2743        }
2744    }
2745    /// Hot-path accessor: returns `Some((a, b))` only when both stack slots
2746    /// at `rb` and `rc` hold integers. Equivalent to two `get_int_at` calls
2747    /// but is shaped so the arithmetic opcode dispatch arms can pattern-match
2748    /// the common case with a single `if let`.
2749    ///
2750    /// the `op_arith_aux` macro.
2751    #[inline(always)]
2752    pub fn get_int_pair_at(
2753        &self,
2754        rb: impl Into<StackIdxConv>,
2755        rc: impl Into<StackIdxConv>,
2756    ) -> Option<(i64, i64)> {
2757        let rb: StackIdx = rb.into().0;
2758        let rc: StackIdx = rc.into().0;
2759        match (self.stack[rb.0 as usize].val, self.stack[rc.0 as usize].val) {
2760            (LuaValue::Int(ib), LuaValue::Int(ic)) => Some((ib, ic)),
2761            _ => None,
2762        }
2763    }
2764    /// Hot-path accessor: returns `Some(f)` when the slot holds a `Float(f)`
2765    /// or coerces an `Int(i)` to `f64`. Returns `None` for any other tag.
2766    /// No `LuaValue` clone — only the primitive payload travels back.
2767    ///
2768    #[inline(always)]
2769    pub fn get_num_at(&self, idx: impl Into<StackIdxConv>) -> Option<f64> {
2770        let i: StackIdx = idx.into().0;
2771        match self.stack.get(i.0 as usize) {
2772            Some(slot) => match &slot.val {
2773                LuaValue::Float(f) => Some(*f),
2774                LuaValue::Int(v) => Some(*v as f64),
2775                _ => None,
2776            },
2777            None => None,
2778        }
2779    }
2780    /// Hot-path accessor: returns `Some(f)` only when the slot holds a
2781    /// `LuaValue::Float(f)`. Does NOT coerce integers; the integer branch is
2782    /// the caller's responsibility. Used by opcode arms that have already
2783    /// ruled out the integer fast path.
2784    #[inline(always)]
2785    pub fn get_float_at(&self, idx: impl Into<StackIdxConv>) -> Option<f64> {
2786        let i: StackIdx = idx.into().0;
2787        match self.stack.get(i.0 as usize) {
2788            Some(slot) => match &slot.val {
2789                LuaValue::Float(f) => Some(*f),
2790                _ => None,
2791            },
2792            None => None,
2793        }
2794    }
2795    /// Hot-path accessor: pair version of `get_num_at` — returns `Some((a,b))`
2796    /// when both slots coerce to `f64` (Float or Int), `None` if either does
2797    /// not. Used by the float fast path of the arith opcodes.
2798    ///
2799    #[inline(always)]
2800    pub fn get_num_pair_at(
2801        &self,
2802        rb: impl Into<StackIdxConv>,
2803        rc: impl Into<StackIdxConv>,
2804    ) -> Option<(f64, f64)> {
2805        let rb: StackIdx = rb.into().0;
2806        let rc: StackIdx = rc.into().0;
2807        match (self.stack[rb.0 as usize].val, self.stack[rc.0 as usize].val) {
2808            (LuaValue::Float(nb), LuaValue::Float(nc)) => Some((nb, nc)),
2809            (LuaValue::Int(ib), LuaValue::Int(ic)) => Some((ib as f64, ic as f64)),
2810            (LuaValue::Int(ib), LuaValue::Float(nc)) => Some((ib as f64, nc)),
2811            (LuaValue::Float(nb), LuaValue::Int(ic)) => Some((nb, ic as f64)),
2812            _ => None,
2813        }
2814    }
2815    /// Set `top` to an absolute stack index. Grows the backing stack vector
2816    /// (filling new slots with `Nil`) when `idx` is past `stack.len()`, but
2817    /// never clobbers existing slots between the old top and the new top —
2818    /// VM opcodes (Call, ForPrep, etc.) write registers via `set_at` and then
2819    /// raise `top` to signal "these are now live"; nil-filling here would
2820    /// erase the just-written values.
2821    ///
2822    /// The `setnilvalue(s2v(L->top.p++))` clear loop in `lua_settop` (lapi.c)
2823    /// is part of the public API path and lives in `api::set_top` instead.
2824    /// Callers here pass an absolute `StackIdx`, not the relative `idx` of
2825    /// the public `lua_settop`. The to-be-closed (`tbclist`) close path
2826    /// lives in `func.rs`, not here.
2827    #[inline(always)]
2828    pub fn set_top(&mut self, idx: impl Into<StackIdxConv>) {
2829        let new_top: StackIdx = idx.into().0;
2830        let new_top_u = new_top.0 as usize;
2831        if new_top_u > self.stack.len() {
2832            self.stack.resize_with(new_top_u, StackValue::default);
2833        }
2834        self.top = new_top;
2835    }
2836    /// Primitive "set top index" — just writes `self.top`, no nil-fill.
2837    ///
2838    /// Callers (`api.rs::set_top`, `raw_set`, etc.) pre-nil-fill or only
2839    /// shrink, so this routine intentionally does no clearing or resizing.
2840    /// The to-be-closed (`tbclist`) close path lives in `func.rs`, not here.
2841    #[inline(always)]
2842    pub fn set_top_idx(&mut self, idx: impl Into<StackIdxConv>) {
2843        let new_top: StackIdx = idx.into().0;
2844        self.top = new_top;
2845    }
2846    /// Decrement `top` by 1 (saturating at zero).
2847    ///
2848    #[inline(always)]
2849    pub fn dec_top(&mut self) {
2850        if self.top.0 > 0 {
2851            self.top = StackIdx(self.top.0 - 1);
2852        }
2853    }
2854    #[inline(always)]
2855    pub fn pop_n(&mut self, n: usize) {
2856        let cur = self.top.0 as usize;
2857        let new = cur.saturating_sub(n);
2858        self.top = StackIdx(new as u32);
2859    }
2860    /// Returns the value at the given stack index without removing it.
2861    ///
2862    #[inline(always)]
2863    pub fn peek_at(&mut self, idx: impl Into<StackIdxConv>) -> LuaValue {
2864        let i: StackIdx = idx.into().0;
2865        match self.stack.get(i.0 as usize) {
2866            Some(slot) => slot.val.clone(),
2867            None => LuaValue::Nil,
2868        }
2869    }
2870    /// Returns the value just below `top` (the topmost live slot) without
2871    /// removing it.
2872    ///
2873    #[inline(always)]
2874    pub fn peek_top(&mut self) -> LuaValue {
2875        if self.top.0 == 0 {
2876            return LuaValue::Nil;
2877        }
2878        self.stack[(self.top.0 - 1) as usize].val.clone()
2879    }
2880    /// Returns the topmost slot interpreted as a string. Panics if the slot
2881    /// is not a `LuaValue::Str`. Callers (e.g. `luaO_pushvfstring`) guarantee
2882    /// the value has been pushed as an interned string immediately prior.
2883    ///
2884    pub fn peek_string_at_top(&mut self) -> GcRef<LuaString> {
2885        match self.peek_top() {
2886            LuaValue::Str(s) => s,
2887            _ => panic!("peek_string_at_top: top of stack is not a string"),
2888        }
2889    }
2890    /// Mutable reference to the value at the given stack slot.
2891    ///
2892    pub fn stack_at(&mut self, idx: impl Into<StackIdxConv>) -> &mut LuaValue {
2893        let i: StackIdx = idx.into().0;
2894        &mut self.stack[i.0 as usize].val
2895    }
2896    /// Writes `Nil` to the given stack slot.
2897    ///
2898    pub fn stack_set_nil(&mut self, idx: impl Into<StackIdxConv>) {
2899        let i: StackIdx = idx.into().0;
2900        let slot = i.0 as usize;
2901        if slot < self.stack.len() {
2902            self.stack[slot].val = LuaValue::Nil;
2903        }
2904    }
2905    /// Resizes the underlying stack vector to `size` slots, padding new slots
2906    /// with `StackValue::default()` (which is `Nil`). Returns `Ok(())` on
2907    /// success — `Vec::resize_with` in Rust does not have a fallible path the
2908    /// way `luaM_reallocvector` does in C, so the `Result` is here for
2909    /// signature parity with future fallible allocators.
2910    ///
2911    /// newsize+EXTRA_STACK, StackValue)`.
2912    pub fn stack_resize(&mut self, size: usize) -> Result<(), LuaError> {
2913        self.stack.resize_with(size, StackValue::default);
2914        Ok(())
2915    }
2916    pub fn stack_available(&mut self) -> usize {
2917        (self.stack_last.0 as usize).saturating_sub(self.top.0 as usize)
2918    }
2919    pub fn check_stack(&mut self, n: i32) -> Result<(), LuaError> {
2920        let free = (self.stack_last.0 as i32) - (self.top.0 as i32);
2921        if free <= n {
2922            self.grow_stack(n, true)?;
2923        }
2924        Ok(())
2925    }
2926    /// Inherent method wrapper around the free function `do_::grow_stack`,
2927    /// preserving the historical `Result<(), LuaError>` signature used by
2928    /// `check_stack` and other VM call sites. The bool returned by the
2929    /// underlying implementation distinguishes soft failure (when
2930    /// `raise_error` is false) from success; that distinction is dropped here
2931    /// because every current caller passes `raise_error = true` and only
2932    /// cares about error propagation.
2933    ///
2934    pub fn grow_stack(&mut self, n: i32, raise_error: bool) -> Result<(), LuaError> {
2935        crate::do_::grow_stack(self, n, raise_error).map(|_| ())
2936    }
2937
2938    #[inline(always)]
2939    pub fn get_ci(&self, idx: CallInfoIdx) -> &CallInfo {
2940        &self.call_info[idx.as_usize()]
2941    }
2942    #[inline(always)]
2943    pub fn get_ci_mut(&mut self, idx: CallInfoIdx) -> &mut CallInfo {
2944        &mut self.call_info[idx.as_usize()]
2945    }
2946    #[inline(always)]
2947    pub fn current_call_info(&self) -> &CallInfo {
2948        &self.call_info[self.ci.as_usize()]
2949    }
2950    #[inline(always)]
2951    pub fn current_call_info_mut(&mut self) -> &mut CallInfo {
2952        let i = self.ci.as_usize();
2953        &mut self.call_info[i]
2954    }
2955    #[inline(always)]
2956    pub fn current_ci_idx(&self) -> CallInfoIdx {
2957        self.ci
2958    }
2959    pub fn call_stack_mut(&mut self) -> &mut Vec<CallInfo> {
2960        &mut self.call_info
2961    }
2962    #[inline(always)]
2963    pub fn next_ci(&mut self) -> Result<CallInfoIdx, LuaError> {
2964        let idx = match self.call_info[self.ci.as_usize()].next {
2965            Some(idx) => idx,
2966            None => extend_ci(self),
2967        };
2968        self.call_info[idx.as_usize()].tailcalls = 0;
2969        Ok(idx)
2970    }
2971
2972    /// Records that a Lua tail call reused the frame at `ci`, so the 5.1
2973    /// `debug.getstack` level walk can synthesize the `(tail call)` frames the
2974    /// 5.1 debug model exposes. Gated to 5.1: 5.2+ dropped synthetic tail frames
2975    /// for the `istailcall` flag and never read `tailcalls`, so on those versions
2976    /// this is a single version compare and return — the hot tail-call path is
2977    /// otherwise byte-identical.
2978    #[inline(always)]
2979    pub fn note_lua_tailcall(&mut self, ci: CallInfoIdx) {
2980        if self.global().lua_version == lua_types::LuaVersion::V51 {
2981            self.call_info[ci.as_usize()].tailcalls =
2982                self.call_info[ci.as_usize()].tailcalls.saturating_add(1);
2983        }
2984    }
2985    #[inline(always)]
2986    pub fn prev_ci(&self, idx: CallInfoIdx) -> Option<CallInfoIdx> {
2987        self.call_info[idx.as_usize()].previous
2988    }
2989    pub fn get_prev_ci(&self, idx: CallInfoIdx) -> Option<&CallInfo> {
2990        self.call_info[idx.as_usize()]
2991            .previous
2992            .map(|p| &self.call_info[p.as_usize()])
2993    }
2994    #[inline(always)]
2995    pub fn is_base_ci(&self, idx: CallInfoIdx) -> bool {
2996        idx.as_usize() == 0
2997    }
2998    #[inline(always)]
2999    pub fn is_current_ci(&self, idx: CallInfoIdx) -> bool {
3000        idx == self.ci
3001    }
3002    pub fn ci_next_func(&self, idx: CallInfoIdx) -> StackIdx {
3003        let next = self.call_info[idx.as_usize()]
3004            .next
3005            .expect("ci_next_func: no next CallInfo");
3006        self.call_info[next.as_usize()].func
3007    }
3008    #[inline(always)]
3009    pub fn ci_top(&self, idx: CallInfoIdx) -> StackIdx {
3010        self.call_info[idx.as_usize()].top
3011    }
3012    /// Hot-loop trap read: `(callstatus & CIST_TRAP) != 0`, one mask with no
3013    /// enum-discriminant branch. A C frame never has `CIST_TRAP` set, so this
3014    /// returns `false` for C frames identically to the pre-flatten fallback,
3015    /// without needing a frame-kind branch — that is the whole point of T2-C2.
3016    #[inline(always)]
3017    pub fn ci_trap(&mut self, idx: CallInfoIdx) -> bool {
3018        self.call_info[idx.as_usize()].trap()
3019    }
3020    #[inline(always)]
3021    pub fn ci_savedpc(&self, idx: CallInfoIdx) -> u32 {
3022        self.call_info[idx.as_usize()].saved_pc()
3023    }
3024    #[inline(always)]
3025    pub fn set_ci_savedpc(&mut self, idx: CallInfoIdx, pc: u32) {
3026        self.call_info[idx.as_usize()].set_saved_pc(pc);
3027    }
3028    #[inline(always)]
3029    pub fn set_ci_previous(&mut self, idx: CallInfoIdx) {
3030        self.ci = self.call_info[idx.as_usize()]
3031            .previous
3032            .expect("set_ci_previous: returning frame has no previous CallInfo");
3033    }
3034    #[inline(always)]
3035    pub fn ci_previous(&self, idx: CallInfoIdx) -> Option<CallInfoIdx> {
3036        self.call_info[idx.as_usize()].previous
3037    }
3038    #[inline(always)]
3039    pub fn ci_adjust_func(&mut self, idx: CallInfoIdx, delta: i32) {
3040        let ci = &mut self.call_info[idx.as_usize()];
3041        ci.func = StackIdx((ci.func.0 as i32 - delta) as u32);
3042    }
3043    #[inline(always)]
3044    pub fn ci_base(&self, idx: CallInfoIdx) -> StackIdx {
3045        self.call_info[idx.as_usize()].func + 1
3046    }
3047    #[inline(always)]
3048    pub fn ci_is_fresh(&self, idx: CallInfoIdx) -> bool {
3049        (self.call_info[idx.as_usize()].callstatus & CIST_FRESH) != 0
3050    }
3051    #[inline(always)]
3052    pub fn ci_lua_closure(
3053        &self,
3054        idx: CallInfoIdx,
3055    ) -> Option<GcRef<lua_types::closure::LuaLClosure>> {
3056        let func_idx = self.call_info[idx.as_usize()].func;
3057        match self.stack.get(func_idx.0 as usize).map(|slot| slot.val) {
3058            Some(LuaValue::Function(lua_types::closure::LuaClosure::Lua(cl))) => Some(cl),
3059            _ => None,
3060        }
3061    }
3062    #[inline(always)]
3063    pub fn ci_nextraargs(&self, idx: CallInfoIdx) -> i32 {
3064        self.call_info[idx.as_usize()].nextra_args()
3065    }
3066    #[inline(always)]
3067    pub fn ci_nres(&self, idx: CallInfoIdx) -> i32 {
3068        self.call_info[idx.as_usize()].u2.value
3069    }
3070    #[inline(always)]
3071    pub fn ci_nres_set(&mut self, idx: CallInfoIdx, n: i32) {
3072        self.call_info[idx.as_usize()].u2.value = n;
3073    }
3074    #[inline(always)]
3075    pub fn ci_nresults(&self, idx: CallInfoIdx) -> i32 {
3076        self.call_info[idx.as_usize()].nresults as i32
3077    }
3078    pub fn ci_prev_instruction(&self, idx: CallInfoIdx) -> lua_types::opcode::Instruction {
3079        let pc = self.call_info[idx.as_usize()].saved_pc();
3080        let cl = self
3081            .ci_lua_closure(idx)
3082            .expect("ci_prev_instruction: CallInfo does not hold a Lua closure");
3083        cl.proto.code[(pc - 1) as usize]
3084    }
3085    pub fn ci_prev2_instruction(&self, idx: CallInfoIdx) -> lua_types::opcode::Instruction {
3086        let pc = self.call_info[idx.as_usize()].saved_pc();
3087        let cl = self
3088            .ci_lua_closure(idx)
3089            .expect("ci_prev2_instruction: CallInfo does not hold a Lua closure");
3090        cl.proto.code[(pc - 2) as usize]
3091    }
3092    pub fn ci_skip_next_instruction(&mut self, idx: CallInfoIdx) {
3093        let pc = self.call_info[idx.as_usize()].saved_pc();
3094        self.call_info[idx.as_usize()].set_saved_pc(pc + 1);
3095    }
3096    pub fn ci_step_pc_back(&mut self, idx: CallInfoIdx) {
3097        let pc = self.call_info[idx.as_usize()].saved_pc();
3098        self.call_info[idx.as_usize()].set_saved_pc(pc - 1);
3099    }
3100    pub fn get_ci_pcrel(&mut self, idx: CallInfoIdx) -> u32 {
3101        self.call_info[idx.as_usize()].saved_pc().saturating_sub(1)
3102    }
3103    pub fn get_ci_u2_funcidx(&mut self, idx: CallInfoIdx) -> i32 {
3104        self.call_info[idx.as_usize()].u2.value
3105    }
3106    pub fn get_ci_u2_nres(&mut self, idx: CallInfoIdx) -> i32 {
3107        self.call_info[idx.as_usize()].u2.value
3108    }
3109    pub fn get_ci_u2_nyield(&mut self, idx: CallInfoIdx) -> i32 {
3110        self.call_info[idx.as_usize()].u2.value
3111    }
3112    pub fn get_ci_vararg_info(&mut self, idx: CallInfoIdx) -> (bool, i32, i32) {
3113        let nextraargs = self.call_info[idx.as_usize()].nextra_args();
3114        match self.ci_lua_closure(idx) {
3115            Some(cl) => (cl.proto.is_vararg, nextraargs, cl.proto.numparams as i32),
3116            None => (false, nextraargs, 0),
3117        }
3118    }
3119    pub fn get_ci_lua_proto_numparams(&mut self, idx: CallInfoIdx) -> u8 {
3120        self.ci_lua_closure(idx)
3121            .map(|cl| cl.proto.numparams)
3122            .unwrap_or(0)
3123    }
3124    pub fn set_ci_u2_nres(&mut self, idx: CallInfoIdx, n: i32) {
3125        self.call_info[idx.as_usize()].u2.value = n;
3126    }
3127    pub fn set_ci_u2_nyield(&mut self, idx: CallInfoIdx, n: i32) {
3128        self.call_info[idx.as_usize()].u2.value = n;
3129    }
3130    pub fn set_ci_transfer_info(&mut self, idx: CallInfoIdx, ftransfer: u16, ntransfer: u16) {
3131        let ci = &mut self.call_info[idx.as_usize()];
3132        ci.u2.ftransfer = ftransfer;
3133        ci.u2.ntransfer = ntransfer;
3134    }
3135    pub fn shrink_ci(&mut self) {
3136        shrink_ci(self)
3137    }
3138    pub fn check_c_stack(&mut self) -> Result<(), LuaError> {
3139        check_c_stack(self)
3140    }
3141
3142    pub fn status(&mut self) -> LuaStatus {
3143        LuaStatus::from_raw(self.status as i32)
3144    }
3145    pub fn errfunc(&mut self) -> isize {
3146        self.errfunc
3147    }
3148    pub fn old_pc(&mut self) -> u32 {
3149        self.oldpc
3150    }
3151    pub fn set_old_pc(&mut self, pc: u32) {
3152        self.oldpc = pc;
3153    }
3154    pub fn set_oldpc(&mut self, pc: u32) {
3155        self.oldpc = pc;
3156    }
3157    pub fn _hook_call_noargs(&mut self) {}
3158    pub fn hook(&self) -> Option<&Box<dyn FnMut(&mut LuaState, &crate::debug::LuaDebug)>> {
3159        self.hook.as_ref()
3160    }
3161    pub fn has_hook(&mut self) -> bool {
3162        self.hook.is_some()
3163    }
3164    pub fn hook_count(&mut self) -> i32 {
3165        self.hookcount
3166    }
3167    pub fn set_hook_count(&mut self, n: i32) {
3168        self.hookcount = n;
3169    }
3170    pub fn hook_mask(&self) -> u8 {
3171        self.hookmask
3172    }
3173    pub fn set_hook_mask(&mut self, m: u8) {
3174        self.hookmask = m;
3175    }
3176    pub fn base_hook_count(&self) -> i32 {
3177        self.basehookcount
3178    }
3179    pub fn set_base_hook_count(&mut self, n: i32) {
3180        self.basehookcount = n;
3181    }
3182    pub fn set_hook(&mut self, h: Option<Box<dyn FnMut(&mut LuaState, &crate::debug::LuaDebug)>>) {
3183        self.hook = h;
3184    }
3185    /// Fire a count or line hook on the currently executing frame.
3186    ///
3187    /// C-Lua's `luaG_traceexec` is the sole caller of `luaD_hook` for count and
3188    /// line events, and it relies on `L->ci` being the same Lua frame after the
3189    /// hook as before it: the bytecode dispatch loop in `luaV_execute` reads
3190    /// `L->ci` (via `trace_exec`) on the next instruction and writes its
3191    /// `savedpc`, which is only valid on a Lua frame. C maintains that invariant
3192    /// implicitly — the unprotected `lua_call` inside the hook restores `L->ci`
3193    /// via `luaD_poscall` on success, and on a hook error it `longjmp`s straight
3194    /// to the nearest protected boundary, which resets `L->ci`, so a corrupted
3195    /// `ci` never re-enters the dispatch loop.
3196    ///
3197    /// Our port reports hook-callback errors through a different path that can
3198    /// leave `self.ci` advanced to the hook's own (C) frame instead of unwinding
3199    /// it, so the invariant the dispatch loop depends on would be broken. Saving
3200    /// `self.ci` here and restoring it after the hook reasserts exactly the
3201    /// invariant C guarantees, so the next `trace_exec` writes `savedpc` on the
3202    /// Lua frame it is actually executing rather than panicking on a C frame.
3203    pub fn call_hook_event(&mut self, event: i32, line: i32) -> Result<(), LuaError> {
3204        let saved_ci = self.ci;
3205        let r = crate::do_::hook(self, event, line, 0, 0);
3206        self.ci = saved_ci;
3207        r
3208    }
3209
3210    pub fn registry_value(&self) -> LuaValue {
3211        self.global().l_registry.clone()
3212    }
3213    pub fn registry_get(&self, key: usize) -> LuaValue {
3214        let reg = self.global().l_registry.clone();
3215        match reg {
3216            LuaValue::Table(t) => t.get(&LuaValue::Int(key as i64)),
3217            _ => LuaValue::Nil,
3218        }
3219    }
3220
3221    pub fn new_string(&mut self, bytes: &[u8]) -> Result<GcRef<LuaString>, LuaError> {
3222        self.intern_or_create_str(bytes)
3223    }
3224
3225    // ── State-owned allocation API ──────────────────────────────────────────
3226    // These methods are the canonical allocation surface. They wrap
3227    // `GcRef::new`, which allocates on the currently active heap. Callers
3228    // must reach them through `&mut LuaState`, which mirrors C-Lua's
3229    // requirement that every allocation passes `lua_State *L`.
3230
3231    /// Allocate a new Lua function prototype.
3232    ///
3233    /// The caller is expected to populate fields on the returned value while
3234    /// it has no other outstanding references (immediately after allocation).
3235    pub fn new_proto(&mut self) -> GcRef<LuaProto> {
3236        self.mark_gc_check_needed();
3237        GcRef::new(LuaProto::placeholder())
3238    }
3239
3240    /// Allocate a Lua-side closure (compiled function + upvalue slots).
3241    pub fn new_lclosure(&mut self, proto: GcRef<LuaProto>, nupvals: usize) -> GcRef<LuaClosureLua> {
3242        self.mark_gc_check_needed();
3243        let mut upvals = Vec::with_capacity(nupvals);
3244        for _ in 0..nupvals {
3245            upvals.push(std::cell::Cell::new(self.new_upval_closed(LuaValue::Nil)));
3246        }
3247        let upvals = upvals.into_boxed_slice();
3248        let closure = GcRef::new(LuaClosureLua { proto, upvals });
3249        closure.account_buffer(closure.buffer_bytes() as isize);
3250        closure
3251    }
3252
3253    /// Allocate a closed upvalue holding the given value.
3254    pub fn new_upval_closed(&mut self, v: LuaValue) -> GcRef<UpVal> {
3255        self.mark_gc_check_needed();
3256        GcRef::new(UpVal::closed(v))
3257    }
3258
3259    /// Allocate an open upvalue referring to a thread's stack slot.
3260    pub fn new_upval_open(&mut self, thread_id: u64, level: StackIdx) -> GcRef<UpVal> {
3261        self.mark_gc_check_needed();
3262        self.legacy_open_upval_touched.set(true);
3263        GcRef::new(UpVal::open(thread_id, level))
3264    }
3265    /// Mirrors `luaS_newlstr`: short strings are interned globally so equal
3266    /// content shares a single TString; long strings (> LUAI_MAXSHORTLEN = 40)
3267    /// always create a fresh TString without interning. This is what lets
3268    /// `string.format("%p", "long" .. "concat")` differ from a same-content
3269    /// literal — concat must produce a new object even when the literal already
3270    /// lives in the lexer's constant pool.
3271    pub fn intern_or_create_str(&mut self, bytes: &[u8]) -> Result<GcRef<LuaString>, LuaError> {
3272        self.intern_str(bytes)
3273    }
3274    /// Allocates a full userdata with `size` payload bytes and `nuvalue` nil
3275    /// user-value slots, returning the `GcRef` without pushing it. Mirrors C's
3276    /// `lua_newuserdatauv` allocation step; the untyped counterpart of
3277    /// [`Self::new_userdata_typed`] (no `__name`-carrying metatable is
3278    /// attached). Callers such as `api::new_userdata_uv` push the result and run
3279    /// the GC step.
3280    pub fn new_userdata(
3281        &mut self,
3282        size: usize,
3283        nuvalue: usize,
3284    ) -> Result<GcRef<LuaUserData>, LuaError> {
3285        debug_assert!(nuvalue < u16::MAX as usize, "invalid value");
3286        self.mark_gc_check_needed();
3287        let u = GcRef::new(LuaUserData {
3288            data: vec![0u8; size].into_boxed_slice(),
3289            uv: std::cell::RefCell::new(vec![LuaValue::Nil; nuvalue]),
3290            metatable: std::cell::RefCell::new(None),
3291            host_value: std::cell::RefCell::new(None),
3292        });
3293        u.account_buffer(u.buffer_bytes() as isize);
3294        Ok(u)
3295    }
3296
3297    /// Registers a C function pointer `f` in the per-state `c_functions` table
3298    /// and returns its `LuaCFnPtr` index. `LuaClosure::LightC`/`LuaCClosure`
3299    /// carry this index rather than a raw pointer because `lua_types` cannot
3300    /// reference `LuaState`. When `dedup` is set (upvalue-less light C
3301    /// functions) an already-registered identical `f` is reused; otherwise a
3302    /// fresh slot is always allocated, since closures with upvalues must not
3303    /// share identity.
3304    pub fn register_c_function(&mut self, f: LuaCFunction, dedup: bool) -> LuaCFnPtr {
3305        let mut g = self.global_mut();
3306        if dedup {
3307            if let Some(i) = g.c_functions.iter().position(|existing| {
3308                existing
3309                    .as_bare()
3310                    .is_some_and(|existing| std::ptr::fn_addr_eq(existing, f))
3311            }) {
3312                return i;
3313            }
3314        }
3315        let i = g.c_functions.len();
3316        g.c_functions.push(LuaCallable::bare(f));
3317        i
3318    }
3319
3320    /// Creates a C closure over `f` with `n` (nil-initialised) upvalue slots and
3321    /// returns it without pushing. Mirrors `lua_pushcclosure`'s object step:
3322    /// `n == 0` yields a light C function, `n > 0` a full C closure. The stack
3323    /// filling of upvalues is the caller's responsibility (see
3324    /// `api::push_cclosure`).
3325    ///
3326    /// `n` is validated against `0..=MAX_UPVAL` before anything is registered,
3327    /// so an out-of-range count errors without polluting the `c_functions`
3328    /// table.
3329    pub fn new_c_closure(&mut self, f: LuaCFunction, n: i32) -> Result<LuaClosure, LuaError> {
3330        if n < 0 || n as i64 > crate::api::MAX_UPVAL as i64 {
3331            return Err(LuaError::runtime(format_args!(
3332                "C closure upvalue count {n} out of range (0..={})",
3333                crate::api::MAX_UPVAL
3334            )));
3335        }
3336        let idx = self.register_c_function(f, n == 0);
3337        if n == 0 {
3338            return Ok(LuaClosure::LightC(idx));
3339        }
3340        self.mark_gc_check_needed();
3341        let cl = LuaClosure::C(GcRef::new(lua_types::closure::LuaCClosure {
3342            func: idx,
3343            upvalues: std::cell::RefCell::new(vec![LuaValue::Nil; n as usize]),
3344        }));
3345        if let LuaClosure::C(ccl) = &cl {
3346            ccl.account_buffer(ccl.buffer_bytes() as isize);
3347        }
3348        Ok(cl)
3349    }
3350    pub fn push_closure(
3351        &mut self,
3352        proto_idx: usize,
3353        ci: CallInfoIdx,
3354        base: StackIdx,
3355        ra: StackIdx,
3356    ) -> Result<(), LuaError> {
3357        let parent_cl = self
3358            .ci_lua_closure(ci)
3359            .expect("push_closure: current frame is not a Lua closure");
3360        let child_proto = parent_cl.proto.p[proto_idx].clone();
3361        let nup = child_proto.upvalues.len();
3362        let mut upvals: Vec<std::cell::Cell<GcRef<UpVal>>> = Vec::with_capacity(nup);
3363        for i in 0..nup {
3364            let desc = &child_proto.upvalues[i];
3365            let uv = if desc.instack {
3366                let level = base + desc.idx as i32;
3367                crate::func::find_upval(self, level)
3368            } else {
3369                parent_cl.upval(desc.idx as usize)
3370            };
3371            upvals.push(std::cell::Cell::new(uv));
3372        }
3373        // LUA_COMPAT closure caching (5.2/5.3 only): if the last closure built
3374        // from this proto captured the identical upvalues, reuse it so the two
3375        // compare `==` (C's `getcached`). 5.1 never cached; 5.4/5.5 removed it.
3376        let cache_enabled = matches!(
3377            self.global().lua_version,
3378            lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
3379        );
3380        if cache_enabled {
3381            if let Some(cached) = child_proto.cache.borrow().as_ref() {
3382                if cached.upvals.len() == nup
3383                    && (0..nup).all(|i| GcRef::ptr_eq(&cached.upvals[i].get(), &upvals[i].get()))
3384                {
3385                    let reused = cached.clone();
3386                    self.set_at(ra, LuaValue::Function(LuaClosure::Lua(reused)));
3387                    return Ok(());
3388                }
3389            }
3390        }
3391        // Upvals are pre-populated from the parent frame here, so this builds
3392        // the closure directly rather than through `state.new_lclosure`,
3393        // which would fill fresh Nil upvals and drop the captured bindings.
3394        self.mark_gc_check_needed();
3395        let new_cl = GcRef::new(LuaClosureLua {
3396            proto: child_proto.clone(),
3397            upvals: upvals.into_boxed_slice(),
3398        });
3399        new_cl.account_buffer(new_cl.buffer_bytes() as isize);
3400        if cache_enabled {
3401            *child_proto.cache.borrow_mut() = Some(new_cl.clone());
3402        }
3403        self.set_at(ra, LuaValue::Function(LuaClosure::Lua(new_cl)));
3404        Ok(())
3405    }
3406    pub fn new_tbc_upval(&mut self, idx: StackIdx) -> Result<(), LuaError> {
3407        crate::func::new_tbc_upval(self, idx)
3408    }
3409
3410    /// Read an open or closed upvalue.
3411    ///
3412    /// Closed upvalues own their value and read trivially. Open upvalues
3413    /// point at a stack slot on the home thread that captured them.
3414    ///
3415    /// Resolution order for an open upvalue whose home is not the current
3416    /// thread:
3417    ///
3418    /// 1. If the home thread is registered in `GlobalState::threads` and
3419    ///    its `RefCell` is currently borrowable, read straight from its
3420    ///    stack. This is the path used when the main thread reads a
3421    ///    closure created inside a now-suspended coroutine, or when one
3422    ///    coroutine reads an upvalue homed on a sibling suspended
3423    ///    coroutine.
3424    /// 2. Otherwise fall back to `GlobalState::cross_thread_upvals`. This
3425    ///    is the path used while inside a `coroutine.resume`: the parent
3426    ///    thread's `LuaState` is held by an outer `&mut` and is not
3427    ///    reachable through any `Rc<RefCell<_>>`, so `aux_resume`
3428    ///    snapshots the parent's open upvalues into the mirror across the
3429    ///    resume boundary.
3430    #[inline(always)]
3431    pub fn upvalue_get(&self, cl: &GcRef<LuaClosureLua>, n: usize) -> LuaValue {
3432        let uv = cl.upval(n);
3433        let (thread_id, idx) = match uv.try_open_payload() {
3434            Some(p) => p,
3435            None => return uv.closed_value(),
3436        };
3437        let current = self.cached_thread_id;
3438        if thread_id == current {
3439            return self.stack[idx.0 as usize].val;
3440        }
3441        self.upvalue_get_cross_thread(thread_id, idx)
3442    }
3443
3444    #[cold]
3445    #[inline(never)]
3446    fn upvalue_get_cross_thread(&self, tid: u64, idx: StackIdx) -> LuaValue {
3447        let entry_rc = {
3448            let g = self.global();
3449            g.threads.get(&tid).map(|e| e.state.clone())
3450        };
3451        if let Some(rc) = entry_rc {
3452            if let Ok(home_state) = rc.try_borrow() {
3453                return home_state.get_at(idx);
3454            }
3455        }
3456        let g = self.global();
3457        match g.cross_thread_upvals.get(&(tid, idx)) {
3458            Some(v) => *v,
3459            None => LuaValue::Nil,
3460        }
3461    }
3462    /// Write an open or closed upvalue.
3463    ///
3464    /// Mirrors [`upvalue_get`]: open upvalues homed on the current thread
3465    /// write through `self.stack`. For cross-thread open upvalues, the
3466    /// home thread's stack is written directly when its `RefCell` is
3467    /// borrowable, otherwise the write lands in
3468    /// `GlobalState::cross_thread_upvals` (the active-resume case where
3469    /// the home thread is borrow-locked further up the call stack).
3470    #[inline(always)]
3471    pub fn upvalue_set(
3472        &mut self,
3473        cl: &GcRef<LuaClosureLua>,
3474        n: usize,
3475        val: LuaValue,
3476    ) -> Result<(), LuaError> {
3477        let uv = cl.upval(n);
3478        match uv.try_open_payload() {
3479            Some((thread_id, idx)) => {
3480                let current = self.cached_thread_id;
3481                if thread_id == current {
3482                    self.stack[idx.0 as usize].val = val;
3483                } else {
3484                    self.upvalue_set_cross_thread(thread_id, idx, val)?;
3485                }
3486            }
3487            None => {
3488                uv.set_closed_value(val);
3489            }
3490        }
3491        if val.is_collectable() {
3492            self.gc_barrier_upval(&uv, &val);
3493        }
3494        Ok(())
3495    }
3496
3497    #[cold]
3498    #[inline(never)]
3499    fn upvalue_set_cross_thread(
3500        &mut self,
3501        tid: u64,
3502        idx: StackIdx,
3503        val: LuaValue,
3504    ) -> Result<(), LuaError> {
3505        let entry_rc = {
3506            let g = self.global();
3507            g.threads.get(&tid).map(|e| e.state.clone())
3508        };
3509        if let Some(rc) = entry_rc {
3510            if let Ok(mut home_state) = rc.try_borrow_mut() {
3511                home_state.set_at(idx, val);
3512                return Ok(());
3513            }
3514        }
3515        let mut g = self.global_mut();
3516        g.cross_thread_upvals.insert((tid, idx), val);
3517        Ok(())
3518    }
3519
3520    pub fn protected_call_raw(
3521        &mut self,
3522        func: StackIdx,
3523        nresults: i32,
3524        errfunc: StackIdx,
3525    ) -> Result<(), LuaError> {
3526        let ef = errfunc.0 as isize;
3527        let status = crate::do_::pcall(self, |s| s.call_no_yield(func, nresults), func, ef);
3528        match status {
3529            LuaStatus::Ok => Ok(()),
3530            LuaStatus::ErrSyntax => {
3531                let err_val = self.get_at(func);
3532                self.set_top(func);
3533                Err(LuaError::Syntax(err_val))
3534            }
3535            LuaStatus::Yield => {
3536                self.set_top(func);
3537                Err(LuaError::Yield)
3538            }
3539            _ => {
3540                let err_val = self.get_at(func);
3541                self.set_top(func);
3542                Err(LuaError::Runtime(err_val))
3543            }
3544        }
3545    }
3546    pub fn protected_parser(
3547        &mut self,
3548        z: crate::zio::ZIO,
3549        name: &[u8],
3550        mode: Option<&[u8]>,
3551    ) -> LuaStatus {
3552        crate::do_::protected_parser(self, z, name, mode)
3553    }
3554    pub fn do_call(&mut self, func: StackIdx, nresults: i32) -> Result<(), LuaError> {
3555        crate::do_::call(self, func, nresults)
3556    }
3557    pub fn do_call_no_yield(&mut self, func: StackIdx, nresults: i32) -> Result<(), LuaError> {
3558        crate::do_::callnoyield(self, func, nresults)
3559    }
3560    pub fn call_no_yield(&mut self, func: StackIdx, nresults: i32) -> Result<(), LuaError> {
3561        crate::do_::callnoyield(self, func, nresults)
3562    }
3563    pub fn call_at(&mut self, func: StackIdx, nresults: i32) -> Result<(), LuaError> {
3564        crate::do_::call(self, func, nresults)
3565    }
3566    #[inline(always)]
3567    pub fn call_known_c_at(&mut self, func: StackIdx, nresults: i32) -> Result<bool, LuaError> {
3568        crate::do_::call_known_c(self, func, nresults)
3569    }
3570    #[inline(always)]
3571    pub fn precall(
3572        &mut self,
3573        func: StackIdx,
3574        nresults: i32,
3575    ) -> Result<Option<CallInfoIdx>, LuaError> {
3576        crate::do_::precall(self, func, nresults)
3577    }
3578    #[inline(always)]
3579    pub fn pretailcall(
3580        &mut self,
3581        ci: CallInfoIdx,
3582        func: StackIdx,
3583        narg1: i32,
3584        delta: i32,
3585    ) -> Result<i32, LuaError> {
3586        crate::do_::pretailcall(self, ci, func, narg1, delta)
3587    }
3588    #[inline(always)]
3589    pub fn poscall<N: TryInto<i32>>(&mut self, ci: CallInfoIdx, nres: N) -> Result<(), LuaError>
3590    where
3591        <N as TryInto<i32>>::Error: std::fmt::Debug,
3592    {
3593        let n = nres.try_into().expect("poscall: nres out of i32 range");
3594        crate::do_::poscall(self, ci, n)
3595    }
3596    pub fn adjust_results(&mut self, nresults: i32) {
3597        const LUA_MULTRET: i32 = -1;
3598        if nresults <= LUA_MULTRET {
3599            let ci_idx = self.ci.as_usize();
3600            if self.call_info[ci_idx].top.0 < self.top.0 {
3601                self.call_info[ci_idx].top = self.top;
3602            }
3603        }
3604    }
3605    pub fn adjust_varargs(
3606        &mut self,
3607        ci: CallInfoIdx,
3608        nfixparams: i32,
3609        cl: &GcRef<lua_types::closure::LuaLClosure>,
3610    ) -> Result<(), LuaError> {
3611        crate::tagmethods::adjust_varargs(self, nfixparams, ci, &cl.0.proto)
3612    }
3613    pub fn get_varargs(&mut self, ci: CallInfoIdx, ra: StackIdx, n: i32) -> Result<i32, LuaError> {
3614        crate::tagmethods::get_varargs(self, ci, ra, n)?;
3615        Ok(0)
3616    }
3617
3618    pub fn close_upvals(&mut self, level: StackIdx) -> Result<(), LuaError> {
3619        crate::func::close_upval(self, level);
3620        Ok(())
3621    }
3622    pub fn close_upvals_status(&mut self, level: StackIdx, _status: i32) -> Result<(), LuaError> {
3623        crate::func::close_upval(self, level);
3624        Ok(())
3625    }
3626    pub fn close_upvals_from_base(&mut self, ci: CallInfoIdx) -> Result<(), LuaError> {
3627        let base = self.ci_base(ci);
3628        crate::func::close_upval(self, base);
3629        Ok(())
3630    }
3631
3632    pub fn arith_op(
3633        &mut self,
3634        op: i32,
3635        p1: &LuaValue,
3636        p2: &LuaValue,
3637    ) -> Result<LuaValue, LuaError> {
3638        let arith_op = match op {
3639            0 => lua_types::arith::ArithOp::Add,
3640            1 => lua_types::arith::ArithOp::Sub,
3641            2 => lua_types::arith::ArithOp::Mul,
3642            3 => lua_types::arith::ArithOp::Mod,
3643            4 => lua_types::arith::ArithOp::Pow,
3644            5 => lua_types::arith::ArithOp::Div,
3645            6 => lua_types::arith::ArithOp::Idiv,
3646            7 => lua_types::arith::ArithOp::Band,
3647            8 => lua_types::arith::ArithOp::Bor,
3648            9 => lua_types::arith::ArithOp::Bxor,
3649            10 => lua_types::arith::ArithOp::Shl,
3650            11 => lua_types::arith::ArithOp::Shr,
3651            12 => lua_types::arith::ArithOp::Unm,
3652            13 => lua_types::arith::ArithOp::Bnot,
3653            _ => return Err(LuaError::runtime(format_args!("invalid arith op {}", op))),
3654        };
3655        let mut res = LuaValue::Nil;
3656        if crate::object::raw_arith(self, arith_op, p1, p2, &mut res)? {
3657            Ok(res)
3658        } else {
3659            Err(LuaError::arith_error(p1, p2, "perform arithmetic on"))
3660        }
3661    }
3662    pub fn concat(&mut self, n: i32) -> Result<(), LuaError> {
3663        crate::vm::concat(self, n)
3664    }
3665    pub fn less_than(&mut self, l: &LuaValue, r: &LuaValue) -> Result<bool, LuaError> {
3666        crate::vm::less_than(self, l, r)
3667    }
3668    pub fn less_equal(&mut self, l: &LuaValue, r: &LuaValue) -> Result<bool, LuaError> {
3669        crate::vm::less_equal(self, l, r)
3670    }
3671    pub fn equal_obj(&self, _ctx: Option<&LuaValue>, l: &LuaValue, r: &LuaValue) -> bool {
3672        crate::vm::equal_obj(None, l, r).unwrap_or(false)
3673    }
3674    pub fn equal_obj_with_tm(&mut self, l: &LuaValue, r: &LuaValue) -> Result<bool, LuaError> {
3675        crate::vm::equal_obj(Some(self), l, r)
3676    }
3677    pub fn obj_len(&mut self, v: &LuaValue) -> Result<LuaValue, LuaError> {
3678        match v {
3679            LuaValue::Table(_) => {
3680                // Lua 5.1 `#t` ignores a table `__len` metamethod (table
3681                // `__len` is 5.2+); always use the primitive length under V51.
3682                let consult_len_tm =
3683                    !matches!(self.global().lua_version, lua_types::LuaVersion::V51);
3684                let tm = if consult_len_tm {
3685                    let mt = self.table_metatable(v);
3686                    self.fast_tm_table(mt.as_ref(), TagMethod::Len)
3687                } else {
3688                    LuaValue::Nil
3689                };
3690                if matches!(tm, LuaValue::Nil) {
3691                    let n = self.table_length(v)?;
3692                    return Ok(LuaValue::Int(n));
3693                }
3694                self.push(LuaValue::Nil);
3695                let slot = StackIdx(self.top.0 - 1);
3696                crate::tagmethods::call_tm_res(self, tm, v.clone(), v.clone(), slot)?;
3697                Ok(self.pop())
3698            }
3699            LuaValue::Str(s) => Ok(LuaValue::Int(s.len() as i64)),
3700            other => {
3701                let tm = crate::tagmethods::get_tm_by_obj(
3702                    self,
3703                    other,
3704                    crate::tagmethods::TagMethod::Len,
3705                );
3706                if matches!(tm, LuaValue::Nil) {
3707                    let mut msg = b"attempt to get length of a ".to_vec();
3708                    msg.extend_from_slice(&self.obj_type_name(other));
3709                    msg.extend_from_slice(b" value");
3710                    return Err(crate::debug::prefixed_runtime_pub(self, msg));
3711                }
3712                self.push(LuaValue::Nil);
3713                let slot = StackIdx(self.top.0 - 1);
3714                crate::tagmethods::call_tm_res(self, tm, v.clone(), v.clone(), slot)?;
3715                Ok(self.pop())
3716            }
3717        }
3718    }
3719    pub fn obj_to_string(&mut self, idx: i32) -> Result<GcRef<LuaString>, LuaError> {
3720        let slot: StackIdx = if idx > 0 {
3721            let ci_func = self.current_call_info().func;
3722            ci_func + idx
3723        } else {
3724            debug_assert!(idx != 0, "invalid index");
3725            StackIdx((self.top_idx().0 as i32 + idx) as u32)
3726        };
3727        let val = self.get_at(slot);
3728        match val {
3729            LuaValue::Str(s) => Ok(s),
3730            LuaValue::Int(_) | LuaValue::Float(_) => {
3731                let s = crate::object::num_to_string(self, &val)?;
3732                self.set_at(slot, LuaValue::Str(s.clone()));
3733                Ok(s)
3734            }
3735            _ => Err(LuaError::type_error(&val, "convert to string")),
3736        }
3737    }
3738    pub fn coerce_to_string(&mut self, idx: StackIdx) -> Result<GcRef<LuaString>, LuaError> {
3739        let val = self.get_at(idx);
3740        match val {
3741            LuaValue::Str(s) => Ok(s),
3742            LuaValue::Int(_) | LuaValue::Float(_) => {
3743                let s = crate::object::num_to_string(self, &val)?;
3744                self.set_at(idx, LuaValue::Str(s.clone()));
3745                Ok(s)
3746            }
3747            _ => Err(LuaError::type_error(&val, "convert to string")),
3748        }
3749    }
3750    /// Parses `s` as a Lua number, returning `(value, consumed)` on success.
3751    ///
3752    /// `object::str2num` is number-model-blind and yields an integer whenever
3753    /// the text parses as one. The float-only versions (5.1/5.2) have no integer
3754    /// subtype, so a string coercion there is normalised to a float: otherwise
3755    /// `tonumber("10")` would carry an integer payload that diverges from the
3756    /// reference on any path that inspects the subtype.
3757    pub fn str_to_num(&mut self, s: &[u8]) -> Option<(LuaValue, usize)> {
3758        let mut out = LuaValue::Nil;
3759        let float_only =
3760            self.global().lua_version.number_model() == lua_types::NumberModel::FloatOnly;
3761        let sz = if float_only {
3762            crate::object::str2num_float_only(s, &mut out)
3763        } else {
3764            crate::object::str2num(s, &mut out)
3765        };
3766        if sz == 0 {
3767            return None;
3768        }
3769        Some((out, sz))
3770    }
3771
3772    #[inline(always)]
3773    pub fn fast_get(&mut self, t: &LuaValue, k: &LuaValue) -> Result<Option<LuaValue>, LuaError> {
3774        let LuaValue::Table(tbl) = t else {
3775            return Ok(None);
3776        };
3777        let v = tbl.get(k);
3778        if matches!(v, LuaValue::Nil) {
3779            Ok(None)
3780        } else {
3781            Ok(Some(v))
3782        }
3783    }
3784    #[inline(always)]
3785    pub fn fast_get_int(&mut self, t: &LuaValue, k: i64) -> Result<Option<LuaValue>, LuaError> {
3786        let LuaValue::Table(tbl) = t else {
3787            return Ok(None);
3788        };
3789        let v = tbl.get_int(k);
3790        if matches!(v, LuaValue::Nil) {
3791            Ok(None)
3792        } else {
3793            Ok(Some(v))
3794        }
3795    }
3796    #[inline(always)]
3797    pub fn fast_get_short_str(
3798        &mut self,
3799        t: &LuaValue,
3800        k: &LuaValue,
3801    ) -> Result<Option<LuaValue>, LuaError> {
3802        let LuaValue::Table(tbl) = t else {
3803            return Ok(None);
3804        };
3805        let LuaValue::Str(s) = k else {
3806            return Ok(None);
3807        };
3808        let v = tbl.get_short_str(s);
3809        if matches!(v, LuaValue::Nil) {
3810            Ok(None)
3811        } else {
3812            Ok(Some(v))
3813        }
3814    }
3815    #[inline(always)]
3816    pub fn fast_tm_table(&mut self, t: Option<&GcRef<LuaTable>>, tm: TagMethod) -> LuaValue {
3817        let Some(mt) = t else {
3818            return LuaValue::Nil;
3819        };
3820        debug_assert!((tm as u8) <= TagMethod::Eq as u8);
3821        let ename = self.global().tmname[tm as usize].clone();
3822        mt.get_short_str(&ename)
3823    }
3824    pub fn fast_tm_ud(&mut self, u: &GcRef<LuaUserData>, tm: TagMethod) -> LuaValue {
3825        // metatable then index by the interned `__xxx` name.
3826        let mt = u.metatable();
3827        self.fast_tm_table(mt.as_ref(), tm)
3828    }
3829
3830    pub fn table_get_with_tm(&mut self, t: &LuaValue, k: &LuaValue) -> Result<LuaValue, LuaError> {
3831        // Fast path: when the table has no metatable, `__index` can never
3832        // fire — so we can return the raw slot value (Nil if absent) without
3833        // routing through finish_get's push/pop scaffolding. Halves the
3834        // get-hot-path cost on tables without metamethods, which is the
3835        // common case in table.remove/insert shift loops and most user code.
3836        if let LuaValue::Table(tbl) = t {
3837            if !tbl.has_metatable() {
3838                return Ok(tbl.get(k));
3839            }
3840        }
3841        if let Some(v) = self.fast_get(t, k)? {
3842            return Ok(v);
3843        }
3844        let res = self.top_idx();
3845        self.push(LuaValue::Nil);
3846        crate::vm::finish_get(self, t.clone(), k.clone(), res, true, None, None)?;
3847        let value = self.get_at(res);
3848        self.pop();
3849        Ok(value)
3850    }
3851    /// Set `t[k] = v` with `__newindex` metamethod awareness.
3852    ///
3853    /// Fast path: when the table has no metatable, `__newindex` can never
3854    /// fire, so the existence check via `fast_get` is pure waste —
3855    /// `try_raw_set` handles both "key exists" and "key absent" cases via
3856    /// a single lookup internally. Removing the `fast_get` halves the
3857    /// lookups per set on the metamethod-free path (table.remove/insert
3858    /// hot loops, most user code).
3859    ///
3860    /// The GC backward barrier is invoked before the store (with `&v`)
3861    /// instead of after; the barrier only inspects the value's color, not
3862    /// its location, so the order is semantically equivalent to upstream
3863    /// C-Lua and lets us move `v` straight into `table_raw_set` without
3864    /// the extra `v.clone()` that the post-store ordering forced.
3865    #[inline]
3866    pub fn table_set_with_tm(
3867        &mut self,
3868        t: &LuaValue,
3869        k: LuaValue,
3870        v: LuaValue,
3871    ) -> Result<(), LuaError> {
3872        if let LuaValue::Table(tbl) = t {
3873            if !tbl.has_metatable() {
3874                self.gc_table_barrier_back(tbl, &v);
3875                return self.table_raw_set(t, k, v);
3876            }
3877        }
3878        if self.fast_get(t, &k)?.is_some() {
3879            self.gc_value_barrier_back(t, &v);
3880            return self.table_raw_set(t, k, v);
3881        }
3882        crate::vm::finish_set(self, t.clone(), k, v, true, None, None)
3883    }
3884    #[inline]
3885    pub fn table_raw_set(
3886        &mut self,
3887        t: &LuaValue,
3888        k: LuaValue,
3889        v: LuaValue,
3890    ) -> Result<(), LuaError> {
3891        let LuaValue::Table(tbl) = t else {
3892            return Err(LuaError::type_error(t, "index"));
3893        };
3894        let tbl = tbl.clone();
3895        tbl.raw_set(self, k, v)
3896    }
3897    #[inline]
3898    pub fn table_array_set(
3899        &mut self,
3900        t: &LuaValue,
3901        idx: usize,
3902        v: LuaValue,
3903    ) -> Result<(), LuaError> {
3904        let LuaValue::Table(tbl) = t else {
3905            return Err(LuaError::type_error(t, "index"));
3906        };
3907        let tbl = tbl.clone();
3908        tbl.raw_set_int(self, idx as i64 + 1, v)
3909    }
3910    pub fn table_ensure_array(&mut self, t: &LuaValue, n: usize) -> Result<(), LuaError> {
3911        let LuaValue::Table(tbl) = t else {
3912            return Err(LuaError::type_error(t, "index"));
3913        };
3914        if n > tbl.array_len() {
3915            tbl.resize(self, n, 0)?;
3916        }
3917        Ok(())
3918    }
3919    pub fn table_length(&mut self, t: &LuaValue) -> Result<i64, LuaError> {
3920        let LuaValue::Table(tbl) = t else {
3921            return Err(LuaError::type_error(t, "get length of"));
3922        };
3923        Ok(tbl.getn() as i64)
3924    }
3925    pub fn table_metatable(&mut self, v: &LuaValue) -> Option<GcRef<LuaTable>> {
3926        match v {
3927            LuaValue::Table(t) => t.metatable(),
3928            LuaValue::UserData(u) => u.metatable(),
3929            other => {
3930                let idx = other.base_type() as usize;
3931                self.global().mt[idx].clone()
3932            }
3933        }
3934    }
3935    pub fn table_resize(
3936        &mut self,
3937        t: &GcRef<LuaTable>,
3938        na: usize,
3939        nh: usize,
3940    ) -> Result<(), LuaError> {
3941        self.mark_gc_check_needed();
3942        t.resize(self, na, nh)
3943    }
3944    pub fn table_getn(&self, t: &GcRef<LuaTable>) -> i64 {
3945        // C's `luaH_getn` returns a boundary i such that t[i] is present and
3946        // t[i+1] is absent (or 0 if t[1] is absent), found via a binary or
3947        // unbound search over the array part. This instead walks integer
3948        // keys linearly from 1 — each `get_int` call is O(1), but the walk
3949        // itself is O(n) in the boundary rather than C's O(log n).
3950        let mut i: i64 = 1;
3951        loop {
3952            let v = t.get_int(i);
3953            if matches!(v, LuaValue::Nil) {
3954                return i - 1;
3955            }
3956            i += 1;
3957        }
3958    }
3959
3960    pub fn try_bin_tm(
3961        &mut self,
3962        p1: &LuaValue,
3963        p1_idx: Option<StackIdx>,
3964        p2: &LuaValue,
3965        p2_idx: Option<StackIdx>,
3966        res: StackIdx,
3967        tm: lua_types::tagmethod::TagMethod,
3968    ) -> Result<(), LuaError> {
3969        let event = crate::tagmethods::TagMethod::from_u8(tm as u8);
3970        crate::tagmethods::try_bin_tm(self, p1, p1_idx, p2, p2_idx, res, event)
3971    }
3972    pub fn try_bin_i_tm(
3973        &mut self,
3974        p1: &LuaValue,
3975        p1_idx: Option<StackIdx>,
3976        imm: i64,
3977        flip: bool,
3978        res: StackIdx,
3979        tm: lua_types::tagmethod::TagMethod,
3980    ) -> Result<(), LuaError> {
3981        let event = crate::tagmethods::TagMethod::from_u8(tm as u8);
3982        crate::tagmethods::try_bini_tm(self, p1, p1_idx, imm, flip, res, event)
3983    }
3984    pub fn try_bin_assoc_tm(
3985        &mut self,
3986        p1: &LuaValue,
3987        p1_idx: Option<StackIdx>,
3988        p2: &LuaValue,
3989        p2_idx: Option<StackIdx>,
3990        flip: bool,
3991        res: StackIdx,
3992        tm: lua_types::tagmethod::TagMethod,
3993    ) -> Result<(), LuaError> {
3994        let event = crate::tagmethods::TagMethod::from_u8(tm as u8);
3995        crate::tagmethods::try_bin_assoc_tm(self, p1, p1_idx, p2, p2_idx, flip, res, event)
3996    }
3997    pub fn try_concat_tm(&mut self, _p1: &LuaValue, _p2: &LuaValue) -> Result<(), LuaError> {
3998        crate::tagmethods::try_concat_tm(self)
3999    }
4000    pub fn call_tm(
4001        &mut self,
4002        f: LuaValue,
4003        p1: &LuaValue,
4004        p2: &LuaValue,
4005        p3: &LuaValue,
4006    ) -> Result<(), LuaError> {
4007        crate::tagmethods::call_tm(self, f, p1.clone(), p2.clone(), p3.clone())
4008    }
4009    pub fn call_tm_res(
4010        &mut self,
4011        f: LuaValue,
4012        p1: &LuaValue,
4013        p2: &LuaValue,
4014        res: StackIdx,
4015    ) -> Result<(), LuaError> {
4016        crate::tagmethods::call_tm_res(self, f, p1.clone(), p2.clone(), res)
4017    }
4018    pub fn call_tm_res_bool(
4019        &mut self,
4020        f: LuaValue,
4021        p1: &LuaValue,
4022        p2: &LuaValue,
4023    ) -> Result<bool, LuaError> {
4024        let res = self.top_idx();
4025        self.push(LuaValue::Nil);
4026        crate::tagmethods::call_tm_res(self, f, p1.clone(), p2.clone(), res)?;
4027        let result = self.get_at(res).clone();
4028        self.pop();
4029        Ok(!matches!(result, LuaValue::Nil | LuaValue::Bool(false)))
4030    }
4031    pub fn call_order_tm(
4032        &mut self,
4033        p1: &LuaValue,
4034        p2: &LuaValue,
4035        tm: lua_types::tagmethod::TagMethod,
4036    ) -> Result<bool, LuaError> {
4037        let event = crate::tagmethods::TagMethod::from_u8(tm as u8);
4038        crate::tagmethods::call_order_tm(self, p1, p2, event)
4039    }
4040    pub fn call_order_i_tm(
4041        &mut self,
4042        p1: &LuaValue,
4043        v2: i64,
4044        flip: bool,
4045        isfloat: bool,
4046        tm: lua_types::tagmethod::TagMethod,
4047    ) -> Result<bool, LuaError> {
4048        let event = crate::tagmethods::TagMethod::from_u8(tm as u8);
4049        crate::tagmethods::call_orderi_tm(self, p1, v2 as i32, flip, isfloat, event)
4050    }
4051
4052    #[inline(always)]
4053    pub fn proto_code(
4054        &self,
4055        cl: &GcRef<lua_types::closure::LuaLClosure>,
4056        pc: u32,
4057    ) -> lua_types::opcode::Instruction {
4058        cl.proto.code[pc as usize]
4059    }
4060    #[inline(always)]
4061    pub fn proto_const(&self, cl: &GcRef<lua_types::closure::LuaLClosure>, idx: usize) -> LuaValue {
4062        cl.proto.k[idx].clone()
4063    }
4064    /// Hot-path accessor: returns `Some(i)` only when the constant pool entry
4065    /// at `idx` is an `Int`. Avoids the full `LuaValue` clone that
4066    /// `proto_const` performs.
4067    ///
4068    /// arithmetic opcode macros (`op_arithK`).
4069    #[inline(always)]
4070    pub fn proto_const_int(
4071        &self,
4072        cl: &GcRef<lua_types::closure::LuaLClosure>,
4073        idx: usize,
4074    ) -> Option<i64> {
4075        match &cl.proto.k[idx] {
4076            LuaValue::Int(v) => Some(*v),
4077            _ => None,
4078        }
4079    }
4080    /// Hot-path accessor: returns `Some(f)` for `Float(f)` or `Int(i)` (coerced)
4081    /// constants. Avoids the full `LuaValue` clone. Used by the float fast
4082    /// path of `OP_ADDK`/`OP_SUBK`/`OP_MULK`/`OP_DIVK`/`OP_POWK`.
4083    #[inline(always)]
4084    pub fn proto_const_num(
4085        &self,
4086        cl: &GcRef<lua_types::closure::LuaLClosure>,
4087        idx: usize,
4088    ) -> Option<f64> {
4089        match &cl.proto.k[idx] {
4090            LuaValue::Float(f) => Some(*f),
4091            LuaValue::Int(v) => Some(*v as f64),
4092            _ => None,
4093        }
4094    }
4095    pub fn get_proto_instr(&self, ci: CallInfoIdx, pc: u32) -> lua_types::opcode::Instruction {
4096        let cl = self
4097            .ci_lua_closure(ci)
4098            .expect("get_proto_instr: CallInfo does not hold a Lua closure");
4099        cl.proto.code[pc as usize]
4100    }
4101    /// flag as `bool` (C returns `int` 0/1).
4102    ///
4103    /// The C function reads `L->ci` directly, so the `_idx` argument is unused;
4104    /// the VM passes its locally tracked `ci` for symmetry with `trace_exec`.
4105    pub fn trace_call(&mut self, _idx: CallInfoIdx) -> Result<bool, LuaError> {
4106        Ok(crate::debug::trace_call(self)? != 0)
4107    }
4108    /// returning `bool` for the trap flag. `_idx` is unused for the same reason
4109    /// as `trace_call`; `pc` is the 0-based index of the next instruction.
4110    pub fn trace_exec(&mut self, _idx: CallInfoIdx, pc: u32) -> Result<bool, LuaError> {
4111        Ok(crate::debug::trace_exec(self, pc)? != 0)
4112    }
4113    /// Fires the call hook for the frame at `idx`.
4114    ///
4115    /// On Lua 5.1 a tail call reuses the caller's frame but still fires an
4116    /// ordinary `"call"` hook for the callee (the synthetic call event is on the
4117    /// return side, as a `"tail return"`). 5.2+ instead report the call as a
4118    /// `"tail call"` event, which `do_::hookcall` derives from the `CIST_TAIL`
4119    /// callstatus bit. To get the 5.1 naming without disturbing `CIST_TAIL`
4120    /// (which `debug.getinfo` still reads to report `what == "tail"`), the bit is
4121    /// masked off across the `hookcall` call and restored afterwards, so on 5.1
4122    /// the event is always `LUA_HOOKCALL`. 5.2+ takes the unchanged delegation.
4123    pub fn hook_call(&mut self, idx: CallInfoIdx) -> Result<(), LuaError> {
4124        if self.global().lua_version == lua_types::LuaVersion::V51 {
4125            let had_tail = self.call_info[idx.as_usize()].callstatus & CIST_TAIL;
4126            self.call_info[idx.as_usize()].callstatus &= !CIST_TAIL;
4127            let r = crate::do_::hookcall(self, idx);
4128            self.call_info[idx.as_usize()].callstatus |= had_tail;
4129            return r;
4130        }
4131        crate::do_::hookcall(self, idx)
4132    }
4133    #[inline(always)]
4134    fn gc_step_flags(&self) -> Option<(bool, bool)> {
4135        let g = self.global();
4136        if !g.is_gc_running() {
4137            return None;
4138        }
4139        let should_collect = g.heap.would_collect();
4140        let has_finalizers = g.finalizers.has_to_be_finalized();
4141        if should_collect || has_finalizers {
4142            Some((should_collect, has_finalizers))
4143        } else {
4144            None
4145        }
4146    }
4147
4148    #[inline(always)]
4149    fn should_check_gc(&mut self) -> bool {
4150        if self.gc_check_needed {
4151            return true;
4152        }
4153        if self.global().finalizers.has_to_be_finalized() {
4154            self.gc_check_needed = true;
4155            return true;
4156        }
4157        false
4158    }
4159
4160    #[inline(always)]
4161    pub(crate) fn mark_gc_check_needed(&mut self) {
4162        self.gc_check_needed = true;
4163    }
4164
4165    /// The stack prefix the GC must treat as live: `[0 .. gc_trace_bound())`.
4166    ///
4167    /// C's `traversethread` walks exactly `[stack .. top)` (`lgc.c`). The
4168    /// companion invariant is that `top` covers every live slot at every
4169    /// point a collect can run: C functions keep `top` exact at all times,
4170    /// and lvm.c's Protect sites raise it (`savestate`: `top = ci->top`)
4171    /// before any mid-opcode operation that can collect. Checkpoints whose
4172    /// C original runs under Protect must therefore do the same top fixup
4173    /// at the call site (e.g. `get_varargs`). Widening the bound here to
4174    /// `ci.top` instead was tried and rejected: every suspended frame's
4175    /// reserved slice stays traced forever, and the over-retention drives
4176    /// the generational pacer into permanent re-collection (db.lua's
4177    /// line-hook section went from seconds to timeout).
4178    pub fn gc_trace_bound(&self) -> usize {
4179        (self.top.0 as usize).min(self.stack.len())
4180    }
4181
4182    /// Nil this thread's dead stack slice `[gc_trace_bound() ..
4183    /// stack.len())`. C clears the equivalent slice in `traversethread`'s
4184    /// atomic phase (`lgc.c`: `setnilvalue` from `top` to `stack_last +
4185    /// EXTRA_STACK`). Without the clear, a slot that was above the bound at
4186    /// one collect (its object swept) and drifts back under a raised bound
4187    /// later feeds a dangling GcRef to the marker — #140 bug B.
4188    pub fn clear_dead_stack_tail(&mut self) {
4189        let bound = self.gc_trace_bound();
4190        for slot in &mut self.stack[bound..] {
4191            slot.val = LuaValue::Nil;
4192        }
4193    }
4194
4195    /// Clear the dead stack slice of this thread and of every registered
4196    /// coroutine whose state is borrowable. Threads held by a resume chain
4197    /// or a debug-API guard are rooted via `suspended_parent_stacks`
4198    /// snapshots and skipped here; their tails are cleared at their next
4199    /// reachable collect. Call before any collection runs (C parity:
4200    /// `traversethread`'s atomic clear).
4201    pub fn gc_clear_dead_stack_tails(&mut self) {
4202        self.clear_dead_stack_tail();
4203        let global = self.global.clone();
4204        let g = global.borrow();
4205        for entry in g.threads.values() {
4206            if let Ok(mut t) = entry.state.try_borrow_mut() {
4207                t.clear_dead_stack_tail();
4208            }
4209        }
4210    }
4211
4212    /// `gc_clear_dead_stack_tails` gated on `would_collect` — the one-line
4213    /// companion for call sites that invoke `gc().check_step()` directly.
4214    /// Zero cost when no collection is due.
4215    pub fn gc_pre_collect_clear(&mut self) {
4216        if self.global().heap.would_collect() {
4217            self.gc_clear_dead_stack_tails();
4218        }
4219    }
4220
4221    #[inline(always)]
4222    pub fn gc_check_step(&mut self) {
4223        if !self.allowhook {
4224            return;
4225        }
4226        if !self.should_check_gc() {
4227            return;
4228        }
4229        let Some((should_collect, has_finalizers)) = self.gc_step_flags() else {
4230            self.gc_check_needed = false;
4231            return;
4232        };
4233        if should_collect || has_finalizers {
4234            if should_collect {
4235                self.gc_clear_dead_stack_tails();
4236                self.gc().check_step();
4237            }
4238            crate::api::run_pending_finalizers(self);
4239            self.gc_check_needed = true;
4240        }
4241        let should_keep_checking = {
4242            let g = self.global();
4243            g.heap.would_collect() || g.finalizers.has_to_be_finalized()
4244        };
4245        self.gc_check_needed = should_keep_checking;
4246    }
4247    #[inline(always)]
4248    pub fn gc_cond_step(&mut self) {
4249        if !self.allowhook {
4250            return;
4251        }
4252        if !self.should_check_gc() {
4253            return;
4254        }
4255        let Some((should_collect, has_finalizers)) = self.gc_step_flags() else {
4256            self.gc_check_needed = false;
4257            return;
4258        };
4259        if should_collect || has_finalizers {
4260            if should_collect {
4261                self.gc_clear_dead_stack_tails();
4262                self.gc().check_step();
4263            }
4264            crate::api::run_pending_finalizers(self);
4265            self.gc_check_needed = true;
4266        }
4267        let should_keep_checking = {
4268            let g = self.global();
4269            g.heap.would_collect() || g.finalizers.has_to_be_finalized()
4270        };
4271        self.gc_check_needed = should_keep_checking;
4272    }
4273    pub fn gc_barrier_back(&mut self, t: &dyn std::any::Any, v: &LuaValue) {
4274        self.gc().barrier_back(t, v);
4275    }
4276    #[inline(always)]
4277    pub fn gc_value_barrier_back(&mut self, t: &LuaValue, v: &LuaValue) {
4278        if !v.is_collectable() {
4279            return;
4280        }
4281        if let LuaValue::Table(tbl) = t {
4282            self.gc_table_barrier_back(tbl, v);
4283        } else {
4284            self.gc_barrier_back(t, v);
4285        }
4286    }
4287    #[inline(always)]
4288    pub fn gc_table_barrier_back(&mut self, t: &GcRef<LuaTable>, v: &LuaValue) {
4289        if !v.is_collectable() {
4290            return;
4291        }
4292        self.gc().table_barrier_back(t, v);
4293    }
4294    pub fn gc_barrier_upval(&mut self, uv: &GcRef<UpVal>, v: &LuaValue) {
4295        self.gc().barrier(uv, v);
4296    }
4297    /// Compares `GlobalState::current_thread_id` against `main_thread_id`;
4298    /// `false` while a coroutine resume has swapped `current_thread_id` to
4299    /// the child's id.
4300    pub fn is_main_thread(&mut self) -> bool {
4301        let g = self.global();
4302        g.current_thread_id == g.main_thread_id
4303    }
4304    pub fn obj_type_name<'v>(&self, v: &'v LuaValue) -> std::borrow::Cow<'static, [u8]> {
4305        let honors_name = self.global().lua_version.honors_name_metafield();
4306        match v {
4307            LuaValue::LightUserData(_) => std::borrow::Cow::Borrowed(b"light userdata"),
4308            LuaValue::Table(t) => {
4309                if honors_name {
4310                    if let Some(mt) = t.metatable() {
4311                        if let LuaValue::Str(s) = mt.get_str_bytes(b"__name") {
4312                            return std::borrow::Cow::Owned(s.as_bytes().to_vec());
4313                        }
4314                    }
4315                }
4316                std::borrow::Cow::Borrowed(crate::tagmethods::type_name(v.base_type()))
4317            }
4318            LuaValue::UserData(u) => {
4319                if honors_name {
4320                    if let Some(mt) = u.metatable() {
4321                        if let LuaValue::Str(s) = mt.get_str_bytes(b"__name") {
4322                            return std::borrow::Cow::Owned(s.as_bytes().to_vec());
4323                        }
4324                    }
4325                }
4326                std::borrow::Cow::Borrowed(crate::tagmethods::type_name(v.base_type()))
4327            }
4328            _ => std::borrow::Cow::Borrowed(crate::tagmethods::type_name(v.base_type())),
4329        }
4330    }
4331
4332    pub fn full_type_name(&mut self, v: &LuaValue) -> Result<Vec<u8>, LuaError> {
4333        crate::tagmethods::obj_type_name(self, v)
4334    }
4335    pub fn emit_warning(&mut self, _msg: &[u8], _to_cont: bool) {
4336        warning(self, _msg, _to_cont)
4337    }
4338}
4339
4340// ─── GcHandle ───────────────────────────────────────────────────────────────
4341
4342/// A short-lived handle returned by `state.gc()` for GC operations.
4343pub struct GcHandle<'a> {
4344    _state: &'a mut LuaState,
4345}
4346
4347/// Composite root passed to `Heap::full_collect`. `new_state` leaves
4348/// `GlobalState.mainthread = None` (to break the self-referential Rc
4349/// cycle — see the field doc), so the running thread's stack and openupval
4350/// list are not reachable from `GlobalState::trace`. Wrapping both
4351/// references in a single `Trace`-implementing root injects the active
4352/// thread as a second mark source for the duration of the collection.
4353struct CollectRoots<'a> {
4354    global: &'a GlobalState,
4355    thread: &'a LuaState,
4356}
4357
4358#[derive(Clone, Copy)]
4359enum HeapCollectMode {
4360    Full,
4361    Step,
4362    Minor,
4363}
4364
4365impl<'a> lua_gc::Trace for CollectRoots<'a> {
4366    fn trace(&self, m: &mut lua_gc::Marker) {
4367        self.global.trace(m);
4368        self.thread.trace(m);
4369    }
4370}
4371
4372#[derive(Clone, Copy)]
4373enum BarrierKind {
4374    Forward,
4375    Backward,
4376}
4377
4378fn barrier_lua_value<P>(
4379    heap: &lua_gc::Heap,
4380    parent: GcRef<P>,
4381    child: &LuaValue,
4382    generational: bool,
4383    kind: BarrierKind,
4384) where
4385    P: lua_gc::Trace + 'static,
4386{
4387    if !child.is_collectable() {
4388        return;
4389    }
4390    if generational && matches!(kind, BarrierKind::Backward) {
4391        heap.generational_backward_barrier(parent.0);
4392    }
4393    match child {
4394        LuaValue::Str(c) => barrier_gc_child(heap, parent, *c, generational, kind),
4395        LuaValue::Table(c) => barrier_gc_child(heap, parent, *c, generational, kind),
4396        LuaValue::Function(LuaClosure::Lua(c)) => {
4397            barrier_gc_child(heap, parent, *c, generational, kind)
4398        }
4399        LuaValue::Function(LuaClosure::C(c)) => {
4400            barrier_gc_child(heap, parent, *c, generational, kind)
4401        }
4402        LuaValue::UserData(c) => barrier_gc_child(heap, parent, *c, generational, kind),
4403        LuaValue::Thread(c) => barrier_gc_child(heap, parent, *c, generational, kind),
4404        LuaValue::Nil
4405        | LuaValue::Bool(_)
4406        | LuaValue::Int(_)
4407        | LuaValue::Float(_)
4408        | LuaValue::LightUserData(_)
4409        | LuaValue::Function(LuaClosure::LightC(_)) => {}
4410    }
4411}
4412
4413fn barrier_gc_child<P, C>(
4414    heap: &lua_gc::Heap,
4415    parent: GcRef<P>,
4416    child: GcRef<C>,
4417    generational: bool,
4418    kind: BarrierKind,
4419) where
4420    P: lua_gc::Trace + 'static,
4421    C: lua_gc::Trace + 'static,
4422{
4423    if generational && matches!(kind, BarrierKind::Forward) {
4424        heap.generational_forward_barrier(parent.0, child.0);
4425    } else if matches!(kind, BarrierKind::Backward) {
4426        heap.barrier_back(parent.0, child.0);
4427    } else {
4428        heap.barrier(parent.0, child.0);
4429    }
4430}
4431
4432fn barrier_child_any<P>(
4433    heap: &lua_gc::Heap,
4434    parent: GcRef<P>,
4435    child: &dyn std::any::Any,
4436    generational: bool,
4437    kind: BarrierKind,
4438) where
4439    P: lua_gc::Trace + 'static,
4440{
4441    if let Some(v) = child.downcast_ref::<LuaValue>() {
4442        barrier_lua_value(heap, parent, v, generational, kind);
4443    } else if let Some(c) = child.downcast_ref::<GcRef<LuaString>>() {
4444        barrier_gc_child(heap, parent, c.clone(), generational, kind);
4445    } else if let Some(c) = child.downcast_ref::<GcRef<LuaTable>>() {
4446        barrier_gc_child(heap, parent, c.clone(), generational, kind);
4447    } else if let Some(c) = child.downcast_ref::<GcRef<LuaClosureLua>>() {
4448        barrier_gc_child(heap, parent, c.clone(), generational, kind);
4449    } else if let Some(c) = child.downcast_ref::<GcRef<LuaClosureC>>() {
4450        barrier_gc_child(heap, parent, c.clone(), generational, kind);
4451    } else if let Some(c) = child.downcast_ref::<GcRef<LuaUserData>>() {
4452        barrier_gc_child(heap, parent, c.clone(), generational, kind);
4453    } else if let Some(c) = child.downcast_ref::<GcRef<lua_types::value::LuaThread>>() {
4454        barrier_gc_child(heap, parent, c.clone(), generational, kind);
4455    } else if let Some(c) = child.downcast_ref::<GcRef<LuaProto>>() {
4456        barrier_gc_child(heap, parent, c.clone(), generational, kind);
4457    } else if let Some(c) = child.downcast_ref::<GcRef<UpVal>>() {
4458        barrier_gc_child(heap, parent, c.clone(), generational, kind);
4459    }
4460}
4461
4462fn barrier_any(
4463    heap: &lua_gc::Heap,
4464    parent: &dyn std::any::Any,
4465    child: &dyn std::any::Any,
4466    generational: bool,
4467    kind: BarrierKind,
4468) {
4469    if let Some(v) = parent.downcast_ref::<LuaValue>() {
4470        match v {
4471            LuaValue::Str(p) => barrier_child_any(heap, *p, child, generational, kind),
4472            LuaValue::Table(p) => barrier_child_any(heap, *p, child, generational, kind),
4473            LuaValue::Function(LuaClosure::Lua(p)) => {
4474                barrier_child_any(heap, *p, child, generational, kind)
4475            }
4476            LuaValue::Function(LuaClosure::C(p)) => {
4477                barrier_child_any(heap, *p, child, generational, kind)
4478            }
4479            LuaValue::UserData(p) => barrier_child_any(heap, *p, child, generational, kind),
4480            LuaValue::Thread(p) => barrier_child_any(heap, *p, child, generational, kind),
4481            LuaValue::Nil
4482            | LuaValue::Bool(_)
4483            | LuaValue::Int(_)
4484            | LuaValue::Float(_)
4485            | LuaValue::LightUserData(_)
4486            | LuaValue::Function(LuaClosure::LightC(_)) => {}
4487        }
4488    } else if let Some(p) = parent.downcast_ref::<GcRef<LuaString>>() {
4489        barrier_child_any(heap, p.clone(), child, generational, kind);
4490    } else if let Some(p) = parent.downcast_ref::<GcRef<LuaTable>>() {
4491        barrier_child_any(heap, p.clone(), child, generational, kind);
4492    } else if let Some(p) = parent.downcast_ref::<GcRef<LuaClosureLua>>() {
4493        barrier_child_any(heap, p.clone(), child, generational, kind);
4494    } else if let Some(p) = parent.downcast_ref::<GcRef<LuaClosureC>>() {
4495        barrier_child_any(heap, p.clone(), child, generational, kind);
4496    } else if let Some(p) = parent.downcast_ref::<GcRef<LuaUserData>>() {
4497        barrier_child_any(heap, p.clone(), child, generational, kind);
4498    } else if let Some(p) = parent.downcast_ref::<GcRef<lua_types::value::LuaThread>>() {
4499        barrier_child_any(heap, p.clone(), child, generational, kind);
4500    } else if let Some(p) = parent.downcast_ref::<GcRef<LuaProto>>() {
4501        barrier_child_any(heap, p.clone(), child, generational, kind);
4502    } else if let Some(p) = parent.downcast_ref::<GcRef<UpVal>>() {
4503        barrier_child_any(heap, p.clone(), child, generational, kind);
4504    }
4505}
4506
4507/// Fixed-point trace of every registered coroutine whose thread handle was
4508/// reached from a real root.
4509///
4510/// A thread whose `RefCell` is mutably borrowed at collect time CANNOT be
4511/// traced — its stack is silently invisible to the marker. Exactly two
4512/// borrow-holders are legitimate: the currently-running thread (rooted
4513/// directly via `CollectRoots.thread`) and resume-chain parents (rooted via
4514/// the `suspended_parent_stacks` snapshots, one per nesting level). Any
4515/// other borrow held across a collect point un-roots that coroutine for the
4516/// whole cycle — the bug-A root-loss class from issue #140 — so debug builds
4517/// assert the failure count stays within snapshot coverage.
4518fn trace_reachable_threads(
4519    global: &GlobalState,
4520    _current_thread_id: u64,
4521    marker: &mut lua_gc::Marker,
4522) {
4523    use lua_gc::Trace;
4524
4525    #[cfg(debug_assertions)]
4526    let mut uncovered_borrowed: Vec<u64> = Vec::new();
4527
4528    loop {
4529        let visited_before = marker.visited_count();
4530        for (id, entry) in global.threads.iter() {
4531            if thread_entry_marked_alive(marker, *id, entry) {
4532                match entry.state.try_borrow() {
4533                    Ok(thread) => thread.trace(marker),
4534                    Err(_) => {
4535                        #[cfg(debug_assertions)]
4536                        if *id != _current_thread_id && !uncovered_borrowed.contains(id) {
4537                            uncovered_borrowed.push(*id);
4538                        }
4539                    }
4540                }
4541            }
4542        }
4543        marker.drain_gray_queue();
4544        if marker.visited_count() == visited_before {
4545            break;
4546        }
4547    }
4548
4549    remark_legacy_open_upvalues(global, marker);
4550
4551    #[cfg(debug_assertions)]
4552    debug_assert!(
4553        uncovered_borrowed.len() <= global.suspended_parent_stacks.len(),
4554        "GC root loss: {} marked-alive coroutine(s) (ids {:?}) were mutably \
4555         borrowed at collect time with only {} parent snapshot(s) covering \
4556         them — their stacks were NOT traced this cycle, so anything only \
4557         reachable from them will be swept (issue #140 bug-A class). A borrow \
4558         of a coroutine's state must not be held across an allocation \
4559         checkpoint without pushing a parent GC snapshot.",
4560        uncovered_borrowed.len(),
4561        uncovered_borrowed,
4562        global.suspended_parent_stacks.len()
4563    );
4564}
4565
4566/// Legacy (5.1/5.2/5.3) `remarkupvals` (lgc.c). After the main mark phase has
4567/// settled which threads are reachable, an unmarked thread's *touched* open
4568/// upvalues have their pointed-to stack values re-marked exactly once, then the
4569/// thread's touched flag is cleared — mirroring C marking each touched upvalue's
4570/// value and removing the thread from `g->twups`.
4571///
4572/// This re-mark resurrects an object reachable only through a suspended thread's
4573/// cycle for one extra collection. Concretely, a `co <-> closure <-> table`
4574/// cycle with a `__gc` on the table is *not* finalized after the first
4575/// `collectgarbage()` (the touched open upvalue keeps the table marked, and the
4576/// table transitively re-marks the thread); on the next collection the flag is
4577/// already cleared, nothing re-marks the table, and it is separated to be
4578/// finalized. That two-collection delay is exactly what 5.3's `gc.lua` asserts
4579/// (`assert(not collected)` after the first collect).
4580///
4581/// From 5.4 the C condition became `!iswhite(uv)` rather than `touched`, so a
4582/// white open upvalue on an unmarked thread is never re-marked and the same
4583/// cycle is finalized after a single collect. Modern versions therefore skip
4584/// this pass entirely, leaving the baked 5.4/5.5 behavior untouched.
4585fn remark_legacy_open_upvalues(global: &GlobalState, marker: &mut lua_gc::Marker) {
4586    use lua_gc::Trace;
4587
4588    let legacy = matches!(
4589        global.lua_version,
4590        lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
4591    );
4592    if !legacy {
4593        return;
4594    }
4595
4596    let mut remarked_any = false;
4597    for (id, entry) in global.threads.iter() {
4598        if entry.value.id != *id {
4599            continue;
4600        }
4601        if thread_entry_marked_alive(marker, *id, entry) {
4602            continue;
4603        }
4604        let Ok(thread) = entry.state.try_borrow() else {
4605            continue;
4606        };
4607        if thread.openupval.is_empty() || !thread.legacy_open_upval_touched.get() {
4608            continue;
4609        }
4610        thread.legacy_open_upval_touched.set(false);
4611        for uv in thread.openupval.iter() {
4612            let Some((_tid, idx)) = uv.try_open_payload() else {
4613                continue;
4614            };
4615            let slot = idx.0 as usize;
4616            if slot < thread.stack.len() {
4617                thread.stack[slot].val.trace(marker);
4618                remarked_any = true;
4619            }
4620        }
4621    }
4622
4623    if !remarked_any {
4624        return;
4625    }
4626    marker.drain_gray_queue();
4627
4628    loop {
4629        let visited_before = marker.visited_count();
4630        for (id, entry) in global.threads.iter() {
4631            if thread_entry_marked_alive(marker, *id, entry) {
4632                if let Ok(thread) = entry.state.try_borrow() {
4633                    thread.trace(marker);
4634                }
4635            }
4636        }
4637        marker.drain_gray_queue();
4638        if marker.visited_count() == visited_before {
4639            break;
4640        }
4641    }
4642}
4643
4644fn thread_entry_marked_alive(
4645    marker: &lua_gc::Marker,
4646    id: u64,
4647    entry: &ThreadRegistryEntry,
4648) -> bool {
4649    marker.is_marked_or_old(entry.value.0) && entry.value.id == id
4650}
4651
4652fn lua_value_marked_or_old(marker: &lua_gc::Marker, value: &LuaValue) -> bool {
4653    match value {
4654        LuaValue::Str(v) => marker.is_marked_or_old(v.0),
4655        LuaValue::Table(v) => marker.is_marked_or_old(v.0),
4656        LuaValue::Function(LuaClosure::Lua(v)) => marker.is_marked_or_old(v.0),
4657        LuaValue::Function(LuaClosure::C(v)) => marker.is_marked_or_old(v.0),
4658        LuaValue::UserData(v) => marker.is_marked_or_old(v.0),
4659        LuaValue::Thread(v) => marker.is_marked_or_old(v.0),
4660        LuaValue::Nil
4661        | LuaValue::Bool(_)
4662        | LuaValue::Int(_)
4663        | LuaValue::Float(_)
4664        | LuaValue::LightUserData(_)
4665        | LuaValue::Function(LuaClosure::LightC(_)) => true,
4666    }
4667}
4668
4669fn finalizer_marked_or_old(marker: &lua_gc::Marker, object: &FinalizerObject) -> bool {
4670    match object {
4671        FinalizerObject::Table(t) => marker.is_marked_or_old(t.0),
4672        FinalizerObject::UserData(u) => marker.is_marked_or_old(u.0),
4673    }
4674}
4675
4676fn weak_snapshot_tables<'a>(
4677    snapshot: &'a lua_gc::WeakRegistrySnapshot<GcRef<LuaTable>>,
4678) -> impl Iterator<Item = &'a GcRef<LuaTable>> {
4679    snapshot
4680        .weak_values
4681        .iter()
4682        .chain(snapshot.ephemeron.iter())
4683        .chain(snapshot.all_weak.iter())
4684}
4685
4686fn close_open_upvalues_for_unreachable_threads(global: &GlobalState, marker: &mut lua_gc::Marker) {
4687    use lua_gc::Trace;
4688
4689    let mut closed_values = Vec::<LuaValue>::new();
4690    for (id, entry) in global.threads.iter() {
4691        if entry.value.id != *id {
4692            continue;
4693        }
4694        if thread_entry_marked_alive(marker, *id, entry) {
4695            continue;
4696        }
4697        let Ok(thread) = entry.state.try_borrow() else {
4698            continue;
4699        };
4700        for uv in thread.openupval.iter() {
4701            if !marker.is_visited(uv.identity()) {
4702                continue;
4703            }
4704            let Some((thread_id, idx)) = uv.try_open_payload() else {
4705                continue;
4706            };
4707            if thread_id != *id {
4708                continue;
4709            }
4710            let value = thread.get_at(idx);
4711            uv.close_with(value.clone());
4712            closed_values.push(value);
4713        }
4714    }
4715    for value in closed_values {
4716        value.trace(marker);
4717    }
4718    marker.drain_gray_queue();
4719}
4720
4721/// Mark-phase half of intern-table cleanup (C: dead strings leave the
4722/// stringtable via `luaS_remove` at free time). The marker and a `&mut`
4723/// global cannot coexist, so this records each DEAD entry's
4724/// `(hash, identity)` pair during the immutable post-mark hook; the
4725/// steady-state output is empty or tiny, replacing the old all-live-ids
4726/// vector (O(table) push + sort + per-entry binary-search retain).
4727fn record_dead_interned_strings(
4728    global: &GlobalState,
4729    marker: &lua_gc::Marker,
4730    dead_pairs: &std::cell::RefCell<Vec<(u32, usize)>>,
4731) {
4732    let mut dead = dead_pairs.borrow_mut();
4733    for s in global.interned_lt.iter() {
4734        let id = s.identity();
4735        if !marker.is_visited(id) {
4736            dead.push((s.hash(), id));
4737        }
4738    }
4739}
4740
4741/// Sweep-phase half: O(dead) bucket removals by cached hash + identity,
4742/// then a single batch-end shrink check.
4743///
4744/// The shrink check runs ONCE per collection here — after every dead entry
4745/// for this cycle has been removed, so only live `GcRef<LuaString>`s remain
4746/// to rehash — and deliberately NOT inside `remove()`. A per-removal shrink
4747/// would rehash O(live) entries on each of the O(dead) removals, turning the
4748/// batch into O(live²); deferring to batch end keeps removal O(dead) and adds
4749/// one bounded load-factor check per GC cycle. This mirrors C, where
4750/// `luaS_remove` only unlinks and the shrink lives in `checkSizes`, called
4751/// once per `singlestep`/`fullgc` cycle.
4752fn remove_dead_interned_strings(global: &mut GlobalState, dead_pairs: Vec<(u32, usize)>) {
4753    for (hash, id) in dead_pairs {
4754        global.interned_lt.remove(hash, id);
4755    }
4756    global.interned_lt.shrink_if_sparse();
4757}
4758
4759impl<'a> GcHandle<'a> {
4760    /// Drives implicit collection when the heap's byte threshold is
4761    /// exceeded. Without this hook, loops that allocate without an
4762    /// explicit `collectgarbage()` call (e.g. `closure.lua`'s
4763    /// `while x[1] do local a = A..A end` GC-driven loop) never settle.
4764    pub fn check_step(&self) {
4765        if !self._state.global().is_gc_running() {
4766            return;
4767        }
4768        if self._state.global().is_gen_mode() {
4769            let should_collect = {
4770                let g = self._state.global();
4771                g.heap.would_collect() || g.gc_debt() > 0
4772            };
4773            if should_collect {
4774                self.generational_step();
4775            }
4776        } else {
4777            self.collect_via_heap(/* force = */ false);
4778        }
4779    }
4780
4781    pub fn full_collect(&self) {
4782        if self._state.global().is_gen_mode() {
4783            self.fullgen();
4784        } else {
4785            self.collect_via_heap(/* force = */ true);
4786        }
4787    }
4788
4789    fn negative_debt(bytes: usize) -> isize {
4790        -(bytes.min(isize::MAX as usize) as isize)
4791    }
4792
4793    fn set_minor_debt(&self) {
4794        let mut g = self._state.global_mut();
4795        let total = g.total_bytes();
4796        let growth = (total / 100).saturating_mul(g.genminormul as usize);
4797        g.heap
4798            .set_threshold_bytes(total.saturating_add(growth.max(1)));
4799        set_debt(&mut *g, Self::negative_debt(growth));
4800    }
4801
4802    fn set_pause_debt(&self) {
4803        let mut g = self._state.global_mut();
4804        let total = g.total_bytes();
4805        let pause = g.gc_pause_param().max(0) as usize;
4806        let threshold = g.gc_estimate.max(1).saturating_mul(pause) / 100;
4807        let debt = if threshold > total {
4808            Self::negative_debt(threshold - total)
4809        } else {
4810            0
4811        };
4812        let heap_threshold = if threshold > total {
4813            threshold
4814        } else {
4815            total.saturating_add(1)
4816        };
4817        g.heap.set_threshold_bytes(heap_threshold);
4818        set_debt(&mut *g, debt);
4819    }
4820
4821    fn enter_incremental_mode(&self) {
4822        let mut g = self._state.global_mut();
4823        g.heap.reset_all_ages();
4824        g.finalizers.reset_generation_boundaries();
4825        g.gckind = GcKind::Incremental as u8;
4826        g.lastatomic = 0;
4827    }
4828
4829    fn enter_generational_mode(&self) -> usize {
4830        self.collect_via_heap_mode(HeapCollectMode::Full);
4831        let numobjs = {
4832            let mut g = self._state.global_mut();
4833            g.heap.promote_all_to_old();
4834            g.finalizers.promote_all_pending_to_old();
4835            g.heap.allgc_count()
4836        };
4837        let total = self._state.global().total_bytes();
4838        {
4839            let mut g = self._state.global_mut();
4840            g.gckind = GcKind::Generational as u8;
4841            g.lastatomic = 0;
4842            g.gc_estimate = total;
4843        }
4844        self.set_minor_debt();
4845        numobjs
4846    }
4847
4848    fn fullgen(&self) -> usize {
4849        self.enter_incremental_mode();
4850        self.enter_generational_mode()
4851    }
4852
4853    fn stepgenfull(&self, lastatomic: usize) {
4854        if self._state.global().gckind == GcKind::Generational as u8 {
4855            self.enter_incremental_mode();
4856        }
4857        self.collect_via_heap_mode(HeapCollectMode::Full);
4858        let newatomic = self._state.global().heap.allgc_count().max(1);
4859        if newatomic < lastatomic.saturating_add(lastatomic >> 3) {
4860            {
4861                let mut g = self._state.global_mut();
4862                g.heap.promote_all_to_old();
4863                g.finalizers.promote_all_pending_to_old();
4864            }
4865            let total = self._state.global().total_bytes();
4866            {
4867                let mut g = self._state.global_mut();
4868                g.gckind = GcKind::Generational as u8;
4869                g.lastatomic = 0;
4870                g.gc_estimate = total;
4871            }
4872            self.set_minor_debt();
4873        } else {
4874            {
4875                let mut g = self._state.global_mut();
4876                g.heap.reset_all_ages();
4877                g.finalizers.reset_generation_boundaries();
4878            }
4879            let total = self._state.global().total_bytes();
4880            {
4881                let mut g = self._state.global_mut();
4882                g.gckind = GcKind::Incremental as u8;
4883                g.lastatomic = newatomic;
4884                g.gc_estimate = total;
4885            }
4886            self.set_pause_debt();
4887        }
4888    }
4889
4890    /// Shared driver behind both `full_collect` (force-collect) and
4891    /// `check_step` (collect only if heap byte threshold exceeded).
4892    ///
4893    /// Snapshots the weak-tables registry, invokes the heap's collect path
4894    /// with a post-mark weak-prune hook, and rebuilds the registry by
4895    /// retaining only entries whose target was reachable. The same hook
4896    /// works for both modes — the heap short-circuits when force=false and
4897    /// the threshold isn't met.
4898    fn collect_via_heap(&self, force: bool) {
4899        self.collect_via_heap_mode(if force {
4900            HeapCollectMode::Full
4901        } else {
4902            HeapCollectMode::Step
4903        });
4904    }
4905
4906    fn collect_via_heap_mode(&self, mode: HeapCollectMode) {
4907        use lua_gc::Trace;
4908        let state_ref: &LuaState = &*self._state;
4909
4910        // Fast path: when the caller did not force a collection, skip all
4911        // the snapshot work (3 Vec allocations + 3 HashSet allocations) if
4912        // the heap is paused or under threshold — a `step()` in that state
4913        // is a no-op, so the snapshot would be pure waste. Called millions
4914        // of times per recursive workload via `gc_check_step` in `precall`.
4915        if matches!(mode, HeapCollectMode::Step) {
4916            let g = state_ref.global.borrow();
4917            if !g.heap.would_collect() {
4918                return;
4919            }
4920        }
4921
4922        // Snapshot weak tables BEFORE the collect. `identity()` reads only
4923        // the pointer address — safe even on still-dangling weak handles —
4924        // and dedup by identity keeps the iteration linear.
4925        let weak_tables_snapshot: lua_gc::WeakRegistrySnapshot<GcRef<LuaTable>> = {
4926            let mut g = state_ref.global.borrow_mut();
4927            g.weak_tables_registry.live_snapshot_by_kind()
4928        };
4929
4930        // Snapshot pending finalizers. `GlobalState::trace` deliberately
4931        // does NOT root these — that's how the post-mark hook below can
4932        // distinguish "still reachable from program state" from "only kept
4933        // alive by the finalizer registry."
4934        let weak_table_capacity = weak_tables_snapshot.len();
4935        let (pending_snapshot, thread_capacity, _interned_capacity): (
4936            Vec<FinalizerObject>,
4937            usize,
4938            usize,
4939        ) = {
4940            let g = state_ref.global.borrow();
4941            let pending = match mode {
4942                HeapCollectMode::Minor => g.finalizers.pending_minor_snapshot(),
4943                HeapCollectMode::Full | HeapCollectMode::Step => g.finalizers.pending_snapshot(),
4944            };
4945            (pending, g.threads.len(), g.interned_lt.len())
4946        };
4947        let finalizer_capacity = pending_snapshot.len();
4948
4949        let alive_ids: std::cell::RefCell<std::collections::HashSet<usize>> =
4950            std::cell::RefCell::new(std::collections::HashSet::new());
4951        let newly_unreachable: std::cell::RefCell<Vec<FinalizerObject>> =
4952            std::cell::RefCell::new(Vec::new());
4953        let alive_thread_ids: std::cell::RefCell<std::collections::HashSet<u64>> =
4954            std::cell::RefCell::new(std::collections::HashSet::new());
4955        let alive_closure_env_ids: std::cell::RefCell<std::collections::HashSet<usize>> =
4956            std::cell::RefCell::new(std::collections::HashSet::new());
4957        let dead_interned: std::cell::RefCell<Vec<(u32, usize)>> = std::cell::RefCell::new(Vec::new());
4958        let collect_ran = std::cell::Cell::new(false);
4959
4960        {
4961            let global = state_ref.global.borrow();
4962            global.heap.unpause();
4963            let roots = CollectRoots {
4964                global: &*global,
4965                thread: state_ref,
4966            };
4967            let hook = |marker: &mut lua_gc::Marker| {
4968                collect_ran.set(true);
4969                alive_ids.borrow_mut().reserve(weak_table_capacity);
4970                newly_unreachable.borrow_mut().reserve(finalizer_capacity);
4971                alive_thread_ids.borrow_mut().reserve(thread_capacity);
4972                trace_reachable_threads(&*global, global.current_thread_id, marker);
4973                close_open_upvalues_for_unreachable_threads(&*global, marker);
4974                // Lua 5.1 weak-key tables are NOT ephemerons. In 5.1
4975                // `traversetable` (lgc.c) a `__mode='k'` table still marks its
4976                // VALUES strongly (`if (!weakvalue) markvalue(g, gval(n))`), so
4977                // a value that references its own weak key keeps that key alive
4978                // (`a[t]=t` survives). Ephemeron semantics — a value reachable
4979                // only if the key is independently reachable — arrived in 5.2.
4980                let legacy_weak_key_values =
4981                    matches!(global.lua_version, lua_types::LuaVersion::V51);
4982                loop {
4983                    let visited_before = marker.visited_count();
4984                    for t in &weak_tables_snapshot.ephemeron {
4985                        if !marker.is_marked_or_old(t.0) {
4986                            continue;
4987                        }
4988                        if legacy_weak_key_values {
4989                            let mut to_mark = Vec::new();
4990                            t.for_each_entry(|_k, v| to_mark.push(v.clone()));
4991                            for v in &to_mark {
4992                                v.trace(marker);
4993                            }
4994                        } else {
4995                            let to_mark = t.ephemeron_values_to_mark_with_value(&|v| {
4996                                lua_value_marked_or_old(marker, v)
4997                            });
4998                            for v in &to_mark {
4999                                v.trace(marker);
5000                            }
5001                        }
5002                    }
5003                    marker.drain_gray_queue();
5004                    if marker.visited_count() == visited_before {
5005                        break;
5006                    }
5007                }
5008                // Clear dead weak VALUES before finalizer resurrection,
5009                // mirroring C's `clearvalues(g->weak, NULL)` /
5010                // `clearvalues(g->allweak, NULL)` which run in `atomic`
5011                // *before* `separatetobefnz`/`markbeingfnz` (lua-5.3.6
5012                // lgc.c). An object that is only reachable through a
5013                // to-be-finalized table is still white at this point, so a
5014                // weak-value reference to it is dropped — and stays dropped
5015                // even after resurrection re-marks the object — so the
5016                // finalizer observes the already-cleared slot. Keys are left
5017                // untouched here; they are cleared post-resurrection.
5018                //
5019                // C iterates the *entire* weak list regardless of table mark
5020                // state, so a weak-value table reachable only via a soon-to-be
5021                // resurrected object (its `__gc` closure stored weakly is the
5022                // canonical case) still has its dead values dropped here, not
5023                // after resurrection re-marks the table. The mark check only
5024                // gates whether surviving value-strings are re-marked: strings
5025                // are values weak tables never collect, but only when the
5026                // owning table itself is reachable.
5027                for t in weak_tables_snapshot
5028                    .weak_values
5029                    .iter()
5030                    .chain(weak_tables_snapshot.all_weak.iter())
5031                {
5032                    let to_mark = t.prune_weak_dead_with_value(
5033                        &|_| true,
5034                        &|v| lua_value_marked_or_old(marker, v),
5035                    );
5036                    if marker.is_marked_or_old(t.0) {
5037                        for v in &to_mark {
5038                            v.trace(marker);
5039                        }
5040                    }
5041                }
5042                marker.drain_gray_queue();
5043                for pf in &pending_snapshot {
5044                    if !finalizer_marked_or_old(marker, pf) {
5045                        pf.mark(marker);
5046                        newly_unreachable.borrow_mut().push(pf.clone());
5047                    }
5048                }
5049                marker.drain_gray_queue();
5050                loop {
5051                    let visited_before = marker.visited_count();
5052                    for t in &weak_tables_snapshot.ephemeron {
5053                        if !marker.is_marked_or_old(t.0) {
5054                            continue;
5055                        }
5056                        if legacy_weak_key_values {
5057                            let mut to_mark = Vec::new();
5058                            t.for_each_entry(|_k, v| to_mark.push(v.clone()));
5059                            for v in &to_mark {
5060                                v.trace(marker);
5061                            }
5062                        } else {
5063                            let to_mark = t.ephemeron_values_to_mark_with_value(&|v| {
5064                                lua_value_marked_or_old(marker, v)
5065                            });
5066                            for v in &to_mark {
5067                                v.trace(marker);
5068                            }
5069                        }
5070                    }
5071                    marker.drain_gray_queue();
5072                    if marker.visited_count() == visited_before {
5073                        break;
5074                    }
5075                }
5076                // Clear dead weak KEYS post-resurrection, mirroring C's
5077                // `clearkeys(g->ephemeron, NULL)` / `clearkeys(g->allweak,
5078                // NULL)`. A key kept alive only by a resurrected (now-marked)
5079                // object survives; a key pending its own finalization is
5080                // already marked by `markbeingfnz`, so `marked_or_old`
5081                // keeps it visible until its `__gc` runs. Values in these
5082                // originally-tracked tables were already settled in the
5083                // pre-resurrection value pass and must not be re-evaluated
5084                // (resurrection can re-mark a value that was correctly
5085                // cleared), so this pass touches keys only — matching the
5086                // `origweak` skip in C's later `clearvalues(g->weak,
5087                // origweak)`.
5088                for t in weak_tables_snapshot
5089                    .ephemeron
5090                    .iter()
5091                    .chain(weak_tables_snapshot.all_weak.iter())
5092                {
5093                    if !marker.is_marked_or_old(t.0) {
5094                        continue;
5095                    }
5096                    let to_mark = t.prune_weak_dead_with_value(
5097                        &|v| lua_value_marked_or_old(marker, v),
5098                        &|_| true,
5099                    );
5100                    for v in &to_mark {
5101                        v.trace(marker);
5102                    }
5103                }
5104                for t in weak_snapshot_tables(&weak_tables_snapshot) {
5105                    if marker.is_marked_or_old(t.0) {
5106                        alive_ids.borrow_mut().insert(t.identity());
5107                    }
5108                }
5109                marker.drain_gray_queue();
5110                {
5111                    let mut alive = alive_thread_ids.borrow_mut();
5112                    for (id, entry) in global.threads.iter() {
5113                        if thread_entry_marked_alive(marker, *id, entry) {
5114                            alive.insert(*id);
5115                        }
5116                    }
5117                }
5118                {
5119                    let mut alive = alive_closure_env_ids.borrow_mut();
5120                    for id in global.closure_envs.keys() {
5121                        if marker.is_visited(*id) {
5122                            alive.insert(*id);
5123                        }
5124                    }
5125                }
5126                record_dead_interned_strings(&*global, marker, &dead_interned);
5127            };
5128            match mode {
5129                HeapCollectMode::Full => global.heap.full_collect_with_post_mark(&roots, hook),
5130                HeapCollectMode::Step => global.heap.step_with_post_mark(&roots, hook),
5131                HeapCollectMode::Minor => global.heap.minor_collect_with_post_mark(&roots, hook),
5132            }
5133        }
5134
5135        if !collect_ran.get() {
5136            return;
5137        }
5138
5139        // After collect, drop weak-table-registry entries whose target was
5140        // swept. This keeps the registry bounded and avoids retaining weak
5141        // handles whose target can no longer upgrade.
5142        let alive_set = alive_ids.into_inner();
5143        let promote: Vec<FinalizerObject> = newly_unreachable.into_inner();
5144        let alive_thread_ids = alive_thread_ids.into_inner();
5145        let alive_closure_env_ids = alive_closure_env_ids.into_inner();
5146        let dead_interned = dead_interned.into_inner();
5147        let mut g = state_ref.global.borrow_mut();
5148        remove_dead_interned_strings(&mut *g, dead_interned);
5149        g.weak_tables_registry.retain_identities(&alive_set);
5150        let main_thread_id = g.main_thread_id;
5151        g.threads.retain(|id, _| alive_thread_ids.contains(id));
5152        g.cross_thread_upvals
5153            .retain(|(id, _), _| *id == main_thread_id || alive_thread_ids.contains(id));
5154        // Lua 5.1 side maps (empty on 5.2–5.5): drop a coroutine's per-thread
5155        // global table once the coroutine is gone, and a closure's stored
5156        // environment once that closure is no longer visited.
5157        g.thread_globals
5158            .retain(|id, _| alive_thread_ids.contains(id));
5159        g.closure_envs
5160            .retain(|id, _| alive_closure_env_ids.contains(id));
5161        // Move newly-unreachable finalizables from `pending_finalizers` to
5162        // `to_be_finalized`. The latter is rooted by `GlobalState::trace`,
5163        // so these tables remain alive until their `__gc` runs.
5164        let promoted = g.finalizers.promote_pending_to_finalized(promote);
5165        for object in &promoted {
5166            if let Some(ptr) = object.heap_ptr() {
5167                g.heap.move_finobj_to_tobefnz(ptr);
5168            }
5169        }
5170        if matches!(mode, HeapCollectMode::Minor) {
5171            g.finalizers.finish_minor_collection();
5172        }
5173    }
5174
5175    /// Run one generational collection step.
5176    pub fn generational_step(&self) -> bool {
5177        self.generational_step_with_major(true)
5178    }
5179
5180    /// Run a generational step forced to the regular minor path.
5181    ///
5182    /// Used for `collectgarbage("step", 0)`: upstream `genstep` treats
5183    /// `GCdebt <= 0` as an explicit zero-size step and performs a minor
5184    /// collection, unless a previous bad major has already armed `lastatomic`.
5185    pub fn generational_step_minor_only(&self) -> bool {
5186        self.generational_step_with_major(false)
5187    }
5188
5189    fn generational_step_with_major(&self, allow_major: bool) -> bool {
5190        let (lastatomic, majorbase, majorinc, should_major) = {
5191            let g = self._state.global();
5192            let majorbase = if g.gc_estimate == 0 {
5193                g.total_bytes()
5194            } else {
5195                g.gc_estimate
5196            };
5197            let majormul = g.gc_genmajormul_param().max(0) as usize;
5198            let majorinc = (majorbase / 100).saturating_mul(majormul);
5199            let debt_due = g.gc_debt() > 0 || g.heap.would_collect();
5200            let should_major =
5201                allow_major && debt_due && g.total_bytes() > majorbase.saturating_add(majorinc);
5202            (g.lastatomic, majorbase, majorinc, should_major)
5203        };
5204
5205        if lastatomic != 0 {
5206            self.stepgenfull(lastatomic);
5207            debug_assert!(self._state.global().is_gen_mode());
5208            return true;
5209        }
5210
5211        if should_major {
5212            let numobjs = self.fullgen();
5213            let after = self._state.global().total_bytes();
5214            if after < majorbase.saturating_add(majorinc / 2) {
5215                self.set_minor_debt();
5216            } else {
5217                {
5218                    let mut g = self._state.global_mut();
5219                    g.lastatomic = numobjs.max(1);
5220                }
5221                self.set_pause_debt();
5222            }
5223        } else {
5224            self.collect_via_heap_mode(HeapCollectMode::Minor);
5225            self.set_minor_debt();
5226            self._state.global_mut().gc_estimate = majorbase;
5227        }
5228
5229        debug_assert!(self._state.global().is_gen_mode());
5230        true
5231    }
5232
5233    /// No-op stub for `luaC_step(L)`; unused. See [`GcHandle::check_step`]
5234    /// for the real incremental-collection entry point.
5235    pub fn step(&self) { /* phase-b no-op */
5236    }
5237
5238    /// Run one budgeted incremental step of the GC.
5239    ///
5240    /// `work_units` is the number of GC work units the step is allowed to
5241    /// perform (one gray trace, one sweep visit, or one phase transition).
5242    /// Returns `true` if the step completed a cycle and the collector is
5243    /// now in the `Pause` state; `false` otherwise.
5244    ///
5245    /// Mirrors `collect_via_heap` for the post-mark weak-table /
5246    /// finalizer-promotion logic, but only the atomic-phase transition will
5247    /// invoke the snapshot-walking hook — propagate and sweep steps reuse
5248    /// the snapshot but never execute it. The snapshot is rebuilt on every
5249    /// call; the cost is `O(weak_tables_registry)` per step.
5250    pub fn incremental_step(&self, work_units: isize) -> bool {
5251        self.incremental_step_to_state(work_units, None)
5252    }
5253
5254    /// TestC/debug helper: run the incremental collector until a specific heap
5255    /// state is entered, preserving the same weak-table/finalizer post-mark
5256    /// hooks as [`Self::incremental_step`]. This is intentionally not used for
5257    /// normal pacing; it exists so official tests can inspect mid-cycle colors.
5258    pub fn run_until_gc_state_for_test(&self, target: lua_gc::GcState) -> bool {
5259        self.incremental_step_to_state(isize::MAX / 4, Some(target));
5260        self._state.global().heap.gc_state() == target
5261    }
5262
5263    fn incremental_step_to_state(
5264        &self,
5265        work_units: isize,
5266        target: Option<lua_gc::GcState>,
5267    ) -> bool {
5268        use lua_gc::{StepBudget, StepOutcome, Trace};
5269        let state_ref: &LuaState = &*self._state;
5270
5271        let weak_tables_snapshot: lua_gc::WeakRegistrySnapshot<GcRef<LuaTable>> = {
5272            let mut g = state_ref.global.borrow_mut();
5273            g.weak_tables_registry.live_snapshot_by_kind()
5274        };
5275
5276        let weak_table_capacity = weak_tables_snapshot.len();
5277        let (pending_snapshot, thread_capacity, _interned_capacity): (
5278            Vec<FinalizerObject>,
5279            usize,
5280            usize,
5281        ) = {
5282            let g = state_ref.global.borrow();
5283            (
5284                g.finalizers.pending_snapshot(),
5285                g.threads.len(),
5286                g.interned_lt.len(),
5287            )
5288        };
5289        let finalizer_capacity = pending_snapshot.len();
5290
5291        let alive_ids: std::cell::RefCell<std::collections::HashSet<usize>> =
5292            std::cell::RefCell::new(std::collections::HashSet::new());
5293        let newly_unreachable: std::cell::RefCell<Vec<FinalizerObject>> =
5294            std::cell::RefCell::new(Vec::new());
5295        let alive_thread_ids: std::cell::RefCell<std::collections::HashSet<u64>> =
5296            std::cell::RefCell::new(std::collections::HashSet::new());
5297        let alive_closure_env_ids: std::cell::RefCell<std::collections::HashSet<usize>> =
5298            std::cell::RefCell::new(std::collections::HashSet::new());
5299        let dead_interned: std::cell::RefCell<Vec<(u32, usize)>> = std::cell::RefCell::new(Vec::new());
5300        let atomic_ran = std::cell::Cell::new(false);
5301
5302        let stop_target = {
5303            let g = state_ref.global.borrow();
5304            match (target, g.heap.gc_state()) {
5305                (Some(target), _) => Some(target),
5306                (None, lua_gc::GcState::CallFin) => None,
5307                (None, _) => Some(lua_gc::GcState::CallFin),
5308            }
5309        };
5310
5311        let outcome = {
5312            let global = state_ref.global.borrow();
5313            global.heap.unpause();
5314            let roots = CollectRoots {
5315                global: &*global,
5316                thread: state_ref,
5317            };
5318            let hook = |marker: &mut lua_gc::Marker| {
5319                atomic_ran.set(true);
5320                alive_ids.borrow_mut().reserve(weak_table_capacity);
5321                newly_unreachable.borrow_mut().reserve(finalizer_capacity);
5322                alive_thread_ids.borrow_mut().reserve(thread_capacity);
5323                trace_reachable_threads(&*global, global.current_thread_id, marker);
5324                close_open_upvalues_for_unreachable_threads(&*global, marker);
5325                // Lua 5.1 weak-key tables are NOT ephemerons; see the
5326                // full-collect hook above. `__mode='k'` still marks its values
5327                // strongly so a value referencing its own weak key survives.
5328                let legacy_weak_key_values =
5329                    matches!(global.lua_version, lua_types::LuaVersion::V51);
5330                loop {
5331                    let visited_before = marker.visited_count();
5332                    for t in &weak_tables_snapshot.ephemeron {
5333                        let t_id = t.identity();
5334                        if !marker.is_visited(t_id) {
5335                            continue;
5336                        }
5337                        if legacy_weak_key_values {
5338                            let mut to_mark = Vec::new();
5339                            t.for_each_entry(|_k, v| to_mark.push(v.clone()));
5340                            for v in &to_mark {
5341                                v.trace(marker);
5342                            }
5343                        } else {
5344                            let to_mark = t.ephemeron_values_to_mark(&|id| marker.is_visited(id));
5345                            for v in &to_mark {
5346                                v.trace(marker);
5347                            }
5348                        }
5349                    }
5350                    marker.drain_gray_queue();
5351                    if marker.visited_count() == visited_before {
5352                        break;
5353                    }
5354                }
5355                // Clear dead weak VALUES before finalizer resurrection,
5356                // mirroring C's `clearvalues(g->weak, NULL)` /
5357                // `clearvalues(g->allweak, NULL)` which run *before*
5358                // `markbeingfnz` in `atomic` (lua-5.3.6 lgc.c). See the
5359                // full-collect hook above for the rationale; this is the
5360                // incremental atomic and is the path the in-mode gc.lua
5361                // weak-table-plus-finalizer test exercises. C iterates the
5362                // entire weak list regardless of table mark state, so a
5363                // weak-value table reachable only via a soon-to-be-resurrected
5364                // object (canonically a `__gc` closure stored weakly) still
5365                // has its dead values dropped here. The visited check only
5366                // gates re-marking surviving value-strings. Keys untouched.
5367                for t in weak_tables_snapshot
5368                    .weak_values
5369                    .iter()
5370                    .chain(weak_tables_snapshot.all_weak.iter())
5371                {
5372                    let to_mark =
5373                        t.prune_weak_dead_with(&|_| true, &|id| marker.is_visited(id));
5374                    if marker.is_visited(t.identity()) {
5375                        for v in &to_mark {
5376                            v.trace(marker);
5377                        }
5378                    }
5379                }
5380                marker.drain_gray_queue();
5381                for pf in &pending_snapshot {
5382                    if !marker.is_visited(pf.identity()) {
5383                        pf.mark(marker);
5384                        newly_unreachable.borrow_mut().push(pf.clone());
5385                    }
5386                }
5387                marker.drain_gray_queue();
5388                loop {
5389                    let visited_before = marker.visited_count();
5390                    for t in &weak_tables_snapshot.ephemeron {
5391                        let t_id = t.identity();
5392                        if !marker.is_visited(t_id) {
5393                            continue;
5394                        }
5395                        if legacy_weak_key_values {
5396                            let mut to_mark = Vec::new();
5397                            t.for_each_entry(|_k, v| to_mark.push(v.clone()));
5398                            for v in &to_mark {
5399                                v.trace(marker);
5400                            }
5401                        } else {
5402                            let to_mark = t.ephemeron_values_to_mark(&|id| marker.is_visited(id));
5403                            for v in &to_mark {
5404                                v.trace(marker);
5405                            }
5406                        }
5407                    }
5408                    marker.drain_gray_queue();
5409                    if marker.visited_count() == visited_before {
5410                        break;
5411                    }
5412                }
5413                // Clear dead weak KEYS post-resurrection, mirroring C's
5414                // `clearkeys(g->ephemeron, NULL)` / `clearkeys(g->allweak,
5415                // NULL)`. Values in these originally-tracked tables were
5416                // already settled in the pre-resurrection pass and must not
5417                // be re-evaluated, so this pass is keys-only (the `origweak`
5418                // skip in C's later `clearvalues(g->weak, origweak)`).
5419                for t in weak_tables_snapshot
5420                    .ephemeron
5421                    .iter()
5422                    .chain(weak_tables_snapshot.all_weak.iter())
5423                {
5424                    if !marker.is_visited(t.identity()) {
5425                        continue;
5426                    }
5427                    let to_mark =
5428                        t.prune_weak_dead_with(&|id| marker.is_visited(id), &|_| true);
5429                    for v in &to_mark {
5430                        v.trace(marker);
5431                    }
5432                }
5433                for t in weak_snapshot_tables(&weak_tables_snapshot) {
5434                    if marker.is_visited(t.identity()) {
5435                        alive_ids.borrow_mut().insert(t.identity());
5436                    }
5437                }
5438                marker.drain_gray_queue();
5439                {
5440                    let mut alive = alive_thread_ids.borrow_mut();
5441                    for (id, entry) in global.threads.iter() {
5442                        if thread_entry_marked_alive(marker, *id, entry) {
5443                            alive.insert(*id);
5444                        }
5445                    }
5446                }
5447                {
5448                    let mut alive = alive_closure_env_ids.borrow_mut();
5449                    for id in global.closure_envs.keys() {
5450                        if marker.is_visited(*id) {
5451                            alive.insert(*id);
5452                        }
5453                    }
5454                }
5455                record_dead_interned_strings(&*global, marker, &dead_interned);
5456            };
5457            let budget = StepBudget::from_work(work_units);
5458            if let Some(target) = stop_target {
5459                global
5460                    .heap
5461                    .incremental_run_until_state_with_post_mark(&roots, target, work_units, hook)
5462            } else {
5463                global
5464                    .heap
5465                    .incremental_step_with_post_mark(&roots, budget, hook)
5466            }
5467        };
5468
5469        if atomic_ran.get() {
5470            let alive_set = alive_ids.into_inner();
5471            let promote: Vec<FinalizerObject> = newly_unreachable.into_inner();
5472            let alive_thread_ids = alive_thread_ids.into_inner();
5473            let alive_closure_env_ids = alive_closure_env_ids.into_inner();
5474            let dead_interned = dead_interned.into_inner();
5475            let mut g = state_ref.global.borrow_mut();
5476            remove_dead_interned_strings(&mut *g, dead_interned);
5477            g.weak_tables_registry.retain_identities(&alive_set);
5478            let main_thread_id = g.main_thread_id;
5479            g.threads.retain(|id, _| alive_thread_ids.contains(id));
5480            g.cross_thread_upvals
5481                .retain(|(id, _), _| *id == main_thread_id || alive_thread_ids.contains(id));
5482            // Lua 5.1 side maps (empty on 5.2–5.5): drop a coroutine's
5483            // per-thread global table once the coroutine is gone, and a
5484            // closure's stored environment once that closure is unvisited.
5485            g.thread_globals
5486                .retain(|id, _| alive_thread_ids.contains(id));
5487            g.closure_envs
5488                .retain(|id, _| alive_closure_env_ids.contains(id));
5489            let promoted = g.finalizers.promote_pending_to_finalized(promote);
5490            for object in &promoted {
5491                if let Some(ptr) = object.heap_ptr() {
5492                    g.heap.move_finobj_to_tobefnz(ptr);
5493                }
5494            }
5495        }
5496
5497        let mut paused = matches!(outcome, StepOutcome::Paused);
5498        if target.is_none()
5499            && self._state.global().heap.gc_state() == lua_gc::GcState::CallFin
5500            && !self._state.global().finalizers.has_to_be_finalized()
5501        {
5502            paused = self._state.global().heap.finish_callfin_phase();
5503        }
5504
5505        paused
5506    }
5507
5508    /// Run only the weak-table atomic cleanup used by legacy generational
5509    /// callers that need mark/prune behavior without sweeping.
5510    ///
5511    /// Explicit generational steps now use [`Self::generational_step`], which
5512    /// performs a young sweep. This helper remains for call sites that only
5513    /// need the weak-table atomic pass.
5514    pub fn prune_weak_tables_mark_only(&self) {
5515        use lua_gc::Trace;
5516        let state_ref: &LuaState = &*self._state;
5517
5518        let weak_tables_snapshot: lua_gc::WeakRegistrySnapshot<GcRef<LuaTable>> = {
5519            let mut g = state_ref.global.borrow_mut();
5520            g.weak_tables_registry.live_snapshot_by_kind()
5521        };
5522        let _interned_capacity = {
5523            let g = state_ref.global.borrow();
5524            g.interned_lt.len()
5525        };
5526
5527        let dead_interned: std::cell::RefCell<Vec<(u32, usize)>> = std::cell::RefCell::new(Vec::new());
5528
5529        {
5530            let global = state_ref.global.borrow();
5531            global.heap.unpause();
5532            let roots = CollectRoots {
5533                global: &*global,
5534                thread: state_ref,
5535            };
5536            let hook = |marker: &mut lua_gc::Marker| {
5537                trace_reachable_threads(&*global, global.current_thread_id, marker);
5538                loop {
5539                    let visited_before = marker.visited_count();
5540                    for t in &weak_tables_snapshot.ephemeron {
5541                        let t_id = t.identity();
5542                        if !marker.is_visited(t_id) {
5543                            continue;
5544                        }
5545                        let to_mark = t.ephemeron_values_to_mark(&|id| marker.is_visited(id));
5546                        for v in &to_mark {
5547                            v.trace(marker);
5548                        }
5549                    }
5550                    marker.drain_gray_queue();
5551                    if marker.visited_count() == visited_before {
5552                        break;
5553                    }
5554                }
5555                for t in weak_snapshot_tables(&weak_tables_snapshot) {
5556                    if marker.is_visited(t.identity()) {
5557                        let to_mark = t.prune_weak_dead(&|id| marker.is_visited(id));
5558                        for v in &to_mark {
5559                            v.trace(marker);
5560                        }
5561                    }
5562                }
5563                marker.drain_gray_queue();
5564                record_dead_interned_strings(&*global, marker, &dead_interned);
5565            };
5566            global.heap.mark_only_with_post_mark(&roots, hook);
5567        }
5568
5569        let dead_interned = dead_interned.into_inner();
5570        let mut g = state_ref.global.borrow_mut();
5571        remove_dead_interned_strings(&mut *g, dead_interned);
5572    }
5573
5574    /// Set the GC kind (incremental/generational).
5575    pub fn change_mode(&self, mode: GcKind) {
5576        let old = self._state.global().gckind;
5577        if old == mode as u8 {
5578            self._state.global_mut().lastatomic = 0;
5579            return;
5580        }
5581        match mode {
5582            GcKind::Generational => {
5583                self.enter_generational_mode();
5584            }
5585            GcKind::Incremental => {
5586                self.enter_incremental_mode();
5587            }
5588        }
5589    }
5590
5591    /// No-op stub for `luaC_fix(L, o)` (pin an object so GC won't collect
5592    /// it). Called from `tagmethods.rs` for interned tag-method name
5593    /// strings, which stay alive via the traced `GlobalState::tmname` root
5594    /// instead.
5595    pub fn fix_object<T: lua_gc::Trace + 'static>(&self, _o: &GcRef<T>) { /* phase-b no-op */
5596    }
5597
5598    /// Free all collectable objects deterministically (called during state
5599    /// teardown by `close_state`), mirroring C-Lua `lua_close`'s guarantee
5600    /// that finalizers and frees complete before the call returns.
5601    ///
5602    /// Object destruction historically rode on `GlobalState`'s eventual `Rc`
5603    /// drop, so `close_state` could return with every heap object still live
5604    /// (issue #260). This now drains the heap through
5605    /// [`Heap::drop_all`](lua_gc::Heap::drop_all) — every destructor runs
5606    /// before this returns — and clears the `GlobalState`-side GC bookkeeping
5607    /// (weak-table registry, finalizer registry, external roots) whose entries
5608    /// would otherwise name freed boxes. `drop_all` clears the allocation-token
5609    /// map, so a pre-existing `GcWeak` stops upgrading immediately, and leaves
5610    /// the heap `closed`, so a `HeapGuard` that outlived close panics instead
5611    /// of resurrecting a torn-down heap.
5612    ///
5613    /// This does not *run* finalizers: `close_state` calls
5614    /// `api::run_close_finalizers` before invoking this on the complete-state
5615    /// branch (mirroring C's `luaC_freeallobjects` = `separatetobefnz` +
5616    /// `callallpendingfinalizers` + free); this only frees.
5617    ///
5618    /// A [`HeapGuard`](lua_gc::HeapGuard) for **this state's own heap** is
5619    /// pushed around the drain: a destructor that allocates via `GcRef::new`
5620    /// resolves the top of the TLS guard stack, so without the push its box
5621    /// would land in whatever heap the caller happened to have active — a
5622    /// different VM's heap under a foreign guard, or a panic with no guard at
5623    /// all. With it, teardown-time allocations always land in (and are drained
5624    /// from) the heap being closed, regardless of ambient guard state.
5625    /// The registry clears below also break the `GlobalState` ↔ coroutine
5626    /// reference cycle: each [`ThreadRegistryEntry`] holds an
5627    /// `Rc<RefCell<LuaState>>` whose `LuaState.global` is a strong
5628    /// `Rc<RefCell<GlobalState>>` back-edge, so a live suspended coroutine at
5629    /// close would otherwise keep the `GlobalState` — and its `Rc<Heap>` —
5630    /// alive forever after the outer state drops. The sibling cross-thread
5631    /// maps hold only `Copy` `GcRef` handles (no cycle), but those handles
5632    /// dangle once `drop_all` frees the boxes, so they are cleared with it.
5633    pub fn free_all_objects(&self) {
5634        let heap = self._state.global().heap.clone();
5635        {
5636            let _own_heap = lua_gc::HeapGuard::push(&heap);
5637            heap.drop_all();
5638        }
5639        let mut g = self._state.global_mut();
5640        g.weak_tables_registry = lua_gc::WeakRegistry::default();
5641        g.finalizers = lua_gc::FinalizerRegistry::default();
5642        g.external_roots = ExternalRootSet::default();
5643        g.threads.clear();
5644        g.thread_globals.clear();
5645        g.cross_thread_upvals.clear();
5646        g.suspended_parent_stacks.clear();
5647        g.suspended_parent_open_upvals.clear();
5648        g.twups.clear();
5649    }
5650
5651    /// GC write barrier for a TValue.
5652    pub fn barrier(&self, p: &dyn std::any::Any, v: &LuaValue) {
5653        let g = self._state.global();
5654        barrier_any(&g.heap, p, v, g.is_gen_mode(), BarrierKind::Forward);
5655    }
5656
5657    /// Backward write barrier.
5658    pub fn barrier_back(&self, p: &dyn std::any::Any, v: &LuaValue) {
5659        let g = self._state.global();
5660        barrier_any(&g.heap, p, v, g.is_gen_mode(), BarrierKind::Backward);
5661    }
5662
5663    /// Typed table backward barrier for table mutation hot paths.
5664    pub fn table_barrier_back(&self, p: &GcRef<LuaTable>, v: &LuaValue) {
5665        let g = self._state.global();
5666        barrier_lua_value(&g.heap, *p, v, g.is_gen_mode(), BarrierKind::Backward);
5667    }
5668
5669    /// Object write barrier.
5670    pub fn obj_barrier(&self, p: &dyn std::any::Any, o: &dyn std::any::Any) {
5671        let g = self._state.global();
5672        barrier_any(&g.heap, p, o, g.is_gen_mode(), BarrierKind::Forward);
5673    }
5674
5675    /// Backward object write barrier.
5676    ///
5677    pub fn obj_barrier_back(&self, p: &dyn std::any::Any, o: &dyn std::any::Any) {
5678        let g = self._state.global();
5679        barrier_any(&g.heap, p, o, g.is_gen_mode(), BarrierKind::Backward);
5680    }
5681}
5682
5683// ─── Functions from lstate.c ──────────────────────────────────────────────────
5684
5685/// C's `luai_makeseed` mixes ASLR entropy (pointer addresses of a heap var,
5686/// stack var, and code symbol) with the current time via `luaS_hash`. Raw
5687/// pointer addresses require `unsafe`, which is forbidden outside
5688/// lua-gc/lua-coro, so native builds use time-only entropy for now — a
5689/// pointer- or `getrandom`-based source would meaningfully improve
5690/// hash-DoS resistance and remains unaddressed. Bare WASM uses a fixed
5691/// seed so state creation never touches a stubbed host clock.
5692fn make_seed() -> u32 {
5693    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
5694    {
5695        return crate::string::hash_bytes(b"lua-rs-wasm-seed", 0x9e37_79b9);
5696    }
5697
5698    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
5699    {
5700        use std::time::{SystemTime, UNIX_EPOCH};
5701        let t = SystemTime::now()
5702            .duration_since(UNIX_EPOCH)
5703            .map(|d| d.as_secs() as u32)
5704            .unwrap_or(0);
5705
5706        crate::string::hash_bytes(&t.to_le_bytes(), t)
5707    }
5708}
5709
5710/// Adjust the compatibility `GCdebt` value against the collector-owned live
5711/// byte count.
5712pub(crate) fn set_debt(g: &mut GlobalState, mut debt: isize) {
5713    let tb = g.total_bytes() as isize;
5714    debug_assert!(tb > 0);
5715    // isize::MAX stands in for C's MAX_LMEM ceiling.
5716    if debt < tb.saturating_sub(isize::MAX) {
5717        debt = tb - isize::MAX;
5718    }
5719    g.gc_debt = debt;
5720}
5721
5722/// Deprecated no-op that returns `LUAI_MAXCCALLS`.
5723pub fn set_c_stack_limit(_state: &mut LuaState, _limit: u32) -> i32 {
5724    let _ = (_state, _limit);
5725    LUAI_MAXCCALLS as i32
5726}
5727
5728/// Allocate a fresh `CallInfo` beyond the current frame and return its index.
5729pub(crate) fn extend_ci(state: &mut LuaState) -> CallInfoIdx {
5730    debug_assert!(
5731        state.call_info[state.ci.0 as usize].next.is_none(),
5732        "extend_ci: current ci already has a cached next frame"
5733    );
5734
5735    let current_idx = state.ci;
5736    // Pushes onto the Vec rather than a separate heap allocation (`luaM_new`).
5737    let new_idx = CallInfoIdx(state.call_info.len() as u32);
5738
5739    state.call_info.push(CallInfo {
5740        previous: Some(current_idx),
5741        next: None,
5742        u: CallInfoFrame::lua_default(),
5743        ..CallInfo::default()
5744    });
5745
5746    state.call_info[current_idx.0 as usize].next = Some(new_idx);
5747
5748    state.nci += 1;
5749
5750    new_idx
5751}
5752
5753/// Free all cached (unused) `CallInfo` frames beyond the current frame.
5754///
5755/// In C, each `CallInfo` is an independent heap allocation freed by
5756/// `luaM_free`. Here, all `CallInfo` entries live in
5757/// `state.call_info: Vec<CallInfo>`: this walks the link chain to count
5758/// removals (updating `nci`), then truncates the Vec — safe as long as all
5759/// free entries have indices greater than `state.ci`.
5760fn free_ci(state: &mut LuaState) {
5761    let ci_idx = state.ci.0 as usize;
5762
5763    let mut next_opt = state.call_info[ci_idx].next.take();
5764
5765    while let Some(idx) = next_opt {
5766        next_opt = state.call_info[idx.0 as usize].next;
5767        state.nci = state.nci.saturating_sub(1);
5768    }
5769
5770    // Truncate: drop all entries beyond the current ci. Assumes all cached
5771    // frames have contiguous indices greater than state.ci; not verified.
5772    state.call_info.truncate(ci_idx + 1);
5773}
5774
5775/// Free approximately half of the cached `CallInfo` frames beyond the current frame.
5776///
5777/// The C code removes every other node from the free-list chain by pointer
5778/// manipulation. Removing elements from the middle of a `Vec` here would
5779/// shift subsequent elements and invalidate `CallInfoIdx` values that point
5780/// past the removal site, so this instead approximates by halving the free
5781/// count via truncation — an O(n) copy for the drop where a slab allocator
5782/// supporting O(1) removal without index invalidation would do better.
5783pub(crate) fn shrink_ci(state: &mut LuaState) {
5784    let ci_idx = state.ci.0 as usize;
5785
5786    if state.call_info[ci_idx].next.is_none() {
5787        return;
5788    }
5789
5790    let free_count = state.call_info.len().saturating_sub(ci_idx + 1);
5791    if free_count <= 1 {
5792        return;
5793    }
5794
5795    // Remove every other cached frame (halve the free list).
5796    let keep = free_count / 2;
5797    let removed = free_count - keep;
5798    let new_len = ci_idx + 1 + keep;
5799    state.call_info.truncate(new_len);
5800    state.nci = state.nci.saturating_sub(removed as u32);
5801
5802    // Terminate the now-last cached frame.
5803    if let Some(last) = state.call_info.last_mut() {
5804        last.next = None;
5805    }
5806}
5807
5808/// Check whether the C-call depth has reached its limit and raise an error if so.
5809pub(crate) fn check_c_stack(state: &mut LuaState) -> Result<(), LuaError> {
5810    // Mirrors luaG_runerror.
5811    if state.c_calls() == LUAI_MAXCCALLS {
5812        return Err(LuaError::runtime(format_args!("C stack overflow")));
5813    }
5814    // Mirrors luaD_throw(L, LUA_ERRERR).
5815    if state.c_calls() >= (LUAI_MAXCCALLS / 10 * 11) {
5816        return Err(LuaError::with_status(LuaStatus::ErrErr));
5817    }
5818    Ok(())
5819}
5820
5821/// Increment the C-call depth counter, checking for overflow.
5822pub fn inc_c_stack(state: &mut LuaState) -> Result<(), LuaError> {
5823    state.n_ccalls += 1;
5824    if state.c_calls() >= LUAI_MAXCCALLS {
5825        check_c_stack(state)?;
5826    }
5827    Ok(())
5828}
5829
5830/// In C, `L` is a separate thread used only for memory allocation (via
5831/// `luaM_newvector`). There is no custom allocator here; all allocation
5832/// goes through the global Rust allocator, so this takes only the new
5833/// thread (`thread`) and ignores the caller.
5834fn stack_init(thread: &mut LuaState) {
5835    let total_slots = BASIC_STACK_SIZE + EXTRA_STACK;
5836    thread.stack = vec![StackValue::default(); total_slots];
5837
5838    // In C, tbclist.p = stack.p is a sentinel meaning "no tbc vars"; here
5839    // the Vec is simply empty when there are no tbc variables.
5840    thread.tbclist = Vec::new();
5841
5842    // The new stack slots are already initialized to LuaValue::Nil via
5843    // StackValue::default().
5844
5845    thread.top = StackIdx(0);
5846
5847    thread.stack_last = StackIdx(BASIC_STACK_SIZE as u32);
5848
5849    let base_ci = CallInfo {
5850        func: StackIdx(0),
5851        top: StackIdx(1 + LUA_MINSTACK as u32),
5852        previous: None,
5853        next: None,
5854        callstatus: CIST_C,
5855        call_metamethods: 0,
5856        tailcalls: 0,
5857        nresults: 0,
5858        u: CallInfoFrame::c_default(),
5859        u2: CallInfoExtra::default(),
5860    };
5861
5862    if thread.call_info.is_empty() {
5863        thread.call_info.push(base_ci);
5864    } else {
5865        thread.call_info[0] = base_ci;
5866        thread.call_info.truncate(1);
5867    }
5868
5869    thread.stack[0] = StackValue {
5870        val: LuaValue::Nil,
5871    };
5872
5873    thread.top = StackIdx(1);
5874
5875    thread.ci = CallInfoIdx(0);
5876}
5877
5878fn free_stack(state: &mut LuaState) {
5879    if state.stack.is_empty() {
5880        return;
5881    }
5882    state.ci = CallInfoIdx(0);
5883    free_ci(state);
5884    debug_assert_eq!(state.nci, 0, "nci should be 0 after free_ci");
5885    state.stack.clear();
5886    state.stack.shrink_to_fit();
5887}
5888
5889/// Populate the registry table's fixed slots and the globals/loaded shadow
5890/// fields.
5891///
5892/// Mirrors C's `init_registry`, which sets `registry[LUA_RIDX_MAINTHREAD]`
5893/// to the main thread and `registry[LUA_RIDX_GLOBALS]` to the globals table
5894/// (`reference/lua-5.4.7/src/lstate.c`). Both have equivalents here:
5895/// `GlobalState::main_thread_value` is a `GcRef<LuaThread>` — a lightweight
5896/// identity handle (just a `u64` id), not the actual `LuaState` — built once
5897/// in `new_state` specifically so it can be shared without the
5898/// self-referential-`Rc` problem that would come from storing a
5899/// `GcRef<LuaState>` pointing at the state's own `GlobalState`; the globals
5900/// table is kept as a direct `GlobalState::globals` field for hot-path
5901/// lookups (`get_global_table`/`push_globals` read it there) and is *also*
5902/// mirrored into `registry[LUA_RIDX_GLOBALS]` here for C-API fidelity, so
5903/// `debug.getregistry()[2]` returns `_G`. `loaded` stays a direct field
5904/// only. Which numeric indices apply is version-dependent — see
5905/// [`set_versioned_registry_slots`].
5906///
5907/// The globals/loaded tables are created before that call so the globals
5908/// handle is available to write into the registry. Runs at the pre-override
5909/// default version (`new_state` always constructs with
5910/// `LuaVersion::default()`); a version-selecting entry point
5911/// (`bootstrap_state`, the CLI) calls [`set_versioned_registry_slots`] again
5912/// once the real version is known. Both calls happen during bootstrap,
5913/// before any user code — see that function's startup-only contract.
5914fn init_registry(state: &mut LuaState) -> Result<(), LuaError> {
5915    let registry = state.new_table();
5916    state.global_mut().l_registry = LuaValue::Table(registry);
5917
5918    let globals = state.new_table();
5919    state.global_mut().globals = LuaValue::Table(globals);
5920    let loaded = state.new_table();
5921    state.global_mut().loaded = LuaValue::Table(loaded);
5922
5923    set_versioned_registry_slots(state)?;
5924
5925    Ok(())
5926}
5927
5928/// Populate the version-dependent numeric registry slots — the main thread
5929/// and the globals table — for the current [`lua_types::LuaVersion`].
5930///
5931/// Which index holds what changed across the Lua line, so this is gated on
5932/// the active version (all indices verified against the reference binaries):
5933///
5934/// - **5.1** — no numeric registry convenience indices at all; globals live
5935///   in the per-thread environment (`fenv`), not the registry, and there is
5936///   no `LUA_RIDX_MAINTHREAD`. `debug.getregistry()` has no numeric keys.
5937/// - **5.2 / 5.3 / 5.4** — `registry[1]` is `LUA_RIDX_MAINTHREAD` (the main
5938///   thread) and `registry[2]` is `LUA_RIDX_GLOBALS` (the globals table).
5939///   `registry[3]` is the `luaL_ref` free-list head (`freelist =
5940///   LUA_RIDX_LAST + 1`; see `lua_ref` in lua-stdlib) and is NOT written
5941///   here.
5942/// - **5.5** — `LUA_RIDX_MAINTHREAD` was renumbered to `3`; `registry[2]` is
5943///   still the globals table; and `registry[1]` is initialized to `false`,
5944///   which is the `luaL_ref` free-list head's "uninitialized" sentinel in C
5945///   5.5 (`luaL_ref` accepts `nil` or `false` there before its first use),
5946///   not a placeholder reserved for some future index.
5947///
5948/// STARTUP-ONLY. This must run during VM bootstrap, before any user code or
5949/// `luaL_ref` call touches the registry. It is called twice in practice
5950/// (once from `init_registry` at the default version, once from the
5951/// version-selecting entry point once the real version is set). To make that
5952/// second call safe it clears a slot only when the slot still holds a value
5953/// *this function itself wrote* at the earlier default version (the
5954/// main-thread handle or the globals table) — never an arbitrary entry, so a
5955/// `luaL_ref` free-list head would survive. It is NOT a general reset and is
5956/// NOT safe to call after `luaL_ref`/user code has begun using the registry:
5957/// the 5.x set paths still overwrite `registry[1..=3]` with fixed values,
5958/// which post-startup could clobber a live reference. Do not expose it as
5959/// such.
5960pub fn set_versioned_registry_slots(state: &mut LuaState) -> Result<(), LuaError> {
5961    let registry = match state.global().l_registry.clone() {
5962        LuaValue::Table(t) => t,
5963        _ => return Ok(()),
5964    };
5965    let main_thread = LuaValue::Thread(state.global().main_thread_value.clone());
5966    let globals = state.global().globals.clone();
5967    let version = state.global().lua_version;
5968
5969    for idx in [1i64, LUA_RIDX_GLOBALS, 3] {
5970        let cur = registry.get_int(idx);
5971        if cur == main_thread || cur == globals {
5972            registry.raw_set_int(state, idx, LuaValue::Nil)?;
5973        }
5974    }
5975
5976    match version {
5977        lua_types::LuaVersion::V51 => {}
5978        lua_types::LuaVersion::V55 => {
5979            registry.raw_set_int(state, 1, LuaValue::Bool(false))?;
5980            registry.raw_set_int(state, LUA_RIDX_GLOBALS, globals)?;
5981            registry.raw_set_int(state, 3, main_thread)?;
5982        }
5983        _ => {
5984            registry.raw_set_int(state, LUA_RIDX_MAINTHREAD, main_thread)?;
5985            registry.raw_set_int(state, LUA_RIDX_GLOBALS, globals)?;
5986        }
5987    }
5988    Ok(())
5989}
5990
5991/// Pre-allocated out-of-memory message, built once at startup so the GC can
5992/// always hand back a valid error string even when the allocator is failing.
5993const MEMERR_MSG: &[u8] = b"not enough memory";
5994
5995/// Build the bootstrap out-of-memory message and pre-fill every API string
5996/// cache slot with it.
5997///
5998/// Must run once during bootstrap, before any allocation can fail. Goes
5999/// through [`LuaState::intern_str`] — the same interning path every other
6000/// Lua string in the VM uses — rather than a separate bootstrap-only string
6001/// table, so `GlobalState::memerrmsg` is an ordinary member of
6002/// `GlobalState::interned_lt` and the `GcRef::ptr_eq` identity check in
6003/// `api::lua_error` keeps working unchanged.
6004///
6005/// C fixes the message in the GC (`luaC_fix`, marking it non-collectable);
6006/// there is no equivalent call here (`state.gc().fix_object` is a no-op —
6007/// see its doc in state.rs). The message instead stays alive for the life
6008/// of the process simply because `GlobalState::memerrmsg` holds a
6009/// permanent strong reference to it.
6010fn init_memerrmsg(state: &mut LuaState) -> Result<(), LuaError> {
6011    let memerrmsg = state.intern_str(MEMERR_MSG)?;
6012    state.global_mut().memerrmsg = memerrmsg.clone();
6013
6014    for i in 0..STRCACHE_N {
6015        for j in 0..STRCACHE_M {
6016            state.global_mut().strcache[i][j] = memerrmsg.clone();
6017        }
6018    }
6019
6020    Ok(())
6021}
6022
6023/// Does not call `lua_lex::init`: that function pre-interns the reserved
6024/// words, mirroring C's `luaX_init`, but this port's keyword recognition
6025/// matches scanned bytes directly against `LUAX_TOKENS` rather than relying
6026/// on identity/tagging of a pre-created string (see `lua_lex::init`'s doc),
6027/// and every reserved word is re-interned anyway the first time it is
6028/// scanned. The call has no observable lexical/parse effect and no startup
6029/// correctness dependency, so it is unnecessary here, not missing.
6030fn lua_open(state: &mut LuaState) -> Result<(), LuaError> {
6031    stack_init(state);
6032    init_registry(state)?;
6033    init_memerrmsg(state)?;
6034    crate::tagmethods::init(state)?;
6035    state.global_mut().gcstp = 0;
6036    state.global().heap.unpause();
6037    // Setting nilvalue = Nil signals completestate() → is_complete() = true.
6038    state.global_mut().nilvalue = LuaValue::Nil;
6039    Ok(())
6040}
6041
6042fn preinit_thread(thread: &mut LuaState, global: Rc<RefCell<GlobalState>>) {
6043    thread.global = global;
6044    thread.stack = Vec::new();
6045    thread.call_info = Vec::new();
6046    // ci is initialized to 0 but call_info is empty; stack_init() must be
6047    // called before any use of call_info.
6048    thread.ci = CallInfoIdx(0);
6049    thread.nci = 0;
6050    // In C, L->twups = L is a self-reference sentinel meaning "no open
6051    // upvals". Here, GlobalState.twups is a Vec<GcRef<LuaState>>; absence
6052    // from that Vec is the sentinel, so there is no per-thread twups field.
6053    thread.n_ccalls = 0;
6054    thread.hook = None;
6055    thread.hookmask = 0;
6056    thread.basehookcount = 0;
6057    thread.allowhook = true;
6058    thread.hookcount = thread.basehookcount;
6059
6060    // Sandbox inheritance: a coroutine joins the runtime-wide instruction/memory
6061    // budget so metering spans every thread, not just the main one. The budget
6062    // itself lives in `GlobalState` (shared); the new thread only needs the
6063    // count-hook mask armed so the dispatch loop traps and charges it.
6064    {
6065        let (active, interval) = {
6066            let g = thread.global.borrow();
6067            (g.sandbox_active(), g.sandbox.interval.get())
6068        };
6069        if active {
6070            thread.hookmask = SANDBOX_COUNT_MASK;
6071            thread.basehookcount = interval;
6072            thread.hookcount = interval;
6073        }
6074    }
6075    thread.openupval = Vec::new();
6076    thread.status = LuaStatus::Ok as u8;
6077    thread.errfunc = 0;
6078    thread.oldpc = 0;
6079    thread.gc_check_needed = true;
6080}
6081
6082/// Tear down a state: run the remaining close-time `__gc` finalizers, then
6083/// free every heap object, mirroring C's `close_state` → `luaC_freeallobjects`
6084/// (= `separatetobefnz` + `callallpendingfinalizers` + free).
6085///
6086/// On the complete-state branch, `api::run_close_finalizers` fires the
6087/// finalizers BEFORE `free_all_objects` tears the boxes down (issue #260).
6088/// `run_close_finalizers` drains the pending registry via `take_pending`, so
6089/// it is idempotent — a host that already ran it (lua-cli's `pmain` does, and
6090/// then never calls `close`) sees a no-op here, never a double-run. The
6091/// incomplete branch (`lua_open` failed mid-bootstrap) has no registered
6092/// finalizers, so it goes straight to the free, as C does.
6093fn close_state(state: &mut LuaState) {
6094    let is_complete = state.global().is_complete();
6095
6096    if !is_complete {
6097        state.gc().free_all_objects();
6098    } else {
6099        state.ci = CallInfoIdx(0);
6100        crate::api::run_close_finalizers(state);
6101        state.gc().free_all_objects();
6102    }
6103
6104    free_stack(state);
6105
6106    // Rust's allocator (via Drop) handles deallocation of GlobalState and
6107    // LuaState automatically; there is no custom-allocator free call here.
6108}
6109
6110/// Allocate a fresh coroutine `LuaState`, register it under a new
6111/// `ThreadId`, and push the resulting `LuaValue::Thread(value)` onto
6112/// `state`'s stack.
6113///
6114/// If `initial_body` is `Some(f)`, `f` is also pushed onto the new
6115/// thread's stack so that `coroutine.status` reports `"suspended"`
6116/// rather than `"dead"`. `co_create` uses this to stage the body function
6117/// without a full stack transfer between threads.
6118pub fn new_thread(state: &mut LuaState, initial_body: Option<LuaValue>) -> Result<(), LuaError> {
6119    state.gc_pre_collect_clear();
6120    state.gc().check_step();
6121
6122    // Unlike C, where the new thread is GC-allocated as part of the allgc
6123    // list, this creates a plain `LuaState` owned by `Rc<RefCell<>>` outside
6124    // the traced heap; reachability while suspended is instead handled by
6125    // `trace_reachable_threads` and the cross-thread snapshot fields on
6126    // `GlobalState` (see their field docs).
6127
6128    let global_rc = state.global_rc();
6129    let hookmask = state.hookmask;
6130    let basehookcount = state.basehookcount;
6131
6132    let reserved_id = {
6133        let mut g = state.global_mut();
6134        let id = g.next_thread_id;
6135        g.next_thread_id += 1;
6136        id
6137    };
6138
6139    // Lua 5.1: a coroutine inherits its creator's global table (`l_gt`) at
6140    // creation, after which the two are independent. Seed the new thread's
6141    // `thread_globals` slot with the running thread's current `l_gt` so the
6142    // coroutine's `setfenv(0, t)` and freshly-loaded chunks resolve through
6143    // its own slot, never the main thread's `globals`. Inert on 5.2–5.5.
6144    if matches!(state.global().lua_version, lua_types::LuaVersion::V51) {
6145        let creator_id = state.global().current_thread_id;
6146        let creator_lgt = state.v51_thread_lgt(creator_id);
6147        state
6148            .global_mut()
6149            .thread_globals
6150            .insert(reserved_id, creator_lgt);
6151    }
6152
6153    let mut new_thread = LuaState {
6154        status: LuaStatus::Ok as u8,
6155        allowhook: true,
6156        nci: 0,
6157        top: StackIdx(0),
6158        stack_last: StackIdx(0),
6159        stack: Vec::new(),
6160        ci: CallInfoIdx(0),
6161        call_info: Vec::new(),
6162        openupval: Vec::new(),
6163        legacy_open_upval_touched: std::cell::Cell::new(false),
6164        tbclist: Vec::new(),
6165        global: global_rc.clone(),
6166        hook: None,
6167        hookmask: 0,
6168        basehookcount: 0,
6169        hookcount: 0,
6170        errfunc: 0,
6171        n_ccalls: 0,
6172        oldpc: 0,
6173        marked: 0,
6174        cached_thread_id: reserved_id,
6175        gc_check_needed: false,
6176    };
6177
6178    preinit_thread(&mut new_thread, global_rc);
6179
6180    new_thread.hookmask = hookmask;
6181    new_thread.basehookcount = basehookcount;
6182    // The hook function itself does not propagate to the new thread: `hook`
6183    // is a non-`Clone` `Box<dyn FnMut(...)>`, so only the mask/counts above
6184    // are copied; sharing the closure would need an `Arc<Mutex<...>>`.
6185    new_thread.reset_hook_count();
6186
6187    stack_init(&mut new_thread);
6188
6189    if let Some(body) = initial_body {
6190        new_thread.push(body);
6191    }
6192
6193    let thread_ref: Rc<RefCell<LuaState>> = Rc::new(RefCell::new(new_thread));
6194
6195    let value = {
6196        let mut g = state.global_mut();
6197        let id = reserved_id;
6198        let value = GcRef::new(lua_types::value::LuaThread::new(id));
6199        g.threads.insert(
6200            id,
6201            ThreadRegistryEntry {
6202                state: thread_ref,
6203                value: value.clone(),
6204            },
6205        );
6206        value
6207    };
6208
6209    state.push(LuaValue::Thread(value));
6210
6211    Ok(())
6212}
6213
6214/// Reset a thread to its base state, closing all to-be-closed variables.
6215///
6216/// Returns the final status code as an `i32` (mirrors the C API).
6217///
6218/// Mirrors C's `luaE_resetthread` (`reference/lua-5.4.7/src/lstate.c`) line
6219/// for line, including its final `luaD_reallocstack(L, ci->top.p -
6220/// L->stack.p, 0)` call — routed here through `crate::do_::realloc_stack`
6221/// with `raise_error = false`, matching C's `raiseerror = 0`. That routes
6222/// through the OOM/emergency-GC-stop path (the point of issue #275 item 4)
6223/// and updates `stack_last`, which the old raw `Vec::resize` left stale.
6224///
6225/// `realloc_stack` shrinks the logical stack length back down but, because
6226/// it goes through `Vec::resize_with`, leaves the backing allocation's
6227/// capacity at the high-water mark — a deliberate high-water policy that is
6228/// correct for the hot grow/shrink paths but means memory a coroutine grew
6229/// deep for is not returned. C's `luaM_reallocvector` reallocates to exactly
6230/// the new size, releasing that memory, so this cold reset path follows the
6231/// realloc with an explicit `shrink_to_fit` to reclaim the capacity too.
6232/// (`reset_thread` runs on coroutine close/reset, never in a hot loop, so
6233/// the extra realloc is not a concern.)
6234pub fn reset_thread(state: &mut LuaState, status: i32) -> i32 {
6235    // Public low-level entry point: the __close error path under
6236    // close_protected() materializes error messages, which requires an
6237    // active heap (issue #253 review). Self-sufficient like lua_resume.
6238    let _heap_guard = {
6239        let g = state.global.borrow();
6240        lua_gc::HeapGuard::push(&g.heap)
6241    };
6242    state.ci = CallInfoIdx(0);
6243    let ci_idx = 0usize;
6244
6245    if !state.stack.is_empty() {
6246        state.stack[0].val = LuaValue::Nil;
6247    }
6248
6249    state.call_info[ci_idx].func = StackIdx(0);
6250    state.call_info[ci_idx].call_metamethods = 0;
6251    state.call_info[ci_idx].callstatus = CIST_C;
6252
6253    let mut status = if status == LuaStatus::Yield as i32 {
6254        LuaStatus::Ok as i32
6255    } else {
6256        status
6257    };
6258
6259    state.status = LuaStatus::Ok as u8;
6260
6261    let close_status = crate::do_::close_protected(state, StackIdx(1), LuaStatus::from_raw(status));
6262    status = close_status as i32;
6263
6264    if status != LuaStatus::Ok as i32 {
6265        crate::do_::set_error_obj(state, LuaStatus::from_raw(status), StackIdx(1));
6266    } else {
6267        state.top = StackIdx(1);
6268    }
6269
6270    let new_ci_top = StackIdx(state.top.0 + LUA_MINSTACK as u32);
6271    state.call_info[ci_idx].top = new_ci_top;
6272
6273    let _ = crate::do_::realloc_stack(state, new_ci_top.0 as usize, false);
6274    state.stack.shrink_to_fit();
6275
6276    status
6277}
6278
6279/// Close a coroutine thread from the perspective of another thread.
6280pub fn close_thread(state: &mut LuaState, from: Option<&LuaState>) -> i32 {
6281    state.n_ccalls = match from {
6282        Some(f) => f.c_calls(),
6283        None => 0,
6284    };
6285    let current_status = state.status as i32;
6286    let result = reset_thread(state, current_status);
6287    result
6288}
6289
6290/// Deprecated wrapper for `close_thread(L, NULL)`.
6291pub fn reset_thread_api(state: &mut LuaState) -> i32 {
6292    close_thread(state, None)
6293}
6294
6295/// Create a new independent Lua state.  Returns `None` only on OOM.
6296///
6297/// The C API takes a custom allocator `(f, ud)`; the Rust-native API uses
6298/// the global Rust allocator instead, so those parameters are dropped.
6299/// Equivalent to `LuaState::new()` at the call site.
6300pub fn new_state() -> Option<LuaState> {
6301    // In Rust, allocation failure panics by default; we use Result internally.
6302
6303    // Build a dummy LuaString for memerrmsg and strcache initialization.
6304    // This is a chicken-and-egg problem: GlobalState.memerrmsg needs to be initialized
6305    // before init_memerrmsg runs, but init_memerrmsg is what creates the real one.
6306    // The heap is created ahead of the GlobalState literal so these two
6307    // pre-state allocations (the placeholder string and the main thread
6308    // value) can live on its heap-owned uncollected list instead of falling
6309    // through GcRef::new's detached arm — this was the last per-VM
6310    // process-lifetime leak, and removing it lets LUA_RS_GC_STRICT_GUARD
6311    // police the detached arm with zero sanctioned exceptions. Moving the
6312    // heap into the literal below is safe: the owner-list heads are Cells
6313    // whose GcBox pointees are stable heap allocations.
6314    let heap = lua_gc::Heap::new();
6315    let placeholder_str = GcRef(heap.allocate_uncollected(LuaString::placeholder()));
6316    let main_thread_value = GcRef(heap.allocate_uncollected(lua_types::value::LuaThread::new(0)));
6317
6318    let initial_white = 1u8 << WHITE0BIT;
6319
6320    // A non-nil nilvalue signals "state not yet complete"; see is_complete().
6321
6322    let global = GlobalState {
6323        parser_hook: None,
6324        cli_argv: None,
6325        cli_preload: None,
6326        lua_version: lua_types::LuaVersion::default(),
6327        file_loader_hook: None,
6328        file_open_hook: None,
6329        stdout_hook: None,
6330        stderr_hook: None,
6331        stdin_hook: None,
6332        env_hook: None,
6333        unix_time_hook: None,
6334        cpu_clock_hook: None,
6335        local_offset_hook: None,
6336        entropy_hook: None,
6337        temp_name_hook: None,
6338        popen_hook: None,
6339        io_streams: None,
6340        file_remove_hook: None,
6341        file_rename_hook: None,
6342        os_execute_hook: None,
6343        dynlib_load_hook: None,
6344        dynlib_symbol_hook: None,
6345        dynlib_unload_hook: None,
6346        sandbox: SandboxLimits::default(),
6347        gc_debt: 0,
6348        gc_estimate: 0,
6349        lastatomic: 0,
6350        l_registry: LuaValue::Nil,
6351        external_roots: ExternalRootSet::default(),
6352        globals: LuaValue::Nil,
6353        loaded: LuaValue::Nil,
6354        nilvalue: LuaValue::Int(0),
6355        seed: make_seed(),
6356        currentwhite: initial_white,
6357        gcstate: GCS_PAUSE,
6358        gckind: GcKind::Incremental as u8,
6359        gcstopem: false,
6360        genminormul: LUAI_GENMINORMUL,
6361        genmajormul: (LUAI_GENMAJORMUL / 4) as u8,
6362        gcstp: GCSTPGC,
6363        gcemergency: false,
6364        gcpause: (LUAI_GCPAUSE / 4) as u8,
6365        gcstepmul: (LUAI_GCMUL / 4) as u8,
6366        gcstepsize: LUAI_GCSTEPSIZE,
6367        // Lua 5.5 collectgarbage("param") defaults, observed on lua5.5.0:
6368        // [minormul, majorminor, minormajor, pause, stepmul, stepsize].
6369        gc55_params: [20, 50, 68, 250, 200, 9600],
6370        sweepgc_cursor: 0,
6371        weak_tables_registry: lua_gc::WeakRegistry::default(),
6372        finalizers: lua_gc::FinalizerRegistry::default(),
6373        gc_finalizer_error: None,
6374        twups: Vec::new(),
6375        panic: None,
6376        mainthread: None,
6377        threads: std::collections::HashMap::new(),
6378        main_thread_value,
6379        current_thread_id: 0,
6380        closing_thread_id: None,
6381        main_thread_id: 0,
6382        next_thread_id: 1,
6383        thread_globals: std::collections::HashMap::new(),
6384        closure_envs: std::collections::HashMap::new(),
6385        memerrmsg: placeholder_str.clone(),
6386        tmname: Vec::new(),
6387        mt: std::array::from_fn(|_| None),
6388        strcache: std::array::from_fn(|_| std::array::from_fn(|_| placeholder_str.clone())),
6389        interned_lt: InternedStringMap::default(),
6390        warnf: None,
6391        warn_mode: WarnMode::Off,
6392        test_warn_enabled: false,
6393        test_warn_on: false,
6394        test_warn_mode: TestWarnMode::Normal,
6395        test_warn_last_to_cont: false,
6396        test_warn_buffer: Vec::new(),
6397        c_functions: Vec::new(),
6398        heap,
6399        cross_thread_upvals: std::collections::HashMap::new(),
6400        suspended_parent_stacks: Vec::new(),
6401        suspended_parent_open_upvals: Vec::new(),
6402        snapshot_stack_pool: Vec::new(),
6403        snapshot_upval_pool: Vec::new(),
6404        resume_value_pool: Vec::new(),
6405        resume_upval_slot_pool: Vec::new(),
6406        resume_flush_pool: Vec::new(),
6407    };
6408
6409    let global_rc = Rc::new(RefCell::new(global));
6410
6411    // issue #249: from here through the end of lua_open() below (registry,
6412    // string pool, tagmethod tables), route allocations onto the heap's
6413    // bootstrap ("uncollected but heap-owned") list rather than the normal
6414    // collectable list. The object graph isn't self-consistent for root
6415    // tracing yet, and lua_open() clears `paused` partway through, so an
6416    // allocation-triggered step during setup must not sweep these objects.
6417    // Heap::drop_all() still frees them when the Lua instance drops — they
6418    // just never leak past that, unlike the previous `Gc::new_uncollected`
6419    // fallback. RAII scope: the lua_open error return below cannot leave the
6420    // heap stuck in bootstrap mode. Callers that continue bootstrapping
6421    // (stdlib install) open a nested window of their own; callers that use
6422    // new_state() directly (low-level GC tests) get a heap that allocates
6423    // normally once this scope drops at return.
6424    let _bootstrap_scope = global_rc.borrow().heap.bootstrap_scope();
6425    let _bootstrap_guard = lua_gc::HeapGuard::push(&global_rc.borrow().heap);
6426
6427    let initial_marked = initial_white;
6428
6429    let mut main_thread = LuaState {
6430        status: LuaStatus::Ok as u8,
6431        allowhook: true,
6432        nci: 0,
6433        top: StackIdx(0),
6434        stack_last: StackIdx(0),
6435        stack: Vec::new(),
6436        ci: CallInfoIdx(0),
6437        call_info: Vec::new(),
6438        openupval: Vec::new(),
6439        legacy_open_upval_touched: std::cell::Cell::new(false),
6440        tbclist: Vec::new(),
6441        global: global_rc.clone(),
6442        hook: None,
6443        hookmask: 0,
6444        basehookcount: 0,
6445        hookcount: 0,
6446        errfunc: 0,
6447        n_ccalls: 0,
6448        oldpc: 0,
6449        marked: initial_marked,
6450        cached_thread_id: 0,
6451        gc_check_needed: false,
6452    };
6453
6454    preinit_thread(&mut main_thread, global_rc.clone());
6455
6456    main_thread.inc_nny();
6457
6458    // `mainthread` is left `None` here — see its field doc on `GlobalState`.
6459
6460    // `lua_open` returns a `Result`, which already gives the same protection
6461    // C gets from wrapping `f_luaopen` in `luaD_rawrunprotected` (a setjmp/
6462    // longjmp catch point); calling it directly and matching the result is
6463    // the Rust-native equivalent, not a missing wrapper.
6464    match lua_open(&mut main_thread) {
6465        Ok(()) => {}
6466        Err(_) => {
6467            close_state(&mut main_thread);
6468            return None;
6469        }
6470    }
6471
6472    Some(main_thread)
6473}
6474
6475/// Close the Lua state and free all resources.
6476///
6477/// In C, `lua_close` gets the main thread via `G(L)->mainthread` and closes
6478/// that regardless of which thread is passed. Here, callers must pass the
6479/// main `LuaState` directly; this does not traverse to the main thread —
6480/// the caller owns the root state — and does not assert that `state` is
6481/// indeed the main thread before closing it.
6482pub fn close(mut state: LuaState) {
6483    close_state(&mut state);
6484}
6485
6486/// Forward a warning message through the configured warning sink.
6487pub(crate) fn warning(state: &mut LuaState, msg: &[u8], to_cont: bool) {
6488    let test_warn_enabled = state.global().test_warn_enabled;
6489    if test_warn_enabled {
6490        test_warn(state, msg, to_cont);
6491        return;
6492    }
6493
6494    // The warnf closure is taken out of GlobalState (and restored after the
6495    // call) rather than invoked while holding a borrow, so a closure that
6496    // calls back into Lua does not hit a re-entrant borrow_mut() panic.
6497    let has_warnf = state.global().warnf.is_some();
6498    if has_warnf {
6499        // Take the warnf closure out to avoid re-entrant borrow.
6500        let mut warnf = state.global_mut().warnf.take();
6501        if let Some(ref mut f) = warnf {
6502            f(msg, to_cont);
6503        }
6504        // Restore the closure.
6505        state.global_mut().warnf = warnf;
6506        return;
6507    }
6508    default_warn(state, msg, to_cont);
6509}
6510
6511fn test_warn(state: &mut LuaState, msg: &[u8], to_cont: bool) {
6512    let is_control = {
6513        let g = state.global();
6514        !g.test_warn_last_to_cont && !to_cont && msg.first() == Some(&b'@')
6515    };
6516    if is_control {
6517        let mut g = state.global_mut();
6518        match &msg[1..] {
6519            b"off" => g.test_warn_on = false,
6520            b"on" => g.test_warn_on = true,
6521            b"normal" => g.test_warn_mode = TestWarnMode::Normal,
6522            b"allow" => g.test_warn_mode = TestWarnMode::Allow,
6523            b"store" => g.test_warn_mode = TestWarnMode::Store,
6524            _ => {}
6525        }
6526        return;
6527    }
6528
6529    let finished = {
6530        let mut g = state.global_mut();
6531        g.test_warn_last_to_cont = to_cont;
6532        g.test_warn_buffer.extend_from_slice(msg);
6533        if to_cont {
6534            None
6535        } else {
6536            Some((
6537                std::mem::take(&mut g.test_warn_buffer),
6538                g.test_warn_mode,
6539                g.test_warn_on,
6540            ))
6541        }
6542    };
6543
6544    let Some((message, mode, warn_on)) = finished else {
6545        return;
6546    };
6547    match mode {
6548        TestWarnMode::Normal => {
6549            if warn_on && message.first() == Some(&b'#') {
6550                write_warning_message(&message);
6551            }
6552        }
6553        TestWarnMode::Allow => {
6554            if warn_on {
6555                write_warning_message(&message);
6556            }
6557        }
6558        TestWarnMode::Store => {
6559            if let Ok(s) = state.intern_str(&message) {
6560                state.push(LuaValue::Str(s));
6561                let _ = crate::api::set_global(state, b"_WARN");
6562            }
6563        }
6564    }
6565}
6566
6567fn write_warning_message(message: &[u8]) {
6568    use std::io::Write;
6569    let stderr = std::io::stderr();
6570    let mut h = stderr.lock();
6571    let _ = h.write_all(b"Lua warning: ");
6572    let _ = h.write_all(message);
6573    let _ = h.write_all(b"\n");
6574}
6575
6576/// The default warning handler: a faithful port of the `warnfoff` /
6577/// `warnfon` / `warnfcont` chain in upstream `lauxlib.c`. State is held in
6578/// `GlobalState::warn_mode` (C threads it via `lua_setwarnf`); output goes to
6579/// stderr (`lua_writestringerror`).
6580fn default_warn(state: &mut LuaState, msg: &[u8], to_cont: bool) {
6581    use std::io::Write;
6582    // checkcontrol: a leading-`@` non-continuation message is a control word.
6583    if !to_cont && msg.first() == Some(&b'@') {
6584        match &msg[1..] {
6585            b"off" => state.global_mut().warn_mode = WarnMode::Off,
6586            b"on" => state.global_mut().warn_mode = WarnMode::On,
6587            _ => {}
6588        }
6589        return;
6590    }
6591    let mode = state.global().warn_mode;
6592    match mode {
6593        WarnMode::Off => {}
6594        WarnMode::On | WarnMode::Cont => {
6595            let stderr = std::io::stderr();
6596            let mut h = stderr.lock();
6597            if mode == WarnMode::On {
6598                let _ = h.write_all(b"Lua warning: ");
6599            }
6600            let _ = h.write_all(msg);
6601            if to_cont {
6602                state.global_mut().warn_mode = WarnMode::Cont;
6603            } else {
6604                let _ = h.write_all(b"\n");
6605                state.global_mut().warn_mode = WarnMode::On;
6606            }
6607        }
6608    }
6609}
6610
6611#[cfg(test)]
6612mod tests {
6613    use super::*;
6614
6615    fn test_noop_cclosure(_: &mut LuaState) -> Result<usize, LuaError> {
6616        Ok(0)
6617    }
6618
6619    /// Issue #278: `new_userdata` (the untyped `lua_newuserdatauv` allocation
6620    /// step) builds a real full userdata rather than erroring. It carries
6621    /// `size` payload bytes, `nuvalue` nil user-value slots, and no metatable.
6622    #[test]
6623    fn new_userdata_builds_untyped_full_userdata() {
6624        let mut state = new_state().expect("state should initialize");
6625        let _heap_guard = {
6626            let g = state.global();
6627            lua_gc::HeapGuard::push(&g.heap)
6628        };
6629        let ud = state
6630            .new_userdata(16, 2)
6631            .expect("new_userdata should build, not error");
6632        assert_eq!(ud.data.len(), 16);
6633        assert_eq!(ud.uv.borrow().len(), 2);
6634        assert!(ud.uv.borrow().iter().all(|v| matches!(v, LuaValue::Nil)));
6635        assert!(ud.metatable.borrow().is_none());
6636    }
6637
6638    /// Issue #278: `new_c_closure` builds a light C function for `n == 0` and a
6639    /// full C closure with `n` nil upvalue slots for `n > 0`, rather than
6640    /// erroring.
6641    #[test]
6642    fn new_c_closure_builds_light_and_full_closures() {
6643        let mut state = new_state().expect("state should initialize");
6644        let _heap_guard = {
6645            let g = state.global();
6646            lua_gc::HeapGuard::push(&g.heap)
6647        };
6648        let light = state
6649            .new_c_closure(test_noop_cclosure, 0)
6650            .expect("light closure should build");
6651        assert!(
6652            matches!(light, LuaClosure::LightC(_)),
6653            "n==0 must yield a light C function"
6654        );
6655
6656        let full = state
6657            .new_c_closure(test_noop_cclosure, 3)
6658            .expect("full closure should build");
6659        match full {
6660            LuaClosure::C(ccl) => {
6661                let ups = ccl.upvalues.borrow();
6662                assert_eq!(ups.len(), 3);
6663                assert!(ups.iter().all(|v| matches!(v, LuaValue::Nil)));
6664            }
6665            _ => panic!("n>0 must yield a full C closure"),
6666        }
6667    }
6668
6669    /// Issue #278: `register_c_function` reuses an identical function's slot
6670    /// when `dedup` is set (the upvalue-less fast path) and always allocates a
6671    /// fresh slot otherwise (closures with upvalues must not share identity).
6672    #[test]
6673    fn register_c_function_dedups_only_when_requested() {
6674        let mut state = new_state().expect("state should initialize");
6675        let _heap_guard = {
6676            let g = state.global();
6677            lua_gc::HeapGuard::push(&g.heap)
6678        };
6679        let a = state.register_c_function(test_noop_cclosure, true);
6680        let b = state.register_c_function(test_noop_cclosure, true);
6681        assert_eq!(a, b, "dedup=true should reuse the identical fn's slot");
6682        let c = state.register_c_function(test_noop_cclosure, false);
6683        assert_ne!(a, c, "dedup=false must always allocate a fresh slot");
6684    }
6685
6686    /// Issue #278: `to_display_string` (C's `luaL_tolstring`; the single
6687    /// stringifier `auxlib::to_lua_string`, `tostring`, `print` and
6688    /// `debug.debug` all route through) must render a table with its real
6689    /// per-value address, never the old fixed `"0x?"` placeholder, and two
6690    /// distinct tables must render distinct addresses.
6691    #[test]
6692    fn to_display_string_renders_distinct_real_table_addresses() {
6693        let mut state = new_state().expect("state should initialize");
6694        let _heap_guard = {
6695            let g = state.global();
6696            lua_gc::HeapGuard::push(&g.heap)
6697        };
6698
6699        let t1 = state.new_table();
6700        state.push(LuaValue::Table(t1));
6701        let s1 = state
6702            .to_display_string(-1)
6703            .expect("to_display_string on table 1");
6704
6705        let t2 = state.new_table();
6706        state.push(LuaValue::Table(t2));
6707        let s2 = state
6708            .to_display_string(-1)
6709            .expect("to_display_string on table 2");
6710
6711        assert!(
6712            s1.starts_with(b"table: 0x"),
6713            "expected a real address, got {:?}",
6714            String::from_utf8_lossy(&s1)
6715        );
6716        assert!(
6717            !s1.windows(3).any(|w| w == b"0x?"),
6718            "the fixed '0x?' placeholder must be gone, got {:?}",
6719            String::from_utf8_lossy(&s1)
6720        );
6721        assert_ne!(s1, s2, "two distinct tables must render distinct addresses");
6722    }
6723
6724    /// Issue #278 fix-round finding 1: the raw `new_userdata` / `new_c_closure`
6725    /// constructors allocate `GcRef`s directly, so they must flag a GC check
6726    /// (the #276-class pacing invariant) — otherwise the debt accumulates with
6727    /// no safe point noticing.
6728    #[test]
6729    fn raw_constructors_flag_gc_check_needed() {
6730        let mut state = new_state().expect("state should initialize");
6731        let _heap_guard = {
6732            let g = state.global();
6733            lua_gc::HeapGuard::push(&g.heap)
6734        };
6735
6736        state.gc_check_needed = false;
6737        let _ = state.new_userdata(32, 1).expect("new_userdata");
6738        assert!(state.gc_check_needed, "new_userdata must flag a GC check");
6739
6740        state.gc_check_needed = false;
6741        let _ = state
6742            .new_c_closure(test_noop_cclosure, 2)
6743            .expect("new_c_closure n>0");
6744        assert!(
6745            state.gc_check_needed,
6746            "new_c_closure(n>0) must flag a GC check"
6747        );
6748    }
6749
6750    /// Issue #278 fix-round finding 2: light userdata renders with the plain
6751    /// `luaL_typename` "userdata" (as C's `luaL_tolstring` does), never the
6752    /// error-message-only "light userdata".
6753    #[test]
6754    fn to_display_string_light_userdata_uses_plain_userdata_name() {
6755        let mut state = new_state().expect("state should initialize");
6756        let _heap_guard = {
6757            let g = state.global();
6758            lua_gc::HeapGuard::push(&g.heap)
6759        };
6760        let ptr = 0x1234usize as *mut core::ffi::c_void;
6761        state.push(LuaValue::LightUserData(ptr));
6762        let s = state
6763            .to_display_string(-1)
6764            .expect("display light userdata");
6765        assert!(
6766            s.starts_with(b"userdata: 0x"),
6767            "expected 'userdata: 0x...', got {:?}",
6768            String::from_utf8_lossy(&s)
6769        );
6770        assert!(
6771            !s.starts_with(b"light userdata"),
6772            "must not use the error-message name 'light userdata'"
6773        );
6774    }
6775
6776    /// Issue #278 fix-round finding 3: a light C function's pointer must be its
6777    /// real code address, never the tiny `c_functions` registry index.
6778    #[test]
6779    fn to_pointer_lightc_is_real_address_not_index() {
6780        let mut state = new_state().expect("state should initialize");
6781        let _heap_guard = {
6782            let g = state.global();
6783            lua_gc::HeapGuard::push(&g.heap)
6784        };
6785        let cl = state
6786            .new_c_closure(test_noop_cclosure, 0)
6787            .expect("light C function");
6788        let idx = match cl {
6789            LuaClosure::LightC(i) => i,
6790            _ => panic!("n==0 must yield LightC"),
6791        };
6792        state.push(LuaValue::Function(cl));
6793        let ptr = crate::api::to_pointer(&state, -1).expect("LightC must have a pointer");
6794        assert!(
6795            ptr > u16::MAX as usize,
6796            "expected a real address, got {ptr:#x} (registry index was {idx})"
6797        );
6798        assert_eq!(
6799            ptr, test_noop_cclosure as usize,
6800            "must resolve to the registered fn's real address"
6801        );
6802    }
6803
6804    /// Issue #278 fix-round finding 6: `to_cfunction` resolves the registered
6805    /// bare fn for light C functions / C closures, and is `None` otherwise.
6806    #[test]
6807    fn to_cfunction_resolves_registered_fn() {
6808        let mut state = new_state().expect("state should initialize");
6809        let _heap_guard = {
6810            let g = state.global();
6811            lua_gc::HeapGuard::push(&g.heap)
6812        };
6813        let cl = state
6814            .new_c_closure(test_noop_cclosure, 0)
6815            .expect("light C function");
6816        state.push(LuaValue::Function(cl));
6817        let f = crate::api::to_cfunction(&state, -1).expect("to_cfunction must resolve");
6818        assert_eq!(f as usize, test_noop_cclosure as usize);
6819
6820        state.push(LuaValue::Int(7));
6821        assert!(
6822            crate::api::to_cfunction(&state, -1).is_none(),
6823            "non-function must yield None"
6824        );
6825    }
6826
6827    /// Issue #278 fix-round finding 5: `new_c_closure` validates the upvalue
6828    /// count against `0..=MAX_UPVAL` before registering anything, so an
6829    /// out-of-range count errors without polluting `c_functions`.
6830    #[test]
6831    fn new_c_closure_rejects_out_of_range_upvalue_count() {
6832        let mut state = new_state().expect("state should initialize");
6833        let _heap_guard = {
6834            let g = state.global();
6835            lua_gc::HeapGuard::push(&g.heap)
6836        };
6837        let before = state.global().c_functions.len();
6838        assert!(
6839            state.new_c_closure(test_noop_cclosure, 256).is_err(),
6840            "n>255 must error"
6841        );
6842        assert!(
6843            state.new_c_closure(test_noop_cclosure, -1).is_err(),
6844            "negative n must error"
6845        );
6846        assert_eq!(
6847            before,
6848            state.global().c_functions.len(),
6849            "an invalid upvalue count must not pollute c_functions"
6850        );
6851        assert!(
6852            state.new_c_closure(test_noop_cclosure, 255).is_ok(),
6853            "n==255 (MAX_UPVAL) must succeed"
6854        );
6855    }
6856
6857    /// Issue #275 item 2 + item 3: the version-dependent numeric registry
6858    /// slots — `LUA_RIDX_MAINTHREAD` (the main thread) and `LUA_RIDX_GLOBALS`
6859    /// (`_G`) — must match C's `init_registry` for every version, and the
6860    /// slots that don't apply must be absent. Verified against the reference
6861    /// binaries: 5.1 has no numeric registry keys; 5.2/5.3/5.4 use index 1 =
6862    /// mainthread, index 2 = globals; 5.5 uses index 3 = mainthread, index 2
6863    /// = globals, index 1 = false (the `luaL_ref` free-list sentinel).
6864    /// Exercises the default-constructed state (V54), then V51, V55, V52 in
6865    /// turn — the same transitions the startup callers make.
6866    #[test]
6867    fn registry_versioned_slots_match_version() {
6868        let mut state = new_state().expect("state should initialize");
6869        let _heap_guard = {
6870            let g = state.global();
6871            lua_gc::HeapGuard::push(&g.heap)
6872        };
6873
6874        let registry = match state.global().l_registry.clone() {
6875            LuaValue::Table(t) => t,
6876            other => panic!("l_registry should be a table, got {other:?}"),
6877        };
6878        let main_thread = LuaValue::Thread(state.global().main_thread_value.clone());
6879        let globals = state.global().globals.clone();
6880        assert!(matches!(globals, LuaValue::Table(_)), "globals should be a table");
6881
6882        assert_eq!(registry.get_int(1), main_thread);
6883        assert_eq!(registry.get_int(LUA_RIDX_GLOBALS), globals);
6884        assert_eq!(registry.get_int(3), LuaValue::Nil);
6885
6886        state.global_mut().lua_version = lua_types::LuaVersion::V51;
6887        set_versioned_registry_slots(&mut state).expect("V51 slot update should succeed");
6888        assert_eq!(registry.get_int(1), LuaValue::Nil);
6889        assert_eq!(registry.get_int(LUA_RIDX_GLOBALS), LuaValue::Nil);
6890        assert_eq!(registry.get_int(3), LuaValue::Nil);
6891
6892        state.global_mut().lua_version = lua_types::LuaVersion::V55;
6893        set_versioned_registry_slots(&mut state).expect("V55 slot update should succeed");
6894        assert_eq!(registry.get_int(1), LuaValue::Bool(false));
6895        assert_eq!(registry.get_int(LUA_RIDX_GLOBALS), globals);
6896        assert_eq!(registry.get_int(3), main_thread);
6897
6898        state.global_mut().lua_version = lua_types::LuaVersion::V52;
6899        set_versioned_registry_slots(&mut state).expect("V52 slot update should succeed");
6900        assert_eq!(registry.get_int(1), main_thread);
6901        assert_eq!(registry.get_int(LUA_RIDX_GLOBALS), globals);
6902        assert_eq!(registry.get_int(3), LuaValue::Nil);
6903    }
6904
6905    /// Issue #275 item 2 (idempotence/safety): a startup re-run of
6906    /// `set_versioned_registry_slots` must never clobber a registry entry it
6907    /// did not write itself — in particular the `luaL_ref` free-list head,
6908    /// which lives at `registry[3]` in this port (`FREELIST_REF`) for
6909    /// 5.2-5.4. Simulates a foreign entry at index 3, re-runs the setter at
6910    /// the same version, and confirms the foreign entry survives while the
6911    /// main-thread/globals slots are still correct.
6912    #[test]
6913    fn versioned_registry_slots_preserve_foreign_entries_on_rerun() {
6914        let mut state = new_state().expect("state should initialize");
6915        let _heap_guard = {
6916            let g = state.global();
6917            lua_gc::HeapGuard::push(&g.heap)
6918        };
6919
6920        let registry = match state.global().l_registry.clone() {
6921            LuaValue::Table(t) => t,
6922            other => panic!("l_registry should be a table, got {other:?}"),
6923        };
6924        let main_thread = LuaValue::Thread(state.global().main_thread_value.clone());
6925        let globals = state.global().globals.clone();
6926
6927        registry
6928            .raw_set_int(&mut state, 3, LuaValue::Int(99))
6929            .expect("seeding a foreign registry entry should succeed");
6930
6931        set_versioned_registry_slots(&mut state).expect("V54 re-run should succeed");
6932
6933        assert_eq!(registry.get_int(3), LuaValue::Int(99));
6934        assert_eq!(registry.get_int(1), main_thread);
6935        assert_eq!(registry.get_int(LUA_RIDX_GLOBALS), globals);
6936    }
6937
6938    /// Issue #275 item 4: `reset_thread` must route the post-close stack
6939    /// resize through `crate::do_::realloc_stack` rather than a raw
6940    /// `Vec::resize`, matching C's `luaE_resetthread`
6941    /// (`reference/lua-5.4.7/src/lstate.c`), whose final step is
6942    /// `luaD_reallocstack(L, ci->top.p - L->stack.p, 0)`. A raw resize only
6943    /// grows and never updates `stack_last`; this test first grows the stack
6944    /// well past a fresh reset's minimal size, then resets and checks that
6945    /// the logical length shrank, `stack_last` (`stack_size()`) reflects the
6946    /// new smaller size instead of the stale pre-reset one, AND the backing
6947    /// allocation's capacity was reclaimed (the `shrink_to_fit` that makes
6948    /// this faithful to C's `luaM_reallocvector` releasing memory — a plain
6949    /// `resize_with` would leave capacity at the high-water mark).
6950    #[test]
6951    fn reset_thread_shrinks_stack_and_updates_stack_last() {
6952        let mut state = new_state().expect("state should initialize");
6953        let _heap_guard = {
6954            let g = state.global();
6955            lua_gc::HeapGuard::push(&g.heap)
6956        };
6957
6958        let grown_size = state.stack_size() + 500;
6959        crate::do_::realloc_stack(&mut state, grown_size, false)
6960            .expect("growing the stack should succeed");
6961        assert_eq!(state.stack_size(), grown_size);
6962        assert_eq!(state.stack.len(), grown_size + EXTRA_STACK);
6963        let grown_capacity = state.stack.capacity();
6964
6965        let status = reset_thread(&mut state, LuaStatus::Ok as i32);
6966        assert_eq!(status, LuaStatus::Ok as i32);
6967
6968        let expected_size = (state.top.0 + LUA_MINSTACK as u32) as usize;
6969        assert_eq!(
6970            state.stack_size(),
6971            expected_size,
6972            "stack_last should track reset_thread's realloc instead of the stale pre-reset size"
6973        );
6974        assert_eq!(
6975            state.stack.len(),
6976            expected_size + EXTRA_STACK,
6977            "reset_thread should shrink the stack length back down, matching C's luaE_resetthread"
6978        );
6979        assert!(
6980            state.stack.capacity() < grown_capacity,
6981            "reset_thread should reclaim the backing capacity (was {}, now {})",
6982            grown_capacity,
6983            state.stack.capacity()
6984        );
6985    }
6986
6987    #[test]
6988    fn memerrmsg_is_the_same_object_a_matching_intern_str_call_returns() {
6989        let mut state = new_state().expect("state should initialize");
6990        let _heap_guard = {
6991            let g = state.global();
6992            lua_gc::HeapGuard::push(&g.heap)
6993        };
6994
6995        let memerrmsg = state.global().memerrmsg.clone();
6996        let interned = state
6997            .intern_str(crate::string::MAX_SHORT_LEN.to_string().as_bytes())
6998            .expect("interning a short string should not fail");
6999        assert!(!GcRef::ptr_eq(&memerrmsg, &interned));
7000
7001        let same_bytes = state
7002            .intern_str(memerrmsg.as_bytes())
7003            .expect("interning the memerrmsg bytes should not fail");
7004        assert!(
7005            GcRef::ptr_eq(&memerrmsg, &same_bytes),
7006            "memerrmsg must be a member of the same intern table as every other \
7007             short string, matching upstream Lua's `eqshrstr` identity semantics \
7008             (a script string spelling the OOM message aliases memerrmsg)"
7009        );
7010    }
7011
7012    #[test]
7013    fn external_root_keys_reject_stale_slot_after_reuse() {
7014        let mut roots = ExternalRootSet::default();
7015
7016        let first = roots.insert(LuaValue::Int(1));
7017        assert_eq!(roots.len(), 1);
7018        assert_eq!(roots.get(first), Some(&LuaValue::Int(1)));
7019
7020        assert_eq!(roots.remove(first), Some(LuaValue::Int(1)));
7021        assert!(roots.get(first).is_none());
7022        assert!(roots.remove(first).is_none());
7023        assert_eq!(roots.len(), 0);
7024        assert_eq!(roots.vacant_len(), 1);
7025        assert!(roots.replace(first, LuaValue::Int(9)).is_none());
7026        assert!(roots.is_empty());
7027
7028        let second = roots.insert(LuaValue::Int(2));
7029        assert_eq!(first.index, second.index);
7030        assert_ne!(first, second);
7031        assert!(roots.get(first).is_none());
7032        assert_eq!(roots.get(second), Some(&LuaValue::Int(2)));
7033        assert!(roots.replace(first, LuaValue::Int(3)).is_none());
7034    }
7035
7036    #[test]
7037    fn external_roots_keep_heap_value_alive_until_unrooted() {
7038        let mut state = new_state().expect("state should initialize");
7039        let _heap_guard = {
7040            let g = state.global();
7041            lua_gc::HeapGuard::push(&g.heap)
7042        };
7043
7044        let table = state.new_table();
7045        assert_eq!(state.global().heap.allgc_count(), 1);
7046
7047        let key = state.external_root_value(LuaValue::Table(table));
7048        state.gc().full_collect();
7049        assert_eq!(state.global().heap.allgc_count(), 1);
7050        assert_eq!(state.global().external_roots.len(), 1);
7051
7052        assert!(state.external_unroot_value(key).is_some());
7053        state.gc().full_collect();
7054        assert_eq!(state.global().heap.allgc_count(), 0);
7055        assert!(state.global().external_roots.is_empty());
7056    }
7057
7058    /// Issue #260 repro at the VM surface: `free_all_objects` (the body of
7059    /// `close_state`) must free heap objects and invalidate a pre-existing
7060    /// `GcWeak` immediately, with an outer `HeapGuard` and a strong `Rc<Heap>`
7061    /// both still alive — proving the weak dies because close cleared the
7062    /// allocation tokens, not because the heap `Rc` was dropped.
7063    #[test]
7064    fn free_all_objects_kills_weak_handle_while_guard_and_heap_alive() {
7065        let mut state = new_state().expect("state should initialize");
7066        let heap_rc = state.global().heap.clone();
7067        let guard = lua_gc::HeapGuard::push(&heap_rc);
7068
7069        let table = state.new_table();
7070        let weak = table.downgrade();
7071        assert!(
7072            weak.upgrade().is_some(),
7073            "weak handle upgrades while the table is live"
7074        );
7075
7076        state.gc().free_all_objects();
7077
7078        assert!(
7079            weak.upgrade().is_none(),
7080            "free_all_objects must free the table and drop its weak token during \
7081             the close call, with the outer HeapGuard and a strong heap Rc still alive"
7082        );
7083        assert!(state.global().heap.is_closed());
7084        assert!(std::rc::Rc::strong_count(&heap_rc) >= 1);
7085
7086        drop(guard);
7087        drop(state);
7088    }
7089
7090    thread_local! {
7091        static CLOSE_GC_RUNS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
7092    }
7093
7094    fn close_gc_probe(_state: &mut LuaState) -> Result<usize, LuaError> {
7095        CLOSE_GC_RUNS.with(|c| c.set(c.get() + 1));
7096        Ok(0)
7097    }
7098
7099    /// Build a table carrying a `__gc = gc_fn` metatable on `state`,
7100    /// registering it in the pending-finalizers list via the canonical
7101    /// `api::set_metatable` path, and leave the object table on the stack so
7102    /// it stays live to close.
7103    fn install_finalizable_table_with(state: &mut LuaState, gc_fn: LuaCFunction) {
7104        let heap = state.global().heap.clone();
7105        let _guard = lua_gc::HeapGuard::push(&heap);
7106        crate::api::create_table(state, 0, 0).expect("object table");
7107        crate::api::create_table(state, 0, 1).expect("metatable");
7108        crate::api::push_cclosure(state, gc_fn, 0).expect("push __gc");
7109        crate::api::set_field(state, -2, b"__gc").expect("mt.__gc");
7110        crate::api::set_metatable(state, -2).expect("setmetatable");
7111    }
7112
7113    fn install_finalizable_table(state: &mut LuaState) {
7114        install_finalizable_table_with(state, close_gc_probe);
7115    }
7116
7117    /// Codex finding 3 on issue #260: `state::close` must run close-time
7118    /// `__gc` finalizers (C `lua_close` → `luaC_freeallobjects` order) now
7119    /// that `free_all_objects` really frees — an object alive at close must
7120    /// observe its finalizer exactly once, before its box is torn down.
7121    #[test]
7122    fn state_close_runs_gc_finalizer_exactly_once() {
7123        CLOSE_GC_RUNS.with(|c| c.set(0));
7124        let mut state = new_state().expect("state should initialize");
7125        install_finalizable_table(&mut state);
7126        assert_eq!(
7127            CLOSE_GC_RUNS.with(|c| c.get()),
7128            0,
7129            "finalizer must not fire while the object is live"
7130        );
7131
7132        close(state);
7133        assert_eq!(
7134            CLOSE_GC_RUNS.with(|c| c.get()),
7135            1,
7136            "close must run the pending __gc exactly once before freeing"
7137        );
7138    }
7139
7140    /// The CLI composition half of finding 3: lua-cli's `pmain` calls
7141    /// `api::run_close_finalizers` itself before the state winds down. A
7142    /// subsequent `close_state` invocation must see the drained pending
7143    /// registry and not double-run the finalizer.
7144    #[test]
7145    fn manual_close_finalizer_pass_then_close_runs_gc_exactly_once() {
7146        CLOSE_GC_RUNS.with(|c| c.set(0));
7147        let mut state = new_state().expect("state should initialize");
7148        install_finalizable_table(&mut state);
7149
7150        crate::api::run_close_finalizers(&mut state);
7151        assert_eq!(CLOSE_GC_RUNS.with(|c| c.get()), 1);
7152
7153        close(state);
7154        assert_eq!(
7155            CLOSE_GC_RUNS.with(|c| c.get()),
7156            1,
7157            "close after a manual run_close_finalizers pass must not double-run __gc"
7158        );
7159    }
7160
7161    /// Codex round 2 finding 3 on #260, queue-only half: leftovers parked in
7162    /// `to_be_finalized` by a bounded incremental pass must still run at
7163    /// close even when `pending` is empty — the old early-return on empty
7164    /// `pending` silently dropped them.
7165    #[test]
7166    fn close_runs_queue_only_finalizer_leftovers() {
7167        CLOSE_GC_RUNS.with(|c| c.set(0));
7168        let mut state = new_state().expect("state should initialize");
7169        install_finalizable_table(&mut state);
7170
7171        {
7172            let mut g = state.global_mut();
7173            let pending: Vec<FinalizerObject> = g.finalizers.take_pending();
7174            assert!(!pending.is_empty());
7175            for object in pending.into_iter().rev() {
7176                let heap_ptr = object.heap_ptr();
7177                g.finalizers.push_to_be_finalized(object);
7178                if let Some(ptr) = heap_ptr {
7179                    g.heap.move_finobj_to_tobefnz(ptr);
7180                }
7181            }
7182            assert_eq!(g.finalizers.pending_len(), 0);
7183            assert!(g.finalizers.has_to_be_finalized());
7184        }
7185
7186        close(state);
7187        assert_eq!(
7188            CLOSE_GC_RUNS.with(|c| c.get()),
7189            1,
7190            "a finalizer parked in to_be_finalized with pending empty must \
7191             still run at close"
7192        );
7193    }
7194
7195    /// `__gc` probe that counts its run and re-registers ITS OWN object for
7196    /// finalization again (setmetatable with the same probe). Used to prove
7197    /// close's cross-pass exactly-once holds for queue-only objects: their
7198    /// identities enter `seen` via the entry seed, not via `take_pending`.
7199    fn self_reregister_gc_probe(state: &mut LuaState) -> Result<usize, LuaError> {
7200        CLOSE_GC_RUNS.with(|c| c.set(c.get() + 1));
7201        crate::api::push_value(state, 1);
7202        crate::api::create_table(state, 0, 1)?;
7203        crate::api::push_cclosure(state, self_reregister_gc_probe, 0)?;
7204        crate::api::set_field(state, -2, b"__gc")?;
7205        crate::api::set_metatable(state, -2)?;
7206        state.pop();
7207        Ok(0)
7208    }
7209
7210    /// Codex round-3 finding on #260: a queue-only object (already parked in
7211    /// `to_be_finalized` when close starts) never passes through
7212    /// `take_pending`, so without seeding `seen` from `to_be_finalized` at
7213    /// entry, its self-re-registration would pass the seen-check and its
7214    /// `__gc` would run a second time. Must run exactly once.
7215    #[test]
7216    fn queue_only_self_reregistering_finalizer_runs_exactly_once() {
7217        CLOSE_GC_RUNS.with(|c| c.set(0));
7218        let mut state = new_state().expect("state should initialize");
7219        install_finalizable_table_with(&mut state, self_reregister_gc_probe);
7220
7221        {
7222            let mut g = state.global_mut();
7223            let pending: Vec<FinalizerObject> = g.finalizers.take_pending();
7224            assert!(!pending.is_empty());
7225            for object in pending.into_iter().rev() {
7226                let heap_ptr = object.heap_ptr();
7227                g.finalizers.push_to_be_finalized(object);
7228                if let Some(ptr) = heap_ptr {
7229                    g.heap.move_finobj_to_tobefnz(ptr);
7230                }
7231            }
7232            assert_eq!(g.finalizers.pending_len(), 0);
7233            assert!(g.finalizers.has_to_be_finalized());
7234        }
7235
7236        close(state);
7237        assert_eq!(
7238            CLOSE_GC_RUNS.with(|c| c.get()),
7239            1,
7240            "a self-re-registering queue-only finalizer must run exactly \
7241             once at close — seen must be seeded from to_be_finalized"
7242        );
7243    }
7244
7245    fn regen_gc_probe(state: &mut LuaState) -> Result<usize, LuaError> {
7246        CLOSE_GC_RUNS.with(|c| c.set(c.get() + 1));
7247        crate::api::create_table(state, 0, 0)?;
7248        crate::api::create_table(state, 0, 1)?;
7249        crate::api::push_cclosure(state, close_gc_probe, 0)?;
7250        crate::api::set_field(state, -2, b"__gc")?;
7251        crate::api::set_metatable(state, -2)?;
7252        state.pop();
7253        Ok(0)
7254    }
7255
7256    /// Codex round 2 finding 3 on #260, re-registration half: a `__gc` that
7257    /// registers a fresh finalizable object during the close drain must have
7258    /// that object's finalizer run by a later pass of the both-queue loop
7259    /// (once each — the cross-pass seen-set prevents re-running).
7260    #[test]
7261    fn finalizer_registering_new_finalizable_during_close_runs_it() {
7262        CLOSE_GC_RUNS.with(|c| c.set(0));
7263        let mut state = new_state().expect("state should initialize");
7264        install_finalizable_table_with(&mut state, regen_gc_probe);
7265
7266        close(state);
7267        assert_eq!(
7268            CLOSE_GC_RUNS.with(|c| c.get()),
7269            2,
7270            "regen_gc_probe runs once, and the fresh finalizable it registered \
7271             during the drain runs exactly once on a later pass"
7272        );
7273    }
7274
7275    /// Codex round 2 finding 5 on #260: `GlobalState::threads` holds
7276    /// `Rc<RefCell<LuaState>>` entries whose `.global` is a strong back-edge
7277    /// to the `GlobalState` — a live suspended coroutine at close is a
7278    /// reference cycle that would keep the heap alive forever after the
7279    /// outer state drops. `free_all_objects` must break it.
7280    #[test]
7281    fn close_with_live_coroutine_lets_heap_drop() {
7282        let mut state = new_state().expect("state should initialize");
7283        let heap_weak = std::rc::Rc::downgrade(&state.global().heap);
7284        {
7285            let heap = state.global().heap.clone();
7286            let _guard = lua_gc::HeapGuard::push(&heap);
7287            new_thread(&mut state, None).expect("coroutine creation");
7288        }
7289        assert_eq!(state.global().threads.len(), 1);
7290
7291        close(state);
7292        assert!(
7293            heap_weak.upgrade().is_none(),
7294            "the heap must actually drop once the outer state drops after \
7295             close — a lingering threads-map cycle would keep it alive"
7296        );
7297    }
7298
7299    /// Flips its flag when dropped; the inner payload for
7300    /// [`VmAllocOnDrop`]'s teardown-time allocation.
7301    struct VmDropFlag(std::rc::Rc<std::cell::Cell<bool>>);
7302    impl lua_gc::Trace for VmDropFlag {
7303        fn trace(&self, _m: &mut lua_gc::Marker) {}
7304    }
7305    impl Drop for VmDropFlag {
7306        fn drop(&mut self) {
7307            self.0.set(true);
7308        }
7309    }
7310
7311    /// A payload whose `Drop` allocates through `GcRef::new` — the path every
7312    /// real VM destructor uses — so it resolves the top of the TLS guard
7313    /// stack. Pins codex finding 4 on issue #260: `free_all_objects` must
7314    /// push a guard for the state's own heap or this lands in the wrong heap
7315    /// (or panics with no ambient guard at all).
7316    struct VmAllocOnDrop {
7317        flag: std::rc::Rc<std::cell::Cell<bool>>,
7318        inner: std::rc::Rc<std::cell::Cell<bool>>,
7319    }
7320    impl lua_gc::Trace for VmAllocOnDrop {
7321        fn trace(&self, _m: &mut lua_gc::Marker) {}
7322    }
7323    impl Drop for VmAllocOnDrop {
7324        fn drop(&mut self) {
7325            self.flag.set(true);
7326            let _ = GcRef::new(VmDropFlag(self.inner.clone()));
7327        }
7328    }
7329
7330    #[test]
7331    fn free_all_objects_provides_own_heap_guard_with_no_ambient_guard() {
7332        let mut state = new_state().expect("state should initialize");
7333        let heap = state.global().heap.clone();
7334        let outer = std::rc::Rc::new(std::cell::Cell::new(false));
7335        let inner = std::rc::Rc::new(std::cell::Cell::new(false));
7336        let _gc = heap.allocate(VmAllocOnDrop {
7337            flag: outer.clone(),
7338            inner: inner.clone(),
7339        });
7340
7341        state.gc().free_all_objects();
7342
7343        assert!(outer.get(), "the destructor itself must have run");
7344        assert!(
7345            inner.get(),
7346            "GcRef::new inside a teardown destructor must land in the closing \
7347             heap (via free_all_objects's own guard) and be drained, even with \
7348             no ambient HeapGuard"
7349        );
7350        assert!(heap.is_closed());
7351    }
7352
7353    #[test]
7354    fn free_all_objects_targets_own_heap_under_foreign_guard() {
7355        let mut state1 = new_state().expect("state 1 should initialize");
7356        let state2 = new_state().expect("state 2 should initialize");
7357        let heap1 = state1.global().heap.clone();
7358        let heap2 = state2.global().heap.clone();
7359        let _foreign = lua_gc::HeapGuard::push(&heap2);
7360
7361        let outer = std::rc::Rc::new(std::cell::Cell::new(false));
7362        let inner = std::rc::Rc::new(std::cell::Cell::new(false));
7363        let _gc = heap1.allocate(VmAllocOnDrop {
7364            flag: outer.clone(),
7365            inner: inner.clone(),
7366        });
7367        let heap2_baseline = heap2.allgc_count();
7368
7369        state1.gc().free_all_objects();
7370
7371        assert!(outer.get());
7372        assert!(
7373            inner.get(),
7374            "the teardown allocation must land in (and be drained from) the \
7375             heap being closed, not the foreign heap on the TLS guard stack"
7376        );
7377        assert_eq!(
7378            heap2.allgc_count(),
7379            heap2_baseline,
7380            "the foreign heap must be untouched by another state's close"
7381        );
7382        assert!(heap1.is_closed());
7383        assert!(!heap2.is_closed());
7384        drop(state2);
7385    }
7386
7387    #[test]
7388    fn interned_string_table_grows_then_shrinks_on_collection() {
7389        let mut state = new_state().expect("state should initialize");
7390        let _heap_guard = {
7391            let g = state.global();
7392            lua_gc::HeapGuard::push(&g.heap)
7393        };
7394
7395        let initial_buckets = state.global().interned_lt.bucket_count();
7396        assert_eq!(
7397            initial_buckets, 64,
7398            "the intern table starts at C's MINSTRTABSIZE-equivalent of 64"
7399        );
7400        let baseline_live = state.global().interned_lt.len();
7401
7402        let mut anchors: Vec<GcRef<LuaString>> = Vec::with_capacity(2000);
7403        for i in 0..2000usize {
7404            let key = format!("intern-shrink-probe-{i:08}");
7405            let s = state
7406                .intern_str(key.as_bytes())
7407                .expect("short string interns");
7408            anchors.push(s);
7409        }
7410
7411        let grown_buckets = state.global().interned_lt.bucket_count();
7412        assert_eq!(
7413            state.global().interned_lt.len(),
7414            baseline_live + 2000,
7415            "all 2000 distinct short strings are interned and live alongside \
7416             the runtime's own rooted strings"
7417        );
7418        assert!(
7419            grown_buckets >= 2048,
7420            "interning 2000 strings must force several bucket doublings past \
7421             the initial 64 (saw {grown_buckets})"
7422        );
7423
7424        drop(anchors);
7425        state.gc().full_collect();
7426
7427        let shrunk_buckets = state.global().interned_lt.bucket_count();
7428        let surviving_live = state.global().interned_lt.len();
7429        assert!(
7430            surviving_live <= baseline_live,
7431            "every probe string is unreachable and must be swept out of the \
7432             intern table, leaving at most the runtime's own strings (baseline \
7433             {baseline_live}, surviving {surviving_live})"
7434        );
7435        assert!(
7436            surviving_live < 2000,
7437            "the 2000 probe strings must not survive collection (surviving \
7438             {surviving_live})"
7439        );
7440        assert_eq!(
7441            shrunk_buckets, 64,
7442            "the batch-end shrink check must reclaim the stale buckets back to \
7443             the 64-bucket floor (saw {shrunk_buckets}, grew to {grown_buckets})"
7444        );
7445        assert!(
7446            shrunk_buckets < grown_buckets,
7447            "shrink must strictly reduce the bucket array"
7448        );
7449    }
7450
7451    #[test]
7452    fn table_buffer_accounting_refunds_on_sweep() {
7453        let mut state = new_state().expect("state should initialize");
7454        let _heap_guard = {
7455            let g = state.global();
7456            lua_gc::HeapGuard::push(&g.heap)
7457        };
7458
7459        let table = state.new_table();
7460        let key = state.external_root_value(LuaValue::Table(table));
7461        let header_bytes = state.global().heap.bytes_used();
7462        assert!(header_bytes > 0);
7463
7464        for i in 1..=128 {
7465            table
7466                .raw_set_int(&mut state, i, LuaValue::Int(i))
7467                .expect("integer table insert should succeed");
7468        }
7469        let grown_bytes = state.global().heap.bytes_used();
7470        assert!(
7471            grown_bytes > header_bytes,
7472            "table array/hash buffer growth must be charged to the GC heap"
7473        );
7474
7475        state.gc().full_collect();
7476        assert_eq!(
7477            state.global().heap.bytes_used(),
7478            grown_bytes,
7479            "rooted table buffer bytes should remain charged after collection"
7480        );
7481
7482        assert!(state.external_unroot_value(key).is_some());
7483        state.gc().full_collect();
7484        assert_eq!(state.global().heap.bytes_used(), 0);
7485        assert_eq!(state.global().heap.allgc_count(), 0);
7486    }
7487
7488    #[test]
7489    fn userdata_buffer_accounting_refunds_on_sweep() {
7490        let mut state = new_state().expect("state should initialize");
7491        let _heap_guard = {
7492            let g = state.global();
7493            lua_gc::HeapGuard::push(&g.heap)
7494        };
7495
7496        let payload_len = 4096;
7497        let userdata = state
7498            .new_userdata_typed(b"accounting", payload_len, 3)
7499            .expect("userdata allocation should succeed");
7500        state.pop_n(1);
7501        let key = state.external_root_value(LuaValue::UserData(userdata));
7502        let allocated_bytes = state.global().heap.bytes_used();
7503        assert!(
7504            allocated_bytes > payload_len,
7505            "userdata payload bytes must be charged to the GC heap"
7506        );
7507
7508        state.gc().full_collect();
7509        assert_eq!(
7510            state.global().heap.bytes_used(),
7511            allocated_bytes,
7512            "rooted userdata payload bytes should remain charged after collection"
7513        );
7514
7515        assert!(state.external_unroot_value(key).is_some());
7516        state.gc().full_collect();
7517        assert_eq!(state.global().heap.bytes_used(), 0);
7518        assert_eq!(state.global().heap.allgc_count(), 0);
7519    }
7520
7521    #[test]
7522    fn cclosure_upvalue_accounting_refunds_on_sweep() {
7523        let mut state = new_state().expect("state should initialize");
7524        let _heap_guard = {
7525            let g = state.global();
7526            lua_gc::HeapGuard::push(&g.heap)
7527        };
7528
7529        let nupvalues = 64;
7530        for i in 0..nupvalues {
7531            state.push(LuaValue::Int(i as i64));
7532        }
7533        crate::api::push_cclosure(&mut state, test_noop_cclosure, nupvalues as i32)
7534            .expect("C closure creation should succeed");
7535        let LuaValue::Function(LuaClosure::C(ccl)) = state.get_at(state.top_idx() - 1) else {
7536            panic!("expected heavy C closure");
7537        };
7538        let expected_payload = ccl.buffer_bytes();
7539        let key = state.external_root_value(LuaValue::Function(LuaClosure::C(ccl)));
7540        state.pop_n(1);
7541        let allocated_bytes = state.global().heap.bytes_used();
7542        assert!(
7543            allocated_bytes >= expected_payload,
7544            "C closure upvalue vector bytes must be charged to the GC heap"
7545        );
7546
7547        state.gc().full_collect();
7548        assert_eq!(
7549            state.global().heap.bytes_used(),
7550            allocated_bytes,
7551            "rooted C closure payload bytes should remain charged after collection"
7552        );
7553
7554        assert!(state.external_unroot_value(key).is_some());
7555        state.gc().full_collect();
7556        assert_eq!(state.global().heap.bytes_used(), 0);
7557        assert_eq!(state.global().heap.allgc_count(), 0);
7558    }
7559
7560    #[test]
7561    fn proto_and_lclosure_accounting_refunds_on_sweep() {
7562        let mut state = new_state().expect("state should initialize");
7563        let _heap_guard = {
7564            let g = state.global();
7565            lua_gc::HeapGuard::push(&g.heap)
7566        };
7567
7568        let mut proto = LuaProto::placeholder();
7569        proto.code = vec![lua_types::opcode::Instruction(0); 2048];
7570        proto.lineinfo = vec![0; 2048];
7571        proto.k = vec![LuaValue::Int(1); 512];
7572        let expected_proto_payload = proto.buffer_bytes();
7573        let proto = GcRef::new(proto);
7574        proto.account_buffer(expected_proto_payload as isize);
7575
7576        let closure = state.new_lclosure(proto, 16);
7577        let expected_closure_payload = closure.buffer_bytes();
7578        let key = state.external_root_value(LuaValue::Function(LuaClosure::Lua(closure)));
7579        let allocated_bytes = state.global().heap.bytes_used();
7580        assert!(
7581            allocated_bytes >= expected_proto_payload + expected_closure_payload,
7582            "proto and Lua closure vector bytes must be charged to the GC heap"
7583        );
7584
7585        state.gc().full_collect();
7586        assert_eq!(
7587            state.global().heap.bytes_used(),
7588            allocated_bytes,
7589            "rooted proto and Lua closure payload bytes should remain charged after collection"
7590        );
7591
7592        assert!(state.external_unroot_value(key).is_some());
7593        state.gc().full_collect();
7594        assert_eq!(state.global().heap.bytes_used(), 0);
7595        assert_eq!(state.global().heap.allgc_count(), 0);
7596    }
7597
7598    #[test]
7599    fn string_buffer_accounting_refunds_on_sweep() {
7600        let mut state = new_state().expect("state should initialize");
7601        let _heap_guard = {
7602            let g = state.global();
7603            lua_gc::HeapGuard::push(&g.heap)
7604        };
7605
7606        let payload = vec![b'x'; crate::string::MAX_SHORT_LEN + 4096];
7607        let string = state
7608            .intern_str(&payload)
7609            .expect("long string should allocate");
7610        let key = state.external_root_value(LuaValue::Str(string));
7611        let allocated_bytes = state.global().heap.bytes_used();
7612        assert!(
7613            allocated_bytes > payload.len(),
7614            "long string backing bytes must be charged to the GC heap"
7615        );
7616
7617        state.gc().full_collect();
7618        assert_eq!(
7619            state.global().heap.bytes_used(),
7620            allocated_bytes,
7621            "rooted string buffer bytes should remain charged after collection"
7622        );
7623
7624        assert!(state.external_unroot_value(key).is_some());
7625        state.gc().full_collect();
7626        assert_eq!(state.global().heap.bytes_used(), 0);
7627        assert_eq!(state.global().heap.allgc_count(), 0);
7628    }
7629
7630    #[test]
7631    fn interned_short_string_cache_does_not_root_unreferenced_string() {
7632        let mut state = new_state().expect("state should initialize");
7633        let _heap_guard = {
7634            let g = state.global();
7635            lua_gc::HeapGuard::push(&g.heap)
7636        };
7637
7638        let payload = b"weak-cache-probe-a";
7639        let string = state
7640            .intern_str(payload)
7641            .expect("short string should intern");
7642        let id = string.identity();
7643        assert!(state.global().interned_lt.contains_key(&payload[..]));
7644        assert_eq!(
7645            state.global().heap.register_allocation_token(id),
7646            state.global().heap.register_allocation_token(id),
7647            "token registration is get-or-insert while the string is provably live"
7648        );
7649        assert!(state.global().heap.allocation_token(id).is_some());
7650
7651        state.gc().full_collect();
7652        assert!(!state.global().interned_lt.contains_key(&payload[..]));
7653        assert_eq!(state.global().heap.allocation_token(id), None);
7654    }
7655
7656    #[test]
7657    fn interned_short_string_cache_keeps_reachable_string_until_unrooted() {
7658        let mut state = new_state().expect("state should initialize");
7659        let _heap_guard = {
7660            let g = state.global();
7661            lua_gc::HeapGuard::push(&g.heap)
7662        };
7663
7664        let payload = b"weak-cache-probe-b";
7665        let string = state
7666            .intern_str(payload)
7667            .expect("short string should intern");
7668        let id = string.identity();
7669        state.global().heap.register_allocation_token(id);
7670        let key = state.external_root_value(LuaValue::Str(string));
7671
7672        state.gc().full_collect();
7673        assert!(state.global().interned_lt.contains_key(&payload[..]));
7674        assert!(state.global().heap.allocation_token(id).is_some());
7675
7676        assert!(state.external_unroot_value(key).is_some());
7677        state.gc().full_collect();
7678        assert!(!state.global().interned_lt.contains_key(&payload[..]));
7679        assert_eq!(state.global().heap.allocation_token(id), None);
7680    }
7681
7682    #[test]
7683    fn gc_phase_predicates_follow_heap_state() {
7684        let mut state = new_state().expect("state should initialize");
7685        let _heap_guard = {
7686            let g = state.global();
7687            lua_gc::HeapGuard::push(&g.heap)
7688        };
7689
7690        {
7691            let mut g = state.global_mut();
7692            g.gckind = GcKind::Incremental as u8;
7693            g.lastatomic = 0;
7694            assert!(!g.is_gen_mode());
7695            g.lastatomic = 1;
7696            assert!(g.is_gen_mode());
7697            g.lastatomic = 0;
7698        }
7699
7700        let mut roots = Vec::new();
7701        for _ in 0..16 {
7702            let table = state.new_table();
7703            roots.push(state.external_root_value(LuaValue::Table(table)));
7704        }
7705
7706        let mut saw_keep = false;
7707        let mut saw_sweep = false;
7708        for _ in 0..128 {
7709            state.gc().incremental_step(1);
7710            let g = state.global();
7711            let heap_state = g.heap.gc_state();
7712            assert_eq!(g.keep_invariant(), heap_state.is_invariant());
7713            assert_eq!(g.is_sweep_phase(), heap_state.is_sweep());
7714            saw_keep |= g.keep_invariant();
7715            saw_sweep |= g.is_sweep_phase();
7716            if heap_state.is_pause() && saw_keep && saw_sweep {
7717                break;
7718            }
7719        }
7720
7721        assert!(
7722            saw_keep,
7723            "incremental cycle should expose an invariant phase"
7724        );
7725        assert!(saw_sweep, "incremental cycle should expose a sweep phase");
7726
7727        for key in roots {
7728            assert!(state.external_unroot_value(key).is_some());
7729        }
7730        state.gc().full_collect();
7731    }
7732
7733    #[test]
7734    fn gc_barrier_keeps_new_child_stored_in_black_parent() {
7735        let mut state = new_state().expect("state should initialize");
7736        let _heap_guard = {
7737            let g = state.global();
7738            lua_gc::HeapGuard::push(&g.heap)
7739        };
7740
7741        let parent = state.new_table();
7742        let parent_key = state.external_root_value(LuaValue::Table(parent));
7743        state.gc().incremental_step(1);
7744        assert!(
7745            state.global().keep_invariant(),
7746            "test setup should leave the parent marked during an active cycle"
7747        );
7748
7749        let child = state.new_table();
7750        let parent_value = LuaValue::Table(parent);
7751        let child_value = LuaValue::Table(child);
7752        parent
7753            .raw_set_int(&mut state, 1, child_value)
7754            .expect("table store should succeed");
7755        state.gc_barrier_back(&parent_value, &child_value);
7756
7757        for _ in 0..128 {
7758            if state.gc().incremental_step(1) {
7759                break;
7760            }
7761        }
7762
7763        assert_eq!(state.global().heap.allgc_count(), 2);
7764        assert_eq!(
7765            parent.get_int(1).as_table().map(|t| t.identity()),
7766            Some(child.identity())
7767        );
7768
7769        assert!(state.external_unroot_value(parent_key).is_some());
7770        state.gc().full_collect();
7771        assert_eq!(state.global().heap.allgc_count(), 0);
7772    }
7773
7774    #[test]
7775    fn generational_mode_promotes_and_barriers_age_objects() {
7776        let mut state = new_state().expect("state should initialize");
7777        let _heap_guard = {
7778            let g = state.global();
7779            lua_gc::HeapGuard::push(&g.heap)
7780        };
7781
7782        let parent = state.new_table();
7783        let parent_key = state.external_root_value(LuaValue::Table(parent));
7784
7785        state.gc().change_mode(GcKind::Generational);
7786        assert_eq!(parent.0.age(), lua_gc::GcAge::Old);
7787        assert_eq!(parent.0.color(), lua_gc::Color::Black);
7788        let majorbase = state.global().gc_estimate;
7789        assert!(majorbase > 0);
7790        assert!(state.global().gc_debt() <= 0);
7791
7792        let child = state.new_table();
7793        let parent_value = LuaValue::Table(parent);
7794        let child_value = LuaValue::Table(child);
7795        parent
7796            .raw_set_int(&mut state, 1, child_value.clone())
7797            .expect("table store should succeed");
7798        state.gc_barrier_back(&parent_value, &child_value);
7799        assert_eq!(parent.0.age(), lua_gc::GcAge::Touched1);
7800        assert_eq!(parent.0.color(), lua_gc::Color::Gray);
7801        assert_eq!(child.0.age(), lua_gc::GcAge::New);
7802
7803        let metatable = state.new_table();
7804        parent.set_metatable(Some(metatable));
7805        state.gc().obj_barrier(&parent, &metatable);
7806        assert_eq!(metatable.0.age(), lua_gc::GcAge::Old0);
7807
7808        assert!(state.gc().generational_step_minor_only());
7809        assert_eq!(parent.0.age(), lua_gc::GcAge::Touched2);
7810        assert_eq!(child.0.age(), lua_gc::GcAge::Survival);
7811        assert_eq!(metatable.0.age(), lua_gc::GcAge::Old1);
7812        assert_eq!(state.global().gc_estimate, majorbase);
7813        assert!(state.global().gc_debt() <= 0);
7814
7815        state.gc().change_mode(GcKind::Incremental);
7816        assert_eq!(parent.0.age(), lua_gc::GcAge::New);
7817        assert_eq!(child.0.age(), lua_gc::GcAge::New);
7818        assert_eq!(metatable.0.age(), lua_gc::GcAge::New);
7819
7820        assert!(state.external_unroot_value(parent_key).is_some());
7821        state.gc().full_collect();
7822    }
7823
7824    #[test]
7825    fn generational_upvalue_write_barrier_marks_young_child_old0() {
7826        let mut state = new_state().expect("state should initialize");
7827        let _heap_guard = {
7828            let g = state.global();
7829            lua_gc::HeapGuard::push(&g.heap)
7830        };
7831
7832        let proto = state.new_proto();
7833        let closure = state.new_lclosure(proto, 1);
7834        let closure_key = state.external_root_value(LuaValue::Function(LuaClosure::Lua(closure)));
7835        state.gc().change_mode(GcKind::Generational);
7836        let uv = closure.upval(0);
7837        assert_eq!(uv.0.age(), lua_gc::GcAge::Old);
7838
7839        let child = state.new_table();
7840        state
7841            .upvalue_set(&closure, 0, LuaValue::Table(child))
7842            .expect("closed upvalue write should succeed");
7843        assert_eq!(child.0.age(), lua_gc::GcAge::Old0);
7844
7845        assert!(state.external_unroot_value(closure_key).is_some());
7846        state.gc().full_collect();
7847    }
7848
7849    #[test]
7850    fn cclosure_setupvalue_replaces_upvalue() {
7851        let mut state = new_state().expect("state should initialize");
7852        let _heap_guard = {
7853            let g = state.global();
7854            lua_gc::HeapGuard::push(&g.heap)
7855        };
7856
7857        let first = state.new_table();
7858        state.push(LuaValue::Table(first));
7859        crate::api::push_cclosure(&mut state, test_noop_cclosure, 1)
7860            .expect("C closure creation should succeed");
7861        let LuaValue::Function(LuaClosure::C(ccl)) = state.get_at(state.top_idx() - 1) else {
7862            panic!("expected heavy C closure");
7863        };
7864
7865        let second = state.new_table();
7866        state.push(LuaValue::Table(second));
7867        let name =
7868            crate::api::setup_value(&mut state, -2, 1).expect("C closure upvalue should exist");
7869
7870        assert!(name.is_empty());
7871        let upvalues = ccl.upvalues.borrow();
7872        let LuaValue::Table(actual) = upvalues[0].clone() else {
7873            panic!("expected table upvalue");
7874        };
7875        assert_eq!(actual.identity(), second.identity());
7876    }
7877
7878    #[test]
7879    fn generational_cclosure_setupvalue_barrier_marks_young_child_old0() {
7880        let mut state = new_state().expect("state should initialize");
7881        let _heap_guard = {
7882            let g = state.global();
7883            lua_gc::HeapGuard::push(&g.heap)
7884        };
7885
7886        state.push(LuaValue::Nil);
7887        crate::api::push_cclosure(&mut state, test_noop_cclosure, 1)
7888            .expect("C closure creation should succeed");
7889        let LuaValue::Function(LuaClosure::C(ccl)) = state.get_at(state.top_idx() - 1) else {
7890            panic!("expected heavy C closure");
7891        };
7892        let closure_key = state.external_root_value(LuaValue::Function(LuaClosure::C(ccl)));
7893
7894        state.gc().change_mode(GcKind::Generational);
7895        assert_eq!(ccl.0.age(), lua_gc::GcAge::Old);
7896
7897        let child = state.new_table();
7898        state.push(LuaValue::Table(child));
7899        crate::api::setup_value(&mut state, -2, 1).expect("C closure upvalue should exist");
7900
7901        assert_eq!(child.0.age(), lua_gc::GcAge::Old0);
7902
7903        assert!(state.external_unroot_value(closure_key).is_some());
7904        state.gc().full_collect();
7905    }
7906
7907    #[test]
7908    fn generational_closure_upvalue_slot_barrier_marks_new_upval_old0() {
7909        let mut state = new_state().expect("state should initialize");
7910        let _heap_guard = {
7911            let g = state.global();
7912            lua_gc::HeapGuard::push(&g.heap)
7913        };
7914
7915        let proto = state.new_proto();
7916        let closure = state.new_lclosure(proto, 1);
7917        let closure_key = state.external_root_value(LuaValue::Function(LuaClosure::Lua(closure)));
7918        state.gc().change_mode(GcKind::Generational);
7919        assert_eq!(closure.0.age(), lua_gc::GcAge::Old);
7920
7921        let replacement = state.new_upval_closed(LuaValue::Nil);
7922        closure.set_upval(0, replacement);
7923        state.gc().obj_barrier(&closure, &replacement);
7924        assert_eq!(replacement.0.age(), lua_gc::GcAge::Old0);
7925
7926        assert!(state.external_unroot_value(closure_key).is_some());
7927        state.gc().full_collect();
7928    }
7929
7930    #[test]
7931    fn cross_thread_upvalue_mirror_traces_values_as_roots() {
7932        let mut state = new_state().expect("state should initialize");
7933        let _heap_guard = {
7934            let g = state.global();
7935            lua_gc::HeapGuard::push(&g.heap)
7936        };
7937
7938        let mirrored = state.new_table();
7939        state
7940            .global_mut()
7941            .cross_thread_upvals
7942            .insert((999, StackIdx(0)), LuaValue::Table(mirrored));
7943
7944        state.gc().full_collect();
7945        assert_eq!(state.global().heap.allgc_count(), 1);
7946
7947        state.global_mut().cross_thread_upvals.clear();
7948        state.gc().full_collect();
7949        assert_eq!(state.global().heap.allgc_count(), 0);
7950    }
7951
7952    #[test]
7953    fn generational_full_collect_promotes_new_survivors_to_old() {
7954        let mut state = new_state().expect("state should initialize");
7955        let _heap_guard = {
7956            let g = state.global();
7957            lua_gc::HeapGuard::push(&g.heap)
7958        };
7959
7960        state.gc().change_mode(GcKind::Generational);
7961        let table = state.new_table();
7962        let table_key = state.external_root_value(LuaValue::Table(table));
7963        assert_eq!(table.0.age(), lua_gc::GcAge::New);
7964
7965        state.gc().full_collect();
7966        assert_eq!(table.0.age(), lua_gc::GcAge::Old);
7967        assert_eq!(table.0.color(), lua_gc::Color::Black);
7968
7969        assert!(state.external_unroot_value(table_key).is_some());
7970        state.gc().full_collect();
7971    }
7972
7973    #[test]
7974    fn gc_packed_params_return_user_visible_values() {
7975        let mut state = new_state().expect("state should initialize");
7976        assert_eq!(
7977            crate::api::gc(&mut state, crate::api::GcArgs::SetPause { value: 200 }),
7978            200
7979        );
7980        assert_eq!(state.global().gc_pause_param(), 200);
7981        assert_eq!(
7982            crate::api::gc(&mut state, crate::api::GcArgs::SetStepMul { value: 200 }),
7983            100
7984        );
7985        assert_eq!(state.global().gc_stepmul_param(), 200);
7986
7987        crate::api::gc(
7988            &mut state,
7989            crate::api::GcArgs::Gen {
7990                minormul: 0,
7991                majormul: 200,
7992            },
7993        );
7994        assert_eq!(state.global().gc_genmajormul_param(), 200);
7995    }
7996
7997    #[test]
7998    fn generational_step_runs_bad_major_when_growth_exceeds_genmajormul() {
7999        let mut state = new_state().expect("state should initialize");
8000        let _heap_guard = {
8001            let g = state.global();
8002            lua_gc::HeapGuard::push(&g.heap)
8003        };
8004
8005        let root = state.new_table();
8006        let root_key = state.external_root_value(LuaValue::Table(root));
8007        state.gc().change_mode(GcKind::Generational);
8008
8009        let root_value = LuaValue::Table(root);
8010        for i in 1..=64 {
8011            let child = state.new_table();
8012            let child_value = LuaValue::Table(child);
8013            root.raw_set_int(&mut state, i, child_value.clone())
8014                .expect("table store should succeed");
8015            state.gc_barrier_back(&root_value, &child_value);
8016        }
8017
8018        {
8019            let mut g = state.global_mut();
8020            g.gc_estimate = 1;
8021            set_debt(&mut *g, 1);
8022        }
8023
8024        assert!(state.gc().generational_step());
8025        let g = state.global();
8026        assert!(g.is_gen_mode());
8027        assert!(
8028            g.lastatomic > 0,
8029            "bad major collection should arm stepgenfull"
8030        );
8031        assert!(g.gc_estimate > 1);
8032        assert!(g.gc_debt() <= 0);
8033        assert_eq!(root.0.age(), lua_gc::GcAge::Old);
8034        drop(g);
8035
8036        assert!(state.external_unroot_value(root_key).is_some());
8037        state.gc().full_collect();
8038    }
8039
8040    #[test]
8041    fn generational_implicit_step_runs_major_when_heap_threshold_exceeded() {
8042        let mut state = new_state().expect("state should initialize");
8043        let _heap_guard = {
8044            let g = state.global();
8045            lua_gc::HeapGuard::push(&g.heap)
8046        };
8047
8048        let root = state.new_table();
8049        let root_key = state.external_root_value(LuaValue::Table(root));
8050        state.gc().change_mode(GcKind::Generational);
8051
8052        let root_value = LuaValue::Table(root);
8053        for i in 1..=64 {
8054            let child = state.new_table();
8055            let child_value = LuaValue::Table(child);
8056            root.raw_set_int(&mut state, i, child_value.clone())
8057                .expect("table store should succeed");
8058            state.gc_barrier_back(&root_value, &child_value);
8059        }
8060
8061        {
8062            let mut g = state.global_mut();
8063            g.gc_estimate = 1;
8064            set_debt(&mut *g, -1);
8065            g.heap.set_threshold_bytes(1);
8066        }
8067
8068        assert!(state.gc().generational_step());
8069        let g = state.global();
8070        assert!(g.is_gen_mode());
8071        assert!(
8072            g.lastatomic > 0,
8073            "implicit threshold-triggered growth should arm a bad major"
8074        );
8075        assert!(g.gc_debt() <= 0);
8076        drop(g);
8077
8078        assert!(state.external_unroot_value(root_key).is_some());
8079        state.gc().full_collect();
8080    }
8081
8082    #[test]
8083    fn generational_stepgenfull_returns_to_gen_after_good_collection() {
8084        let mut state = new_state().expect("state should initialize");
8085        let _heap_guard = {
8086            let g = state.global();
8087            lua_gc::HeapGuard::push(&g.heap)
8088        };
8089
8090        let root = state.new_table();
8091        let root_key = state.external_root_value(LuaValue::Table(root));
8092        state.gc().change_mode(GcKind::Generational);
8093        {
8094            let mut g = state.global_mut();
8095            g.lastatomic = 1024;
8096        }
8097
8098        assert!(state.gc().generational_step());
8099        let g = state.global();
8100        assert_eq!(g.gckind, GcKind::Generational as u8);
8101        assert_eq!(g.lastatomic, 0);
8102        assert!(g.gc_debt() <= 0);
8103        assert_eq!(root.0.age(), lua_gc::GcAge::Old);
8104        assert_eq!(root.0.color(), lua_gc::Color::Black);
8105        drop(g);
8106
8107        assert!(state.external_unroot_value(root_key).is_some());
8108        state.gc().full_collect();
8109    }
8110
8111    #[test]
8112    fn generational_step_zero_reports_false_without_positive_debt() {
8113        let mut state = new_state().expect("state should initialize");
8114        let _heap_guard = {
8115            let g = state.global();
8116            lua_gc::HeapGuard::push(&g.heap)
8117        };
8118
8119        state.gc().change_mode(GcKind::Generational);
8120        assert_eq!(
8121            crate::api::gc(&mut state, crate::api::GcArgs::Step { data: 0 }),
8122            0
8123        );
8124        assert_eq!(
8125            crate::api::gc(&mut state, crate::api::GcArgs::Step { data: 1 }),
8126            1
8127        );
8128    }
8129}