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
13// PORT NOTE: The C `LX` (thread + extra space) and `LG` (LX + global state) layout
14// wrappers are C-only pointer-arithmetic helpers for allocating the main thread and
15// GlobalState as one contiguous block. In Rust, `GlobalState` and `LuaState` are
16// separate heap-allocated values linked via `Rc<RefCell<GlobalState>>`. No LX/LG
17// equivalents are needed.
18
19// PORT NOTE: C macro `fromstate(L)` (cast LX* from lua_State*) is C-only pointer
20// arithmetic and is not translated. Rust owns the allocations via Rc/Box.
21
22use std::cell::RefCell;
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 { i.0 as i32 }
39
40impl From<u32> for StackIdxConv {
41    #[inline(always)]
42    fn from(v: u32) -> Self { StackIdxConv(StackIdx(v)) }
43}
44impl From<i32> for StackIdxConv {
45    #[inline(always)]
46    fn from(v: i32) -> Self { StackIdxConv(StackIdx(v.max(0) as u32)) }
47}
48impl From<usize> for StackIdxConv {
49    #[inline(always)]
50    fn from(v: usize) -> Self { StackIdxConv(StackIdx(v as u32)) }
51}
52impl From<StackIdx> for StackIdxConv {
53    #[inline(always)]
54    fn from(v: StackIdx) -> Self { StackIdxConv(v) }
55}
56pub use lua_types::value::{LuaTable, LuaValue, F2Imod};
57pub use lua_types::string::LuaString;
58pub use lua_types::userdata::LuaUserData;
59pub use lua_types::closure::{LuaCFnPtr, LuaClosure, LuaLClosure as LuaClosureLua, LuaCClosure as LuaClosureC};
60pub use lua_types::proto::LuaProto;
61pub use lua_types::upval::{UpVal, UpValState};
62pub use lua_types::gc::GcRef;
63
64/// A Lua-callable function pointer. C: `lua_CFunction`.
65///
66/// TODO(phase-b): the lua-types crate uses a placeholder
67/// `LuaCFnPtr = fn() -> i32` since it can't reference `LuaState` without a
68/// circular dep. The real signature is `fn(&mut LuaState) -> Result<usize, LuaError>`,
69/// kept here as the lua-vm-facing type alias.
70pub type LuaCFunction = fn(&mut LuaState) -> Result<usize, LuaError>;
71
72// ─── Constants (from macros.tsv) ──────────────────────────────────────────────
73
74// macros.tsv: EXTRA_STACK → const EXTRA_STACK: u32 = 5
75pub(crate) const EXTRA_STACK: usize = 5;
76
77// macros.tsv: LUA_MINSTACK → const LUA_MINSTACK: u32 = 20
78pub(crate) const LUA_MINSTACK: usize = 20;
79
80// macros.tsv: BASIC_STACK_SIZE → const BASIC_STACK_SIZE: u32 = 2 * LUA_MINSTACK
81pub(crate) const BASIC_STACK_SIZE: usize = 2 * LUA_MINSTACK;
82
83// PORT NOTE: lowered from 200 to 80 because our debug-build Rust frames
84// are ~5–10× larger than C frames (debuginfo, stack-allocated CallInfo
85// arrays, marker state). At 200 we SIGSEGV on cstack's 1000-coroutine
86// close cascade before nCcalls trips. 80 is safe for an 8 MB Rust thread
87// stack with a comfortable margin.
88pub(crate) const LUAI_MAXCCALLS: u32 = 200;
89
90// macros.tsv: CIST_C → const CIST_C: u16 = 1 << 1
91pub(crate) const CIST_C: u16 = 1 << 1;
92
93// Remaining CIST_* bits from macros.tsv
94pub(crate) const CIST_OAH: u16 = 1 << 0;
95pub(crate) const CIST_FRESH: u16 = 1 << 2;
96pub(crate) const CIST_HOOKED: u16 = 1 << 3;
97pub(crate) const CIST_YPCALL: u16 = 1 << 4;
98pub(crate) const CIST_TAIL: u16 = 1 << 5;
99pub(crate) const CIST_HOOKYIELD: u16 = 1 << 6;
100pub(crate) const CIST_FIN: u16 = 1 << 7;
101pub(crate) const CIST_TRAN: u16 = 1 << 8;
102pub(crate) const CIST_CLSRET: u16 = 1 << 9;
103pub(crate) const CIST_RECST: u32 = 10;
104
105// macros.tsv: LUA_RIDX_MAINTHREAD → const LUA_RIDX_MAINTHREAD: i64 = 1
106pub(crate) const LUA_RIDX_MAINTHREAD: i64 = 1;
107pub(crate) const LUA_RIDX_GLOBALS: i64 = 2;
108pub(crate) const LUA_RIDX_LAST: usize = 2;
109
110// macros.tsv: LUA_NUMTYPES → const LUA_NUMTYPES: usize = 9
111const LUA_NUMTYPES: usize = 9;
112
113const LUA_EXTRASPACE: usize = std::mem::size_of::<*mut ()>();
114
115// TODO(port): import from crate::gc (lgc.c → gc.rs) once it exists in Phase D
116const GCSTPUSR: u8 = 1;
117const GCSTPGC: u8 = 2;
118
119// TODO(port): import from crate::gc in Phase D
120const GCS_PAUSE: u8 = 0;
121
122const LUAI_GCPAUSE: u32 = 200;
123const LUAI_GCMUL: u32 = 100;
124const LUAI_GCSTEPSIZE: u8 = 13;
125const LUAI_GENMAJORMUL: u32 = 100;
126const LUAI_GENMINORMUL: u8 = 20;
127
128const WHITE0BIT: u8 = 0;
129
130const STRCACHE_N: usize = 53;
131const STRCACHE_M: usize = 2;
132
133// ─── GcKind enum ─────────────────────────────────────────────────────────────
134
135/// Garbage collector operating mode.
136///
137/// macros.tsv: `KGC_INC → GcKind::Incremental`, `KGC_GEN → GcKind::Generational`
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub enum GcKind {
140    Incremental = 0,
141    Generational = 1,
142}
143
144// ─── LuaStatus enum ──────────────────────────────────────────────────────────
145
146/// Thread / call status codes.
147///
148pub use lua_types::status::LuaStatus;
149
150// ─── StackValue ───────────────────────────────────────────────────────────────
151
152/// One slot on the Lua value stack.  Wraps a `LuaValue` and an optional
153/// to-be-closed delta (for the `tbclist` mechanism).
154///
155/// types.tsv: `StackValue → StackValue { val: LuaValue, tbclist.delta: u16 }`
156#[derive(Clone)]
157pub struct StackValue {
158    pub val: LuaValue,
159    pub tbc_delta: u16,
160}
161
162impl Default for StackValue {
163    fn default() -> Self {
164        StackValue {
165            val: LuaValue::Nil,
166            tbc_delta: 0,
167        }
168    }
169}
170
171// ─── CallInfo ────────────────────────────────────────────────────────────────
172
173/// Saved state for a Lua or C call frame.
174///
175/// types.tsv: CallInfo → CallInfo (several fields renamed / adapted).
176///
177/// The C intrusive doubly-linked list (`previous`, `next` as raw pointers) is
178/// replaced by `Option<CallInfoIdx>` indices into `LuaState::call_info`.
179#[derive(Clone)]
180pub struct CallInfo {
181    // types.tsv: CallInfo.func → StackIdx
182    pub func: StackIdx,
183
184    // types.tsv: CallInfo.top → StackIdx
185    pub top: StackIdx,
186
187    // types.tsv: CallInfo.previous → CallInfoIdx (Option at boundary)
188    pub previous: Option<CallInfoIdx>,
189
190    // types.tsv: CallInfo.next → CallInfoIdx (Option at tail)
191    pub next: Option<CallInfoIdx>,
192
193    pub u: CallInfoFrame,
194
195    pub u2: CallInfoExtra,
196
197    // types.tsv: CallInfo.nresults → i16
198    pub nresults: i16,
199
200    // types.tsv: CallInfo.callstatus → u16 (bit-packed CIST_* flags)
201    pub callstatus: u16,
202}
203
204/// Payload of `CallInfo.u`.
205///
206#[derive(Clone, Copy)]
207pub enum CallInfoFrame {
208    Lua {
209        // types.tsv: CallInfo.u.l.savedpc → u32
210        savedpc: u32,
211        // types.tsv: CallInfo.u.l.trap → bool
212        trap: bool,
213        // types.tsv: CallInfo.u.l.nextraargs → i32
214        nextraargs: i32,
215    },
216    C {
217        // types.tsv: CallInfo.u.c.k → Option<lua_KFunction>
218        k: Option<LuaKFunction>,
219        // types.tsv: CallInfo.u.c.old_errfunc → isize
220        old_errfunc: isize,
221        // types.tsv: CallInfo.u.c.ctx → isize
222        ctx: isize,
223    },
224}
225
226/// Continuation function for yieldable C calls.  C: `lua_KFunction`.
227pub type LuaKFunction = fn(&mut LuaState, status: i32, ctx: isize) -> Result<usize, LuaError>;
228
229/// Payload of `CallInfo.u2`.
230///
231/// types.tsv: CallInfo.u2 → CallInfoExtra (Rust: struct with all fields, interpretation by context)
232#[derive(Default, Clone, Copy)]
233pub struct CallInfoExtra {
234    pub value: i32,
235    pub ftransfer: u16,
236    pub ntransfer: u16,
237}
238
239impl CallInfoFrame {
240    /// Default C-call frame (no continuation, zero context).
241    pub fn c_default() -> Self {
242        CallInfoFrame::C {
243            k: None,
244            old_errfunc: 0,
245            ctx: 0,
246        }
247    }
248
249    /// Default Lua-call frame (pc=0, no trap, no extra args).
250    pub fn lua_default() -> Self {
251        CallInfoFrame::Lua {
252            savedpc: 0,
253            trap: false,
254            nextraargs: 0,
255        }
256    }
257}
258
259impl Default for CallInfo {
260    fn default() -> Self {
261        CallInfo {
262            func: StackIdx(0),
263            top: StackIdx(0),
264            previous: None,
265            next: None,
266            u: CallInfoFrame::c_default(),
267            u2: CallInfoExtra::default(),
268            nresults: 0,
269            callstatus: 0,
270        }
271    }
272}
273
274impl CallInfo {
275    pub fn is_lua(&self) -> bool { (self.callstatus & CIST_C) == 0 }
276    pub fn is_lua_code(&self) -> bool { self.is_lua() }
277    /// Whether the active function is a vararg function.
278    ///
279    /// Currently returns `false` unconditionally — vararg introspection via
280    /// `debug.getinfo` reports no vararg info instead of panicking.
281    ///
282    /// TODO(port): wire when CallInfo carries proto access for vararg detection.
283    pub fn is_vararg_func(&self) -> bool { false }
284    pub fn saved_pc(&self) -> u32 {
285        if let CallInfoFrame::Lua { savedpc, .. } = self.u { savedpc } else { 0 }
286    }
287    pub fn set_saved_pc(&mut self, pc: u32) {
288        if let CallInfoFrame::Lua { ref mut savedpc, .. } = self.u { *savedpc = pc; }
289    }
290    pub fn nextra_args(&self) -> i32 {
291        if let CallInfoFrame::Lua { nextraargs, .. } = self.u { nextraargs } else { 0 }
292    }
293    pub fn transfer_ftransfer(&self) -> u16 { self.u2.ftransfer }
294    pub fn transfer_ntransfer(&self) -> u16 { self.u2.ntransfer }
295    pub fn set_trap(&mut self, t: bool) {
296        if let CallInfoFrame::Lua { ref mut trap, .. } = self.u { *trap = t; }
297    }
298    /// Read the 3-bit recover-status field packed into bits 10-12 of callstatus.
299    ///
300    pub fn recover_status(&self) -> i32 {
301        ((self.callstatus >> CIST_RECST) & 7) as i32
302    }
303    /// Write the 3-bit recover-status field. `status` must fit in three bits.
304    ///
305    pub fn set_recover_status<T: Into<i32>>(&mut self, status: T) {
306        let st = (status.into() & 7) as u16;
307        self.callstatus = (self.callstatus & !(7u16 << CIST_RECST)) | (st << CIST_RECST);
308    }
309    pub fn get_oah(&self) -> bool { (self.callstatus & CIST_OAH) != 0 }
310    /// Store the current `allowhook` value into callstatus bit 0 (CIST_OAH).
311    ///
312    pub fn set_oah(&mut self, allow: bool) {
313        self.callstatus = (self.callstatus & !CIST_OAH) | (if allow { CIST_OAH } else { 0 });
314    }
315    pub fn u_c_old_errfunc(&self) -> isize {
316        if let CallInfoFrame::C { old_errfunc, .. } = self.u { old_errfunc } else { 0 }
317    }
318    pub fn u_c_ctx(&self) -> isize {
319        if let CallInfoFrame::C { ctx, .. } = self.u { ctx } else { 0 }
320    }
321    pub fn u_c_k(&self) -> Option<LuaKFunction> {
322        if let CallInfoFrame::C { k, .. } = self.u { k } else { None }
323    }
324    /// Set continuation function on a C-call frame.
325    ///
326    /// Panics if invoked on a Lua frame (callers must check `is_lua()` first).
327    pub fn set_u_c_k(&mut self, k: Option<LuaKFunction>) {
328        if let CallInfoFrame::C { k: ref mut slot, .. } = self.u {
329            *slot = k;
330        }
331    }
332    /// Set continuation context on a C-call frame.
333    pub fn set_u_c_ctx(&mut self, ctx: isize) {
334        if let CallInfoFrame::C { ctx: ref mut slot, .. } = self.u {
335            *slot = ctx;
336        }
337    }
338    /// Set saved old_errfunc on a C-call frame.
339    pub fn set_u_c_old_errfunc(&mut self, old_errfunc: isize) {
340        if let CallInfoFrame::C { old_errfunc: ref mut slot, .. } = self.u {
341            *slot = old_errfunc;
342        }
343    }
344    /// Set the `u2.funcidx` field, used by yieldable pcall for error recovery.
345    ///
346    pub fn set_u2_funcidx(&mut self, idx: i32) {
347        self.u2.value = idx;
348    }
349}
350
351// ─── Phase-B value/proto/instruction helpers ──────────────────────────────────
352
353/// Extension methods on `LuaValue`. TODO(phase-b): move these to
354/// `lua_types::value` (or wherever the canonical impl lives) once the type
355/// helpers stabilise.
356pub trait LuaValueExt {
357    fn base_type(&self) -> lua_types::LuaType;
358    fn to_number_no_strconv(&self) -> Option<f64>;
359    fn to_number_with_strconv(&self) -> Option<f64>;
360    fn to_integer_no_strconv(&self) -> Option<i64>;
361    fn to_integer_with_strconv(&self) -> Option<i64>;
362    fn full_type_tag(&self) -> u8;
363}
364
365impl LuaValueExt for LuaValue {
366    fn base_type(&self) -> lua_types::LuaType { self.type_tag() }
367    fn to_number_no_strconv(&self) -> Option<f64> {
368        match self {
369            LuaValue::Float(f) => Some(*f),
370            LuaValue::Int(i) => Some(*i as f64),
371            _ => None,
372        }
373    }
374    fn to_number_with_strconv(&self) -> Option<f64> {
375        if let Some(n) = self.to_number_no_strconv() { return Some(n); }
376        if let LuaValue::Str(s) = self {
377            let mut tmp = LuaValue::Nil;
378            let sz = crate::object::str2num(s.as_bytes(), &mut tmp);
379            if sz == 0 { return None; }
380            return match tmp {
381                LuaValue::Int(i) => Some(i as f64),
382                LuaValue::Float(f) => Some(f),
383                _ => None,
384            };
385        }
386        None
387    }
388    fn to_integer_no_strconv(&self) -> Option<i64> {
389        match self {
390            LuaValue::Int(i) => Some(*i),
391            LuaValue::Float(f) if f.fract() == 0.0 && f.is_finite() => {
392                //   d >= LUA_MININTEGER && d < -(lua_Number)LUA_MININTEGER.
393                // Without this, Rust's `as i64` saturates and silently
394                // produces i64::MAX / i64::MIN for out-of-range floats.
395                let min_f = i64::MIN as f64;
396                let max_plus1_f = -(i64::MIN as f64);
397                if *f >= min_f && *f < max_plus1_f {
398                    Some(*f as i64)
399                } else {
400                    None
401                }
402            }
403            _ => None,
404        }
405    }
406    fn to_integer_with_strconv(&self) -> Option<i64> {
407        if let Some(i) = self.to_integer_no_strconv() { return Some(i); }
408        if let LuaValue::Str(s) = self {
409            let mut tmp = LuaValue::Nil;
410            let sz = crate::object::str2num(s.as_bytes(), &mut tmp);
411            if sz == 0 { return None; }
412            return tmp.to_integer_no_strconv();
413        }
414        None
415    }
416    fn full_type_tag(&self) -> u8 {
417        match self {
418            LuaValue::Nil => 0x00,
419            LuaValue::Bool(false) => 0x01,
420            LuaValue::Bool(true) => 0x11,
421            LuaValue::Int(_) => 0x03,
422            LuaValue::Float(_) => 0x13,
423            LuaValue::Str(s) if s.is_short() => 0x04,
424            LuaValue::Str(_) => 0x14,
425            LuaValue::LightUserData(_) => 0x02,
426            LuaValue::Table(_) => 0x05,
427            LuaValue::Function(LuaClosure::Lua(_)) => 0x06,
428            LuaValue::Function(LuaClosure::LightC(_)) => 0x16,
429            LuaValue::Function(LuaClosure::C(_)) => 0x26,
430            LuaValue::UserData(_) => 0x07,
431            LuaValue::Thread(_) => 0x08,
432        }
433    }
434}
435
436/// Extension methods on `lua_types::LuaType`.
437pub trait LuaTypeExt {
438    fn type_name(&self) -> &'static [u8];
439}
440
441impl LuaTypeExt for lua_types::LuaType {
442    fn type_name(&self) -> &'static [u8] {
443        use lua_types::LuaType::*;
444        match self {
445            None => b"no value",
446            Nil => b"nil",
447            Boolean => b"boolean",
448            LightUserData => b"userdata",
449            Number => b"number",
450            String => b"string",
451            Table => b"table",
452            Function => b"function",
453            UserData => b"userdata",
454            Thread => b"thread",
455        }
456    }
457}
458
459/// StackIdx checked-arithmetic helpers. Returns the raw `u32` because Phase A
460/// callers use the result in arithmetic comparisons against other `u32`
461/// quantities (stack-distance offsets).
462pub trait StackIdxExt {
463    fn saturating_sub(self, n: impl Into<StackIdxConv>) -> u32;
464    fn wrapping_sub(self, n: impl Into<StackIdxConv>) -> u32;
465    fn raw(self) -> u32;
466}
467impl StackIdxExt for StackIdx {
468    #[inline(always)]
469    fn saturating_sub(self, n: impl Into<StackIdxConv>) -> u32 { self.0.saturating_sub(n.into().0.0) }
470    #[inline(always)]
471    fn wrapping_sub(self, n: impl Into<StackIdxConv>) -> u32 { self.0.wrapping_sub(n.into().0.0) }
472    #[inline(always)]
473    fn raw(self) -> u32 { self.0 }
474}
475
476/// `GcRef<LuaTable>` / `GcRef<LuaUserData>` field-access helpers. These
477/// methods are needed by api.rs and tagmethods.rs but the lua-types
478/// placeholders don't yet expose them. TODO(phase-b): replace with real
479/// accessor methods on the canonical types in lua-types.
480///
481/// PORT NOTE: the historical `reject_invalid_table_key` precheck used to
482/// guard nil/NaN keys at this layer; it has moved inside
483/// [`LuaTable::try_raw_set`] (alongside the integer-fast-path match) so
484/// the lua-vm wrapper does not double-check.
485pub trait LuaTableRefExt {
486    fn metatable(&self) -> Option<GcRef<LuaTable>>;
487    fn as_ptr(&self) -> *const ();
488    fn get(&self, _k: &LuaValue) -> LuaValue;
489    fn get_int(&self, _k: i64) -> LuaValue;
490    fn get_short_str(&self, _k: &GcRef<LuaString>) -> LuaValue;
491    fn raw_set(&self, _state: &mut LuaState, _k: LuaValue, _v: LuaValue) -> Result<(), LuaError>;
492    fn raw_set_int(&self, _state: &mut LuaState, _k: i64, _v: LuaValue) -> Result<(), LuaError>;
493    fn invalidate_tm_cache(&self);
494    fn resize(&self, _state: &mut LuaState, _na: usize, _nh: usize) -> Result<(), LuaError>;
495    fn next(&self, _k: LuaValue) -> Result<Option<(LuaValue, LuaValue)>, LuaError>;
496}
497impl LuaTableRefExt for GcRef<LuaTable> {
498    #[inline]
499    fn metatable(&self) -> Option<GcRef<LuaTable>> { (**self).metatable() }
500    #[inline]
501    fn as_ptr(&self) -> *const () { GcRef::identity(self) as *const () }
502    #[inline]
503    fn get(&self, k: &LuaValue) -> LuaValue { (**self).get(k) }
504    #[inline]
505    fn get_int(&self, k: i64) -> LuaValue { (**self).get_int(k) }
506    #[inline]
507    fn get_short_str(&self, k: &GcRef<LuaString>) -> LuaValue { (**self).get_short_str(k) }
508    /// Forwards to [`LuaTable::try_raw_set`], which performs the nil/NaN
509    /// key validation internally as part of its integer-fast-path match.
510    #[inline]
511    fn raw_set(&self, _state: &mut LuaState, k: LuaValue, v: LuaValue) -> Result<(), LuaError> {
512        (**self).try_raw_set(k, v)
513    }
514    #[inline]
515    fn raw_set_int(&self, _state: &mut LuaState, k: i64, v: LuaValue) -> Result<(), LuaError> {
516        (**self).try_raw_set_int(k, v)
517    }
518    fn invalidate_tm_cache(&self) {}
519    fn resize(&self, _state: &mut LuaState, na: usize, nh: usize) -> Result<(), LuaError> {
520        let na32 = na.min(u32::MAX as usize) as u32;
521        let nh32 = nh.min(u32::MAX as usize) as u32;
522        (**self).resize(na32, nh32)
523    }
524    fn next(&self, k: LuaValue) -> Result<Option<(LuaValue, LuaValue)>, LuaError> {
525        (**self).try_next_pair(&k)
526    }
527}
528
529pub trait LuaUserDataRefExt {
530    fn metatable(&self) -> Option<GcRef<LuaTable>>;
531    fn set_metatable(&self, mt: Option<GcRef<LuaTable>>);
532    fn as_ptr(&self) -> *const ();
533    fn len(&self) -> usize;
534}
535impl LuaUserDataRefExt for GcRef<LuaUserData> {
536    fn metatable(&self) -> Option<GcRef<LuaTable>> { (**self).metatable() }
537    fn set_metatable(&self, mt: Option<GcRef<LuaTable>>) { (**self).set_metatable(mt); }
538    fn as_ptr(&self) -> *const () { GcRef::identity(self) as *const () }
539    fn len(&self) -> usize { self.0.data.len() }
540}
541
542pub trait LuaStringRefExt {
543    fn is_white(&self) -> bool;
544    fn hash(&self) -> u32;
545    fn as_gc_ref(&self) -> GcRef<LuaString>;
546}
547impl LuaStringRefExt for GcRef<LuaString> {
548    fn is_white(&self) -> bool { false }
549    fn hash(&self) -> u32 { self.0.hash() }
550    fn as_gc_ref(&self) -> GcRef<LuaString> { self.clone() }
551}
552
553pub trait LuaLClosureRefExt {
554    fn proto(&self) -> &GcRef<LuaProto>;
555    fn nupvalues(&self) -> usize;
556}
557impl LuaLClosureRefExt for GcRef<lua_types::closure::LuaLClosure> {
558    fn proto(&self) -> &GcRef<LuaProto> { &self.0.proto }
559    fn nupvalues(&self) -> usize { self.0.upvals.len() }
560}
561
562/// `LuaClosure` accessor — `nupvalues()` reports the upvalue count uniformly.
563pub trait LuaClosureExt {
564    fn nupvalues(&self) -> usize;
565}
566impl LuaClosureExt for LuaClosure {
567    fn nupvalues(&self) -> usize {
568        match self {
569            LuaClosure::Lua(l) => l.0.upvals.len(),
570            LuaClosure::C(c) => c.0.upvalues.len(),
571            LuaClosure::LightC(_) => 0,
572        }
573    }
574}
575
576/// `LuaProto` source bytes accessor.
577pub trait LuaProtoExt {
578    fn source_bytes(&self) -> &[u8];
579    fn source_string(&self) -> Option<&GcRef<LuaString>>;
580}
581impl LuaProtoExt for LuaProto {
582    fn source_bytes(&self) -> &[u8] {
583        match &self.source { Some(s) => s.0.as_bytes(), None => &[] }
584    }
585    fn source_string(&self) -> Option<&GcRef<LuaString>> { self.source.as_ref() }
586}
587
588// ─── Collectable trait (GC interface) ────────────────────────────────────────
589
590/// Marker trait for GC-managed objects.
591///
592/// Phase D: real tracing GC.
593/// types.tsv: `GCObject → (trait Collectable; concrete = GcRef<T>)`
594pub trait Collectable: std::fmt::Debug {}
595
596impl std::fmt::Debug for LuaState {
597    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
598        write!(f, "LuaState")
599    }
600}
601impl Collectable for LuaState {}
602
603// ─── GlobalState ─────────────────────────────────────────────────────────────
604
605/// Function-pointer signature for the text-source parser, installed on
606/// [`GlobalState::parser_hook`] by the embedder.
607///
608/// The implementation lives in `lua-parse`; `lua-vm` cannot depend on it
609/// directly (that would form a cycle), so the parser is reached via this
610/// function pointer registered at startup.
611pub type ParserHook = fn(
612    state: &mut LuaState,
613    source: &[u8],
614    name: &[u8],
615    firstchar: i32,
616) -> Result<GcRef<lua_types::closure::LuaLClosure>, LuaError>;
617
618/// Function-pointer signature for reading a file's full contents into memory,
619/// installed on [`GlobalState::file_loader_hook`] by the embedder.
620///
621/// `std::fs` is banned outside `lua-cli`, so `lua-stdlib`'s `loadfile` and
622/// `searcher_lua` reach the filesystem via this hook. `None` keeps the file
623/// system unreachable, which is appropriate for embeddings where modules are
624/// served exclusively from `package.preload`.
625pub type FileLoaderHook = fn(filename: &[u8]) -> Result<Vec<u8>, LuaError>;
626
627/// Function-pointer signature for opening a file handle, installed on
628/// [`GlobalState::file_open_hook`] by the embedder.
629///
630/// `std::fs` is banned outside `lua-cli`, so `lua-stdlib`'s io library reaches
631/// the filesystem via this hook. `None` causes `io.open` and `io.output(name)`
632/// to return a "file system not available" error, which is appropriate for
633/// sandboxed embeddings.
634///
635/// `mode` is a Lua fopen-style mode string (e.g. `b"r"`, `b"w"`, `b"a"`,
636/// `b"r+"`, etc.). The hook must honour at least `r`, `w`, and `a`.
637pub type FileOpenHook =
638    fn(filename: &[u8], mode: &[u8]) -> Result<Box<dyn lua_types::LuaFileHandle>, LuaError>;
639
640/// Function-pointer signature for spawning a child process with a connected
641/// pipe, installed on [`GlobalState::popen_hook`] by the embedder.
642///
643/// `std::process::Command` is banned outside `lua-cli`, so `lua-stdlib`'s
644/// `io.popen` reaches the OS through this hook. `None` causes `io.popen` to
645/// raise a clean Lua error ("popen not enabled in this build"), which is
646/// appropriate for sandboxed embeddings.
647///
648/// `mode` is the Lua popen mode string — `b"r"` for reading the child's
649/// stdout, `b"w"` for writing to the child's stdin.
650pub type PopenHook =
651    fn(cmd: &[u8], mode: &[u8]) -> Result<Box<dyn lua_types::LuaFileHandle>, LuaError>;
652
653/// Function-pointer signature for removing a file, installed on
654/// [`GlobalState::file_remove_hook`] by the embedder.
655///
656/// `std::fs` is banned outside `lua-cli`, so `lua-stdlib`'s `os.remove`
657/// reaches the filesystem via this hook. Returns `Ok(())` on success.
658pub type FileRemoveHook = fn(filename: &[u8]) -> Result<(), LuaError>;
659
660/// Function-pointer signature for renaming a file, installed on
661/// [`GlobalState::file_rename_hook`] by the embedder.
662///
663/// `std::fs` is banned outside `lua-cli`, so `lua-stdlib`'s `os.rename`
664/// reaches the filesystem via this hook. Returns `Ok(())` on success.
665pub type FileRenameHook = fn(from: &[u8], to: &[u8]) -> Result<(), LuaError>;
666
667/// Reason a shell command terminated, returned by [`OsExecuteHook`].
668///
669/// Mirrors the two string literals that C-Lua's `l_inspectstat` / `luaL_execresult`
670/// can produce: `"exit"` for normal process exit, `"signal"` for signal termination
671/// (POSIX only).
672#[derive(Clone, Copy, Debug)]
673pub enum OsExecuteReason {
674    /// Process exited with an exit code (`WIFEXITED` / `ExitStatus::code()` is `Some`).
675    Exit,
676    /// Process was terminated by a signal (`WIFSIGNALED` / `ExitStatus::signal()` is `Some`).
677    Signal,
678}
679
680/// Result returned by [`OsExecuteHook`], carrying the three values that
681/// C-Lua's `luaL_execresult` pushes: `(boolean|nil, "exit"|"signal", int)`.
682#[derive(Debug)]
683pub struct OsExecuteResult {
684    /// `true` when the command exited successfully (exit code 0).
685    pub success: bool,
686    /// How the process terminated.
687    pub reason: OsExecuteReason,
688    /// Exit code (for `Exit`) or signal number (for `Signal`).
689    pub code: i32,
690}
691
692/// Function-pointer signature for executing a shell command, installed on
693/// [`GlobalState::os_execute_hook`] by the embedder.
694///
695/// `std::process` is banned outside `lua-cli`, so `lua-stdlib`'s `os.execute`
696/// reaches the shell via this hook. Returns an [`OsExecuteResult`] on success,
697/// or a [`LuaError`] when the spawn itself fails.
698pub type OsExecuteHook = fn(cmd: &[u8]) -> Result<OsExecuteResult, LuaError>;
699
700/// Opaque handle to a dynamically loaded library, allocated by a
701/// [`DynLibLoadHook`] backend and stored in `package._CLIBS`.
702///
703/// The handle is a backend-owned `u64`; the embedder is free to use it as an
704/// index into a `Vec<libloading::Library>` or a `HashMap` key. `lua-stdlib`
705/// stores the value verbatim and never inspects it.
706#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
707pub struct DynLibId(pub u64);
708
709/// Resolved dynamic-library symbol.
710///
711/// Only `RustNative` is callable by this build of the VM. `LuaCAbi` resolves
712/// to a real C function pointer compiled against stock Lua 5.4's `lua_State *`
713/// ABI but cannot be safely invoked here — it is reported as an `"init"`
714/// failure with a clear message. `Unsupported` carries an embedder-provided
715/// reason byte-string.
716pub enum DynamicSymbol {
717    /// Function pointer that follows this build's Rust-native module ABI:
718    /// `fn(&mut LuaState) -> Result<usize, LuaError>`.
719    RustNative(LuaCFunction),
720    /// Symbol exported against stock Lua 5.4's C ABI. The function pointer is
721    /// resolved but never called from this build, since `lua_State *` is not
722    /// our `LuaState`. Kept as a payload so a future C-ABI facade can pick it
723    /// up; the embedder is responsible for ensuring the underlying library
724    /// outlives this value.
725    LuaCAbi(*const ()),
726    /// Embedder-provided refusal reason, e.g. "symbol resolved but ABI version
727    /// mismatch". Reported verbatim as an `"init"` failure.
728    Unsupported { reason: Vec<u8> },
729}
730
731/// Function-pointer signature for loading a dynamic library, installed on
732/// [`GlobalState::dynlib_load_hook`] by the embedder.
733///
734/// `libloading`/`dlopen`/`LoadLibraryEx` are FFI calls and require `unsafe`,
735/// which is banned in `lua-stdlib`. `lua-cli` installs a `libloading`-backed
736/// implementation. `None` causes `package.loadlib` to return the C-Lua
737/// `"absent"` failure shape, matching the fallback platform stub.
738///
739/// `see_global` mirrors C-Lua's `seeglb` (POSIX `RTLD_GLOBAL`): set when the
740/// caller invokes `package.loadlib(path, "*")`.
741pub type DynLibLoadHook =
742    fn(state: &mut LuaState, path: &[u8], see_global: bool) -> Result<DynLibId, LuaError>;
743
744/// Function-pointer signature for resolving a symbol in a previously loaded
745/// dynamic library, installed on [`GlobalState::dynlib_symbol_hook`].
746///
747/// The hook receives the [`DynLibId`] returned by [`DynLibLoadHook`] and the
748/// requested symbol name. Returning `DynamicSymbol::RustNative` makes the
749/// symbol callable; `LuaCAbi`/`Unsupported` propagate to `package.loadlib`
750/// as an `"init"` failure with a clear message.
751pub type DynLibSymbolHook =
752    fn(state: &mut LuaState, handle: DynLibId, symbol: &[u8]) -> Result<DynamicSymbol, LuaError>;
753
754/// Function-pointer signature for unloading a dynamic library, installed on
755/// [`GlobalState::dynlib_unload_hook`].
756///
757/// Called from the `_CLIBS` `__gc` metamethod when the Lua state closes.
758/// `libloading`'s safety model requires every loaded library to outlive the
759/// last symbol it exports; the CLI backend is therefore free to ignore this
760/// hook and keep libraries alive until process exit.
761pub type DynLibUnloadHook = fn(handle: DynLibId);
762
763/// One row of [`GlobalState::threads`]. Pairs the per-thread `LuaState`
764/// with the canonical `GcRef<LuaThread>` so every `push_thread` for the
765/// same id shares pointer-identity. Phase E-1 adds this; Phase E-2
766/// extends it with interior-mutability bookkeeping when `resume`/`yield`
767/// need to mutate the child thread while the parent holds a borrow.
768pub struct ThreadRegistryEntry {
769    /// The owned coroutine `LuaState`. Wrapped in `Rc<RefCell<...>>` so
770    /// that `coroutine.resume` can borrow the child mutably while the
771    /// parent is still in scope. Single-threaded — borrows never overlap
772    /// in practice because only one resume path is live at a time.
773    pub state: Rc<RefCell<LuaState>>,
774    /// Canonical thread-value handle. Reused on every push so
775    /// `GcRef::ptr_eq` is true across pushes.
776    pub value: GcRef<lua_types::value::LuaThread>,
777}
778
779/// Process-wide state shared by all Lua threads.
780///
781/// types.tsv: `global_State → GlobalState`
782///
783/// Not exposed directly at the API; accessed via `state.global()` / `state.global_mut()`.
784pub struct GlobalState {
785    /// Phase-B hook for the Lua text parser. Set by the embedder (`lua-cli`
786    /// or stdlib host) to bridge the cyclic crate split between `lua-vm` and
787    /// `lua-parse`: when `f_parser` decides the chunk is text, it invokes
788    /// this hook instead of the parser stub. `None` leaves the stub in place
789    /// so unit tests that never load text still work.
790    pub parser_hook: Option<ParserHook>,
791
792    /// Phase-B hook for reading a Lua source file from disk. Set by `lua-cli`
793    /// (or any embedder that wants `require`/`loadfile` to reach the file
794    /// system) since `std::fs` is banned in `lua-stdlib`. `None` makes
795    /// `loadfile` and the Lua-file searcher report a file-not-found error.
796    pub file_loader_hook: Option<FileLoaderHook>,
797
798    /// Phase-B hook for opening a file handle for read/write/append. Set by
799    /// `lua-cli` since `std::fs` is banned in `lua-stdlib`. `None` causes
800    /// `io.open` and `io.output(name)` to return an error; the standard streams
801    /// (`io.stdin`, `io.stdout`, `io.stderr`) remain functional.
802    pub file_open_hook: Option<FileOpenHook>,
803
804    /// Phase-G hook for spawning a child process and connecting one stream
805    /// (stdin or stdout) to a Lua file handle. Set by `lua-cli` since
806    /// `std::process::Command` is banned in `lua-stdlib`. `None` causes
807    /// `io.popen` to raise a Lua error rather than panic.
808    pub popen_hook: Option<PopenHook>,
809
810    /// Phase-B hook for removing a file. Set by `lua-cli` since `std::fs` is
811    /// banned in `lua-stdlib`. `None` causes `os.remove` to return an error.
812    pub file_remove_hook: Option<FileRemoveHook>,
813
814    /// Phase-B hook for renaming a file. Set by `lua-cli` since `std::fs` is
815    /// banned in `lua-stdlib`. `None` causes `os.rename` to return an error.
816    pub file_rename_hook: Option<FileRenameHook>,
817
818    /// Phase-G hook for executing a shell command. Set by `lua-cli` since
819    /// `std::process` is banned in `lua-stdlib`. `None` causes `os.execute`
820    /// to report no shell available (matching C-Lua's `system(NULL) == 0`).
821    pub os_execute_hook: Option<OsExecuteHook>,
822
823    /// Phase-D-3.5 hook for loading a dynamic library (`dlopen` /
824    /// `LoadLibraryEx`). Set by `lua-cli` since `libloading` is FFI and
825    /// requires `unsafe`, which is banned in `lua-stdlib`. `None` causes
826    /// `package.loadlib` to return the `"absent"` fallback shape.
827    pub dynlib_load_hook: Option<DynLibLoadHook>,
828
829    /// Phase-D-3.5 hook for resolving a symbol in a previously loaded
830    /// dynamic library (`dlsym` / `GetProcAddress`). Set by `lua-cli`.
831    /// `None` is treated as "absent" by `package.loadlib`.
832    pub dynlib_symbol_hook: Option<DynLibSymbolHook>,
833
834    /// Phase-D-3.5 hook for unloading a dynamic library (`dlclose` /
835    /// `FreeLibrary`). Set by `lua-cli`. `None` keeps libraries loaded
836    /// until process exit, which matches `libloading`'s safety model.
837    pub dynlib_unload_hook: Option<DynLibUnloadHook>,
838
839    // types.tsv: global_State.totalbytes → isize
840    pub totalbytes: isize,
841
842    // types.tsv: global_State.GCdebt → isize
843    pub gc_debt: isize,
844
845    pub gc_estimate: usize,
846
847    // types.tsv: global_State.lastatomic → usize
848    pub lastatomic: usize,
849
850    // types.tsv: global_State.strt → StringPool
851    pub strt: StringPool,
852
853    // types.tsv: global_State.l_registry → LuaValue
854    pub l_registry: LuaValue,
855
856    // PORT NOTE (phase-b-reconcile): The lua-types LuaTable placeholder has
857    // no storage, so we cannot persist `registry[LUA_RIDX_GLOBALS] = globals`
858    // via the canonical registry path. Until the placeholder reconciles with
859    // lua-vm::table::LuaTable, the globals table lives in a direct field
860    // and `get_global_table` reads it from here. Same for `loaded` (the
861    // module cache normally at `registry[_LOADED]`).
862    pub globals: LuaValue,
863    pub loaded: LuaValue,
864
865    // types.tsv: global_State.nilvalue → LuaValue
866    // PORT NOTE: In Rust we use a dedicated `is_complete: bool` flag rather than
867    // the C trick of checking `ttisnil(&g->nilvalue)`. See `is_complete()`.
868    pub nilvalue: LuaValue,
869
870    // types.tsv: global_State.seed → u32
871    pub seed: u32,
872
873    // types.tsv: global_State.currentwhite → u8
874    pub currentwhite: u8,
875
876    pub gcstate: u8,
877
878    pub gckind: u8,
879
880    pub gcstopem: bool,
881
882    // types.tsv: global_State.genminormul → u8
883    pub genminormul: u8,
884
885    pub genmajormul: u8,
886
887    pub gcstp: u8,
888
889    pub gcemergency: bool,
890
891    // types.tsv: global_State.gcpause → u8
892    pub gcpause: u8,
893
894    // types.tsv: global_State.gcstepmul → u8
895    pub gcstepmul: u8,
896
897    pub gcstepsize: u8,
898
899    // Phase-D NOTE: the C-Lua intrusive GC lists (allgc, sweepgc, finobj,
900    // gray, grayagain, weak, ephemeron, allweak) were declared here as
901    // `Vec<GcRef<dyn Collectable>>` during Phase A but never populated or
902    // read. The real GC owns its own allgc chain inside `self.heap`
903    // (lua_gc::Heap). Removed during D-1e-prep to clear the `?Sized` blocker
904    // for swapping `GcRef<T> = Gc<T>` (Gc requires T: Sized for unsizing).
905    // sweepgc_cursor stayed because non-list bookkeeping kept it.
906    pub sweepgc_cursor: usize,
907
908    /// Phase-B cross-table weak-sweep registry.
909    ///
910    /// `lua_types::value::sweep_weak_tables` iterates this list at
911    /// `collectgarbage("collect")` time to clear entries whose weak target
912    /// is held only by other weak slots. Holds `Weak<LuaTable>` so the
913    /// registry itself does not pin tables that the user has dropped.
914    /// Replaced by the proper `weak` / `ephemeron` / `allweak` lists when
915    /// Phase D's incremental sweep lands.
916    pub weak_tables_registry: Vec<lua_types::gc::GcWeak<lua_types::value::LuaTable>>,
917
918    /// Phase-B long-string allocation tracker.
919    ///
920    /// Each entry pairs a `Weak<LuaString>` with the byte count that was
921    /// added to `gc_debt` at allocation time. `collectgarbage("count")` walks
922    /// the list and reclaims `gc_debt` for entries whose weak target has been
923    /// dropped, so the Lua-visible memory total tracks live long-string bytes.
924    /// Short strings are interned and bounded in size, so they are not tracked
925    /// individually. Replaced by Phase D's real allocator accounting.
926    pub gc_tracked_long_strings: Vec<(lua_types::gc::GcWeak<lua_types::string::LuaString>, usize)>,
927
928    /// Phase-B pending-finalizer registry.
929    ///
930    /// Each entry is a strong `GcRef<LuaTable>` to a table whose metatable
931    /// carried `__gc` at the time `setmetatable` was called. The strong ref
932    /// pins the table so a normal `Rc::drop` does not destroy it before its
933    /// `__gc` metamethod runs. The Phase-B finalizer sweep
934    /// (`crate::api::run_pending_finalizers`) scans this list, takes any
935    /// entry whose strong count is 1 (only this list holds it — i.e. the
936    /// user has dropped every reference), and invokes its `__gc` before
937    /// releasing the ref. Replaced by `finobj` / `tobefnz` when the real
938    /// incremental GC lands in Phase D.
939    pub pending_finalizers: Vec<GcRef<lua_types::value::LuaTable>>,
940
941    /// Tables identified by the most recent `collect_via_heap` mark phase as
942    /// reachable only through `pending_finalizers` (i.e. the user has dropped
943    /// every reference). Their `__gc` runs the next time
944    /// `run_pending_finalizers` executes; entries are then cleared. Traced as
945    /// strong roots so they survive the sweep that scheduled them.
946    pub to_be_finalized: Vec<GcRef<lua_types::value::LuaTable>>,
947
948    // Phase-D NOTE: tobefnz + fixedgc removed (dead since Phase A — see
949    // sibling note above re allgc et al). Pending finalizers live in
950    // `pending_finalizers` above; fixed objects live in heap.allgc with the
951    // GC's own `fixed` bit.
952
953    // Generational cohort markers — Phase D only
954    // types.tsv: global_State.survival/old1/reallyold/firstold1/finobjsur/finobjold1/finobjrold
955    //   → (removed; replaced by index cursors in Phase D)
956
957    // types.tsv: global_State.twups → Vec<GcRef<LuaState>>
958    pub twups: Vec<GcRef<LuaState>>,
959
960    // types.tsv: global_State.panic → Option<lua_CFunction>
961    pub panic: Option<LuaCFunction>,
962
963    // types.tsv: global_State.mainthread → GcRef<LuaState>
964    // TODO(port): self-referential Rc cycle; Phase D GC handles cycles properly
965    pub mainthread: Option<GcRef<LuaState>>,
966
967    /// Registry of all live coroutine threads, keyed by `ThreadId`. Phase E-1
968    /// replaces the `thread_token` placeholder with a real id-indexed map so
969    /// `coroutine.create` allocates a fresh `LuaState`, registers it, and
970    /// returns a value that resolves back to the same state on every
971    /// `coroutine.status` / `coroutine.resume` call.
972    ///
973    /// Each entry pairs the per-thread `LuaState` with the canonical
974    /// `GcRef<LuaThread>` value, so two `LuaValue::Thread` pushes of the
975    /// same id share `GcRef::ptr_eq` identity. The main thread is NOT
976    /// stored here — its `LuaState` is owned externally by the embedder.
977    /// `main_thread_id` is reserved as `0` and a `LuaValue::Thread`
978    /// carrying id `0` is recognized as the main thread by lookup helpers.
979    pub threads: std::collections::HashMap<u64, ThreadRegistryEntry>,
980
981    /// Cached `LuaValue::Thread` payload for the main thread (id 0).
982    /// Built once during `new_state` so every `push_thread` on the main
983    /// thread shares the same `GcRef<LuaThread>` and thus compares
984    /// pointer-equal under `LuaValue::PartialEq`.
985    pub main_thread_value: GcRef<lua_types::value::LuaThread>,
986
987    /// Identity of the currently-running thread. `0` (main) until a
988    /// coroutine resume swaps it in slice 02b. The Phase E-1 slice
989    /// always leaves this at `main_thread_id` because resume is not yet
990    /// implemented.
991    pub current_thread_id: u64,
992
993    /// Identity of the main thread. Convention: `0`. Held as a field so
994    /// the lookup helpers can read it without hard-coding the constant.
995    pub main_thread_id: u64,
996
997    /// Monotonic counter handing out fresh ids in `new_thread`. Starts
998    /// at `1` because `0` is reserved for the main thread.
999    pub next_thread_id: u64,
1000
1001    // types.tsv: global_State.memerrmsg → GcRef<LuaString>
1002    pub memerrmsg: GcRef<LuaString>,
1003
1004    // types.tsv: global_State.tmname → [GcRef<LuaString>; TM_N]
1005    // TODO(port): TM_N constant and TagMethod enum come from ltm.c → tagmethods.rs
1006    pub tmname: Vec<GcRef<LuaString>>,
1007
1008    // types.tsv: global_State.mt → [Option<GcRef<LuaTable>>; LUA_NUMTYPES]
1009    pub mt: [Option<GcRef<LuaTable>>; LUA_NUMTYPES],
1010
1011    // types.tsv: global_State.strcache → [[GcRef<LuaString>; STRCACHE_M]; STRCACHE_N]
1012    pub strcache: [[GcRef<LuaString>; STRCACHE_M]; STRCACHE_N],
1013
1014    /// Stable intern map for the public [`LuaString`] type. Distinct from
1015    /// `strt` (which keys internal `LuaStringImpl`) because the parser and
1016    /// stdlib need pointer-equality across `intern_str` calls so
1017    /// `GcRef::ptr_eq` can resolve variable identity. Without this map each
1018    /// call allocates a fresh `GcRef` and locals/upvalues fail to resolve.
1019    pub interned_lt: std::collections::HashMap<Box<[u8]>, GcRef<LuaString>>,
1020
1021    // types.tsv: global_State.warnf → Option<Box<dyn FnMut(&[u8], bool)>>
1022    pub warnf: Option<Box<dyn FnMut(&[u8], bool)>>,
1023
1024    /// Registry of native `LuaCFunction` pointers. Lua-types cannot reference
1025    /// `LuaState`, so `LuaClosure::LightC` carries a `usize` index into this
1026    /// vector instead of the real function pointer. `push_c_function`
1027    /// registers the function and stores the resulting index in the closure.
1028    pub c_functions: Vec<LuaCFunction>,
1029
1030    /// Phase-D heap. Owns the allgc intrusive list and runs collections.
1031    /// During Phase A-C this is `paused=true`, so allocations don't auto-
1032    /// register and `step` is a no-op. Phase D-1d wires `unpause()` after
1033    /// state initialization, at which point `step` runs during VM dispatch.
1034    pub heap: lua_gc::Heap,
1035
1036    /// Phase E-3 cross-thread open-upvalue mirror. Maps `(thread_id, stack_idx)`
1037    /// to the live value of an open upvalue whose home thread is currently
1038    /// suspended while another thread runs. `coroutine.resume` snapshots the
1039    /// parent's open upvalues into this map before yielding control to the
1040    /// child, and reads the (possibly mutated) values back into the parent's
1041    /// stack when the child suspends or returns. From the running thread's
1042    /// perspective, `upvalue_get` / `upvalue_set` consult the mirror whenever
1043    /// an open upvalue's `thread_id` does not match `current_thread_id`.
1044    ///
1045    /// This avoids a stack refactor: the parent's `LuaState` is held by a
1046    /// `&mut` reference up the call stack during resume, so its stack cannot
1047    /// be reached directly through any `Rc<RefCell<_>>`. The mirror is the
1048    /// shared scratchpad that bridges the gap for the duration of a resume.
1049    pub cross_thread_upvals: std::collections::HashMap<(u64, StackIdx), LuaValue>,
1050
1051    /// Phase F-1.a workaround for GC use-after-free across coroutine boundaries.
1052    /// When `aux_resume` switches to a child thread, the parent's live stack
1053    /// values would otherwise become unreachable to the tracer for the duration
1054    /// of the resume (the parent `LuaState` is held only as a stack-borrowed
1055    /// `&mut` up the call chain and is not part of any traced root set). To
1056    /// keep those values alive, `aux_resume` pushes a snapshot of the parent
1057    /// stack here before transferring control, and pops it on suspension or
1058    /// completion. The tracer visits every snapshot as a GC root via the
1059    /// `Trace for GlobalState` impl in `trace_impls.rs`.
1060    ///
1061    /// Phase F-2.b added a reachability-driven thread sweep that supersedes
1062    /// most of this, but the snapshot still guards values that live only on
1063    /// the parent's stack (i.e. not yet rooted by any thread node).
1064    pub suspended_parent_stacks: Vec<Vec<LuaValue>>,
1065
1066    /// Open-upvalue handles belonging to the same suspended parent windows as
1067    /// `suspended_parent_stacks`. Stack snapshots keep the pointed-to values
1068    /// alive; this roots the `UpVal` objects themselves so a GC inside the
1069    /// child coroutine cannot sweep entries still present in the parent's
1070    /// `openupval` list.
1071    pub suspended_parent_open_upvals: Vec<Vec<GcRef<UpVal>>>,
1072}
1073
1074impl GlobalState {
1075    /// Total live bytes allocated (GCdebt + totalbytes).
1076    ///
1077    /// macros.tsv: `gettotalbytes → g.total_bytes()`
1078    pub fn total_bytes(&self) -> usize {
1079        (self.totalbytes + self.gc_debt) as usize
1080    }
1081
1082    /// Look up the coroutine `LuaState` registered under `id`. Returns
1083    /// `None` for the main-thread id (the main `LuaState` is owned by
1084    /// the embedder, not stored in `threads`) and for ids that were
1085    /// never issued or have already been closed.
1086    pub fn get_thread(&self, id: u64) -> Option<&ThreadRegistryEntry> {
1087        self.threads.get(&id)
1088    }
1089
1090    /// Return the canonical `GcRef<LuaThread>` for `id`. For the main
1091    /// thread that's `main_thread_value`; for a coroutine it's the
1092    /// value stored in the registry. Returns `None` if `id` is unknown.
1093    pub fn thread_value_for(&self, id: u64) -> Option<GcRef<lua_types::value::LuaThread>> {
1094        if id == self.main_thread_id {
1095            Some(self.main_thread_value.clone())
1096        } else {
1097            self.threads.get(&id).map(|e| e.value.clone())
1098        }
1099    }
1100
1101    /// Returns `true` when the state has been fully initialized.
1102    ///
1103    /// macros.tsv: `completestate → g.is_complete()`
1104    ///
1105    /// PORT NOTE: C uses `g->nilvalue` being nil as the "complete" signal.
1106    /// We replicate the same logic: `nilvalue == Nil` means complete.
1107    pub fn is_complete(&self) -> bool {
1108        matches!(self.nilvalue, LuaValue::Nil)
1109    }
1110
1111    /// Returns the "current white" GC color bitmask.
1112    ///
1113    /// macros.tsv: `luaC_white → g.current_white()`
1114    ///
1115    /// PORT NOTE: GC color management deferred to Phase D; always returns
1116    /// the initial white bit.
1117    pub fn current_white(&self) -> u8 {
1118        self.currentwhite
1119    }
1120
1121    /// Returns the "other white" GC color bitmask.
1122    ///
1123    /// macros.tsv: `otherwhite → g.other_white()`
1124    pub fn other_white(&self) -> u8 {
1125        // TODO(port): Phase D — toggle white bit properly
1126        self.currentwhite ^ 0x03
1127    }
1128
1129    /// Returns `true` if the GC is in generational mode.
1130    ///
1131    /// macros.tsv: `isdecGCmodegen → g.is_gen_mode()`
1132    pub fn is_gen_mode(&self) -> bool {
1133        self.gckind == GcKind::Generational as u8
1134    }
1135
1136    /// Returns `true` if the GC is currently running.
1137    ///
1138    /// macros.tsv: `gcrunning → g.gc_running()`
1139    pub fn gc_running(&self) -> bool {
1140        self.gcstp == 0
1141    }
1142
1143    /// Returns `true` while the GC is in its propagation phase.
1144    ///
1145    /// macros.tsv: `keepinvariant → g.keep_invariant()`
1146    pub fn keep_invariant(&self) -> bool {
1147        // TODO(port): Phase D — check gcstate for propagation phases
1148        false
1149    }
1150
1151    /// Returns `true` while the GC is in a sweep phase.
1152    ///
1153    /// macros.tsv: `issweepphase → g.is_sweep_phase()`
1154    pub fn is_sweep_phase(&self) -> bool {
1155        // TODO(port): Phase D — check gcstate for sweep states (GCSswpallgc etc.)
1156        false
1157    }
1158
1159    // ── Phase-B stubs ─────────────────────────────────────────────────────────
1160    pub fn gc_debt(&self) -> isize { self.gc_debt }
1161    pub fn set_gc_debt(&mut self, d: isize) { self.gc_debt = d; }
1162    pub fn gc_at_pause(&self) -> bool { self.gcstate == 0 }
1163    pub fn gc_pause_param(&self) -> u8 { self.gcpause }
1164    pub fn set_gc_pause_param(&mut self, p: u8) { self.gcpause = p; }
1165    pub fn gc_stepmul_param(&self) -> u8 { self.gcstepmul }
1166    pub fn set_gc_stepmul_param(&mut self, p: u8) { self.gcstepmul = p; }
1167    pub fn set_gc_genmajormul(&mut self, p: u8) { self.genmajormul = p; }
1168    pub fn gc_stop_flags(&self) -> u8 { self.gcstp }
1169    pub fn set_gc_stop_flags(&mut self, f: u8) { self.gcstp = f; }
1170    pub fn stop_gc_internal(&mut self) -> u8 {
1171        let old = self.gcstp;
1172        self.gcstp |= GCSTPGC;
1173        old
1174    }
1175    pub fn set_gc_stop_user(&mut self) {
1176        // GCSTPUSR (lgc.h:155) = 1 — bit set when GC is stopped by user (lua_gc(L, LUA_GCSTOP)).
1177        self.gcstp = GCSTPUSR;
1178    }
1179    pub fn clear_gc_stop(&mut self) { self.gcstp = 0; }
1180    pub fn is_gc_running(&self) -> bool { self.gcstp == 0 }
1181    /// True when the GC has been disabled internally (state setup, mid-GC,
1182    /// or while closing); user-stop via `collectgarbage("stop")` does NOT
1183    /// set this bit, so `lua_gc` continues to honour Count/Step/etc.
1184    ///
1185    pub fn is_gc_stopped_internally(&self) -> bool { (self.gcstp & GCSTPGC) != 0 }
1186
1187    /// Returns the interned `__xxx` name string for tag method `tm`, or
1188    /// `None` if `tmname` has not yet been initialised (early bootstrap).
1189    ///
1190    /// macros.tsv: `getshrstr(G(L)->tmname[tm]) → g.tm_name(tm)`.
1191    ///
1192    /// PORT NOTE: The lua-vm crate carries two distinct `TagMethod` enums
1193    /// (one in `lua-types`, one in `crate::tagmethods`) with identical
1194    /// `#[repr(u8)]` ordering. The [`TmIndex`] trait bridges them so callers
1195    /// from either side can index `tmname` uniformly.
1196    pub fn tm_name<T: TmIndex>(&self, tm: T) -> Option<GcRef<LuaString>> {
1197        self.tmname.get(tm.tm_index()).cloned()
1198    }
1199}
1200
1201/// Discriminant-to-index conversion for the two parallel `TagMethod` enums.
1202///
1203/// Both `lua_types::tagmethod::TagMethod` and `crate::tagmethods::TagMethod`
1204/// are `#[repr(u8)]` with the same ORDER TM layout, so casting through `u8`
1205/// yields the correct `GlobalState.tmname` index for either type.
1206pub trait TmIndex: Copy {
1207    fn tm_index(self) -> usize;
1208}
1209impl TmIndex for lua_types::tagmethod::TagMethod {
1210    fn tm_index(self) -> usize { self as u8 as usize }
1211}
1212impl TmIndex for crate::tagmethods::TagMethod {
1213    fn tm_index(self) -> usize { self as u8 as usize }
1214}
1215impl TmIndex for usize {
1216    fn tm_index(self) -> usize { self }
1217}
1218impl TmIndex for u8 {
1219    fn tm_index(self) -> usize { self as usize }
1220}
1221
1222use lua_types::tagmethod::TagMethod;
1223
1224// ─── LuaState ────────────────────────────────────────────────────────────────
1225
1226/// Per-thread Lua execution state.
1227///
1228/// types.tsv: `lua_State → LuaState`
1229///
1230/// All stack-pointer fields in C (`StkIdRel`, `StkId`) become `StackIdx` (u32
1231/// index into `stack: Vec<StackValue>`).  The C intrusive `CallInfo` linked list
1232/// becomes `call_info: Vec<CallInfo>` indexed by `CallInfoIdx`.
1233pub struct LuaState {
1234    // ── Thread status ──
1235
1236    // types.tsv: lua_State.status → u8
1237    pub status: u8,
1238
1239    // types.tsv: lua_State.allowhook → bool
1240    pub allowhook: bool,
1241
1242    // types.tsv: lua_State.nci → u32
1243    pub nci: u32,
1244
1245    // ── Stack ──
1246
1247    // types.tsv: lua_State.top → StackIdx
1248    pub top: StackIdx,
1249
1250    // types.tsv: lua_State.stack_last → StackIdx (redundant once Vec; kept for parity)
1251    pub stack_last: StackIdx,
1252
1253    // types.tsv: lua_State.stack → Vec<StackValue>
1254    pub stack: Vec<StackValue>,
1255
1256    // ── Call info ──
1257
1258    // types.tsv: lua_State.ci → CallInfoIdx
1259    pub ci: CallInfoIdx,
1260
1261    // types.tsv: lua_State.base_ci → CallInfo  (Vec element 0)
1262    // PORT NOTE: In Rust, base_ci is call_info[0]. There is no separate field.
1263    pub call_info: Vec<CallInfo>,
1264
1265    // ── Upvalues / to-be-closed ──
1266
1267    // types.tsv: lua_State.openupval → Vec<GcRef<UpVal>>
1268    pub openupval: Vec<GcRef<UpVal>>,
1269
1270    // types.tsv: lua_State.tbclist → Vec<StackIdx>
1271    pub tbclist: Vec<StackIdx>,
1272
1273    // ── Global state ──
1274
1275    // types.tsv: lua_State.l_G → (accessed via method)
1276    // PORT NOTE: Rc<RefCell<>> for shared ownership across coroutine threads.
1277    pub(crate) global: Rc<RefCell<GlobalState>>,
1278
1279    // ── Hooks ──
1280
1281    // types.tsv: lua_State.hook → Option<Box<dyn FnMut(&mut LuaState, &LuaDebug)>>
1282    pub hook: Option<Box<dyn FnMut(&mut LuaState, &crate::debug::LuaDebug)>>,
1283
1284    // types.tsv: lua_State.hookmask → u8
1285    pub hookmask: u8,
1286
1287    // types.tsv: lua_State.basehookcount → i32
1288    pub basehookcount: i32,
1289
1290    // types.tsv: lua_State.hookcount → i32
1291    pub hookcount: i32,
1292
1293    // ── Error handling ──
1294
1295    // types.tsv: lua_State.errorJmp → (removed; replaced by Result<T, LuaError>)
1296    // PORT NOTE: Entirely removed. The `?` operator replaces setjmp/longjmp.
1297
1298    // types.tsv: lua_State.errfunc → isize
1299    pub errfunc: isize,
1300
1301    // ── C-call depth ──
1302
1303    // types.tsv: lua_State.nCcalls → u32
1304    pub nCcalls: u32,
1305
1306    // ── Debug / hooks ──
1307
1308    // types.tsv: lua_State.oldpc → u32
1309    pub oldpc: u32,
1310
1311    // ── GC color (Phase D) ──
1312
1313    // types.tsv: GCObject.marked → u8
1314    pub marked: u8,
1315
1316    /// Owner thread id for this `LuaState`, cached as a plain `u64` so the
1317    /// hot path of `upvalue_get` can compare against an open upvalue's
1318    /// `thread_id` without taking a `RefCell::borrow` on the shared
1319    /// `GlobalState`.
1320    ///
1321    /// Invariant: while this `LuaState` is the actively running thread,
1322    /// `GlobalState::current_thread_id == self.cached_thread_id`. This is
1323    /// maintained structurally by `new_state`/`new_thread` (which set
1324    /// `cached_thread_id` to the thread's own id once at construction)
1325    /// combined with the coroutine resume protocol: `coro_lib::resume`
1326    /// writes `co_state.global.current_thread_id = co_id` before the
1327    /// coroutine runs, and restores `parent_thread_id` on yield/return.
1328    /// Because each thread caches its own id (not the global's id), the
1329    /// invariant survives every context switch without an explicit refresh
1330    /// at the resume site.
1331    pub cached_thread_id: u64,
1332
1333}
1334
1335impl LuaState {
1336    /// Access the process-wide `GlobalState` immutably.
1337    ///
1338    /// macros.tsv: `G → state.global()`
1339    ///
1340    /// PORT NOTE: Returns `std::cell::Ref<GlobalState>` because GlobalState is held in
1341    /// `Rc<RefCell<...>>`. Call sites that do `state.global().field` should work fine
1342    /// via `Deref`. Callers must not hold the `Ref` across a `global_mut()` call.
1343    pub fn global(&self) -> std::cell::Ref<'_, GlobalState> {
1344        self.global.borrow()
1345    }
1346
1347    /// Access the process-wide `GlobalState` mutably.
1348    ///
1349    /// macros.tsv: `G → state.global()` (writes use `state.global_mut()`)
1350    pub fn global_mut(&self) -> std::cell::RefMut<'_, GlobalState> {
1351        self.global.borrow_mut()
1352    }
1353
1354    /// Clone the `Rc` handle to the GlobalState for sharing with a new coroutine.
1355    ///
1356    /// Used in `new_thread` to give the child thread access to the same GlobalState.
1357    pub fn global_rc(&self) -> Rc<RefCell<GlobalState>> {
1358        Rc::clone(&self.global)
1359    }
1360
1361    /// Return the current C-call recursion depth (lower 16 bits of `nCcalls`).
1362    ///
1363    /// macros.tsv: `getCcalls → state.c_calls()`
1364    pub fn c_calls(&self) -> u32 {
1365        self.nCcalls & 0xffff
1366    }
1367
1368    /// Increment the non-yieldable call count (upper 16 bits of `nCcalls`).
1369    ///
1370    /// macros.tsv: `incnny → state.inc_nny()`
1371    pub fn inc_nny(&mut self) {
1372        self.nCcalls += 0x10000;
1373    }
1374
1375    /// Decrement the non-yieldable call count.
1376    ///
1377    /// macros.tsv: `decnny → state.dec_nny()`
1378    pub fn dec_nny(&mut self) {
1379        self.nCcalls -= 0x10000;
1380    }
1381
1382    /// Returns `true` if the thread can yield (no non-yieldable frames on the stack).
1383    ///
1384    /// macros.tsv: `yieldable → state.is_yieldable()`
1385    pub fn is_yieldable(&self) -> bool {
1386        (self.nCcalls & 0xffff0000) == 0
1387    }
1388
1389    /// Reset the hook countdown to the baseline.
1390    ///
1391    /// macros.tsv: `resethookcount → state.reset_hook_count()`
1392    pub fn reset_hook_count(&mut self) {
1393        self.hookcount = self.basehookcount;
1394    }
1395
1396    /// Returns the current stack capacity (slots between base and stack_last).
1397    ///
1398    /// macros.tsv: `stacksize → state.stack_size()`
1399    pub fn stack_size(&self) -> usize {
1400        self.stack_last.0 as usize
1401    }
1402
1403    /// Push a value onto the stack, incrementing `top`.
1404    ///
1405    /// macros.tsv: `api_incr_top → gone — state.push() already increments`
1406    #[inline(always)]
1407    pub fn push(&mut self, val: LuaValue) {
1408        let top = self.top.0 as usize;
1409        if top < self.stack.len() {
1410            self.stack[top] = StackValue { val, tbc_delta: 0 };
1411        } else {
1412            self.stack.push(StackValue { val, tbc_delta: 0 });
1413        }
1414        self.top = StackIdx(self.top.0 + 1);
1415    }
1416
1417    /// Pop the top value from the stack, decrementing `top`.
1418    ///
1419    #[inline(always)]
1420    pub fn pop(&mut self) -> LuaValue {
1421        if self.top.0 == 0 {
1422            return LuaValue::Nil;
1423        }
1424        self.top = StackIdx(self.top.0 - 1);
1425        self.stack[self.top.0 as usize].val.clone()
1426    }
1427
1428    /// Retrieve the value at the given stack index without removing it.
1429    ///
1430    /// macros.tsv: `s2v → state.stack_at(idx)` → returns `&LuaValue`
1431    #[inline(always)]
1432    pub fn stack_val(&self, idx: StackIdx) -> &LuaValue {
1433        &self.stack[idx.0 as usize].val
1434    }
1435
1436    /// Write a value to a specific stack slot.
1437    #[inline(always)]
1438    pub fn set_stack_val(&mut self, idx: StackIdx, val: LuaValue) {
1439        self.stack[idx.0 as usize].val = val;
1440    }
1441
1442    /// Returns a no-op GC handle.
1443    ///
1444    /// macros.tsv: `luaC_checkGC → state.gc().check_step()`, etc.
1445    ///
1446    /// PORT NOTE: In Phases A–C the GC is `Rc`-based and all GC operations are
1447    /// no-ops. Phase D replaces this with real GC logic in `lua-gc`.
1448    pub fn gc(&mut self) -> GcHandle<'_> {
1449        GcHandle { _state: self }
1450    }
1451
1452    /// Create a new empty table and register it with the GC.
1453    ///
1454    /// macros.tsv: `lua_newtable → state.new_table()`
1455    pub fn new_table(&mut self) -> GcRef<LuaTable> {
1456        // TODO(port): register with GC tracking (state.global_mut().allgc) in Phase D
1457        GcRef::new(LuaTable::placeholder())
1458    }
1459
1460    /// Intern a byte string in the global string pool.
1461    ///
1462    /// In C, short strings (≤ LUAI_MAXSHORTLEN = 40 bytes) are interned globally
1463    /// via `luaS_newlstr`, while long strings allocate a fresh TString each
1464    /// call so distinct long strings keep distinct object identity (observable
1465    /// via `string.format("%p", s)`). The parser separately deduplicates
1466    /// long-string literals within a single chunk through `luaX_newstring`'s
1467    /// `ls->h` anchor table.
1468    ///
1469    /// macros.tsv: `luaS_new → state.intern_str(s)`
1470    pub fn intern_str(&mut self, bytes: &[u8]) -> Result<GcRef<LuaString>, LuaError> {
1471        if bytes.len() <= crate::string::MAX_SHORT_LEN {
1472            if let Some(existing) = self.global().interned_lt.get(bytes) {
1473                return Ok(existing.clone());
1474            }
1475            let _local = crate::string::new(self, bytes)?;
1476            let new_ref = GcRef::new(LuaString::from_bytes(bytes.to_vec()));
1477            self.global_mut()
1478                .interned_lt
1479                .insert(bytes.to_vec().into_boxed_slice(), new_ref.clone());
1480            Ok(new_ref)
1481        } else {
1482            let new_ref = GcRef::new(LuaString::from_bytes(bytes.to_vec()));
1483            // PORT NOTE: Phase-B byte tracking for `collectgarbage("count")`.
1484            // C-Lua's `luaC_newobj` calls `luaM_malloc`, which adds
1485            // `sizeof(TString) + len + 1` to `g->GCdebt`. Phases A–C bypass
1486            // that allocator, so without explicit accounting the Lua-visible
1487            // memory total never reflects string payload — gc.lua's
1488            // string-keys-in-weak-tables block depends on observing the >8MB
1489            // jump after allocating two 4MB strings. Short strings are
1490            // interned (bounded in size) so they are not tracked here.
1491            // `reclaim_dead_long_strings` later subtracts the size back out
1492            // when the underlying `Rc` is dropped.
1493            let size = bytes.len()
1494                + std::mem::size_of::<LuaString>()
1495                + std::mem::size_of::<usize>();
1496            let mut g = self.global_mut();
1497            g.gc_debt += size as isize;
1498            g.gc_tracked_long_strings
1499                .push((new_ref.downgrade(), size));
1500            Ok(new_ref)
1501        }
1502    }
1503
1504    /// Returns the current CallInfo index (the active call frame).
1505    #[inline(always)]
1506    pub fn top_idx(&self) -> StackIdx {
1507        self.top
1508    }
1509}
1510
1511// ─── Phase-B stub methods ─────────────────────────────────────────────────────
1512//
1513// The methods in the impl blocks below were referenced by api.rs, debug.rs,
1514// do_.rs, vm.rs, tagmethods.rs etc. during Phase A. Each body is a `todo!()`
1515// pinned to a phase-b task; once the corresponding C function is faithfully
1516// ported the stub will be replaced. Signatures are inferred from call sites
1517// and should be treated as Phase-B-grade approximations.
1518
1519impl LuaState {
1520    #[inline(always)]
1521    pub fn get_at(&self, idx: impl Into<StackIdxConv>) -> LuaValue {
1522        let i: StackIdx = idx.into().0;
1523        match self.stack.get(i.0 as usize) {
1524            Some(slot) => slot.val.clone(),
1525            None => LuaValue::Nil,
1526        }
1527    }
1528    #[inline(always)]
1529    pub fn set_at(&mut self, idx: impl Into<StackIdxConv>, v: LuaValue) {
1530        let i: StackIdx = idx.into().0;
1531        self.stack[i.0 as usize].val = v;
1532    }
1533
1534    /// Clear stack slots in `[start, end)` without changing `top`.
1535    ///
1536    /// Internal call setup reserves space up to `ci.top`; while GC tracing is
1537    /// conservative over that range, the unused tail must not retain stale
1538    /// collectable values from previous frames.
1539    pub fn clear_stack_range(&mut self, start: StackIdx, end: StackIdx) {
1540        if end.0 <= start.0 {
1541            return;
1542        }
1543        let end_u = end.0 as usize;
1544        if end_u > self.stack.len() {
1545            self.stack.resize_with(end_u, StackValue::default);
1546        }
1547        for i in start.0..end.0 {
1548            self.stack[i as usize].val = LuaValue::Nil;
1549            self.stack[i as usize].tbc_delta = 0;
1550        }
1551    }
1552    /// Hot-path accessor: returns `Some(i)` only when the stack slot at `idx`
1553    /// holds a `LuaValue::Int(i)`. Returns `None` for any other tag (including
1554    /// out-of-bounds, which behaves as `Nil`).
1555    ///
1556    /// `ttisinteger` predicate that gates the integer arithmetic fast path in
1557    /// `lvm.c`'s `op_arith_aux` macro. Avoids the full `LuaValue` clone that
1558    /// `get_at` performs — the operand is only needed for its `i64` payload.
1559    #[inline]
1560    pub fn get_int_at(&self, idx: impl Into<StackIdxConv>) -> Option<i64> {
1561        let i: StackIdx = idx.into().0;
1562        match self.stack.get(i.0 as usize) {
1563            Some(slot) => match &slot.val {
1564                LuaValue::Int(v) => Some(*v),
1565                _ => None,
1566            },
1567            None => None,
1568        }
1569    }
1570    /// Hot-path accessor: returns `Some((a, b))` only when both stack slots
1571    /// at `rb` and `rc` hold integers. Equivalent to two `get_int_at` calls
1572    /// but is shaped so the arithmetic opcode dispatch arms can pattern-match
1573    /// the common case with a single `if let`.
1574    ///
1575    /// the `op_arith_aux` macro.
1576    #[inline]
1577    pub fn get_int_pair_at(
1578        &self,
1579        rb: impl Into<StackIdxConv>,
1580        rc: impl Into<StackIdxConv>,
1581    ) -> Option<(i64, i64)> {
1582        let ib = self.get_int_at(rb)?;
1583        let ic = self.get_int_at(rc)?;
1584        Some((ib, ic))
1585    }
1586    /// Hot-path accessor: returns `Some(f)` when the slot holds a `Float(f)`
1587    /// or coerces an `Int(i)` to `f64`. Returns `None` for any other tag.
1588    /// No `LuaValue` clone — only the primitive payload travels back.
1589    ///
1590    #[inline]
1591    pub fn get_num_at(&self, idx: impl Into<StackIdxConv>) -> Option<f64> {
1592        let i: StackIdx = idx.into().0;
1593        match self.stack.get(i.0 as usize) {
1594            Some(slot) => match &slot.val {
1595                LuaValue::Float(f) => Some(*f),
1596                LuaValue::Int(v) => Some(*v as f64),
1597                _ => None,
1598            },
1599            None => None,
1600        }
1601    }
1602    /// Hot-path accessor: returns `Some(f)` only when the slot holds a
1603    /// `LuaValue::Float(f)`. Does NOT coerce integers; the integer branch is
1604    /// the caller's responsibility. Used by opcode arms that have already
1605    /// ruled out the integer fast path.
1606    #[inline]
1607    pub fn get_float_at(&self, idx: impl Into<StackIdxConv>) -> Option<f64> {
1608        let i: StackIdx = idx.into().0;
1609        match self.stack.get(i.0 as usize) {
1610            Some(slot) => match &slot.val {
1611                LuaValue::Float(f) => Some(*f),
1612                _ => None,
1613            },
1614            None => None,
1615        }
1616    }
1617    /// Hot-path accessor: pair version of `get_num_at` — returns `Some((a,b))`
1618    /// when both slots coerce to `f64` (Float or Int), `None` if either does
1619    /// not. Used by the float fast path of the arith opcodes.
1620    ///
1621    #[inline]
1622    pub fn get_num_pair_at(
1623        &self,
1624        rb: impl Into<StackIdxConv>,
1625        rc: impl Into<StackIdxConv>,
1626    ) -> Option<(f64, f64)> {
1627        let nb = self.get_num_at(rb)?;
1628        let nc = self.get_num_at(rc)?;
1629        Some((nb, nc))
1630    }
1631    /// Set `top` to an absolute stack index. Grows the backing stack vector
1632    /// (filling new slots with `Nil`) when `idx` is past `stack.len()`, but
1633    /// never clobbers existing slots between the old top and the new top —
1634    /// VM opcodes (Call, ForPrep, etc.) write registers via `set_at` and then
1635    /// raise `top` to signal "these are now live"; nil-filling here would
1636    /// erase the just-written values.
1637    ///
1638    /// setnilvalue(s2v(L->top.p++))` clear loop in `lua_settop` (lapi.c) is
1639    /// part of the public API path and lives in `api::set_top` instead.
1640    /// PORT NOTE: callers pass an absolute `StackIdx`, not the relative `idx`
1641    /// of the public `lua_settop`. The to-be-closed (`tbclist`) close path
1642    /// is Phase E and not handled here.
1643    #[inline(always)]
1644    pub fn set_top(&mut self, idx: impl Into<StackIdxConv>) {
1645        let new_top: StackIdx = idx.into().0;
1646        let new_top_u = new_top.0 as usize;
1647        if new_top_u > self.stack.len() {
1648            self.stack.resize_with(new_top_u, StackValue::default);
1649        }
1650        self.top = new_top;
1651    }
1652    /// Primitive "set top index" — just writes `self.top`, no nil-fill.
1653    ///
1654    /// PORT NOTE: callers (`api.rs::set_top`, `raw_set`, etc.) pre-nil-fill or
1655    /// only shrink, so this routine intentionally does no clearing or resizing.
1656    /// The to-be-closed (`tbclist`) close path is Phase E.
1657    #[inline(always)]
1658    pub fn set_top_idx(&mut self, idx: impl Into<StackIdxConv>) {
1659        let new_top: StackIdx = idx.into().0;
1660        self.top = new_top;
1661    }
1662    /// Decrement `top` by 1 (saturating at zero).
1663    ///
1664    #[inline(always)]
1665    pub fn dec_top(&mut self) {
1666        if self.top.0 > 0 {
1667            self.top = StackIdx(self.top.0 - 1);
1668        }
1669    }
1670    #[inline(always)]
1671    pub fn pop_n(&mut self, n: usize) {
1672        let cur = self.top.0 as usize;
1673        let new = cur.saturating_sub(n);
1674        self.top = StackIdx(new as u32);
1675    }
1676    /// Returns the value at the given stack index without removing it.
1677    ///
1678    #[inline(always)]
1679    pub fn peek_at(&mut self, idx: impl Into<StackIdxConv>) -> LuaValue {
1680        let i: StackIdx = idx.into().0;
1681        match self.stack.get(i.0 as usize) {
1682            Some(slot) => slot.val.clone(),
1683            None => LuaValue::Nil,
1684        }
1685    }
1686    /// Returns the value just below `top` (the topmost live slot) without
1687    /// removing it.
1688    ///
1689    #[inline(always)]
1690    pub fn peek_top(&mut self) -> LuaValue {
1691        if self.top.0 == 0 {
1692            return LuaValue::Nil;
1693        }
1694        self.stack[(self.top.0 - 1) as usize].val.clone()
1695    }
1696    /// Returns the topmost slot interpreted as a string. Panics if the slot
1697    /// is not a `LuaValue::Str`. Callers (e.g. `luaO_pushvfstring`) guarantee
1698    /// the value has been pushed as an interned string immediately prior.
1699    ///
1700    pub fn peek_string_at_top(&mut self) -> GcRef<LuaString> {
1701        match self.peek_top() {
1702            LuaValue::Str(s) => s,
1703            _ => panic!("peek_string_at_top: top of stack is not a string"),
1704        }
1705    }
1706    /// Mutable reference to the value at the given stack slot.
1707    ///
1708    pub fn stack_at(&mut self, idx: impl Into<StackIdxConv>) -> &mut LuaValue {
1709        let i: StackIdx = idx.into().0;
1710        &mut self.stack[i.0 as usize].val
1711    }
1712    /// Writes `Nil` to the given stack slot.
1713    ///
1714    pub fn stack_set_nil(&mut self, idx: impl Into<StackIdxConv>) {
1715        let i: StackIdx = idx.into().0;
1716        let slot = i.0 as usize;
1717        if slot < self.stack.len() {
1718            self.stack[slot].val = LuaValue::Nil;
1719        }
1720    }
1721    /// Resizes the underlying stack vector to `size` slots, padding new slots
1722    /// with `StackValue::default()` (which is `Nil`). Returns `Ok(())` on
1723    /// success — `Vec::resize_with` in Rust does not have a fallible path the
1724    /// way `luaM_reallocvector` does in C, so the `Result` is here for
1725    /// signature parity with future fallible allocators.
1726    ///
1727    ///                         newsize+EXTRA_STACK, StackValue)`.
1728    pub fn stack_resize(&mut self, size: usize) -> Result<(), LuaError> {
1729        self.stack.resize_with(size, StackValue::default);
1730        Ok(())
1731    }
1732    pub fn stack_available(&mut self) -> usize {
1733        (self.stack_last.0 as usize).saturating_sub(self.top.0 as usize)
1734    }
1735    pub fn check_stack(&mut self, n: i32) -> Result<(), LuaError> {
1736        let free = (self.stack_last.0 as i32) - (self.top.0 as i32);
1737        if free <= n {
1738            self.grow_stack(n, true)?;
1739        }
1740        Ok(())
1741    }
1742    /// Inherent method wrapper around the free function `do_::grow_stack`,
1743    /// preserving the historical `Result<(), LuaError>` signature used by
1744    /// `check_stack` and other VM call sites. The bool returned by the
1745    /// underlying implementation distinguishes soft failure (when
1746    /// `raise_error` is false) from success; that distinction is dropped here
1747    /// because every current caller passes `raise_error = true` and only
1748    /// cares about error propagation.
1749    ///
1750    pub fn grow_stack(&mut self, n: i32, raise_error: bool) -> Result<(), LuaError> {
1751        crate::do_::grow_stack(self, n, raise_error).map(|_| ())
1752    }
1753
1754    #[inline(always)]
1755    pub fn get_ci(&self, idx: CallInfoIdx) -> &CallInfo { &self.call_info[idx.as_usize()] }
1756    #[inline(always)]
1757    pub fn get_ci_mut(&mut self, idx: CallInfoIdx) -> &mut CallInfo { &mut self.call_info[idx.as_usize()] }
1758    #[inline(always)]
1759    pub fn current_call_info(&self) -> &CallInfo { &self.call_info[self.ci.as_usize()] }
1760    #[inline(always)]
1761    pub fn current_call_info_mut(&mut self) -> &mut CallInfo { let i = self.ci.as_usize(); &mut self.call_info[i] }
1762    #[inline(always)]
1763    pub fn current_ci_idx(&self) -> CallInfoIdx { self.ci }
1764    pub fn call_stack_mut(&mut self) -> &mut Vec<CallInfo> { &mut self.call_info }
1765    #[inline(always)]
1766    pub fn next_ci(&mut self) -> Result<CallInfoIdx, LuaError> {
1767        match self.call_info[self.ci.as_usize()].next {
1768            Some(idx) => Ok(idx),
1769            None => Ok(extend_ci(self)),
1770        }
1771    }
1772    #[inline(always)]
1773    pub fn prev_ci(&self, idx: CallInfoIdx) -> Option<CallInfoIdx> { self.call_info[idx.as_usize()].previous }
1774    pub fn get_prev_ci(&self, idx: CallInfoIdx) -> Option<&CallInfo> {
1775        self.call_info[idx.as_usize()]
1776            .previous
1777            .map(|p| &self.call_info[p.as_usize()])
1778    }
1779    #[inline(always)]
1780    pub fn is_base_ci(&self, idx: CallInfoIdx) -> bool { idx.as_usize() == 0 }
1781    #[inline(always)]
1782    pub fn is_current_ci(&self, idx: CallInfoIdx) -> bool { idx == self.ci }
1783    pub fn ci_next_func(&self, idx: CallInfoIdx) -> StackIdx {
1784        let next = self.call_info[idx.as_usize()]
1785            .next
1786            .expect("ci_next_func: no next CallInfo");
1787        self.call_info[next.as_usize()].func
1788    }
1789    #[inline(always)]
1790    pub fn ci_top(&self, idx: CallInfoIdx) -> StackIdx { self.call_info[idx.as_usize()].top }
1791    #[inline(always)]
1792    pub fn ci_trap(&mut self, idx: CallInfoIdx) -> bool {
1793        if let CallInfoFrame::Lua { trap, .. } = self.call_info[idx.as_usize()].u {
1794            trap
1795        } else {
1796            false
1797        }
1798    }
1799    #[inline(always)]
1800    pub fn ci_savedpc(&self, idx: CallInfoIdx) -> u32 { self.call_info[idx.as_usize()].saved_pc() }
1801    #[inline(always)]
1802    pub fn set_ci_savedpc(&mut self, idx: CallInfoIdx, pc: u32) {
1803        self.call_info[idx.as_usize()].set_saved_pc(pc);
1804    }
1805    #[inline(always)]
1806    pub fn set_ci_previous(&mut self, idx: CallInfoIdx) {
1807        self.ci = self.call_info[idx.as_usize()]
1808            .previous
1809            .expect("set_ci_previous: returning frame has no previous CallInfo");
1810    }
1811    #[inline(always)]
1812    pub fn ci_previous(&self, idx: CallInfoIdx) -> Option<CallInfoIdx> { self.call_info[idx.as_usize()].previous }
1813    #[inline(always)]
1814    pub fn ci_adjust_func(&mut self, idx: CallInfoIdx, delta: i32) {
1815        let ci = &mut self.call_info[idx.as_usize()];
1816        ci.func = StackIdx((ci.func.0 as i32 - delta) as u32);
1817    }
1818    #[inline(always)]
1819    pub fn ci_base(&self, idx: CallInfoIdx) -> StackIdx { self.call_info[idx.as_usize()].func + 1 }
1820    #[inline(always)]
1821    pub fn ci_is_fresh(&self, idx: CallInfoIdx) -> bool {
1822        (self.call_info[idx.as_usize()].callstatus & CIST_FRESH) != 0
1823    }
1824    #[inline(always)]
1825    pub fn ci_lua_closure(&self, idx: CallInfoIdx) -> Option<GcRef<lua_types::closure::LuaLClosure>> {
1826        let func_idx = self.call_info[idx.as_usize()].func;
1827        match self.get_at(func_idx) {
1828            LuaValue::Function(lua_types::closure::LuaClosure::Lua(cl)) => Some(cl),
1829            _ => None,
1830        }
1831    }
1832    #[inline(always)]
1833    pub fn ci_nextraargs(&self, idx: CallInfoIdx) -> i32 {
1834        self.call_info[idx.as_usize()].nextra_args()
1835    }
1836    #[inline(always)]
1837    pub fn ci_nres(&self, idx: CallInfoIdx) -> i32 {
1838        self.call_info[idx.as_usize()].u2.value
1839    }
1840    #[inline(always)]
1841    pub fn ci_nres_set(&mut self, idx: CallInfoIdx, n: i32) {
1842        self.call_info[idx.as_usize()].u2.value = n;
1843    }
1844    #[inline(always)]
1845    pub fn ci_nresults(&self, idx: CallInfoIdx) -> i32 { self.call_info[idx.as_usize()].nresults as i32 }
1846    pub fn ci_prev_instruction(&self, idx: CallInfoIdx) -> lua_types::opcode::Instruction {
1847        let pc = self.call_info[idx.as_usize()].saved_pc();
1848        let cl = self.ci_lua_closure(idx)
1849            .expect("ci_prev_instruction: CallInfo does not hold a Lua closure");
1850        cl.proto.code[(pc - 1) as usize]
1851    }
1852    pub fn ci_prev2_instruction(&self, idx: CallInfoIdx) -> lua_types::opcode::Instruction {
1853        let pc = self.call_info[idx.as_usize()].saved_pc();
1854        let cl = self.ci_lua_closure(idx)
1855            .expect("ci_prev2_instruction: CallInfo does not hold a Lua closure");
1856        cl.proto.code[(pc - 2) as usize]
1857    }
1858    pub fn ci_skip_next_instruction(&mut self, idx: CallInfoIdx) {
1859        let pc = self.call_info[idx.as_usize()].saved_pc();
1860        self.call_info[idx.as_usize()].set_saved_pc(pc + 1);
1861    }
1862    pub fn ci_step_pc_back(&mut self, idx: CallInfoIdx) {
1863        let pc = self.call_info[idx.as_usize()].saved_pc();
1864        self.call_info[idx.as_usize()].set_saved_pc(pc - 1);
1865    }
1866    pub fn get_ci_pcrel(&mut self, idx: CallInfoIdx) -> u32 {
1867        self.call_info[idx.as_usize()].saved_pc().saturating_sub(1)
1868    }
1869    pub fn get_ci_u2_funcidx(&mut self, idx: CallInfoIdx) -> i32 {
1870        self.call_info[idx.as_usize()].u2.value
1871    }
1872    pub fn get_ci_u2_nres(&mut self, idx: CallInfoIdx) -> i32 {
1873        self.call_info[idx.as_usize()].u2.value
1874    }
1875    pub fn get_ci_u2_nyield(&mut self, idx: CallInfoIdx) -> i32 {
1876        self.call_info[idx.as_usize()].u2.value
1877    }
1878    pub fn get_ci_vararg_info(&mut self, idx: CallInfoIdx) -> (bool, i32, i32) {
1879        let nextraargs = self.call_info[idx.as_usize()].nextra_args();
1880        match self.ci_lua_closure(idx) {
1881            Some(cl) => (cl.proto.is_vararg, nextraargs, cl.proto.numparams as i32),
1882            None => (false, nextraargs, 0),
1883        }
1884    }
1885    pub fn get_ci_lua_proto_numparams(&mut self, idx: CallInfoIdx) -> u8 {
1886        self.ci_lua_closure(idx)
1887            .map(|cl| cl.proto.numparams)
1888            .unwrap_or(0)
1889    }
1890    pub fn set_ci_u2_nres(&mut self, idx: CallInfoIdx, n: i32) {
1891        self.call_info[idx.as_usize()].u2.value = n;
1892    }
1893    pub fn set_ci_u2_nyield(&mut self, idx: CallInfoIdx, n: i32) {
1894        self.call_info[idx.as_usize()].u2.value = n;
1895    }
1896    pub fn set_ci_transfer_info(&mut self, idx: CallInfoIdx, ftransfer: u16, ntransfer: u16) {
1897        let ci = &mut self.call_info[idx.as_usize()];
1898        ci.u2.ftransfer = ftransfer;
1899        ci.u2.ntransfer = ntransfer;
1900    }
1901    pub fn shrink_ci(&mut self) { shrink_ci(self) }
1902    pub fn check_c_stack(&mut self) -> Result<(), LuaError> { check_c_stack(self) }
1903
1904    pub fn status(&mut self) -> LuaStatus { LuaStatus::from_raw(self.status as i32) }
1905    pub fn errfunc(&mut self) -> isize { self.errfunc }
1906    pub fn old_pc(&mut self) -> u32 { self.oldpc }
1907    pub fn set_old_pc(&mut self, pc: u32) { self.oldpc = pc; }
1908    pub fn set_oldpc(&mut self, pc: u32) { self.oldpc = pc; }
1909    pub fn _hook_call_noargs(&mut self) {}
1910    pub fn hook(&self) -> Option<&Box<dyn FnMut(&mut LuaState, &crate::debug::LuaDebug)>> {
1911        self.hook.as_ref()
1912    }
1913    pub fn has_hook(&mut self) -> bool { self.hook.is_some() }
1914    pub fn hook_count(&mut self) -> i32 { self.hookcount }
1915    pub fn set_hook_count(&mut self, n: i32) { self.hookcount = n; }
1916    pub fn hook_mask(&self) -> u8 { self.hookmask }
1917    pub fn set_hook_mask(&mut self, m: u8) { self.hookmask = m; }
1918    pub fn base_hook_count(&self) -> i32 { self.basehookcount }
1919    pub fn set_base_hook_count(&mut self, n: i32) { self.basehookcount = n; }
1920    pub fn set_hook(&mut self, h: Option<Box<dyn FnMut(&mut LuaState, &crate::debug::LuaDebug)>>) {
1921        self.hook = h;
1922    }
1923    pub fn call_hook_event(&mut self, event: i32, line: i32) -> Result<(), LuaError> {
1924        crate::do_::hook(self, event, line, 0, 0)
1925    }
1926
1927    pub fn registry_value(&self) -> LuaValue { self.global().l_registry.clone() }
1928    pub fn registry_get(&self, key: usize) -> LuaValue {
1929        let reg = self.global().l_registry.clone();
1930        match reg {
1931            LuaValue::Table(t) => t.get(&LuaValue::Int(key as i64)),
1932            _ => LuaValue::Nil,
1933        }
1934    }
1935
1936    pub fn new_string(&mut self, bytes: &[u8]) -> Result<GcRef<LuaString>, LuaError> { self.intern_or_create_str(bytes) }
1937
1938    // ── Phase D-1a: state-owned allocation API ──────────────────────────────
1939    // These methods are the canonical allocation surface. They wrap
1940    // `GcRef::new` today; at D-1e they route through `state.global.heap.allocate`.
1941    // Callers must reach them through `&mut LuaState`, which mirrors C-Lua's
1942    // requirement that every allocation passes `lua_State *L`.
1943
1944    /// Allocate a new Lua function prototype.
1945    ///
1946    /// Caller mutates the returned proto in place (it's behind GcRef, which is
1947    /// Rc during Phase D-1; mutable access via `Rc::get_mut` only works while
1948    /// no other GcRefs alias it — true at construction).
1949    pub fn new_proto(&mut self) -> GcRef<LuaProto> {
1950        GcRef::new(LuaProto::placeholder())
1951    }
1952
1953    /// Allocate a Lua-side closure (compiled function + upvalue slots).
1954    pub fn new_lclosure(&mut self, proto: GcRef<LuaProto>, nupvals: usize) -> GcRef<LuaClosureLua> {
1955        let mut upvals = Vec::with_capacity(nupvals);
1956        for _ in 0..nupvals {
1957            upvals.push(std::cell::Cell::new(self.new_upval_closed(LuaValue::Nil)));
1958        }
1959        GcRef::new(LuaClosureLua { proto, upvals })
1960    }
1961
1962    /// Allocate a closed upvalue holding the given value.
1963    pub fn new_upval_closed(&mut self, v: LuaValue) -> GcRef<UpVal> {
1964        GcRef::new(UpVal::closed(v))
1965    }
1966
1967    /// Allocate an open upvalue referring to a thread's stack slot.
1968    pub fn new_upval_open(&mut self, thread_id: usize, level: StackIdx) -> GcRef<UpVal> {
1969        GcRef::new(UpVal::open(thread_id, level))
1970    }
1971    /// Mirrors `luaS_newlstr`: short strings are interned globally so equal
1972    /// content shares a single TString; long strings (> LUAI_MAXSHORTLEN = 40)
1973    /// always create a fresh TString without interning. This is what lets
1974    /// `string.format("%p", "long" .. "concat")` differ from a same-content
1975    /// literal — concat must produce a new object even when the literal already
1976    /// lives in the lexer's constant pool.
1977    pub fn intern_or_create_str(&mut self, bytes: &[u8]) -> Result<GcRef<LuaString>, LuaError> {
1978        self.intern_str(bytes)
1979    }
1980    pub fn new_userdata(&mut self, _size: usize, _nuvalue: usize) -> Result<GcRef<LuaUserData>, LuaError> {
1981        Err(LuaError::runtime(format_args!("new_userdata not implemented in this Phase-B build; use new_userdata_typed instead")))
1982    }
1983    pub fn new_c_closure(&mut self, _f: LuaCFunction, _n: i32) -> Result<LuaClosure, LuaError> {
1984        Err(LuaError::runtime(format_args!("new_c_closure not implemented in this Phase-B build; use push_cclosure in lua_vm::api instead")))
1985    }
1986    pub fn push_closure(
1987        &mut self,
1988        proto_idx: usize,
1989        ci: CallInfoIdx,
1990        base: StackIdx,
1991        ra: StackIdx,
1992    ) -> Result<(), LuaError> {
1993        let parent_cl = self.ci_lua_closure(ci).expect(
1994            "push_closure: current frame is not a Lua closure",
1995        );
1996        let child_proto = parent_cl.proto.p[proto_idx].clone();
1997        let nup = child_proto.upvalues.len();
1998        let mut upvals: Vec<std::cell::Cell<GcRef<UpVal>>> = Vec::with_capacity(nup);
1999        for i in 0..nup {
2000            let desc = &child_proto.upvalues[i];
2001            let uv = if desc.instack {
2002                let level = base + desc.idx as i32;
2003                crate::func::find_upval(self, level)
2004            } else {
2005                parent_cl.upval(desc.idx as usize)
2006            };
2007            upvals.push(std::cell::Cell::new(uv));
2008        }
2009        // TODO(D-1c-bridge): upvals are pre-populated from parent frame; state.new_lclosure
2010        // fills with fresh Nil upvals which would drop the captured bindings.
2011        let new_cl = GcRef::new(LuaClosureLua {
2012            proto: child_proto,
2013            upvals,
2014        });
2015        self.set_at(ra, LuaValue::Function(LuaClosure::Lua(new_cl)));
2016        Ok(())
2017    }
2018    pub fn new_tbc_upval(&mut self, idx: StackIdx) -> Result<(), LuaError> {
2019        crate::func::new_tbc_upval(self, idx)
2020    }
2021
2022    /// Read an open or closed upvalue.
2023    ///
2024    /// Closed upvalues own their value and read trivially. Open upvalues
2025    /// point at a stack slot on the home thread that captured them.
2026    ///
2027    /// Resolution order for an open upvalue whose home is not the current
2028    /// thread:
2029    ///
2030    /// 1. If the home thread is registered in `GlobalState::threads` and
2031    ///    its `RefCell` is currently borrowable, read straight from its
2032    ///    stack. This is the path used when the main thread reads a
2033    ///    closure created inside a now-suspended coroutine, or when one
2034    ///    coroutine reads an upvalue homed on a sibling suspended
2035    ///    coroutine.
2036    /// 2. Otherwise fall back to `GlobalState::cross_thread_upvals`. This
2037    ///    is the path used while inside a `coroutine.resume`: the parent
2038    ///    thread's `LuaState` is held by an outer `&mut` and is not
2039    ///    reachable through any `Rc<RefCell<_>>`, so `aux_resume`
2040    ///    snapshots the parent's open upvalues into the mirror across the
2041    ///    resume boundary.
2042    #[inline(always)]
2043    pub fn upvalue_get(&self, cl: &GcRef<LuaClosureLua>, n: usize) -> LuaValue {
2044        let uv = cl.upval(n);
2045        let (thread_id, idx) = match uv.try_open_payload() {
2046            Some(p) => p,
2047            None => return *uv.closed_value(),
2048        };
2049        let current = self.cached_thread_id;
2050        let tid = thread_id as u64;
2051        if tid == current {
2052            return self.stack[idx.0 as usize].val;
2053        }
2054        self.upvalue_get_cross_thread(tid, idx)
2055    }
2056
2057    #[cold]
2058    #[inline(never)]
2059    fn upvalue_get_cross_thread(&self, tid: u64, idx: StackIdx) -> LuaValue {
2060        let entry_rc = {
2061            let g = self.global();
2062            g.threads.get(&tid).map(|e| e.state.clone())
2063        };
2064        if let Some(rc) = entry_rc {
2065            if let Ok(home_state) = rc.try_borrow() {
2066                return home_state.get_at(idx);
2067            }
2068        }
2069        let g = self.global();
2070        match g.cross_thread_upvals.get(&(tid, idx)) {
2071            Some(v) => *v,
2072            None => LuaValue::Nil,
2073        }
2074    }
2075    /// Write an open or closed upvalue.
2076    ///
2077    /// Mirrors [`upvalue_get`]: open upvalues homed on the current thread
2078    /// write through `self.stack`. For cross-thread open upvalues, the
2079    /// home thread's stack is written directly when its `RefCell` is
2080    /// borrowable, otherwise the write lands in
2081    /// `GlobalState::cross_thread_upvals` (the active-resume case where
2082    /// the home thread is borrow-locked further up the call stack).
2083    #[inline(always)]
2084    pub fn upvalue_set(&mut self, cl: &GcRef<LuaClosureLua>, n: usize, val: LuaValue) -> Result<(), LuaError> {
2085        let uv = cl.upval(n);
2086        match uv.try_open_payload() {
2087            Some((thread_id, idx)) => {
2088                let tid = thread_id as u64;
2089                let current = self.cached_thread_id;
2090                if tid == current {
2091                    self.stack[idx.0 as usize].val = val;
2092                    return Ok(());
2093                }
2094                return self.upvalue_set_cross_thread(tid, idx, val);
2095            }
2096            None => {
2097                uv.set_closed_value(val);
2098            }
2099        }
2100        Ok(())
2101    }
2102
2103    #[cold]
2104    #[inline(never)]
2105    fn upvalue_set_cross_thread(
2106        &mut self,
2107        tid: u64,
2108        idx: StackIdx,
2109        val: LuaValue,
2110    ) -> Result<(), LuaError> {
2111        let entry_rc = {
2112            let g = self.global();
2113            g.threads.get(&tid).map(|e| e.state.clone())
2114        };
2115        if let Some(rc) = entry_rc {
2116            if let Ok(mut home_state) = rc.try_borrow_mut() {
2117                home_state.set_at(idx, val);
2118                return Ok(());
2119            }
2120        }
2121        let mut g = self.global_mut();
2122        g.cross_thread_upvals.insert((tid, idx), val);
2123        Ok(())
2124    }
2125
2126    pub fn protected_call_raw(&mut self, func: StackIdx, nresults: i32, errfunc: StackIdx) -> Result<(), LuaError> {
2127        let ef = errfunc.0 as isize;
2128        let status = crate::do_::pcall(
2129            self,
2130            |s| s.call_no_yield(func, nresults),
2131            func,
2132            ef,
2133        );
2134        match status {
2135            LuaStatus::Ok => Ok(()),
2136            LuaStatus::ErrSyntax => {
2137                let err_val = self.get_at(func);
2138                self.set_top(func);
2139                Err(LuaError::Syntax(err_val))
2140            }
2141            LuaStatus::Yield => {
2142                self.set_top(func);
2143                Err(LuaError::Yield)
2144            }
2145            _ => {
2146                let err_val = self.get_at(func);
2147                self.set_top(func);
2148                Err(LuaError::Runtime(err_val))
2149            }
2150        }
2151    }
2152    pub fn protected_parser(&mut self, z: crate::zio::ZIO, name: &[u8], mode: Option<&[u8]>) -> LuaStatus {
2153        crate::do_::protected_parser(self, z, name, mode)
2154    }
2155    pub fn do_call(&mut self, func: StackIdx, nresults: i32) -> Result<(), LuaError> {
2156        crate::do_::call(self, func, nresults)
2157    }
2158    pub fn do_call_no_yield(&mut self, func: StackIdx, nresults: i32) -> Result<(), LuaError> {
2159        crate::do_::callnoyield(self, func, nresults)
2160    }
2161    pub fn call_no_yield(&mut self, func: StackIdx, nresults: i32) -> Result<(), LuaError> {
2162        crate::do_::callnoyield(self, func, nresults)
2163    }
2164    pub fn call_at(&mut self, func: StackIdx, nresults: i32) -> Result<(), LuaError> {
2165        crate::do_::call(self, func, nresults)
2166    }
2167    #[inline(always)]
2168    pub fn precall(&mut self, func: StackIdx, nresults: i32) -> Result<Option<CallInfoIdx>, LuaError> {
2169        crate::do_::precall(self, func, nresults)
2170    }
2171    #[inline(always)]
2172    pub fn pretailcall(
2173        &mut self,
2174        ci: CallInfoIdx,
2175        func: StackIdx,
2176        narg1: i32,
2177        delta: i32,
2178    ) -> Result<i32, LuaError> {
2179        crate::do_::pretailcall(self, ci, func, narg1, delta)
2180    }
2181    #[inline(always)]
2182    pub fn poscall<N: TryInto<i32>>(&mut self, ci: CallInfoIdx, nres: N) -> Result<(), LuaError>
2183    where
2184        <N as TryInto<i32>>::Error: std::fmt::Debug,
2185    {
2186        let n = nres.try_into().expect("poscall: nres out of i32 range");
2187        crate::do_::poscall(self, ci, n)
2188    }
2189    pub fn adjust_results(&mut self, nresults: i32) {
2190        const LUA_MULTRET: i32 = -1;
2191        if nresults <= LUA_MULTRET {
2192            let ci_idx = self.ci.as_usize();
2193            if self.call_info[ci_idx].top.0 < self.top.0 {
2194                self.call_info[ci_idx].top = self.top;
2195            }
2196        }
2197    }
2198    pub fn adjust_varargs(
2199        &mut self,
2200        ci: CallInfoIdx,
2201        nfixparams: i32,
2202        cl: &GcRef<lua_types::closure::LuaLClosure>,
2203    ) -> Result<(), LuaError> {
2204        crate::tagmethods::adjust_varargs(self, nfixparams, ci, &cl.0.proto)
2205    }
2206    pub fn get_varargs(
2207        &mut self,
2208        ci: CallInfoIdx,
2209        ra: StackIdx,
2210        n: i32,
2211    ) -> Result<i32, LuaError> {
2212        crate::tagmethods::get_varargs(self, ci, ra, n)?;
2213        Ok(0)
2214    }
2215
2216    pub fn close_upvals(&mut self, level: StackIdx) -> Result<(), LuaError> {
2217        crate::func::close_upval(self, level);
2218        Ok(())
2219    }
2220    pub fn close_upvals_status(&mut self, level: StackIdx, _status: i32) -> Result<(), LuaError> {
2221        crate::func::close_upval(self, level);
2222        Ok(())
2223    }
2224    pub fn close_upvals_from_base(&mut self, ci: CallInfoIdx) -> Result<(), LuaError> {
2225        let base = self.ci_base(ci);
2226        crate::func::close_upval(self, base);
2227        Ok(())
2228    }
2229
2230    pub fn arith_op(&mut self, op: i32, p1: &LuaValue, p2: &LuaValue) -> Result<LuaValue, LuaError> {
2231        let arith_op = match op {
2232            0  => lua_types::arith::ArithOp::Add,
2233            1  => lua_types::arith::ArithOp::Sub,
2234            2  => lua_types::arith::ArithOp::Mul,
2235            3  => lua_types::arith::ArithOp::Mod,
2236            4  => lua_types::arith::ArithOp::Pow,
2237            5  => lua_types::arith::ArithOp::Div,
2238            6  => lua_types::arith::ArithOp::Idiv,
2239            7  => lua_types::arith::ArithOp::Band,
2240            8  => lua_types::arith::ArithOp::Bor,
2241            9  => lua_types::arith::ArithOp::Bxor,
2242            10 => lua_types::arith::ArithOp::Shl,
2243            11 => lua_types::arith::ArithOp::Shr,
2244            12 => lua_types::arith::ArithOp::Unm,
2245            13 => lua_types::arith::ArithOp::Bnot,
2246            _  => return Err(LuaError::runtime(format_args!("invalid arith op {}", op))),
2247        };
2248        let mut res = LuaValue::Nil;
2249        if crate::object::raw_arith(self, arith_op, p1, p2, &mut res)? {
2250            Ok(res)
2251        } else {
2252            Err(LuaError::arith_error(p1, p2, "perform arithmetic on"))
2253        }
2254    }
2255    pub fn concat(&mut self, n: i32) -> Result<(), LuaError> {
2256        crate::vm::concat(self, n)
2257    }
2258    pub fn less_than(&mut self, l: &LuaValue, r: &LuaValue) -> Result<bool, LuaError> {
2259        crate::vm::less_than(self, l, r)
2260    }
2261    pub fn less_equal(&mut self, l: &LuaValue, r: &LuaValue) -> Result<bool, LuaError> {
2262        crate::vm::less_equal(self, l, r)
2263    }
2264    pub fn equal_obj(&self, _ctx: Option<&LuaValue>, l: &LuaValue, r: &LuaValue) -> bool {
2265        crate::vm::equal_obj(None, l, r).unwrap_or(false)
2266    }
2267    pub fn equal_obj_with_tm(&mut self, l: &LuaValue, r: &LuaValue) -> Result<bool, LuaError> {
2268        crate::vm::equal_obj(Some(self), l, r)
2269    }
2270    pub fn obj_len(&mut self, v: &LuaValue) -> Result<LuaValue, LuaError> {
2271        match v {
2272            LuaValue::Table(_) => {
2273                let mt = self.table_metatable(v);
2274                let tm = self.fast_tm_table(mt.as_ref(), TagMethod::Len);
2275                if matches!(tm, LuaValue::Nil) {
2276                    let n = self.table_length(v)?;
2277                    return Ok(LuaValue::Int(n));
2278                }
2279                self.push(LuaValue::Nil);
2280                let slot = StackIdx(self.top.0 - 1);
2281                crate::tagmethods::call_tm_res(self, tm, v.clone(), v.clone(), slot)?;
2282                Ok(self.pop())
2283            }
2284            LuaValue::Str(s) => Ok(LuaValue::Int(s.len() as i64)),
2285            other => {
2286                let tm = crate::tagmethods::get_tm_by_obj(self, other, crate::tagmethods::TagMethod::Len);
2287                if matches!(tm, LuaValue::Nil) {
2288                    return Err(LuaError::type_error(other, "get length of"));
2289                }
2290                self.push(LuaValue::Nil);
2291                let slot = StackIdx(self.top.0 - 1);
2292                crate::tagmethods::call_tm_res(self, tm, v.clone(), v.clone(), slot)?;
2293                Ok(self.pop())
2294            }
2295        }
2296    }
2297    pub fn obj_to_string(&mut self, idx: i32) -> Result<GcRef<LuaString>, LuaError> {
2298        let slot: StackIdx = if idx > 0 {
2299            let ci_func = self.current_call_info().func;
2300            ci_func + idx
2301        } else {
2302            debug_assert!(idx != 0, "invalid index");
2303            StackIdx((self.top_idx().0 as i32 + idx) as u32)
2304        };
2305        let val = self.get_at(slot);
2306        match val {
2307            LuaValue::Str(s) => Ok(s),
2308            LuaValue::Int(_) | LuaValue::Float(_) => {
2309                let s = crate::object::num_to_string(self, &val)?;
2310                self.set_at(slot, LuaValue::Str(s.clone()));
2311                Ok(s)
2312            }
2313            _ => Err(LuaError::type_error(&val, "convert to string")),
2314        }
2315    }
2316    pub fn coerce_to_string(&mut self, idx: StackIdx) -> Result<GcRef<LuaString>, LuaError> {
2317        let val = self.get_at(idx);
2318        match val {
2319            LuaValue::Str(s) => Ok(s),
2320            LuaValue::Int(_) | LuaValue::Float(_) => {
2321                let s = crate::object::num_to_string(self, &val)?;
2322                self.set_at(idx, LuaValue::Str(s.clone()));
2323                Ok(s)
2324            }
2325            _ => Err(LuaError::type_error(&val, "convert to string")),
2326        }
2327    }
2328    pub fn str_to_num(&mut self, s: &[u8]) -> Option<(LuaValue, usize)> {
2329        let mut out = LuaValue::Nil;
2330        let sz = crate::object::str2num(s, &mut out);
2331        if sz == 0 { None } else { Some((out, sz)) }
2332    }
2333
2334    pub fn fast_get(&mut self, t: &LuaValue, k: &LuaValue) -> Result<Option<LuaValue>, LuaError> {
2335        let LuaValue::Table(tbl) = t else { return Ok(None); };
2336        let v = tbl.get(k);
2337        if matches!(v, LuaValue::Nil) { Ok(None) } else { Ok(Some(v)) }
2338    }
2339    pub fn fast_get_int(&mut self, t: &LuaValue, k: i64) -> Result<Option<LuaValue>, LuaError> {
2340        let LuaValue::Table(tbl) = t else { return Ok(None); };
2341        let v = tbl.get_int(k);
2342        if matches!(v, LuaValue::Nil) { Ok(None) } else { Ok(Some(v)) }
2343    }
2344    pub fn fast_get_short_str(&mut self, t: &LuaValue, k: &LuaValue) -> Result<Option<LuaValue>, LuaError> {
2345        let LuaValue::Table(tbl) = t else { return Ok(None); };
2346        let LuaValue::Str(s) = k else { return Ok(None); };
2347        let v = tbl.get_short_str(s);
2348        if matches!(v, LuaValue::Nil) { Ok(None) } else { Ok(Some(v)) }
2349    }
2350    pub fn fast_tm_table(&mut self, t: Option<&GcRef<LuaTable>>, tm: TagMethod) -> LuaValue {
2351        let Some(mt) = t else { return LuaValue::Nil; };
2352        debug_assert!((tm as u8) <= TagMethod::Eq as u8);
2353        let ename = self.global().tmname[tm as usize].clone();
2354        mt.get_short_str(&ename)
2355    }
2356    pub fn fast_tm_ud(&mut self, u: &GcRef<LuaUserData>, tm: TagMethod) -> LuaValue {
2357        // metatable then index by the interned `__xxx` name.
2358        let mt = u.metatable();
2359        self.fast_tm_table(mt.as_ref(), tm)
2360    }
2361
2362    pub fn table_get_with_tm(&mut self, t: &LuaValue, k: &LuaValue) -> Result<LuaValue, LuaError> {
2363        // Fast path: when the table has no metatable, `__index` can never
2364        // fire — so we can return the raw slot value (Nil if absent) without
2365        // routing through finish_get's push/pop scaffolding. Halves the
2366        // get-hot-path cost on tables without metamethods, which is the
2367        // common case in table.remove/insert shift loops and most user code.
2368        if let LuaValue::Table(tbl) = t {
2369            if tbl.metatable().is_none() {
2370                return Ok(tbl.get(k));
2371            }
2372        }
2373        if let Some(v) = self.fast_get(t, k)? {
2374            return Ok(v);
2375        }
2376        let res = self.top_idx();
2377        self.push(LuaValue::Nil);
2378        crate::vm::finish_get(self, t.clone(), k.clone(), res, true, None)?;
2379        let value = self.get_at(res);
2380        self.pop();
2381        Ok(value)
2382    }
2383    /// Set `t[k] = v` with `__newindex` metamethod awareness.
2384    ///
2385    /// Fast path: when the table has no metatable, `__newindex` can never
2386    /// fire, so the existence check via `fast_get` is pure waste —
2387    /// `try_raw_set` handles both "key exists" and "key absent" cases via
2388    /// a single lookup internally. Removing the `fast_get` halves the
2389    /// lookups per set on the metamethod-free path (table.remove/insert
2390    /// hot loops, most user code).
2391    ///
2392    /// The GC backward barrier is invoked before the store (with `&v`)
2393    /// instead of after; the barrier only inspects the value's color, not
2394    /// its location, so the order is semantically equivalent to upstream
2395    /// C-Lua and lets us move `v` straight into `table_raw_set` without
2396    /// the extra `v.clone()` that the post-store ordering forced.
2397    #[inline]
2398    pub fn table_set_with_tm(&mut self, t: &LuaValue, k: LuaValue, v: LuaValue) -> Result<(), LuaError> {
2399        if let LuaValue::Table(tbl) = t {
2400            if tbl.metatable().is_none() {
2401                self.gc_barrier_back(t, &v);
2402                return self.table_raw_set(t, k, v);
2403            }
2404        }
2405        if self.fast_get(t, &k)?.is_some() {
2406            self.gc_barrier_back(t, &v);
2407            return self.table_raw_set(t, k, v);
2408        }
2409        crate::vm::finish_set(self, t.clone(), k, v, true, None, None)
2410    }
2411    #[inline]
2412    pub fn table_raw_set(&mut self, t: &LuaValue, k: LuaValue, v: LuaValue) -> Result<(), LuaError> {
2413        let LuaValue::Table(tbl) = t else {
2414            return Err(LuaError::type_error(t, "index"));
2415        };
2416        let tbl = tbl.clone();
2417        tbl.raw_set(self, k, v)
2418    }
2419    #[inline]
2420    pub fn table_array_set(&mut self, t: &LuaValue, idx: usize, v: LuaValue) -> Result<(), LuaError> {
2421        let LuaValue::Table(tbl) = t else {
2422            return Err(LuaError::type_error(t, "index"));
2423        };
2424        let tbl = tbl.clone();
2425        tbl.raw_set_int(self, idx as i64 + 1, v)
2426    }
2427    pub fn table_ensure_array(&mut self, t: &LuaValue, n: usize) -> Result<(), LuaError> {
2428        let LuaValue::Table(tbl) = t else {
2429            return Err(LuaError::type_error(t, "index"));
2430        };
2431        if n > tbl.array_len() {
2432            tbl.resize(self, n, 0)?;
2433        }
2434        Ok(())
2435    }
2436    pub fn table_length(&mut self, t: &LuaValue) -> Result<i64, LuaError> {
2437        let LuaValue::Table(tbl) = t else {
2438            return Err(LuaError::type_error(t, "get length of"));
2439        };
2440        Ok(tbl.getn() as i64)
2441    }
2442    pub fn table_metatable(&mut self, v: &LuaValue) -> Option<GcRef<LuaTable>> {
2443        match v {
2444            LuaValue::Table(t) => t.metatable(),
2445            LuaValue::UserData(u) => u.metatable(),
2446            other => {
2447                let idx = other.base_type() as usize;
2448                self.global().mt[idx].clone()
2449            }
2450        }
2451    }
2452    pub fn table_resize(&mut self, t: &GcRef<LuaTable>, na: usize, nh: usize) -> Result<(), LuaError> {
2453        t.resize(self, na, nh)
2454    }
2455    pub fn table_getn(&self, t: &GcRef<LuaTable>) -> i64 {
2456        // PORT NOTE: C's `luaH_getn` returns a boundary i such that t[i] is
2457        // present and t[i+1] is absent (or 0 if t[1] is absent), exploiting the
2458        // hybrid array+hash layout. Phase B's LuaTable (lua-types/src/value.rs)
2459        // is a flat Vec<(K,V)> with no array part, so we linearly probe integer
2460        // keys starting at 1. The rich array+hash impl in
2461        // crates/lua-vm/src/table.rs lights up in Phase D.
2462        // PERF(port): O(n) linear scan with O(n) lookups → O(n²); Phase D fixes.
2463        let mut i: i64 = 1;
2464        loop {
2465            let v = t.get_int(i);
2466            if matches!(v, LuaValue::Nil) {
2467                return i - 1;
2468            }
2469            i += 1;
2470        }
2471    }
2472
2473    pub fn try_bin_tm(&mut self, p1: &LuaValue, p1_idx: Option<StackIdx>, p2: &LuaValue, p2_idx: Option<StackIdx>, res: StackIdx, tm: lua_types::tagmethod::TagMethod) -> Result<(), LuaError> {
2474        let event = crate::tagmethods::TagMethod::from_u8(tm as u8);
2475        crate::tagmethods::try_bin_tm(self, p1, p1_idx, p2, p2_idx, res, event)
2476    }
2477    pub fn try_bin_i_tm(&mut self, p1: &LuaValue, p1_idx: Option<StackIdx>, imm: i64, flip: bool, res: StackIdx, tm: lua_types::tagmethod::TagMethod) -> Result<(), LuaError> {
2478        let event = crate::tagmethods::TagMethod::from_u8(tm as u8);
2479        crate::tagmethods::try_bini_tm(self, p1, p1_idx, imm, flip, res, event)
2480    }
2481    pub fn try_bin_assoc_tm(&mut self, p1: &LuaValue, p1_idx: Option<StackIdx>, p2: &LuaValue, p2_idx: Option<StackIdx>, flip: bool, res: StackIdx, tm: lua_types::tagmethod::TagMethod) -> Result<(), LuaError> {
2482        let event = crate::tagmethods::TagMethod::from_u8(tm as u8);
2483        crate::tagmethods::try_bin_assoc_tm(self, p1, p1_idx, p2, p2_idx, flip, res, event)
2484    }
2485    pub fn try_concat_tm(&mut self, _p1: &LuaValue, _p2: &LuaValue) -> Result<(), LuaError> {
2486        crate::tagmethods::try_concat_tm(self)
2487    }
2488    pub fn call_tm(&mut self, f: LuaValue, p1: &LuaValue, p2: &LuaValue, p3: &LuaValue) -> Result<(), LuaError> {
2489        crate::tagmethods::call_tm(self, f, p1.clone(), p2.clone(), p3.clone())
2490    }
2491    pub fn call_tm_res(&mut self, f: LuaValue, p1: &LuaValue, p2: &LuaValue, res: StackIdx) -> Result<(), LuaError> {
2492        crate::tagmethods::call_tm_res(self, f, p1.clone(), p2.clone(), res)
2493    }
2494    pub fn call_tm_res_bool(&mut self, f: LuaValue, p1: &LuaValue, p2: &LuaValue) -> Result<bool, LuaError> {
2495        let res = self.top_idx();
2496        self.push(LuaValue::Nil);
2497        crate::tagmethods::call_tm_res(self, f, p1.clone(), p2.clone(), res)?;
2498        let result = self.get_at(res).clone();
2499        self.pop();
2500        Ok(!matches!(result, LuaValue::Nil | LuaValue::Bool(false)))
2501    }
2502    pub fn call_order_tm(&mut self, p1: &LuaValue, p2: &LuaValue, tm: lua_types::tagmethod::TagMethod) -> Result<bool, LuaError> {
2503        let event = crate::tagmethods::TagMethod::from_u8(tm as u8);
2504        crate::tagmethods::call_order_tm(self, p1, p2, event)
2505    }
2506    pub fn call_order_i_tm(&mut self, p1: &LuaValue, v2: i64, flip: bool, isfloat: bool, tm: lua_types::tagmethod::TagMethod) -> Result<bool, LuaError> {
2507        let event = crate::tagmethods::TagMethod::from_u8(tm as u8);
2508        crate::tagmethods::call_orderi_tm(self, p1, v2 as i32, flip, isfloat, event)
2509    }
2510
2511    #[inline(always)]
2512    pub fn proto_code(&self, cl: &GcRef<lua_types::closure::LuaLClosure>, pc: u32) -> lua_types::opcode::Instruction {
2513        cl.proto.code[pc as usize]
2514    }
2515    #[inline(always)]
2516    pub fn proto_const(&self, cl: &GcRef<lua_types::closure::LuaLClosure>, idx: usize) -> LuaValue {
2517        cl.proto.k[idx].clone()
2518    }
2519    /// Hot-path accessor: returns `Some(i)` only when the constant pool entry
2520    /// at `idx` is an `Int`. Avoids the full `LuaValue` clone that
2521    /// `proto_const` performs.
2522    ///
2523    /// arithmetic opcode macros (`op_arithK`).
2524    #[inline(always)]
2525    pub fn proto_const_int(&self, cl: &GcRef<lua_types::closure::LuaLClosure>, idx: usize) -> Option<i64> {
2526        match &cl.proto.k[idx] {
2527            LuaValue::Int(v) => Some(*v),
2528            _ => None,
2529        }
2530    }
2531    /// Hot-path accessor: returns `Some(f)` for `Float(f)` or `Int(i)` (coerced)
2532    /// constants. Avoids the full `LuaValue` clone. Used by the float fast
2533    /// path of `OP_ADDK`/`OP_SUBK`/`OP_MULK`/`OP_DIVK`/`OP_POWK`.
2534    #[inline(always)]
2535    pub fn proto_const_num(&self, cl: &GcRef<lua_types::closure::LuaLClosure>, idx: usize) -> Option<f64> {
2536        match &cl.proto.k[idx] {
2537            LuaValue::Float(f) => Some(*f),
2538            LuaValue::Int(v) => Some(*v as f64),
2539            _ => None,
2540        }
2541    }
2542    pub fn get_proto_instr(&self, ci: CallInfoIdx, pc: u32) -> lua_types::opcode::Instruction {
2543        let cl = self.ci_lua_closure(ci)
2544            .expect("get_proto_instr: CallInfo does not hold a Lua closure");
2545        cl.proto.code[pc as usize]
2546    }
2547    /// flag as `bool` (C returns `int` 0/1).
2548    ///
2549    /// The C function reads `L->ci` directly, so the `_idx` argument is unused;
2550    /// the VM passes its locally tracked `ci` for symmetry with `trace_exec`.
2551    pub fn trace_call(&mut self, _idx: CallInfoIdx) -> Result<bool, LuaError> {
2552        Ok(crate::debug::trace_call(self)? != 0)
2553    }
2554    /// returning `bool` for the trap flag. `_idx` is unused for the same reason
2555    /// as `trace_call`; `pc` is the 0-based index of the next instruction.
2556    pub fn trace_exec(&mut self, _idx: CallInfoIdx, pc: u32) -> Result<bool, LuaError> {
2557        Ok(crate::debug::trace_exec(self, pc)? != 0)
2558    }
2559    pub fn hook_call(&mut self, idx: CallInfoIdx) -> Result<(), LuaError> {
2560        crate::do_::hookcall(self, idx)
2561    }
2562    #[inline(always)]
2563    fn gc_step_flags(&self) -> Option<(bool, bool)> {
2564        let g = self.global();
2565        if !g.is_gc_running() {
2566            return None;
2567        }
2568        let should_collect = g.heap.would_collect();
2569        let has_finalizers = !g.to_be_finalized.is_empty();
2570        if should_collect || has_finalizers {
2571            Some((should_collect, has_finalizers))
2572        } else {
2573            None
2574        }
2575    }
2576
2577    #[inline(always)]
2578    pub fn gc_check_step(&mut self) {
2579        if !self.allowhook {
2580            return;
2581        }
2582        let Some((should_collect, has_finalizers)) = self.gc_step_flags() else {
2583            return;
2584        };
2585        if should_collect {
2586            self.gc().check_step();
2587        }
2588        if has_finalizers || !self.global().to_be_finalized.is_empty() {
2589            crate::api::run_pending_finalizers(self);
2590        }
2591    }
2592    #[inline(always)]
2593    pub fn gc_cond_step(&mut self) {
2594        if !self.allowhook {
2595            return;
2596        }
2597        let Some((should_collect, has_finalizers)) = self.gc_step_flags() else {
2598            return;
2599        };
2600        if should_collect {
2601            self.gc().check_step();
2602        }
2603        if has_finalizers || !self.global().to_be_finalized.is_empty() {
2604            crate::api::run_pending_finalizers(self);
2605        }
2606    }
2607    pub fn gc_barrier_back<T, U>(&mut self, _t: T, _v: U) { /* phase-b no-op */ }
2608    pub fn gc_barrier_upval<T, U, V>(&mut self, _cl: T, _uv: U, _v: V) { /* phase-b no-op */ }
2609    ///
2610    /// Phase E-1: compares `GlobalState::current_thread_id` against
2611    /// `main_thread_id`. Coroutine resume (slice 02b) is what will swap
2612    /// `current_thread_id` in and out; until then the running thread is
2613    /// always the main thread and this returns `true`.
2614    pub fn is_main_thread(&mut self) -> bool {
2615        let g = self.global();
2616        g.current_thread_id == g.main_thread_id
2617    }
2618    pub fn obj_type_name<'v>(&self, v: &'v LuaValue) -> std::borrow::Cow<'static, [u8]> {
2619        match v {
2620            LuaValue::LightUserData(_) => std::borrow::Cow::Borrowed(b"light userdata"),
2621            LuaValue::Table(t) => {
2622                if let Some(mt) = t.metatable() {
2623                    if let LuaValue::Str(s) = mt.get_str_bytes(b"__name") {
2624                        return std::borrow::Cow::Owned(s.as_bytes().to_vec());
2625                    }
2626                }
2627                std::borrow::Cow::Borrowed(crate::tagmethods::type_name(v.base_type()))
2628            }
2629            LuaValue::UserData(u) => {
2630                if let Some(mt) = u.metatable() {
2631                    if let LuaValue::Str(s) = mt.get_str_bytes(b"__name") {
2632                        return std::borrow::Cow::Owned(s.as_bytes().to_vec());
2633                    }
2634                }
2635                std::borrow::Cow::Borrowed(crate::tagmethods::type_name(v.base_type()))
2636            }
2637            _ => std::borrow::Cow::Borrowed(crate::tagmethods::type_name(v.base_type())),
2638        }
2639    }
2640
2641    pub fn full_type_name(&mut self, v: &LuaValue) -> Result<Vec<u8>, LuaError> {
2642        crate::tagmethods::obj_type_name(self, v)
2643    }
2644    pub fn emit_warning(&mut self, _msg: &[u8], _to_cont: bool) { warning(self, _msg, _to_cont) }
2645}
2646
2647// ─── GcHandle — no-op GC facade ───────────────────────────────────────────────
2648
2649/// A short-lived handle returned by `state.gc()` for GC operations.
2650///
2651/// In Phases A–C all methods are no-ops. Phase D replaces with real GC.
2652pub struct GcHandle<'a> {
2653    _state: &'a mut LuaState,
2654}
2655
2656/// Composite root passed to `Heap::full_collect`. The Phase-A workaround in
2657/// `new_state` leaves `GlobalState.mainthread = None` (to break the
2658/// self-referential Rc cycle pre-D), so the running thread's stack and
2659/// openupval list are not reachable from `GlobalState::trace`. Wrapping both
2660/// references in a single `Trace`-implementing root injects the active
2661/// thread as a second mark source for the duration of the collection.
2662struct CollectRoots<'a> {
2663    global: &'a GlobalState,
2664    thread: &'a LuaState,
2665}
2666
2667impl<'a> lua_gc::Trace for CollectRoots<'a> {
2668    fn trace(&self, m: &mut lua_gc::Marker) {
2669        self.global.trace(m);
2670        self.thread.trace(m);
2671    }
2672}
2673
2674fn trace_reachable_threads(
2675    global: &GlobalState,
2676    _current_thread_id: u64,
2677    marker: &mut lua_gc::Marker,
2678) {
2679    use lua_gc::Trace;
2680
2681    loop {
2682        let visited_before = marker.visited_count();
2683        for (id, entry) in global.threads.iter() {
2684            if thread_entry_marked_alive(marker, *id, entry) {
2685                if let Ok(thread) = entry.state.try_borrow() {
2686                    thread.trace(marker);
2687                }
2688            }
2689        }
2690        marker.drain_gray_queue();
2691        if marker.visited_count() == visited_before {
2692            break;
2693        }
2694    }
2695}
2696
2697fn thread_entry_marked_alive(
2698    marker: &lua_gc::Marker,
2699    id: u64,
2700    entry: &ThreadRegistryEntry,
2701) -> bool {
2702    marker.is_visited(entry.value.identity()) && entry.value.id == id
2703}
2704
2705fn close_open_upvalues_for_unreachable_threads(
2706    global: &GlobalState,
2707    marker: &mut lua_gc::Marker,
2708) {
2709    use lua_gc::Trace;
2710
2711    let mut closed_values = Vec::<LuaValue>::new();
2712    for (id, entry) in global.threads.iter() {
2713        if entry.value.id != *id {
2714            continue;
2715        }
2716        if thread_entry_marked_alive(marker, *id, entry) {
2717            continue;
2718        }
2719        let Ok(thread) = entry.state.try_borrow() else {
2720            continue;
2721        };
2722        for uv in thread.openupval.iter() {
2723            if !marker.is_visited(uv.identity()) {
2724                continue;
2725            }
2726            let Some((thread_id, idx)) = uv.try_open_payload() else {
2727                continue;
2728            };
2729            if thread_id as u64 != *id {
2730                continue;
2731            }
2732            let value = thread.get_at(idx);
2733            uv.close_with(value.clone());
2734            closed_values.push(value);
2735        }
2736    }
2737    for value in closed_values {
2738        value.trace(marker);
2739    }
2740    marker.drain_gray_queue();
2741}
2742
2743impl<'a> GcHandle<'a> {
2744    /// macros.tsv: `luaC_checkGC → state.gc().check_step()`
2745    ///
2746    /// Phase D-2: drives implicit collection when the heap's byte threshold
2747    /// is exceeded. Without this hook, loops that allocate without an
2748    /// explicit `collectgarbage()` call (e.g. `closure.lua`'s
2749    /// `while x[1] do local a = A..A end` GC-driven loop) never settle.
2750    pub fn check_step(&self) {
2751        if !self._state.global().is_gc_running() {
2752            return;
2753        }
2754        self.collect_via_heap(/* force = */ false);
2755    }
2756
2757    /// macros.tsv: `luaC_fullgc → state.gc().full_collect()`
2758    pub fn full_collect(&self) {
2759        self.collect_via_heap(/* force = */ true);
2760    }
2761
2762    /// Shared driver behind both `full_collect` (force-collect) and
2763    /// `check_step` (collect only if heap byte threshold exceeded).
2764    ///
2765    /// Snapshots the weak-tables registry, invokes the heap's collect path
2766    /// with a post-mark weak-prune hook, and rebuilds the registry by
2767    /// retaining only entries whose target was reachable. The same hook
2768    /// works for both modes — the heap short-circuits when force=false and
2769    /// the threshold isn't met.
2770    fn collect_via_heap(&self, force: bool) {
2771        use lua_gc::Trace;
2772        let state_ref: &LuaState = &*self._state;
2773
2774        // Fast path: when the caller did not force a collection, skip all
2775        // the snapshot work (3 Vec allocations + 3 HashSet allocations) if
2776        // the heap is paused or under threshold — a `step()` in that state
2777        // is a no-op, so the snapshot would be pure waste. Called millions
2778        // of times per recursive workload via `gc_check_step` in `precall`.
2779        if !force {
2780            let g = state_ref.global.borrow();
2781            if !g.heap.would_collect() {
2782                return;
2783            }
2784        }
2785
2786        // Snapshot weak tables BEFORE the collect. `identity()` reads only
2787        // the pointer address — safe even on still-dangling weak handles —
2788        // and dedup by identity keeps the iteration linear.
2789        let weak_tables_snapshot: Vec<lua_types::gc::GcRef<lua_types::value::LuaTable>> = {
2790            let g = state_ref.global.borrow();
2791            let mut seen = std::collections::HashSet::<usize>::new();
2792            g.weak_tables_registry
2793                .iter()
2794                .filter_map(|w| w.upgrade())
2795                .filter(|t| seen.insert(t.identity()))
2796                .collect()
2797        };
2798
2799        // Snapshot pending finalizers. `GlobalState::trace` deliberately
2800        // does NOT root these — that's how the post-mark hook below can
2801        // distinguish "still reachable from program state" from "only kept
2802        // alive by the finalizer registry."
2803        let pending_snapshot: Vec<lua_types::gc::GcRef<lua_types::value::LuaTable>> = {
2804            let g = state_ref.global.borrow();
2805            g.pending_finalizers.clone()
2806        };
2807
2808        // Snapshot tracked long-string identities + byte sizes BEFORE the
2809        // collect. The post-mark hook compares each identity against the
2810        // marker's visited set; anything not visited is unreachable and
2811        // its bytes get reclaimed from `gc_debt` after the heap collect
2812        // returns. Bare `usize` is safe to carry across the hook — long
2813        // strings use `new_uncollected` so the pointer never dangles.
2814        let long_string_snapshot: Vec<(usize, usize)> = {
2815            let g = state_ref.global.borrow();
2816            g.gc_tracked_long_strings
2817                .iter()
2818                .map(|(w, sz)| (w.0.identity(), *sz))
2819                .collect()
2820        };
2821
2822        let alive_ids: std::cell::RefCell<std::collections::HashSet<usize>> =
2823            std::cell::RefCell::new(std::collections::HashSet::new());
2824        let newly_unreachable: std::cell::RefCell<Vec<lua_types::gc::GcRef<lua_types::value::LuaTable>>> =
2825            std::cell::RefCell::new(Vec::new());
2826        let dead_long_strings: std::cell::RefCell<std::collections::HashSet<usize>> =
2827            std::cell::RefCell::new(std::collections::HashSet::new());
2828        let alive_thread_ids: std::cell::RefCell<std::collections::HashSet<u64>> =
2829            std::cell::RefCell::new(std::collections::HashSet::new());
2830        let collect_ran = std::cell::Cell::new(false);
2831
2832        {
2833            let global = state_ref.global.borrow();
2834            global.heap.unpause();
2835            let roots = CollectRoots { global: &*global, thread: state_ref };
2836            let hook = |marker: &mut lua_gc::Marker| {
2837                collect_ran.set(true);
2838                trace_reachable_threads(&*global, global.current_thread_id, marker);
2839                close_open_upvalues_for_unreachable_threads(&*global, marker);
2840                loop {
2841                    let visited_before = marker.visited_count();
2842                    for t in &weak_tables_snapshot {
2843                        let t_id = t.identity();
2844                        if !marker.is_visited(t_id) {
2845                            continue;
2846                        }
2847                        let to_mark = t.ephemeron_values_to_mark(
2848                            &|id| marker.is_visited(id),
2849                        );
2850                        for v in &to_mark {
2851                            v.trace(marker);
2852                        }
2853                    }
2854                    marker.drain_gray_queue();
2855                    if marker.visited_count() == visited_before {
2856                        break;
2857                    }
2858                }
2859                for pf in &pending_snapshot {
2860                    if !marker.is_visited(pf.identity()) {
2861                        marker.mark(pf.0);
2862                        newly_unreachable.borrow_mut().push(pf.clone());
2863                    }
2864                }
2865                marker.drain_gray_queue();
2866                loop {
2867                    let visited_before = marker.visited_count();
2868                    for t in &weak_tables_snapshot {
2869                        let t_id = t.identity();
2870                        if !marker.is_visited(t_id) {
2871                            continue;
2872                        }
2873                        let to_mark = t.ephemeron_values_to_mark(
2874                            &|id| marker.is_visited(id),
2875                        );
2876                        for v in &to_mark {
2877                            v.trace(marker);
2878                        }
2879                    }
2880                    marker.drain_gray_queue();
2881                    if marker.visited_count() == visited_before {
2882                        break;
2883                    }
2884                }
2885                for t in &weak_tables_snapshot {
2886                    let id = t.identity();
2887                    if marker.is_visited(id) {
2888                        let to_mark = t.prune_weak_dead(&|id| marker.is_visited(id));
2889                        for v in &to_mark {
2890                            v.trace(marker);
2891                        }
2892                        alive_ids.borrow_mut().insert(id);
2893                    }
2894                }
2895                marker.drain_gray_queue();
2896                // Long-string Phase-B reclaim. With `new_uncollected`
2897                // allocation, long strings never enter the heap's sweep
2898                // path, so we rely on the marker's visited set: any
2899                // tracked long-string identity that wasn't reached by mark
2900                // is unreferenced and its bytes can be returned to
2901                // `gc_debt`. Done here (inside the hook) so it sees the
2902                // visited set BEFORE drop of the marker.
2903                {
2904                    let mut dead = dead_long_strings.borrow_mut();
2905                    for (id, _sz) in &long_string_snapshot {
2906                        if !marker.is_visited(*id) {
2907                            dead.insert(*id);
2908                        }
2909                    }
2910                }
2911                {
2912                    let mut alive = alive_thread_ids.borrow_mut();
2913                    for (id, entry) in global.threads.iter() {
2914                        if thread_entry_marked_alive(marker, *id, entry) {
2915                            alive.insert(*id);
2916                        }
2917                    }
2918                }
2919            };
2920            if force {
2921                global.heap.full_collect_with_post_mark(&roots, hook);
2922            } else {
2923                global.heap.step_with_post_mark(&roots, hook);
2924            }
2925        }
2926
2927        if !collect_ran.get() {
2928            return;
2929        }
2930
2931        // After collect, drop weak-table-registry entries whose target was
2932        // swept. Without this filter the registry leaks one dangling
2933        // `GcWeak<LuaTable>` per dead weak table; the next collect would
2934        // upgrade those handles (current placeholder GcWeak always returns
2935        // Some) and the prune walk would deref freed memory.
2936        let alive_set = alive_ids.into_inner();
2937        let promote: Vec<lua_types::gc::GcRef<lua_types::value::LuaTable>> =
2938            newly_unreachable.into_inner();
2939        let promote_ids: std::collections::HashSet<usize> =
2940            promote.iter().map(|t| t.identity()).collect();
2941        let dead_ls_ids = dead_long_strings.into_inner();
2942        let alive_thread_ids = alive_thread_ids.into_inner();
2943        let mut g = state_ref.global.borrow_mut();
2944        g.weak_tables_registry
2945            .retain(|w| alive_set.contains(&w.0.identity()));
2946        let main_thread_id = g.main_thread_id;
2947        g.threads.retain(|id, _| alive_thread_ids.contains(id));
2948        g.cross_thread_upvals
2949            .retain(|(id, _), _| *id == main_thread_id || alive_thread_ids.contains(id));
2950        // Move newly-unreachable finalizables from `pending_finalizers` to
2951        // `to_be_finalized`. The latter is rooted by `GlobalState::trace`,
2952        // so these tables remain alive until their `__gc` runs.
2953        g.pending_finalizers
2954            .retain(|t| !promote_ids.contains(&t.identity()));
2955        g.to_be_finalized.extend(promote);
2956        // Reclaim long-string byte accounting for entries the marker said
2957        // were unreachable. The underlying `Gc<LuaString>` was allocated
2958        // via `new_uncollected` and stays live in process memory; only
2959        // `gc_debt` is adjusted so `collectgarbage("count")` reflects the
2960        // drop in user-visible live bytes.
2961        if !dead_ls_ids.is_empty() {
2962            let mut freed: isize = 0;
2963            g.gc_tracked_long_strings.retain(|(w, sz)| {
2964                if dead_ls_ids.contains(&w.0.identity()) {
2965                    freed += *sz as isize;
2966                    false
2967                } else {
2968                    true
2969                }
2970            });
2971            g.gc_debt -= freed;
2972        }
2973    }
2974
2975    /// Phase-B stub for `luaC_step(L)`.
2976    pub fn step(&self) { /* phase-b no-op */ }
2977
2978    /// Run one budgeted incremental step of the GC.
2979    ///
2980    /// `work_units` is the number of GC work units the step is allowed to
2981    /// perform (one gray trace, one sweep visit, or one phase transition).
2982    /// Returns `true` if the step completed a cycle and the collector is
2983    /// now in the `Pause` state; `false` otherwise.
2984    ///
2985    /// Mirrors `collect_via_heap` for the post-mark weak-table /
2986    /// finalizer-promotion logic, but only the atomic-phase transition will
2987    /// invoke the snapshot-walking hook — propagate and sweep steps reuse
2988    /// the snapshot but never execute it. The snapshot is rebuilt on every
2989    /// call; the cost is `O(weak_tables_registry)` per step.
2990    pub fn incremental_step(&self, work_units: isize) -> bool {
2991        use lua_gc::{StepBudget, StepOutcome, Trace};
2992        let state_ref: &LuaState = &*self._state;
2993
2994        let weak_tables_snapshot: Vec<lua_types::gc::GcRef<lua_types::value::LuaTable>> = {
2995            let g = state_ref.global.borrow();
2996            let mut seen = std::collections::HashSet::<usize>::new();
2997            g.weak_tables_registry
2998                .iter()
2999                .filter_map(|w| w.upgrade())
3000                .filter(|t| seen.insert(t.identity()))
3001                .collect()
3002        };
3003
3004        let pending_snapshot: Vec<lua_types::gc::GcRef<lua_types::value::LuaTable>> = {
3005            let g = state_ref.global.borrow();
3006            g.pending_finalizers.clone()
3007        };
3008
3009        let long_string_snapshot: Vec<(usize, usize)> = {
3010            let g = state_ref.global.borrow();
3011            g.gc_tracked_long_strings
3012                .iter()
3013                .map(|(w, sz)| (w.0.identity(), *sz))
3014                .collect()
3015        };
3016
3017        let alive_ids: std::cell::RefCell<std::collections::HashSet<usize>> =
3018            std::cell::RefCell::new(std::collections::HashSet::new());
3019        let newly_unreachable: std::cell::RefCell<Vec<lua_types::gc::GcRef<lua_types::value::LuaTable>>> =
3020            std::cell::RefCell::new(Vec::new());
3021        let dead_long_strings: std::cell::RefCell<std::collections::HashSet<usize>> =
3022            std::cell::RefCell::new(std::collections::HashSet::new());
3023        let alive_thread_ids: std::cell::RefCell<std::collections::HashSet<u64>> =
3024            std::cell::RefCell::new(std::collections::HashSet::new());
3025        let atomic_ran = std::cell::Cell::new(false);
3026
3027        let outcome = {
3028            let global = state_ref.global.borrow();
3029            global.heap.unpause();
3030            let roots = CollectRoots { global: &*global, thread: state_ref };
3031            let hook = |marker: &mut lua_gc::Marker| {
3032                atomic_ran.set(true);
3033                trace_reachable_threads(&*global, global.current_thread_id, marker);
3034                close_open_upvalues_for_unreachable_threads(&*global, marker);
3035                loop {
3036                    let visited_before = marker.visited_count();
3037                    for t in &weak_tables_snapshot {
3038                        let t_id = t.identity();
3039                        if !marker.is_visited(t_id) {
3040                            continue;
3041                        }
3042                        let to_mark = t.ephemeron_values_to_mark(
3043                            &|id| marker.is_visited(id),
3044                        );
3045                        for v in &to_mark {
3046                            v.trace(marker);
3047                        }
3048                    }
3049                    marker.drain_gray_queue();
3050                    if marker.visited_count() == visited_before {
3051                        break;
3052                    }
3053                }
3054                for pf in &pending_snapshot {
3055                    if !marker.is_visited(pf.identity()) {
3056                        marker.mark(pf.0);
3057                        newly_unreachable.borrow_mut().push(pf.clone());
3058                    }
3059                }
3060                marker.drain_gray_queue();
3061                loop {
3062                    let visited_before = marker.visited_count();
3063                    for t in &weak_tables_snapshot {
3064                        let t_id = t.identity();
3065                        if !marker.is_visited(t_id) {
3066                            continue;
3067                        }
3068                        let to_mark = t.ephemeron_values_to_mark(
3069                            &|id| marker.is_visited(id),
3070                        );
3071                        for v in &to_mark {
3072                            v.trace(marker);
3073                        }
3074                    }
3075                    marker.drain_gray_queue();
3076                    if marker.visited_count() == visited_before {
3077                        break;
3078                    }
3079                }
3080                for t in &weak_tables_snapshot {
3081                    let id = t.identity();
3082                    if marker.is_visited(id) {
3083                        let to_mark = t.prune_weak_dead(&|id| marker.is_visited(id));
3084                        for v in &to_mark {
3085                            v.trace(marker);
3086                        }
3087                        alive_ids.borrow_mut().insert(id);
3088                    }
3089                }
3090                marker.drain_gray_queue();
3091                {
3092                    let mut dead = dead_long_strings.borrow_mut();
3093                    for (id, _sz) in &long_string_snapshot {
3094                        if !marker.is_visited(*id) {
3095                            dead.insert(*id);
3096                        }
3097                    }
3098                }
3099                {
3100                    let mut alive = alive_thread_ids.borrow_mut();
3101                    for (id, entry) in global.threads.iter() {
3102                        if thread_entry_marked_alive(marker, *id, entry) {
3103                            alive.insert(*id);
3104                        }
3105                    }
3106                }
3107            };
3108            let budget = StepBudget::from_work(work_units);
3109            global.heap.incremental_step_with_post_mark(&roots, budget, hook)
3110        };
3111
3112        if atomic_ran.get() {
3113            let alive_set = alive_ids.into_inner();
3114            let promote: Vec<lua_types::gc::GcRef<lua_types::value::LuaTable>> =
3115                newly_unreachable.into_inner();
3116            let promote_ids: std::collections::HashSet<usize> =
3117                promote.iter().map(|t| t.identity()).collect();
3118            let dead_ls_ids = dead_long_strings.into_inner();
3119            let alive_thread_ids = alive_thread_ids.into_inner();
3120            let mut g = state_ref.global.borrow_mut();
3121            g.weak_tables_registry
3122                .retain(|w| alive_set.contains(&w.0.identity()));
3123            let main_thread_id = g.main_thread_id;
3124            g.threads.retain(|id, _| alive_thread_ids.contains(id));
3125            g.cross_thread_upvals
3126                .retain(|(id, _), _| *id == main_thread_id || alive_thread_ids.contains(id));
3127            g.pending_finalizers
3128                .retain(|t| !promote_ids.contains(&t.identity()));
3129            g.to_be_finalized.extend(promote);
3130            if !dead_ls_ids.is_empty() {
3131                let mut freed: isize = 0;
3132                g.gc_tracked_long_strings.retain(|(w, sz)| {
3133                    if dead_ls_ids.contains(&w.0.identity()) {
3134                        freed += *sz as isize;
3135                        false
3136                    } else {
3137                        true
3138                    }
3139                });
3140                g.gc_debt -= freed;
3141            }
3142        }
3143
3144        matches!(outcome, StepOutcome::Paused)
3145    }
3146
3147    /// Run only the weak-table atomic cleanup used by a generational step.
3148    ///
3149    /// C-Lua's `genstep` performs young/full generational work and includes
3150    /// weak-table clearing at the atomic boundary. This heap does not model
3151    /// ages yet; this mark-only pass gives explicit generational steps the
3152    /// weak cleanup they need without sweeping objects from suspended threads.
3153    pub fn prune_weak_tables_mark_only(&self) {
3154        use lua_gc::Trace;
3155        let state_ref: &LuaState = &*self._state;
3156
3157        let weak_tables_snapshot: Vec<lua_types::gc::GcRef<lua_types::value::LuaTable>> = {
3158            let g = state_ref.global.borrow();
3159            let mut seen = std::collections::HashSet::<usize>::new();
3160            g.weak_tables_registry
3161                .iter()
3162                .filter_map(|w| w.upgrade())
3163                .filter(|t| seen.insert(t.identity()))
3164                .collect()
3165        };
3166
3167        let global = state_ref.global.borrow();
3168        global.heap.unpause();
3169        let roots = CollectRoots { global: &*global, thread: state_ref };
3170        let hook = |marker: &mut lua_gc::Marker| {
3171            trace_reachable_threads(&*global, global.current_thread_id, marker);
3172            loop {
3173                let visited_before = marker.visited_count();
3174                for t in &weak_tables_snapshot {
3175                    let t_id = t.identity();
3176                    if !marker.is_visited(t_id) {
3177                        continue;
3178                    }
3179                    let to_mark = t.ephemeron_values_to_mark(
3180                        &|id| marker.is_visited(id),
3181                    );
3182                    for v in &to_mark {
3183                        v.trace(marker);
3184                    }
3185                }
3186                marker.drain_gray_queue();
3187                if marker.visited_count() == visited_before {
3188                    break;
3189                }
3190            }
3191            for t in &weak_tables_snapshot {
3192                if marker.is_visited(t.identity()) {
3193                    let to_mark = t.prune_weak_dead(&|id| marker.is_visited(id));
3194                    for v in &to_mark {
3195                        v.trace(marker);
3196                    }
3197                }
3198            }
3199        };
3200        global.heap.mark_only_with_post_mark(&roots, hook);
3201    }
3202
3203    /// Set the GC kind (incremental/generational).
3204    ///
3205    /// itself is `Rc`-based, so the only observable effect is the mode flag
3206    /// returned by `lua_gc(LUA_GCGEN)` / `lua_gc(LUA_GCINC)` on the next call.
3207    pub fn change_mode(&self, mode: GcKind) {
3208        self._state.global_mut().gckind = mode as u8;
3209    }
3210
3211    /// Phase-B stub for `luaC_fix(L, o)` — pin an object so GC won't collect it.
3212    pub fn fix_object<T: lua_gc::Trace + 'static>(&self, _o: &GcRef<T>) { /* phase-b no-op */ }
3213
3214    /// Free all collectable objects (called during state teardown).
3215    ///
3216    /// PORT NOTE: In Phases A–C, Rc drop chains handle deallocation automatically.
3217    pub fn free_all_objects(&self) {
3218        // PORT NOTE: Phase A–C no-op; Rc::drop handles deallocation
3219    }
3220
3221    /// GC write barrier for a TValue.
3222    ///
3223    /// macros.tsv: `luaC_barrier → state.gc().barrier(p, v)` — no-op in Phases A–C
3224    pub fn barrier(&self, _p: &dyn std::any::Any, _v: &LuaValue) {}
3225
3226    /// Backward write barrier.
3227    ///
3228    /// macros.tsv: `luaC_barrierback → state.gc().barrier_back(p, v)` — no-op
3229    pub fn barrier_back(&self, _p: &dyn std::any::Any, _v: &LuaValue) {}
3230
3231    /// Object write barrier.
3232    ///
3233    /// macros.tsv: `luaC_objbarrier → state.gc().obj_barrier(p, o)` — no-op
3234    pub fn obj_barrier(&self, _p: &dyn std::any::Any, _o: &dyn std::any::Any) {}
3235
3236    /// Backward object write barrier.
3237    ///
3238    pub fn obj_barrier_back(&self, _p: &dyn std::any::Any, _o: &dyn std::any::Any) {}
3239}
3240
3241// ─── Functions from lstate.c ──────────────────────────────────────────────────
3242
3243//
3244// PORT NOTE: `luai_makeseed` in C mixed ASLR entropy (pointer addresses of a
3245// heap var, stack var, and code symbol) with the current time via `luaS_hash`.
3246// In Rust, raw pointer addresses require `unsafe` which is forbidden outside
3247// lua-gc/lua-coro.  Phase A uses time-only entropy.  The hash is computed via
3248// `crate::string::hash_bytes` to match the Lua FNV-style algorithm.
3249fn make_seed() -> u32 {
3250    use std::time::{SystemTime, UNIX_EPOCH};
3251    let t = SystemTime::now()
3252        .duration_since(UNIX_EPOCH)
3253        .map(|d| d.as_secs() as u32)
3254        .unwrap_or(0);
3255
3256    // TODO(port): mix in ASLR entropy (pointer to heap / stack / code).
3257    // Requires a short `unsafe` block to cast references to usize.
3258    // The entropy improvement is important for hash DoS resistance (CVE-class).
3259    // Phase B should add this via a platform-specific helper in lua-gc or via
3260    // the `getrandom` crate if it is added as a dependency.
3261
3262    // For Phase A, just hash the time bytes against itself.
3263    crate::string::hash_bytes(&t.to_le_bytes(), t)
3264}
3265
3266/// Adjust `GCdebt` to `debt` while preserving the `totalbytes + GCdebt` invariant.
3267///
3268///
3269/// ```c
3270///
3271/// //   l_mem tb = gettotalbytes(g);
3272/// //   lua_assert(tb > 0);
3273/// //   if (debt < tb - MAX_LMEM)
3274/// //     debt = tb - MAX_LMEM;
3275/// //   g->totalbytes = tb - debt;
3276/// //   g->GCdebt = debt;
3277/// // }
3278/// ```
3279pub(crate) fn set_debt(g: &mut GlobalState, mut debt: isize) {
3280    let tb = g.total_bytes() as isize;
3281    debug_assert!(tb > 0);
3282    // macros.tsv: MAX_LMEM → isize::MAX
3283    if debt < tb.saturating_sub(isize::MAX) {
3284        debt = tb - isize::MAX;
3285    }
3286    g.totalbytes = tb - debt;
3287    g.gc_debt = debt;
3288}
3289
3290/// Sweep the Phase-B long-string tracker and decrement `gc_debt` by the
3291/// recorded byte count of any entry whose underlying `Rc` has been dropped.
3292///
3293/// PORT NOTE: Phase D will replace this with the real allocator's per-object
3294/// accounting through `luaM_realloc`. For now, long-string creation pushes a
3295/// `(Weak, size)` pair onto `gc_tracked_long_strings`, and this helper
3296/// reclaims the bytes lazily — at every `collectgarbage("count")` query and
3297/// at the end of `collectgarbage("collect")` — so the Lua-visible memory
3298/// total reflects live string bytes rather than peak allocation.
3299pub(crate) fn reclaim_dead_long_strings(g: &mut GlobalState) {
3300    let mut freed: isize = 0;
3301    g.gc_tracked_long_strings.retain(|(w, sz)| {
3302        if w.strong_count() == 0 {
3303            freed += *sz as isize;
3304            false
3305        } else {
3306            true
3307        }
3308    });
3309    g.gc_debt -= freed;
3310}
3311
3312/// Deprecated no-op that returns `LUAI_MAXCCALLS`.
3313///
3314///
3315/// ```c
3316///
3317/// //   UNUSED(L); UNUSED(limit);
3318/// //   return LUAI_MAXCCALLS;  /* warning?? */
3319/// // }
3320/// ```
3321pub fn set_c_stack_limit(_state: &mut LuaState, _limit: u32) -> i32 {
3322    let _ = (_state, _limit);
3323    LUAI_MAXCCALLS as i32
3324}
3325
3326/// Allocate a fresh `CallInfo` beyond the current frame and return its index.
3327///
3328///
3329/// ```c
3330///
3331/// //   CallInfo *ci;
3332/// //   lua_assert(L->ci->next == NULL);
3333/// //   ci = luaM_new(L, CallInfo);
3334/// //   L->ci->next = ci;
3335/// //   ci->previous = L->ci;
3336/// //   ci->next = NULL;
3337/// //   ci->u.l.trap = 0;
3338/// //   L->nci++;
3339/// //   return ci;
3340/// // }
3341/// ```
3342pub(crate) fn extend_ci(state: &mut LuaState) -> CallInfoIdx {
3343    debug_assert!(
3344        state.call_info[state.ci.0 as usize].next.is_none(),
3345        "extend_ci: current ci already has a cached next frame"
3346    );
3347
3348    let current_idx = state.ci;
3349    // macros.tsv: luaM_new → Box::new(T::default()) — here we push onto the Vec
3350    let new_idx = CallInfoIdx(state.call_info.len() as u32);
3351
3352    state.call_info.push(CallInfo {
3353        previous: Some(current_idx),
3354        next: None,
3355        u: CallInfoFrame::lua_default(),
3356        ..CallInfo::default()
3357    });
3358
3359    state.call_info[current_idx.0 as usize].next = Some(new_idx);
3360
3361    state.nci += 1;
3362
3363    new_idx
3364}
3365
3366/// Free all cached (unused) `CallInfo` frames beyond the current frame.
3367///
3368///
3369/// ```c
3370///
3371/// //   CallInfo *ci = L->ci;
3372/// //   CallInfo *next = ci->next;
3373/// //   ci->next = NULL;
3374/// //   while ((ci = next) != NULL) {
3375/// //     next = ci->next;
3376/// //     luaM_free(L, ci);
3377/// //     L->nci--;
3378/// //   }
3379/// // }
3380/// ```
3381///
3382/// PORT NOTE: In C, each `CallInfo` is an independent heap allocation freed by
3383/// `luaM_free`.  In Rust, all `CallInfo` entries live in `state.call_info: Vec<CallInfo>`.
3384/// We walk the link chain to count removals (updating `nci`), then truncate the Vec.
3385/// This is safe as long as all free entries have indices greater than `state.ci`.
3386fn free_ci(state: &mut LuaState) {
3387    let ci_idx = state.ci.0 as usize;
3388
3389    let mut next_opt = state.call_info[ci_idx].next.take();
3390
3391    while let Some(idx) = next_opt {
3392        next_opt = state.call_info[idx.0 as usize].next;
3393        state.nci = state.nci.saturating_sub(1);
3394    }
3395
3396    // Truncate: drop all entries beyond the current ci.
3397    // TODO(port): verify invariant that all cached frames have contiguous indices > state.ci
3398    state.call_info.truncate(ci_idx + 1);
3399}
3400
3401/// Free approximately half of the cached `CallInfo` frames beyond the current frame.
3402///
3403///
3404/// ```c
3405///
3406/// //   CallInfo *ci = L->ci->next;
3407/// //   CallInfo *next;
3408/// //   if (ci == NULL) return;
3409/// //   while ((next = ci->next) != NULL) {
3410/// //     CallInfo *next2 = next->next;
3411/// //     ci->next = next2;
3412/// //     L->nci--;
3413/// //     luaM_free(L, next);
3414/// //     if (next2 == NULL) break;
3415/// //     else { next2->previous = ci; ci = next2; }
3416/// //   }
3417/// // }
3418/// ```
3419///
3420/// PORT NOTE: The C code removes every other node from the free-list chain by
3421/// pointer manipulation.  In Rust, removing elements from the middle of a `Vec`
3422/// shifts subsequent elements and invalidates `CallInfoIdx` values that point
3423/// past the removal site.  For Phase A, we approximate by halving the free count
3424/// via truncation.  TODO(port): Phase B should implement a proper free-list
3425/// pool (e.g., a slab) that allows O(1) element removal without index
3426/// invalidation.
3427pub(crate) fn shrink_ci(state: &mut LuaState) {
3428    let ci_idx = state.ci.0 as usize;
3429
3430    if state.call_info[ci_idx].next.is_none() {
3431        return;
3432    }
3433
3434    let free_count = state.call_info.len().saturating_sub(ci_idx + 1);
3435    if free_count <= 1 {
3436        return;
3437    }
3438
3439    // Remove every other cached frame (halve the free list).
3440    // PERF(port): truncation is O(n) copy for the drop; a slab allocator
3441    // would be O(1) — profile in Phase B.
3442    let keep = free_count / 2;
3443    let removed = free_count - keep;
3444    let new_len = ci_idx + 1 + keep;
3445    state.call_info.truncate(new_len);
3446    state.nci = state.nci.saturating_sub(removed as u32);
3447
3448    // Terminate the now-last cached frame.
3449    if let Some(last) = state.call_info.last_mut() {
3450        last.next = None;
3451    }
3452}
3453
3454/// Check whether the C-call depth has reached its limit and raise an error if so.
3455///
3456///
3457/// ```c
3458///
3459/// //   if (getCcalls(L) == LUAI_MAXCCALLS)
3460/// //     luaG_runerror(L, "C stack overflow");
3461/// //   else if (getCcalls(L) >= (LUAI_MAXCCALLS / 10 * 11))
3462/// //     luaD_throw(L, LUA_ERRERR);
3463/// // }
3464/// ```
3465pub(crate) fn check_c_stack(state: &mut LuaState) -> Result<(), LuaError> {
3466    // macros.tsv: getCcalls → state.c_calls()
3467    // error_sites.tsv: luaG_runerror → return Err(LuaError::runtime(format_args!(...)))
3468    if state.c_calls() == LUAI_MAXCCALLS {
3469        return Err(LuaError::runtime(format_args!("C stack overflow")));
3470    }
3471    // error_sites.tsv: luaD_throw(L, LUA_ERRERR) → return Err(LuaError::with_status(LuaStatus::ErrErr))
3472    if state.c_calls() >= (LUAI_MAXCCALLS / 10 * 11) {
3473        // TODO(port): LuaError::with_status takes a LuaStatus enum, not a raw i32.
3474        // The exact constructor shape depends on lua-types/error.rs in Phase B.
3475        return Err(LuaError::runtime(format_args!(
3476            "error while handling stack overflow (C stack overflow)"
3477        )));
3478    }
3479    Ok(())
3480}
3481
3482/// Increment the C-call depth counter, checking for overflow.
3483///
3484///
3485/// ```c
3486///
3487/// //   L->nCcalls++;
3488/// //   if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS))
3489/// //     luaE_checkcstack(L);
3490/// // }
3491/// ```
3492pub fn inc_c_stack(state: &mut LuaState) -> Result<(), LuaError> {
3493    state.nCcalls += 1;
3494    // macros.tsv: l_unlikely → x (drop branch hint); getCcalls → state.c_calls()
3495    if state.c_calls() >= LUAI_MAXCCALLS {
3496        check_c_stack(state)?;
3497    }
3498    Ok(())
3499}
3500
3501//
3502// PORT NOTE: In C, `L` is a separate thread used only for memory allocation
3503// (via `luaM_newvector`).  In Rust we don't have a custom allocator; all
3504// allocation goes through the global Rust allocator.  The function takes only
3505// the new thread (`thread`) and ignores the caller.
3506fn stack_init(thread: &mut LuaState) {
3507    // macros.tsv: luaM_newvector → vec![T::default(); n]
3508    let total_slots = BASIC_STACK_SIZE + EXTRA_STACK;
3509    thread.stack = vec![StackValue::default(); total_slots];
3510
3511    // types.tsv: lua_State.tbclist → Vec<StackIdx>
3512    // PORT NOTE: In C, tbclist.p = stack.p is a sentinel meaning "no tbc vars".
3513    // In Rust the Vec is empty when there are no tbc variables.
3514    thread.tbclist = Vec::new();
3515
3516    //      setnilvalue(s2v(L1->stack.p + i));  /* erase new stack */
3517    // macros.tsv: setnilvalue → *o = LuaValue::Nil
3518    // Already initialized to LuaValue::Nil via StackValue::default().
3519
3520    thread.top = StackIdx(0);
3521
3522    thread.stack_last = StackIdx(BASIC_STACK_SIZE as u32);
3523
3524
3525    let base_ci = CallInfo {
3526        func: StackIdx(0),
3527        top: StackIdx(1 + LUA_MINSTACK as u32),
3528        previous: None,
3529        next: None,
3530        callstatus: CIST_C,
3531        nresults: 0,
3532        u: CallInfoFrame::c_default(),
3533        u2: CallInfoExtra::default(),
3534    };
3535
3536    if thread.call_info.is_empty() {
3537        thread.call_info.push(base_ci);
3538    } else {
3539        thread.call_info[0] = base_ci;
3540        thread.call_info.truncate(1);
3541    }
3542
3543    thread.stack[0] = StackValue { val: LuaValue::Nil, tbc_delta: 0 };
3544
3545    thread.top = StackIdx(1);
3546
3547    thread.ci = CallInfoIdx(0);
3548}
3549
3550fn free_stack(state: &mut LuaState) {
3551    if state.stack.is_empty() {
3552        return;
3553    }
3554    state.ci = CallInfoIdx(0);
3555    free_ci(state);
3556    debug_assert_eq!(state.nci, 0, "nci should be 0 after free_ci");
3557    // macros.tsv: luaM_freearray → (Rust's Drop handles deallocation; drop the call)
3558    state.stack.clear();
3559    state.stack.shrink_to_fit();
3560}
3561
3562fn init_registry(state: &mut LuaState) -> Result<(), LuaError> {
3563    // macros.tsv: luaH_new → state.new_table()
3564    let registry = state.new_table();
3565
3566    // macros.tsv: sethvalue → *o = LuaValue::Table(x.clone())
3567    state.global_mut().l_registry = LuaValue::Table(registry.clone());
3568
3569    // macros.tsv: luaH_resize → t.resize(state, na, nh)?
3570    // TODO(port): registry is a GcRef<LuaTable> (Rc); calling methods requires borrow_mut()
3571    // For Phase A, use RefCell interior mutability on LuaTable, or accept the limitation.
3572    // Using Rc::get_mut is not available because of possible aliasing.
3573    // TODO(port): LuaTable resize requires &mut access through Rc — needs RefCell<LuaTable>
3574    //   or a redesign in Phase B.
3575
3576    // macros.tsv: setthvalue → *o = LuaValue::Thread(x.clone())
3577    // TODO(port): cannot create GcRef<LuaState> to self (self-referential Rc).
3578    // In Phase E this would be resolved once coroutine threads are GcRef-tracked.
3579    // For Phase A: leave registry[LUA_RIDX_MAINTHREAD-1] as Nil and add a TODO.
3580    // TODO(port): set registry[LUA_RIDX_MAINTHREAD - 1] = LuaValue::Thread(main_thread_gcref)
3581
3582    // PORT NOTE (phase-b-reconcile): The lua-types LuaTable placeholder is
3583    // storage-less, so we can't actually persist the globals table inside
3584    // the registry via array_set. Store it in a direct GlobalState field
3585    // and patch get_global_table to read it from there. Symmetric for the
3586    // _LOADED module cache. Once the LuaTable placeholder reconciles, the
3587    // canonical registry storage takes over and these fields disappear.
3588    let globals = state.new_table();
3589    state.global_mut().globals = LuaValue::Table(globals);
3590    let loaded = state.new_table();
3591    state.global_mut().loaded = LuaValue::Table(loaded);
3592
3593    Ok(())
3594}
3595
3596fn lua_open(state: &mut LuaState) -> Result<(), LuaError> {
3597    stack_init(state);
3598    init_registry(state)?;
3599    crate::string::init(state)?;
3600    crate::tagmethods::init(state)?;
3601    // TODO(port): luaX_init lives in the lua-lex crate; cross-crate call needed in Phase B
3602    state.global_mut().gcstp = 0;
3603    state.global().heap.unpause();
3604    // macros.tsv: setnilvalue → *o = LuaValue::Nil
3605    // PORT NOTE: setting nilvalue = Nil signals completestate() → is_complete() = true
3606    state.global_mut().nilvalue = LuaValue::Nil;
3607    // macros.tsv: luai_userstateopen → (extension hook, no-op default; drop)
3608    Ok(())
3609}
3610
3611fn preinit_thread(thread: &mut LuaState, global: Rc<RefCell<GlobalState>>) {
3612    thread.global = global;
3613    thread.stack = Vec::new();
3614    thread.call_info = Vec::new();
3615    // PORT NOTE: We initialize ci to 0 but call_info is empty; stack_init() must be
3616    // called before any use of call_info.
3617    thread.ci = CallInfoIdx(0);
3618    thread.nci = 0;
3619    // PORT NOTE: In C, L->twups = L is a self-reference sentinel meaning "no open upvals".
3620    // In Rust, GlobalState.twups is a Vec<GcRef<LuaState>>; absence from that Vec is the
3621    // sentinel.  The per-thread `twups` field is removed (types.tsv: lua_State.twups → removed).
3622    thread.nCcalls = 0;
3623    thread.hook = None;
3624    thread.hookmask = 0;
3625    thread.basehookcount = 0;
3626    thread.allowhook = true;
3627    // macros.tsv: resethookcount → state.reset_hook_count()
3628    thread.hookcount = thread.basehookcount;
3629    thread.openupval = Vec::new();
3630    thread.status = LuaStatus::Ok as u8;
3631    thread.errfunc = 0;
3632    thread.oldpc = 0;
3633}
3634
3635fn close_state(state: &mut LuaState) {
3636    let is_complete = state.global().is_complete();
3637
3638    if !is_complete {
3639        // macros.tsv: luaC_freeallobjects via GcHandle
3640        state.gc().free_all_objects();
3641    } else {
3642        state.ci = CallInfoIdx(0);
3643        // TODO(port): crate::do_::close_protected(state, StackIdx(1), LuaStatus::Ok)
3644        // Ignoring result here because we are in teardown (same as C behavior).
3645        state.gc().free_all_objects();
3646        // macros.tsv: luai_userstateclose → (extension hook; drop)
3647    }
3648
3649    // macros.tsv: luaM_freearray → (Rust's Drop handles deallocation; drop the call)
3650    state.global_mut().strt = StringPool::default();
3651
3652    free_stack(state);
3653
3654    // PORT NOTE: C-specific memory accounting assertion; not applicable in Rust.
3655
3656    // PORT NOTE: Custom allocator freed LG here. Rust's allocator (via Drop) handles
3657    // deallocation of GlobalState and LuaState automatically.
3658}
3659
3660/// Create a new coroutine thread sharing the same GlobalState as the caller.
3661///
3662/// Pushes the new thread onto the caller's stack and returns `Ok(())`.
3663///
3664///
3665/// ```c
3666///
3667/// //   global_State *g = G(L);
3668/// //   GCObject *o;
3669/// //   lua_State *L1;
3670/// //   lua_lock(L); luaC_checkGC(L);
3671/// //   o = luaC_newobjdt(L, LUA_TTHREAD, sizeof(LX), offsetof(LX, l));
3672/// //   L1 = gco2th(o);
3673/// //   setthvalue2s(L, L->top.p, L1); api_incr_top(L);
3674/// //   preinit_thread(L1, g);
3675/// //   ... (copy hook settings, extra space, stack_init) ...
3676/// //   lua_unlock(L); return L1;
3677/// // }
3678/// ```
3679/// Allocate a fresh coroutine `LuaState`, register it under a new
3680/// `ThreadId`, and push the resulting `LuaValue::Thread(value)` onto
3681/// `state`'s stack.
3682///
3683/// If `initial_body` is `Some(f)`, `f` is also pushed onto the new
3684/// thread's stack so that `coroutine.status` reports `"suspended"`
3685/// rather than `"dead"`. The full cross-thread `xmove` from caller to
3686/// coroutine arrives in slice 02b; `co_create` uses `initial_body` to
3687/// stage the body without needing a real `xmove`.
3688pub fn new_thread(state: &mut LuaState, initial_body: Option<LuaValue>) -> Result<(), LuaError> {
3689    state.gc().check_step();
3690
3691    // PORT NOTE: In C, the new thread is GC-allocated as part of the allgc list.
3692    // In Rust (Phase A), we create a plain LuaState; Phase D will wire GC registration.
3693    // TODO(port): allocate via state.gc().new_obj(LuaType::Thread, ...) in Phase D
3694
3695    let global_rc = state.global_rc();
3696    let hookmask = state.hookmask;
3697    let basehookcount = state.basehookcount;
3698
3699    let reserved_id = {
3700        let mut g = state.global_mut();
3701        let id = g.next_thread_id;
3702        g.next_thread_id += 1;
3703        id
3704    };
3705
3706    let mut new_thread = LuaState {
3707        status: LuaStatus::Ok as u8,
3708        allowhook: true,
3709        nci: 0,
3710        top: StackIdx(0),
3711        stack_last: StackIdx(0),
3712        stack: Vec::new(),
3713        ci: CallInfoIdx(0),
3714        call_info: Vec::new(),
3715        openupval: Vec::new(),
3716        tbclist: Vec::new(),
3717        global: global_rc.clone(),
3718        hook: None,
3719        hookmask: 0,
3720        basehookcount: 0,
3721        hookcount: 0,
3722        errfunc: 0,
3723        nCcalls: 0,
3724        oldpc: 0,
3725        marked: 0,
3726        cached_thread_id: reserved_id,
3727    };
3728
3729    preinit_thread(&mut new_thread, global_rc);
3730
3731    new_thread.hookmask = hookmask;
3732    new_thread.basehookcount = basehookcount;
3733    // TODO(port): lua_Hook is Box<dyn FnMut(...)>; not Clone.
3734    // Sharing a hook between threads would require Arc<Mutex<...>> (Phase E debug).
3735    new_thread.reset_hook_count();
3736
3737    // macros.tsv: lua_getextraspace → state.extra_space_mut() → &mut [u8]
3738    // TODO(port): LuaState.extra_space field not yet defined; Phase B
3739
3740    // macros.tsv: luai_userstatethread → (extension hook; drop)
3741
3742    stack_init(&mut new_thread);
3743
3744    if let Some(body) = initial_body {
3745        new_thread.push(body);
3746    }
3747
3748    let thread_ref: Rc<RefCell<LuaState>> = Rc::new(RefCell::new(new_thread));
3749
3750    let value = {
3751        let mut g = state.global_mut();
3752        let id = reserved_id;
3753        let value = GcRef::new(lua_types::value::LuaThread::new(id));
3754        g.threads.insert(
3755            id,
3756            ThreadRegistryEntry { state: thread_ref, value: value.clone() },
3757        );
3758        value
3759    };
3760
3761    state.push(LuaValue::Thread(value));
3762
3763    Ok(())
3764}
3765
3766/// Free all resources held by a coroutine thread.
3767///
3768///
3769/// ```c
3770///
3771/// //   LX *l = fromstate(L1);
3772/// //   luaF_closeupval(L1, L1->stack.p);  /* close all upvalues */
3773/// //   lua_assert(L1->openupval == NULL);
3774/// //   luai_userstatefree(L, L1);
3775/// //   freestack(L1);
3776/// //   luaM_free(L, l);
3777/// // }
3778/// ```
3779pub(crate) fn free_thread(caller: &mut LuaState, thread: &mut LuaState) {
3780    // TODO(port): crate::func::close_upval(thread, StackIdx(0)) — lfunc.c → func.rs
3781    let _ = caller; // caller used only for luai_userstatefree (no-op)
3782
3783    // macros.tsv: lua_assert → debug_assert!
3784    debug_assert!(
3785        thread.openupval.is_empty(),
3786        "free_thread: open upvalues remain after close_upval"
3787    );
3788
3789    // macros.tsv: luai_userstatefree → (extension hook; drop)
3790
3791    free_stack(thread);
3792
3793}
3794
3795/// Reset a thread to its base state, closing all to-be-closed variables.
3796///
3797/// Returns the final status code as an `i32` (mirrors the C API).
3798///
3799///
3800/// ```c
3801///
3802/// //   CallInfo *ci = L->ci = &L->base_ci;
3803/// //   setnilvalue(s2v(L->stack.p));
3804/// //   ci->func.p = L->stack.p;
3805/// //   ci->callstatus = CIST_C;
3806/// //   if (status == LUA_YIELD) status = LUA_OK;
3807/// //   L->status = LUA_OK;  /* so it can run __close metamethods */
3808/// //   status = luaD_closeprotected(L, 1, status);
3809/// //   if (status != LUA_OK) luaD_seterrorobj(L, status, L->stack.p + 1);
3810/// //   else L->top.p = L->stack.p + 1;
3811/// //   ci->top.p = L->top.p + LUA_MINSTACK;
3812/// //   luaD_reallocstack(L, cast_int(ci->top.p - L->stack.p), 0);
3813/// //   return status;
3814/// // }
3815/// ```
3816pub fn reset_thread(state: &mut LuaState, status: i32) -> i32 {
3817    state.ci = CallInfoIdx(0);
3818    let ci_idx = 0usize;
3819
3820    // macros.tsv: setnilvalue → *o = LuaValue::Nil; s2v → state.stack_at(idx)
3821    if !state.stack.is_empty() {
3822        state.stack[0].val = LuaValue::Nil;
3823    }
3824
3825    state.call_info[ci_idx].func = StackIdx(0);
3826    state.call_info[ci_idx].callstatus = CIST_C;
3827
3828    let mut status = if status == LuaStatus::Yield as i32 {
3829        LuaStatus::Ok as i32
3830    } else {
3831        status
3832    };
3833
3834    state.status = LuaStatus::Ok as u8;
3835
3836    let close_status = crate::do_::close_protected(
3837        state,
3838        StackIdx(1),
3839        LuaStatus::from_raw(status),
3840    );
3841    status = close_status as i32;
3842
3843    if status != LuaStatus::Ok as i32 {
3844        crate::do_::set_error_obj(state, LuaStatus::from_raw(status), StackIdx(1));
3845    } else {
3846        state.top = StackIdx(1);
3847    }
3848
3849    let new_ci_top = StackIdx(state.top.0 + LUA_MINSTACK as u32);
3850    state.call_info[ci_idx].top = new_ci_top;
3851
3852    // TODO(port): crate::do_::realloc_stack(state, new_ci_top.0 as i32, 0) — ldo.c → do_.rs
3853    // For Phase A, grow the stack if needed to at least new_ci_top slots.
3854    let needed = new_ci_top.0 as usize;
3855    if state.stack.len() < needed {
3856        state.stack.resize(needed, StackValue::default());
3857    }
3858
3859    status
3860}
3861
3862/// Close a coroutine thread from the perspective of another thread.
3863///
3864///
3865/// ```c
3866///
3867/// //   int status;
3868/// //   lua_lock(L);
3869/// //   L->nCcalls = (from) ? getCcalls(from) : 0;
3870/// //   status = luaE_resetthread(L, L->status);
3871/// //   lua_unlock(L);
3872/// //   return status;
3873/// // }
3874/// ```
3875pub fn close_thread(state: &mut LuaState, from: Option<&LuaState>) -> i32 {
3876    // macros.tsv: getCcalls → state.c_calls()
3877    state.nCcalls = match from {
3878        Some(f) => f.c_calls(),
3879        None => 0,
3880    };
3881    let current_status = state.status as i32;
3882    let result = reset_thread(state, current_status);
3883    result
3884}
3885
3886/// Deprecated wrapper for `close_thread(L, NULL)`.
3887///
3888///
3889/// ```c
3890///
3891/// //   return lua_closethread(L, NULL);
3892/// // }
3893/// ```
3894pub fn reset_thread_api(state: &mut LuaState) -> i32 {
3895    close_thread(state, None)
3896}
3897
3898/// Create a new independent Lua state.  Returns `None` only on OOM.
3899///
3900///
3901/// PORT NOTE: The C API takes a custom allocator `(f, ud)`.  The Rust-native API
3902/// uses the global Rust allocator; those parameters are dropped.  Equivalent to
3903/// `LuaState::new()` at the call site.
3904///
3905/// ```c
3906///
3907/// //   int i;
3908/// //   lua_State *L;
3909/// //   global_State *g;
3910/// //   LG *l = cast(LG *, (*f)(ud, NULL, LUA_TTHREAD, sizeof(LG)));
3911/// //   if (l == NULL) return NULL;
3912/// //   L = &l->l.l; g = &l->g;
3913/// //   L->tt = LUA_VTHREAD;
3914/// //   g->currentwhite = bitmask(WHITE0BIT);
3915/// //   L->marked = luaC_white(g);
3916/// //   preinit_thread(L, g);
3917/// //   g->allgc = obj2gco(L);
3918/// //   L->next = NULL;
3919/// //   incnny(L);
3920/// //   g->frealloc = f; g->ud = ud; g->warnf = NULL; g->ud_warn = NULL;
3921/// //   g->mainthread = L; g->seed = luai_makeseed(L);
3922/// //   g->gcstp = GCSTPGC;
3923/// //   ... (zero-init all GC list pointers and tunables) ...
3924/// //   setivalue(&g->nilvalue, 0);  /* signal: state not yet built */
3925/// //   ... (setgcparam tunables) ...
3926/// //   for (i=0; i < LUA_NUMTAGS; i++) g->mt[i] = NULL;
3927/// //   if (luaD_rawrunprotected(L, f_luaopen, NULL) != LUA_OK) {
3928/// //     close_state(L); L = NULL;
3929/// //   }
3930/// //   return L;
3931/// // }
3932/// ```
3933pub fn new_state() -> Option<LuaState> {
3934    // In Rust, allocation failure panics by default; we use Result internally.
3935
3936    // Build a dummy LuaString for memerrmsg and strcache initialization.
3937    // This is a chicken-and-egg problem: GlobalState.memerrmsg needs to be initialized
3938    // before luaS_init, but luaS_init creates the memerrmsg.
3939    // We use a placeholder Rc<LuaString> that will be replaced by luaS_init.
3940    // TODO(port): this is fragile; Phase B should ensure memerrmsg is properly set by luaS_init.
3941    // TODO(D-1c-bridge): allocation outside state context (new_state() free fn — no LuaState yet)
3942    let placeholder_str = GcRef::new(LuaString::placeholder());
3943
3944    // macros.tsv: bitmask → (1u32 << b); WHITE0BIT = 0 → 1u8
3945    let initial_white = 1u8 << WHITE0BIT;
3946
3947    // macros.tsv: setivalue → *o = LuaValue::Int(x)
3948    // PORT NOTE: non-nil nilvalue signals "state not yet complete"; see is_complete().
3949
3950    let global = GlobalState {
3951        parser_hook: None,
3952        file_loader_hook: None,
3953        file_open_hook: None,
3954        popen_hook: None,
3955        file_remove_hook: None,
3956        file_rename_hook: None,
3957        os_execute_hook: None,
3958        dynlib_load_hook: None,
3959        dynlib_symbol_hook: None,
3960        dynlib_unload_hook: None,
3961        totalbytes: std::mem::size_of::<GlobalState>() as isize,
3962        gc_debt: 0,
3963        gc_estimate: 0,
3964        lastatomic: 0,
3965        strt: StringPool::default(),
3966        l_registry: LuaValue::Nil,
3967        globals: LuaValue::Nil,
3968        loaded: LuaValue::Nil,
3969        nilvalue: LuaValue::Int(0),
3970        seed: make_seed(),
3971        currentwhite: initial_white,
3972        gcstate: GCS_PAUSE,
3973        // macros.tsv: KGC_INC → GcKind::Incremental
3974        gckind: GcKind::Incremental as u8,
3975        gcstopem: false,
3976        genminormul: LUAI_GENMINORMUL,
3977        // macros.tsv: setgcparam → p = v / 4
3978        genmajormul: (LUAI_GENMAJORMUL / 4) as u8,
3979        gcstp: GCSTPGC,
3980        gcemergency: false,
3981        gcpause: (LUAI_GCPAUSE / 4) as u8,
3982        gcstepmul: (LUAI_GCMUL / 4) as u8,
3983        gcstepsize: LUAI_GCSTEPSIZE,
3984        sweepgc_cursor: 0,
3985        weak_tables_registry: Vec::new(),
3986        gc_tracked_long_strings: Vec::new(),
3987        pending_finalizers: Vec::new(),
3988        to_be_finalized: Vec::new(),
3989        twups: Vec::new(),
3990        panic: None,
3991        mainthread: None,
3992        threads: std::collections::HashMap::new(),
3993        main_thread_value: GcRef::new(lua_types::value::LuaThread::new(0)),
3994        current_thread_id: 0,
3995        main_thread_id: 0,
3996        next_thread_id: 1,
3997        memerrmsg: placeholder_str.clone(),
3998        tmname: Vec::new(),
3999        mt: std::array::from_fn(|_| None),
4000        strcache: std::array::from_fn(|_| {
4001            std::array::from_fn(|_| placeholder_str.clone())
4002        }),
4003        interned_lt: std::collections::HashMap::new(),
4004        warnf: None,
4005        c_functions: Vec::new(),
4006        heap: lua_gc::Heap::new(),
4007        cross_thread_upvals: std::collections::HashMap::new(),
4008        suspended_parent_stacks: Vec::new(),
4009        suspended_parent_open_upvals: Vec::new(),
4010    };
4011
4012    let global_rc = Rc::new(RefCell::new(global));
4013
4014    // macros.tsv: luaC_white → g.current_white()
4015    let initial_marked = initial_white;
4016
4017    let mut main_thread = LuaState {
4018        status: LuaStatus::Ok as u8,
4019        allowhook: true,
4020        nci: 0,
4021        top: StackIdx(0),
4022        stack_last: StackIdx(0),
4023        stack: Vec::new(),
4024        ci: CallInfoIdx(0),
4025        call_info: Vec::new(),
4026        openupval: Vec::new(),
4027        tbclist: Vec::new(),
4028        global: global_rc.clone(),
4029        hook: None,
4030        hookmask: 0,
4031        basehookcount: 0,
4032        hookcount: 0,
4033        errfunc: 0,
4034        nCcalls: 0,
4035        oldpc: 0,
4036        marked: initial_marked,
4037        cached_thread_id: 0,
4038    };
4039
4040    preinit_thread(&mut main_thread, global_rc.clone());
4041
4042    // macros.tsv: incnny → state.inc_nny() → L->nCcalls += 0x10000
4043    main_thread.inc_nny();
4044
4045    // TODO(port): self-referential Rc cycle; Phase D GC handles cycles.
4046    // For Phase A: skip setting mainthread to avoid the cycle.
4047
4048    // TODO(port): Phase D — register main_thread in allgc as a GcRef
4049
4050    //      close_state(L); L = NULL; }
4051    // error_sites.tsv: luaD_rawrunprotected → state.run_protected(|s| f(s, ud))
4052    // PORT NOTE: We call lua_open directly since we're not using the protected-call
4053    // machinery yet (ldo.c is not ported). Errors from lua_open propagate as Err.
4054    match lua_open(&mut main_thread) {
4055        Ok(()) => {}
4056        Err(_) => {
4057            close_state(&mut main_thread);
4058            return None;
4059        }
4060    }
4061
4062    Some(main_thread)
4063}
4064
4065/// Close the Lua state and free all resources.
4066///
4067///
4068/// PORT NOTE: In C, `lua_close` gets the main thread via `G(L)->mainthread`
4069/// and closes that regardless of which thread is passed.  In Rust, the caller
4070/// should hold the main `LuaState` and drop it (which triggers `close_state`
4071/// via this function or `Drop`).
4072///
4073/// ```c
4074///
4075/// //   lua_lock(L);
4076/// //   L = G(L)->mainthread;  /* only the main thread can be closed */
4077/// //   close_state(L);
4078/// // }
4079/// ```
4080pub fn close(mut state: LuaState) {
4081    // PORT NOTE: In Rust, callers must pass the main LuaState directly (or obtain it
4082    // from GlobalState.mainthread).  We do not traverse to the main thread here;
4083    // the caller owns the root state.
4084    // TODO(port): assert that `state` is indeed the main thread before closing
4085    close_state(&mut state);
4086}
4087
4088/// Forward a warning message through the configured warning sink.
4089///
4090///
4091/// ```c
4092///
4093/// //   lua_WarnFunction wf = G(L)->warnf;
4094/// //   if (wf != NULL) wf(G(L)->ud_warn, msg, tocont);
4095/// // }
4096/// ```
4097pub(crate) fn warning(state: &mut LuaState, msg: &[u8], to_cont: bool) {
4098    // types.tsv: global_State.warnf → Option<Box<dyn FnMut(&[u8], bool)>>
4099    // types.tsv: global_State.ud_warn → (removed; folded into the closure)
4100    // PORT NOTE: We must drop the RefMut borrow before calling the closure to avoid
4101    // a potential re-entrant borrow_mut() if the closure calls back into Lua.
4102    // We check for the presence of warnf while holding a borrow, then call it.
4103    // TODO(port): if the warning function needs to call back into state (e.g. to push
4104    // a Lua error), this will panic at runtime due to RefCell re-entry. Phase B should
4105    // design a safe re-entrance pattern (e.g. take + restore the warnf closure).
4106    let has_warnf = state.global().warnf.is_some();
4107    if has_warnf {
4108        // Take the warnf closure out to avoid re-entrant borrow.
4109        let mut warnf = state.global_mut().warnf.take();
4110        if let Some(ref mut f) = warnf {
4111            f(msg, to_cont);
4112        }
4113        // Restore the closure.
4114        state.global_mut().warnf = warnf;
4115    }
4116}
4117
4118/// Emit a warning composed from the error object on top of the stack and a location.
4119///
4120///
4121/// ```c
4122///
4123/// //   TValue *errobj = s2v(L->top.p - 1);
4124/// //   const char *msg = (ttisstring(errobj))
4125/// //                   ? getstr(tsvalue(errobj))
4126/// //                   : "error object is not a string";
4127/// //   luaE_warning(L, "error in ", 1);
4128/// //   luaE_warning(L, where, 1);
4129/// //   luaE_warning(L, " (", 1);
4130/// //   luaE_warning(L, msg, 1);
4131/// //   luaE_warning(L, ")", 0);
4132/// // }
4133/// ```
4134pub(crate) fn warn_error(state: &mut LuaState, where_: &[u8]) {
4135    // macros.tsv: s2v → state.stack_at(idx)
4136    let top_idx = state.top.0.saturating_sub(1) as usize;
4137    let errobj = state.stack.get(top_idx).map(|sv| sv.val.clone()).unwrap_or(LuaValue::Nil);
4138
4139    // macros.tsv: ttisstring → matches!(o, LuaValue::Str(_))
4140    // macros.tsv: getstr → ts.as_bytes(); tsvalue → o.as_string().expect("not string")
4141    // PORT NOTE: Clone the message bytes to avoid holding a borrow on `state.stack`
4142    // across the subsequent `warning()` calls which mutably borrow `state`.
4143    let msg: Vec<u8> = if let LuaValue::Str(ref s) = errobj {
4144        s.as_bytes().to_vec()
4145    } else {
4146        b"error object is not a string".to_vec()
4147    };
4148
4149    warning(state, b"error in ", true);
4150    warning(state, where_, true);
4151    warning(state, b" (", true);
4152    warning(state, &msg, true);
4153    warning(state, b")", false);
4154}
4155
4156// ──────────────────────────────────────────────────────────────────────────────
4157// PORT STATUS
4158//   source:        src/lstate.c  (445 lines, 25 functions)
4159//                  src/lstate.h  (408 lines; struct definitions merged)
4160//   target_crate:  lua-vm
4161//   confidence:    medium
4162//   todos:         44
4163//   port_notes:    34
4164//   unsafe_blocks: 0   (must be 0 outside explicit unsafe-budget crates)
4165//   notes:         Logic faithfully follows lstate.c. Key structural changes:
4166//                  (1) LX/LG C layout wrappers dropped; GlobalState is Rc<RefCell<>>.
4167//                  (2) CallInfo linked list → Vec<CallInfo> with CallInfoIdx indices;
4168//                      shrink_ci uses truncation rather than node-by-node removal.
4169//                  (3) lua_State.twups self-reference → membership in GlobalState.twups Vec.
4170//                  (4) errorJmp/setjmp → removed; errors use Result<T, LuaError>.
4171//                  (5) Custom allocator (lua_Alloc) → dropped; Rust's allocator handles it.
4172//                  (6) make_seed: ASLR pointer entropy requires unsafe; time-only for Phase A.
4173//                  (7) Perf: LuaState.cached_thread_id stores the thread's own id once at
4174//                      construction; upvalue_get/_set compare against this u64 field
4175//                      instead of borrowing global.current_thread_id on every read.
4176//                      Invariant survives coroutine resume because each thread caches its
4177//                      OWN id, not the global's id (see field doc on cached_thread_id).
4178//                  (8) Perf: LuaTableRefExt::{raw_set, raw_set_int, get, get_int,
4179//                      get_short_str, metatable, as_ptr} and table_{raw,set_with_tm,
4180//                      array_set} carry #[inline] so the per-set dispatch chain
4181//                      collapses into set_i_value / vm.rs OP_SETI callers. The
4182//                      historical reject_invalid_table_key precheck moved into
4183//                      LuaTable::try_raw_set (lua-types) and was dropped at this
4184//                      layer; raw_set now takes the key by value, eliminating a
4185//                      24-byte LuaValue clone per set. gc_barrier_back is invoked
4186//                      before the store in table_set_with_tm (semantically
4187//                      equivalent: the barrier only inspects the value's color,
4188//                      not its location), letting v be moved directly into
4189//                      table_raw_set without an intermediate clone.
4190//                  Key TODOs: luaT_init and luaX_init cross-crate calls (Phase B);
4191//                  init_registry table mutations through Rc (needs RefCell<LuaTable>);
4192//                  luaD_closeprotected/seterrorobj/reallocstack in reset_thread (ldo.c);
4193//                  GcRef<LuaState> self-reference for mainthread (Phase D);
4194//                  LuaString::placeholder() helper needed for GlobalState init;
4195//                  LuaValue and LuaTable should move to object.rs once that lands.
4196// ──────────────────────────────────────────────────────────────────────────────