Skip to main content

lua_vm/
api.rs

1//
2// PORT NOTE: This is the Rust-native translation of lapi.c.
3// The C-API surface (lua_State *, int stack-index protocol) is replaced by
4// methods on LuaState.  `lua_lock` / `lua_unlock` are dropped (no-op in the
5// single-threaded default build).  `api_incr_top` is dropped; `state.push()`
6// already increments.  Stack pointers (StkId) become StackIdx (u32).
7
8#![allow(dead_code)]
9
10use std::convert::Infallible;
11#[allow(unused_imports)] use crate::prelude::*;
12
13use crate::state::{LuaState, LuaCFunction, LuaCallable, StackIdx,
14    LuaValueExt, LuaTypeExt, StackIdxExt,
15    LuaTableRefExt, LuaUserDataRefExt};
16use lua_types::{
17    LuaValue, LuaType, LuaError, LuaString, LuaUserData, LuaClosure,
18    GcRef, LuaStatus,
19};
20use lua_types::value::LuaTable;
21
22pub const LUA_IDENT: &[u8] =
23    b"$LuaVersion: Lua 5.4.7  Copyright (C) 1994-2024 Lua.org, PUC-Rio $\
24      $LuaAuthors: R. Ierusalimschy, L. H. Figueiredo, W. Celes $";
25
26const LUA_REGISTRYINDEX: i32 = -(1_000_000) - 1000;
27
28const LUA_MULTRET: i32 = -1;
29
30const LUA_RIDX_GLOBALS: i64 = 2;
31
32const MAX_UPVAL: u8 = 255;
33
34#[inline]
35fn is_pseudo(idx: i32) -> bool {
36    idx <= LUA_REGISTRYINDEX
37}
38
39#[inline]
40fn is_upvalue(idx: i32) -> bool {
41    idx < LUA_REGISTRYINDEX
42}
43
44// PORT NOTE: In C, the only "invalid" TValue is the global nilvalue singleton
45// pointer returned by index2value when the index is out of range. In Rust we
46// cannot do pointer-equality on a singleton, so validity is decided by whether
47// the index resolves to a real stack/upvalue slot — see `is_valid_index`.
48#[inline]
49fn is_valid_index(state: &LuaState, idx: i32) -> bool {
50    if idx == 0 {
51        return false;
52    }
53    let ci = state.current_call_info();
54    if idx > 0 {
55        let slot = ci.func + idx;
56        slot.0 < state.top_idx().0
57    } else if !is_pseudo(idx) {
58        (-idx) as u32 <= state.top_idx().0.saturating_sub(ci.func.0 + 1)
59    } else if idx == LUA_REGISTRYINDEX {
60        true
61    } else {
62        let upval_n = (LUA_REGISTRYINDEX - idx) as usize;
63        let func_val = state.get_at(ci.func);
64        if let LuaValue::Function(LuaClosure::C(ref ccl)) = func_val {
65            upval_n >= 1 && upval_n <= ccl.upvalues.len()
66        } else {
67            false
68        }
69    }
70}
71
72// ── index helpers ─────────────────────────────────────────────────────────────
73
74// PORT NOTE: In Rust we cannot return a pointer; we return a cloned LuaValue.
75// Writers use a companion index_to_stack_idx() for actual stack slots.
76fn index_to_value(state: &LuaState, idx: i32) -> LuaValue {
77    let ci = state.current_call_info();
78    if idx > 0 {
79        let func_idx = ci.func;
80        let slot = func_idx + idx;
81        debug_assert!(
82            idx as u32 <= ci.top.saturating_sub(func_idx + 1),
83            "unacceptable index"
84        );
85        if slot.0 >= state.top_idx().0 {
86            LuaValue::Nil
87        } else {
88            state.get_at(slot)
89        }
90    } else if !is_pseudo(idx) {
91        // negative index
92        debug_assert!(
93            idx != 0,
94            "invalid index"
95        );
96        let top = state.top_idx();
97        let slot = (top.0 as i32 + idx) as u32;
98        state.get_at(slot)
99    } else if idx == LUA_REGISTRYINDEX {
100        state.registry_value()
101    } else {
102        // upvalues: idx = LUA_REGISTRYINDEX - idx  (idx < LUA_REGISTRYINDEX)
103        let upval_n = (LUA_REGISTRYINDEX - idx) as usize;
104        debug_assert!(upval_n <= MAX_UPVAL as usize + 1, "upvalue index too large");
105        let func_val = state.get_at(ci.func);
106        if let LuaValue::Function(LuaClosure::C(ref ccl)) = func_val {
107            // C closure upvalue
108            if upval_n >= 1 && upval_n <= ccl.upvalues.len() {
109                ccl.upvalues[upval_n - 1].clone()
110            } else {
111                LuaValue::Nil
112            }
113        } else {
114            LuaValue::Nil
115        }
116    }
117}
118
119// Returns a StackIdx for a valid (non-pseudo) actual stack slot.
120#[inline]
121fn index_to_stack_idx(state: &LuaState, idx: i32) -> StackIdx {
122    let ci = state.current_call_info();
123    if idx > 0 {
124        let slot = ci.func + idx;
125        debug_assert!(slot.0 < state.top_idx().0, "invalid index");
126        slot
127    } else {
128        debug_assert!(idx != 0 && !is_pseudo(idx), "invalid index");
129        StackIdx((state.top_idx().0 as i32 + idx) as u32)
130    }
131}
132
133// ── stack manipulation ────────────────────────────────────────────────────────
134
135pub fn check_stack(state: &mut LuaState, n: i32) -> bool {
136    debug_assert!(n >= 0, "negative 'n'");
137    let available = state.stack_available();
138    let res = if available > n as usize {
139        true
140    } else {
141        crate::do_::grow_stack(state, n, false).unwrap_or(false)
142    };
143    if res {
144        let needed_top = state.top_idx() + n as i32;
145        let ci_idx = state.current_ci_idx();
146        if state.get_ci(ci_idx).top.0 < needed_top.0 {
147            let live_top = state.top_idx();
148            state.get_ci_mut(ci_idx).top = needed_top;
149            state.clear_stack_range(live_top, needed_top);
150        }
151    }
152    res
153}
154
155/// Move the top `n` values from `from`'s stack onto `to`'s stack.
156///
157/// Both threads must share the same `GlobalState` (i.e. one is a
158/// coroutine the other created via `coroutine.create`). Calling with
159/// `from` == `to` is a no-op. Equivalent to:
160///
161/// ```text
162/// args = from.stack[top-n..top].clone();
163/// from.set_top(top - n);
164/// for v in args { to.push(v); }
165/// ```
166///
167///
168/// Phase E-3: implemented for the same-`GlobalState` case (the only one
169/// `lua-stdlib` uses today). `lua-vm` callers should prefer this helper
170/// over hand-rolling the snapshot/push dance.
171pub fn xmove(from: &mut LuaState, to: &mut LuaState, n: i32) {
172    if n <= 0 {
173        return;
174    }
175    if std::ptr::eq(from as *const LuaState, to as *const LuaState) {
176        return;
177    }
178    let abs_top = from.top_idx().0 as i32;
179    debug_assert!(abs_top >= n, "lua_xmove: from stack underflow");
180    let first_abs = abs_top - n;
181    let mut buf: Vec<lua_types::LuaValue> = Vec::with_capacity(n as usize);
182    for i in 0..n {
183        let idx = StackIdx((first_abs + i) as u32);
184        buf.push(from.get_at(idx));
185    }
186    from.set_top(StackIdx(first_abs as u32));
187    for v in buf {
188        to.push(v);
189    }
190}
191
192pub fn at_panic(
193    state: &mut LuaState,
194    panicf: Option<fn(&mut LuaState) -> Result<usize, LuaError>>,
195) -> Option<fn(&mut LuaState) -> Result<usize, LuaError>> {
196    let old = state.global_mut().panic;
197    state.global_mut().panic = panicf;
198    old
199}
200
201pub fn version(_state: &LuaState) -> f64 {
202    504.0
203}
204
205pub fn abs_index(state: &LuaState, idx: i32) -> i32 {
206    //          : cast_int(L->top.p - L->ci->func.p) + idx;
207    if idx > 0 || is_pseudo(idx) {
208        idx
209    } else {
210        let ci = state.current_call_info();
211        (state.top_idx().0 as i32 - ci.func.0 as i32) + idx
212    }
213}
214
215pub fn get_top(state: &LuaState) -> i32 {
216    let ci = state.current_call_info();
217    (state.top_idx().0 as i32) - (ci.func.0 as i32 + 1)
218}
219
220pub fn set_top(state: &mut LuaState, idx: i32) -> Result<(), LuaError> {
221    let func = state.current_call_info().func;
222    let ci_top = state.current_call_info().top;
223    if idx >= 0 {
224        debug_assert!(
225            idx as u32 <= ci_top.saturating_sub(func + 1),
226            "new top too large"
227        );
228        let new_top = func + 1 + idx as i32;
229        let old_top = state.top_idx();
230        if new_top.0 > old_top.0 {
231            for i in old_top.0..new_top.0 {
232                state.set_at(i, LuaValue::Nil);
233            }
234        }
235        // TODO(port): to-be-closed variable closing on stack shrink;
236        // luaF_close not yet translated. Skipping close logic for Phase A.
237        state.set_top_idx(new_top);
238    } else {
239        debug_assert!(
240            -(idx + 1) <= (state.top_idx().0 as i32 - (func.0 as i32 + 1)),
241            "invalid new top"
242        );
243        let new_top = (state.top_idx().0 as i32 + idx + 1) as u32;
244        // TODO(port): to-be-closed variable closing on stack shrink (same as above)
245        state.set_top_idx(new_top);
246    }
247    Ok(())
248}
249
250pub fn close_slot(state: &mut LuaState, idx: i32) -> Result<(), LuaError> {
251    let level = index_to_stack_idx(state, idx);
252    // TODO(port): tbc-list check and luaF_close not yet translated.
253    state.set_at(level, LuaValue::Nil);
254    Ok(())
255}
256
257#[inline]
258fn reverse_segment(state: &mut LuaState, from: StackIdx, to: StackIdx) {
259    let mut lo = from.0;
260    let mut hi = to.0;
261    while lo < hi {
262        let temp = state.get_at(StackIdx(lo));
263        let hi_val = state.get_at(StackIdx(hi));
264        state.set_at(StackIdx(lo), hi_val);
265        state.set_at(StackIdx(hi), temp);
266        lo += 1;
267        hi -= 1;
268    }
269}
270
271pub fn rotate(state: &mut LuaState, idx: i32, n: i32) {
272    let t = state.top_idx() - 1;
273    let p = index_to_stack_idx(state, idx);
274    debug_assert!((n.unsigned_abs() as i32) <= ((t.0 as i32) - (p.0 as i32) + 1), "invalid 'n'");
275    let m = if n >= 0 {
276        t - n
277    } else {
278        StackIdx((p.0 as i32 - n - 1) as u32)
279    };
280    reverse_segment(state, p, m);
281    reverse_segment(state, m + 1, t);
282    reverse_segment(state, p, t);
283}
284
285pub fn copy(state: &mut LuaState, fromidx: i32, toidx: i32) {
286    let fr = index_to_value(state, fromidx);
287    if is_upvalue(toidx) {
288        // Writing to a function upvalue pseudo-index
289        let upval_n = (LUA_REGISTRYINDEX - toidx) as usize;
290        let func_val = state.get_at(state.current_call_info().func);
291        if let LuaValue::Function(LuaClosure::C(ref ccl)) = func_val {
292            // TODO(port): CClosure upvalue write requires interior mutability on GcRef<CClosure>
293            // state.gc().barrier(ccl, &fr);
294            let _ = (upval_n, ccl);
295        }
296        // TODO(port): implement upvalue write for copy() to C closure upvalues
297    } else if toidx == LUA_REGISTRYINDEX {
298        // TODO(port): write to registry — needs GlobalState::set_registry(fr)
299    } else {
300        let to_slot = index_to_stack_idx(state, toidx);
301        state.set_at(to_slot, fr);
302    }
303}
304
305pub fn push_value(state: &mut LuaState, idx: i32) {
306    let v = index_to_value(state, idx);
307    state.push(v);
308}
309
310/// Inherent `push_copy` so the `LuaStateStubExt::push_copy` default
311/// `todo!()` no longer fires. Phase-A `state.push_copy(idx)` call-sites
312/// (base.rs, etc.) duplicate the value at `idx` onto the top of the stack —
313/// the same semantics as `lua_pushvalue`.
314impl LuaState {
315    pub fn push_copy(&mut self, idx: i32) -> Result<(), LuaError> {
316        push_value(self, idx);
317        Ok(())
318    }
319
320    pub fn push_value_at(&mut self, idx: i32) -> Result<(), LuaError> {
321        push_value(self, idx);
322        Ok(())
323    }
324
325    pub fn insert(&mut self, idx: i32) -> Result<(), LuaError> {
326        rotate(self, idx, 1);
327        Ok(())
328    }
329
330    /// Inherent `length_at` mirroring `luaL_len` from `lauxlib.c`: push the
331    /// value's length onto the stack (honouring `__len`), pop it as an
332    /// integer, and error if the result is not an integer. Defined on
333    /// `LuaState` so it overrides the `LuaStateStubExt::length_at` trait
334    /// default `todo!()`.
335    pub fn length_at(&mut self, idx: i32) -> Result<i64, LuaError> {
336        len(self, idx)?;
337        let l = match to_integer_x(self, -1) {
338            Some(n) => n,
339            None => {
340                return Err(LuaError::runtime(format_args!(
341                    "object length is not an integer"
342                )));
343            }
344        };
345        self.pop_n(1);
346        Ok(l)
347    }
348
349    /// Write `msg` bytes verbatim to standard output. Mirrors the C macro
350    /// `lua_writestring(s, l) = fwrite(s, 1, l, stdout)` from `lauxlib.h`,
351    /// used by `print` and friends. A failed write is propagated as a
352    /// `LuaError::runtime`; this matches C-Lua's behaviour where an I/O
353    /// error during `lua_writestring` would surface through the host's
354    /// error handling.
355    pub fn write_output(&mut self, msg: &[u8]) -> Result<(), LuaError> {
356        if let Some(write_fn) = self.global().stdout_hook {
357            write_fn(msg).map_err(|e| LuaError::runtime(format_args!("{}", e)))?;
358            return Ok(());
359        }
360
361        #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
362        {
363            let _ = msg;
364            Err(LuaError::runtime(format_args!(
365                "stdout not available in this host"
366            )))
367        }
368
369        #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
370        {
371            use std::io::Write;
372            let stdout = std::io::stdout();
373            let mut handle = stdout.lock();
374            handle
375                .write_all(msg)
376                .map_err(|e| LuaError::runtime(format_args!("{}", e)))?;
377            handle
378                .flush()
379                .map_err(|e| LuaError::runtime(format_args!("{}", e)))?;
380            Ok(())
381        }
382    }
383
384    /// Convert the value at `idx` to a display string, push the result onto
385    /// the stack, and return a copy of its bytes. Mirrors `luaL_tolstring`
386    /// from `lauxlib.c`. The default Lua formatting is used for primitives
387    /// (`"true"`/`"false"`/`"nil"`, `%I` integers, `%.14g` floats); for other
388    /// reference types the result is `"<typename>: 0x<hex pointer>"`.
389    ///
390    /// If the value has a `__tostring` metamethod, it is invoked first and its
391    /// (string) result is used in place of the default formatting (matching
392    pub fn to_display_string(&mut self, idx: i32) -> Result<Vec<u8>, LuaError> {
393        let abs = abs_index(self, idx);
394        let v = index_to_value(self, abs);
395        let mt: Option<GcRef<LuaTable>> = match &v {
396            LuaValue::Table(t) => t.metatable(),
397            LuaValue::UserData(u) => u.metatable(),
398            _ => self.global().mt[v.base_type() as usize].clone(),
399        };
400        if let Some(mt_ref) = mt {
401            let key = self.intern_str(b"__tostring")?;
402            let f = mt_ref.get_short_str(&key);
403            if !matches!(f, LuaValue::Nil) {
404                let func_idx = self.top_idx();
405                self.push(f);
406                self.push(v.clone());
407                if self.current_ci().is_lua_code() {
408                    self.do_call(func_idx, 1)?;
409                } else {
410                    self.do_call_no_yield(func_idx, 1)?;
411                }
412                let top = self.top_idx();
413                let result = self.get_at(StackIdx(top.0 - 1));
414                if let LuaValue::Str(s) = result {
415                    return Ok(s.as_bytes().to_vec());
416                }
417                return Err(LuaError::runtime(format_args!(
418                    "'__tostring' must return a string"
419                )));
420            }
421        }
422        let bytes: Vec<u8> = match &v {
423            LuaValue::Str(s) => {
424                let out = s.as_bytes().to_vec();
425                self.push(LuaValue::Str(s.clone()));
426                out
427            }
428            LuaValue::Int(_) | LuaValue::Float(_) => {
429                let s = crate::object::num_to_string(self, &v)?;
430                let out = s.as_bytes().to_vec();
431                self.push(LuaValue::Str(s));
432                out
433            }
434            LuaValue::Bool(b) => {
435                let lit: &[u8] = if *b { b"true" } else { b"false" };
436                let s = self.intern_str(lit)?;
437                self.push(LuaValue::Str(s));
438                lit.to_vec()
439            }
440            LuaValue::Nil => {
441                let s = self.intern_str(b"nil")?;
442                self.push(LuaValue::Str(s));
443                b"nil".to_vec()
444            }
445            _ => {
446                let kind = crate::tagmethods::obj_type_name(self, &v)?;
447                let ptr = to_pointer(self, abs).unwrap_or(0);
448                let mut buf = kind;
449                buf.extend_from_slice(b": 0x");
450                buf.extend_from_slice(format!("{:x}", ptr).as_bytes());
451                let s = self.intern_str(&buf)?;
452                self.push(LuaValue::Str(s));
453                buf
454            }
455        };
456        Ok(bytes)
457    }
458
459    /// (stack top minus the slot just after the frame's `func`).
460    ///
461    /// Receiver is `&mut self` to match the `LuaStateStubExt::top` trait
462    /// signature exactly; with a different receiver shape (`&self`), Rust's
463    /// method-resolution picks the trait default and the program panics on
464    /// `todo!("phase-b-reconcile: top")`.
465    pub fn top(&mut self) -> i32 {
466        get_top(self)
467    }
468
469    /// `LuaStateStubExt::get_top` trait method. Inherent method shadows the
470    /// trait default so the `todo!("phase-b-reconcile: get_top")` shim never
471    /// fires.
472    pub fn get_top(&mut self) -> i32 {
473        get_top(self)
474    }
475
476    /// stack index `idx`, or `LuaType::None` if `idx` falls outside the
477    /// active call frame. Inherent method shadows the
478    /// `LuaStateStubExt::type_at` trait default so the `todo!()` shim
479    /// never fires.
480    pub fn type_at(&mut self, idx: i32) -> LuaType {
481        lua_type_at(self, idx)
482    }
483
484    /// #N (value expected)` error if the slot at `arg` is `LUA_TNONE`
485    /// (i.e. beyond the active call frame's top). Otherwise a no-op.
486    ///
487    /// Inherent method on LuaState shadows the `LuaStateStubExt::check_arg_any`
488    /// trait default so the `todo!()` shim never fires.
489    pub fn check_arg_any(&mut self, arg: i32) -> Result<(), LuaError> {
490        if lua_type_at(self, arg) == LuaType::None {
491            return Err(LuaError::arg_error(arg, "value expected"));
492        }
493        Ok(())
494    }
495
496    /// at `arg` to a string via `lua_tolstring` (which coerces numbers to
497    /// their string form) and returns the bytes. Raises
498    /// `bad argument #N (string expected, got <type>)` if the value is not a
499    /// string and not number-coercible.
500    ///
501    /// Inherent method on LuaState shadows the `LuaStateStubExt::check_arg_string`
502    /// trait default so the `todo!()` shim never fires. Uses the free `to_lua_string`
503    /// helper here rather than `auxlib::check_lstring`, which routes through
504    /// `state.to_lua_string` / `state.type_name` — both still trait stubs.
505    pub fn check_arg_string(&mut self, arg: i32) -> Result<Vec<u8>, LuaError> {
506        match to_lua_string(self, arg)? {
507            Some(s) => Ok(s.as_bytes().to_vec()),
508            None => {
509                let got = index_to_value(self, arg);
510                let got_name = crate::tagmethods::obj_type_name(self, &got)?;
511                let extramsg = format!(
512                    "string expected, got {}",
513                    String::from_utf8_lossy(&got_name)
514                );
515                Err(crate::debug::arg_error_impl(self, arg, extramsg.as_bytes()))
516            }
517        }
518    }
519
520    /// `arg` to a `lua_Integer` (i64) via `lua_tointegerx` (which accepts
521    /// ints, floats with exact integer value, and string-form integers).
522    /// Raises `bad argument #N (number has no integer representation)` if
523    /// the value is a number but not representable as an integer, or
524    /// `bad argument #N (number expected, got <type>)` otherwise.
525    ///
526    /// Inherent method on LuaState shadows the `LuaStateStubExt::check_arg_integer`
527    /// trait default so the `todo!()` shim never fires. Uses the free
528    /// `to_integer_x` / `is_number` helpers in this file rather than
529    /// `auxlib::check_integer`, which routes through `state.to_integer_x`
530    /// and `state.type_name` — both still trait stubs.
531    pub fn check_arg_integer(&mut self, arg: i32) -> Result<i64, LuaError> {
532        match to_integer_x(self, arg) {
533            Some(d) => Ok(d),
534            None => {
535                if is_number(self, arg) {
536                    Err(LuaError::arg_error(
537                        arg,
538                        "number has no integer representation",
539                    ))
540                } else {
541                    let got = index_to_value(self, arg);
542                    let got_name = crate::tagmethods::obj_type_name(self, &got)?;
543                    let extramsg = format!(
544                        "number expected, got {}",
545                        String::from_utf8_lossy(&got_name)
546                    );
547                    Err(crate::debug::arg_error_impl(self, arg, extramsg.as_bytes()))
548                }
549            }
550        }
551    }
552
553    /// `arg` to an `f64` via `lua_tonumberx` (which accepts ints, floats,
554    /// and number-shaped strings) and raises `bad argument #N (number
555    /// expected, got <type>)` if the value is not number-coercible.
556    ///
557    /// Inherent method on LuaState shadows the `LuaStateStubExt::check_number`
558    /// trait default so the `todo!()` shim never fires. Uses the free
559    /// `to_number_x` helper here rather than `auxlib::check_number`, which
560    /// routes through `state.to_number_x` and `state.type_name` — both still
561    /// trait stubs.
562    pub fn check_number(&mut self, arg: i32) -> Result<f64, LuaError> {
563        match to_number_x(self, arg) {
564            Some(d) => Ok(d),
565            None => {
566                let got = index_to_value(self, arg);
567                let got_name = crate::tagmethods::obj_type_name(self, &got)?;
568                let extramsg = format!(
569                    "number expected, got {}",
570                    String::from_utf8_lossy(&got_name)
571                );
572                Err(crate::debug::arg_error_impl(self, arg, extramsg.as_bytes()))
573            }
574        }
575    }
576
577    /// `arg` is absent (`LUA_TNONE`) or `nil`, return `def`; otherwise
578    /// convert it to an integer (with the same string-to-number coercion
579    /// `lua_tointegerx` applies) and raise on failure.
580    ///
581    /// Inherent method on LuaState shadows the `LuaStateStubExt::opt_arg_integer`
582    /// trait default so the `todo!()` shim never fires. Implemented with the
583    /// free-function helpers in this file rather than `auxlib::opt_integer`
584    /// because the latter routes through `state.is_none_or_nil` and
585    /// `state.to_integer_x`, which are themselves stubbed.
586    pub fn opt_arg_integer(&mut self, arg: i32, def: i64) -> Result<i64, LuaError> {
587        match lua_type_at(self, arg) {
588            LuaType::None | LuaType::Nil => Ok(def),
589            _ => match to_integer_x(self, arg) {
590                Some(d) => Ok(d),
591                None => {
592                    if is_number(self, arg) {
593                        Err(LuaError::arg_error(
594                            arg,
595                            "number has no integer representation",
596                        ))
597                    } else {
598                        let got = index_to_value(self, arg);
599                        Err(LuaError::type_arg_error(arg, "number", &got))
600                    }
601                }
602            },
603        }
604    }
605
606    /// `lua_pcallk` with no continuation. Defers to the existing `pcall_k`
607    /// free function, which routes through `protected_call_raw` and
608    /// surfaces any runtime / syntax error as `Err(LuaError::Runtime|Syntax)`.
609    ///
610    /// Inherent method on LuaState shadows the `LuaStateStubExt::protected_call`
611    /// trait default so the `todo!()` shim never fires.
612    pub fn protected_call(&mut self, nargs: i32, nresults: i32, msgh: i32) -> Result<(), LuaError> {
613        pcall_k(self, nargs, nresults, msgh, 0, None).map(|_| ())
614    }
615
616    /// protected call. When `k` is set and the thread is yieldable, an
617    /// inner yield propagates as `LuaError::Yield` and the continuation
618    /// fires on resume via `finishCcall` → `finishpcallk`.
619    pub fn protected_call_k(
620        &mut self,
621        nargs: i32,
622        nresults: i32,
623        msgh: i32,
624        ctx: isize,
625        k: Option<crate::state::LuaKFunction>,
626    ) -> Result<(), LuaError> {
627        pcall_k(self, nargs, nresults, msgh, ctx, k).map(|_| ())
628    }
629
630    pub fn push_string(&mut self, s: &[u8]) -> Result<(), LuaError> {
631        push_lstring(self, s)?;
632        Ok(())
633    }
634
635    pub fn push_c_closure(
636        &mut self,
637        f: fn(&mut LuaState) -> Result<usize, LuaError>,
638        n: i32,
639    ) -> Result<(), LuaError> {
640        push_cclosure(self, f, n)
641    }
642
643    pub fn raw_seti(&mut self, idx: i32, n: i64) -> Result<(), LuaError> {
644        raw_set_i(self, idx, n)
645    }
646
647    pub fn table_set_i(&mut self, idx: i32, n: i64) -> Result<(), LuaError> {
648        set_i(self, idx, n)
649    }
650
651    /// Get `t[n]` where `t` is a pre-resolved `LuaValue`, bypassing stack-index
652    /// resolution. Use this in tight loops that operate on the same table
653    /// repeatedly to avoid the `index_to_value` call per iteration.
654    pub fn table_get_i_value(&mut self, t: &LuaValue, n: i64) -> Result<LuaType, LuaError> {
655        get_i_value(self, t, n)
656    }
657
658    /// Set `t[n] = stack_top` (then pop) where `t` is a pre-resolved `LuaValue`,
659    /// bypassing stack-index resolution. Use this in tight loops that operate on
660    /// the same table repeatedly to avoid the `index_to_value` call per iteration.
661    pub fn table_set_i_value(&mut self, t: &LuaValue, n: i64) -> Result<(), LuaError> {
662        set_i_value(self, t, n)
663    }
664
665    pub fn create_table(&mut self, narr: i32, nrec: i32) -> Result<(), LuaError> {
666        create_table(self, narr, nrec)
667    }
668
669    /// Pop the value on top of the stack and store it in the registry under
670    /// the string `key`.
671    ///
672    pub fn registry_set(&mut self, key: &[u8]) -> Result<(), LuaError> {
673        set_field(self, LUA_REGISTRYINDEX, key)
674    }
675
676    /// Create a new metatable in the registry under key `tname`. Leaves the
677    /// new metatable on top of the stack and returns `true` when newly
678    /// created. If `registry[tname]` already exists, leaves it on top of the
679    /// stack and returns `false`.
680    ///
681    pub fn new_metatable(&mut self, tname: &[u8]) -> Result<bool, LuaError> {
682        if get_field(self, LUA_REGISTRYINDEX, tname)? != LuaType::Nil {
683            return Ok(false);
684        }
685        self.pop_n(1);
686        create_table(self, 0, 2)?;
687        push_lstring(self, tname)?;
688        set_field(self, -2, b"__name")?;
689        push_value(self, -1);
690        set_field(self, LUA_REGISTRYINDEX, tname)?;
691        Ok(true)
692    }
693
694    /// Create a new library table sized for `funcs` and register each entry as
695    /// a closure field on it. Leaves the table on the top of the stack.
696    ///
697    ///   `luaL_checkversion(L), luaL_newlibtable(L,l), luaL_setfuncs(L,l,0)`.
698    /// `luaL_checkversion` is a no-op here (no ABI-version mismatch is
699    /// possible inside the Rust port).
700    pub fn new_lib(
701        &mut self,
702        funcs: &[(&[u8], LuaCFunction)],
703    ) -> Result<(), LuaError> {
704        create_table(self, 0, funcs.len() as i32)?;
705        for (name, f) in funcs {
706            push_cclosure(self, *f, 0)?;
707            set_field(self, -2, name)?;
708        }
709        Ok(())
710    }
711
712    /// Create and populate a library table for `funcs`, leaving it on top of
713    /// the stack. The `_name` argument is informational and matches the
714    /// `luaL_register`-style call sites in the Phase-A stdlib; the actual
715    /// global binding for the library happens later via `luaL_requiref`.
716    ///
717    pub fn register_lib(
718        &mut self,
719        _name: &[u8],
720        funcs: &[(&[u8], LuaCFunction)],
721    ) -> Result<(), LuaError> {
722        self.new_lib(funcs)
723    }
724
725    /// Create a new empty table presized to hold every entry in `funcs`, and
726    /// leave it on top of the stack. No registration is performed — callers
727    /// typically follow up with `set_funcs` / `set_funcs_with_upvalues` to
728    /// populate the table.
729    ///
730    ///   `lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1)`. The C macro's
731    /// `- 1` discounts the sentinel `{NULL, NULL}` entry; the Rust slice has
732    /// no sentinel, so we use `funcs.len()` directly.
733    pub fn new_lib_table(
734        &mut self,
735        funcs: &[(&[u8], LuaCFunction)],
736    ) -> Result<(), LuaError> {
737        create_table(self, 0, funcs.len() as i32)
738    }
739
740    /// Register each entry in `funcs` as a C closure on the table at index
741    /// `-(nup + 2)`, sharing the `nup` values currently on top of the stack
742    /// as upvalues. The upvalues are popped at the end.
743    ///
744    pub fn set_funcs_with_upvalues(
745        &mut self,
746        funcs: &[(&[u8], LuaCFunction)],
747        nup: i32,
748    ) -> Result<(), LuaError> {
749        check_stack(self, nup);
750        for (name, f) in funcs {
751            for _ in 0..nup {
752                push_value(self, -nup);
753            }
754            push_cclosure(self, *f, nup)?;
755            set_field(self, -(nup + 2), name)?;
756        }
757        self.pop_n(nup as usize);
758        Ok(())
759    }
760
761    pub fn set_metatable(&mut self, objindex: i32) -> Result<(), LuaError> {
762        set_metatable(self, objindex)?;
763        Ok(())
764    }
765
766    /// Fetch the metatable registered under `name` in the registry and assign
767    /// it as the metatable of the value currently on top of the stack. The
768    /// fetched metatable is popped after assignment, leaving the original top
769    /// value in place.
770    ///
771    pub fn set_metatable_by_name(&mut self, name: &[u8]) -> Result<(), LuaError> {
772        get_field(self, LUA_REGISTRYINDEX, name)?;
773        set_metatable(self, -2)?;
774        Ok(())
775    }
776
777    /// Ensure `registry[name]` is a table; push it onto the stack.
778    /// Returns `true` if the table already existed, `false` if newly created.
779    ///
780    pub fn get_subtable_registry(&mut self, name: &[u8]) -> Result<bool, LuaError> {
781        if get_field(self, LUA_REGISTRYINDEX, name)? == LuaType::Table {
782            return Ok(true);
783        }
784        self.pop_n(1);
785        let idx = abs_index(self, LUA_REGISTRYINDEX);
786        let new_tbl = self.new_table();
787        self.push(LuaValue::Table(new_tbl));
788        push_value(self, -1);
789        set_field(self, idx, name)?;
790        Ok(false)
791    }
792
793    /// Allocate a fresh full-userdata block of `size` bytes with `nuvalue`
794    /// nil-initialised user-value slots, push it on the stack, and return a
795    /// `GcRef` to it. The `_name` parameter is advisory — callers typically
796    /// follow up with `set_metatable_by_name(name)` to attach the registered
797    /// metatable.
798    ///
799    /// C-correspondent: `lua_newuserdatauv(L, size, nuvalue)` (no name
800    /// parameter on the C side; the Rust signature carries it for callers'
801    /// convenience).
802    pub fn new_userdata_typed(
803        &mut self,
804        _name: &[u8],
805        size: usize,
806        nuvalue: i32,
807    ) -> Result<GcRef<LuaUserData>, LuaError> {
808        debug_assert!(nuvalue >= 0 && nuvalue < u16::MAX as i32, "invalid value");
809        // TODO(D-1c-bridge): state.new_userdata is still todo!(); keep direct alloc
810        let u = GcRef::new(LuaUserData {
811            data: vec![0u8; size].into_boxed_slice(),
812            uv: vec![LuaValue::Nil; nuvalue as usize],
813            metatable: std::cell::RefCell::new(None),
814            host_value: std::cell::RefCell::new(None),
815        });
816        self.push(LuaValue::UserData(u.clone()));
817        self.gc().check_step();
818        Ok(u)
819    }
820}
821
822// ── access functions (stack → Rust) ──────────────────────────────────────────
823
824pub fn lua_type_at(state: &LuaState, idx: i32) -> LuaType {
825    if !is_valid_index(state, idx) {
826        return LuaType::None;
827    }
828    index_to_value(state, idx).base_type()
829}
830
831pub fn type_name(_state: &LuaState, t: LuaType) -> &'static [u8] {
832    t.type_name()
833}
834
835pub fn is_cfunction(state: &LuaState, idx: i32) -> bool {
836    let o = index_to_value(state, idx);
837    matches!(o, LuaValue::Function(LuaClosure::LightC(_)) | LuaValue::Function(LuaClosure::C(_)))
838}
839
840pub fn is_integer(state: &LuaState, idx: i32) -> bool {
841    let o = index_to_value(state, idx);
842    matches!(o, LuaValue::Int(_))
843}
844
845pub fn is_number(state: &LuaState, idx: i32) -> bool {
846    let o = index_to_value(state, idx);
847    o.to_number_with_strconv().is_some()
848}
849
850pub fn is_string(state: &LuaState, idx: i32) -> bool {
851    let o = index_to_value(state, idx);
852    matches!(o, LuaValue::Str(_) | LuaValue::Int(_) | LuaValue::Float(_))
853}
854
855pub fn is_userdata(state: &LuaState, idx: i32) -> bool {
856    let o = index_to_value(state, idx);
857    matches!(o, LuaValue::UserData(_) | LuaValue::LightUserData(_))
858}
859
860pub fn raw_equal(state: &LuaState, index1: i32, index2: i32) -> bool {
861    if !is_valid_index(state, index1) || !is_valid_index(state, index2) {
862        return false;
863    }
864    let o1 = index_to_value(state, index1);
865    let o2 = index_to_value(state, index2);
866    state.equal_obj(None, &o1, &o2)
867}
868
869// PORT NOTE: LUA_OPUNM / LUA_OPBNOT are unary; all others are binary.
870pub fn arith(state: &mut LuaState, op: i32) -> Result<(), LuaError> {
871    // TODO(port): LUA_OPUNM and LUA_OPBNOT constant values not yet defined in
872    // Rust; using raw i32 comparison for now.
873    const LUA_OPUNM: i32 = 12;
874    const LUA_OPBNOT: i32 = 14;
875    if op == LUA_OPUNM || op == LUA_OPBNOT {
876        // unary — duplicate top as fake second operand
877        let top_val = state.get_at(state.top_idx() - 1);
878        state.push(top_val);
879    }
880    let top = state.top_idx();
881    let a = state.get_at(top - 2);
882    let b = state.get_at(top - 1);
883    let result = state.arith_op(op, &a, &b)?;
884    state.set_at(top - 2, result);
885    state.pop();
886    Ok(())
887}
888
889pub fn compare(state: &mut LuaState, index1: i32, index2: i32, op: i32) -> Result<bool, LuaError> {
890    let valid = is_valid_index(state, index1) && is_valid_index(state, index2);
891    let o1 = index_to_value(state, index1);
892    let o2 = index_to_value(state, index2);
893    if valid {
894        match op {
895            0 => Ok(state.equal_obj_with_tm(&o1, &o2)?),
896            1 => state.less_than(&o1, &o2),
897            2 => state.less_equal(&o1, &o2),
898            _ => {
899                debug_assert!(false, "invalid option");
900                Ok(false)
901            }
902        }
903    } else {
904        Ok(false)
905    }
906}
907
908pub fn string_to_number(state: &mut LuaState, s: &[u8]) -> usize {
909    // TODO(port): luaO_str2num not yet translated; push result if successful.
910    match state.str_to_num(s) {
911        Some((val, consumed)) => {
912            state.push(val);
913            consumed
914        }
915        None => 0,
916    }
917}
918
919pub fn to_number_x(state: &LuaState, idx: i32) -> Option<f64> {
920    let o = index_to_value(state, idx);
921    o.to_number_with_strconv()
922}
923
924pub fn to_integer_x(state: &LuaState, idx: i32) -> Option<i64> {
925    let o = index_to_value(state, idx);
926    o.to_integer_with_strconv()
927}
928
929pub fn to_boolean(state: &LuaState, idx: i32) -> bool {
930    let o = index_to_value(state, idx);
931    !matches!(o, LuaValue::Nil | LuaValue::Bool(false))
932}
933
934// PORT NOTE: returns Option<GcRef<LuaString>> instead of raw C pointer+len.
935pub fn to_lua_string(
936    state: &mut LuaState,
937    idx: i32,
938) -> Result<Option<GcRef<LuaString>>, LuaError> {
939    let o = index_to_value(state, idx);
940    if let LuaValue::Str(s) = &o {
941        return Ok(Some(s.clone()));
942    }
943    if !matches!(o, LuaValue::Int(_) | LuaValue::Float(_)) {
944        return Ok(None);
945    }
946    state.obj_to_string(idx)?;
947    state.gc().check_step();
948    let updated = index_to_value(state, idx);
949    if let LuaValue::Str(s) = updated {
950        Ok(Some(s))
951    } else {
952        Ok(None)
953    }
954}
955
956pub fn raw_len(state: &LuaState, idx: i32) -> u64 {
957    let o = index_to_value(state, idx);
958    match &o {
959        LuaValue::Str(s) => s.len() as u64,
960        LuaValue::UserData(u) => u.len() as u64,
961        LuaValue::Table(t) => state.table_getn(t) as u64,
962        _ => 0,
963    }
964}
965
966pub fn to_cfunction(
967    state: &LuaState,
968    idx: i32,
969) -> Option<fn(&mut LuaState) -> Result<usize, LuaError>> {
970    let o = index_to_value(state, idx);
971    match o {
972        // TODO(phase-b): lua-types `LuaClosure::LightC` carries a placeholder
973        // `fn() -> i32` until it can reference `LuaState`. The real cast
974        // happens once lua-types absorbs the LuaState-aware signature.
975        LuaValue::Function(LuaClosure::LightC(_f)) => None,
976        LuaValue::Function(LuaClosure::C(_ccl)) => None,
977        _ => None,
978    }
979}
980
981#[inline]
982fn to_userdata_ptr(o: &LuaValue) -> Option<*mut core::ffi::c_void> {
983    match o {
984        LuaValue::UserData(u) => {
985            // TODO(port): getudatamem returns a pointer to the raw byte payload of Udata.
986            // In Rust, LuaUserData carries a Box<[u8]>; we'd need to return a raw ptr.
987            // This is only safe inside lua-gc; stubbing with None for Phase A.
988            let _ = u;
989            None
990        }
991        LuaValue::LightUserData(p) => Some(*p),
992        _ => None,
993    }
994}
995
996pub fn to_userdata(state: &LuaState, idx: i32) -> Option<*mut core::ffi::c_void> {
997    let o = index_to_value(state, idx);
998    to_userdata_ptr(&o)
999}
1000
1001pub fn to_thread(state: &LuaState, idx: i32) -> Option<GcRef<lua_types::value::LuaThread>> {
1002    // TODO(phase-b): lua-vm's rich LuaState is not the same type as
1003    // lua_types::value::LuaThread; the latter is a placeholder. Resolve in
1004    // Phase B by unifying thread types.
1005    let o = index_to_value(state, idx);
1006    if let LuaValue::Thread(t) = o {
1007        Some(t)
1008    } else {
1009        None
1010    }
1011}
1012
1013// PORT NOTE: returns a usize (opaque identity) rather than a raw void*.
1014// Raw pointers are only allowed in lua-gc / lua-coro.
1015pub fn to_pointer(state: &LuaState, idx: i32) -> Option<usize> {
1016    let o = index_to_value(state, idx);
1017    // TODO(port): returning a raw pointer here is not safe outside lua-gc.
1018    // Returning the GC identity as a usize for opaque pointer identity purposes.
1019    match &o {
1020        LuaValue::Function(LuaClosure::LightC(f)) => Some(*f as usize),
1021        LuaValue::LightUserData(p) => Some(*p as usize),
1022        LuaValue::Str(s) => Some(GcRef::identity(s)),
1023        LuaValue::Table(t) => Some(GcRef::identity(t)),
1024        LuaValue::Function(LuaClosure::Lua(f)) => Some(GcRef::identity(f)),
1025        LuaValue::Function(LuaClosure::C(f)) => Some(GcRef::identity(f)),
1026        LuaValue::UserData(u) => Some(GcRef::identity(u)),
1027        LuaValue::Thread(t) => Some(GcRef::identity(t)),
1028        _ => None,
1029    }
1030}
1031
1032// ── push functions (Rust → stack) ────────────────────────────────────────────
1033
1034pub fn push_nil(state: &mut LuaState) {
1035    state.push(LuaValue::Nil);
1036}
1037
1038pub fn push_number(state: &mut LuaState, n: f64) {
1039    state.push(LuaValue::Float(n));
1040}
1041
1042pub fn push_integer(state: &mut LuaState, n: i64) {
1043    state.push(LuaValue::Int(n));
1044}
1045
1046// PORT NOTE: returns the interned LuaString instead of a raw C pointer.
1047pub fn push_lstring(state: &mut LuaState, s: &[u8]) -> Result<GcRef<LuaString>, LuaError> {
1048    let ts = state.intern_str(s)?;
1049    state.push(LuaValue::Str(ts.clone()));
1050    state.gc().check_step();
1051    Ok(ts)
1052}
1053
1054pub fn push_string(state: &mut LuaState, s: Option<&[u8]>) -> Result<Option<GcRef<LuaString>>, LuaError> {
1055    match s {
1056        None => {
1057            state.push(LuaValue::Nil);
1058            state.gc().check_step();
1059            Ok(None)
1060        }
1061        Some(bytes) => {
1062            let ts = state.intern_str(bytes)?;
1063            state.push(LuaValue::Str(ts.clone()));
1064            state.gc().check_step();
1065            Ok(Some(ts))
1066        }
1067    }
1068}
1069
1070// PORT NOTE: va_list is not representable in safe Rust; callers pass a pre-formatted &[u8].
1071// TODO(port): lua_pushvfstring uses C varargs (va_list); no direct Rust equivalent.
1072// The Rust API uses state.push_fstring(format_args!(...)) instead.
1073pub fn push_vfstring(state: &mut LuaState, formatted: &[u8]) -> Result<GcRef<LuaString>, LuaError> {
1074    let ts = state.intern_str(formatted)?;
1075    state.push(LuaValue::Str(ts.clone()));
1076    state.gc().check_step();
1077    Ok(ts)
1078}
1079
1080// PORT NOTE: C varargs not used; callers use format_args! and push_fstring.
1081pub fn push_fstring(state: &mut LuaState, formatted: &[u8]) -> Result<GcRef<LuaString>, LuaError> {
1082    push_vfstring(state, formatted)
1083}
1084
1085pub fn push_cclosure(
1086    state: &mut LuaState,
1087    f: fn(&mut LuaState) -> Result<usize, LuaError>,
1088    n: i32,
1089) -> Result<(), LuaError> {
1090    //    if (n == 0) { setfvalue(s2v(L->top.p), fn); api_incr_top(L); }
1091    //    else { api_checknelems(L, n); api_check(L, n <= MAXUPVAL, ...);
1092    //           cl = luaF_newCclosure(L, n); cl->f = fn;
1093    //           L->top.p -= n;
1094    //           while (n--) setobj2n(L, &cl->upvalue[n], s2v(L->top.p + n));
1095    //           setclCvalue(L, s2v(L->top.p), cl); api_incr_top(L);
1096    //           luaC_checkGC(L); }
1097    //    lua_unlock(L);
1098    //
1099    // PORT NOTE: `LuaClosure::LightC` and `LuaCClosure` carry a `LuaCFnPtr`
1100    // (a `usize` index into `GlobalState.c_functions`) rather than the raw
1101    // function pointer, because lua-types cannot reference `LuaState`. We
1102    // register `f` in the per-state registry and store the resulting index.
1103    let idx: lua_types::closure::LuaCFnPtr = {
1104        let mut g = state.global_mut();
1105        if n == 0 {
1106            match g.c_functions.iter().position(|existing| {
1107                existing
1108                    .as_bare()
1109                    .is_some_and(|existing| std::ptr::fn_addr_eq(existing, f))
1110            }) {
1111                Some(i) => i,
1112                None => {
1113                    let i = g.c_functions.len();
1114                    g.c_functions.push(LuaCallable::bare(f));
1115                    i
1116                }
1117            }
1118        } else {
1119            let i = g.c_functions.len();
1120            g.c_functions.push(LuaCallable::bare(f));
1121            i
1122        }
1123    };
1124    if n == 0 {
1125        state.push(LuaValue::Function(LuaClosure::LightC(idx)));
1126    } else {
1127        debug_assert!(n > 0 && (n as u32) <= MAX_UPVAL as u32, "upvalue index too large");
1128        let n_usize = n as usize;
1129        let top = state.top_idx();
1130        debug_assert!((top.0 as usize) >= n_usize, "not enough elements on stack");
1131        let base = top.0 as usize - n_usize;
1132        let mut upvalues: Vec<LuaValue> = Vec::with_capacity(n_usize);
1133        for i in 0..n_usize {
1134            upvalues.push(state.get_at(crate::state::StackIdx((base + i) as u32)));
1135        }
1136        state.pop_n(n_usize);
1137        // TODO(D-1c-bridge): state.new_c_closure is still todo!(); keep direct alloc
1138        let cl = LuaClosure::C(GcRef::new(lua_types::closure::LuaCClosure {
1139            func: idx,
1140            upvalues,
1141        }));
1142        state.push(LuaValue::Function(cl));
1143        state.gc().check_step();
1144    }
1145    Ok(())
1146}
1147
1148pub fn push_boolean(state: &mut LuaState, b: bool) {
1149    state.push(LuaValue::Bool(b));
1150}
1151
1152pub fn push_light_userdata(state: &mut LuaState, p: *mut core::ffi::c_void) {
1153    state.push(LuaValue::LightUserData(p));
1154}
1155
1156// Returns true if pushed thread is the main thread.
1157pub fn push_thread(state: &mut LuaState) -> bool {
1158    let (value, is_main) = {
1159        let g = state.global();
1160        let id = g.current_thread_id;
1161        let v = g
1162            .thread_value_for(id)
1163            .expect("current_thread_id must always resolve to a registered thread");
1164        (v, id == g.main_thread_id)
1165    };
1166    state.push(LuaValue::Thread(value));
1167    is_main
1168}
1169
1170// ── get functions (Lua → stack) ───────────────────────────────────────────────
1171
1172fn aux_get_str(state: &mut LuaState, t: LuaValue, k: &[u8]) -> Result<LuaType, LuaError> {
1173    let str_val = {
1174        let ts = state.intern_str(k)?;
1175        LuaValue::Str(ts)
1176    };
1177    // TODO(port): luaV_fastget / luaV_finishget not yet translated; using
1178    // a simplified table_get that may miss metamethod chains.
1179    let result = state.table_get_with_tm(&t, &str_val)?;
1180    state.push(result);
1181    let top = state.top_idx();
1182    Ok(state.get_at(top - 1).base_type())
1183}
1184
1185fn get_global_table(state: &LuaState) -> LuaValue {
1186    // PORT NOTE (phase-b-reconcile): The lua-types LuaTable placeholder has
1187    // no storage, so we cannot fetch the globals table from the registry's
1188    // array slot. init_registry now stashes globals in a direct
1189    // GlobalState field; read it from there until the LuaTable placeholder
1190    // reconciles with lua-vm::table::LuaTable.
1191    state.global().globals.clone()
1192}
1193
1194pub fn get_global(state: &mut LuaState, name: &[u8]) -> Result<LuaType, LuaError> {
1195    let g = get_global_table(state);
1196    aux_get_str(state, g, name)
1197}
1198
1199pub fn get_table(state: &mut LuaState, idx: i32) -> Result<LuaType, LuaError> {
1200    let t = index_to_value(state, idx);
1201    let top = state.top_idx();
1202    let key = state.get_at(top - 1);
1203    let result = state.table_get_with_tm(&t, &key)?;
1204    state.set_at(top - 1, result);
1205    let val = state.get_at(top - 1);
1206    Ok(val.base_type())
1207}
1208
1209pub fn get_field(state: &mut LuaState, idx: i32, k: &[u8]) -> Result<LuaType, LuaError> {
1210    let t = index_to_value(state, idx);
1211    aux_get_str(state, t, k)
1212}
1213
1214pub fn get_i(state: &mut LuaState, idx: i32, n: i64) -> Result<LuaType, LuaError> {
1215    let t = index_to_value(state, idx);
1216    let key = LuaValue::Int(n);
1217    let result = state.table_get_with_tm(&t, &key)?;
1218    state.push(result);
1219    let top = state.top_idx();
1220    Ok(state.get_at(top - 1).base_type())
1221}
1222
1223/// Variant of `get_i` that accepts a pre-resolved table value instead of a
1224/// stack index. Callers that invoke `get_i` repeatedly on the same table
1225/// (e.g. the shift loops in `table.remove` / `table.insert`) should resolve
1226/// the table once and use this function to avoid calling `index_to_value`
1227/// on every iteration.
1228pub fn get_i_value(state: &mut LuaState, t: &LuaValue, n: i64) -> Result<LuaType, LuaError> {
1229    let key = LuaValue::Int(n);
1230    let result = state.table_get_with_tm(t, &key)?;
1231    state.push(result);
1232    let top = state.top_idx();
1233    Ok(state.get_at(top - 1).base_type())
1234}
1235
1236fn finish_raw_get(state: &mut LuaState, val: Option<LuaValue>) -> LuaType {
1237    let v = val.unwrap_or(LuaValue::Nil);
1238    state.push(v);
1239    let top = state.top_idx();
1240    state.get_at(top - 1).base_type()
1241}
1242
1243fn get_table_value(state: &LuaState, idx: i32) -> Option<GcRef<LuaTable>> {
1244    let t = index_to_value(state, idx);
1245    debug_assert!(matches!(t, LuaValue::Table(_)), "table expected");
1246    if let LuaValue::Table(tbl) = t {
1247        Some(tbl)
1248    } else {
1249        None
1250    }
1251}
1252
1253pub fn raw_get(state: &mut LuaState, idx: i32) -> LuaType {
1254    let t = get_table_value(state, idx);
1255    let top = state.top_idx();
1256    let key = state.get_at(top - 1);
1257    let val = t.as_ref().map(|tbl| tbl.get(&key));
1258    state.set_top_idx(top - 1);
1259    finish_raw_get(state, val)
1260}
1261
1262pub fn raw_get_i(state: &mut LuaState, idx: i32, n: i64) -> LuaType {
1263    let t = get_table_value(state, idx);
1264    let val = t.as_ref().map(|tbl| tbl.get_int(n));
1265    finish_raw_get(state, val)
1266}
1267
1268pub fn raw_get_p(state: &mut LuaState, idx: i32, p: *const core::ffi::c_void) -> LuaType {
1269    let t = get_table_value(state, idx);
1270    let key = LuaValue::LightUserData(p as *mut core::ffi::c_void);
1271    let val = t.as_ref().map(|tbl| tbl.get(&key));
1272    finish_raw_get(state, val)
1273}
1274
1275pub fn create_table(state: &mut LuaState, narray: i32, nrec: i32) -> Result<(), LuaError> {
1276    let t = state.new_table();
1277    if narray > 0 || nrec > 0 {
1278        t.resize(state, narray as usize, nrec as usize)?;
1279    }
1280    state.push(LuaValue::Table(t));
1281    state.gc().check_step();
1282    Ok(())
1283}
1284
1285pub fn get_metatable(state: &mut LuaState, objindex: i32) -> bool {
1286    let obj = index_to_value(state, objindex);
1287    let mt: Option<GcRef<LuaTable>> = match &obj {
1288        LuaValue::Table(t) => t.metatable(),
1289        LuaValue::UserData(u) => u.metatable(),
1290        other => {
1291            let idx = other.base_type() as usize;
1292            state.global().mt[idx].clone()
1293        }
1294    };
1295    if let Some(mt_table) = mt {
1296        state.push(LuaValue::Table(mt_table));
1297        true
1298    } else {
1299        false
1300    }
1301}
1302
1303pub fn get_i_uservalue(state: &mut LuaState, idx: i32, n: i32) -> LuaType {
1304    let o = index_to_value(state, idx);
1305    debug_assert!(matches!(o, LuaValue::UserData(_)), "full userdata expected");
1306    if let LuaValue::UserData(ref u) = o {
1307        let uv_count = u.uv.len() as i32;
1308        if n <= 0 || n > uv_count {
1309            state.push(LuaValue::Nil);
1310            LuaType::None
1311        } else {
1312            let val = u.uv[(n - 1) as usize].clone();
1313            let t = val.base_type();
1314            state.push(val);
1315            t
1316        }
1317    } else {
1318        state.push(LuaValue::Nil);
1319        LuaType::None
1320    }
1321}
1322
1323// ── set functions (stack → Lua) ───────────────────────────────────────────────
1324
1325fn aux_set_str(state: &mut LuaState, t: LuaValue, k: &[u8]) -> Result<(), LuaError> {
1326    let str_val = {
1327        let ts = state.intern_str(k)?;
1328        LuaValue::Str(ts)
1329    };
1330    //       luaV_finishfastset(L, t, slot, s2v(L->top.p - 1)); L->top.p--;
1331    //    else { setsvalue2s L->top.p str; api_incr_top;
1332    //           luaV_finishset(L, t, s2v(L->top.p-1), s2v(L->top.p-2), slot);
1333    //           L->top.p -= 2; }
1334    let top = state.top_idx();
1335    let val = state.get_at(top - 1);
1336    state.table_set_with_tm(&t, str_val, val)?;
1337    state.pop();
1338    Ok(())
1339}
1340
1341pub fn set_global(state: &mut LuaState, name: &[u8]) -> Result<(), LuaError> {
1342    let g = get_global_table(state);
1343    aux_set_str(state, g, name)
1344}
1345
1346pub fn set_table(state: &mut LuaState, idx: i32) -> Result<(), LuaError> {
1347    let t = index_to_value(state, idx);
1348    let top = state.top_idx();
1349    let key = state.get_at(top - 2);
1350    let val = state.get_at(top - 1);
1351    state.table_set_with_tm(&t, key, val)?;
1352    state.set_top_idx(top - 2);
1353    Ok(())
1354}
1355
1356pub fn set_field(state: &mut LuaState, idx: i32, k: &[u8]) -> Result<(), LuaError> {
1357    let t = index_to_value(state, idx);
1358    aux_set_str(state, t, k)
1359}
1360
1361pub fn set_i(state: &mut LuaState, idx: i32, n: i64) -> Result<(), LuaError> {
1362    let t = index_to_value(state, idx);
1363    let top = state.top_idx();
1364    let val = state.get_at(top - 1);
1365    let key = LuaValue::Int(n);
1366    state.table_set_with_tm(&t, key, val)?;
1367    state.pop();
1368    Ok(())
1369}
1370
1371/// Variant of `set_i` that accepts a pre-resolved table value instead of a
1372/// stack index. Callers that invoke `set_i` repeatedly on the same table
1373/// (e.g. the shift loops in `table.remove` / `table.insert`) should resolve
1374/// the table once and use this function to avoid calling `index_to_value`
1375/// on every iteration.
1376pub fn set_i_value(state: &mut LuaState, t: &LuaValue, n: i64) -> Result<(), LuaError> {
1377    let top = state.top_idx();
1378    let val = state.get_at(top - 1);
1379    let key = LuaValue::Int(n);
1380    state.table_set_with_tm(t, key, val)?;
1381    state.pop();
1382    Ok(())
1383}
1384
1385fn aux_raw_set(state: &mut LuaState, idx: i32, key: LuaValue, n: u32) -> Result<(), LuaError> {
1386    let t = get_table_value(state, idx)
1387        .ok_or_else(|| LuaError::runtime(format_args!("table expected")))?;
1388    let top = state.top_idx();
1389    let val = state.get_at(top - 1);
1390    t.raw_set(state, key, val)?;
1391    t.invalidate_tm_cache();
1392    let top_val = state.get_at(top - 1);
1393    state.gc().barrier_back(&t, &top_val);
1394    state.set_top_idx(top - n as i32);
1395    Ok(())
1396}
1397
1398pub fn raw_set(state: &mut LuaState, idx: i32) -> Result<(), LuaError> {
1399    let top = state.top_idx();
1400    let key = state.get_at(top - 2);
1401    aux_raw_set(state, idx, key, 2)
1402}
1403
1404pub fn raw_set_p(state: &mut LuaState, idx: i32, p: *const core::ffi::c_void) -> Result<(), LuaError> {
1405    let key = LuaValue::LightUserData(p as *mut core::ffi::c_void);
1406    aux_raw_set(state, idx, key, 1)
1407}
1408
1409pub fn raw_set_i(state: &mut LuaState, idx: i32, n: i64) -> Result<(), LuaError> {
1410    let t = get_table_value(state, idx)
1411        .ok_or_else(|| LuaError::runtime(format_args!("table expected")))?;
1412    let top = state.top_idx();
1413    let val = state.get_at(top - 1);
1414    t.raw_set_int(state, n, val)?;
1415    let top_val = state.get_at(top - 1);
1416    state.gc().barrier_back(&t, &top_val);
1417    state.pop();
1418    Ok(())
1419}
1420
1421/// Returns true if `mt` (a metatable) holds a non-nil `__gc` entry.
1422///
1423/// PORT NOTE: Mirrors the body of C's `tofinalize` in `lgc.c` minus the bits
1424/// that consult per-object GC bits (irrelevant in Phase B's Rc world).
1425fn metatable_has_gc(state: &LuaState, mt: &GcRef<LuaTable>) -> bool {
1426    let name = state.global().tmname[crate::tagmethods::TagMethod::Gc as usize].clone();
1427    !matches!(mt.get_short_str(&name), LuaValue::Nil)
1428}
1429
1430/// Pin `tbl` in `pending_finalizers` if not already present.
1431fn register_finalizable_table(state: &mut LuaState, tbl: &GcRef<LuaTable>) {
1432    let already = state
1433        .global()
1434        .pending_finalizers
1435        .iter()
1436        .any(|t| GcRef::ptr_eq(t, tbl));
1437    if !already {
1438        state.global_mut().pending_finalizers.push(tbl.clone());
1439    }
1440}
1441
1442/// Phase-B `__gc` driver.
1443///
1444/// Scans `pending_finalizers` for tables whose only strong ref is the list
1445/// itself (`Rc::strong_count == 1`), runs their `__gc` metamethod in a
1446/// protected call, then drops the list's pin so the table can be freed.
1447/// Iterates in reverse so the most-recently registered finalizers run first,
1448/// matching C-Lua's order (`finobj` is a LIFO stack).
1449///
1450/// PORT NOTE: This stands in for C-Lua's `GCSatomic` finalizer-promotion step
1451/// plus `GCTM`. The real GC walks the heap to decide which `finobj` entries
1452/// are unreachable; in Phase B we use the `Rc` strong-count as the proxy.
1453/// Replaced by `lua_gc::run_pending_finalizers` when Phase D's incremental
1454/// GC lands.
1455pub fn run_pending_finalizers(state: &mut LuaState) {
1456    let mut did_run = false;
1457    loop {
1458        // `to_be_finalized` was populated by the most recent
1459        // `collect_via_heap` mark phase. Drain in LIFO order so the most
1460        // recently dead object runs its `__gc` first — matches C-Lua's
1461        // `finobj` stack ordering.
1462        let target_idx = {
1463            let to_fin = &state.global().to_be_finalized;
1464            if to_fin.is_empty() { None } else { Some(to_fin.len() - 1) }
1465        };
1466        let Some(i) = target_idx else { break; };
1467        // The Phase-A pre-finalizer weak-value sweep (mirroring C-Lua's
1468        // `clearbyvalues(g, g->weak, NULL)` from `atomic()`) is no longer
1469        // needed: under D-2, weak-table sweeping runs inside the post-mark
1470        // hook of `Heap::full_collect_with_post_mark`, which uses
1471        // reachability instead of strong_count and therefore clears such
1472        // entries BEFORE this finalizer pass runs. The full "bug-in-5.1"
1473        // ordering (finalizer-visible state) still requires reachability-
1474        // based detection of which finalizable tables are about to die — a
1475        // gap tracked under D-2 ephemeron/finalizer follow-up.
1476        let tbl = state.global_mut().to_be_finalized.swap_remove(i);
1477        let mt = tbl.metatable();
1478        let gc_fn = match mt {
1479            Some(ref m) => {
1480                let name = state.global().tmname[crate::tagmethods::TagMethod::Gc as usize].clone();
1481                m.get_short_str(&name)
1482            }
1483            None => LuaValue::Nil,
1484        };
1485        if !matches!(gc_fn, LuaValue::Function(_)) {
1486            continue;
1487        }
1488        did_run = true;
1489        let saved_top = state.top_idx();
1490        let ci_top = state.current_call_info().top;
1491        if saved_top.0 < ci_top.0 {
1492            state.clear_stack_range(saved_top, ci_top);
1493            state.set_top(ci_top);
1494        }
1495        state.push(gc_fn);
1496        state.push(LuaValue::Table(tbl));
1497        let func_idx = state.top_idx() - 2;
1498        let _heap_guard = {
1499            let g = state.global.borrow();
1500            lua_gc::HeapGuard::push(&g.heap)
1501        };
1502        let old_allowhook = state.allowhook;
1503        let old_gcstp = state.global_mut().stop_gc_internal();
1504        state.allowhook = false;
1505        let caller_ci = state.ci;
1506        let caller_status = state.get_ci(caller_ci).callstatus;
1507        state.get_ci_mut(caller_ci).callstatus = caller_status | crate::state::CIST_FIN;
1508        let _ = crate::do_::pcall(
1509            state,
1510            |s| s.call_no_yield(func_idx, 0),
1511            func_idx,
1512            0,
1513        );
1514        state.get_ci_mut(caller_ci).callstatus = caller_status;
1515        state.allowhook = old_allowhook;
1516        state.global_mut().set_gc_stop_flags(old_gcstp);
1517        state.set_top(saved_top);
1518    }
1519    // Post-finalizer weak sweep is also obsolete: any weak entries newly
1520    // exposed by the finalizer pass will be cleared on the NEXT
1521    // `Heap::full_collect_with_post_mark`. We accept the one-cycle lag.
1522    let _ = did_run;
1523}
1524
1525/// Run every still-pending `__gc` finalizer at state close.
1526///
1527/// Mirrors C-Lua's `luaC_freeallobjects` (`lgc.c`), which calls
1528/// `separatetobefnz(g, 1)` to move *all* remaining finalizable objects
1529/// (regardless of reachability) into the to-be-finalized list, then
1530/// `callallpendingfinalizers` to invoke each `__gc` before the objects are
1531/// freed. At `lua_close`, objects the program kept alive to program end —
1532/// e.g. a table held by a global — still have their finalizer run; that is
1533/// what emits messages like `>>> closing state <<<` from `gc.lua`.
1534///
1535/// Phase-B note: the live registry of finalizable objects is
1536/// `pending_finalizers`. A single snapshot of that list is promoted into
1537/// `to_be_finalized` and drained by [`run_pending_finalizers`]. We snapshot
1538/// once (matching C's single `separatetobefnz` call): a finalizer may
1539/// resurrect its object or register new finalizables via `setmetatable`, but
1540/// C does not re-finalize those at close (`gcstp = GCSTPCLS`), so neither do
1541/// we — the freshly-registered entries are left in `pending_finalizers` and
1542/// simply dropped with the state.
1543pub fn run_close_finalizers(state: &mut LuaState) {
1544    let pending: Vec<GcRef<lua_types::value::LuaTable>> =
1545        std::mem::take(&mut state.global_mut().pending_finalizers);
1546    if pending.is_empty() {
1547        return;
1548    }
1549    let mut seen = std::collections::HashSet::<usize>::new();
1550    {
1551        let mut g = state.global_mut();
1552        for tbl in pending {
1553            if seen.insert(tbl.identity()) {
1554                g.to_be_finalized.push(tbl);
1555            }
1556        }
1557    }
1558    run_pending_finalizers(state);
1559}
1560
1561/// Snapshot the currently-live weak tables from
1562/// `GlobalState.weak_tables_registry`, deduplicating by Rc pointer and
1563/// dropping any whose backing storage has been freed. Used by both the
1564/// pre-finalizer and post-finalizer sweeps in [`run_pending_finalizers`]
1565/// and by the explicit `collectgarbage("collect")` path.
1566fn collect_live_weak_tables(state: &mut LuaState) -> Vec<GcRef<lua_types::value::LuaTable>> {
1567    let mut g = state.global_mut();
1568    g.weak_tables_registry.retain(|w| w.strong_count() > 0);
1569    let mut seen = std::collections::HashSet::<usize>::new();
1570    g.weak_tables_registry
1571        .iter()
1572        .filter_map(|w| w.upgrade())
1573        .filter_map(|rc| {
1574            let id = rc.identity();
1575            if seen.insert(id) {
1576                Some(rc)
1577            } else {
1578                None
1579            }
1580        })
1581        .collect()
1582}
1583
1584pub fn set_metatable(state: &mut LuaState, objindex: i32) -> Result<bool, LuaError> {
1585    let top = state.top_idx();
1586    let mt_val = state.get_at(top - 1);
1587    let mt: Option<GcRef<LuaTable>> = if matches!(mt_val, LuaValue::Nil) {
1588        None
1589    } else {
1590        debug_assert!(matches!(mt_val, LuaValue::Table(_)), "table expected");
1591        if let LuaValue::Table(t) = mt_val {
1592            Some(t)
1593        } else {
1594            None
1595        }
1596    };
1597
1598    let obj = index_to_value(state, objindex);
1599    match obj {
1600        LuaValue::Table(ref tbl) => {
1601            if mt.is_some() {
1602                state.gc().obj_barrier(tbl, mt.as_ref().unwrap());
1603            }
1604            tbl.set_metatable(mt.clone());
1605            if tbl.weak_mode() != 0 {
1606                state
1607                    .global_mut()
1608                    .weak_tables_registry
1609                    .push(tbl.downgrade());
1610            }
1611            // Phase-B finalizer registration: if the new metatable carries
1612            // `__gc` and `obj` was not already registered, pin `obj` in the
1613            // pending-finalizers list so that `run_pending_finalizers` can
1614            // invoke the finalizer before the object is freed.
1615            if let Some(ref mt_table) = mt {
1616                if metatable_has_gc(state, mt_table) {
1617                    register_finalizable_table(state, tbl);
1618                }
1619            }
1620        }
1621        LuaValue::UserData(ref ud) => {
1622            if let Some(ref mt_table) = mt {
1623                state.gc().obj_barrier(ud, mt_table);
1624                // TODO(port): luaC_checkfinalizer
1625            }
1626            ud.set_metatable(mt);
1627        }
1628        ref other => {
1629            let idx = other.base_type() as usize;
1630            state.global_mut().mt[idx] = mt;
1631        }
1632    }
1633    state.pop();
1634    Ok(true)
1635}
1636
1637pub fn set_i_uservalue(state: &mut LuaState, idx: i32, n: i32) -> Result<bool, LuaError> {
1638    let o = index_to_value(state, idx);
1639    debug_assert!(matches!(o, LuaValue::UserData(_)), "full userdata expected");
1640    let top = state.top_idx();
1641    let val = state.get_at(top - 1);
1642    let res = if let LuaValue::UserData(ref ud) = o {
1643        let nuvalue = ud.uv.len() as i32;
1644        if n < 1 || n > nuvalue {
1645            false
1646        } else {
1647            // TODO(port): LuaUserData uv field needs interior mutability for write
1648            // ud.uv[(n - 1) as usize] = val.clone();
1649            state.gc().barrier_back(ud, &val);
1650            let _ = (n, ud);
1651            true
1652        }
1653    } else {
1654        false
1655    };
1656    state.pop();
1657    Ok(res)
1658}
1659
1660// ── load/call functions ───────────────────────────────────────────────────────
1661
1662//                            lua_KContext ctx, lua_KFunction k)
1663pub fn call_k(
1664    state: &mut LuaState,
1665    nargs: i32,
1666    nresults: i32,
1667    ctx: isize,
1668    k: Option<fn(&mut LuaState, i32, isize) -> Result<usize, LuaError>>,
1669) -> Result<(), LuaError> {
1670    let top = state.top_idx();
1671    let func_idx = top - (nargs + 1);
1672    //      L->ci->u.c.k = k; L->ci->u.c.ctx = ctx;
1673    //      luaD_call(L, func, nresults);
1674    //    } else {
1675    //      luaD_callnoyield(L, func, nresults);
1676    //    }
1677    if k.is_some() && state.is_yieldable() {
1678        let ci_idx = state.ci;
1679        {
1680            let ci = state.get_ci_mut(ci_idx);
1681            ci.set_u_c_k(k);
1682            ci.set_u_c_ctx(ctx);
1683        }
1684        state.call_at(func_idx, nresults)?;
1685    } else {
1686        state.call_no_yield(func_idx, nresults)?;
1687    }
1688    state.adjust_results(nresults);
1689    Ok(())
1690}
1691
1692//                            lua_KContext ctx, lua_KFunction k)
1693pub fn pcall_k(
1694    state: &mut LuaState,
1695    nargs: i32,
1696    nresults: i32,
1697    errfunc: i32,
1698    ctx: isize,
1699    k: Option<fn(&mut LuaState, i32, isize) -> Result<usize, LuaError>>,
1700) -> Result<LuaStatus, LuaError> {
1701    // Phase D-1c: activate the heap for the duration of this protected call.
1702    // GcRef::new (post D-1e) and any future allocator-aware code will route
1703    // through state.global.heap via with_current_heap(...). Stacked so nested
1704    // pcalls inside the same thread don't clobber each other.
1705    let _heap_guard = {
1706        let g = state.global.borrow();
1707        // The HeapGuard borrows &Heap; we let it live for the function scope.
1708        // The borrow of `g` is dropped immediately; the guard's NonNull
1709        // outlives it (the heap field is pinned inside GlobalState which
1710        // is Rc-managed and won't move).
1711        lua_gc::HeapGuard::push(&g.heap)
1712    };
1713    let err_handler_idx: isize = if errfunc == 0 {
1714        0
1715    } else {
1716        let o = index_to_stack_idx(state, errfunc);
1717        debug_assert!(
1718            matches!(state.get_at(o), LuaValue::Function(_)),
1719            "error handler must be a function"
1720        );
1721        o.0 as isize
1722    };
1723    let top = state.top_idx();
1724    let func_idx = top - (nargs + 1);
1725    if k.is_none() || !state.is_yieldable() {
1726        state.protected_call_raw(func_idx, nresults, StackIdx(err_handler_idx as u32))?;
1727        state.adjust_results(nresults);
1728        return Ok(LuaStatus::Ok);
1729    }
1730    // Yieldable continuation path: arrange for an interrupted call (yield or
1731    // recoverable error) to be resumable. The call is already protected by
1732    // `lua_resume`; real errors must propagate with CIST_YPCALL still set so
1733    // `precover` can run `finish_pcallk`.
1734    //
1735    let ci_idx = state.ci;
1736    let allow = state.allowhook;
1737    let saved_errfunc = state.errfunc;
1738    {
1739        let ci = state.get_ci_mut(ci_idx);
1740        ci.set_u_c_k(k);
1741        ci.set_u_c_ctx(ctx);
1742        ci.set_u2_funcidx(func_idx.0 as i32);
1743        ci.set_u_c_old_errfunc(saved_errfunc);
1744        ci.set_oah(allow);
1745        ci.callstatus |= crate::state::CIST_YPCALL;
1746    }
1747    state.errfunc = err_handler_idx;
1748    let call_result = crate::do_::call(state, func_idx, nresults);
1749    match call_result {
1750        Ok(()) => {
1751            //    L->errfunc = ci->u.c.old_errfunc;
1752            //    status = LUA_OK;
1753            state.get_ci_mut(ci_idx).callstatus &= !crate::state::CIST_YPCALL;
1754            state.errfunc = saved_errfunc;
1755            state.adjust_results(nresults);
1756            Ok(LuaStatus::Ok)
1757        }
1758        Err(crate::state::LuaError::Yield) => {
1759            // Yield must propagate up to lua_resume. The recovery prep stays
1760            // on `ci_idx` so that on resume, `finishCcall` will call
1761            // `finishpcallk` followed by the continuation `k`.
1762            Err(crate::state::LuaError::Yield)
1763        }
1764        Err(e) => {
1765            // Real errors take the same path as C longjmp: they unwind to
1766            // lua_resume's protected runner, which calls precover and then
1767            // finish_pcallk while this C frame still advertises CIST_YPCALL.
1768            Err(e)
1769        }
1770    }
1771}
1772
1773//                          const char *chunkname, const char *mode)
1774// PORT NOTE: lua_Reader (void* callback) is replaced by Box<dyn FnMut>; mode
1775// is &[u8].
1776pub fn load(
1777    state: &mut LuaState,
1778    reader: Box<dyn FnMut() -> Option<Vec<u8>>>,
1779    chunkname: Option<&[u8]>,
1780    mode: Option<&[u8]>,
1781) -> Result<LuaStatus, LuaError> {
1782    let name = chunkname.unwrap_or(b"?");
1783    let z = crate::zio::ZIO::new(reader);
1784    let status = state.protected_parser(z, name, mode);
1785    if status == LuaStatus::Ok {
1786        let top = state.top_idx();
1787        let func_val = state.get_at(top - 1);
1788        if let LuaValue::Function(LuaClosure::Lua(lcl)) = func_val {
1789            if !lcl.upvals.is_empty() {
1790                let gt = get_global_table(state);
1791                let uv = state.new_upval_closed(gt);
1792                lcl.set_upval(0, uv);
1793            }
1794        }
1795    }
1796    Ok(status)
1797}
1798
1799pub fn dump(
1800    state: &LuaState,
1801    writer: &mut dyn FnMut(&[u8]) -> Result<(), LuaError>,
1802    strip: bool,
1803) -> Result<bool, LuaError> {
1804    let top = state.top_idx();
1805    let o = state.get_at(top - 1);
1806    if let LuaValue::Function(LuaClosure::Lua(ref lcl)) = o {
1807        crate::dump::dump(state, &lcl.proto, writer, strip)?;
1808        Ok(true)
1809    } else {
1810        Ok(false)
1811    }
1812}
1813
1814pub fn status(state: &LuaState) -> LuaStatus {
1815    LuaStatus::from_raw(state.status as i32)
1816}
1817
1818// ── garbage collection ────────────────────────────────────────────────────────
1819
1820/// GC operation codes (C: LUA_GC* constants)
1821#[repr(i32)]
1822#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1823pub enum GcWhat {
1824    Stop = 0,
1825    Restart = 1,
1826    Collect = 2,
1827    Count = 3,
1828    CountB = 4,
1829    Step = 5,
1830    SetPause = 6,
1831    SetStepMul = 7,
1832    IsRunning = 9,
1833    Gen = 10,
1834    Inc = 11,
1835}
1836
1837// PORT NOTE: C varargs replaced by explicit GcArgs enum; callers supply parameters directly.
1838pub enum GcArgs {
1839    Stop,
1840    Restart,
1841    Collect,
1842    Count,
1843    CountB,
1844    Step { data: i32 },
1845    SetPause { value: i32 },
1846    SetStepMul { value: i32 },
1847    IsRunning,
1848    Gen { minormul: i32, majormul: i32 },
1849    Inc { pause: i32, stepmul: i32, stepsize: i32 },
1850}
1851
1852pub fn gc(state: &mut LuaState, args: GcArgs) -> i32 {
1853    if state.global().is_gc_stopped_internally() {
1854        return -1;
1855    }
1856    match args {
1857        GcArgs::Stop => {
1858            state.global_mut().set_gc_stop_user();
1859        }
1860        GcArgs::Restart => {
1861            {
1862                let mut g = state.global_mut();
1863                crate::state::set_debt(&mut *g, 0);
1864            }
1865            state.global_mut().clear_gc_stop();
1866        }
1867        GcArgs::Collect => {
1868            if !state.allowhook {
1869                return 0;
1870            }
1871            // Under D-2, weak-table sweep happens INSIDE the heap's
1872            // post-mark hook (see GcHandle::full_collect), driven by
1873            // reachability rather than strong_count. The standalone weak
1874            // sweep that used to run here would now be a no-op against an
1875            // already-clean state and is removed.
1876            state.gc().full_collect();
1877            // Phase-B: drain pending __gc finalizers for tables whose user
1878            // refs have all been dropped. Kept for legacy compat; runs
1879            // after the heap's collect so weak entries have been cleared.
1880            run_pending_finalizers(state);
1881            // PORT NOTE: Phase-B long-string accounting. Reclaim `gc_debt`
1882            // for any tracked long-string Rc whose strong count has dropped
1883            // to zero (either because the weak-table sweep above released
1884            // the last reference, or because the user dropped it directly).
1885            // Without this, `collectgarbage("count")` would report peak
1886            // allocation rather than live bytes — gc.lua's weak-string-key
1887            // block depends on the post-collect count being lower than the
1888            // pre-collect count.
1889            {
1890                let mut g = state.global_mut();
1891                crate::state::reclaim_dead_long_strings(&mut *g);
1892            }
1893            // PORT NOTE: Phase B has no per-allocation totalbytes tracking,
1894            // so total_bytes() only ever shrinks (each `Step` simulates
1895            // freed memory). Refill to a baseline here so subsequent Step
1896            // calls have headroom to actually drop count*1024 — the test
1897            // pattern `collectgarbage(); local x = gcinfo(); collectgarbage('step'); assert(gcinfo()<x)`
1898            // needs gcinfo to be high enough that decrementing by 1 KB is
1899            // observable. Removed in Phase D when real GC tracks bytes.
1900            {
1901                let mut g = state.global_mut();
1902                let target_tb = 32_768_isize;
1903                let cur_tb = g.totalbytes + g.gc_debt;
1904                if cur_tb < target_tb {
1905                    g.totalbytes += target_tb - cur_tb;
1906                }
1907            }
1908        }
1909        GcArgs::Count => {
1910            {
1911                let mut g = state.global_mut();
1912                crate::state::reclaim_dead_long_strings(&mut *g);
1913            }
1914            let g = state.global();
1915            let long_string_bytes: usize = g.gc_tracked_long_strings.iter().map(|(_, sz)| sz).sum();
1916            let total = g.heap.bytes_used() + long_string_bytes;
1917            return (total >> 10) as i32;
1918        }
1919        GcArgs::CountB => {
1920            {
1921                let mut g = state.global_mut();
1922                crate::state::reclaim_dead_long_strings(&mut *g);
1923            }
1924            let g = state.global();
1925            let long_string_bytes: usize = g.gc_tracked_long_strings.iter().map(|(_, sz)| sz).sum();
1926            let total = g.heap.bytes_used() + long_string_bytes;
1927            return (total & 0x3ff) as i32;
1928        }
1929        GcArgs::Step { data } => {
1930            let old_stp = {
1931                let mut g = state.global_mut();
1932                let old = g.gc_stop_flags();
1933                g.clear_gc_stop();
1934                old
1935            };
1936            // C-Lua converts `data` KiB of added debt into work units via
1937            // `stepmul`. We use a simpler mapping: the work-unit count is
1938            // `data * stepmul / 4` (stepmul is the user-tunable speed,
1939            // /4-encoded in `gcstepmul`), with a floor of 1 unit. When
1940            // `data == 0` the call still performs one basic step (matching
1941            // C-Lua's `luaC_step(L)` after `setdebt(g, 0)`).
1942            let stepmul = (state.global().gc_stepmul_param() as isize | 1).max(1);
1943            let work_units = if data == 0 {
1944                stepmul
1945            } else {
1946                let raw = (data as isize).saturating_mul(stepmul);
1947                raw.max(1)
1948            };
1949            if data == 0 {
1950                let mut g = state.global_mut();
1951                crate::state::set_debt(&mut *g, 0);
1952            } else {
1953                let debt = data as isize * 1024 + state.global().gc_debt();
1954                let mut g = state.global_mut();
1955                crate::state::set_debt(&mut *g, debt);
1956            }
1957            let cycle_complete = state.gc().incremental_step(work_units);
1958            if state.global().is_gen_mode() {
1959                state.gc().prune_weak_tables_mark_only();
1960            }
1961            state.global_mut().set_gc_stop_flags(old_stp);
1962            // Phase-B byte accounting: real allocation isn't tracked, so
1963            // simulate C-Lua's post-sweep totalbytes drop here. Halving
1964            // the current `tb` makes `gcinfo() < x` hold across a step
1965            // that completes a cycle (gc.lua `dosteps()` line 194), while
1966            // the floor at 1 KB preserves `set_debt`'s `tb > 0` invariant
1967            // across many back-to-back step calls.
1968            if cycle_complete {
1969                let mut g = state.global_mut();
1970                let floor: isize = 1024;
1971                let cur_tb = g.totalbytes + g.gc_debt;
1972                let new_tb = (cur_tb / 2).max(floor);
1973                if new_tb < cur_tb {
1974                    g.totalbytes -= cur_tb - new_tb;
1975                }
1976            }
1977            // Sync the global gcstate byte for `gc_at_pause()` callers.
1978            {
1979                let heap_state = state.global().heap.gc_state();
1980                let mut g = state.global_mut();
1981                g.gcstate = if heap_state.is_pause() { 0 } else { 1 };
1982            }
1983            return if cycle_complete { 1 } else { 0 };
1984        }
1985        GcArgs::SetPause { value } => {
1986            let old = state.global().gc_pause_param() as i32;
1987            state.global_mut().set_gc_pause_param(value as u8);
1988            return old;
1989        }
1990        GcArgs::SetStepMul { value } => {
1991            let old = state.global().gc_stepmul_param() as i32;
1992            state.global_mut().set_gc_stepmul_param(value as u8);
1993            return old;
1994        }
1995        GcArgs::IsRunning => {
1996            return state.global().gc_running() as i32;
1997        }
1998        GcArgs::Gen { minormul, majormul } => {
1999            let old_mode = if state.global().is_gen_mode() { 10i32 } else { 11i32 };
2000            if minormul != 0 {
2001                state.global_mut().genminormul = minormul as u8;
2002            }
2003            if majormul != 0 {
2004                state.global_mut().set_gc_genmajormul(majormul as u8);
2005            }
2006            state.gc().change_mode(crate::state::GcKind::Generational);
2007            return old_mode;
2008        }
2009        GcArgs::Inc { pause, stepmul, stepsize } => {
2010            let old_mode = if state.global().is_gen_mode() { 10i32 } else { 11i32 };
2011            if pause != 0 {
2012                state.global_mut().set_gc_pause_param(pause as u8);
2013            }
2014            if stepmul != 0 {
2015                state.global_mut().set_gc_stepmul_param(stepmul as u8);
2016            }
2017            if stepsize != 0 {
2018                state.global_mut().gcstepsize = stepsize as u8;
2019            }
2020            state.gc().change_mode(crate::state::GcKind::Incremental);
2021            return old_mode;
2022        }
2023    }
2024    0
2025}
2026
2027// ── miscellaneous functions ───────────────────────────────────────────────────
2028
2029// PORT NOTE: returns Result<Infallible, _> — semantically "always Err". The
2030// translator originally wrote `Result<!, _>` but the `!` type in a return
2031// position is still nightly-only as of Rust 1.93; Infallible is the stable
2032// stand-in. Callsites just pattern-match on Err.
2033pub fn lua_error(state: &mut LuaState) -> Result<Infallible, LuaError> {
2034    //      luaM_error(L);  /* memory error */
2035    //    else
2036    //      luaG_errormsg(L);  /* regular error */
2037    let top = state.top_idx();
2038    let errobj = state.get_at(top - 1);
2039    let is_mem_err = if let LuaValue::Str(ref s) = errobj {
2040        let memerr = state.global().memerrmsg.clone();
2041        GcRef::ptr_eq(s, &memerr)
2042    } else {
2043        false
2044    };
2045    if is_mem_err {
2046        Err(LuaError::Memory)
2047    } else {
2048        Err(LuaError::from_value(errobj))
2049    }
2050}
2051
2052pub fn next(state: &mut LuaState, idx: i32) -> Result<bool, LuaError> {
2053    let t = get_table_value(state, idx)
2054        .ok_or_else(|| LuaError::runtime(format_args!("table expected")))?;
2055    let top = state.top_idx();
2056    let key = state.get_at(top - 1);
2057    match t.next(key)? {
2058        Some((next_key, next_val)) => {
2059            state.set_at(top - 1, next_key);
2060            state.push(next_val);
2061            Ok(true)
2062        }
2063        None => {
2064            state.set_top_idx(top - 1);
2065            Ok(false)
2066        }
2067    }
2068}
2069
2070pub fn to_close(state: &mut LuaState, idx: i32) -> Result<(), LuaError> {
2071    let _level = index_to_stack_idx(state, idx);
2072    // TODO(port): luaF_newtbcupval and to-be-closed variable infrastructure
2073    // not yet translated. Stubbing for Phase A.
2074    Ok(())
2075}
2076
2077pub fn concat(state: &mut LuaState, n: i32) -> Result<(), LuaError> {
2078    if n > 0 {
2079        state.concat(n)?;
2080    } else {
2081        let empty = state.intern_str(b"")?;
2082        state.push(LuaValue::Str(empty));
2083    }
2084    state.gc().check_step();
2085    Ok(())
2086}
2087
2088pub fn len(state: &mut LuaState, idx: i32) -> Result<(), LuaError> {
2089    let t = index_to_value(state, idx);
2090    let result = state.obj_len(&t)?;
2091    state.push(result);
2092    Ok(())
2093}
2094
2095// PORT NOTE: The custom allocator hook is not exposed in the Rust-native API.
2096// Rust's allocator handles all allocation.
2097// These are intentionally omitted.
2098
2099pub fn set_warn_f(
2100    state: &mut LuaState,
2101    f: Option<Box<dyn FnMut(&[u8], bool)>>,
2102) {
2103    // PORT NOTE: ud_warn userdata is folded into the closure per types.tsv.
2104    state.global_mut().warnf = f;
2105}
2106
2107pub fn warning(state: &mut LuaState, msg: &[u8], tocont: bool) {
2108    state.emit_warning(msg, tocont);
2109}
2110
2111pub fn new_userdata_uv(
2112    state: &mut LuaState,
2113    size: usize,
2114    nuvalue: i32,
2115) -> Result<GcRef<LuaUserData>, LuaError> {
2116    debug_assert!(nuvalue >= 0 && nuvalue < u16::MAX as i32, "invalid value");
2117    let u = state.new_userdata(size, nuvalue as usize)?;
2118    state.push(LuaValue::UserData(u.clone()));
2119    state.gc().check_step();
2120    Ok(u)
2121}
2122
2123// ── upvalue access ────────────────────────────────────────────────────────────
2124
2125// PORT NOTE: Returns (name, value) instead of mutating output pointers. The name
2126// is returned as an owned Vec<u8> because Lua upvalue names live in the proto's
2127// LuaString table (GC heap), not in static storage.
2128fn aux_upvalue(
2129    state: &LuaState,
2130    fi: &LuaValue,
2131    n: i32,
2132) -> Option<(Vec<u8>, LuaValue)> {
2133    match fi {
2134        LuaValue::Function(LuaClosure::C(ccl)) => {
2135            let nupvalues = ccl.upvalues.len() as i32;
2136            if n < 1 || n > nupvalues {
2137                return None;
2138            }
2139            Some((Vec::new(), ccl.upvalues[(n - 1) as usize].clone()))
2140        }
2141        LuaValue::Function(LuaClosure::Lua(lcl)) => {
2142            let nupvalues = lcl.upvals.len() as i32;
2143            if n < 1 || n > nupvalues {
2144                return None;
2145            }
2146            let val = state.upvalue_get(lcl, (n - 1) as usize);
2147            // The proto records the static name of each upvalue (e.g. "_ENV"
2148            // for the main chunk's environment upvalue). Stripped chunks have
2149            // no upvalue-name debug info; Lua reports those as "(no name)".
2150            let name: Vec<u8> = lcl
2151                .proto
2152                .upvalues
2153                .get((n - 1) as usize)
2154                .and_then(|ud| ud.name.as_ref())
2155                .map(|s| s.as_bytes().to_vec())
2156                .unwrap_or_else(|| b"(no name)".to_vec());
2157            Some((name, val))
2158        }
2159        _ => None,
2160    }
2161}
2162
2163pub fn get_upvalue(state: &mut LuaState, funcindex: i32, n: i32) -> Option<Vec<u8>> {
2164    let fi = index_to_value(state, funcindex);
2165    if let Some((name, val)) = aux_upvalue(state, &fi, n) {
2166        state.push(val);
2167        Some(name)
2168    } else {
2169        None
2170    }
2171}
2172
2173pub fn setup_value(state: &mut LuaState, funcindex: i32, n: i32) -> Option<Vec<u8>> {
2174    let fi = index_to_value(state, funcindex);
2175    let (name, _) = aux_upvalue(state, &fi, n)?;
2176    let new_val = state.pop();
2177    match &fi {
2178        LuaValue::Function(LuaClosure::Lua(lcl)) => {
2179            state.upvalue_set(lcl, (n - 1) as usize, new_val).ok()?;
2180        }
2181        LuaValue::Function(LuaClosure::C(_ccl)) => {
2182            // TODO(port): C-closure upvalue writes need interior mutability on
2183            // LuaCClosure.upvalues. Not exercised by current tests.
2184            let _ = new_val;
2185        }
2186        _ => return None,
2187    }
2188    Some(name)
2189}
2190
2191// PORT NOTE: returns an index into the upvals vec rather than a pointer-to-pointer.
2192// Returns None if n is out of range.
2193fn get_upval_ref_idx(state: &LuaState, fidx: i32, n: i32) -> Option<usize> {
2194    let fi = index_to_value(state, fidx);
2195    debug_assert!(matches!(fi, LuaValue::Function(LuaClosure::Lua(_))), "Lua function expected");
2196    if let LuaValue::Function(LuaClosure::Lua(ref lcl)) = fi {
2197        let sizeupvalues = lcl.upvals.len() as i32;
2198        if n >= 1 && n <= sizeupvalues {
2199            Some((n - 1) as usize)
2200        } else {
2201            None
2202        }
2203    } else {
2204        None
2205    }
2206}
2207
2208// PORT NOTE: Returns Option<usize> identity instead of raw void*.
2209pub fn upvalue_id(state: &LuaState, fidx: i32, n: i32) -> Option<usize> {
2210    let fi = index_to_value(state, fidx);
2211    match &fi {
2212        LuaValue::Function(LuaClosure::Lua(lcl)) => {
2213            let idx = get_upval_ref_idx(state, fidx, n)?;
2214            // Return the identity of the UpVal GcRef
2215            Some(GcRef::identity(&lcl.upval(idx)))
2216        }
2217        LuaValue::Function(LuaClosure::C(ccl)) => {
2218            if n >= 1 && n <= ccl.upvalues.len() as i32 {
2219                // TODO(port): returning address of upvalue slot not possible without raw ptr.
2220                // Return a synthetic identity based on the closure's identity + n.
2221                Some(GcRef::identity(ccl) ^ (n as usize))
2222            } else {
2223                None
2224            }
2225        }
2226        LuaValue::Function(LuaClosure::LightC(_)) => None,
2227        _ => {
2228            debug_assert!(false, "function expected");
2229            None
2230        }
2231    }
2232}
2233
2234//                                               int fidx2, int n2)
2235pub fn upvalue_join(state: &mut LuaState, fidx1: i32, n1: i32, fidx2: i32, n2: i32) {
2236    let idx1 = match get_upval_ref_idx(state, fidx1, n1) {
2237        Some(i) => i,
2238        None => return,
2239    };
2240    let idx2 = match get_upval_ref_idx(state, fidx2, n2) {
2241        Some(i) => i,
2242        None => return,
2243    };
2244    let f1 = index_to_value(state, fidx1);
2245    let f2 = index_to_value(state, fidx2);
2246    if let (
2247        LuaValue::Function(LuaClosure::Lua(lcl1)),
2248        LuaValue::Function(LuaClosure::Lua(lcl2)),
2249    ) = (&f1, &f2)
2250    {
2251        let shared = lcl2.upval(idx2);
2252        lcl1.set_upval(idx1, shared);
2253    }
2254}
2255
2256// ──────────────────────────────────────────────────────────────────────────
2257// PORT STATUS
2258//   source:        src/lapi.c  (1464 lines, ~47 functions)
2259//   target_crate:  lua-vm
2260//   confidence:    low
2261//   todos:         18
2262//   port_notes:    8
2263//   unsafe_blocks: 0   (must be 0 outside explicit unsafe-budget crates)
2264//   notes:         Heavy use of interior mutability TODOs (GcRef writes for
2265//                  metatables, upvalue writes, userdata uv writes). The
2266//                  index2value helper returns cloned LuaValue not a pointer,
2267//                  so write-back paths that C achieves with TValue* are
2268//                  stubbed. Stack pointer arithmetic faithfully translated to
2269//                  StackIdx (u32) arithmetic. va_list functions (pushvfstring,
2270//                  pushfstring) replaced by &[u8] forwarders. lua_gc varargs
2271//                  replaced by explicit GcArgs enum. Raw pointer returns
2272//                  (topointer, touserdata, upvalueid) return Option<usize>
2273//                  identity values; actual *mut void only legal in lua-gc.
2274//                  lua_pushthread stubbed (needs self_gcref()), lua_xmove
2275//                  stubbed (split-borrow), upvalue_join stubbed (GcRef write).
2276//                  Phase B must wire up: state.grow_stack, state.call_no_yield,
2277//                  state.protected_call_raw, state.adjust_results,
2278//                  state.table_get_with_tm, state.table_set_with_tm,
2279//                  state.arith_op, state.concat, state.obj_len,
2280//                  state.obj_to_string, state.str_to_num, state.table_getn,
2281//                  state.registry_value, state.registry_get,
2282//                  GcRef::identity, GcRef::ptr_eq, GlobalState GC accessors.
2283// ──────────────────────────────────────────────────────────────────────────