Skip to main content

lua_stdlib/
base.rs

1//! Base library — Lua's built-in functions (`print`, `type`, `pairs`, `pcall`, …),
2//! a port of `lbaselib.c` covering Lua 5.1–5.5 from one source.
3//!
4//! GRADUATED (Phase-2 idiomatization, 2026-06-14, `idiom/base`). base is the
5//! most VM-adjacent stdlib module: `pcall`/`xpcall`/`error` drive unwinding,
6//! `load` compiles, `next`/`pairs`/`ipairs` iterate, `type`/`tostring`/`raw*`
7//! are hot. All of that plumbing is **load-bearing** and was idiomatized
8//! AROUND, never through — the only edits are in the cold arg-checking /
9//! result-shaping / version-dispatch / registration layers. The behavioral net
10//! that now guards it: `tests/base_strengthen.rs` (reference-pinned across all
11//! five versions), `multiversion_oracle`, the official `calls`/`errors`/
12//! `nextvar`/`constructs` suites, and `check.sh` ×5. Net-strengthening FIRST
13//! caught three cross-version bugs the weak net hid — `ipairs` (raw read +
14//! table-check + `__ipairs` on 5.1/5.2), `assert` (5.1/5.2 string-coercible
15//! message), `rawlen` (function-named, version-gated reject) — all fixed in the
16//! cold seam layer. Two bugs needing VM-internal changes were reported, not
17//! forced: `__name` honored pre-5.3 (lives in `obj_type_name_cow`) and the
18//! 5.1/5.2 `'?'`/`'_G.'` arg-error function-name resolution.
19
20use crate::state_stub::{LuaState, LuaStateStubExt as _};
21use lua_types::{closure::LuaClosure, error::LuaError, value::LuaValue, LuaStatus, LuaType};
22
23// ── Module-level constants ────────────────────────────────────────────────────
24
25/// ASCII whitespace characters used by `b_str2int` for strspn-style skipping.
26const SPACECHARS: &[u8] = b" \x0c\n\r\t\x0b";
27
28/// Reserved stack slot used by `generic_reader` to anchor the current chunk
29/// string so it is not collected while `lua_load` is running.
30const RESERVED_SLOT: i32 = 5;
31
32/// Name of the global environment table stored as a global itself.
33const LUA_GNAME: &[u8] = b"_G";
34
35/// Sentinel indicating "all return values" for call/pcall helpers.
36const LUA_MULTRET: i32 = -1;
37
38// ── GC operation codes ────────────────────────────────────────────────────────
39
40/// Identifies a GC control operation passed to the `collectgarbage` built-in.
41/// The discriminants are the integer codes the `lua-vm` GC API accepts.
42#[repr(i32)]
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44enum GcOp {
45    Stop = 0,
46    Restart = 1,
47    Collect = 2,
48    Count = 3,
49    #[expect(
50        dead_code,
51        reason = "ported stdlib helper; not yet wired into the runtime"
52    )]
53    CountB = 4,
54    Step = 5,
55    SetPause = 6,
56    SetStepMul = 7,
57    IsRunning = 9,
58    Gen = 10,
59    Inc = 11,
60    Param = 12,
61}
62
63// ── LuaState forward declaration ─────────────────────────────────────────────
64
65// LuaState is provided by crate::state_stub.
66
67// ── Type alias for standard Lua-callable functions ────────────────────────────
68
69/// Rust equivalent of `lua_CFunction`: a bare function that receives the
70/// interpreter state and returns a count of pushed results.
71pub(crate) type LuaLibFn = fn(&mut LuaState) -> Result<usize, LuaError>;
72
73// ── Helper: push_mode ─────────────────────────────────────────────────────────
74
75/// Push the GC mode string ("incremental" or "generational") onto the stack,
76/// or push `nil` (fail) when `oldmode == -1` (invalid call inside a finalizer).
77///
78fn push_mode(state: &mut LuaState, oldmode: i32) -> Result<usize, LuaError> {
79    if oldmode == -1 {
80        state.push(LuaValue::Nil);
81    } else {
82        let s: &[u8] = if oldmode == GcOp::Inc as i32 {
83            b"incremental"
84        } else {
85            b"generational"
86        };
87        state.push_string(s)?;
88    }
89    Ok(1)
90}
91
92/// Push the result of `collectgarbage("generational"|"incremental")`.
93///
94/// 5.4/5.5 return the previous mode as a STRING name (`"incremental"` /
95/// `"generational"`) via [`push_mode`]. 5.2 — the only pre-5.4 family that
96/// accepts these options — instead returns the previous mode as the INTEGER 0
97/// (`lua_pushinteger(L, lua_gc(...))` in lua5.2.4's `lbaselib.c`, where the GC
98/// mode is the integer constant `0`). The version that owns the running state
99/// selects the form.
100fn push_gc_mode(
101    state: &mut LuaState,
102    version: lua_types::LuaVersion,
103    oldmode: i32,
104) -> Result<usize, LuaError> {
105    if matches!(version, lua_types::LuaVersion::V52) {
106        state.push(LuaValue::Int(0));
107        return Ok(1);
108    }
109    push_mode(state, oldmode)
110}
111
112// ── Helper: finish_pcall ──────────────────────────────────────────────────────
113
114/// Shared result-adjustment logic for `pcall` and `xpcall`.
115///
116/// On success: returns the count of values already on the stack minus `extra`
117/// skipped sentinel values.  On failure: replaces whatever is on the stack
118/// with `[false, error_message]` and returns 2.
119///
120fn finish_pcall(state: &mut LuaState, ok: bool, extra: i32) -> Result<usize, LuaError> {
121    if !ok {
122        state.push(LuaValue::Bool(false));
123        state.push_copy(-2)?;
124        return Ok(2);
125    }
126    Ok((state.top() as i32 - extra) as usize)
127}
128
129// ── Helper: b_str2int ─────────────────────────────────────────────────────────
130
131/// Parse an integer in an arbitrary base from the byte slice `s`.
132///
133/// Returns `Some((consumed, value))` on success, where `consumed` is the number
134/// of bytes from the start of `s` that were processed (leading and trailing
135/// ASCII whitespace included).  Returns `None` when the slice contains no valid
136/// numeral in `base`.
137///
138/// The caller checks `consumed == s.len()` to verify the whole string was used.
139///
140fn b_str2int(s: &[u8], base: u32) -> Option<(usize, i64)> {
141    let mut pos = 0usize;
142    while pos < s.len() && SPACECHARS.contains(&s[pos]) {
143        pos += 1;
144    }
145    let neg = if pos < s.len() && s[pos] == b'-' {
146        pos += 1;
147        true
148    } else {
149        if pos < s.len() && s[pos] == b'+' {
150            pos += 1;
151        }
152        false
153    };
154    if pos >= s.len() || !s[pos].is_ascii_alphanumeric() {
155        return None;
156    }
157    let mut n: u64 = 0u64;
158    loop {
159        let byte = s[pos];
160        let digit = if byte.is_ascii_digit() {
161            (byte - b'0') as u32
162        } else {
163            (byte.to_ascii_uppercase() - b'A') as u32 + 10
164        };
165        if digit >= base {
166            return None;
167        }
168        n = n.wrapping_mul(base as u64).wrapping_add(digit as u64);
169        pos += 1;
170        if pos >= s.len() || !s[pos].is_ascii_alphanumeric() {
171            break;
172        }
173    }
174    while pos < s.len() && SPACECHARS.contains(&s[pos]) {
175        pos += 1;
176    }
177    let value: i64 = if neg {
178        0u64.wrapping_sub(n) as i64
179    } else {
180        n as i64
181    };
182    Some((pos, value))
183}
184
185// ── Helper: load_aux ──────────────────────────────────────────────────────────
186
187/// Shared post-load logic for `load` and `loadfile`.
188///
189/// On success (status_ok == true): optionally installs an environment upvalue,
190/// then returns 1 (the chunk function is on the stack).
191/// On failure: pushes nil then moves it before the error message, returns 2.
192///
193fn load_aux(state: &mut LuaState, status_ok: bool, envidx: i32) -> Result<usize, LuaError> {
194    if status_ok {
195        if envidx != 0 {
196            state.push_copy(envidx)?;
197            if state.set_upvalue(-2, 1)?.is_none() {
198                state.pop_n(1);
199            }
200        }
201        Ok(1)
202    } else {
203        state.push(LuaValue::Nil);
204        state.insert(-2)?;
205        Ok(2)
206    }
207}
208
209fn check_load_mode(state: &mut LuaState, idx: i32, default: &[u8]) -> Result<Vec<u8>, LuaError> {
210    let mode = state.opt_arg_string(idx, default)?;
211    if matches!(state.global().lua_version, lua_types::LuaVersion::V55) && mode.contains(&b'B') {
212        return Err(lua_vm::debug::arg_error_impl(state, idx, b"invalid mode"));
213    }
214    Ok(mode)
215}
216
217// ── print ─────────────────────────────────────────────────────────────────────
218
219/// Converts each argument to a string, separates them with tabs, writes them to
220/// standard output, and finishes with a newline.
221///
222/// The conversion mechanism is a genuine cross-version split:
223///
224/// - Lua 5.1/5.2/5.3 `luaB_print` fetch the **global** `tostring` and *call* it
225///   on each argument. Redefining global `tostring` therefore changes `print`,
226///   a `nil` global makes `print` raise `attempt to call a nil value`, and a
227///   result that is neither a string nor a coercible number raises
228///   `'tostring' must return a string to 'print'`.
229/// - Lua 5.4/5.5 `luaB_print` use `luaL_tolstring` directly: it honors the
230///   `__tostring` / `__name` metafields but ignores the global `tostring`.
231///
232pub(crate) fn print_fn(state: &mut LuaState) -> Result<usize, LuaError> {
233    let calls_global_tostring = matches!(
234        state.global().lua_version,
235        lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
236    );
237    if calls_global_tostring {
238        return print_via_global_tostring(state);
239    }
240    let n = state.top();
241    for i in 1..=n {
242        let bytes = state.to_display_string(i)?;
243        if i > 1 {
244            state.write_output(b"\t")?;
245        }
246        state.write_output(&bytes)?;
247        state.pop_n(1);
248    }
249    state.write_output(b"\n")?;
250    Ok(0)
251}
252
253/// Faithful port of the Lua 5.1/5.2/5.3 `luaB_print`: fetch the global
254/// `tostring` once, then call it on each argument.
255///
256fn print_via_global_tostring(state: &mut LuaState) -> Result<usize, LuaError> {
257    let n = state.top();
258    lua_vm::api::get_global(state, b"tostring")?;
259    for i in 1..=n {
260        state.push_copy(-1)?;
261        state.push_copy(i)?;
262        state.call(1, 1)?;
263        // lua_tolstring returns NULL for anything that is neither a string nor a
264        // coercible number; the reference raises in that case.
265        if !matches!(state.type_at(-1), LuaType::String | LuaType::Number) {
266            return Err(state.where_error(1, b"'tostring' must return a string to 'print'"));
267        }
268        let bytes = state
269            .to_lua_string_bytes(-1)
270            .expect("string/number coerces to bytes");
271        if i > 1 {
272            state.write_output(b"\t")?;
273        }
274        state.write_output(&bytes)?;
275        state.pop_n(1);
276    }
277    state.write_output(b"\n")?;
278    Ok(0)
279}
280
281// ── warn ──────────────────────────────────────────────────────────────────────
282
283/// Validates that every argument is a string, then forwards them as a
284/// multi-part warning message via the state's warning hook.
285///
286pub(crate) fn warn_fn(state: &mut LuaState) -> Result<usize, LuaError> {
287    let n = state.top();
288    state.check_arg_string(1)?;
289    for i in 2..=n {
290        state.check_arg_string(i)?;
291    }
292    for i in 1..n {
293        // Clone bytes before further mutation to avoid borrow conflict.
294        // PORTING.md §8: "No &LuaValue across a stack-mutating call."
295        let s: Vec<u8> = state
296            .to_lua_string_bytes(i)
297            .map(|b| b.to_vec())
298            .unwrap_or_default();
299        // continue = true (1) — more parts follow
300        state.warning(&s, true)?;
301    }
302    let s: Vec<u8> = state
303        .to_lua_string_bytes(n)
304        .map(|b| b.to_vec())
305        .unwrap_or_default();
306    state.warning(&s, false)?;
307    Ok(0)
308}
309
310// ── tonumber ──────────────────────────────────────────────────────────────────
311
312/// Converts a value to a number, optionally in a given numeric base (2–36).
313///
314pub(crate) fn tonumber_fn(state: &mut LuaState) -> Result<usize, LuaError> {
315    if matches!(state.type_at(2), LuaType::None | LuaType::Nil) {
316        if state.type_at(1) == LuaType::Number {
317            lua_vm::api::set_top(state, 1)?;
318            return Ok(1);
319        }
320        // lua_stringtonumber returns bytes consumed including the NUL terminator,
321        // so success iff consumed == string_length + 1.
322        if let Some(len) = state.to_lua_string_len(1) {
323            if let Some(consumed) = state.string_to_number(1) {
324                if consumed == len + 1 {
325                    return Ok(1);
326                }
327            }
328        }
329        state.check_arg_any(1)?;
330    } else {
331        let base = state.check_arg_integer(2)?;
332        state.check_arg_type(1, LuaType::String)?;
333        // Clone before further state ops (PORTING.md §8).
334        let bytes: Vec<u8> = state
335            .to_lua_string_bytes(1)
336            .map(|b| b.to_vec())
337            .unwrap_or_default();
338        if !(2..=36).contains(&base) {
339            return Err(lua_vm::debug::arg_error_impl(
340                state,
341                2,
342                b"base out of range",
343            ));
344        }
345        if let Some((consumed, n)) = b_str2int(&bytes, base as u32) {
346            if consumed == bytes.len() {
347                state.push(LuaValue::Int(n));
348                return Ok(1);
349            }
350        }
351    }
352    state.push(LuaValue::Nil);
353    Ok(1)
354}
355
356// ── error ─────────────────────────────────────────────────────────────────────
357
358/// Raises the value at stack[1] as a Lua error, optionally prepending
359/// source-location information for string errors when `level > 0`.
360///
361pub(crate) fn error_fn(state: &mut LuaState) -> Result<usize, LuaError> {
362    let level = state.opt_arg_integer(2, 1)? as i32;
363    lua_vm::api::set_top(state, 1)?;
364    let ty = state.type_at(1);
365    // 5.1/5.2 prepend the `luaL_where` location to a string OR a number error
366    // value (their guard is `lua_isstring`, which is true for numbers since
367    // numbers coerce to strings); `lua_concat` then stringifies the number. 5.3
368    // tightened this to strict strings only (`ttisstring`), so a number error is
369    // re-raised unchanged. 5.4 is the unchangeable baseline; the number branch is
370    // gated to the legacy family.
371    let legacy_number_prefix = matches!(
372        state.global().lua_version,
373        lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52
374    ) && ty == LuaType::Number;
375    if (ty == LuaType::String || legacy_number_prefix) && level > 0 {
376        state.push_where(level)?;
377        state.push_copy(1)?;
378        state.concat(2)?;
379    }
380    Err(LuaError::from_value(state.pop()))
381}
382
383// ── getmetatable ──────────────────────────────────────────────────────────────
384
385/// Returns the metatable of the first argument, or the `__metatable` field of
386/// the metatable if that field exists (protecting the raw metatable).
387///
388pub(crate) fn getmetatable_fn(state: &mut LuaState) -> Result<usize, LuaError> {
389    state.check_arg_any(1)?;
390    if !state.get_metatable(1)? {
391        state.push(LuaValue::Nil);
392        return Ok(1);
393    }
394    // Returns LuaType::Nil if metatable has no __metatable; otherwise pushes it.
395    state.get_metafield(1, b"__metatable")?;
396    Ok(1)
397}
398
399// ── setmetatable ──────────────────────────────────────────────────────────────
400
401/// Sets the metatable of the table at argument 1 to the value at argument 2
402/// (nil clears it).  Raises an error if the current metatable is protected via
403/// `__metatable`.
404///
405pub(crate) fn setmetatable_fn(state: &mut LuaState) -> Result<usize, LuaError> {
406    let t = state.type_at(2);
407    state.check_arg_type(1, LuaType::Table)?;
408    if !(t == LuaType::Nil || t == LuaType::Table) {
409        let got = state.value_at(2);
410        return Err(LuaError::type_arg_error(2, "nil or table", &got));
411    }
412    if state.get_metafield(1, b"__metatable")? != LuaType::Nil {
413        return Err(LuaError::runtime(format_args!(
414            "cannot change a protected metatable"
415        )));
416    }
417    lua_vm::api::set_top(state, 2)?;
418    state.set_metatable(1)?;
419    Ok(1)
420}
421
422// ── rawequal ──────────────────────────────────────────────────────────────────
423
424/// Raw equality check (no metamethods).
425///
426pub(crate) fn rawequal_fn(state: &mut LuaState) -> Result<usize, LuaError> {
427    state.check_arg_any(1)?;
428    state.check_arg_any(2)?;
429    let eq = state.raw_equal(1, 2)?;
430    state.push(LuaValue::Bool(eq));
431    Ok(1)
432}
433
434// ── rawlen ────────────────────────────────────────────────────────────────────
435
436/// Raw length (#) without metamethods; accepts tables and strings only.
437///
438/// The reject message names the function (`to 'rawlen'`) on every version that
439/// has `rawlen` (5.2+). The `, got <type>` suffix is version-gated: 5.2/5.3 use
440/// `luaL_argcheck(..., "table or string expected")` (no suffix); 5.4/5.5 use
441/// `luaL_argexpected(..., "table or string")`, which appends `, got <type>`
442/// from `luaL_typename` (so an `__name`'d table reports its `__name`).
443pub(crate) fn rawlen_fn(state: &mut LuaState) -> Result<usize, LuaError> {
444    let t = state.type_at(1);
445    if !(t == LuaType::Table || t == LuaType::String) {
446        let extramsg: Vec<u8> = if matches!(state.global().lua_version, lua_types::LuaVersion::V54 | lua_types::LuaVersion::V55) {
447            let got = state.value_at(1);
448            let got_name = state.full_type_name(&got)?;
449            let mut m = b"table or string expected, got ".to_vec();
450            m.extend_from_slice(&got_name);
451            m
452        } else {
453            b"table or string expected".to_vec()
454        };
455        return Err(lua_vm::debug::arg_error_impl(state, 1, &extramsg));
456    }
457    let len = state.raw_len(1);
458    state.push(LuaValue::Int(len));
459    Ok(1)
460}
461
462// ── rawget ────────────────────────────────────────────────────────────────────
463
464/// Raw table read (no metamethods).
465///
466pub(crate) fn rawget_fn(state: &mut LuaState) -> Result<usize, LuaError> {
467    state.check_arg_type(1, LuaType::Table)?;
468    state.check_arg_any(2)?;
469    lua_vm::api::set_top(state, 2)?;
470    state.raw_get(1)?;
471    Ok(1)
472}
473
474// ── rawset ────────────────────────────────────────────────────────────────────
475
476/// Raw table write (no metamethods).
477///
478pub(crate) fn rawset_fn(state: &mut LuaState) -> Result<usize, LuaError> {
479    state.check_arg_type(1, LuaType::Table)?;
480    state.check_arg_any(2)?;
481    state.check_arg_any(3)?;
482    lua_vm::api::set_top(state, 3)?;
483    state.raw_set(1)?;
484    Ok(1)
485}
486
487// ── collectgarbage ────────────────────────────────────────────────────────────
488
489/// Expose GC control to Lua scripts.  The first argument selects the operation;
490/// subsequent arguments are operation-specific parameters.
491///
492/// A GC primitive that returns `-1` was called inside a finalizer and must
493/// `fail` (push `nil`). Each match arm either returns its result early or
494/// evaluates to the `valid` flag `false`, which falls through to the trailing
495/// pushfail — the structured-control-flow form of C's `checkvalres` break.
496pub(crate) fn collectgarbage_fn(state: &mut LuaState) -> Result<usize, LuaError> {
497    // Explicit collections bypass the checkpoint wrappers, so the dead
498    // stack slices must be cleared here before any collect dispatch
499    // (C parity: traversethread's atomic clear; see #140 / GC_ROOTS.md).
500    state.gc_clear_dead_stack_tails();
501    // The option set is version-gated. 5.4/5.3 expose `setpause`/`setstepmul`;
502    // 5.5 removed both and added `param` (lbaselib.c). The version that owns
503    // the running state decides which list/mapping applies.
504    let version = state.global().lua_version;
505    let is_v55 = version == lua_types::LuaVersion::V55;
506    // Lua 5.1's `collectgarbage` accepts only `collect/stop/restart/count/step/
507    // setpause/setstepmul`; the 5.2 `isrunning`/`generational`, the 5.4
508    // `incremental`, and the 5.5 `param` must be rejected with `invalid option`.
509    // Verified against lua5.1.5: `collectgarbage("isrunning")` errors. (5.2 DOES
510    // accept `isrunning`/`generational`, so it stays on OPTS_54.) See
511    // specs/followup/5.1-roster-syntax.md §1.
512    static OPTS_51: &[&[u8]] = &[
513        b"stop",
514        b"restart",
515        b"collect",
516        b"count",
517        b"step",
518        b"setpause",
519        b"setstepmul",
520    ];
521    static OPTS_NUM_51: &[GcOp] = &[
522        GcOp::Stop,
523        GcOp::Restart,
524        GcOp::Collect,
525        GcOp::Count,
526        GcOp::Step,
527        GcOp::SetPause,
528        GcOp::SetStepMul,
529    ];
530    // 5.2 accepts `generational`/`incremental` (both return the PREVIOUS GC mode
531    // as the integer 0 — there is no string mode name pre-5.4) and `isrunning`,
532    // but NOT 5.3's narrower roster. 5.3 removed `generational`/`incremental`
533    // entirely (they raise `invalid option`), keeping only the incremental knobs.
534    // Verified by probing lua5.2.4 / lua5.3.6 (`specs/followup` GC roster). The
535    // 5.2-only `setmajorinc` is a generational-GC param this reused incremental
536    // core does not carry, so it is left out of scope here.
537    static OPTS_52: &[&[u8]] = &[
538        b"stop",
539        b"restart",
540        b"collect",
541        b"count",
542        b"step",
543        b"setpause",
544        b"setstepmul",
545        b"isrunning",
546        b"generational",
547        b"incremental",
548    ];
549    static OPTS_NUM_52: &[GcOp] = &[
550        GcOp::Stop,
551        GcOp::Restart,
552        GcOp::Collect,
553        GcOp::Count,
554        GcOp::Step,
555        GcOp::SetPause,
556        GcOp::SetStepMul,
557        GcOp::IsRunning,
558        GcOp::Gen,
559        GcOp::Inc,
560    ];
561    static OPTS_53: &[&[u8]] = &[
562        b"stop",
563        b"restart",
564        b"collect",
565        b"count",
566        b"step",
567        b"setpause",
568        b"setstepmul",
569        b"isrunning",
570    ];
571    static OPTS_NUM_53: &[GcOp] = &[
572        GcOp::Stop,
573        GcOp::Restart,
574        GcOp::Collect,
575        GcOp::Count,
576        GcOp::Step,
577        GcOp::SetPause,
578        GcOp::SetStepMul,
579        GcOp::IsRunning,
580    ];
581    static OPTS_54: &[&[u8]] = &[
582        b"stop",
583        b"restart",
584        b"collect",
585        b"count",
586        b"step",
587        b"setpause",
588        b"setstepmul",
589        b"isrunning",
590        b"generational",
591        b"incremental",
592    ];
593    static OPTS_NUM_54: &[GcOp] = &[
594        GcOp::Stop,
595        GcOp::Restart,
596        GcOp::Collect,
597        GcOp::Count,
598        GcOp::Step,
599        GcOp::SetPause,
600        GcOp::SetStepMul,
601        GcOp::IsRunning,
602        GcOp::Gen,
603        GcOp::Inc,
604    ];
605    static OPTS_55: &[&[u8]] = &[
606        b"stop",
607        b"restart",
608        b"collect",
609        b"count",
610        b"step",
611        b"isrunning",
612        b"generational",
613        b"incremental",
614        b"param",
615    ];
616    static OPTS_NUM_55: &[GcOp] = &[
617        GcOp::Stop,
618        GcOp::Restart,
619        GcOp::Collect,
620        GcOp::Count,
621        GcOp::Step,
622        GcOp::IsRunning,
623        GcOp::Gen,
624        GcOp::Inc,
625        GcOp::Param,
626    ];
627    let (opts, opts_num): (&[&[u8]], &[GcOp]) = if is_v55 {
628        (OPTS_55, OPTS_NUM_55)
629    } else if matches!(version, lua_types::LuaVersion::V51) {
630        (OPTS_51, OPTS_NUM_51)
631    } else if matches!(version, lua_types::LuaVersion::V52) {
632        (OPTS_52, OPTS_NUM_52)
633    } else if matches!(version, lua_types::LuaVersion::V53) {
634        (OPTS_53, OPTS_NUM_53)
635    } else {
636        (OPTS_54, OPTS_NUM_54)
637    };
638    let idx = state.check_arg_option(1, Some(b"collect"), opts)?;
639    let op = opts_num[idx];
640
641    // Each arm either returns early on success, or evaluates to `false`
642    // (meaning checkvalres fired — fall through to pushfail).
643    let valid: bool = match op {
644        GcOp::Count => {
645            let k = state.gc_count()?;
646            let b = state.gc_count_b()?;
647            if k == -1 {
648                false
649            } else {
650                state.push(LuaValue::Float(k as f64 + b as f64 / 1024.0));
651                // 5.2 returns a SECOND result, the byte remainder `b` (0..1024)
652                // — `lua_pushinteger(L, lua_gc(L, LUA_GCCOUNTB, 0))`. 5.3 dropped
653                // it (`collectgarbage("count")` is one value there on), so the
654                // second result is gated to V52. Verified against lua5.2.4 /
655                // lua5.3.6.
656                if matches!(version, lua_types::LuaVersion::V52) {
657                    state.push(LuaValue::Int(b as i64));
658                    return Ok(2);
659                }
660                return Ok(1);
661            }
662        }
663        GcOp::Step => {
664            let step = state.opt_arg_integer(2, 0)? as i32;
665            let res = state.gc_step(step)?;
666            if res == -1 {
667                false
668            } else {
669                state.push(LuaValue::Bool(res != 0));
670                return Ok(1);
671            }
672        }
673        GcOp::SetPause | GcOp::SetStepMul => {
674            let p = state.opt_arg_integer(2, 0)? as i32;
675            let previous = state.gc_set_param(op as i32, p)?;
676            if previous == -1 {
677                false
678            } else {
679                state.push(LuaValue::Int(previous as i64));
680                return Ok(1);
681            }
682        }
683        GcOp::IsRunning => {
684            let res = state.gc_is_running()?;
685            state.push(LuaValue::Bool(res));
686            return Ok(1);
687        }
688        GcOp::Gen => {
689            let minormul = state.opt_arg_integer(2, 0)? as i32;
690            let majormul = state.opt_arg_integer(3, 0)? as i32;
691            let oldmode = state.gc_gen(minormul, majormul)?;
692            return push_gc_mode(state, version, oldmode);
693        }
694        GcOp::Inc => {
695            let pause = state.opt_arg_integer(2, 0)? as i32;
696            let stepmul = state.opt_arg_integer(3, 0)? as i32;
697            let stepsize = state.opt_arg_integer(4, 0)? as i32;
698            let oldmode = state.gc_inc(pause, stepmul, stepsize)?;
699            return push_gc_mode(state, version, oldmode);
700        }
701        GcOp::Param => {
702            // 5.5 collectgarbage("param", name [, value]): read or write a GC
703            // parameter, always returning the OLD integer value. arg2 selects
704            // the param; arg3 (default -1 = read-only) is the new value.
705            static PARAMS: &[&[u8]] = &[
706                b"minormul",
707                b"majorminor",
708                b"minormajor",
709                b"pause",
710                b"stepmul",
711                b"stepsize",
712            ];
713            let pidx = state.check_arg_option(2, None, PARAMS)?;
714            let value = state.opt_arg_integer(3, -1)?;
715            let old = state.gc_param(pidx, value)?;
716            state.push(LuaValue::Int(old));
717            return Ok(1);
718        }
719        _ => {
720            let res = state.gc_control_simple(op as i32)?;
721            if res == -1 {
722                false
723            } else {
724                state.push(LuaValue::Int(res as i64));
725                return Ok(1);
726            }
727        }
728    };
729    debug_assert!(
730        !valid,
731        "valid arms return early; reaching here means checkvalres fired"
732    );
733    state.push(LuaValue::Nil);
734    Ok(1)
735}
736
737// ── type ──────────────────────────────────────────────────────────────────────
738
739/// Returns the type name of its argument as a string.
740///
741pub(crate) fn type_fn(state: &mut LuaState) -> Result<usize, LuaError> {
742    let t = state.type_at(1);
743    if t == LuaType::None {
744        return Err(lua_vm::debug::arg_error_impl(state, 1, b"value expected"));
745    }
746    // Clone the bytes before the push to avoid borrow conflict with state.
747    let name: Vec<u8> = state.type_name(t).to_vec();
748    state.push_string(&name)?;
749    Ok(1)
750}
751
752// ── getfenv / setfenv (Lua 5.1 fenv globals) ──────────────────────────────────
753
754/// Truncate a numeric `getfenv`/`setfenv` level toward zero.
755///
756/// 5.1's `luaL_checkint` casts `lua_Number` to a C `int`, truncating toward
757/// zero, so `getfenv(1.9)` is level 1 and `getfenv(-0.5)` is level 0. Under the
758/// float-only V51 model every number arrives as a `Float`; the `Int` arm is a
759/// defensive no-op. A non-number never reaches this helper.
760fn fenv_level(v: &LuaValue) -> i64 {
761    match v {
762        LuaValue::Float(f) => f.trunc() as i64,
763        LuaValue::Int(i) => *i,
764        _ => 0,
765    }
766}
767
768/// Resolve the function value targeted by a `getfenv`/`setfenv` first argument.
769///
770/// Returns the `LuaValue::Function` whose environment is being read or written.
771/// `arg1` is interpreted exactly as Lua 5.1's `getfunc`/`setfunc`
772/// (lbaselib.c): a function value targets that function directly; a number is a
773/// stack *level* (floored toward zero), where level 1 is the function calling
774/// `getfenv`/`setfenv`. Level 0 is handled by the callers (it denotes the
775/// running thread's global table, not a function) and never reaches here.
776///
777/// Errors mirror lua5.1.5:
778/// - negative level → `level must be non-negative`
779/// - level past the stack → `invalid level`
780/// - neither number nor function → `number expected, got <type>`
781fn fenv_getfunc(state: &mut LuaState, level: i64) -> Result<LuaValue, LuaError> {
782    if level < 0 {
783        return Err(lua_vm::debug::arg_error_impl(
784            state,
785            1,
786            b"level must be non-negative",
787        ));
788    }
789    let mut ar = lua_vm::debug::LuaDebug::default();
790    if !lua_vm::debug::get_stack(state, level as i32, &mut ar) {
791        return Err(lua_vm::debug::arg_error_impl(state, 1, b"invalid level"));
792    }
793    let ci_idx = ar
794        .i_ci
795        .ok_or_else(|| lua_vm::debug::arg_error_impl(state, 1, b"invalid level"))?;
796    if state.global().lua_version == lua_types::LuaVersion::V51 && state.is_base_ci(ci_idx) {
797        return Err(LuaError::runtime(format_args!(
798            "no function environment for tail call at level {}",
799            level
800        )));
801    }
802    let func_slot = state.get_ci(ci_idx).func;
803    Ok(state.get_at(func_slot))
804}
805
806/// Index of a Lua closure's `_ENV` upvalue, by upvalue name.
807///
808/// The reused modern parser threads an upvalue literally named `_ENV` and
809/// resolves every free (global) name through it; under V51 that upvalue *is* the
810/// function environment. It is NOT always upvalue 0 — a nested closure that
811/// captures locals places those first, with `_ENV` at a later index — so it must
812/// be located by name, not position. A closure that references no free names has
813/// no `_ENV` upvalue and returns `None`.
814fn fenv_env_upval_index(
815    lcl: &lua_types::gc::GcRef<lua_types::closure::LuaLClosure>,
816) -> Option<usize> {
817    lcl.proto
818        .upvalues
819        .iter()
820        .position(|ud| ud.name.as_ref().map(|s| s.as_bytes()) == Some(b"_ENV"))
821}
822
823/// Read the environment of a resolved function value.
824///
825/// A Lua closure's environment is its `_ENV` upvalue. A Lua closure that
826/// references no globals has no `_ENV` upvalue; its environment lives in the
827/// `closure_envs` side map once `setfenv` has set one, otherwise it has never
828/// been given a distinct environment and resolves to the running thread's
829/// global table. A C/Rust function likewise reports the thread global table —
830/// the common 5.1 case and the documented `LUA_ENVIRONINDEX` gap
831/// (specs/followup/5.1-fenv.md §4).
832fn fenv_read(state: &LuaState, func: &LuaValue) -> LuaValue {
833    if let LuaValue::Function(LuaClosure::Lua(lcl)) = func {
834        if let Some(idx) = fenv_env_upval_index(lcl) {
835            return state.upvalue_get(lcl, idx);
836        }
837        if let Some(env) = state.global().closure_envs.get(&lcl.identity()) {
838            return env.clone();
839        }
840    }
841    let running = state.global().current_thread_id;
842    state.v51_thread_lgt(running)
843}
844
845/// Set the environment of a Lua closure that carries no `_ENV` upvalue.
846///
847/// Such a closure (the modern parser threads `_ENV` only onto closures that
848/// reference a free global name) has no upvalue slot to write, so 5.1's
849/// `setfenv` stores its environment in the `closure_envs` side map keyed by
850/// closure identity. A closure that *does* have an `_ENV` upvalue is handled by
851/// the upvalue-cell path and never reaches here.
852fn fenv_set_closure_env(
853    state: &mut LuaState,
854    lcl: &lua_types::gc::GcRef<lua_types::closure::LuaLClosure>,
855    new_env: LuaValue,
856) {
857    state
858        .global_mut()
859        .closure_envs
860        .insert(lcl.identity(), new_env);
861}
862
863/// `getfenv([f])` — Lua 5.1 only.
864///
865/// Returns the environment of the function `f` (a function value or a stack
866/// level), or the running function's environment when the argument is absent,
867/// `nil`, or `1`. 5.1's `getfunc` resolves the level via `luaL_optint(L, 1, 1)`,
868/// which defaults both an absent and an explicit `nil` argument to level 1.
869/// Level `0` returns the running thread's global table. See
870/// `specs/followup/5.1-fenv.md` §2.
871pub(crate) fn getfenv_fn(state: &mut LuaState) -> Result<usize, LuaError> {
872    let arg1 = state.value_at(1);
873    let func = match &arg1 {
874        LuaValue::Function(_) => arg1.clone(),
875        LuaValue::Nil => fenv_getfunc(state, 1)?,
876        LuaValue::Float(_) | LuaValue::Int(_) => {
877            let level = fenv_level(&arg1);
878            if level == 0 {
879                let running = state.global().current_thread_id;
880                let lgt = state.v51_thread_lgt(running);
881                state.push(lgt);
882                return Ok(1);
883            }
884            fenv_getfunc(state, level)?
885        }
886        other => {
887            let got = state.obj_type_name(other);
888            let msg = format!("number expected, got {}", String::from_utf8_lossy(&got));
889            return Err(lua_vm::debug::arg_error_impl(state, 1, msg.as_bytes()));
890        }
891    };
892    let env = fenv_read(state, &func);
893    state.push(env);
894    Ok(1)
895}
896
897/// `setfenv(f, table)` — Lua 5.1 only.
898///
899/// Sets the environment of the function `f` (a function value or a stack level)
900/// to `table`. `setfenv(0, t)` sets the running thread's global table. Returns
901/// the affected function (or the running thread for level 0). A C/Rust function
902/// (or any non-Lua object) cannot have its environment changed and raises,
903/// matching lua5.1.5. See `specs/followup/5.1-fenv.md` §2.
904pub(crate) fn setfenv_fn(state: &mut LuaState) -> Result<usize, LuaError> {
905    state.check_arg_type(2, LuaType::Table)?;
906    let new_env = state.value_at(2);
907
908    let arg1 = state.value_at(1);
909    let is_level_zero =
910        matches!(&arg1, LuaValue::Int(0)) || matches!(&arg1, LuaValue::Float(f) if *f == 0.0);
911    if is_level_zero {
912        // Level 0: replace the *running thread's* global table (5.1's
913        // per-thread `l_gt`) and return the running thread. Subsequently
914        // loaded top-level chunks take this env. From inside a coroutine this
915        // touches only that coroutine's `l_gt`, never the main thread's
916        // globals.
917        let running = state.global().current_thread_id;
918        state.v51_set_thread_lgt(running, new_env);
919        lua_vm::api::push_thread(state);
920        return Ok(1);
921    }
922
923    let func = match &arg1 {
924        LuaValue::Function(_) => arg1.clone(),
925        LuaValue::Float(_) | LuaValue::Int(_) => {
926            let level = fenv_level(&arg1);
927            fenv_getfunc(state, level)?
928        }
929        other => {
930            let got = state.obj_type_name(other);
931            let msg = format!("number expected, got {}", String::from_utf8_lossy(&got));
932            return Err(lua_vm::debug::arg_error_impl(state, 1, msg.as_bytes()));
933        }
934    };
935
936    match &func {
937        LuaValue::Function(LuaClosure::Lua(lcl)) => {
938            if let Some(idx) = fenv_env_upval_index(lcl) {
939                // Give the closure a PRIVATE environment: replace its `_ENV`
940                // upvalue *cell* with a fresh closed upvalue holding `new_env`.
941                // Mutating the existing cell's value (`upvalue_set`) would alter
942                // every closure sharing that upvalue (e.g. the main chunk's
943                // `_G`), which is wrong — `setfenv(f, e)` must not change the
944                // caller's globals. A new cell isolates `f`.
945                let uv = state.new_upval_closed(new_env);
946                lcl.set_upval(idx, uv);
947                state.gc().obj_barrier(lcl, &uv);
948            } else {
949                // A Lua closure that references no free global name has no
950                // `_ENV` upvalue, so there is no upvalue cell to write. 5.1
951                // still sets its environment; store it in the `closure_envs`
952                // side map keyed by closure identity, where `getfenv(f)` /
953                // `getfenv(level)` reads it back.
954                let lcl = *lcl;
955                fenv_set_closure_env(state, &lcl, new_env);
956            }
957        }
958        _ => {
959            // C/Rust functions cannot have their environment changed. 5.1
960            // raises this exact message (via luaL_error, so it carries the
961            // caller's source location) for any object whose env is fixed.
962            return Err(
963                state.where_error(1, b"'setfenv' cannot change environment of given object")
964            );
965        }
966    }
967    state.push(func);
968    Ok(1)
969}
970
971/// Set the environment of the Lua closure `level` frames up the running stack
972/// to `new_env`, the internal equivalent of `setfenv(level, new_env)`.
973///
974/// Used by `module` (5.1 `package` library), which sets its caller's
975/// environment to the module table. A non-Lua function (or a closure with no
976/// `_ENV` upvalue) is left unchanged, matching the inert-set behavior of
977/// `setfenv`. See specs/followup/5.1-fenv.md.
978pub(crate) fn set_func_env_at_level(
979    state: &mut LuaState,
980    level: i64,
981    new_env: LuaValue,
982) -> Result<(), LuaError> {
983    let func = fenv_getfunc(state, level)?;
984    if let LuaValue::Function(LuaClosure::Lua(lcl)) = &func {
985        if let Some(idx) = fenv_env_upval_index(lcl) {
986            let uv = state.new_upval_closed(new_env);
987            lcl.set_upval(idx, uv);
988            state.gc().obj_barrier(lcl, &uv);
989        } else {
990            let lcl = *lcl;
991            fenv_set_closure_env(state, &lcl, new_env);
992        }
993    }
994    Ok(())
995}
996
997/// `debug.getfenv(o)` — Lua 5.1 only.
998///
999/// Returns the environment of object `o` *directly* (`db_getfenv` =
1000/// `luaL_checkany; lua_getfenv`). Unlike the global `getfenv`, the argument is
1001/// the object itself, never a stack level: `debug.getfenv(1)` returns `nil`
1002/// because the number 1 has no environment. A function returns its `_ENV`
1003/// environment; a value with no environment returns `nil`. Absent argument
1004/// raises `value expected`.
1005///
1006/// Gap: 5.1 userdata/thread environments live in fields this reused modern core
1007/// does not expose, so those return `nil` here rather than their stored table.
1008/// The common function/non-function cases match lua5.1.5.
1009pub(crate) fn debug_getfenv_fn(state: &mut LuaState) -> Result<usize, LuaError> {
1010    if state.type_at(1) == LuaType::None {
1011        return Err(lua_vm::debug::arg_error_impl(state, 1, b"value expected"));
1012    }
1013    let obj = state.value_at(1);
1014    match &obj {
1015        LuaValue::Function(_) => {
1016            let env = fenv_read(state, &obj);
1017            state.push(env);
1018        }
1019        LuaValue::Thread(th) => {
1020            // A thread's environment is its per-thread global table (`l_gt`):
1021            // `debug.getfenv(co)` returns the global table that `co`'s freshly
1022            // loaded chunks and `getfenv(0)` see (closure.lua@5.1).
1023            let lgt = state.v51_thread_lgt(th.id);
1024            state.push(lgt);
1025        }
1026        _ => {
1027            state.push(LuaValue::Nil);
1028        }
1029    }
1030    Ok(1)
1031}
1032
1033/// `debug.setfenv(o, t)` — Lua 5.1 only.
1034///
1035/// Sets object `o`'s environment to table `t` and returns `o` (`db_setfenv` =
1036/// `luaL_checktype(2, TABLE); lua_setfenv`). For a Lua closure this installs a
1037/// fresh closed `_ENV` upvalue cell (the same private-environment isolation
1038/// `setfenv` uses). An object whose environment cannot be set raises
1039/// `'setfenv' cannot change environment of given object`.
1040pub(crate) fn debug_setfenv_fn(state: &mut LuaState) -> Result<usize, LuaError> {
1041    state.check_arg_type(2, LuaType::Table)?;
1042    let new_env = state.value_at(2);
1043    let obj = state.value_at(1);
1044    match &obj {
1045        LuaValue::Function(LuaClosure::Lua(lcl)) => {
1046            if let Some(idx) = fenv_env_upval_index(lcl) {
1047                let uv = state.new_upval_closed(new_env);
1048                lcl.set_upval(idx, uv);
1049                state.gc().obj_barrier(lcl, &uv);
1050            } else {
1051                let lcl = *lcl;
1052                fenv_set_closure_env(state, &lcl, new_env);
1053            }
1054        }
1055        LuaValue::Thread(th) => {
1056            // `debug.setfenv(co, t)` sets thread `co`'s per-thread global
1057            // table (`l_gt`), the env its freshly loaded chunks and
1058            // `getfenv(0)` resolve through (closure.lua@5.1).
1059            state.v51_set_thread_lgt(th.id, new_env);
1060        }
1061        LuaValue::Function(_) => {
1062            return Err(
1063                state.where_error(1, b"'setfenv' cannot change environment of given object")
1064            );
1065        }
1066        _ => {
1067            return Err(
1068                state.where_error(1, b"'setfenv' cannot change environment of given object")
1069            );
1070        }
1071    }
1072    state.push(obj);
1073    Ok(1)
1074}
1075
1076// ── next ──────────────────────────────────────────────────────────────────────
1077
1078/// Table traversal iterator: given a table and a key, pushes the next key-value
1079/// pair.  Pushes nil and returns 1 when the traversal is exhausted.
1080///
1081pub(crate) fn next_fn(state: &mut LuaState) -> Result<usize, LuaError> {
1082    state.check_arg_type(1, LuaType::Table)?;
1083    lua_vm::api::set_top(state, 2)?;
1084    if state.table_next(1)? {
1085        Ok(2)
1086    } else {
1087        state.push(LuaValue::Nil);
1088        Ok(1)
1089    }
1090}
1091
1092// ── pairs continuation (coroutine stub) ───────────────────────────────────────
1093
1094/// Continuation for `pairs` when the `__pairs` metamethod yields.
1095/// Re-invoked by `finishCcall` after the yielded `__pairs` resumes.
1096///
1097fn pairs_cont(state: &mut LuaState, _status: i32, _ctx: isize) -> Result<usize, LuaError> {
1098    if state.global().lua_version == lua_types::LuaVersion::V55 {
1099        Ok(4)
1100    } else {
1101        Ok(3)
1102    }
1103}
1104
1105// ── pairs ─────────────────────────────────────────────────────────────────────
1106
1107/// Returns the `next` function, the table, and nil (or invokes a `__pairs`
1108/// metamethod).
1109///
1110pub(crate) fn pairs_fn(state: &mut LuaState) -> Result<usize, LuaError> {
1111    state.check_arg_any(1)?;
1112    // Lua 5.1 has no `__pairs` metamethod; `pairs(t)` always iterates the raw
1113    // table even when a `__pairs` is set (it is silently ignored). Lua 5.5
1114    // extends the result list with a fourth to-be-closed object.
1115    let consult_pairs_tm = !matches!(state.global().lua_version, lua_types::LuaVersion::V51);
1116    let nresults = if state.global().lua_version == lua_types::LuaVersion::V55 {
1117        4
1118    } else {
1119        3
1120    };
1121    if !consult_pairs_tm || state.get_metafield(1, b"__pairs")? == LuaType::Nil {
1122        state.push_c_function(next_fn)?;
1123        state.push_copy(1)?;
1124        state.push(LuaValue::Nil);
1125        if nresults == 4 {
1126            state.push(LuaValue::Nil);
1127        }
1128    } else {
1129        state.push_copy(1)?;
1130        state.call_k(1, nresults as i32, 0, Some(pairs_cont))?;
1131    }
1132    Ok(nresults)
1133}
1134
1135// ── ipairs auxiliary ──────────────────────────────────────────────────────────
1136
1137/// Iterator step function for `ipairs`: increments the counter and fetches
1138/// the next array element.  Returns the index + value, or just the index when
1139/// the value is nil (signalling end-of-iteration).
1140///
1141/// The element fetch is a genuine cross-version split. Lua 5.1/5.2's
1142/// `ipairsaux` reads with `lua_rawgeti` — `__index` is NOT consulted, so an
1143/// empty array part stops immediately even when an `__index` would supply
1144/// values. Lua 5.3 switched to `lua_geti`, which honors `__index`.
1145///
1146/// The split is resolved ONCE in the cold `ipairs_fn` setup, which registers
1147/// the matching specialization (`ipairs_aux_raw` for 5.1/5.2, `ipairs_aux` for
1148/// 5.3+). This per-step loop body therefore carries NO version branch — the GC
1149/// `global()` borrow stays out of the hot iteration path (cf. the string
1150/// packet's `gmatch_aux` const-split). The `RAW` const folds at monomorphization.
1151fn ipairs_step<const RAW: bool>(state: &mut LuaState) -> Result<usize, LuaError> {
1152    let i = match lua_vm::api::positive_index_value(state, 2) {
1153        LuaValue::Int(i) => i,
1154        _ => state.check_arg_integer(2)?,
1155    };
1156    // luaL_intop(+, a, b) → wrapping integer addition (PORTING.md §9 / macros.tsv `intop`)
1157    let i = (i as u64).wrapping_add(1u64) as i64;
1158    state.push(LuaValue::Int(i));
1159    let t = if RAW {
1160        // 5.1/5.2: `lua_rawgeti`. The first argument is guaranteed a table
1161        // (`ipairs` type-checks it on those versions), so the raw read is safe.
1162        lua_vm::api::raw_get_i(state, 1, i)
1163    } else {
1164        let table = lua_vm::api::positive_index_value(state, 1);
1165        state.table_get_i_value(&table, i)?
1166    };
1167    if t == LuaType::Nil {
1168        Ok(1)
1169    } else {
1170        Ok(2)
1171    }
1172}
1173
1174/// 5.3+ `ipairsaux`: honors `__index` via `lua_geti`.
1175fn ipairs_aux(state: &mut LuaState) -> Result<usize, LuaError> {
1176    ipairs_step::<false>(state)
1177}
1178
1179/// 5.1/5.2 `ipairsaux`: raw `lua_rawgeti`, no `__index`.
1180fn ipairs_aux_raw(state: &mut LuaState) -> Result<usize, LuaError> {
1181    ipairs_step::<true>(state)
1182}
1183
1184// ── ipairs ────────────────────────────────────────────────────────────────────
1185
1186/// Returns the `ipairsaux` iterator, the table, and 0 as the initial counter
1187/// (or invokes an `__ipairs` metamethod on the versions that honor it).
1188///
1189/// Three cross-version seams converge here, all in this cold setup path:
1190///
1191/// - **`__ipairs` metamethod.** The `LUA_COMPAT_IPAIRS` macro (default ON in
1192///   5.2/5.3 via `LUA_COMPAT_5_2`) routes `ipairs` through `pairsmeta`, which
1193///   calls `t.__ipairs(t)` for the iterator triple when present. 5.1 predates
1194///   `__ipairs`; 5.4/5.5 removed the compat path. Honored only on 5.2/5.3.
1195/// - **Setup type check.** 5.1's `luaB_ipairs` (and 5.2's `pairsmeta` when no
1196///   `__ipairs` is found) does `luaL_checktype(1, TABLE)` — `ipairs(non_table)`
1197///   raises at the `ipairs` call. 5.3+ relaxed this to `luaL_checkany`, so a
1198///   non-table reaches the iterator and only errors (or stops) there.
1199/// - **Raw vs `__index` read** is handled in `ipairs_aux` (5.1/5.2 raw).
1200pub(crate) fn ipairs_fn(state: &mut LuaState) -> Result<usize, LuaError> {
1201    let version = state.global().lua_version;
1202    let consult_ipairs_tm = matches!(
1203        version,
1204        lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
1205    );
1206    if consult_ipairs_tm && state.get_metafield(1, b"__ipairs")? != LuaType::Nil {
1207        state.push_copy(1)?;
1208        state.call(1, 3)?;
1209        return Ok(3);
1210    }
1211    let legacy = matches!(
1212        version,
1213        lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52
1214    );
1215    if legacy {
1216        state.check_arg_type(1, LuaType::Table)?;
1217        state.push_c_function(ipairs_aux_raw)?;
1218    } else {
1219        state.check_arg_any(1)?;
1220        state.push_c_function(ipairs_aux)?;
1221    }
1222    state.push_copy(1)?;
1223    state.push(LuaValue::Int(0));
1224    Ok(3)
1225}
1226
1227// ── loadfile ──────────────────────────────────────────────────────────────────
1228
1229/// Loads a Lua chunk from a file.
1230///
1231pub(crate) fn loadfile_fn(state: &mut LuaState) -> Result<usize, LuaError> {
1232    let fname: Option<Vec<u8>> = state.opt_arg_lstring(1, None)?;
1233    let mode: Option<Vec<u8>> = if state.is_none_or_nil(2) {
1234        None
1235    } else {
1236        Some(check_load_mode(state, 2, b"bt")?)
1237    };
1238    let env = if state.type_at(3) != LuaType::None {
1239        3
1240    } else {
1241        0
1242    };
1243    let status_ok = state.load_file_ex(fname.as_deref(), mode.as_deref())?;
1244    load_aux(state, status_ok, env)
1245}
1246
1247// ── generic_reader ────────────────────────────────────────────────────────────
1248
1249/// Reader callback for `load` when the chunk source is a Lua function.
1250///
1251/// Calls the function at stack[1] repeatedly to obtain successive chunks; a
1252/// `nil` return ends the stream and anything that is neither a string nor a
1253/// coercible number (the C `lua_isstring` test) is rejected. The latest chunk
1254/// is anchored in `RESERVED_SLOT` so the GC cannot collect it while `lua_load`
1255/// consumes it. `state.load_with_reader` drives this as the reader.
1256fn generic_reader(state: &mut LuaState) -> Result<Option<Vec<u8>>, LuaError> {
1257    state.ensure_stack(2, b"too many nested functions")?;
1258    state.push_copy(1)?;
1259    state.call(0, 1)?;
1260    if state.type_at(-1) == LuaType::Nil {
1261        state.pop_n(1);
1262        return Ok(None);
1263    }
1264    if !matches!(state.type_at(-1), LuaType::String | LuaType::Number) {
1265        return Err(LuaError::runtime(format_args!(
1266            "reader function must return a string"
1267        )));
1268    }
1269    state.replace(RESERVED_SLOT)?;
1270    let bytes = state.to_lua_string_bytes(RESERVED_SLOT).map(|b| b.to_vec());
1271    Ok(bytes)
1272}
1273
1274// ── load ──────────────────────────────────────────────────────────────────────
1275
1276/// Loads a Lua chunk from a string or a reader function.
1277///
1278pub(crate) fn load_fn(state: &mut LuaState) -> Result<usize, LuaError> {
1279    // Lua 5.1's `load` takes a *reader function only* — string loading is
1280    // `loadstring`'s job. `load("...")` errors with `function expected, got
1281    // string`. The string-or-function overload is a 5.2 addition. Verified
1282    // against lua5.1.5; see specs/followup/5.1-roster-syntax.md §1.
1283    if matches!(state.global().lua_version, lua_types::LuaVersion::V51) {
1284        state.check_arg_type(1, LuaType::Function)?;
1285    }
1286    // Determine whether argument 1 is a string (load from buffer) or a
1287    // function (load from reader).
1288    let is_string = matches!(state.type_at(1), LuaType::String | LuaType::Number);
1289    let mode: Vec<u8> = check_load_mode(state, 3, b"bt")?;
1290    let env = if state.type_at(4) != LuaType::None {
1291        4
1292    } else {
1293        0
1294    };
1295    let status_ok = if is_string {
1296        let chunk: Vec<u8> = state.to_lua_string_bytes(1).unwrap_or_default();
1297        let chunkname: Vec<u8> = if state.is_none_or_nil(2) {
1298            chunk.clone()
1299        } else {
1300            state.check_arg_string(2)?
1301        };
1302        state.load_buffer_ex(&chunk, &chunkname, &mode)?
1303    } else {
1304        let chunkname: Vec<u8> = state
1305            .opt_arg_string_bytes(2)
1306            .unwrap_or_else(|_| b"=(load)".to_vec());
1307        state.check_arg_type(1, LuaType::Function)?;
1308        lua_vm::api::set_top(state, RESERVED_SLOT)?;
1309        state.load_with_reader(generic_reader, &chunkname, &mode)?
1310    };
1311    load_aux(state, status_ok, env)
1312}
1313
1314/// `loadstring(s [, chunkname])` — Lua 5.1 only.
1315///
1316/// Loads a string as a Lua chunk. In 5.1 this is the string-loading counterpart
1317/// to `load` (which takes a reader function only). The second argument is the
1318/// chunk name. Verified against lua5.1.5; see
1319/// specs/followup/5.1-roster-syntax.md §1.
1320pub(crate) fn loadstring_fn(state: &mut LuaState) -> Result<usize, LuaError> {
1321    let chunk: Vec<u8> = state.check_arg_string(1)?;
1322    let chunkname: Vec<u8> = if state.is_none_or_nil(2) {
1323        chunk.clone()
1324    } else {
1325        state.check_arg_string(2)?
1326    };
1327    let status_ok = state.load_buffer_ex(&chunk, &chunkname, b"bt")?;
1328    load_aux(state, status_ok, 0)
1329}
1330
1331/// `gcinfo()` — Lua 5.1 only. Returns the amount of memory in use by Lua, in
1332/// kilobytes. A deprecated holdover of `collectgarbage("count")` that returns
1333/// just the integer KB count. Verified against lua5.1.5: returns a number. See
1334/// specs/followup/5.1-roster-syntax.md §1.
1335pub(crate) fn gcinfo_fn(state: &mut LuaState) -> Result<usize, LuaError> {
1336    let k = state.gc_count()?;
1337    state.push(LuaValue::Int(k as i64));
1338    Ok(1)
1339}
1340
1341/// `newproxy([boolean | proxy])` — Lua 5.1 only.
1342///
1343/// Creates a zero-size userdata (a "proxy"). With no argument or `false`, the
1344/// proxy has no metatable. With `true`, it gets a fresh empty metatable (so a
1345/// host can install `__gc`/`__len`, the userdata idiom these metamethods need
1346/// in 5.1). With another proxy, it shares that proxy's metatable. Mirrors
1347/// `luaB_newproxy` in 5.1 `lbaselib.c`; see specs/followup/5.1-roster-syntax.md
1348/// §1. The C version validates the proxy argument against a weak table of
1349/// metatables it created; this port instead accepts any userdata that carries a
1350/// metatable, which is observably equivalent for the proxy idiom.
1351pub(crate) fn newproxy_fn(state: &mut LuaState) -> Result<usize, LuaError> {
1352    lua_vm::api::set_top(state, 1)?;
1353    // The new userdata is pushed at stack position 2.
1354    state.new_userdata_typed(b"", 0, 0)?;
1355    if !state.to_boolean(1) {
1356        return Ok(1); // no metatable
1357    }
1358    if matches!(state.type_at(1), LuaType::Boolean) {
1359        // `true`: create and attach a fresh empty metatable.
1360        let mt = state.new_table();
1361        state.push(LuaValue::Table(mt));
1362        state.set_metatable(2)?;
1363    } else {
1364        // A proxy argument: share its metatable. Validate it is a userdata that
1365        // carries one (the C version checks a weak table of valid metatables).
1366        let is_proxy = matches!(state.type_at(1), LuaType::UserData) && state.get_metatable(1)?;
1367        if !is_proxy {
1368            return Err(lua_vm::debug::arg_error_impl(
1369                state,
1370                1,
1371                b"boolean or proxy expected",
1372            ));
1373        }
1374        // get_metatable pushed arg1's metatable on top; attach it to the proxy.
1375        state.set_metatable(2)?;
1376    }
1377    Ok(1)
1378}
1379
1380// ── dofile ────────────────────────────────────────────────────────────────────
1381
1382/// Loads and runs a Lua file, forwarding all return values.
1383///
1384fn dofile_cont(state: &mut LuaState, _status: i32, _ctx: isize) -> Result<usize, LuaError> {
1385    Ok((state.top() as i32 - 1) as usize)
1386}
1387
1388pub(crate) fn dofile_fn(state: &mut LuaState) -> Result<usize, LuaError> {
1389    let fname: Option<Vec<u8>> = state.opt_arg_lstring(1, None)?;
1390    lua_vm::api::set_top(state, 1)?;
1391    if !state.load_file(fname.as_deref())? {
1392        return Err(LuaError::from_value(state.pop()));
1393    }
1394    state.call_k(0, LUA_MULTRET, 0, Some(dofile_cont))?;
1395    dofile_cont(state, 0, 0)
1396}
1397
1398// ── assert ────────────────────────────────────────────────────────────────────
1399
1400/// Raises an error if the first argument is falsy, otherwise passes all
1401/// arguments through as return values.
1402///
1403/// The message handling is a cross-version split. Lua 5.1/5.2 `luaB_assert`
1404/// raise via `luaL_error("%s", luaL_optstring(L, 2, "assertion failed!"))`:
1405/// the message must be string-coercible, so a present non-string/non-number
1406/// second argument raises `bad argument #2 to 'assert' (string expected,
1407/// got <type>)`, a number is stringified, and the result is location-prefixed.
1408/// Lua 5.3+ forward the raw second argument (any value) to `error`, so a table
1409/// message becomes the error object itself, unprefixed.
1410pub(crate) fn assert_fn(state: &mut LuaState) -> Result<usize, LuaError> {
1411    if state.to_boolean(1) {
1412        return Ok(state.top() as usize);
1413    }
1414    if matches!(
1415        state.global().lua_version,
1416        lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52
1417    ) {
1418        let msg = state.opt_arg_string(2, b"assertion failed!")?;
1419        return Err(state.where_error(1, &msg));
1420    }
1421    state.check_arg_any(1)?;
1422    state.remove(1)?;
1423    state.push_string(b"assertion failed!")?;
1424    lua_vm::api::set_top(state, 1)?;
1425    error_fn(state)
1426}
1427
1428// ── select ────────────────────────────────────────────────────────────────────
1429
1430/// Returns a slice of its arguments starting at the given index, or returns
1431/// the count of arguments when called with `"#"`.
1432///
1433pub(crate) fn select_fn(state: &mut LuaState) -> Result<usize, LuaError> {
1434    let n = state.top() as i64;
1435    // Check for '#' first byte without holding a borrow across subsequent ops.
1436    let first_is_hash = state.type_at(1) == LuaType::String && {
1437        state
1438            .to_lua_string_bytes(1)
1439            .and_then(|b| b.first().copied())
1440            == Some(b'#')
1441    };
1442    if first_is_hash {
1443        state.push(LuaValue::Int(n - 1));
1444        return Ok(1);
1445    }
1446    let mut i = state.check_arg_integer(1)?;
1447    if i < 0 {
1448        i = n + i;
1449    } else if i > n {
1450        i = n;
1451    }
1452    if i < 1 {
1453        return Err(lua_vm::debug::arg_error_impl(
1454            state,
1455            1,
1456            b"index out of range",
1457        ));
1458    }
1459    // The values at stack positions [i+1 .. n] are already in place; the
1460    // runtime picks up the top (n - i) of them as results.
1461    Ok((n - i) as usize)
1462}
1463
1464// ── pcall ─────────────────────────────────────────────────────────────────────
1465
1466/// Protected call: returns true + results on success, or false + error on
1467/// failure.
1468///
1469pub(crate) fn pcall_fn(state: &mut LuaState) -> Result<usize, LuaError> {
1470    state.check_arg_any(1)?;
1471    // Stack before: [f, a1, …, aN]
1472    // Stack after:  [true, f, a1, …, aN]
1473    state.push(LuaValue::Bool(true));
1474    state.insert(1)?;
1475    // nargs = gettop - 2 (subtract the sentinel `true` and the function).
1476    let nargs = state.top() as i32 - 2;
1477    let yieldable = state.is_yieldable();
1478    let ok = match state.protected_call_k(nargs, LUA_MULTRET, 0, 0, Some(finish_pcall_k)) {
1479        Ok(()) => true,
1480        // `LuaError::Yield` must bubble up to `lua_resume` so the continuation
1481        // saved on this frame can be invoked on resume.
1482        Err(LuaError::Yield) => return Err(LuaError::Yield),
1483        // A sandbox budget trip is uncatchable: re-raise instead of catching so
1484        // untrusted code cannot defeat the budget with `while true do pcall(..) end`.
1485        Err(e) if state.sandbox_aborting() => return Err(e),
1486        Err(e) if yieldable => return Err(e),
1487        Err(e) => {
1488            state.push(e.into_value());
1489            false
1490        }
1491    };
1492    finish_pcall(state, ok, 0)
1493}
1494
1495/// Continuation matching `LuaKFunction`. Invoked by `finishCcall` on the
1496/// resume path after a yield through pcall (or after a `__close` ran during
1497/// pcall error recovery).
1498///
1499fn finish_pcall_k(state: &mut LuaState, status: i32, extra: isize) -> Result<usize, LuaError> {
1500    let ok = status == LuaStatus::Ok as i32 || status == LuaStatus::Yield as i32;
1501    finish_pcall(state, ok, extra as i32)
1502}
1503
1504// ── xpcall ────────────────────────────────────────────────────────────────────
1505
1506/// Protected call with a separate error-handler function.
1507///
1508pub(crate) fn xpcall_fn(state: &mut LuaState) -> Result<usize, LuaError> {
1509    // Lua 5.1's `xpcall(f, h)` does NOT forward extra arguments to `f` — `f` is
1510    // always called with zero arguments. The extra-argument forwarding is a 5.2
1511    // addition. Verified against lua5.1.5: `xpcall(fn, h, 1,2,3)` calls `fn`
1512    // with `select("#",...) == 0`. Drop any args past the handler. See
1513    // specs/followup/5.1-roster-syntax.md §1.
1514    if matches!(state.global().lua_version, lua_types::LuaVersion::V51) && state.top() > 2 {
1515        lua_vm::api::set_top(state, 2)?;
1516    }
1517    let n = state.top() as i32;
1518    state.check_arg_type(2, LuaType::Function)?;
1519    // Stack before rotate: [f, err, a1, …, aN, true, f]
1520    // Stack after rotate:  [f, err, true, f, a1, …, aN]
1521    state.push(LuaValue::Bool(true));
1522    state.push_copy(1)?;
1523    state.rotate(3, 2)?;
1524    // errfunc is at stack index 2; extra=2 means finishpcall skips 2 values.
1525    let yieldable = state.is_yieldable();
1526    let ok = match state.protected_call_k(n - 2, LUA_MULTRET, 2, 2, Some(finish_pcall_k)) {
1527        Ok(()) => true,
1528        Err(LuaError::Yield) => return Err(LuaError::Yield),
1529        // Uncatchable sandbox abort: re-raise without running the message
1530        // handler, so an `xpcall` handler can neither swallow nor loop on it.
1531        Err(e) if state.sandbox_aborting() => return Err(e),
1532        Err(e) if yieldable => return Err(e),
1533        Err(e) => {
1534            state.push(e.into_value());
1535            false
1536        }
1537    };
1538    finish_pcall(state, ok, 2)
1539}
1540
1541// ── tostring ──────────────────────────────────────────────────────────────────
1542
1543/// Converts any value to its string representation.
1544///
1545/// `to_display_string` honors the `__tostring` metamethod (and, from 5.3, the
1546/// `__name` metafield via the VM's type-naming core), pushes the converted
1547/// string, and leaves it on top as this function's single result.
1548pub(crate) fn tostring_fn(state: &mut LuaState) -> Result<usize, LuaError> {
1549    state.check_arg_any(1)?;
1550    state.to_display_string(1)?;
1551    Ok(1)
1552}
1553
1554// ── Registration table ────────────────────────────────────────────────────────
1555
1556/// All base-library functions registered into the global table by `open`.
1557///
1558///
1559/// `_G` and `_VERSION` are not functions and so are absent here; `open()`
1560/// installs them (and the per-version roster deltas) explicitly.
1561pub(crate) const BASE_FUNCS: &[(&[u8], LuaLibFn)] = &[
1562    (b"assert", assert_fn),
1563    (b"collectgarbage", collectgarbage_fn),
1564    (b"dofile", dofile_fn),
1565    (b"error", error_fn),
1566    (b"getmetatable", getmetatable_fn),
1567    (b"ipairs", ipairs_fn),
1568    (b"loadfile", loadfile_fn),
1569    (b"load", load_fn),
1570    (b"next", next_fn),
1571    (b"pairs", pairs_fn),
1572    (b"pcall", pcall_fn),
1573    (b"print", print_fn),
1574    (b"warn", warn_fn),
1575    (b"rawequal", rawequal_fn),
1576    (b"rawlen", rawlen_fn),
1577    (b"rawget", rawget_fn),
1578    (b"rawset", rawset_fn),
1579    (b"select", select_fn),
1580    (b"setmetatable", setmetatable_fn),
1581    (b"tonumber", tonumber_fn),
1582    (b"tostring", tostring_fn),
1583    (b"type", type_fn),
1584    (b"xpcall", xpcall_fn),
1585];
1586
1587// ── Module opener ─────────────────────────────────────────────────────────────
1588
1589/// Open the base library: register all base functions into the global table,
1590/// then set `_G` (a self-reference) and `_VERSION`.
1591///
1592pub fn open(state: &mut LuaState) -> Result<usize, LuaError> {
1593    state.push_globals()?;
1594    state.set_funcs(BASE_FUNCS, 0)?;
1595    state.push_copy(-1)?;
1596    state.set_field(-2, LUA_GNAME)?;
1597    let version_str = state.global().lua_version.version_str();
1598    state.push_string(version_str.as_bytes())?;
1599    state.set_field(-2, b"_VERSION")?;
1600    // `warn` was introduced in Lua 5.4; it is absent on 5.1/5.2/5.3.
1601    if matches!(
1602        state.global().lua_version,
1603        lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53
1604    ) {
1605        state.push(LuaValue::Nil);
1606        state.set_field(-2, b"warn")?;
1607    }
1608    // Lua 5.1/5.2 carry two globals that were removed in 5.3: `unpack` (an alias
1609    // of `table.unpack`) and `loadstring` (an alias of `load`). Verified against
1610    // lua5.2.4: both are functions. The base table is on the stack top here.
1611    if matches!(
1612        state.global().lua_version,
1613        lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52
1614    ) {
1615        state.push_c_function(crate::table_lib::unpack)?;
1616        state.set_field(-2, b"unpack")?;
1617    }
1618    // `loadstring` aliases `load` in 5.2 (whose `load` accepts a string), but in
1619    // 5.1 `load` is reader-only, so `loadstring` is a distinct string-loader.
1620    // Both are absent in 5.3+. See specs/followup/5.1-roster-syntax.md §1.
1621    if matches!(state.global().lua_version, lua_types::LuaVersion::V52) {
1622        state.push_c_function(load_fn)?;
1623        state.set_field(-2, b"loadstring")?;
1624    }
1625    if matches!(state.global().lua_version, lua_types::LuaVersion::V51) {
1626        state.push_c_function(loadstring_fn)?;
1627        state.set_field(-2, b"loadstring")?;
1628        // `gcinfo()` and `newproxy()` are 5.1 holdovers absent in 5.2+.
1629        state.push_c_function(gcinfo_fn)?;
1630        state.set_field(-2, b"gcinfo")?;
1631        state.push_c_function(newproxy_fn)?;
1632        state.set_field(-2, b"newproxy")?;
1633        // `rawlen` is a Lua 5.2 addition; it is absent in 5.1. Verified against
1634        // lua5.1.5: `type(rawlen)` == "nil". It lives in BASE_FUNCS (registered
1635        // for every version), so withhold it under V51.
1636        state.push(LuaValue::Nil);
1637        state.set_field(-2, b"rawlen")?;
1638    }
1639    // Lua 5.1's fenv-based globals model: `getfenv`/`setfenv` read and write a
1640    // function's environment (its `_ENV` upvalue under the reused modern core)
1641    // or the running thread's global table for level 0. Both were removed in
1642    // 5.2 (which switched to lexical `_ENV`), so they are V51-only. See
1643    // specs/followup/5.1-fenv.md.
1644    if matches!(state.global().lua_version, lua_types::LuaVersion::V51) {
1645        state.push_c_function(getfenv_fn)?;
1646        state.set_field(-2, b"getfenv")?;
1647        state.push_c_function(setfenv_fn)?;
1648        state.set_field(-2, b"setfenv")?;
1649    }
1650    Ok(1)
1651}
1652
1653// ──────────────────────────────────────────────────────────────────────────────
1654// PORT STATUS
1655//   source:        src/lbaselib.c (5.1–5.5, version-gated from one source)
1656//   target_crate:  lua-stdlib
1657//   unsafe_blocks: 0
1658//   net:           tests/base_strengthen.rs + multiversion_oracle +
1659//                  official calls/errors/nextvar/constructs + check.sh ×5
1660//   load-bearing:  pcall/xpcall/error unwinding, load/compile, next/pairs/ipairs
1661//                  iteration, collectgarbage, type/tostring/raw* fast paths, and
1662//                  every per-version roster/behavior gate — idiomatize AROUND.
1663//   version-gated: error() prefixes luaL_where onto a NUMBER value on 5.1/5.2
1664//                  (lua_isstring true for numbers) but only strict strings on
1665//                  5.3+. collectgarbage "count" returns a 2nd byte-remainder
1666//                  result on 5.2 only; "generational"/"incremental" are valid on
1667//                  5.2 (return integer 0) / 5.4+ (return the string mode) but
1668//                  invalid on 5.3 (per-version OPTS_5x sets). debug_getfenv_fn/
1669//                  debug_setfenv_fn are the 5.1 object-form fenv accessors used
1670//                  by debug_lib (distinct from the level-aware getfenv/setfenv).
1671//   deferred:      __name pre-5.3 gating + 5.1/5.2 arg-error fn-name ('?'/'_G.')
1672//                  live in lua-vm (obj_type_name_cow / arg_error_impl); see the
1673//                  module header. Not base-fixable. 5.2 collectgarbage
1674//                  "setmajorinc" (a generational-GC param) is also out of scope.
1675// ──────────────────────────────────────────────────────────────────────────────