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.message_bytes() {
332 Some(b) => b.to_vec(),
333 None => format!("{:?}", e).into_bytes(),
334 }
335}
336
337/// Encode a [`DynLibId`] as a `*mut c_void` for storage in `_CLIBS` as light
338/// userdata. The cast is the inverse of [`decode_dynlib_id`]; neither side
339/// ever dereferences the pointer.
340fn encode_dynlib_id(id: DynLibId) -> *mut std::ffi::c_void {
341 id.0 as usize as *mut std::ffi::c_void
342}
343
344/// Decode a [`DynLibId`] previously stored via [`encode_dynlib_id`].
345fn decode_dynlib_id(p: *mut std::ffi::c_void) -> DynLibId {
346 DynLibId(p as usize as u64)
347}
348
349// ── Path helpers ──────────────────────────────────────────────────────────────
350
351/// Return `registry["LUA_NOENV"]` as a boolean.
352///
353fn noenv(state: &mut LuaState) -> bool {
354 let _ = state.get_field_registry(b"LUA_NOENV");
355 let b = state.to_boolean(-1);
356 state.pop_n(1);
357 b
358}
359
360/// Set `package[fieldname]` to the appropriate path value.
361///
362/// Priority: versioned env var (e.g. `LUA_PATH_5_4`) → unversioned env var
363/// (`LUA_PATH`) → compiled-in default. When the env var contains `;;`, the
364/// compiled-in default is spliced in place of `;;`. The caller must leave the
365/// `package` table at the stack top; the path value is set on it directly (the
366/// versioned env-var name is computed off-stack, so no index bookkeeping is
367/// needed).
368fn setpath(
369 state: &mut LuaState,
370 fieldname: &[u8],
371 envname: &[u8],
372 dft: &[u8],
373) -> Result<(), LuaError> {
374 let mut nver = envname.to_vec();
375 nver.extend_from_slice(LUA_VERSUFFIX);
376
377 let path_opt = if noenv(state) {
378 None
379 } else {
380 getenv_bytes(state, &nver).or_else(|| getenv_bytes(state, envname))
381 };
382
383 let final_path: Vec<u8> = if path_opt.is_none() {
384 dft.to_vec()
385 } else {
386 let path = path_opt.unwrap();
387 let double_sep = [LUA_PATH_SEP, LUA_PATH_SEP];
388 if let Some(dftmark_pos) = find_subslice(&path, &double_sep) {
389 // Path contains ";;": replace with default.
390 let mut buf = Vec::new();
391 if dftmark_pos > 0 {
392 buf.extend_from_slice(&path[..dftmark_pos]);
393 buf.push(LUA_PATH_SEP);
394 }
395 buf.extend_from_slice(dft);
396 let after = dftmark_pos + 2;
397 if after < path.len() {
398 buf.push(LUA_PATH_SEP);
399 buf.extend_from_slice(&path[after..]);
400 }
401 buf
402 } else {
403 path
404 }
405 };
406
407 // The Windows `setprogdir` step (replace `LUA_EXEC_DIR` with the running
408 // executable's directory via `GetModuleFileNameA`, a Win32/`unsafe` call) is
409 // a no-op on every other platform and is not yet implemented here, so the
410 // `LUA_EXEC_DIR` substitution is skipped.
411 let s = state.intern_str(&final_path)?;
412 state.push(LuaValue::Str(s));
413 state.set_field(-2, fieldname)?;
414
415 Ok(())
416}
417
418// ── CLIBS registry table ──────────────────────────────────────────────────────
419
420/// Return the library handle stored at `registry._CLIBS[path]`, or `None`.
421///
422fn checkclib(state: &mut LuaState, path: &[u8]) -> Option<DynLibId> {
423 let _ = state.get_field_registry(CLIBS);
424 let _ = state.get_field(-1, path);
425 let handle = state.to_light_userdata(-1).map(decode_dynlib_id);
426 state.pop_n(2);
427 handle
428}
429
430/// Register a library handle in the CLIBS table (both by path and sequentially).
431///
432fn addtoclib(state: &mut LuaState, path: &[u8], plib: DynLibId) -> Result<(), LuaError> {
433 state.get_field_registry(CLIBS)?;
434 state.push(LuaValue::LightUserData(encode_dynlib_id(plib)));
435 state.push_value(-1)?;
436 state.set_field(-3, path)?;
437 let n = state.len_at(-2);
438 state.raw_seti(-2, n + 1)?;
439 state.pop_n(1);
440 Ok(())
441}
442
443/// `__gc` metamethod for the CLIBS table: unloads all registered C libraries
444/// in reverse order when the Lua state closes.
445///
446fn gctm(state: &mut LuaState) -> Result<usize, LuaError> {
447 let n = state.len_at(1);
448 let mut i = n;
449 while i >= 1 {
450 state.raw_geti(1, i)?;
451 if let Some(handle) = state.to_light_userdata(-1).map(decode_dynlib_id) {
452 lsys_unloadlib(state, handle);
453 }
454 state.pop_n(1);
455 i -= 1;
456 }
457 Ok(0)
458}
459
460// ── Dynamic function lookup ───────────────────────────────────────────────────
461
462/// Outcome of looking for a C function in a dynamically loaded library.
463///
464/// On success the function (or `true` for the `*` sentinel) is on the stack;
465/// on a non-fatal failure an error-message string is on the stack and the
466/// variant tells the caller what to report. Fatal errors propagate via `Err`.
467/// `Ok` is C's success; `ErrLib(tag)` is C's `ERRLIB` carrying the `LIB_FAIL`
468/// string (`"open"` for a true dlopen failure, `"absent"` when no backend is
469/// installed or the file does not exist); `ErrFunc` is C's `ERRFUNC` (the
470/// library opened but the symbol was not found).
471enum LookForFuncStatus {
472 /// Loader successfully resolved a symbol (function pushed on stack).
473 Ok,
474 /// Library could not be opened. `tag` is the `LIB_FAIL` string.
475 ErrLib(&'static [u8]),
476 /// Library opened but symbol could not be resolved.
477 ErrFunc,
478}
479
480fn lookforfunc(
481 state: &mut LuaState,
482 path: &[u8],
483 sym: &[u8],
484) -> Result<LookForFuncStatus, LuaError> {
485 let reg = match checkclib(state, path) {
486 Some(handle) => handle,
487 None => {
488 let (loaded, tag) = lsys_load(state, path, sym.first() == Some(&b'*'));
489 match loaded {
490 Some(handle) => {
491 addtoclib(state, path, handle)?;
492 handle
493 }
494 None => return Ok(LookForFuncStatus::ErrLib(tag)),
495 }
496 }
497 };
498 if sym.first() == Some(&b'*') {
499 state.push(LuaValue::Bool(true));
500 return Ok(LookForFuncStatus::Ok);
501 }
502 match lsys_sym(state, reg, sym) {
503 SymOutcome::Found(func) => {
504 state.push_c_function(func)?;
505 Ok(LookForFuncStatus::Ok)
506 }
507 SymOutcome::Missing => Ok(LookForFuncStatus::ErrFunc),
508 }
509}
510
511// ── Lua-callable package functions ────────────────────────────────────────────
512
513/// `package.loadlib(filename, funcname)` — open a C library and return a
514/// Lua-callable wrapper for `funcname`.
515///
516/// Returns: on success, the loader function (1 value).
517/// On error: `false`, error-message string, and `"open"` or `"init"` (3 values).
518///
519pub fn ll_loadlib(state: &mut LuaState) -> Result<usize, LuaError> {
520 let path = state.check_arg_string(1)?.to_vec();
521 let init = state.check_arg_string(2)?.to_vec();
522 let stat = lookforfunc(state, &path, &init)?;
523 let where_bytes: &[u8] = match stat {
524 LookForFuncStatus::Ok => return Ok(1),
525 LookForFuncStatus::ErrLib(tag) => tag,
526 LookForFuncStatus::ErrFunc => b"init",
527 };
528 // `luaL_pushfail` is `lua_pushnil` on every version (5.4 included); the fail
529 // value is `nil`, not `false`. The `LIB_FAIL` tag is chosen at run time: the
530 // CLI backend reports `LuaError::File` for a missing library → `"absent"`
531 // (matching C-Lua's no-dlfcn fallback), a true `dlopen` failure → `"open"`,
532 // and the "init" branch (symbol resolution failed after the library opened)
533 // is identical in every build.
534 state.push(LuaValue::Nil);
535 state.insert(-2)?;
536 let where_s = state.intern_str(where_bytes)?;
537 state.push(LuaValue::Str(where_s));
538 Ok(3)
539}
540
541// ── File existence check ──────────────────────────────────────────────────────
542
543/// Whether `filename` can be opened for reading.
544///
545/// `std::fs` is banned in `lua-stdlib`, so the probe is delegated to the
546/// embedder-registered `file_loader_hook` on `GlobalState`. Without a hook
547/// installed, `readable` reports `false` (the file system is unreachable) — so
548/// the in-process searcher tests deterministically see every path as not-found.
549fn readable(state: &LuaState, filename: &[u8]) -> bool {
550 match state.global().file_loader_hook {
551 Some(hook) => hook(filename).is_ok(),
552 None => false,
553 }
554}
555
556// ── Path-component iterator ───────────────────────────────────────────────────
557
558/// Iterator over `;`-separated path-template components, yielding each as an
559/// immutable slice (the C original walked one mutable buffer, swapping each
560/// separator for a NUL and back; this produces the identical sequence).
561struct PathComponents<'a> {
562 remaining: &'a [u8],
563}
564
565impl<'a> PathComponents<'a> {
566 fn new(path: &'a [u8]) -> Self {
567 PathComponents { remaining: path }
568 }
569}
570
571impl<'a> Iterator for PathComponents<'a> {
572 type Item = &'a [u8];
573
574 fn next(&mut self) -> Option<Self::Item> {
575 if self.remaining.is_empty() {
576 return None;
577 }
578 let component = match self.remaining.iter().position(|&b| b == LUA_PATH_SEP) {
579 Some(sep_pos) => {
580 let c = &self.remaining[..sep_pos];
581 self.remaining = &self.remaining[sep_pos + 1..];
582 c
583 }
584 None => {
585 let c = self.remaining;
586 self.remaining = &[];
587 c
588 }
589 };
590 Some(component)
591 }
592}
593
594// ── Error-message helpers ─────────────────────────────────────────────────────
595
596/// Push an error message listing all files in `path` that were not found.
597///
598/// Example output: `"no file 'a.lua'\n\tno file 'b.lua'"`
599///
600fn pusherrornotfound(state: &mut LuaState, path: &[u8]) -> Result<(), LuaError> {
601 let mut buf: Vec<u8> = Vec::new();
602 buf.extend_from_slice(b"no file '");
603 gsub_append(&mut buf, path, &[LUA_PATH_SEP], b"'\n\tno file '");
604 buf.push(b'\'');
605 let s = state.intern_str(&buf)?;
606 state.push(LuaValue::Str(s));
607 Ok(())
608}
609
610// ── Path search ───────────────────────────────────────────────────────────────
611
612/// Search for a readable file matching `name` in the `;`-separated `path`.
613///
614/// `sep` bytes in `name` are first replaced by `dirsep`; then each template's
615/// `?` is replaced by the adjusted name. On the first readable match, pushes the
616/// filename string and returns `Some(filename_bytes)`; otherwise pushes the
617/// not-found message and returns `None`.
618fn searchpath(
619 state: &mut LuaState,
620 name: &[u8],
621 path: &[u8],
622 sep: &[u8],
623 dirsep: &[u8],
624) -> Result<Option<Vec<u8>>, LuaError> {
625 let name_buf: Vec<u8> = if !sep.is_empty() && name.contains(&sep[0]) {
626 gsub_bytes(name, sep, dirsep)
627 } else {
628 name.to_vec()
629 };
630
631 let pathname: Vec<u8> = gsub_bytes(path, &[LUA_PATH_MARK], &name_buf);
632
633 for filename in PathComponents::new(&pathname) {
634 if readable(state, filename) {
635 let s = state.intern_str(filename)?;
636 state.push(LuaValue::Str(s));
637 return Ok(Some(filename.to_vec()));
638 }
639 }
640
641 pusherrornotfound(state, &pathname)?;
642 Ok(None)
643}
644
645/// `package.searchpath(name, path [, sep [, rep]])`.
646///
647/// Returns the first readable file in `path` with `sep` occurrences in `name`
648/// replaced by `rep`. On failure returns `luaL_pushfail` (a `nil`, NOT `false`,
649/// on every version) plus the error message. See [`ll_loadlib`] for the same
650/// `luaL_pushfail` = `lua_pushnil` translation.
651pub fn ll_searchpath(state: &mut LuaState) -> Result<usize, LuaError> {
652 let name = state.check_arg_string(1)?.to_vec();
653 let path = state.check_arg_string(2)?.to_vec();
654 let sep = state.opt_arg_string(3, b".")?;
655 let dirsep_default = [LUA_DIRSEP];
656 let dirsep = state.opt_arg_string(4, &dirsep_default)?;
657
658 let found = searchpath(state, &name, &path, &sep, &dirsep)?;
659 if found.is_some() {
660 return Ok(1);
661 }
662 if searchpath_error_has_leading_separator(state.global().lua_version) {
663 prepend_searchpath_separator(state)?;
664 }
665 state.push(LuaValue::Nil);
666 state.insert(-2)?;
667 Ok(2)
668}
669
670/// Whether the standalone `package.searchpath` error message carries a leading
671/// `\n\t` separator before its first `no file '…'` line.
672///
673/// In 5.2/5.3 the `searchpath` helper builds each entry as `"\n\tno file '%s'"`,
674/// so the first line is prefixed too; 5.4 moved that prefix into `findloader`'s
675/// per-iteration accumulator and made `searchpath`'s own message bare (the form
676/// this port's `pusherrornotfound` produces). The `require` trace is unaffected
677/// either way — there `findloader` supplies the single `\n\t` per searcher — so
678/// the seam is observable ONLY through the standalone Lua function. (5.1 has no
679/// `package.searchpath`.) Pinned in `tests/loadlib_strengthen.rs`.
680fn searchpath_error_has_leading_separator(version: lua_types::LuaVersion) -> bool {
681 matches!(version, lua_types::LuaVersion::V52 | lua_types::LuaVersion::V53)
682}
683
684/// Replace the not-found message on the stack top with one carrying a leading
685/// `\n\t` (the 5.2/5.3 `searchpath` form). The message produced by
686/// `pusherrornotfound` is bare; this restores the legacy prefix.
687fn prepend_searchpath_separator(state: &mut LuaState) -> Result<(), LuaError> {
688 let Some(bare) = state.to_bytes(-1) else {
689 return Ok(());
690 };
691 state.pop_n(1);
692 let mut prefixed = b"\n\t".to_vec();
693 prefixed.extend_from_slice(&bare);
694 let s = state.intern_str(&prefixed)?;
695 state.push(LuaValue::Str(s));
696 Ok(())
697}
698
699/// Find a module file using the path stored in `package[pname]` (e.g.
700/// `package.path` / `package.cpath`), read from upvalue #1 of the searcher
701/// closure. Errors if that field is not a string.
702fn findfile(
703 state: &mut LuaState,
704 name: &[u8],
705 pname: &[u8],
706 dirsep: u8,
707) -> Result<Option<Vec<u8>>, LuaError> {
708 let uv = state.upvalue_index(1);
709 let _ = state.get_field(uv, pname);
710 let path_opt: Option<Vec<u8>> = state.to_bytes(-1);
711 let Some(path) = path_opt else {
712 state.pop_n(1);
713 return Err(LuaError::runtime(format_args!(
714 "'package.{}' must be a string",
715 String::from_utf8_lossy(pname)
716 )));
717 };
718 state.pop_n(1);
719 searchpath(state, name, &path, b".", &[dirsep])
720}
721
722/// Check whether a module load succeeded, returning the open function + filename
723/// (2 values) on success or raising an error on failure.
724///
725fn checkload(state: &mut LuaState, stat: bool, filename: &[u8]) -> Result<usize, LuaError> {
726 if stat {
727 let s = state.intern_str(filename)?;
728 state.push(LuaValue::Str(s));
729 Ok(2)
730 } else {
731 // The error embeds the module name (the `require` arg at stack[1]) and
732 // the loader's own error message (the searcher's pushed string at the
733 // stack top). Both are owned byte copies, so there is no aliasing.
734 let modname = state.to_bytes(1).unwrap_or_else(|| b"?".to_vec());
735 let loader_err = state.to_bytes(-1).unwrap_or_else(|| b"?".to_vec());
736
737 let mut msg = b"error loading module '".to_vec();
738 msg.extend_from_slice(&modname);
739 msg.extend_from_slice(b"' from file '");
740 msg.extend_from_slice(filename);
741 msg.extend_from_slice(b"':\n\t");
742 msg.extend_from_slice(&loader_err);
743
744 let s = state.intern_str(&msg)?;
745 return Err(LuaError::from_value(LuaValue::Str(s)));
746 }
747}
748
749// ── Searcher functions ────────────────────────────────────────────────────────
750
751/// Searcher that looks in `package.path` for a Lua source file.
752///
753/// Returns 1 value (error-message string) if not found, or 2 values (loader
754/// function, filename) if found and loaded successfully.
755///
756fn searcher_lua(state: &mut LuaState) -> Result<usize, LuaError> {
757 let name = state.check_arg_string(1)?.to_vec();
758 let filename = findfile(state, &name, b"path", LUA_LSUBSEP)?;
759 if filename.is_none() {
760 return Ok(1);
761 }
762 let filename = filename.unwrap();
763 // `std::fs` is banned in `lua-stdlib`, so file contents arrive via the
764 // embedder-registered `file_loader_hook` on `GlobalState`; the bytes are then
765 // parsed through `state.load(...)` (which dispatches to the parser hook) and
766 // the resulting closure is left on the stack for `checkload` to pair with the
767 // filename.
768 let chunk = match state.global().file_loader_hook {
769 Some(hook) => hook(&filename),
770 None => Err(LuaError::runtime(format_args!(
771 "no file_loader_hook registered; cannot read '{}'",
772 String::from_utf8_lossy(&filename)
773 ))),
774 };
775 let load_ok = match chunk {
776 Ok(bytes) => {
777 // Use a chunk name of the form `@filename` matching C's luaL_loadfilex.
778 let mut chunkname = b"@".to_vec();
779 chunkname.extend_from_slice(&filename);
780 match state.load(&bytes, &chunkname, None) {
781 Ok(true) => true,
782 Ok(false) => false,
783 Err(e) => {
784 let msg = match e.message_bytes() {
785 Some(b) => b.to_vec(),
786 None => format!("{:?}", &e).into_bytes(),
787 };
788 let s = state.intern_str(&msg)?;
789 state.push(LuaValue::Str(s));
790 false
791 }
792 }
793 }
794 Err(e) => {
795 let msg = match e.message_bytes() {
796 Some(b) => b.to_vec(),
797 None => format!("{:?}", &e).into_bytes(),
798 };
799 let s = state.intern_str(&msg)?;
800 state.push(LuaValue::Str(s));
801 false
802 }
803 };
804 checkload(state, load_ok, &filename)
805}
806
807/// Try to load `modname`'s open function from the C dynamic library at `filename`.
808///
809/// Handles the "ignore mark" (`-`) convention: `"foo-bar"` first tries
810/// `luaopen_foo`, then `luaopen_bar` as a fallback.
811///
812fn loadfunc(
813 state: &mut LuaState,
814 filename: &[u8],
815 modname: &[u8],
816) -> Result<LookForFuncStatus, LuaError> {
817 let modname: Vec<u8> = gsub_bytes(modname, b".", LUA_OFSEP);
818
819 if let Some(mark_pos) = modname.iter().position(|&b| b == LUA_IGMARK) {
820 let prefix = &modname[..mark_pos];
821 let mut openfunc = LUA_POF.to_vec();
822 openfunc.extend_from_slice(prefix);
823 let stat = lookforfunc(state, filename, &openfunc)?;
824 if !matches!(stat, LookForFuncStatus::ErrFunc) {
825 return Ok(stat);
826 }
827 let tail = &modname[mark_pos + 1..];
828 let mut openfunc2 = LUA_POF.to_vec();
829 openfunc2.extend_from_slice(tail);
830 return lookforfunc(state, filename, &openfunc2);
831 }
832
833 let mut openfunc = LUA_POF.to_vec();
834 openfunc.extend_from_slice(&modname);
835 lookforfunc(state, filename, &openfunc)
836}
837
838/// Searcher that looks in `package.cpath` for a C dynamic library.
839///
840fn searcher_c(state: &mut LuaState) -> Result<usize, LuaError> {
841 let name = state.check_arg_string(1)?.to_vec();
842 let filename = findfile(state, &name, b"cpath", LUA_CSUBSEP)?;
843 if filename.is_none() {
844 return Ok(1);
845 }
846 let filename = filename.unwrap();
847 let stat = loadfunc(state, &filename, &name)?;
848 let ok = matches!(stat, LookForFuncStatus::Ok);
849 checkload(state, ok, &filename)
850}
851
852/// Searcher that looks in `package.cpath` using only the root component
853/// (everything before the first `.`) of the module name.
854///
855fn searcher_croot(state: &mut LuaState) -> Result<usize, LuaError> {
856 let name = state.check_arg_string(1)?.to_vec();
857 let dot_pos = name.iter().position(|&b| b == b'.');
858 if dot_pos.is_none() {
859 return Ok(0);
860 }
861 let dot_pos = dot_pos.unwrap();
862
863 let root = &name[..dot_pos];
864
865 let filename = findfile(state, root, b"cpath", LUA_CSUBSEP)?;
866
867 if filename.is_none() {
868 return Ok(1);
869 }
870 let filename = filename.unwrap();
871
872 let stat = loadfunc(state, &filename, &name)?;
873 match stat {
874 LookForFuncStatus::Ok => {}
875 LookForFuncStatus::ErrFunc => {
876 let mut msg = b"no module '".to_vec();
877 msg.extend_from_slice(&name);
878 msg.extend_from_slice(b"' in file '");
879 msg.extend_from_slice(&filename);
880 msg.push(b'\'');
881 let s = state.intern_str(&msg)?;
882 state.push(LuaValue::Str(s));
883 return Ok(1);
884 }
885 LookForFuncStatus::ErrLib(_) => {
886 return checkload(state, false, &filename);
887 }
888 }
889
890 let s = state.intern_str(&filename)?;
891 state.push(LuaValue::Str(s));
892 Ok(2)
893}
894
895/// Searcher that looks in `package.preload` for a pre-registered loader.
896///
897/// On a hit, every version leaves the loader function on the stack. From **5.4**
898/// the searcher also returns the `:preload:` sentinel as loader data (a 2nd
899/// value); 5.1/5.2/5.3 return only the function. See [`require_returns_loader_data`].
900fn searcher_preload(state: &mut LuaState) -> Result<usize, LuaError> {
901 let name = state.check_arg_string(1)?.to_vec();
902 state.get_field_registry(b"_PRELOAD")?;
903 let ty = state.get_field(-1, &name)?;
904 if ty == LuaType::Nil {
905 let mut msg = b"no field package.preload['".to_vec();
906 msg.extend_from_slice(&name);
907 msg.push(b'\'');
908 msg.push(b']');
909 let s = state.intern_str(&msg)?;
910 state.push(LuaValue::Str(s));
911 return Ok(1);
912 }
913 if !require_returns_loader_data(state.global().lua_version) {
914 return Ok(1);
915 }
916 let tag = state.intern_str(b":preload:")?;
917 state.push(LuaValue::Str(tag));
918 Ok(2)
919}
920
921// ── require implementation ────────────────────────────────────────────────────
922
923/// Iterate through `package.searchers` to find a loader for module `name`.
924///
925/// On success, leaves `(loader_function, loader_data)` at the top of the stack
926/// (below the searchers table). On failure, raises a runtime error.
927///
928/// The accumulated `module '<name>' not found:` message lists one searcher per
929/// line; the per-iteration `\n\t` prefix matches 5.4+ `findloader`, while the
930/// pre-5.4 searchers prepend their own separator (the two regimes converge on
931/// the identical trace, pinned in `tests/loadlib_strengthen.rs`).
932fn findloader(state: &mut LuaState, name: &[u8]) -> Result<(), LuaError> {
933 let uv = state.upvalue_index(1);
934 // In 5.1 the searcher list lives in `package.loaders`; 5.2 renamed it to
935 // `package.searchers` (5.2 keeps `loaders` as an alias). Read the name this
936 // version exposes. See specs/followup/5.1-roster-syntax.md §1.
937 let field: &[u8] = if matches!(state.global().lua_version, lua_types::LuaVersion::V51) {
938 b"loaders"
939 } else {
940 b"searchers"
941 };
942 let ty = state.get_field(uv, field)?;
943 if ty != LuaType::Table {
944 return Err(LuaError::runtime(format_args!(
945 "'package.searchers' must be a table"
946 )));
947 }
948
949 let mut msg_buf: Vec<u8> = Vec::new();
950
951 let mut i: i64 = 1;
952 loop {
953 msg_buf.extend_from_slice(b"\n\t");
954
955 let item_ty = state.raw_geti(-1, i)?;
956 if item_ty == LuaType::Nil {
957 state.pop_n(1);
958 let len = msg_buf.len();
959 if len >= 2 {
960 msg_buf.truncate(len - 2);
961 }
962 // Build the error message as a Lua string then raise.
963 let mut err = b"module '".to_vec();
964 err.extend_from_slice(name);
965 err.extend_from_slice(b"' not found:");
966 err.extend_from_slice(&msg_buf);
967 let err_s = state.intern_str(&err)?;
968 return Err(LuaError::from_value(LuaValue::Str(err_s)));
969 }
970
971 let name_s = state.intern_str(name)?;
972 state.push(LuaValue::Str(name_s));
973
974 state.call(1, 2)?;
975
976 // After call: two return values r1 (at -2) and r2 (at -1) on top.
977 if state.type_at(-2) == LuaType::Function {
978 // Loader found; leave (r1=function, r2=data) on stack and return.
979 return Ok(());
980 }
981
982 if state.type_at(-2) == LuaType::String {
983 // r1 is an error-message string from the searcher.
984 state.pop_n(1);
985 if let Some(bytes) = state.to_bytes(-1) {
986 msg_buf.extend_from_slice(&bytes);
987 }
988 state.pop_n(1);
989 } else {
990 state.pop_n(2);
991 let len = msg_buf.len();
992 if len >= 2 {
993 msg_buf.truncate(len - 2);
994 }
995 }
996
997 i += 1;
998 }
999}
1000
1001/// `require(modname)` — load a module by name, using `package.loaded` as a
1002/// cache and `package.searchers` to find and load it if not already cached.
1003///
1004/// Returns the module value (and optionally the loader data) — 2 values.
1005///
1006pub fn ll_require(state: &mut LuaState) -> Result<usize, LuaError> {
1007 let name = state.check_arg_string(1)?.to_vec();
1008 let version = state.global().lua_version;
1009
1010 // Use the public-API `set_top` (relative to the current C-frame's `func`),
1011 // not the inherent `LuaState::set_top`, which sets an absolute index and
1012 // would truncate the whole stack.
1013 lua_vm::api::set_top(state, 1)?;
1014
1015 state.get_field_registry(b"_LOADED")?;
1016
1017 state.get_field(2, &name)?;
1018
1019 if state.to_boolean(-1) {
1020 return Ok(1);
1021 }
1022
1023 state.pop_n(1);
1024
1025 // `findloader` leaves (loader function, loader data) at the top.
1026 findloader(state, &name)?;
1027
1028 if require_passes_loader_data(version) {
1029 // 5.2+: the loader receives (name, loader data). 5.4+ additionally
1030 // returns the loader data as `require`'s 2nd value, so the data is kept
1031 // below the function (rotate) and re-pushed; 5.2/5.3 pass it but discard
1032 // it (return 1).
1033 state.rotate(-2, 1)?;
1034 state.push_value(1)?;
1035 state.push_value(-3)?;
1036 state.call(2, 1)?;
1037 } else {
1038 // 5.1: the loader receives only the name; there is no loader data.
1039 state.pop_n(1);
1040 state.push_value(1)?;
1041 state.call(1, 1)?;
1042 }
1043
1044 if state.type_at(-1) != LuaType::Nil {
1045 state.set_field(2, &name)?;
1046 } else {
1047 state.pop_n(1);
1048 }
1049
1050 let ty = state.get_field(2, &name)?;
1051 if ty == LuaType::Nil {
1052 state.push(LuaValue::Bool(true));
1053 state.copy_value(-1, -2)?;
1054 state.set_field(2, &name)?;
1055 }
1056
1057 if require_returns_loader_data(version) {
1058 // 5.4+: return (module result, loader data). The loader data is still on
1059 // the stack below the module result; swap them to module-result-first.
1060 state.rotate(-2, 1)?;
1061 Ok(2)
1062 } else {
1063 // 5.1/5.2/5.3: `ll_require` returns only the module (return 1). On the
1064 // 5.2/5.3 path the loader data is still on the stack below the result;
1065 // drop it so the single return value is the module.
1066 if require_passes_loader_data(version) {
1067 state.remove(-2)?;
1068 }
1069 Ok(1)
1070 }
1071}
1072
1073/// Whether `require` passes the searcher's loader data to the module loader as
1074/// a SECOND argument (after the module name).
1075///
1076/// 5.1's `ll_require` calls the loader with one argument (`lua_call(L, 1, 1)`);
1077/// 5.2 widened it to two (`lua_call(L, 2, 1)`), so every later version passes the
1078/// loader data too. Pinned in `tests/loadlib_strengthen.rs`.
1079fn require_passes_loader_data(version: lua_types::LuaVersion) -> bool {
1080 !matches!(version, lua_types::LuaVersion::V51)
1081}
1082
1083/// Whether `require` returns the searcher's loader data as a SECOND result.
1084///
1085/// This is a **5.4** addition (`ll_require`'s `return 2`); 5.1/5.2/5.3 return only
1086/// the module (`return 1`), so `local _, d = require(m)` yields `d == nil` there.
1087/// It is the same seam the preload searcher's `:preload:` sentinel rides on
1088/// (a searcher only bothers returning loader data on a version that surfaces it).
1089/// Pinned in `tests/loadlib_strengthen.rs`.
1090fn require_returns_loader_data(version: lua_types::LuaVersion) -> bool {
1091 matches!(version, lua_types::LuaVersion::V54 | lua_types::LuaVersion::V55)
1092}
1093
1094// ── Package library setup ─────────────────────────────────────────────────────
1095
1096/// Create the `searchers` table and install the four built-in searchers, each
1097/// with the `package` table as upvalue #1.
1098///
1099fn createsearcherstable(state: &mut LuaState) -> Result<(), LuaError> {
1100 let searchers: &[fn(&mut LuaState) -> Result<usize, LuaError>] =
1101 &[searcher_preload, searcher_lua, searcher_c, searcher_croot];
1102
1103 state.create_table(searchers.len() as i32, 0)?;
1104
1105 for (i, &f) in searchers.iter().enumerate() {
1106 // Each searcher closes over the `package` table (upvalue #1) so
1107 // `findfile` can read `package.path`/`package.cpath` via
1108 // `lua_upvalueindex(1)`.
1109 state.push_value(-2)?;
1110 state.push_c_closure(f, 1)?;
1111 state.raw_seti(-2, (i + 1) as i64)?;
1112 }
1113 // Roster name deltas for the searcher list:
1114 // - 5.1: the table is named `package.loaders`; there is NO
1115 // `package.searchers` (verified against lua5.1.5: `package.searchers` is
1116 // nil, `package.loaders` is a table).
1117 // - 5.2: renamed to `package.searchers` but kept `package.loaders` as a
1118 // compat alias (both point at the same list).
1119 // - 5.3+: `package.searchers` only.
1120 let version = state.global().lua_version;
1121 let has_loaders = matches!(
1122 version,
1123 lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52
1124 );
1125 let has_searchers = !matches!(version, lua_types::LuaVersion::V51);
1126 if has_loaders {
1127 state.push_value(-1)?;
1128 state.set_field(-3, b"loaders")?;
1129 }
1130 if has_searchers {
1131 state.set_field(-2, b"searchers")?;
1132 } else {
1133 // No `searchers` field under 5.1; drop the table copy left on the stack.
1134 state.pop_n(1);
1135 }
1136 Ok(())
1137}
1138
1139/// Create the `_CLIBS` registry table with a `__gc` finalizer that closes all
1140/// loaded C libraries when the Lua state is closed.
1141///
1142fn createclibstable(state: &mut LuaState) -> Result<(), LuaError> {
1143 state.get_subtable_registry(CLIBS)?;
1144 state.create_table(0, 1)?;
1145 state.push_c_function(gctm)?;
1146 state.set_field(-2, b"__gc")?;
1147 state.set_metatable(-2)?;
1148 Ok(())
1149}
1150
1151// ── Lua 5.1 `module` / `package.seeall` (deprecated module system) ────────────
1152//
1153// These ship only in the default lua5.1.5 build (`loadlib.c`) and were removed
1154// in 5.2. Registered under the V51 backend; see
1155// specs/followup/5.1-roster-syntax.md §1. They lean on the 5.1 fenv globals
1156// model: `module` sets its caller's environment to the module table (via
1157// `crate::base::set_func_env_at_level`), and `package.seeall` points a module
1158// table's `__index` at `_G`.
1159
1160/// `package.seeall(module)` — make a module table inherit globals.
1161///
1162/// Sets (creating if absent) `module`'s metatable `__index` to the global
1163/// table. Mirrors `ll_seeall` in 5.1 `loadlib.c`. Verified against lua5.1.5.
1164fn ll_seeall(state: &mut LuaState) -> Result<usize, LuaError> {
1165 state.check_arg_type(1, LuaType::Table)?;
1166 if !state.get_metatable(1)? {
1167 state.create_table(0, 1)?;
1168 state.push_value(-1)?;
1169 state.set_metatable(1)?;
1170 }
1171 state.push_globals()?;
1172 state.set_field(-2, b"__index")?;
1173 Ok(0)
1174}
1175
1176/// Walk a dotted module name from a table on the stack, creating intermediate
1177/// tables as needed, leaving the final (sub)table on the stack top. A faithful
1178/// reduction of `luaL_findtable(L, idx, name, 1)`; returns `Err` on a name
1179/// conflict (an intermediate path component is a non-table, non-nil value).
1180fn findtable(state: &mut LuaState, table_idx: i32, name: &[u8]) -> Result<(), LuaError> {
1181 // Start from a copy of the base table on the stack top.
1182 state.push_value_at(table_idx)?;
1183 for part in name.split(|&b| b == b'.') {
1184 // Stack top holds the current table; fetch current[part].
1185 let ty = state.get_field(-1, part)?;
1186 if ty == LuaType::Nil {
1187 state.pop_n(1); // remove nil
1188 state.create_table(0, 1)?; // new subtable
1189 state.push_value(-1)?; // duplicate it
1190 state.set_field(-3, part)?; // current[part] = subtable
1191 // Stack: ..., current, subtable. Remove the parent, keep subtable.
1192 state.remove(-2)?;
1193 } else if ty == LuaType::Table {
1194 // Stack: ..., current, value. Remove the parent, keep value.
1195 state.remove(-2)?;
1196 } else {
1197 return Err(LuaError::runtime(format_args!(
1198 "name conflict for module '{}'",
1199 String::from_utf8_lossy(name)
1200 )));
1201 }
1202 }
1203 Ok(())
1204}
1205
1206/// `module(name [, ...])` — Lua 5.1 only.
1207///
1208/// Creates (or reuses) a module table named `name`, registers it in
1209/// `package.loaded`, initializes its `_NAME`/`_M`/`_PACKAGE` fields, applies any
1210/// option functions (e.g. `package.seeall`), and sets the calling chunk's
1211/// environment to the module table. Mirrors `ll_module` in 5.1 `loadlib.c`.
1212fn ll_module(state: &mut LuaState) -> Result<usize, LuaError> {
1213 let modname: Vec<u8> = state.check_arg_string(1)?;
1214 let n_opts = state.top() as i32;
1215
1216 // Fetch _LOADED[modname]; create the module table if absent.
1217 state.get_field_registry(b"_LOADED")?;
1218 let loaded_idx = state.top() as i32;
1219 state.get_field(loaded_idx, &modname)?;
1220 if state.type_at(-1) != LuaType::Table {
1221 state.pop_n(1); // remove non-table result
1222 // Find/create a global table named `modname` (supporting dotted names).
1223 state.push_globals()?;
1224 let g_idx = state.top() as i32;
1225 findtable(state, g_idx, &modname)?;
1226 state.remove(g_idx)?; // drop the globals table copy, keep the module table
1227 state.push_value(-1)?;
1228 state.set_field(loaded_idx, &modname)?; // _LOADED[modname] = module
1229 }
1230
1231 // Initialize the module if it has no `_NAME` yet.
1232 let has_name = state.get_field(-1, b"_NAME")? != LuaType::Nil;
1233 state.pop_n(1);
1234 if !has_name {
1235 // module._M = module
1236 state.push_value(-1)?;
1237 state.set_field(-2, b"_M")?;
1238 // module._NAME = modname
1239 state.push_string(&modname)?;
1240 state.set_field(-2, b"_NAME")?;
1241 // module._PACKAGE = full name minus the last dotted component.
1242 let pkg: &[u8] = match modname.iter().rposition(|&b| b == b'.') {
1243 Some(dot) => &modname[..=dot],
1244 None => b"",
1245 };
1246 state.push_string(pkg)?;
1247 state.set_field(-2, b"_PACKAGE")?;
1248 }
1249
1250 // Set the caller's environment to the module table (the running closure that
1251 // invoked `module`, i.e. level 1 relative to this C function).
1252 let module_tbl = state.value_at(-1);
1253 crate::base::set_func_env_at_level(state, 1, module_tbl)?;
1254
1255 // Apply option functions: for each extra arg, call `option(module)`.
1256 let mut i = 2;
1257 while i <= n_opts {
1258 state.push_value_at(i)?; // option function
1259 state.push_value(-2)?; // module table
1260 state.call(1, 0)?;
1261 i += 1;
1262 }
1263 Ok(0)
1264}
1265
1266/// Open the `package` library and return the `package` table.
1267///
1268pub fn luaopen_package(state: &mut LuaState) -> Result<usize, LuaError> {
1269 createclibstable(state)?;
1270
1271 // The C `pk_funcs` table also has placeholder entries for "preload",
1272 // "cpath", "path", "searchers", "loaded" (all NULL); those fields are set
1273 // explicitly below. Only `loadlib` is unconditional — `package.searchpath`
1274 // was added in 5.2 (absent on 5.1), so it is registered separately below.
1275 state.new_lib(&[(
1276 b"loadlib" as &[u8],
1277 ll_loadlib as fn(&mut LuaState) -> Result<usize, LuaError>,
1278 )])?;
1279
1280 if !matches!(state.global().lua_version, lua_types::LuaVersion::V51) {
1281 state.push_c_function(ll_searchpath)?;
1282 state.set_field(-2, b"searchpath")?;
1283 }
1284
1285 createsearcherstable(state)?;
1286
1287 setpath(state, b"path", LUA_PATH_VAR, LUA_PATH_DEFAULT)?;
1288
1289 setpath(state, b"cpath", LUA_CPATH_VAR, LUA_CPATH_DEFAULT)?;
1290
1291 let config = package_config(state.global().lua_version);
1292 let config_s = state.intern_str(&config)?;
1293 state.push(LuaValue::Str(config_s));
1294
1295 state.set_field(-2, b"config")?;
1296
1297 state.get_subtable_registry(b"_LOADED")?;
1298 state.set_field(-2, b"loaded")?;
1299
1300 state.get_subtable_registry(b"_PRELOAD")?;
1301 state.set_field(-2, b"preload")?;
1302
1303 state.push_globals()?;
1304 state.push_value(-2)?;
1305 state.set_funcs_with_upvalues(
1306 &[(
1307 b"require" as &[u8],
1308 ll_require as fn(&mut LuaState) -> Result<usize, LuaError>,
1309 )],
1310 1,
1311 )?;
1312 state.pop_n(1);
1313
1314 // The deprecated module system: `package.seeall` (a field on the package
1315 // table) and the `module` global. Present in 5.1 and kept in 5.2.4 via the
1316 // default-on `LUA_COMPAT_MODULE`; fully removed in 5.3. Verified against
1317 // lua5.1.5 and lua5.2.4. See specs/followup/5.1-roster-syntax.md §1.
1318 if matches!(
1319 state.global().lua_version,
1320 lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52
1321 ) {
1322 // The package table is on top of the stack here.
1323 state.push_c_function(ll_seeall)?;
1324 state.set_field(-2, b"seeall")?;
1325 // `module` is a *global*, not a `package` field.
1326 state.push_c_function(ll_module)?;
1327 state.set_global(b"module")?;
1328 }
1329
1330 Ok(1)
1331}
1332
1333// ──────────────────────────────────────────────────────────────────────────
1334// PORT STATUS
1335// target_crate: lua-stdlib
1336// unsafe_blocks: 0 (the dlopen/dlsym FFI lives in lua-cli, behind the
1337// dynlib_*_hook indirection on GlobalState; this crate stays
1338// unsafe-free per its `unsafe_code = "forbid"`)
1339// deferred: two genuine TODOs — LUA_VERSUFFIX / LUA_PATH_DEFAULT /
1340// LUA_CPATH_DEFAULT are hardcoded for 5.4 rather than tracking
1341// the selected version + a platform install prefix; the Windows
1342// setprogdir LUA_EXEC_DIR substitution is unimplemented.
1343// notes: Idiomatization Sprint 2 / Phase 2 (cold module, no perf
1344// arbiter). The deterministic pure-Lua surface (package.config,
1345// require + package.loaded caching, the four-searcher not-found
1346// trace, package.searchpath string logic, the loaders/searchers
1347// rename, module/seeall 5.1 roster, the nil-vs-false fail value)
1348// is pinned by tests/loadlib_strengthen.rs, which caught SEVEN
1349// cross-version divergences fixed here (see GRADUATED.md
1350// "loadlib"). The platform/FFI surface is left LOAD-BEARING and
1351// untouched: the dlopen/dlsym bridge (— POSIX/Windows notes on
1352// lsys_load/lsys_sym/lsys_unloadlib), the file probe + module
1353// read via file_loader_hook, the "open"/"absent"/"init" tags
1354// and platform error strings, and the unsupported-stock-C-ABI
1355// message (DynamicSymbol::LuaCAbi). None of that is
1356// reference-pinnable without a real .so + host loader.
1357// ──────────────────────────────────────────────────────────────────────────