Skip to main content

lua_stdlib/
loadlib.rs

1//! The Lua `package` library: `require`, `package.loadlib`,
2//! `package.searchpath`, and the four built-in module searchers (preload,
3//! Lua-file, C-library, C-root).
4//!
5//! ## Graduation (Idiomatization Sprint 2 / Phase 2 — cold, platform-FFI module)
6//!
7//! Split cleanly into two regimes, and treated as such:
8//!
9//! * **Deterministic pure-Lua package logic** — now guarded by
10//!   `tests/loadlib_strengthen.rs` (16 reference-pinned cross-version
11//!   assertions). Strengthening that net FIRST caught **seven** divergences our
12//!   weaker net hid: the 5.1 `package.config` trailing newline, `require`'s 5.4+
13//!   2nd return value, the 5.1 preload-loader arg count, a C-root searcher
14//!   message truncation, the `nil`-vs-`false` `luaL_pushfail` value, the 5.1
15//!   absence of `package.searchpath`, and the 5.2/5.3 searchpath-error leading
16//!   separator. All were fixed via single-source version helpers; the version
17//!   gates are explicit and load-bearing. See `GRADUATED.md` "loadlib".
18//! * **Platform / dynamic-loading FFI** — left LOAD-BEARING and untouched. The
19//!   three platform calls (`lsys_load`, `lsys_sym`, `lsys_unloadlib`) dispatch
20//!   through embedder hooks on [`lua_vm::state::GlobalState`]
21//!   (`dynlib_load_hook`, `dynlib_symbol_hook`, `dynlib_unload_hook`); `lua-cli`
22//!   installs a `libloading`-backed (genuinely `unsafe`) implementation, while
23//!   embeddings that omit the hooks behave like C-Lua's fallback stub
24//!   (`LIB_FAIL = "absent"`). This indirection keeps `lua-stdlib` itself
25//!   `unsafe`-free (`unsafe_code = "forbid"`); the real FFI bridge lives in
26//!   `lua-cli`. Its behavior — the dlopen/dlsym path, the platform error
27//!   strings, the `"open"`/`"absent"`/`"init"` tags — needs a real shared
28//!   object and host loader, so it is NOT reference-pinnable and is a documented
29//!   honest-negative (the analogue of math's platform `rand()`).
30
31use crate::state_stub::{lua_CFunction, LuaState, LuaStateStubExt as _};
32use lua_types::{LuaError, LuaType, LuaValue};
33use lua_vm::state::{DynLibId, DynamicSymbol};
34
35// ── Module-level constants ────────────────────────────────────────────────────
36
37const LUA_POF: &[u8] = b"luaopen_";
38
39const LUA_OFSEP: &[u8] = b"_";
40
41const CLIBS: &[u8] = b"_CLIBS";
42
43// `lsys_load` chooses the tag at runtime: `"open"` when a load hook is
44// installed (matching POSIX/Windows behaviour) and `"absent"` when no hook
45// is registered (matching the fallback stub). The constant below carries the
46// fallback-stub spelling; the load-hook path uses `b"open"` directly.
47const LIB_FAIL_ABSENT: &[u8] = b"absent";
48
49const LUA_PATH_SEP: u8 = b';';
50
51const LUA_PATH_MARK: u8 = b'?';
52
53const LUA_IGMARK: u8 = b'-';
54
55#[cfg(target_os = "windows")]
56const LUA_DIRSEP: u8 = b'\\';
57#[cfg(not(target_os = "windows"))]
58const LUA_DIRSEP: u8 = b'/';
59
60// Both default to LUA_DIRSEP on all platforms.
61const LUA_CSUBSEP: u8 = LUA_DIRSEP;
62const LUA_LSUBSEP: u8 = LUA_DIRSEP;
63
64// The fail-tag spelling travels with `LookForFuncStatus` (below) rather than a
65// single compile-time `LIB_FAIL` constant, so each failure carries its own tag.
66
67// Pushed when no `dynlib_load_hook`/`dynlib_symbol_hook` is registered on
68// `GlobalState`. With a backend installed the CLI supplies its own error
69// strings via the hook's `Err` return for "open" failures.
70const DLMSG: &[u8] = b"dynamic libraries not enabled; check your Lua installation";
71
72// Message returned via `(false, msg, "init")` when a hook resolves a symbol
73// against stock Lua 5.4's `lua_State *` C ABI. That ABI is not callable
74// against this build's `LuaState`; supporting it is a separate compatibility
75// project (see docs/LUA_PHASE_E_RUNTIME_SPEC.md Part 3).
76const C_ABI_UNSUPPORTED_MSG: &[u8] =
77    b"dynamic library loaded, but Lua C ABI modules are not supported by this build";
78
79const LUA_PATH_VAR: &[u8] = b"LUA_PATH";
80const LUA_CPATH_VAR: &[u8] = b"LUA_CPATH";
81
82// Matches C-Lua's luaconf.h defaults exactly: LUA_LDIR entries first, then
83// LUA_CDIR entries, then the local ./? fallback last.
84// TODO(port): These should come from a platform configuration crate, not be
85// hardcoded. Lua's build system inserts the actual install prefix here.
86#[cfg(not(target_os = "windows"))]
87const LUA_PATH_DEFAULT: &[u8] = b"/usr/local/share/lua/5.4/?.lua;/usr/local/share/lua/5.4/?/init.lua;/usr/local/lib/lua/5.4/?.lua;/usr/local/lib/lua/5.4/?/init.lua;./?.lua;./?/init.lua";
88#[cfg(target_os = "windows")]
89const LUA_PATH_DEFAULT: &[u8] = b"./?.lua;./?/init.lua";
90
91#[cfg(not(target_os = "windows"))]
92const LUA_CPATH_DEFAULT: &[u8] =
93    b"/usr/local/lib/lua/5.4/?.so;/usr/local/lib/lua/5.4/loadall.so;./?.so";
94#[cfg(target_os = "windows")]
95const LUA_CPATH_DEFAULT: &[u8] = b"./?.dll";
96
97// TODO(port): Centralise version constants; this is duplicated from luaconf.h.
98const LUA_VERSUFFIX: &[u8] = b"_5_4";
99
100/// Build the `package.config` string for `version`.
101///
102/// Five lines encoding the platform separators: directory separator, path
103/// separator, the `?` substitution mark, the `!` exec-dir mark, and the `-`
104/// ignore mark. The trailing newline after the ignore mark is a **5.2 addition**
105/// (`LUA_IGMARK "\n"` in 5.2+ `loadlib.c`); 5.1's string ends at `-`, so 5.1 is
106/// 9 bytes and 5.2+ are 10 (pinned in `tests/loadlib_strengthen.rs`).
107fn package_config(version: lua_types::LuaVersion) -> Vec<u8> {
108    let mut config = vec![
109        LUA_DIRSEP,
110        b'\n',
111        LUA_PATH_SEP,
112        b'\n',
113        LUA_PATH_MARK,
114        b'\n',
115        b'!',
116        b'\n',
117        LUA_IGMARK,
118    ];
119    if !matches!(version, lua_types::LuaVersion::V51) {
120        config.push(b'\n');
121    }
122    config
123}
124
125fn getenv_bytes(state: &LuaState, name: &[u8]) -> Option<Vec<u8>> {
126    if let Some(env_fn) = state.global().env_hook {
127        return env_fn(name);
128    }
129
130    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
131    {
132        None
133    }
134
135    #[cfg(all(unix, not(all(target_arch = "wasm32", target_os = "unknown"))))]
136    {
137        use std::ffi::OsStr;
138        use std::os::unix::ffi::{OsStrExt, OsStringExt};
139
140        let os_name = OsStr::from_bytes(name);
141        std::env::var_os(os_name).map(|v| v.into_vec())
142    }
143
144    #[cfg(all(not(unix), not(all(target_arch = "wasm32", target_os = "unknown"))))]
145    {
146        std::str::from_utf8(name)
147            .ok()
148            .and_then(|name_str| std::env::var(name_str).ok())
149            .map(|s| s.into_bytes())
150    }
151}
152
153// ── Opaque library handle ─────────────────────────────────────────────────────
154//
155//
156// In this port, the library identity is the opaque `DynLibId(u64)` allocated
157// by the embedder-installed [`DynLibLoadHook`]. `lua-stdlib` never inspects
158// the value; it stashes the raw `u64` in `_CLIBS` as light userdata (cast
159// through `*mut c_void` to match C-Lua's representation) and hands it back to
160// the symbol and unload hooks.
161
162// ── Byte-string utilities ─────────────────────────────────────────────────────
163
164/// Append to `buf` the bytes of `s` with all non-overlapping occurrences of
165/// `pattern` replaced by `replacement`.
166///
167fn gsub_append(buf: &mut Vec<u8>, s: &[u8], pattern: &[u8], replacement: &[u8]) {
168    if pattern.is_empty() {
169        buf.extend_from_slice(s);
170        return;
171    }
172    let mut pos = 0;
173    while pos < s.len() {
174        if s[pos..].starts_with(pattern) {
175            buf.extend_from_slice(replacement);
176            pos += pattern.len();
177        } else {
178            buf.push(s[pos]);
179            pos += 1;
180        }
181    }
182}
183
184/// Return a new `Vec<u8>` with all non-overlapping occurrences of `pattern`
185/// in `s` replaced by `replacement`.
186fn gsub_bytes(s: &[u8], pattern: &[u8], replacement: &[u8]) -> Vec<u8> {
187    let mut out = Vec::new();
188    gsub_append(&mut out, s, pattern, replacement);
189    out
190}
191
192/// Find the byte offset of `needle` in `haystack`, or `None`.
193fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
194    if needle.is_empty() {
195        return Some(0);
196    }
197    haystack.windows(needle.len()).position(|w| w == needle)
198}
199
200// ── Platform-specific dynamic-loading dispatch ────────────────────────────────
201
202/// Unload a previously loaded C library.
203///
204///    — POSIX: `dlclose(lib)`; Windows: `FreeLibrary(lib)`.
205///
206/// Delegates to [`GlobalState::dynlib_unload_hook`]. When no hook is
207/// registered the library is leaked, which matches `libloading`'s safety
208/// model (the library must outlive every symbol it exports, and the simplest
209/// correct policy is to keep it alive for the state's lifetime).
210fn lsys_unloadlib(state: &mut LuaState, lib: DynLibId) {
211    if let Some(hook) = state.global().dynlib_unload_hook {
212        hook(lib);
213    }
214}
215
216/// Load a C library from `path`. If `see_glb` is true, make symbols globally
217/// visible (POSIX RTLD_GLOBAL). On failure, pushes an error string onto `state`.
218///
219///    — POSIX: `dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL))`
220///    — Windows: `LoadLibraryExA(path, NULL, LUA_LLE_FLAGS)`
221///
222/// Returns `(handle, lib_fail_tag)`. The tag is `"absent"` when no hook is
223/// registered (matching C's fallback-stub `LIB_FAIL`) and `"open"` when the
224/// hook itself reports a failure (matching POSIX/Windows builds).
225fn lsys_load(
226    state: &mut LuaState,
227    path: &[u8],
228    see_glb: bool,
229) -> (Option<DynLibId>, &'static [u8]) {
230    let hook = state.global().dynlib_load_hook;
231    let Some(load_fn) = hook else {
232        let s = match state.intern_str(DLMSG) {
233            Ok(s) => s,
234            Err(_) => return (None, LIB_FAIL_ABSENT),
235        };
236        state.push(LuaValue::Str(s));
237        return (None, LIB_FAIL_ABSENT);
238    };
239    match load_fn(state, path, see_glb) {
240        Ok(id) => (Some(id), b"open"),
241        // `LuaError::File` is reserved for "no shared library at this path":
242        // map it to the fallback-stub `"absent"` tag so a probe like
243        // `package.loadlib("./nonexistent.so", ...)` reports `"absent"`
244        // regardless of whether a backend is installed. Every other `Err` is a
245        // true open-time failure → `"open"`.
246        Err(LuaError::File) => {
247            let mut msg = b"cannot find library '".to_vec();
248            msg.extend_from_slice(path);
249            msg.push(b'\'');
250            let s = match state.intern_str(&msg) {
251                Ok(s) => s,
252                Err(_) => return (None, LIB_FAIL_ABSENT),
253            };
254            state.push(LuaValue::Str(s));
255            (None, LIB_FAIL_ABSENT)
256        }
257        Err(err) => {
258            let msg = error_to_bytes(&err);
259            let s = match state.intern_str(&msg) {
260                Ok(s) => s,
261                Err(_) => return (None, b"open"),
262            };
263            state.push(LuaValue::Str(s));
264            (None, b"open")
265        }
266    }
267}
268
269/// Find symbol `sym` in library `lib` and either push it as a callable Lua
270/// function (returning `SymOutcome::Found`) or push an error message string
271/// and report which failure category the caller should propagate.
272///
273///    — POSIX: `cast_func(dlsym(lib, sym))`
274///    — Windows: `(lua_CFunction)(voidf)GetProcAddress(lib, sym)`
275fn lsys_sym(state: &mut LuaState, lib: DynLibId, sym: &[u8]) -> SymOutcome {
276    let hook = state.global().dynlib_symbol_hook;
277    let Some(sym_fn) = hook else {
278        let s = match state.intern_str(DLMSG) {
279            Ok(s) => s,
280            Err(_) => return SymOutcome::Missing,
281        };
282        state.push(LuaValue::Str(s));
283        return SymOutcome::Missing;
284    };
285    match sym_fn(state, lib, sym) {
286        Ok(DynamicSymbol::RustNative(f)) => SymOutcome::Found(f),
287        Ok(DynamicSymbol::LuaCAbi(_)) => {
288            let s = match state.intern_str(C_ABI_UNSUPPORTED_MSG) {
289                Ok(s) => s,
290                Err(_) => return SymOutcome::Missing,
291            };
292            state.push(LuaValue::Str(s));
293            SymOutcome::Missing
294        }
295        Ok(DynamicSymbol::Unsupported { reason }) => {
296            let s = match state.intern_str(&reason) {
297                Ok(s) => s,
298                Err(_) => return SymOutcome::Missing,
299            };
300            state.push(LuaValue::Str(s));
301            SymOutcome::Missing
302        }
303        Err(err) => {
304            let msg = error_to_bytes(&err);
305            let s = match state.intern_str(&msg) {
306                Ok(s) => s,
307                Err(_) => return SymOutcome::Missing,
308            };
309            state.push(LuaValue::Str(s));
310            SymOutcome::Missing
311        }
312    }
313}
314
315/// Outcome of `lsys_sym`.
316///
317/// `Missing` covers every non-success path (unknown symbol, ABI mismatch, hook
318/// absent, embedder-supplied refusal); in every case an error-message string
319/// has already been pushed onto the Lua stack, so the caller maps `Missing`
320/// to `ERRFUNC` / `"init"` without further work.
321enum SymOutcome {
322    /// Resolved to a Rust-native callable.
323    Found(lua_CFunction),
324    /// Resolution failed; an error-message string is on the stack.
325    Missing,
326}
327
328/// Extract a byte-string error message from a `LuaError`, falling back to a
329/// debug rendering for non-string variants.
330fn error_to_bytes(e: &LuaError) -> Vec<u8> {
331    match e {
332        LuaError::Runtime(LuaValue::Str(s)) | LuaError::Syntax(LuaValue::Str(s)) => {
333            s.as_bytes().to_vec()
334        }
335        other => format!("{:?}", other).into_bytes(),
336    }
337}
338
339/// Encode a [`DynLibId`] as a `*mut c_void` for storage in `_CLIBS` as light
340/// userdata. The cast is the inverse of [`decode_dynlib_id`]; neither side
341/// ever dereferences the pointer.
342fn encode_dynlib_id(id: DynLibId) -> *mut std::ffi::c_void {
343    id.0 as usize as *mut std::ffi::c_void
344}
345
346/// Decode a [`DynLibId`] previously stored via [`encode_dynlib_id`].
347fn decode_dynlib_id(p: *mut std::ffi::c_void) -> DynLibId {
348    DynLibId(p as usize as u64)
349}
350
351// ── Path helpers ──────────────────────────────────────────────────────────────
352
353/// Return `registry["LUA_NOENV"]` as a boolean.
354///
355fn noenv(state: &mut LuaState) -> bool {
356    let _ = state.get_field_registry(b"LUA_NOENV");
357    let b = state.to_boolean(-1);
358    state.pop_n(1);
359    b
360}
361
362/// Set `package[fieldname]` to the appropriate path value.
363///
364/// Priority: versioned env var (e.g. `LUA_PATH_5_4`) → unversioned env var
365/// (`LUA_PATH`) → compiled-in default. When the env var contains `;;`, the
366/// compiled-in default is spliced in place of `;;`. The caller must leave the
367/// `package` table at the stack top; the path value is set on it directly (the
368/// versioned env-var name is computed off-stack, so no index bookkeeping is
369/// needed).
370fn setpath(
371    state: &mut LuaState,
372    fieldname: &[u8],
373    envname: &[u8],
374    dft: &[u8],
375) -> Result<(), LuaError> {
376    let mut nver = envname.to_vec();
377    nver.extend_from_slice(LUA_VERSUFFIX);
378
379    let path_opt = if noenv(state) {
380        None
381    } else {
382        getenv_bytes(state, &nver).or_else(|| getenv_bytes(state, envname))
383    };
384
385    let final_path: Vec<u8> = if path_opt.is_none() {
386        dft.to_vec()
387    } else {
388        let path = path_opt.unwrap();
389        let double_sep = [LUA_PATH_SEP, LUA_PATH_SEP];
390        if let Some(dftmark_pos) = find_subslice(&path, &double_sep) {
391            // Path contains ";;": replace with default.
392            let mut buf = Vec::new();
393            if dftmark_pos > 0 {
394                buf.extend_from_slice(&path[..dftmark_pos]);
395                buf.push(LUA_PATH_SEP);
396            }
397            buf.extend_from_slice(dft);
398            let after = dftmark_pos + 2;
399            if after < path.len() {
400                buf.push(LUA_PATH_SEP);
401                buf.extend_from_slice(&path[after..]);
402            }
403            buf
404        } else {
405            path
406        }
407    };
408
409    // The Windows `setprogdir` step (replace `LUA_EXEC_DIR` with the running
410    // executable's directory via `GetModuleFileNameA`, a Win32/`unsafe` call) is
411    // a no-op on every other platform and is not yet implemented here, so the
412    // `LUA_EXEC_DIR` substitution is skipped.
413    let s = state.intern_str(&final_path)?;
414    state.push(LuaValue::Str(s));
415    state.set_field(-2, fieldname)?;
416
417    Ok(())
418}
419
420// ── CLIBS registry table ──────────────────────────────────────────────────────
421
422/// Return the library handle stored at `registry._CLIBS[path]`, or `None`.
423///
424fn checkclib(state: &mut LuaState, path: &[u8]) -> Option<DynLibId> {
425    let _ = state.get_field_registry(CLIBS);
426    let _ = state.get_field(-1, path);
427    let handle = state.to_light_userdata(-1).map(decode_dynlib_id);
428    state.pop_n(2);
429    handle
430}
431
432/// Register a library handle in the CLIBS table (both by path and sequentially).
433///
434fn addtoclib(state: &mut LuaState, path: &[u8], plib: DynLibId) -> Result<(), LuaError> {
435    state.get_field_registry(CLIBS)?;
436    state.push(LuaValue::LightUserData(encode_dynlib_id(plib)));
437    state.push_value(-1)?;
438    state.set_field(-3, path)?;
439    let n = state.len_at(-2);
440    state.raw_seti(-2, n + 1)?;
441    state.pop_n(1);
442    Ok(())
443}
444
445/// `__gc` metamethod for the CLIBS table: unloads all registered C libraries
446/// in reverse order when the Lua state closes.
447///
448fn gctm(state: &mut LuaState) -> Result<usize, LuaError> {
449    let n = state.len_at(1);
450    let mut i = n;
451    while i >= 1 {
452        state.raw_geti(1, i)?;
453        if let Some(handle) = state.to_light_userdata(-1).map(decode_dynlib_id) {
454            lsys_unloadlib(state, handle);
455        }
456        state.pop_n(1);
457        i -= 1;
458    }
459    Ok(0)
460}
461
462// ── Dynamic function lookup ───────────────────────────────────────────────────
463
464/// Outcome of looking for a C function in a dynamically loaded library.
465///
466/// On success the function (or `true` for the `*` sentinel) is on the stack;
467/// on a non-fatal failure an error-message string is on the stack and the
468/// variant tells the caller what to report. Fatal errors propagate via `Err`.
469/// `Ok` is C's success; `ErrLib(tag)` is C's `ERRLIB` carrying the `LIB_FAIL`
470/// string (`"open"` for a true dlopen failure, `"absent"` when no backend is
471/// installed or the file does not exist); `ErrFunc` is C's `ERRFUNC` (the
472/// library opened but the symbol was not found).
473enum LookForFuncStatus {
474    /// Loader successfully resolved a symbol (function pushed on stack).
475    Ok,
476    /// Library could not be opened. `tag` is the `LIB_FAIL` string.
477    ErrLib(&'static [u8]),
478    /// Library opened but symbol could not be resolved.
479    ErrFunc,
480}
481
482fn lookforfunc(
483    state: &mut LuaState,
484    path: &[u8],
485    sym: &[u8],
486) -> Result<LookForFuncStatus, LuaError> {
487    let reg = match checkclib(state, path) {
488        Some(handle) => handle,
489        None => {
490            let (loaded, tag) = lsys_load(state, path, sym.first() == Some(&b'*'));
491            match loaded {
492                Some(handle) => {
493                    addtoclib(state, path, handle)?;
494                    handle
495                }
496                None => return Ok(LookForFuncStatus::ErrLib(tag)),
497            }
498        }
499    };
500    if sym.first() == Some(&b'*') {
501        state.push(LuaValue::Bool(true));
502        return Ok(LookForFuncStatus::Ok);
503    }
504    match lsys_sym(state, reg, sym) {
505        SymOutcome::Found(func) => {
506            state.push_c_function(func)?;
507            Ok(LookForFuncStatus::Ok)
508        }
509        SymOutcome::Missing => Ok(LookForFuncStatus::ErrFunc),
510    }
511}
512
513// ── Lua-callable package functions ────────────────────────────────────────────
514
515/// `package.loadlib(filename, funcname)` — open a C library and return a
516/// Lua-callable wrapper for `funcname`.
517///
518/// Returns: on success, the loader function (1 value).
519/// On error: `false`, error-message string, and `"open"` or `"init"` (3 values).
520///
521pub fn ll_loadlib(state: &mut LuaState) -> Result<usize, LuaError> {
522    let path = state.check_arg_string(1)?.to_vec();
523    let init = state.check_arg_string(2)?.to_vec();
524    let stat = lookforfunc(state, &path, &init)?;
525    let where_bytes: &[u8] = match stat {
526        LookForFuncStatus::Ok => return Ok(1),
527        LookForFuncStatus::ErrLib(tag) => tag,
528        LookForFuncStatus::ErrFunc => b"init",
529    };
530    // `luaL_pushfail` is `lua_pushnil` on every version (5.4 included); the fail
531    // value is `nil`, not `false`. The `LIB_FAIL` tag is chosen at run time: the
532    // CLI backend reports `LuaError::File` for a missing library → `"absent"`
533    // (matching C-Lua's no-dlfcn fallback), a true `dlopen` failure → `"open"`,
534    // and the "init" branch (symbol resolution failed after the library opened)
535    // is identical in every build.
536    state.push(LuaValue::Nil);
537    state.insert(-2)?;
538    let where_s = state.intern_str(where_bytes)?;
539    state.push(LuaValue::Str(where_s));
540    Ok(3)
541}
542
543// ── File existence check ──────────────────────────────────────────────────────
544
545/// Whether `filename` can be opened for reading.
546///
547/// `std::fs` is banned in `lua-stdlib`, so the probe is delegated to the
548/// embedder-registered `file_loader_hook` on `GlobalState`. Without a hook
549/// installed, `readable` reports `false` (the file system is unreachable) — so
550/// the in-process searcher tests deterministically see every path as not-found.
551fn readable(state: &LuaState, filename: &[u8]) -> bool {
552    match state.global().file_loader_hook {
553        Some(hook) => hook(filename).is_ok(),
554        None => false,
555    }
556}
557
558// ── Path-component iterator ───────────────────────────────────────────────────
559
560/// Iterator over `;`-separated path-template components, yielding each as an
561/// immutable slice (the C original walked one mutable buffer, swapping each
562/// separator for a NUL and back; this produces the identical sequence).
563struct PathComponents<'a> {
564    remaining: &'a [u8],
565}
566
567impl<'a> PathComponents<'a> {
568    fn new(path: &'a [u8]) -> Self {
569        PathComponents { remaining: path }
570    }
571}
572
573impl<'a> Iterator for PathComponents<'a> {
574    type Item = &'a [u8];
575
576    fn next(&mut self) -> Option<Self::Item> {
577        if self.remaining.is_empty() {
578            return None;
579        }
580        let component = match self.remaining.iter().position(|&b| b == LUA_PATH_SEP) {
581            Some(sep_pos) => {
582                let c = &self.remaining[..sep_pos];
583                self.remaining = &self.remaining[sep_pos + 1..];
584                c
585            }
586            None => {
587                let c = self.remaining;
588                self.remaining = &[];
589                c
590            }
591        };
592        Some(component)
593    }
594}
595
596// ── Error-message helpers ─────────────────────────────────────────────────────
597
598/// Push an error message listing all files in `path` that were not found.
599///
600/// Example output: `"no file 'a.lua'\n\tno file 'b.lua'"`
601///
602fn pusherrornotfound(state: &mut LuaState, path: &[u8]) -> Result<(), LuaError> {
603    let mut buf: Vec<u8> = Vec::new();
604    buf.extend_from_slice(b"no file '");
605    gsub_append(&mut buf, path, &[LUA_PATH_SEP], b"'\n\tno file '");
606    buf.push(b'\'');
607    let s = state.intern_str(&buf)?;
608    state.push(LuaValue::Str(s));
609    Ok(())
610}
611
612// ── Path search ───────────────────────────────────────────────────────────────
613
614/// Search for a readable file matching `name` in the `;`-separated `path`.
615///
616/// `sep` bytes in `name` are first replaced by `dirsep`; then each template's
617/// `?` is replaced by the adjusted name. On the first readable match, pushes the
618/// filename string and returns `Some(filename_bytes)`; otherwise pushes the
619/// not-found message and returns `None`.
620fn searchpath(
621    state: &mut LuaState,
622    name: &[u8],
623    path: &[u8],
624    sep: &[u8],
625    dirsep: &[u8],
626) -> Result<Option<Vec<u8>>, LuaError> {
627    let name_buf: Vec<u8> = if !sep.is_empty() && name.contains(&sep[0]) {
628        gsub_bytes(name, sep, dirsep)
629    } else {
630        name.to_vec()
631    };
632
633    let pathname: Vec<u8> = gsub_bytes(path, &[LUA_PATH_MARK], &name_buf);
634
635    for filename in PathComponents::new(&pathname) {
636        if readable(state, filename) {
637            let s = state.intern_str(filename)?;
638            state.push(LuaValue::Str(s));
639            return Ok(Some(filename.to_vec()));
640        }
641    }
642
643    pusherrornotfound(state, &pathname)?;
644    Ok(None)
645}
646
647/// `package.searchpath(name, path [, sep [, rep]])`.
648///
649/// Returns the first readable file in `path` with `sep` occurrences in `name`
650/// replaced by `rep`. On failure returns `luaL_pushfail` (a `nil`, NOT `false`,
651/// on every version) plus the error message. See [`ll_loadlib`] for the same
652/// `luaL_pushfail` = `lua_pushnil` translation.
653pub fn ll_searchpath(state: &mut LuaState) -> Result<usize, LuaError> {
654    let name = state.check_arg_string(1)?.to_vec();
655    let path = state.check_arg_string(2)?.to_vec();
656    let sep = state.opt_arg_string(3, b".")?;
657    let dirsep_default = [LUA_DIRSEP];
658    let dirsep = state.opt_arg_string(4, &dirsep_default)?;
659
660    let found = searchpath(state, &name, &path, &sep, &dirsep)?;
661    if found.is_some() {
662        return Ok(1);
663    }
664    if searchpath_error_has_leading_separator(state.global().lua_version) {
665        prepend_searchpath_separator(state)?;
666    }
667    state.push(LuaValue::Nil);
668    state.insert(-2)?;
669    Ok(2)
670}
671
672/// Whether the standalone `package.searchpath` error message carries a leading
673/// `\n\t` separator before its first `no file '…'` line.
674///
675/// In 5.2/5.3 the `searchpath` helper builds each entry as `"\n\tno file '%s'"`,
676/// so the first line is prefixed too; 5.4 moved that prefix into `findloader`'s
677/// per-iteration accumulator and made `searchpath`'s own message bare (the form
678/// this port's `pusherrornotfound` produces). The `require` trace is unaffected
679/// either way — there `findloader` supplies the single `\n\t` per searcher — so
680/// the seam is observable ONLY through the standalone Lua function. (5.1 has no
681/// `package.searchpath`.) Pinned in `tests/loadlib_strengthen.rs`.
682fn searchpath_error_has_leading_separator(version: lua_types::LuaVersion) -> bool {
683    matches!(version, lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53)
684}
685
686/// Replace the not-found message on the stack top with one carrying a leading
687/// `\n\t` (the 5.2/5.3 `searchpath` form). The message produced by
688/// `pusherrornotfound` is bare; this restores the legacy prefix.
689fn prepend_searchpath_separator(state: &mut LuaState) -> Result<(), LuaError> {
690    let Some(bare) = state.to_bytes(-1) else {
691        return Ok(());
692    };
693    state.pop_n(1);
694    let mut prefixed = b"\n\t".to_vec();
695    prefixed.extend_from_slice(&bare);
696    let s = state.intern_str(&prefixed)?;
697    state.push(LuaValue::Str(s));
698    Ok(())
699}
700
701/// Find a module file using the path stored in `package[pname]` (e.g.
702/// `package.path` / `package.cpath`), read from upvalue #1 of the searcher
703/// closure. Errors if that field is not a string.
704fn findfile(
705    state: &mut LuaState,
706    name: &[u8],
707    pname: &[u8],
708    dirsep: u8,
709) -> Result<Option<Vec<u8>>, LuaError> {
710    let uv = state.upvalue_index(1);
711    let _ = state.get_field(uv, pname);
712    let path_opt: Option<Vec<u8>> = state.to_bytes(-1);
713    let Some(path) = path_opt else {
714        state.pop_n(1);
715        return Err(LuaError::runtime(format_args!(
716            "'package.{}' must be a string",
717            String::from_utf8_lossy(pname)
718        )));
719    };
720    state.pop_n(1);
721    searchpath(state, name, &path, b".", &[dirsep])
722}
723
724/// Check whether a module load succeeded, returning the open function + filename
725/// (2 values) on success or raising an error on failure.
726///
727fn checkload(state: &mut LuaState, stat: bool, filename: &[u8]) -> Result<usize, LuaError> {
728    if stat {
729        let s = state.intern_str(filename)?;
730        state.push(LuaValue::Str(s));
731        Ok(2)
732    } else {
733        // The error embeds the module name (the `require` arg at stack[1]) and
734        // the loader's own error message (the searcher's pushed string at the
735        // stack top). Both are owned byte copies, so there is no aliasing.
736        let modname = state.to_bytes(1).unwrap_or_else(|| b"?".to_vec());
737        let loader_err = state.to_bytes(-1).unwrap_or_else(|| b"?".to_vec());
738
739        let mut msg = b"error loading module '".to_vec();
740        msg.extend_from_slice(&modname);
741        msg.extend_from_slice(b"' from file '");
742        msg.extend_from_slice(filename);
743        msg.extend_from_slice(b"':\n\t");
744        msg.extend_from_slice(&loader_err);
745
746        let s = state.intern_str(&msg)?;
747        return Err(LuaError::from_value(LuaValue::Str(s)));
748    }
749}
750
751// ── Searcher functions ────────────────────────────────────────────────────────
752
753/// Searcher that looks in `package.path` for a Lua source file.
754///
755/// Returns 1 value (error-message string) if not found, or 2 values (loader
756/// function, filename) if found and loaded successfully.
757///
758fn searcher_lua(state: &mut LuaState) -> Result<usize, LuaError> {
759    let name = state.check_arg_string(1)?.to_vec();
760    let filename = findfile(state, &name, b"path", LUA_LSUBSEP)?;
761    if filename.is_none() {
762        return Ok(1);
763    }
764    let filename = filename.unwrap();
765    // `std::fs` is banned in `lua-stdlib`, so file contents arrive via the
766    // embedder-registered `file_loader_hook` on `GlobalState`; the bytes are then
767    // parsed through `state.load(...)` (which dispatches to the parser hook) and
768    // the resulting closure is left on the stack for `checkload` to pair with the
769    // filename.
770    let chunk = match state.global().file_loader_hook {
771        Some(hook) => hook(&filename),
772        None => Err(LuaError::runtime(format_args!(
773            "no file_loader_hook registered; cannot read '{}'",
774            String::from_utf8_lossy(&filename)
775        ))),
776    };
777    let load_ok = match chunk {
778        Ok(bytes) => {
779            // Use a chunk name of the form `@filename` matching C's luaL_loadfilex.
780            let mut chunkname = b"@".to_vec();
781            chunkname.extend_from_slice(&filename);
782            match state.load(&bytes, &chunkname, None) {
783                Ok(true) => true,
784                Ok(false) => false,
785                Err(e) => {
786                    let msg = match e {
787                        LuaError::Syntax(LuaValue::Str(ref s))
788                        | LuaError::Runtime(LuaValue::Str(ref s)) => s.as_bytes().to_vec(),
789                        other => format!("{:?}", other).into_bytes(),
790                    };
791                    let s = state.intern_str(&msg)?;
792                    state.push(LuaValue::Str(s));
793                    false
794                }
795            }
796        }
797        Err(e) => {
798            let msg = match e {
799                LuaError::Runtime(LuaValue::Str(ref s)) => s.as_bytes().to_vec(),
800                other => format!("{:?}", other).into_bytes(),
801            };
802            let s = state.intern_str(&msg)?;
803            state.push(LuaValue::Str(s));
804            false
805        }
806    };
807    checkload(state, load_ok, &filename)
808}
809
810/// Try to load `modname`'s open function from the C dynamic library at `filename`.
811///
812/// Handles the "ignore mark" (`-`) convention: `"foo-bar"` first tries
813/// `luaopen_foo`, then `luaopen_bar` as a fallback.
814///
815fn loadfunc(
816    state: &mut LuaState,
817    filename: &[u8],
818    modname: &[u8],
819) -> Result<LookForFuncStatus, LuaError> {
820    let modname: Vec<u8> = gsub_bytes(modname, b".", LUA_OFSEP);
821
822    if let Some(mark_pos) = modname.iter().position(|&b| b == LUA_IGMARK) {
823        let prefix = &modname[..mark_pos];
824        let mut openfunc = LUA_POF.to_vec();
825        openfunc.extend_from_slice(prefix);
826        let stat = lookforfunc(state, filename, &openfunc)?;
827        if !matches!(stat, LookForFuncStatus::ErrFunc) {
828            return Ok(stat);
829        }
830        let tail = &modname[mark_pos + 1..];
831        let mut openfunc2 = LUA_POF.to_vec();
832        openfunc2.extend_from_slice(tail);
833        return lookforfunc(state, filename, &openfunc2);
834    }
835
836    let mut openfunc = LUA_POF.to_vec();
837    openfunc.extend_from_slice(&modname);
838    lookforfunc(state, filename, &openfunc)
839}
840
841/// Searcher that looks in `package.cpath` for a C dynamic library.
842///
843fn searcher_c(state: &mut LuaState) -> Result<usize, LuaError> {
844    let name = state.check_arg_string(1)?.to_vec();
845    let filename = findfile(state, &name, b"cpath", LUA_CSUBSEP)?;
846    if filename.is_none() {
847        return Ok(1);
848    }
849    let filename = filename.unwrap();
850    let stat = loadfunc(state, &filename, &name)?;
851    let ok = matches!(stat, LookForFuncStatus::Ok);
852    checkload(state, ok, &filename)
853}
854
855/// Searcher that looks in `package.cpath` using only the root component
856/// (everything before the first `.`) of the module name.
857///
858fn searcher_croot(state: &mut LuaState) -> Result<usize, LuaError> {
859    let name = state.check_arg_string(1)?.to_vec();
860    let dot_pos = name.iter().position(|&b| b == b'.');
861    if dot_pos.is_none() {
862        return Ok(0);
863    }
864    let dot_pos = dot_pos.unwrap();
865
866    let root = &name[..dot_pos];
867
868    let filename = findfile(state, root, b"cpath", LUA_CSUBSEP)?;
869
870    if filename.is_none() {
871        return Ok(1);
872    }
873    let filename = filename.unwrap();
874
875    let stat = loadfunc(state, &filename, &name)?;
876    match stat {
877        LookForFuncStatus::Ok => {}
878        LookForFuncStatus::ErrFunc => {
879            let mut msg = b"no module '".to_vec();
880            msg.extend_from_slice(&name);
881            msg.extend_from_slice(b"' in file '");
882            msg.extend_from_slice(&filename);
883            msg.push(b'\'');
884            let s = state.intern_str(&msg)?;
885            state.push(LuaValue::Str(s));
886            return Ok(1);
887        }
888        LookForFuncStatus::ErrLib(_) => {
889            return checkload(state, false, &filename);
890        }
891    }
892
893    let s = state.intern_str(&filename)?;
894    state.push(LuaValue::Str(s));
895    Ok(2)
896}
897
898/// Searcher that looks in `package.preload` for a pre-registered loader.
899///
900/// On a hit, every version leaves the loader function on the stack. From **5.4**
901/// the searcher also returns the `:preload:` sentinel as loader data (a 2nd
902/// value); 5.1/5.2/5.3 return only the function. See [`require_returns_loader_data`].
903fn searcher_preload(state: &mut LuaState) -> Result<usize, LuaError> {
904    let name = state.check_arg_string(1)?.to_vec();
905    state.get_field_registry(b"_PRELOAD")?;
906    let ty = state.get_field(-1, &name)?;
907    if ty == LuaType::Nil {
908        let mut msg = b"no field package.preload['".to_vec();
909        msg.extend_from_slice(&name);
910        msg.push(b'\'');
911        msg.push(b']');
912        let s = state.intern_str(&msg)?;
913        state.push(LuaValue::Str(s));
914        return Ok(1);
915    }
916    if !require_returns_loader_data(state.global().lua_version) {
917        return Ok(1);
918    }
919    let tag = state.intern_str(b":preload:")?;
920    state.push(LuaValue::Str(tag));
921    Ok(2)
922}
923
924// ── require implementation ────────────────────────────────────────────────────
925
926/// Iterate through `package.searchers` to find a loader for module `name`.
927///
928/// On success, leaves `(loader_function, loader_data)` at the top of the stack
929/// (below the searchers table). On failure, raises a runtime error.
930///
931/// The accumulated `module '<name>' not found:` message lists one searcher per
932/// line; the per-iteration `\n\t` prefix matches 5.4+ `findloader`, while the
933/// pre-5.4 searchers prepend their own separator (the two regimes converge on
934/// the identical trace, pinned in `tests/loadlib_strengthen.rs`).
935fn findloader(state: &mut LuaState, name: &[u8]) -> Result<(), LuaError> {
936    let uv = state.upvalue_index(1);
937    // In 5.1 the searcher list lives in `package.loaders`; 5.2 renamed it to
938    // `package.searchers` (5.2 keeps `loaders` as an alias). Read the name this
939    // version exposes. See specs/followup/5.1-roster-syntax.md §1.
940    let field: &[u8] = if matches!(state.global().lua_version, lua_types::LuaVersion::V51) {
941        b"loaders"
942    } else {
943        b"searchers"
944    };
945    let ty = state.get_field(uv, field)?;
946    if ty != LuaType::Table {
947        return Err(LuaError::runtime(format_args!(
948            "'package.searchers' must be a table"
949        )));
950    }
951
952    let mut msg_buf: Vec<u8> = Vec::new();
953
954    let mut i: i64 = 1;
955    loop {
956        msg_buf.extend_from_slice(b"\n\t");
957
958        let item_ty = state.raw_geti(-1, i)?;
959        if item_ty == LuaType::Nil {
960            state.pop_n(1);
961            let len = msg_buf.len();
962            if len >= 2 {
963                msg_buf.truncate(len - 2);
964            }
965            // Build the error message as a Lua string then raise.
966            let mut err = b"module '".to_vec();
967            err.extend_from_slice(name);
968            err.extend_from_slice(b"' not found:");
969            err.extend_from_slice(&msg_buf);
970            let err_s = state.intern_str(&err)?;
971            return Err(LuaError::from_value(LuaValue::Str(err_s)));
972        }
973
974        let name_s = state.intern_str(name)?;
975        state.push(LuaValue::Str(name_s));
976
977        state.call(1, 2)?;
978
979        // After call: two return values r1 (at -2) and r2 (at -1) on top.
980        if state.type_at(-2) == LuaType::Function {
981            // Loader found; leave (r1=function, r2=data) on stack and return.
982            return Ok(());
983        }
984
985        if state.type_at(-2) == LuaType::String {
986            // r1 is an error-message string from the searcher.
987            state.pop_n(1);
988            if let Some(bytes) = state.to_bytes(-1) {
989                msg_buf.extend_from_slice(&bytes);
990            }
991            state.pop_n(1);
992        } else {
993            state.pop_n(2);
994            let len = msg_buf.len();
995            if len >= 2 {
996                msg_buf.truncate(len - 2);
997            }
998        }
999
1000        i += 1;
1001    }
1002}
1003
1004/// `require(modname)` — load a module by name, using `package.loaded` as a
1005/// cache and `package.searchers` to find and load it if not already cached.
1006///
1007/// Returns the module value (and optionally the loader data) — 2 values.
1008///
1009pub fn ll_require(state: &mut LuaState) -> Result<usize, LuaError> {
1010    let name = state.check_arg_string(1)?.to_vec();
1011    let version = state.global().lua_version;
1012
1013    // Use the public-API `set_top` (relative to the current C-frame's `func`),
1014    // not the inherent `LuaState::set_top`, which sets an absolute index and
1015    // would truncate the whole stack.
1016    lua_vm::api::set_top(state, 1)?;
1017
1018    state.get_field_registry(b"_LOADED")?;
1019
1020    state.get_field(2, &name)?;
1021
1022    if state.to_boolean(-1) {
1023        return Ok(1);
1024    }
1025
1026    state.pop_n(1);
1027
1028    // `findloader` leaves (loader function, loader data) at the top.
1029    findloader(state, &name)?;
1030
1031    if require_passes_loader_data(version) {
1032        // 5.2+: the loader receives (name, loader data). 5.4+ additionally
1033        // returns the loader data as `require`'s 2nd value, so the data is kept
1034        // below the function (rotate) and re-pushed; 5.2/5.3 pass it but discard
1035        // it (return 1).
1036        state.rotate(-2, 1)?;
1037        state.push_value(1)?;
1038        state.push_value(-3)?;
1039        state.call(2, 1)?;
1040    } else {
1041        // 5.1: the loader receives only the name; there is no loader data.
1042        state.pop_n(1);
1043        state.push_value(1)?;
1044        state.call(1, 1)?;
1045    }
1046
1047    if state.type_at(-1) != LuaType::Nil {
1048        state.set_field(2, &name)?;
1049    } else {
1050        state.pop_n(1);
1051    }
1052
1053    let ty = state.get_field(2, &name)?;
1054    if ty == LuaType::Nil {
1055        state.push(LuaValue::Bool(true));
1056        state.copy_value(-1, -2)?;
1057        state.set_field(2, &name)?;
1058    }
1059
1060    if require_returns_loader_data(version) {
1061        // 5.4+: return (module result, loader data). The loader data is still on
1062        // the stack below the module result; swap them to module-result-first.
1063        state.rotate(-2, 1)?;
1064        Ok(2)
1065    } else {
1066        // 5.1/5.2/5.3: `ll_require` returns only the module (return 1). On the
1067        // 5.2/5.3 path the loader data is still on the stack below the result;
1068        // drop it so the single return value is the module.
1069        if require_passes_loader_data(version) {
1070            state.remove(-2)?;
1071        }
1072        Ok(1)
1073    }
1074}
1075
1076/// Whether `require` passes the searcher's loader data to the module loader as
1077/// a SECOND argument (after the module name).
1078///
1079/// 5.1's `ll_require` calls the loader with one argument (`lua_call(L, 1, 1)`);
1080/// 5.2 widened it to two (`lua_call(L, 2, 1)`), so every later version passes the
1081/// loader data too. Pinned in `tests/loadlib_strengthen.rs`.
1082fn require_passes_loader_data(version: lua_types::LuaVersion) -> bool {
1083    !matches!(version, lua_types::LuaVersion::V51)
1084}
1085
1086/// Whether `require` returns the searcher's loader data as a SECOND result.
1087///
1088/// This is a **5.4** addition (`ll_require`'s `return 2`); 5.1/5.2/5.3 return only
1089/// the module (`return 1`), so `local _, d = require(m)` yields `d == nil` there.
1090/// It is the same seam the preload searcher's `:preload:` sentinel rides on
1091/// (a searcher only bothers returning loader data on a version that surfaces it).
1092/// Pinned in `tests/loadlib_strengthen.rs`.
1093fn require_returns_loader_data(version: lua_types::LuaVersion) -> bool {
1094    matches!(version, lua_types::LuaVersion::V54 | lua_types::LuaVersion::V55)
1095}
1096
1097// ── Package library setup ─────────────────────────────────────────────────────
1098
1099/// Create the `searchers` table and install the four built-in searchers, each
1100/// with the `package` table as upvalue #1.
1101///
1102fn createsearcherstable(state: &mut LuaState) -> Result<(), LuaError> {
1103    let searchers: &[fn(&mut LuaState) -> Result<usize, LuaError>] =
1104        &[searcher_preload, searcher_lua, searcher_c, searcher_croot];
1105
1106    state.create_table(searchers.len() as i32, 0)?;
1107
1108    for (i, &f) in searchers.iter().enumerate() {
1109        // Each searcher closes over the `package` table (upvalue #1) so
1110        // `findfile` can read `package.path`/`package.cpath` via
1111        // `lua_upvalueindex(1)`.
1112        state.push_value(-2)?;
1113        state.push_c_closure(f, 1)?;
1114        state.raw_seti(-2, (i + 1) as i64)?;
1115    }
1116    // Roster name deltas for the searcher list:
1117    //  - 5.1: the table is named `package.loaders`; there is NO
1118    //    `package.searchers` (verified against lua5.1.5: `package.searchers` is
1119    //    nil, `package.loaders` is a table).
1120    //  - 5.2: renamed to `package.searchers` but kept `package.loaders` as a
1121    //    compat alias (both point at the same list).
1122    //  - 5.3+: `package.searchers` only.
1123    let version = state.global().lua_version;
1124    let has_loaders = matches!(
1125        version,
1126        lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52
1127    );
1128    let has_searchers = !matches!(version, lua_types::LuaVersion::V51);
1129    if has_loaders {
1130        state.push_value(-1)?;
1131        state.set_field(-3, b"loaders")?;
1132    }
1133    if has_searchers {
1134        state.set_field(-2, b"searchers")?;
1135    } else {
1136        // No `searchers` field under 5.1; drop the table copy left on the stack.
1137        state.pop_n(1);
1138    }
1139    Ok(())
1140}
1141
1142/// Create the `_CLIBS` registry table with a `__gc` finalizer that closes all
1143/// loaded C libraries when the Lua state is closed.
1144///
1145fn createclibstable(state: &mut LuaState) -> Result<(), LuaError> {
1146    state.get_subtable_registry(CLIBS)?;
1147    state.create_table(0, 1)?;
1148    state.push_c_function(gctm)?;
1149    state.set_field(-2, b"__gc")?;
1150    state.set_metatable(-2)?;
1151    Ok(())
1152}
1153
1154// ── Lua 5.1 `module` / `package.seeall` (deprecated module system) ────────────
1155//
1156// These ship only in the default lua5.1.5 build (`loadlib.c`) and were removed
1157// in 5.2. Registered under the V51 backend; see
1158// specs/followup/5.1-roster-syntax.md §1. They lean on the 5.1 fenv globals
1159// model: `module` sets its caller's environment to the module table (via
1160// `crate::base::set_func_env_at_level`), and `package.seeall` points a module
1161// table's `__index` at `_G`.
1162
1163/// `package.seeall(module)` — make a module table inherit globals.
1164///
1165/// Sets (creating if absent) `module`'s metatable `__index` to the global
1166/// table. Mirrors `ll_seeall` in 5.1 `loadlib.c`. Verified against lua5.1.5.
1167fn ll_seeall(state: &mut LuaState) -> Result<usize, LuaError> {
1168    state.check_arg_type(1, LuaType::Table)?;
1169    if !state.get_metatable(1)? {
1170        state.create_table(0, 1)?;
1171        state.push_value(-1)?;
1172        state.set_metatable(1)?;
1173    }
1174    state.push_globals()?;
1175    state.set_field(-2, b"__index")?;
1176    Ok(0)
1177}
1178
1179/// Walk a dotted module name from a table on the stack, creating intermediate
1180/// tables as needed, leaving the final (sub)table on the stack top. A faithful
1181/// reduction of `luaL_findtable(L, idx, name, 1)`; returns `Err` on a name
1182/// conflict (an intermediate path component is a non-table, non-nil value).
1183fn findtable(state: &mut LuaState, table_idx: i32, name: &[u8]) -> Result<(), LuaError> {
1184    // Start from a copy of the base table on the stack top.
1185    state.push_value_at(table_idx)?;
1186    for part in name.split(|&b| b == b'.') {
1187        // Stack top holds the current table; fetch current[part].
1188        let ty = state.get_field(-1, part)?;
1189        if ty == LuaType::Nil {
1190            state.pop_n(1); // remove nil
1191            state.create_table(0, 1)?; // new subtable
1192            state.push_value(-1)?; // duplicate it
1193            state.set_field(-3, part)?; // current[part] = subtable
1194                                        // Stack: ..., current, subtable. Remove the parent, keep subtable.
1195            state.remove(-2)?;
1196        } else if ty == LuaType::Table {
1197            // Stack: ..., current, value. Remove the parent, keep value.
1198            state.remove(-2)?;
1199        } else {
1200            return Err(LuaError::runtime(format_args!(
1201                "name conflict for module '{}'",
1202                String::from_utf8_lossy(name)
1203            )));
1204        }
1205    }
1206    Ok(())
1207}
1208
1209/// `module(name [, ...])` — Lua 5.1 only.
1210///
1211/// Creates (or reuses) a module table named `name`, registers it in
1212/// `package.loaded`, initializes its `_NAME`/`_M`/`_PACKAGE` fields, applies any
1213/// option functions (e.g. `package.seeall`), and sets the calling chunk's
1214/// environment to the module table. Mirrors `ll_module` in 5.1 `loadlib.c`.
1215fn ll_module(state: &mut LuaState) -> Result<usize, LuaError> {
1216    let modname: Vec<u8> = state.check_arg_string(1)?;
1217    let n_opts = state.top() as i32;
1218
1219    // Fetch _LOADED[modname]; create the module table if absent.
1220    state.get_field_registry(b"_LOADED")?;
1221    let loaded_idx = state.top() as i32;
1222    state.get_field(loaded_idx, &modname)?;
1223    if state.type_at(-1) != LuaType::Table {
1224        state.pop_n(1); // remove non-table result
1225                        // Find/create a global table named `modname` (supporting dotted names).
1226        state.push_globals()?;
1227        let g_idx = state.top() as i32;
1228        findtable(state, g_idx, &modname)?;
1229        state.remove(g_idx)?; // drop the globals table copy, keep the module table
1230        state.push_value(-1)?;
1231        state.set_field(loaded_idx, &modname)?; // _LOADED[modname] = module
1232    }
1233
1234    // Initialize the module if it has no `_NAME` yet.
1235    let has_name = state.get_field(-1, b"_NAME")? != LuaType::Nil;
1236    state.pop_n(1);
1237    if !has_name {
1238        // module._M = module
1239        state.push_value(-1)?;
1240        state.set_field(-2, b"_M")?;
1241        // module._NAME = modname
1242        state.push_string(&modname)?;
1243        state.set_field(-2, b"_NAME")?;
1244        // module._PACKAGE = full name minus the last dotted component.
1245        let pkg: &[u8] = match modname.iter().rposition(|&b| b == b'.') {
1246            Some(dot) => &modname[..=dot],
1247            None => b"",
1248        };
1249        state.push_string(pkg)?;
1250        state.set_field(-2, b"_PACKAGE")?;
1251    }
1252
1253    // Set the caller's environment to the module table (the running closure that
1254    // invoked `module`, i.e. level 1 relative to this C function).
1255    let module_tbl = state.value_at(-1);
1256    crate::base::set_func_env_at_level(state, 1, module_tbl)?;
1257
1258    // Apply option functions: for each extra arg, call `option(module)`.
1259    let mut i = 2;
1260    while i <= n_opts {
1261        state.push_value_at(i)?; // option function
1262        state.push_value(-2)?; // module table
1263        state.call(1, 0)?;
1264        i += 1;
1265    }
1266    Ok(0)
1267}
1268
1269/// Open the `package` library and return the `package` table.
1270///
1271pub fn luaopen_package(state: &mut LuaState) -> Result<usize, LuaError> {
1272    createclibstable(state)?;
1273
1274    // The C `pk_funcs` table also has placeholder entries for "preload",
1275    // "cpath", "path", "searchers", "loaded" (all NULL); those fields are set
1276    // explicitly below. Only `loadlib` is unconditional — `package.searchpath`
1277    // was added in 5.2 (absent on 5.1), so it is registered separately below.
1278    state.new_lib(&[(
1279        b"loadlib" as &[u8],
1280        ll_loadlib as fn(&mut LuaState) -> Result<usize, LuaError>,
1281    )])?;
1282
1283    if !matches!(state.global().lua_version, lua_types::LuaVersion::V51) {
1284        state.push_c_function(ll_searchpath)?;
1285        state.set_field(-2, b"searchpath")?;
1286    }
1287
1288    createsearcherstable(state)?;
1289
1290    setpath(state, b"path", LUA_PATH_VAR, LUA_PATH_DEFAULT)?;
1291
1292    setpath(state, b"cpath", LUA_CPATH_VAR, LUA_CPATH_DEFAULT)?;
1293
1294    let config = package_config(state.global().lua_version);
1295    let config_s = state.intern_str(&config)?;
1296    state.push(LuaValue::Str(config_s));
1297
1298    state.set_field(-2, b"config")?;
1299
1300    state.get_subtable_registry(b"_LOADED")?;
1301    state.set_field(-2, b"loaded")?;
1302
1303    state.get_subtable_registry(b"_PRELOAD")?;
1304    state.set_field(-2, b"preload")?;
1305
1306    state.push_globals()?;
1307    state.push_value(-2)?;
1308    state.set_funcs_with_upvalues(
1309        &[(
1310            b"require" as &[u8],
1311            ll_require as fn(&mut LuaState) -> Result<usize, LuaError>,
1312        )],
1313        1,
1314    )?;
1315    state.pop_n(1);
1316
1317    // The deprecated module system: `package.seeall` (a field on the package
1318    // table) and the `module` global. Present in 5.1 and kept in 5.2.4 via the
1319    // default-on `LUA_COMPAT_MODULE`; fully removed in 5.3. Verified against
1320    // lua5.1.5 and lua5.2.4. See specs/followup/5.1-roster-syntax.md §1.
1321    if matches!(
1322        state.global().lua_version,
1323        lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52
1324    ) {
1325        // The package table is on top of the stack here.
1326        state.push_c_function(ll_seeall)?;
1327        state.set_field(-2, b"seeall")?;
1328        // `module` is a *global*, not a `package` field.
1329        state.push_c_function(ll_module)?;
1330        state.set_global(b"module")?;
1331    }
1332
1333    Ok(1)
1334}
1335
1336// ──────────────────────────────────────────────────────────────────────────
1337// PORT STATUS
1338//   target_crate:  lua-stdlib
1339//   unsafe_blocks: 0  (the dlopen/dlsym FFI lives in lua-cli, behind the
1340//                  dynlib_*_hook indirection on GlobalState; this crate stays
1341//                  unsafe-free per its `unsafe_code = "forbid"`)
1342//   deferred:      two genuine TODOs — LUA_VERSUFFIX / LUA_PATH_DEFAULT /
1343//                  LUA_CPATH_DEFAULT are hardcoded for 5.4 rather than tracking
1344//                  the selected version + a platform install prefix; the Windows
1345//                  setprogdir LUA_EXEC_DIR substitution is unimplemented.
1346//   notes:         Idiomatization Sprint 2 / Phase 2 (cold module, no perf
1347//                  arbiter). The deterministic pure-Lua surface (package.config,
1348//                  require + package.loaded caching, the four-searcher not-found
1349//                  trace, package.searchpath string logic, the loaders/searchers
1350//                  rename, module/seeall 5.1 roster, the nil-vs-false fail value)
1351//                  is pinned by tests/loadlib_strengthen.rs, which caught SEVEN
1352//                  cross-version divergences fixed here (see GRADUATED.md
1353//                  "loadlib"). The platform/FFI surface is left LOAD-BEARING and
1354//                  untouched: the dlopen/dlsym bridge (— POSIX/Windows notes on
1355//                  lsys_load/lsys_sym/lsys_unloadlib), the file probe + module
1356//                  read via file_loader_hook, the "open"/"absent"/"init" tags
1357//                  and platform error strings, and the unsupported-stock-C-ABI
1358//                  message (DynamicSymbol::LuaCAbi). None of that is
1359//                  reference-pinnable without a real .so + host loader.
1360// ──────────────────────────────────────────────────────────────────────────