Skip to main content

lua_vm/
state.rs

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