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